content
stringlengths
42
6.51k
def bubble_sort(input_list): """ Compare each element with each other element to provide a sorted array. :param input_list A list of objects to be reversed. :return A sorted version/copy of the list. """ for i in range(0, len(input_list)): for j in range(i + 1, len(input_list)): if input_list[i] > input_list[j]: tmp = input_list[i] input_list[i] = input_list[j] input_list[j] = tmp return input_list
def map_range(x, in_min, in_max, out_min, out_max): """ Maps a number from one range to another. :return: Returns value mapped to new range :rtype: float """ mapped = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min if out_min <= out_max: return max(min(mapped, out_max), out_min) return min(max(mapped, out_max), out_min)
def compare_dictionaries(reference, comparee, ignore=None): """ Compares two dictionary objects and displays the differences in a useful fashion. """ if not isinstance(reference, dict): raise Exception("reference was %s, not dictionary" % type(reference)) if not isinstance(comparee, dict): raise Exception("comparee was %s, not dictionary" % type(comparee)) if ignore is None: ignore = [] b = set((x, y) for x, y in comparee.items() if x not in ignore) a = set((x, y) for x, y in reference.items() if x not in ignore) differences_a = a - b differences_b = b - a if len(differences_a) == 0 and len(differences_b) == 0: return True try: differences_a = sorted(differences_a) differences_b = sorted(differences_b) except Exception: pass print("These dictionaries are not identical:") if differences_a: print("in reference, not in comparee:") for x, y in differences_a: print("\t", x, y) if differences_b: print("in comparee, not in reference:") for x, y in differences_b: print("\t", x, y) return False
def __renumber(dictionary): """Renumber the values of the dictionary from 0 to n """ count = 0 ret = dictionary.copy() new_values = dict([]) for key in dictionary.keys(): value = dictionary[key] new_value = new_values.get(value, -1) if new_value == -1: new_values[value] = count new_value = count count += 1 ret[key] = new_value return ret
def end_of_chunk(prev_tag, tag, prev_type, type_): """Checks if a chunk ended between the previous and current word. Args: prev_tag: previous chunk tag. tag: current chunk tag. prev_type: previous type. type_: current type. Returns: chunk_end: boolean. """ chunk_end = False if prev_tag == 'E': chunk_end = True if prev_tag == 'S': chunk_end = True if prev_tag == 'B' and tag == 'B': chunk_end = True if prev_tag == 'B' and tag == 'S': chunk_end = True if prev_tag == 'B' and tag == 'O': chunk_end = True if prev_tag == 'I' and tag == 'B': chunk_end = True if prev_tag == 'I' and tag == 'S': chunk_end = True if prev_tag == 'I' and tag == 'O': chunk_end = True if prev_tag != 'O' and prev_tag != '.' and prev_type != type_: chunk_end = True return chunk_end
def get_session_value(key_string, prefix='', rconn=None): """If key_string is not found, return None""" if not key_string: return if rconn is None: return keystring = prefix+key_string if not rconn.exists(key_string): # no value exists return binvalues = rconn.lrange(key_string, 0, -1) # binvalues is a list of binary values values = [] for bval in binvalues: val = bval.decode('utf-8') if val == '_': str_val = '' else: str_val = val values.append(str_val) return values
def bitreversed_decimal(dec_input, maxbits): """Description: Compute bit-reversed value of a decimal number Parameters ---------- dec_input Decimal input whose bit-reversed value must be computed maxbits Total number of bits in binary used to represent 'in' and 'out'. Returns ------- out Bit-reversed value of 'in'. """ if maxbits == 0: bit_rev = 0 return # dec_input = bin(dec_input, maxbits) dec_input = int(dec_input) maxbits = int(maxbits) dec_input = bin(dec_input) dec_input = dec_input[2:] if len(dec_input)<maxbits: dec_input = '0'*(maxbits-len(dec_input))+dec_input # bit_rev = '0'*maxbits bit_rev = str('') for i in range(0,maxbits): # print(' ** Loop #',i) # print(' maxbits: ', maxbits) # print(' dec_input', dec_input) bit_rev = bit_rev + dec_input[maxbits-1-i] # print(' bit_rev: ', bit_rev) bit_rev = int(bit_rev,2) return bit_rev
def calculate_income_range(income): """ if income < 25000: return 0 elif income < 50000: return 1 elif income < 75000: return 2 else: return 3 """ return int(income/10000)
def config_to_kvmap(config_data, config_data_map): """ """ return dict([ (k, config_data[config_data_map[k]][2]) for k in config_data_map ])
def literal(c, code): """literal value 0x00-0x1F (literal)""" v = "0x%04X" % (code - 0x20) return v
def tryint(x, sub=-1): """Tries to convert object to integer. Like ``COALESCE(CAST(x as int), -1)`` but won't fail on `'1.23'` :Returns: int(x), ``sub`` value if fails (default: -1) """ try: return int(x) except: return sub
def create_figure(path, caption=None, align=None, alt=None, width=None): """ This method is available within ``.. exec::``. It allows someone to create a figure with a caption. """ rst = [".. figure:: {}".format(path)] if align: rst += [" :align: {}".format(align)] if alt: rst += [" :alt: {}".format(alt)] if width: rst += [" :width: {}".format(width)] if caption: rst += [""] if caption: rst += [" {}".format(caption)] return rst
def findall(root, tag, namespace=None): """ Get all nodes by tag and namespace under Node root. """ if root is None: return [] if namespace is None: return root.getElementsByTagName(tag) else: return root.getElementsByTagNameNS(namespace, tag)
def parse_bool(data): """Parse a string value to bool""" if data.lower() in ('yes', 'true',): return True elif data.lower() in ('no', 'false',): return False else: err = f'"{data}" could not be interpreted as a boolean' raise TypeError(err)
def YFrequencyList_to_HFrequencyList(y_frequency_list): """ Converts Y parameters into h-parameters. ABCD-parameters should be in the form [[f,Y11,Y12,Y21,Y22],...] Returns data in the form [[f,h11,h12,h21,h22],...] """ h_frequency_list=[] for row in y_frequency_list[:]: [frequency,Y11,Y12,Y21,Y22]=row h11=1/Y11 h12=-1*Y12/Y11 h21=Y21/Y11 h22=(Y11*Y22-Y12*Y21)/Y11 h_frequency_list.append([frequency,h11,h12,h21,h22]) return h_frequency_list
def get_args(text: str) -> str: """Return the part of message following the command.""" splitted = text.split(" ", 1) if not len(splitted) == 2: splitted = text.split("\n", 1) if not len(splitted) == 2: return "" prefix, args = splitted print(prefix) args = args.strip() print(args) return args
def get_hashtags(tweet: dict) -> list: """ The tweet argument is a dict. So get 'entities' key or return a empty dict. This is required for the second .get() to not throw a error where we try to get 'hashtags' """ entities = tweet.get('entities', {}) hashtags = entities.get('hashtags', []) return ["#" + tag['text'] for tag in hashtags]
def params_deepTools_plotHeatmap_xAxisLabel(wildcards): """ Created: 2017-05-07 18:51:43 Aim: what to show take argument with spaces which is not very good with paths. xAxisLabel-tss/xAxisLabel-peak-center """ tmp = str(wildcards['deepTools_plotHeatmap_xAxisLabel_id']); xAxisLabel = { 'tss': "'TSS'", 'gene-distance-bp': "'gene distance'", 'nuc-center': "'nuc. center'", 'peak-center': "'peak center'", 'distance-to-nucleosome-center-bp': "'nuc. distance to nucleosome center'" } return "--xAxisLabel " + xAxisLabel[tmp]
def eqiv(values): """Recursive function that does eqivalent boolean operations Example: Input: [True, True, False, False] (((True == True) == False) == False)) is True """ try: values = list(values) except TypeError: return values try: outcome = values[0] == values[1] except IndexError: return values[0] try: new_values = [outcome] + values[2:] return eqiv(new_values) except IndexError: return outcome
def project_to_2D(xyz): """Projection to (0, X, Z) plane.""" return xyz[0], xyz[2]
def _is_leap(year): """year -> 1 if leap year, else 0.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def swapxy(v:list) -> list: """Swaps the first two values in a list Args: list[x, y] Returns: list[y, x] """ return [v[1], v[0]]
def kwargs_nonempty(**kwargs): """Returns any keyword arguments with non-empty values as a dict.""" return {x: y for x, y in kwargs.items() if y}
def bestrelpath(path, relto=None): """Return a relative path only if it's under $PWD (or `relto`)""" if relto is None: from os import getcwd relto = getcwd() from os.path import relpath relpath = relpath(path, relto) if relpath.startswith('.'): return path else: return relpath
def create_response(bot_reply, end_of_session=False): """Base reply for Alexa""" response = { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": bot_reply, }, "reprompt": { "outputSpeech": { "type": "PlainText", "text": "Plain text string to speak", "playBehavior": "REPLACE_ENQUEUED" } }, "shouldEndSession": end_of_session } } return response
def _join_matchers(matcher, *matchers): """Joins matchers of lists correctly.""" output = {k: [e for e in v] for k, v in matcher.items()} for matcher_to_join in matchers: has_default = False for key, value in matcher_to_join.items(): if key == "default": # Default has a special case. has_default = True if key in output: output[key].extend(value) else: # Important to add the "default" value, if it exists, as the new # key was a "default", but is not anymore. output[key] = value if "default" in output and key != "default": value.extend(output["default"]) if has_default: for key in output.keys(): # All keys from output that are not in matcher_to_join were part # of "default" in matcher_to_join, so they need to be added the # default. if key not in matcher_to_join: output[key].extend(matcher_to_join["default"]) return output
def _find_imports(*args): """ Helper sorting the named modules into existing and not existing. """ import importlib exists = { True: [], False: [], } for name in args: name = name.replace('-', '_') try: importlib.import_module(name) exists[True].append(name) except ImportError: exists[False].append(name) return exists
def heuristic(parent, switch): """ rules: ? """ k, i, f = switch if (k, f, i) in parent: return False for kk, ii, ff in parent: if kk > k and ii == i and ff == f: return False return True
def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) k=list(d.keys()) return k[v.index(max(v))]
def _join_description_strs(strs): """Join lines to a single string while removing empty lines.""" strs = [str_i for str_i in strs if len(str_i) > 0] return "\n".join(strs)
def to_real(real, x): """ Helper function to convert a value x to a type real. This exists because not every type has a direct conversion, but maybe we can help it? """ try: # the obvious way return real(x) except TypeError as exc: # well seems like that won't work # let's see what types we can help it with if hasattr(x, 'denominator'): # ah, it's a fraction! return to_real(real, x.numerator) / to_real(real, x.denominator) # welp, we failed raise exc
def desnake(text): """Turns underscores into spaces""" return text.strip().replace("_", " ")
def make_operator(_operator, _double_pipe_c): """Handles concatenation operators.""" if _operator == 'C': if _double_pipe_c: return '||' else: return '+' else: return _operator
def interp(val, array_value, array_ref): """ Interpolate the array_value from the array_ref with val. The array_ref must be in an increasing order! """ if val <= array_ref[0]: return array_value[0] elif val > array_ref[len(array_ref)-1]: return array_value[len(array_ref)-1] else: i = 1 while val > array_ref[i]: i += 1 delta = array_ref[i] - array_ref[i-1] return ((array_ref[i]-val)*array_value[i-1]+array_value[i]*(val-array_ref[i-1]))/delta
def getUntilCRLF(str): """text section ends on CRLF """ return str.split("\r\n", 1)[0]
def filter_dict(dict, keywords): """ Returns only the keywords that are part of a dictionary Parameters ---------- dictionary : dict Dictionary for filtering keywords : list of str Keywords that will be filtered Returns ------- keywords : list of str List containing the keywords that are keys in dictionary """ return [key for key in keywords if key in dict]
def add_to_dict_of_levels(dict_levels, c, cur_level, index): """ Function returns the dict of positions according to the level of space or comma Example: {'1_,': [14], '2_,': [9], '0_ ': [3], '1_ ': [12]} comma of level 1: position 14 comma of level 2: position 9 space of level 0: position 3 space of level 1: position 12 """ symbol = str(cur_level) + '_' + c if symbol not in dict_levels: dict_levels[symbol] = [] dict_levels[symbol].append(index) return dict_levels
def leftlimit(minpoint, ds, tau): """ Find left limit. Args: minpoint (int): x coordinate of the local minimum ds (list): list of numbers representing derivative of the time-series signal s tau (int): threshold to determine a slope 'too sharp' Returns: minpoint (int): x coordinate of the left-modified local minimum """ slope = ds[minpoint-1] while slope > tau and slope < 0 and minpoint > 0: minpoint -= 1 slope = ds[minpoint-1] return minpoint
def maybe_job_id(value: str) -> bool: """Check whether the string looks like a job id""" return value.startswith("job-")
def split_sentence(sentence: str, length: int=100): """ :param sentence: :param length: :return: """ result = [] start = 0 while start < len(sentence): result.append(sentence[start: start + length]) start += length return result
def parse_properties(properties): """ Return a dictionary of attributes based on properties. Convert properties of form "property1=value1,property2=value2, ..." to {'property1': value1, 'property2': value2, ...}. """ pairs = [ (k.strip(), eval(v.strip())) for k, v in [prop.split('=', 1) for prop in properties.split(',')] ] attrs = dict() for k, v in pairs: if k in attrs: if not isinstance(attrs[k], list): attrs[k] = [attrs[k]] attrs[k].append(v) else: attrs[k] = v return attrs
def divide(dividend, divisor): """ :param dividend: a numerical value :param divisor: a numerical :return: a numerical value if division is possible. Otherwise, None """ quotient = None if divisor is not None : if divisor != 0: quotient = dividend / divisor return quotient
def rle_len( rle ): """ Return the number of characters covered by a run length encoded attribute list. """ run = 0 for v in rle: assert type(v) == tuple, repr(rle) a, r = v run += r return run
def set_image_paras(no_data, min_size, min_depth, interval, resolution): """Sets the input image parameters for level-set method. Args: no_data (float): The no_data value of the input DEM. min_size (int): The minimum nuber of pixels to be considered as a depressioin. min_depth (float): The minimum depth to be considered as a depression. interval (float): The slicing interval. resolution (float): The spatial resolution of the DEM. Returns: dict: A dictionary containing image parameters. """ image_paras = {} image_paras["no_data"] = no_data image_paras["min_size"] = min_size image_paras["min_depth"] = min_depth image_paras["interval"] = interval image_paras["resolution"] = resolution return image_paras
def _recursive_guid(input_key, input_value, indicators): """ """ results = [] if input_key in indicators: results.append(input_value) return results elif isinstance(input_value, list): for v in input_value: results.extend(_recursive_guid(None, v, indicators)) elif isinstance(input_value, dict): for k, v in input_value.items(): results.extend(_recursive_guid(k, v, indicators)) return results
def quick_doctext(doctext, indicator, value, unit=''): """ Convenience function to standardize the output format of a string. """ unitspace = ' ' if unit == '%': unitspace = '' return str('{0}\n{1} {2}{3}{4}'.format(doctext, indicator, value, unitspace, unit))
def get_int_for_unk_type(dtype): """ Returns the int for an unknown type from Sonar. The DNS type is the integer at the end of the "unk_in_{num}" string. """ return int(dtype[7:])
def postprocess_data(data: str): """ Example of a task provided by a workflow library. Task-specific details such as the Docker image and memory needs are defined here on the task. However, it is left to the user to define the executor 'utils_executor', so that user can customize project-specific details such as batch queue, and job roles. """ return f"postprocess_data({data})"
def do_stuff(num): """Adds 5 to passed int""" try: return int(num) + 5 except ValueError as err: return err
def pulse_train(time, start, duration, repeat_time, end): """ Implements vensim's PULSE TRAIN function. Parameters ---------- time: function Function that returns the current time. start: float Starting time of the pulse. duration: float Duration of the pulse. repeat_time: float Time interval of the pulse repetition. end: float Final time of the pulse. Returns ------- float: - In range [-inf, start): returns 0 - In range [start + n*repeat_time, start + n*repeat_time + duration): returns 1 - In range [start + n*repeat_time + duration, start + (n+1)*repeat_time): returns 0 """ t = time() if start <= t < end: return 1 if (t - start) % repeat_time < duration else 0 else: return 0
def get_factors(num): """Returns a list Factors of the number passed as argument """ factors = [] inc_value = 1 while inc_value * inc_value <= num: if num % inc_value == 0: if num//inc_value == inc_value: factors.append(inc_value) else: factors.append(inc_value) factors.append(num//inc_value) inc_value += 1 return factors
def anagrams(word, words): """Return list of words that are anagrams.""" final_list = [] to_match = ''.join(sorted(word)) for i in words: if ''.join(sorted(i)) == to_match: final_list.append(i) return final_list
def df_variant_id(row): """Get variant ID from pyvcf in DataFrame""" if row['ID'] != '.': return row['ID'] else: return row['CHROM'] + ':' + str(row['POS'])
def _pick_access(parameters_json: dict) -> str: """ return permissions_use if it exists, else "creator_administrative_unit, else none """ part_of = parameters_json.get('partOf', '') while isinstance(part_of, list): part_of = part_of[0] if "zp38w953h0s" in part_of or parameters_json.get('id', '') == 'zp38w953h0s': # Commencement Programs return 'Permission to publish or publicly disseminate reproductions of any material obtained from the University Archives must be secured from the University Archives and any additional copyright owners prior to such use. Please see <a href="http://archives.nd.edu/about/useform.pdf">Conditions Governing Reproduction and Use of Material</a> for additional information' # noqa: E501 return parameters_json.get('permissions_use', parameters_json.get('creator_administrative_unit', None))
def compute_files_to_download(client_hashes, server_hashes): """Given a dictionary of file hashes from the client and the server, specify which files should be downloaded from the server Params: client_hashes- a dictionary where the filenames are keys and the values are md5 hashes as strings server_hashes- a dictionary where the filenames are keys and the values are md5 hashes as strings Return values: a list of 2 lists -> [to_dload, to_delete] to_dload- a list of filenames to get from the server to_delete- a list of filenames to delete from the folder Note: we will get a file from the server if a) it is not on the client or b) the md5 differs between the client and server Note: we will mark a file for deletion if it is not available on the server """ to_dload, to_delete = [], [] for filename in server_hashes: if filename not in client_hashes: to_dload.append(filename) continue if client_hashes[filename] != server_hashes[filename]: to_dload.append(filename) for filename in client_hashes: if filename not in server_hashes: to_delete.append(filename) return [to_dload, to_delete]
def _concat(*lists): """Concatenates the items in `lists`, ignoring `None` arguments.""" concatenated = [] for list in lists: if list: concatenated += list return concatenated
def read_paragraph_element(element): """Returns the text in the given ParagraphElement. Args: element: a ParagraphElement from a Google Doc. """ text_run = element.get('textRun') if not text_run: return '' if text_run.get('textStyle', {}).get('weightedFontFamily', {}).get('fontFamily','') == 'Consolas': return text_run.get('content') else: return ''
def isBoxed(binary): """Determines if a bit array contains the marker border box.""" for bit in binary[0]: if bit != 0: return False for bit in binary[7]: if bit != 0: return False c = 1 while c < 7: if binary[c][0] != 0 or binary[c][7] != 0: return False c += 1 return True
def num_same_chars(w1: str, w2: str)->int: """Compute the similarity of two strings based on the number of matching characters""" sim = 0 for ch in w1: if ch in w2: sim += 1 return sim
def removeDocstringAndImports(src): """ Remove the docstring and import statements from the given code. We return the source code, minus the initial docstring (if any) and any import statements. """ if src.startswith('"""'): # We have a docstring. Search for the ending docstring, and pull the # remaining source code out. i = src.find('"""', 3) if i == -1: src = "" else: src = src[i+3:].lstrip() dst = [] for line in src.split("\n"): if not line.startswith("import") and not line.startswith("from"): dst.append(line) return "\n".join(dst)
def get_status(node): """ Builds a dict of status from a workflow manifest. Parameters ---------- node : dict Returns ------- str """ # check if pipeline was interrupted if "message" in node and str(node["message"]) == "terminated": status = "Terminated" else: status = str(node["phase"]) return status
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations" f"/api/v1.0/tobs <br>" f"/api/v1.0/start_date <br> " f"/api/v1.0/end_date <br> " )
def get_new_filename(artist: str, title: str) -> str: """ Get new filename for the track. Remove all symbols, replace spaces with underscores :param artist: :param title: :return: """ tmp_data = [] for data in [artist, title]: tmp_data.append(''.join([i.lower() if i != ' ' else '_' for i in data if i.isalnum() or i == ' '])) return '{0}-{1}.mp3'.format(*tmp_data)
def solar_panels(area): """ Given area, this function outputs a list containing the largest perfect squares that can be extracted from what remains from area. Example: If area = 12, then 9 is the largest square, and 3 remains from where 1 is the largest perfect square, and 2 remains, from where 1 is again the largest square, and 1 remains, from which finally 1 is again the largest square. Therefore, the out put would be the list [9,1,1,1] """ # For this one one only needs to compute square root, subtract # and repeat. I don't think the challenge's testcases had very large inputs # but if they did, or if one wants it to work for very large inputs, # then one should avoid the temptation of using floating point # square roots. Instead compute integer square root # (https://en.wikipedia.org/wiki/Integer_square_root) def isqrt_Newton(n): """ Integer square root using Newton's method """ x0 = n x1 = (n+1)//2 while not x1 == x0 and not x1 == x0+1: x1, x0 = (x1 + n//x1)//2, x1 return x0 def isqrt_bitwise(n): """ Computes the integer square root of n using bitwise operations. """ if n < 0: raise shift = 2 nShifted = n >> shift while not nShifted == 0 and not nShifted == n: shift += 2 nShifted = n >> shift shift -= 2 result = 0 while shift >= 0: result = result << 1 candidateResult = result + 1 if candidateResult * candidateResult <= (n >> shift): result = candidateResult shift -= 2 return result # The actual computation result = [] while area > 0: # Compute the square of the integer square root. square = int(isqrt_bitwise(area))**2 # Add to the list the square as many times as it divides the # total area, and repeat result += (area // square) * [square] area %=square return result
def convertToStepUpCDF(x, y): """Convert to a "stepped" data format by duplicating all but the last elt. Step goes up, rather than to the right. """ newx = [] newy = [] for i, d in enumerate(x): newx.append(d) newy.append(y[i]) if i != len(x) - 1: newx.append(x[i]) newy.append(y[i + 1]) newx.append(newx[-1]) newy.append(1.0) return newx, newy
def validate_users_input(users_input, word): """ Function validate_users_input - validate the user's input --------------------------------------------------------- Author : Arthur Molia - <moliaarthu@eisti.eu> Parameters : users_input : user's input word : game's solution Misc : Remarks... --------------------------------------------------------- """ autorised_characters = "AZERTYUIOPQSDFGHJKLMWXCVBN" + word valid_input = True for i in range(len(users_input)): valid_input = valid_input and (users_input[i] in autorised_characters) return valid_input and (len(users_input) == len(word))
def detectFormat(fileName): """Get the extension of a file""" ext = fileName.split(".")[1] return ext
def minimum_format_ensurer(products): """ This is a function to ensure that there is at least 2 digits to each input. It adds a leading or an ending zero to each single-digit entry, all values will be turned to str or tuples containing str to maintain the format. Any item not of int or float will be skipped. str.zfill() is a good alternative, but not so much for decimals. Parameters ------- h: dict this is the dict of each product. k: str This is the key of each dict entry. i: str/int/float This is the value of each entry, which does not stay standard. Returns ------- : list """ for h in products: for k, i in h.items(): if k == 'pQua': continue; if type(i) is int and len(str(i)) == 1: #print('is int !') i = '0' + str(i) elif type(i) is float: #print('is float !') AED = str(i).split('.')[0] FIL = str(i).split('.')[-1] if len(AED) == 1: AED = '0' + AED if len(FIL) == 1: FIL = FIL + '0' i = (AED, FIL) #print(AED, FIL) else: #print('is undesirable !') continue h[k] = i; return products
def rgb_to_hex(red: int, green: int, blue: int) -> str: """Converts RGB into hext string. Examples: >>> assert rgb_to_hex(1, 2, 3) == "010203" """ def to_hex(number: int) -> str: if number > 255: return "FF" if number < 0: return "00" return f"{number:X}".zfill(2) return f"{to_hex(red)}{to_hex(green)}{to_hex(blue)}"
def t_any(cls): """ Verifies if input is of same class """ class AnyClass(cls): def __eq__(self, other): return True return AnyClass()
def _get_item_properties(item, fields): """Return a tuple containing the item properties.""" row = [] for field in fields: row.append(item.get(field, '')) return tuple(row)
def time_to_iso(time_struct): """ time to iso format """ #return '%(hour)s:%(minute)s' % time_struct hour = int(time_struct['hour']) if not hour: hour = '00' return '%s:%s' % (hour, time_struct['minute'])
def parse_non_lang_item_with_subkey(key: str, item: dict): """ Given a single item, in a list of XML values, which does not contain a language key, but does contain a hidden "sub label" e.g. {'$': 'geoscanid:123456'} create the key:value mapping for the associated column, adding the subkey to the column name e.g. key_geoscanid:123456 :param key: the XML key associated with the list that this item came from :param item: the list item :returns: k, v - the key with which this item should be associated and the item's value """ k, v = item['$'].split(':') if k not in ['geoscanid', 'info']: raise ValueError() k = f'{key}_{k}' return k, v
def enable_checking(flag = True): """Convenience function to set the checking_enabled flag. Intended for use in an assert statement, so the call depends on -o flag. """ global checking_enabled checking_enabled = flag return checking_enabled
def _count(n, word): """format word according to n""" if n == 1: return "%d %s" % (n, word) else: return "%d %ss" % (n, word)
def lorenz(num_points=15000, start=[0.10, 0.10, 0.10], scaling_factor=20, delta=0.008, a=0.1, b=4.0, c=14.0, d=0.08): """ Generates Lorenz strange attractor. """ verts = [] x = start[0] y = start[1] z = start[2] for i in range(0, num_points): # calculate delta values dx = -a * x + (y * y) - (z * z) + a * c dy = x * (y - b * z) + d dz = z + x * (b * y + z) # calculate new coordinates x = x + delta * dx y = y + delta * dy z = z + delta * dz # scale and add them to the list verts.extend([ x * scaling_factor, z * scaling_factor, y * scaling_factor ]) return verts
def _format_links(link_x): """ Format links part :param link_x: list, which has several dicts in it :return: formatted string """ try: pairs = "" for _dict in link_x: pairs += _dict['rel'] + '-> ' + _dict['href'] + '\n' return pairs[:-1] except Exception: return link_x
def calculate_slpercentage_base_price_long(sl_price, base_price): """Calculate the SL percentage of the base price for a long deal""" return round( 100.0 - ((sl_price / base_price) * 100.0), 2 )
def calibrate_magnitude(instr_mag, airmass, ref_color, zero, extinct, color, instr=None): """ Calibrate instrumental magnitude to a standard photometric system. This assumes that ref_color has already been adjusted for any non-linearities between the instrumental magnitudes and the photometric system. Otherwise use `~calibrate_magnitude_full` """ if instr is None: result = instr_mag-extinct*airmass+zero+color*ref_color else: result = instr*(instr_mag-extinct*airmass)+zero+color*ref_color return result
def u2u3(u2): """ inch to feet&inch, all strings u3 is a tuple of (feet, inch) """ u2 = float(u2) f = u2//12 i = u2%12 inch_int = int(i//1) inch_frac = i%1 # 1/4" accuracy test = round(inch_frac/0.25) if test == 0: i = str(inch_int) elif test == 4: i = str(inch_int+1) elif test == 2: i = str(inch_int) + " 1/2" else: i = str(inch_int) + " " + str(test) + "/4" return (str(int(f)), i)
def is_boolean(value): """ Checks if `value` is a boolean value. Args: value (mixed): Value to check. Returns: bool: Whether `value` is a boolean. Example: >>> is_boolean(True) True >>> is_boolean(False) True >>> is_boolean(0) False .. versionadded:: 1.0.0 .. versionchanged:: 3.0.0 Added ``is_bool`` as alias. .. versionchanged:: 4.0.0 Removed alias ``is_bool``. """ return isinstance(value, bool)
def __stretch__(p,s1,f1): """ If a point has coordinate p when the steep/flat points are at s0/f0, this returns its coordinates when the steep/flat points are at s1/f1. This is necessary to preserve the colourmap features. """ s0 = 0.3125 f0 = 0.75 dsf = f0 - s0 if p <= s0: return p*s1/s0 elif p <= f0: return ( (p-s0)*f1 + (f0-p)*s1 )/dsf else: return ( (p-f0) + (1.-p)*f1 )/(1-f0)
def drop_key_safely(dictionary, key): """Drop a key from a dict if it exists and return that change""" if key in dictionary: del dictionary[key] return dictionary
def search_linearf(a, x): """ Returns the index of x in a if present, None elsewhere. """ for i in range(len(a)): if a[i] == x: return i return None
def enterprise_format_numbers( unparsed_int # type: int ): """Unpack and parse [enterprise,format] numbers""" sample_type_binary = '{0:032b}'.format(unparsed_int) # Break out the binary enterprise_num = int(sample_type_binary[:20],2) # Enterprise number first 20 bits sample_data_format = int(sample_type_binary[20:32],2) # Format number last 12 bits return [enterprise_num,sample_data_format]
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ value = value.strip(separator) if not max_length: return value if len(value) < max_length: return value if not word_boundaries: return value[:max_length].strip(separator) if separator not in value: return value[:max_length] truncated = '' for word in value.split(separator): if word: next_len = len(truncated) + len(word) + len(separator) if next_len <= max_length: truncated += '{0}{1}'.format(word, separator) if not truncated: truncated = value[:max_length] return truncated.strip(separator)
def remove_first1(alist,k): """Removes the first occurrence of k from alist. It is not efficient; even it removes one occurrence, it goes on processing the input.""" retval = [] removed = False for x in alist: if x == k and not removed: removed = True else: retval.append(x) return retval
def cross(a: complex, b: complex) -> complex: """2D cross product (a.k.a. wedge product) of two vectors. Args: a (complex): First vector. b (complex): Second vector. Returns: complex: 2D cross product: a.x * b.y - a.y * b.x """ return (a.conjugate() * b).imag
def is_change_applicable_for_power_state(current_power_state, apply_power_state): """ checks if changes are applicable or not for current system state :param current_power_state: Current power state :type current_power_state: str :param apply_power_state: Required power state :type apply_power_state: str :return: boolean True if changes is applicable """ on_states = ["On", "PoweringOn"] off_states = ["Off", "PoweringOff"] reset_map_apply = { ("On", "ForceOn",): off_states, ("PushPowerButton",): on_states + off_states, ("ForceOff", "ForceRestart", "GracefulRestart", "GracefulShutdown", "Nmi", "PowerCycle",): on_states } is_reset_applicable = False for apply_states, applicable_states in reset_map_apply.items(): if apply_power_state in apply_states: if current_power_state in applicable_states: is_reset_applicable = True break break return is_reset_applicable
def list_startswith(_list, lstart): """ Check if a list (_list) starts with all the items from another list (lstart) :param _list: list :param lstart: list :return: bool, True if _list starts with all the items of lstart. """ if _list is None: return False lenlist = len(_list) lenstart = len(lstart) if lenlist >= lenstart: # if _list longer or as long as lstart, check 1st items: return (_list[:lenstart] == lstart) else: # _list smaller than lstart: always false return False
def assign_labels(sentences): """ Assigns the majority class label to each sentence for each task. Returns two lists: predicted AC and predicted SP """ predictions_category = [] predictions_sentiment = [] for sentence in sentences: prediction_cat = 'NA' predictions_category.append(prediction_cat) prediction_sent = 'Neutral' predictions_sentiment.append(prediction_sent) return predictions_category, predictions_sentiment
def _is_line_empty(line: str) -> bool: """Return true if the given string is empty or only whitespace""" return len(line.strip()) == 0
def parse_assigned_variable_name(stack_frames, constructor_name): """Analyses the provided stack frames and parses Python assignment expressions like some.namespace.variable_name = some.module.name.`constructor_name`(...) from the caller's call site and returns the name of the variable being assigned as a string. If the assignment expression is not found, returns None. """ if isinstance(stack_frames, list) and len(stack_frames) > 1: parent_stack_frame = stack_frames[1] if isinstance(parent_stack_frame, tuple) and len(parent_stack_frame) == 6: (_, _, _, _, source_lines, _) = parent_stack_frame if isinstance(source_lines, list) and source_lines: source_line = source_lines[0] if source_line: import re assignment_regexp = r"(?:\w+\.)*(\w+)\s*=\s*(?:\w+\.)*" + re.escape(constructor_name) + r"\(.*\)" match = re.match(assignment_regexp, source_line) if match: return match.group(1)
def _process_line(group, flag, value, is_fixed, dict_): """ This function processes most parts of the initialization file. """ # This aligns the label from the initialization file with the label # inside the RESPY logic. if flag == 'coeff': flag = 'coeffs' # Prepare container for information about coefficients if ('coeffs' not in dict_[group].keys()) and (flag in ['coeffs']): dict_[group]['coeffs'] = [] dict_[group]['fixed'] = [] # Collect information if flag in ['coeffs']: dict_[group]['coeffs'] += [value] dict_[group]['fixed'] += [is_fixed] else: dict_[group][flag] = value # Finishing. return dict_
def CLng(num): """Return the closest long of a value""" return int(round(float(num)))
def partition(arr, left, right, pivot_index): """ Partition the array into three groups: less that pivot, equal to it and more than pivot Args: input_list(list): Input List left(int): start index right(int): end index pivot_index(int): index of the pivot element Returns: (int),(int): left and right index - boundary of the pivot element on the right place when array is sorted. All elements to the left index are smaller than the pivot, all element to the right inidex are bigger. All elements between left and right (including them) are equla to the pivot. """ pivot = arr[pivot_index] store_index = left # move pivot to the end arr[right], arr[pivot_index] = arr[pivot_index], arr[right] # move all elements smaller than or equal to pivot to the left for i in range(left, right): if arr[i] <= pivot: arr[store_index], arr[i] = arr[i], arr[store_index] store_index += 1 # move the pivot to its final position arr[right], arr[store_index] = arr[store_index], arr[right] # find left boundary in case of pivot duplicates pivot_left_index = store_index while pivot_left_index >= 0 and arr[pivot_left_index] == pivot: pivot_left_index -= 1 return (pivot_left_index + 1, store_index)
def rshift(val, n): """ Python equivalent to TypeScripts >>> operator. @see https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python """ return (val % 0x100000000) >> n
def summarise_app(app): """Return a string the summarises the important information about the app""" state = app["state"] if state != "Installed": state = state.upper() pin_status = "Pinned" if app["is_pinned"] else "NOT PINNED" known_status = "UNKNOWN" if app["application_version"]["is_unknown"] else "Known" return f"{state}, {pin_status}, {known_status}"
def search_trie(trie, token, token_i=0): """ Search the given character-trie for paths that match the `token` string. """ if "*" in trie: return trie["*"] if "$" in trie and token_i == len(token): return trie["$"] if token_i < len(token): char = token[token_i] if char in trie: return search_trie(trie[char], token, token_i + 1) return []
def find_min_recursive(array, left, right): """ Find the minimum in rotated array in O(log n) time. >>> find_min_recursive([1,2,3,4,5,6], 0, 5) 1 >>> find_min_recursive([6, 5, 4, 3, 2, 1], 0, 5) 1 >>> find_min_recursive([6, 5, 1, 4, 3, 2], 0, 5) 1 """ if array[left] <= array[right]: return array[left] mid = left + (right - left) // 2 if array[mid] < array[right]: return find_min_recursive(array, left, mid) else: return find_min_recursive(array, mid + 1, right)