content
stringlengths
42
6.51k
def lower_endian_to_number(l, base): """Helper function: convert a list of digits in the given base to a number.""" return sum([d * (base**i) for i, d in enumerate(l)])
def cs_gpi(A): """Cross section for pion photoproduction averaged over E[.14, 1.] GeV Average cross section values obtained by Monte Carlo simulations, for nuclei of different masses, starting at 7Li. It includes the production of pions of all types. Arguments: A {int} -- Number of nucleons in the target n...
def has_theme_spark(x, theme): """ Is the given theme included in any of the listed themes? """ return any([theme in lst.split("_") for lst in x])
def _shortnameByCaps(name): """ uses hungarian notation (aka camelCaps) to generate a shortname, with a maximum of 3 letters ex. myProc --> mp fooBar --> fb superCrazyLongProc --> scl """ shortname = name[0] count = 1 for each in name[1:]: if...
def get_job_type(x): """ returns the int value for the nominal value job-type """ if x == 'Government': return 1 elif x == 'Private': return 2 elif x == 'Self-employed': return 3 else: return 0
def cast_time(time_value, offset): """Time value represented as number of ms, us, etc Args: time_value (float): Time value. offset (int): Offset serves to purpose of changing time interval rate. Returns: int: Time value represented as number of ms, us, etc For representing di...
def get_parsed_year( data ): """ Return only the year portion from the given data section, or an empty string. The "data" should be the part of the parsed section down to the "date" index.""" value = '' if data['is_known']: modifier = data['min']['modifier'].upper() if modifi...
def multi_replace(s, rep_dict): """ Replace multi strings Parameter --------- s: string The string need to be replaced rep_dict: dict The replace patterns, {old: new} Return ------ s: string The replaced string """ for pattern ...
def merge_sort(l): """Sort list using merge sort. Complexity: O(n log n) @param l list to sort. @returns sorted list. """ def merge(l1, l2): """Merge sorted lists l1 and l2. [1, 2, 4], [1, 3, 4, 5] -> [1, 1, 2, 3, 4, 5] @param l1 sorted list @param l2 sorted li...
def find_primes(max_value): """returns every prime up to a given value.""" # NOTE: dict is exponentially faster than list numbers = {a: True for a in range(2, max_value+1)} # sieve = list(filter(lambda f: f <= max_value**0.5, numbers)) sieve = [n for n in numbers if n <= max_value**0.5] ...
def bleu_score(predictions, references): """Compute BLEU score for predictions.""" score = 0 return dict(bleu_4=score)
def to_uri(uri_data): """ Convenient function to encase the resource filename or data in url('') keyword Args: uri_data (str): filename or base64 data of the resource file Returns: str: the input string encased in url('') ie. url('/res:image.png') """ return ("url('...
def hhmm(time): """ textual representation of time in format HH:MM """ return time.strftime("%H:%M") if time else ''
def ds_loss(depth=4, loss_function='categorical_crossentropy', layer_name='out-', start_offset=0): """ Loss for deep supervision. :param depth: Positive int. Network depth. :param loss_function: String. Loss function. :param layer_name: String. Name prefix of output layers in levels. :param sta...
def correct_timing(offset, stimuli): """Correct Timing. Given the offset and stimuli array, return an array of data with stimuli corrected to the offset! """ print('Calculating the correct trigger times in relation to offset... \n') new_stimuli = [] for stim in stimuli: # Th...
def _check_int(value): """Check if value is an int or int-like string. :param value: The value to test :return: The value :rtype: int :raises TypeError: If value is not an int or int-like string """ if isinstance(value, int): return value elif isinstance(value, str) and value.is...
def _paths_from_ls(recs): """The xenstore-ls command returns a listing that isn't terribly useful. This method cleans that up into a dict with each path as the key, and the associated string as the value. """ ret = {} last_nm = "" level = 0 path = [] ret = [] for ln in recs.split...
def distance(xmass1, xmass2): """ Define distance between two mass positions in upper limit space. The distance is defined as d = 2*|xmass1-xmass2|/(xmass1+xmass2). :parameter xmass1: upper limit value (in fb) for the mass1 :parameter xmass2: upper limit value (in fb) for the mass2 :re...
def at_partition_start(t, d): """ Return True if t represents the beginning of a binary partition of depth d >>> at_partition_start(0, 0) True >>> at_partition_start(0, 1) True >>> at_partition_start(0, 34) True >>> at_partition_start(0, 1) True >>> at_partition_st...
def DFS(graph, start, end, path = []): """ Depth First Search """ path += [start] # path found if start == end: return path # check if start not in edge if not start in graph.keys(): return None # explore nodes for node in graph[start]: # avoid cycles ...
def make_complete_graph(num_nodes): """ take in param num_nodes, output a complete graph """ graph = {} if num_nodes > 0 : for node in range(num_nodes): temp = set([]) for itr in range(node): temp.add(itr) for itr in range(node + 1, num_nodes): ...
def alloc(amt): """Allocates more "memory", as used by load and store below.""" return "@mem:=CONCAT(@mem,REPEAT('<m></m>',{}))".format(amt)
def get_bandwidth(data, duration): """ Module to determine the bandwidth for a segment download""" return data * 8 / duration
def normalize(package_name): """Return normalized package name. Dashes to underscores (to help Django apps). And all-lowercase. """ package_name = package_name.lower() package_name = package_name.replace('-', '_') return package_name
def __getStationName(name, id): """Construct a staiion name.""" name = name.replace("Meetstation", "") name = name.strip() name += " (%s)" % id return name
def run(text: str, value: int) -> int: """ Runs the assembly code directly with the given digits as input, and returns the value in z """ memory = [0, 0, 0, 0] # w x y z indexes = {'w': 0, 'x': 1, 'y': 2, 'z': 3} def ref(p): if p in indexes: return memory[indexes[p]] return...
def make_gufunc(f, core_dims_in, core_dims_out): """ Automatically turn a function f into a generalized universal function (gufunc). :param f: :param core_dims_in: :param core_dims_out: :return: """ return def gufunc(args): args = generalized_broadcast(args) data_s...
def get_number_string(n, w): """ :param int n: number to be formatted :param int w: width of the number (w of 0004 is 4) :return str: """ return ("{0:0%d}" % w).format(n)
def conjoin_args(args): """ Conjoin from left to right. Args: args (list): [<something> CONJUNCTION] <something> Returns: dict: MongoDB filter """ if len(args) == 1: return args[0] conj = f"${args[1].value.lower()}" return {conj: [args[0], args[2]]}
def _get_label(asm_str): """returns a single label""" if len(asm_str.strip().split()) > 1: raise SyntaxError('Unexpected separator in label') if len(asm_str.strip()) == 0: raise SyntaxError('label expected') return asm_str.strip()
def _mk_init_name(fullname): """Return the name of the __init__ module for a given package name. """ if fullname.endswith('.__init__'): return fullname return fullname + '.__init__'
def CheckResponse(code): """ Analyze the given response code. :param code: Integer value :return: String response describing API response code """ response_codes = {200:'Success', 301:'Server Redirecting to new endpoint.', 401:'Credentials Not Authenticate...
def _lat_heimisphere(latitude): """Return the hemisphere (N, S or '' for 0) for the given latitude.""" if latitude > 0: hemisphere = 'N' elif latitude < 0: hemisphere = 'S' else: hemisphere = '' return hemisphere
def parse_tag(source_name): """ Check the ending of the source_name, return the ending if found. """ split = source_name.split("_") if len(split) == 1: return "default" else: return split[-1]
def key_value_parsing(cookie): """ >>> key_value_parsing('foo=bar&baz=qux&zap=zazzle') {'foo': 'bar', 'baz': 'qux', 'zap': 'zazzle'} """ return dict(kv.split("=") for kv in cookie.split("&"))
def should_concat(prev_type, cur_type): """This function contains the logic deciding if the current node should be grouped with the previous node in the same notebook cell. Args: prev_type: (str) type of the previous node. cur_type: (str) type of the current node. Returns A Boolean """ ...
def is_funny(s): """ :type s: str :rtype: bool """ r = s[::-1] for i in range(1, len(s) - 1): if abs(ord(s[i]) - ord(s[i - 1])) != abs(ord(r[i]) - ord(r[i - 1])): return False return True
def sanitized_filename(proj): """Remove undesired characters from a filename component""" proj = proj.replace('+', '') for c in r'/\:*?"<>|': proj = proj.replace(c, '_') return proj.strip().replace(' ', '-')
def month_num_to_name(month_num): """ Takes a String or Int input of a Month's Number, and returns a string of the the name of the corresponding Month. """ month_names = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'Novemeber', 'Decembe...
def _fabric_network_name(fabric_name, network_type): """Fabric network name. :param fabric_name: string :param network_type: string (One of the constants defined in NetworkType) :return: string """ return '%s-%s-network' % (fabric_name, network_type)
def replace_string(text, to_find, replacement): """Search for items in strings and replace. Search for characters or sequences of charaters in a string and replace them i.e. replace all commas. Args: text (str): The string to be searched. to_find (str): The character or sequence of cha...
def linear_item_score(i): """Function weights events based on their position in a sequence. Output is normalized to the range [0:1]. For the long sequences of events (index 10+) it returns zero. Parameters ---------- i : int Item position. Returns ------- result : float ...
def get_zamid_a(zamid): """Gets the mass number (a) from a nuclide's z-a-m id. Parameters ---------- zamid: str z-a-m id of a nuclide """ a = int(zamid[-4:-1]) return a
def dot(u, v): """ Take dot product between two arrays. """ return sum(u[i]*v[i] for i in range(len(u)))
def harmonic_mean(score1, score2): """get harmonic mean value""" if score1+score2 == 0: return 0 else: return (2*score1*score2) / (score1+score2)
def EscapeDelimiters(s): """ EscapeDelimiters() changes "" into "\" and "|" into "\|" in the input string. This is an internal functions which is used for saving perspectives. """ result = s.replace(";", "\\") result = result.replace("|", "|\\") return result
def format_money(raw_doc): """" description: converts money into float-convertible strings. returns converted list of strings. raw_doc: raw document. """ chars_to_remove = [",", "$"] for idx, word in enumerate(raw_doc): if any(c.isdigit() for c in word): for c in chars_to_re...
def select_to_text_readable(caption, choices): """ A function to convert a select item to text in a more verbose, readable format. Format is: [question] Send 1 for [choice1], 2 for [choice2]... """ return "%s Send %s" % (caption, ", ".join(["%s for %s" % (i+1, val...
def get_vcs(name, data, type_): """ @param name: resource name @param data: rosdoc manifest data @param type_: resource type ('stack' or 'package') """ return data.get('vcs', '')
def _format_report_data(day, query_output): """Format the output of the query to a simpler dict.""" result = {'day': day, 'changed': 0, 'unchanged': 0, 'failed': 0} for out in query_output: if out['status'] == 'changed': result['changed'] = out['count'] elif out['status'] == 'unc...
def get_normalized(x, xmax, xmin): """ Normalized a value given max and min """ x_norm = (x - xmin)/(xmax - xmin) return x_norm
def bbox_to_rect_params(bbox, offset=None): """Convert values in bbox tuple to the format that `matplotlib.patches.Rectangle()` takes. Parameters ---------- bbox : tuple (containing 4 float values) A tuple of bounding box in the format of `(x1, y1, x2, y2)` (bottom-left and top-righ...
def name_of(obj): """Returns the name of function or class.""" class_name = type(obj).__name__ if class_name in ['function', 'type']: return obj.__name__ else: return class_name
def lower(value): """Converts a string into all lowercase""" return value.lower()
def make_prefix_table(words) -> dict: """Constructs a dictionary holding the words and their prefixes""" table = {} for word in words: for size in range(1, len(word)): prefix = word[0:size] if prefix not in table: table[prefix] = None table[word] = wor...
def fibonacci(n): """ Generates the first n Fibonacci numbers. Adopted from: https://docs.python.org/3/tutorial/modules.html """ result = [] a, b = 0, 1 while len(result) < n: result.append(b) a, b = b, a + b return result
def epoch_time(start_time, end_time): """Calculates the elapsed time between the epochs.""" elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs
def to_on_off(state): """ Convert boolean to "on" or "off. Return string String containing "on" or "off" """ return "on" if state else "off"
def parse_home_score(d): """ Used to parse score of home team. """ string_value = d.get("uitslag", " 0- 0") (h, _) = string_value.replace(" ", "").split("-") return int(h)
def standardize_bool_hors_nk(hors_nk_str): """This column contains string while it could be a boolean. To ease future data manipulation, let's convert it to a boolean, with a value of 1 if the data is not in Nouakchott, and 0 is the data is from Nouakchott. It returns None if we can't recognize the string i...
def trackSpeeds_to_bodyFixed(right_track_speed, left_track_speed, track_width): """ Function maps speeds for individual skid-steering tracks to the body-fixed velocity and angular velocity Arguments: right_track_speed - speed of the right track left_track_speed - speed of left track ...
def GetBinaryNameForPC(pc_val, user_lib_info = None): """ find the binary in user_lib_info that the passed pc_val falls in range of. params: pc_val : int - integer form of the pc address user_lib_info: [] of [] which hold start, end, binary name returns: str - Nam...
def reformatHex(i): """[summary] Converts the given integer into 8-digit hex number. Arguments: i {[int]} -- [integer] """ hexrep = format(i,'08x') thing = "" for i in [3,2,1,0]: thing += hexrep[2*i:2*i+2] return thing
def find_event_by_backtracking( initial_event, events, condition_fn, break_fn=None ): """Backtracks to the first event that matches a specific condition and returns that event""" event = initial_event visited_events = [] for _ in range(len(events)): if condition_fn(event): return...
def truncate(source, max_len: int, el: str = "...", align: str = "<") -> str: """Return a truncated string. :param source: The string to truncate. :param max_len: The total length of the string to be returned. :param el: The ellipsis characters to append to the end of the string if it exceeds max_len. ...
def check_port(port_num, name='port'): """Check that the port is a valid number. You'd be surprised.""" if not isinstance(port_num, int): raise ValueError('Error! {} ({}) is not an integer!'.format(name, port_num)) elif port_num > 65535: raise ValueError('Error! {} number too large ({}})'.f...
def hex_to_rgb(color): """ "#FFFFFF" -> [255,255,255] """ return [int(color[i:i+2], 16) for i in range(1, 6, 2)]
def config_data_test(data): """ This function is a test to determine the data type. :param data: :return: """ if data == "True" or data == "False": return True else: return False
def add_dataline_to_dict(data_dict, header_list_raw, dataline): """ For each line of data, add the line to the corresponding dictionary header. """ # turn the dataline into a list of numbers datalist = [float(x) for x in dataline.split()] # add it to the right header for i, h in enumer...
def get_train_valid_test_split_(splits_string, size): """Get dataset splits from comma or '/' separated string list.""" splits = [] if splits_string.find(",") != -1: splits = [float(s) for s in splits_string.split(",")] elif splits_string.find("/") != -1: splits = [float(s) for s in spl...
def is_in_t(pt): """Checks if a point is in the template triangle T. :param pt: The point to be checked. :type pt: tuple(float,float). :returns: True if pt is in T. :rtype: bool. """ flag = True if pt[0] < 0 or pt[1] < 0: flag = False if pt[0] + pt[1] > 1: ...
def join_shop_recipes(recipes): """recipes is a list of dictionaries that shop_recipe returns """ joined_recipes = {} for recipe in recipes: for k, v in recipe.items(): if k not in joined_recipes: joined_recipes[k] = v else: joined_recipes[...
def groupbykey(iterable, key=None): """ Returns a list of sublists of *iterable* grouped by key: all elements x of a given sublist have the same value key(x). key(x) must return a hashable object, such that set(key(x) for x in iterable) is possible. If not given, key() is the identity func...
def FindDegeneracies(Es,small=1e-4): """ gives an index list of degenerate state. For example, if Es[0]==Es[1] and Es[2] is different, it gives [[0,1],[2]] """ deg=[] n=0 while (n<len(Es)): degc = [n] i=n+1 for i in range(n+1,len(Es)): if abs(Es[i]-Es[i-1]...
def is_multichannel(meta): """Determines if an image is RGB after checking its metadata. """ try: return meta['itype'] in ('rgb', 'rgba', 'multi', 'multichannel') except KeyError: return False
def y_fitted_line(m_val, b_val, vec_x): """ This function returns the fitted baseline constructed by coeffecient m and b and x values. ---------- Parameters ---------- x : list Output of the split vector function. x value of the input. m : int/float inclination of the bas...
def get_flux_data(src_data): """ Gets flux as a function of frequency for the source @param src_data : data returned from a call to get_cal_data @return: (list of freqs, list of fluxes) """ S = {} for key in list(src_data.keys()): if key[0:2] == "mm": if src_data[key] != None and src_data[key]...
def lastFrameFromSegmentLength(dist, first_frame, length): """Retrieves the index of the last frame for our current analysis. last_frame should be 'dist' meters away from first_frame in terms of distance traveled along the trajectory. Args: dist (List[float]): distance along the trajectory, incr...
def format_time(time_string): """ Function to format the time according to Mysql syntax """ date = time_string.split("T")[0] time = time_string.split("T")[1] #2008-01-01 00:00:01 return date+" "+time.split(".")[0]
def convert_ms(ms): """ Converts milliseconds into h:m:s :param ms: int :return: str """ seconds = (ms / 1000) % 60 seconds = int(seconds) if seconds < 10: seconds = "0" + str(seconds) else: seconds = str(seconds) minutes = (ms / (1000 * 60)) % 60 minutes = ...
def short_state(state: str) -> str: """Return a short version of query state. >>> short_state("active") 'active' >>> short_state("idle in transaction") 'idle in trans' >>> short_state("idle in transaction (aborted)") 'idle in trans (a)' """ return { "idle in transaction": "i...
def reverse_word(string): """ Reverse the input string. Arguments: string -- a list of input string. Returns: reverse_string -- a string reverse word of input string. """ return ' '.join(string.split(' ')[::-1])
def str_indent(c): """Return a string with C spaces""" return ' ' * c
def index_to_url(index): """Construct a relative hyperlink to a tree node given its path.""" if index: return '%s.html' % '.'.join(index) return 'index.html'
def _parse_sha_file(file_content): """Parses terraform SHA256SUMS file and returns map from zip to SHA. Args: file_content: Content of a SHA256SUMS file (see example below) Returns: A dict from a TF zip (e.g. terraform_1.1.2_darwin_amd64.zip) to zip SHA Here is an example couple lines...
def pop(lines): """ Pop from the top of list, this has the (desired) side-effect of removing the first line from the list. :param lines: the list of extracted text fields, one per line :return: the next line """ return lines.pop(0)
def chunks(l: list, n: int) -> list: """ returns successive n-sized chunks from l. >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c', 'd', 'e', 'f'] >>> chunks(l, 5) [[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], ['a', 'b', 'c', 'd', 'e'], ['f']] >>> chunks(l, 1) [[1], [2], [3], [4], [5], [6], [7], [...
def _native_type(s): """ Convert value in the string to its native (i.e. either int, float or str) type. :param s: string :return: value in native type """ try: return int(s) except ValueError: try: return float(s) except ValueError: return s
def not_implemented(*args: tuple, **kwargs: dict) -> dict: """ Default responce if pair is valid, bot no action is taken :return: OpenC2 response message - dict """ return dict( status=501, status_text=f"command valid, no action taken" )
def _gen_color_request(sheet_id, row, column, color): """Request to change color of the specified cell. Args: sheet_id (int): Numeric sheet id. row (int): Number of the row to highlight with color. column (int): Number of the column to highlight with color. color (str): Color co...
def calculate_offset(address, base, shadow_base=0): """ Calculates an offset between two addresses, taking optional shadow base into consideration. Args: address (int): first address base (int): second address shadow_base (int): mask of shadow address that is applied to `base` ...
def check(lst: list, search_element: int) -> bool: """Check if the list contains the search_element.""" return any([True for i in lst if i == search_element])
def parse_error_object_to_list(error_object): """ This is to parse if the error message is dictionary object - this scenario occurs from URL validator """ error_list = [] for element in error_object: if type(element) is dict: for key in element: error_list.append...
def update(uid): """Update a user, triggered by sign-on-o-tron When a user is updated in sign-on-o-tron, sign-on-o-tron will send a PUT request to the url of this controller, with a bearer token of the user that sends the request. The user which sends the request is specified by the sidekiq queue t...
def isclose(one, two, err=1e-09): """ Check if two number are close enought Args: one (float) two (float) Returns: bool """ return abs(one-two) <= err
def climatology_plus_stdev_check(inval, inclimav, instdev, stdev_limits, limit): """ Climatology check which uses standardised anomalies. :param inval: value to be compared to climatology :param inclimav: the climatological average to which the value will be compare...
def crossover_bounce( new_config, new_app_running, happy_new_tasks, old_app_live_tasks, ): """Starts a new app if necessary; slowly kills old apps as instances of the new app become happy. See the docstring for brutal_bounce() for parameters and return value. """ if not new_app_running...
def path_from_schedule(jobs, start): """ The evaluation is based on building the travel path. For example in the network A,B,C with 4 trips as: 1 (A,B), 2 (A,C), 3 (B,A), 4 (C,A) which have the travel path: [A,B,A,C,B,A,C,A] The shortest path for these jobs is: [A,C,A,B,A] which uses the order:...
def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) [2, 8] >>> solution(15) [2, 8] >>> solution(2) [2] >>> solution(1) [] >>> solution(34) [2, 8, 34] """ ls = [] a, b = 0,...
def get_int(obj, dft): """ Returns int :param obj: str :param dft: default value :return: int """ try: return int(obj) except (TypeError, ValueError): return dft