content
stringlengths
42
6.51k
def RPL_SERVLIST(sender, receipient, message): """ Reply Code 234 """ return "<" + sender + ">: " + message
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num == 0: raise ValueError return None if num == 1: return '1' # appeasing tests with string seq = [0, ...
def _validate_tile_placement(tile_placement, prefix=None): """Validate the given ``tile_placement`` input. Warnings -------- This method is intended for internal use only. """ # Ensure tile placement value is valid valid = {"all", "lower", "upper"} if tile_placement.lower() not in vali...
def statistics(prediction, ground_truth, beta=1): """Computes performance statistics for classifiers. Parameters ---------- prediction : set Set of objects predicted to be labeled positive. ground_truth : set Set of objects actually labeled positive. beta : float, optional ...
def _remove_pad(line): """Remove the pad from the *line*.""" try: pad_length = ord(line[-1:]) except TypeError: # ord() was unable to get the value of the byte. return None if pad_length > len(line): # Pad length should be less than or equal to the length of the ...
def _strxor(plain_text: bytes, key: bytes) -> bytes: """returns encrypted plain text by repeatedly xoring it with key""" len_key = len(key) encoded = bytearray(len(plain_text)) for i, k in enumerate(plain_text): encoded[i] = k ^ key[i % len_key] return bytes(encoded)
def uint_to_little_endian_bytearray(number, size): """Converts an unsigned interger to a little endian bytearray. :param in number: The number to convert. :param in size: The length of the target bytearray. :rtype: [int] >>> uint_to_little_endian_bytearray(0x42, 1) [66] >>> uint_to_little_...
def pitch_from_midinum(m): """Return pitch of midi note number Midi note numbers go from 0-127, middle C is 60. Given a note number this function computes the frequency. The return value is a floating point number. """ # formula from wikipedia on "pitch" if m is None: return None ret...
def nn_string(value): """Returns a string that will be None (replaced by '').""" if value == None: return '' return value
def dec_bytes(data: bytes, sep: str= " "): """ Format a bytes() object as a decimal dump """ return sep.join(str(bval) for bval in data)
def circularArrayLoop( nums): """ :type nums: List[int] :rtype: bool """ def move(i): res = (i+nums[i])%len(nums) return res slow = move(0) fast = move(slow) while slow != fast: slow = move(slow) fast = move(move(fast)) fast = move(slow) if fast ==...
def count(it): """Returns how many values in the iterator (depletes the iterator).""" return sum(1 for _value in it)
def bytes_isalnum(x: bytes) -> bool: """Checks if given bytes object contains only alphanumeric elements. Compiling bytes.isalum compiles this function. This function is only intended to be executed in this compiled form. Args: x: The bytes object to examine. Returns: Result of ch...
def func_args(*args): """func. Parameters ---------- *args Returns ------- None, None, None, None args: tuple None, None, None """ return None, None, None, None, args, None, None, None
def remove_forbidden_keys(data): """Remove forbidden keys from data that are not needed in Socrata Args: data (list): A list of dictionaries, one per transactions Returns: list: A list of dictionariess, one per transaction, with forbidden keys removed """ # There are different for...
def configsection(config,section): """ gets the list of keys in a section Input: - config - section Output: - list of keys in the section """ try: ret = config.options(section) except: ret = [] return ret
def filter_keys(func, a_dict): """Return a copy of adict with only entries where the func(key) is True. Equivalent to the following in Python 3: {k:v for (k, v) in a_dict.items() if func(k)} """ return dict((k, v) for (k, v) in a_dict.items() if func(k))
def poly_lines_to_lines(polyline_list): """Convert a set of polylines to a simple lines (start and end points) Arguments: polyline_list {list} -- Set of polylines Returns: list -- Set of lines """ line_list = [] for polyline in polyline_list: prev_pt = None for...
def find_max_sub(l): """ Find subset with higest sum Example: [-2, 3, -4, 5, 1, -5] -> (3,4), 6 @param l list @returns subset bounds and highest sum """ # max sum max = l[0] # current sum m = 0 # max sum subset bounds bounds = (0, 0) # current subset start s = 0 ...
def estimateGalaxyMass(pot_ext, r_gal, G): """ Estimate the equivalent mass of galaxy by - pot_ext*r_gal/G Parameters: ------------- pot_ext: float the external potential of the center of the particle system r_gal: float the distance between the center of the particle system to the gal...
def calculate(a, b): """Calculate the dot product of two vectors of the same length.""" if len(b) != len(a): return None product = 0 for a_i, b_i in zip(a, b): try: product += a_i * b_i except TypeError: return None return product
def generic_strategy_wrapper(player, opponent, proposed_action, *args, **kwargs): """ Strategy wrapper functions should be of the following form. Parameters ---------- player: Player object or subclass (self) opponent: Player object or subclass proposed_action: ...
def format_time(decisecond): """ Convert time in tenths of seconds into formatted string m:ss.t :param decisecond: int >= 0 :return: str """ assert isinstance(decisecond, int) assert decisecond >= 0 decisecond, tenths = decisecond//10, decisecond % 10 minutes, seconds = decise...
def lcmHcf(num1, num2): """ Calculates least common multiple and highest common factor of two numbers Arguments: num1 {integer} -- term 1 num2 {integer} -- term 2 Returns: (lcm, hcf) {tuple of integers} """ def hcf(a, b): """ Computes the...
def quote_literal(s): """Quote a literal string constant.""" return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
def is_int(x): """Check if value (e.g. string) can be converted to integer.""" try: a = float(x) b = int(a) except ValueError: return False else: return a == b
def scale_box2d(box, scale): """Scale box.""" h, w = box[1] return (box[0], (h * scale, w * scale), box[2])
def format_duration(sec): """ Format duration in seconds Args: sec (int): seconds since 1970... """ hours,remainder = divmod(sec,3600) min = remainder//60 ftime = "%s:%s" % (hours,str(min).rjust(2,'0')) return str(ftime).rjust(5)
def transpose_list_of_lists(lol): """Transpose a list of equally-sized python lists. Args: lol: a list of lists Returns: a list of lists """ assert lol, "cannot pass the empty list" return [list(x) for x in zip(*lol)]
def expand_multival_arg(args, name, count): """Expand a "multival" argument.""" value = args.get(name) if value is None: raise ValueError('missing value for {0}'.format(name)) parts = value.split(',') if len(parts) < count: parts += [parts[-1]] * (count - len(parts)) elif len(par...
def EscapeEcho(s): """ Quick and dirty way of escaping characters that may otherwise be interpreted by bash / the echo command (rather than preserved). """ return s.replace("\\", r"\\").replace("$", r"\$").replace('"', r"\"")
def calculate_allocation_from_cash( last_cash_after_trade: float, last_securities_after_transaction: float, spot_price: float ) -> float: """Calculates the current allocation.""" security_bankrupt = spot_price <= 0.0 cash_and_securities_zero = last_cash_after_trade == 0.0 and last_securities_after_trans...
def _get_max(lhs, rhs): """Get max value""" if lhs < 0: return lhs if rhs < 0: return rhs return max(lhs, rhs)
def loob(arg): """Complement of bool. :param arg: Python value. :returns: Complementary boolean value. """ return not bool(arg)
def calculateAccuracy(correct,average,count): """returns the accuracy value""" return ((int(count)-1)*float(average)+int(correct))*100/int(count)
def truncate_float(number, length): """Truncate float numbers, up to the number specified in length that must be an integer""" number = number * pow(10, length) number = int(number) number = float(number) number /= pow(10, length) return number
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata from six import text_type value = text_type(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignor...
def is_pattern_exist(seq: str): """ Check the existence of patterns in the sequence seq: A string that contains a comma seperated numbers returns: True if there is a string pattern in the sequence. """ pattern_exist = False pattern_exist = pattern_exist or ("?" in seq) pattern_exist = pa...
def cuboid_volume(a,b,c): """ Parameters ---------- a : float b : float c : cloat Return ------ cuboid_volume : float """ if a < 0 or b < 0 or c < 0: return 0 else: return a*b*c
def check_lost (grid): """return True if there are no 0 values and there are no adjacent values that are equal; otherwise False""" for i in grid: if i.count(0) > 0: return False else: for i in range((len(grid))): for j in range((len(grid[i])-1)): i...
def __find_non_overlapping_cycles__(covered, existing_set): """ In every common switch, just pick up only one swap order pair of switches :param covered: :param existing_set: :return: """ selected = set() removes = set() current_cycle = None for cv in covered: if len(cv) ...
def read_attribute_from_config_file(attribute, config, compulsory=False): """ :param attribute: key name of the config json file :param config: loaded json file :param compulsory: Boolean value: whether the attribute is must present or not in the config file :return: """ if attribute in con...
def _calculate_shrinking_factor(initial_shrinking_factor: float, step_number: int, n_dim: int) -> float: """The length of each in interval bounding the parameter space needs to be multiplied by this number. Args: initial_shrinking_factor: in each step the total volume is shrunk by this amount s...
def check_age(observation): """ Validates that observation contains valid age value Returns: - assertion value: True if age is valid, False otherwise - error message: empty if age is valid, False otherwise """ age = observation.get("SubjectAge") if...
def get_bit(byte, index): """Return the value of the bit at `index` of `byte`. Parameters ---------- byte : bytes The value to process. index : int The index of the bit to return, where index ``0`` is the most significant bit and index ``7`` is the least significant. Re...
def parseDeviceName(deviceName): """ Parse the device name, which is of the format card#. Parameters: deviceName -- Device name to parse """ return deviceName[4:]
def dict_get(dict, key): """How to Use {{ dict|dict_get:key }} """ return dict.get(key)
def get_fabric_id_details(name, all_fabrics): """ obtain the fabric id using fabric name :param name: fabric name :param all_fabrics: All available fabric in the system :return: tuple 1st item: fabric id 2nd item: all details of fabric specified in dict """ fabric_id, fabric_details ...
def hashf(t): """ This function returns the key corresponding to which the tuple t will be hashed in the hashtable. """ d=0 for i in range(24): d*=10 d+=t[i] return d%99991
def data_size_str(bytecount: int) -> str: """Given a size in bytes, returns a short human readable string. This should be 6 or fewer chars for most all sane file sizes. """ # pylint: disable=too-many-return-statements if bytecount <= 999: return f'{bytecount} B' kbytecount = bytecount /...
def left_to_right_check(input_line: str, pivot: int): """ Check row-wise visibility from left to right. Return True if number of building from the left-most hint is visible\ looking to the right, False otherwise. input_line - representing board row. pivot - number on the left-most hint of the i...
def get_namespace_parent(namespace): """ From a provided namespace, return it's parent or None if there's no parent. >>> get_namespace_parent('org.foo.bar') 'org.foo' >>> get_namespace_parent('org') is None True :param str namespace: The namespace to namespace. :return: The parent name...
def rgb2mpl(rgb): """ convert 8 bit RGB data to 0 to 1 range for mpl """ if len(rgb) == 3: return [rgb[0]/255., rgb[1]/255., rgb[2]/255.] elif len(rgb) == 4: return [rgb[0]/255., rgb[1]/255., rgb[2]/255., rgb[3]/255.]
def make_keyword(keyword): """Adds HTML <code> tags around input """ return '<code class="docutils literal">{}</code>'.format(keyword)
def stopw_removal(inp, stop): """ Stopwords removal in line of text. Input: - inp: str, string of the text input - stop: list, list of stop-words to be removed """ # Final string to be returned final = '' for w in inp.lower().split(): if w not in stop...
def is_palindrome_permutation_v2(phrase): """checks if a string is a permutation of a palindrome""" d = dict() for c in phrase: if c not in d: d.update({c: 1}) else: d[c] = 0 return sum(d[key]%2 for key in d) <= 1
def get_comment_and_endline(input_string: str, start_line: int): """ Remove the useless comment lines from the input description of the card :param input_string: Must be a string, it's the card description :param start_line: Must be an integer, it's the line number of the card in the mcnp input ...
def guess_identifier_format(identifier_str): """Guess identifier format. :param str identifier_str: Chemical identifier string. :return: 'inchi' or 'smiles' string. :rtype: :py:class:`str` """ if identifier_str.startswith('InChI='): return 'inchi' else: return 'smiles'
def build_dict(seq, key): """ Turn an unnamed list of dicts into a nammed list of dicts Taken from stackoverflow https://stackoverflow.com/questions/4391697/find-the-index-of-a-dict-within-a-list-by-matching-the-dicts-value """ return dict((d[key], dict(d, index=index)) for (index, d) in enumera...
def sandwich_unicode(value, encoding='utf-8'): """Sandwich unicode values. This function always returns bytes. """ if isinstance(value, bytes): return value else: return value.encode(encoding)
def format_authors(paper): """ format_authors formats list of author fields to strings :param paper: dict of paper meta data :type paper: dict :return: string format of authors :rtype: str """ authors = paper["authors"] if len(authors) > 2: author = authors[0]["name"].split(...
def intersection(A,B,C,D,infinite=True): """ Returns the intersection point of two lines AB & CD. A,B,C,D and return value are all lists of two coordinates each. If lines are parallel or do not intersect, returns a pair of Nones. Code taken from Stephen Wise, pp. 48-9 Args: ...
def project_operational_periods(project_vintages_set, operational_periods_by_project_vintage_set): """ :param project_vintages_set: the possible project-vintages when capacity can be built :param operational_periods_by_project_vintage_set: the project operational ...
def midpointint(f, a, b, n): """Uses lists and for loop to iterate through a midpoint integration function""" h = (b - a) / float(n) sum = 0 for i in range(n): sum = sum + h * f(a - (h /2) + (i+1) * h) return sum
def calc_modulus_sq_by_complex_vector(vector_1, flag_vector_1=False): """Square of modulus of complex vector. The vector is given as tuple of its coordinates defined in Chartezian coordinate system. """ modulus_comp = tuple([(v_1*v_1.conjugate()).real for v_1 in vector_1]) modulus = modulus_com...
def methods_of(obj): """Get all callable methods of an object that don't start with underscore returns a list of tuples of the form (method_name, method) """ result = [] for fn in dir(obj): if callable(getattr(obj, fn)) and not fn.startswith('_'): result.append((fn, getattr(obj...
def endswith_xFFxD9(data): """ Checks whether the given data endswith `b'\xD9\xFF'` ignoring empty bytes at the end of it. Parameters ---------- data : `bytes-like` Returns ------- result : `bool` """ index = len(data) - 1 while index > 1: actual = data[index] ...
def relu_number(n): """Calculate the relu of a number Keyword arguments: n -- the number """ return max(0, n)
def repetition_checksum(ids): """Return checksum - No. of ids with doubled letters * No. with tripled.""" doubles, triples = 0, 0 for code in ids: no_doubles, no_triples = True, True for letter in set(code): count = code.count(letter) if count == 2 and no_doubles: ...
def calculateGrades(grade1, grade2, grade3, grade4, grade5): """assumes grade1 to grade5 are numbers returns a string lenght 1, the letter grade """ average_grade = (grade1 + grade2 + grade3 + grade4 + grade5) / 5 if average_grade > 90: return "A" elif average_grade > 80: return ...
def verse(bottle): """Sing a verse and account for plurality""" next_bottle = bottle - 1 s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_text = 'No more' if bottle == 1 else next_bottle return '\n'.join([ f'{bottle} bottle{s1} of beer on the wall,', ...
def find_keys(key_list, keys, require_match=False): """Find the indices of keys into a list of keys. Parameters ---------- key_list : iterable keys : iterable require_match : bool Require that `key_list` contain every element of `keys`, and if not, raise ValueError. Returns...
def tof(i, shape): """Check whether i is tensor or initialization function; return tensor or initialized tensor; Parameters ------- i : tensor or function Tensor or function to initialize tensor shape : list or tuple Shape of tensor to initialize Returns ------- ...
def diagonal_DM(dt, chanBW, center_freq): """ diagonal_DM(dt, chanBW, center_freq): Return the so-called "diagonal DM" where the smearing across one channel is equal to the sample time. """ return (0.0001205 * center_freq * center_freq * center_freq) * dt / chanBW
def overlap(layer, interval): """ calculate the thickness for a layer that overlapping with an interval :param layer: (from_depth, to_depth) :param interval: (from_depth, to_depth) :return: the overlapping thickness """ res = 0 if layer[0] >= interval[0] and layer[1] <= interval[1]: # c...
def _process_keys(left, right): """ Helper function to compose cycler keys Parameters ---------- left, right : iterable of dictionaries or None The cyclers to be composed Returns ------- keys : set The keys in the composition of the two cyclers """ l...
def _sum_frts(results:dict): """ Get total number of FRTs Arguments: results {dict} -- Result set from `get_total_frts` Returns: int -- Total number of FRTs in the nation """ if results == None: return 0 total_frts = 0 for result in results: if result['...
def users_to_tags(users): """Convert a list of Users to a list of tags (str). """ return ["<@!{}>".format(u.id) if u is not None else '' for u in users]
def path_ref(num): """ if num is a number, return an index [num] as a string, otherwise just return num.""" if isinstance(num, int): num = '[{}]'.format(num) return num
def _is_float(string): """If string s is a float, return true, else return false """ try: float(string) return True except ValueError: return False
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
def key_value_filter(properties, key, value_substring): """Check whether the port has a manufacturer with the specified substring.""" predicate = value_substring in properties[key] return predicate
def rational_to_cfrac(n,d): """ Terms of the simple continued fraction representation of n/d """ out = [] while d != 0: i = n//d out.append(i) n,d = d,n-(d*i) return out
def build_url(video_id: str) -> str: """Converts a YouTube video ID into a valid URL. Args: video_id: YouTube video ID. Returns: YouTube video URL. """ return f"https://youtube.com/watch?v={video_id}"
def largest_factor(n): """ *** write a proper docstring here *** >>> largest_factor(15) # factors are 1, 3, 5 5 >>> largest_factor(13) # factor is 1 since 13 is prime 1 *** add two more testcases here *** """ # *** YOUR CODE HERE *** return n
def transform_release_toolchains(toolchains, version): """ Given a list of toolchains and a release version, return a list of only the supported toolchains for that release toolchains: The list of toolchains version: The release version string. Should be a string contained within RELEASE_VERSIONS "...
def __validate_float_fields(value: float, error_msg: str) -> float: """Validate float values from a dictionary. Parameters ---------- value : float Value to be validated. error_msg : str Error message for an invalid value. Returns ------- float Validated value. ...
def extract_hour(datestring): """ Return hour part of date string as integer. """ hour = int(datestring[11:13]) cycle = datestring[17:19] if hour == 12 and cycle == 'am': hour = 0 if cycle == 'pm': hour += 12 return hour
def color_check(origin_color: list, target_color: list) -> bool: """ Function that check if it is the color we're looking for in C.I. Set C.I. properly for handling between accuracy and robustness. """ CI = 20 # Confidential Interval if target_color[0]-CI <= origin_color[0] <= target_color[0]+CI\ and target_col...
def int_incrementor(input_string: str): """ In some cases, you are pvodided a string that is a number and you need to adjust the number while preserve the string format. e.g. 0010, expecting 0011. Not hard to do but super annoying to handle elegantly each time. :param str: :return: """ ...
def get_cwd(process): """ Get the cwd of a process catching AccessDenied exceptions """ try: cwd = process.getcwd() except: cwd = 'AccessDenied' return cwd
def JNumber(state_list): """Calculate the angular momentum from the number of sub-states in the list. Parameters: state_list (list): List of sub-states of a single angular momentum state. Returns int: The total angular momentum of the state. """ return int((len(state_list)-...
def is_power_2_natrual(n): """ only for Natural number 1,+2,+4,+8,... """ if not isinstance(n, int) or n <= 0: raise Exception('Not an Natural Number') return not (n & (n - 1))
def anal_zpe(data_dict): """ Function for parsing the ZPE out of the raw data dictionary. Takes the full dictionary as input, and returns the ZPE. """ zpe = 0. # Different syntax for different CFOUR function calls for word in ["frequency", "freq"]: try: zpe = data_dict[wo...
def distribute(x, values, level): """Distribute elements in values on nth level of nested lists. This creates an additional nested level of lists. Exemple: distribute([[[1,2], [1,3]], [[2,2]]], ['a', 'b'], 2) --> [[ [[1,2,'a'], [1,2,'b']], [[1,3,'a'], [1,3,'b']] ...
def splitBy(data, num): """ Turn a list to list of list """ return [data[i:i + num] for i in range(0, len(data), num)]
def quoted_split(haystack, needle=None, maxsplit=-1): """ Split `haystack` on `needle`, except inside quote signs """ start = 0 search = 0 parts = [] while maxsplit == -1 or len(parts) < maxsplit: if needle: p = haystack.find(needle, search) if p < 0: break search = p + len(needle) else: p = s...
def get_bandwidth(data, duration): """ Module to determine the bandwidth for a segment download""" return data * 8/duration
def wrap_code_block(str): """Format code block.""" return f"```\n{str}\n```"
def short_sha(sha: str) -> str: """Return an abbreviated version of the provided SHA1 hexstring.""" return sha[:7]