content
stringlengths
42
6.51k
def _extract_url_and_sha_from_deps_entry(entry): """Split a DEPS file entry into a URL and git sha.""" assert 'url' in entry and 'rev' in entry, 'Unexpected format: %s' % entry url = entry['url'] sha = entry['rev'] # Strip unnecessary ".git" from the URL where applicable. if url.endswith('.git'): url =...
def all_filled(board): """ Returns True if all board is filled, False otherwise. """ for i in range(len(board)): if board[i].count(None): return False return True
def hours_minutes_seconds( time_spec ): """ Interprets a string argument as a time of day specification and returns a string "hh:mm:ss" in 24 hour clock. The string can contain am, pm, and colons, such as "3pm" or "21:30". If the interpretation fails, an exception is raised. """ orig = tim...
def get_box_coordinates(box,img_shape): """#convert model coordinates format to (xmin,ymin,width,height) Args: box ((xmin,xmax,ymin,ymax)): the coordinates are relative [0,1] img_shape ((height,width,channels)): the frame size Returns: (xmin,ymin,width,height): (xmin,ymin,width,hei...
def flipx(tile): """ Return a copy of the tile, flipped horizontally """ return list(reversed(tile))
def is_iterable(obj): """ Returns True if 'obj' is iterable and False otherwise. We check for __iter__ and for __getitem__ here because an iterable type must, by definition, define one of these attributes but is not required or guarenteed to define both of them. For more information on iterable typ...
def get_ext(file): """Return the extension of the given filename.""" return file.split('.')[-1]
def factorial(n): """ returns factorial of n """ if n < 0: return None if n < 2: return 1 return n * factorial(n - 1)
def Fibonacci(n): """ Returns the nth term of the Fibonacci Sequence n is zero based indexed """ if n < 0: raise Exception("Invalid Argument") elif n < 2: return n else: return Fibonacci(n-1) + Fibonacci(n-2)
def unpackLine(string, separator="|"): """ Unpacks a string that was packed by packLine. """ result = [] token = None escaped = False for char in string: if token is None: token = "" if escaped and char in ('\\', separator): token += char escaped =...
def convert_iob_to_bio(seq): """Convert a sequence of IOB tags to BIO tags. The difference between IOB and BIO (also called IOB2) is that in IOB the B- prefix is only used to separate two chunks of the same type while in BIO the B- prefix is used to start every chunk. :param seq: `List[str]` The l...
def get_iou(bboxes1, bboxes2): """ Adapted from https://gist.github.com/zacharybell/8d9b1b25749fe6494511f843361bb167 Calculates the intersection-over-union of two bounding boxes. Args: bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2. bbox2 (numpy.array, list of fl...
def get_usa_veh_id(acc_id, vehicle_index): """ Returns global vehicle id for USA, year and index of accident. The id is constructed as <Acc_id><Vehicle_index> where Vehicle_index is three digits max. """ veh_id = acc_id * 1000 veh_id += vehicle_index return veh_id
def thresholdClassify(sim_vec_dict, sim_thres): """Method to classify the given similarity vector dictionary with regard to a given similarity threshold (in the range 0.0 to 1.0), where record pairs with an average similarity of at least this threshold are classified as matches and all others as no...
def is_gerrit_issue(issue): """Returns true, if the issue is likely legacy Gerrit issue. Doesn't do database requests and guesses based purely on issue. """ # Gerrit CQ used to post urls for Gerrit users usign same code as Rietveld. # The only easy way to distinguish Rietveld from Gerrit issue, is that # a...
def max_clique(dic): """Return the maximum clique in the given graph represented by dic. See readme for detailed description. Args: dic: dictionary{int : {'name' : str, 'edges' : a set of int}} Returns: list of int """ max_c = [] V = dic.keys() for v...
def find_infinite_loop(instructions: list) -> tuple: """Find the infinite loop in the program, and return the accumulator :param instructions: List of instructions in the program :return: Value of the accumulator, and a flag """ accumulator = 0 line = 0 line_history = [] flag = -1 w...
def decimal_to_hexadecimal(decimal: int)-> str: """Convert a Decimal Number to a Hexadecimal Number.""" if not isinstance(decimal , int): raise TypeError("You must enter integer value") if decimal == 0: return '0x0' is_negative = '-' if decimal < 0 else '' decimal = abs(decimal) ...
def human_format(num): """Returns a formated number depending on digits (e.g., 30K instead of 30,000)""" num = float("{:.2g}".format(num)) magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 return "{}{}".format( "{:f}".format(num).rstrip("0").rstrip("."), ...
def kelvin(value: float, target_unit: str) -> float: """ Utility function for Kelvin conversion in Celsius or in Fahrenheit :param value: temperature :param target_unit: Celsius, Kelvin or Fahrenheit :return: value converted in the right scale """ if target_unit == "C": # Convert in...
def _decode(x): """ Decoding input, if needed """ try: x = x.decode('utf-8') except AttributeError: pass return x
def uniquify(lst): """ Make the elements of a list unique by inserting them into a dictionary. This must not change the order of the input lst. """ dct = {} result = [] for k in lst: if k not in dct: result.append(k) dct[k] = 1 return result
def lifo_pre_sequencing(dataset, *args, **kwargs): """ Generates an initial job sequence based on the last-in-first-out dispatching strategy. The job sequence will be feed to the model. """ sequence = [] for job in dataset.values(): sequence.insert(0, job) return sequence
def derive_queue_id_from_dscp(dscp): """ Derive queue id form DSCP using following mapping DSCP -> Queue mapping 8 0 5 2 3 3 4 4 46 5 48 6 Rest 1 """ dscp_...
def is_match(item, pattern): """implements DP algorithm for string matching""" length = len(item) if len(pattern) - pattern.count('*') > length: return False matches = [True] + [False] * length for i in pattern: if i != '*': for index in reversed(range(length)): ...
def bit_count(int_no): """Computes Hamming weight of a number.""" c = 0 while int_no: int_no &= int_no - 1 c += 1 return c
def _get_data(title, func, dest): """Populate dest with data from the given function. Args: title: The name of the data func: The function which will return the data dest: a dict which will store the data Returns: dest: The modified destination dict """ # Get inter...
def duration_string(duration: float) -> str: """Convert duration in seconds to human readable string. Parameters ---------- duration : float duration in seconds Returns ------- str human readable duration string """ if duration < 60: return f"{duration:.1f} ...
def multi_getattr(obj, attr, default=None): """ Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is equivalent to x.a.b.c.d. When a default argument is given, it is returned when any attribute in the chain doesn't exist; without it, an exception is raised when a missing attribute is...
def _asciiz_to_bytestr(a_bytestring): """Transform a null-terminated string of any length into a Python str. Returns a normal Python str that has been terminated. """ i = a_bytestring.find(b'\0') if i > -1: a_bytestring = a_bytestring[0:i] return a_bytestring
def build_response(session_attributes, speechlet_response): """ Build the Response :param session_attributes: :param speechlet_response: :return: """ return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response }
def calculate_chksum(buffer): """ Calculate simple checksum by XOR'ing each byte in the buffer Returns the checksum """ checksum = 0 for b in buffer: if not b == '\n': checksum ^= int(b, 16) return checksum
def splitPgpassLine(a): """ If the user has specified a .pgpass file, we'll have to parse it. We simply split the string into arrays at :. We could just use a native python function but we need to escape the ':' character. """ b = [] escape = False d = '' for c in a: if not e...
def _input_key_to_id(model_id: str, key: str) -> str: """Gets the name of the feature accumulator resource.""" # Escape the commas that are used to separate the column resource id. # Those IDs have not impact to the final model, but they should be unique and # not contain commas. # # Turn the character '|'...
def _nint(str): """Nearest integer, internal use.""" x = float(str) if x >= 0: return int(x+0.5) else: return int(x-0.5)
def month_passed(date): """ Get the month from a date, month should be between 0 and 11 :date: a date in format YYYY/MM/DD :return: integer between 0 and 11 """ return 0 if date.split('/')[0] == '2010' else int(date.split('/')[1])
def creditcard_auth(customer, order_total): """Test function to approve/denigh an authorization request""" # Always fails Joan's auth if customer.upper() == "JOAN": return False else: return True
def frozenset_repr(iterable): """ Return a repr() of frozenset compatible with Python 2.6. Python 2.6 doesn't have set literals, and newer versions of Python use set literals in the ``frozenset()`` ``__repr__()``. """ return "frozenset(({0}))".format( ", ".join(map(repr, iterable)) ...
def samplenamer(listofdata, indexposition=0): """Tries to replicate the Illumina rules to create file names from 'Sample_Name' :param listofdata: a list of data extracted from a file :param indexposition: """ samplename = listofdata[indexposition].rstrip().replace(" ", "-").replace(".", "-").replace...
def print_issues(issues): """ Append each of the issues to the release notes string in a form suitable for HTML output. """ text = '' for issue in issues: text += '<li>' text += '[<a href="{}">{}</a>] - {}'\ .format(issue.permalink(), issue.key, issue.fields.summ...
def downcast(var_specs): """ Cast python scalars down to most common type of arrays used. Right now, focus on complex and float types. Ignore int types. Require all arrays to have same type before forcing downcasts. Note: var_specs are currently altered in place (horrors...
def generate_pin(color, coordinate): """ generates a pin for the stops :param color: the color of the pin :param coordinate: the coordinate of the pin :return: the string to write to the KML file """ output = "" # output string description = "" # description of pin image_url =...
def if_else(condition, a, b): """ It's helper for lambda functions. """ if condition: return a else: return b
def _convert_to_str(value): """Ensure that a value is converted to a string. This ensure proper XML build. """ if type(value) in [int, float]: return str(value) elif type(value) == bool: return str(int(value)) return value
def cars_cross_path(car_lane, car_intention, other_car_lane, other_car_intention): """ Check if the path of one car crosses tih the path o f another. It is true if the other car is the same lane or if the other car is in one of the perpendicular lanes. :param car_lane: lane of the car :param ca...
def get_epoch_from_header(sig_header: str)-> str: """Extracts epoch timestamp from the X-Telnyx-Signature header value""" sig_key_value = dict(param.split("=", 1) for param in sig_header.split(",")) epoch = sig_key_value["t"] return epoch
def norm_rgb(r, g, b): """ Normalise RGB components so the most intense (unless all are zero) has a value of 1. """ greatest = max([r, g, b]) if greatest > 0: r /= greatest g /= greatest b /= greatest return(r, g, b)
def repeated(t, k): """Return the first value in iterator T that appears K times in a row. Iterate through the items such that if the same iterator is passed into the function twice, it continues in the second call at the point it left off in the first. >>> s = iter([10, 9, 10, 9, 9, 10, 8, 8, 8, 7...
def safe_eval(expression, value, names=None): """ Safely evaluates expression given value and names. Supposed to be used to parse string parameters and allow dependencies between parameters (e.g. number of channels) in subsequent layers. Parameters ---------- expression : str Valid Pyth...
def class_decode(b): """Decode the data type from a byte. Parameters: b (byte): Byte with the encoded type Returns: str: Name of the decoded data type """ if b == b'\x00': cls = 'float64' elif b == b'\x01': cls = 'float32' elif b == b'\x02': cls = 'bool' ...
def incremental_mean(mu_i, n, x): """ Calculates the mean after adding x to a vector with given mean and size. :param mu_i: Mean before adding x. :param n: Number of elements before adding x. :param x: Element to be added. :return: New mean. """ delta = (x - mu_i) / float(n + 1) mu...
def ResolveForwardingRuleURI(project, region, forwarding_rule, resource_parser): """Resolves the URI of a forwarding rule.""" if project and region and forwarding_rule and resource_parser: return str( resource_parser.Parse( forwarding_rule, collection='compute.forwardingRules', ...
def formatRs(Rs): """ :param Rs: list of triplet (multiplicity, representation order, [parity]) :return: simplified version of the same list with the parity """ d = { 0: "", 1: "+", -1: "-", } return ",".join("{}{}{}".format("{}x".format(mul) if mul > 1 else "", l, d[...
def insertion_sort(t_input): """ Insertion Sort Algorithm Simple, stable algorithm with in-place sorting http://en.wikipedia.org/wiki/Insertion_sort Best case performance: O(n) - when array is already sorted Worst case performance: O(n^2) - when array sorted in reverse order Worst Case A...
def get_scale(W, H, scale): """ Computes the scales for bird-eye view image Parameters ---------- W : int Polygon ROI width H : int Polygon ROI height scale: list [height, width] """ dis_w = int(scale[1]) dis_h = int(scale[0]) ret...
def build_mu(mut, grid, full_levels=False): """Build 3D mu on full or half-levels from 2D mu and grid constants.""" if full_levels: mu = grid["C1F"] * mut + grid["C2F"] else: mu = grid["C1H"] * mut + grid["C2H"] return mu
def mean(data): """Returns the average of a list of numbers Args: data: a list of numbers returns: a float that is the average of the list of numbers """ if len(data)==0: return 0 return sum(data) / float(len(data))
def get_host_id(item): """ get id of the device """ return int(item.split(" ")[0])
def get_timestamps(frames, fps, offset=0.0): """Returns timestamps for frames in a video.""" return [offset + x/float(fps) for x in range(len(frames))]
def to_lower_camel_case(snake_case_str): """Converts snake_case to lowerCamelCase. Example: foo_bar -> fooBar fooBar -> foobar """ words = snake_case_str.split("_") if len(words) > 1: capitalized = [w.title() for w in words] capitalized[0] = words[0] return "...
def get_model_name(param): """ name = vector_name + num_epochs + rnn_number_of_layers + rnn_dropout + GRU/LSTM separated by underscore :param param: :return: """ if param['pretrained_vectors'] == None: model_name = f"own" else: model_name = f"{param['pretrained_vectors']....
def size_seq(seq1, seq2): """identify the largest and smallest sequence. Output tuple of big and sequence. """ if len(seq1) >= len(seq2): big, little = seq1, seq2 else: big, little = seq2, seq1 return big, little
def getver(value): """Return pair of integers that represent version. >>> getver('2.5') (2, 5) >>> getver('2.6.4') (2, 6) >>> getver(None) '' """ if not value: return '' return tuple(int(i) for i in value.split('.', 2))[:2]
def _get_chan_from_name(nm): """Extract channel number from filename. Given a ABI filename, extract the channel number. Args: nm (str): Filename / path to ABI file Returns: int: channel number """ return int(nm.split("/")[-1].split("-")[3][3:5])
def RowXorCol(xy1, xy2): """ Evaluates to true if the given positions are in the same row / column but are in different columns / rows """ return (xy1[0] == xy2[0]) != (xy1[1] == xy2[1])
def f(x): """ Helper function to determine number on a Gann square at coords: x, 0. If x = 0 -> 1 If x < 0 -> f(-x) - 4 * (-x) Else -> f(x-1) + 8 * x - 3 :param x: x position :return: value """ return 1 if x == 0 else (f(-x) - 4 * (-x) if x < 0 else f(x-1) + 8 * x - 3)
def preprocess(raw): """ Basic text formatting e.g. BOM at start of file """ ## 1. Remove byte order marks if necessary if raw[0]=='\ufeff': raw = raw[1:] # if raw[0] == '\xef': # raw = raw[1:] # if raw[0] == '\xbb': # raw = raw[1:] # if ...
def stubs(nodes, relns): """Return the list of stub nodes.""" # start from every node, drop any node that is ever a peer or a provider stubs = set(range(0, nodes)) for ((u, v), relp) in relns.items(): if relp == "cust_prov": stubs.discard(v) elif relp == "peer_peer": ...
def get_atmos_url(year:int, variable ="PM25") -> str: """ Constructs URL to download data from the Atmospheric Composition Analysis Group given a year and a band :param year: year :param variable: Gridmet band (variable) :return: URL for download """ base = "http://fizz.phys.dal.ca...
def ping(host, silent=False): """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. """ import platform # For getting the operating system name import subprocess # For executing a shell command ...
def get_jid(log_name): """Strip path and file type from the log name to return the jid as int""" return int(log_name.split('/')[-1].split('.')[0])
def split_by_predicate(iterable, predicate): """Split an iterable into two lists the according to a predicate Return a tuple of two lists: The first has the values for which `predicate` returned True The second has the values for which `predicate` returned False :param iterable: An Iterable[T] ...
def _check_detector(detector, **kwargs): """ checks to see if detector is in right format. """ detector_numbers = [str(i) for i in range(12)] detector_list = ['n' + i for i in detector_numbers] if detector.lower() in detector_list: return detector elif detector in detector_numbers: ...
def merge(left, right, lt): """Assumes left and right are sorted lists. lt defines an ordering on the elements of the lists. Returns a new sorted(by lt) list containing the same elements as (left + right) would contain.""" result = [] i,j = 0, 0 while i < len(left) and j < len(right): ...
def fully_qualified_name(type_: type) -> str: """Construct the fully qualified name of a type.""" return getattr(type_, '__module__', '') + '.' + getattr(type_, '__qualname__', '')
def get_dlons_from_case(case: dict): """pull list of latitudes from test case""" dlons = [geo[1] for geo in case["destinations"]] return dlons
def uniform_pdf(x: float) -> float: """Uniform probability density function (PDF)""" return 1 if 0 <= x < 1 else 0
def roi_center(roi): """Return center point of an ``roi``.""" def slice_center(s): return (s.start + s.stop) * 0.5 if isinstance(roi, slice): return slice_center(roi) return tuple(slice_center(s) for s in roi)
def depth_sort(files): """Sort a list of files by folder depth.""" return sorted(files, key=lambda x: x.count('/'), reverse=True)
def example_function_with_default_args( positional_arg: int, default_arg: str = "optional" ) -> str: """Return a string that tells what args you passed in. Args: positional_arg: any number to print default_arg: any string to print Returns: A success message that includes the ...
def heatCapacity(T, hCP): """ heatCapacity(T, hCP) heatCapacity = A + B*T + C*T^2 Parameters T, temperature in Kelvin hCP, A=hCP[0], B=hCP[1], C=hCP[2] A, B, and C are regression coefficients Returns heat capacity at T """ return hCP[0] + hCP[1]*T + hCP[2]*T*...
def different_delimiter_chars(one: int, two: int, three: int): """I am a sneaky function. Args: one -- this one is a no brainer even with dashes three -- noticed you're missing docstring for two and I'm multiline too! Returns: the first string argument concatenated with i...
def align(axes:str): """ axes:str -> Updates the command's execution position, aligning to its current block position "x", "xz", "xyz", "yz", "y", "z", "xy" """ if not isinstance(axes, str): return "" h = ["x", "y", "z"] b = [] for i in axes: if (not i in h) or i in b: ...
def remove_text_inside_brackets(s, brackets="()[]"): """ From http://stackoverflow.com/a/14603508/610569 """ count = [0] * (len(brackets) // 2) # count open/close brackets saved_chars = [] for character in s: for i, b in enumerate(brackets): if character == b: # found bracket...
def delete(sentence, mainword, **kwargs): #Done with testing """Delete entire sentence if <mainword> is present""" if mainword not in sentence: return False, sentence else: return True, ''
def falling_factorial( x, n ): """ Calculate falling factorial of x. [https://en.wikipedia.org/wiki/Falling_and_rising_factorials] """ c = 1 for k in range(n): c *= x-k return c
def prepare_results(results): """ Prepare a given set of results and return a dict structure that contains, for each size of words, a dict structure that contains, for each number of states, a list of words that have this size and this number of states. """ words = dict() for word, size in...
def makeGray(rgb, factor, maskColor): """ Make a pixel grayed-out. If the pixel matches the maskColor, it won't be changed. :param tuple `rgb`: a tuple of red, green, blue integers, defining the pixel :class:`wx.Colour`; :param float `factor`: the amount for which we want to grey out a pixel colour...
def get_activation_details(name, layer_type, layer, keyword_arguments): """ Creates the layer details data for the activation function """ return { 'layer_details': None, 'name': name, 'type': layer_type, 'layer': layer, "keyword_arguments": keyword_arguments ...
def confirm_feature_relationships(feature, feature_list_name, feature_id_sets_dict): """ Pass in a feature and the list that the feature came from, it then verifies if all feature ids in the relationships are present Note it does not check if a relationship field is present as some features will not hav...
def string_to_format(value, target_format): """Convert string to specified format""" if target_format == float: try: ret = float(value) except ValueError: ret = value elif target_format == int: try: ret = float(value) ret = in...
def disemvowel(string): """Return string with vowels removed""" vowels = 'aeiouAEIOU' return "".join([c for c in string if c not in vowels])
def flat_list(_list): """[(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in _list], [])
def create_tag(name): """create a viewer tag from a class name.""" model_name = '%s_model' % name.lower() tag = { 'name': model_name, 'x-displayName': name, 'description': '<SchemaDefinition schemaRef=\"#/components/schemas/%s\" />\n' % name } return model_name, t...
def update_cse(cse_subs_tup_list, new_subs): """ :param cse_subs_tup_list: list of tuples: [(x1, a+b), (x2, x1*b**2)] :param new_subs: list of tuples: [(a, b + 5), (b, 3)] :return: list of tuples [(x1, 11), (x2, 99)] useful to substitute values in a collection returned by sympy.cse (common sub...
def transform_is_ascii( is_ascii ): """ what it says ... currently list is manual make auto ?? auto now in test """ if is_ascii == 1: return "Yes" else: return "No"
def get_conversion(img_height, leftx_base, rightx_base): """ Get the conversion factors for pixel/meters """ # y-direction: # the lane lines are about 30 m long # in the perspective transform we take about half of that # and project it to the warped image ym_per_pix = 15/img_height ...
def unescape_json_str(st): """ Unescape Monero json encoded string /monero/external/rapidjson/reader.h :param st: :return: """ c = 0 ln = len(st) escape_chmap = { b'b': b'\b', b'f': b'\f', b'n': b'\n', b'r': b'\r', b't': b'\t', b'\\': ...
def constant_series(z): """ returns 1 + z + z ** 2 + ... """ return 1 / (1 - z)
def find_next_perfect_square(sq): """ sq: a number that is the square of an integer (perfect square) return: -1 if sq is not a perfect square and the square of the square root of sq + 1 if sq is a perfect square """ if (sq**0.5)*10 == int(sq**0.5)*10: return int(((sq**0.5)+1)**2) return -1