content
stringlengths
42
6.51k
def roundToNearest(value, roundValue=1000): """ Return the value, rounded to nearest roundValue (defaults to 1000). Args: value (float): Value to be rounded. roundValue (float): Number to which the value should be rounded. Returns: float: Rounded value. """ if roundValue < 1: ds = str(roundValue) nd = len(ds) - (ds.find('.')+1) value = value * 10**nd roundValue = roundValue * 10**nd value = int(round(float(value)/roundValue)*roundValue) value = float(value) / 10**nd else: value = int(round(float(value)/roundValue)*roundValue) return value
def format_network_speed(raw_bps=0): """ Formats a network speed test to human readable format """ fmt = ['b/s', 'Kb/s', 'Mb/s', 'Gb/s'] index = 0 speed = raw_bps while speed > 1024: index += 1 speed /= 1024 return "%0.2f %s" % (speed, fmt[index])
def dict_adapter(values, names): """Adapter returns name-values dict instead of pure tuple from iteration scheme. """ return dict(zip(names, values))
def get_unique_item(lst): """ For a list, return a set of the unique items in the list. """ return list(set(lst))
def string_to_list(s: str) -> list: """ :param str s: A serialized list. :return list: The actual list. """ return s.split(', ')
def no_similar_images(similar_image): """return bool""" return similar_image["target path"] == ""
def pluralize_pl(value, arg=u's'): """ pluralize_pl is fully compatible with Django's "pluralize" filter. Works exactly the same as long as you are giving it up to 2 comma-separated arguments. The difference is you can provide it with a third argument, which will be used as a second plural form and applied according to Polish grammar rules: * If value is 0, {{ value|pluralize:"komentarz,komentarzy,komentarze" }} displays "0 komentarzy". * If value is 1, {{ value|pluralize:"komentarz,komentarzy,komentarze" }} displays "1 komentarz". * If value is 2, {{ value|pluralize:"komentarz,komentarzy,komentarze" }} displays "2 komentarze". * If value is 5, {{ value|pluralize:"komentarz,komentarzy,komentarze" }} displays "5 komentarzy". It also can be used with i18n: (the following examples assume "spam,spams" is translated into Polish in language files as "mielonka,mielonek,mielonki") * If value is 1 and current language is English, {{ value|pluralize:_("dog,dogs") }} displays "1 spam". * If value is 4 and current language is English, {{ value|pluralize:_("dog,dogs") }} displays "4 spams". * If value is 5 and current language is English, {{ value|pluralize:_("dog,dogs") }} displays "5 spams". * If value is 1 and current language is Polish, {{ value|pluralize:_("dog,dogs") }} displays "1 mielonka". * If value is 4 and current language is Polish, {{ value|pluralize:_("dog,dogs") }} displays "4 mielonki". * If value is 5 and current language is Polish, {{ value|pluralize:_("dog,dogs") }} displays "5 mielonek". """ if not u',' in arg: arg = u',' + arg bits = arg.split(u',') if len(bits) > 3: return u'' elif len(bits) == 2: bits.append(bits[1]) # If there is no second plural form given use the same for both. singular_suffix, plural_suffix, plural_suffix2 = bits[:3] try: n = int(value) except ValueError: # Invalid string that's not a number. Assume 1. n = 1 except TypeError: # Value isn't a string or a number; maybe it's a list? try: n = len(value) except TypeError: # len() of unsized object. Assume 1. n = 1 if n == 1 or n == -1: return singular_suffix elif str(n)[-1:] in ['2','3','4'] and str(n)[-2:-1] != '1': return plural_suffix2 else: return plural_suffix
def find_scan_node(scan_node): """ utility function to find the parent node of "scan" type, meaning some of its children (DAQ_scan case) or co-nodes (daq_logger case) are navigation axes Parameters ---------- scan_node: (pytables node) data node from where this function look for its navigation axes if any Returns ------- node: the parent node of 'scan' type list: the data nodes of type 'navigation_axis' corresponding to the initial data node """ try: while True: if scan_node.attrs['type'] == 'scan': break else: scan_node = scan_node.parent_node children = list(scan_node.children().values()) # for data saved using daq_scan children.extend([scan_node.parent_node.children()[child] for child in scan_node.parent_node.children_name()]) # for data saved using the daq_logger nav_children = [] for child in children: if 'type' in child.attrs.attrs_name: if child.attrs['type'] == 'navigation_axis': nav_children.append(child) return scan_node, nav_children except Exception: return None, []
def _check_coordinate_precision(coord, precision): """Coordinate precision is <= specified number of digits""" if '.' not in coord: return True else: return len(coord.split('.')[-1]) <= precision
def calculate_velocity(mom1,mom2,mom3,dens): """Calculates the 3-vector velocity from 3-vector momentum density and scalar density.""" v1 = mom1/dens v2 = mom2/dens v3 = mom3/dens return v1,v2,v3
def make_field(name: str, value: str) -> str: """ Return an ADIF field/value, like "<adif_ver:5>value" """ return f"<{name}:{len(value)}>{value}"
def get_links_for_pages(link): """ retrieve pagnation link for the category """ # 5 pages for each category return [link + '?page=' + str(i) for i in range(1, 6)]
def daybounds( season ): """Input is a 3-character season, e.g. JAN, JJA, ANN. Output is bounds for that season in units of "days since 0". In most cases the bounds will be like [[lo,hi]]. But for DJF it will be like [[lo1,hi1],[lo2,hi2]]. The noleap (365 day) calendar is required.""" # This is an incredibly crude way to do it, but works for now. # If permanent, I would make these dictionaries global for performance. dbddic = { 'JAN': [[0,31]], 'FEB': [[31,59]], 'MAR': [[59,90]], 'APR': [[90,120]], 'MAY': [[120,151]], 'JUN': [[151,181]], 'JUL': [[181,212]], 'AUG': [[212,243]], 'SEP': [[243,273]], 'OCT': [[273,304]], 'NOV': [[304,334]], 'DEC': [[334,365]] } sesdic = { 'MAM': [[ dbddic['MAR'][0][0], dbddic['MAY'][0][1] ]], 'JJA': [[ dbddic['JUN'][0][0], dbddic['AUG'][0][1] ]], 'SON': [[ dbddic['SEP'][0][0], dbddic['NOV'][0][1] ]], 'DJF': [ dbddic['DEC'][0], [dbddic['JAN'][0][0], dbddic['FEB'][0][1]] ], 'ANN': [[ dbddic['JAN'][0][0], dbddic['DEC'][0][1] ]] } dbddic.update( sesdic ) return dbddic[season]
def compare_dict(dict1, dict2): """Compare two dictionaries. This function checks that two objects that contain similar keys have the same value """ dict1_keys = set(dict1) dict2_keys = set(dict2) intersect = dict1_keys.intersection(dict2_keys) if not intersect: return False for key in intersect: if dict1[key] != dict2[key]: return False return True
def tokenize_char(sent): """ Return the character tokens of a sentence including punctuation. """ return list(sent.lower())
def filter_git_files(files): """Remove any git/datalad files from a list of files.""" return [f for f in files if not (f.startswith('.datalad/') or f == '.gitattributes')]
def approx2step(val, x0, dx): """Approximate value, val, to closest increment/step, dx, starting from x0.""" while True: if x0 > val: break x0 += dx return x0
def formalize_table_neural_experiments(name, d): """ Takes the data from find_best_f1 and parses it, and returns an array with name + performance. """ if (d is None): return [name, 0, 0, 0, 0] best_f1, best_acc, best_prc, best_rc = d["f1"], d["acc"], d["precision"], d['recall'] best_f1, best_acc, best_prc, best_rc = ["{:.2f}".format(float(inst)) for inst in [best_f1, best_acc, best_prc, best_rc]] return [name, best_f1, best_acc, best_prc, best_rc]
def compress_dna(text: str) -> int: """Compress a DNA string into a bit string Arguments: text {str} -- DNA string to compress Returns: int -- integer bit-string representing DNA Example: >>> compress_dna("ACGT") 283 """ bit_string = 1 for nt in text.upper(): bit_string <<= 2 if nt == "A": bit_string |= 0b00 elif nt == "C": bit_string |= 0b01 elif nt == "G": bit_string |= 0b10 elif nt == "T": bit_string |= 0b11 else: raise ValueError(f'Invalid nucleotide: {nt}') return bit_string
def union(interval1, interval2): """ Given [0, 4] and [1, 10] returns [0, 10] Given [0, 4] and [8, 10] returns False """ if interval1[0] <= interval2[0] <= interval1[1]: start = interval1[0] end = interval1[1] if interval2[1] <= interval1[1] else interval2[1] elif interval1[0] <= interval2[1] <= interval1[1]: start = interval2[0] if interval2[0] <= interval1[0] else interval1[0] end = interval1[1] else: return False return (start, end)
def find_even_index(arr): """Return the index where sum of both sides are equal.""" if len(arr) == 0: return 0 for i in range(0, len(arr)): sum1 = 0 sum2 = 0 for j in range(0, i): sum1 += arr[j] for k in range(i + 1, len(arr)): sum2 += arr[k] if sum1 == sum2: return i return -1
def map_wrapper(x): """For multi-threading""" return x[0](*(x[1:]))
def sum_attributes(triplet): """ return the sum of the attributes of a triplet ie: triplet = (((2, 2, 2, 2), (3, 3, 3, 3), (1, 2, 3, 1))) returns [6, 7, 8, 6] <- [2+3+1, 2+3+2, 2+3+3, 2+3+1] """ return [sum(a) for a in zip(*triplet)]
def genomic_del1_rel_37(genomic_del1_37_loc): """Create test fixture relative copy number variation""" return { "type": "RelativeCopyNumber", "_id": "ga4gh:VRC.2_BewkjhJtvj8J814SE0RVxp-OdYxJSo", "subject": genomic_del1_37_loc, "relative_copy_class": "copy neutral" }
def map(func, data, processes=4): """ This maps the data to func in parallel using multiple processes. This works fine in the IPython terminal, but not in IPython notebook. **Arguments**: *func*: Function to map the data with. *data*: Data sent to func. **Returns**: Returns whatever func returns. """ from multiprocessing import Pool pool = Pool(processes=processes) output = pool.map(func, data) pool.close() pool.join() return output
def select_to_text_compact(caption, choices): """ A function to convert a select item to text in a compact format. Format is: [question] 1:[choice1], 2:[choice2]... """ return "%s %s." % (caption, ", ".join(["%s:%s" % (i+1, val) for i, val in \ enumerate(choices)]))
def kwargs_to_string(kwargs): """ Given a set of kwargs, turns them into a string which can then be passed to a command. :param kwargs: kwargs from a function call. :return: outstr: A string, which is '' if no kwargs were given, and the kwargs in string format otherwise. """ outstr = '' for arg in kwargs: outstr += ' {}={}'.format(arg, kwargs[arg]) return outstr
def strip(value): """ Strip all leading and trailing whitespaces. :param value: The value :type value: str :return: The value with all leading and trailing whitespaces removed :rtype: str """ return value.strip()
def get_stream_fps(streams): """ accepts a list of plex streams or a list of the plex api streams """ for stream in streams: # video stream_type = getattr(stream, "type", getattr(stream, "stream_type", None)) if stream_type == 1: return getattr(stream, "frameRate", getattr(stream, "frame_rate", "25.000")) return "25.000"
def append_bias(vector): """ Takes a list of n entries and appends a 1 for the bias Args: vector - a list Returns: a list """ temp_vector = [x for x in vector] temp_vector.append(1) return temp_vector
def repeat_list_elements(a_list, rep): """ Creates a list where each element is repeated rep times. """ return [element for _ in range(rep) for element in a_list]
def calc_section_data(size, num_parts): """ Calculates info about each part of a file of given size separated into given number of parts. Returns a list of dicts having 3 pieces of information: - 'start' offset inclusive - 'end' offset inclusive - 'size' """ # Changing this vital function could # completely break functionality. # # "Jar Jar is the key to all of this." if not size: return [{'start': 0, 'end': 0, 'size': 0}] elif not num_parts: num_parts = 1 elif num_parts > size: num_parts = size section_size = size // num_parts remainder = size % num_parts section_data = [] start = 0 for _ in range(num_parts): end = start + section_size if remainder != 0: end += 1 remainder -= 1 section_data.append({'start': start, 'end': end - 1, 'size': end - start}) start = end return section_data
def getTimeZone(lat, lon): """Get timezone for a given lat/lon """ #Need to fix for Python 2.x and 3.X support import urllib.request, urllib.error, urllib.parse import xml.etree.ElementTree as ET #http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query.xml?points=37.78%2C-122.42%3B40.71%2C-74.01&databases=Point%2CTimeZone%2CAstronomy%2CNaturalEarthCountry%2CUsState2010%2CUsCounty2010%2CUsCountySubdivision2010%2CUsTract2010%2CUsBlockGroup2010%2CUsPlace2010%2CUsZcta2010 req = "http://api.askgeo.com/v1/918/aa8292ec06199d1207ccc15be3180213c984832707f0cbf3d3859db279b4b324/query.xml?points="+str(lat)+"%2C"+str(lon)+"&databases=TimeZone" opener = urllib.request.build_opener() f = opener.open(req) tree = ET.parse(f) root = tree.getroot() #Check response tzid = None if root.attrib['code'] == '0': tz = list(root.iter('TimeZone'))[0] #shortname = tz.attrib['ShortName'] tzid = tz.attrib['TimeZoneId'] return tzid
def _remove_pronominal(verb): """ Remove the pronominal prefix in a verb """ if verb.split()[0] == 'se': infinitive = verb.split()[1] elif verb.split("'")[0] == "s": infinitive = verb.split("'")[1] else: infinitive = verb return infinitive
def x_in_y(query, base): """Checks if query is a subsequence of base""" try: l = len(query) except TypeError: l = 1 query = type(base)((query,)) for i in range(len(base)): if base[i:i+l] == query: return True return False
def read_file_to_list(filename): """Returns a list of (stripped) lines for a given filename.""" with open(filename) as f: return [line.rstrip('\n') for line in f]
def _flatten_nested_keys(dictionary): """ Flatten the nested values of a dictionary into tuple keys E.g. {"a": {"b": [1], "c": [2]}} becomes {("a", "b"): [1], ("a", "c"): [2]} """ # Find the parameters that are nested dictionaries nested_keys = {k for k, v in dictionary.items() if type(v) is dict} # Flatten them into tuples flattened_nested_keys = {(nk, k): dictionary[nk][k] for nk in nested_keys for k in dictionary[nk]} # Get original dictionary without the nested keys dictionary_without_nested_keys = {k: v for k, v in dictionary.items() if k not in nested_keys} # Return merged dicts return {**dictionary_without_nested_keys, **flattened_nested_keys}
def indent(indent): """Indentation. @param indent Level of indentation. @return String. """ return " "*indent
def union(value: list, other: list) -> list: """Union of two lists. .. code-block:: yaml - vars: new_list: "{{ [2, 4, 6, 8, 12] | union([3, 6, 9, 12, 15]) }}" # -> [2, 3, 4, 6, 8, 9, 12, 15] .. versionadded:: 1.1 """ return list(set(value).union(other))
def SurrRateMult(t): """Surrender rate multiple (Default: 1)""" if t == 0: return 1 else: return SurrRateMult(t-1)
def trim_item(item): """Trims unnecessary fields in the track item""" track = item['track'] if 'album' in track: to_delete = ['album_type', 'available_markets', 'external_urls', 'href', 'images', 'uri'] for key in to_delete: try: del track['album'][key] except KeyError: pass to_delete = ['available_markets', 'external_ids', 'external_urls', 'href', 'is_local', 'preview_url', 'uri'] for key in to_delete: try: del track[key] except KeyError: pass return item
def str2num(size, s): """Convert a string of decimal digits to an integer.""" i = 0 n = 0 while i < size: n = n | (ord(s[i]) << (i*8)) i = i + 1 return n
def generic_response(status_code, success, message, data=None): """ This function handles all the requests going through the backend :rtype: object """ response = { "success": success, "message": message, "data": data } return response, status_code
def inst_attributes(obj,of_class=None): """ Find all instance attributes of obj that are instances of of_class and return them as dictionary. """ d = {} if of_class: for k,v in obj.__dict__.items(): if isinstance(v,of_class): d[k] = v else: d.update(obj.__dict__) return d
def cal_trans(ref, adj): """ calculate transfer function algorithm refering to wiki item: Histogram matching """ table = list(range(0, 256)) for i in list(range(1, 256)): for j in list(range(1, 256)): if ref[i] >= adj[j - 1] and ref[i] <= adj[j]: table[i] = j break table[255] = 255 return table
def _pop(inlist): """ make a list of lists into a list """ if isinstance(inlist, (list, tuple)): return inlist[0] return inlist
def move_right_row(row, debug=True): """move single row to right.""" if debug: print(row) row_del_0 = [] for i in row: # copy non-zero blocks if i != 0: row_del_0.append(i) #print(row_del_0) row = row_del_0 i = 0 j = len(row_del_0) - 1 while i < j: # combine blocks #print(i, j) if row[j] == row[j-1]: row[j-1] *= 2 del row[j] j -= 2 else: j -= 1 #print(i, j) #print(row_del_0) for i in range(4 - len(row_del_0)): # insert zeros row_del_0.insert(0,0) if debug: print(row) return row
def _instance_overrides_method(base, instance, method_name): """ Returns True if instance overrides a method (method_name) inherited from base. """ bound_method = getattr(instance.__class__, method_name) unbound_method = getattr(base, method_name) return unbound_method != bound_method
def linear_search(array, val): """Linear search.""" length = len(array) for i in range(length): if array[i] == val: return i return None
def resample_factor_str(sig_sample_rate_hz: float, wav_sample_rate_hz: float) -> str: """ Compute file string for oversample and downsample options :param sig_sample_rate_hz: input signal sample rate :param wav_sample_rate_hz: wav sample rate; supports permitted_wav_fs_values :return: string with resample factor """ resample_factor = wav_sample_rate_hz / sig_sample_rate_hz # If resample factor is unity, no change resample_str = '_preserve' if resample_factor > 1: resample_str = '_upsample_' + str(int(10.*resample_factor)/10) + 'x_to' elif 1 > resample_factor > 0: resample_str = '_decimate_' + str(int(10./resample_factor)/10) + 'x_to' elif resample_factor < 0: print("Resample factor is negative: address") return resample_str
def get_intermixed_trials(trials, n, n_user_suggestions): """Filters the exploration trials for intermixed ensemble search.""" return [ trial for trial in trials if trial.id % n != 0 or trial.id <= n_user_suggestions ]
def get_spacing_dimensions(widget_list): """ will be further developed """ space_dimensions = space_label = 0 for widg in widget_list: space_d = widg.get('dimensions', '') space_l = widg.get('label', '') if space_d: space_d_new = len(list(space_d)) if space_d_new > space_dimensions: space_dimensions = space_d_new # if space_l: if space_dimensions == 0: size_unit = {'size_unit': 'null'} elif 0 < space_dimensions <= 2: size_unit = {'size_unit': 's'} elif 2 < space_dimensions <= 6: size_unit = {'size_unit': 'm'} else: size_unit = {'size_unit': 'l'} return size_unit
def parse_trans_table(trans_table): """returns a dict with the taxa names indexed by number""" result = {} for line in trans_table: line = line.strip() if line == ";": pass else: label, name = line.split(None, 1) # take comma out of name if it is there if name.endswith(","): name = name[0:-1] # remove single quotes if name.startswith("'") and name.endswith("'"): name = name[1:-1] result[label] = name return result
def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. >>> removeall(3, [1, 2, 3, 3, 2, 1, 3]) [1, 2, 2, 1] >>> removeall(4, [1, 2, 3]) [1, 2, 3] """ if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in seq if x != item]
def product(l): """Get the product of the items in an iterable.""" t = 1 for i in l: t *= int(i) return t
def prime_test(i, j=2): """ Cases: Return False if i is not prime Return True if i is prime Caveat: cannot test 1. Caveat 2: Cannot test 2. It is fortuitous that these tests both return true. """ if j >= i: # i used greater than to cover 1 return True if i % j == 0: # this chokes on 1 % 2 return False return prime_test(i, j+1)
def camel_case_to_upper(name): """ :Examples: >>> camel_case_to_upper('squareRoot') 'SQUARE_ROOT' >>> camel_case_to_upper('SquareRoot') 'SQUARE_ROOT' >>> camel_case_to_upper('ComputeSQRT') 'COMPUTE_SQRT' >>> camel_case_to_upper('SQRTCompute') 'SQRT_COMPUTE' >>> camel_case_to_upper('Char_U') """ lowername = '_' index = 0 while index < len(name): if name[index].islower(): lowername += name[index].upper() index += 1 else: if not name[index] == '_': if not lowername[-1] == '_': lowername += '_' lowername += name[index].upper() index += 1 if index < len(name) and not name[index].islower(): while index < len(name) and not name[index].islower(): lowername += name[index] index += 1 if index < len(name): lowername = lowername[:-1] + '_' + lowername[-1] else: if not lowername[-1] == '_': lowername += '_' index += 1 lowername = lowername.lstrip('_') return lowername
def solve(n, coins, k): """ Solution for count_change :param n: money :param coins: List of coins. :param k: coins[k] :return: Count of combinations. """ # print("n: %d, k: %d" % (n, k)) if k < 0 or n < 0: return 0 if n == 0: # Change for 0 is only empty one. return 1 # print(" n: %d, k: %d" % (n, k - 1)) # print(" n: %d, k: %d" % (n - coins[k], k))
def threshold_predictions(predictions, thr=0.999): """This method will threshold predictions. :param thr: the threshold (if None, no threshold will be applied). :return: thresholded predictions """ if thr is None: return predictions[:] thresholded_preds = predictions[:] low_values_indices = thresholded_preds <= thr thresholded_preds[low_values_indices] = 0 low_values_indices = thresholded_preds > thr thresholded_preds[low_values_indices] = 1 return thresholded_preds
def is_uniform(x, epsilon=0.000000001): """Determine if the vector is uniform within epsilon tolerance. Useful to stop a simulation if the fitness landscape has become essentially uniform.""" x_0 = x[0] for i in range(1, len(x)): if abs(x[i] - x_0) > epsilon: return False return True
def float2int_ensure_precision(value, scale): """Cast a float to an int with the given scale but ensure the best precision.""" # Round it to make sure we have the utmost precision return int(round(value * pow(10.0, scale)))
def setup(): """Sets paths and initializes modules, to be able to run the tests.""" res = True # # Make available to configure.py the top level dir. # scarlett_os_dir = get_scarlett_os_dir() # sys.path.insert(0, scarlett_os_dir) # # NOTE: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # SUPER IMPORTANT # CONFIGURE RELATES TO A SCRIPT THAT GENERATES Pitivi MAKEFILES ( Since they compile stuff as well ) # IT IS NOT THE BASIC CONFIGURATION FOR THE APPLICATION # IF YOU NEED THAT YOU SHOULD BE LOOKING AT settings.py # from scarlett_os import configure # # # Make available the compiled C code. # sys.path.append(configure.BUILDDIR) # subproject_paths = os.path.join(configure.BUILDDIR, "subprojects", "gst-transcoder") # # _prepend_env_paths(LD_LIBRARY_PATH=subproject_paths, # GST_PLUGIN_PATH=subproject_paths, # GI_TYPELIB_PATH=subproject_paths, # GST_PRESET_PATH=[os.path.join(scarlett_os_dir, "data", "videopresets"), # os.path.join(scarlett_os_dir, "data", "audiopresets")], # GST_ENCODING_TARGET_PATH=[os.path.join(scarlett_os_dir, "data", "encoding-profiles")]) # os.environ.setdefault('SCARLETT_OS_TOP_LEVEL_DIR', scarlett_os_dir) # # # Make sure the modules are initialized correctly. # from scarlett_os import check # check.initialize_modules() # res = check.check_requirements() # # from scarlett_os.utils import loggable as log # log.init('SCARLETT_OS_DEBUG') return res
def gnome_sort(a): """ Sorts the list 'a' using gnome sort >>> from pydsa import gnome_sort >>> a = [5, 6, 1, 9, 3] >>> gnome_sort(a) [1, 3, 5, 6, 9] """ i = 0 while i < len(a): if i != 0 and a[i] < a[i-1]: a[i], a[i-1] = a[i-1], a[i] i -= 1 else: i += 1 return a
def full_name_with_qualname(klass: type) -> str: """Returns the klass module name + klass qualname.""" return f"{klass.__module__}.{klass.__qualname__}"
def remove_root(field): """Replace txt.""" return field.replace("/media", "media").replace("<p>","").replace("</p>","")
def is_empty(s): """Is this an empty value? None or whitespace only counts as empty; anything else doesn't. @param s: value to test @return: True if the value is empty """ return (s is None or s == '' or str(s).isspace())
def transform_shape(shape): """ Transforms a shape to resize an image after that. Shape size must be equal to 2 or 3, otherwise it raises a ValueError. Returns: A tuple of the same size. Raises: A ValueError if the shape size is not equal to 2 or 3. Example: >>> shape = (4850, 650, 3) >>> new_shape = transform_shape(shape) >>> print(new_shape) (5000, 1000, 3) """ if len(shape) < 2 or len(shape) > 3: raise ValueError("ERROR: Shape size must be in [2;3]") # Create a tuple to store the new shape new_shape = tuple() for value in shape[:2]: # Convert this value to a string val = str(value) # Get the first two values and store the rest in another # variable sup, inf = val[:-3] if val[:-3] != '' else "1", val[-3:] if int(inf) > 500: sup = str(int(sup)+1) new_shape += (int(sup + "000"),) # Don't forget the last element (only if it exists) if len(shape) == 3: new_shape += (shape[2],) return new_shape
def jacobianDouble(Xp, Yp, Zp, A, P): """ Double a point in elliptic curves :param (Xp,Yp,Zp): Point you want to double :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if not Yp: return (0, 0, 0) ysq = (Yp ** 2) % P S = (4 * Xp * ysq) % P M = (3 * Xp ** 2 + A * Zp ** 4) % P nx = (M**2 - 2 * S) % P ny = (M * (S - nx) - 8 * ysq ** 2) % P nz = (2 * Yp * Zp) % P return nx, ny, nz
def get_customized_ini_name(env: str) -> str: """ get customized service config ini file name :return: """ return f'{env}.ini'
def split_long_lat(long_lat): """ Takes in a string that looks like "-02398470+09384779" in order to obtain the first value and the second value of the string. In this case, the longitude is -02398470 and the latitude is +09384779. This function is needed because the TIGER/Line files have the longitudes and latitudes in this format. Parameters ---------- long_lat : str has the format listed in the description of the function Returns ------- int, int the first int is the longitude of the point and the second is the latitude of the point """ long_x = "" lat_y = "" reached_center = False for i, c in enumerate(long_lat): if c.isdigit() == False and i != 0: reached_center = True if reached_center: lat_y += c else: long_x += c if reached_center: return int(long_x), int(lat_y) else: return None, None
def next_power_of_2(x): """ Returns the first power of two >= x, so f(2) = 2, f(127) = 128, f(65530) = 65536 :param x: :return: """ # NOTES for this black magic: # * .bit_length returns the number of bits necessary to represent self in binary # * x << y means 1 with the bits shifted to the left by y, which is the same as multiplying x by 2**y (but faster) return 1 << (x - 1).bit_length()
def notice(title, text, style="info"): """ A notice panel. :param title: Notice title :param text: Notice information :param style: Notice style (info, danger, success, default) """ return { "class": "notice", "title": title, "text": text, "style": style }
def sigref(nod1, nod2, tsys_nod2): """ Signal-Reference ('nod') calibration ; ((dcsig-dcref)/dcref) * dcref.tsys see GBTIDL's dosigref """ return (nod1-nod2)/nod2*tsys_nod2
def card(id, title, s): """Build a card by ID.""" return """<card id="%(id)s" title="%(title)s"><p>%(s)s</p></card>""" % \ {'id': id, 'title': title, 's': s}
def calc_nbar(n_0, n_curr): """ Calculate the n2o concentration average between the historical n2o and current n2o concentrations Parameters ---------- n_0 : float Historical n2o concentration, in ppm n_curr : float Current n2o concentration, in ppm Return ------ n_bar : float Averaged concentration, in W m^-2 ppb^-1 """ n_bar = 0.5 * (n_0 + n_curr) return n_bar
def remove_non_datastore_keys(form_data): """Remove keys not relevant to creating a datastore object.""" form_dict = {k: v[0] for k, v in form_data.items()} for key in ["csrfmiddlewaretoken", "name", "type", "owner"]: form_dict.pop(key, None) return form_dict
def series1_proc_func(indep_var, dep_var, xoffset): """Process data 1 series.""" return (indep_var * 1e-3) - xoffset, dep_var
def validate_placement(placement): """ Validate placement policy """ for item in placement: if item not in ['requirements', 'preferences']: return (False, 'invalid item "%s" in placement policy' % item) if 'requirements' in placement: for item in placement['requirements']: if item not in ['sites', 'regions']: return (False, 'invalid item "%s" in requirements' % item) if not isinstance(placement['requirements'][item], list): return (False, '%s in requirements must be a list' % item) if 'preferences' in placement: for item in placement['preferences']: if item not in ['sites', 'regions']: return (False, 'invalid item "%s" in preferences' % item) if not isinstance(placement['preferences'][item], list): return (False, '%s in preferences must be a list' % item) return (True, '')
def test_cab (archive, compression, cmd, verbosity, interactive): """Test a CAB archive.""" return [cmd, '-t', archive]
def try_convert_to_aggregation_function(token): """ This method tries to convert the given token to be an aggregation function name. Return None if failure. Args: token (str): the given token to be converted. Returns: Return the converted aggregation function name if the conversion succeeds. Otherwise, return None. """ AGGREGATION_FUNCTIONS = { 'SUM': 'sum', } return AGGREGATION_FUNCTIONS.get(token, None)
def _is_sunder(name: str) -> bool: """Return True if a _sunder_ name, False otherwise.""" return name[0] == name[-1] == "_" and name[1:2] != "_" and name[-2:-1] != "_" and len(name) > 2
def find_role_from_parents(team_roles, team_parents, team_id): """Searches for the first parent with defined role >>> find_role_from_parents({42: 'member'}, {1: 2, 2: 42}, 1) 'member' """ if team_roles.get(team_id) is not None: return team_roles[team_id] current_team_id = team_id visited = [] while True: visited.append(current_team_id) current_team_id = team_parents.get(current_team_id) if current_team_id is None: return None # at the top of the tree if current_team_id in visited: raise ValueError( "Cycles in the tree; path: {} -> {}".format(visited, current_team_id) ) current_team_role = team_roles.get(current_team_id) if current_team_role is not None: return current_team_role
def _parse_seq_body(line): """ Ex: {()YVPFARKYRPKFFREVIGQEAPVRILKALNcknpskgepcgereiDRGVFPDVRA-LKLLDQASVYGE()}* MENINNI{()----------FKLILVGDGKFFSSSGEIIFNIWDTKFGGLRDGYYRLTYKNEDDM()}* Or: {(HY)ELPWVEKYR... The sequence fragments in parentheses represent N- or C-terminal flanking regions that are not part of the alignment block (I think). Most tools don't include them, but some do, apparently. """ line = line.rstrip('*') if '{()' in line: head, _rest = line.split('{()', 1) else: # Match parens _rest = line.split('{(', 1)[1] head, _rest = _rest.split(')', 1) if '()}' in _rest: molseq, tail = _rest.split('()}', 1) else: # Match parens molseq, _rest = _rest.split('(', 1) tail = _rest.split(')}', 1)[0] return (head, molseq, tail)
def get_iterable(input_var): """ Returns an iterable, in case input_var is None it just returns an empty tuple :param input_var: can be a list, tuple or None :return: input_var or () if it is None """ if input_var is None: return () return input_var
def _create_primes(threshold): """ Generate prime values using sieve of Eratosthenes method. Parameters ---------- threshold : int The upper bound for the size of the prime values. Returns ------ List All primes from 2 and up to ``threshold``. """ if threshold == 2: return [2] elif threshold < 2: return [] numbers = list(range(3, threshold+1, 2)) root_of_threshold = threshold ** 0.5 half = int((threshold+1)/2-1) idx = 0 counter = 3 while counter <= root_of_threshold: if numbers[idx]: idy = int((counter*counter-3)/2) numbers[idy] = 0 while idy < half: numbers[idy] = 0 idy += counter idx += 1 counter = 2*idx+3 return [2] + [number for number in numbers if number]
def getSizeTable(cursor, tableName): """ Get the size in MB of a table. (Includes the size of the table and the large objects (LOBs) contained in table.""" tableName = tableName.upper() try: if type(tableName) == str: tableName = [tableName, ] queryArgs = {} segs = [] tabs = [] for i in range(len(tableName)): name = 'name' + str(i) queryArgs[name] = tableName[i] segs.append('segment_name = :' + name) tabs.append('table_name = :' + name) cursor.execute(""" SELECT sum(bytes/1024/1024) size_in_MB FROM user_segments WHERE (""" + ' OR '.join(segs) + """ OR segment_name in ( SELECT segment_name FROM user_lobs WHERE """ + ' OR '.join(tabs) + """ UNION SELECT index_name FROM user_lobs WHERE """ + ' OR '.join(tabs) + """ ) )""", queryArgs) size = cursor.fetchall()[0][0] if size == None: size = 0 except: size = 0 return size
def parallel_variance(mean_a, count_a, var_a, mean_b, count_b, var_b): """Compute the variance based on stats from two partitions of the data. See "Parallel Algorithm" in https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance Args: mean_a: the mean of partition a count_a: the number of elements in partition a var_a: the variance of partition a mean_b: the mean of partition b count_b: the number of elements in partition b var_b: the variance of partition b Return: the variance of the two partitions if they were combined """ delta = mean_b - mean_a m_a = var_a * (count_a - 1) m_b = var_b * (count_b - 1) M2 = m_a + m_b + delta**2 * count_a * count_b / (count_a + count_b) var = M2 / (count_a + count_b - 1) return var
def _postprocess_feature(feature): """Make a feature compatible with graph tuples""" # always return an iterable if not hasattr(feature, "__len__"): feature = (feature,) # transparently convert bools etc. to float return [float(value) for value in feature]
def allPointsBetween_int(x1, y1, x2, y2, accuracy): """Does not use allPointsBetween() Requires extra parameter accuracy (1=default) Returns in integer.""" # slope = dy/dx (rise/run) dy = y2 - y1 dx = x2 - x1 currXadd = 0 # x2 # int currYadd = 0 # y2 # int pointGraphArr = [(x1, y1)] while True: currXadd += dx / accuracy currYadd += dy / accuracy pointGraphArr.append((int(currXadd), int(currYadd))) if pointGraphArr[len(pointGraphArr) - 1][0] > x2: pointGraphArr.pop() # it added a number larger than xpos return pointGraphArr
def oauth_url(client_id, permissions=None, server=None, redirect_uri=None): """A helper function that returns the OAuth2 URL for inviting the bot into servers. Parameters ----------- client_id : str The client ID for your bot. permissions : :class:`Permissions` The permissions you're requesting. If not given then you won't be requesting any permissions. server : :class:`Server` The server to pre-select in the authorization screen, if available. redirect_uri : str An optional valid redirect URI. """ url = 'https://discordapp.com/oauth2/authorize?client_id={}&scope=bot'.format(client_id) if permissions is not None: url = url + '&permissions=' + str(permissions.value) if server is not None: url = url + "&guild_id=" + server.id if redirect_uri is not None: from urllib.parse import urlencode url = url + "&response_type=code&" + urlencode({'redirect_uri': redirect_uri}) return url
def extract_state(x): """ Extracts state from location. """ split = x.split(', ') if len(split) != 2: return '' return split[1]
def calculate_octant(vector): """Calculates in which octant vector lies and returns the normalized vector for this octant. :param vector: given vector :type vector: array :rtype: normalized vector """ #Small offset between octants epsilon = 30 if epsilon > vector[0] and vector[0] > -epsilon: direction_x = 0 else: if vector[0] > 0: direction_x = 1 else: direction_x = -1 if epsilon > vector[1] and vector[1] > -epsilon: direction_y = 0 else: if vector[1] > 0: direction_y = 1 else: direction_y = -1 #Normalize if not direction_y == 0 and not direction_x == 0: if direction_y < 0: direction_y = -0.75 else: direction_y = 0.75 if direction_x < 0: direction_x = -0.75 else: direction_x = 0.75 return (direction_x, direction_y)
def get_new_classes(update_records): """ """ relabeled_classes = [] for rec in update_records: relabeled_classes += [rec.relabeled_class] return set(relabeled_classes)
def norm(value): """ Convert to Unicode """ if hasattr(value,'items'): return dict([(norm(n),norm(v)) for n,v in list(value.items())]) try: return value.decode('utf-8') except: return value.decode('iso-8859-1')
def apply_transform(service, t, x): """Apply a transformation using `self` as object reference.""" if t is None: return x else: return t(service, x)
def is_retryable_error(error): """ Determines whether the given error is retryable or not. :param error: (:class:`~hazelcast.exception.HazelcastError`), the given error. :return: (bool), ``true`` if the given error is retryable, ``false`` otherwise. """ return hasattr(error, 'retryable')
def is_duplicate_policy(link_contents, domain, policy_dict): """ Since the crawler does its work automatically, it is not immune to gathering duplicate policies (sometimes from different initial sources). This function will compare the current policy with the previously verified policies to see if it is a duplicate. """ # digest = md5(link_contents.encode()) # digest = digest.hexdigest() if link_contents in policy_dict: return True else: policy_dict[link_contents] = domain return False
def caesar_cipher_decode(n: int, text: str, p: str) -> str: """ Returns a string where the characters in text are shifted left n number of spaces. The characters in text are only decrypted if they exist in p. If they don't exist in p, they will remain unchanged. Ex. str = 'def45' n = 3 returns - 'abc12' Notes: Currently p can be string.ascii_lowercase or string.printable characters. The only whitespace string.printable will use is " ". (one space only, no newline, tabs, etc.) str.maketrans returns a translation table that replaces items in p with items in p[-n:] + p[:-n], which is just the string p shifted to the left n units. my_str.translate(lookup_table) returns a copy of my_str using the lookup table. """ lookup_table = str.maketrans(p, p[-n:] + p[:-n]) return text.translate(lookup_table)
def cell_associate(pathloss_matrix, users, basestations): """Associate a user with a basestation that provides the minimum pathloss. Args: pathloss_matrix: (list) of numpy arrays users: (obj) list of users! basestations: (obj) list of basestations! Returns: (list of) tuples containing the UE object and the BS it is associated to. """ index_list_min_pl = [] # List that contains tuple of (index(min(pathloss)), pathloss) for eacb UE! list_bs = [] # List of basestation objects associated with each UE in order! for _ in pathloss_matrix: index_list_min_pl.append(min(enumerate(_), key=(lambda x: x[1]))) for _ in index_list_min_pl: index = _[0] list_bs.append(basestations[index]) cell_associate_list = list(zip(users, list_bs)) # List that contains tuple: (ue_object, bs_associated)! return cell_associate_list
def drop_none(arr): """ Drop none from the list :param arr: :return: """ return [x for x in arr if x is not None]