content
stringlengths
42
6.51k
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
def flow_configs(port_configs): """This fixture demonstrates adding flows to port configurations.""" for config in port_configs: f = config.flows.flow()[-1] f.tx_rx.device.tx_names = [config.devices[0].name] f.tx_rx.device.rx_names = [config.devices[1].name] f.name = "%s --> %s" % (config.ports[0].name, config.ports[1].name) f.size.fixed = 128 f.duration.fixed_packets.packets = 10000000 return port_configs
def char(cA, cB): """Returns the appropriate single qubit pauli character when merging.""" if cA == "I": return cB return cA
def colorbar_abs(float, color_list): """ returns RGB triplet when given float between 0 and 1 input: - float float between 0 and 1 - color_list list of RGB triplets (lists of 3 floats) output: - RGB list of 3 floats """ index = int(round(float * (len(color_list) - 1))) RGB = color_list[index] return RGB
def get_recursively(search_dict, field, no_field_recursive=False): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. """ fields_found = [] for key, value in search_dict.items(): if key == field: if no_field_recursive \ and (isinstance(value, dict) or isinstance(key, list)): continue fields_found.append(value) elif isinstance(value, dict): results = get_recursively(value, field, no_field_recursive) for result in results: fields_found.append(result) elif isinstance(value, list): for item in value: if isinstance(item, dict): more_results = get_recursively(item, field, no_field_recursive) for another_result in more_results: fields_found.append(another_result) return fields_found
def str_2_sec(timein): """ Convert time in days / hrs / mins etc to total seconds used) """ splitdays = timein.split('-') if len(splitdays) == 2: # Have list of days and time secs = 24*60*60*int(splitdays[0]) + str_2_sec(splitdays[1]) elif len(splitdays) == 1: # Just have a time splittime = timein.split(':') assert len(splittime) == 3, 'not enough bits' secs = int(splittime[2]) + 60*int(splittime[1]) + 60*60*int(splittime[0]) else: # Bust assert False, 'time conversion error' return secs
def getClass(obj): """ Return the class or type of object 'obj'. Returns sensible result for oldstyle and newstyle instances and types. """ if hasattr(obj, '__class__'): return obj.__class__ else: return type(obj)
def get_query_string(params) -> str: """ Gets the query string of a URL parameter dictionary.abs :param params: URL params. :return: Query string. """ if not params: return '' return '?' + '&'.join([str(k) + '=' + str(v) for k, v in params.items()])
def angle_wrap(s): """Return s surrounded by angle brackets, added only if necessary""" # This is the inverse behavior of email.utils.unquote # (which you might think email.utils.quote would do, but it doesn't) if len(s) > 0: if s[0] != '<': s = '<' + s if s[-1] != '>': s = s + '>' return s
def upper_bound(x): """Return the upper bound of interval x.""" "*** YOUR CODE HERE ***" return x[-1]
def average(num): """Gets the average of the numbers in a list""" total = 0 for n in num: total += n return (total / (len(num)))
def clamp(val, low, high): """Return val, within [low,high]""" if val < low: return low elif val > high: return high return val
def plural(num): """ Gets the English plural ending for an ordinal number. """ return "" if num == 1 else "s"
def setbit(byte, offset, value): """ Set a bit in a byte to 1 if value is truthy, 0 if not. """ if value: return byte | (1 << offset) else: return byte & ~(1 << offset)
def tickets(number, day, premium_seating): """ The cost of the cinema ticket. Normal ticket cost is $10.99 Wednesdays reduce the cost by $2.00 Premium seating adds an extra $1.50 regardless of the day Parameters: ---------- number: int integer value representing the number of seats to book day: int day of the week to book (1 = Monday ... 7 = Sunday) premium_seating: bool boolean True/False. Are premium seats required. Returns: ------- float """ #fill in your code here. return 0.0
def get_eff_k(k1, k2): """ Returns effective bulk modulus Parameters ---------- k1: float First bulk modulus k2 : float Second bulk modulus Returns ------- float Effective bulk modulus """ return 2. * k1 * k2 / (k1 + k2)
def duplicate(somelist): """ biore binary search na srodku listy sprawdzam :param somelist: :return: """ emptylist = [] for i in somelist: if len(emptylist) == 0: emptylist.append(i) else: if i in emptylist: return i emptylist.append(i)
def translate(tile, offset): """ Move a tile. This returns a moved copy; the original is unchaged. Parameters ---------- tile : tuple containing y and x slice objects offset : tuple translation, given as ``(y, x)`` Returns ------- tile : tuple a copy; the input is unchaged """ dy, dx = offset y, x = tile new_tile = (slice(y.start + dy, y.stop + dy), slice(x.start + dx, x.stop + dx)) return new_tile
def pretty_duration(seconds): """Return a pretty duration string Parameters ---------- seconds : float Duration in seconds Examples -------- >>> pretty_duration(2.1e-6) '0.00ms' >>> pretty_duration(2.1e-5) '0.02ms' >>> pretty_duration(2.1e-4) '0.21ms' >>> pretty_duration(2.1e-3) '2.1ms' >>> pretty_duration(2.1e-2) '21ms' >>> pretty_duration(2.1e-1) '0.21s' >>> pretty_duration(2.1) '2.10s' >>> pretty_duration(12.1) '12.1s' >>> pretty_duration(22.1) '22s' >>> pretty_duration(62.1) '1:02' >>> pretty_duration(621.1) '10:21' >>> pretty_duration(6217.1) '1:43:37' """ miliseconds = seconds * 1000 if miliseconds < 1: return "{:.2f}ms".format(miliseconds) elif miliseconds < 10: return "{:.1f}ms".format(miliseconds) elif miliseconds < 100: return "{:.0f}ms".format(miliseconds) elif seconds < 10: return "{:.2f}s".format(seconds) elif seconds < 20: return "{:.1f}s".format(seconds) elif seconds < 60: return "{:.0f}s".format(seconds) else: minutes = seconds // 60 seconds = int(seconds - minutes * 60) if minutes < 60: return "{minutes:.0f}:{seconds:02}".format(**locals()) else: hours = minutes // 60 minutes = int(minutes - hours * 60) return "{hours:.0f}:{minutes:02}:{seconds:02}".format(**locals())
def Lipinski(calc, exp, low, high): """ Input: listLike calculated and experimental data you want to compare float low and high limits for the test returns: number of correctly predicted values (in or outside range) number of false positives number of false negatives """ correct = 0 falsePos = 0 falseNeg = 0 for c,e in zip(calc, exp): # If the calculated value is in range if low <= c <= high: # If the experimental is in range then add to correct if low <= e <= high: correct += 1 else: # Otherwise it is a false positive falsePos += 1 else: # c not in range # If experimental is in range then its a false negative if low <= e <= high: falseNeg += 1 else: # Otherwise they're both out so it's correct correct += 1 # Return number correctly predicted, number of false positives, number of false negatives return correct, falsePos, falseNeg
def build_group_name(four_p): """ :param four_p: (low click rate, high click rate, hazard rate, interrogation time) :return: string """ # lowrate = ('{:f}'.format(round(four_p[0], 2))).rstrip('0').rstrip('.') highrate = ('{:f}'.format(round(four_p[1], 2))).rstrip('0').rstrip('.') hazard_rate = ('{:f}'.format(four_p[2])).rstrip('0').rstrip('.') interr_time = ('{:f}'.format(four_p[3])).rstrip('0').rstrip('.') return 'lr{}hr{}h{}T{}'.format(lowrate, highrate, hazard_rate, interr_time)
def checkForOverlappingGrants(grant, frequency_range): """Returns True if a grant overlaps with a given frequency range. If the lowFrequency or the highFrequency of the grant falls within the low and high frequencies of the given range then the grant is considered to be overlapping. Args: grant: A |GrantData| object dictionary defined in SAS-SAS spec frequency_range: The frequency range in Hz as a dictionary with keys 'lowFrequency' and 'highFrequency'. """ low_frequency_cbsd = grant['operationParam']['operationFrequencyRange']['lowFrequency'] high_frequency_cbsd = grant['operationParam']['operationFrequencyRange']['highFrequency'] low_frequency = frequency_range['lowFrequency'] high_frequency = frequency_range['highFrequency'] assert low_frequency_cbsd < high_frequency_cbsd assert low_frequency < high_frequency return ((low_frequency_cbsd < high_frequency) and (low_frequency < high_frequency_cbsd))
def error_exists(checkResult): """check if in conditions array exists at least one non-False value (an error) """ for value in checkResult: if value: return True return False
def get_db_path(spider_dir, db_id): """ Return path to SQLite database file. Args: spider_dir: path to SPIDER benchmark db_id: database identifier Returns: path to SQLite database file """ return f'{spider_dir}/database/{db_id}/{db_id}.sqlite'
def interpolation_search(sample_input, lowest, highest, item): """ function to search the item in a give list of item :param sample_input: list of number :param lowest: the lowest element on our list :param highest: the highest element on our list :param item: the item element to search in our list :return: true if found else fals """ distance = item - sample_input[lowest] value_range = sample_input[highest] - sample_input[lowest] ratio = distance / value_range found = False estimation = int(lowest + ratio * (highest - lowest)) if sample_input[estimation] == item: found = True elif item < sample_input[estimation]: highest = estimation else: lowest = estimation while lowest <= highest and not found: mid = (lowest + highest) // 2 if sample_input[mid] == item: found = True elif sample_input[mid] < item: lowest = mid + 1 else: highest = mid - 1 return found
def zigbee2mqtt_device_name(topic, data, srv=None): """Return the last part of the MQTT topic name.""" return dict(name=topic.split("/")[-1])
def compare_all_to_exported(filelist_a, filelist_b, barrel_name): """ Check the difference between the list of files """ files_a = set(filelist_a) files_b = set(filelist_b) result = sorted(files_a.union(files_b).difference(files_a.intersection(files_b))) result = ["export * from './{}'".format(elem.rstrip('.ts')) for elem in result if elem != barrel_name and '.ts' in elem] return result
def remove_invalid_characters(input_string): """ Edit a string by replacing underscores with spaces and removing commas, single quotes and new line characters :param input_string: the string which needs to be altered :return: edited string """ return input_string.replace(" ", "_").replace(",", "").replace("'", "")\ .replace("\n", "").replace("/", "_").replace(":", "")
def is_create_required(event): """ Indicates whether a create is required in order to update. :param event: to check """ if event['RequestType'] == 'Create': return True new = event['ResourceProperties'] old = event['OldResourceProperties'] if 'OldResourceProperties' in event else new return old.get('Priority', 0) != new.get('Priority', 0) or old.get('ListenerArn', None) != new.get('ListenerArn', None)
def binary_search(array, element): """ Binary Search Complexity: O(logN) Requires a sorted array. Small modifications needed to work with descending order as well. """ lower = 0 upper = len(array) - 1 while lower <= upper: mid = (lower+upper) // 2 if array[mid] < element: lower = mid + 1 elif array[mid] > element: upper = mid - 1 else: return mid return -1
def log(x): """ Simulation to math.log with base e No doctests needed """ n = 1e10 return n * ((x ** (1/n)) - 1)
def is_port_free(port, host="localhost"): """Checks if port is open on host""" #based on http://stackoverflow.com/a/35370008/952600 import socket from contextlib import closing with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: if sock.connect_ex((host, port)) == 0: return False else: return True
def axlbool(value): """ convert suds.sax.text.Text to python bool """ if value is None: return None if not value: return False if value.lower() == 'true': return True return False
def combination_sum_bottom_up(nums, target): """Find number of possible combinations in nums that add up to target, in bottom-up manner. Keyword arguments: nums -- positive integer array without duplicates target -- integer describing what a valid combination should add to """ combs = [0] * (target + 1) combs[0] = 1 for i in range(0, len(combs)): for num in nums: if i - num >= 0: combs[i] += combs[i - num] return combs[target]
def aslist(item): """ aslist wraps a single value in a list, or just returns the list """ return item if type(item) == list else [item]
def parseDigits(digits: str, base: int) -> int: """ Wrapper around the "int" constructor that generates a slightly more detailed ValueError message if the given string contains characters that are not valid as digits in the given base. """ try: return int(digits, base) except ValueError: baseDesc = {2: "binary", 10: "decimal", 16: "hexadecimal"} raise ValueError(f"bad {baseDesc[base]} number: {digits}") from None
def pi(p, q): """ Calculates premium policy for insurance company Args: q (float): Coverage amount p (float): Probability of loss Returns: (float): Premium policy of bundle """ return (p*q)
def lists2dict(listA, listB): """ Given two lists of the same length, merge them in one dictionary """ return dict(zip(listA, listB))
def convert_lcs_positions(index): """ Given the index of a pick in LCS order, returns the position id corresponding to that index. LCS picks are submitted in the following order Index | Role | Position 0 Top 3 1 Jng 4 2 Mid 2 3 Adc 1 4 Sup 5 """ lcsOrderToPos = {i:j for i,j in enumerate([3,4,2,1,5])} return lcsOrderToPos[index]
def write_bc(bcdict, bc="bc.dyn"): """write node BCs Args: bcdict: dict of node BCs, with DOF values bc: (Default value = "bc.dyn") Returns: 0 """ with open(bc, 'w') as bcf: bcf.write("$ Generated using bc.py\n") bcf.write('*BOUNDARY_SPC_NODE\n') for i in bcdict: bcf.write(f'{i},0,') bcf.write(f'{bcdict[i]}\n') bcf.write('*END\n') return 0
def valid_odd_size(size): """ Validates that a kernel shape is of odd ints and of with 2 dimensions :param size: the shape (size) to be checked :return: False if size is invalid """ if type(size) not in (list, tuple): return False if len(size) != 2: return False if size[0] % 2 != 1 or size[1] % 2 != 1: return False return True
def get_regex(value): """Returns regex string based on main parameter""" return r'({}:\s*)(.+\S)'.format(value)
def has_possible_route(total_route, sub_routes): """ Check how it is possible to construct the total route from the sub_routes (part a, b and c) Sub_routes has 3 items (0, 1, 2) """ # start at idx state = list() state.append((total_route, [])) while len(state) > 0: current_route, actions = state.pop() # Found a solution when we covered the whole route if len(current_route) == 0: # Also the main routine (the actions) also has a restriction of 20 chars if (len(actions) * 2 - 1) <= 20: return True, actions else: continue # check if a sub_route matches for idx, sub_route in enumerate(sub_routes): size = len(sub_route) if size > 0 and current_route[:size] == sub_route: state.append((current_route[size:], actions + [idx])) # no solution return False, None
def within_percent(a, b, percent): """Returns true if a is within some percent of b""" return percent >= 100*abs(a-b)/b
def validate_input(input_val): """ Helper function to check if the input is indeed a float :param input_val: the value to check :return: the floating point number if the input is of the right type, None if it cannot be converted """ try: float_input = float(input_val) return float_input except ValueError: return None
def extract_time_spent_in_region(person_dict_list): """ Get the time spent in each region Parameters ---------- person_dict_list: list regions people have passed during vaccination lifecycle Returns ------- dict time spent in each region """ # seperate the time values for each region region1_times = [] region2_times = [] region3_times = [] region4_times = [] region5_times = [] region6_times = [] region7_times = [] region8_times = [] region9_times = [] for person in person_dict_list: for key in person: if key == 1: region1_times.append(person[key]) elif key == 2: region2_times.append(person[key]) elif key == 3: region3_times.append(person[key]) elif key == 4: region4_times.append(person[key]) elif key == 5: region5_times.append(person[key]) elif key == 6: region6_times.append(person[key]) elif key == 7: region7_times.append(person[key]) elif key == 8: region8_times.append(person[key]) elif key == 9: region9_times.append(person[key]) elif key =="time": continue else: raise RuntimeError( "There is region key different from [1, 3, 5, 6, 8] and waiting rooms. Unknown region %d", key, ) return { "region1": region1_times, "region2": region2_times, "region3": region3_times, "region4": region4_times, "region5": region5_times, "region6": region6_times, "region7": region7_times, "region8": region8_times, "region9": region9_times, }
def paint_text(text_str, color_str): """ Adds markup around given text. Supports some colors by name instead of hexadecimal. :param text_str: :param color_str: (str) Hexadecimal color. :return: (str) """ return '[color={color_str}]{text_str}[/color]'.format(text_str=text_str, color_str=color_str)
def is_bbox(line): """is there a bbox as attribute of a changeset i.e. min_lat, max_lon, min_lon, max_lin """ if 'min_lat' in line: return True return False
def init_hash_counters(): """ Use counters to create a simple output stats file in tandem with json details Initialize counters to zero """ hash_counters = {} hash_count_values = ['total samples', 'malware', 'mal_inactive_sig', 'mal_active_sig', 'mal_no_sig', 'grayware', 'benign', 'phishing', 'No sample found'] for value in hash_count_values: hash_counters[value] = 0 return hash_counters
def hms2stringTime(h, m, s, precision=5): """ Convert a sexagesimal time to a formatted string. Parameters ---------- hour, min, sec : int, float precision : int Returns ------- String formatted HH:MM:SS.SSSSS """ if h < 0 or m < 0 or s < 0: pm = '-' else: pm = '+' formString = '%s%02d:%02d:%0' + str(precision + 3) + '.' + str(precision) + 'f' return formString % (pm, abs(h), abs(m), abs(s))
def is_box_inside(in_box, out_box): """ check if in_box is inside out_box (both are 4 dim box coordinates in [x1, y1, x2, y2] format) """ xmin_o, ymin_o, xmax_o, ymax_o = out_box xmin_i, ymin_i, xmax_i, ymax_i = in_box if (xmin_o > xmin_i) or (xmax_o < xmax_i) or (ymin_o > ymin_i) or (ymax_o < ymax_i): return False return True
def edit_distance(list1, list2): """ Find the minimum number of insertions, deletions, or replacements required to turn list1 into list2, using the typical dynamic programming algorithm. >>> edit_distance('test', 'test') 0 >>> edit_distance([], []) 0 >>> edit_distance('test', 'toast') 2 >>> edit_distance(['T', 'EH1', 'S', 'T'], ['T', 'OH1', 'S', 'T']) 1 >>> edit_distance('xxxx', 'yyyyyyyy') 8 """ m = len(list1) n = len(list2) data = [[0 for col in range(n+1)] for row in range(m+1)] for col in range(n+1): data[0][col] = col for row in range(m+1): data[row][0] = row for a in range(1, m+1): for b in range(1, n+1): if list1[a-1] == list2[b-1]: data[a][b] = data[a-1][b-1] else: data[a][b] = 1 + min(data[a-1][b], data[a][b-1], data[a-1][b-1]) return data[m][n]
def _is_png(filename): """Determine if a file contains a PNG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a PNG. """ return '.png' in filename
def create_flow_control(n): """returns a list for flow control. The list can be mutated outside the function and will remain in memory""" return [False] * n
def add_to_stack(a,b): """ makes a list of lists of lists. Indices are [image i][antinode j][params within antinode j] """ if (a is None): return [b] return a + [b]
def arithmetic_wrangle(x): """Do some non trivial arithmetic.""" result = -x**2/x**0.2 return result
def checkEqual(lst: list)->bool: """ Small function to quickly check if all elements in a list have the same value. Parameter: - lst : input list Returns: Boolean: True if all are equal, False else. Source: http://stackoverflow.com/q/3844948/ part of the thread: https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical (Seems to be roughly the fastest...) """ return not lst or lst.count(lst[0]) == len(lst)
def add(x,y): """ Binary Adddition bing carried out """ carry="" result="" carry="0" for i in range(len(x)-1,-1,-1): a=carry[0] b=x[i] c=y[i] if a==b and b==c and c=='0': result="0"+result carry="0" elif a==b and b==c and c=='1': result="1"+result carry="1" else: if a=='1' and b==c and c=='0': result="1"+result carry="0" elif a=='0' and b=='1' and c=='0': result="1"+result carry="0" elif a=='0' and b=='0' and c=='1': result="1"+result carry="0" elif a=='0' and b=='1' and c=='1': result="0"+result carry="1" elif a=='1' and b=='0' and c=='1': result="0"+result carry="1" elif a=='1' and b=='1' and c=='0': result="0"+result carry='1' return result
def hello(name): """ python3 fn.py Yazid > Hello Yazid! """ return 'Hello {name}!'.format(name=name)
def to_float(MIC): """ Ensures input can be compared to float, in case input is string with inequalities """ MIC=str(MIC) for equality_smb in ['=','<','>']: MIC = MIC.replace(equality_smb,'') return float(MIC)
def is_kind_of_class(obj, a_class): """ checks class inheritance Args: obj: object to evaluate a_class: suspect father """ return isinstance(obj, a_class)
def _calculate_score_for_underpaid(current_salary, level_salary): """ Maximize how much each dollar reduces percent diff from level salary. Higher scores get raise dollars first :param current_salary: :param level_salary: :return: """ assert current_salary <= level_salary absolute_diff = current_salary - level_salary percent_diff = current_salary / level_salary if absolute_diff != 0: marginal_percentage = percent_diff / absolute_diff else: marginal_percentage = -1.0 return marginal_percentage
def matrixMultVec(matrix, vector): """ Multiplies a matrix with a vector and returns the result as a new vector. :param matrix: Matrix :param vector: vector :return: vector """ new_vector = [] x = 0 for row in matrix: for index, number in enumerate(row): x += number * vector[index] new_vector.append(x) x = 0 return new_vector
def remove_result_attr(result): """Remove all attributes from the output""" filtered_list = [] for tup in result: lis = list(tup) removeset = set([2]) filtered_list.append(tuple([v for i, v in enumerate(lis) if i not in removeset])) return filtered_list
def mask(bits: int) -> int: """ Generate mask of specified size (sequence of '1') """ return (1 << bits) - 1
def _target_selectors(targets): """ Return the target selectors from the given target list. Transforms the target lists that the client sends in annotation create and update requests into our internal target_selectors format. """ # Any targets other than the first in the list are discarded. # Any fields of the target other than 'selector' are discarded. if targets and 'selector' in targets[0]: return targets[0]['selector'] else: return []
def get_all_species_alive_area(species_list, area): """Get all names of species that are alive from a certain area. Parameters ---------- species_list : list of strings List of all species. area : str name of area for which the species should be returned. Returns ------- numb_total_population_alive : list of strings List of all species excluding dead species from the specified area. """ total_population_alive = [ x for x in species_list.keys() if ("dead" not in x) and (area in x) ] numb_total_population_alive = "+".join(total_population_alive) return numb_total_population_alive
def setSizeToInt(size): """" Converts the sizes string notation to the corresponding integer (in bytes). Input size can be given with the following magnitudes: B, K, M and G. """ if isinstance(size, int): return size elif isinstance(size, float): return int(size) try: conversions = {'B': 1, 'K': 1e3, 'M': 1e6, 'G': 1e9} digits_list = list(range(48, 58)) + [ord(".")] magnitude = chr( sum([ord(x) if (ord(x) not in digits_list) else 0 for x in size])) digit = float(size[0:(size.index(magnitude))]) magnitude = conversions[magnitude] return int(magnitude*digit) except: print("Conversion Fail") return 0
def time_format_store_ymdhms(dt, addMilliseconds=True): """ Return time format as y_m_d__h_m_s[_ms]. :param dt: The timestamp or date to convert to string :type dt: datetime object or timestamp :param addMilliseconds: If milliseconds should be added :type addMilliseconds: bool :return: Timeformat as \"y_m_d__h_m_s[_ms]\" :rtype: str """ if dt is None: return "UUPs its (None)" import datetime if (isinstance(dt, datetime.datetime) is False and isinstance(dt, datetime.timedelta) is False): dt = datetime.datetime.fromtimestamp(dt) if addMilliseconds: return "%s:%s" % ( dt.strftime('%Y_%m_%d__%H_%M_%S'), str("%03i" % (int(dt.microsecond/1000))) ) else: return "%s" % ( dt.strftime('%Y_%m_%d__%H_%M_%S') )
def to_s3_model(*args): """ Returns the S3 URL for to a model, rooted under ${REACH_S3_PREFIX}/models/""" return ( '{{ conf.get("core", "reach_s3_prefix") }}' '/models/%s' ) % '/'.join(args)
def get_last_id(provider): """Load last known id from file.""" filename = ('last_known_id_{}.txt').format(provider) try: with open(filename, 'r') as (id_file): id = id_file.read() id_file.close() if len(id) == 0: id = 0 return int(id) except: initial_value = '0' with open(filename, 'w+') as (id_file): id_file.write(initial_value) id_file.close() return int(initial_value)
def is_clustal_seq_line(line): """Returns True if line starts with a non-blank character but not 'CLUSTAL'. Useful for filtering other lines out of the file. """ return line and (not line[0].isspace()) and\ (not line.startswith('CLUSTAL')) and (not line.startswith('MUSCLE'))
def encode_byte(value): """Encode a byte type.""" return bytearray([value])
def convert_list_type(x, to_type=int): """Convert elements in list to given type.""" return list(map(to_type, x))
def get_type(name, attr_dict): """ """ try: v_type = attr_dict[name]["type"] if v_type in ["string", str, "str", "String"]: v_type = None except KeyError: v_type = None return v_type
def hello_my_user(user): """ this serves as a demo purpPOSTose :param user: :return: str """ return "Hello %s!" % user
def triangular_number(n: int): """ >>> triangular_number(4) # 4 + 3 + 2 + 1 10 """ assert n >= 0 return n * (n + 1) // 2
def try_parse_int(value): """Attempts to parse a string into an integer, returns 0 if unable to parse. No errors.""" try: return int(value) except: # Not a bug or error, just for added clarity print("Not a valid entry. Try again.") return 0
def bounded(num, start, end): """Determine if a number is within the bounds of `start` and `end`. :param num (int): An integer. :param start (int): A start minimum. :param end (int): An end maximum. :rtype is_bounded (bool): Whether number is bounded by start and end. """ return num >= start and num <= end
def delete_contact(contact_id): """ Deletes the contact for the id sent Returns an "OK" message with code 200. If the contact does not exists returns "Unexistent Contact" with code 404 :param contact_id: the contact id """ return "Not implemented", 500
def aggregate_f(loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore): """ Compute aggregate metric for xView3 scoring Args: loc_fscore (float): F1 score for overall maritime object detection length_acc (float): Aggregate percent error for vessel length estimation vessel_fscore (float): F1 score for vessel vs. non-vessel task fishing_fscore (float): F1 score for fishing vessel vs. non-fishing vessel task loc_fscore_shore (float): F1 score for close-to-shore maritime object detection Returns: aggregate (float): aggregate metric for xView3 scoring """ # Note: should be between zero and one, and score should be heavily weighted on # overall maritime object detection! aggregate = loc_fscore * (1 + length_acc + vessel_fscore + fishing_fscore + loc_fscore_shore) / 5 return aggregate
def _permission_extract(sciobj_dict): """Return a dict of subject to list of permissions on object.""" return { perm_subj: ["read", "write", "changePermission"][: perm_level + 1] for perm_subj, perm_level in zip( sciobj_dict["permission_subject"], sciobj_dict["permission_level"] ) }
def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind
def tokenize(lines, token='word'): """Split text lines into word or character tokens.""" if token == 'word': return [line.split() for line in lines] elif token == 'char': return [list(line) for line in lines] else: print('ERROR: unknown token type: ' + token)
def get_range(time): """An function used to get the correct 4 hour interval for the TIME_BIN column Takes a dataframe and creates a column with the times binned by every 4 hours Args: time (int): A time int representation in the format hhmmss Ex: noon would be represented as 120000 Returns: output (float): The 4 hour time interval that the integer input time belongs to """ hours = [0, 40000, 80000, 120000, 160000, 200000] prev = 0 output = 0.0 for h in hours: if time <= h and time > prev: output = float(h/10000) return output elif time == 200000: output = float(200000/10000) return output elif time > float(200000): output = float(24) return output # midnight elif time == 0: output = float(24) return output
def normalize_color_tuple(h :int, s:int, x:int) -> tuple: """ Normalize an HSV or HSL tuple. Args: h: `int` in {0, ..., 360} corresponding to hue. s: `int` in {0, ..., 100} corresponding to saturation. x: `int` in {0, ..., 100} corresponding to light or value. Returns:l The corresponding normalized tuple. """ return (h / 360, s / 100, x / 100)
def action_color(status): """ Get a action color based on the workflow status. """ if status == 'success': return 'good' elif status == 'failure': return 'danger' else: return 'warning'
def is_independent_nfs(role): """NFS not on infra""" return "nfs" in role and not (set(["infra", "etcd", "kubernetes_master"]) & set(role))
def str_to_bool(s): """ Basic converter for Python boolean values written as a str. @param s: The value to convert. @return: The boolean value of the given string. @raises: ValueError if the string value cannot be converted. """ if s == 'True': return True elif s == 'False': return False else: raise ValueError("Cannot covert {} to a bool".format(s))
def isvector(a): """ one-dimensional arrays having shape [N], row and column matrices having shape [1 N] and [N 1] correspondingly, and their generalizations having shape [1 1 ... N ... 1 1 1] """ try: return a.ndim-a.shape.count(1) == 1 except: return False
def std_url(url): """ Standardizes urls by removing protocoll and final slash. """ if url: url = url.split("//")[-1] if url.endswith("/"): url = url[:len(url)-1] return url
def extensionOf(path): """Answer the extension of path. Answer None of there is no extension. >>> extensionOf('../../images/myImage.jpg') 'jpg' >>> extensionOf('aFile.PDF') # Answer a lowercase 'pdf' >>> extensionOf('aFile') is None # No extension True >>> extensionOf('../../aFile') is None # No extension on file name True """ parts = path.split('/')[-1].split('.') if len(parts) > 1: return parts[-1].lower() return None
def json_set_auths(struct, auth): """Recusrsively finds auth in script JSON and sets them. Args: struct: (dict) A dictionary representation fo the JSON script. auth: (string) Either 'service' or 'user'. Returns: (struct) same structure but with all auth fields replaced. """ if isinstance(struct, dict): if 'auth' in struct: struct['auth'] = auth for key, value in struct.items(): json_set_auths(value, auth) elif isinstance(struct, list) or isinstance(struct, tuple): for index, value in enumerate(struct): json_set_auths(value, auth) return struct
def is_valid_email(email_address): """ Given a possible email address, determine if it is valid. :param email_address: a string with a proposed email address :return: true if email_address is valid, false if not """ valid = False if '@' in email_address and '.' in email_address: # check for the basic elements # allowable domains email_end = ('com', 'org', 'edu', 'net', 'mail', 'me') end_part = email_address[-3:] if end_part in email_end: # look at characters in local_part if proper ending local_part = email_address[:email_address.index('@')] valid = True l_p_chars = 'abcdefghijklmnopqrstuvwxyz' # allowable characters for the domain dom_chars = l_p_chars + l_p_chars.upper() # allowable characters for the local part l_p_chars += l_p_chars.upper() + '_-.123456789' for ch in local_part: if ch not in l_p_chars: valid = False break if valid: # look at characters in domain domain_part = email_address[email_address.index('@') + 1:len(email_address) - 4] for ch in domain_part: if ch not in dom_chars: valid = False break return valid
def mac_addr(address): """Convert a MAC address to a readable/printable string Args: address (str): a MAC address in hex form (e.g. '\x01\x02\x03\x04\x05\x06') Returns: str: Printable/readable MAC address """ return ':'.join('%02x' % ord(b) for b in address)
def first_org_id_from_org_roles(org_roles): """ Return first Jisc ID found in an objectOrganisationRole.""" for role in org_roles: if not isinstance(role, dict): continue org = role.get('organisation') if not isinstance(org, dict): continue org_id = org.get('organisationJiscId') if not org_id: continue return str(org_id).strip()
def update_effective_sample_size( effective_sample_size, batch_size, forgetting_factor ): """ :param effective_sample_size: :param batch_size: :param forgetting_factor: :return: >>> update_effective_sample_size(1.0,1.0,1.0) (2.0, 1.0) """ updated_sample_size = ( effective_sample_size * forgetting_factor + batch_size ) weight = 1 - ( (effective_sample_size*1.0 - batch_size) / (effective_sample_size*1.0) ) return updated_sample_size, weight
def fib2(n): # return Fibonacci series up to n """Return a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) # see below a, b = b, a+b return result
def read_uint(data, start, length): """Extract a uint from a position in a sequence.""" return int.from_bytes(data[start:start+length], byteorder='big')
def _get_md_from_url(url): """Get markdown name and network name from url.""" values = url.split('/') return values[-1].split('.')[0] + '.md'