content
stringlengths
42
6.51k
def unpack_data(data_str): """Extract the code and message from a received string. Parameters ---------- data_str : str Returns ------- code : str msg : str """ if data_str: data_list = data_str.split(' ', 1) code = data_list[0] msg = None if len(data_li...
def reverse_long_words(sentence: str) -> str: """ Reverse all words that are longer than 4 characters in a sentence. >>> reverse_long_words("Hey wollef sroirraw") 'Hey fellow warriors' >>> reverse_long_words("nohtyP is nohtyP") 'Python is Python' >>> reverse_long_words("1 12 123 1234 54321 ...
def normalizer(dataset, colorby): """normalizes dataset using min and max values""" valnorm_lst = [] if colorby not in ["atom_type", "residue_type"]: for val in dataset.values(): val = float(val) # used if all values in the set are the same if max(dataset.values(...
def extract_scalar_reward(value, scalar_key='default'): """ Extract scalar reward from trial result. Parameters ---------- value : int, float, dict the reported final metric data scalar_key : str the key name that indicates the numeric number Raises ------ RuntimeEr...
def is_complex(object): """Check if the given object is a complex number""" return isinstance(object, complex)
def _worker_command_line(thing, arguments): """ Create a worker command line suitable for Popen with only the options the worker process requires """ def a(name): "options with values" return [name, arguments[name]] * (arguments[name] is not None) def b(name): "boolean op...
def email_escape_char(email_address): """ Escape problematic characters in the given email address string""" return email_address.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
def detect_graphql(payload): """ """ return "query" in payload
def _truncate_location(location): """ Cuts off anything after the first colon in location strings. This allows for easy comparison even when line numbers change (as they do regularly). """ return location.split(":", 1)[0]
def calculate_roc_points(instances): """From a sorted list of instances, calculate the points that draw the ROC curve.""" # Calculate the number of positives and negatives (the real ones). P = N = 0 for label, score in instances: if label == 'p': P += 1 else: N +...
def get_sentiment_emoji(sentiment): """Returns an emoji representing the sentiment score.""" if sentiment == 0: return ":neutral_face:" elif sentiment > 0: return ":thumbsup:" else: # sentiment < 0: return ":thumbsdown:"
def moveParameters(target): """ Iterate through all paths and move the parameter types to the schema subsection """ for path in target['paths']: for verb in target['paths'][path]: #Only need to be performed on 'parameters' key if verb == 'parameters': para...
def GenerateAuthProviderCmdArgs(kind, cluster_id, location): """Generates command arguments for kubeconfig's authorization provider. Args: kind: str, kind of the cluster e.g. aws, azure. cluster_id: str, ID of the cluster. location: str, Google location of the cluster. Returns: The command argum...
def allow_minkowski_specification(value): """Dash callback for enabling/disabling the Minkowski distance input widget for k nearest neighbors. Given a distance metric to use for measuring the distance between neighbors in the k nearest neighbors algorithm, only allow user input of the Minkowski dis...
def tree_intersection(tree_one, tree_two): """ Function that takes in two binary trees, and returns a list of all common values in both trees In: 2 parameters - 2 trees Out: List of all common values found in both trees """ if tree_one is None or tree_two is None: return [] seen = ...
def factorial(number): """ This method calculates the factorial of the number """ result = 1 for index in range(1,number+1): result *= index return result
def diff(n, l): """ Runtime: O(n) """ occurences = {} count = 0 for i in l: if i in occurences.keys(): occurences[i] += 1 else: occurences[i] = 1 for i in occurences.keys(): if i + n in occurences.keys(): c1 = occurences[i] c2 = occurences[i+n] count += c1 * c2 ...
def normalise_toolshed_url(tool_shed): """ Return complete URL for a tool shed Arguments: tool_shed (str): partial or full URL for a toolshed server Returns: str: full URL for toolshed, including leading protocol. """ if tool_shed.startswith('http://') or \ ...
def get_track_row(name, performer, time, row_format='raw'): """ function to get track row in specified format """ if row_format == 'csv': return '"{}","{}","{}"\n'.format(name, performer, time) return '{0:<60} - {1:<60}{2:<60}\n'.format(name, performer, time)
def _get_hash(bytestring): """Get sha256 hash of `bytestring`.""" import hashlib return hashlib.sha256(bytestring).hexdigest()
def page_moment(n, na, m): """Return average trace of moment of reduced density matrix for ergodic states. """ if m == 2: return 1/2**na + 1/2**(n-na) if m == 3: return 1/2**(2*na)+1/2**(2*(n-na))+1/2**(2*n)+3/2**n
def addVectors(a, b): """Add two list-like objects, pair-wise.""" return tuple([a[i] + b[i] for i in range(len(a))])
def validate_subnet_mask(subnet_mask): """Checks that the argument is a valid subnet mask. :param str subnet_mask: The subnet mask to check. :return: True if the subnet mask is valid; false if not. :rtype: bool :raises ValueError: if the subnet mask is invalid. .. seealso:: https://c...
def split(s, sep=None, maxsplit=0): """split(str [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is nonzero, splits into at most maxsplit words If sep is not specified, any whitespace string is a separator. Maxs...
def saml_assertion_to_ldap_style_name(assertion_attributes): """ Return string, approximating a NOAA LDAP-style name for SAML user Keyword Parameters: assertion_attributes -- Dict, representing SAML assertion attributes for a logged in user >>> test_attributes = {'mail': ['Pat.Ng@noaa.gov']...
def weWantThisPixel(col, row): """ a function that returns True if we want # @IndentOk the pixel at col, row and False otherwise """ if col%10 == 0 and row%10 == 0: return True else: return False
def complement(dna): """ This function will return the complement of dna sequence of the input sequence :param dna: (string) original dna :return: (string) complement dna """ ans = '' for base in dna: if base == 'A': ans += 'T' if base == 'T': ans += '...
def is_int(string): """Checks if a string can be converted into an integer""" try: int(string) return True except ValueError: return False
def lowercase_voc(voc): """ In case of conflict take the max of two. """ print("....") vocl = {} for v in voc: vl = v.lower() if vl not in vocl or vocl[vl] < voc[v]: vocl[vl] = voc[v] else: pass return vocl
def get_chess_square_border(size, x, y): """ Returns the coordinates of the square block's border """ return (x * size // 8 + 2, y * size // 8 + 2)
def put_on_device(dev, tensors): """Put arguments on specific device Places the positional arguments onto the user-specified device Parameters ---------- dev : str Device identifier tensors : sequence/list Sequence of torch.Tensor variables that are to be put on the device ...
def split_dirname(dirname): """Splits the capitalized suffix out from the given directories. Looks for the longest suffix that is CamelCased; specifically, where each directory starts with a capitalized letter. See go/haskell-standard-names for the motivation of this scheme. For example: ...
def to_list(collection): """:yaql:toList Returns list built from iterable. :signature: collection.toList() :receiverArg collection: collection to be transferred to list :argType collection: iterable :returnType: list .. code:: yaql> range(3).toList() [0, 1, 2] """ ...
def xor_bytes(a, b): """ Returns a new byte array with the elements xor'ed. """ return bytes(i^j for i, j in zip(a, b))
def does_not_compose(left, right): """ Composition error. """ return "{} does not compose with {}.".format(left, right)
def flatten_with_key_paths( d, sep=None, flat_list=True, reverse_key_value=False, condition_fn=None ): """ Example: >>> d = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} >>> flatten_with_key_paths(d, flat_list=False) {('a',): 1, ('c', 'a'): 2, ('c', 'b', 'x'): 5, ('c', 'b'...
def comparable(bytes): """ Helper function to make byte-array output more readable in failed test assertions. """ readables = ["%02x" % v for v in bytes] return " ".join(readables)
def sum_of_lines(line1, line2): """ sum of snailfish lines """ return "[" + line1 + "," + line2 + "]"
def allowed_file(filename, allowed_extensions): """ Check for whether a filename is in the ALLOWED_EXTENSIONS Args: filename (str): filename to check Returns: bool: whether the filename is in allowed extensions """ return '.' in filename and \ filename.rsplit('.', 1)...
def join_url(*args): # type: (*str) -> str """ Joins given arguments into an url and add trailing slash """ parts = [part[:-1] if part and part[-1] == '/' else part for part in args] parts.append('') return '/'.join(parts)
def calculate_a(sigma1: float, sigma2: float, rho: float) -> float: """Calculates Clark's expression for a (degeneracy condition).""" a2 = sigma1 ** 2 + sigma2 ** 2 - 2 * sigma1 * sigma2 * rho a = a2 ** 0.5 return a
def is_luminous(rgb): """Is an "rgb" value luminous. Notes ----- Determined using the formula at: https://www.w3.org/TR/WCAG20/#relativeluminancedef """ new_color = [] for c in rgb: if c <= 0.03928: new_color.append(c / 12.92) else: new_col...
def get_corpus(tokens): """ Combine the list of tokens into a string :return: a long string that combines all the tokens together """ corpus = ' '.join(tokens) return corpus
def bps_to_mbps(value): """Bits per second to Mbit/sec""" return round(int(value) / (1000**2), 3)
def format_birthday_for_database(p_birthday_of_contact_month, p_birthday_of_contact_day, p_birthday_of_contact_year): """Takes an input of contact's birthday month, day, and year and creates a string to insert into the contacts database.""" formated_birthday_string = p_birthday_of_contact_month + "/" + p_birthd...
def _hemisphere(latitude): """ This function defines the hemisphere from latitude :param latitude: float :return: String 'S' is South 'N' is North """ # if latitude > 0: # min_max hemisphere_lat = 'N' # North else:...
def buildUpdateFields(params): """Join fields and values for SQL update statement """ return ",".join(['%s = "%s"' % (k, v) for k, v in list(params.items())])
def f_raw(x, a, b): """ The raw function call, performs no checks on valid parameters.. :return: """ return a * x + b
def cast_value(value, requested_type): """ Tries to cast the given value to the given type """ try: if requested_type == "Boolean": return value == "True" if requested_type == "Integer": return int(value) if requested_type == "Float": return float(valu...
def normalize_path_for_settings(path, escape_drive_sep=False): """ Normalize a path for a settings file in case backslashes are treated as escape characters :param path: The path to process (string or pathlib.Path) :param escape_drive_sep: Option to escape any ':' driver separator (wi...
def _check_transform_file_ending(fn, f_format=".sdf"): """Checks if there is sdf(or optional other) file ending. If not it adds a file ending. """ if fn.endswith(f_format): return fn else: return fn + f_format
def amplitude(times, signal, period): """ Computes the mean amplitude of a periodic signal params: - times: instants when the measures were taken - signal: values of the measure - period: period of the signal """ n = len(times) if not len(signal) == len(times): ...
def endlToFudgeInterpolation( interpolation ) : """This function converts an endl interpolation value (0 or 2 is lin-lin, 3 is log-lin, 4 is lin-log and 5 is log-log) into a fudge interpolation value (0 is lin-lin, 1 is log-lin, 2 is lin-log and 3 is log-log).""" if( ( interpolation < 0 ) or ( interpolatio...
def no_none_get(dictionary, key, alternative): """Gets the value for a key in a dictionary if it exists and is not None. dictionary is where the value is taken from. key is the key that is attempted to be retrieved from the dictionary. alternative is what returns if the key doesn't exist.""" if key...
def pre_cell(data, html_class='center'): """Formats table <pre> cell data for processing in jinja template.""" return { 'cell_type': 'pre', 'data': data, 'class': html_class, }
def merge_variables(program, node, variables): """Create a combined Variable for a list of variables. The purpose of this function is to create a final result variable for functions that return a list of "temporary" variables. (E.g. function calls). Args: program: A cfg.Program instance. node: The c...
def ife(test, if_result, else_result): """ Utility if-then-else syntactic sugar """ if(test): return if_result return else_result
def two_sum_problem_hash(data, total, distinct=False): """ Returns the pairs of number in input list which sum to the given total. Complexity O(n) Args: data: list, all the numbers available to compute the sums. total: int, the sum to look for. distinct: boolean, whether to accept ...
def nested_dict(dict_, keys, val): """Assign value to dictionary.""" cloned = dict_.copy() if len(keys) == 1: cloned[keys[0]] = val return cloned dd = cloned[keys[0]] for k in keys[1:len(keys) - 1]: dd = dd[k] last_key = keys[len(keys) - 1] dd[last_key] = val return cloned
def actor_phrase_match(patphrase, phrasefrag): """ Determines whether the actor pattern patphrase occurs in phrasefrag. Returns True if match is successful. Insha'Allah... """ ret = False APMprint = False connector = patphrase[1] kfrag = 1 # already know first word matched kpatword...
def _symbolize_path(keypath): """ Take a key path like `gust.version`, and convert it to a global symbol like `GUST_VERSION`, which is usable as, say, an environment variable. """ return keypath.replace(".", "_").upper()
def _max(arr): """Maximum of an array, return 1 on empty arrays.""" return arr.max() if arr is not None and len(arr) > 0 else 1
def create_unimplemented_message(param, method): """Message to tell you request is succeed but requested API is unimplemented. :param param: request param :param method: request method :return: message object """ date = { 'message': 'Request is succeed, but this API is unimplemented.', ...
def index(s, *args): """index(s, sub [,start [,end]]) -> int Like find but raises ValueError when the substring is not found. """ return s.index(*args)
def duration_as_string(years, months): """ Return duration as printable string """ duration_y = '' duration_m = '' if years > 1: duration_y = '{} years'.format(years) elif years == 1: duration_y = '1 year' if months > 1: duration_m = '{} months'.format(months) elif mo...
def combine_english_defs(senses, separator=u', '): """Combines the English definitions in senses. Args: senses: An array with dict elements with English info. Returns: A string of English definitions separated by the separator. """ # Each sense contains a list of English definitions....
def has_same_spaces(plain, cipher): """has same number of spaces in same positions""" if len(plain) != len(cipher): return False if plain.count(' ') != cipher.count(' '): return False for p, c in zip(plain, cipher): if p==' ' and c != p: return False return...
def get_eta_powerlaw_params(param_dict): """ Extract and return parameters from dictionary for powerlaw form """ rScale = param_dict['rScale'] rc = param_dict['rc'] etaScale = param_dict['etaScale'] betaDelta = param_dict['betaDelta'] return rScale, rc, etaScale, betaDelta
def add_database_name(db, name): """Add database name to datasets""" for ds in db: ds['database'] = name return db
def preprocess_txt(input_ids, masks, labels): """ format for tf model """ return {'input_ids': input_ids, 'attention_mask': masks}, labels
def findAnEven(L): """Assumes L is a list of integers Returns the first even number in L Raises ValueError if L does not contain an even number""" for e in L: if e%2 == 0: return e else: e = e raise ValueError('The provided list does not contain an even number...
def empty_chunk(n): """ Produce a 2D list of size n x n that is populated with ".". """ return [["." for _ in range(n)] for _ in range(n)]
def index_to_tier(index): """Convert numerical index to named tier""" tier = ("Primary" if index == 1 else "Reserve" if index == 2 else "Index %s" % index) return tier
def get_list(data): """ Return list of data from string. Args: data (str): String to convert to list Raises: None Returns: TYPE: list """ obtained_list = [ele.strip(" ").strip("\n") \ for ele in data.split(",")] return obtained_list
def set_count(items): """ This is similar to "set", but this just creates a list with values. The list will be ordered from most frequent down. Example: >>> inventory = ["apple", "lemon", "apple", "orange", "lemon", "lemon"] >>> set_count(inventory) [("lemon", 3), ("apple", 2), ...
def get_module_description(module_name: str, max_lines=5) -> str: """ Attempt to get the module docstring and use it as description for search results """ desc = "" try: doc = "" name_chunks = module_name.split(".") if len(name_chunks) > 1: tail = name_chunks[-1] ...
def filter_dict(dictionary, keep_fields): """ Filter a dictionary's entries. :param dictionary: Dictionary that is going to be filtered. :type dictionary: dict :param keep_fields: Dictionary keys that aren't going to be filtered. :type keep_fields: dict or list or set :return: Filtered ...
def early_stop(patience, max_factor, vae_loss_val, em_loss_val): """ Manual implementation of https://keras.io/api/callbacks/early_stopping/. :param patience: max number of epochs loss has not decreased :param max_factor: max_factor * current loss is the max acceptable loss :param vae_loss_val: list...
def logical_any_terminal_condition(env, conditions): """A logical "Any" operator for terminal conditions. Args: env: An instance of MinitaurGymEnv conditions: a list of terminal conditions Returns: A boolean indicating if any of terminal conditions is satisfied """ return any([cond(env) for cond...
def sign(num): """ Determines the sign of a number """ if num >= 0: return 1 else: return -1
def validate(observation): """Make sure the observation table is valid, or raise an error.""" if observation is not None and type(observation) == dict: return observation elif type(observation) == list: return observation else: raise RuntimeError('Must return dictionary from act(...
def selectionsort(arr): """ In each iteration, find the min of arr[lo:hi+1] and swap with arr[lo], then increment lo Invariant: everything to the left of lo is sorted """ lo = 0 hi = len(arr) - 1 while lo <= hi: minval = arr[lo] minindx = lo for curr in range(lo +...
def ignorefunc(original, ignore): """A function to replace ignored characters to noting :v""" text = str(original) ignore = list(ignore) for ch in ignore: if ch in text: text=text.replace(ch,"") # I don't know why, but text is not a tuple text = text.replace("(", "") text = text.replace(")", "") text =...
def checksum(string): """Fetch string and calculate the checksum. This function is copied from sample code file. Args: :param string: A string of the time in seconds since the epoch. Returns: :return: The value of checksum (integer type). """ csum = 0 count_to = (len(strin...
def next_indentation(line, tab_length): """Given a code line, return the indentation of the next line.""" line = line.expandtabs(tab_length) indentation = (len(line) - len(line.lstrip(" "))) // tab_length if line.rstrip().endswith(":"): indentation += 1 elif indentation >= 1: if line...
def remove_dup(a): """ remove duplicates using extra array """ res = [] count = 0 for i in range(0, len(a)-1): if a[i] != a[i+1]: res.append(a[i]) count = count + 1 res.append(a[len(a)-1]) print('Total count of unique elements: {}'.format(count +1)) return res
def sort_list_by (sorting_key: str, array_to_sort: list) -> list: """ Sort a list of dictionaries by one of the dictionary key values """ return sorted(array_to_sort, key=lambda keyy: keyy[sorting_key], reverse=True)
def convert(number): """ input: a number return: a string """ sound = "" if number % 3 == 0: sound = "Pling" if number % 5 == 0: sound = sound + "Plang" if number % 7 == 0: sound = sound + "Plong" if sound == "": sound = str(number) return sound
def uses_only( word, letters ): """Return True if the word contains only letters in the list. """ for w in word: if w not in letters: return False return True
def nlp_process(search_cond): """ Build structured search criteria from constraints specified in the natural language input string :param search_cond: natural language english input with email search criteria :return: mail_box, gmail mail box to retrieve emails from :return: search_criteria, structu...
def quote_str(obj): """ Adds extra quotes to a string. If the argument is not a string it is returned unmodified :param obj: Object :type obj: any :rtype: Same as argument For example: >>> import putil.misc >>> putil.misc.quote_str(5) 5 >>> putil.misc.quo...
def is_monotonically_increasing(series): """ Check if a given list or array is monotonically increasing. Examples -------- >>> import pandas as pd >>> times = pd.date_range('1980-01-19', periods=10) >>> all(is_monotonically_increasing(times)) True >>> import numpy as np >>> all(...
def c_to_f(tempc): """ Parameters Temp (C) Returns Temp (F) """ tempf = tempc * (9./5.) + 32. return tempf
def get_code(file_path: str) -> str: """Gets the source code of the specified file.""" with open(file_path, "r") as file: code = file.read() return code
def get_link_to_osm(lat, lon, zoom=15): """Return link to OSM centered in lat, lon.""" return ('http://openstreetmap.org/?mlat=%(lat)s&mlon=%(lon)s' '&zoom=%(zoom)s' % {'lat': lat, 'lon': lon, 'zoom': zoom})
def cntDivisor(n): """ >>> cntDivisor(14) 4 >>> cntDivisor(140) 12 """ rem = 1 cnt = 2 while 1: rem += 1 num = n / rem if num < rem: break if n % rem == 0: cnt += 2 if num == rem: cnt -= 1 ...
def graph_is_connected(edges, players): """ Test if a set of edges defines a complete graph on a set of players. This is used by the spatial tournaments. Parameters: ----------- edges : a list of 2 tuples players : a list of player names Returns: -------- boolean : True if the...
def string_to_bool(val): """Convert string to bool.""" if val is None: return False if isinstance(val, bool): return val if isinstance(val, str): if val.lower() in ("yes", "true", "t", "y", "1"): return True elif val.lower() in ("no", "false", "f", "n", "0")...
def _HasNewFailures(current_failures, new_failures): """Checks if there are any new failures in the current build.""" if current_failures == new_failures: return False for step, tests in current_failures.iteritems(): if not new_failures.get(step): # New step. return True for test in tests: ...
def position_angle(freq, pa_zero, rm, freq_cen): """ Polarisation position angle as a function of freq.""" c = 2.998e8 # vacuum speed of light in m/s return pa_zero + rm*(((c/freq)**2) - ((c/(freq_cen*1e6))**2))