content
stringlengths
42
6.51k
def flatten(items): """ Flatten a list of lists. """ if items == []: return items if isinstance(items, list): flattend = [] for item in items: flattend.extend(flatten(item)) return flattend return [items]
def xyzw2wxyz(xyzw): """Convert quaternions from XYZW format to WXYZ.""" x, y, z, w = xyzw return w, x, y, z
def cipher(text, shift, encrypt=True): """ 1. Description: The Caesar cipher is one of the simplest and most widely known encryption techniques. In short, each letter is replaced by a letter some fixed number of positions down the alphabet. Apparently, Julius Caesar used it in his private correspondence. 2. Explanation: The first input is a string that you want to decipher The second input is the amount of shift for each letters in that string The output will be the outcome of the orginal string after a certain shifting. 3. Example: If you put "gdkkn" and 1 in the cipher function like this: cipher("gdkkn", 1), you will get "hello" """ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if index == -1: new_text += c else: new_index = index + shift if encrypt == True else index - shift new_index %= len(alphabet) new_text += alphabet[new_index:new_index+1] return new_text
def is_struture(s): """doc""" return isinstance(s, list) or isinstance(s, tuple)
def concat_field_values(*args): """Return string of field values for search indexing. Args: Any number of QuerySet objects, the result of value_list calls. Returns: String for search indexing. """ field_names = [] for queryset in args: for instance in queryset: for field in instance: field_names.append(str(field)) return ' '.join(field_names)
def reverse_padding(xs, PAD_IDX=0): """ Move the PAD_IDX in front of the dialog :param xs: input dialogs, which are encoded by dictionary, :param PAD_IDX: the index of the __NULL__ Examples -------- >>> xs = [[3, 1, 2, 0, 0], ... [2, 1, 4, 0, 0]] >>> reverse_padding(xs, 0) [[0, 0, 3, 1, 2], [0, 0, 2, 1, 4]] """ if not isinstance(xs, list): xs = [[x for x in ex] for ex in xs] ans = [] if len(xs) == 0: return xs n = len(xs[0]) for line in xs: end_idx = n - 1 for end_idx in range(n - 1, -1, -1): if line[end_idx] != PAD_IDX: break end_idx += 1 padding_num = n - end_idx new_line = [PAD_IDX] * padding_num + line[:end_idx] ans.append(new_line) return ans
def count_if(my_list, key, value): """ return number of records in my_list where key==value pair matches """ counter = (1 for item in my_list if item.get(key) == value) return sum(counter)
def output_env(data): """ >>> output_env({'a':1, 'b':2}) 'a=1\\nb=2\\n' """ from io import StringIO output = StringIO() for key, value in data.items(): output.write(f'{key}={value}\n') output.seek(0) return output.read()
def unique_dicts_by_value(d, key): """Removes duplicate dictionaries from a list by filtering one of the key values. Args: d (:obj:`list` of :obj:`dict`): List of dictionaries with the same keys. Returns (:obj:`list` of :obj:`dict`) """ return list({v[key]: v for v in d}.values())
def get_ip(a=0, b=0, c=0, d=0, suffix=None): """ a.b.c.d """ ip = '%s.%s.%s.%s' % (a,b,c,d) if suffix is not None: return '%s/%s' % (ip, suffix) return ip
def broken_6(n): """ What comes in: A positive integer n. What goes out: Returns the sum: 1 + 1/2 + 1/3 + ... + 1/n. Side effects: None. """ total = 0 for k in range(n): total = total + (1 / (k + 1)) return total
def join_number(string, num, width=None): """ Join a number to the end of a string in the standard way If width is provided will backfill >>> join_number('fred', 10) 'fred-10' >>> join_number('fred', 10, 3) 'fred-010' """ num = str(num) if width: num = num.rjust(width, '0') return string + '-' + str(num)
def flat(chunks, map=None): """Concatnate chunks into a data Aimed for the use of crafting ROP chains Args: chunks : The target chunks to concat Returns: bytes: split chunks """ assert isinstance(chunks, list) result = chunks[0] if map is None else map(chunks[0]) for i in range(1, len(chunks)): result += chunks[i] if map is None else map(chunks[i]) return result
def int_to_decimal_str(integer): """ Helper to convert integers (representing cents) into decimal currency string. WARNING: DO NOT TRY TO DO THIS BY DIVISION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param integer The amount in cents @return string The amount in currency with full stop decimal separator """ int_string = str(integer) if len(int_string) < 2: return "0." + int_string.zfill(2) else: return int_string[:-2] + "." + int_string[-2:]
def has_tag_requirements(tags, required_tags, qtype): """ Returns True if `tags` meets the requirements based on the values of `required_tags` and `qtype`. False otherwise. """ has_tag_requirements = False tag_intersection = set(required_tags).intersection(set(tags)) if qtype == "or": if len(tag_intersection) > 0: has_tag_requirements = True if qtype == "and": if len(tag_intersection) == len(required_tags): has_tag_requirements = True return has_tag_requirements
def list_caps(payload): """Transform a list of capabilities into a string.""" return ','.join([cap["name"] for cap in payload["request"]["capabilities"]])
def sort_tuple(tup, n=2): """ Sort a tuple by the first n values :param tup: :param n: :return: """ return tuple(sorted(tup, key=lambda t: t[:n]))
def GetModules(files): """! Return a list of any files in the input list that match as '.py' files. Ignores files with leading '_'. @param files: List of file names (path optional) @return all file names in the list that match the criteria. ## Profile * line count: 3 * characters: 110 * returns: return mod """ mod = [f for f in files if (len(f) > 3 and f[-3:] == '.py' and f[0] != '_')] return mod
def add_link(s): """ if `s` is a url, then adds anchor tags for html representation in ipynb. """ if s.startswith('http'): a = '<a href="{0}" target="_blank">'.format(s) a += s a += '</a>' return a
def vroll(vel_1, vel_2): """ Calculate the rolling speed in a tribological contact based on contact body velocities. Parameters ---------- vel_1: ndarray, scalar The contact velocity of body 1. vel_2: ndarray, scalar The contact velocity of body 2 Returns ------- vel_roll: ndarray, scalar The rolling velocity in the tribological contact. """ vel_roll = (vel_1 + vel_2) / 2 return vel_roll
def Split_Lines(raw_string, size): """ Splits up a piece of text into a list of lines x amount of chars in length. CODE: koding.Split_Lines(raw_string, size) AVAILABLE PARAMS: (*) raw_string - This is the text you want split up into lines (*) size - This is the maximum size you want the line length to be (in characters) EXAMPLE CODE: raw_string = 'This is some test code, let\'s take a look and see what happens if we split this up into lines of 20 chars per line' dialog.ok('[COLOR gold]ORIGINAL TEXT[/COLOR]',raw_string) my_list = koding.Split_Lines(raw_string,20) koding.Text_Box('List of lines',str(my_list)) ~""" final_list=[""] for i in raw_string: length = len(final_list)-1 if len(final_list[length]) < size: final_list[length]+=i else: final_list += [i] return final_list
def create_headers(bearer_token: str): """ Creates the header to be sent along with the request to the api :param bearer_token: the authentication token :return: dictionary with authentication information """ return {"Authorization": f"Bearer {bearer_token}"}
def valid_sort(sort, allow_empty=False): """Returns validated sort name or throws Assert.""" if not sort: assert allow_empty, 'sort must be specified' return "" assert isinstance(sort, str), 'sort must be a string' valid_sorts = ['trending', 'promoted', 'hot', 'created', 'payout', 'payout_comments'] assert sort in valid_sorts, 'invalid sort `%s`' % sort return sort
def until(predicate, transformation, value): """Takes a predicate, a transformation function, and an initial value, and returns a value of the same type as the initial value. It does so by applying the transformation until the predicate is satisfied, at which point it returns the satisfactory value""" out = transformation(value) while predicate(out): out = transformation(out) return out
def simple_list(li): """ takes in a list li returns a sorted list without doubles """ return sorted(set(li))
def tilecache_path(tile_coord): """ >>> tilecache_path((1234567, 87654321, 9)) '09/001/234/567/087/654/321' """ x, y, z = tile_coord parts = ("%02d" % z, "%03d" % int(x / 1000000), "%03d" % (int(x / 1000) % 1000), "%03d" % (int(x) % 1000), "%03d" % int(y / 1000000), "%03d" % (int(y / 1000) % 1000), "%03d" % (int(y) % 1000)) return '/'.join(parts)
def insertionsort(x): """ input x takes in a list, output is a sorted list, numnber of assignments, and number of conditionals """ assignment = 0 conditional = 0 list_length = len(x) assignment += 1 for i in range(1,list_length): cur_value = x[i] pos = i assignment += 3 conditional += 2 while pos > 0 and x[pos-1] > cur_value: x[pos] = x[pos-1] pos = pos - 1 assignment +=2 x[pos] = cur_value assignment += 1 return x, assignment, conditional
def solve(captcha): """Solve captcha. :input: captcha string :return: sum of all paired digits that match >>> solve('1122') 3 >>> solve('1111') 4 >>> solve('98769') 9 """ return sum(int(x) for x, y in zip(captcha, captcha[1:] + captcha[0]) if x == y)
def primes(n): """ Simple test function Taken from http://www.huyng.com/posts/python-performance-analysis/ """ if n==2: return [2] elif n<2: return [] s=list(range(3,n+1,2)) mroot = n ** 0.5 half=(n+1)//2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)//2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x]
def flatten(dict_in, delim="__", loc=[]): """Un-nests the dict by combining keys, e.g. {'a': {'b': 1}} -> {'a_b': 1}""" loc = loc or [] output = {} if not dict_in and loc: output[delim.join(loc)] = {} for key in dict_in: if isinstance(dict_in[key], dict): nest_out = flatten(dict_in[key], delim=delim, loc=loc + [str(key)]) output.update(nest_out) else: base_key = delim.join(loc + [str(key)]) output[base_key] = dict_in[key] return output
def complete_url(string): """Return complete url""" return "http://www.viraindo.com/" + string
def weekday_name(day_of_week): """Return name of weekday. >>> weekday_name(1) 'Sunday' >>> weekday_name(7) 'Saturday' For days not between 1 and 7, return None >>> weekday_name(9) >>> weekday_name(0) """ if day_of_week == 1: return "Sunday" elif day_of_week == 2: return "Monday" elif day_of_week == 3: return "Tuesday" elif day_of_week == 4: return "Wednesday" elif day_of_week == 5: return "Thursday" elif day_of_week == 6: return "Friday" elif day_of_week == 7: return "Saturday" return None
def calcsfh_existing_files(pref, optfilter1=''): """file formats for param match and matchfake""" param = pref + '.param' match = pref + '.match' fake = pref + '.matchfake' return (param, match, fake)
def square_of_sum(number): """ Return the square of sum of first [number] neutral integers """ return sum(range(1, number + 1)) ** 2
def auth(req, **kwargs): """ :kwargs: None """ return {'status': True, 'msg': 'Login Verified.'}
def filter(question, answer): """Takes in tokenized question and answer and decides whether to skip.""" if len(answer) == 1: if answer[0].text.lower() in ['true', 'false', 'yes', 'no']: return True return False
def assert_gravitational_parameter_is_positive(mu): """ Checks if the gravitational parameter is positive. Parameters ---------- mu: float Gravitational parameter """ # Check positive gravitational parameter if mu <= 0: raise ValueError("Gravitational parameter must be positive!") else: return True
def translate_interface_name(name): """ Define shortcutting interface name """ if 'tengigabitethernet' in name.lower(): name = name.replace('TenGigabitEthernet', 'Te') return name if 'gigabitethernet' in name.lower(): name = name.replace('GigabitEthernet', 'Gi') return name if 'fastethernet' in name.lower(): name = name.replace('FastEthernet', 'Fa') return name if 'ethernet' in name.lower(): name = name.replace('Ethernet', 'Eth') return name return name
def sort_points_by_X(points): """ Sort a list of points by their X coordinate Args: points: List of points [(p1_x, p1_y), (p2_x, p2_y), ...] Returns: List of points sorted by X coordinate """ points.sort() return points pass
def iterables_equal(a, b) -> bool: """ Return whether the two iterables ``a`` and ``b`` are equal. """ if len(a) != len(b): return False return all(x == y for x, y in zip(a, b))
def filter_characters(words, anagram): """ Filters out all the words from the wordlist which have symbols not appearing in the anagram. """ ret = [] append_flag = True for word in words: chars = set(word) for char in chars: if char not in anagram: append_flag = False break if append_flag: ret.append(word) append_flag = True return ret
def tar_extract_all(file_path, tmp_dir): """Extracts the contents of a TAR file.""" extracted = False try: tf = tarfile.open(file_path, "r:*") tf.extractall(tmp_dir) tf.close() extracted = tmp_dir except Exception as e: print("Error extracting TAR file: {}".format(e)) return extracted
def lzip(*args): """ this function emulates the python2 behavior of zip (saving parentheses in py3) """ return list(zip(*args))
def average_above_zero(tab): """ brief: computes the average of the lists Args: tab: a list of numeric values, expects at least one positive values Return: the computed average Raises: ValueError if no positive value is found """ if not(isinstance(tab, list)): raise ValueError('Expected a list as input') average=-99 valSum=0.0 nPositiveValues=0 for val in tab: if val > 0: valSum+=float(val) nPositiveValues+=1 if nPositiveValues <= 0: raise ValueError('No positive value found') average=valSum/nPositiveValues return average
def truncate(base, length, ellipsis="..."): """Truncate a string""" lenbase = len(base) if length >= lenbase: return base return base[: length - len(ellipsis)] + ellipsis
def maxSubarray(l): """returns (a, b, c) such that sum(l[a:b]) = c and c is maximized""" best = 0 cur = 0 curi = starti = besti = 0 for ind, i in enumerate(l): if cur+i > 0: cur += i else: # reset start position cur, curi = 0, ind+1 if cur > best: starti, besti, best = curi, ind+1, cur return starti, besti, best
def score_to_formatted_string(score, characters=9): """Transform a number (score) into a best-format string. The format will be either int (2234), float (10.234) or engineering (1.20E5), whichever is shorter. The score is then padded with left whitespaces to obtained the desired number of ``characters``.""" raw = str(int(score) if (int(score) == score) else score) as_float = "%.02f" % score as_eng = "%.02E." % score return min([raw, as_float, as_eng], key=len).rjust(characters)
def formatter(obj, allowed_keys): """Pull attributes from objects and convert to camelCase """ data = {} for key in allowed_keys: val = getattr(obj, key, None) data[key] = val return data
def summarize_reduced_diffs(reduced_diffs): """ Print a human-readable summary of the relevant reduced diff data """ buf = "" ### General summary if 'sum_data_units_read_gibs' not in reduced_diffs: read_gibs = reduced_diffs.get('sum_data_units_read_bytes', 0) * 2.0**(-40) write_gibs = reduced_diffs.get('sum_data_units_written_bytes', 0) * 2.0**(-40) else: read_gibs = reduced_diffs.get('sum_data_units_read_gibs', 0) write_gibs = reduced_diffs.get('sum_data_units_written_gibs', 0) buf += "Read: %10.2f TiB, %10.2f MOps\n" % ( read_gibs, reduced_diffs.get('sum_host_read_commands', 0) / 1000000.0) buf += "Written: %10.2f TiB, %10.2f MOps\n" % ( write_gibs, reduced_diffs.get('sum_host_write_commands', 0) / 1000000.0) buf += "WAF: %+10.4f\n" % reduced_diffs.get('max_write_amplification_factor', 0) return buf
def euler_step(u, f, dt, *args): """ Returns the solution at the next time step using Euler's method. Parameters ---------- u : numpy.ndarray Solution at the previous time step as a 1D array of floats. f : function Function to compute the right-hand side of the system. dt : float Time-step size. args : tuple, optional Positional arguments to pass to the function f. Returns ------- u_new : numpy.ndarray The solution at the next time step as a 1D array of floats. """ u_new = u + dt * f(u, *args) return u_new
def scaleNumber(val, src, dst): """ http://stackoverflow.com/a/4155197 Scale the given value from the scale of src to the scale of dst. @rtype : int @type dst: list @type src: list @type val: int Examples: >> scaleNumber(0, (0.0, 99.0), (-1.0, 1.0)) -1.0 >> scaleNumber(99, (0.0, 99.0), (-1.0, 1.0)) 1 >> scaleNumber(1, (0.0, 2.0), (0.0, 1.0)) 0.5 """ try: return ((val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0] except ZeroDivisionError: return dst[1] / 2.0
def convert_token(token): """ Convert PTB tokens to normal tokens """ if (token.lower() == '-lrb-'): return '(' elif (token.lower() == '-rrb-'): return ')' elif (token.lower() == '-lsb-'): return '[' elif (token.lower() == '-rsb-'): return ']' elif (token.lower() == '-lcb-'): return '{' elif (token.lower() == '-rcb-'): return '}' return token
def battery_voltage_profile(soc) -> float: """The battery profile. :param soc: State of charge :return: float -- the present voltage. """ if 0 <= soc <= 75: return 50 * soc / 75 + 310 return 360
def _depgrep_conjunction_action(_s, _l, tokens, join_char="&"): """ Builds a lambda function representing a predicate on a tree node from the conjunction of several other such lambda functions. This is prototypically called for expressions like (`depgrep_rel_conjunction`):: < NP & < AP < VP where tokens is a list of predicates representing the relations (`< NP`, `< AP`, and `< VP`), possibly with the character `&` included (as in the example here). This is also called for expressions like (`depgrep_node_expr2`):: NP < NN S=s < /NP/=n : s < /VP/=v : n .. v tokens[0] is a depgrep_expr predicate; tokens[1:] are an (optional) list of segmented patterns (`depgrep_expr_labeled`, processed by `_depgrep_segmented_pattern_action`). """ # filter out the ampersand tokens = [x for x in tokens if x != join_char] # print 'relation conjunction tokens: ', tokens if len(tokens) == 1: return tokens[0] else: return ( lambda ts: lambda n, m=None, el=None: all( predicate(n, m, el) for predicate in ts ) )(tokens)
def extract_data_values(data, value_key): """Extract value from a pandas.DataFrame Parmeters --------- data : dict The raw data. value_key : string A column in data which contains the values we are to extract. Returns ------- values : dict A dict where the keys are the id's found in data_key and the values are the correconding values from data_value. """ values = {} for key in data: values[key] = data[key][value_key] return values
def entry_lookup(target, row, case_sensitive=True): """ Return the index of a specified target value in a list. Throws a KeyError if no match :param target: str :param row: list :param case_sensitive: bool :return: int """ if case_sensitive: for i in range(0, len(row)): if row[i] == target: return i raise KeyError('{0} not found'.format(target)) else: target = target.lower() for i in range(0, len(row)): if row[i].lower() == target: return i raise KeyError('{0} not found'.format(target))
def normalize(vector): """ Returns a 3-element vector as a unit vector. """ sum = vector[0] + vector[1] + vector[2] return (vector[0]/(sum+0.0), vector[1]/(sum+0.0), vector[2]/(sum+0.0))
def fill_list(list, target_size): """ Creates a new list out of a given one and extends it with last element of the list :return: the extended list """ new_list = [] given_list_len = len(list) i = 1 while i <= target_size: if i < given_list_len: new_list.append(list[i - 1]) else: new_list.append(list[given_list_len - 1]) i += 1 return new_list
def fix_short_sentences(summary_content): """ Merge short sentences with previous sentences :param summary_content: summary text """ LEN_95_PERCENTILE = 20 # merge short sentences ix = 0 fixed_content = [] while ix < len(summary_content): sentence = summary_content[ix] if len(sentence) < LEN_95_PERCENTILE: if fixed_content and sentence[0].islower(): fixed_content[-1] = fixed_content[-1] + " " + sentence ix += 1 elif ix+1 < len(summary_content): fixed_content.append(sentence + " " + summary_content[ix+1]) ix += 2 else: try: fixed_content[-1] = fixed_content[-1] + " " + sentence except: print ("sentence: ", sentence) print ("summary_content: ", summary_content) print ("fixed_content: ", fixed_content) ix += 1 else: fixed_content.append(sentence) ix += 1 return fixed_content
def cross(*args): """ compute cross-product of args """ ans = [] for arg in args[0]: for arg2 in args[1]: ans.append(arg + arg2) return ans # alternatively: # ans = [[]] # for arg in args: # ans = [x+y for x in ans for y in arg] # return ans
def to_plotly_rgb(r, g, b): """Convert seaborn-style colour tuple to plotly RGB string. Args: r (float): between 0 to 1 g (float): between 0 to 1 b (float): between 0 to 1 Returns: a string for plotly """ return f"rgb({r * 255:.0f}, {g * 255:.0f}, {b * 255:.0f})"
def decStrToBin(numStr, bits): """Convert decimal sring into int of n-bits (negative numbers as 2's complement)""" return int(int(numStr) & 2**bits-1)
def get_exit_event(state, events): """Check if a given state has been exited at some point during an execution""" return next( ( e for e in events if e["type"].endswith("StateExited") and e["stateExitedEventDetails"]["name"] == state ), None, )
def _flp2(number): """ .. funktion:: _flp2(number) Rounds x to the largest z | z=2**n. :type number: int :rtype: int """ number |= (number >> 1) number |= (number >> 2) number |= (number >> 4) number |= (number >> 8) number |= (number >> 16) return number - (number >> 1)
def calculate_return_rate(net_values): """ Args: net_values: net values of fund as a list Returns: return_rate """ return_rate = [] for i in range(len(net_values) - 1): return_rate.append((net_values[i] - net_values[i + 1]) / net_values[i+1]) return return_rate
def check_youtube(url: str) -> bool: """ Check if url from youtube :param url: URL :return: True if url from youtube else False """ if "youtube.com" in url or "youtu.be" in url: return True else: return False
def to_value_seq(values): """ values might be a sequence or a single float value. Returns either the original sequence or a sequence whose only item is the value""" try: val = float(values) return [val,] except: return values
def __check_flag__(all_vars, flag, requirements): # type: (dict, str, list) -> list """ Checks the given flag against the requirements looking for issues. :param all_vars: All variables. :param flag: Flag to check. :param requirements: Flag requirements. :returns: A list of issues (empty if none). """ flag_header = "Flag " is_not = " is not " issues = [] if len(requirements) == 1: # Only check type req_type = requirements[0] if not type(all_vars[flag]) in req_type: issues.append(flag_header + flag + is_not + str(req_type)) if len(requirements) == 2: # Check type req_type = requirements[0] req_values = requirements[1] if not type(all_vars[flag]) in req_type: issues.append(flag_header + flag + is_not + str(req_type)) else: # Check that it is also one of the options if not all_vars[flag] in req_values: issues.append(flag_header + flag + "=" + all_vars[flag] + " is not supported. Available values: " + str(req_values)) return issues
def _reception_coord(x_t, y_t, z_t, vx, vy, vz, travel_time): """ Calculates satellite coordinates at signal reception time Input: satellite coordinates at transmission time (x_t, y_t, z_t) [m] satellite velocity in ECEF frame [m/s] signal travel time calculated from pseudorange [s] Output: satellite coordinates at signal reception time """ x_r = x_t-vx*travel_time y_r = y_t-vy*travel_time z_r = z_t-vz*travel_time return x_r, y_r, z_r
def closest_in_list(lst, val, num=2): """ Returns two (`num` in general) closest values of `val` in list `lst` """ idxs = sorted(lst, key=lambda x: abs(x - val))[:num] return sorted(list(lst).index(x) for x in idxs)
def match_entry_type(types): """Get the type identifier from the type attributes of an entry. :param set types: set with wp vocabularies as string. :return: entry_type: type identifier, used as first key to the main graph ('nodes' -> graph[entry_type][node_id]) :rtype: Optional[str] """ # Matches the vocabularies set from wp (could be indicated one or more types) specified in # RDF as URI namespaces (previous URI parsing). if types == {'core#Collection', 'wp#Pathway'} or types == {'wp#PublicationReference'}: return 'pathway_info' elif ( types == {'wp#DataNode', 'wp#Protein'} or types == {'wp#DataNode', 'wp#Metabolite'} or types == {'wp#DataNode', 'wp#GeneProduct'} or types == {'wp#DataNode'} ): return 'nodes' elif ( types == {'wp#Interaction', 'wp#DirectedInteraction'} or types == {'wp#Catalysis', 'wp#DirectedInteraction', 'wp#Interaction'} or types == {'wp#Interaction', 'wp#ComplexBinding', 'wp#Binding'} ): return 'interactions' elif types == {'wp#Interaction'} or types == {'wp#Complex'}: return 'complex' raise Exception('Entry type/s not recognised %s', types)
def split_record(line, separator=';'): """Split `line` to a list of fields and a comment >>> split_record('0000..0009 ; XXX # some value') (['0000..0009', 'XXX'], 'some value') """ try: i = line.index('#') except ValueError: record_line = line comment = '' else: record_line = line[:i] comment = line[i+1:] fields = [x.strip() for x in record_line.split(separator)] comment = comment.strip() return fields, comment
def get_query_by_analysis_id(analysis_id): """Return query that filters by analysis_id""" return { "query": { "bool": { "filter": { "term": { "dashboard_id": analysis_id } } } } }
def change_exclusion_header_format(header): """ Method to modify the exclusion header format. ex: content-type to Content-Type""" if type(header) is list: tmp_list = list() for head in header: tmp = head.split("-") val = str() for t in tmp: val = val + "-" + t.capitalize() tmp_list.append(val.replace("-", "", 1)) return tmp_list else: tmp = header.split("-") val = str() for t in tmp: val = val + "-" + t.capitalize() return val.replace("-", "", 1)
def encoding_sequence(text, sequence): """ Function to encode the character sequence into number sequence Args: text (string): cleaned text sequence (list): character sequence list Returns: dict: dictionary mapping of all unique input charcters to integers list: number encoded charachter sequences """ mapping = dict((c, i) for i, c in enumerate(sorted(list(set(text))))) encoded_sequence = [[mapping[char] for char in sub_sequence] for sub_sequence in sequence] return mapping, encoded_sequence
def complementary(a): """Get complementary nucleobase. Args: a: One of four nucleobases ('A', 'G', 'C', 'U'). Returns: b: Complementary base. """ a = a.upper() if a == 'A': return 'U' if a == 'U': return 'A' if a == 'C': return 'G' if a == 'G': return 'C' raise Exception('The given letter is not a valid RNA base.')
def variant_name(variant): """Return a human-readable string representation of variant.""" if variant is None: return '<default>' return variant
def dedupeClauses(terms): """Return a list of terms in the same order with duplicates removed. - Input: a list. - Output: a list with duplicates removed. """ newTerms = [] for t in terms: if t not in newTerms: newTerms.append(t) return newTerms
def cloudtrail_network_acl_ingress_anywhere(rec): """ author: @mimeframe description: Alert on AWS Network ACLs that allow ingress from anywhere. reference_1: http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html reference_2: http://docs.aws.amazon.com/AWSEC2/ latest/APIReference/API_CreateNetworkAclEntry.html """ if rec['detail']['eventName'] != 'CreateNetworkAclEntry': return False req_params = rec['detail']['requestParameters'] return (req_params['cidrBlock'] == '0.0.0.0/0' and req_params['ruleAction'] == 'allow' and req_params['egress'] is False)
def _disjoint_p(M, N, strict=False): """Check if Mobius transforms define disjoint intervals.""" a1, b1, c1, d1 = M a2, b2, c2, d2 = N a1d1, b1c1 = a1*d1, b1*c1 a2d2, b2c2 = a2*d2, b2*c2 if a1d1 == b1c1 and a2d2 == b2c2: return True if a1d1 > b1c1: a1, c1, b1, d1 = b1, d1, a1, c1 if a2d2 > b2c2: a2, c2, b2, d2 = b2, d2, a2, c2 if not strict: return a2*d1 >= c2*b1 or b2*c1 <= d2*a1 else: return a2*d1 > c2*b1 or b2*c1 < d2*a1
def termTypeIdentifier(element, dataType): """ Identifies the termtype of the object 'element' based on itself and its datatype 'dataType' and returns it """ if(len(str(element).split(":")) == 2 or "http" in str(element) or dataType == "anyURI"): return 'IRI', '~iri' else: return 'Literal', ''
def extendBin(bnum, length): """ :param str bnum: binary number or integer :param int length: :return list-str: binary number with leading zeros """ if not isinstance(bnum, str): bnum = bin(bnum) result = list(bnum)[2:] while len(result) < length: result.insert(0, '0') return result
def _mangle_name(internal_name, class_name): """Transform *name* (which is assumed to be an "__internal" name) into a "_ClassName__internal" name. :param str internal_name: the assumed-to-be-"__internal" member name :param str class_name: the name of the class where *name* is defined :return: the transformed "_ClassName__internal" name :rtype: str """ return "_%s%s" % (class_name.lstrip('_'), internal_name)
def to_minute_of_day(s): """ from hh:mm string to minute of day, no check """ _ = s.partition(':') return int(_[0]) * 60 + int(_[2])
def create_template(path, filename): """This method is used to format the template of the plugin that is being created given the filename and the path in which it will be stored. """ template = """cd """ + path + """ cat >> """ + filename + """.py << EOL # All plugins should inherite from this library from plugin import plugin # This is the standard form of a plugin for jarvis # Anytime you make a change REMEMBER TO RESTART Jarvis # You can run it through jarvis by the name # in the @plugin tag. @plugin("my plugin") def my_plugin(jarvis, s): # Prints 'This is my new plugin!' jarvis.say("This is my new plugin!") # For more info about plugin development visit: # https://github.com/sukeesh/Jarvis/blob/master/doc/PLUGINS.md EOL""" return template
def two_list_dictionary(keys, values): """Given keys and values, make dictionary of those. >>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7]) {'x': 9, 'y': 8, 'z': 7} If there are fewer values than keys, remaining keys should have value of None: >>> two_list_dictionary(['a', 'b', 'c', 'd'], [1, 2, 3]) {'a': 1, 'b': 2, 'c': 3, 'd': None} If there are fewer keys, ignore remaining values: >>> two_list_dictionary(['a', 'b', 'c'], [1, 2, 3, 4]) {'a': 1, 'b': 2, 'c': 3} """ out = {} for idx, val in enumerate(keys): out[val] = values[idx] if idx < len(values) else None return out # Another way using a feature from Python's standard library. We don't expect # you to have found this one---but it's a good example of how knowing the # standard library is so useful! # from itertools import zip_longest # return dict(zip_longest(keys, values))
def get_cat_by_index(idx, encodings): """Return the name of the category for the given encoded index""" for key in encodings.keys(): if encodings[key] == idx: return key
def get_maximum_rows(sheet_object): """Temporal fix to row count in openpyxl [Source](https://stackoverflow.com/questions/46569496/openpyxl-max-row-and-max-column-wrongly-reports-a-larger-figure) """ rows = 0 for _, row in enumerate(sheet_object, 1): if not all(col.value is None for col in row): rows += 1 return rows
def fold_left(f, init, l): """ f : a -> b -> b init : b l : a list Returns f(...f(l[1],f(l[0], init)) """ res = init for x in l: res = f(x, res) return res
def is_response(body): """judge if is http response by http status line""" return body.startswith(b'HTTP/')
def validate_pin4(pin): """ Aha! This version bypasses using regex and just uses .isdigit() """ return len(pin) in (4, 6) and pin.isdigit()
def convert_to_absolute(values, shapes): """ Convert a value from relative to absolute if it is not :param values: a List with two values for height and width :param shape: The shape of the image :return: Absolute values """ return [int(value * shape) for value, shape in zip(values, shapes) if value < 1 and value > 0]
def all_disjoint(sets): """http://stackoverflow.com/questions/22432814/check-if-a-collection-of-sets-is-pairwise-disjoint""" all = set() for s in sets: for x in s: if x in all: return False all.add(x) return True
def gain(xi=100.0, xf=110.0): """ Calculate gain from intial to final value. """ return (xf - xi) / xi
def merge_two_dicts(x, y): """ Python 2/3 compatible method to merge two dictionaries. Ref: https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression :param x: Dictionary 1. :param y: Dictionary 2. :return: Merged dicts. """ z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z
def byte_len(s): """Return the length of ``s`` in number of bytes. :param s: The `string` or `bytes` object to test. :type s: str or bytes :return: The length of ``s`` in bytes. :rtype: int :raises TypeError: If ``s`` is not a `str` or `bytes`. """ if isinstance(s, str): return len(s.encode()) elif isinstance(s, bytes): return len(s) else: raise TypeError('Cannot determine byte length for type {}'.format(type(s)))
def find_duplicates(customList): """find all duplicates by name""" name_lookup = {} for c, i in enumerate(customList): name_lookup.setdefault(i.depth, []).append(c) duplicates = set() for name, indices in name_lookup.items(): for i in indices[:-1]: duplicates.add(i) return sorted(list(duplicates))
def deepmap(f, dl): """ Performs a deep map over deeply nested list. Examples -------- Let us define a deep list: >>> dl = [0, 1, [2, [3], 4]] Now we can apply the function over each leaf of the list: >>> deepmap(lambda x: x + 1, dl) [1, 2, [3, [4], 5]] """ if isinstance(dl, list): return map(lambda x: deepmap(f, x), dl) else: return f(dl)
def str_upper(value: str) -> str: """Converts a string to all upper case. Parameters ---------- value : str The string to turn to upper case. Returns ------- str The upper case string. """ return value.upper()
def transform_predicate(predicate: str): """ Stems the predicate by two rules ends with s -> remove s ends with ed -> remove d :param predicate: :return: """ if predicate.endswith('s'): return predicate[:-1] if predicate.endswith('ed'): return predicate[:-1] return predicate