content
stringlengths
42
6.51k
def isFrozen(status): """ Return a boolean indicating whether the given status name is frozen or not. @type status: C{unicode} @rtype: C{bool} """ return status.startswith(u'.')
def unwrap_string(s): """A utility function that converts a "'string'" to a "string" """ s = s.replace("'", "") return s
def list_of_val(val_for_list, list_len, num_lists = 1): """Generate a list or list of lists containing a single value. Parameters ---------- val_for_list : any Value that will be repeated in list or lists of lists. list_len : int Length of list output, or lists within list if multiple. num_lists : int, optional If > 1, number of lists within list of lists output. The default is 1. Returns ------- list or list of lists A list [val_for_list, val_for_list, ...] or list of such lists. """ output_list = [] temp_list = [] for _ in range(0, int(list_len)): temp_list.append(val_for_list) if num_lists <= 1: return temp_list else: for _ in range(0, int(num_lists)): output_list.append(temp_list) return output_list
def set_tif_names(directory, file_names): """ This function returns the directory + file_name of the inputs. In general, it is used to do mosaic with many geotiff files. :param directory: String :param file_names: String :return: list It returns a list with Strings. Each string has the merge of the directory and file name. """ tif_names = [] for i in file_names: tif_names.append(directory + i + '.tif') return tif_names
def bubble_sort(lis): """ Put the largest element to the rightmost position each time 1. Set done flag = True 2. Start with i = 0, swap i and i + 1 if num[i] > num[i + 1] 3. done = False if any swap occured 4. Keep running while done is False """ j = 0 done = False while not done: done = True for i in range(len(lis) - j - 1): if lis[i] > lis[i + 1]: lis[i], lis[i + 1] = lis[i + 1], lis[i] done = False j += 1 return lis
def get_neighbor(rows, ele): """ :param rows: lst, letters get from user :param ele: lst, current letter position :return neighbor: lst, the location tuple next to ele """ neighbor = [] # find valid location tuples that in 3x3 grid centered by ele for x in range(-1, 2): for y in range(-1, 2): test_x = ele[0] + x test_y = ele[1] + y # see if test_x and test_y within rows if 0 <= test_x < len(rows[0]) and 0 <= test_y < len(rows): if (test_x, test_y) != ele: neighbor.append((test_x, test_y)) return neighbor
def str_to_byn(str_): """ str_to_bin([string]) UTF-8 Takes string. Return string of binary bites splited with " " Example input: bynary_to_string.str_to_byn('ex') output: '1100101 1111000' """ return ' '.join(bin(byte).lstrip('0b') for Item in str_ for byte in Item.encode())
def bigram_similarity(word1: str, word2: str) -> float: """ Returns a number within the range [0, 1] determining how similar item1 is to item2. 0 indicates perfect dissimilarity while 1 indicates equality. The similarity value is calculated by counting the number of bigrams both words share in common. """ word1 = word1.lower() word2 = word2.lower() word1_length = len(word1) word2_length = len(word2) pairs1 = [] pairs2 = [] for i in range(word1_length): if i == word1_length - 1: continue pairs1.append(word1[i] + word1[i + 1]) for i in range(word2_length): if i == word2_length - 1: continue pairs2.append(word2[i] + word2[i + 1]) similar = [word for word in pairs1 if word in pairs2] return float(len(similar)) / float(max(len(pairs1), len(pairs2)))
def parse_citations(citations_text): """ """ citations = [c for c in citations_text.split("**ENTRY**") if c.strip()] citation_tuples = [] for citation in citations: if citation.startswith("doi"): citation_tuples.append( ("doi", citation[len("doi"):].strip() ) ) else: citation_tuples.append( ("bibtex", citation[len("bibtex"):].strip() ) ) return citation_tuples
def listsplit(liststr=''): """Return a split and stripped list.""" ret = [] for e in liststr.split(','): ret.append(e.strip()) return ret
def cliprgb(r, g, b): """ clip r,g,b values into range 0..254 """ def clip(x): """ clip x value into range 0..254 """ if x < 0: x = 0 elif x > 254: x = 254 return x return clip(r), clip(g), clip(b)
def _snmp_octetstr_2_string(binary_value): """Convert SNMP OCTETSTR to string. Args: binary_value: Binary value to convert Returns: result: String equivalent of binary_value """ # Convert and return result = ''.join( ['%0.2x' % ord(_) for _ in binary_value.decode('utf-8')]) return result.lower()
def _PruneMessage(obj): """Remove any common structure in the message object before printing.""" if isinstance(obj, list) and len(obj) == 1: return _PruneMessage(obj[0]) elif isinstance(obj, dict) and len(obj) == 1: for v in obj.values(): return _PruneMessage(v) else: return obj
def crr_m(ksigma, msf, crr_m7p5): """Cyclic resistance ratio corrected for magnitude and confining stress""" return crr_m7p5 * ksigma * msf
def power(n, power): """Prints the power""" value = n ** power print("%s to the power of %s is %s" % (n, power, value)) return n, power, value
def divide(a, b): """ >>> divide(10, 2) 5.0 >>> divide(15, 3) 5.0 >>> divide(12, 3) 4.0 """ return a / b try: return float(a) / float(b) except ValueError: return "You can't divide that data type!" except ZeroDivisionError: return "You can't divide by zero!"
def _get_db_value(value): """ Convert value into db value. """ if isinstance(value, str): result = value.encode("UTF-8") elif isinstance(value, int): result = b"%d" % value elif isinstance(value, bytes): result = value else: assert False return result
def map_per_image(label, predictions, k: int = 5): """Computes the precision score of one image. Parameters ---------- label : string The true label of the image predictions : list A list of predicted elements (order does matter, k predictions allowed per image) k : int MAP@k Returns ------- score : double """ try: return 1 / (predictions[:k].index(label) + 1) except ValueError: return 0.0
def extractImports(src): """ Extract the set of import statements in the given source code. We return a set object containing the import statements in the given source code. """ imports = set() for line in src.split("\n"): if line.startswith("import"): imports.add(line) elif line.startswith("from "): i = line.find(" import ") if i > -1: fromModule = line[5:i] modules = line[i+8:].split(",") for module in modules: imports.add("from "+fromModule+" import "+module.strip()) return imports
def respond_to(key=None): """ training sentences which the agent should have knowledge about """ respond = { "FACEBOOK_WELCOME": ['Greetings !, I am a weather robot glad to help you to find the forecast'], "NOT_FOUND": ["Sorry, I can't reach out this city !"], "GET_STARTED": ["How would you like to get a weather forecast?"], "TEMP": ["Temperature in <city> is <value> Celsius"], "WEATHER": { "TITLE": "Here is the forecast i found", "TEMP": "Temperature is <value> Celsius", "MAX": "Maximum temperature is <value> Celssius", "MIN": "Minimum temperature is <value> Celssius", "HUMIDITY": "Humidity is <value> %", "STATUS": "Weather status <value>", "WIND": "Wind speed is <value> m/s", }, "CANT_UNDERSTAND": ["I can't understand your sentence structure !!"], "VIA_CITY": ["Please enter the city name"], "VIA_GPS": ["Please wait i am getting your GPS coordinates", { "WEATHER": { "TITLE": "Here is the forecast i found", "TEMP": "Temperature is <value> Celsius", "MAX": "Maximum temperature is <value> Celssius", "MIN": "Minimum temperature is <value> Celssius", "HUMIDITY": "Humidity is <value> %", "STATUS": "Weather status <value>", "WIND": "Wind speed is <value> m/s", } }] } return respond[key] if key is not None else respond
def make_dummy_notebook_name(fig_no): """ convert 1.11 to fig_1_11.ipynb """ return f"fig_{fig_no.replace('.','_')}.ipynb"
def get_scales(acc, scale): """Returns the item scales required to get the accumulator value given the global scale""" res = [] i = scale while acc > 0: if acc & 1: res.append(i) acc >>= 1 i -= 1 return res
def get_character_interactions(links, main_ch): """ Gets the interactions of all characters with the main character :param links: List of all links in the network :param main_ch: The assumes main character name :return: Dictionary of all characters and their interactions with the main character """ character_interactions = {} for link in links: if link['source'] == main_ch: character_interactions[link['target']] = link['value'] elif link['target'] == main_ch: if link['source'] in character_interactions.keys(): character_interactions[link['source']] += link['value'] else: character_interactions[link['source']] = link['value'] return character_interactions
def patch_id(options): """Returns the review ID or the GitHub pull request number.""" return options['review_id'] or options['github']
def sequence_accuracy_score(y_true, y_pred): """ Return sequence accuracy score. Match is counted only when the two sequences are equal. :param y_true: true labels :param y_pred: predicted labels :return: sequence accuracy as a fraction of the sample (1 is prefect, 0 is all incorrect) """ total = len(y_true) matches = sum(1 for yseq_true, yseq_pred in zip(y_true, y_pred) if list(yseq_true) == list(yseq_pred)) return matches / total
def _escape(s): """ Escape HTML characters and return an escaped string. """ s = s.replace('&', '&amp;') s = s.replace('<', '&lt;') s = s.replace('>', '&gt;') return s
def myround(x, base=5, integer=True, round_up=False): """ Round up values - mappable function for pandas processing NOTES: - credit: Alok Singhal """ # round_up=True # Kludge - always set this to True # round to nearest base number rounded = base * round(float(x)/base) if round_up: # ensure rounded number is to nearest next base if rounded < x: rounded += base if integer: return int(rounded) else: return rounded
def pos_upper(num, string): """ Returns a string containing its first argument, and its second argument in upper case. :param num: int :param string: str :return: str """ return f'{num}:{string.upper()}'
def get_resource(row): """Get resource from STO query result row.""" resource_split_list = row.split('/') resource = '/'.join(resource_split_list[4:]) return resource
def count_ways(target_value, available_coins, currently_considered=0): """Returns number of ways in which a given `target_value` may be realized with the use of an infinite number of `available_coins` of given values.""" # If target == 0, then there is only one valid solution # (use 0 of each of the available coins): if target_value == 0: return 1 # There is no way to obtain a negative sum, either: if target_value < 0: return 0 # If there are no more coins to use, but the target value is not zero, # there is no way to obtain the target value: if currently_considered >= len(available_coins) and target_value != 0: return 0 # The number of the ways is a sum of two simpler cases: # (1): solutions that do not use the first coin at all # (2): solutions that use the first coin at least once. return (count_ways(target_value, available_coins, currently_considered+1) + count_ways(target_value-available_coins[currently_considered], available_coins, currently_considered))
def set_line_style(color, width=3, line_style="solid"): """ Defines default styling of scatter graphs with some smoothing. Args: color: line_style: Returns: line_style dict parameters """ style = dict( color=color, width=width, # shape='spline', # smoothing=1.3, dash=line_style ) return style
def _digest_buffer(buf): """Debug function for showing buffers""" if not isinstance(buf, str): return ''.join(["\\x%02x" % c for c in buf]) return ''.join(["\\x%02x" % ord(c) for c in buf])
def _extract_values_json(obj, key): """Pull all values of specified key from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict, list)): extract(v, arr, key) elif k == key: arr.append(v) elif isinstance(obj, list): for item in obj: extract(item, arr, key) return arr results = extract(obj, arr, key) return results
def rgb(red, green, blue): """ Return the string HTML representation of the color in 'rgb(red, blue, green)' format. :param red: 0 <= int <= 255 :param green: 0 <= int <= 255 :param blue: 0 <= int <= 255 :return: str """ assert isinstance(red, int) assert 0 <= red < 256 assert isinstance(green, int) assert 0 <= green < 256 assert isinstance(blue, int) assert 0 <= blue < 256 return 'rgba(%d, %d, %d)' % (red, green, blue)
def make_passwd_line(claims): """Create an entry for /etc/passwd based on our claims. Returns a newline-terminated string. """ uname = claims["uid"] uid = claims["uidNumber"] pwline = "{}:x:{}:{}::/home/{}:/bin/bash\n".format(uname, uid, uid, uname) return pwline
def FormatLogMessage(msg,context,level): """ Generic log message formatter. This is a crude initial attempt: I'm sure we could do much better. msg - is message to be logged context - is a string describing the source of the message (can be used for filtering) level - indicates the message severity: 0 - diagnostic, 1 - warning, 2 - error """ if level == 0: leveltag = "TRACE" elif level == 1: leveltag = "INFO" elif level == 2: leveltag = "WARNING" elif level == 3: leveltag = "ERROR" else: leveltag = "UKNOWN" if context: context = context+": " return "%s%s - %s" % (context,leveltag,msg)
def rgb_to_hsv(r, g, b): """ Convert a color from rgb space to hsv :param r: red composant of rgb color :param g: green composant of rgb color :param b: blue composant of rgb color :return: h, s, v composants """ maxc = max(r, g, b) minc = min(r, g, b) v = maxc if minc == maxc: return 0.0, 0.0, v s = (maxc-minc) / maxc rc = (maxc-r) / (maxc-minc) gc = (maxc-g) / (maxc-minc) bc = (maxc-b) / (maxc-minc) if r == maxc: h = bc-gc elif g == maxc: h = 2.0+rc-bc else: h = 4.0+gc-rc h = (h/6.0) % 1.0 return h, s, v
def do_something(a, b, c=None): """Do something. """ return a + b if c else 0
def expandPrefix(prefix): """Expand prefix string by adding a trailing period if needed. expandPrefix(p) should be used instead of p+'.' in most contexts. """ if prefix and not prefix.endswith('.'): return prefix + '.' return prefix
def IsNumeric(value): """ * Determine if string is numeric. """ if not isinstance(value, str): raise Exception('value must be a string.') try: valtxt = value value = int(valtxt) value = float(valtxt) return True except: return False
def convert_to_binary(decimal) -> str: """ Converts Decimal numbers into Binanry Digits """ binary = bin(decimal).replace("0b", "") return binary
def clip_black_by_channels(color, threshold): """Replace any individual r, g, or b value less than threshold with 0. color: an (r, g, b) tuple threshold: a float """ r, g, b = color if r < threshold: r = 0 if g < threshold: g = 0 if b < threshold: b = 0 return (r, g, b)
def isproductofsmallprimes(num): """ CLFFT only supports array sizes which are products of primes <= 13; Is this integer a product of primes no greater than that? """ tmp = num*1 # make copy small_primes = [2,3,5,7,9,11,13] for p in small_primes: quotient, remainder = divmod(tmp, p) while not remainder: tmp = quotient quotient, remainder = divmod(tmp, p) if tmp==1: return True # if we get to 1 we're done return False
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start/<start><br/>" f"/api/v1.0/start/<start>/end/<end>" )
def w_fct(stim, color_control): """function for word_task, to modulate strength of word reading based on 1-strength of color_naming ControlSignal""" # print('stim: ', stim) # print("Color control: ", color_control) return stim * (1 - color_control)
def is_command(meth): """ Return True if method is an exposed Lua command """ return getattr(meth, '_is_command', False)
def IsHash(git_hash): """Returns True iff git_hash is a full SHA-1 hash. Commits keyed by full git hashes are guaranteed to not change. It's unsafe to cache things that can change (e.g. `HEAD`, `master`, tag names) """ return git_hash.isalnum() and len(git_hash) == 40
def str_to_nat(s): """Convert string to natural number.""" return ord(s) - ord("a")
def display_value(value: float, thousands_separator: str = ',', decimal_separator: str = '.') -> str: """ Display a value as a string with specific format. Parameters ---------- value : float Value to display. thousands_separator : str The separator used to separate thousands. decimal_separator : str The separator used to separate decimal values. Returns ------- str Examples -------- >>> display_value(1255000, thousands_separator=',') '1,255,000' """ value_str = '{:,}'.format(value).replace(',', '/thousands/').replace('.', '/decimal/') return value_str.replace('/thousands/', thousands_separator).replace('/decimal/', decimal_separator)
def parse_url(url: str) -> str: """ Makes sure the URL starts with 'http://' """ # Replace HTTPS with HTTP (if exists) url = url.replace("https://", "http://") if url.startswith("http://"): return url return f"http://{url}"
def date(string): """Strip off the T from the datetime string""" return string.replace('T', ' ')
def split1d(Astart,Aend,Bstart,Bend): """For a 1-d pair of lines A and B: given start and end locations, produce new set of points for A, split by B. For example: split1d(1,9,3,5) splits the line from 1 to 9 into 3 pieces, 1 to 3 3 to 5 and 5 to 9 it returns these three pairs and a list of whether those points were inside B. In this case the list is [False,True,False] """ #five options #1 A and B don't intersect. This shouldn't happen if (Astart>=Bend) or (Bstart>=Aend): #Not sure what to do assert False #2 B starts first, and ends inside A: if (Astart>=Bstart) and (Bend<Aend): #return Astart-Bend Bend-Aend return [[Astart,Bend],[Bend,Aend]], [True, False] #3 B extends beyond limits of A in both directions: if (Bstart<=Astart) and (Bend>=Aend): #return A return [[Astart,Aend]], [True] #4 B starts in A and finishes after A if (Astart<Bstart) and (Bend>=Aend): #return Astart-Bstart Bstart-Aend return [[Astart,Bstart],[Bstart,Aend]], [False,True] #5 B is inside A if (Astart<Bstart) and (Bend<Aend): #return Astart-Bstart Bstart-Bend Bend-Aend return [[Astart,Bstart],[Bstart,Bend],[Bend,Aend]], [False,True,False]
def format_card(note: str) -> str: """Formats a single org-mode note as an HTML card.""" lines = note.split('\n') if lines[0].startswith('* '): card_front = '<br />{}<br />'.format(lines[0][2:]) else: print('Received an incorrectly formatted note: {}'.format(note)) return '' card_back = '<br />'.join(lines[1:]) return card_front + '\t' + card_back
def os_ls(thepath="."): """Displays the content of the given directory. Default value is the current directory. Examples: >>> os_ls()\n ['temp.py', 'worksheet.py'] >>> os_ls('../..')\n ['ps1_files', 'sec_ops', 'pyplay', 'bashplay'] """ import os return os.listdir(thepath)
def obter_pos_l(pos): """ obter_pos_l: posicao -> str Recebe uma posicao e devolve a componente linha da posicao. """ return pos['l']
def get_available_directions(character: dict, columns: int, rows: int) -> list: """ Get the list of available directions. :param character: a dictionary :param columns: an integer :param rows: an integer :precondition: character must be a dictionary :precondition: columns >= 0 :precondition: rows >= 0 :precondition: character keys must have "X-coordinate" and "Y-coordinate" :precondition: character values must be integers that are >= 0 :postcondtition: returns a list of available directions based on current character's coordinates :postcondtion: :return: available directions as a list >>> get_available_directions({"Y-coordinate": 0, "X-coordinate": 0}, 4, 4) ['south', 'east'] >>> get_available_directions({"Y-coordinate": 1, "X-coordinate": 1}, 4, 4) ['north', 'south', 'west', 'east'] >>> get_available_directions({"Y-coordinate": 1, "X-coordinate": 3}, 4, 4) ['north', 'south', 'west'] """ available_directions = [] if character["Y-coordinate"] > 0: available_directions.append("north") if character["Y-coordinate"] < rows - 1: available_directions.append("south") if character["X-coordinate"] > 0: available_directions.append("west") if character["X-coordinate"] < columns - 1: available_directions.append("east") return available_directions
def count_words(my_string): """ This function counts words :param my_string: str - A string of words or characters :return: int - length of words """ if not isinstance(my_string, str): raise TypeError("only accepts strings") special_characters = ['-', '+', '\n'] for character in special_characters: my_string = my_string.replace(character, " ") words = my_string.split() return len(words)
def remove_leading_trailing_pipe(line): """ Remove optional leading and trailing pipe """ return line.strip('|')
def cookable_recipes(ings, recipes): """ # Takes in a list of ingredients and a dictionary # of recipes. Returns the recipes that are able to be # made. A recipe can be made if all the components # are in the ingredients list. >>> rec = {'Egg Fried Rice': ['egg', 'rice', 'msg'], \ 'Spaghetti': ['noodle', 'tomato sauce'], 'Steamed Rice': ['rice']} >>> cookable_recipes(['egg', 'msg', 'rice'], rec) ['Egg Fried Rice', 'Steamed Rice'] >>> cookable_recipes(['egg', 'rice', 'msg', 'noodle', 'tomato sauce'], rec) ['Egg Fried Rice', 'Spaghetti', 'Steamed Rice'] >>> cookable_recipes(['egg'], rec) [] # Add at least 3 doctests below here # >>> cookable_recipes(['eggs', 'beef', 'flour'], {'Egg Noodle': \ ['egg', 'flour'], 'Beef Noodle': ['eggs', 'beef', 'flour'], \ 'Beef Wrap': ['flour', 'beef']}) ['Beef Noodle', 'Beef Wrap'] >>> cookable_recipes([], {}) [] >>> cookable_recipes(['egg', 'beefs', 'flour'], {'Egg Noodle': \ ['egg', 'flour'], 'Beef Noodle': ['eggs', 'beef', 'flour'], \ 'Beef Wrap': ['flour', 'beef']}) ['Egg Noodle'] """ possible_recipes = [] ings_counter = 0 for keys, values in recipes.items(): for j in ings: if j in values: ings_counter += 1 if ings_counter == len(values): possible_recipes.append(keys) break ings_counter = 0 return possible_recipes
def _str_to_bool(s): """Convert either of the strings 'True' or 'False' to their Boolean equivalent""" if s == 'True': return True elif s == 'False': return False else: raise ValueError("Please specify either True or False")
def parse_int(val, name): """Parse a number to an integer if possible""" if val is None: return val try: return int(val) except ValueError: raise ValueError( f"Please provide a number for {name}, instead of {val}" )
def check_bit(val, offs): """Test bit at offset 'offs' in value.""" return True if val & (1 << offs) else False
def get_vector(vector, vulnerability): """Get a vector out of the CVSS definition (if present) for a vulnerability.""" vectors = [] # Some sources have metadata as { metadata: NVD: CVSSv3: Vectors: "..." } # and others have { metadata: CVSSv2: "..." } if 'metadata' in vulnerability: if 'NVD' in vulnerability['metadata']: vectors = vulnerability['metadata']['NVD'].get( 'CVSSv3', {}).get('Vectors', '').split('/') if len(vectors) == 1: vectors = vulnerability['metadata']['NVD'].get( 'CVSSv2', {}).get('Vectors', '').split('/') else: cvssV2 = vulnerability['metadata'].get('CVSSv2', None) if isinstance(cvssV2, str): vectors = cvssV2.split('/') # The first element is the score, which we're not using here vectors.pop(0) found = list(filter(lambda x: vector in x, vectors)) if found: return found[0] return None
def get_tag_list(itera): """ Multiple items has the name as a tag value, this includes directors and genres, this function creates a horizontal string list of the tag attribute from all objects in a list :param itera: iterable containing elements with a tag attribute :return: horizontal string list of with the tag attribute from each element """ taglist = "" for item in itera: taglist += item.tag if len(itera) > 1: taglist += " | " return taglist
def ping(): """Pinging back and example of function with types documented in the docstring. `PEP 484`_ type annotations are supported. If attribute, parameter, and return types are annotated according to `PEP 484`_, they do not need to be included in the docstring: Args: param1 (int): The first parameter. param2 (str): The second parameter. Returns: bool: The return value. True for success, False otherwise. .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ return {"ping": "pong"}
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/<start><br/>" f"/api/v1.0/<start>/<end><br/>" )
def validate_line(line): """ Validates ``line``. """ # if not VALID_PATTERN.match(line): # raise MalformedPacket("Got malformed packet: {}".format(line)) return True
def add_filters(input, output): """ This function is designed to filter output when using include, exclude, etc. :param input: Raw output string :param output: Raw output from command :return: Filtered string """ if "|" in input: newout = "" incmd = input.split("|")[1].strip() filterlist = incmd.split(" ") outlist = output.split("\n") newout = outlist[0] + "\n" if filterlist[0] in ["i", "in", "inc", "incl", "inclu", "includ", "include"]: for o in outlist[1:]: if " ".join(filterlist[1:]).lower() in o.lower(): newout += o + "\n" elif filterlist[0] in ["e", "ex", "exc", "excl", "exclu", "exclud", "exclude"]: for o in outlist[1:]: if " ".join(filterlist[1:]).lower() not in o.lower(): newout += o + "\n" elif filterlist[0] in ["b", "be", "beg", "begi", "begin"]: foundbeg = False for o in outlist[1:]: if " ".join(filterlist[1:]).lower() in o.lower(): foundbeg = True if foundbeg: newout += o + "\n" if newout[-2:] == "\n\n": return newout[0:-1] else: return newout return output
def format_node(cluster_name, node): """Formats a string representation of a node.""" return '<{0}[{1}]>'.format(cluster_name, node)
def _get_matched_row(rows, lookup): """ Return row that matches lookup fields. """ for index, row in enumerate(rows): matched = True for field, value in lookup.items(): if str(row.get(field, '')).strip() != value: matched = False break if matched: return index, row return None, None
def format_title(artist: str, title: str) -> str: """Removes artist name if "Genius" is in the artist name Args: artist (str): item artist. title (str): item title/name. Returns: str: formatted title. """ if "Genius" in artist: final_title = title else: final_title = f"{artist} - {title}" return final_title
def get_null_value(value): """Gets None from null token""" if value.lower().strip(' ') == "null": return None else: return value
def transform_databases(values): """Transform the output of databases to something more manageable. :param list values: The list of values from `SHOW DATABASES` :rtype: dict """ output = {} for row in values: if row['name'] not in output: output[row['name']] = {} for k, v in row.items(): if k in ['database', 'force_user', 'host', 'name', 'port', 'pool_mode']: continue output[row['name']][k] = v return output
def str_to_list(str, def_val=[]): """ try to return a list of some sort """ ret_val = def_val try: ret_val = str.split(",") finally: try: if ret_val is None: ret_val = [str] except: pass return ret_val
def fname_remove_invalid_chars(fname: str, symbol='-') -> str: """ Takes a file name with potentially invalid characters, and substitutes the symbol in, in place of those invalid characters. Arguments: fname: str (name of file) symbol: str (symbol to substitute invalid characters to) Returns: str with the new file name containing symbol in place of any illegal characters """ # Replace invalid characters with - to make filename valid INVALID_CHARS = ["/", ":"] for char in INVALID_CHARS: if (fname.find(char) != -1): temp = list(fname) temp[fname.find(char)] = symbol fname = "".join(temp) return fname
def listget(lst, ind, default=None): """ Returns `lst[ind]` if it exists, `default` otherwise. >>> listget(['a'], 0) 'a' >>> listget(['a'], 1) >>> listget(['a'], 1, 'b') 'b' """ if len(lst)-1 < ind: return default return lst[ind]
def _fix_axis_dim_pairs(pairs, name): """Helper function to make `pairs` a list if needed.""" if isinstance(pairs[0], int): pairs = [pairs] for pair in pairs: if len(pair) != 2: raise ValueError( '{} must consist of axis-value pairs, but found {}'.format( name, pair)) return pairs
def package_in_installed(new_package, installed): """ Searches for new_package in the installed tree, returns error message (or empty string) (checks the root of the tree and walks the installed tree) """ conflict = "" if 'dependencies' in installed: previous = installed['dependencies'] for used in previous.keys(): # logger.debug("=====\npackage\n%s\nvs\n%s" % (pprint.pformat(new_package), pprint.pformat(previous[used]))) used_conflict="" if new_package['package_description']['name'] == used: if 'archive' in new_package and new_package['archive']: # this is a dependency of the new package, so we have archive data if new_package['archive']['url'].rsplit('/',1)[-1] \ != previous[used]['archive']['url'].rsplit('/',1)[-1]: used_conflict += " installed url %s\n" % previous[used]['archive']['url'] used_conflict += " vs %s\n" % new_package['archive']['url'] if new_package['archive']['hash'] != previous[used]['archive']['hash']: used_conflict += " installed hash %s\n" % previous[used]['archive']['hash'] used_conflict += " vs %s\n" % new_package['archive']['hash'] else: # this is the newly imported package, so we don't have a url for it pass if new_package['configuration'] != previous[used]['configuration']: used_conflict += " installed configuration %s\n" % previous[used]['configuration'] used_conflict += " vs %s\n" % new_package['configuration'] if new_package['package_description']['version'] != previous[used]['package_description']['version']: used_conflict += " installed version %s\n" % previous[used]['package_description']['version'] used_conflict += " vs %s\n" % new_package['package_description']['version'] if new_package['build_id'] != previous[used]['build_id']: used_conflict += " installed build_id %s\n" % previous[used]['build_id'] used_conflict += " vs %s\n" % new_package['build_id'] if used_conflict: conflict += used + "\n" + used_conflict else: # recurse to check the dependencies of previous[used] conflict += package_in_installed(new_package, previous[used]) if conflict: conflict += "used by %s version %s build %s\n" % \ ( previous[used]['package_description']['name'], previous[used]['package_description']['version'], previous[used]['build_id']) if conflict: # in order to be able to add the import path, we only detect the first conflict return conflict return ""
def search_st(ingroup: list, potential_rank: list, potential_group: list, subtrees): """ given the membership of the partition dictated by a snp, what subtree has that membership Parameters ---------- ingroup : list Itemized list of leaf members that either all have the ref allele or the alt allele potential_rank : list Currently identified potential subtree ranks that might be supported by the partition potential_group : list Currently identified potential subtree group ids that might be supported by the partition subtrees : dictionary contains the subtree information, keys represent the size of the sub tree, values are a tuple of leaf names, rank_id, g_id Returns ------- potential_rank : list Currently identified potential subtree ranks that might be supported by the partition potential_group : list Currently identified potential subtree group ids that might be supported by the partition """ # extract the size of the snp sharing group part_size = len(ingroup) # get the dictionary section that corresponds to the trees of the same size # as the snp sharing group if it exists if part_size not in subtrees.keys(): return potential_rank, potential_group potential = subtrees[part_size] ingroup.sort() # for each subtree of the target size check to see if it has # the same members as the snp sharing group for item in potential: from_subtrees = item[0] from_subtrees.sort() if from_subtrees == ingroup: potential_rank.append(item[1]) potential_group.append(item[2]) # sort through the potential subtrees and order based on rank id if len(potential_rank) > 1: target_index = 0 for i in range(0, len(potential_rank)): if potential_rank[i] == min(potential_rank): target_index = i potential_rank = [potential_rank[target_index]] potential_group = [potential_group[target_index]] return potential_rank, potential_group
def _nested_splitchars(x, encoding): """Replace each string in a nested list with a list of char substrings.""" if isinstance(x, list): return [_nested_splitchars(v, encoding) for v in x] else: b = x.encode("utf-32-be") chars = zip(b[::4], b[1::4], b[2::4], b[3::4]) if str is bytes: return [b"".join(c).decode("utf-32-be").encode(encoding) for c in chars] else: return [bytes(c).decode("utf-32-be").encode(encoding) for c in chars]
def find_in_path(filenames): """Find file on system path.""" # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52224 from os.path import exists, join, abspath from os import pathsep, environ search_path = environ["PATH"] paths = search_path.split(pathsep) for path in paths: for filename in filenames: if exists(join(path, filename)): return abspath(join(path, filename))
def timeToTuple(duration): """Converts time float to tuple Args: duration (float): converts duration to a tuple Returns: tuple: Duration split into hours, minutes, and seconds """ hours, rem = divmod(duration, 3600) minutes, rem2 = divmod(rem, 60) seconds, mseconds = divmod(rem2, 1) return int(hours), int(minutes), int(seconds), round(mseconds * 1000)
def format_commands_help(cmds): """ Helps format plugin commands for display. """ longest_cmd_name = max(cmds.keys(), key=len) help_string = "" for cmd in sorted(cmds.keys()): # For the top-level entry point, `cmds` is a single-level # dictionary with `short_help` as the values. For plugins, # `cmds` is a two-level dictionary, where `short_help` is a # field in each sub-dictionary. short_help = cmds[cmd] if isinstance(short_help, dict): short_help = short_help["short_help"] num_spaces = len(longest_cmd_name) - len(cmd) + 2 help_string += " %s%s%s\n" % (cmd, " " * num_spaces, short_help) return help_string
def generate_results_file_name(world_folder): """ Generate a filename to output results to, with no file extension. """ name = world_folder if world_folder[:9] == "tw_games/": if world_folder[-1:] == "/": name = world_folder[9:-1] else: name = world_folder[9:] else: name = world_folder return "test_results/" + name
def get_mr_title(commit_prefix, source_branch): """Gets the title of the MR. If a prefix exists we add it to the URL. By default we add a prefix of WIP, so the MR doesn't get merged by accident. Args: commit_prefix (str): Prefix for the MR title i.e. WIP. source_branch (str): The source branch to merge into.. Returns: str: Title of the MR we will create . """ commit_title = source_branch if commit_prefix: commit_title = f"{commit_prefix}: {commit_title}" return commit_title
def edit_form_link(link_text='Submit edits'): """Return HTML for link to form for edits""" return f'<a href="https://docs.google.com/forms/d/e/1FAIpQLScw8EUGIOtUj994IYEM1W7PfBGV0anXjEmz_YKiKJc4fm-tTg/viewform">{link_text}</a>'
def _is_clustal_seq_line(line): """Returns True if line starts with a non-blank character but not 'CLUSTAL' Useful for filtering other lines out of the file. """ return line and (not line[0].isspace()) and\ (not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE'))
def point_in_polygon(point, polygon): """ Determines whether a [x,y] point is strictly inside a convex polygon defined as an ordered list of [x,y] points. :param point: the point to check :param polygon: the polygon :return: True if point is inside polygon, False otherwise """ x = point[0] y = point[1] n = len(polygon) inside = False xints = 0.0 p1x, p1y = polygon[0] for i in range(n + 1): p2x, p2y = polygon[i % n] if y > min(p1y, p2y): if y <= max(p1y, p2y): if x <= max(p1x, p2x): if p1y != p2y: xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x if p1x == p2x or x <= xints: inside = not inside p1x, p1y = p2x, p2y return inside
def extract_from_dictionary(ls_of_dictionaries, key_name): """ Iterates through a list of dictionaries and, based on the inserted key name, extracts that data. :param: ls_of_dictionaries: a list of dictionaries :param: key_name: a string with ('') that indexes which set of the dictionary you want to extract :returns: list with the specified (keyed) datatype """ #index = [] partic_name = [] data_element = [] for index, dictionary in enumerate(ls_of_dictionaries): data = dictionary[key_name] partic_name = dictionary['partic_number'] data_element.append(data) return(data_element)
def height_human(float_inches): """Takes float inches and converts to human height in ft/inches""" feet = int(round(float_inches / 12, 2)) # round down inches_left = round(float_inches - feet * 12) result = f"{feet} foot, {inches_left} inches" return result
def iou(box_a, box_b, norm): """Apply intersection-over-union overlap between box_a and box_b """ xmin_a = min(box_a[0], box_a[2]) ymin_a = min(box_a[1], box_a[3]) xmax_a = max(box_a[0], box_a[2]) ymax_a = max(box_a[1], box_a[3]) xmin_b = min(box_b[0], box_b[2]) ymin_b = min(box_b[1], box_b[3]) xmax_b = max(box_b[0], box_b[2]) ymax_b = max(box_b[1], box_b[3]) area_a = (ymax_a - ymin_a + (norm == False)) * (xmax_a - xmin_a + (norm == False)) area_b = (ymax_b - ymin_b + (norm == False)) * (xmax_b - xmin_b + (norm == False)) if area_a <= 0 and area_b <= 0: return 0.0 xa = max(xmin_a, xmin_b) ya = max(ymin_a, ymin_b) xb = min(xmax_a, xmax_b) yb = min(ymax_a, ymax_b) inter_area = max(xb - xa + (norm == False), 0.0) * max(yb - ya + (norm == False), 0.0) iou_ratio = inter_area / (area_a + area_b - inter_area) return iou_ratio
def get_tex_label(fs): """Makes labels look nice. Parameters ---------- fs : string An annihilation final state for one of the models defined in hazma. Returns ------- label : string The LaTeX string to be used for labeling plots with the final state. """ tex_label = r"$" + fs tex_label = tex_label.replace("pi0", r"\pi^0") tex_label = tex_label.replace("pi pi", r"\pi^+ \pi^-") tex_label = tex_label.replace("mu mu", r"\mu^+ \mu^-") tex_label = tex_label.replace("g", r"\gamma") tex_label = tex_label.replace("e e", r"e^+ e^-") tex_label = tex_label.replace("x x", r"\bar{\chi} \chi") tex_label = tex_label.replace("s s", r"S S") tex_label = tex_label.replace("v v", r"V V") tex_label = tex_label.replace("pi0 v", r"\pi^0 V") return tex_label + r"$"
def z_score(x, mean, std): """z_score""" return (x - mean) / std
def unique(data): """ in python 3: TypeError: '<' not supported between instances of 'int' and 'str' need to keep the same Type of member in List """ data.sort() l = len(data) - 1 i = 0 while i < l: if (data[i] == data[i + 1]): del data[i] i -= 1 l -= 1 i += 1 return data
def ned_enu_conversion(eta, nu): """Rotates from north-east-down to east-north-up Args: eta (array) : Drone position and rotation nu (array) : Twitch of the drone - angular and linear velocities Returns: Array: Rotated eta and nu """ # yaw velocity is wrong -> ask aksel why! return [eta[0], eta[1], eta[2], eta[3], eta[4], eta[5]], [ nu[0], nu[1], nu[2], nu[3], nu[4], -nu[5], ]
def getBasePV(PVArguments): """ Returns the first base PV found in the list of PVArguments. It looks for the first colon starting from the right and then returns the string up until the colon. Takes as input a string or a list of strings. """ if type(PVArguments) != list: PVArguments = [PVArguments] for arg in PVArguments: if ':' not in arg: continue for i, char in enumerate(arg[::-1]): if char == ':': return arg[:-i] return None
def tinyurlFindUrlend( msg, urlstart ): """Finds the ends of URLs (Strips following punctuation)""" m = msg[urlstart:] index = m.find( " " ) if index == -1: index = len(m) while msg[index-1] in ( "?", ".", "!" ): index -= 1 return index + urlstart
def regular_polygon_area(perimeter, apothem): """Returns the area of a regular polygon""" # You have to code here # REMEMBER: Tests first!!! return (1/2) * perimeter * apothem
def bytearray_xor(b1, b2): """ xor 2 bytearray Args: b1 -- bytearray b2 -- bytearray return a bytearray """ result = bytearray() for x, y in zip(b1, b2): result.append(x ^ y) return result
def format_revision(sha): """ Return a shorter git sha """ return sha[:7]