content
stringlengths
42
6.51k
def invert(d: dict) -> dict: """Invert keys and values in a dictionary""" return { v: k for k, v in d.items() }
def capfirst(value): """Capitalizes the first character of the value.""" return value and value[0].upper() + value[1:]
def len_ignore_leading_ansi(s: str) -> int: """Returns the length of the string or 0 if it starts with `\033[`""" return 0 if s.startswith("\033[") else len(s)
def h(x): """Convert an integer into a raw hexadecimal representation.""" return hex(x).replace("0x", "").replace("L", "").upper()
def strip_type_prefix(path, prefix): """Strip source type prefix from the path. This function strips prefix from strings like:: [<prefix>]://<path> For example:: pyfile://home/me/config.py -> /home/me/config.py json://path/to/some.cfg -> /path/to/some.cfg Args: path: Path string. prefix: Prefix to strip. Returns: Path string. """ path = path.lstrip() if path.startswith(prefix + '://'): path = path[len(prefix) + 2:] return path
def algebraic_equasion_defunction(x): """ This function makes a calculation for an Algebraic equasion It calculates f'(x) with the given equasion and x as a parameter """ formula = 2*x + 6 return formula
def groupSubjects(segments): """Group subjects by parent page mongo id""" grouped = {} for s in segments: if s['parent_subject_id']['$oid'] in grouped: grouped[s['parent_subject_id']['$oid']].append(s) else: grouped[s['parent_subject_id']['$oid']] = [s] return grouped
def get_protocol(request = None): """ Return the protocol of the current request. """ if request is None: # We have no request, we return an empty string return '' return 'https' if request.is_secure() else 'http'
def get_capillary_diameter(line1, line2): """ Defines capillary diameter in pixel length. line1 = int32 - first point on left edge of capillary line2 = int32 - second point on right edge of capillary """ #express first points on opposite side of capillary as x,z coordinates L1x,L1y = line1 L2x,L2y = line2 #find straight line distance between points dist = ((L2x-L1x)**2+(L2y-L1y)**2)**0.5 #Assumption: rotation of image is very small such that the scaled straight #line distance is very close to true diameter of the capillary return dist
def function(domain_set, target_set): """ Determine if a relation is a function and tupe of the function. :return: Function or not and type of the function. """ if len(domain_set) == len(set(domain_set)): function_type = 'General function' if len(target_set) != len(set(target_set)): if len(target_set) < len(domain_set) or len(target_set) == len(domain_set): function_type = 'Surjective function' elif len(target_set) > len(domain_set) or len(target_set) == len(domain_set): function_type = 'Injective function' elif len(target_set) == len(set(target_set)) and len(domain_set) == len(target_set): function_type = 'Bijective function' else: function_type = 'Not function' return function_type
def ordinal(value): """ Converts zero or a *postive* integer (or their string representations) to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... u'1st' u'2nd' u'3rd' u'4th' u'5th' u'6th' u'7th' u'8th' u'9th' u'10th' u'11th' u'12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ... u'100th' u'111th' u'112th' u'1011th' """ try: value = int(value) except ValueError: return value except TypeError: return value if value % 100//10 != 1: if value % 10 == 1: ordval = u"%d%s" % (value, "st") elif value % 10 == 2: ordval = u"%d%s" % (value, "nd") elif value % 10 == 3: ordval = u"%d%s" % (value, "rd") else: ordval = u"%d%s" % (value, "th") else: ordval = u"%d%s" % (value, "th") return ordval
def say_hello(name): """ Say hello """ return "Hello {}".format(name)
def get_alt_support_by_color(support_color): """ :return: """ if 240.0 <= support_color <= 255.0: return 1 if 0.0 <= support_color <= 10.0: return 0
def sort_and_format_devices(devices): """ Takes a (list) of (dict)s devices and returns a (list) of (dict)s. Sorts by SCSI ID acending (0 to 7). For SCSI IDs where no device is attached, inject a (dict) with placeholder text. """ occupied_ids = [] for device in devices: occupied_ids.append(device["id"]) formatted_devices = devices # Add padding devices and sort the list for i in range(8): if i not in occupied_ids: formatted_devices.append({"id": i, "device_type": "-", \ "status": "-", "file": "-", "product": "-"}) # Sort list of devices by id formatted_devices.sort(key=lambda dic: str(dic["id"])) return formatted_devices
def get_earliest(*dates): """ Find earliest date in list of provided date strings Parameters: dates (list): List of date strings in format "mm/dd/yyyy" Returns: str: Earliest date found in list of date strings """ earliest = "99/99/9999" for date in list(dates): if date[-4:] < earliest[-4:]: earliest = date elif date[-4:] == earliest[-4:]: if date[0:2] < earliest[0:2]: earliest = date elif date[0:2] == earliest[0:2]: if date[3:5] < earliest[3:5]: earliest = date return earliest
def housecall_status(events): """Returns how many housecalls there are on the calendar.""" if not events: # no events means no housecalls print('No upcoming events found.') return 0 count = 0 for event in events: name = event['summary'].lower() if ('house' in name) and ('call' in name): count += 1 # increment # housecalls return count
def _new_activity_share_format(share): """ Convert the share from the internal format used by FTS3 to the RESTful one [{"A": 1}, {"B": 2}] => {"A": 1, "B": 2} """ new_share = dict() for entry in share: new_share.update(entry) return new_share
def check_for_radicals(mol_list): """Check if list of molecules contains a radical. """ to_remove = [] for name in mol_list: if 'radical' in name: # new_name = name.replace('radical', '').lstrip().rstrip() # if new_name in mol_list: print('removing', name, 'as it is a radical') to_remove.append(name) return to_remove
def roundto(num, nearest): """ Rounds :param:`num` to the nearest increment of :param:`nearest` """ return int((num + (nearest / 2)) // nearest * nearest)
def filter_ensuretrailingslash(host): """ Adds a trailing slash to URLs (or anything, really) if one isn't present Usage: {{ 'www.example.com' | ensuretrailingslash }} Output: 'www.example.com/' """ if not host.endswith("/"): host = host + "/" return host
def _compute_timeout(count: int, delay: float) -> int: """Dumb logic for a max timeout, this could be better ``max_tasks_fn_timeout`` is the amount of seconds and is the anticipated amount of time to do all concurrent requests in the workflow's (see ``tasks_fn``). Empirically, when all default tasks are concurrently requested on my machine, it takes around 6 seconds. 15 seconds is double this time with a 3 seconds of buffer (2 * 6) + 3. """ max_tasks_fn_timeout = 15 # 15 seconds return int((count * max_tasks_fn_timeout) + (delay * count))
def create_y_range(motile_count, non_motile_count, auto_motile_count, auto_non_motile_count): """ Generate the y range on the motility bar :param motile_count: the amount of motile life at this frame :param non_motile_count: the amount of non motile life at this frame :param auto_count: the amount of hand labeled tracks at this frame :return: the amount of life at this frame """ y = [] if motile_count is not None: y += motile_count if non_motile_count is not None: y += non_motile_count if auto_motile_count is not None: y += auto_motile_count if auto_non_motile_count is not None: y += auto_non_motile_count _min = None _max = None if y: _min = min(y) _max = max(y) + 1 return [_min, _max]
def _apply_func(func, x, none_safe): """Helper for `update_with_redict()` containing logic for running func(x). """ if func is not None: if not none_safe: x = func(x) else: if x is not None: x = func(x) return x
def between_markers(text: str, begin: str, end: str) -> str: """ returns substring between two given markers """ a_index = text.index(begin) b_index = text.index(end) return text[a_index + 1 : b_index]
def split_string(text, chars_per_string): """ Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string. This is very useful for splitting one giant message into multiples. :param text: The text to split :param chars_per_string: The number of characters per line the text is split into. :return: The splitted text as a list of strings. """ return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)]
def xy2z(x, y): """ Interleave lower 16 bits of x and y, so the bits of x are in the even positions and bits from y in the odd; z gets the resulting 32-bit Morton Number. x and y must initially be less than 65536. Source: http://graphics.stanford.edu/~seander/bithacks.html """ B = [0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF] S = [1, 2, 4, 8] x = (x | (x << S[3])) & B[3] x = (x | (x << S[2])) & B[2] x = (x | (x << S[1])) & B[1] x = (x | (x << S[0])) & B[0] y = (y | (y << S[3])) & B[3] y = (y | (y << S[2])) & B[2] y = (y | (y << S[1])) & B[1] y = (y | (y << S[0])) & B[0] z = x | (y << 1); return x | (y << 1)
def getR(m, t, a): """ Returns the matrix R as in the canonical form [[Q,R],[0,I]] m is the input matrix, t is the list of the transient states, a is the list of the absorbing states. """ R = [] for r in range(len(t)): qrow = [] for c in range(len(a)): qrow.append(m[t[r]][a[c]]) R.append(qrow) return R
def evenOdd(num): """Returns the string "even", "odd", or "UNKNOWN".""" if num % 2 == 0: return "even" elif num % 2 == 1: return "odd" else: return "UNKNOWN"
def make_shit_comma_separated_func(x, y): """ func for use in reduce() methods to make a list a comma separated string :param x: :param y: :return: """ return str(x) + ',' + str(y)
def mean( xs ): """ Return the mean value of a sequence of values. >>> mean([2,4,4,4,5,5,7,9]) 5.0 >>> mean([9,10,11,7,13]) 10.0 >>> mean([1,1,10,19,19]) 10.0 >>> mean([10,10,10,10,10]) 10.0 >>> mean([1,"b"]) Traceback (most recent call last): ... ValueError: Input can't have non-numeric elements >>> mean([]) Traceback (most recent call last): ... ValueError: Input can't be empty """ try: return sum( xs ) / float( len( xs ) ) except TypeError: raise ValueError( "Input can't have non-numeric elements" ) except ZeroDivisionError: raise ValueError( "Input can't be empty" )
def FindPart(part: dict, mime_type: str): """ Recursively parses the parts of an email and returns the first part with the requested mime_type. :param part: Part of the email to parse (generally called on the payload). :param mime_type: MIME Type to look for. :return: The part of the email with the matching type. """ if part['mimeType'] == mime_type: return part elif 'multipart' in part['mimeType']: for child in part['parts']: out = FindPart(child, mime_type) if out is not None: return out
def gcd(x, y): """This function implements the Euclidian algorithm to find G.C.D. of two numbers""" while(y): x, y = y, x % y return x
def allpairs(x): """ return all possible pairs in sequence *x* """ return [(s, f) for i, f in enumerate(x) for s in x[i + 1:]]
def dividir(a, b): """ DIVIDIR realiza la division de 2 numeros """ try: return a/b except Exception as e: print(e) return 0
def assert_raises(ex_type, func, *args, **kwargs): """ Checks that a function raises an error when given specific arguments. Args: ex_type (Exception): exception type func (callable): live python function Example: >>> ex_type = AssertionError >>> func = len >>> assert_raises(ex_type, assert_raises, ex_type, func, []) >>> assert_raises(ValueError, [].index, 0) """ try: func(*args, **kwargs) except Exception as ex: assert isinstance(ex, ex_type), ( 'Raised %r but type should have been %r' % (ex, ex_type)) return True else: raise AssertionError('No error was raised')
def bit_bitlist_to_str(ordlist): """Given a list of ordinals, convert them back to a string""" return ''.join(map(chr, ordlist))
def initial_state(loops): """Given a set of loops, create the initial counters""" return tuple(row[2] for row in loops)
def get_song_stereotypy(sequence_linearity: float, sequence_consistency: float) -> float: """Average between linearity and consistency""" song_stereotypy = (sequence_linearity + sequence_consistency) / 2 return song_stereotypy
def overall_chromatic_response(M_yb, M_rg): """ Returns the overall chromatic response :math:`M`. Parameters ---------- M_yb : numeric Yellowness / blueness response :math:`M_{yb}`. M_rg : numeric Redness / greenness response :math:`M_{rg}`. Returns ------- numeric Overall chromatic response :math:`M`. Examples -------- >>> M_yb = -0.008237223618824608 >>> M_rg = -0.00010444758327626432 >>> overall_chromatic_response(M_yb, M_rg) # doctest: +ELLIPSIS 0.0082378... """ M = ((M_yb ** 2) + (M_rg ** 2)) ** 0.5 return M
def process_tweet(text, target, do_short): """Check it's ok and remove some stuff""" # print(len(text) > 140, len(text)) if not text: return None if do_short and len(text) > 141: return None elif not do_short and len(text) <= 140: return None if (text.startswith("RT ") or "@" in text or "#" in text or "http" in text): return None text_lower = text.lower() if target.lower() not in text_lower: return None exclude = [] if any(substr in text_lower for substr in exclude): return None # return split_from(target, text) return text
def convert_keyname_to_safe_field(obj): """convert keyname into safe field name. when dict key include dash(-), convert to safe field name under_score(_). """ if isinstance(obj, dict): for org_key in list(obj.keys()): new_key = org_key if '-' in org_key: new_key = org_key.translate({ord('-'): ord('_')}) obj[new_key] = obj.pop(org_key) convert_keyname_to_safe_field(obj[new_key]) elif isinstance(obj, list): for val in obj: convert_keyname_to_safe_field(val) else: pass return obj
def str_to_int(text, default=0): """ >>> str_to_int("3") 3 >>> str_to_int("moo") 0 >>> str_to_int(None) 0 >>> str_to_int(str_to_int) 0 >>> str_to_int("cake", default=6) 6 """ try: return int(text) except (ValueError, TypeError): return default
def color(string, color=None): """ Change text color for the Linux terminal. (Taken from Empire: https://github.com/EmpireProject/Empire/blob/master/lib/common/helpers.py) """ attr = [] # bold attr.append('1') if color: if color.lower() == "red": attr.append('31') elif color.lower() == "green": attr.append('32') elif color.lower() == "yellow": attr.append('33') elif color.lower() == "blue": attr.append('34') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) else: if string.strip().startswith("[!]"): attr.append('31') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) elif string.strip().startswith("[+]"): attr.append('32') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) elif string.strip().startswith("[..]"): attr.append('33') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) elif string.strip().startswith("[*]"): attr.append('34') return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) else: return string
def count_random_set_bits(n, k, random_set): """Counts the number of ones in the randomly chosen k digits of binary. Args: n: Integer, the integer of interest. k: Integer, the number of binary digits that the subset parity acts on. random_set: List of integers, random binary string with ones in k locations. Returns: A subset parity value specified by a binary string of length k. """ count = 0 digits = 1 bit_index = 0 while n and digits <= k: n >>= 1 if random_set[bit_index] > 0: count += n & 1 digits += 1 bit_index += 1 return count
def isOccluded(match, tiles): """Returns true if the match is already occluded by another match in the tiles list. "Note that "not occluded" is taken to mean that none of the tokens Pp to Pp+maxmatch-1 and Tt to Tt+maxmatch-1 has been marked during the creation of an earlier tile. However, given that smaller tiles cannot be created before larger ones, it suffices that only the ends of each new putative tile be testet for occlusion, rather than the whole maxmimal match." ["String Similarity via Greedy String Tiling and Running Karp-Rabin Matching" http://www.pam1.bcs.uwa.edu.au/~michaelw/ftp/doc/RKR_GST.ps] """ for m in tiles: if (m[0]+m[2] == match[0]+match[2] and m[1]+m[2] == match[1]+match[2]): return True return False
def GetMaxRounds(board_list): """ Gets the maximum number of rounds any team has played in the tournament. """ if not board_list: return 0 board_counts = {} for bs in board_list: for bsl in bs.ScoreBoard(): hr = bsl.hr() board_counts[hr.ns_pair_no()] = 1 + board_counts.get(hr.ns_pair_no(), 0) board_counts[hr.ew_pair_no()] = 1 + board_counts.get(hr.ew_pair_no(), 0) return max(board_counts.values())
def bool_to_bin(bool_value): """ Helper function to map a boolean value to a binary value. :param bool_value: boolean boolean value [bool] :return: binary value [int] """ if bool_value: return 1 else: return 0
def add_webmention_endpoint(response): """ This publishes a webmention endpoint for everything, including error pages (necessary for receiving pings to private entries) and image resources. Please fix the endpoint URL before uncommenting this. """ #response.headers.add('link', '<https://webmention.io/DOMAIN_GOES_HERE/webmention>; rel="webmention"') return response
def parse_single_alignment(string, reverse=False, one_add=False, one_indexed=False): """ Given an alignment (as a string such as "3-2" or "5p4"), return the index pair. """ assert '-' in string or 'p' in string a, b = string.replace('p', '-').split('-') a, b = int(a), int(b) if one_indexed: a = a - 1 b = b - 1 if one_add: a = a + 1 b = b + 1 if reverse: a, b = b, a return a, b
def load32(byte): """ bytearray to int (little endianness) """ return sum((byte[i] << (8 * i)) for i in range(4))
def cleandef(s): """E.g. given a def string 'C & ~Z', return ' C & ~Z' so it lines up with other table rows i.e. BEFORE: | eq 4'h0 | Z | -------- | hi 4'h8 | C & ~Z | | ne 4'h1 | ~Z | -------- | ls 4'h9 | ~C \| Z | AFTER: | eq 4'h0 | Z | -------- | hi 4'h8 | C & ~Z | | ne 4'h1 | ~Z | -------- | ls 4'h9 | ~C \| Z |""" if s == "C & ~Z" : s = " C & ~Z" if s == "~C \| Z" : s = "~C | Z" if s == "(N == V)": s = " N == V" if s == "(N != V)": s = " N != V" if s == "Z \| (N != V)": s = " Z | (N != V)" if s == "res_lut" : s = "lut_code[{bit2,bit1,bit0}]" return s
def map_field(fn, m) : """ Maps a field name, given a mapping file. Returns input if fieldname is unmapped. """ if m is None: return fn if fn in m: return m[fn] else: return fn
def shell_strip_comment(cmd): """ hi # testing => hi""" if '#' in cmd: return cmd.split('#', 1)[0] else: return cmd
def Get_LonghurstProvinceName4Num(input): """ Get full Longhurst Province for given number """ LonghurstProvinceDict = { 'ALSK': 'AlaskaDownwellingCoastalProvince', 'ANTA': 'AntarcticProvince', 'APLR': 'AustralPolarProvince', 'ARAB': 'NWArabianUpwellingProvince', 'ARCH': 'ArchipelagicDeepBasinsProvince', 'ARCT': 'AtlanticArcticProvince', 'AUSE': 'EastAustralianCoastalProvince', 'AUSW': 'AustraliaIndonesiaCoastalProvince', 'BENG': 'BenguelaCurrentCoastalProvince', 'BERS': 'N.PacificEpicontinentalProvince', 'BPLR': 'BorealPolarProvince(POLR)', 'BRAZ': 'BrazilCurrentCoastalProvince', 'CAMR': 'CentralAmericanCoastalProvince', 'CARB': 'CaribbeanProvince', 'CCAL': 'CaliforniaUpwellingCoastalProvince', 'CHIL': 'ChilePeruCurrentCoastalProvince', 'CHIN': 'ChinaSeaCoastalProvince', 'CHSB': 'CheasapeakeBayProvince', 'CNRY': 'CanaryCoastalProvince(EACB)', 'EAFR': 'E.AfricaCoastalProvince', 'ETRA': 'EasternTropicalAtlanticProvince', 'FKLD': 'SWAtlanticShelvesProvince', 'GFST': 'GulfStreamProvince', 'GUIA': 'GuianasCoastalProvince', 'GUIN': 'GuineaCurrentCoastalProvince', 'INDE': 'E.IndiaCoastalProvince', 'INDW': 'W.IndiaCoastalProvince', 'ISSG': 'IndianS.SubtropicalGyreProvince', 'KURO': 'KuroshioCurrentProvince', 'LAKE': 'CaspianSea,AralSea', 'MEDI': 'MediterraneanSea,BlackSeaProvince', 'MONS': 'IndianMonsoonGyresProvince', 'NADR': 'N.AtlanticDriftProvince(WWDR)', 'NASE': 'N.AtlanticSubtropicalGyralProvince(East)(STGE)', 'NASW': 'N.AtlanticSubtropicalGyralProvince(West)(STGW)', 'NATR': 'N.AtlanticTropicalGyralProvince(TRPG)', 'NECS': 'NEAtlanticShelvesProvince', 'NEWZ': 'NewZealandCoastalProvince', 'NPPF': 'N.PacificPolarFrontProvince', 'NPSE': 'N.PacificSubtropicalGyreProvince(East)', 'NPSW': 'N.PacificSubtropicalGyreProvince(West)', 'NPTG': 'N.PacificTropicalGyreProvince', 'NWCS': 'NWAtlanticShelvesProvince', 'OCAL': 'OffshoreCaliforniaCurrentProvince', 'PEQD': 'PacificEquatorialDivergenceProvince', 'PNEC': 'N.PacificEquatorialCountercurrentProvince', 'PSAE': 'PacificSubarcticGyresProvince(East)', 'PSAW': 'PacificSubarcticGyresProvince(West)', 'REDS': 'RedSea,PersianGulfProvince', 'SANT': 'SubantarcticProvince', 'SARC': 'AtlanticSubarcticProvince', 'SATL': 'SouthAtlanticGyralProvince(SATG)', 'SPSG': 'S.PacificSubtropicalGyreProvince', 'SSTC': 'S.SubtropicalConvergenceProvince', 'SUND': 'SundaArafuraShelvesProvince', 'TASM': 'TasmanSeaProvince', 'WARM': 'W.PacificWarmPoolProvince', 'WTRA': 'WesternTropicalAtlanticProvince' } return LonghurstProvinceDict[input]
def _strip_trailing_newline(s): """Returns a modified version of the string with the last character truncated if it's a newline. :param s: string to trim :type s: str :returns: modified string :rtype: str """ if s == "": return s else: return s[:-1] if s[-1] == '\n' else s
def html_document(text): """Wrap an HTML snippet in <body> tags, etc. to make it a full document.""" return f"""<!DOCTYPE html> <html> <body> {text} </body> </html> """
def ngrams(sentence, n): """ Returns: list: a list of lists of words corresponding to the ngrams in the sentence. """ return [sentence[i:i + n] for i in range(len(sentence)-n+1)]
def mergesort_lists(*lists): """Supposet that lists are sorted Complexity is O(n+m+l+...) """ def next_(iterator): """ Provide dict {"id":id , ...} for id comparison""" return next(iterator, {'id': float("inf")}) iters = [] # List iterators are stored here items = [] # Dictionaries with id and other stuff are stored here values = [] # id's are stored here for comparison for l in lists: i = iter(l) iters.append(i) it = next_(i) items.append(it) v = it['id'] values.append(v) # To build merged list merged = [] while True: min_ = float('inf') # define current min as infinity pos = -1 # Traverse to find a min value to apend it next for idx, val in enumerate(values): if val < min_: min_ = val pos = idx # if min value was not reached then all are inf and that means StopIteration for all lists if pos == -1: return merged merged.append(items[pos]) # Change iterators and binded data iterator = iters[pos] item = next_(iterator) value = item['id'] items[pos] = item values[pos] = value
def upper(value): """ convert to uppercase :param value: :return: """ return value.upper()
def parse_custom_command(command: str) -> list: """ Convert custom medusa command from string to list to be usable in subprocess. :param command: Custom medusa command :return: Parameters for medusa command """ command_split = command.split(" ") command_list = [] for parameter in command_split: command_list.append(parameter) return command_list
def get_list(text, delim=',', lower=False): """ Take a string and return trim segments given the delimiter: "A, B,\tC" => ["A", "B", "C"] :param text: :param delim: delimiter str :param lower: True if you want items lowercased :return: array """ if not text: return [] data = text.split(delim) arr = [] for v in data: _v = v.strip() if _v: if lower: _v = _v.lower() arr.append(_v) return arr
def asFloat(val): """Converts floats, integers and string representations of either to floats. Raises ValueError or TypeError for all other values """ if hasattr(val, "lower") and val.lower() == "nan": raise ValueError("%s is not a valid float" % (val,)) else: return float(val)
def count_query(tablename,condition): """ Function to process query for count process """ if isinstance(tablename, str): pass else: raise ValueError("Tablename should be a String") if condition == None or isinstance(condition, str): pass else: raise ValueError("Condition can only be either None or String") if condition == None: query = "select count(*) from " + tablename else: # building the query query = "select count(*) from " + tablename + " where " + condition return query
def new_task_id(sources, prefix=""): """Generate a new unique task ID The task ID will be unique for the given sources, and with the given prefix. """ existing_ids = set() for source in sources: existing_ids |= {int(key[len(prefix):]) for key in source.task_ids if key.startswith(prefix) and key[len(prefix):].isnumeric()} if len(existing_ids) > 0: highest = max(existing_ids) else: highest = 0 return prefix + str(highest+1)
def is_hex(HEX_MAYBE): """ Checks if a string could be expressed in hexidecimal. """ try: int(HEX_MAYBE, 16) return True except ValueError: return False
def is_string_palindrom(string): """Testuje, zdali je zadany retezec (string) palindrom a to bez pouziti funkce reverse. Vraci True v pripade, ze je palindrom, jinak False. """ if string is None: return False i = 0 while i < len(string): if string[i] == string[len(string) -1 - i]: i+=1 continue else: return False return True
def check_skip(selector, chrom): """ :param selector: :param chrom: :return: """ if selector is None: return False elif selector.match(chrom) is None: return True else: return False
def get_attr_value(attrs, key): """Read attr value from terncy attributes.""" for att in attrs: if "attr" in att and att["attr"] == key: return att["value"] return None
def active_llr_level(i, n): """ Find the first 1 in the binary expansion of i. """ mask = 2**(n-1) count = 1 for k in range(n): if (mask & i) == 0: count += 1 mask >>= 1 else: break return min(count, n)
def count_sql(name): """ Generate SQL to count the number of rows in a table :param name: table name :return: SQL string """ return f'SELECT COUNT(*) FROM "{name}";'
def unique_group(groups): """Find unique groups in list not including None.""" ugroups = set(groups) ugroups -= set((None,)) ugroups = list(ugroups) ugroups.sort() return ugroups
def toFloat( value, shift=0 ): """Take single-byte integer value return floating point equivalent""" return ((value&(255<<shift))>>shift)/255.0
def get_tarball_valid_unpack_directory_name(package_name: str, version_number: str) -> str: """ get the name of the folder that should be obtained by unpacking the tarball :param package_name: name of the package to check :param version_number: version number :return: the name of the folder that is obtained by unpacking the tarball """ return f"{package_name}_{version_number}"
def normalize_teh_marbuta_xmlbw(s): """Normalize all occurences of Teh Marbuta characters to a Heh character in a XML Buckwalter encoded string. Args: s (:obj:`str`): The string to be normalized. Returns: :obj:`str`: The normalized string. """ return s.replace(u'p', u'h')
def print_heading_structure(h: int, text: str) -> str: """ This method prints our heading, represented as an integer (which is the level of the heading, h1 is 1 ...) :param h: Integer that represents our headings (which is the level of the heading, h1 is 1 ...) :param text: Text to add to our headings, in our case the text of the heading tag :return: We return a string that contains the heading in the format described above """ # We leave as many two blank spaces as the level of the heading (" "*h) so for instance for h1 we will leave " " # for h2 we leave " " and so on, then we print hx (x being the level of the heading) and then the text heading = " " * h + "h{0}: - {1}\n".format(h, text.replace("\n", "")) # We return the str return heading
def sanitize_line(line, commenter='!'): """Clean up input line.""" return line.split(commenter, 1)[0].strip()
def next_good(bad_samples_idx, i): """ Find the index of the next good item in the list. :param bad_samples_idx: List of the indices of the bad samples. :param i: Index of the current item. :return: Index of the next good item. """ while True: i += 1 if i >= (len(bad_samples_idx) - 1): return bad_samples_idx[-1] + 1 if (bad_samples_idx[i] + 1) == bad_samples_idx[i + 1]: continue else: break return bad_samples_idx[i] + 1
def dict_remove_empty(d): """remove keys that have [] or {} or as values""" new = {} for k, v in d.items(): if not (v == [] or v == {}): new[k] = v return new
def drange(v0, v1, d): """Returns a discrete range.""" assert v0 < v1, str((v0, v1, d)) return list(range(int(v0) // d, int(v1 + d) // d))
def bubbleSort(myList: list): """ Sorts the list in Ascendant mode and returns it properly sorted. """ listLen = len(myList) for i in range(listLen): for j in range(0, listLen-i-1): # O(n) * O(n) = O(n*n) = O(n**2) if (myList[j] > myList[j+1]): myList[j], myList[j+1] = myList[j+1], myList[j] return myList
def UNKNOWN_FILE(project_id, file_id): """Error message for requests that access project files. Parameters ---------- project_id: string Unique project identifier. file_id: string Unique file identifier. Returns ------- string """ msg = "unknown file '{}' or project '{}'" return msg.format(file_id, project_id)
def filter_dictionary_by_resolution(raw_data, threshold=False): """Filter SidechainNet data by removing poor-resolution training entries. Args: raw_data (dict): SidechainNet dictionary. threshold (float, bool): Entries with resolution values greater than this value are discarded. Test set entries have no measured resolution and are not excluded. Default is 3 Angstroms. If False, nothing is filtered. Returns: Filtered dictionary. """ if not threshold: return raw_data if isinstance(threshold, bool) and threshold is True: threshold = 3 new_data = { "seq": [], "ang": [], "ids": [], "evo": [], "msk": [], "crd": [], "sec": [], "res": [] } train = raw_data["train"] n_filtered_entries = 0 total_entires = 0. for seq, ang, crd, msk, evo, _id, res, sec in zip(train['seq'], train['ang'], train['crd'], train['msk'], train['evo'], train['ids'], train['res'], train['sec']): total_entires += 1 if not res or res > threshold: n_filtered_entries += 1 continue else: new_data["seq"].append(seq) new_data["ang"].append(ang) new_data["ids"].append(_id) new_data["evo"].append(evo) new_data["msk"].append(msk) new_data["crd"].append(crd) new_data["sec"].append(sec) new_data["res"].append(res) if n_filtered_entries: print(f"{n_filtered_entries} ({n_filtered_entries/total_entires:.1%})" " training set entries were excluded based on resolution.") raw_data["train"] = new_data return raw_data
def abband(matrix, vecin, vecout, neq, iband): """ Multiplies [ banded ]{vector} = {vector} """ for i in range(neq): jlim = max(0, i - iband + 1) for j in range(jlim, i): val = vecin[j] vecout[i] += val * matrix[j][i - j + 1] # jlim = min(iband, neq - i + 1) for j in range(1, jlim): val = vecin[i + j - 1] vecout[i] += val * matrix[i][j] # return vecout
def is_pos_int(num): """Function: is_pos_int Description: Returns True|False if number is an integer and positive. Arguments: (input) num -> Integer value. (output) True|False -> Number is an integer and positive. """ return isinstance(num, int) and num > 0
def generate_hypotheses_for_effect(cause_alpha, effect, window_start, window_end): """ Lists all hypotheses for a given effect. Excludes hypotheses where the cause and effect are the same variable. See the docs of `generate_hypotheses_for_effects` """ hyps = [] for cause in cause_alpha: if cause != effect: t = (cause, effect, window_start, window_end) hyps.append(t) return(hyps)
def _normalize_integer_rgb(value): """ Internal normalization function for clipping integer values into the permitted range (0-255, inclusive). """ return 0 if value < 0 \ else 255 if value > 255 \ else value
def unescape(text): """ Do reverse escaping. """ text = text.replace('&amp;', '&') text = text.replace('&lt;', '<') text = text.replace('&gt;', '>') text = text.replace('&quot;', '"') text = text.replace('&#39;', '\'') return text
def are_entities_in_augmented_text(entities: list, augmented_text: str) -> bool: """ Given a list of entities, check if all the words associated to each entity are still present in augmented text. Parameters ---------- entities : list entities associated to initial text, must be in the following format: [ { 'entity': str, 'word': str, 'startCharIndex': int, 'endCharIndex': int }, { ... } ] augmented_text : str Returns ------- True if all entities are present in augmented text, False otherwise """ check = True for ent in entities: if ent['word'] not in augmented_text: check = False return check return check
def transition_filename(tr): """Get the part of the filename specifying the transition (e.g. BKstar) from a transition string (e.g. B->K*).""" return tr.replace('->', '').replace('*', 'star')
def extract_validatable_type(type_name, models): """Returns a jsonschema-compatible typename from the Swagger type. This is necessary because for our Swagger specs to be compatible with swagger-ui, they must not use a $ref to internal models. :returns: A key-value that jsonschema can validate. Key will be either 'type' or '$ref' as is approriate. :rtype: dict """ if type_name in models: return {'$ref': type_name} else: return {'type': type_name}
def xorCrypt(str, key=6): """Encrypt or decrypt a string with the given XOR key.""" output = "" for x in range(0, len(str)): output += chr(key ^ ord(str[x])) return output
def compute_inv_permute_vector(permute_vector): """ Given a permutation vector, compute its inverse permutation vector s.t. an array will have the same shape after permutation and inverse permutation. """ inv_permute_vector = [] for i in range(len(permute_vector)): # print('i = {}'.format(i)) position_of_i = permute_vector.index(i) # print('position_of_i = {}'.format(position_of_i)) inv_permute_vector.append(position_of_i) return tuple(inv_permute_vector)
def _get_character_pairs(text): """Returns a defaultdict(int) of adjacent character pair counts. >>> _get_character_pairs('Test is') {'IS': 1, 'TE': 1, 'ES': 1, 'ST': 1} >>> _get_character_pairs('Test 123') {'23': 1, '12': 1, 'TE': 1, 'ES': 1, 'ST': 1} >>> _get_character_pairs('Test TEST') {'TE': 2, 'ES': 2, 'ST': 2} >>> _get_character_pairs('ai a al a') {'AI': 1, 'AL': 1} >>> _get_character_pairs('12345') {'34': 1, '12': 1, '45': 1, '23': 1} >>> _get_character_pairs('A') {} >>> _get_character_pairs('A B') {} >>> _get_character_pairs(123) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "strikeamatch.py", line 31, in _get_character_pairs if not hasattr(text, "upper"): raise ValueError ValueError: Invalid argument """ if not hasattr(text, "upper"): raise ValueError("Invalid argument") results = dict() for word in text.upper().split(): for pair in [word[i]+word[i+1] for i in range(len(word)-1)]: if pair in results: results[pair] += 1 else: results[pair] = 1 return results
def format_weight_imperial(weight): """Formats a weight in hectograms as L lb.""" return "%.1f lb" % (weight / 10 * 2.20462262)
def str_to_enum(name): """Create an enum value from a string.""" return name.replace(' ', '_').replace('-', '_').upper()
def __replaceMonth(_strFecha, _intMonth): """Reemplaza en Mes en Ingles por el Mes en Espanol de la cadena del parametro y segun el numero de mes""" result = '' if 1 == _intMonth: result = _strFecha.replace('January', u'Enero') elif 2 == _intMonth: result = _strFecha.replace('February', u'Febrero') elif 3 == _intMonth: result = _strFecha.replace('March', u'Marzo') elif 4 == _intMonth: result = _strFecha.replace('April', u'Abril') elif 5 == _intMonth: result = _strFecha.replace('May', u'Mayo') elif 6 == _intMonth: result = _strFecha.replace('June', u'Junio') elif 7 == _intMonth: result = _strFecha.replace('July', u'Julio') elif 8 == _intMonth: result = _strFecha.replace('August', u'Agosto') elif 9 == _intMonth: result = _strFecha.replace('September', u'Septiembre') elif 10 == _intMonth: result = _strFecha.replace('October', u'Octubre') elif 11 == _intMonth: result = _strFecha.replace('November', u'Noviembre') elif 12 == _intMonth: result = _strFecha.replace('December', u'Diciembre') # return result
def ConvertDecimalToHexadecimal (integer: int, minimumLength: int = -1) -> str: """ Convert integer to hexadecimal string :type integer: int :param minimumLength: If the hexadecimal is shorter than this number it will be padded with extra zeros. :type minimumLength: int :type: str """ hexString = hex(integer)[2:] if len(hexString) < minimumLength: hexString = "0" * (minimumLength - len(hexString)) + hexString hexString = hexString.upper() return hexString
def get_WNID_from_line(line): """Return the WNID without anything else from categories.txt""" WNID = line.split(" ")[0] return WNID
def generate_bounding_coordinates(lat_list, lng_list): """ This function takes in two lists containing coordinates in the latitude and longitude direction and generates a list containing coordinates for each bounding box. """ lat_list = list(reversed(lat_list)) coordinate_list = [] for i in range(len(lng_list) - 1): for j in range(len(lat_list) - 1): coordinate_list.append([lat_list[j + 1], lng_list[i], lat_list[j], lng_list[i + 1]]) return coordinate_list
def is_between(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is greater than or equal to a supplied ``minimum`` and/or less than or equal to ``maximum``. .. note:: This function works on any ``value`` that support comparison operators, whether they are numbers or not. Technically, this means that ``value``, ``minimum``, or ``maximum`` need to implement the Python magic methods :func:`__lte__ <python:object.__lte__>` and :func:`__gte__ <python:object.__gte__>`. If ``value``, ``minimum``, or ``maximum`` do not support comparison operators, they will raise :class:`NotImplemented <python:NotImplemented>`. :param value: The ``value`` to check. :type value: anything that supports comparison operators :param minimum: If supplied, will return ``True`` if ``value`` is greater than or equal to this value. :type minimum: anything that supports comparison operators / :obj:`None <python:None>` :param maximum: If supplied, will return ``True`` if ``value`` is less than or equal to this value. :type maximum: anything that supports comparison operators / :obj:`None <python:None>` :returns: ``True`` if ``value`` is greater than or equal to a supplied ``minimum`` and less than or equal to a supplied ``maximum``. Otherwise, returns ``False``. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator :raises NotImplemented: if ``value``, ``minimum``, or ``maximum`` do not support comparison operators :raises ValueError: if both ``minimum`` and ``maximum`` are :obj:`None <python:None>` """ if minimum is None and maximum is None: raise ValueError('minimum and maximum cannot both be None') if value is None: return False if minimum is not None and maximum is None: return value >= minimum elif minimum is None and maximum is not None: return value <= maximum elif minimum is not None and maximum is not None: return value >= minimum and value <= maximum