content
stringlengths
42
6.51k
def create_featseltuple(ids): """Add the flat y coordinate to an index list.""" newlist = [] for part_id in ids: newlist.extend([part_id, part_id + 91]) return tuple(sorted(newlist))
def cursorBoxHit(mouse_x, mouse_y, x1, x2, y1, y2, tab): """Description. More... """ if (mouse_x >= x1) and (mouse_x <= x2) and (mouse_y >= y1) and (mouse_y <= y2) and tab: return True else: return False
def split64(long_int): """Split long_int into 64-bit words big-endian""" assert(long_int >= 0) if long_int == 0: return [ "0" ] result = [] while long_int: result += [ "0x%xULL" % (long_int & (2**64-1)) ] long_int >>= 64 return result
def listdict2dict(L_dict, i): """ :param L_dict: dictionary of lists, all same length :param i: index in to L_dict lists :return: dictionary with same keys as L_dict, in which key k maps to element i of L_dict[i] """ return {key:L_dict[key][i] for key in L_dict.keys()}
def bed_convert_coords(reg_s, reg_e, ref_s, ref_e, pol): """ Convert BED coordinates derived from a region within a subsequence of the reference (chromsome or transcript) to chromosome or transcript reference coordinates. Return start + end (BED format) positions. reg_s: Region within subsequence start position, with 0 to len(subsequence) coordinates reg_e: Region within subsequence end position, with 0 to len(subsequence) coordinates ref_s: Subsequence start position on reference sequence ref_e: Subsequence end position on reference sequence pol: Polarity on reference (use + for transcripts, + or - for chromosomal regions) >>> bed_convert_coords(10, 20, 1000, 2000, "+") (1010, 1020) >>> bed_convert_coords(10, 20, 1000, 2000, "-") (1980, 1990) """ assert pol == "+" or pol == "-", "invalid polarity given" assert reg_s < reg_e, "Invalid BED coordinates given: reg_s >= reg_e" assert ref_s < ref_e, "Invalid BED coordinates given: ref_s >= ref_e" new_s = ref_s + reg_s new_e = ref_s + reg_e if pol == "-": new_s = ref_e - reg_e new_e = ref_e - reg_s return new_s, new_e
def font(unit, size, family=None, style=None): """Font setter for all the widgets""" f, s, sy = 'Comic Sans MS', 1, 'bold' rem = int(unit / 100 * (size * 0.05 + s)) if not family and not style: return f, rem, sy if family and style: return family, rem, style if not family and style: return f, rem, style if family and not style: return family, rem, sy
def part_a(f, x, h): """Forward difference""" return (f(x+h) - f(x)) / h
def _comp_nom(nco): """ To be correctly read in a MED viewer, each component must be a string of width 16. Since we do not know the physical nature of the data, we just use V1, V2, ... """ return "".join(["V%-15d" % (i + 1) for i in range(nco)])
def fibonacci(n): """ ecursive function that return the nth Fibonacci number in the sequence Parameters ---------- n : int The element of the Fibonacci sequence that is desired. Raises ------ ValueError If n <= 0. Returns ------- int The value of the nth element of the Fibonacci sequence. """ if n<=0: raise ValueError("Input cannot be less than 1") elif n==1: return 0 elif n==2: return 1 else: return fibonacci(n-1)+fibonacci(n-2)
def computeLogSubTicks(ticks, lowBound, highBound): """Return the sub ticks for the log scale for all given ticks if subtick is in [lowBound, highBound] :param ticks: log10 of the ticks :param lowBound: the lower boundary of ticks :param highBound: the higher boundary of ticks :return: all the sub ticks contained in ticks (log10) """ if len(ticks) < 1: return [] res = [] for logPos in ticks: dataOrigPos = logPos for index in range(2, 10): dataPos = dataOrigPos * index if lowBound <= dataPos <= highBound: res.append(dataPos) return res
def right_pad(message, pad_to=20, pad_with=' '): """Pad a string with chars on the right until it reaches a certain width Useful for aligning columns in console outputs. """ message = str(message) while len(message) < pad_to: message = message + pad_with return message
def argListToString(argList): """Converts a list of arguments into a single argument string""" string = "" for arg in argList: stringVersion = str(arg) # Wrap arguments with spaces in them in "" so they stay together if stringVersion.find(' ') >= 0: string = string + '"' + stringVersion + '" ' else: string = string + stringVersion + ' ' return string
def _to_bool(s): """Convert a value into a CSV bool.""" if s == 'True': return True elif s == 'False': return False else: raise ValueError('String cannot be converted to bool')
def prefix_from_bowtie2_index(index_files): """ Given a list of index files for bowtie2, return the corresponding prefix. """ if isinstance(index_files, str): return '.'.join(index_files.replace('.rev', '').split('.')[:-2]) else: prefixes = list( set( map( lambda x: '.'.join(x.replace('.rev', '').split('.')[:-2]), index_files) ) ) if len(prefixes) != 1: raise ValueError( "More than one prefix detected from '{0}'".format(prefixes) ) return prefixes[0]
def is_remote(file): """ Does the filename start with 'gs://'? :param file: :return: true or false """ return file is not None and file.startswith('gs://')
def _handle_arg(arg): """ Clean up arguments. Mostly used to handle strings. Returns: Cleaned up argument. """ if (arg.startswith("'") and arg.endswith("'")) or ( arg.startswith('"') and arg.endswith('"') ): return arg[1:-1]
def average(x): """calculates the averade of a list x""" assert len(x) > 0 return float(sum(x)) / len(x)
def is_int_as_str(x): """ Test if string x is an integer. If not a string return False. """ try: return x.isdecimal() except AttributeError: return False
def dehex(s): """ convert input string containing \x00 into hex values in string :todo: Python3 >>> dehex('abc') 'abc' >>> dehex(r'abc\x00') 'abc\x00' >>> dehex(r'\xffabc\x00') '\xffabc\x00' """ sr = '' while s: sl = s.split(r'\x',1) sr += sl[0] if len(sl) == 1: return sr s = sl[1][2:] x = sl[1][0:2] sr += chr( int(x,base=16)) return sr
def r_size(x): """Returns the difference between the largest and smallest value in a collection. Parameters ---------- x : collection of numbers Examples -------- >>> r_size([2,4,6,8]) 6 >>> r_size({3,6,9,11}) 8 """ return max(x) - min(x)
def ra_dec_to_deg(right_ascension, declination): """Converts right ascension and declination to degrees Args: right_ascension (str): Right ascension in the format hh:mm:ss.sss declination (str): Declination in the format dd:mm:ss.sss Returns: right_ascension_deg (float): Right ascension in degrees declination_deg (float): Declination in degrees """ right_ascension = right_ascension.split(":") declination = declination.split(":") # RIGHT ASCENSION conversion right_ascension_deg = (float(right_ascension[0]) + (float(right_ascension[1]) + (float(right_ascension[2]) / 60.)) / 60.) * \ (360. / 24.) # DECLINATION conversion if float(declination[0]) == abs(float(declination[0])): sign = 1 else: sign = -1 declination_deg = sign * (abs(float(declination[0])) + (float(declination[1]) + (float(declination[2]) / 60.)) / 60.) return right_ascension_deg, declination_deg
def in_time_frame(sim_start_epoch, sim_end_epoch, rec_start_epoch, rec_end_epoch): """ Check wheter record is inside the simulation time frame. :param sim_start_epoch: simluation start. :param sim_end_epoch: simulation end. :param rec_start_epoch: record start. :param rec_end_epoch: record end. :return: True if record overlaps with the simulation time frame. """ outside = (rec_end_epoch <= sim_start_epoch or sim_end_epoch <= rec_start_epoch) return not outside
def _remove_spaces_column_name(name): """Check if name contains any spaces, if it contains any spaces the spaces will be removed and an underscore suffix is added.""" if not isinstance(name, str) or " " not in name: return name return name.replace(" ", "_") + "_BACKTICK_QUOTED_STRING"
def angle_adjust(angle): """Adjust angle from sensehat range to game range. Args: angle (float): sensehat angle reading. Returns: float """ if angle > 180.0: angle -= 360.0 return angle
def _optional_dict_to_list(param_value_dict, key_string='id', value_string='stringValue'): """ If given a dictionary, convert it to a list of key-value dictionary entries. If not given a dictionary, just return whatever we were given. """ if not isinstance(param_value_dict, dict): return param_value_dict value_objects = [] for param_id, value in param_value_dict.items(): value_objects.append({key_string: param_id, value_string: value}) return value_objects
def better_approach(digits, steps,offset = 0): """Things to improve on: Avoid unnecessary multiplications and additions of zero """ L = len(digits) digits = digits[offset:] PAT = [0,1,0,-1] for i in range(steps): output = [] for cycle_length in range(offset,L): # Cycle length starting at 1 was useful before, but breaks my head now v = 0 if cycle_length >= L//2: v = sum(digits[cycle_length-offset:]) elif cycle_length >= L//3: v = sum(digits[cycle_length-offset:2*cycle_length+1-offset]) elif cycle_length >= L//4: v = sum(digits[cycle_length-offset:2*cycle_length+1-offset]) - sum(digits[3*cycle_length+2-offset:]) else: for i, d in enumerate(digits[cycle_length-offset:], start=cycle_length-offset): # Can only start from i, because 0 prior to this. v += d * PAT[((i+1) % (4 * (cycle_length+1))) // (cycle_length+1)] # pattern(i, cycle_length) having this function made it 3x slower digits[cycle_length-offset] = abs(v) % 10 #output.append(abs(v)%10) #digits = [i for i in output] return digits
def custom_hash(key:str) -> int: """ Hashes the key in a consistent manner, since python changes the seeding between sessions for ''''''security reasons'''''' """ h = "" for character in key: h += str(ord(character)) return int(h)
def generate_root_filename(rawname, add="_mass"): """Generate the appropriate root filename based on a file's LJH name. Takes /path/to/data_chan33.ljh --> /path/to/data_mass.root """ import re fparts = re.split(r"_chan\d+", rawname) prefix_path = fparts[0] return prefix_path + add + ".root"
def calculate_score(args): """Parallelize at the score level (not currently in use)""" gene, function, scoring_args = args score = function(gene, scoring_args) return score
def custom_validator(language, options): """Custom validator.""" okay = True for k in options.keys(): if k != 'opt': okay = False break if okay: if options['opt'] != "A": okay = False return okay
def instanceof(obj, classinfo): """Wrap isinstance to only return True/False""" try: return isinstance(obj, classinfo) except TypeError: # pragma: no cover # No coverage since we never call this without a class, # type, or tuple of classes, types, or such typles. return False
def _to_list(a): """Return a as list for unroll_scan.""" if isinstance(a, list): return a elif isinstance(a, tuple): return list(a) elif a is None: return [] else: return [a]
def get_assign_name(guid, state): """Get the assigned name for the entity.""" guid = " ".join(guid.split()) if 'name_table' not in state: state['name_table'] = {} if 'names' not in state: state['names'] = {} if guid not in state['names']: names = state['name_table'] addr = guid.split() # Add host part if addr[0] not in names: names[addr[0]] = {} state['names'][addr[0]] = "H" + str(len(names)) name = state['names'][addr[0]] # Add application part if len(addr) >= 2: app_guid = addr[0] + " " + addr[1] if addr[1] not in names[addr[0]]: names[addr[0]][addr[1]] = [] app_name = name + ".A" + str(len(names[addr[0]])) state['names'][app_guid] = app_name name = state['names'][app_guid] # Add participant part if len(addr) >= 3: app_dict = names[addr[0]][addr[1]] if addr[2] not in app_dict: app_dict.append(addr[2]) name += ".P" + str(len(app_dict)) state['names'][guid] = name return state['names'][guid]
def concatenate_items(items, sep=', '): """Concatenate a sequence of tokens into an English string. Parameters ---------- items : list-like List / sequence of items to be printed. sep : str, optional Separator to use when generating the string Returns ------- str """ if len(items) == 0: return "" if len(items) == 1: return items[0] items = list(map(str, items)) if sep == ', ': s = sep.join(items[:-1]) s += ' and ' + items[-1] else: s = sep.join(items) return s
def charCodeAt(src: str, pos: int): """ Returns the Unicode value of the character at the specified location. @param - index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. This was added for compatibility with python """ try: return ord(src[pos]) except IndexError: return None
def hanleyMcNeil(auc: float, n0: int, n1: int) -> float: """The very good power-law variance estimate from Hanley/McNeil""" auc2=auc*auc q1=auc/(2.-auc) q2=2.*auc2/(1.+auc) return( (auc-auc2+(n1-1.)*(q1-auc2)+(n0-1.)*(q2-auc2))/n0/n1 )
def clamp(num, min_val, max_val): """Clamps `min` within the range [`min_val`..`max_val`].""" return max(min_val, min(num, max_val))
def _calculate_value_in_range(min_val, max_val, percentage): """Get the value within a range based on percentage. Example: A percentage 0.0 maps to min_val A percentage of 1.0 maps to max_val """ value_range = max_val - min_val return min_val + int(percentage * value_range)
def get_items_from_index(x,y): """ decipher the values of items in a list from their indices. """ z = [] for i in y: try: z.append(x[i]) except: pass return z """ #example: x = [1,3,5,8] y = [1, 3] get_items_from_index(x, y) #result >>> [3,8] """
def calcBTreeEuropeanOpValue(po, p, pstar, step_discount): """Computes and returns the options value at time 0.""" if po is None: po = [] po = [(p * po[i + 1] + pstar * po[i]) * step_discount for i in range(len(po) - 1)] if len(po) == 1: return po[0] else: return calcBTreeEuropeanOpValue(po, p, pstar, step_discount) # temp = [] # i = 0 # while i < (len(po) - 1): # temp.append(pstar * po[i] + p * po[i + 1] * step_discount) # i += 1 # print(temp) # if len(temp) > 1: # po = temp # return calcBTreeEuropeanOpValue(po, p, pstar, step_discount) # if len(temp) == 1: # return temp[0]
def uses_all( word, letters ): """Return True if the word uses all the required letters. """ for letter in letters: if letter not in word: return False return True
def bounding_boxes_xyxy2xywh(bbox_list): """ Transform bounding boxes coordinates. :param bbox_list: list of coordinates as: [[xmin, ymin, xmax, ymax], [xmin, ymin, xmax, ymax]] :return: list of coordinates as: [[xmin, ymin, width, height], [xmin, ymin, width, height]] """ new_coordinates = [] for box in bbox_list: new_coordinates.append([box[0], box[1], box[2] - box[0], box[3] - box[1]]) return new_coordinates
def update_active_boxes(cur_boxes, active_boxes=None): """ Args: cur_boxes: active_boxes: Returns: """ if active_boxes is None: active_boxes = cur_boxes else: active_boxes[0] = min(active_boxes[0], cur_boxes[0]) active_boxes[1] = min(active_boxes[1], cur_boxes[1]) active_boxes[2] = max(active_boxes[2], cur_boxes[2]) active_boxes[3] = max(active_boxes[3], cur_boxes[3]) return active_boxes
def add_path(tdict, path): """ Create or extend an argument tree `tdict` from `path`. :param tdict: a dictionary representing a argument tree :param path: a path list :return: a dictionary Convert a list of items in a 'path' into a nested dict, where the second to last item becomes the key for the final item. The remaining items in the path become keys in the nested dict around that final pair of items. For example, for input values of: tdict={} path = ['assertion', 'subject', 'subject_confirmation', 'method', 'urn:oasis:names:tc:SAML:2.0:cm:bearer'] Returns an output value of: {'assertion': {'subject': {'subject_confirmation': {'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}}}} Another example, this time with a non-empty tdict input: tdict={'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'}, path=['subject_confirmation_data', 'in_response_to', '_012345'] Returns an output value of: {'subject_confirmation_data': {'in_response_to': '_012345'}, 'method': 'urn:oasis:names:tc:SAML:2.0:cm:bearer'} """ t = tdict for step in path[:-2]: try: t = t[step] except KeyError: t[step] = {} t = t[step] t[path[-2]] = path[-1] return tdict
def mongodb_uri(mongodb_url, mongodb_port, db_name='tuplex-history'): """ constructs a fully qualified MongoDB URI Args: mongodb_url: hostname mongodb_port: port db_name: database name Returns: string representing MongoDB URI """ return 'mongodb://{}:{}/{}'.format(mongodb_url, mongodb_port, db_name)
def exponential_backoff(c_factor): """Calculate backoff time for reconnect.""" return int(((2**c_factor)-1)/2)
def _merged_gaps(a_gaps: dict, b_gaps: dict) -> dict: """merges gaps that occupy same position Parameters ---------- a_gaps, b_gaps [(gap position, length),...] Returns ------- Merged places as {gap position: length, ...} Notes ----- If a_gaps and b_gaps are from the same underlying sequence, set function to 'max'. Use 'sum' when the gaps derive from different sequences. """ if not a_gaps: return b_gaps if not b_gaps: return a_gaps places = set(a_gaps) | set(b_gaps) return { place: max( a_gaps.get(place, 0), b_gaps.get(place, 0), ) for place in places }
def split_array(text): """Split a string assuming it's an array. :param text: the text to split :type text: str :returns: list of splitted strings :rtype: list """ if not isinstance(text, str): return text # for some reason, titles.akas.tsv.gz contains \x02 as a separator sep = ',' if ',' in text else '\x02' return text.split(sep)
def example_keys_response(default_kid, rsa_public_key, rsa_public_key_2): """ Return an example response JSON returned from the ``/jwt/keys`` endpoint in fence. """ return {"keys": [[default_kid, rsa_public_key], ["key-02", rsa_public_key_2]]}
def get_fieldnames(content): """ Return the longest Dict Item for csv header writing """ item_length = 0 csv_header = [] for item in content: if len(item) >= item_length: longest_item = item item_length = len(item) for key in longest_item.keys(): if key not in csv_header: csv_header.append(key) return csv_header
def binarySearch(arr, x): """Returns the lowest index of the element equal to `x` or NaN if not found.""" if len(arr) == 0: return 0 m = len(arr) // 2 if arr[m] < x: return m + 1 + binarySearch(arr[m + 1:], x) elif x < arr[m] or (0 < m and arr[m - 1] == x): return binarySearch(arr[:m], x) else: return m
def is_valid_followup_permutation(perm, prev_perm): """ Checks if a given permutation is a valid following permutation to all previously known permutations. (only one more) """ for p in prev_perm: if len(perm - p) == 1: return True return False
def tagref(row, args): """A single tag pattern standing alone. @param row: the HXL data row @param args: the arguments parsed """ return row.get(args[0])
def dict_to_list(dict_to_convert): """Converts a dictionary to a multi-dimensional array. The first item of the tuple is the key from the dictionary""" result_list = [] for name, values in dict_to_convert.items(): result_list.append([name] + values.get_all_stats()) return result_list
def code(string: str) -> str: """ Add code md style. :param string: The string to process. :type string:str :return: Formatted String. :rtype: str """ return f"`{string}`"
def superclass_in_base_classes(base_classes, the_class): """ recursively determine if the_class is among or is a superclass of one of the classes in base_classes. The comparison is done by name so that even if reload is called on a module, this still works. """ for base_class in base_classes: if base_class.__name__ == the_class.__name__: return True else: #if the base class in turn has base classes of its own if len(base_class.__bases__)!=1 or\ base_class.__bases__[0].__name__ != 'object': #check them. If there's a hit, return True if (superclass_in_base_classes( base_classes=base_class.__bases__, the_class=the_class)): return True #if 'True' was not returned in the code above, that means we don't #have a superclass return False
def binary_string_to_int(binary): """ Convert a binary string to a decimal number. @type binary: str @param binary: Binary string @rtype: int @return: Converted bit string """ return int(binary, 2)
def _param(param, value): """ create 'parameter=value' """ return "{0}={1}".format(param, value)
def DAY_OF_MONTH(expression): """ Returns the day of the month for a date as a number between 1 and 31. See https://docs.mongodb.com/manual/reference/operator/aggregation/dayOfMonth/ for more details :param expression: expression or variable of a Date, a Timestamp, or an ObjectID :return: Aggregation operator """ return {'$dayOfMonth': expression}
def _html_escape(string): """HTML escape all of these " & < >""" html_codes = { '"': '&quot;', '<': '&lt;', '>': '&gt;', } # & must be handled first string = string.replace('&', '&amp;') for char in html_codes: string = string.replace(char, html_codes[char]) return string
def is_scoped_package(name): """ Return True if name contains a namespace. For example:: >>> is_scoped_package('@angular') True >>> is_scoped_package('some@angular') False >>> is_scoped_package('linq') False >>> is_scoped_package('%40angular') True """ return name.startswith(('@', '%40',))
def _parse_line(line): """If line is in the form Tag=value[#Comment] returns a (tag, value) tuple, otherwise returns None.""" non_comment = line.split('#')[0].strip() if len(non_comment) > 0: tag_value = [x.strip() for x in non_comment.split('=')] if len(tag_value) != 2: raise Exception("Line '" + line + "' not understood") return (tag_value[0], tag_value[1]) return None
def style_function_color_map(item, style_dict): """Style for geojson polygons.""" feature_key = item['id'] if feature_key not in style_dict: color = '#d7e3f4' opacity = 0.0 else: color = style_dict[feature_key]['color'] opacity = style_dict[feature_key]['opacity'] style = { 'fillColor': color, 'fillOpacity': opacity, 'color': '#262626', 'weight': 0.5, } return style
def to_base_10_int(n, input_base): """ Converts an integer in any base into it's decimal representation. Args: n - An integer represented as a tuple of digits in the specified base. input_base - the base of the input number. Returns: integer converted into base 10. Example: >>> to_base_10_int((8,1), 16) 129 """ return sum(c * input_base ** i for i, c in enumerate(n[::-1]))
def number_strip(meaning): """ strips numbers from the meaning array :param meaning: array :return: stripped list of meaning """ integer_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] returnVal = [] flag = False for everyWord in meaning: for everyChar in everyWord: if everyChar in integer_array: flag = True returnVal.append(everyWord[2:].capitalize().strip()) if not flag: flag = False returnVal.append(everyWord.capitalize().strip()) return returnVal
def der_value_offset_length(der): """Returns the offset and length of the value part of the DER tag-length-value object.""" tag_len = 1 # Assume 1 byte tag if der[tag_len] < 0x80: # Length is short-form, only 1 byte len_len = 1 len = int(der[tag_len]) else: # Length is long-form, lower 7 bits indicates how many additional bytes are required len_len = (der[tag_len] & 0x7F) + 1 len = int().from_bytes(der[tag_len+1:tag_len+len_len], byteorder='big', signed=False) return {'offset':tag_len+len_len, 'length':len}
def parse_sam_region(string): """Parse 1-based genomic region string into 0-based tuple.""" if not string: return () parts = string.strip().split(":") if len(parts) == 1: chrom = parts[0] return (chrom,) else: chrom = parts[0] positions = parts[1].split("-") positions = [int(s) for s in positions] positions[0] = positions[0] - 1 # offset return (chrom,) + tuple(positions)
def ms(val): """ Turn a float value into milliseconds as an integer. """ return int(val * 1000)
def encode(sample_encoder, label_encoder, variant): """Generate sample and label encoding for variant.""" encoding = sample_encoder(variant) label = label_encoder(variant) return (encoding, label)
def fib(x): """ @desc assumes x an int >= 0 @param {int} x Assumes it is an integer at least 0 or greater @return Fibonacci of x """ if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2)
def intersection(a, b): """ intersection(list, list): """ if not a: return [] if not b: return [] d = [] for i in a: if (i in b) and (i not in d): d.append(i) for i in b: if (i in a) and (i not in d): d.append(i) return d
def smallest_evenly_divisible(min_divisor, max_divisor, minimum_dividend=0): """Returns the smallest number that is evenly divisible (divisible with no remainder) by all of the numbers from `min_divisor` to `max_divisor`. If a `minimum_dividend` is provided, only dividends greater than this number will be evaluated. """ factors = range(max_divisor,0,-min_divisor) while True: counter = 0 for i in factors: if minimum_dividend % i != 0: break else: counter += 1 if counter == len(factors): return minimum_dividend minimum_dividend += 1
def polar_line_boundaries(polar_line, boundaries = None): """ Input `polar_line` should contain: (rho, cos_theta, sin_theta) Returns line points in cartesian space from the polar space parameters for that line: (x1, y1, x2, y2) `boundaries` if provided define the image boundaries over which the segment should be presented. """ x1, y1, x2, y2 = 0, 0, 0, 0 rho, cos_theta, sin_theta, d = polar_line # Provide more numerical robustness by dividing over greater # projection for the line normal if cos_theta >= abs(sin_theta): y1 = 0 if boundaries: y2 = boundaries[0] else: y2 = 1 x1 = (rho - sin_theta * y1) / cos_theta x2 = (rho - sin_theta * y2) / cos_theta else: x1 = 0 if boundaries: x2 = boundaries[1] else: x2 = 1 y1 = (rho - cos_theta * x1) / sin_theta y2 = (rho - cos_theta * x2) / sin_theta return (x1, y1, x2, y2)
def compare(parameter=0): """ Enumerate devices on host """ return 'compare', 'ifconfig -s | tail -n +2 | awk \'{print $1}\' | xargs echo -e NET: && lsblk -l | grep / | awk \'{print $1}\' | xargs echo DISK:'
def _remove_dot_from_extension( extensions ): """remove the dot from an extension Args: extensions (str or list): the extension Returns: the extension without the dot """ if isinstance(extensions, str): ext : str = extensions extensions = ext.replace(".","") return extensions
def separate_appetizers(dishes, appetizers): """ :param dishes: list of dish names :param appetizers: list of appetizer names :return: list of dish names The function should return the list of dish names with appetizer names removed. Either list could contain duplicates and may require de-duping. """ dish_set = set(dishes) appetizer_set = set(appetizers) remaining_dish = dish_set - appetizer_set return remaining_dish
def is_basic_datatype(value): """ We only save "basic" datatypes like ints, floats, strings and lists, dictionaries or sets of these as pickles in restart files This function returns True if the datatype is such a basic data type """ if isinstance(value, (int, float, str, bytes, bool)): return True elif isinstance(value, (list, tuple, set)): return all(is_basic_datatype(v) for v in value) elif isinstance(value, dict): return all( is_basic_datatype(k) and is_basic_datatype(v) for k, v in value.items() ) return False
def convert_number(number, denominators): """ Convert floats to mixed fractions """ int_number = int(number) if int_number == number: return int_number, 0, 1 frac_number = abs(number - int_number) if not denominators: denominators = range(1, 21) for denominator in denominators: numerator = abs(frac_number) * denominator if (abs(numerator - round(numerator)) < 0.01): break else: return None return int_number, int(round(numerator)), denominator
def expand_part(app, part): """Expand the single string 'part' into a list of strings Expands: - '%n' to [filename of the selected item] - '%f' to [full path of selected item] - '%s' to [full path of selected item 1, full path of selected item 2, ...] - '%p' to [full path of folder of selected item] """ if part == '%n': return [str(app.current_panel.selected_path.name)] elif part == '%f': return [str(app.current_panel.selected_path)] elif part == '%s': return [str(p) for p in app.current_panel.selected_paths] elif part == '%p': return [str(app.current_panel.selected_path.parent)] return [part]
def phy_re_ratio(carbon, d_carbon, previous_ratio, nutrient_limiter): """carbon and d_carbon im moles""" return ((carbon+d_carbon) / ((1/previous_ratio)*(carbon+d_carbon*nutrient_limiter)))
def n_mass(e): """ Calculate and return the value of mass using given value of the energy of nuclear reaction How to Use: Give arguments for e parameter, *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: e (int):nuclear energy in Joule Returns: int: the value of mass in kg """ c = 3 * 10 ** 8 m = e / c ** 2 return m
def extract_usertag(data): """Extract user tag """ user = data['user'] position = data.get('position') if not position: position = [data['x'], data['y']] return { "user": { "pk": int(user.get("id", user.get("pk"))), "username": user["username"], "full_name": user.get("full_name"), "profile_pic_url": user.get("profile_pic_url"), "is_verified": user.get("is_verified"), }, "position": position }
def find_previous_match(_list, _start_idx, _match): """Finds previous _match from _start_idx""" for _curr_idx in range(_start_idx, 0, -1): if _list[_curr_idx] == _match: return _curr_idx return -1
def constant_time_compare(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. Lifted from: http://code.djangoproject.com/svn/django/trunk/django/utils/crypto.py >>> constant_time_compare("ABC", "ABC") True >>> constant_time_compare("ABC", "ABD") False >>> constant_time_compare("ABC", "ABCD") False """ if len(val1) != len(val2): return False result = 0 for x, y in zip(val1, val2): result |= ord(x) ^ ord(y) return result == 0
def gcd(a, b): """Find the greatest common divisor using Euclid's algorithm. >>> gcd(1, 3) 1 >>> gcd(2, 10) 2 >>> gcd(6, 9) 3 >>> gcd(17, 289) 17 >>> gcd(2512561, 152351) 1 """ if a % b == 0: return b return gcd(b, a % b)
def splitter(number): """ splits the number in 10's for correct pronunciation. """ if number <= 20: return number, 0 elif 21 <= number <= 100: x, y = divmod(number, 10) return 10 * x, y elif 101 <= number <= 1000: x, y = divmod(number, 100) return 100 * x, y
def min_max_scale(X): """Scale the element of X into an interval [0, 1] Arguments: X {list} -- 2d list object with int or float Returns: list -- 2d list object with float """ m = len(X[0]) x_max = [-float('inf') for _ in range(m)] x_min = [float('inf') for _ in range(m)] for row in X: x_max = [max(a, b) for a, b in zip(x_max, row)] x_min = [min(a, b) for a, b in zip(x_min, row)] ret = [] for row in X: tmp = [(x - b)/(a - b) for a, b, x in zip(x_max, x_min, row)] ret.append(tmp) return ret
def count(text): """ Count net number of braces in text (add 1 for each opening brace, subtract one for each closing brace). Parameters ---------- text: String A string. Returns ------- counts: Integer Net number of braces. Examples -------- >>> from bibmanager.utils import count >>> count('{Hello} world') 0 """ return text.count("{") - text.count("}")
def format_thousands(x, pos=None): """The two args are the value and tick position.""" return '%1.0fK' % (x * 1e-3)
def diagnose(start, end): """Format a line of diagnosis markers from a range of character positions""" return (' ' * start) + ('^' * (end - start))
def has_method(obj, method): """ Returns whether input object contains the given method """ method_op = getattr(obj, method, None) return callable(method_op)
def factorial(n): """Return the factorial of n, an exact integer >= 0. >>> [factorial(n) for n in range(6)] [1, 1, 2, 6, 24, 120] >>> factorial(30) 265252859812191058636308480000000 >>> factorial(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 Factorials of floats are OK, but the float must be an exact integer: >>> factorial(30.1) Traceback (most recent call last): ... ValueError: n must be exact integer >>> factorial(30.0) 265252859812191058636308480000000 It must also not be ridiculously large: >>> factorial(1e100) Traceback (most recent call last): ... OverflowError: n too large """ import math if not n >= 0: raise ValueError("n must be >= 0") if math.floor(n) != n: raise ValueError("n must be exact integer") if n+1 == n: # catch a value like 1e300 raise OverflowError("n too large") result = 1 factor = 2 while factor <= n: result *= factor factor += 1 return result
def fibo(n): """Returns nth fibonacci number.""" a, b = 0, 1 for i in range(1, n): a, b = b, a+b return b
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str: """ Given a trait name, filters and hostname, create a url with which to query Zooma. Return this url. :param trait_name: A string containing a trait name from a ClinVar record. :param filters: A dictionary containing filters used when querying OxO :param zooma_host: Hostname of a Zooma instance to query. :return: String of a url which can be requested """ url = "{}/spot/zooma/v2/api/services/annotate?propertyValue={}".format(zooma_host, trait_name) url_filters = [ "required:[{}]".format(filters["required"]), "ontologies:[{}]".format(filters["ontologies"]), "preferred:[{}]".format(filters["preferred"]) ] url += "&filter={}".format(",".join(url_filters)) return url
def uniquify_tablewidgetitems(a): """ Eliminates duplicate list entries in a list of TableWidgetItems. It relies on the row property being available for comparison. """ if (len(a) == 0): tmp = [] else: tmp = [a[0]] # XXX: we need to compare row #s because # PySide doesn't allow equality comparison for QTableWidgetItems tmp_rows = set() tmp_rows.add(a[0].row()) for i in range(1,len(a)): if (a[i].row() not in tmp_rows): tmp.append(a[i]) tmp_rows.add(a[i].row()) return tmp
def avg_side_metrics(side_metrics): """ :param side_metrics: list of metric dicts :return: dict of metric dicts with average """ keys = side_metrics[0].keys() result = {} for key in keys: acum = sum(d[key] for d in side_metrics) result[key] = acum / len(side_metrics) return result
def convert_logical(logic_func): """ Converts the func as per format needed by the truths module""" logic_operator = {'.': '&', '+': '|', '~': 'not', 'XOR': '^', 'xor': '^'} for exp in logic_operator.keys(): logic_func = logic_func.replace(exp, logic_operator[exp]) return logic_func
def five_year_fcf(FCF,growth_rate = 0.25): """ Returns 5 year cashflow projection in a list of float elements calculated from estimated short term growth rate and free cash flow. """ #make it into dictionary year_0 = FCF year_1 = year_0*(1+growth_rate) year_2 = year_1*(1+growth_rate) year_3 = year_2*(1+growth_rate) year_4 = year_3*(1+growth_rate) year_5 = year_4*(1+growth_rate) return year_0,year_1,year_2,year_3,year_4,year_5
def f(x, y): """ sample func """ return x * x - y * y
def _email_validator(value): """Email address.""" # ridiculously yet robust simple email validator ;) if value.count('@') != 1: raise ValueError('Incorrect email format: {}'.format(value)) return value