content
stringlengths
42
6.51k
def selection_sort(arr: list): """Simple implementation of the Selection Sort algorithm. Loops through the array, looking for the smallest item to the right of the current one and swapping those two values. :param arr (list) : List to be sorted. :return (list) : Sorted list. """ # Loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index # Find next smallest item to the right of current item for j in range(cur_index + 1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j # Swap the values at the two indices in question # First, extract the two values cur_index_val = arr[cur_index] smallest_index_val = arr[smallest_index] # Assign each to the other's index arr[cur_index] = smallest_index_val arr[smallest_index] = cur_index_val return arr
def format_input_amount(amount): """ jinja2 filter function for treatment of input number""" return '{}'.format(amount).rstrip("0").rstrip(".")
def is_two_words(w): """ Returns: True if w is 2 words sep by 1 or more spaces. A word is a string with no spaces. So this means that 1. The first characters is not a space (or empty) 2. The last character is not a space (or empty) 3. There is at least one space in the middle 4. If there is more than one space, the spaces are adjacent Parameter w: the string to test Precondition: w is a string """ if not ' ' in w: return False # Find the first space first = w.find(' ') # Find the Last space last = w.rfind(' ') # Break the string into three parts w0 = w[:first] w1 = w[first:last+1] w2 = w[last+1:] # Make sure middle is only spaces cond1 = w1.count(' ') == len(w1) # Make sure other strings not empty cond0 = w0 != '' cond2 = w2 != '' return cond0 and cond1 and cond2
def format_number(num, digits=0): """ Give long numbers an SI prefix. """ formatstring = '{{:.{}f}}{{}}'.format(digits) prefixes = [(1e24, 'Y'), (1e21, 'Z'), (1e18, 'E'), (1e15, 'P'), (1e12, 'T'), (1e9, 'G'), (1e6, 'M'), (1e3, 'k'), (1, '')] for magnitude, label in prefixes: if num >= magnitude: return formatstring.format(num / magnitude, label)
def human_time(s): """ Return human-readable string of n seconds >>> human_time(42) '42s' >>> human_time(32490) '9h01m30s' """ if s > 3600: return '%ih%02im%02is' % (s / 3600, s / 60 % 60, s % 60) if s > 60: return '%im%02is' % (s / 60, s % 60) return '%02is' % s
def rtsafe(func, xlow, xhigh, epsilon): """ Root finding by combined bisection and Newton iteration; func must return f, df/dx at x desired root must be on [xlow, xhigh] """ flow, df = func(xlow) fhigh, df = func(xhigh) assert flow*fhigh < 0 # early termination: If it worked, just return! if abs(flow) <= epsilon: return xlow if abs(fhigh) <= epsilon: return xhigh # if bracketing values don't give flow<0, reverse them if flow>0: xlow, xhigh = xhigh, xlow xmid = 0.5*(xlow+xhigh) dxold = abs(xhigh-xlow) dx = dxold fmid, df = func(xmid) MAXINT = 50 for i in range(MAXINT): # if newton will take us outside the range, # or if convergence is too slow, use bisection if ((xmid-xhigh)*df - fmid) * ((xmid-xlow)*df - fmid) > 0 or abs(2*fmid) > abs(dxold*df): dxold = dx dx = 0.5*(xhigh-xlow) xmid = xlow + dx if xlow == xmid: return xmid # otherwise use newton else: dxold = dx dx = fmid/df temp = xmid xmid -= dx # if adding the correction doesn't change xmid, return it; # we're as close as we can get if temp==xmid: return xmid # if we are close enough, return the result if abs(fmid) < epsilon or abs(dx) < epsilon: return xmid fmid, df = func(xmid) if fmid<0: # on left side of root, update xlow xlow = xmid else: # on right side of root, update xr xhigh = xmid print("rtsafe: no convergence in ", MAXINT, "iterations; returning 'None'") return None
def no_numbers(data: str): """ Checks whether data contain numbers. :param data: text line to be checked :return: True if the line does not contain any numbers """ numbers = "0123456789" for c in data: if c in numbers: return False return True
def time_str_to_int(value: str) -> int: """Convert time as string to integer (seconds).""" minutes, seconds = value.split(':') return int(minutes) * 60 + int(seconds)
def degrees2text(num): """ Convert Degrees 0-360 to Readable Text """ val = int((num/22.5)+.5) arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] return arr[(val % 16)]
def FilterListClass(objclass,inlist,exclude=False): """ select list elements that [NOT when exclude=True] belong to (a group of) classes. Arguments: objclass --> class name or tuple of class name """ if exclude==True: return [lm for lm in inlist if not isinstance(lm,objclass)] else: return [lm for lm in inlist if isinstance(lm,objclass)]
def _make_json_bed_entry(bed_file, display_name, dir_url): """add a bed file to json """ entry = {} entry["type"] = "bed" entry["url"] = "{}/{}".format(dir_url, bed_file) entry["name"] = display_name entry["mode"] = "full" return entry
def normalize(s): """ Normalize strings to space joined chars. Args: s: a list of strings. Returns: A list of normalized strings. """ if not s: return s normalized = [] for ss in s: tokens = [c for c in list(ss) if len(c.strip()) != 0] normalized.append(' '.join(tokens)) return normalized
def max_number(input_num): """Create largest possible number out of the input. Parameters ---------- input_num : int Positive integer. Returns ------- max_num : int Maximum number that can be made out of digits present in input_num. """ num_to_str = str(input_num) num_to_list = list(num_to_str) num_to_list.sort(reverse=True) max_str = "".join(num_to_list) max_num = int(max_str) return max_num
def validate_container_command(output: str, name: str) -> tuple: """ Validates output from one of the *_container functions, eg start_container. :param output: output from the command line :param name: container name or ID :return: success boolean, message """ if "no such container" in output: return False, "no such container" elif output != name.lower(): return False, output else: return True, "ok"
def mpl_color(plotly_color): """ Convert a plotly color name to a matplotlib compatible one. Parameters ---------- plotly_color : str A plotly color value, e.g. `"#FF0023"` or `"rgb(0,255,128)"`. Returns ------- str """ plotly_color = plotly_color.strip() # remove any whitespace if plotly_color.startswith('#'): return plotly_color # matplotlib understands "#FF0013" elif plotly_color.startswith('rgb(') and plotly_color.endswith(')'): tupstr = plotly_color[len('rgb('):-1] tup = [float(x) / 256.0 for x in tupstr.split(',')] return tuple(tup) elif plotly_color.startswith('rgba(') and plotly_color.endswith(')'): tupstr = plotly_color[len('rgba('):-1] rgba = tupstr.split(',') tup = [float(x) / 256.0 for x in rgba[0:3]] + [float(rgba[3])] return tuple(tup) else: return plotly_color
def extra_chars_to_encode(string): """Return the additional chars needed to escape string For example: "" becomes "\"\"" ie two escaped quotes with additional surrounding quotes "abc" "\"abc\"" "aaa\"aaa" "\"abc\\\"aaa\"" "\x27" "\"\\x27\"" """ # Start with the additional enclosing quotes total_extra = 2 # Then backlashes needed for existing quotes total_extra += string.count('"') # Then backlashes for backslashes total_extra += string.count("\\") return total_extra
def unsigned_leb128_encode(value: int) -> bytes: """Encode number as into unsigned leb128 encoding .. doctest:: >>> from ppci.utils.leb128 import unsigned_leb128_encode >>> unsigned_leb128_encode(42) b'*' """ if not isinstance(value, int): raise TypeError("Expected int but got {}".format(type(value))) if value < 0: raise ValueError("Cannot encode negative number as unsigned leb128") data = [] # ints, really while True: byte = value & 0x7F value >>= 7 if value == 0: # We are done! data.append(byte) break else: data.append(byte | 0x80) # Append data and continuation marker return bytes(data)
def partTypeNum(partType): """ Mapping between common names and numeric particle types. """ if str(partType).isdigit(): return int(partType) if str(partType).lower() in ['gas','cells']: return 0 if str(partType).lower() in ['dm','darkmatter']: return 1 if str(partType).lower() in ['tracer','tracers','tracermc','trmc']: return 3 if str(partType).lower() in ['star','stars','stellar']: return 4 # only those with GFM_StellarFormationTime>0 if str(partType).lower() in ['wind']: return 4 # only those with GFM_StellarFormationTime<0 if str(partType).lower() in ['bh','bhs','blackhole','blackholes']: return 5 raise Exception("Unknown particle type name.")
def templated_sequence_components(location_descriptors): """Provide possible templated sequence component input data.""" return [ { "component_type": "templated_sequence", "strand": "+", "region": location_descriptors[5] }, { "component_type": "templated_sequence", "strand": "-", "region": location_descriptors[4] } ]
def get_rank_hit_metrics(y_id, pred_ids): """ :type y_id: int :type pred_ids:list, k possible ids order by score desc """ ranking = pred_ids.index(y_id) + 1 _matrics = { 'MRR': 1.0 / ranking, 'MR': float(ranking), 'HITS@1': 1.0 if ranking <= 1 else 0.0, 'HITS@3': 1.0 if ranking <= 3 else 0.0, 'HITS@10': 1.0 if ranking <= 10 else 0.0} return _matrics
def _steps_to_run(steps_in_current_epoch, steps_per_epoch, steps_per_loop): """Calculates steps to run on device.""" if steps_per_loop <= 0: raise ValueError('steps_per_loop should be positive integer.') if steps_per_loop == 1: return steps_per_loop return min(steps_per_loop, steps_per_epoch - steps_in_current_epoch)
def convoltuion_shape(img_height, img_width, filter_shape, stride, padding): """Calculate output shape for convolution layer.""" height = (img_height + 2 * padding[0] - filter_shape[0]) / float(stride[0]) + 1 width = (img_width + 2 * padding[1] - filter_shape[1]) / float(stride[1]) + 1 assert height % 1 == 0 assert width % 1 == 0 return int(height), int(width)
def extract_name_email (txt): """ Extracts the name and email from RFC-2822 encoded email address. For eg. "Jeff Jeff <jeff.jeff@gmail.com>" returns ("Jeff Jeff", "jeff.jeff@gmail.com") """ if "<" in txt and ">" in txt: name, email = txt.split("<") return name[:-1], email[:-1] elif "<" not in txt and ">" not in txt: return "", txt else: return None
def decimal_year(year, month, day, hour, minute, second): """decimal_year converts a date (year,month,day,hour,minute,second) into a decimal date. credit : Kimvais https://stackoverflow.com/questions/6451655/how-to-convert-python-datetime-dates-to-decimal-float-years""" # Standard Library dependencies from datetime import datetime d = datetime(year, month, day, hour, minute, second) year_ = (float(d.strftime("%j")) - 1) / 366 + float(d.strftime("%Y")) return year_
def lesser(tup,value): """ Returns the number of elements in tup strictly less than value Examples: lesser((5, 9, 1, 7), 6) returns 2 lesser((1, 2, 3), -1) returns 0 Parameter tup: the tuple to check Precondition: tup is a non-empty tuple of ints Parameter value: the value to compare to the tuple Precondition: value is an int """ assert type(tup) == tuple, 'tup isnt a tuple' assert len(tup) >= 1, 'tuple cant be empty' assert type(value) == int, 'value isnt an int' count = 0 for index in tup: # assigns index as a element in tup equiv to index = tup[:]? if index < value: count += 1 return count # pass
def set_bit(value, index, high=True): """Set the index:th bit of value. Args: value (int): Number that will have bit modified. index (int): Index of bit to set. high (bool): True (default) = set bit high, False = set bit low """ mask = 1 << index value &= ~mask if high: value |= mask return value
def parse_sn(seqnum, base=10): """Parse the sequence number and return as a number.""" seqnum = seqnum.split(',') high_sn = int(seqnum[0], base) low_sn = int(seqnum[1], base) return (high_sn << 32) | (low_sn)
def reformate_path(path): """On certain editors (e.g. Spyder on Windows) a copy-paste of the path from the explorer includes a 'file:///' attribute before the real path. This function removes this extra piece Args: path: original path Returns: Reformatted path """ _path = path.split('file:///', 2) if len(_path) == 2: new_path = path.split('file:///', 2)[1] else: new_path = path return new_path
def record_has(inrec, fieldvals): """Accept a record, and a dictionary of field values. The format is {'field_name': set([val1, val2])}. If any field in the record has a matching value, the function returns True. Otherwise, returns False. """ retval = False for field in fieldvals: if isinstance(inrec[field], str): set1 = {inrec[field]} else: set1 = set(inrec[field]) if (set1 & fieldvals[field]): retval = True break return retval
def fonts(*names): """Join fonts with quotes and commas. >>> fonts("Comic Sans, "sans") "\"Comic Sans\", \"Sans\"" """ return ",".join('"%s"' % name for name in names)
def _scopes_to_resource(*scopes): """Convert an AADv2 scope to an AADv1 resource""" if len(scopes) != 1: raise ValueError("This credential requires exactly one scope per token request.") resource = scopes[0] if resource.endswith("/.default"): resource = resource[: -len("/.default")] return resource
def sum_of_digits(number: int) -> int: """ Returns the sum of digits for the entered number """ return eval("+".join([i for i in str(number)]))
def make_html_tag(tag, text=None, **params): """Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_tag('a', text="Hello", href="/another/page") -> <a href="/another/page">Hello</a> To use reserved Python keywords like "class" as a parameter prepend it with an underscore. Instead of "class='green'" use "_class='green'". Warning: Quotes and apostrophes are not escaped.""" params_string = "" # Parameters are passed. Turn the dict into a string like "a=1 b=2 c=3" string. for key, value in sorted(params.items()): # Strip off a leading underscore from the attribute's key to allow attributes like '_class' # to be used as a CSS class specification instead of the reserved Python keyword 'class'. key = key.lstrip("_") params_string += u' {0}="{1}"'.format(key, value) # Create the tag string tag_string = u"<{0}{1}>".format(tag, params_string) # Add text and closing tag if required. if text: tag_string += u"{0}</{1}>".format(text, tag) return tag_string
def calculate_tax(income): """Implement the code required to make this function work. Write a function `calculate_tax` that receives a number (`income`) and calculates how much of Federal taxes is due, according to the following table: | Income | Tax Percentage | | ------------- | ------------- | | <= $50,000 | 15% | | <= $75,000 | 25% | | <= $100,000 | 30% | | > $100,000 | 35% | Example: income = 30000 # $30,000 is less than $50,000 calculate_tax(income) # $30,000 * 0.15 = 4500 = $4,500 income = 80000 # $80,000 is more than $75,000 but less than $80,000 calculate_tax(income) # $80,000 * 0.25 = 20000 = $20,000 income = 210000 # $210,000 is more than $100,000 calculate_tax(income) # $210,000 * 0.35 = 73500 = $73,500 """ tax = 0 if income <= 50000: tax += (income *.15) return tax elif income >= 50000 and income <= 75000: tax += (income * .25) return tax elif income >= 75000 and income <= 100000: tax += (income * .30) return tax elif income >= 100000: tax += (income * .35) return tax
def get_function_name_from_url(queue_url) -> str: """ Returns a string with the name of the lambda function :param str queue_url: :return str: """ return queue_url[41:]
def get_overrides(token_fields_base, token_fields_from_args): """Returns true if there are any overrides from the token key args. Handles nested fields args split by a period.""" overrides = [] for key_raw, _ in token_fields_from_args.items(): keys = key_raw.split('.') base_ref = token_fields_base try: for key in keys: base_ref = base_ref[key] # no KeyError means that the token_fields_base has an existing value corresponding with the arg overrides.append(key_raw) except KeyError: pass return overrides
def is_track_in_tracks(song_uri, tracks): """ Checks whether song is within a list of songs :param song_uri: ID of target song :param tracks: Page object of track or playlist track objects :return: Whether or a not a song is within a list of tracks """ for track in tracks['items']: try: # If playlist track it contains the track object within the key 'track' if song_uri == track['track']['uri']: return True except KeyError: if song_uri == track['uri']: return True return False
def parse_hex(hex_string): """ Helper function for RA and Dec parsing, takes hex string, returns list of floats. :param hex_string: string in either full hex ("12:34:56.7777" or "12 34 56.7777"), or degrees ("234.55") :return: list of strings representing floats (hours:min:sec or deg:arcmin:arcsec). from photrix August 2018. """ colon_list = hex_string.split(':') space_list = hex_string.split() # multiple spaces act as one delimiter if len(colon_list) >= len(space_list): return [x.strip() for x in colon_list] return space_list
def addArgs(args, subparser): """Add args to the given subparser""" if (args is not None): for arg in args: if not arg.choices: subparser.add_argument(arg.name, help=arg.help) else: subparser.add_argument(arg.name, choices=arg.choices, help=arg.help) return subparser
def related_to_hardware(cpes): """ Return True if the CVE item is related to hardware. """ for cpe in cpes: cpe_comps = cpe.split(":") # CPE follow the format cpe:cpe_version:product_type:vendor:product if len(cpe_comps) > 2 and cpe_comps[2] == "h": return True return False
def name(name_, swap=False, end='\n'): """ Return the name in brackets. For example:\n ```text [abc def] [abc-def ghi] ``` """ name_ = name_.split('/')[1] if 'submission/' in name_ else name_ name_ = ' '.join(reversed(name_.split(' '))) if swap else name_ return f'[{name_}]'
def any_are_none(*args): """Return True if any of args are None.""" for arg in args: if arg is None: return True return False
def cmd(arg1, arg2): """ This is a command that does things. Yay! :param arg1: The first argument. :type arg1: :py:obj:`something` :param arg2: The second argument. aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaa :return: A thingy. :rtype: :py:obj:`Deferred` """ a = 1 a += 2 return a
def reverse_word(string, word_start, word_end): """ reverses a sub string from start index to end index in place. """ # this whole function could be replaced by splicing # see the function below start = word_start end = word_end if end - start > 1: while start >= word_start and end <= word_end and start < end: string[start], string[end] = string[end], string[start] start += 1 end -= 1 return string
def line_contains_all(the_line, items): """ Determine if all of the members of items are present in the string, if so, return True :param the_line: The input line to check against :param items: The (list of) check items :return: True if all items found, False otherwise """ for the_item in items: if the_item not in the_line: return False return True
def workid_from_url(url): """Get the workid from an archiveofourown.org website url Args: url (str): Work URL Returns: int: Work ID """ split_url = url.split("/") try: index = split_url.index("works") except ValueError: return if len(split_url) >= index+1: workid = split_url[index+1].split("?")[0] if workid.isdigit(): return int(workid) return
def lcs(string_a, string_b): """ Calculate the length of the longest common subsequence of characters between two strings. The time complexity of this implementation is dominated by the two nested loops, let the length of string_a and string_b is 'n' and 'm' respectively. This would lead to a time complexity of O(n*m). But in general, we can consider it as O(n*n) instead of O(n*m). """ matrix = [[0 for i in range(len(string_a) + 1)] for j in range(len(string_b) + 1)] for y in range(1, len(string_b) + 1): for x in range(1, len(string_a) + 1): if string_a[x-1] == string_b[y-1]: matrix[y][x] = matrix[y-1][x-1] + 1 else: matrix[y][x] = max(matrix[y-1][x], matrix[y][x-1]) return matrix[-1][-1]
def create_proxyauth_extension(proxy_host, proxy_port, proxy_username, proxy_password, scheme='http', plugin_path=None): """ Proxy Auth Extension args: proxy_host (str): domain or ip address, ie proxy.domain.com proxy_port (int): port proxy_username (str): auth username proxy_password (str): auth password kwargs: scheme (str): proxy scheme, default http plugin_path (str): absolute path of the extension return str -> plugin_path """ import string import zipfile if plugin_path is None: plugin_path = '/tmp/chrome_proxyauth_plugin.zip' manifest_json = """ { "version": "1.0.0", "manifest_version": 2, "name": "Chrome Proxy", "permissions": [ "proxy", "tabs", "unlimitedStorage", "storage", "<all_urls>", "webRequest", "webRequestBlocking" ], "background": { "scripts": ["background.js"] }, "minimum_chrome_version":"22.0.0" } """ background_js = string.Template( """ var config = { mode: "fixed_servers", rules: { singleProxy: { scheme: "${scheme}", host: "${host}", port: parseInt(${port}) }, bypassList: ["foobar.com"] } }; chrome.proxy.settings.set({value: config, scope: "regular"}, function() {}); function callbackFn(details) { return { authCredentials: { username: "${username}", password: "${password}" } }; } chrome.webRequest.onAuthRequired.addListener( callbackFn, {urls: ["<all_urls>"]}, ['blocking'] ); """ ).substitute( host=proxy_host, port=proxy_port, username=proxy_username, password=proxy_password, scheme=scheme, ) with zipfile.ZipFile(plugin_path, 'w') as zp: zp.writestr("manifest.json", manifest_json) zp.writestr("background.js", background_js) return plugin_path
def _make_iter(obj, make_fn, **options): """ :param obj: A mapping objects or other primitive object :param make_fn: Function to make/convert to :param options: Optional keyword arguments. :return: Mapping object """ return type(obj)(make_fn(v, **options) for v in obj)
def is_pandas_df(obj): """Check if an object is a Pandas dataframe The benefit here is that Pandas doesn't have to be included in the dependencies for pydeck The drawback of course is that the Pandas API might change and break this function """ return obj.__class__.__module__ == 'pandas.core.frame' and obj.to_records and obj.to_dict
def translate_user_agent_string(user_agent): """Returns the most likely user agent type for the given user agent string.""" if not user_agent: return None if "CFNetwork" in user_agent: return "iOS" elif "okhttp" in user_agent: return "Android" elif "Android" in user_agent: return "Android Browser" elif "Mobile" in user_agent and "Safari" in user_agent: return "Mobile Safari" else: return "Desktop"
def asn_pool_absent(module, session, my_pool): """ Remove ASN pool if exist and is not in use :param module: Ansible built in :param session: dict :param my_pool: dict :return: success(bool), changed(bool), results(dict) """ # If the resource does not exist, return directly if not my_pool: return True, False, {'display_name': '', 'id': '', 'msg': 'Pool does not exist'} if my_pool['status'] != 'not_in_use': return False, False, {"msg": "Unable to delete ASN Pool {}," " currently in use".format(my_pool['display_name'])} if not module.check_mode: aos_delete(session, ENDPOINT, my_pool['id']) return True, True, my_pool return True, False, my_pool
def turn_check_perturb(base_dir, targ_dir): """ :param base_dir: the direction (NESW) from the previous step :param targ_dir: the target direction (NESW) :rtype: string :return: 'right' or 'left' depending on where the camera should turn, otherwise 'straight' if the camera is facing in the target direction and should not turn """ if targ_dir == "Dir.WEST": if base_dir == "Dir.NORTH": return "left" elif base_dir == "Dir.SOUTH": return "right" elif targ_dir == "Dir.EAST": if base_dir == "Dir.NORTH": return "right" elif base_dir == "Dir.SOUTH": return "left" elif targ_dir == "Dir.NORTH": if base_dir == "Dir.WEST": return "right" elif base_dir == "Dir.EAST": return "left" elif targ_dir == "Dir.SOUTH": if base_dir == "Dir.WEST": return "left" elif base_dir == "Dir.EAST": return "right" return "straight"
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: Dictionary. Structured data with the following schema: { "kernel_name": string, "node_name": string, "kernel_release": string, "operating_system": string, "hardware_platform": string, "processor": string, "machine": string, "kernel_version": string } """ # nothing to process return proc_data
def det_mat3(m): """Find the determinant of the given matrix. This function is ONLY defined so we can test variable good_mats. >>> len(good_mats) 24 >>> all(( a != b for a, b in itertools.combinations(good_mats, 2) )) True >>> all(( det_mat3(mat) == 1 for mat in good_mats )) True """ assert type(m) == list assert len(m) == 3 assert all(( type(colvec) == list for colvec in m )) d0 = m[1][1]*m[2][2]-m[1][2]*m[2][1] d1 = m[1][0]*m[2][2]-m[1][2]*m[2][0] d2 = m[1][0]*m[2][1]-m[1][1]*m[2][0] return m[0][0]*d0 - m[0][1]*d1 + m[0][2]*d2
def fixName(s): """ Hack. Some Astrobee commands have a parameter with id 'name_', which is a workaround for 'name' being a reserved word in XPJSON. For backward compatibility, we convert 'name_' to 'name' in some cases. """ if s == 'name_': return 'name' else: return s
def crc16(frame): """Compute CRC16 :param frame: frame :type frame: str (Python2) or class bytes (Python3) :returns: CRC16 :rtype: int """ crc = 0xFFFF for item in bytearray(frame): next_byte = item crc ^= next_byte for _ in range(8): lsb = crc & 1 crc >>= 1 if lsb: crc ^= 0xA001 return crc
def isaxial(IOP): """ Check whether an instance is axial Parameters ---------- IOP: {list, numpy.ndarray} Image Orientation Patient Returns: bool Axial result ------- """ IOP = [round(float(s)) for s in IOP] if IOP == [1, 0, 0, 0, 1, 0]: return True else: return False
def is_prime(number: int) -> bool: """Returns True if number is prime or False if the number is not prime""" results_list = [x for x in range(2, number) if number % x == 0] return len(results_list) == 0
def fibonacci_dp(n): """Fibonacci series by bottom-up dynamic programming. - Time complexity: O(n). - Space complexity: O(n). """ T = [None] * (n + 1) T[0] = 0 T[1] = 1 for n in range(2, n + 1): T[n] = T[n - 1] + T[n - 2] return T[n]
def improve_sponsor_award_id(s): """ Given a string with a sponsor award id, standardize presentation and regularize NIH award ids :param s: string with sponsor award id :return: string improved sponsor award id :rtype: string """ import re s = s.strip() nih_pattern = re.compile('.*([A-Za-z][0-9][0-9]).*([A-Za-z][A-Za-z][0-9]{6})') match_object = nih_pattern.match(s) if match_object: return match_object.group(1).upper() + match_object.group(2).upper() else: return s
def elideCompiles(words, line): """If the first word of line is in words then delete all but the first and last word in the line.""" for word in words: if line.startswith(word): lwords = line.split() return '%s %s' % (lwords[0], lwords[-1]) return line
def nl_strip(string: str) -> str: """ Strip blanks and punctuation symbols :param string: :return: """ return string.strip().strip('.,:!?').strip()
def _set_default_contact_rating(contact_rating_id: int, type_id: int) -> int: """Set the default contact rating for mechanical relays. :param contact_form_id: the current contact rating ID. :param type_id: the type ID of the relay with missing defaults. :return: _contact_rating_id :rtype: int """ if contact_rating_id > 0: return contact_rating_id return {1: 2, 2: 4, 3: 2, 4: 1, 5: 2, 6: 2}[type_id]
def copy_metadata(nb_data): """Copy metadata of notebook Args: nb_data (JSON): a json data load from jupyter notebook Returns: dict: metadate copied from nb_data """ metadata = dict() metadata["metadata"] = nb_data["metadata"] metadata["nbformat"] = nb_data["nbformat"] metadata["nbformat_minor"] = nb_data["nbformat_minor"] return metadata
def _sdq(input_text = ''): """function to escape ' in xpath for tagui live mode""" # change identifier single quote ' to double quote " return input_text.replace("'",'"')
def enquote2(text): """Quotes input string with double-quote""" in_str = text.replace('"', r'\"') return '"%s"' % text
def sum_of_differentials(lists_of_vals): """ Given a list of list of vals, return the sum of all the differentials from one list to the next. Returns a val. Ex: sum_of_differentials([[1,1,1],[1,2,3],[1,2,2]]) evaluates to 4 """ total_diff = [0 for x in lists_of_vals[0]] for i in range(len(lists_of_vals) - 1): diff = [abs(lists_of_vals[i][j] - lists_of_vals[i+1][j]) for j in range(len(lists_of_vals[i]))] total_diff = [diff[x] + total_diff[x] for x in range(len(total_diff))] return sum(total_diff)
def _makefpartparamsizes(nbparams): """return a struct format to read part parameter sizes The number parameters is variable so we need to build that format dynamically. """ return '>'+('BB'*nbparams)
def nibbles(s): """Chops up an iterable of int-ables to nibbles""" ns = [] for c in s: ns.append((int(c) & 0x0f)) ns.append((int(c) >> 4)) return ns
def _FlagIsExplicitlySet(args, flag): """Return True if --flag is explicitly passed by the user.""" # hasattr check is to allow the same code to work for release tracks that # don't have the args at all yet. return hasattr(args, flag) and args.IsSpecified(flag)
def _get_ex_msg(obj): """Get exception message.""" return obj.value.args[0] if hasattr(obj, "value") else obj.args[0]
def is_prefix(needle, p): """ Is needle[p:end] a prefix of needle? """ j = 0 for i in range(p, len(needle)): if needle[i] != needle[j]: return 0 j += 1 return 1
def cargoport_url(package, pkg_version, bioc_version=None): """ Constructs a url for the package as archived on the galaxy cargo-port Parameters ---------- package : str Case-sensitive Bioconductor package name pkg_version : str Bioconductor package version bioc_version : str Bioconductor release version. Not used;, only included for API compatibility with other url funcs """ package = package.lower() return ( 'https://depot.galaxyproject.org/software/bioconductor-{0}/bioconductor-{0}_' '{1}_src_all.tar.gz'.format(package, pkg_version) )
def mag2(v): """ Returns square of the magnitude of v. """ x, y, z = v return x*x + y*y + z*z
def reverse_range(values): """Yields reverse range of values: list(reverse_range([1, 2, 3])) -> [2, 1, 0].""" return range(len(values) - 1, -1, -1)
def build_cost_matrix(preference_dictionary): """ :param preference_dictionary: :return cost_matrix: """ cost_matrix = [] for costs in preference_dictionary.values(): cost_matrix.append(costs) return cost_matrix
def acceptance_rule_naive(x_likelihood, x_new_likelihood, debug=False): """ Decides whether to accept new point, x_new, or not, based on its likelihood. Args: x_likelihood: likelihood of the old parameter point x_new_likelihood: likelihood of the new parameter point debug (bool): if True extensive print will be used Returns: True if the new points is accepted @author: xhajnal """ ## If likelihood of new point is higher (than likelihood of current point) accept the new point if x_new_likelihood > x_likelihood: return True
def get_default_coefficient_name(predictor): """Get default name for coefficient.""" return 'beta_{}'.format(predictor)
def replace(template, ctx): """Replace placeholders with their values and return the result. Example: >>> replace("$NAME is down", {"$NAME": "foo"}) foo is down This function explicitly ignores "variable variables". In this example, placeholder's value itself contains a placeholder: >>> replace("Hello $FOO", {"$FOO": "$BAR", "$BAR": "World"}) Wrong: Hello World Correct: Hello $BAR >>> replace("Hello $$FOO", {"$FOO": "BAR", "$BAR": "World"}) Wrong: Hello World Correct: Hello $BAR In other words, this function only replaces placeholders that appear in the original template. It ignores any placeholders that "emerge" during string substitutions. This is done mainly to avoid unexpected behavior when check names or tags contain dollar signs. """ parts = template.split("$") result = [parts.pop(0)] for part in parts: part = "$" + part for placeholder, value in ctx.items(): if part.startswith(placeholder): part = part.replace(placeholder, value, 1) break result.append(part) return "".join(result)
def is_hashable(obj): """Return True if hash(obj) will succeed, False otherwise. Some types will pass a test against collections.Hashable but fail when they are actually hashed with hash(). Distinguish between these and other types by trying the call to hash() and seeing if they raise TypeError. Examples -------- >>> a = ([],) >>> isinstance(a, collections.Hashable) True >>> is_hashable(a) False """ # Unfortunately, we can't use isinstance(obj, collections.Hashable), which # can be faster than calling hash. That is because numpy scalars on Python # 3 fail this test. # Reconsider this decision once this numpy bug is fixed: # https://github.com/numpy/numpy/issues/5562 try: hash(obj) except TypeError: return False else: return True
def format_best(best_ans, close=True): """Formats best answer to match format of reference answers""" best = best_ans.strip() if close: if best[-1] != '.': best = best + '.' return best
def normalize_angle_change(d1, d0): """ Calculates the difference in degrees, taking into account 360 degree rollover. """ change = d1 - d0 if change > 180: change -= 360 elif change < -180: change += 360 return change
def kalman_pseudo(data_input, prev_data): """ data_input represents the ranking of hashes (modify input to represent sorted list of tuples) i.e. data_input = [(file_name, percentage of common hashes),()] prev_data will represent the previous recording's hashes. i.e. prev_data = file_name """ if prev_data in [x for x,y in data_input]: return prev_data return data_input[0][0]
def parse_grid_to_dict(data: str) -> dict: """ Parse grid given as a string to dictionary. k: coordinates (x, y) v: value Example: X.O => { (0, 0): 'X', (1, 0): '.', (2, 0): 'O', ... (0, 1): '.', (1, 1): '.', (2, 1): '.', ..O (0, 2): '.', (1, 2): '.', (2, 2): 'O', } """ return { (x, y): v for y, row in enumerate(data.strip().split('\n')) for x, v in enumerate(row.strip()) }
def cast_tuple_int_list(tup): """Set tuple float values to int for more predictable test results""" return [int(a) for a in tup]
def merge_lists(list1, list2): """ Return a merged list while preserving order. """ ipos = 0 list_merged = [] for x in list1: if x not in list_merged: if x in list2: xpos = list2.index(x) list_merged += list2[ipos:xpos] ipos = xpos + 1 list_merged.append(x) # list2 might have extra items if len(list2) > ipos: list_merged += list2[ipos:] return list_merged
def f(x, y): """ Function that will be optimized Parameters ---------- x : float Value for parameter x. y : float Value for parameter x. Returns ------- float Function value for f(x,y). """ if (x**2 + y**2) <= 2: return (1-x)**2 + 100*((y - x**2)**2) else: return 10**8
def kappa_approximation(R): """ Kappa MLE approximation from (Mardia and Jupp, 2000, pg. 85,86). """ # For "small" R (5.3.7); R < 0.53 if R < 0.53: return 2*R + R**3 + (5/6)*(R**5) # For "large" R (5.3.8); R >= 0.85 if R >= 0.85: return (1 / (2 * (1 - R) - ((1-R)**2) - ((1-R)**3))) # return (1 / (2*(1-R))) # (5.3.9) - this isn't a good approximation # For "medium" R (5.3.10); 0.53 <= R < 0.85 return -0.4 + 1.39*R + (0.43/(1-R))
def determine_section_of_contour(checkboxes, rect): """This does work with my hacky solution. this needs work - but afterwards we should be in good shape to finish this project wanna be bigger than checkbox so sort by y - normally- and as soon as we are larger than """ search = [x for x in checkboxes if x[4] == rect[4]] for y in sorted(search, key=lambda x: (x[1]))[::-1]: if rect[1] > y[1]: return y[5] return max([x[5] for x in checkboxes])
def equalize_array(array): """ Expand all rows of 2D array to the same length """ if len(array) == 0: return array max_length = max([len(i) for i in array]) for row in array: diff = max_length - len(row) row.extend([""] * diff) return array
def factorial(integer: int) -> int: """Return the factorial of a given integer. Args: integer (int): the integer whose factorial is going to be calculated Returns: int: the factorial of the provided integer """ if integer in {0, 1}: return 1 return integer * factorial(integer - 1)
def to_language(locale): """Turns a locale name (en_US) into a language name (en-us).""" p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
def is_group(child: dict) -> bool: """Return true if child is a group.""" if child.get("is_group"): return True elif len( set(child.keys()) - set([ "account_type", "root_type", "is_group", "tax_rate", "account_number" ]) ): return True return False
def bubblesort(unsorted_list): """Sort an unsorted list.""" swapped = True while swapped: swapped = False for i in range(len(unsorted_list) - 1): if unsorted_list[i] > unsorted_list[i + 1]: unsorted_list[i], unsorted_list[i + 1] = unsorted_list[i + 1], unsorted_list[i] swapped = True return unsorted_list
def groupName(resName): """ returns a group interaction label """ if resName == "ASP" or resName == "GLU" or resName == "C- ": name = "COO" elif resName == "ASN" or resName == "GLN": name = "AMD" elif resName == "SER" or resName == "THR": name = "ROH" else: name = resName return name
def intcode_two(parameter_list, code_list): """Multiplies elements in the parameter_list's first two elements. Places product in parameter_list[2]. Returns True. """ code_list[parameter_list[2]] = parameter_list[0] * parameter_list[1] return True
def tree_children(tree): """Returns the children subtrees of tree""" if isinstance(tree, list): return tree[1:] else: return []
def numberString2Integers(list): """Gets a list of strings and returns a list of the correspondant integers. Returns the translated list. """ integerList = [] for element in list: integerList.append(int(element)) return integerList
def merge_two_config(a, b): """ :param a: first dict :param b: second dict :return: merged dict """ c = a.copy() c.update(b) return c