content
stringlengths
42
6.51k
def LeaveOneOut(seq, pos): """Return a new list, with element at the given position removed.""" return [v for i, v in enumerate(seq) if i != pos]
def convert_product_id_to_name(id): """ Given product id number, return product name """ product_id_to_name = {} if id in product_id_to_name: return product_id_to_name[id] else: return id
def intersects(s1 : set, s2 : set): """Return true if the intersection of s1 and s2 is non-empty.""" if len(s1) > len(s2): s1, s2 = s2, s1 return any(x in s2 for x in s1)
def unzip(zipedList): """ unzips """ temp = list( zip( *zipedList ) ) return list( temp[0] ), list( temp[1] )
def list_of(obj, keep_none=False): """Filters out None from the list. If object is provided, puts it in the list""" if obj is None: return [None] if keep_none else [] else: if type(obj) == list: return [o for o in obj if keep_none or o is not None] return [obj]
def shipSkinNameToToolName(skinName : str) -> str: """Construct a name of a shipSkinTool from the name of the skin of the skin. :param str skinName: The name of the skin this tool name should reference :return: The name that should be given to a shipSkinTool that applies the named shipSkin """ retu...
def others(state, alive=True): """ Get a dictionary of other players. :param state: The current game state. :returns: (dict) {id: player data, ...} """ me = state['current_player'] all_players = state['gladiators'] others = {i: g for i, g in enumerate(all_players) if i != me} if al...
def convert_geo(val): """Convert 36-00-36.3550N to decimal""" tokens = val.strip()[:-1].split("-") number = ((float(tokens[2]) / 60.0) + float(tokens[1])) / 60.0 + float( tokens[0] ) if val[-1] in ["W", "S"]: number = 0 - number return number
def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ dict = {} count = 1 max_count = 0 for letter in list(s): key, value = letter, count if key not in dict: dict[key] = [value] else: dict[key].append(value) nonrepeated_list...
def _make_pretty_usage(usage): """ Makes the usage description pretty and returns a formatted string. Otherwise, returns None. """ if usage is not None and usage.strip() != "": usage = "\n".join(map(lambda u: u.strip(), usage.split("\n"))) return "%s\n\n" % usage
def pwr2enr(pwr, time): """ This function converts the power given in [W] to the corresponding energy [J], depending on the input time given in [s] Parameters ---------- pwr : float The power given in [W]. time : float The time given in [s]. Returns ------- enr ...
def knapsack(val, wt, W): """ Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack """ n = len(val) table = [ [0]*(W + 1) for i in range(n + 1) ] for i in range(1, n + 1): for w in range(1, W + 1): if wt[i - 1] <= W: table[...
def find_endurance_tier_iops_per_gb(volume): """Find the tier for the given endurance volume (IOPS per GB) :param volume: The volume for which the tier level is desired :return: Returns a float value indicating the IOPS per GB for the volume """ tier = volume['storageTierLevel'] iops_per_gb = 0...
def _replaceRenamedPairMembers(kerning, leftRename, rightRename): """ Populate the renamed pair members into the kerning. """ renamedKerning = {} for (left, right), value in kerning.items(): left = leftRename.get(left, left) right = rightRename.get(right, right) renamedKernin...
def gfMDS_make_cmd_string(info): """ Purpose: Construct the command line options string passed to the MDS C code. Usage: Author: PRI Date: May 2018 """ # create the input files string in_files = info["in_file_paths"][0] for in_file in info["in_file_paths"][1:]: in_files ...
def get_item(obj: object, k: str): """Template tag to get object field value or dict value.""" if isinstance(obj, dict): return obj.get(str(k)) return getattr(obj, str(k), None)
def get_L_exon_num(exon_num): """20% of exons must be affected to lost the gene.""" if exon_num == 1: return 1 elif exon_num <= 10: return 2 else: twenty_perc = exon_num / 5 return twenty_perc
def cast_bool_to_yesno(value): """Returns "Yes" if a passed boolean value is True else False.""" return "Yes" if value is True else "No"
def slice_repr(slice_obj): """ Get the best guess of a minimal representation of a slice, as it would be created by indexing. """ slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step] if slice_items[-1] is None: slice_items.pop() if slice_items[-1] is None: if slice...
def parseResources(chunk): """ Takes a chunk of log text that includes the "Partitionable Resources" table and returns a parsed dict of {"diskUsage": xxx, "memUsage": yyy } :chunk: The text block containing the Partitional Resources table from standard HTCondor output. :returns: Dictionary of the f...
def nm_to_u(s): """Get the user part of a nickmask. (The source of an Event is a nickmask.) """ s = s.split("!")[1] return s.split("@")[0]
def _swap_curly(string): """Swap single and double curly brackets""" return (string .replace('{{ ', '{{') .replace('{{', '\x00') .replace('{', '{{') .replace('\x00', '{') .replace(' }}', '}}') .replace('}}', '\x00') .replace('}'...
def mod_depth_to_sideband_power(gamma): """Takes in modulation depth, returns the total sideband power: p = 2 (gamma^2/4) """ sideband_power = gamma**2 / 2 return sideband_power
def min_and_max(iterable): """Efficiently get the min and max of an iterable Args: iterable (Iterable): An iterable whose elements can all be compared with each other Returns: tuple(min, max) """ minimum = iterable[0] maximum = iterable[0] for value in iterable: ...
def _check_method(obj, meth): """Check that an object obj has a method meth.""" if not hasattr(obj, meth): return False return callable(getattr(obj, meth))
def left_edge(lines): """ Gets the left left_tile_edge of the lines. Args: lines (list[str]) Returns: str: The `left_tile_edge` of the lines. """ return "".join(line[0] for line in lines)
def _make_sql_url(hostname, database, **kwargs): """Build a URL for SQLAlchemy""" url = hostname if kwargs.get("port"): url = "{}:{}".format(url, kwargs["port"]) if kwargs.get("user"): credentials = kwargs["user"] if kwargs.get("password"): credentials = "{}:{}".forma...
def remove_properties_and_basics(resource_data): """ Given a mapping of resource_data attributes to use as "kwargs", return a new mapping with the known properties removed. """ return dict([(k, v) for k, v in resource_data.items() if k not in ('type', 'base_name', 'extension', 'path', 'n...
def maxVal(toConsider, avail): """Assumes toConsider a list of items, avail a weight Returns a tuples of the total value of a solution to the 0/1 knapsack problem and the items of that solution""" if toConsider == [] or avail == 0: result = (0, ()) elif toConsider[0].getCost() > avail: ...
def is_prime(input_num): """ Checks if an input number is prime and returns a boolean value :param input_num: Input number to check :return: True if prime, False if not prime """ # Flag to keep track if a number is prime prime_flag = True # If number is under 2, it's not prime if ...
def is_empty(obj): """ These conditions are considered empty s = [], s = None, s = '', s = ' ', s = 'None' """ if isinstance(obj, str): obj = obj.replace('None', '').strip() if obj: return False return True
def compute_classification_accuracy(correctly_classified, incorrectly_classified): """ Computes the accuracy of the model based on the number of correctly and incorrectly classified points. Expresses accuracy as a percentage value. :param correctly_classified: count of correctly classified data points ...
def sqrt(x): """Return square root of x""" return x ** (0.5)
def greet(adventurer: str) -> str: """ returns a greeting string that greets the title cased adventurers name >>> greet('bob') 'Hello Brave Bob' :param adventurer: the name of the adventurer to greet :return: a greeting "Hello ..." """ return f"Hello Brave {adventurer.title()}"
def normalize(text: str) -> str: """Remove whitespace, uppercase, convert spaces to underscores""" return text.strip().upper().replace(' ', '_')
def update_varSum(idx_new, series, win_size, prevVal=None): """ Returns the power sum average based on the blog post from Subliminal Messages. Use the power sum average to help derive the running variance. sources: http://subluminal.wordpress.com/2008/07/31/running-standard-deviations/ Keyword...
def parallel_helper(obj, methodname, *args, **kwargs): """Workaround for Python 2 limitations of pickling instance methods Parameters ---------- obj methodname *args **kwargs """ return getattr(obj, methodname)(*args, **kwargs)
def get_rst_bullet_list_item(text, level=1): """ Return a list item in the RST format """ item = '* ' + str(text) + '\n' return item
def helper2(lst_nodes): """Helper function to convert given list of neighbor nodes to dictionary with string type keys""" neighbors = {} for node in lst_nodes: neighbors[node[0].value] = node return neighbors
def get_fnone(fsize): """ Get sentinel value for filesize when writing OS/radio links. :param fsize: Filesize. :type fsize: int """ return True if fsize is None else False
def l1sub(data, placeholder): """Substitutes data with a character (default: *). :param data: list or string: Data containing one or more values :param placeholder: int or string: <br />If int: Not used in code but allows to call this function with the standard (data,level) format ...
def toVName(name, stripNum=0, upper=False): """ Turn a Python name into an iCalendar style name, optionally uppercase and with characters stripped off. """ if upper: name = name.upper() if stripNum != 0: name = name[:-stripNum] return name.replace('_', '-')
def translate_flags(argmap, args): """ Translates flags in 'args' using 'argmap' for the new value. If 'args' key is not found in 'argmap', it is ignored. New dictionary with the translated flags is returned.""" params = {} # Loop through operation results to translate dashes off flags if len(ar...
def get_rsb_texture_name(filename: str) -> str: """Match source texture names to RSB texture names that were shipped""" ext = filename.lower()[-4:] newfilename = filename if ext in (".bmp", ".tga"): #Replace extension with .RSB newfilename = newfilename[:-4] newfilename += ".RSB"...
def trim(d, prepended_msg): """remove the prepended-msg from the keys of dictionary d.""" keys = [x.split(prepended_msg)[1] for x in d.keys()] return {k:v for k,v in zip(keys, d.values())}
def int_to_words(int_val, word_size, num_words): """ :param int_val: Unsigned integer to be divided into words of equal size. :param word_size: Width (in bits) of each unsigned integer word value. :param num_words: Number of unsigned integer words expected. :return: A tuple contain unsigned integ...
def variation_descriptors(civic_vid99, civic_vid113, civic_vid1686): """Create test fixture for variants.""" return [civic_vid99, civic_vid113, civic_vid1686]
def raw_headers_to_dict(raw_headers): """ :param raw_headers: head and trail no \n :return: headers dcit """ a = raw_headers.split('\n') b = dict([x.split(": ", 1) for x in a]) return b
def prepare_data_for_piechart(data, unit='jobs', cutoff=None): """ prepare_data_for_piechart data ... result of a queryset unit ... 'jobs', or 'jobDefs', or 'jobSets' cutoff ... anything with share smaller than cutoff percent will be grouped into 'Other' ...
def cmmdc(x, y): """Computes CMMDC for two numbers.""" if y == 0: return x return cmmdc(y, x % y)
def split_seq(seq, n_jobs): """ Splits a 'seq' in 'n_jobs' groups of items. """ newseq = [] splitsize = int(len(seq)/n_jobs) for i in range(0, n_jobs): newseq.append(seq[i*splitsize:i*splitsize+splitsize]) newseq_count = sum(len(s) for s in newseq) if newseq_count < len(seq): ...
def FormatKey(key): """Normalize a key by making sure it has a .html extension, and convert any '.'s to '_'s. """ if key.endswith('.html'): key = key[:-len('.html')] safe_key = key.replace('.', '_') return '%s.html' % safe_key
def dc_average_from_dc_values( dc_electrical_value: float, dc_thermal_value: float ) -> float: """ Determines the average demand covered across both electrical and thermal outputs. :param dc_electrical_value: The value for the electrical demand covered. :param dc_thermal_value: The...
def multi_replace(text, patterns): """Replaces multiple pairs in a string Arguments: text {str} -- A "string text" patterns {dict} -- A dict of {"old text": "new text"} Returns: text -- str """ for old, new in patterns.items(): text = text.replace(old, new) retu...
def largest_differing_bit(value1, value2): """ Returns index(from 0 to 127) of largest differing bit: Eg. for argument 011010...0 and 011110...0 it returns 3. :param value1: First id :param value2: Second id :return: index(from 0 to 127) of largest differing bit. """ distance = value1 ^ valu...
def to_tag(name): """ Creates a XML tag from a given string. """ temp = name.lower().replace(' ', '_') temp = temp.replace('fir_', 'FIR_') temp = temp.replace('a0_', 'A0_') return temp
def get_romb_offset(rom_slot, rom_split, rom_bases, roms_file=False): """ Get ROM slot offset in SPI Flash or ROMS.ZX1 file :param rom_slot: ROM slot index :param rom_split: Slot number where rom binary data is split in two :param rom_bases: Offsets for ROM binary data :param roms_file: If True,...
def get_date_time_from_timestamp(timestamp): """Get the date time from a timestamp. The timestamp must have the following format: 'year.month.day.hour.minutes' Example: '2017.12.20.10.31' -> '2017/12/20 10:31' """ date_time_string = timestamp sp = timestamp.split('.') if len(sp) >= ...
def parameter_varmap(px, qx): """Return map `{(a, b): (u, v), ... }`.""" assert set(px) == set(qx), (px, qx) d = dict() for x in px: a = px[x]['a'] b = px[x]['b'] u = qx[x]['a'] v = qx[x]['b'] d[(a, b)] = (u, v) return d
def _check_args(args, **kwargs): """ Used internally by expect_response to check if an argument to the request exists and contains the correct data :param key: The argument to be checked, ex: params :param required: The required keys in the required argument's dictionary :param kwargs: The argum...
def epsg_code(geojson): """ get the espg code from the crs system """ if isinstance(geojson, dict): if 'crs' in geojson: urn = geojson['crs']['properties']['name'].split(':') if 'EPSG' in urn: try: return int(urn[-1]) except (T...
def validate_uuid4(uuid_string): """ Validate that a UUID string is in fact a valid uuid4. Happily, the uuid module does the actual checking for us. It is vital that the 'version' kwarg be passed to the UUID() call, otherwise any 32-character hex string is considered valid. """ ...
def remove_empty(values_to_select, project_values): """ Remove empty fields, create request for fields to be inserted on server Input: values_to_select: list of all variables selected from relay project_values: request returned by the relay (type: dictionary) Output: values_to_in...
def _int_bin_length(x): """Determine how many bits are needed to represent an integer.""" # Rely on the fact that Python's "bin" method prepends the string # with "0b": https://docs.python.org/3/library/functions.html#bin return len(bin(x)[2:])
def bitshift_right(case, caselen): """Shift bit by bit right, adding ones from the left""" bitshifts = [] for bit in range(1, caselen + 1): shift = "1" * bit + case[0:(len(case) - bit)] bitshifts.append(shift) return bitshifts
def pathsplit(path): """Splits a path into (head, tail) pair. This function splits a path into a pair (head, tail) where 'tail' is the last pathname component and 'head' is all preceding components. :param path: Path to split >>> pathsplit("foo/bar") ('foo', 'bar') >>> pathsplit("foo/bar...
def load_result(filename): """ Loads results from specified file """ inputs = open(filename, "r") lines = inputs.readlines() ls = [] for line in lines: ls.append(float(line.strip())) return ls
def generate_spreadsheet_from_sessions(sessions): """Generate spreadsheet data from a given session list. :param sessions: The sessions to include in the spreadsheet """ column_names = ['ID', 'Title', 'Description', 'Type', 'Code'] rows = [{'ID': sess.friendly_id, 'Title': sess.title, ...
def github_encode(s): """Github encode strings so for example "bootstrap frontend" => "bootstrap+frontend" """ return '+'.join(s.split())
def _getVersionTuple(v): """Convert version string into a version tuple for easier comparison. """ return tuple(map(int, (v.split("."))))
def add_suffix_if_exists(candidate, existing_names, suffix_patt="_v{}"): """ Append a auto-incrementing suffix to a candidate name as long as the candidate name is in the existing names. Parameters ---------- candidate : str Candidate name to add a suffix to if present in the existing names...
def _s(strs): """ Convert a byte array to string using UTF8 encoding. """ if strs is None: return None if isinstance(strs, bytes): return strs.decode('utf8') return list([s.decode('utf8') if s is not None else None for s in strs])
def ToHexSize(val): """Return the size of an object in hex Returns: hex value of size, or 'None' if the value is None """ return 'None' if val is None else '%#x' % len(val)
def histogram(n, num_list): """Return histograms of number and list""" lst = [] for i in range(n): count = 0 for num in num_list: if num == i: count += 1 lst.append(count) return lst
def even_and_odd(n: int) -> tuple: """ This function return two numbers NE and NO such as NE is formed by even digits of N and NO is formed by odd digits of N """ NE = ''.join(i for i in str(n) if not int(i) % 2) NO = ''.join(i for i in str(n) if int(i) % 2) if not NE: return (0, int(NO)) ...
def obtener_secciones(adn, n): """ (str, num) -> list of str >>> obtener_secciones('AATCGAATCC',5) ['AA', 'TC', 'GA', 'AT', 'CC'] >>> obtener_secciones('ATTGCTAAC',3) ['ATT', 'GCT', 'AAC'] >>> obtener_secciones('GAGATCTCAGT',2) ['GAGAT', 'CTCAGT'] obtiene secciones de una cadena co...
def strip_newsgroup_header(text): """Given text in "news" format, strip the headers, by removing everything before the first blank line. """ _before, _blankline, after = text.partition('\n\n') return after
def author(name): """ Returns a Twitter query-by-author-name that can be passed to Twitter.search(). For example: Twitter().search(author("tom_de_smedt")) """ return "from:%s" % name
def get_data_source(name): """Guesses data source from file name. If the name contains 'terr' then we guess terrestrial data, otherwise we assume satellite. Arguments ========= name : str File name Returns ======= int 0 if satellite, 1 if terrestrial """ i...
def full_igram_list(slclist): """Create the list of all possible igram pairs from slclist""" return [ (early, late) for (idx, early) in enumerate(slclist[:-1]) for late in slclist[idx + 1 :] ]
def count_through_grid(count, gridwidth): """ Generate row/column indices for a number of intergers. :param count: int, how many elements has the grid :param gridwidth: int, how wide is the grid :return: """ row = int(count / gridwidth) column = count - row * gridwidth return row, co...
def alphav_apikey_set(apikey, filename=None): """Store the Alphavantage Token in $HOME/.updoon_alphav Parameters: ----------- apikey : str The API Key from the Alphavantage Website. See https://www.alphavantage.co/support/#api-key filename : str Absolute path to the text wh...
def get_attr(obj, *args): """ Get nested attributes """ data = obj for key in args: if not isinstance(data, dict) and hasattr(data, '__dict__'): data = data.__dict__ # noinspection PyTypeChecker # LOGGER.debug('getting key [%s] of %s', key, data) if isinst...
def show_post(post_id: int) -> str: """Show the post with the given id.""" return f'Post {post_id}'
def LimiterG1forRSU(r): """Return the limiter for Roe-Sweby Upwind TVD limiter function. This limited is further used to calculate the flux limiter function given by Equation 6-137. Calculated using Equation 6-138 in CFD Vol. 1 by Hoffmann. """ # Equation 6-138 G = max(0.0, min(1.0,...
def build_facets(data): """ Data from facets-serves.json Data structure: { "services" : [ {"(type)": "quolab...ClassName", "id": "<name>"} ] } """ deprecated = {"casetree", "cache-id", "indirect"} services = [service["id"] for service in data["services"] if ...
def get_result_bits(n): """Returns a string of the bitvectors to be added to produce the final output. Take in an integer n, and return a string representing the bitvectors to be added together to produce the final multiplication result. Args: n: An integer, the number of bits in each bitvector """ bits ...
def cleanup_markdown_string(aString): """ Cleans up markdown so it looks a bit prettier - removes lots of empty lines - removes empty lines with lots of spaces. """ #print('debug:cleanup_markdown_string') import re # Remove spaces following new line. def strip_spaces_empty_lines(mat...
def indent_lines(message): """This will indent all lines except the first by 7 spaces. """ indented = message.replace("\n", "\n ").rstrip() return indented
def get_domain(link): """Short hand for splitting a cleaned source and returning the domaen ie. en.wikipedia.org""" return link.split('/')[0]
def _format_mac_string_to_bytes(mac_string): """ "00-11-22-33-44-55-66-77" -> [0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77] :param str mac_string: :return: the mac address as list of bytes :rtype: list """ return [int(b,16) for b in mac_string.split('-')]
def generator_expression(function, argument_list): """Apply a multivariate function to a list of arguments in a serial fashion. Uses Python's built-in generator expressions. Args: function: A callable object that accepts more than one argument argument_list: An iterable object of input arg...
def hi_to_lo(octets, signed=False): """Reads the given octets as a big-endian value. The function name comes from how such values are described in the packet format spec.""" octets = list(octets) if len(octets) == 0: return 0 # If this is a signed field (i.e., temperature), the highest-orde...
def parse_seconds_to_str(total_seconds: float = 0) -> str: """This is a function I wrote in a different project.""" def plural_check(n: float): return 's' if n > 1 else '' minutes, seconds = divmod(total_seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) ...
def pov_array(arr): """Convert an array to POV-Ray format, e.g. (0, 1, 2, 3) --> array[4] {0, 1, 2, 3} """ return "array[{}] {{{}}}".format(len(arr), ", ".join(str(x) for x in arr))
def encrypt(plaintext, key, cipher): """ Using Vignere cipher to encrypt plaintext. :param plaintext: plaintext to encrypt with given key and given cipher :param key: the key is appended until it has same length as plaintext; each character of the key decides which cipher to use to ...
def eval_cell(cell): """ evaluates the new cell that received the pawns from another cell return : 0 if nothing, 1 or -1 if not a full tower and 5 or -5 if full tower """ if not cell: return 0 x = 1 if len(cell) < 5 else 5 return x if not cell[-1] else -x
def sizeof_fmt(num): """ Formats number of bytes into a human readable form. From: """ for size in ['bytes', 'KB', 'MB', 'GB']: if -1024.0 < num < 1024.0: return "%3.1f %s" % (num, size) num /= 1024.0 return "%3.1f %s" % (num, 'TB')
def get_options_dict(activation, lstm_dims, lstm_layers, pos_dims): """Generates dictionary with all parser options.""" return { "activation": activation, "lstm_dims": lstm_dims, "lstm_layers": lstm_layers, "pembedding_dims": pos_dims, "wembedding_dims": 100, "rem...
def snakify(str_: str) -> str: """Convert a string to snake case Args: str_: The string to convert """ return str_.replace(" ", "_").lower()