content
stringlengths
42
6.51k
def mk_eqv_expr(expr1, expr2): """ returns an or expression of the form (EXPR1 <=> EXPR2) where EXPR1 and EXPR2 are expressions """ return {"type" : "eqv" , "expr1" : expr1 , "expr2" : expr2 }
def get_zk_path(config_file_path): """Get zk path based upon config file path. e.g. '/var/config/config.manageddata.spam.domain_hidelist' -> '/config/manageddata/spam/domain_hidelist' """ return '/' + config_file_path.split('/')[-1].replace('.', '/')
def reconstruct_by_ids(raw_dct, key, reference_list, default_dct): """ Filling missing values in the dict read by raw_read_file. :param raw_dct: initial dict :param key: key with indexes in the raw_dct :param reference_list: reference list of indexes containing all values :param default_dct: dict with default values for columns from raw_dct that will be filled for missing indexes :return: """ ret_dct = {k: [] for k in raw_dct.keys()} ref_dct = {k: i for i, k in enumerate(raw_dct[key])} keys = [x for x in raw_dct.keys() if x != key] for i in reference_list: try: idx = ref_dct[i] for k in keys: ret_dct[k].append(raw_dct[k][idx]) except Exception as e: for k in keys: ret_dct[k].append(default_dct[k]) ret_dct[key].append(i) return ret_dct
def minhash_lsh_probability(s: float, bands: int, rows: int) -> float: """Probability of Minhash LSH returning item with similarity s""" return 1 - (1 - s ** rows) ** bands
def _padding(length): """ Figure out how much padding is required to pad 'length' bits up to a round number of bytes. e.g. 23 would need padding up to 24 (3 bytes) -> returns 1 :param length: the length of a bit array :return: the number of bits needed to pad the array to a round number of bytes """ if length % 8 != 0: floor = length // 8 return ((floor + 1) * 8) - length return 0
def dict2argstring(argString): """Converts an argString dict into a string otherwise returns the string unchanged :Parameters: argString : str | dict argument string to pass to job - if str, will be passed as-is else if dict will be converted to compatible string :return: an argString :rtype: str """ if isinstance(argString, dict): return ' '.join(['-' + str(k) + ' ' + str(v) for k, v in argString.items()]) else: return argString
def check_permutations(s_one, s_two): """ Question 2: Given two strings, write a method to decide if one is a permutation of the other. """ if len(s_one) != len(s_two): return False h_table = {} for index, char in enumerate(s_two): h_table[char] = index for char in set(s_one): if char not in list(h_table.keys()): return False del h_table[char] return True
def get_tracking_sort_by_urls(direction, sort_by): """ Args: direction - string, either 'asc' or 'desc' sort_by - column name to sort by Returns: dict with keys for name and value is the url """ urls = {} base = '/tracking?sort={}&direction={}' urls['date'] = base.format('date', 'desc') urls['name'] = base.format('name', 'desc') urls['vac'] = base.format('vac', 'desc') # flip the direction (for currently selected sorting column) new_direction = 'asc' if direction == 'desc' else 'desc' urls[sort_by] = base.format(sort_by, new_direction) return urls
def check_config(H, P, N, O, C): """ Checks if config data format is correct """ if H != 'irc.twitch.tv': return False if not isinstance(P, int): return False if P != 6697: return False if not isinstance(N, str): return False if not isinstance(O, str): return False if O[:6] != 'oauth:': return False if C[0] != '#': return False return True
def shunt(infix): """Function which returns the infix expression in postfix""" # Convert input input to a stack ish list infix = list(infix)[::-1] # Operator Stack Output list. opers , postfix = [] ,[] # Operator precedence prec = {'*': 100 , '.': 80, '|': 60, ')': 40 , '(':20} # Loop through the input one character at a time. while infix: # Pop a character from the input c=infix.pop() # Decide what to do based on the character. if c=='(': # Push an open bracket to the opers stack. opers.append(c) elif c==')': # Pop the operators stack until you find an (. while opers[-1] != '(': postfix.append(opers.pop()) # Get rid of the '('. opers.pop() elif c in prec: # Push any operators on the opers stack with higher prec to the output. while opers and prec[c] < prec[opers[-1]]: postfix.append(opers.pop()) # Push c to the operator stack. opers.append(c) else: # Typicallu , we just push the character to the output. postfix.append(c) while opers: postfix.append(opers.pop()) return ''.join(postfix)
def filter_entity(entity_ref): """Filter out private items in an entity dict. :param entity_ref: the entity dictionary. The 'dn' field will be removed. 'dn' is used in LDAP, but should not be returned to the user. This value may be modified. :returns: entity_ref """ if entity_ref: entity_ref.pop('dn', None) return entity_ref
def expmod(b, e, m): """ b^e mod m """ if e == 0: return 1 t = expmod(b, e / 2, m)**2 % m if e & 1: t = (t * b) % m return t
def get_present_types(robots): """Get unique set of types present in given list""" return {type_char for robot in robots for type_char in robot.type_chars}
def parse_csv_data(csv_filename): """ This function takes a csv file and returns the data in a list :param csv_filename: the name of the csv file to be read :return: the data in a list format """ csv_data = [] f = open(csv_filename, 'r') for line in f.readlines(): splits = [] for x in line.split(','): splits.append(x) csv_data.append(splits) return csv_data
def set_bit(value, index, new_bit): """ Set the index'th bit of value to new_bit, and return the new value. :param value: The integer to set the new_bit in :type value: int :param index: 0-based index :param new_bit: New value the bit shall have (0 or 1) :return: Changed value :rtype: int """ mask = 1 << index value &= ~mask if new_bit: value |= mask return value
def fetch(addr=None, heap=None): """Symbolic accessor for the fetch command""" return '@', addr, heap
def _is_kanji(char): """ Check if given character is a Kanji. """ return ord("\u4e00") < ord(char) < ord("\u9fff")
def _has_callable(type, name) -> bool: """Determine if `type` has a callable attribute with the given name.""" return hasattr(type, name) and callable(getattr(type, name))
def dehumanize_time(time): """Convert a human readable time in 24h format to what the database needs. Args: time::String - The time to convert. Returns: _::Int - The converted time. """ if time[3:] == '15': return int(time[:2] + '25') if time[3:] == '30': return int(time[:2] + '50') if time[3:] == '45': return int(time[:2] + '75') if time[3:] == '50': return int(time[:2]+time[3:])+50 return int(time[:2] + '00')
def valuefy(strings, type_cast=None): """Return a list of value, type casted by type_cast list Args: strings (str): A string with value seperated by '_' type_cast (List[types]): A list with type for each elements Returns: List[any]: A list of values typecasted by type_cast array elements. If type_cast is None, all elements are type casted to int. """ vals_string = strings.split('_') if type_cast is None: type_cast = [int]*len(vals_string) assert len(vals_string) == len(type_cast) return [t(e) for e, t in zip(vals_string, type_cast)]
def _find_shortest_indentation(lines): """Return most shortest indentation.""" assert not isinstance(lines, str) indentation = None for line in lines: if line.strip(): non_whitespace_index = len(line) - len(line.lstrip()) _indent = line[:non_whitespace_index] if indentation is None or len(_indent) < len(indentation): indentation = _indent return indentation or ''
def basesStr(bases): """Pretty print list of bases""" return ', '.join([str(base) for base in bases])
def strip_unexecutable(lines): """Remove all code that we can't execute""" valid = [] for l in lines: if l.startswith("get_ipython"): continue valid.append(l) return valid
def pure_literal(ast_set): """ Performs pure literal rule on list format CNF :param: Result of cnf_as_disjunction_lists :return: CNF with clauses eliminated >>> pure_literal([['a']]) [] >>> pure_literal([[(Op.NOT, 'a')], ['x', (Op.NOT, 'y'), 'b'], ['z'], ['c', 'd']]) [] >>> pure_literal([[(Op.NOT, 'a')], ['a', (Op.NOT, 'c')]]) [[(Op.NOT, 'a')]] >>> pure_literal([['a'], [(Op.NOT, 'a')], ['b']]) [['a'], [(Op.NOT, 'a')]] >>> pure_literal([[(Op.NOT, 'a')], ['a', (Op.NOT, 'c')], ['c']]) [[(Op.NOT, 'a')], ['a', (Op.NOT, 'c')], ['c']] >>> pure_literal([[(Op.NOT, 'a')], [(Op.NOT, 'b')], ['a', 'b'], ['c']]) [[(Op.NOT, 'a')], [(Op.NOT, 'b')], ['a', 'b']] >>> pure_literal([['a', 'b', (Op.NOT, 'c'), (Op.NOT, 'b')], ['d', (Op.NOT, 'e'), (Op.NOT, 'b'), 'e'], [(Op.NOT, 'a'), (Op.NOT, 'b'), 'c']]) [['a', 'b', (Op.NOT, 'c'), (Op.NOT, 'b')], [(Op.NOT, 'a'), (Op.NOT, 'b'), 'c']] """ positive_variables = [] negative_variables = [] new_ast = [] for expression in ast_set: for segment in expression: # Case for NOTs if isinstance(segment, tuple): negative_variables.append(segment[1]) # Case for lone variables else: positive_variables.append(segment) positive_only = set(positive_variables) - set(negative_variables) negative_only = set(negative_variables) - set(positive_variables) for expression in ast_set: elim_clause = False for segment in expression: if isinstance(segment, tuple) and segment[1] in negative_only: elim_clause = True elif segment in positive_only: elim_clause = True if not elim_clause: new_ast.append(expression) return new_ast
def _dict_path(d, *steps): """Traverses throuth a dict of dicts. Returns always a list. If the object to return is not a list, it's encapsulated in one. If any of the path steps does not exist, an empty list is returned. """ x = d for key in steps: try: x = x[key] except KeyError: return [] if not isinstance(x, list): x = [x] return x
def isRepeatedNumber(string): """ Returns True if any value in the list passed as a parameter repeats itself """ for i in string: if string.count(i) > 1: return True
def cut(word, part="www."): """ Where word is a string Removes the section specified by part """ split = word.split(part) truncated = "".join(split) return truncated
def SplitVersion(version): """Splits version number stored in an int. Returns: tuple; (major, minor, revision) """ assert isinstance(version, int) (major, remainder) = divmod(version, 1000000) (minor, revision) = divmod(remainder, 10000) return (major, minor, revision)
def check_any_str(list_to_check, input_string): """Check if any items in a list have a string in them. Parameters ---------- list_to_check : list[str] A list of strings. input_string : str A string to check items in the list. Returns ------- Boolean True or False, depending on whether input_string is found in >= list item. """ return any(input_string in string for string in list_to_check)
def parse_search(data): """ parse search result from tunein """ qr_name = data['head']['title'] search_result = [] search_error = {} if data['head']['status'] == "200": for r in data['body']: if 'type' in r: if r['type'] == 'audio': search_result.append({ 'text': r['text'], 'img': r['image'], 'url': r['URL'] }) elif 'children' in r: search_error = {'text': 'No result'} else: search_error = {'text': r['text']} else: search_error = {'code': data['head']['status']} return qr_name, search_result, search_error
def get_stream_names(streams, type=None): """ extract stream name from xdf stream :param streams: list of dictionnaries xdf streams to parse :param type: string type of stream, eg. 'Signal' or 'Markers' :return: list list of stream name contained in streams """ if type is None: return [stream["info"]["name"][0] for stream in streams] else: return [ stream["info"]["name"][0] for stream in streams if stream["info"]["type"][0] == type ]
def dict2opts( dct, doubledash=True, change_underscores=True, assign_sign='='): """ dictionary to options """ opts = [] for kw in dct.keys(): # use long or short options? dash = '--' if doubledash else '-' # remove first underscore if it is present opt = kw[1:] if kw[0] == '_' else kw if change_underscores: # change remaining underscores to single dash opt = opt.replace('_', '-') if not type(dct[kw]) == bool: opts.append('{0}{1}{2}{3}'.format(dash, opt, assign_sign, dct[kw])) elif dct[kw] is True: opts.append('{0}{1}'.format(dash, opt)) return opts
def count(n, target): """Count # of times non-None target exists in linked list, n.""" ct = 0 if n is None: return 0 if n.value == target: ct = 1 return ct + count(n.next, target)
def repeating_key(bs, key): """ Implementation of repeating-key XOR. """ # XOR each byte of the byte array with its appropriate key byte. return bytearray([bs[i] ^ key[i%len(key)] for i in range(len(bs))])
def z_fn_nu(nu, f, p, pv0, e, B, R, eta): """ Steady-state solution for z as a fn of nu, where nu is calculated at steady-state using cubsol3 """ return (B*(1 - e*nu)*p - p/pv0)/(1 + B*(1 - e*nu)*p - p/pv0)
def repr(obj): """ :func:`repr` is a function for representing of object using object's name and object's properties """ properties = {k: v for k, v in vars(obj).items()} return f"{type(obj).__name__}({properties})"
def get_expression(date): """Returns a date expression for a date object. Concatenates start and end dates if no date expression exists. :param dict date: an ArchivesSpace date :returns: date expression for the date object. :rtype: str """ try: expression = date["expression"] except KeyError: if date.get("end"): expression = "{0}-{1}".format(date["begin"], date["end"]) else: expression = date["begin"] return expression
def pad_sentences(sentences_indexed, sequence_length): """ Pad setences to same length """ sentences_padded = [] for sentence in sentences_indexed: num_padding = sequence_length - len(sentence) sentences_padded.append(sentence[:sequence_length - 1] + [0] * max(num_padding, 1)) return sentences_padded
def event_summary(event_info, summary_keys=['host', 'task', 'role', 'event']): """ Provide a quick overview of the event code_data :param event_info: dict/json of a job event :param summary_keys: list of fields that represent a summary of the event the event data is checked at the outer level, and in the event_data namespace :return: Returns summary metadata for the event """ if summary_keys: base = {k: event_info[k] for k in summary_keys if k in event_info} event_data = {k: event_info['event_data'][k] for k in summary_keys if k in event_info.get('event_data')} # python3.5 an above idiom # return {**base, **event_data} merged = base.copy() merged.update(event_data) return merged else: return event_info
def get_stereo_cymbal2_note(instrument=24, start=0.0, duration=0.5, amplitude=30000, pitch=8.00, pan=0.7, fc=5333, q=40.0, otamp=0.5, otfqc=1.5, otq=0.2, mix=0.2, hit=None): """ ; Cymbal ; Sta Dur Amp Pitch Pan Fc Q OTAmp OTFqc OTQ Mix i24 0.0 0.25 30000 8.00 0.7 5333 40.0 0.5 1.5 0.2 .2 """ return "i%s %s %s %s %s %s %s %s %s %s %s %s" % \ (instrument, start, duration, amplitude, pitch, pan, fc, q, otamp, otfqc, otq, mix)
def evaluate_sensitivity(tp: int, fn: int) -> float: """Sensitivity, aka Recall, aka True Positive Rate (TPR). $TPR=\dfrac{TP}{TP + FN}$ Args: tp: True Positives fn: False Negatives """ try: return tp / (tp + fn) except ZeroDivisionError: return 0.0
def binary_xor(a: int, b: int): """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both input must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both input must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) )
def in_3d_box(box, coords): """ Check if point is in a box Args: box (tuple): ((x0, x1), (y0, y1), (z0, z1)). coords (tuple): (x, y, z). Returns bool """ cx = coords[0] >= box[0][0] and coords[0] <= box[0][1] cy = coords[1] >= box[1][0] and coords[1] <= box[1][1] cz = coords[2] >= box[2][0] and coords[2] <= box[2][1] return cx and cy and cz
def get_distance_by_dir(inputD, genom_loc, intern_loc, Dhit): """Limits the hit by a distance window depending on peak's position relative-to-feature """ [D_upstr, D_downstr] = inputD # D_upstr = D_downstr when len(input_D) = 1 if genom_loc == "upstream" or genom_loc == "overlapStart": return Dhit <= D_upstr if genom_loc == "downstream" or genom_loc == "overlapEnd": return Dhit <= D_downstr if any(intern_loc): best_dist = map(lambda l: Dhit <= D_upstr if l == "upstream" else Dhit <= D_downstr, intern_loc) # when 3 positions given: any Dhit inside limit-> hit accepted // if 1 # given any(True) =True return any(best_dist)
def good_fit_step(x, y): """Returns a step interval to use when selecting keys. The step will ensure that we create no more than num_shards. """ step, remainder = divmod(x, y) if remainder: step = (x + remainder) // y if step == 0: step = 1 return step
def get_vg_obj_name(obj): """ Gets the name of an object from the VG dataset. This is necessary because objects are inconsistent-- some have 'name' and some have 'names'. :( Args: obj: an object from the VG dataset Returns string containing the name of the object """ try: name = obj["name"] except KeyError: name = obj["names"][0] return name
def sort_employees_by_salary(employee_list): """ Returns a new employee list, sorted by low to high salary then last_name """ employee_list.sort(key=lambda employee: (employee.last_name, employee.job.salary)) return employee_list
def common_start(*args): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for s in zip(*args): if len(set(s)) < len(args): yield s[0] else: return out = "".join(_iter()).strip() result = [s for s in args if not s.startswith(out)] result.insert(0, out) return ', '.join(result)
def not_none(**kwargs): """Confirms that at least one of the items is not None. Parameters ---------- **kwargs : dict of any, optional Items of arbitrary type. Returns ------- dict of any Items that are not None. Raises ------- ValueError If all of the items are None. """ valid_items = {} all_none = True for key, value in kwargs.items(): if value is not None: all_none = False valid_items[key] = value if all_none: raise ValueError('At least one of {{{}}} should be not None!'.format( ', '.join(kwargs))) return valid_items
def agreement_type(value): """Display agreement_type""" value = value.strip() return { 'OG': 'Original general', 'OS': 'Original specific', }.get(value, 'Unknown')
def is_start_byte(b: int) -> bool: """Check if b is a start character byte in utf8 See https://en.wikipedia.org/wiki/UTF-8 for encoding details Args: b (int): a utf8 byte Returns: bool: whether or not b is a valid starting byte """ # a non-start char has encoding 10xxxxxx return (b >> 6) != 2
def clear_timestamp(x): """Replaces (recursively) values of all keys named 'timestamp'.""" if isinstance(x, dict): if 'timestamp' in x: x['timestamp'] = 'cleared' for v in x.values(): clear_timestamp(v) elif isinstance(x, list) or isinstance(x, tuple): for v in x: clear_timestamp(v) return x
def _swap_list_items(arr, i1, i2) -> list: """Swap position of two items in a list. Parameters ---------- arr : list in which to swap elements i1 : element 1 in list i2 : element 2 in list Returns ------- list copy of list with swapped elements """ i = list(arr).copy() a, b = i.index(i1), i.index(i2) i[b], i[a] = i[a], i[b] return i
def _UTMLetterDesignator(Lat): """ This routine determines the correct UTM letter designator for the given latitude returns 'Z' if latitude is outside the UTM limits of 84N to 80S Written by Chuck Gantz- chuck.gantz@globalstar.com """ if 84 >= Lat >= 72: return 'X' elif 72 > Lat >= 64: return 'W' elif 64 > Lat >= 56: return 'V' elif 56 > Lat >= 48: return 'U' elif 48 > Lat >= 40: return 'T' elif 40 > Lat >= 32: return 'S' elif 32 > Lat >= 24: return 'R' elif 24 > Lat >= 16: return 'Q' elif 16 > Lat >= 8: return 'P' elif 8 > Lat >= 0: return 'N' elif 0 > Lat >= -8: return 'M' elif -8 > Lat >= -16: return 'L' elif -16 > Lat >= -24: return 'K' elif -24 > Lat >= -32: return 'J' elif -32 > Lat >= -40: return 'H' elif -40 > Lat >= -48: return 'G' elif -48 > Lat >= -56: return 'F' elif -56 > Lat >= -64: return 'E' elif -64 > Lat >= -72: return 'D' elif -72 > Lat >= -80: return 'C' else: return 'Z' # if the Latitude is outside the UTM limits
def check_number_threads(numThreads): """Checks whether or not the requested number of threads has a valid value. Parameters ---------- numThreads : int or str The requested number of threads, should either be a strictly positive integer or "max" or None Returns ------- numThreads : int Corrected number of threads """ if (numThreads is None) or (isinstance(numThreads, str) and numThreads.lower() == 'max'): return -1 if (not isinstance(numThreads, int)) or numThreads < 1: raise ValueError('numThreads should either be "max" or a strictly positive integer') return numThreads
def redondeo(coordenadas, base=1/12): """ Devuelve las coordenadas pasadas redondeadas Parametros: coordenadas -- lista de latitud y longitud base -- base del redondeo """ return base * round(coordenadas/base)
def isnointeger(number): """ This method decides if a given floating point number is an integer or not -- so only 0s after the decimal point. For example 1.0 is an integer 1.0002 is not.""" return number % 1 != 0
def formatFilename( name ): """ replace special characters in filename and make lowercase """ return name.\ replace( " ", "" ).\ replace( ".", "_" ).\ replace( "-", "_" ).\ replace( "/", "_" ).\ replace( "(", "_" ).\ replace( ")", "_" ).\ lower()
def cat_arg_and_value(arg_name, value): """Concatenate a command line argument and its value This function returns ``arg_name`` and ``value concatenated in the best possible way for a command line execution, namely: - if arg_name starts with `--` (e.g. `--arg`): `arg_name=value` is returned (i.e. `--arg=val`) - if arg_name starts with `-` (e.g. `-a`): `arg_name value` is returned (i.e. `-a val`) - if arg_name does not start with `-` and it is a long option (e.g. `arg`): `--arg_name=value` (i.e., `--arg=val`) - if arg_name does not start with `-` and it is a short option (e.g. `a`): `-arg_name=value` (i.e., `-a val`) :param arg_name: the command line argument name :type arg_name: str :param value: the command line argument value :type value: str """ if arg_name.startswith("--"): return "=".join((arg_name, str(value))) elif arg_name.startswith("-"): return " ".join((arg_name, str(value))) elif len(arg_name) == 1: return " ".join(("-" + arg_name, str(value))) else: return "=".join(("--" + arg_name, str(value)))
def python_to_swagger_types(python_type): """ :param python_type: """ switcher = { "str": "string", "int": "integer", "float": "number", "complex": "number", "datetime.datetime": "string", "datetime": "string", "dict": "object", "bool": "boolean", } return switcher.get(python_type, "string")
def readable(filename: str) -> bool: """Conditional method to check if the given file (via filename) can be opened in this thread. :param filename: name of the file :type filename: str :return: true if file can be read, otherwise false :rtype: bool """ try: handler = open(filename, 'r') # If the file is closed for some reason, we don't want to # attempt reading it. result = handler.closed handler.close() return not result except IOError: #* File probably doesn't exist or not in given directory. return False
def strip_yaml_extension(filename): """ remove ending '.yaml' in *filename* """ return filename[:-5] if filename.lower().endswith('.yaml') else filename
def build_s3_path(s3_filepath, unit, category, filename): """ Input: maria-quiteria/files/tcmbapublicconsultation/2020/mensal/12/consulta-publica-12-2020.json Output: s3://dadosabertosdefeira/maria-quiteria/files/tcmbapublicconsultation/2020/mensal/12/<unit>/<category>/<filename> """ prefix = "s3://dadosabertosdefeira/" parts = s3_filepath.split("/") parts.pop() # remove json da lista parts.extend([unit, category, filename]) return f"{prefix}{'/'.join(parts)}"
def apply_func(key_kwargs_, func): """ given some keywords and a function call the function :param key_kwargs_: a tuple of (key, args) to use :param func: function to call :return: the key for this and the value returned from calling the func """ key = key_kwargs_[0] kwargs_ = key_kwargs_[1] val = func(*kwargs_) return key, val
def p_approx ( a, rho, temperature ): """Returns approximate pressure.""" # Original expression given by Groot and Warren, J Chem Phys 107, 4423 (1997), alpha = 0.101 # This is the revised formula due to Liyana-Arachchi, Jamadagni, Elke, Koenig, Siepmann, # J Chem Phys 142, 044902 (2015) import numpy as np c1, c2 = 0.0802, 0.7787 b = [1.705e-8,-2.585e-6,1.556e-4,-4.912e-3,9.755e-2] b2 = np.polyval (b,a) # This is B2/a, eqn (10) of above paper alpha = b2 / ( 1 + rho**3 ) + ( c1*rho**2 ) / ( 1 + c2*rho**2 ) # This is eqn (14) of above paper return rho * temperature + alpha * a * rho**2
def sum_pairs(ints, s): """Pair to sum up to s.""" lookup = {} for n, i in enumerate(ints): lookup.setdefault(i, []).append(n) options = [] for k in lookup: if s - k in lookup: if s - k == k and len(lookup[s - k]) < 2: continue if s - k == k and len(lookup[s - k]) >= 2: options.append( [k, s - k, max(lookup[k])] ) continue options.append( [k, s - k, max(min(lookup[k]), min(lookup[s - k]))] ) print(options) if options: return sorted(min(options, key=lambda x: x[2])[:-1], key=lookup.__getitem__) return None
def stem(word: str) -> str: """Get the stem of a word""" return word.lower().rstrip(",.!:;'-\"").lstrip("'\"")
def represents_int(s): """ A custom Jinja filter function which determines if a string input represents a number""" try: int(s) return True except ValueError: return False
def push_n(int_n): """ Opcode to push some number of bytes. """ assert 1 <= int_n <= 75, "Can't push more than 75 bytes with PUSH(N) in a single byte." n = hex(int_n)[2:] n = n if len(n) == 2 else '0' + n return bytes.fromhex(n)
def expand_cond(cond): """ Change the input SQL condition into a dict. :param cond: the input SQL matching condition :type cond: list or dict :rtype: dict """ conddict = { 'join': [], # list of tuple (type, table, [(var1, var2), ...]) 'where': [], # list of tuple (type, var, const) 'group': [], # list of vars 'having': [], # same as where 'order': [], # tuple (var, is_asc) 'limit': None # None or count or (offset, count) } if isinstance(cond, list): # this is a simple cond conddict['where'] = cond elif 'where' in cond: conddict.update(cond) else: conddict['where'] = [('=', key, value) for key, value in cond.items()] return conddict
def extensions(includes): """Format a list of header files to include.""" return [ "".join([i.split(".")[0], ".h"]) for i in includes if i.split(".")[0] != "types" ]
def validDate(date: str) -> bool: """Return whether a string follows the format of ####-##-##.""" if len(date) == 10: return date[0:4].isnumeric() and date[5:7].isnumeric() and date[8:10].isnumeric() and date[4] == "-" and date[7] == "-" return False
def locToPath(p): """Back compatibility -- handle converting locations into paths. """ if "path" not in p and "location" in p: p["path"] = p["location"].replace("file:", "") return p
def fabclass_2_umax(fab_class): """ Maximum displacement for a given fabrication class acc. to EC3-1-6. Parameters ---------- fab_class : {"fcA", "fcB", "fcC"} """ # Assign imperfection amplitude, u_max acc. to the fabrication class if fab_class is 'fcA': u_max = 0.006 elif fab_class is 'fcB': u_max = 0.010 else: u_max = 0.016 # Return values return u_max
def connect_vec_list(vec_list1, vec_lists2): """ get connected vec lists of two lists """ return (vec_list1 + vec_lists2)
def get_teaching_hours(school_type): """Return the number of teaching hours / day for different school types.""" teaching_hours = { 'primary':4, 'primary_dc':4, 'lower_secondary':6, 'lower_secondary_dc':6, 'upper_secondary':8, 'secondary':8, 'secondary_dc':8 } return teaching_hours[school_type]
def is_int(str_val: str) -> bool: """ Checks whether a string can be converted to int. Parameters ---------- str_val : str A string to be checked. Returns ------- bool True if can be converted to int, otherwise False """ return not (len(str_val) == 0 or any([c not in "0123456789" for c in str_val]))
def isnumeric(s): """ Converts strings into numbers (floats) """ try: x = float(s) return x except ValueError: return float('nan')
def _describe_instance_attribute_response(response, attribute, attr_map): """ Generates a response for a describe instance attribute request. @param response: Response from Cloudstack. @param attribute: Attribute to Describe. @param attr_map: Map of attributes from EC2 to Cloudstack. @return: Response. """ response = { 'template_name_or_list': 'instance_attribute.xml', 'response_type': 'DescribeInstanceAttributeResponse', 'attribute': attribute, 'response': response[attr_map[attribute]], 'id': response['id'] } return response
def comp_float(x, y): """Approximate comparison of floats.""" return abs(x - y) <= 1e-5
def from_epsg(code): """Given an integer code, returns an EPSG-like mapping. Note: the input code is not validated against an EPSG database. """ if int(code) <= 0: raise ValueError("EPSG codes are positive integers") return {'init': "epsg:%s" % code, 'no_defs': True}
def Bayes_runtime(fmin, rt_40): """ Compute runtime of Bayesian PE for a min. freq. fmin given the rt_40 as the runtime when fmin=40 Hz. """ return rt_40 * (fmin / 40.)**(-8./3.)
def bids_dir_to_fsl_dir(bids_dir): """Converts BIDS PhaseEncodingDirection parameters (i,j,k,i-,j-,k-) to FSL direction (x,y,z,x-,y-,z-).""" fsl_dir = bids_dir.lower() if "i" not in fsl_dir and "j" not in fsl_dir and "k" not in fsl_dir: raise ValueError( f"Unknown PhaseEncodingDirection {fsl_dir}: it should be a value in (i, j, k, i-, j-, k-)" ) return fsl_dir.replace("i", "x").replace("j", "y").replace("k", "z")
def isSvnUrl(url): """ this function returns true, if the Url given as parameter is a svn url """ if url.startswith("[svn]"): return True elif "svn:" in url: return True return False
def filter_stories(stories, triggerlist): """ Takes in a list of NewsStory-s. Returns only those stories for whom a trigger in triggerlist fires. """ filtered_stories = [] for story in stories: for trigger in triggerlist: if trigger.evaluate(story): filtered_stories.append(story) break return filtered_stories
def split(sorting_list): """ Divide the unsorted list at midpoint into sublist Returns two sublist - left and right Takes overall O(log n) time """ mid = len(sorting_list) // 2 left = sorting_list[: mid] right = sorting_list[mid:] return left, right
def count_affected_areas(hurricanes): """Find the count of affected areas across all hurricanes and return as a dictionary with the affected areas as keys.""" affected_areas_count = dict() for cane in hurricanes: for area in hurricanes[cane]['Areas Affected']: if area not in affected_areas_count: affected_areas_count[area] = 1 else: affected_areas_count[area] += 1 return affected_areas_count
def SetPageSize(unused_ref, args, request): """Set page size to request.pageSize. Args: unused_ref: unused. args: The argparse namespace. request: The request to modify. Returns: The updated request. """ if hasattr(args, 'page_size') and args.IsSpecified('page_size'): request.pageSize = int(args.page_size) return request
def task10(number: int) -> None: """ Function that take an integer number as string and print the "It is an even number" if the number is even, otherwise print "It is an odd number". Input: number Output: None """ if number % 2 == 0: print("It is an even number") else: print("It is an odd number") return None
def get_features(geojson): """ Helper function to extract features from dictionary. If it doesn't find it, raise a value error with a more informative error message. """ try: features = geojson["features"] except KeyError: raise KeyError(f"{geojson} is an invalid GeoJSON. Not a feature collection") return features
def prime_check(n): """Checks if natural number n is prime. Args: n: integer value > 0. Returns: A boolean, True if n prime and False otherwise. """ assert type(n) is int, "Non int passed" assert n > 0, "No negative values allowed, or zero" if n == 1: return False i = 2 while i*i < n + 1: if n != i and n % i == 0: return False i += 1 return True
def parse_cluster_pubsub_numsub(res, **options): """ Result callback, handles different return types switchable by the `aggregate` flag. """ aggregate = options.get('aggregate', True) if not aggregate: return res numsub_d = {} for _, numsub_tups in res.items(): for channel, numsubbed in numsub_tups: try: numsub_d[channel] += numsubbed except KeyError: numsub_d[channel] = numsubbed ret_numsub = [] for channel, numsub in numsub_d.items(): ret_numsub.append((channel, numsub)) return ret_numsub
def generate_marketplace(queue_size): """ Generates the marketplace :type queue_size: int :param queue_size: the queue size for each producer :return dict :return: a dict representing the markeplace """ marketplace = {"queue_size_per_producer": queue_size} return marketplace
def namestr(obj, namespace): """ called via: >>> a = 'some var' >>> b = namestr(a, globals()) assert b == ['a'] #for test """ return [name for name in namespace if namespace[name] is obj]
def ModelMatch(comp): """ Summary : This functions compares a list to model with typo handling Parameters : comparison list Return : Boolean """ for item in comp: try: item = item.lower() except: continue if item == 'model': return True, item if item == 'pose' or item == 'name': continue char_match = 0 if 'm' in item: char_match += 1 if 'o' in item: char_match += 1 if 'd' in item: char_match += 1 if 'e' in item: char_match += 1 if 'l' in item: char_match += 1 if char_match >= 4: return True, item else: continue return False, None
def dechaffify(chaffy_val, chaff_val = 98127634): """ Dechaffs the given chaffed value. chaff_val must be the same as given to chaffify(). If the value does not seem to be correctly chaffed, raises a ValueError. """ val, chaff = divmod(chaffy_val, chaff_val) if chaff != 0: raise ValueError("Invalid chaff in value") return val
def CONCAT_ARRAYS(*arrays): """ Concatenates arrays to return the concatenated array. See https://docs.mongodb.com/manual/reference/operator/aggregation/concatArrays/ for more details :param arrays: A set of arrays(expressions). :return: Aggregation operator """ return {'$concatArrays': list(arrays)}
def suit_to_color(a): """Red is 1. Black is 0.""" return (a == 'H' or a == 'D')
def apply_pbcs(index: int, boundary: int) -> int: """Applies periodic boundary conditions (PBCs). Args: index (int): Index to apply the PBCs to boundary (int): Length of the boundary Returns: int: Index with PBCs applied to it """ if index < 0: index += boundary elif index >= boundary: index -= boundary return index
def tokenize_char(sent): """ Tokenize a string by splitting on characters. """ return list(sent.lower())