content
stringlengths
42
6.51k
def mask(x): """Turn a string into an equal-length string of asterisks""" try: return len(x) * '*' except TypeError: # not a string - perhaps None - just return it as-is return x
def self_powers(d, stop, vol=0): """ Returns the last d digits of 1^1 + 2^2 + ... + stop ^ stop """ total = 0 mod = 10 ** d for a in range(1, stop + 1): total += a ** a total %= mod if vol >= 1: print(f"The last {d} digits are {total}") return total
def verify_data(phone, items, carrier): """ Verifies if the phone is 11 digits and carrier is there""" return True if len(phone) == 11 and len(items) > 0 and carrier is not None else False
def triangle_area(base, height): """Returns the area of a triangle""" # You have to code here # REMEMBER: Tests first!!! return (base * height) / 2
def dict_to_str(dic, separate='\n'): """ Converts a dictionary to a nicely formatted string :param dic: (dict) to convert :param separate: (str) string to use to separate dictionary elements :return: (str) of dictionary content """ dict_str = '' for key, value in dic.items(): dict_...
def flat(*nums): """ Build a tuple of ints from float or integer arguments. Useful because PIL crop and resize require integer points. """ return tuple(int(round(n)) for n in nums)
def create_headers(bearer_token): """create the header needed for bearer authorization Arguments: - time_delta: how often to run this """ headers = {"Authorization": "Bearer {}".format(bearer_token)} return headers
def transform_labels(label_column): """ Function to encode the process ID column into binary labels for foreground (4-top) and background. let :label_column: pandas series """ map = {'ttbarW': 'background', '4top': '4top', 'ttbarHiggs': 'background', 'ttbarZ': 'background', 'ttbar': 'background'} return [map[x] f...
def clamp(value, min_value, max_value): """ Return *value* clipped to the range *min_value* to *max_value* inclusive. """ return min(max_value, max(min_value, value))
def positive_sum(arr): """ You get an array of numbers, return the sum of all of the positives ones. Note: if there is nothing to sum, the sum is default to 0. :param arr: An array of integers. :return: The sum all positive integers within the given array. """ return sum([x for x in arr if x...
def _getWords(strongs, words_strongs_index): """ Returns a list of words that match the strong's number. :param strongs: :param words_strongs_index: :param words_false_positives_index: :return: """ if strongs in words_strongs_index: return words_strongs_index[strongs] else: ...
def escape(text): """ Minimal HTML escaping, not for attribute values (unlike html.escape). """ return f"{text}".replace("&", "&amp;").replace("<", "&lt;")
def control_value(f): """ Return the value of a control field (arg1). """ return f[3][1]
def get_issue_link(repo_name: str, issue_number: int) -> str: """ Build an issue URL for manual browser access using full repository name and issue number :param repo_name: full repository name (i.e. `{username}/{repoanme}`) :param issue_number: issue number used on GitHub :return: An issue URL ...
def values_of(choices): """ Returns a tuple of values from choices options represented as a tuple of tuples (value, label). For example: .. sourcecode:: python >>> values_of(( ... ('1', 'One'), ... ('2', 'Two'),)) ('1', '2') :rtype: tuple """ ...
def calculate_num_modules(slot_map): """ Reads the slot map and counts the number of modules we have in total :param slot_map: The Slot map containing the number of modules. :return: The number of modules counted in the config. """ return sum([len(v) for v in slot_map.values()])
def mediaValues(x): """ return the media of a list """ return sum(x)/len(x)
def is_solved(puzzle): """Return True is the puzzle is solved, False otherwise.""" # simply check if the list is sorted return all(puzzle[i] < puzzle[i + 1] for i in range(len(puzzle) - 1))
def baskets(items, count): """ Place list itmes in list with given basket count. Original order is not preserved. Example: > baskets([1,2,3,4,5,6,7,8, 9, 10], 3) [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]] """ _baskets = [[] for _ in range(count)] for i, item in enumerate(items): ...
def invert_dict(dct: dict) -> dict: """ >>> invert_dict({'a': 4, 'b': 3, 'c': 2, 'd': 1}) {4: 'a', 3: 'b', 2: 'c', 1: 'd'} """ from operator import itemgetter invert = itemgetter(1, 0) items = dct.items() return dict(map(invert, items))
def rev(s): """ function used to compare strings in decreasing order""" return ''.join([chr(255-ord(c)) for c in s])
def comma_join(items, stringify=False): """ Joins an iterable of strings with commas. """ if stringify: return ', '.join(str(item) for item in items) else: return ', '.join(items)
def getUrl(host, port): """ return url for host and port """ return f"http://{host}:{port}"
def is_auto(item): """ Checks if a parameter should be automatically determined """ if isinstance(item, float): if item == 9999.9: return True elif isinstance(item, str): if 'auto' in item.lower(): return True return False
def benchmark(rel): """Add relationship category prefix for benchmark resources. Parameters ---------- rel: string Link relationship identifier Returns ------- string """ return 'benchmarks:{}'.format(rel)
def final_score_calculator(score_list): """Returns final Levenshtein Word Score Iterates through all the scores for the various queries. Final score is calculated by averaging the ratio of the score with the word length of the ground truth. A given score is capped at 1. """ final_score = 0.0 ...
def get_transaction_specific_information(json_list_of_transactions): """Function that extracts transaction specific information and stores each it in a table in the venmo transactions database.""" transactions = [] weird_transactions= [] # Not including in _id because that is the object id from V...
def sum2digits(d): """Sum digits of a number that is less or equal 18. >>> sum2digits(2) 2 >>> sum2digits(17) 8 """ return (d // 10) + (d % 10)
def de_list_pair(x, y=None): """De-list pair.""" if isinstance(x, list) and not y: return x[0], x[1] return x, y
def tamper(payload, **kwargs): """ Replaces instances of UNION ALL SELECT with UNION SELECT counterpart >>> tamper('-1 UNION ALL SELECT') '-1 UNION SELECT' """ return payload.replace("UNION ALL SELECT", "UNION SELECT") if payload else payload
def remove_duplicates_without_buffer(llist): """ time complexity: O(n*n) space complexity: O(1) """ i = 0 while i < len(llist): j = i + 1 while j < len(llist): if llist[j] == llist[i]: del llist[j] else: j += 1 i +...
def mean(data): """Return the sample arithmetic mean of data.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/n
def invertMap(map): """Invert a one-to-one mapping.""" inv = {} for (k, v) in list(map.items()): # generates sequence of (key, value) pairs inv[v] = k # backwards -- from v to k if len(map) != len(inv): # if set inv[v] more than once for some v raise Exception('Map not on...
def format_header(collection_data, first_keys): """Organizes the keys of the documents to be exported into a list of column titles. collection_data is the type of data. first_keys are the keys that need to be the first columns in the spreadsheet. """ # All the keys that will be used to write header...
def cleanup_ocr_text(txt): """Do some basic cleanup to make OCR text better. Err on the side of safety. Don't make fixes that could cause other issues. :param txt: The txt output from the OCR engine. :return: Txt output, cleaned up. """ simple_replacements = ( (u"Fi|ed", u"Filed"), ...
def stack_is_failing(events): """iterate stack events, determine if resource creation failed""" failed = False failure_modes = ('CREATE_FAILED', 'UPDATE_ROLLBACK_IN_PROGRESS') for event in events['StackEvents']: if event['ResourceStatus'] in failure_modes: failed = True if ev...
def isprime(n): """ This is the description of the function ~ Loves it Parameters ---------- n : int int to check if prime Returns ------- bool true if n prime """ if n>=2: for i in range(2,n): if not (n % i...
def solve(firewall): """Return severity if the trip through the firewall. :firewall: list of depth and range of the scanner (separated by a colon) for each layer (separated by newline) :returns: severity of a trip >>> solve('''0: 3 ... 1: 2 ... 4: 4 ... 6: 4''') 24 "...
def hello(_): """ Return data from DBas discussion_reaction page. :return: dbas.discussion_reaction(True) """ return { "status": "ok", "message": "Connection established. \"Back when PHP had less than 100 functions and the function hashing " "mechanism was strlen(...
def clean_line(line): """Strip whitespace off a line and separate out the comment, if any.""" if "//" in line: line, _sep, comment = line.partition("//") if "/*" in line: line, _sep, comment = line.partition("/*") comment, _sep, _trash = comment.partition("*/") else: comm...
def _filter_event_bracket_response(response): """Filters the Smash.gg response to something more managable""" bracket_ids = [] for bracket in response['entities']['groups']: bracket_ids.append(str(bracket['id'])) return { 'bracket_ids': bracket_ids, 'event_name': response['entit...
def get_path(parents, end): """ Returns a list starting with the start node implied by the parents dictionary, and ending with the specified end node. If no path exists, returns an empty list. Parameters: parents - a dictionary rooted at an arbitrary graph node, "start". ...
def is_udp_network_error(exc: BaseException) -> bool: """Is the provided exception a network-related error? This should be passed an exception which resulted from creating and using a socket.SOCK_DGRAM type socket. It should return True for any errors that could conceivably arise due to unavailable/poo...
def term(field, value): """ Filter docs by a field 'value' can be a singleton or a list. """ if isinstance(value, list): return {"terms": {field: value}} elif isinstance(value, tuple): return {"terms": {field: list(value)}} elif isinstance(value, set): return {"terms"...
def _ProcessReporterSD(fmt): """Convert a 'reporter' sort directive into SQL.""" left_joins = [ (fmt('User AS {alias} ON Issue.reporter_id = {alias}.user_id'), [])] order_by = [ (fmt('ISNULL({alias}.email) {sort_dir}'), []), (fmt('{alias}.email {sort_dir}'), [])] return left_joins, order_by
def _is_iter(val): """Check if value is of accepted iterable type.""" return type(val) in [tuple, list]
def capitalize(s): """ Just capitalize first letter (different from .title, as it preserves the rest of the case). e.g. accountSettings -> AccountSettings """ return s[0].upper() + s[1:]
def get_max(max, min, N): """ Binary search. Return the maximun number, X, between MAX and MIN that multiplied by MAX is greater than N. """ precision = 10 while precision > 0: mid = (max+min)//2 if mid*min > N: max = mid else: min = mid ...
def ToUpper(v): """Transform a string to upper case. >>> s = Schema(ToUpper) >>> s('hi') 'HI' """ return str(v).upper()
def create_message(pre_msg): """ Create pre-format message for body in Jira issue :param pre_msg: JSON-object :return: string """ msg = 'Host: {host_name} \n\ Trigger: {trigger_name} \n\ Trigger status: {trigger_status} \n\ Trigger severity: {trigger_severity} \n\ Trigger URL: {problem_url} \n\ ...
def adjust_tokens_for_transformers(sentence): """ Adjust tokens for BERT See https://github.com/DoodleJZ/HPSG-Neural-Parser/blob/master/src_joint/Zparser.py#L1204 Parameters ---------- sentence """ cleaned_words = [] for word in sentence: # word = BERT_TOKEN_MAPPING.get(word...
def insertion_sort(some_list): """ https://en.wikipedia.org/wiki/Insertion_sort Split the array into a "sorted" and "unsorted" portion. As we go through the unsorted portion we will backtrack through the sorted portion to INSERT the element-under-inspection into the correct slot. O(N^2) """ ...
def make_important(bulk): """makes every property in a string !important. """ return ';'.join('%s !important' % p if not p.endswith('!important') else p for p in bulk.split(';'))
def create_nodes(pages, init_id=0): """ args: [[url, html_text]] init_id: start id number of relatives """ nodes = [] count_id = init_id for page in pages: node = {} node["r_id"] = count_id node["r_url"] = page[0] node["r_html"] = page[1] #...
def rivers_with_station(stations): """Given list of MonitoringStation objects; returns a set of names of rivers with a monitoring station given in the original list.""" output = set() for station in stations: output.add(station.river) return output
def lorentzian(x, x0, gamma, I): """ Function to evaluate a Lorentzian lineshape function. Parameters ---------- x : Numpy 1D array Array of floats corresponding to the x values to evaluate on x0 : float Center for the distribution gamma : float Width of the dist...
def union(A, B) : """ A + B """ return list(set(A).intersection(B))
def duplicate(i_list: list,n)-> list: """ Duplicate each element of the list :param i_list: The source list :param n: The number of repetitions for each element :return: The duplicated list """ _shallow_list = [] for element in i_list: i=0 while i<n: _shallow_...
def kron_d(i, j): """ The Kronecker delta. """ return 1 if i == j else 0
def finditem(func, seq): """Finds and returns first item in iterable for which func(item) is True. """ return next((item for item in seq if func(item)))
def string2dict(string, dic): """split a string into a dict record its frequent""" wl = string.split() for w in wl: if w == '\n': continue # if len(w) <= 3: # continue if w not in dic: dic[w] = 1 else: dic[w] += 1 return dic
def drift_stability_ind( missing_recs_drift, drift_tab, missing_recs_stability, stability_tab ): """ This function helps to produce the drift & stability indicator for further processing. Ideally a data with both drift & stability should produce a list of [1,1] Parameters ---------- missing_recs...
def union(set1, set2): """ set1 and set2 are collections of objects, each of which might be empty. Each set has no duplicates within itself, but there may be objects that are in both sets. Objects are assumed to be of the same type. This function returns one set containing all elements from bot...
def compare_values(answer, submitted_answer): """Comparing values""" if answer["value_type"] == "number": if "comparison_type" in answer and answer["comparison_type"] == "absolute": return abs(answer["value"]) == abs(submitted_answer) if answer["value_type"] != "string": return a...
def detail_table_xpath(label: str) -> str: """ For details table get cell value under header """ return '//dt[text()="{dt_label}"]/following::dd/text()'.format(dt_label=label)
def __get_eval_result(status, message, confidence): """Builds a evaluation response object from given information Parameters: status (String): Result of evalution PASSED/FAILED/ERROR message (String): Message of evaluation, error on ERROR confidence (Number): Confidence level of result (0-100) ...
def application_error(e): """Return a custom 500 error.""" return 'Sorry, unexpected error: {}'.format(e), 500
def find_existing_path(dict_: dict, path: list) -> tuple: """Return a tuple consisting of: - A pointer to any part of the path that already exists in the declared dict. - The remaining part of the path that needs to be created. """ try: subfolder = path.pop(0) except IndexError: ...
def __compress(list_events): """ Compress a list of events, using one instantiation for the same key/value. Parameters -------------- list_events List of events of the stream Returns -------------- :param list_events: :return: """ compress_dict = {} i = 0 ...
def asoctal(s): """Convert the given octal string to an actual number.""" return int(s, 8)
def _NameToIndex(name, L): """Return index of name in list, appending if necessary This routine uses a list instead of a dictionary, because a dictionary can't store two different keys if the keys have the same value but different types, e.g. 2 and 2L. The compiler must treat these two separately,...
def wrap_to_pmh(x, to2): """Wrap x to [-to/2,to/2).""" to = to2/2 return (x + to)%to2 - to
def get_dir_keys(grid): """Only add a key for directory creation if it is being changed.""" keys = [] for key in grid: if isinstance(grid[key], list) and len(grid[key]) > 1: keys.append(key) return keys
def clamp(v, lo, hi): """ Clamp a value between low and high limits. """ return lo if v < lo else (hi if v > hi else v)
def get_sfdc_mysql_dt(sfdc_dtype, sfdc_length, sfdc_precision, sfdc_scale): """Function converts SFDC datatypes into MySQL compatible datatypes Args: sfdc_datatype, sfdc_length, sfdc_precision, fdc_scale Returns: dictionary of MySQL compatible datatypes """ d_sfdc_mysql_dtype_map = { "id":"varchar", "boo...
def create_pymol_selection_from_socket_results(indices): """create pymol-readable selection from socket data (converted to bundleDesc) input: list of helices, each helix represented as a tuple in format (first_residue_number, last_residue_number, chain_id) output: list of pymol-readable selections, each as a string ...
def InsertShimImports(text: str) -> str: """A preprocessor which inserts a set of shim imports. Args: text: Text to prepend imports to. Returns: The text with imports prepended. """ return f"""\ import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.util.*; import java.time...
def duplicate_check(warning, warning_log): """This function checks to make sure that the warning has not been reported before. Inputs: - warning: current warning to be checked [string] - warning_log: log containing all warnings written previously [list of strings] Outputs: - skip: ...
def search2path(search_string): """Turn the input search string into a path entry for figures""" search_string = search_string.replace(':', '_') search_string = search_string.replace('=', '') search_string = search_string.replace(', ', '_') return search_string
def _dim_arg(value, units): """Concatenate a specified units string to a numerical input. Parameters ---------- value : str or number Valid expression string in the AEDT modeler. For example, ``"5mm"``. units : str Valid units string in the AEDT modeler. For example, ``"mm"``. ...
def select_criteria(comparison_data, crit): """Extracts not None comparisons of one criteria comparison_data: output of fetch_data() crit: str, name of criteria Returns: - list of all ratings for this criteria ie list of [contributor_id: int, video_id_1: int, video_id_2: int, ...
def copyAsList(value): """ Copy value and, if it is not a list, turn it into a list with a single entry. Parameters ---------- value: single variable of any type, or list Returns ------- value: list Copy of value if it is a list of [value] otherwise. """ if isinstance(v...
def inclusive_range(start, stop, step=1): """ A range() clone, but this includes the right limit as is if the last step doesn't divide on stop """ l = [] x = start while x <= stop: l.append(x) x += step if x > stop: l.append(stop) return l
def get_shape(obj): """ Get the shape of a :code:'numpy.ndarray' or of a nested list. Parameters(obj): obj: The object of which to determine the shape. Returns: A tuple describing the shape of the :code:`ndarray` or the nested list or :code:`(1,)`` if obj is not an instance of ...
def create_paper(paper_id, paper_title, paper_abstract, paper_year, paper_citations): """Initialize a paper.""" paper = { "id": paper_id, "title": paper_title, "abstract": paper_abstract, "year": paper_year, "is_influential": False, "citations": paper_citations, ...
def update_guess_word(word, guess_word, guess): """ Updates the guess_word with the newly guessed letter. By iterating over the word and comparing each character, we can find all occurences of that letter and can replace the underscores in the guess word for each found occurence. E.g. if the w...
def _name_to_description(name_str) -> str: """Gets the description of the layer contained in the lyp name field. It is not strictly necessary to have a description. If none there, it returns ''. Default format of the lyp name is key - layer/datatype - description or key - descriptio...
def get_character_ngrams(token: str, n: int): """ Returns character n-grams for given words. Input(s): 1) token - The word to be used for generating n-gram. 2) n - Size of n-gram Output(s): 1) A list containing character n-grams. """ return [token[char:char+n] for c...
def getType(vv): """ Gets the variable type from its name Types are: 0 - str 1 - int 2 - float 3 - time """ vartype = {'station_id':0,'sensor_id':0,'"latitude (degree)"':2,'"longitude (degree)"':2,\ 'date_time':3,'"sensor_depth...
def quote_string(v): """ RedisGraph strings must be quoted, quote_string wraps given v with quotes incase v is a string. """ if isinstance(v, bytes): v = v.decode() elif not isinstance(v, str): return v if len(v) == 0: return '""' v = v.replace('"', '\\"') ...
def upper_section_score(die_value, final_dice, scorepad, ): """Evaluate dice from a roll for a given value and multiply the count by that value. E.g. for a die value of 3 and a count of two dice with that value the total score is 6 (die...
def html(text): """Escape bad sequences (in HTML) in user-generated lines.""" return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def append_a(string): """Append "_a" to string and return the modified string""" string = '{}{}'.format(string, '_a') return string
def determine_num_samples(distance_m): """ Guarantee a number of samples between 2 and 600. Longley-Rice Irregular Terrain Model is limited to only 600 surface points, so this function ensures this number is not passed. Parameters ---------- distance_m : int Distance between tr...
def is_flush(suits): """Return True if hand is a flush. Compare if card suit values are all equal. """ return suits[0] == suits[1] == suits[2] == suits[3] == suits[4]
def RequestControlTuples(ldapControls): """ Return list of readily encoded 3-tuples which can be directly passed to C module _ldap ldapControls sequence-type of RequestControl objects """ if ldapControls is None: return None else: result = [ (c.controlType,c.criticality,c.encodeContro...
def _string_from_cmd_list(cmd_list): """Takes a list of command line arguments and returns a pretty representation for printing.""" cl = [] for arg in map(str, cmd_list): if ' ' in arg or '\t' in arg: arg = '"' + arg + '"' cl.append(arg) return ' '.join(cl)
def _cpp_integer_type_for_range(min_val, max_val): """Returns the appropriate C++ integer type to hold min_val up to max_val.""" # The choice of int32_t, uint32_t, int64_t, then uint64_t is somewhat # arbitrary here, and might not be perfectly ideal. I (bolms@) have chosen # this set of types to a) minimize th...
def _json2coloring(coloring): """ Convert all of the None entries in rowcol_map to full slices. Parameters ---------- coloring : dict Dict of coloring metadata. Returns ------- dict Dict of coloring metadata. """ full_slice = slice(None) for mode in ('fwd', ...
def _check_type(par,par_type): """function for checking if python parameter 'par' and DBASIC type 'par_type' are compatible""" if par_type=='String': if type(par)==str: return True else: raise TypeError("Parameter of DBASIC type 'String' must be of python type 'str'") ...