content
stringlengths
42
6.51k
def int_to_string( long_int, padto=None ): """ Convert integer long_int into a string of bytes, as per X9.62. If 'padto' defined, result is zero padded to this length. """ if long_int > 0: octet_string = "" while long_int > 0: long_int, r = divmod( long_int, 256 ) octet_string = chr( r ) + octet_string elif long_int == 0: octet_string = chr(0) else: raise ValueError('int_to-string unable to convert negative numbers') if padto: padlen = padto - len(octet_string) assert padlen >= 0 octet_string = padlen*chr(0) + octet_string return octet_string
def _abs2(x): """Absolute square of data""" return x.real*x.real + x.imag*x.imag
def virus_test(name): """Tests whether "virus" is in a species name or not. Written by Phil Wilmarth, OHSU, 2009. """ return ('virus' in name)
def get_fun_elem_from_fun_inter(interface_list, fun_elem_list): """Get output_list = [[fun_elem_1, fun_elem_2, fun_inter]...] list from interface_list = [[producer, consumer, fun_inter]...] and put value to False if (first, second, interface) have been added to output_list (i.e. fun_elem_1/fun_elem_2 have been found for a fun_inter)""" output_list = [] for ix, (first, second, interface) in enumerate(interface_list): fun_elem_1 = None fun_elem_2 = None if first: for elem_1 in fun_elem_list: if any(s == interface.id for s in elem_1.exposed_interface_list): if not elem_1.child_list: fun_elem_1 = elem_1 else: check = True for child in elem_1.child_list: if any(s == interface.id for s in child.exposed_interface_list): check = False if check: fun_elem_1 = elem_1 if second: for elem_2 in fun_elem_list: if not first: if any(s == interface.id for s in elem_2.exposed_interface_list): if not elem_2.child_list: fun_elem_2 = elem_2 else: check = True for child in elem_2.child_list: if any(s == interface.id for s in child.exposed_interface_list): check = False if check: fun_elem_2 = elem_2 else: if any(s == interface.id for s in elem_2.exposed_interface_list) and \ elem_2 != fun_elem_1: if not elem_2.child_list: fun_elem_2 = elem_2 else: check = True for child in elem_2.child_list: if any(s == interface.id for s in child.exposed_interface_list): check = False if check: fun_elem_2 = elem_2 if not (not fun_elem_1 and not fun_elem_2): if [fun_elem_1, fun_elem_2, interface] not in output_list: output_list.append([fun_elem_1, fun_elem_2, interface]) interface_list[ix] = False return output_list, interface_list
def get_tokens(line): """tokenize an Epanet line (i.e. split words; stopping when ; encountered)""" tokens=list() words=line.split() for word in words: if word[:1] == ';': break else: tokens.append(word) return tokens
def rename_qty2stdunit(unit): """ Clean OFF quantity unit to a standard unit name (g, kg, mg, gal, egg, portion, l...) Args: unit (str): OFF quantity unit Returns: std_unit (str): standard unit name """ clean_matrix = {None:[None,''], 'g':['g','gr','grammes','G','grams','gramme','grs','Grammes', 'gram','gramm','grames','GR','gms','gm','grammi', 'grm','gramos','gammes','Grs','gramas','Gramos', 'grme','Gramm','gra','Gr','grms','ghr','gfd'], 'kg':['kg','Kg','KG','kgs','kilogrammae','klg','Kilogramm','kgi', 'kgr','kilos','kilo'], 'mg':['mg','mcg','mG','Mg','MG'], 'gal':['gal','gallon','GAL','Gal','GALLON','Gallon'], 'egg':['egg','eggs','Eggs','huevos','oeufs','Oeufs','ufs'], 'portion':['portion','servings','Servings','Serving', 'Unidad', 'triangles','beignets','galettes','baguettines', 'oranges','magret','baguette','Galettes','courge', 'galetttes','meringues','galetted','baguettes', 'Burger','gaufrettes','mangue','yogourts','gaufres', 'Gaufres','burgers','galletas','hamburguesas','vegano', 'fromage','mignonnettes','Portionsfilets','avocats', 'Fruit','fruits','fruit','portions','filets'], 'l':['l','L','litre','litres','Litre','Litres','Liters','liter', 'litro','Liter'], 'ml':['ml','mL','ML','Ml'], 'cl':['cl','cL','CL','Cl'], 'dl':['dl','dL','DL','Dl'], 'oz':['oz','OZ','Oz','oZ'], 'lb':['lb','LB','Lb','lB','lbs']} std_unit = [key for (key, value) in clean_matrix.items() if (unit in value)] std_unit = [unit] if not std_unit else std_unit return std_unit[0]
def obtain_all_devices(my_devices): """Dynamically create 'all' group.""" new_devices = {} for device_name, device_or_group in my_devices.items(): # Skip any groups if not isinstance(device_or_group, list): new_devices[device_name] = device_or_group return new_devices
def frequency_to_n(freq, grid=0.00625e12): """ converts frequency into the n value (ITU grid) """ return (int)((freq-193.1e12)/grid)
def _get_pairs(data): """Return data in pairs This uses a clever hack, based on the fact that zip will consume items from the same iterator, for each reference found in each row. Example:: >>> _get_pairs([1, 2, 3, 4]) [(1, 2), (3, 4)] """ return list(zip(*((iter(data),)*2)))
def slice(n): """Return slice for rank n array""" return ", ".join(["1"] * n)
def get_lane_mean_x(lane): """Get mean x of the lane. :param lane: target lane :type lane: list :return: the mean value of x :rtype: float """ x_pos_list = [] for pt in lane: x_pos_list.append(pt.x) x_mean = 0 if len(x_pos_list) == 1: x_mean = x_pos_list[0] elif len(x_pos_list) > 1: x_mean = (x_pos_list[0] + x_pos_list[-1]) / 2 return x_mean
def taux_boost(cote, boost_selon_cote=True, boost=1): """ Calcul du taux de boost pour promotion Betclic """ if not boost_selon_cote: return boost if cote < 2: return 0 if cote < 2.51: return 0.25 if cote < 3.51: return 0.5 return 1
def sgn(x): """ Return the sign of *x*. """ return 1 if x.real > 0 else -1 if x.real < 0 else 0
def unique_preserve_order(lst): """ Deduplicate lst without changing the order. Return a new list. The elements of lst are not required to be hashable. """ new_lst = [] for item in lst: if item not in new_lst: new_lst.append(item) return new_lst
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in earlier dicts. Modified from http://stackoverflow.com/a/26853961/554546 :param list[dict] dict_args: An iterable of dictionaries. :return: A dictionary merged as above. :rtype: dict """ result = {} for dictionary in reversed(dict_args): result.update(dictionary) return result
def padding_4ch(s): """ Add zeros to form 4 continuous characters and add spaces every 4 characters :type s: str """ n = len(s) r = n % 4 if r != 0: k = 4 - r s = k * '0' + s else: s = s s = s[::-1] s = ' '.join(s[i:i + 4] for i in range(0, len(s), 4)) s = s[::-1] return s
def networkx_json_to_visjs(res): """Convert JSON output from networkx to visjs compatible version Params ------ res: JSON output from networkx of the graph """ colors = {1: 'green', 2: 'red', 3: 'rgba(255,168,7)'} if res: links = res['links'] new_links = [] for _link in links: _link['from'] = _link.pop('source') _link['to'] = _link.pop('target') _link['font'] = {'align': 'middle'} _link['arrows'] = 'to' new_links.append(_link) res['links'] = new_links new_nodes = [] for _node in res['nodes']: _node['label'] = _node['identifier'][4:] + ':' + str(_node['id']) _node['color'] = colors[_node['level']] if 'equivalent_ids' in _node: equ_ids = [] for k, v in _node['equivalent_ids'].items(): if isinstance(v, list): for _v in v: equ_ids.append(k + ':' + str(_v)) else: equ_ids.append(k + ":" + str(v)) equ_ids = '<br>'.join(equ_ids) _node['equivalent_ids'] = equ_ids new_nodes.append(_node) res['nodes'] = new_nodes return res
def join_host_strings(user, host, port=None): """Turn user/host/port strings into ``user@host:port`` combined string.""" port_string = '' if port: port_string = ":%s" % port return "%s@%s%s" % (user, host, port_string)
def normalize(size_sequence): """ :param size_sequence: list or tuple of [k1, k2, ... , kn] :return: a tuple of (k1/(k1 + k2 + ... + kn), k2/(k1 + k2 + ... + kn), ... , kn/(k1 + k2 + ... + kn),) """ total = sum(size_sequence) denominator = 1.0 / total result = [item * denominator for item in size_sequence] return tuple(result)
def RequestArgsGetHeader(args, kwargs, header, default=None): """Get a specific header given the args and kwargs of an Http Request call.""" if 'headers' in kwargs: return kwargs['headers'].get(header, default) elif len(args) > 3: return args[3].get(header, default) else: return default
def expand_shape(shape): """ Expands a flat shape to an expanded shape >>> expand_shape([2, 3]) [2, [3, 3]] >>> expand_shape([2, 3, 4]) [2, [3, 3], [[4, 4, 4], [4, 4, 4]]] """ expanded = [shape[0]] for i in range(1, len(shape)): next = [shape[i]] * shape[i-1] for j in range(1, i): next = [next] * shape[j] expanded.append(next) return expanded
def is_pid_valid(pid): """Checks whether a pid is a valid process ID of a currently running process.""" # adapted from http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid import os, errno if pid <= 0: raise ValueError('Invalid PID.') try: os.kill(pid, 0) except OSError as err: if err.errno == errno.ESRCH: # No such process return False elif err.errno == errno.EPERM: # Not permitted to send signal return True else: # EINVAL raise else: return True
def comment(commentstr=u''): """Insert comment.""" return u'<!-- ' + commentstr.replace(u'--',u'') + u' -->'
def check_if_seq(NN_config): """ Parameters ---------- NN_config : list Specifies the architecture of neural network. Returns ------- return_seq : bool Specifies if there are some GRU or LSTM layers in the NN_config (or its part). """ if "g" in NN_config or "l" in NN_config: return_seq = True else: return_seq = False return return_seq
def cast_string(f, s): """ Generic function that casts a string. :param f: (function) Any casting function. :param s: (str) String to cast. :return: The casted object """ try: return f(s) except ValueError as e: return None
def forms_processed_per_hour(total_forms_processed, total_time_in_seconds): """Calculate forms processed per hour. Divide total forms processed by the total time it took to process all the forms. :param total_forms_processed: Total number of forms processed. :param total_time_in_seconds: Total time for processing all forms. :returns: An Integer of forms processed per hour. """ one_minute_in_seconds = 60 minutes = divmod(total_time_in_seconds, one_minute_in_seconds)[0] hours = divmod(minutes, one_minute_in_seconds)[0] forms_processed_per_hour = None if round(hours): forms_processed_per_hour = total_forms_processed/float(hours) return forms_processed_per_hour\ if forms_processed_per_hour else total_forms_processed
def _wcversion_value(ver_string): """ Integer-mapped value of given dotted version string. :param str ver_string: Unicode version string, of form ``n.n.n``. :rtype: tuple(int) :returns: tuple of digit tuples, ``tuple(int, [...])``. """ retval = tuple(map(int, (ver_string.split('.')))) return retval
def acos(c): """acos - Safe inverse cosine Input argument c is shrunk to admissible interval to avoid case where a small rounding error causes a math domain error. """ from math import acos if c > 1: c=1 if c < -1: c=-1 return acos(c)
def _format_time(seconds): """Formats seconds to readable time string. This function is used to display time in progress bar. """ if not seconds: return '--:--' seconds = int(seconds) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if hours: return f'{hours}:{minutes:02d}:{seconds:02d}' return f'{minutes:02d}:{seconds:02d}'
def GetTokensInSubRange(tokens, start, end): """Get a subset of tokens within the range [start, end).""" tokens_in_range = [] for tok in tokens: tok_range = (tok.lineno, tok.column) if tok_range >= start and tok_range < end: tokens_in_range.append(tok) return tokens_in_range
def deduped_table(table): """ De-deplicate the codepoint entries in the from-disk table according to WHATWG specs. """ tmp_table_1 = [x for x in table] # Remove all except the _last_ entries for code points U+2550, U+255E, # U+2561, U+256A, U+5341, and U+5345. tmp_table_1.reverse() tmp_table_2 = [] seen = set() for (index, codepoint) in tmp_table_1: if codepoint not in seen: if codepoint in [0x2550, 0x255E, 0x2561, 0x256A, 0x5341, 0x5345]: seen.add(codepoint) tmp_table_2 += [(index, codepoint)] tmp_table_2.reverse() # For the rest, remove all except the _first_ entries. new_table = [] seen = set() for (index, codepoint) in tmp_table_2: if codepoint not in seen: seen.add(codepoint) new_table += [(index, codepoint)] return new_table
def is_number(s): """return True if s is a number, or False otherwise""" try: float(s) return True except ValueError: return False
def generate_command(input_dir, output_dir, vocab_file, bert_config, init_checkpoint, layers, max_seq_length, batch_size): """ generete command :param input_dir: :param output_dir: :param vocab_file: :param bert_config: :param init_checkpoint: :param layers: :param max_seq_length: :param batch_size: :return: """ result = "" result += "python extract_features.py " result += "--input_file="+input_dir result += " --output_file=" + output_dir result += " --vocab_file="+vocab_file result += " --bert_config_file="+bert_config result += " --init_checkpoint="+init_checkpoint result += " --layers="+layers result += " --max_seq_length="+str(max_seq_length) result += " --batch_size="+str(batch_size) return result
def _get_nested(dict_, keys): """ Nested get method for dictionaries (and lists, tuples). """ try: for key in keys: dict_ = dict_[key] except (KeyError, IndexError, TypeError): return None return dict_
def uniformFunc( dispX, dispY, radius ): """ Density Estimation using uniform function -> square in 2D """ maskX = dispX <= radius maskY = dispY <= radius maskXY = maskX & maskY return maskXY/ float(radius *radius)
def prime(num): """" To check whether a number is prime """ num2 = num while num2 > 0: if num == num2: num2 -= 1 elif num2 == 1: num2 -= 1 elif num % num2 == 0: return False num2 -= 1 return True
def to_sequence(index, text): """Returns a list of integer indicies of lemmas in `text` to the word2idx vocab in `index`. :param index: word2idx vocab. :param text: list of tokens / lemmas / words to be indexed :returns: list of indicies """ indexes = [index[word] for word in text if word in index] return indexes
def unique(seq): """ unique: Retorna valores unicos de uma lista Parametros ---------- seq: array de objetos lista de objetos Examples -------- # >> import file_utils # >>> file_utils.unique([1,1,2,3,3,4]) # lista de numeros # array([1,2,3,4]) """ set1 = set(seq) return list(set1)
def _resolve(dikt, var): """ Resolve a complex key using dot notation to a value in a dict. Args: dikt: Dictionary of key-value pairs, where some values may be sub dictionaries, recursively. var: Key or string of dot-separated keys denoting path through dict Returns: The referenced value, or None if none found """ arr = var.split('.', 1) try: if len(arr) == 1: return dikt[arr[0]] return _resolve(dikt[arr[0]], arr[1]) except KeyError: return None
def sumSquare(number): """ This function will do the math required to calculate the difference in the stated problem. """ sumSq = 0 # Sum of the squares. sqOfSum = 0 # Square of the sum. for i in range(1, number+1): sumSq += i**2 # Get the sum of the squares. sqOfSum += i # Get the sum of natural numbers. sqOfSum = sqOfSum**2 # Squaring the sum. diff = sqOfSum - sumSq # Difference of the Sum of Square. return diff
def precipitation_intensity(precip_intensity, unit): """ :param precip_intensity: float containing the currently precipIntensity :param unit: string of unit for precipitation rate ('in/h' or 'mm/h') :return: string of precipitation rate. Note: this is appended to and used in special event times """ intensities = { 'in/h': { 'very-light': ('very-light', 0.002), 'light': ('light', 0.017), 'moderate': ('moderate', 0.1), 'heavy': ('heavy', 0.4) }, 'mm/h': { 'very-light':('very-light', 0.051), 'light': ('light', 0.432), 'moderate': ('moderate', 2.540), 'heavy': ('heavy', 5.08) } } if precip_intensity >= intensities[unit]['heavy'][1]: return intensities[unit]['heavy'][0] elif precip_intensity >= intensities[unit]['moderate'][1]: return intensities[unit]['moderate'][0] elif precip_intensity >= intensities[unit]['light'][1]: return intensities[unit]['light'][0] elif precip_intensity >= intensities[unit]['very-light'][1]: return intensities[unit]['very-light'][0] else: return 'none'
def remove_unnecessary(string): """Removes unnecessary symbols from a string and returns the string.""" string = string.replace('@?', '') string = string.replace('?@', '') return string
def fibonacciNumber(n): """ :return: n'th fibonacci Number """ if n == 0: return 0 elif n == 1: return 1 else: return fibonacciNumber(n - 1) + fibonacciNumber(n - 2)
def get_note_freq(note: int) -> float: """Return the frequency of a note value in Hz (C2=0).""" return 440 * 2 ** ((note - 33) / 12)
def tokenize_doc(json_data): """ IMPLEMENT ME! Tokenize a document and return its bag-of-words representation. doc - a string representing a document. returns a dictionary mapping each word to the number of times it appears in doc. """ words = {} for w in json_data['ingredients']: if w not in words: words[w] =0 words[w] +=1 return words
def MinMod(pa,pb): """ Minmod averaging function """ s = (0.5 if pa>0.0 else -0.5) + (0.5 if pb>0.0 else -0.5) return min([abs(pa),abs(pb)])*s
def index_of_value(x, value): """ Takes the list x and returns a list of indices where it takes value """ indices = [i for i in range(len(x)) if x[i]==value] if indices == []: print("There is no item=={v} in the list".format(v=value)) else: return indices
def _endswith(prop_value, cmp_value, ignore_case=False): """ Helper function that take two arguments and checks if :param prop_value: endswith :param cmp_value: :param prop_value: Property value that you are checking. :type prop_value: :class:`str` :param cmp_value: Value that you are checking if it is in the property value endswith. :type cmp_value: :class:`str` :param ignore_case: True to run using incase sensitive. :type ignore_case: :class:`bool` :returns: True if :param prop_value: endswith :param cmp_value: :rtype: class:`bool` """ if ignore_case is True: prop_value = prop_value.lower() cmp_value = cmp_value.lower() return prop_value.endswith(cmp_value)
def evaluations(ty, pv): """ evaluations(ty, pv) -> ACC Calculate accuracy using the true values (ty) and predicted values (pv). """ if len(ty) != len(pv): raise ValueError("len(ty) must equal to len(pv)") total_correct = total_error = 0 for v, y in zip(pv, ty): if y == v: total_correct += 1 l = len(ty) ACC = 100.0 * total_correct / l return ACC
def get_scale(a_index, w_index): """ Returns the proper scale for the BBQ multliplication index Parameters ---------- a_index : Integer Current activation bit index w_index : Integer Current weight bit index """ scale = pow(2, (a_index + w_index)) return scale
def find_path(matrix, task): """ Find a all available paths for a next step :param matrix: :param task: :return: """ result = [] goal = (len(matrix) - 1, len(matrix[-1]) - 1) while True: candidate = [] last_point = task[-1] if len(matrix) > last_point[0] + 1: if len(matrix[last_point[0] + 1]) > last_point[1] + 1 and not matrix[last_point[0] + 1][last_point[1] + 1] and (last_point[0] + 1, last_point[1] + 1) not in task: candidate.append((last_point[0] + 1, last_point[1] + 1)) if last_point[1] - 1 >= 0 and len(matrix[last_point[0] + 1]) > last_point[1] + 1 and not matrix[last_point[0] + 1][last_point[1] - 1] and (last_point[0] + 1, last_point[1] - 1) not in task: candidate.append((last_point[0] + 1, last_point[1] - 1)) if last_point[0] - 1 >= 0: if len(matrix[last_point[0] - 1]) > last_point[1] + 1 and not matrix[last_point[0] - 1][last_point[1] + 1] and (last_point[0] - 1, last_point[1] + 1) not in task: candidate.append((last_point[0] - 1, last_point[1] + 1)) if 0 <= last_point[1] - 1 < len(matrix[last_point[0] - 1]) and not matrix[last_point[0] - 1][last_point[1] - 1] and (last_point[0] - 1, last_point[1] - 1) not in task: candidate.append((last_point[0] - 1, last_point[1] - 1)) if not len(candidate): result = [] break if len(candidate) == 1: task.append(candidate.pop()) if task[-1] == goal: return [task] if len(candidate) > 1: for item in candidate: if item == goal: result = [task + [item]] return result result.append(task + [item]) break return result
def extract(x, *keys): """ Args: x (dict or list): dict or list of dicts Returns: (tuple): tuple with the elements of the dict or the dicts of the list """ if isinstance(x, dict): return tuple(x[k] for k in keys) elif isinstance(x, list): return tuple([xi[k] for xi in x] for k in keys) else: raise NotImplementedError
def make_cost_matrix(profit_matrix, inversion_function): """ Create a cost matrix from a profit matrix by calling 'inversion_function' to invert each value. The inversion function must take one numeric argument (of any type) and return another numeric argument which is presumed to be the cost inverse of the original profit. This is a static method. Call it like this: .. python:: cost_matrix = Munkres.make_cost_matrix(matrix, inversion_func) For example: .. python:: cost_matrix = Munkres.make_cost_matrix(matrix, lambda x : sys.maxint - x) :Parameters: profit_matrix : list of lists The matrix to convert from a profit to a cost matrix inversion_function : function The function to use to invert each entry in the profit matrix :rtype: list of lists :return: The converted matrix """ cost_matrix = [] for row in profit_matrix: cost_matrix.append([inversion_function(value) for value in row]) return cost_matrix
def add_start_end(tokens, start_word="<START>", end_word="<END>"): """ Add start and end words for a caption string Args: tokens: original tokenized caption start_word: word to indicate start of a caption sentence end_word: word to indicate end of a caption sentence Returns: token_caption: tokenized caption """ token_caption = [start_word] token_caption.extend(tokens) token_caption.append(end_word) return token_caption
def pretty_machine_stamp(machst): """Return a human-readable hex string for a machine stamp.""" return " ".join("0x{:02x}".format(byte) for byte in machst)
def _try_compile(source, name): """Attempts to compile the given source, first as an expression and then as a statement if the first approach fails. Utility function to accept strings in functions that otherwise expect code objects """ try: c = compile(source, name, "eval") except SyntaxError: c = compile(source, name, "exec") return c
def is_valid_wager_amount(wager, balance): """ To determine whether the balance is less than or equal to the wager If the wager is less than or equal to the balance Returns true Otherwise, Returns false Returns: The boolean value (boolean) """ if wager <= balance: return True else: return False
def _trim_doc(doc): """Trims the quotes from a quoted STRING token (eg. "'''text'''" -> "text") """ l = len(doc) i = 0 while i < l/2 and (doc[i] == "'" or doc[i] == '"'): i += 1 return doc[i:-i]
def getProcVer(version: str) -> str: """Process a version string. This is pretty opinionated. Args: version (str): the version Returns: str: the processed version """ if version.startswith("^"): major = int(version[1:].split(".")[0]) if major > 1990 or major == 0: # if cal ver or zero ver return f"<{major + 2},>={version[1:]}" return f"<{major + 1},>={version[1:]}" return version
def matrix_divided(matrix, div): """ Divides all the elements of a matrix by a divisor, result is rounded by two decimal places. Args: matrix: list of lists containing dividends div: divisor Raises: TypeError: matrix must be a matrix (list of lists) of integers/floats TypeError: Each row of the matrix must have the same size TypeError: div must be a number ZeroDivisionError: division by zero Return: Addition type int """ tperror = 0 result = [] indX = 0 size = 0 if type(matrix) is list: if type(div) not in {int, float}: raise TypeError("div must be a number") if div == 0: raise ZeroDivisionError("division by zero") for X in matrix: if size == 0: size = len(X) elif size is not len(X): raise TypeError("Each row of the matrix " + "must have the same size") if tperror == 1: break if type(X) is list: result.append([]) for num in X: if type(num) in (int, float): result[indX].append(round(num / div, 2)) else: tperror = 1 break indX += 1 else: tperror = 1 else: tperror = 1 if tperror == 1 or len(matrix) == 0: raise TypeError("matrix must be a matrix" + " (list of lists) of integers/floats") return (result)
def quote(s): """Ensure that any string S with white space is enclosed in quotes.""" if isinstance(s, str): if " " in s or len(s.split()) > 1: start, end = s[0], s[-1] if start != end or start not in ('"', "'"): q1s, q1d, q3s, q3d = "'", '"', 3 * "'", 3 * '"' if q1d not in s: s = q1d + s + q1d elif q1s not in s: s = q1s + s + q1s elif q3d not in s: s = q3d + s + q3d elif q3s not in s: s = q3s + s + q3s return s
def cyclic_pattern(maxlen, n = 3): """Generate the De Bruijn Sequence (a cyclic pattern) up to `maxlen` characters and subsequences of length `n`. Modified from github.com/longld/peda/. """ charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" k = len(charset) a = [0] * k * n sequence = [] def db(t, p): if len(sequence) == maxlen: return if t > n: if n % p == 0: for j in range(1, p + 1): sequence.append(charset[a[j]]) if len(sequence) == maxlen: return else: a[t] = a[t - p] db(t + 1, p) for j in range(a[t - p] + 1, k): a[t] = j db(t + 1, t) db(1,1) return ''.join(sequence)
def sequence(value): """Return tuple containing value if value is not a sequence. >>> sequence(1) (1,) >>> sequence([1]) [1] """ try: len(value) return value except TypeError: return (value,)
def transformed_name(key: str) -> str: """Generate the name of the transformed feature from original name.""" return f"{key}_xf"
def calc_minutes(hhmm): """Convert 'HH:MM' to minutes""" return int(hhmm[:2]) * 60 + int(hhmm[3:])
def map_wrapper(x): """[summary] Args: x ([type]): [description] Returns: [type]: [description] """ return x[0](*(x[1:]))
def _obj2dict(obj): """ Convert plain object to dictionary (for json dump) """ d = {} for attr in dir(obj): if not attr.startswith('__'): d[attr] = getattr(obj, attr) return d
def formatHex(data, delimiter = " ", group_size = 2): """ formatHex(data, delimiter = " ", group_size = 2): Returns a nice hex version of a string data - The string to turn into hex values delimiter - The delimter between hex values group_size - How many characters do we want in a group? """ if not isinstance(data, bytes): hex = bytearray(data, "iso8859-1").hex() else: hex = data.hex() retval = delimiter.join(hex[i:i + group_size] for i in range(0, len(hex), group_size)) return(retval)
def _compute_scale(dimension, spread, special_scale): """See BFaS; p. 83. Parameters ---------- dimension: int Spatial dimensionality of state space model spread: float Spread of sigma points around mean (1; alpha) special_scale: float Spread of sigma points around mean (2; kappa) Returns ------- float Scaling parameter for unscented transform """ return spread ** 2 * (dimension + special_scale) - dimension
def fmatch(string, match): """Test the forward part of string matches another string or not. """ assert len(string) >= len(match) return string[:len(match)] == match
def extract_capa_units(string): """ Takes a string and returns a list of floats representing the string given. Temporary capacity unit model. Usage:: test_string = 'mAh/g' end_value = extract_value(test_string) print(end_value) # "Gram^(-1.0) Hour^(1.0) MilliAmpere^(1.0)" :param str string: A representation of the units as a string :returns: The unit model :rtype: string """ if string == "Ah/kg" or string == "Ahkg-1": return "Ampere^(1.0) Hour^(1.0) KiloGram^(-1.0)" elif string == "Ah/g" or string == "Ahg-1": return "Ampere^(1.0) Gram^(-1.0) Hour^(1.0)" elif string == "mAh/kg" or string == "mAhkg-1": return "Hour^(1.0) KiloGram^(-1.0) MilliAmpere^(1.0)" else: return "Gram^(-1.0) Hour^(1.0) MilliAmpere^(1.0)"
def clamp(value: float, minimum: float, maximum: float) -> float: """Clamp a floating point value within a min,max range""" return min(maximum, max(minimum, value))
def list_to_choices(l, sort=True): """Converts a list of strings to the proper PyInquirer 'choice' format Args: l (list): a list of str values sort (bool, optional): Defaults to True. Whether or not the choices should be sorted alphabetically. Returns: list: a list of dicts in questionary format """ if sort: l = sorted(l) choices = [] for item in l: choices.append({"name": item}) return choices
def avp_from_rhmax(svp_temperature_min, relative_humidity_max): """ Estimate actual vapour pressure (*e*a) from saturation vapour pressure at daily minimum temperature and maximum relative humidity Based on FAO equation 18 in Allen et al (1998). :param svp_temperature_min: Saturation vapour pressure at daily minimum temperature [kPa]. Can be estimated using ``svp_from_t()``. :param relative_humidity_max: Maximum relative humidity [%] :return: Actual vapour pressure [kPa] :rtype: float """ return svp_temperature_min * (relative_humidity_max / 100.0)
def first(iterable): """Returns the first item of 'iterable' """ try: return next(iter(iterable)) except StopIteration: return None
def pad_dscrp(in_str, out_len=67, pad_char='-'): """Pad DESCRIP with dashes until required length is met. Parameters ---------- in_str : string String to pad. out_len : int, optional The required length. CDBS default is 67 char. pad_char : char, optional Char to pad with. CDBS default is '-'. Returns ------- out_str : string Padded string. """ sz_str = len(in_str) if sz_str > out_len: # truncate out_str = in_str[:out_len] elif sz_str < out_len: # pad out_str = in_str + pad_char * (out_len - sz_str) else: # no change out_str = in_str return out_str
def brighten_everything(output_dict, light_profile_mag, bands): """ Brighten everything in a light profile by a given number of mags. Args: output_dict (dict): flat dictionary being used to simulate images light_profile_mag (str): light profile id to be recolored + '-' + mags to brighten. E.g. 'LIGHT_PROFILE_1-2.5' bands (str): comma-separated string of bands used Returns: output_dict: the same dictionary with some overwritten values """ light_profile = light_profile_mag.split('-')[0] mag = float(light_profile_mag.split('-')[1]) for band, sim_dict in output_dict.items(): for k in sim_dict.keys(): if k.find(light_profile + '-magnitude') != -1: output_dict[band][k] = output_dict[band][k] - mag return output_dict
def calculatePoint(listName): """ Point system used to determine wether a card has moved up or down Args: cardName (STR): Name of the list that the card came from Returns: [type]: [description] """ if listName in ["Backlog", "To Do"]: return 1 elif listName in ["In Progress"]: return 2 elif listName in ["Review/QA", "Review", "Review/Editing"]: return 3 elif listName in ["Done" , "Ready for Implementation"]: return 4
def phi_function(n): """ generates a Collatz sequence given a starting number""" result = [n] while n > 1: if n % 2 == 0: n = n / 2 else: n = 3 * n + 1 result.append(n) return result # return len(result)
def sgd_updates(params, grads, stepsizes): """Return a list of (pairs) that can be used as updates in theano.function to implement stochastic gradient descent. :param params: variables to adjust in order to minimize some cost :type params: a list of variables (theano.function will require shared variables) :param grads: the gradient on each param (with respect to some cost) :type grads: list of theano expressions :param stepsizes: step by this amount times the negative gradient on each iteration :type stepsizes: [symbolic] scalar or list of one [symbolic] scalar per param """ try: iter(stepsizes) except Exception: stepsizes = [stepsizes for p in params] if len(params) != len(grads): raise ValueError('params and grads have different lens') updates = [(p, p - step * gp) for (step, p, gp) in zip(stepsizes, params, grads)] return updates
def text_or_default(element, selector, default=None): """Same as one_or_default, except it returns stripped text contents of the found element """ try: return element.select_one(selector).get_text().strip() except Exception as e: return default
def is_done(value): """ Helper function for deciding if value is sign of successfull update's procession. :param value: value to interpret :returns: True if value is None or equals to "DONE" otherwise False """ return value is None or value == "DONE"
def _remove_prefix(path): """Remove the web/ or build/ prefix of a pdfjs-file-path. Args: path: Path as string where the prefix should be stripped off. """ prefixes = {'web/', 'build/'} if any(path.startswith(prefix) for prefix in prefixes): return path.split('/', maxsplit=1)[1] # Return the unchanged path if no prefix is found return path
def x(n): """ Args: n: Returns: """ if n > 0: return n-1 return 0
def expand_dups(hdr_tuples): """ Given a list of header tuples, unpacks multiple null separated values for the same header name. """ out_tuples = list() for (n, v) in hdr_tuples: for val in v.split('\x00'): if len(val) > 0: out_tuples.append((n, val)) return out_tuples
def count_equal_from_left(original: list, new: list) -> int: """ Count the number of equal elements starting from the element with index 0. """ for index, (e1, e2) in enumerate(zip(original, new)): if e1 != e2: return index return min(len(original), len(new))
def rivers_with_station(stations): """Given a list of stations, return a alphabetically sorted set of rivers with at least one monitoring station""" river_set = set() for station in stations: river_set.add(station.river) river_set = sorted(river_set) return river_set
def int_converter(value): """To deal with Courtney CTD codes""" return int(float(value.split(":")[-1].strip()))
def Data(url,data): """ Check url and data path """ if url.endswith('/') and data.startswith('/'): return url[:-1] + "?" + data[1:] if not url.endswith('/') and data.startswith('/'): return url + "?" + data[1:] if url.endswith('/') and not data.startswith('/'): return url[:-1] + "?" + data else: return url + "?" + data
def merge_dicts(*dict_args): """ Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts. Backwards compatible function; Python 3.5+ equivalent of foo = {**x, **y, **z} """ result = {} for dictionary in dict_args: result.update(dictionary) return result
def get_tokens_list_from_column_list(column_name_list: list, delimiter: str = '!!') -> list: """Function that returns list of tokens present in the list of column names. Args: column_name_list: The list of column name strings. delimiter: delimiter seperating tokens within single column name string. Returns: A list of tokens present in the list of column names. """ tokens = [] for column_name in column_name_list: for tok in column_name.split(delimiter): if tok not in tokens: tokens.append(tok) return tokens
def compute_expected_salary(salary_from, salary_to, **kwargs): """Compute and return expected salary. Expected salary compute using the "from" & "to" salary fields of the vacancy. Giving "from" and "to," fields, calculate the expected salary as an average. Giving only "from", multiply by 1.2, else if only "to", multiply by 0.8. If wanted currency doesn't mach with currency of the vacancy, return None. Args: salary_from (number): minimum possible salary salary_to (number): maximum possible salary Returns: expected_salary (number): calculated expected salary """ if salary_from and salary_to: expected_salary = (salary_from + salary_to) / 2 return expected_salary elif salary_from and not salary_to: expected_salary = salary_from * 1.2 elif salary_to and not salary_from: expected_salary = salary_to * 0.8 else: expected_salary = None return expected_salary
def list_duplicates_of(seq, item): """ Predicts the indexes of duplicate elements inside a list args: -seq - List containing repeated elements -item - Repeated element returns: A list containing the index numbers of the duplicate elements inside the list, 'seq' """ start_at = -1 locs = [] while True: try: loc = seq.index(item, start_at+1) except ValueError: break else: locs.append(loc) start_at = loc return locs
def binary_search(lo, hi, condition): """Binary search.""" # time complexity: O(log N) # space complexity: O(1) # dep: condition() # keep looping as long as the substring exists while lo <= hi: mid = (lo + hi) // 2 # the int division result = condition(mid) if result == 'found': return mid elif result == 'left': hi = mid - 1 # move `hi` (thus next `mid`) to the left elif result == 'right': lo = mid + 1 # move to the right # if nothing is returned, nothing is found return -1
def solution(array): """ Finds the number of combinations (ai, aj), given: - ai == 0 - aj == 1 - j > i Time Complexity: O(n), as we go through the array only once (in reverse order) Space Complexity O(1), as we store three variables and create one iterator """ result = 0 count = 0 # We iterate over array in reverse order to reuse the counter of 1s for i in range(len(array) - 1, -1, -1): if array[i] == 1: count += 1 else: if result + count > 1000000000: return -1 # We never reset "count", as we need to sum the number of all 1s after each 0 result += count return result
def comp (a, b): """compare two arrays""" if len(a) != len(b): return False for e in zip(a, b): if e[0] != e[1]: return False return True
def parse_STATS_header(header): """ Extract the header from a binary STATS data file. This extracts the STATS binary file header information into variables with meaningful names. It also converts year and day_of_year to seconds at midnight since the epoch used by UNIX systems. @param header : string of binary data @return: tuple (spcid, vsrid, chanid, bps, srate, errflg, year, doy, sec, freq, orate,nsubchan) """ (spcid, # 1) station id - 10, 40, 60, 21 vsrid, # 2) vsr1a, vsr1b ... chanid, # 3) subchannel id 0,1,2,3 bps, # 4) number of bits per sample - 1, 2, 4, 8, or 16 srate, # 5) number of samples per second in samples per second errflg, # 6) hardware error flag, dma error or num_samples # error, 0 ==> no errors year, # 7) time tag - year doy, # 8) time tag - day of year sec, # 9) time tag - second of day freq, # 10) frequency in Hz orate, # 11) number of statistics samples per second nsubchan # 12) number of output sub chans ) = header return spcid, vsrid, chanid, bps, srate, errflg, year, doy, sec, freq, \ orate,nsubchan
def _create_partial_storm_id(previous_numeric_id): """Creates partial (primary or secondary) storm ID. :param previous_numeric_id: Integer ID for previous storm. :return: string_id: String ID for new storm. :return: numeric_id: Integer ID for new storm. """ numeric_id = previous_numeric_id + 1 return '{0:d}'.format(numeric_id), numeric_id
def read_file(filename): """ Read a file, and return its contents. """ program = None try: with open(filename, 'r') as f: program = f.read() return program except (IOError, OSError) as e: print("Unable to read file: {}".format(e)) return None
def capitalize(txt: str) -> str: """Trim, then turn only the first character into upper case. This function can be used as a colander preparer. """ if txt is None or ( not isinstance(txt, str) and repr(txt) == "<colander.null>" ): return txt txt = str(txt).strip() if txt == "": return txt val = txt[0].upper() if len(txt) > 1: val += txt[1:] return val