content
stringlengths
42
6.51k
def signature(rle): """ Return the sequence of characters in a run-length encoding (i.e. the signature). Also works with variable run-length encodings """ return ''.join(r[0] for r in rle)
def make_rep(req, body=None): """Utility which creates a reply object based on the headers in the request object.""" rep = { 'head': { 'seq': req['head']['seq'] +1, 'cmd': req['head']['cmd'], 'rSeq': req['head']['seq'] }} if body: rep['body'] = body ...
def json_extract(obj, key): """Recursively fetch values from nested JSON.""" arr = [] def extract(obj, arr, key): """Recursively search for values of key in JSON tree.""" if isinstance(obj, dict): for k, val_ue in obj.items(): if isinstance(val_ue, (dict, list)):...
def rule2string(lhs,rhs,isCopy=False): """ Makes a string from a rule. Used in printing and in making a dict of rules and probs. Arguments: lhs : string rhs : string list isCopy : boolean indicating a copy rule. Only used in cky_constituent_copy """ s = "%s->%s"%(lhs,".".join(rhs)...
def label_maker(benchmark_covariate, kd, ky, digits=2): """ Return a string created by appending the covariate name to the multiplier(s) ky and (if applicable) kd. Parameters ---------- benchmark_covariates : string or list of strings a string or list of strings with names of the variables ...
def validate_gff_gtf_filename(f): """Ensure file extension is gff or gtf""" if "gtf" in f.lower(): return True elif "gff" in f.lower(): return True else: return False
def compute_f(match_num, test_num, gold_num, significant, f_only): """ Compute the f-score based on the matching clause number, clause number of DRS set 1, clause number of DRS set 2 Args: match_num: matching clause number tes...
def _nt_colour(nt): """ Set default colours for 21, 22 and 24 nt sRNAs :param nt: aligned read length (int) :return: colour code (str) """ hex_dict = {18: '#669999', 19: '#33cccc', 20: '#33cccc', 21: '#00CC00', 22: '#FF3399', 23: '#d8d408', 24: '#3333FF', 25: '#cccc00', ...
def unescape_path_key(key): """Unescape path key.""" key = key.replace(r'\\', '\\') key = key.replace(r'\.', r'.') return key
def reverse(x: int) -> int: """ Function to find reverse of any number """ rev = 0 while x > 0: rev = (rev * 10) + x % 10 x = int(x / 10) return rev
def solution(array): """Returns the first ten digits of the sum of the array elements. >>> import os >>> sum = 0 >>> array = [] >>> with open(os.path.dirname(__file__) + "/num.txt","r") as f: ... for line in f: ... array.append(int(line)) ... >>> solution(array) '553...
def notenum_to_freq(notenum): """Converts MIDI note number to frequency.""" f0 = 440.0 a = 2 ** (1.0 / 12.0) return f0 * (a ** (notenum - 69))
def _mirrorpod_filter(pod): """Check if a pod contains the mirror K8s annotation. Args: - pod: kubernetes pod object Returns: (False, "") if the pod has the mirror annotation, (True, "") if not """ mirror_annotation = "kubernetes.io/config.mirror" annotations = pod["metadata...
def handler(event, context): """ Handle bounds requests """ print(event, context) return True
def extractConfigParameter(configParameter, era, run): """ _extractConfigParameter_ Checks if configParameter is era or run dependent. If it is, use the provided era and run information to extract the correct parameter. """ if isinstance(configParameter, dict): if 'acqEra' in configPara...
def strToBytes(raw_str): """ convert str to bytes after bytesToStr conversion to return the original bytes content """ return bytes.fromhex(raw_str)
def shell_escape(string): """ Escape double quotes, backticks and dollar signs in given ``string``. For example:: >>> _shell_escape('abc$') 'abc\\\\$' >>> _shell_escape('"') '\\\\"' """ for char in ('"', '$', '`'): string = string.replace(char, '\\{}'.format...
def gcd(a: int, b: int) -> int: """ Calculate the greatest common divisor. Currently, this uses the Euclidean algorithm. Parameters ---------- a : int Non-zero b : int Non-zero Returns ------- greatest_common_divisor : int Examples -------- >>> gcd...
def chk_abbreviation(abbreviation): """Checks whether the abbreviation is composed only by letters.""" toret = False for ch in abbreviation: if not ch.isalpha(): break else: toret = True return toret
def installation_token_payload(passed_keywords: dict) -> dict: """Create a properly formatted payload for handling installation tokens. { "expires_timestamp": "2021-09-22T02:28:11.762Z", "label": "string", "type": "string", [CREATE only] "revoked": boolean [...
def compile_route_to_regex(route): """Compiles a route to regex Arguments: route {masonite.routes.Route} -- The Masonite route object Returns: string -- Returns the regex of the route. """ # Split the route split_given_route = route.split('/') # compile the provided url i...
def reverse_compliment(pattern): """returns reverse complement for the input pattern""" compliment = {'C': 'G', 'G': 'C', 'A': 'T', 'T': 'A'} output = [] for key in pattern: output.append(compliment[key]) reverse_output = (output[::-1]) ...
def hf_vs_hadr_energy(hadr_energy): """Hadronic factor as a function of a hadronic cascade's energy. Parameters ---------- hadr_energy Returns ------- hadr_factor Notes ----- C++ function originally named "HadronicFactorHadEM" """ E0 = 0.18791678 # pylint: disable=in...
def test_middleware(components): """ Test middleware function that returns a simple number """ for component in components: component['quantity'] = component['quantity'] + 1 return components
def clean_newick_id(name): """ Return a version of name suitable for placement in a newick file :param name: The name to clean up :return: a name with no colons, spaces, etc """ name = name.replace(' ', '_') name = name.replace(':', '_') name = name.replace('[', '_') name = name.repl...
def sum(a, b): """ >>> sum(2, 4) 6 >>> sum('a', 'b') 'ab' """ return a+b+b
def add_two(a, b): """adds two numbers Arguments: a {int} -- num one b {int} -- num two Returns: [int] -- [number added] """ if not a or not b: return None return a + b
def is_leap_year(given_year): """ Checks if a given year denoted by 'given_year' is leap-year or not. Returns True if 'given_year' is leap-year. Returns False otherwise. """ if given_year % 100 == 0: if given_year % 400 == 0: return True else: return False...
def lloyd_only_rref_p(et, p): """ Soil respiration of Lloyd & Taylor (1994) with fix E0 If E0 is know in Lloyd & Taylor (1994) then one can calc the exponential term outside the routine and the fitting becomes linear. One could also use functions.line0. Parameters ---------- et : float...
def average(iterable): """Return the average of the values in iterable. iterable may not be empty. """ it = iterable.__iter__() try: s = next(it) count = 1 except StopIteration: raise ValueError("empty average") for value in it: s = s + value count ...
def enc(s): """UTF-8 encode a string.""" return s.encode('utf-8')
def join_lines(x): """Inverse of split_lines""" if all(isinstance(i, str) for i in x): return "\n".join(x) elif all(isinstance(i, list) for i in x): return [join_lines(i) for i in x] else: raise TypeError(f"{[type(i) for i in x]} {str(x)[:20]}")
def profit(initial_capital, multiplier): """Calculate the profit based on multiplier factor. :param initial_capital: Initial amount of capital :type initial_capital: float :param multiplier: Multiplying factor :type multiplier: float :return: Profit :rtype: float """ return initi...
def CorelatedGame(*args): """The more arguments are equal to the first argument, the higher the return value.""" incr = 1.0/len(args) r = 0.0 x = args[0] for y in args: if y == x: r += incr return r
def noise_removal_w_regex(input_text): """Removing noise from using using regular expression. :param input_text: Noisy text. :return: Clean text. """ import re # pattern to remove hashtagged words eg. #this r_pattern = "#[\w]*" # matches iterator matches = re.finditer(r_pattern...
def _get_subclass_entry(cls, clss, exc_msg="", exc=NotImplementedError): """In a list of tuples (cls, ...) return the entry for the first occurrence of the class of which `cls` is a subclass of. Otherwise raise `exc` with the given message""" for clstuple in clss: if issubclass(cls, clstuple[0]...
def is_correct_type(item, expected_type): """Function for check if a given item has the excpected type. returns True if the expected type matches the item, False if not Parameters: -item: the piece of data we are going to check. -expected_type: the expected data type for item. """ ...
def _is_comment(cells): """Returns True if it is a comment row, False otherwise.""" for cell in cells: if cell.strip() == '': continue return cell.lstrip().startswith('#') return False
def unitDecoder(text): """changes css length unit to rough approximation in char cells""" scale = 1 unit_to_char_dict = { 'em': 2, 'ex': 1, 'ch': 1, 'rem': 2, 'cm': 5, 'mm': 0.5, 'in': 12.7, 'px': 0.13, ...
def adjacent_nodes(graph, start): """Given a node `start` it returns a list which shows which nodes are reachable from `start`. If the list return by start looks like [True True False True], that means that nodes 0, 1 and 3 are reachable from node K. Time Complexity: # O(V + E), where V = number of...
def rgb_to_int(rgb): """Given an rgb, return an int""" return rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256)
def filter_metadata(context, metadata: dict) -> dict: """ Remove metadata indicated by fixtures :param context: Behave context :param metadata: Metadata dictionary containing macro parameters """ if getattr(context, 'disable_payload', False): metadata = {k: v for k, v in metadat...
def find_val_or_next_smaller(bst, x): """Get the greatest value <= x in a binary search tree. Returns None if no such value can be found. """ if bst is None: return None elif bst.val == x: return x elif bst.val > x: return find_val_or_next_smaller(bst.left, x) else: ...
def get_web_url_from_stage(stage: str) -> str: """Return the full URL of given web environment. :param stage: environment name. Can be 'production', 'dev' (aliases: 'local', 'development'), 'staging', 'preview', or the name of any other environment """ if stage in ['local', 'dev', 'de...
def normalize_azimuth(azimuth): """Normalize azimuth to (-180, 180].""" if azimuth <= -180: return azimuth + 360 elif azimuth > 180: return azimuth - 360 else: return azimuth
def activity_region(activity_arn): """ Return the region for an AWS activity_arn. 'arn:aws:states:us-east-2:123456789012:stateMachine:hello_world' => 'us-east-2' """ if activity_arn: parts = activity_arn.split(':') return parts[3] if len(parts) >= 4 else None else: retur...
def node_text_content(node) -> str: """ Get the text content of a node. """ if node is None: return "" if isinstance(node, str): return node if isinstance(node, list): return " ".join(map(node_text_content, node)) if isinstance(node, dict): if "text" in node: ...
def ireplace(old, new, string): """Returns a copy of `string` where all the occurrences of a case-insensitive search after `old` is replaced with `new`. :param old: the item in `string` to do a case insensitive search after. :param new: new item to replace `old` with. :param string: string to searc...
def CountRect(a, b, c, d): """Counts number of small rectangles inside a big (incomplete) rectangle. The input rectangle axb has 4 corners (two cxc/2, two dxd/2) cut.""" vertex = [[1 for i in range(b+1)] for j in range(a+1)] # a row, b col for i in range(c): # cuts two c corners for j in range(i+1): ...
def bytes2human(n, format='%(value).1f %(symbol)sB'): """ Convert n bytes into a human readable string based on format. symbols can be either "customary", "customary_ext", "iec" or "iec_ext", see: http://goo.gl/kTQMs >>> bytes2human(1) '1.0 B' >>> bytes2human(1024) '1.0 KB' ...
def flatten_dictionary(json_data): """Return flat meta report dictionary from nested dictionary.""" meta = {} meta["report"] = {} for item in json_data: if type(json_data[item]) is dict: for values in json_data[item]: if type(json_data[item][values]) is dict: ...
def dict_other_json(imagePath, imageData, shapes, fillColor=None, lineColor=None): """ :param lineColor: list :param fillColor: list :param imageData: str :param imagePath: str :return: dict"" """ # return {"shapes": shapes, "lineColor": lineColor, "fillColor": fillColor, "imageData": im...
def sort_dict_desc(dictionary): """Sorts dictionary in descending order by values.""" return sorted(dictionary.items(), key=lambda item: item[1], reverse=True)
def day_2_strategy(passphrase): """Return if passphrase is valid is no repeat words and no anagrams.""" valid = True words = set() for word in passphrase.split(): sorted_word = ''.join(sorted(word)) if sorted_word not in words: words.add(sorted_word) else: ...
def _bytes_to_unicode(obj): """ Convert a non-`bytes` type object into a unicode string. :param obj: the object to convert :return: If the supplied `obj` is of type `bytes`, decode it into a unicode string. If the `obj` is anything else (including None), the original `obj` is returned. ...
def calculate(base_price, artist_markup, quantity): """ Doing the math for getting total value of the cart. :param base_price: Base price of the product :param artist_markup: Artist markup value from the cart. :param quantity: Quntity from the cart. :return: Price of the product """ retu...
def check_for_debug(supernova_args, nova_args): """ If the user wanted to run the executable with debugging enabled, we need to apply the correct arguments to the executable. Heat is a corner case since it uses -d instead of --debug. """ # Heat requires special handling for debug arguments ...
def get_comment_style(fextension): """ get the comment style for the specific extension extension: (before, after) """ comments = {'.py': ('#', ''), '.cfg': ('#', ''), '.js': ('//', ''), '.html': ('<!--', ' -->'), '.css': ('/*', '*/')} ...
def eea(a, b): """ Calculates u*a + v*b = ggT returns (ggT, u, v, steps) """ u, v, s, t, steps = 1, 0, 0, 1, 0 while b > 0: q = a//b a, b = b, a-q*b u, s = s, u-q*s v, t = t, v-q*t steps += 1 return a, u, v, steps
def iou(box1, box2): """ Calculate intersection over union between two boxes """ x_min_1, y_min_1, width_1, height_1 = box1 x_min_2, y_min_2, width_2, height_2 = box2 assert width_1 * height_1 > 0 assert width_2 * height_2 > 0 x_max_1, y_max_1 = x_min_1 + width_1, y_min_1 + height_1 ...
def get_degree_abbrev(degree): """Replaces long names of degrees to shorter names of those degrees Example: Bachelor of Science => BSc""" subs = { 'Bachelor of Science': 'BSc', 'Master of Science': 'MSc', 'Master of Science, Applied': 'MScA', 'Bachelor of Arts': 'BA', ...
def string_to_dependencies(text: str) -> set: """Return the set of pip dependencies from a multi-line string. Whitespace and empty lines are not significant. Comment lines are ignored. """ lines = text.splitlines() lines = [line for line in lines if not line.startswith("#")] collapsed_lines...
def _equivalence(self, other): """A function to assert equivalence between client and server side copies of model instances""" return type(self) == type(other) and self.uid == other.uid
def calculateTopicNZ(topicCoOccurrenceList, coOccurrenceDict): """ Calculates and returns a topic's total NZ. """ sumNZ = 0 for topicCoOccurrence in topicCoOccurrenceList: if coOccurrenceDict[topicCoOccurrence] == 0.0: sumNZ += 1 return sumNZ
def set_chunk_size(data_type, stream_id, new_size): """ Construct a 'SET_CHUNK_SIZE' message to adjust the chunk size at which the RTMP library works with. :param data_type: int the RTMP datatype. :param stream_id: int the stream which the message will be sent on. :param new_size: int the new size o...
def get_mean(iterable): """ Returns the mean of a given iterable which is defined as the sum divided by the number of items. """ return sum(iterable) / len(iterable)
def parse_mode(cipher_nme): """ Parse the cipher mode from cipher name e.g. aes-128-gcm, the mode is gcm :param cipher_nme: str cipher name, aes-128-cfb, aes-128-gcm ... :return: str/None The mode, cfb, gcm ... """ hyphen = cipher_nme.rfind('-') if hyphen > 0: return cipher_nme[h...
def find_kth(nums1, nums2, k): """find kth number of two sorted arrays >>> find_kth([1, 3], [2], 2) 2 >>> find_kth([2], [1, 3], 1) 1 >>> find_kth([1, 3], [2], 3) 3 >>> find_kth([1], [2], 1) 1 >>> find_kth([1], [2], 2) 2 """ # assume len(nums1) <= len(nums2) if le...
def excel_column_name(index): """ Converts 1-based index to the Excel column name. Parameters ---------- index : int The column number. Must be 1-based, ie. the first column number is 1 rather than 0. Returns ------- col_name : str The column name for the input ...
def rotate(i, length): """Given integer i and number of digits, rotate its digits by 1 spot""" s = str(i) ans = 0 if len(s) == 1: return i if len(s) == 2: ans = int(s[1] + s[0]) else: ans = int(s[1:] + s[0]) while len(str(ans)) < length: #solve for 011 being rotated t...
def CacheKey(state, status, urlkey): """Calculates the cache key for the given combination of parameters.""" return 'GetBugs_state_%s_status_%s_key_%s' % (state, status, urlkey)
def get_ylabel(toa_files, ohu_files, ohc_files): """Get the label for the yaxis""" toa_plot = False if toa_files == [] else True ohu_plot = False if ohu_files == [] else True ohc_plot = False if ohc_files == [] else True ylabel = 'heat uptake/storage (J)' if not ohc_plot: ylabel = 'hea...
def create_node_string(identifier, event_type, event_type_uri, example_incidents): """ """ line_one = f'{identifier}[label=<<table>' line_two = f'<tr><td href="{event_type_uri}">{event_type}</td></tr>' lines = [line_one, ...
def bool2str(x): """Return Fortran bool string for bool input.""" return '.true.' if x else '.false.'
def convert_args_to_str(args, max_len=None): """ Convert args to a string, allowing for some arguments to raise exceptions during conversion and ignoring them. """ length = 0 strs = ["" for i in range(len(args))] for i, arg in enumerate(args): try: sarg = repr(arg) ex...
def String_to_File(string,file_name="test"): """Saves a string as a file""" out_file=open(file_name,'w') out_file.write(string) out_file.close() return file_name
def format_message(name, message, version): """Message formatter to create `DeprecationWarning` messages such as: 'fn' is deprecated and will be remove in future versions (1.0). """ return "'{}' is deprecated and will be remove in future versions{}. {}".format( name, ' ({})'.for...
def areaTriangle(base: float, height: float) -> float: """Finds area of triangle""" area: float = (height * base) / 2 return area
def is_in_bounds(grid, x, y): """Get whether an (x, y) coordinate is within bounds of the grid.""" return (0 <= x < len(grid)) and (0 <= y < len(grid[0]))
def get_fi_repeated_prime(p, k=1): """ Return Euler totient for prime power p^k :param p: prime number :param k: power :return: fi(p^k) """ return pow(p, k - 1) * (p - 1)
def last_index(arr, item): """Return not first (as `.index`) but last index of `item` in `arr`. """ return len(arr) - arr[::-1].index(item) - 1
def diff(previous, current): """Deep diff 2 dicts Return a dict of new elements in the `current` dict. Does not handle removed elements. """ result = {} for key in current.keys(): value = current[key] p_value = previous.get(key, None) if p_value is None: res...
def format_trace_id(trace_id): """Format the trace id according to b3 specification.""" # hack: trim traceID to LSB return format(trace_id, "016x")[-16:]
def check_related_lot_status(tender, award): """Check if related lot not in status cancelled""" lot_id = award.get('lotID') if lot_id: if [l['status'] for l in tender.get('lots', []) if l['id'] == lot_id][0] != 'active': return False return True
def within_bounds(world_state, pose): """ Returns true if pose is inside bounds of world_state """ if pose[0] >= len(world_state) or pose[1] >= len(world_state[0]) or pose[0] < 0 or pose[1] < 0: return False else: return True
def divisors(n): """Return the integers that evenly divide n. >>> divisors(1) [1] >>> divisors(4) [1, 2] >>> divisors(12) [1, 2, 3, 4, 6] >>> [n for n in range(1, 1000) if sum(divisors(n)) == n] [1, 6, 28, 496] """ return [1] + [x for x in range(2, n) if n % x == 0]
def adjust_kafka_timestamp(data): """ This is needed for the log-event-duration service to work properly """ if data is not None and "timestamp" in data: data["@timestamp"] = data["timestamp"] return data
def rgb_to_hex_v2(r: int, g: int, b: int) -> str: """ Dengan menggunakan: * [list comprehension](\ https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) * [conditional expressions](\ https://docs.python.org/3/reference/expressions.html#conditional-expressions) ...
def list_to_string(item_name, values): """Return a pretty version of the list.""" values = sorted(values) if len(values) < 5: values_string = "{}{}={}".format( item_name, "s" if len(values) > 1 else "", ",".join(values) ) else: values_string = ...
def normalize_content(content: str) -> str: """ Remove preceding and trailing whitespaces from `content` string. :param content: string to be normalized. :returns: normalized string. """ return content.strip(' \n\t')
def delta(a, b): """ Kronecker delta function """ return 1 if a == b else 0
def temp_ampersand_fixer(s): """As a workaround for ampersands stored as escape sequences in database, unescape text before use on a safe page Explicitly differentiate from safe_unescape_html in case use cases/behaviors diverge """ return s.replace('&amp;', '&')
def _rot_list(l, k): """Rotate list by k items forward. Ie. item at position 0 will be at position k in returned list. Negative k is allowed.""" n = len(l) k %= n if not k: return l return l[n-k:] + l[:n-k]
def desi_dr8_url(ra, dec): """ Construct URL for public DESI DR8 cutout. from SkyPortal """ return ( f"http://legacysurvey.org/viewer/jpeg-cutout?ra={ra}" f"&dec={dec}&size=200&layer=dr8&pixscale=0.262&bands=grz" )
def hit2csv_header(csv_writer, ichunk, is_simplified): """ Returns the header row of the csv that is created. For the simplified export, only the article title and text content are included. """ es_header_names = kb_header_names = [] metadata_header_name = ["metadata"] if not is_simplified:...
def to_camel_case(snake_str: str) -> str: """ Converts snake case to camel case. :param snake_str: The string in snake case to be converted :return: The converted string in camel case """ components = snake_str.split('_') return ' '.join(x.title() for x in components)
def pluralize(n: int, singular: str, plural: str) -> str: """Choose between the singular and plural forms of a word depending on the given count. """ if n == 1: return singular else: return plural
def fast_non_dominated_sort(p): """NSGA-II's fast non dominated sort :param p: values to sort :type p: iterable :return: indices of values sorted into their domination ranks (only first element used) :rtype: list of lists of indices """ S = [[] for _ in p] # which values dominate other? ...
def sgi_2016_to_1973(sgi_id: str) -> str: """ Convert the slightly different SGI2016 to the SGI1973 id format. :examples: >>> sgi_2016_to_1973("B55") 'B55' >>> sgi_2016_to_1973("B55-19") 'B55-19' >>> sgi_2016_to_1973("E73-02") 'E73-2' """ if "-" n...
def s2i(symbols): """ Examples: >>> symbols=['H', 'Li', 'H', 'F'] >>> s2i(symbols) {'H': [0, 2], 'F': [3], 'Li': [1]} """ out = {} for i, symbol in enumerate(symbols): if symbol not in out: out[symbol] = [] out[symbol].append(i) return out