content
stringlengths
42
6.51k
def make_str_from_column(board, column_index): """ (list of list of str, int) -> str Return the characters from the column of the board with index column_index as a single string. >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1) 'NS' """ #first index change +1 ...
def insertTime(line, time): """ inserts a new time into an event file line. """ dt = line[0:line.find(' ')] return line.replace(dt, time)
def remove_quotes(text): """Replace quote marks in text.""" index = 0 length = len(text) while index < length: if '\"' in text[index]: text[index] = text[index].replace('\"','*') if '\'' in text[index]: text[index] = text[index].replace('\'','*') index = i...
def aic(log_lik, n_samples, dof): """ Calculates the Akaike Information Criterion. Parameters ---------- log_lik: float The observed data log-likelihood. n_samples: int Number of samples. dof: int Number of degrees of freedom. Output ------ bic: float ...
def bit_to_str(bit): """ Converts a tuple (frame, bit, value) to its string representation. """ s = "!" if not bit[2] else "" return "{}{}_{:02d}".format(s, bit[0], bit[1])
def generate_symbol_definitions_table(symbols, prefix): """Generate a listing of symbol definitions for symbol table.""" ret = [] for ii in symbols: ret += [ii.generate_rename_tabled(prefix)] return "\n".join(ret)
def _add_columns(data): """ This function return the list of columns with contains to display in custom view. :param data: ctx_result["data"] :return: list of columns to display """ columns_dict = [] available_columns = list(set().union(*data)) # Columns to display in view columns_in_...
def _get_speaking_time(main_segment_list): """ calculating the speaking time""" duration = 0 for a_segment in main_segment_list: duration += (a_segment[1] - a_segment[0]) return duration
def convert_range(p): """Convert a float from 0-1 range to integer 0-255 range.""" return max(0, min(255, round(255 * p)))
def get_status(runs): """Get the most recent status of workflow for the current PR. Parameters ---------- runs : list List of comment objects sorted by the time of creation in decreasing order. Returns ------- status : string The most recent status of workflow. Can ...
def div(a, b): """Helper function for division :param a: first parameter :type a: int :param b: second parameter :type b: int :return: integer division result :rtype: int """ return int(a / b)
def check_length_for_tweet(revision, message): """ Recursively remove a word from the message until it is small enough to tweet """ # I think 115 is the hard limit once the url is shortened if len(revision) + len(message) > 110: # get rid of a word message = ' '.join(message.s...
def arraytoyf(args, lengths): """Inverse of yfarray().""" return tuple(tuple(1 if a & (1 << m) else 0 for m in range(n)) for n, a in zip(lengths, args))
def dist_median(distribution, count): """Returns the median value for a distribution """ counter = 0 previous_value = None for value, instances in distribution: counter += instances if counter > count / 2.0: if (not count % 2 and (counter - 1) == (count / 2) and ...
def calculate_ema(close, periods, previous_ema): """ Calculates the exponential moving average. EMA = Price(t)*weighting_multipler + previous_ema*(1-weighting_multiplier) *weighting_multiplier is given by 2/(periods + 1) Args: close: Float representing the exchange rate at the end of an int...
def sgd(w, dw, learning_rate=1e-3, config=None): """ stochastic gradient descent :param w: weights :param dw: grads of weights :param learning_rate: learning rate :return: new weights """ w -= dw * learning_rate return w, config
def strip_csv_row(row): """ Strip values in a CSV row, casing '' -> None. """ return { key: val.strip() or None for key, val in row.items() }
def id_from_uri(uri: str) -> str: """Get the item ID from URI address.""" return uri.rstrip("/").split("/")[-1]
def index_to_voxel(index, Y_size, Z_size): """ index to voxel, eg. 0 -> (0,0,0). """ i = index % (Y_size) index = index // (Y_size) j = index % (Z_size) index = index // (Z_size) k = index return (i, j, k)
def decimalTobinary(n): """Convert a decimal number to binary""" assert int(n) == n, 'input number must be integer' if n == 0: return 0 else: return n%2 + 10 * decimalTobinary(int(n/2))
def _average(expression, probes, *args, **kwargs): """ Averages expression data for probes representing the same gene Parameters ---------- expression : list of (P, S) pandas.DataFrame Each dataframe should have `P` rows representing probes and `S` columns representing distinct samp...
def extract_value(val_info, yaml_dict=None): """ extract field value """ res = None if "constant" in val_info: res = val_info["constant"]["value"] elif "constant_reference" in val_info: val_list = [] for source_info in val_info["constant_reference"]["source_name"]: ...
def write_file(filename="", text=""): """writes a string to a text file (UTF8) and returns the number of characters written""" with open(filename, 'w', encoding='utf=8') as file: return file.write(text)
def reduce_repeated_chars(str_in: str, char: str, remaining_chars: int) -> str: """ :param str_in: text to be cleaned :param char: character that should not occur more than remaining_chars times in sequence :param remaining_chars: remaining_chars :return: """ cnt = 0 out = "" for k i...
def sort_members_key(name): """Sort members of an object :param name: name :type name: str :return: the order of sorting :rtype: int """ if name.startswith("__"): return 3 elif name.startswith("_"): return 2 elif name.isupper(): return 1 else: ret...
def gen_obj_name(name: str) -> str: """ Generates an object name from a menu title or name (spaces to underscores and lowercase) """ return name.replace(" ", "_").lower()
def read_codepage(text, codepage='cp437'): """ Keep only characters belonging to the character set of a language Args: -- text: input text -- code page: for each language. Example: Code page 437 is the original code page of the IBM PC. https://www.ascii-codes.com/cp437.html """ text...
def sql_convert(s): """format a string to be printed in an SQL statement""" if isinstance(s, str): s = "'"+s.replace("\\", "\\\\").replace("'", "\\'")+"'" if isinstance(s, bytes): s = "'"+s.decode('utf-8').replace("\\", "\\\\").replace("'", "\\'")+"'" else: s = str(s) return ...
def calculate_kinetic_energy(mass, velocity): """Returns kinetic energy of mass [kg] with velocity [ms].""" return 0.5 * mass * velocity ** 2 def test_calculate_kinetic_energy(): mass = 10 # [kg] velocity = 4 # [m/s] assert calculate_kinetic_energy(mass, velocity) == 80
def is_binary_file(file_obj): """ Returns True if file has non-ASCII characters (> 0x7F, or 127) Should work in both Python 2 and 3 """ start = file_obj.tell() fbytes = file_obj.read(1024) file_obj.seek(start) is_str = isinstance(fbytes, str) for fbyte in fbytes: if is_str: ...
def remove_dups(head): """ 2.1 Remove Dups! Write code to remove duplicates from an unsorted linked list. FOLLOW UP: How would you solve this problem if a temporary buffer is not allowed? """ def chase(node, val): while node != None and node.value == val: node = node.next ...
def get_mod_func(callback): """ Converts 'django.views.news.stories.story_detail' to ('django.views.news.stories', 'story_detail') """ try: dot = callback.rindex('.') except ValueError: return callback, '' return callback[:dot], callback[dot + 1:]
def extract_name(str): """ Return string up to double underline """ return str[:str.find('__')]
def crop_from_right(sequence_string, crop_length): """ return a sequence string without last crop_length characters drops values at end ie chops off right side if crop_length > length sequence_string --> returns "" if crop_length <= 0 returns string """ if (crop_length <= 0): return ...
def lines(data): """ Convenience function to format each element on its own line for output suitable to be assigned to a bash array. Example: r = lines(_["foo"]) """ return "\n".join(str(i) for i in data)
def filter_actuals_data(json): """ Filter "actuals" data from input, taken as parameter, and return it in dict format. Return None if input is not valid. """ if not json: return None actuals_data = {} for entry in json: actuals_data[entry["state"]] = {"actuals": ...
def add_type_restriction(step): """ for a given step, look for object type and construct a SPARQL fragement to restrict the graph to objects of the type. If the object does not have a type restriction, return an empty string. :param step: The step for which an object restriction is requested :return...
def sum_of_n_odd_numbers(n): """ Returns sum of first n odd numbers """ try: n+1 except TypeError: # invlid input hence return early return if n < 0: # invlid input hence return early return return n*n
def datatable(columns, rows): """Columns and rows are both arrays, the former of (name, type) tuples""" return { "cols": [{"label": key, "type": val} for (key, val) in columns], "rows": [ {"c": [{"v": cell} for cell in row]} for row in rows] }
def sort(data): """Sorts data by allocated size and number of allocations""" return sorted( data, key=lambda info: (info.allocated_size, len(info.sizes)), reverse=True)
def get_input_commands(input_data): """extract instructions che from input text input data (str): plain text read from txt file""" input_lines = input_data.split("\n") result = [] for il in input_lines: if il != "": res = il.split(" ") result.append([res[0], int(res[1...
def readadc(chip, channel): """read channel CHANNEL of the MCP3008 CHIP should be an SpiDev object""" if ((channel > 7) or (channel < 0)): return -1 r = chip.xfer2([1,(8+channel)<<4,0]) adcout = ((r[1]&3) << 8) + r[2] return adcout
def project_metadata(data): """Returns project metadata""" project = data["project"] checkout_dir = project["checkout_dir"] oath_token = project["oath"] org = project["org"] return checkout_dir, oath_token, org
def is_trash(text): """ Decide whether a sentence is of low quality based on simple heuristics. Args: text (str): The string to be analyzed. Returns: bool: True if string is trash, False otherwise. """ if not text.endswith(('.', ':', '!', '?')) or len(text) < 6: return...
def hover_over(spell: str, stopcast: bool = False, dismount: bool = True, ) -> str: """ Hover over target. """ macro = f'#showtooltip {spell}\n' if stopcast: macro += '/stopcast\n' if dismount: macro += '/dismount\n' macro += f'/use [@mous...
def isLowerHull(dx, dy): """ Checks if a line is part of the lower hull :param float dx: :param float dy: """ lowerHull = (dx < 0.0) or (dx == 0.0 and dy < 0.0) return lowerHull
def check_surname(collection, id_, cont): """ Surname checking """ return cont.replace('-', '').isalpha()
def get_instrument(name): """Return the instrument inferred from the track name.""" if "viola" in name.lower(): return "Viola" if "cello" in name.lower(): return "Cello" for key in ("1st", "violin 1", "violin1", "violino i"): if key in name.lower(): return "Violin 1" ...
def max_subarray(L): """ Also known as Kadane's algorithm, this problem was first posed by Ulf Grenander of Brown University in 1977. A linear time algorithm was found soon afterwards by Jay Kadane of Carnegie Mellon University. Performance =========== O(n) """ max_ending_here = max...
def gardner(vp, alpha=310, beta=0.25): """ Compute bulk density (in kg/m^3) from vp (in m/s) """ return alpha * vp**beta
def get_error(op): """Return the error structure for the operation.""" return op.get('error')
def square_root_convergents(n): """ This function calculates every number of the sequence defined by frac function, and count the number of results that have a denominator with more digit than the numerator. """ i = 0 nb_frac = 0 num = 1 den = 2 while i < n: if i % 10 == 0: ...
def fibonacci(n): """Return the nth Fibonacci number.""" if n == 1: return 0 # r[i] will contain the ith Fibonacci number r = [-1] * (n + 1) r[0] = 0 r[1] = 1 for i in range(2, n + 1): r[i] = r[i - 1] + r[i - 2] return r[n - 1]
def sort(tupleo, key=None, reverse=False): """ sort(...) method of tupleo.tuple instance T.sort(tupleo, key=None, reverse=False) -> None -- stable sort *IN PLACE tuple, tupleo* """ if type(tupleo) != tuple: raise TypeError("{} is not tuple".format(tupleo)) convertlist = list(tupleo) ...
def mobile_path(s: str) -> bool: """ Checks if path specified points to a phone On windows, path can have a drive letter and that adds : to the path. To overcome that we only check for `:` that is not the second letter of string, where the drive letter colon should always be. """ return s.fi...
def ensure_list(val): """Converts the argument to a list, wrapping in [] if needed""" return val if isinstance(val, list) else [val]
def change_to_pubs_test(pubs_url): """ flips pubs urls to pubs-test urls to work around annoying apache config on test tier :param pubs_url: a pubs.er.usgs.gov url :return: a pubs-test.er.usgs.gov url """ pubs_test_url = pubs_url.replace('pubs.er', 'pubs-test.er') return pubs_test_url
def three_sum_closest(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # Like nomral 3-sum, but because we need to find the closest sum # thus we need bookkeeping and use offset to adjust scan direction. nums.sort() sum, dist = 0, 1 << 31 i = 0 while...
def trapezoidal(f, a, b, n=10000): """trapez method for numerical integration; same result for n = 100000""" s = 0.0 h = (b - a) / n for i in range(0, n): s += f(a + i * h) return h * (s + 0.5 * (f(a) + f(b)))
def locality(values, locdef): """ """ length = locdef[0] repeat = locdef[1] if repeat <= 1: return values values = [ values[i:i + length] * repeat for i in range(0, len(values), length) ] values = [item for sublist in values for item in sublist] return valu...
def strip_right_multiline(txt: str) -> str: """Useful for prettytable output where there are a lot of right spaces.""" return '\n'.join([x.strip() for x in txt.splitlines()])
def _check_ncluster_nquestions(n_questions, n_pairs, n_clusters): """ Args: n_questions (int): n_clusters (int): n_pairs (int): Returns: boolean """ if n_questions > n_pairs: return False elif n_questions * n_clusters > n_pairs: return False ...
def _earth_check( game_data ): """ Without will, an individual is unable to continue. """ for p in range(2): if game_data[str(p)]['will'] > game_data[str(p)]['earth']: game_data[str(p)]['will'] = game_data[str(p)]['earth'] if game_data['0']['will'] <= 0 and game_data['1']['will'] <= 0: game_data['game']['...
def subtract(matrix_a: list, matrix_b: list) -> list: """ Function for substracting two matrices :param matrix_a: the first input matrix :param matrix_b: the second input matrix :return: the result matrix """ result = matrix_a.copy() for i in range(len(matrix_a)): for j in range...
def arrays_to_list_of_tuples(arrays, colnames): """Convert a dict of arrays (as given by the numpy protocol handler) to a list of tuples""" first_array = arrays[colnames[0]] return [tuple(arrays[colname][i] for colname in colnames) for i in range(len(first_array))]
def contestant_pick_again_swap(adjusted_stage, contestant_first_pick): """Contestant swaps choices with the remaining door.""" if contestant_first_pick == 0: if adjusted_stage[1] == -1: return 2 else: return 1 elif contestant_first_pick == 1: if adjusted_stage...
def solution(A): # O(N/2) """ Write a function to check if the input string is a palindrome. A palindrome is defined a string that reads the same backwards and forwards. >>> solution('citic') True >>> solution('thisisapalindromemordnilapasisiht...
def dict_raise_on_duplicates(ordered_pairs): """Reject duplicate keys.""" d = {} for k, v in ordered_pairs: if k in d: raise ValueError("duplicate key: %r" % (k,)) else: d[k] = v return d
def stringify(message, *args): """Return formatted message by applying args, if any.""" if args: return u'%s\n' % (message % (args)) else: return u'%s\n' % (message)
def set_shared_crosshear(dashboard): """Enabled Shared Crosshear.""" if 'graphTooltip' not in dashboard.keys(): return dashboard dashboard['graphTooltip'] = 1 return dashboard
def get_comping_long_help(self) -> str: """Returns the long help associated with process or action object. Defaults to the docstring of the wrapped object, if available; otherwise a null string.""" try: text = self.obj.__comping__.long_help if text: return text except Attribu...
def append(list, item): """Return a list with the given item added to the end.""" if list == (): return (item, ()) else: head, tail = list return (head, append(tail, item))
def files_constraint(session, types): """ This function... :param session: :param types: :return: """ return [("session", session), ("type", types)]
def StrChangeFileExt(FileName,NewExt): """ Example : StrChangeFileExt(FileName='1.txt',NewExt='py') set new extesion for file. """ return FileName[:FileName.rfind('.')+1]+NewExt
def is_page_publisher(user, page): """ This predicate checks whether the given user is one of the publishers of the given page. :param user: The user who's permission should be checked :type user: ~django.contrib.auth.models.User :param page: The requested page :type page: ~cms.models.pages.pa...
def mel2hz(mel): """Convert Mel frequency to frequency. Args: mel:Mel frequency Returns: Frequency. """ return 700*(10**(mel/2595.0)-1)
def _check_if_found(new_term: str, targets: list) -> bool: """ Checks if `new_term` matches `targets`. :param new_term: string to check :param targets: list of strings to match to `new_term`. Targets can be a list of specific targets, e.g. ['UBERON:123219', 'UBERON:1288990'] or of general ontol...
def ordinal_str(num: int) -> str: """ Converts a given integer to a string with an ordinal suffix applied, preserving the sign. :param num: Any integer, be it positive, negative, or zero. :return: The number as a string with the correct ordinal suffix applied. 0 becomes "0th", 1 becomes "1st", 10...
def extend_rsltdict(D, key, val, Extend=False): """Helper for form_delta() --- Given a result dictionary D, extend it, depending on the setting of Boolean Extend. For some dictionaries, duplicates mean "extend"; for others, that means error. This is a crucial helper used by "form_...
def replace_repeated_characters(text): """Replaces every 3+ repetition of a character with a 2-repetition.""" if not text: return text res = text[0] c_prev = text[0] n_reps = 0 for c in text[1:]: if c == c_prev: n_reps += 1 if n_reps < 2: res += c else: n_reps = 0 ...
def check_substation_LTC(new_ckt_info, xfmr_name): """Function to assign settings if regulator upgrades are on substation transformer """ subltc_dict = None if isinstance(new_ckt_info["substation_xfmr"], dict): if new_ckt_info["substation_xfmr"]["name"].lower() == xfmr_name: ...
def convert_encode(sequences, list_letters): """ Return list of vector encoding the sequences letters transformed in 1000, 0100, 0010, 0001""" dict_trad = {list_letters[0]:[1.,0.,0.,0.], list_letters[1]:[0.,1.,0.,0.], list_letters[2]:[0.,0.,1.,0.], list_letters[3]:[0.,0.,0., 1.] } final = [] for i in r...
def scan_runtime(step, fname): """ Find runtime of VPR log (if any), else returns empty str. """ try: with open(fname, 'r') as f: step_runtime = 0 total_runtime = 0 for line in f: if line.startswith("# {} took".format(step)): step_r...
def repeated(f, n, x): """Returns the result of composing f n times on x. >>> def square(x): ... return x * x ... >>> repeated(square, 2, 3) # square(square(3)), or 3 ** 4 81 >>> repeated(square, 1, 4) # square(4) 16 >>> repeated(square, 6, 2) # big number 184467440737095...
def round_upper_bound (value): """ This method expects an integer or float value, and will return an integer upper bound suitable for example to define plot ranges. The upper bound is the smallest value larger than the input value which is a multiple of 1, 2 or 5 times the order of magnitude (10**x...
def query(_port, prop, _repo=False): """Query a property of a package.""" if prop == "config": return False else: assert not "unknown package property '%s'" % prop
def fix(x, field): """ makes square field feels like Thor """ a = len(field) if x >= a: return x - a if x < 0: return x + a return x
def exists(var): """ Return a boolean value that indicate if a variable exists or not. Parameters ---------- var Variable to test Returns ------- bool Boolean that indicate the existance or not of the variable """ try: var except NameError: ...
def get_opacities(opacity): """ Provide defaults for all supported opacity settings. """ defaults = { 'wireframe' : 0.05, 'scalar_cut_plane' : 0.5, 'vector_cut_plane' : 0.5, 'surface' : 1.0, 'iso_surface' : 0.3, 'arrows_surface' : 0.3, 'glyphs' : 1...
def from_string(val): """escape a python string""" escape = val.translate( str.maketrans({ "'": "''", '\\': '\\\\', '\0': '\\0', '\b': '\\b', '\n': '\\n', '\r': '\\r', '\t': '\\t', # ctrl z: windows end-of-fi...
def cb_valid_actions(state): """ Helper function to return valid actions at conditional bandit states. Used for plotting maze. :param state: state tuple :return: list of valid actions """ if state == [3, 6]: return [2, 3] elif state == [9, 6]: return [2, 3] elif state ==...
def varintSize(value): """Compute the size of a varint value.""" if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: return 4 if value <= 0x7ffffffff: return 5 if value <= 0x3ffffffffff: return 6 if value <= 0x1ffffffffffff: retur...
def webotsToScenicPosition(pos): """Convert a Webots position to a Scenic position. Drops the Webots Y coordinate. """ x, y, z = pos return (x, -z)
def mininet_dpid(int_dpid): """Return stringified hex version, of int DPID for mininet.""" return str('%x' % int(int_dpid))
def get_all_pixels(coordinates): """Get all pixel coordinates, given the top left and bottom right.""" pixels = [] x1, y1 = coordinates[0] x2, y2 = coordinates[1] for ix in range(x1, x2 + 1): for iy in range(y1, y2 + 1): pixels.append((ix, iy)) return pixels
def MOSQ_MSB(A): """get most significant byte.""" return (( A & 0xFF00) >> 8)
def gridlookup(n, grid, valplace): """Check in which interval/ capital state valplace is""" ilow = 0 ihigh = n-1 distance = 2 while (distance > 1): inow = int((ilow+ihigh)/2) valnow = grid[inow] # The strict inequality here ensures that grid[iloc] is less tha...
def vertical_check(board: list): """ Check if board are ready for game in columns. Return True of False >>> print(vertical_check(board = ["**** ****","***1 ****","** 3****",\ "* 4 1****"," 9 5 "," 6 83 *","3 1 **"," 8 2***",\ " 2 ****"])) False """ for idx in range(...
def scan(str_data): """ Takes a string and scans for words, returning a list of words. """ return str_data.split()
def _InsertString(original_string, inserted_string, index): """Insert a string into another string at a given index.""" return original_string[0:index] + inserted_string + original_string[index:]