content
stringlengths
42
6.51k
def _recall(conf_mat): """ Compute the recall score, i.e. the ratio of true positives to true positives and false negatives. Answers the question: "Which share of the pixels that are actually slum was identified by the model as such?" :param conf_mat: Confusion matrix produced by conf_mat(). :return: Recall score, ranging from 0 to 1. """ # print('recall: ', conf_mat['tp'], conf_mat['tn'], conf_mat['fp'], conf_mat['fn']) if conf_mat['tp'] + conf_mat['fn'] == 0: recall = 0 else: recall = conf_mat['tp'] / (conf_mat['tp'] + conf_mat['fn']) return recall
def swap_dict_key_and_values(d): """ Given a dictionary, return a dictionary with the keys and values of the original dictionary swapped """ d2 = {} for key, value in d.items(): if type(value)==int: d2[int(value)] = key else: d2['{}'.format(value)] = key return d2
def snake_to_camel(word: str) -> str: """Converts string in snake case to camel case. For example, "test_string" becomes "TestString" """ return ''.join(x.capitalize() or '_' for x in word.split('_'))
def _str_fmt_dct(dct): """Assumes dict mapping str to float.""" return " | ".join("%s: %.4g" % (k, v) for k, v in dct.items())
def get_number(num): """Return the number one less than the given positive number. If the number is nonpositive, return a string "Enter a positive number!". Arguments: num -- an integer. Return values: An integer one less than the input number. """ return "Enter a positive number!" if num < 1 else num - 1
def long_birth(well, origin, irid): """If the well is empty and the well h distance away is an xantophore, create a melanophore""" if (well == 'S') & (origin == 'X') & (~ irid): return 'M' else: return well
def attribute_hex(x): """return a python code string for a hex value""" if x is None: return 'None' return '0x%x' % x
def prodtypes_remediation(rule_obj, r_type): """ For a rule object, check if the prodtypes match between the YAML and the remediations of type r_type. """ rule_id = rule_obj['id'] rule_products = set(rule_obj['products']) if not rule_products: return remediation_products = set() for remediation in rule_obj['remediations'][r_type]: remediation_products.update(rule_obj['remediations'][r_type][remediation]['products']) if not remediation_products: return sym_diff = sorted(rule_products.symmetric_difference(remediation_products)) check = len(sym_diff) > 0 and rule_products and remediation_products if check: return "\trule_id:%s has a different prodtypes between YAML and %s remediations: %s" % \ (rule_id, r_type, ','.join(sym_diff))
def get_theta(pressure, temperature): """calculate potential temperature profile""" # standard reference pressure [Pa] ref_pressure = 1e5 # gas constant [kg m**2 s**-2 K**-1 mol*-1] gas_constant = 8.3144598 # specific heat capacity at constant pressure for air spec_heat_capacity = 29.07 return ( temperature * (ref_pressure / pressure) ** (gas_constant / spec_heat_capacity) )
def cleanup_ip(ip): """ Given ip address string, it cleans it up """ ip = ip.strip().lower() if (ip.startswith('::ffff:')): return ip.replace('::ffff:', '') return ip
def is_integer(obj): """ Return True if *obj* is an int, False otherwise. """ return isinstance(obj, int)
def writeBenchScript(dir, benchmark_name, size, synthetic): """ This method creates a script in dir which will be eventually passed to the simulated system (to run a specific benchmark at bootup). """ input_file_name = '{}/run_{}_{}'.format(dir, benchmark_name, size) if (synthetic): with open(input_file_name,"w") as f: f.write('./{} -g {}\n'.format(benchmark_name, size)) elif(synthetic==0): with open(input_file_name,"w") as f: f.write('./{} -sf {}'.format(benchmark_name, size)) return input_file_name
def is_not_excluded_type(file, exclude_types): """Return False if file type excluded, else True""" if exclude_types: for exclude_type in exclude_types: if file.lower().endswith(exclude_type.lower()): return False return True
def url_parse_server_protocol(settings_dict): """Return the public HTTP protocol, given the public base URL >>> url_parse_server_protocol({'USE_SSL': True}) 'https' >>> url_parse_server_protocol({'USE_SSL': False}) 'http' """ return "https" if settings_dict["USE_SSL"] else "http"
def chunks_alignment_sequence(alignment_sequence_pairs, min_length): """Yield successive n-sized chunks from l.""" chunks = [] for i in range(0, len(alignment_sequence_pairs), min_length): chunks.append(alignment_sequence_pairs[i:i + min_length]) return chunks
def generate_parallelogrammatic_board(width=5, height=5): """ Creates a board with a shape of a parallelogram. Width and height specify the size (in fields) of the board. """ return [[1] * height for _ in range(width)]
def freezedicts(obj): """Recursively iterate over ``obj``, supporting dicts, tuples and lists, and freeze ``dicts`` such that ``obj`` can be used with hash(). """ if isinstance(obj, (list, tuple)): return type(obj)([freezedicts(sub) for sub in obj]) if isinstance(obj, dict): return frozenset(six.iteritems(obj)) return obj
def get_tags_from_message(message): """ Given a message string, extracts hashtags and returns a comma-separated list :param message: a Hipchat message body """ tags = {word.strip('#') for word in message.split() if word.startswith('#')} return ','.join(tags)
def _convert_index(index, pos, m=None, is_start=True): """Converts index.""" if index[pos] is not None: return index[pos] n = len(index) rear = pos while rear < n - 1 and index[rear] is None: rear += 1 front = pos while front > 0 and index[front] is None: front -= 1 assert index[front] is not None or index[rear] is not None if index[front] is None: if index[rear] >= 1: if is_start: return 0 else: return index[rear] - 1 return index[rear] if index[rear] is None: if m is not None and index[front] < m - 1: if is_start: return index[front] + 1 else: return m - 1 return index[front] if is_start: if index[rear] > index[front] + 1: return index[front] + 1 else: return index[rear] else: if index[rear] > index[front] + 1: return index[rear] - 1 else: return index[front]
def anagrams(S): # S is a set of strings """group a set of words into anagrams :param S: set of strings :returns: list of lists of strings :complexity: :math:`O(n k log k)` in average, for n words of length at most k. :math:`O(n^2 k log k)` in worst case due to the usage of a dictionary. """ d = {} # maps s to list of words with signature s for word in S: # group words according to the signature s = ''.join(sorted(word)) # calculate the signature if s in d: d[s].append(word) # append a word to an existing signature else: d[s] = [word] # add a new signature and its first word # -- extract anagrams, ingoring anagram groups of size 1 return [d[s] for s in d if len(d[s]) > 1]
def window_bounds(i, n, wn): """Start and stop indices for a moving window. Parameters ---------- i : int Current index n : int Total number of points wn : int, odd Total window size Returns ------- start : int Start index stop : int Stop index at_end : bool Whether we are truncating the window """ at_end = False hw = wn // 2 start = i - hw stop = i + hw + 1 if start < 0: at_end = True start = 0 elif stop > n: at_end = True stop = n return start, stop, at_end
def trc2id(t, row, col, grid_dim): """ Convert row, col, cell type to state id """ s_id = (t * grid_dim[0] * grid_dim[1] + row * grid_dim[1] + col) // 1 return s_id
def _help_message(msgs, tag=None, vals=None): """ extend a basic help message with a tag and a list of possible argument values """ msgs = list(msgs) if vals is not None: msgs.append('options: {:s}'.format(', '.join(map(str, vals)))) help_msg = '; '.join(msgs) if tag is not None: assert isinstance(tag, str) assert isinstance(help_msg, str) help_msg = '[{:s}] {:s}'.format(tag, help_msg) return help_msg
def split_slack(kp): """ Computes the expected value and Args: kp: Returns: """ s = (1 + 1 / kp) ** kp base = 1 + 1 / kp k = - (base ** (kp) - 1) * base k = k + (base ** (kp + 1) - 1 - base) * (kp + 3) k = k - 2 * kp * (base ** (kp + 2) - (5 * kp ** 2 + 7 * kp + 2) / (2 * kp ** 2)) return (s, k)
def makeWennerArray(numElectrodes=32, id0=0): """ creates a schedule (A,B,M, N) for a Wenner array of length numElectrodes """ schedule=[] for a in range(1, (numElectrodes+2)//3): for k in range(0, numElectrodes-3*a): schedule.append((k+id0, k+3*a+id0, k+1*a+id0, k+2*a+id0)) return schedule
def type_name(type_: type) -> str: """Convert a type object to a string in a consistent manner. :param type_: the type object to convert :return: a string with the type name """ type_qualname = type_.__qualname__ type_module = type_.__module__ if type_module not in ("__main__", "builtins"): type_qualname = type_module + '.' + type_qualname return type_qualname
def make_balanced_tree(size): """Make a balanced binary tree with size nodes, where size is a power of 2.""" if size <= 1: return 0 return (make_balanced_tree(size/2), make_balanced_tree(size/2))
def rejectBranchUsage(err=''): """ Prints the Usage() statement for this method """ m = '' if len(err): m += '%s\n\n' %err m += 'This script will reject a Task Branch (TB) on Salesforce.\n' m += '\n' m += 'Usage:\n' m += ' rejectbranch -s <stream> -b <branch_Name> \n' return m
def rec_sum_digits(num): """rec_sum_digits(int) -> int Recursive function which takes an integer and computes the cumulative sum the individual digits of that integer. >>> sum_digts(4321) 10 """ if not isinstance(num, int): raise TypeError("Must be a positive int") # Base Case if num == 0: return 0 return num % 10 + rec_sum_digits(num / 10)
def config(path): """ Set CONFIG_FILE, the path to the configuration JSON file, to the given path, and return the new path. No error or sanity checking is performed. """ global CONFIG_FILE CONFIG_FILE = path return CONFIG_FILE
def isfile(string): """ Is string an existing file? :param string: path :return: abspath or raise FileNotFoundError if is not a dir """ import os if os.path.isfile(string): return os.path.abspath(string) else: raise FileNotFoundError(string)
def has_duplicates(s): """Returns True if any element appears more than once in a sequence. s: string or list returns: bool """ t = list(s) t.sort() for i in range(len(t)-1): if t[i] == t[i+1]: return True return False
def extract_mac_address(scanlist): """ Extracts MAC address from the scan output. """ if "Address:" in "".join(scanlist): mac_address_index = scanlist.index("Address:") + 1 mac_address = scanlist[mac_address_index] return mac_address.strip() else: return "Unknown"
def IsPakFileName(file_name): """Returns whether the given file name ends with .pak or .lpak.""" return file_name.endswith('.pak') or file_name.endswith('.lpak')
def strToRange(s): """ Convert string to range """ return [int(i) for i in s.split(',')]
def tf_shape_to_list(shape): """Get shape from tensorflow attr 'shape'.""" dims = None try: if not shape.unknown_rank: dims = [int(d.size) for d in shape.dim] except: # pylint: disable=bare-except pass return dims
def _header(string): """Make API REQUEST strings human readable.""" # Example: volume_space -> Volume Space camelized = [] split = string.split('_') for word in split: word = word.lower() camel = word[0].upper() + word[1:] camelized.append(camel) return ' '.join(camelized)
def _container_name(kata): """Calculate the name of the container for a given kata. """ # Important: this accounts for docker's limitation that container names # can only be lower case. The user might (and probably will) include # upper-case letters in their kata id. We lower-case those here. return 'cyber-dojo-repler-container-python-{}'.format(kata.lower())
def maj_jud_median_calc(totals_array): """The array contains totals for every judgment. An array like [12,32,45,67] means: 12 votes of 0 32 votes of 1 45 votes of 2 67 votes of 3 """ n = len(totals_array) element_count = 0 for i in totals_array: element_count = element_count + i if element_count == 0: return 0 if element_count/2 == int(element_count/2): median_position = element_count/2-1 else: median_position = (element_count+1)/2-1 #print("median=" + str(median_position)) partial_count = 0 result = None for i in range(n): partial_count = partial_count + totals_array[i] if partial_count > median_position: result = i break return result
def _quadratic_poly_coef_from_3_values(x1, x2, x3, n1, n2, n3): """ Returns the coeficients a, b and c of a quadratic polynomial of the form n = a*x**2 * b*x + c from 3 known points. Parameters ---------- x1, x2, x3 : float The positions of the values. n1, n2, n3 : float The values at positions x1, x2 and x3 respectively. Returns ------- a, b, c : float The coefficients. """ a = (((n2 - n1) * (x1 - x3) + (n3 - n1) * (x2 - x1)) / ((x1 - x3) * (x2**2 - x1**2) + (x2 - x1) * (x3**2 - x1**2))) b = ((n2 - n1) - a * (x2**2 - x1**2)) / (x2 - x1) c = n1 - a * x1**2 - b * x1 return a,b,c
def validate_input(user_input, input_map): """ Checks user_input for validity and appends any validation errors to return data. Input: - user_input: Dictionary containing the following input keys: values - amount: float - prefix: string - type: string - base: string - input_map: Dictionary containing the following valid keys: values prefix: - valid_prefix_key: string type: - valid_type_key: string base: - valid_base_key: string Output: Validated user_input dictionary with errors list as key errors """ # Split out user_input keys amt_value = user_input['amount'] amt_prefix = user_input['prefix'].lower() amt_type = user_input['type'].lower() amt_base = user_input['base'].lower() # Set up error list to track any input issues errors = [] # Convert input amount from string to float for use in calculations try: amt_value = float(amt_value) except ValueError: # Append error string to errors list in user_input err_str = "'{}' is not a valid value for amount, use numbers only.".format(amt_value) errors.append(err_str) # Check user input against valid value lists valid_prefix = True if amt_prefix in input_map['prefix'] else False valid_type = True if amt_type in input_map['type'] else False valid_base = True if amt_base in input_map['base'] else False if not valid_prefix: # Append error string to errors list in user_input err_str = "'{}' is not a valid prefix: ({})".format( amt_prefix, ', '.join(input_map['prefix'])) errors.append(err_str) if not valid_type: # Append error string to errors list in user_input err_str = "'{}' is not a valid type: ({})".format( amt_type, ', '.join(input_map['type'])) errors.append(err_str) if not valid_base: # Append error string to errors list in user_input err_str = "'{}' is not a valid base: ({})".format( amt_base, ', '.join(input_map['base'])) errors.append(err_str) validated_input = { 'amount': amt_value, 'prefix': amt_prefix, 'type': amt_type, 'base': amt_base, 'errors': errors } return validated_input
def make_sns_raw_record(topic_name, sns_data): """Helper for creating the sns raw record""" raw_record = { 'EventSource': 'aws:kinesis', 'EventSubscriptionArn': 'arn:aws:sns:us-east-1:123456789012:{}'.format(topic_name), 'Sns': { 'MessageId': 'unit test message id', 'Message': sns_data}} return raw_record
def calc_GC(seq): """ Calc. seq G+C content """ gc = {'G', 'C', 'g', 'c'} return len([x for x in seq if x in gc]) / float(len(seq)) * 100
def scale(x, min_value, max_value): """ scale x to values between 0 and 1 """ domain = max_value - min_value x = (x - min_value) / domain return x
def command_line_option_to_keyword(option): """ Convert the command line version of the option to a keyword. Parameters ---------- option: string The "long" command line option version Returns ------- keyword: string The "keyword" version of the option. Namely, the initial "--" is removed and all internal "-"s are replaced with "_"s. """ # first, remove the initial "--" option = option[2:] # and replace "-" with "_" option = option.replace("-", "_") return option
def coding_problem_19(house_costs): """ A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and kth column represents the cost to build the nth house with kth color, return the minimum cost. Example: >>> house_size = [1, 2, 4, 2] # size of the house >>> color_cost = [1, 2, 4] # cost of paint for each color >>> house_costs = [[cc * hs for cc in color_cost] for hs in house_size] # 4 houses, 3 colors >>> coding_problem_19(house_costs) # [1,2,4,2] . [1,2,1,2] == 1*1 + 2*2 + 1*4 + 2*2 == 13 13 Notes: this is dynamic programming in disguise. We assign a color to each house in order, and keep track of the minimum cost associated with each choice of color. These costs are the minimum over all possible permutation in which the last added house is of a particular color. """ best_costs = [0] * len(house_costs[0]) for color_costs in house_costs: # color_costs are those paid to paint last added house with a certain color best_costs = [color_costs[i] + min(best_costs[:i] + best_costs[i + 1:]) for i in range(len(best_costs))] return min(best_costs)
def idx_to_array_index(idx: int, idxpos0: int): """ Converts a nucleotide index to an 0-included array index :param idx: The index to convert :param idxpos0: The start index :return: The index of the element in the array >>> idx_to_array_index(10, 5) 5 >>> idx_to_array_index(10, -200) 209 >>> idx_to_array_index(1, -1) 1 """ return idx - idxpos0 - (1 if (idxpos0 < 0 < idx or idx < 0 < idxpos0) else 0)
def sec_dev(f, x, h=1e-6): """ Calculates the second derivative of a function at a given x, given a small h """ return (f(x - h) - 2 * f(x) + f(x + h)) / float(h**2)
def write_vcf(lines, vcf): """Create a file from the provided list""" with open(vcf, "w") as vcf_handle: vcf_handle.write('\n'.join(lines)) return vcf
def merge_intervals(intervals, delta= 0.0): """ A simple algorithm can be used: 1. Sort the intervals in increasing order 2. Push the first interval on the stack 3. Iterate through intervals and for each one compare current interval with the top of the stack and: A. If current interval does not overlap, push on to stack B. If current interval does overlap, merge both intervals in to one and push on to stack 4. At the end return stack """ if not intervals: return intervals intervals = sorted(intervals, key=lambda x: x[0]) merged = [intervals[0]] for current in intervals: previous = merged[-1] if current[0] <= previous[1]: previous[1] = max(previous[1], current[1]) else: merged.append(current) return merged
def tzdel(dt): """ Create timezone naive datetime from a timezone aware one by removing the timezone component. >>> from plone.event.utils import tzdel, utctz >>> from datetime import datetime >>> dt = utctz().localize(datetime(2011, 05, 21, 12, 25)) Remove the timezone: >>> tzdel(dt) datetime.datetime(2011, 5, 21, 12, 25) Using tzdel on a dt instance doesn't alter it: >>> dt datetime.datetime(2011, 5, 21, 12, 25, tzinfo=<UTC>) """ if dt: return dt.replace(tzinfo=None) else: return None
def get_volume_fn_from_mask_fn(mask_filename): """Extract volume path from mask path""" return mask_filename.replace("S-label", "")
def check_clip_len(options, duration): """ Function to determine the number of clips of a specified duration. Parameters ---------- options : list of 2-item tuples or lists start and stop times to evaluate duration : numeric (int or float) minimum desired clip duration Returns ------- remaining_options : list of 2-item tuples or lists or empty list start and stop times that are at least sepcified duration, or an empty list if no given clips are sufficiently long """ remaining_options = [] for pair in options: if ((pair[1] - pair[0]) > duration): remaining_options.append(pair) print(''.join(["Here's an option: ", str(pair[0]), ":", str(pair[ 1])])) return remaining_options
def wiki_title(name): """Like title(), except it never lowercases a letter.""" return ''.join(min(x,y) for x,y in zip(name, name.title()))
def val_coding_ht_path(build): """ HT of coding variants for validating callset data type. HT written using hail-elasticsearch-pipelines/download_and_create_reference_datasets/v02/hail_scripts/write_dataset_validation_ht.py """ return f"gs://seqr-reference-data/GRCh{build}/validate_ht/common_coding_variants.grch{build}.ht"
def get_name_receipt_without_extention(receipt_name): """ get the name of the file without the extension so we can store the json file with the same name """ index = receipt_name.index(".") return receipt_name[0:index]
def maybe_unwrap_results(results): """ Gets raw results back from wrapped results. Can be used in plotting functions or other post-estimation type routines. """ return getattr(results, '_results', results)
def route_error_500(error): """Handle server-side errors.""" return 'Internal server error', 500
def format_map(m): """pleasing output for dc name and node count""" keys = sorted(m) items = [] for key in keys: count = m[key] items.append("%s: %s" % (key, count)) if not m: return "N/A" return "{ %s }" % ", ".join(items)
def lowercase_list(l): """Transform list items to string type and convert to lowercase Args: l: List of specification values """ return [str(i).lower() for i in l]
def rgb2hsv(rgb): """Converts RGB to HSV. Note that H may be None when S is 0 (for grey colors). """ r, g, b = rgb minimum = min(r, g, b) maximum = max(r, g, b) v = maximum delta = maximum - minimum if delta != 0: s = delta / maximum else: # h is undefined s = 0 h = None return (h, s, v) if r == maximum: h = (g - b) / delta # between yellow & magenta elif g == maximum: h = 2 + (b - r) / delta # between cyan & yellow else: h = 4 + (r - g) / delta # between magenta & cyan h *= 60 # degrees if h < 0: h += 360 return (h, s, v)
def sum(lst): """ Returns: the sum of all elements in the list Example: sum([1,2,3]) returns 6 sum([5]) returns 5 Parameter lst: the list to sum Precondition: lst is a nonempty list of numbers (either floats or ints) """ result = 0 # Accumulator for x in lst: result = result+x return result
def get_file_type(command: str) -> str: """ Used to understand if a command run uses a .msi or a .exe installer / uninstaller #### Arguments command (str): The command to infer the installer type from Returns: str: The filetype of the installer infered from the command """ # msiexe.exe is used to run a MSI installer, so we know it's an msi file if 'msiexec.exe' in command.lower(): return '.msi' # Otherwise it's an executable (.exe) return '.exe'
def markAvgMedian(marks): """ markAvgMedian (marks) - returns the average median of the top 6 marks in the list of marks given """ top6 = [] for x in marks: if len(top6) >= 6: if x > min(top6): top6.pop(top6.index(min(top6))) top6.append(x) else: top6.append(x) top6.sort() return top6[2]
def quotify(comment, username): """ Converts 'Foo\nbar' to: @username > Foo > bar \n\n """ header = "@%s" % username lines = comment.splitlines() quote = "\n> ".join(lines) quote = "%(header)s\n> %(quote)s\n\n" % ({'header': header, 'quote': quote}) return quote
def any7(nums): """Are any of these numbers a 7? (True/False)""" # YOUR CODE HERE for loop_num in nums: if loop_num == 7: return True return False
def bytes_ljust(x: bytes, width: int, fill: bytes) -> bytes: """Given a bytes object, a line width, and a fill byte, left-justifies the bytes object within the line. Compiling bytes.ljust compiles this function. This function is only intended to be executed in this compiled form. Checking the fill length is assumed to be done outside this function. Args: x: A bytes object. width: Line width. fill: A bytes object of length 1. Returns: Transformed bytes object. """ if width <= len(x): return x return x + fill * (width - len(x))
def overlap(e1_start: int, e1_end: int, e2_start: int, e2_end: int) -> bool: """ Check if two spans overlap with each other Args: e1_start (int): span 1 begin offset e1_end (int): span 1 end offset e2_start (int): span 2 begin offset e2_end (int): span 2 end offset Returns: bool: True if they overlap, False otherwise """ if e1_start <= e2_start < e2_end <= e1_end: return True elif e2_start <= e1_start < e1_end <= e2_end: return True elif e1_start <= e2_start < e1_end <= e2_end: return True elif e2_start <= e1_start < e2_end <= e1_end: return True return False
def calc_x_for_contact_depth(m, c, contact): """Calculate x for contact depth Args: m: slope from `last_base_slope` c: intercept from `c0` """ return 1 / m * (contact - c)
def rectangles_overlap(rectangle1, rectangle2): """ True when two rectangles overlap. """ from_x1, from_y1, to_x1, to_y1 = rectangle1 from_x2, from_y2, to_x2, to_y2 = rectangle2 def overlap_1d(from1, from2, to1, to2): return from1 < to2 and to1 > from2 return (overlap_1d(from_x1, from_x2, to_x1, to_x2) and overlap_1d(from_y1, from_y2, to_y1, to_y2))
def find_largest_digit_helper(n, l): """ helper function base case: n//10 == 0 n//10 => remove the units digit of n n%10 => get the units digit of n :param n: (int) the number which units digit are removing. :param l: (int) the stored largest digit so far """ if n//10 == 0: # base case: no more digits after removal of units digit if n % 10 > l: # if this number is larger than the largest digit so far. l = n % 10 return l else: # recursive case: still have more than 1 digit. if n % 10 > l: # if this number is larger than the largest digit so far. l = n % 10 return find_largest_digit_helper(n//10, l)
def MaybeToNumber(instance): """Convert to an int or float if possible.""" if isinstance(instance, (float, int)) or instance is None: return instance try: return int(instance) except (TypeError, ValueError): pass try: return float(instance) except (TypeError, ValueError): pass return instance
def to_css_length(x): """ Return the standard length string of css. It's compatible with number values in old versions. :param x: :return: """ if isinstance(x, (int, float)): return '{}px'.format(x) else: return x
def _ExtractCLPath(output_of_where): """Gets the path to cl.exe based on the output of calling the environment setup batch file, followed by the equivalent of `where`.""" # Take the first line, as that's the first found in the PATH. for line in output_of_where.strip().splitlines(): if line.startswith('LOC:'): return line[len('LOC:'):].strip()
def vm_to_mm(verbal_model): """ Convert VM to MM. Time information will be lost. >>> a = VerbalModels.Prop(name="a", neg=False, identifying=False, t=123) >>> non_b = VerbalModels.Prop(name="b", neg=True, identifying=False, t=456) >>> vm = [VerbalModels.Individual(props=[a], t=789), VerbalModels.Individual(props=[a, non_b], t=159)] >>> vm_to_mm(vm) [['a'], ['a', '-b']] """ mental_model = [] for i, ind in enumerate(verbal_model): mental_model.append([]) for p in ind.props: p_str = "-"+p.name if p.neg else p.name mental_model[i].append(p_str) return [sorted(row, key=lambda e: e[-1]) for row in mental_model]
def sort_by_month(orders: list) -> tuple: """ A function which sorts the contents of the CSV file into months. :param orders: List :return: tuple """ jan: list = [] feb: list = [] mar: list = [] apr: list = [] may: list = [] jun: list = [] jul: list = [] aug: list = [] sep: list = [] _oct: list = [] nov: list = [] dec: list = [] for order in orders: if "Jan" in order["date"]: jan.append(order) elif "Feb" in order["date"]: feb.append(order) elif "Mar" in order["date"]: mar.append(order) elif "Apr" in order["date"]: apr.append(order) elif "May" in order["date"]: may.append(order) elif "Jun" in order["date"]: jun.append(order) elif "Jul" in order["date"]: jul.append(order) elif "Aug" in order["date"]: aug.append(order) elif "Sep" in order["date"]: sep.append(order) elif "Oct" in order["date"]: _oct.append(order) elif "Nov" in order["date"]: nov.append(order) elif "Dec" in order["date"]: dec.append(order) return jan, feb, mar, apr, may, jun, jul, aug, sep, _oct, nov, dec
def deindent(s): """ >>> print(deindent(''' ... bepa ... apa ... ... cepa ... ''')) <BLANKLINE> bepa apa <BLANKLINE> cepa <BLANKLINE> """ lines = s.split('\n') chop = 98765 for line in lines: if line.strip(): m = len(line) - len(line.lstrip()) if m < chop: chop = m return '\n'.join(line[chop:] for line in lines)
def B(A: int, D: int) -> int: """Function that should become part of the graph - B""" return A * A + D
def pad_data(data, pad_amount, pad_value=b"\x00", start_at=0): """ Pad a piece of data according to the padding value and returns the result. Use start_at to specify an offset at the starting point. """ end_position = len(data) + start_at if end_position % pad_amount != 0: pad_size = pad_amount - (end_position % pad_amount) data += pad_value * pad_size return data
def _is_max_limit_reached(current: int, maximum: int = -1) -> bool: """Check if the limit has been reached (if enabled). Args: current: the current value maximum: the maximum value (or -1 to disable limit) Returns: bool: whether the limit has been reached """ return maximum != -1 and current >= maximum
def py3to2_remove_raise_from(content): """ Removes expression such as: ``raise Exception ("...") from e``. The function is very basic. It should be done with a grammar. @param content file content @return script """ lines = content.split("\n") r = None for i, line in enumerate(lines): if " raise " in line: r = i if " from " in line and r is not None: spl = line.split(" from ") if len(spl[0].strip(" \n")) > 0: lines[i] = line = spl[0] + "# from " + " - ".join(spl[1:]) if r is not None and i > r + 3: r = None return "\n".join(lines)
def families_dipoles(): """.""" return ['B']
def check_is_number(s): """Summary Args: s (TYPE): Description Returns: TYPE: Description """ try: float(s) return True except ValueError: return False
def ship_new(name): """Create a new ship name: The name to attribute to the ship """ return "Created ship {0}".format(name)
def cast_vanilla(value, cur): # pylint: disable=unused-argument """Vanilla Type caster for psycopg2 Simply returns the string representation. """ if value is None: return None else: return str(value)
def write_readmap(fh, rmap, namedic=None): """Write a read map to a tab-delimited file. Parameters ---------- fh : file handle Output file. rmap : dict Read-to-taxon(a) map. namedic : dict, optional Taxon name dictionary. """ # sort subjects by count (high-to-low) then by alphabet def sortkey(x): return -x[1], x[0] for read, taxa in rmap.items(): row = [read] if isinstance(taxa, dict): for taxon, count in sorted(taxa.items(), key=sortkey): if namedic and taxon in namedic: taxon = namedic[taxon] row.append(taxon + ':' + str(count)) elif namedic and taxa in namedic: row.append(namedic[taxa]) else: row.append(taxa) print('\t'.join(row), file=fh)
def hard_label(ypred, thresh=0.5): """ Hard assign label after prediction of Keras model Args: ypred (int): Percentage that the label will be 0 or 1. thresh (float): Default=0.5 Threshold to assign labels. Returns: Label 0 if smaller than threshold and label 1 if larger than threshold. """ if ypred > thresh: return 1 else: return 0
def map_encoding(encoding): """Replace specific unwanted encodings with compatible alternative.""" encoding_map = { None : 'utf-8', '' : 'utf-8', 'ascii' : 'utf-8' } lower_encoding = (encoding or '').lower() return encoding_map.get(lower_encoding) or lower_encoding
def grid_coordinates(roi, x_divisions, y_divisions, position): """ Function that returns the grid coordinates of a given position. To do so it computes, for a given area and taking into account the number of x and y divisions which is the total amount of cells. After that it maps the given position to the cell it falls inside and returns the coordinates of that cell. Finally, it is assumed that the position is always inside the grid :param roi: region of interest to be gridezied :param x_divisions:number of divisions in the x axis :param y_divisions:number of divisions in the y axis :param position: position to transform into grid coordinates """ px_per_x_division = float(roi[0][1]-roi[0][0])/x_divisions px_per_y_division = float(roi[1][1]-roi[1][0])/y_divisions x_in_grid = position[0] - roi[0][0] y_in_grid = position[1] - roi[1][0] return (int(x_in_grid/px_per_x_division), int(y_in_grid/px_per_y_division))
def pad(input: str, spaces: int) -> str: """Pads the input lines with spaces except for the first line. We don't need opts here because the default mode will always be a single line so we'll never invoke this. """ lines = input.splitlines() pad = " " * spaces return f"\n{pad}".join(lines)
def get_correct_ids(hgnc_symbol, alias_genes): """Try to get the correct gene based on hgnc_symbol The HGNC symbol is unfortunately not a persistent gene identifier. Many of the resources that are used by Scout only provides the hgnc symbol to identify a gene. We need a way to guess what gene is pointed at. Args: hgnc_symbol(str): The symbol used by a resource alias_genes(dict): A dictionary with all the alias symbols (including the current symbol) for all genes Returns: hgnc_ids(iterable(int)): Hopefully only one but a symbol could map to several ids """ hgnc_ids = set() hgnc_symbol = hgnc_symbol.upper() if hgnc_symbol in alias_genes: hgnc_id_info = alias_genes[hgnc_symbol] if hgnc_id_info['true']: return set([hgnc_id_info['true']]) else: return set(hgnc_id_info['ids']) return hgnc_ids
def bps_mbps(val: float) -> float: """ Converts bits per second (bps) into megabits per second (mbps). Examples: >>> bps_mbps(1000000) 1.0 >>> bps_mbps(1129000) 1.13 Args: val (float): The value in bits per second to convert. Returns: Returns val in megabits per second. """ return round(float(val) / 1000000, 2)
def foo(param): """Simple foo function that returns a string with an exclamation point Parameters ---------- param : str Param string to pass in Returns ------- str A str with a passed in param concat with an exclamation point """ param = param + '!' return param
def reverse_list_valued_dict(dict_obj): """Reverse a list-valued dict, so each element in a list maps to its key. Parameters ---------- dict_obj : dict A dict where each key maps to a list of unique values. Values are assumed to be unique across the entire dict, on not just per-list. Returns ------- dict A dict where each element in a value list of the input dict maps to the key that mapped to the list it belongs to. Example ------- >>> dicti = {'a': [1, 2], 'b': [3, 4]} >>> reverse_list_valued_dict(dicti) {1: 'a', 2: 'a', 3: 'b', 4: 'b'} """ new_dict = {} for key in dict_obj: for element in dict_obj[key]: new_dict[element] = key return new_dict
def _color_for_labels(label_color, default_color, seq_index): """Helper function to get a color for a label with index `seq_index`.""" if label_color is None: if hasattr(default_color, '__getitem__'): c = default_color[seq_index] else: c = default_color else: c = label_color return c or 'black'
def split_float_colons(string_values): """ Uses numpy-ish syntax to parse a set of two floats. Blanks are interpreted as None. Parse the following: 1:10 1: :100 1.1:200 1:300. """ if string_values: assert ',' not in string_values, string_values sline = string_values.split(':') assert len(sline) <= 2, sline values = [] for svalue in sline: if svalue == '': val = None else: val = float(svalue) values.append(val) else: assert string_values is None, None values = None # all values return values
def float_replication(field, old_field): """*4., *(11.5)""" msg = 'field=%r; expected *(1.), *2., ..., *11.' % field assert field[0] == '*', msg assert '.' in field, msg assert len(field) >= 3, msg if '(' in field: assert field[1] == '(', msg assert field[-1] == ')', msg fieldi = field[2:-1] assert '(' not in fieldi, msg assert ')' not in fieldi, msg else: assert '(' not in field, msg assert ')' not in field, msg fieldi = field[1:] nfloat = float(fieldi) field2 = nfloat + float(old_field) return field2
def fix_spans_due_to_empty_words(action_dict, words): """Return modified (action_dict, words)""" def reduce_span_vals_gte(d, i): for k, v in d.items(): if type(v) == dict: reduce_span_vals_gte(v, i) continue try: a, b = v if a >= i: a -= 1 if b >= i: b -= 1 d[k] = [a, b] except ValueError: pass except TypeError: pass # remove trailing empty strings while words[-1] == "": del words[-1] # fix span i = 0 while i < len(words): if words[i] == "": reduce_span_vals_gte(action_dict, i) del words[i] else: i += 1 return action_dict, words
def euler191(nb_days=4): """Solution for problem 191.""" # 0 late : a, b, c for 0, 1, 2 consecutive absences # 1 late : d, e, f for 0, 1, 2 consecutive absences a, b, c, d, e, f = 1, 0, 0, 0, 0, 0 for _ in range(nb_days + 1): # 1 more iteration to have the res in d a, b, c, d, e, f = a + b + c, a, b, a + b + c + d + e + f, d, e return d
def extract_tty_phone(service_center): """ Extract a TTY phone number if one exists from the service_center entry in the YAML. """ tty_phones = [p for p in service_center['phone'] if 'TTY' in p] if len(tty_phones) > 0: return tty_phones[0]