content
stringlengths
42
6.51k
def take_params(params,selection): """params: list selection: tuple """ params_sel = [] if type(selection) == int: selection = (selection,selection) for n in range(len(params)): if n in selection: params_sel.append(params[n]) return params_sel
def map_dict_keys(fn, d): """Transform {x: y} to {fn(x): y}.""" return dict((fn(k), v) for k, v in d.items())
def n_log(n, i=0): """answer""" if n / 2 < 1: return i return n_log(n/2, i+1)
def get_params_autogen(term): """Sets the parameters for the API call for the initial user-entered term""" params = { "action": "parse", "prop": "links", "page": term, "format": "json", } # Parameter set to query the Wikipedia page for a given term and retrieve up to 250 ...
def _two_days_apart_restricted_days(selected_course_day): """ input: selected day for one course, set days not available for the other courses """ # if selected_course_day == 'Wednesday': # raise Exception('Cannot have Wednesday for two days apart requirement') restricted_days = {'Monday'...
def o_dedup(seq): """ remove duplicates while preserving order https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def try_eval(expression): """ Returns an evaluated expression if possible. If not evaluatable the expression is returned. """ if expression: try: return eval(expression) except: pass return expression
def enum_value(enum_str): """Strip chars around enum value str. :param str enum_str: Enum value. """ return enum_str.strip(' \'')
def element_wise_product(A, B): """ Returns `hadamard_product` from a pair of matrix with matching dimensions. Parameters ---------- A : list The given left-hand side matrix. B : list The given right-hand side matrix. Returns ------- hadamard_product : list (mat...
def _path_is_absolute(path): """Returns `True` if `path` is an absolute path. Args: path: A path (which is a string). Returns: `True` if `path` is an absolute path. """ return path.startswith("/") or (len(path) > 2 and path[1] == ":")
def get_select_all_query(table_name): """ Returns a SELECT all query for the provided :param table_name :param table_name: Name of table :return: The string "SELECT * FROM :param table_name" """ return "SELECT * FROM " + str(table_name)
def compare_and_filter(prevs, news): """ input: both are dictionaries of (game_id, event) returns: dictionary of (game_id, row_data) of new data """ to_write = {} for k, v in news.items(): if not prevs.get(k) or prevs.get(k) != v: to_write[k] = v else:...
def space_tokenize_with_eow(sentence): """Add </w> markers to ensure word-boundary alignment.""" return [t + "</w>" for t in sentence.split()]
def overlap(a, b): """ Checks to see if two casings intersect, or have identical start/end positions. """ # If the casing start/end intersects intersect = (a[0] > b[0] and a[0] < b[1]) or (a[1] > b[0] and a[1] < b[1]) # If the casings start or end in the same place overlap = (a[0] == b[0]) o...
def _get_short_from_big_endian_bytearray(array, offset): """ Get a short from a byte array, using big-endian representation, starting at the given offset :param array: The byte array to get the short from :type array: bytearray :param offset: The offset at which to start looking :type offse...
def tribonacci_number(N): """ Closed-form formula to calculate the Nth Tribonacci number. Of course, no one would expect this in an interview :) """ a1 = (19 + 3 * 33**0.5)**(1 / 3) a2 = (19 - 3 * 33**0.5)**(1 / 3) b = (586 + 102 * 33**0.5)**(1 / 3) numerator = 3 * b * (1 / 3 * (a1 + a2 ...
def to_internal_repr(addrx): """Returns a bytearray twice the length of the given address so that each nibble may be indexed """ assert type(addrx) is bytes addri = bytearray() for b in addrx: addri.extend([b >> 4, b & 0xf]) return addri
def _make_dict(kwarg_str): """ Takes a string with arguments and returns a dict example >>> _make_dict("red=1, green=2, blue=3") >>> {'red':1, 'green':2, 'blue':3} >>> _make_dict("red='age', green=2, blue=3") >>> _make_dict("red=df, green=2, blue=3") """ def _eval2dict(**kwargs): ...
def authorize_security_group_ingress(ec2_c, sg_id, port): """ Alows us to open a TCP port. """ try: ec2_c.authorize_security_group_ingress( GroupId=sg_id.id, IpPermissions=[{ 'IpProtocol': 'tcp', 'FromPort': int(port), 'ToPort': int...
def merge(arrA, arrB): """Merge two sorted arrays. :param arrA (list): First/left list to be merged. :param arrB (list): Second/right list to be merged. :return merged_arr (list): Resulting merged list. """ merged_arr = [] # Start with a blank list while arrA and arrB: # Loop until at lea...
def GetLibFuzzerOption(option_name, option_value): """Gets the libFuzzer command line option with the specified name and value. Args: option_name: The name of the libFuzzer option. option_value: The value of the libFuzzer option. Returns: The libFuzzer option composed of |option_name| and |option_va...
def returnInput(*args): """ This is a function that returns exactly what is passed to it. Useful to hold a place in the dataflow without modifying the data. """ if len(args) == 1: # A single argument has been passed and is now packaged inside a tuple because of *. # Unpack it: ...
def _get_indentation(string): """Return the number of spaces before the current line.""" return len(string) - len(string.lstrip(' '))
def vector(b,e): """Subtracts two vectors. Parameters ---------- v : list First 3D vector. e : list Second 3D vector. Returns ------- tuple Returns the vector `e` - `v`. Examples -------- >>> from .pycgmKinetics import vector >>> v = [1,2,3] ...
def isprime(n): """Returns True if N is a prime number, False otherwise.""" if n != int(n) or n < 1: return False p = 2 while p < n: if n % p == 0: return False p += 1 return True
def options(item_id: int) -> dict: """ Example function """ return { 'options': 'post' }
def get_span(num_samples, sample_rate): """ Gets the span of some consecutive samples in seconds. The *span* of consecutive samples is defined as the time elapsed from the first sample to the last sample. The span of zero samples is defined to be zero. :Parameters: nu...
def is_edit_mode(request): """ Return whether edit mode is enabled; output is wrapped in ``<div>`` elements with metadata for frontend editing. """ return getattr(request, '_fluent_contents_edit_mode', False)
def __evaluate_string(p_value, p_operator, target_value): """ :param p_value: :param p_operator: :param target_value: :return: """ if p_operator == "in_list": if p_value in target_value: return True else: return False if p_operator == "contains":...
def spawned_fishes(fish, days): """ Fish are independent, so each of them can be processed separately. This function computes the number of fish that will have spawned after X days from a single fish """ # build a dict of {day: spawns} bank = {fish: 1} days_to_process = [i for i in bank....
def make_2d_constant_array(width, height, value): """ Create a width-by-height array with each cell as a given value. For example, the call make_2d_constant_array(5, 5, 0) would return: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, ...
def get_modelpath_and_name(savedmodel_path): """ Help function which returns the full path to a model, excluding the epoch number at the end, e.g. "./mybestmodel-40" returns "./mybestmodel". """ return savedmodel_path[:savedmodel_path.rfind("-")]
def arr2dict(arr,keyname="key",valuename="value"): """ arr2dict - transform an array to dictionary key: """ res = {} for item in arr: res[item[keyname]]= item[valuename] if valuename in item else None return res
def sub_val(objective:str, selector:str="@s", value:int=0): """ objective:str -> The id of the scoreboard selector:str -> The entity of which scoreboard value needs to be changed value:int -> The Value that needs to be subtracted to the specific scoreboard (ONLY +ve) """ if value < 0: r...
def reward_min_delay(state, *args): """Minimizing the delay Reward definition 1: Minimizing the delay Params: ------ * state: ilurl.state.State captures the delay experienced by phases. Returns: -------- * ret: dict<str, float> keys: tls_ids, values: rewards Refer...
def unit_split(trace): """ Takes trace in form of["A-B-C", "A"], splits into list [["A","B","C"], ["A"]] :param trace: :return: """ lists = [] for event_list in trace: lists.append(event_list.split("-")) return lists
def normalize(block): """ Normalize a block of text to perform comparison. Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace from each line. """ assert isinstance(block, str) block = block.strip("\n") return [line.rstrip() for l...
def test_is_dict(input): """ Simple test that returns true if item is a dictionary """ return isinstance(input, dict)
def check_sentence_quality(left_match_right): """ Take a tuple with the left and right side of the matched word and check a few conditions to determine whether it's a good example or not Args: left_match_right (tuple): a tuple of three strings: the left side of the NKJP match, the m...
def get_prop_type(value, key=None): """ Performs typing and value conversion for the graph_tool PropertyMap class. If a key is provided, it also ensures the key is in a format that can be used with the PropertyMap. Returns a tuple, (type name, value, key) """ # if isinstance(key, unicode): #...
def in_real_grid(pos): """ Checks if the given position is on the game field. """ if 40 <= pos[0] <= 840 and 40 <= pos[1] <= 840: return True return False
def _add_base(base, **kwargs): """Return Dockerfile FROM instruction to specify base image. Parameters ---------- base : str Base image. """ return "FROM {}".format(base)
def get_url(urn, page=1, part=200): """From a representaion of URN (serial number or any string with serial number) - mapped to digibok""" import re urnserial = re.findall('[0-9]+', str(urn)) if urnserial != []: urnserial = urnserial[0] else: return "" urn = "URN:NBN:no-nb_d...
def switch_player(mark): """Switches player's marks to play next turn.""" return 'O' if mark == 'X' else 'X'
def join_cuts(*list_of_cuts): """Joins list of cuts (strings) into something ROOT can handle. Example: given ('1<2','','5>4') returns '1<2&&5>4'""" list_of_nonempty_cuts = [] for cut in list_of_cuts: if cut: list_of_nonempty_cuts.append(cut) return '&&'.join(list_of_nonempty_cut...
def differentiate(coefficients): """ Calculates the derivative of a polynomial and returns the corresponding coefficients. """ new_cos = [] for deg, prev_co in enumerate(coefficients[1:]): new_cos.append((deg + 1) * prev_co) return new_cos
def _build_namespace(resource: dict): """Given a resource dictionary, returns a full Terraform namespace for the resource. Args: resource (dict): the resource dictionary parsed from the remote state file Returns: A string respresenting the full Terraform namespace. For example: mod...
def parser_target_background_grid_Descriptor(data,i,length,end): """\ parser_background_grid_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "background_grid", "contents" : unparsed_descriptor_content...
def embed_hex(runtime_hex, python_hex=None): """ Given a string representing the MicroPython runtime hex, will embed a string representing a hex encoded Python script into it. Returns a string representation of the resulting combination. Will raise a ValueError if the runtime_hex is missing. ...
def extract_gif_param(proc: str): """ Extracts the parameter for an animated GIF, currently just the frame display duration in milliseconds, from a string that ends with an integer, in parentheses. """ a = proc.strip(")").split("(") assert len(a) == 2 return int(a[1])
def main_RNA(dna): """Transcribing DNA into RNA.""" valid_dna = 'ACGT' if not (all(i in valid_dna for i in dna)): # not a valid DNA raise Exception('Input Error') return dna.replace('T', 'U')
def myAdd(num1, num2): """The myAdd function takes two arguments (num1 and num2) and adds them together to create a nre variable (arg_sum) which is returned to the user. The value needs to be printed outside of the function either by passing it to a new variable or wrapping it in the print() method....
def map_distance(mapping1, mapping2): """ Measures the distance of any two mapped reads based on a mapping to a common reference :param mapping1: A mapping of a read to a reference :param mapping2: A mapping of another read to the same reference :return: an integer score corresponding to the number ...
def get_probabilities(histogram: dict) -> dict: """ Pl {"a":20,"b":80} -> {"a":0.2,"b":0.8} """ sum_ = sum(histogram.values()) return {k: (v / sum_) for k, v in histogram.items()}
def iob2_iobes(tags): """ IOB -> IOBES """ new_tags = [] for i, tag in enumerate(tags): if tag == 'O': new_tags.append(tag) elif tag.split('-')[0] == 'B': if i + 1 != len(tags) and \ tags[i + 1].split('-')[0] == 'I': new_tags.app...
def isInt(val): """ Return (bool) whether the input is a integer """ return val == int(val)
def thin_string_list(list_of_strings, max_nonempty_strings=50, blank=''): """Designed for composing lists of strings suitable for pyplot axis labels Often the xtick spacing doesn't allow room for 100's of text labels, so this eliminates every other one, then every other one of those, until they fit. >...
def channel_filter(channel, channel_spec): """ Utility function to return True iff the given channel matches channel_spec. """ if isinstance(channel_spec, int): return channel == channel_spec if isinstance(channel_spec, tuple): return channel in channel_spec raise ValueError("Inc...
def detect_number(angle): """ Return the dialed number based on the minimum rotation achieved. Starting at 360 degrees, we subtract the rotation. These values were determined by observation. """ if angle < 32: return 0 elif angle < 63: return 9 elif angle < 94: r...
def get_subs(n): """Get list of all possible n-length sequences of genes""" from itertools import product return [''.join(sub) for sub in product('CATGN', repeat=n)]
def format_label(sl, fmt=None): """ Combine a list of strings to a single str, joined by sep. Passes through single strings. :param sl: :return: """ if isinstance(sl, str): # Already is a string. return sl if fmt: return fmt.format(*sl) return ' '.join(str(s...
def tstv(ts, tv): """ Calculate ts/tv, and avoid division by zero error """ try: return round(float(ts) / float(tv), 4) except ZeroDivisionError: return 0
def property_name_to_column_name(name: str) -> str: """Convert names like "To do" to "to_do".""" return name.replace(" ", "_").lower()
def int_to_bytes(x): """ 32 bit int to big-endian 4 byte conversion. """ assert x < 2 ** 32 and x >= -(2 ** 32) return [(x >> 8 * i) % 256 for i in (3, 2, 1, 0)]
def algorithm_2(array: list) -> int: """ Algorithm 2 - Brute Force Optimized It is easy to make Algorithm 1 more efficient by removing one loop from it. This is possible by calculating the sum at the same time when the right end of the subarray moves. The time complexity is O(n^2). """ ...
def API_error(description): """Create an API error message.""" return {"status": "error", "error": description}
def strHypInd(i, j): """ Returns string identifier for a hyperplane of ith and jth observation, regardless of ordering. """ if i > j: i, j = j, i return str(i) + '-' + str(j)
def whack_a_mole_model(dictionary): """ Too lazy to do it properly, but we need to replace numpy types in dicts. :param dictionary: :return: """ if dictionary is not None: try: dictionary = {int(k):int(v) for k, v in dictionary.items()} except TypeError: d...
def leadingzero(number, minlength): """ Add leading zeros to a number number: The number to add the leading zeros to minlength: If the number is shorter than this length than add leading zeros to make the length correct """ return str(number).zfill(int(minlength))
def parse_index(idx): """ Parsing user-provided index (which seqs to write) """ if idx == '0': return None x = idx.split('-') if len(x) > 1: return set([x for x in range(int(x[0]), int(x[1])+1)]) return set([int(x) for x in idx.split(',')])
def replaceFontName(fontName, replacementDict): """ Replaces all keys with vals from replacement_dict in font_name. """ for key, val in replacementDict.items(): fontName = fontName.replace(key, val) return fontName
def get_base_by_color(base): """ Get color based on a base. - Uses different band of the same channel. :param base: :return: """ if 250.0 <= base <= 255.0: return 'A' if 99.0 <= base <= 105.0: return 'C' if 180.0 <= base <= 185.0: return 'G' if 25.0 <= bas...
def dict_to_cols(dict_obj, cols): """Converts a dict to a cliff-compatible value list. For cliff lister.Lister objects, you should use list_to_cols() instead of this function. 'cols' shouls be a list of (key, Name) tuples. """ values = [] for col in cols: values.append(dict_obj.get(...
def is_shuffle(s1, s2, s3): """ Runtime: O(n) """ if len(s3) != len(s1) + len(s2): return False i1 = i2 = i3 = 0 while i1 < len(s1) and i2 < len(s2): c = s3[i3] if s1[i1] == c: i1 += 1 elif s2[i2] == c: i2 += 1 else: return False i3 += 1 return True
def check_model_structure(model): """Checks the model structure to see if it contains all the needed keys """ return (isinstance(model, dict) and 'resource' in model and model['resource'] is not None and ('object' in model and 'model' in model['object'] or 'model' in mo...
def get_tool_id(tool_id): """ Convert ``toolshed.g2.bx.psu.edu/repos/devteam/column_maker/Add_a_column1/1.1.0`` to ``Add_a_column`` :param str tool_id: a tool id, can be the short kind (e.g. upload1) or the long kind with the full TS path. :returns: a short tool ID. :rtype: str """ if ...
def to_arcgis_date(datetime_obj): """ Converts a datetime to an ArcGIS timestamp. :param datetime_obj: A datetime.datetime :return: An int expressing the same date/time as an ArcGIS timestamp. """ if datetime_obj is not None: return datetime_obj.timestamp() * 1000 return None
def get_payout(inches: int) -> int: """Get payout according to inches (int) returns int""" # Return 2 to the power of inches removed from wingspan, times 10 return (2 ** inches) * 10
def sanitize_fb_return_data(results): """ Sometimes integers are returned as string try to sanitize this a bit Parameters ---------- results: dict dict of results from fritzconnection call Returns ------- dict: sanitized version of results """ return_results = {} ...
def _is_png(filename): """Determine if a file contains a PNG format image. Args: filename: string, path of the image file. Returns: boolean indicating if the image is a PNG. """ return '.png' in filename
def _r_long(int_bytes): """Convert 4 bytes in little-endian to an integer.""" return int.from_bytes(int_bytes, 'little')
def untokenize(tokens): """ Combine a list of tokens into a single string of text. """ return ' '.join(tokens)
def build_linked_data(location_number, location_name, agency_code, latitude, longitude, available_parameter_codes): """ Given site metadata, construct a dictionary / json-ld for the site. The constructed json-ld conforms to the context documents at https://opengeospatial.github.io/ELFIE/json-ld/elf-inde...
def _gr_pop_ ( graph , i = None ) : """Pop the point fro mthe graph >>> graph = ... >>> graph.pop ( 3 ) ## pop the point #3 >>> graph.pop ( ) ## pop th elast point """ if i is None : last = len ( graph ) if 1 <= last : point = graph [ -1 ] ...
def _to_boolean(val): """Retrieve the Boolean value of the provided input. If the value is a Boolean, return the value. Otherwise check to see if the value is in ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ] and return True if the value is not in the list. Parameters ...
def traditional_isf_equation(tdd): """ Traditional ISF equation with constants fit to Jaeb dataset """ a = 1800.8 return a / tdd
def _invert_dict(data): """{a: [b]} -> {b: [a]}""" inv_dict = {} for key in data.keys(): for value in data[key]: inv_dict[value] = inv_dict.get(value, []) + [key] return inv_dict
def calculate_manhattan_dist(idx, value, n): """calculate the manhattan distance of a tile""" if value == 0: return 0 value_x, value_y = idx // n, idx % n sol_x, sol_y = value // n, value % n return abs(sol_x-value_x) + abs(sol_y-value_y)
def is_triggerable(obj): """Check if ``obj`` can handle the bot's triggers. :param obj: any :term:`function` to check :return: ``True`` if ``obj`` can handle the bot's triggers A triggerable is a callable that will be used by the bot to handle a particular trigger (i.e. an IRC message): it can be ...
def remove_markers(text): """ strip out asterics and hashes from the file""" markers = "*#" for char in markers: text = text.replace(char, "") return text
def generateTileDir(startX, startY, stopX, stopY): """Generate the name of a tile based on its location""" tileString = 'tile_' + str(startX) + '_' + str(startY) + '_' + str(stopX) + '_' + str(stopY) return tileString
def skip_member(app, what, name, obj, skip, options): """ Determine of a name should be skipped when listing methods. We override this to allow __init__ to be listed. """ del app, what, obj, options if name == "__init__": return False return skip
def _get_reduce_out_dim(keep_dims, x_dim, x_ndim, batch_axis): """get out_dim for reduce* operation.""" if keep_dims: out_dim = x_dim else: out_dim = 0 for i in range(x_ndim): if i == x_dim: break if i in batch_axis: continue ...
def initialBoardState(numCards=52): """Create a board that can display the current state of the game, i.e. whether any given card has been correctly matched yet, or not""" displayBoard = [] for n in range(0, numCards): displayBoard.append('U') return displayBoard
def first_order(t: float, q: list, k: float, q_index: int) -> float: """Simple first-order rate function. :param t: model time :param q: Vector (list) of mass distribution through compartments :param k: Time constant of the rate function. :param q_index: Index within q on which th...
def _update_set(index, n_qubits): """The bits that need to be updated upon flipping the occupancy of a mode.""" indices = set() # For bit manipulation we need to count from 1 rather than 0 index += 1 while index <= n_qubits: indices.add(index - 1) # Add least significant one to...
def _compute_explicit_padding(kernel_size, dilation_rate): """Compute the necessary padding based on kernel size and dilation rate.""" if isinstance(kernel_size, int): kernel_size = [kernel_size, kernel_size] if isinstance(dilation_rate, int): dilation_rate = [dilation_rate, dilation_rate] kernel_size_e...
def split_chunks(x): """split x into lists(chunks) according to Bool val. Ie. [T, T, F, T, T] -> [[T, T], [F], [T, T]] This allows for use in get_optimal_chunks()""" chunks = [] previous = None for sample in x: if sample != previous: chunks.append([]) chunks[-1].append(sa...
def int_to_bytes(i: int) -> bytes: """Convert an integer to its WAMP bytes representation. Args: i: Integer to convert. Returns: Byte representation. """ return i.to_bytes(3, "big", signed=False)
def lr_schedule(epoch): """ Returns a custom learning rate that decreases as epochs progress. """ learning_rate = 0.2 if epoch > 10: learning_rate = 0.02 if epoch > 20: learning_rate = 0.01 if epoch > 50: learning_rate = 0.005 return learning_rate