content
stringlengths
42
6.51k
def a2hex(s): """Converts strin to hex representation: ff:00:ff:00 ...""" return ':'.join(x.encode('hex') for x in s)
def quote_dsn_param(s, _special=' \\\''): """Apply the escaping rule required by PQconnectdb.""" if not s: return "''" for char in _special: if char in s: return "'%s'" % s.replace("\\", "\\\\").replace("'", "\\'") return s
def path_cost(path): """The total cost of a path (which is stored in a tuple with the final action.""" # path = (state, (action, total_cost), state, ... ) if len(path) < 3: return 0 else: action, total_cost = path[-2] return total_cost
def increment_counts(counters, data): """ Counter structure: { "PRDP (program)": { "2014 (year)": { "budget": 123, "count": 123, "has_kml": 123, "has_image": 123, "has_classification": 123, "has_eplc_id": 123, "has_completion_data": 123 } } } """ # program if data['program'] not in counters: counters[data['program']] = {} # year if data['year'] not in counters[data['program']]: counters[data['program']][data['year']] = {} # has classification if 'has_classification' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['has_classification'] = 0 counters[data['program']][data['year']]['has_classification'] += data['has_classification'] # has kml if 'has_kml' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['has_kml'] = 0 counters[data['program']][data['year']]['has_kml'] += data['has_kml'] # has image if 'has_image' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['has_image'] = 0 counters[data['program']][data['year']]['has_image'] += data['has_image'] # has eplc_id if 'has_eplc_id' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['has_eplc_id'] = 0 counters[data['program']][data['year']]['has_eplc_id'] += data['has_eplc_id'] # has completion_data if 'has_completion_data' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['has_completion_data'] = 0 counters[data['program']][data['year']]['has_completion_data'] += data['has_completion_data'] # with eplc and has completion_data if 'has_eplc_and_completion_data' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['has_eplc_and_completion_data'] = 0 if data['has_eplc_id'] and data['has_completion_data']: counters[data['program']][data['year']]['has_eplc_and_completion_data'] += 1 # budget if 'budget' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['budget'] = 0 counters[data['program']][data['year']]['budget'] += data['budget'] # count if 'count' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['count'] = 0 counters[data['program']][data['year']]['count'] += 1 # count images if 'images' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['images'] = 0 counters[data['program']][data['year']]['images'] += data['images'] # count kmls if 'kmls' not in counters[data['program']][data['year']]: counters[data['program']][data['year']]['kmls'] = 0 counters[data['program']][data['year']]['kmls'] += data['kmls'] return counters
def get_bounds(im_centre, xlen, width, height): """ calculate the bottom left and top right coordinates """ x, y = im_centre ylen = xlen * (width / height) hx = xlen / 2 hy = ylen / 2 # bottom left and then top right return (x - hx, y - hy), (x + hx, y + hy)
def render_to_log_kwargs(wrapped_logger, method_name, event_dict): """ Render `event_dict` into keyword arguments for :func:`logging.log`. The `event` field is translated into `msg` and the rest of the `event_dict` is added as `extra`. This allows you to defer formatting to :mod:`logging`. .. versionadded:: 17.1.0 """ return {"msg": event_dict.pop("event"), "extra": event_dict}
def get_xdist_worker_id(config): """ Parameters ---------- config: _pytest.config.Config Returns ------- str the id of the current worker ('gw0', 'gw1', etc) or 'master' if running on the 'master' node. If not distributing tests (for example passing `-n0` or not passing `-n` at all) also return 'master'. """ worker_input = getattr(config, "workerinput", None) if worker_input: return worker_input["workerid"] return "master"
def weighted_average(items, weights): """ Returns the weighted average of a list of items. Arguments: items is a list of numbers. weights is a list of numbers, whose sum is nonzero. Each weight in weights corresponds to the item in items at the same index. items and weights must be the same length. """ num = 0 denom = 0 assert len(items) > 0 assert len(items) == len(weights) #Verifying the lengths are equal for i in range(0,len(items)): num = num+(items[i]*weights[i]) #Calculate weighted avg denom += weights[i] return num/denom
def rectangle_default(length=7, width=4): """ 7. Function with more than one default input arguments This function demonstrates how a function handles more than one input arguments and returns multiple outputs This function calculates the area and perimeter of a rectangle length: the length of a rectangle, default value is set to 7 width: the width of a rectangle, default value is set to 4 area : the area of the square, must be a positive number perimeter: the perimeter of the square, must be a positive number """ area = length * width perimeter = 2 * (length + width) return area, perimeter
def find_possible_orientations(field, coords, length): """ Find possible orientations for a ship. ARGUMENTS: field - field in which to find orientations coords - origin coords of ship in format [x, y] length - length of ship in format int(length) RETURNS: list of possible orientations(each orientation characterized by vector) """ orientations = [(-1, 0), (0, -1), (1, 0), (0, 1)] possible = [] # for every possible orientation for vctr in orientations: # if outside the field, skip to next orientation if coords[0]+(length-1)*vctr[0] > 9 or coords[1]+(length-1)*vctr[1] > 9: continue if coords[0]+(length-1)*vctr[0] < 0 or coords[1]+(length-1)*vctr[1] < 0: continue # for length of the ship for i in range(length): position = [] position.append(coords[0]+i*vctr[0]) position.append(coords[1]+i*vctr[1]) # if current position occupied, skip to next orientation if not field[position[0]][position[1]]["content"] == "water": break # if length unnoccupied, add vector to possible orientations list if i == length-1: possible.append(vctr) return possible
def gc(i): """Return the Gray code index of i.""" return i ^ (i >> 1)
def logistic(y, t=0, r=1, k=1): """Logistic growth model """ dydt = r*y*(1 - y/k) return dydt
def get_window_start_times(profileDict): """ Gets the times of the start of the sampling windows used in the profiled run Args: profileDict (dict): Dictionary of values representing an Arm MAP profiled run Returns: List of start times of sampling window """ assert isinstance(profileDict, dict) and "samples" in profileDict return profileDict["samples"]["window_start_offsets"]
def filter_groups(lint_list): """Remove lints""" return [x for x in lint_list if x['cellId'] != 'group']
def get_band_names(list_of_contents): """ Will return a dictionary of names of bands :param list_of_contents: :return: dict of bands """ bands = {} for x in list_of_contents: if x.endswith('.tif'): if 'band4' in x: bands['red'] = x if 'band3' in x: bands['green'] = x if 'band2' in x: bands['blue'] = x if 'band5' in x: bands['near_ir'] = x if 'band7' in x: bands['sh_ir2'] = x if 'ndvi' in x: bands['ndvi'] = x return bands
def get_neighbours(x, y, z): """Get neighbours for three dimension point.""" neighbours = [] for nx in (x - 1, x, x + 1): for ny in (y - 1, y, y + 1): for nz in (z - 1, z, z + 1): if (any(num < 0 for num in (nx, ny, nz)) or (x, y, z) == (nx, ny, nz)): continue neighbours.append((nx, ny, nz)) return neighbours
def treatment(pop_input, variables_input, treatment_method_input): """Modular function which receives the treatment method that will be applied for individuals which get out of the function borders.""" return treatment_method_input(pop_input, variables_input)
def delete_resource(payload): """Delete resource""" return {'Dummy': 'ResourceDeleted'}
def in_ranges(char, ranges): """Determines whether the given character is in one of several ranges. :param int char: An integer encoding a Unicode character. :param ranges: A sequence of pairs, where the first element of each pair is the start Unicode character code (including) and the second element of each pair is the end Unicode character code (including) of a range. """ return any(start <= char and char <= stop for start, stop in ranges)
def _calc_histogram_bins(count): """ Calculates experience-based optimal bins number for histogram. There should be enough number in each bin. So we calc bin numbers according to count. For very small count(1 - 10), we assign carefully chosen number. For large count, we tried to make sure there are 9-10 numbers in each bucket on average. Too many bins will slow down performance, so we set max number of bins to 90. Args: count (int): Valid number count for the tensor. Returns: int, number of histogram bins. """ max_bins, max_per_bin = 90, 10 if not count: return 1 if count <= 5: return 2 if count <= 10: return 3 if count <= 880: # note that math.ceil(881/10) + 1 equals 90 return count // max_per_bin + 1 return max_bins
def handle_filename_collision(filename, filenames): """ Avoid filename collision, add a sequence number to the name when required. 'file.txt' will be renamed into 'file-01.txt' then 'file-02.txt' ... until their is no more collision. The file is not added to the list. Windows don't make the difference between lower and upper case. To avoid "case" collision, the function compare C{filename.lower()} to the list. If you provide a list in lower case only, then any collisions will be avoided. @type filename: str @param filename: the filename @type filenames: list or set @param filenames: a list of filenames. @rtype: str @returns: the I{filename} or the appropriately I{indexed} I{filename} >>> handle_filename_collision('file.txt', [ ]) 'file.txt' >>> handle_filename_collision('file.txt', [ 'file.txt' ]) 'file-01.txt' >>> handle_filename_collision('file.txt', [ 'file.txt', 'file-01.txt',]) 'file-02.txt' >>> handle_filename_collision('foo', [ 'foo',]) 'foo-01' >>> handle_filename_collision('foo', [ 'foo', 'foo-01',]) 'foo-02' >>> handle_filename_collision('FOO', [ 'foo', 'foo-01',]) 'FOO-02' """ if filename.lower() in filenames: try: basename, ext=filename.rsplit('.', 1) ext='.'+ext except ValueError: basename, ext=filename, '' i=1 while True: filename='%s-%02d%s' % (basename, i, ext) if filename.lower() not in filenames: break i+=1 return filename
def choose(n, k, d={}): """The binomial coefficient "n choose k". Args: n: number of trials k: number of successes d: map from (n,k) tuples to cached results Returns: int """ if k == 0: return 1 if n == 0: return 0 try: return d[n, k] except KeyError: res = choose(n-1, k) + choose(n-1, k-1) d[n, k] = res return res
def edits1(word): """ Return all strings that are one edits away. """ alphabet = 'abcdefghijklmnopqrstuvwxyz' def splits(word): """ return a list of all possible pairs that the input word is made of """ return [(word[:i], word[i:]) for i in range(len(word)+1)] pairs = splits(word) deletes = [a+b[1:] for (a,b) in pairs if b] transposes = [a+b[1]+b[0]+b[2:] for (a,b) in pairs if len(b) >1] replaces = [a+c+b[1:] for (a,b) in pairs for c in alphabet if b] inserts = [a+c+b for (a,b) in pairs for c in alphabet] return(set(deletes + transposes + replaces + inserts))
def lookup_verbs(roots, spacy_lemmas): """Return a full of list light verbs and all its forms""" def flatten(list_of_lists): "Return a flattened list of a list of lists" return [item for sublist in list_of_lists for item in sublist] verblist = [] for root in roots: verbs = [key for key in spacy_lemmas if spacy_lemmas[key] == root] verbs.append(root) verblist.append(verbs) return flatten(verblist)
def locate_candidate_recommendation(recommendation_list): """ Locates a candidate recommendation for workflow testing in our recommendation list. Args: recommendation_list (list[Recommendation]): List of possible recommendations to be our candidate. Returns: Recommendation: A candidate recommendation for testing. Looks for a recommendation with NEW status by preference, then REJECTED, and then ACCEPTED. If none is found, returns None. """ for initial_status in ['NEW', 'REJECTED', 'ACCEPTED']: rec_candidates = [rec for rec in recommendation_list if rec.rule_type == 'reputation_override' and rec.workflow_.status == initial_status] if len(rec_candidates) > 0: return rec_candidates[0] return None
def ipc_error_response(resp_data): """Make error response.""" response = ("error", resp_data) return response
def flux(rho, u_max, rho_max): """ Computes the traffic flux F = V * rho. Parameters ---------- rho : numpy.ndarray Traffic density along the road as a 1D array of floats. u_max : float Maximum speed allowed on the road. rho_max : float Maximum car density allowed on the road. Returns ------- F : numpy.ndarray The traffic flux along the road as a 1D array of floats. """ F = rho * u_max * (1.0 - rho / rho_max) return F
def pick_one(iterable): """ Helper function that returns an element of an iterable (it the iterable is ordered this will be the first element). """ it = iter(iterable) return next(it)
def extract_fixed_price(fixed_payment_type: str) -> int: """ Returns the fixed price as int for message_printer() if-statement """ # Accounts for job_post["Budget"] == "$1,234" if "," in fixed_payment_type: return int((fixed_payment_type).replace(",", "").lstrip("$")) # Accounts for job_post["Budget"] == "$XK" or "$X.YK" elif "K" in fixed_payment_type: if "." in fixed_payment_type: return int((float(fixed_payment_type.lstrip("$").rstrip("K"))) * 1000) else: return int(fixed_payment_type.lstrip("$").rstrip("K")) * 1000 # Accounts for job_post["Budget"] == "$X" else: return int(fixed_payment_type.lstrip("$"))
def normalize_name(name): """Normalizes a transformice nickname.""" if name[0] == "+": name = "+" + (name[1:].capitalize()) else: name = name.capitalize() if "#" not in name: name += "#0000" return name
def get_relation_phrases(relations): """ :param relations: yaml dict of relation to partial phrases :return: a mapping from relation to all possible phrases """ rel_to_phrases = {} for key, val in relations.items(): for gender in ['male', 'female']: rel = val[gender]['rel'] rel_to_phrases[(key, rel)] = val[gender]['p'] return rel_to_phrases
def guess_ip_version(ip_string): """ Guess the version of an IP address, check its validity \param ip_string A string containing an IP address \return The version of the IP protocol used (int(4) for IPv4 or int(6) for IPv6, int(0) otherwise) """ import socket try: ipv4_buffer = socket.inet_pton(socket.AF_INET, ip_string) return 4 except socket.error: pass if socket.has_ipv6: try: ipv6_buffer = socket.inet_pton(socket.AF_INET, ip_string) return 6 except socket.error: pass return 0
def create_dictionary(all_groups, sub_keys): """ Create nested dictionary - each group within a file and its properties. Parameters ---------- all_groups : List, groups within .h5 file. sub_keys : List, keys for each group within .h5 file. Returns ------- dictionary : Dictionary in format: {Group1: [key, Key ...], Group2: [Key, Key ...]}. """ dictionary = {group: [key for key in sub_keys[i]] for i, group in enumerate(all_groups)} return dictionary
def calculate_sample_required(conc1, conc2, vol2): """Classic C1V1 = C2V2. Calculates V1. All arguments should be floats. """ if conc1 == 0.0: conc1 = 0.000001 # don't want to divide by zero :) return (conc2 * vol2) / conc1
def multv(A, V, MOD): """ produit matrice/vecteur: A * V """ a00, a10, a01, a11 = A b0, b1 = V return [(a00 * b0 + a10 * b1) % MOD, (a01 * b0 + a11 * b1) % MOD]
def rk4_step(f, x0, t0, t1): """ One time step of Runge-Kutta method f : function dx_dt(t0, x0) x0 : initial condition t0 : this step time t1 : next step time """ delta_t = (t1 - t0) delta_t_half = delta_t * 0.5 t_half = t0 + delta_t_half # Step 1 s1 = f(t0, x0) # Step 2 s2 = f(t_half, x0 + s1 * delta_t_half) # Step 3 s3 = f(t_half, x0 + s2 * delta_t_half) # Step 4 s4 = f(t1, x0 + s3 * delta_t) # Step 5 s = (1.0 / 6.0) * (s1 + (s2 + s3) * 2 + s4) # Step 6 x1 = x0 + s * delta_t return x1
def nside2npix(nside): """ Convert healpix resolution (nside) to the number of healpix pixels in a full-sky map. """ return 12 * nside * nside
def _check_n_components(n_features, n_components): """Checks that n_components is less than n_features and deal with the None case""" if n_components is None: return n_features if 0 < n_components <= n_features: return n_components raise ValueError('Invalid n_components, must be in [1, %d]' % n_features)
def Newcombprecangles(epoch1, epoch2): """ ---------------------------------------------------------------------- Purpose: Calculate precession angles for a precession in FK4, using Newcombs method (Woolard and Clemence angles) Input: Besselian start epoch1 and Besselian end epoch2 Returns: Angles zeta, z, theta in degrees Reference: ES 3.214 p.106 Notes: Newcomb's precession angles for old catalogs (FK4), see ES 3.214 p.106 Input are Besselian epochs! Adopted accumulated precession angles from equator and equinox at B1950 to 1984 January 1d 0h according to ES (table 3.214.1, p 107) are: zeta=783.7092, z=783.8009 and theta=681.3883 The Woolard and Clemence angles (derived in this routine) are: zeta=783.70925, z=783.80093 and theta=681.38830 (same ES table) This routine found (in seconds of arc): zeta,z,theta = 783.709246271 783.800934641 681.388298284 for t1 = 0.1 and t2 = 0.133999566814 using the lines in the example Examples: >>> b1 = 1950.0 >>> b2 = celestial.epochs("F1984-01-01")[0] >>> print [x*3600 for x in celestial.Newcombprecangles(be1, be2)] [783.70924627097793, 783.80093464073127, 681.38829828393466] ---------------------------------------------------------------------- """ t1 = (epoch1-1850.0)/1000.0 #1000 tropical years t2 = (epoch2-1850.0)/1000.0 tau = t2 - t1 d0 = 23035.545; d1 = 139.720; d2 = 0.060; d3 = 30.240; d4 = -0.27; d5 = 17.995 a0 = d0 + t1*(d1+d2*t1); a1 = d3 + d4*t1; a2 = d5 zeta_a = tau*(a0+tau*(a1+tau*a2)) d0 = 23035.545; d1 = 139.720; d2 = 0.060; d3 = 109.480; d4 = 0.39; d5 = 18.325 a0 = d0 + t1*(d1+d2*t1); a1 = d3 + d4*t1; a2 = d5 z_a = tau*(a0+tau*(a1+tau*a2)) d0 = 20051.12; d1 = -85.29; d2 = -0.37; d3 = -42.65; d4 = -0.37; d5 = -41.80 a0 = d0 + t1*(d1+d2*t1); a1 = d3 + d4*t1; a2 = d5 theta_a = tau*(a0+tau*(a1+tau*a2)) # Return values in degrees return zeta_a/3600.0, z_a/3600.0, theta_a/3600.0
def polygon_clip(poly, clip_poly): """ Computes the intersection of an arbitray polygon with a convex clipping polygon, by implementing Sutherland-Hodgman's algorithm for polygon clipping. :param poly: list of tuples, representing the arbitrary polygon :param clip_poly: list of tuples, representing the convex clipping polygon, given in counter-clockwise order :return: list of tuples, representing the intersection / clipped polygon """ def is_inside(r, e): """ Returns `True` if the point `r` lies on the inside of the edge `e = (p,q)`. To do so, it computes the z-coordinate of the cross product of the two vectors `[pq]` & `[pr]`. If the result is 0, the points are collinear. If it is positive, the three points constitute a 'left turn' (counter-clockwise), otherwise a 'right turn' (clockwise). """ p = e[0] q = e[1] return (q[0] - p[0]) * (r[1] - p[1]) - (r[0] - p[0]) * (q[1] - p[1]) > 0 def compute_intersection(e1, e2): """ Computes the intersection point of the edges `e1` & `e2`. """ # x-y-coordinates of the four points x1, y1 = e1[0][0], e1[0][1] x2, y2 = e1[1][0], e1[1][1] x3, y3 = e2[0][0], e2[0][1] x4, y4 = e2[1][0], e2[1][1] # help variables to reduce computations dx12 = x1 - x2 dx34 = x3 - x4 dy12 = y1 - y2 dy34 = y3 - y4 # nominator part 1 and 2 n1 = x1 * y2 - y1 * x2 n2 = x3 * y4 - y3 * x4 # denominator d = 1.0 / (dx12 * dy34 - dy12 * dx34) # intersection point return (n1 * dx34 - dx12 * n2) * d, (n1 * dy34 - dy12 * n2) * d output_poly = poly c1 = clip_poly[-1] # clip poly against each edge in clip_poly for c2 in clip_poly: # input is the clipped output from the previous run input_poly = output_poly # we build the new output from scratch output_poly = [] clip_edge = (c1, c2) p1 = input_poly[-1] # go over each poly edge individually for p2 in input_poly: poly_edge = (p1, p2) # add (and implicitly remove) points depending on the four cases if is_inside(p2, clip_edge): if not is_inside(p1, clip_edge): output_poly.append(compute_intersection(poly_edge, clip_edge)) output_poly.append(p2) elif is_inside(p1, clip_edge): output_poly.append(compute_intersection(poly_edge, clip_edge)) # go to next poly edge p1 = p2 # no intersection if not output_poly: return [] # go to next clip edge c1 = c2 return output_poly
def kHat(c, ell, em, ess=-2): """ Compute diagonal elements of sparse matrix to be solved. Inputs: c (float): a * omega ell (int): swsh mode number em (int): mode number ess (int) [-2]: spin number Returns: kHat (float): diagonal element """ # print(ell) # print(np.where(ell == 0)[0]) if ell == 0 and em == 0: return c ** 2 / 3 else: ell2 = ell * ell em2 = em * em ell3 = ell2 * ell ess2 = ess * ess c2 = c * c return (-(ell*(1 + ell)) + (2*em*ess2*c)/(ell + ell2) + ((1 + (2*(ell + ell2 - 3*em2)*(ell + ell2 - 3*ess2))/ (ell*(-3 + ell + 8*ell2 + 4*ell3)))*c2)/3.)
def prune_empty(row): """ prune attributes whose value is None """ new_row = {} for k in row: if row[k]: new_row[k] = row[k] return new_row
def test_lambda(n): """ >>> [f() for f in test_lambda(3)] [0, 1, 2] """ return [lambda v=i: v for i in range(n)]
def flt(val): """ Returns ------- returns a float value """ try: return float(val) except: return float(0)
def getdate(targetconnection, ymdstr, default=None): """Convert a string of the form 'yyyy-MM-dd' to a Date object. The returned Date is in the given targetconnection's format. Arguments: - targetconnection: a ConnectionWrapper whose underlying module's Date format is used - ymdstr: the string to convert - default: The value to return if the conversion fails """ try: (year, month, day) = ymdstr.split('-') modref = targetconnection.getunderlyingmodule() return modref.Date(int(year), int(month), int(day)) except Exception: return default
def is_float(s): """ Returns True if string 's' is float and False if not. 's' MUST be a string. :param s: string with number :type s: str :rtype: bool """ try: float(s) return True except ValueError: return False
def getAliasString(emailList): """ Function to extract and return a list (String, comma separated) of Mamga aliases from provided email list """ toAlias = '' for toAdd in emailList: toA = toAdd.split('@molten-magma.com')[0] if toAlias == '': toAlias = '%s' %(toA) else: toAlias = '%s,%s' %(toAlias,toA) return toAlias
def reverse_list(in_list): """Return list in reversed index order""" return list(reversed(in_list))
def lever_pressing(eventcode, lever1, lever2=False): """ :param eventcode: list of event codes from operant conditioning file :param lever1: eventcode for lever pressing or :param lever2: optional parameter for second lever eventcode if two levers are used :return: count of first lever presses, second lever presses, and total lever presses, as int """ lever1_presses = eventcode.count(lever1) if lever2: lever2_presses = eventcode.count(lever2) else: lever2_presses = 0 total_lever_presses = lever1_presses + lever2_presses return lever1_presses, lever2_presses, total_lever_presses
def check_theme(theme, themes): """Check if theme is legit. """ if theme in themes: return theme print(('(!) Theme "{0}" not in {1}, ' 'using "{2}"').format(theme, themes, themes[0])) return themes[0]
def flat_list(l): """ Convert a nested list to a flat list """ try: return [item for sublist in l for item in sublist] except: return l
def deepupdate_dict(target, update): """ Updates dicts and calls itself recursively if a list or dict is encountered to perform updating at nesting levels instead of just the first one. Does not work with tuples. """ for k, v in update.items(): if isinstance(v, list): target[k] = target.get(k, []) + v elif isinstance(v, dict): target[k] = deepupdate_dict(target.get(k, {}), v) else: target[k] = v return target
def generate_power_sets(sample_list): """Generate all possible subsets from the `sample_list`. Parameters ---------- sample_list : [int] Returns ------- [[int]] All possible subsets """ num_of_combinations = pow(2, len(sample_list)) all_sets = [] for element_number in range(num_of_combinations): set_for_number = [] for binary_num in range(len(sample_list)): if (1 << binary_num) & element_number: set_for_number.append(sample_list[binary_num]) all_sets.append(set_for_number) return all_sets
def classify(gc_content): """ gc_content - a number representing the GC content Returns a string representing GC Classification. Must return one of these: "low", "moderate", or "high" """ classification = "high" if gc_content < .4: classification = "low" elif gc_content <= .6: classification = "moderate" return classification
def df_string(*args): """ Creates DF command line string """ return ('df', ) + args
def get_vcf(config, var_caller, sample): """ input: BALSAMIC config file output: retrieve list of vcf files """ vcf = [] for v in var_caller: for s in sample: vcf.append(config["vcf"][v]["type"] + "." + config["vcf"][v]["mutation"] + "." + s + "." + v) return vcf
def show_popover_descripcion(descripcion): """ mostrar un pop up con la descripcion de las notificaciones """ return {'descripcion': descripcion}
def report_spdu(spdu_dict: dict) -> str: """A testing/debugging function that returns a printable report of SPDU contents after parsing :param spdu_dict: a dictionary containing SPDU fields such as returned from parse_received_spdu() :type spdu_dict: dict :return: a string representation of the SPDU fields :rtype str """ report = "" for key in spdu_dict.keys(): report += key + "\t\t\t" + str(spdu_dict[key]) + "\n" return report
def generate_city_code(citi): """ A dictionary of city codes used by megabus to identify each city. :return: The proper city code, string. """ citi = citi.strip() # Strips the city provided of any extra spaces citi = citi.upper() citi_codes = { 'ALBANY, NY': '89', 'AMHERST, MA': '90', 'ANN ARBOR, MI': '91', 'ATLANTIC CITY, NJ': '92', 'BINGHAMTON, NY': '93', 'BOSTON, MA': '94', 'BUFFALO, NY': '95', 'BURLINGTON, VT': '96', 'CAMDEN': '97', 'CHAMPAIGN, IL': '98', 'CHARLOTTE, NC': '99', 'CHICAGO, IL': '100', 'CHRISTIANSBURG, VA': '101', 'CINCINNATI, OH': '102', 'CLEVELAND, OH': '103', 'COLUMBIA, MO': '104', 'COLUMBUS, OH': '105', 'DES MOINES, IA': '106', 'DETROIT, MI': '107', 'ERIE, PA': '108', 'FREDERICK, MD': '109', 'HAMPTON, VA': '110', 'HARRISBURG, PA': '111', 'HARTFORD, CT': '112', 'HOLYOKE, CT': '113', 'HYANNIS, MA': '114', 'INDIANAPOLIS, IN': '115', 'IOWA CITY, IA': '116', 'KANSAS CITY, MO': '117', 'KNOXVILLE, TN': '118', 'MADISON, WI': '119', 'MEMPHIS, TN': '120', 'MILWAUKEE, WI': '121', 'NEW HAVEN, CT': '122', 'NEW YORK, NY': '123', 'NIAGARA FALLS, ON': '124', 'NORMAL, IL': '125', 'OMAHA, NE': '126', 'PHILADELPHIA, PA': '127', 'PITTSBURGH, PA': '128', 'PORTLAND, ME': '129', 'PROVIDENCE, RI': '130', 'DURHAM, NC': '131', 'RICHMOND, VA': '132', 'RIDGEWOOD, NJ': '133', 'ROCHESTER, NY': '134', 'SECAUCUS, NJ': '135', 'ST LOUIS, MO': '136', 'STATE COLLEGE, PA': '137', 'STORRS, CT': '138', 'SYRACUSE, NY': '139', 'TOLEDO, OH': '140', } return citi_codes[citi]
def move1(course): """Meh >>> move1(EX_INPUT.split('\\n')) (15, 10, 150) """ horiz = 0 depth = 0 for mvt in course: if not len(mvt): continue where, count = mvt.split(" ") count = int(count) if where == "forward": horiz += count elif where == "down": depth += count elif where == "up": depth -= count return (horiz, depth, horiz * depth)
def calculate_initial_position_of_sliding_window(num_seeds): """ Calculate the initial position where the sliding position will start its calculations. """ # Calculate the initial position of the sliding window: # We know that the left part of the first interval in the sliding window is: # i - num_seeds / 2 = 1 # So, if we want to know i (the initial position) we have to calculate: # i = 1 + num_seeds / 2 initial_position = 1 + int( float(num_seeds) / float(2) ) #print('Initial position: {}'.format(initial_position)) return initial_position
def get_selected_sentences_with_different_vocabulary(sorted_score_index, sorted_indeces_no_predicted_chunks, step_size, majority_category, inactive_learning, prefer_predicted_chunks): """ Help function to do the final selection of samples. """ #print("sorted_score_index", sorted_score_index) #print("sorted_indeces_no_predicted_chunks", sorted_indeces_no_predicted_chunks) if not prefer_predicted_chunks: sorted_score_index = sorted_score_index + sorted_indeces_no_predicted_chunks if inactive_learning: print("Running in reversed mode, selecting the samples for which the learning is most certain.") sorted_score_index = sorted(sorted_score_index, reverse=True) else: # This is the the option that is typically used. The one in which active learning is achieved. sorted_score_index = sorted(sorted_score_index) #print("sorted_score_index", sorted_score_index) """ print("The best candidates before word spread is taken into account") for el in sorted_score_index[:10]: print(el) """ indeces_to_use = [] indeces_not_to_use = [] predicted_words = set() already_used_sentence = set() for (score, index, predicted, sentence) in sorted_score_index: current_sentence = " ".join(sentence) sentence_has_already_used_word = False if current_sentence in already_used_sentence: similar_sentence_has_alread_been_picked = True print("Sentence already used") print("Current sentence") else: similar_sentence_has_alread_been_picked = False already_used_sentence.add(current_sentence) for i, el in enumerate(predicted): if el != majority_category: predicted_word = sentence[i] if predicted_word in predicted_words: sentence_has_already_used_word = True predicted_words.add(predicted_word) if not sentence_has_already_used_word: indeces_to_use.append(index) else: indeces_not_to_use.append(index) if len(indeces_to_use) >= step_size: break print("predicted_words", predicted_words) if len(indeces_to_use) < step_size: #if there weren't enough uncertain with large word spread, take those that have been filtered out print("Can't return samples with the requested word spread") print("Filtered out indeces, that will be used anyway, therefore:") print(step_size - len(indeces_to_use)) print(indeces_not_to_use[:step_size - len(indeces_to_use)]) indeces_to_use = indeces_to_use + indeces_not_to_use[:step_size - len(indeces_to_use)] #first_indeces = [index for (score, index, predicted, sentence) in sorted_score_index[:step_size]] print("indeces_to_use", indeces_to_use) # Only for printing information if prefer_predicted_chunks: indeces_to_use = indeces_to_use + [el[1] for el in sorted_indeces_no_predicted_chunks] print("The best candidates without a predicted chunk") print("indeces_to_use with chunks all", indeces_to_use) return indeces_to_use
def comma_separated_list(value): """ Configuration-friendly list type converter. Supports both list-valued and string-valued inputs (which are comma-delimited lists of values, e.g. from env vars). """ if isinstance(value, list): return value if value == "": return [] return value.split(",")
def cross(A, B): """Calculate the cross product of two arrays. Args: A(list) - the left side of the cross product B(list) - the right side of the cross product Returns: A list containing all possible combinations of elements from A and B """ return [ s+t for s in A for t in B ]
def get_head(page, marker): """ Returns page content before the marker """ if page is None: return None if marker in page: return page.split(marker,1)[0]
def get_uce_name(header): """use own function vs. import from match_contigs_to_probes - we don't want lowercase""" return header.lstrip('>').split(' ')[0].split('_')[0]
def cvtRange(x, in_min, in_max, out_min, out_max): """ Convert a value, x, from its old range of (in_min to in_max) to the new range of (out_min to out_max) """ return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def unique(x): """Convert a list in a unique list.""" return list(set(x))
def tenth(raw_table, base_index): """ Word value divide by ten """ raw_value = raw_table[base_index] if raw_value == 0xFFFF: return None sign = 1 if raw_value & 0x8000: sign = -1 return sign * (raw_value & 0x7FFF) / 10
def combine_dictionaries( dictionaries): """Utility for merging entries from all dictionaries in `dictionaries`. If there are multiple dictionaries with the same key, the entry from the latest dictionary is used for that key. Args: dictionaries: Iterable of dictionaries to combine entries of. Returns: A dictionary with the combined results. """ result = {} for dictionary in dictionaries: result.update(dictionary) return result
def fetch_token_mock(self, token_url=None, code=None, authorization_response=None, body='', auth=None, username=None, password=None, method='POST', timeout=None, headers=None, verify=True, proxies=None, **kwargs): """Mock token fetching api call.""" token = { "orcid": "123", "name": "ros", "access_token": "xyz", "refresh_token": "xyz", "scope": ["/activities/update", "/read/limited"], "expires_in": "12121" } return token
def compress(uncompressed): # uncompressed is a string """Compress a string to a list of output symbols.""" # Build the dictionary. dict_size = 256 dictionary = {chr(i): i for i in range(dict_size)} w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) # Add wc to the dictionary. dictionary[wc] = dict_size dict_size += 1 w = c # Output the code for w. if w: result.append(dictionary[w]) return result
def birth_x(well): """If the chosen well is empty, will create an xantophore""" if well == 'S': return 'X' else: return well
def inRegion(reg, site): """given a region tuple, (start, end) returns True if site is >= start <= end""" return site >= reg[0] and site <= reg[1]
def intcode_parse(code): """Accepts intcode. Parses intcode and returns individual parameters. """ actual_code = code % 100 parameter_piece = code - actual_code parameter_piece = parameter_piece // 100 parameter_code_list = [] while parameter_piece > 0: parameter_code_list.append(parameter_piece % 10) parameter_piece = parameter_piece // 10 return (actual_code, parameter_code_list)
def calculate_m(q_c1ncs): """ m parameter from CPT, Eq 2.15b """ m = 1.338 - 0.249 * q_c1ncs ** 0.264 if q_c1ncs >= 254: m = 0.263823991466759 if q_c1ncs <= 21: m = 0.781756126201587 return m
def __is_dead(ref): """Return ``True`` if the weak reference `ref` no longer points to an in-memory object. """ return ref() is None
def clear(x, y, player, game_map): """ check if cell is safe to move in """ # if there is no shipyard, or there is player's shipyard # and there is no ship if ((game_map[x][y]["shipyard"] == player or game_map[x][y]["shipyard"] == None) and game_map[x][y]["ship"] == None): return True return False
def strongly_connected_components(graph): """ Tarjan's Algorithm (named for its discoverer, Robert Tarjan) is a graph theory algorithm for finding the strongly connected components of a graph. graph should be a dictionary mapping node names to lists of successor nodes. Based on: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm By Dries Verdegem (assumed public domain) """ index_counter = [0] stack = [] lowlinks = {} index = {} result = [] def strongconnect(node): # set the depth index for this node to the smallest unused index index[node] = index_counter[0] lowlinks[node] = index_counter[0] index_counter[0] += 1 stack.append(node) # Consider successors of `node` try: successors = graph[node] except: successors = [] for successor in successors: if successor not in lowlinks: # Successor has not yet been visited; recurse on it strongconnect(successor) lowlinks[node] = min(lowlinks[node],lowlinks[successor]) elif successor in stack: # the successor is in the stack and hence in the current # strongly connected component (SCC) lowlinks[node] = min(lowlinks[node],index[successor]) # If `node` is a root node, pop the stack and generate an SCC if lowlinks[node] == index[node]: connected_component = [] while True: successor = stack.pop() connected_component.append(successor) if successor == node: break component = tuple(connected_component) # storing the result result.append(component) for node in graph: if node not in lowlinks: strongconnect(node) return result
def druckumrechner(inHG): """ Umwandlung von inHG in mBar :param inHG: int, float or None :return: float or None """ if isinstance(inHG, (int, float)): mbar = inHG * 33.86389 mbar = round(mbar, 2) return mbar else: return None
def number_of_ways_for_the_frog_to_jump_n_feet(n): """number of ways for the frog to jump n feet :param n: num of feets :return: """ global total if n == 0: return 1 if n < 0: return 0 return number_of_ways_for_the_frog_to_jump_n_feet(n - 1) + number_of_ways_for_the_frog_to_jump_n_feet(n - 2)
def location_name(country=None, state=None): """return the name of the country and/or state used in the current filter""" locations = [] if state: locations.append(state) if country: locations.append(country) return " - ".join(locations) if len(locations) > 0 else "everywhere"
def is_subpath(x, y): """Returns True if x is a subpath of y, otherwise return False. Example: is_subpath('/a/', '/b/') = False is_subpath('/a/', '/a/') = True is_subpath('/a/abc', '/a/') = True is_subpath('/a/', '/a/abc') = False """ if y.endswith("/"): return x.startswith(y) or x == y[:-1] else: return x.startswith(y + "/") or x == y
def sanitize_name(name: str): """ Sanitize the callsites for general dataset. """ ret_name = "" if name is None: ret_name = "Unknown" return ret_name if "/" in name: name_split = name.split("/") ret_name = name_split[len(name_split) - 1] else: ret_name = name return ret_name
def format_nri_list(data): """Return NRI lists as dict with names or ids as the key.""" if not data: return None info = {} for item in data: if item.get("name") is not None: key = item.pop("name") elif item.get("id") is not None: key = item.pop("id") else: return None info[key] = item return info
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy. Credit: http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression""" z = x.copy() z.update(y) return z
def validate_tag(tag): """ Chceks if tag is valid. Tag should not be empty and should start with '#' character """ tag = tag.strip().lower() return len(tag) > 1 and tag.startswith("#")
def get_public_members(obj): """ Retrieves a list of member-like objects (members or properties) that are publically exposed. :param obj: The object to probe. :return: A list of strings. """ return {attr: getattr(obj, attr) for attr in dir(obj) if not attr.startswith("_") and not hasattr(getattr(obj, attr), '__call__')}
def cast_string_to_int_error(what): """ Retrieves the "can not cast from string to integer" error message. :param what: Environment variable name. :return: String - Can not cast from string to integer. """ return "ERROR: " + what + " value cannot be cast from string to int"
def column_names(row, colnames): """ Pair items in row with corresponding column name. Return dictionary keyed by the column names. """ mapped = {col_name: val for val, col_name in zip(row, colnames)} return mapped
def get_bucket_name(gem_group, barcode, num_buckets): """ gem_group - integer barcode - barcode sequence num_buckets - desired number of buckets for gem group """ # NOTE: Python modulo returns non-negative numbers here, which we want return str(gem_group) + '-' + str(hash(barcode) % num_buckets)
def make_table_options(param): """make table param of Embedding tables Args: param (dict or list): param can be initializer or list of column_option. initializer can be made by make_uniform_initializer or make_normal_initializer, column options can be made by make_column_options Returns: dict: table param of Embedding tables For example: .. code-block:: python >>> import oneflow as flow >>> initializer = flow.one_embedding.make_uniform_initializer(low=-scale, high=scale) >>> table1 = flow.one_embedding.make_table_options(initializer) >>> table2 = flow.one_embedding.make_table_options(initializer) >>> tables = [table1, table2] >>> # pass the tables to the "tables" param of flow.one_embedding.MultiTableEmbedding or flow.one_embedding.MultiTableMultiColumnEmbedding >>> # ... """ if isinstance(param, dict): table = {"initializer": param} elif isinstance(param, (list, tuple)): table = {"columns": param} else: raise ValueError("param must be initializer or columns") return table
def power_bin_recursive(base, exp): """Funkce vypocita hodnotu base^exp pomoci rekurzivniho algoritmu v O(log(exp)). Staci se omezit na prirozene hodnoty exp. """ if exp == 0: return 1 if exp % 2 == 1: return base * power_bin_recursive(base * base, exp // 2) return power_bin_recursive(base * base, exp // 2)
def mass_to_richness(mass, norm=2.7e13, slope=1.4): """Calculate richness from mass. Mass-richness relation assumed is: mass = norm * (richness / 20) ^ slope. Parameters ---------- mass : ndarray or float Cluster mass value(s) in units of solar masses. norm : float, optional Normalization of mass-richness relation in units of solar masses, defaults to 2.7e13. slope : float, optional Slope of mass-richness relation in units of solar masses, defaults to 1.4. Returns ---------- ndarray or float Cluster richness(es), of same type as mass. See Also ---------- richness_to_mass : The inverse of this function. """ richness = 20. * (mass / norm)**(1. / slope) return richness
def trim_string(text: str, max_length: int = 200, ellipsis: str = "...") -> str: """ If text is longer than max_length then return a trimmed string. """ assert max_length >= len(ellipsis) if len(text) > max_length: return text[: max_length - len(ellipsis)] + ellipsis else: return text
def _escape_column(column): """ transfer columns, return tuple, such as ('a', 'b', 'c'), when constructing SQL, direct use the__ str__ () method """ if not len(column): raise ValueError('Field cannot be empty') if len(column) == 1: column = column[0] if isinstance(column, str): column = tuple(o.strip(' ') for o in column.split(',')) return column if isinstance(column, (tuple, list)): return tuple(o.strip(' ') for o in column) raise ValueError('column error') return column
def center(numpoints, refcoords): """Center a molecule using equally weighted points. :param numpoints: number of points :type numpoints: int :param refcoords: list of reference coordinates, with each set a list of form [x,y,z] :type refcoords: [[float, float, float]] :return: (center of the set of points, moved refcoords relative to refcenter) """ relcoords = [] refcenter = [0.0 for _ in range(3)] for i in range(numpoints): refcenter[0] += refcoords[i][0] refcenter[1] += refcoords[i][1] refcenter[2] += refcoords[i][2] for i in range(3): refcenter[i] = refcenter[i] / numpoints for i in range(numpoints): relcoords.append([]) relcoords[i].append(refcoords[i][0] - refcenter[0]) relcoords[i].append(refcoords[i][1] - refcenter[1]) relcoords[i].append(refcoords[i][2] - refcenter[2]) return refcenter, relcoords
def replace(txt, start, end, repltxt): """Replaces the part of txt between index start and end with repltxt""" return txt[:start] + repltxt + txt[end+1:]
def vec_is_void(a): """ Check whether a given vector is empty A vector is considered "void" if it is None or has no elements. Parameters ---------- a: list[] The vector to be checked Returns ------- bool True if the vector is empty, False otherwise """ return a is None or len(a) == 0
def float_or_string(arg): """Force float or string """ try: res = float(arg) except ValueError: res = arg return res