content
stringlengths
42
6.51k
def get_kth_minimum(x, k=1): """ gets the k^th minimum element of the list x (note: k=1 is the minimum, k=2 is 2nd minimum) ... based on the incomplete selection sort pseudocode """ n = len(x) for i in range(n): minIndex = i minValue = x[i] for j in range(i+1, n): if x[j] < minValue: minIndex = j minValue = x[j] x[i], x[minIndex] = x[minIndex], x[i] return x[k-1]
def parse_list(list, keyword): """ Parses the port/or alarmlist(list). (keyword) triggers on. Returns a list of active in list """ cnt = 1 ports = [] for port in list: if port == keyword: ports.append(cnt) cnt += 1 return ports
def k_const(k): """Returns the constant reaction rate coefficients INPUTS ====== k: float, constant reaction rate coefficient RETURNS ======= constant reaction rate coefficients, which is k EXAMPLES ======== >>> k_const(1.5) 1.5 """ k1 = k return k1
def _parse_mapping_config(config: str): """Parse config such as: numpy -> asnumpy, reshape, ... Return a list of string pairs """ mapping = [] for line in config.splitlines(): for term in line.split(','): term = term.strip() if not term: continue if len(term.split('->')) == 2: a, b = term.split('->') mapping.append((a.strip(), b.strip())) else: mapping.append((term, term)) return mapping
def find_levels(variable_names): """This method... .. note: Might need the dataframe to check ints! Returns ------- list Variables with the word levels in it. """ return [c for c in variable_names if 'level' in c]
def escape(content): """ Escapes a string's HTML. """ return content.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')\ .replace('"', '&quot;').replace("'", '&#039;')
def isProperStage(stage): """Checks if the stage is a proper stage Arguments: stage(list) a 3x3 list containg a tic-tac-toe stage Returns: retVal(bool) True if the stage is a 3x3 list """ retVal = True if type(stage) == list and len(stage) == 3: for row in stage: if not (type(row) == list and len(row) == 3): retVal = False break #No need to continue if even 1 row is bad elif not (type(stage) == list and len(stage) == 9): retVal = False return retVal
def relax_menu_text(text): """Remove any &, lower case, stop at first \\t""" tmp = text.replace('&', '').lower() tabind = tmp.find('\t') if tabind > 0: tmp = tmp[:tabind] return tmp.strip()
def _jacobi_symbol(a: int, n: int) -> int: """ Calculate the Jacobi symbol (a/n) """ if n == 1: # pragma: no cover return 1 if a == 0: return 0 if a == 1: return 1 if a == 2: if n % 8 in [3, 5]: return -1 if n % 8 in [1, 7]: return 1 elif a < 0: return int((-1)**((n-1)//2) * _jacobi_symbol(-1*a, n)) if a % 2 == 0: return _jacobi_symbol(2, n) * _jacobi_symbol(a // 2, n) if a % n != a: return _jacobi_symbol(a % n, n) if a % 4 == n % 4 == 3: return -1 * _jacobi_symbol(n, a) # pylint: disable=arguments-out-of-order return _jacobi_symbol(n, a)
def build_header(item, suffix='rating'): """ Build the row of header for a CSV file :param item: A test item, normally the first test item in responses of a test :param suffix: This will be using in a test with rating bar :return: CSV format string including double quota """ if item['type'] == 1: # Question if 'questionControl' in item and 'question' in item['questionControl']: return item['questionControl']['question'] or '' else: return '' elif item['type'] == 2 or item['type'] == 3: # Example with suffix or training if 'example' in item: return item['title'] + ' ' + (suffix if item['type'] == 2 else '') else: return '' else: # 0: Section header, 3 Training return None
def split_html_by_tds(html): """get a peace of html containing tds and returns the content of each td as a elemenent in a list""" splited_html = html.split('</td>') result = [] for html_chunck in splited_html: striped_html_chunk = html_chunck.strip() if striped_html_chunk: arrow_right_index = striped_html_chunk.find('>') result.append(striped_html_chunk[arrow_right_index + 1:]) return result
def decode_synchsafe_int( i ): """Decode SynchSafe integers from ID3v2 tags""" i = int.from_bytes( i, 'big' ) if i & 0x80808080: raise Exception( 'Bad sync in SynchSafe integer!' ) return ( ( i & 0xFF000000 ) >> 3 ) | ( ( i & 0x00FF0000 ) >> 2 ) | ( ( i & 0x0000FF00 ) >> 1 ) | ( i & 0x000000FF )
def uptime_collect(self): """Static collected uptime data for testing.""" return { 'response_time': 120.10, 'uptime_ratio': 99.96 }
def trapezoid_height(base_short,base_long,area): """Usage: Find height of a trapezoid""" return 2*(area/(base_short+base_long))
def standardize_number(phone_number): """ >>> standardize_number('07895462130') '+91 78954 62130' >>> standardize_number('919875641230') '+91 98756 41230' >>> standardize_number('9195969878') '+91 91959 69878' """ return "+91 %s %s" % (phone_number[-10:-5], phone_number[-5:])
def split_list_into_chunks(list_to_split, max_entries_per_list): """ Takes a list and splits it up into smaller lists """ chunks = [] for i in range(0, len(list_to_split), max_entries_per_list): chunk = list_to_split[i:i + max_entries_per_list] chunks.append(chunk) return chunks
def pad(name): """Add a space if name is a non-empty string.""" if name != '': return ' ' + name else: return ''
def check_for_files(item_json): """Find all files and extentions of an item, add their size together. Arguments: item_json -- (json) the json of the item being parsed. Returns: item_data -- (dictionary) a dictionary including a list of all file jsons attached to the item, the total size of the item, and the number of files found within the item. """ file_list = [] size = 0 try: files = item_json["files"] for sb_file in files: file_list.append(sb_file) size += sb_file["size"] except KeyError: pass # No files try: extentions = item_json["facets"] for extention in extentions: try: files = extention["files"] for sb_file in files: file_list.append(sb_file) size += sb_file["size"] except KeyError: pass # No files except KeyError: pass # No extentions num_files = len(file_list) item_data = {"file_list": file_list, "size": size, "num_files": num_files} return item_data
def dict_chs_best(iterable, max_key=lambda x: len(x.eventarray)): """ Group an iterable of utype-ch_struct pairs into a dict, keeping only those channels with the highest sample length for their utype. """ result = {} for utype, ch_struct in iterable: if not utype in result: result[utype] = ch_struct continue result[utype] = max(result[utype], ch_struct, key=max_key) return result
def allocated_size(allocation_unit, requested_size): """ Round ``requested_size`` up to the nearest ``allocation_unit``. :param int allocation_unit: The interval in ``bytes`` to which ``requested_size`` will be rounded up. :param int requested_size: The size in ``bytes`` that is required. :return: The ``allocated_size`` in ``bytes``. """ allocation_unit = int(allocation_unit) requested_size = int(requested_size) previous_interval_size = ( (requested_size // allocation_unit) * allocation_unit ) if previous_interval_size < requested_size: return previous_interval_size + allocation_unit else: return requested_size
def merge_dicts(x, y): """ Merge dictionaries :param Mapping x: dict to merge :param Mapping y: dict to merge :return Mapping: merged dict """ z = x.copy() z.update(y) return z
def nearest_color(palette, in_color): """returns nearest RGB color in palette""" out_color = min(palette, key=lambda palette_entry: sum((pe - c) ** 2 for pe, c in zip(palette_entry, in_color))) return out_color
def rootFolder(exp=''): """ Get root folder path for Hansard modeling experiments Args: exp (str, optional): name of experiment. Defaults to ''. Returns: str: full path for a given experiment """ root_folder = '/home/azureuser/cloudfiles/code/data/processing/hansard/experiment' if (len(exp) > 0): if (exp.find('/') == 0): exp = exp[1:] import os.path root_folder = os.path.join(root_folder, exp) if not os.path.exists(root_folder): print(f'Directory {root_folder} does not exist.. ') print(f'.. create direcotry') os.makedirs(root_folder) return(root_folder)
def underline(text: str) -> str: """Formats text for discord message as underlined""" return f"__{text}__"
def to_python_type(py_type: str) -> type: """Transform an OpenAPI-like type to a Python one. https://swagger.io/docs/specification/data-models/data-types """ TYPES = { "string": str, "number": float, "integer": int, "boolean": bool, "array": list, "object": dict, } return TYPES[py_type]
def json_parsing(obj, key): """Recursively pull values of specified key from nested JSON.""" arr = [] def extract(obj, arr, key): """Return all matching values in an object.""" if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict)) or (isinstance(v, (list)) and v and isinstance(v[0], (list, dict))): extract(v, arr, key) elif k == key: arr.append(v) elif isinstance(obj, list): for item in obj: extract(item, arr, key) return arr results = extract(obj, arr, key) return results[0] if results else results
def convergents(v): """ Returns the partial convergents of the continued fraction v. Input: v -- list of integers [a0, a1, a2, ..., am] Output: list -- list [(p0,q0), (p1,q1), ...] of pairs (pm,qm) such that the mth convergent of v is pm/qm. Examples: >>> convergents([1, 2]) [(1, 1), (3, 2)] >>> convergents([3, 7, 15, 1, 292]) [(3, 1), (22, 7), (333, 106), (355, 113), (103993, 33102)] """ w = [(0,1), (1,0)] for n in range(len(v)): pn = v[n]*w[n+1][0] + w[n][0] qn = v[n]*w[n+1][1] + w[n][1] w.append((pn, qn)) del w[0]; del w[0] # remove first entries of w return w
def linterp(xind, yarr, frac): """ Linear interpolation """ return yarr[xind] * (1 - frac) + yarr[xind + 1] * frac
def eec(u, v): """ The Extended Eculidean Algorithm For u and v this algorithm finds (u1, u2, u3) such that uu1 + vu2 = u3 = gcd(u, v) We also use auxiliary vectors (v1, v2, v3) and (tmp1, tmp2, tmp3) """ (u1, u2, u3) = (1, 0, u) (v1, v2, v3) = (0, 1, v) while (v3 != 0): quotient = u3 // v3 tmp1 = u1 - quotient * v1 tmp2 = u2 - quotient * v2 tmp3 = u3 - quotient * v3 (u1, u2, u3) = (v1, v2, v3) (v1, v2, v3) = (tmp1, tmp2, tmp3) return u3, u1, u2
def as_bytes(string): """ Ensure that whatever type of string is incoming, it is returned as bytes, encoding to utf-8 otherwise """ if isinstance(string, bytes): return string return string.encode('utf-8', errors='ignore')
def is_fixed(state): """Helper to discover if fixed limits have been selected""" return state.get("colorbar", {}).get("fixed", False)
def check_zip(zip_code): """check if zip code has correct format. Args: zip_code as a string Returns: a boolean indicating if valid (True) or not (False) """ if len(zip_code) < 5: return False if not zip_code[:5].isdigit(): return False return True
def is_string_an_integer(string: str) -> bool: """ AUTHORS: -------- :author: Alix Leroy DESCRIPTION: ------------ Check whether a string is an integer or not PARAMETERS: ----------- :param string(str): The string to analyze RETURN: ------- :return (bool): Whether the string is an integer or not """ try: int(string) return True except ValueError: return False
def half_up_round(value, scale): """ Round values using the "half up" logic See more: https://docs.python.org/3/library/decimal.html#rounding-modes >>> half_up_round(7.5, 0) 8.0 >>> half_up_round(6.5, 0) 7.0 >>> half_up_round(-7.5, 0) -8.0 >>> half_up_round(-6.5, 0) -7.0 """ # Python2 and Python3's round behavior differs for rounding e.g. 0.5 # hence we handle the "half" case so that it is rounded up scaled_value = (value * (10 ** scale)) removed_part = scaled_value % 1 if removed_part == 0.5: sign = -1 if value < 0 else 1 value += 10 ** -(scale + 1) * sign return round(value, scale)
def bits2MB(bits): """ Convert bits to MB. :param bits: number of bits :type bits: int :return: MiB :rtype: float """ return bits / (8 * 1000 * 1000)
def ContiguousRanges(seq): """Given an integer sequence, return contiguous ranges. This is expected to be useful for the tr-98 WLANConfig PossibleChannels parameter. Args: seq: a sequence of integers, like [1,2,3,4,5] Returns: A string of the collapsed ranges. Given [1,2,3,4,5] as input, will return '1-5' """ in_range = False prev = seq[0] output = list(str(seq[0])) for item in seq[1:]: if item == prev + 1: if not in_range: in_range = True output.append('-') else: if in_range: output.append(str(prev)) output.append(',' + str(item)) in_range = False prev = item if in_range: output.append(str(prev)) return ''.join(output)
def get_attrs(obj): """ Utility function to return all non-function variables in an object :param obj: The object to retrieve vars from :return: The vars found, excluding all methods """ return [x for x in dir(obj) if not x.startswith('__') and not callable(getattr(obj, x))]
def insertion_sort(list): """ Takes in a list and sorts the list using an insertion sort method. Modifies the list in place, but returns it for convenience. """ round_number = 1 curr = round_number while round_number < len(list): while curr > 0: if list[curr] < list[curr - 1]: list[curr], list[curr - 1] = list[curr - 1], list[curr] curr -= 1 else: break round_number += 1 curr = round_number return list
def cap(value: float, minimum: float, maximum: float) -> float: """Caps the value at given minumum and maximum. Arguments: value {float} -- The value being capped. minimum {float} -- Smallest value. maximum {float} -- Largest value. Returns: float -- The capped value or the original value if within range. """ if value > maximum: return maximum elif value < minimum: return minimum else: return value
def mktext_from_rec(rec): """ Return textual representation of rec dotfields. """ # Get list of dot fields in alphabetical order. # dot fields = [all rec fields] - [base fields] base_fields = {'_id', '_body'} dot_fields = sorted(set(rec.keys()).difference(base_fields)) dotfield_lines = [] for field in dot_fields: line = ".%s %s" % (field, rec[field]) dotfield_lines.append(line) body = rec.get('_body', "") field_part = '\n'.join(dotfield_lines) if not body: return field_part return (body + "\n" + field_part)
def dotify(adict): """ Contract a dictionary to use "dot notation". This support both standard dict or OrderedDict, or any dict subclass. For example:: .. code-block:: python3 adict = { 'key1': { 'key2': { 'key3': 'string1', 'key4': 1000, }, }, 'key4': { 'key5': 'string2', }, } contracted = dotify(adict) Will produce: .. code-block:: python3 { 'key1.key2.key3': 'string1', 'key1.key2.key4': 1000, 'key4.key5': 'string2', } :param dict adict: Original dictionary. :return: The contracted dictionary. Same datatype of the input. :rtype: dict """ assert isinstance(adict, dict), 'Invalid dictionary' dotdict = type(adict)() def _dotify(anode, crumbs): if isinstance(anode, dict): for key, value in anode.items(): _dotify(value, crumbs + [key]) return dotdict['.'.join(crumbs)] = anode _dotify(adict, []) return dotdict
def get_decimal_len(s): """used to find the length of the decimal part of lan/lon""" t = str(s) for c in t: if c not in '-.0123456789': return -1 if '.' not in t: return 0 while '.' in t: try: t = t[1:] except: pass return len(t)
def EmoteListToString(emoteList): """Convert an EmoteList to a string.""" # Use string.join to glue string of emotes in emoteList separator = " " return separator.join(emoteList)
def _generateEscapeSequence(styleSequence, preNum=0): """ Generate Escape Sequence Parameters: styleSequence (list): Sequenced list of escape sequence preNum (int): Number, that prepends before sequence count Returns: variables (str): Newline separated list consisting set of variables to be later used, instead of escape sequences """ count = 1 variables = '' if preNum: postStyle = '' if int(preNum) == 9: # if preNum is 9, then color from escape sequence is light postStyle = '_l' for style in styleSequence: style += postStyle variables += f"{style} = '\\x1b[{preNum}{count}m'\n" count += 1 else: for _ in styleSequence: variables += f"{_} = '\\x1b[{count}m'\n" count += 1 return variables
def list_to_string(l: list) -> str: """ :param list l: A list to serialize. :return str: The same list, as a string. """ return ', '.join([str(v) for v in l])
def twos_comp(val, bits): """compute 2's complement """ if val & (1 << (bits - 1)): val = val - (1 << bits) return val
def degTohms(ideg): """ Converts degrees to hours:minutes:seconds :param ideg: objects coordinates in degrees :type ideg: float :return: hours:minutes:seconds :rtype: string """ ihours = ideg / 15. hours = int(ihours) + 0. m = 60. * (ihours - hours) minutes = int(m) + 0. seconds = 60. * (m - minutes) hms = "%02d:%02d:%06.3f" % (hours, minutes, seconds) return hms
def get_request_method(environ: dict) -> str: """ Returns a method name of HTTP request. :param environ: WSGI environment :return: HTTP method name """ method = environ["REQUEST_METHOD"] return method
def prob_mass_grey_from_ndvi(ndvi, old_min=0.1, old_max=0.7): """ Calculates probability masses for grey from NDVI values :param ndvi: :param old_min: :param old_max: :return: """ # Not Green belief if ndvi > old_max: return 0 elif ndvi < old_min: return 1 else: new_max = 1 new_min = 0 old_range = old_max - old_min new_range = new_max - new_min return 1 - (((ndvi - old_min) * new_range) / old_range) + new_min
def is_master(config): """Return true we're on a master node.""" return not hasattr(config, 'workerinput')
def clean_hotel_prefer(string): """ Cambie por esta condicion porque me tiraba un warning si hacia solo if hotel_preferente: """ if string is not None: r = 1 else: r = 0 return r
def make_deps_full_name(i): """ Input: { deps - dict with deps } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 full_name - full name of deps } """ x=i['deps'] y=str(x.get('data_name','')) y1=str(x.get('version','')) if y1!='': y+=' '+y1 y1=str(x.get('git_revision','')) if y1!='': y+=' ('+y1+')' return {'return':0, 'full_name':y}
def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words. """ return (sep or ' ').join(x.capitalize() for x in s.split(sep))
def importName(modulename, name): """ Import a named object from a module in the context of this function, which means you should use fully qualified module paths. Return None on failure. """ try: module = __import__(modulename, globals(), locals(), [name]) except ImportError: return None return vars(module)[name]
def schemaFile(csvFile): """ Rename the csv file with schema notation and change to json file :param csvFile: input csv file name :return: new file name """ return csvFile.replace('.csv', '_schema.json')
def _append_extended_basins(basin_list): """Replace extended basins with components, e.g. atlExt with atl, mexico ... Note: atlExt etc are removed from the list for error checking later on. Parameters ---------- basin_list : list of strings list of basin names potentially including 'atlExt', 'pacExt', 'indExt' Returns ------- basin_list : list of strings list of basin names with "Ext" version replaced with "sub"basins """ for name in basin_list: if name == 'atlExt': basin_list.remove('atlExt') basin_list.append('atl') basin_list.append('mexico') basin_list.append('hudson') basin_list.append('med') basin_list.append('north') basin_list.append('baffin') basin_list.append('gin') elif name == 'pacExt': basin_list.remove('pacExt') basin_list.append('pac') basin_list.append('bering') basin_list.append('okhotsk') basin_list.append('japan') basin_list.append('eastChina') elif name == 'indExt': basin_list.remove('indExt') basin_list.append('ind') basin_list.append('southChina') basin_list.append('java') basin_list.append('timor') basin_list.append('red') basin_list.append('gulf') return basin_list
def img_resize_bilinear(grid, w2, h2): """ From techalgorithm.com """ w = len(grid[0]) h = len(grid) newgrid = [] x_ratio = (w-1)/float(w2) y_ratio = (h-1)/float(h2) for i in range(0, h2): y = int(y_ratio * i) y_diff = (y_ratio * i) - y newrow = [] for j in range(0, w2): x = int(x_ratio * j) x_diff = (x_ratio * j) - x A = grid[y][x] B = grid[y][x+1] C = grid[y+1][x] D = grid[y+1][x+1] # Y = A(1-w)(1-h) + B(w)(1-h) + C(h)(1-w) + Dwh newval = A*(1-x_diff)*(1-y_diff) + B*(x_diff)*(1-y_diff) + C*(y_diff)*(1-x_diff) + D*(x_diff*y_diff) newrow.append(newval) newgrid.append(newrow) return newgrid
def is_sorted(x): """ Test whether a list is sorted """ return all(a <= b for a,b in zip(x[0:-1], x[1:]))
def arrayAlista(array): """ Transforma un array de numpy en una lista """ lista = [] for elem in array: lista.append(list(elem)) return lista
def to_glob(pattern): """Given a pattern in match format, returns a glob in shell format.""" if "*" in pattern: return pattern return "*" + pattern + "*"
def calculate_pizzas_dumb(participants, n_pizza_types, pizza_types): """Determine pizza types and number of feeded participants. Parameters ---------- participants : Int Number of people to be feeded by pizza. n_pizza_types : type Description of parameter `n_pizza_types`. pizza_types : type Description of parameter `pizza_types`. Returns ------- type Description of returned object. """ residuals = participants type_list = [] for index, n_pizzas in reversed(list(enumerate(pizza_types))): temp_residuals = residuals - n_pizzas if temp_residuals >= 0: residuals = temp_residuals type_list.append(index) # Calcualte saturation - Number of feeded participants saturation = sum([pizza_types[idx] for idx in type_list]) unsaturated_participants = participants - saturation return type_list[::-1], unsaturated_participants
def generateDictFilename(series_abbr, host_name, series_code): """------------------------------------------------------------------- Function: [generateDictFilename] Description: Systematically generates a filename for a dictionary file given the host name, series abbreviation and code Input: [series_abbr] Series abbreviation [host_name] Name of the series host [series_code] Series code Return: String representing the name of the dictionary file associated with the given series attributes ------------------------------------------------------------------ """ fname = "%s_%s_%s.dict" % (series_abbr, host_name, series_code) return fname
def options_as_dictionary(meta): """ Transforms a list of tuples to a dictionary Args: meta (list): A list ot option tuples Retuns: dict: A dictionary of options key - values """ module_config = {} for seltuple in meta: module_config.update({seltuple[0]: seltuple[1]}) return module_config
def language_pretty(input: str) -> str: """.repo-metadata.json language field to pretty language.""" if input == "nodejs": return "Node.js" return input
def UniformPrior(Parameter,Bounds): """ Uniform prior to limit a parameter within a bound """ if Parameter < Bounds[0] or Parameter > Bounds[1]: return 0 else: return 1
def _GetMassCenter(MassCoordinates): """ ################################################################# Get the center of mass. INPUT: MassCoordinates is [[atommass,[x,y,z]],......]. ################################################################# """ res1 = 0.0 res2 = 0.0 res3 = 0.0 temp = [] for i in MassCoordinates: res1 = res1 + i[0] * i[1][0] res2 = res2 + i[0] * i[1][1] res3 = res3 + i[0] * i[1][2] temp.append(i[0]) result = [res1 / sum(temp), res2 / sum(temp), res3 / sum(temp)] return result
def check_url(input_str): """Check if a string is a 'https' url. Parameters ---------- input_str : str An input string or path. Returns ------- bool True if input_string is url, else False. """ return 'https' in str(input_str)
def split_get_output(output: str): """' Parse output like: -1 0 CS{Cell{...} bits: 64..66; refs: 0..0} CS{Cell{...} bits: 66..333; refs: 0..0} C{...} To: [-1, 0, "CS{Cell{...} bits: 64..66; refs: 0..0}", "CS{Cell{...} bits: 66..333; refs: 0..0}", "C{...}"] """ data = output.split() result = [] to_fix = 0 for i in data: if to_fix > 0: result[-1] += f" {i}" else: result.append(i) tmp_to_fix = i.count('{') tmp_to_not_fix = i.count("}") to_fix += tmp_to_fix - tmp_to_not_fix return result
def should_force_step(step_name, force_steps): """ Check if step_name is in force_steps We support multi-level flags, ex for step_name = "a.b.c", we allow : "a", "a.b", "a.b.c" If one of force_steps is a wildcard (*), it will also force the step """ for step in force_steps: if step == "*" or step == step_name or step_name.startswith(step + "."): return True return False
def get_all_dates(year_start, month_start, year_end, month_end): """get_all_dates Get all the dates between two dates. :param year_start: The starting year :param month_start: The starting month :param year_end: The ending year :param month_end: The ending month """ assert (year_start < year_end or year_start == year_end and month_start <= month_end), "Start date before end date" import calendar cal = calendar.TextCalendar() current_year = year_start current_month = month_start dates = [] while current_year != year_end or current_month != month_end: for i in cal.itermonthdays(current_year, current_month): if i != 0: dates.append(str(current_year)+"/"+str(current_month)+"/"+str(i)) current_month += 1 if current_month == 13: current_year += 1 current_month = 1 for i in cal.itermonthdays(current_year, current_month): if i != 0: dates.append(str(current_year)+"/"+str(current_month)+"/"+str(i)) return dates
def get_size_to_pretty(the_size, in_bits=False): """ Get a pretty string of a number of bits or bytes :param the_size: The Size in bits or bytes :param in_bits: Should the pretty string show bits? :return: A pretty string, reduced version of the_size """ if the_size >= 1000000: return '%d%s' % (the_size / 1000000, 'MBit' if in_bits else 'MByte') elif the_size >= 1000: return '%d%s' % (the_size / 1000, 'KBit' if in_bits else 'KByte') return '%d%s' % (the_size, 'Bits' if in_bits else 'Bytes')
def expandCommaSeparatedRanges(s): """ 's' format - comma separated ranges or values a-b,c,..,d,e-f,a etc. Includes the first and the last value in the range """ range_list = s.split(',') values = list() for r in range_list: # range a-b if '-' in r: # start and end of the range can have # any number of digits ind = r.index('-') s = int(r[0:ind]) e = int(r[ind+1:]) values += (range(s,e+1)) # single value else: values.append(int(r)) return values
def build_target_command(target_bin: str, config: str) -> str: """ Builds a command that starts a singer target connector with the required command line arguments Args: target_bin: path the target python executable config: path to config json file Returns: string of command line executable """ target_command = f'{target_bin} --config {config}' return target_command
def _rhs(model_expression): """ Get only the right-hand side of a patsy model expression. Parameters ---------- model_expression : str Returns ------- rhs : str """ if '~' not in model_expression: return model_expression else: return model_expression.split('~')[1].strip()
def Convert2Num(text): """converts text to python type in order Int, hex, Float, Complex ValueError if can't """ #convert to number if possible try: value = int(text, 10) return value except ValueError as ex: pass try: value = int(text, 16) return value except ValueError as ex: pass try: value = float(text) return value except ValueError as ex: pass try: value = complex(text) return value except ValueError as ex: pass raise ValueError("Expected Number got '{0}'".format(text)) # return None
def making_change(amt: int, coins: list) -> int: """Iterative implementation of the making change algorithm. :param amt (int) : Amount, in cents, to be made into change. :param coins (list) : List of coin denominations :return (int) : Number of different combinations of change. """ # calc[i] represents the number of ways to get to amount i calc = [0] * (amt + 1) # 1 way to get zero calc[0] = 1 # Pick all coins one by one and update calc[] values after the # index greater than or equal to the value of the picked coin for coin_val in coins: for j in range(coin_val, amt + 1): calc[j] += calc[j - coin_val] return calc[amt]
def file_from_list_of_images(file_list, current_file, request): """ return filename from file_list depends of request request: position on the list """ if file_list: if request == "first": file = file_list[0] elif request == "previous": position = file_list.index(current_file) if position > 0: file = file_list[position - 1] else: file = None elif request == "next": position = file_list.index(current_file) if position <= len(file_list) - 2: file = file_list[position + 1] else: file = None elif request == "last": file = file_list[-1] else: file = None else: file = None if file == current_file: file = None return file
def convert_2_BIO(label): """ Convert inplace IOBES encoding to BIO encoding """ tag = [] i = 0 while i < len(label): char = label[i] i += 1 if char == 'S': tag.append('B') elif char == 'E': tag.append('I') elif char == 'I': tag.append('I') if i < len(label) and label[i] == 'B': tag.append('I') i = i + 1 else: tag.append(char) return tag
def is_leap(year): """Return True for leap years, False for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def find_ngrams(input_list, n, **kwargs): """Generates all n-gram combinations from a list of strings Args: input_list (list): List of string to n-gramize n (int): The size of the n-gram Returns: list: A list of ngrams across all the strings in the \ input list """ del kwargs result = [] for ngram in zip(*[input_list[i:] for i in range(n)]): result.append(" ".join(ngram)) return result
def average_(numList, printed=False): """Find the average/mean of a set of numbers.""" # The sum of the numbers in the numList divided by the length of the list. if printed: print(sum(numList)/len(numList)) else: return sum(numList)/len(numList)
def flatten(array): """ Return a flattened copy of a list of lists. """ return [item for row in array for item in row]
def extract_first_three_lanes(polys): """ Extract the first three lanes Input polys: all lanes Ouput the first three lanes """ return polys[:3]
def get_dat_id(datnum, datname): """Returns unique dat_id within one experiment.""" name = f'Dat{datnum}' if datname != 'base': name += f'[{datname}]' return name
def clip(min, val, max): """ Returns `val` clipped to `min` and `max`. """ return min if val < min else max if val > max else val
def to_str(var): """Similar to to_list function, but for string attributes.""" try: return str(var) except TypeError: raise ValueError("{} cannot be converted to string.".format(var))
def decbin(num): """ Converts a decimal number(num) to binary Parameters ---------- num : int or string Returns ------- integer denoting value of decimal number in binary format. """ try: return bin(int(num))[2:] except: raise ValueError("Expected a Number as input")
def trace(X_ref, Y_ref): """ Calculates the slope and intercept for the trace, given the position of the direct image in physical pixels. These coefficients are for the WFC3 G141 grism. See also: https://ui.adsabs.harvard.edu/abs/2009wfc..rept...17K/abstract """ BEAMA_i = 15 BEAMA_f = 196 DYDX_0_0 = 1.96882E+00 DYDX_0_1 = 9.09159E-05 DYDX_0_2 = -1.93260E-03 DYDX_1_0 = 1.04275E-02 DYDX_1_1 = -7.96978E-06 DYDX_1_2 = -2.49607E-06 DYDX_1_3 = 1.45963E-09 DYDX_1_4 = 1.39757E-08 DYDX_1_5 = 4.84940E-10 DYDX_0 = DYDX_0_0 + DYDX_0_1*X_ref + DYDX_0_2*Y_ref DYDX_1 = DYDX_1_0 + DYDX_1_1*X_ref + DYDX_1_2*Y_ref + DYDX_1_3*X_ref**2 + DYDX_1_4*X_ref*Y_ref + DYDX_1_5*Y_ref**2 return [DYDX_0, DYDX_1]
def normalize_encoding(encoding, default): """Normalize the encoding name, replace ASCII w/ UTF-8.""" if encoding is None: return default encoding = encoding.lower().strip() if encoding in ['', 'ascii']: return default return encoding
def traverse_json_obj(obj, path=None, callback=None): """ Recursively loop through object and perform the function defined in callback for every element. Only JSON data types are supported. :param obj: object to traverse :param path: current path :param callback: callback executed on every element :return: potentially altered object """ if path is None: path = [] if isinstance(obj, dict): value = {k: traverse_json_obj(v, path + [k], callback) for k, v in obj.items()} elif isinstance(obj, list): value = [traverse_json_obj(elem, path + [[]], callback) for elem in obj] else: value = obj if callback is None: return value return callback(value)
def get_max_episode(num_h_layers, epoch_factor, penalty_every, **_): """Routine to calculate the total number of training episodes (1 episode = 1 penalty epoch + *penalty_every* normal epochs""" max_episode = (num_h_layers * epoch_factor) // penalty_every if max_episode == 0: raise ValueError('Penalty_every has to be smaller than the total number of epochs.') return max_episode
def pairwise_reduce(op, x): """ Parameters ---------- op Operation x Input list Returns ------- """ while len(x) > 1: v = [op(i, j) for i, j in zip(x[::2], x[1::2])] if len(x) > 1 and len(x) % 2 == 1: v[-1] = op(v[-1], x[-1]) x = v return x[0]
def to_upper(ins): """ A trivial function to test from pytest in the app file. """ return ins.upper()
def func_poly2d(x,y,*args): """ 2D polynomial surface""" p = args np = len(p) if np==0: a = p[0] elif np==3: a = p[0] + p[1]*x + p[2]*y elif np==4: a = p[0] + p[1]*x + p[2]*x*y + p[3]*y elif np==6: a = p[0] + p[1]*x + p[2]*x**2 + p[3]*x*y + p[4]*y + p[5]*y**2 elif np==8: a = p[0] + p[1]*x + p[2]*x**2 + p[3]*x*y + p[4]*(x**2)*y + p[5]*x*y**2 + p[6]*y + p[7]*y**2 elif np==11: a = p[0] + p[1]*x + p[2]*x**2.0 + p[3]*x**3.0 + p[4]*x*y + p[5]*(x**2.0)*y + \ p[6]*x*y**2.0 + p[7]*(x**2.0)*(y**2.0) + p[8]*y + p[9]*y**2.0 + p[10]*y**3.0 elif np==15: a = p[0] + p[1]*x + p[2]*x**2 + p[3]*x**3 + p[4]*x**4 + p[5]*y + p[6]*x*y + \ p[7]*(x**2)*y + p[8]*(x**3)*y + p[9]*y**2 + p[10]*x*y**2 + p[11]*(x**2)*y**2 + \ p[12]*y**3 + p[13]*x*y**3 + p[14]*y**4 elif np==21: a = p[0] + p[1]*x + p[2]*x**2 + p[3]*x**3 + p[4]*x**4 + p[5]*x**5 + p[6]*y + p[7]*x*y + \ p[8]*(x**2)*y + p[9]*(x**3)*y + p[10]*(x**4)*y + p[11]*y**2 + p[12]*x*y**2 + \ p[13]*(x**2)*y**2 + p[14]*(x**3)*y**2 + p[15]*y**3 + p[16]*x*y**3 + p[17]*(x**2)*y**3 + \ p[18]*y**4 + p[19]*x*y**4 + p[20]*y**5 else: raise Exception('Only 3, 4, 6, 8, 11 amd 15 parameters supported') return a
def pig_it(string): """Function creates string with simple pig latin words.""" pyg = "ay" final_output = "" for word in string.split(): if not word.isalpha(): final_output += word + " " break else: first = word[0] new_word = word + first + pyg new_word = new_word[1:len(new_word)] final_output += new_word + " " return(final_output[:-1])
def clean_kwargs(kwargs, keys=None): """Removes each key from kwargs dict if found Parameters ---------- kwargs : dict * dict of keyword args keys : list of str, optional * default: ['obj', 'pytan_help', 'objtype'] * list of strs of keys to remove from kwargs Returns ------- clean_kwargs : dict * the new dict of kwargs with keys removed """ if keys is None: keys = ['obj', 'pytan_help', 'objtype'] clean_kwargs = dict(kwargs) [clean_kwargs.pop(x) for x in keys if x in kwargs] return clean_kwargs
def msb(value: bytearray) -> int: """ Return the value of the highest digit of the number 'value'. Args: value: The number for which you want to determine the value of the high order. """ return value[0] & 0x80
def get_pos(sequence): """ Get the positions of 'A', 'C', 'T', 'G' on the sequence :param letter: the sequence :return: the positions of 'A', 'C', 'T', 'G' on the sequence """ Apos = [] Cpos = [] Gpos = [] Tpos = [] length = len(sequence) for pos in range(length): if sequence[pos] == 'A' or\ sequence[pos] == 'a': Apos.append(pos) elif sequence[pos] == 'C' or\ sequence[pos] == 'c': Cpos.append(pos) elif sequence[pos] == 'G' or\ sequence[pos] == 'g': Gpos.append(pos) elif sequence[pos] == 'T' or\ sequence[pos] == 't': Tpos.append(pos) else: print("wrong letter") finalpos = {} finalpos['A'] = Apos finalpos['C'] = Cpos finalpos['G'] = Gpos finalpos['T'] = Tpos return finalpos
def _even_quotient(a, b, tol=1e-6): """Returns a / b if it is an integer, -1 if it is not..""" num = int(round(a / b)) if abs(a - b * num) < abs(b * tol): return num return -1
def convert_tok_str_to_sent(tok_str): """Returns the sentence given the subword tokens""" res = '' tokens = tok_str.split(' ') for token in tokens: if '#' in token: token = token.replace('#', '') res += token else: res = res + ' ' + token return res.strip()