content
stringlengths
42
6.51k
def startWebPage(myTitle): """ Returns a string with the head element for a web page with title myTitle. Example: webPageHeader("Temperatures") returns the header for a web page with temperatures on it, i.e. <head> <title>Temperatures</title> </head> """ return ("<html>\n<head>\n" + " <title>"+ myTitle + "</title>\n" + "</head>\n<body>\n<h1>"+myTitle+"</h1>\n")
def constr_leaf_value(xml_str, leafName, leafValue): """construct the leaf update string""" if leafValue is not None: xml_str += "<" + leafName + ">" xml_str += "%s" % leafValue xml_str += "</" + leafName + ">\r\n" return xml_str
def sortedDictLists(d, byvalue=True, onlykeys=None, reverse=False): """Return (key list, value list) pair from a dictionary, sorted by value (default) or key. Adapted from an original function by Duncan Booth. """ if onlykeys is None: onlykeys = list(d.keys()) if byvalue: i = [(val, key) for (key, val) in d.items() if key in onlykeys] i.sort() if reverse: i.reverse() rvals = [val for (val, key) in i] rkeys = [key for (val, key) in i] else: # by key i = [(key, val) for (key, val) in d.items() if key in onlykeys] i.sort() if reverse: i.reverse() rvals = [val for (key, val) in i] rkeys = [key for (key, val) in i] return (rkeys, rvals)
def video(data_type, stream_id, data, control, timestamp): """ Construct a video message to send video data to the server. :param data_type: int the RTMP datatype. :param stream_id: int the stream which the message will be sent on (same as the publish StreamID). :param data: bytes the raw video data. :param control: bytes in hex the control type to send the data as. :param timestamp: int the timestamp of the packet. """ msg = {'msg': data_type, 'stream_id': stream_id, 'timestamp': timestamp, 'body': {'control': control, 'data': data}} return msg
def convert_args_to_str(args, max_len=None): """ Convert args to a string, allowing for some arguments to raise exceptions during conversion and ignoring them. """ length = 0 strs = ["" for i in range(len(args))] for i, arg in enumerate(args): try: sarg = repr(arg) except Exception: sarg = "< could not convert arg to str >" strs[i] = sarg length += len(sarg) + 2 if max_len is not None and length > max_len: return "({}".format(", ".join(strs[:i + 1]))[:max_len] else: return "({})".format(", ".join(strs))
def escape(s, quote=True): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") s = s.replace('\'', "&#x27;") return s
def get_db_engine(snapshot_response): """Function to parse snapshot response from AWS for DB engine. Args: snapshot_response (str): The snapshot identifier to parse. Returns: :obj:`str`: The DB engine of the snapshot. """ db_source_snapshot = snapshot_response['DBSnapshots'][0]['DBSnapshotArn'] print(f'Checking snapshot engine for {db_source_snapshot}') return snapshot_response['DBSnapshots'][0]['Engine']
def turn(p, q, r): """Returns -1, 0, 1 if p,q,r forms a right, straight, or left turn.""" t = (q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]) # Update to make jarvis run with Python 3.3: if t < 0: return -1 if t == 0: return 0 if t > 0: return 1
def stripExtension(path): """Return the part of the path before the extension. @param path: The path to split. @type path: string @return: The part of the path before the extension. @rtype: string """ end = path.rfind("\\") end = max(path.rfind("/", end + 1), end) + 1 # We search in the substring AFTER the last slash. # In the case that a slash is not found, the -1 returned by rfind becomes zero, # and so searches the whole string extStart = path.rfind(".", end) if extStart > end and path.count(".", end, extStart) != extStart - end: return path[:extStart] else: return path
def rle_decode(data): """Decodes PackBits encoded data.""" i = 0 output = bytearray() while i < len(data): val = data[i] i += 1 if val == 0x80: continue if val > 0x80: repeats = 0x101 - val output += data[i:i + 1] * repeats i += 1 else: output += data[i:i + val + 1] i += val + 1 return output
def Col_to_row(m): """Column-To-Row Transposition : moves the nibble in the position ( i , j ) to the position ( j , i )""" n = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] for i in range(4): for j in range(4): try: n[j][i] = m[i][j] except IndexError: print('Invalid Input!!') exit(0) return n
def check_for_ticket_quantity_error(quantity): """ Returns any error message if the ticket's quantity is not between 1 and 100 else if there is no errors it returns false. :param quantity: the ticket's quantity as a string :return: false if no error, else returns the error as a string message """ if int(quantity) < 1 or int(quantity) > 100: return "The quantity of the ticket must be between 1 and 100" return False
def digits(n,B=10): """ Number of digits of n in base B """ n = abs(n) ctr = 0 while n != 0: n //= B ctr += 1 return ctr
def get_rank(target, ranks): """ Get rank of a target entity within all ranked entities. Args: target (str): Target entity which rank should be determined. ranks (list): List of tuples of an entity and its rank. Returns: int: Rank of entity or -1 if entity is not present in ranks. """ for i in range(len(ranks)): word, rank = ranks[i] if word == target: return i return -1
def check_password_vs_blacklist(current_string, blacklist): """Checks a string to determine whether it is contained within a blacklist Arguments: current_string {string} -- the string to be checked against blacklist blacklist {list} -- list of words defined within a given blacklist file Returns: [bool] -- whether current_string was found within the blacklist file """ if (((current_string.strip()).strip('\"') in blacklist) or ((current_string.strip()).strip("'") in blacklist) or ((current_string.strip()).strip('`') in blacklist)): return True else: return False
def month_name_to_number_string(string): """ :param string: :return: """ m = { 'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05', 'jun': '06', 'jul': '07', 'aug': '08', 'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'} s = string.strip()[:3].lower() try: out = m[s] return out except ValueError: raise ValueError(string + ' is not a month')
def api_command_wrapper(api_command_result): """Prints the result of the command and raises RuntimeError to interrupt command sequence if there is an error. Args: api_command_result: result of the api command """ print(api_command_result) if not api_command_result["status"] == "SUCCESS": raise RuntimeError("command was not successful!") return api_command_result
def example_combi(pos, a=None, b=1, c='test'): """ I'm a harder case: a slice is indicated by : Args: pos: a: value b: test returns: a list separated by colon (:) """ return pos, a, b, c
def dead_zone(controller_input, dead_zone): """This is the dead zone code, essential for any 4009 'bot.""" if controller_input <= dead_zone and controller_input >= -dead_zone: return 0 elif controller_input > 0: return ((controller_input-dead_zone)/(1-dead_zone)) else: return ((-controller_input-dead_zone)/(dead_zone-1))
def decode_bytes(data: bytes) -> str: """ Decodes provided bytes using `utf-8` decoding, ignoring potential decoding errors. """ return data.decode('utf-8', 'ignore')
def slice_as_int(s: slice, l: int): """Converts slices of length 1 to the integer index they'll access.""" out = list(range(*s.indices(l))) assert len(out) == 1 return out[0]
def isGitUrl(Url): """ this function returns true, if the Url given as parameter is a git url: it either starts with git:// or the first part before the first '|' ends with .git or if the url starts with the token [git] """ if Url.startswith('git://'): return True # split away branch and tags splitUrl = Url.split('|') if splitUrl[0].endswith(".git"): return True if Url.startswith("[git]"): return True return False
def formatDirPath(path): """Appends trailing separator to non-empty path if it is missing. Args: path: path string, which may be with or without a trailing separator, or even empty or None Returns: path unchanged if path evaluates to False or already ends with a trailing separator; otherwise, a / separator is appended """ if path and not path.endswith('/'): path = path + '/' return path
def prepend_protocol(url: str) -> str: """Prefix a URL with a protocol schema if not present Args: url (str) Returns: str """ if '://' not in url: url = 'https://' + url return url
def ring_idxs(gra_rings): """ Get idxs for rings """ _ring_idxs = tuple() for ring in gra_rings: idxs = tuple(ring[0].keys()) if idxs: _ring_idxs += (idxs,) return _ring_idxs
def bin2dec(string_num): """Turn binary into decimal.""" return str(int(string_num, 2))
def parse_game_type(data: dict) -> str: """Parse and format a game's type.""" is_rated = data.get('rated') speed = data.get('speed') variant = data.get('variant') game_type = 'unknown' if speed: game_type = '%s (%s)' % (speed, variant or 'standard') if is_rated: game_type = 'rated %s' % game_type else: game_type = 'unrated %s' % game_type return game_type
def validate_move(move): """ Takes user input and validates it, returning the result if valid. """ try: move = int(move) assert move in [1, 2, 3, 4, 5, 6] except (ValueError, AssertionError): raise ValueError("Choose a value in [1-6]. Please try again.") return move
def horizontal_index(ncols, row, col): """ Compute the array index using horizontal-display logic """ # lambda ncols, row, col: ncols * (row - 1) + col return ncols * (row - 1) + col
def remove_whitespace(html): """Removes whitespace from an HTML buffer""" return ''.join([line.strip() for line in html.split('\n')])
def even(arg: int) -> bool: """ Tells if the given arg number is even. """ return arg % 2 == 0
def convert_custom_objects(obj, custom_objects={}): """Handles custom object lookup. # Arguments obj: object, dict, or list. # Returns The same structure, where occurences of a custom object name have been replaced with the custom object. """ if isinstance(obj, list): deserialized = [] for value in obj: if value in custom_objects: deserialized.append(custom_objects[value]) else: deserialized.append(value) return deserialized if isinstance(obj, dict): deserialized = {} for key, value in obj.items(): if value in custom_objects: deserialized[key] = custom_objects[value] else: deserialized[key] = value return deserialized if obj in custom_objects: return custom_objects[obj] return obj
def check_valid_password_2(minimum, maximum, letter, password): """PART TWO Checks if a password is valid based on the criteria. The min/max in this example are actually the indexes (no index 0 here) of where the letter should occur. Only one occurence of the letter is acceptable (an "a") at both 1 and 3 won't work. """ if ( password[minimum - 1] == letter and password[maximum - 1] != letter or password[maximum - 1] == letter and password[minimum - 1] != letter ): # print(minimum, maximum, letter, password) return True
def make_sub_rst(id_, x): """Turn (id, original) into valid RST which can be inserted in a document for parsing.""" return ":sub:`(%s)%s`"%(id_, x.replace("`", r"\`").strip())
def valid_parentheses(string): """.""" stack = [] for i in string: if i == '(': stack.append(0) elif i == ')': if stack == []: return False else: stack.pop() return stack == []
def replace_with_ids(tokens, vocab): """Takes in a list of tokens and returns a list of word ids. <unk> must be included in vocabulary! Args: tokens: List of tokens. vocab: A dictionary from word -> word_id. MUST INCLUDE THE TERM <unk>. Returns: List of word ids. """ return [vocab.get(t, vocab.get('<unk>')) for t in tokens]
def compute_start_points(shapes, margin): """ tiling features in horizontal direction with a given margin shapes: list, in NCHW format margin: int, margin to tiling features of different levels """ N, C, H0, W0 = shapes[0] x0 = 0 start_points = [] ranges = [] for shape in shapes: _, _, H, W = shape y0 = H0 - H start_points.append((y0, x0)) ranges.append((x0, y0, x0 + W, y0 + H)) x0 += W + margin return start_points, ranges, (H0, x0)
def generate_matrix(dim): """Generate the matrix with enumarated elements. Args: dim: Dimension of the matrix. Returns: Generated matrix as a nested list. """ matr = [] for i in range(dim): # Start by 1 and increase the number for each new element by one. matr.append(list(range((i+1)*dim-dim+1, (i+1)*dim+1))) return matr
def sequence_del(my_str): """ :param my_str: :return: List made of the received string of all the products the user entered """ List = list(my_str.split(',')) print(List) return List
def _data_not_in_spec(spec): """ check to see if the data element is defined for this spec """ if isinstance(spec, dict): return 'data' not in spec return True
def get_localizable_attributes(obj): """Returns a dictionary with localizable attributes of `obj`.""" # FIXME: use some kind of class attribute to get list of localizable attributes locale = {} try: if obj.label: locale["label"] = obj.label except: pass try: if obj.description: locale["description"] = obj.description except: pass return locale
def lasso_and_ridge_from_enet(pen_val, l1_ratio): """ Returns the lasso and L2 penalties from the elastic net parameterization Parameters ---------- pen_val: float l1_ratio: float, None Output ------ lasso_pen, ridge_pen """ if l1_ratio is None or l1_ratio == 0: lasso_pen = None ridge_pen = pen_val elif l1_ratio == 1: lasso_pen = pen_val ridge_pen = None else: lasso_pen = pen_val * l1_ratio ridge_pen = pen_val * (1 - l1_ratio) return lasso_pen, ridge_pen
def calc_stats(total_unique_molecular_bases, total_bases, output_bases, genome_size, coverage): """ >>> calc_stats(0, 0, 0, 0, 0) == \ {'genome_size': 0, 'coverage': 0, 'total_bases': 0, 'total_unique_molecular_bases': 0, \ 'output_bases': 0, 'unique_molecular_avg_cov': 0.0, 'output_avg_cov': 0.0, 'total_avg_cov': 0.0} True >>> calc_stats(10000, 100000, 2000, 1000, 2) == \ {'genome_size': 1000, 'coverage': 2, 'total_bases': 100000, 'total_unique_molecular_bases': 10000, \ 'output_bases': 2000, 'unique_molecular_avg_cov': 10.0, 'output_avg_cov': 2.0, 'total_avg_cov': 100.0} True """ unique_molecular_avg_cov = 0.0 if genome_size == 0 else float(total_unique_molecular_bases) / float(genome_size) total_avg_cov = 0.0 if genome_size == 0 else float(total_bases) / float(genome_size) output_avg_cov = 0.0 if genome_size == 0 else float(output_bases) / float(genome_size) ret = {} ret['genome_size'] = genome_size ret['coverage'] = coverage ret['total_bases'] = total_bases ret['total_unique_molecular_bases'] = total_unique_molecular_bases ret['output_bases'] = output_bases ret['total_avg_cov'] = total_avg_cov ret['unique_molecular_avg_cov'] = unique_molecular_avg_cov ret['output_avg_cov'] = output_avg_cov return ret
def translate_tuple_to_basemask(tup, demux_tool): """Return illumina or picard-style base mask string""" picard_to_illumina = {"T": "y", "S": "n", "B": "I"} if demux_tool == "bcl2fastq": return picard_to_illumina[tup[0]] + str(tup[1]) else: return str(tup[1]) + tup[0]
def is_var_desc(p, pltype): """ The variable description will either follow a Var Name or be a continuation of a Var Desc line Note: This test is dependent on other identifications before it. """ import re if pltype in ['Var Name', 'Var Desc']: pparser = re.compile(r"[\t ]+\.") words = pparser.split(p) if len(words) == 1 and p[0] != '.': return True return False
def has_method(o, name): """ Verifies whether an object has a specific method """ return callable(getattr(o, name, None))
def show_best_slave(slaves, args_array): """Method: show_best_slave Description: Stub holder for mysql_rep_failover.show_best_slave function. Arguments: (input) slaves (input) args_array """ status = False if slaves and args_array: status = False return status, None
def jacobi(a, b): """Calculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd """ if a == 0: return 0 result = 1 while a > 1: if a & 1: if ((a-1)*(b-1) >> 2) & 1: result = -result a, b = b % a, a else: if (((b * b) - 1) >> 3) & 1: result = -result a >>= 1 if a == 0: return 0 return result
def text_type(s): """ Given an unnamed piece of data, try to guess its content type. Detects HTML, XML, and plain text. :return: A MIME type string such as 'text/html'. :rtype: str :param bytes s: The binary data to examine. """ # at least the maximum length of any tags we look for max_tags = 14 s2 = s.strip()[:max_tags].lower() if len(s2) == max_tags: if s2.startswith(b'<html>'): return 'text/html' if s2.startswith(b'<!doctype html'): return 'text/html' # what about encodings?? if s2.startswith(b'<?xml'): return 'text/xml' # we also recognize small snippets of HTML - the closing tag might be # anywhere, even at the end of if b'</' in s: return 'text/html' return 'text/plain'
def get_ring(gossip): """ Return the ring status in a structured way. Args: gossip: A list of gossip info for each node. Returns: A list of nodes represented by dictionaries. """ nodes = sorted(gossip, key=lambda node: node['token']) for index, node in enumerate(nodes): node['index'] = index if not nodes: raise Exception('Unable to find nodes in ring') # Calculate skew and diff for each node in ring. ideal_load = sum(node['load'] for node in nodes) / len(nodes) for index, node in enumerate(nodes): try: node['skew'] = abs(node['load'] - ideal_load) / ideal_load except ZeroDivisionError: node['skew'] = 0 node['diff'] = abs(node['load'] - nodes[index - 1]['load']) return nodes
def create_annotationlist_id(manifest_info, canvas_id, annolist_idx, opts): """ Return (uri, filename) for annotation list """ prefix = opts['url_prefix'] if not prefix: # use manifest id as prefix prefix = manifest_info['id'] scheme = opts['annolist_name_scheme'] if scheme == 'canvas': # use last part of canvas id canvas_part = canvas_id.split('/')[-1] fn = canvas_part + '-annolist.json' uri = prefix + '/' + fn else: fn = f"annolist-{annolist_idx}.json" uri = prefix + '/' + fn return uri, fn
def is_prime(n): """Returns True if n is a prime number. :param n: The nummer to test """ if n == 2 or n == 3: return True if n < 2 or n % 2 == 0: return False if n < 9: return True if n % 3 == 0: return False r = int(n ** 0.5) f = 5 while f <= r: if n % f == 0: return False if n % (f + 2) == 0: return False f += 6 return True
def reverse_bisect_left(a, x, lo=0, hi=None): """\ Similar to ``bisect.bisect_left``, but expects the data in the array ``a`` to be provided in descending order, rather than the ascending order assumed by ``bisect_left``. The returned index ``i`` partitions the array ``a`` into two halves so that: - left side: ``all(val > x for val in a[lo:i])`` - right side: ``all(val <= x for val in a[i:hi])`` """ if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo + hi) // 2 if a[mid] > x: lo = mid + 1 else: hi = mid return lo
def End_Path(path): """ Split the path at every '/' and return the final file/folder name. If your path uses backslashes rather than forward slashes it will use that as the separator. CODE: End_Path(path) AVAILABLE PARAMS: path - This is the path where you want to grab the end item name. EXAMPLE CODE: addons_path = xbmc.translatePath('special://home/addons') file_name = koding.End_Path(path=addons_path) dialog.ok('ADDONS FOLDER','Path checked:',addons_path,'Folder Name: [COLOR=dodgerblue]%s[/COLOR]'%file_name) file_path = xbmc.translatePath('special://home/addons/script.module.python.koding.aio/addon.xml') file_name = koding.End_Path(path=file_path) dialog.ok('FILE NAME','Path checked:',file_path,'File Name: [COLOR=dodgerblue]%s[/COLOR]'%file_name) ~""" if '/' in path: path_array = path.split('/') if path_array[-1] == '': path_array.pop() elif '\\' in path: path_array = path.split('\\') if path_array[-1] == '': path_array.pop() else: return path return path_array[-1]
def mw_sigma_leonard(rake): """ sigma values are determined from the Leonard 2014 paper, based on Table 3 - S(a) passing it through the equation rake: to determine if DS or SS returns sigma value for mean Mw """ if round(rake % 360 / 90.0) % 2: sigma = 0.3 else: sigma = 0.26 return sigma
def get_aws_connection_data(assumed_account_id, assumed_role_name, assumed_region_name=""): """ Build a key-value dictionnatiory args for aws cross connections """ if assumed_account_id and assumed_role_name: aws_connection_data = dict( [("assumed_account_id", assumed_account_id), ("assumed_role_name", assumed_role_name), ("assumed_region_name", assumed_region_name)]) else: aws_connection_data = dict() return (aws_connection_data)
def _shortnameByCaps(name): """ uses hungarian notation (aka camelCaps) to generate a shortname, with a maximum of 3 letters ex. myProc --> mp fooBar --> fb superCrazyLongProc --> scl """ shortname = name[0] count = 1 for each in name[1:]: if each.isupper() or each.isdigit(): shortname += each.lower() count += 1 if count == 3: break return shortname
def create_file_name(scale=1, invert=False, flip=False): """Helper function to dynamically create a file name Keyword arguments: scale -- scale of the printed icon invert -- boolean to invert the binary symbols flip -- boolean to flip icon 180 degrees """ return ('icon_scaled_x' + str(scale) + ('_inverted' if invert == True else '') + ('_flipped' if flip == True else '') + '.txt')
def unbox(boxed_pixels): """ assumes the pixels came from box and unboxes them! """ flat_pixels = [] for boxed_row in boxed_pixels: flat_row = [] for pixel in boxed_row: flat_row.extend(pixel) flat_pixels.append(flat_row) return flat_pixels
def phaseY(father, child): """Phase Y chromosome genotype of a male child given the genotype of the father. This function only checks that the genotype of the child could have been inherited from the father. Arguments: mother (string): genotype of father expressed in the form 0/1, 0/0 etc child (string): genotype of child Returns: The phased genotype of the child if it is unambiguously resolvable. Otherwise the genotype is returned as is, i.e. unphased >>> phaseY('0/1', '0/1') '0/1' >>> phaseY('0/1', '1/1') '1|1' >>> phaseY('0/2', '1/1') '1/1' >>> phaseY('./.', '3/3') '3/3' """ #ca, _, cb = child ca, cb = child.split('/') if ca != cb: # we have Y chromosome heterozygosity return child if ca in father: return '%s|%s' % (ca, ca) else: return child
def unquote(s): """unquote('abc%20def') -> 'abc def'.""" mychr = chr myatoi = int list = s.split('%') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('%' + item) else: myappend('%' + item) return "".join(res)
def check_has_backup_this_year(year, existing_backups): """ Check if any backup in existing_backups matches year. """ for backup in existing_backups: if backup.createdYear == year: return True return False
def has_doc(obj): """ Return whether an object has a docstring :param obj: Object to check for docstring on :return: Whether the object has a docstring """ return hasattr(obj, "__doc__") and isinstance(obj.__doc__, str)
def _check_noise_dict(noise_dict, component): """Ensure noise compatibility for the noises of the components provided when building a state space model. Returns ------- noise_dict : dict Checked input. """ sub_component = component.split('_') if isinstance(noise_dict, dict): for c in sub_component: if c not in noise_dict: raise ValueError( "You need to provide noise for '{}' component".format(c)) if noise_dict[c] < 0: raise ValueError( "noise for '{}' must be >= 0".format(c)) return noise_dict else: raise ValueError( "noise should be a dict. Received {}".format(type(noise_dict)))
def get_set_from_annotation(annotation_list, key): """ Takes list of annotation dicts and a key. Returns a set of all values of that key """ return set([x[key] for x in annotation_list])
def tof_cm(time_of_flight): """ EZ1 ultrasonic sensor is measuring "time of flight" Converts time of flight into distance in centimeters """ convert_to_cm = 58 cm = time_of_flight / convert_to_cm return cm
def constrain(x, min_=0, max_=255): """ constrain a number between two values """ return min(max_, max(min_, x));
def counter(alist, func=None): """ - counts the number of things in a list - can apply a function (func) to item """ adict = {} for item in alist: if func is not None: item = func(item) if item is not None: adict[item] = adict.get(item, 0) + 1 return adict
def getCharacterFromGame(gtitle: str) -> str: """Return a query to get characters with lower Ryu Number to a game. The query will retrieve the name and Ryu Number of a character whose Ryu Number is exactly one less than the Ryu Number of the game whose title is passed. This is used primarily for path-finding towards Ryu. The resulting query takes the following form for game_character as C: `(C.name: str, C.ryu_number: int)` """ return (f"SELECT DISTINCT C.name, C.ryu_number " f"FROM appears_in " f"INNER JOIN game_character AS C ON cname=C.name " f"INNER JOIN game AS G ON gtitle=G.title " f"WHERE gtitle LIKE '{gtitle}' AND C.ryu_number=G.ryu_number-1;" )
def new_dict_trie(lines): """ `new_dict_trie` returns a new trie, encoded as a dictionary, containing `lines`. """ trie = {} for line in lines: node = trie for char in line: if char not in node: node[char] = {} node = node[char] node[-1] = True return trie
def filter_bolts(table, header): """ filter to keep bolts """ bolts_info = [] for row in table: if row[0] == 'bolt': bolts_info.append(row) return bolts_info, header
def decode_dec_ttl(value): """Decodes dec_ttl and dec_ttl(id, id[2], ...) actions""" if not value: return True return [int(idx) for idx in value.split(",")]
def get_fieldnames(records): """ Extract fieldnames for CSV headers from list of results :param records: list :return: list """ fieldnames = [] ordered_fieldname = ( "time_last", "time_first", "source", "count", "bailiwick", "rrname", "rrtype", "rdata", ) # build a list of unique keys from all returned records for record in records: keys = list(record.keys()) for key in keys: if key not in fieldnames: fieldnames.append(key) # sort fieldnames based on order in ordered_fieldname fieldnames = sorted(fieldnames, key=lambda x: ordered_fieldname.index(x)) return fieldnames
def _linear_decay(value, origin, offset, scale, decay): """ https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html """ s = scale / (1 - decay) return max(0, (s - max(0, abs(value - origin) - offset)) / s)
def get_text(boxes): """ Merge text from boxes (Textblock) Parameters:: (TextBlock[]): boxes -- OCR boundingbox grouping to retreive test from Returns: TextS (String): concat textblock text """ text = "" for b in boxes: text = text + " " + b.text return text
def filter_disabled(s): """ Filter out all disabled items. :param s: :return: """ return list(filter(lambda x: "is_disabled" not in x or not x["is_disabled"], s))
def get_int(value, allow_sign=False) -> int: """Convert a value to an integer. Args: value: String value to convert. allow_sign: If True, negative values are allowed. Return: int(value) if possible. """ try: # rstrip needed when 0. is passed via [count] int_val = int(value.rstrip(".")) except ValueError: error = "Could not convert '%s' to int" % (value) raise ValueError(error) if int_val < 0 and not allow_sign: raise ValueError("Negative numbers are not supported.") return int_val
def stars_amount_counter(board: list) -> int: """Counts amount of stars in the given board. >>> stars_amount_counter(["**** ****", "***1 ****", "** 3****", "* 4 1****",\ "7 9 5 ", " 6 83 *", "3 2 **", " 8 2***", " 2 9****"]) 36 """ stars = 0 for i in range(9): for j in range(9): if board[i][j] == '*': stars += 1 return stars
def price_data(sp_available=False, sp_traded=False, ex_best_offers=False, ex_all_offers=False, ex_traded=False): """ Create PriceData filter list from all args passed as True. :param bool sp_available: Amount available for the BSP auction. :param bool sp_traded: Amount traded in the BSP auction. :param bool ex_best_offers: Only the best prices available for each runner, to requested price depth. :param bool ex_all_offers: trumps EX_BEST_OFFERS if both settings are present :param bool ex_traded: Amount traded on the exchange. :returns: string values of all args specified as True. :rtype: list """ args = locals().copy() return [ k.upper() for k, v in args.items() if v is True ]
def generate_tokens_map_by_flatten_pqa_data(flatten_data_list): """ flatten_data_list: List[(paragraph, question, answer)] """ token_map = {} for (paragraph_text, question_text, answer_text) in flatten_data_list: paragraph_tokens = paragraph_text.split(" ") question_tokens = question_text.split(" ") answer_tokens = answer_text.split(" ") for token in paragraph_tokens + question_tokens + answer_tokens: if token_map.get(token) is None: token_map[token] = 1 return token_map
def eh_celula(cell): """ eh_celula: universal >>> logico - Determina se o valor dado e do tipo celula ou nao """ if not isinstance(cell, dict): return False elif "valor" not in cell or len(cell.keys()) != 1: return False return cell["valor"] in (-1, 0, 1)
def drop_fst_arg(args_dict): """ Convinient function to drop the first argument, for example when applying a contract to class methods and you don't need the ``self`` argument. """ if "arg__0" in args_dict: del args_dict["arg__0"] return args_dict
def eq_tokens(token_sequence1: str, token_sequence2: str) -> bool: """Returns True if bothe token sequences contain the same tokens, no matter in what order:: >>> eq_tokens('red thin stroked', 'stroked red thin') True >>> eq_tokens('red thin', 'thin blue') False """ return set(token_sequence1.split(' ')) - {''} == set(token_sequence2.split(' ')) - {''}
def compare_samples(s1, s2): """ s1, s2 - samples with the following fields: 'node_tree', 'name' """ if s1 is None or s2 is None: return False else: def remove_field(node, field): if field in node: node.pop(field) return node # don't compare 'source_meta' field s1_nt = [remove_field(n, 'source_meta') for n in s1['node_tree']] s2_nt = [remove_field(n, 'source_meta') for n in s2['node_tree']] return s1['name'] == s2['name'] and s1_nt == s2_nt
def dummy_list_of_objects(dummy_dict): """Return a list of objects""" return [ { 1: {1.1: "1.1.1", 1.2: ["1.2.1", "1.2.2"]}, }, [4, 5], {2: {2.1: "2.1.1", 2.2: {}}, 3: {}}, ]
def add_something(num1, num2): """This function adds two numbers and returns the result >>> add_something(2,3) 5 >>> add_something(-4, 4) 0 >>> add_something(-3, -5) -8 """ return(num1 + num2)
def is_pythonfile(file): """Returns True if file extension is py and if not then false.""" if file.endswith('py'): return True else: return False
def _binary_search(array, elt): """Modified binary search on an array.""" start = 0 end = len(array) - 1 while start <= end: mid = (start + end) // 2 if elt == array[mid]: return mid + 1 if elt < array[mid]: end = mid - 1 else: start = mid + 1 if start > end: return start
def experience_converting(current_exp: int): """Return tuple(level, gained_after_lvl_up, left_before_lvl_up)""" a1 = 100 q = 1.1 current_lvl = 0 Sn = 100 prevSn = 0 while Sn <= current_exp: prevSn = Sn Sn = int(a1 * (q**(current_lvl + 2) - 1) / (q - 1)) current_lvl += 1 need_for_lvl_up = Sn - prevSn gained_after_lvl_up = current_exp - prevSn return (current_lvl, gained_after_lvl_up, need_for_lvl_up)
def SortCrescent(li, index): """ Argument: - li a list of lists. - index an integer Return: - A sorted list of lists in a crescent order by the elements located at the index position of each list contained in li. """ #ex :[ """""" return(sorted(li, key = lambda x: x[index]))
def __has_value(cell): """Checks if a cell value from a Pandas dataframe is a valid string The following are treated as invalid: * empty cell (None) * empty string ('') * zero (0) * type = nan OR type = None * 'null' OR 'NULL' * 'none' OR 'NONE' Args: cell (Any): Value of a cell from pandas dataframe Returns: Boolean: Whether or not value is valid string """ # Falsy values are FALSE if not cell: return False # nan values FALSE if not isinstance(cell, str): return False # strings == 'none' or 'null' or '0' are also FALSE if ( cell.lower() == "none" or cell.lower() == "null" or cell.lower() == "nan" or cell == "0" ): return False return True
def get_fp_color(n, col_set=1): """ Get the color of a fixed point given the number of unstable modes Arguments: n (int): number of unstable modes col_set (int): which colors set to use Returns: color (str) """ if n == 0: color = "seagreen" if col_set == 1 else "lightseagreen" elif n == 1: color = "salmon" if col_set == 1 else "lightsalmon" elif n == 2: color = "skyblue" if col_set == 1 else "deepskyblue" else: color = "magenta" if col_set == 1 else "purple" return color
def map_platforms(platforms): """ Takes in a list of platforms and translates Grinder platorms to corresponding GitHub-hosted runners. This function both modifies and returns the 'platforms' argument. """ platform_map = { 'x86-64_windows': 'windows-latest', 'x86-64_mac': 'mac-latest', 'x86-64_linux': 'ubuntu-latest' } for i, platform in enumerate(platforms): if platform in platform_map: platforms[i] = platform_map[platform] return platforms
def default(value: object): """Formatter functions handle Knack values by returning a formatted (aka, humanized) value. The `default()` formatter handles any field type for which another formatter function has not been defined. If the input value is a list, it returns a comma separated string of list values. Otherwise, it simply returns the input value without additional formatting. You'll notice that each formatter function's name matches its field type. If you want to write a custom formatter, do that. See also: knackpy.Fields """ if isinstance(value, list): return ", ".join(str(v) for v in value) return value
def replace_stuff(url): """ Remove common domain suffixes and prefixes """ stuff = ['www.', 'm.', 'blog.', 'help.', 'blogs.', 'gist.', 'en.', '.co', 'www2.', '.wordpress'] for item in stuff: url = url.replace(item, '') return url
def atoi(text): """ Based on a stackoverflow post: https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside """ return int(text) if text.isdigit() else text
def part_1(commands): """ Calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth? :param commands: the list of commands :return: product of final horizontal position and depth """ horizontal_pos = 0 depth = 0 for command in commands: details = command.split() value = int(details[1].strip()) if details[0] == "forward": horizontal_pos += value elif details[0] == "up": depth -= value elif details[0] == "down": depth += value print(f"Horizontal position: {horizontal_pos} and depth: {depth}") return horizontal_pos * depth
def _get_value(entry_quals, key, cb=lambda x: x): """Get the value from the entry and apply the callback """ return list(map(lambda v: cb(v), entry_quals.get(key, [])))
def maxValue(inputArray): """ maxValue Function used to calculate the maximum value of an array @param inputArray Array passed for calculation @return maxValueReturn The integer value returned by the calculation """ maxValueReturn = max(inputArray) return maxValueReturn
def to_binary(val, expected_length=8): """Converts decimal value to binary :param val: decimal :param expected_length: length of data :return: binary value """ val = bin(val)[2:] # to binary while len(val) < expected_length: val = "0" + val return val