content
stringlengths
42
6.51k
def _max(*args): """Returns the maximum value.""" return max(*args)
def transformedList(L) : """ Creates a list R which is the list L whithout the dices with value 10 cancelled by those with value 1 Parameters ---------- L: int list Decreasing sorted list with values between 1 and 10. """ R = [] for r in L : if r == 10 : ...
def ensure_unicode(x, encoding='ascii'): """ Decode bytes to unicode if necessary. Parameters ---------- obj : bytes or unicode encoding : str, default "ascii" Returns ------- unicode """ if isinstance(x, bytes): return x.decode(encoding) return x
def human_readable_to_bytes(value: int, unit: str) -> int: """ Converts the given value and unit to bytes. As an example, it should convert (8, GB) to 8388608. Even though technically MB means 1000 * 1000, many producers actually mean MiB, which is 1024 * 1024. Even Windows displays as unit GB, eve...
def braced(s): """Wrap the given string in braces, which is awkward with str.format""" return '{' + s + '}'
def get_fields_list(scope, field_value): """List of values to search for; `field_value`, plus possibly variants on it""" if scope in ['congressional_code', 'county_code']: try: # Congressional and county codes are not uniform and contain multiple variables # In the location table...
def CountFalseInList(input_list): """Counts number of falses in the input list.""" num_false = 0 for item in input_list: if not item: num_false += 1 return num_false
def readSat(inString): """Convert a string representing a CNF formula into a Python data structure representing the same formula. Convert a string representing a CNF formula into a Python data structure representing the same formula. The parameter inString must describe a CNF formula in the ASCII f...
def tostring(s): """ Convert the object to string for py2/py3 compat. """ try: s = s.decode() except (UnicodeDecodeError, AttributeError): pass return s
def get_all_names(actions): """ Returns all action names present in the given actions dictionnary.""" assert isinstance(actions, dict) names = set(actions.keys()) return names
def remove_spaces_before_punc(fib_string): """Removes spaces before punctuation. Removes the spaces after blanks and before punctuation (i.e. ___n___ .) that are created by " ".join(fib). Args: fib_string (str): the concatenated fill-in-the-blank with the unwanted spaces. Returns: ...
def _set_default_active_pins( subcategory_id: int, type_id: int, ) -> int: """Set the default number of active pins value. :param subcategory_id: the subcategory ID of the connection with missing defaults. :return: _n_active_pins :rtype: int """ if subcategory_id == 1 and type_id in {1,...
def find_all(input_str: str, search_str: str) -> list: """ Find the index(s) of where `input_str` appears in `search_str` Args: input_str (`str`): Text to search for search_str (`str`): Text to search within Returns: List of start indexes where `input_st...
def segmentImgs(imgs, cap): """ Segments imgs in n sets of maximum <cap> images. :param imgs: Full list of all images :param cap: Maximum number of images per set :return: List containing n sets of images, where n is how many sets of <cap> images can be created. """ if len(imgs) ...
def get_ordered_weather_ids_timestamps(weather_timestamps: dict) -> tuple: """Returns a tuple containing the ordered list of weather IDs and their associated timestamps Arguments: weather_timestamps: the dictionary of weather IDs and their timestamps Return: A tuple containing an ordered tup...
def row_check(board: list) -> bool: """ Check whether colored cells of each row contains numbers from 1 to 9 without repetition >>> row_check(["**** ***.","***1 **.*","** 3*.**","* 4 1.***",\ " .9 5 "," 6 .83 *","3 . 1 **"," .8 2***",". 2 ****"]) True """ count = 0 board_edited =...
def convert_units(input_unit): """ Convert units into CloudWatch understandable units. """ input_unit = input_unit.lower() if input_unit == "s/op": return "Seconds" elif input_unit == "bytes" or input_unit == "byte": return "Bytes" elif input_unit == "op/s": return "C...
def solve(equation, answer): """ Solve equation and check if user is correct or incorrect """ splitted = equation.split('=') left = splitted[0].strip().replace('?', str(answer)).replace('x', '*') right = splitted[1].strip().replace('?', str(answer)).replace('x', '*') try: if right.isdigit(...
def subsets(collection): """ Creates a list of all subsets of the collection provided pre: collection can be a list or a collection of items post: returns a list of all subsets of collection """ collection = list(collection) if not collection: return [[]] tail = subsets(c...
def avg(l): """:param l: list of numbers to be averaged :return: average of numbers in list""" lg = len(l) if lg > 0: return sum(l) / lg else: return sum(l)
def pairs(arr): """Return count of pairs with consecutive nums.""" count = 0 pairs = [arr[i:i + 2] for i in range(0, len(arr), 2)] for pair in pairs: if len(pair) == 2: if abs(pair[0] - pair[1]) == 1: count += 1 return count
def default_cmp(x, y): """ Default comparison function """ if x < y: return -1 elif x > y: return +1 else: return 0
def set(x, y): """Set cursor position.""" return "\033[" + str(y) + ";" + str(x) + "H"
def ParsePointCoordinates(coordinates): """ Parse <coordinates> for a Point Permits a sloppy Point coordinates. Arg: coordinates: lon,lat,alt or lon,lat with spaces allowed Returns: None: if coordinates was not 2 or 3 comma separated numbers (lon,lat): float tuple (lon,lat,alt): float tuple ...
def calculate_recall(tp, n): """ :param tp: int Number of True Positives :param n: int Number of total instances :return: float Recall """ if n == 0: return 0 return tp / n
def addKeysWithoutValueToDict(valDict, keyArray): """This function adds keys from keyArray to valDict in case it does not exist yet, the default value is an empty string >>> addKeysWithoutValueToDict({'a': 'valA', 'b': 'valB'}, ['a', 'b', 'c']) {'a': 'valA', 'b': 'valB', 'c': ''} """ for key in keyArray: ...
def interp_drop(p1, p2, p3, eps): """Computesinterpolation and checks if middle point falls within threshold""" t = p1[1] + (p3[1] - p1[1]) / (p3[0] - p1[0]) * (p2[0] - p1[0]) return abs(t - p2[1]) < eps
def _GetSuccessCountDetails(test_suite_overviews): """Build a string with status count sums for testSuiteOverviews.""" total = 0 skipped = 0 for overview in test_suite_overviews: total += overview.totalCount or 0 skipped += overview.skippedCount or 0 passed = total - skipped if passed: msg = '{p...
def ode_euler(func, x, q, time, dt): """ ODE integration using Euler approximation. Parameters ---------- func : function Function defining the system dynamics. x : (dim_x, ) ndarray Previous system state. q : (dim_q, ) ndarray System (process) noise. time : (...
def jaccard_similariy_index(first, second): """ Returns the jaccard similarity between two strings :param first: first string we are comparing :param second: second string we are comparing :return: how similar the two strings are """ # First, split the sentences into words tokenize_firs...
def computeCap(rent, price, expenses=35): """ rent - annual price price expenses ; 0 to 100 for a rate, otherwise dollar ammount return cap rate [%] """ if expenses<100: return rent*(100-expenses)/100./price * 100 else: return (rent-expenses)/price * 100
def apply(kcycles, element): """ Given a set of kcycles inside variable kcycles, apply would give the result for which element will be change in the process. """ result = element # result defined for aesthetic and debug purposes # Go over the Kcycle elements, applying the ones to the ...
def is_number_tryexcept(s): """ Returns True is string is a number. """ try: float(s) return True except ValueError: return False
def digit_sum(n): """Returns the sum of the digits of n""" a = str(n) dsum = 0 for char in a: dsum += int(char) return(dsum)
def chao1_bias_corrected(observed, singles, doubles): """Calculates bias-corrected chao1 given counts: Eq. 2 in EstimateS manual. Formula: chao1 = S_obs + N_1(N_1-1)/(2*(N_2+1)) where N_1 and N_2 are count of singletons and doubletons respectively. Note: this is the bias-corrected formulat from Chao 1...
def check_program(pred, gt): """Check if the input programs matches""" # ground truth programs have a start token as the first entry for i in range(len(pred)): if pred[i] != gt[i + 1]: return False if pred[i] == 2: break return True
def unrecognized_message(actual_value, unexpected_kind, name): """Return message for unrecognized actual_value of unexpected_kind described by name""" return "Value '{0}' is an unrecognized {1} of '{2}'".format(actual_value, name, unexpected_kind)
def solution(A): # O(N/2) """ Write a function to reverse a list without affecting special characters and without using the built-in function. >>> solution(['a', ',', 'b', '$', 'c']) ['c', ',', 'b', '$', 'a'] >>> solution(['A', 'b', ',', 'c', '...
def mod_powers(pwr, div): """Prints all possible residues when raised to ```pwr``` mod ```div```.""" res = set() for i in range(div): res.add(pow(i, pwr, div)) return res
def dump_report_to_json(report): """ Creates a json variant of the report, used internally. :return: """ return {'id': report["id"], 'urllist_id': report["urllist_id"], 'average_internet_nl_score': report["average_internet_nl_score"], 'total_urls': report["total_u...
def data2int(data, format): """ data sample to integer """ dec = 0 if format == 'RDEF': for power in range(len(data)-1, -1, -1): dec = dec + data[power]*(2**(8*power)) elif format == 'VDR' or format == 'SFDU': for power in range(0, len(data)): dec = dec + ...
def uniquify_names(names): """ Takes a list of strings. If there are repeated values, appends some suffixes to make them unique. """ count = {} for name in names: count.setdefault(name, 0) count[name] += 1 seen = set() res = [] for name in names: unique = cou...
def dsname2total(dataset): """Convert dataset name to total image name. Typical dataset name is hst_10188_10_acs_wfc (with no filter) but also works with hst_10188_10_acs_wfc_total. This translates Steve's WFPC2 dataset names (e.g. HST_08553_01_WFPC2_WFPC2) to HLA-style names (hst_08553_01_wfpc...
def compret(annual_interest, years): """ Compound `annual_interest` over given `years` """ return (1.0 + annual_interest)**years - 1.0
def boolean_to_binary(is_grid_valid): """ Converts boolean to binary :param is_grid_valid(boolean): Boolean value :return: Binary representation od boolean value """ return bin(int(is_grid_valid))
def iand(a, b): """Same as a &= b.""" a &= b return a
def dict_equal(dict1, dict2): """Check if 2 dictionaries are equal""" return len(dict1) == len(dict2) == len(dict1.items() & dict2.items())
def consec_len(ilist, start): """return the length of consecutive integers - always at least 1""" prev = ilist[start] length = len(ilist) ind = start for ind in range(start+1, length+1): if ind == length: break if ilist[ind] != prev + 1: break prev = ilist[ind] if ind == st...
def skriveegenskap2endringssett( egenskapdict ): """ Konverterer dictionary med egenskapid : verdi til den strukturen APISKRIV skal ha """ skriveg = [ ] for eg in egenskapdict.items(): skriveg.append( { 'typeId': eg[0], 'verdi' : [ eg[1] ] } ) return skriveg
def extended_gcd(a, b): """ ----- THIS FUNCTION WAS TAKEN FROM THE INTERNET ----- Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb """ # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg return values for i or j are made posi...
def parsed_to_str(config, condition): """Convert a parsed condition back to its original string. :param config: VALVE config dict :param condition: parsed condition to convert :return: string version of condition """ cond_type = condition["type"] if cond_type == "string": val = cond...
def clean_dict(dictionary): """ Returns a new but cleaned dictionary. * Keys with None type values are removed * Keys with empty string values are removed This function is designed so we only return useful data """ newdict = dict(dictionary) for key in dictionary.keys(): if di...
def compat(data): """ Check data type, transform to string if needed. Args: data: The data. Returns: The data as a string, trimmed. """ if not isinstance(data, str): data = data.decode() return data.rstrip()
def total_compression(*compressions): """Compute the total amount of compression achieved for multiple datasets that have the same number of samples. Input ----- compressions -- list or array containing the compression factors for each dataset Output ------ The total compre...
def tagged_array_columns(typegraph, array_id): """ Return a dict mapping the array column names to versions tagged with the id. Example: The original table headers are array_id value_index type_at_index id_or_value_at_index the tagged versions become t8754_array_id t8754_valu...
def prop_eq_or(default, key, value, dct): """ Ramda propEq plus propOr implementation :param default: :param key: :param value: :param dct: :return: """ return dct[key] and dct[key] == value if key in dct else default
def doubleFactorial(n : int) -> int: """ if n is even it returns the sum of all the even numbers\n if n is odd it returns the sum of all the odd numbers\n in the range(1,n)\n ** Uses the built in functool's module lru_cache decorator """ if n in (1,0): return 1 return n *...
def from_json(json_data: dict, delimeter: str = "|") -> str: """Transforms JSON into a plain text :param json_data: JSON object that needs to be converted to plain text :param delimeter: Delimeter to be used in the plain text :type json_data: dict :type delimeter: str :return: Plain text from J...
def get_message_id(message): """Similar to :meth:`get_input_peer`, but for message IDs.""" if message is None: return None if isinstance(message, int): return message try: if message.SUBCLASS_OF_ID == 0x790009e3: # hex(crc32(b'Message')) = 0x790009e3 ret...
def mock_match(A, B): """ Checked for params on a mocked function is as expected It is necesary as sometimes we get a tuple and at the mock data we have lists. Examples: ``` >>> mock_match("A", "A") True >>> mock_match("A", "B") False >>> mock_match(["A", "B", "C"], ["A", "...
def add_integer(a, b=98): """ This function returns the sum of two int """ if (a is None): raise TypeError("a must be an integer") if (type(a) is not int) and (type(a) is not float): raise TypeError("a must be an integer") if (type(b) is not int) and (type(b) is not float): ...
def expand_ALL_constant(model, fieldnames): """Replaces the constant ``__all__`` with all concrete fields of the model""" if "__all__" in fieldnames: concrete_fields = [] for f in model._meta.get_fields(): if f.concrete: if f.one_to_one or f.many_to_many: ...
def HasEnabledCa(ca_list, messages): """Checks if there are any enabled CAs in the CA list.""" for ca in ca_list: if ca.state == messages.CertificateAuthority.StateValueValuesEnum.ENABLED: return True return False
def verification_challenge(data: dict) -> bool: """ Slack sends a verification challenge in order to connect with their slack platform (verification done)""" return data.get("type") == "url_verification"
def _xfrm_ffz(data): """Helper for load_ffz - parse a FFZ-format JSON file""" return {em["code"]: em["images"]["1x"] for em in data}
def _construct_version(major, minor, patch, level, pre_identifier, dev_identifier, post_identifier): """Construct a PEP0440 compatible version number to be set to __version__""" assert level in ["alpha", "beta", "candidate", "final"] version = "{0}.{1}".format(major, minor) if patch: version +=...
def find_wifi(*args): """ Takes any number of fields Looks for wifi indicators returns Bool """ wifilist = ['Google', 'Sprint', 'Wireless', 'Mobil'] for x in args: if x is not None: if any(word in x for word in wifilist): return True return False
def sequence(index): """ Generate a W*****l number given the index """ element = (index << index) - 1 return element
def chem_correction( melting_temp, DMSO=0, fmd=0, DMSOfactor=0.75, fmdfactor=0.65, fmdmethod=1, GC=None ): """Correct a given Tm for DMSO and formamide. Please note that these corrections are +/- rough approximations. Arguments: - melting_temp: Melting temperature. - DMSO: Percent DMSO. ...
def strip_suffix(text, suffix): """ Cut a set of the last characters from a provided string :param text: Base string to cut :param suffix: String to remove if found at the end of text :return: text without the provided suffix """ if text is not None and text.endswith(suffix): return ...
def optimize_parallel_run(num_samples, num_threads, num_cores): """ Optimizes the pool_size and the number of threads for any parallel operation """ print("Optimizing parallel jobs for number ot threads and samples run at a time") print("Parameters passed : no. samples {0} , no. threads {1} , no. c...
def get_log_filepath(conf): """Assuming a valid conf containing the `datastores` key, retrieves the 'location' key of an object in the `datastores` list whose `type` is "file". Default is `./tasks/`. """ return next( filter(lambda ds: ds.get('type').lower() == 'file', conf.get('datastores')...
def _tokenize_table(table): """Tokenize fields and values in table.""" return [(field.split(), value.split()) for field, value in table]
def PReLU(v, alfa=1): """ Parametric ReLU activation function. """ return alfa*v if v<0 else v
def _mnl_transform_deriv_alpha(*args, **kwargs): """ Returns None. This is a place holder function since the MNL model has no intercept parameters outside of the index. """ # This is a place holder function since the MNL model has no intercept # parameters outside the index. return None
def is_prime(number): """determine if a number is prime""" # 0 and 1 are not considered prime numbers although 1 is positive and divisible by 1 and itself prime = number > 1 for possible_divider in range(2, number): if number % possible_divider == 0: prime = False return prime
def make_proportion(col): """ turn an integer column into a decimal proportion. """ answer = col / 100 return(answer)
def get_factor(spacegroup, gamma): """ Determines bond length multiplication factor. Depends on spacegroup and gamma angle. """ if spacegroup == 12: return 1.4 elif spacegroup == 33: return 1.4 elif spacegroup == 167: return 1.5 elif spacegroup == 194: ret...
def calc_predict_next_token_index(state, total_kv_pooling, max_len, chunk_len, chunk_offset): """Arithmetic calculation for the current_token and sequence_length.""" current_token = state // total_kv_pooling sequence_length = max_len if chunk_len is not None: if chunk_offs...
def prepad_signed(hex_str): """Given a hexadecimal string prepad with 00 if not within range. Args: hex_str (string): The hexadecimal string. """ msb = hex_str[0] if msb < "0" or msb > "7": return "00%s" % hex_str return hex_str
def get_palette(num_cls): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ n = num_cls palette = [0] * (n * 3) for j in range(0, n): lab = j palette[j * 3 + 0] = 0 palette[j * ...
def is_read_pair(rec1, rec2, casava18=True): """Returns true if the two records belong to the same read pair, determined by matching the header strings and disregarding the read field """ # Handle pre-casava1.8 headers if not casava18: return (rec1[0][0:-1] == rec2[0][0:-1]) r1 =...
def _get_join_conditions_dict(join_query_results): """ Creates a dictionary with the results of the JOIN_CONDITION_PARSING_QUERY. The keys are the identifiers of the child triples maps of the join condition. The values of the dictionary are in turn other dictionaries with two items, child_value and pare...
def getAvailableLetters(lettersGuessed: list) -> str: """Returns letter in alph not guessed Args: lettersGuessed: what letters have been guessed so far Returns: str: comprised of letters that represents what letters have not yet been guessed. """ # Created alph 1, using list ...
def as_iterable(iterable_or_scalar): """Utility for converting an object to an iterable. Parameters ---------- iterable_or_scalar : anything Returns ------- l : iterable If `obj` was None, return the empty tuple. If `obj` was not iterable returns a 1-tuple containing `obj`. Ot...
def sefl(c, f, f0): """ Semi-empirical normalized force limit. Parameters ---------- c : scalar Constant based on experience, typically around 1.5 f : scalar Frequency of interest, typically lower end of band. f0 : scalar Fundamental frequency in direction of interes...
def get_data(code, adil, flags, src, dst, mpdu_len, tpci_apci, payload): """Encode to cemi data raw bytes.""" return bytes( [ code, adil, # adil (flags >> 8) & 255, # flags flags & 255, # flags (src >> 8) & 255, # src src & 255,...
def sort_dicts(dicts, sort_by): """ :param dicts: list of dictionaries :param sort_by: key by which the list should be sorted :return: sorted list of dicts """ return sorted(dicts, key=lambda k: k[sort_by])
def polynomiale_carre(a: float, b: float, c: float, x: float) -> float: """Retourne la valeur de ax^4 + bx^2 + c """ return a*x*x*x*x + b*x*x + c
def dict_update(orig, updates): """Recursively merges two objects""" for key, val in updates.items(): if isinstance(val, dict): orig[key] = dict_update(orig.get(key, {}), val) else: orig[key] = updates[key] return orig
def escape_for_markdown(text: str or None) -> str: """ Escapes text to use as plain text in a markdown document :param text: the original text :return: the escaped text """ text = str(text) escaped = text.replace("*", "\\*").replace("_", "\\_") return escaped
def parse_bool(b): """ Useful for environment variables, intelligently converts any reasonable string to a Python bool, or None if it is None or empty/whitespace string.""" if b is None: return None if b is True: return True if b is False: return False if b.str...
def remove_macro_defines( blocks, excludedMacros=set() ): """remove macro definitions like #define <macroName> ....""" result = [] for b in blocks: macroName = b.isDefine() if macroName == None or not macroName in excludedMacros: result.append(b) return result
def _get_filter_syntax(_filter_info, _prefix=True): """This function retrieves the proper filter syntax for an API call.""" if type(_filter_info) != tuple and type(_filter_info) != list: raise TypeError("Filter information must be provided as a tuple (element, criteria) or a list of tuples.") elif t...
def unindent(source): """ Removes the indentation of the source code that is common to all lines. """ def normalize(line): normalized = [] for i, c in enumerate(line): if c == " ": normalized.append(" ") elif c == '\t': normali...
def normalizeGlyphRightMargin(value): """ Normalizes glyph right margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph right margin mus...
def analysis_find_numbers( database, arg_five_or_seven_numbers): """Find numbers """ found_five = {} found_euro = {} for key, numbers in database.items(): for vals in numbers: if len(arg_five_or_seven_numbers) >= 5: numbers_five = [vals[0],vals[1],vals[2],vals[3]...
def hide_individual_data_files(fns): """To display concisely: _build/eval/data/A/B/C/D -> _build/eval/data/A.""" concise_fns = set() for fn in fns: concise_fn = [] fn_components = fn.split('/') i = 0 seen_data = False while i < len(fn_components) and not seen_data: ...
def get_kqshift(ngkpt, kshift, qshift): """Add an absolute qshift to a relative kshift.""" kqshiftk = [ kshift[i] + qshift[i] * ngkpt[i] for i in range(3) ] return kqshiftk
def _set_log_format(color: bool, include_caller: bool) -> str: """ Set log format :param color: Log message is colored :param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123] :return: string of log format """ level_name = "* %(levelname)1s" time = "%(asctime)s,%...