content
stringlengths
42
6.51k
def get_media_resource_image_path(_, file): """ Get the path that a media resource's image should be uploaded to. Args: _: The media resource the image belongs to. file: The original name of the file being uploaded. Returns: The path that the media resource should be uploaded to. """ return f"cms/media-resources/images/{file}"
def calc_overlap3(set_pred, set_gt): """ Calculates if the overlap between prediction and ground truth is enough fora potential True positive """ # Length of each and intersection try: len_gt = len(set_gt) len_pred = len(set_pred) inter = len(set_gt & set_pred) overlap_1 = inter / len_gt overlap_2 = inter/ len_pred return overlap_1 >= 0.5 and overlap_2 >= 0.5 except: # at least one of the input is NaN return False
def collision_checker(obstacle_map: list, dx: int, dy: int, verbose: bool) -> int: """ Lool for tree collisions along the specified path, return the number of collisions Inputs: obstacle_map: list - The grid map of obstacles: '.' represents a clear space '#' represents a tree dx: int - Amount of right run on the path dy: int - Amount of down run on the path verbose: bool - Print the collision map for debugging purposes Outputs: int - Total number of tree collisions detected along the tobaggon path """ collisions = 0 width = len(obstacle_map[0]) x = 0 for line_num, line in enumerate(obstacle_map): if line_num % dy: continue # ------------------------------------------------------------------------ if '#' == line[x]: collisions += 1 # ------------------------------------------------------------------------ if verbose: collision_map = [] for i, char in enumerate(line): if i == x: collision_map.append('X' if '#' == line[x] else 'O') else: collision_map.append(char) print('{:03d},{:03d}: {}'.format(line_num+1, x, ''.join(collision_map))) # ------------------------------------------------------------------------ x = (x + dx) % width return collisions
def jarManifest(target, source, env, for_signature): """Look in sources for a manifest file, if any.""" for src in source: contents = src.get_text_contents() if contents.startswith("Manifest-Version"): return src return ''
def zigzag(n): """ Produce a list of indexes that traverse a matrix of size n * n using the JPEG zig-zag order. Taken from https://rosettacode.org/wiki/Zig-zag_matrix#Alternative_version.2C_Translation_of:_Common_Lisp :param n: size of square matrix to iterate over :return: list of indexes in the matrix, sorted by visit order """ def move(i, j): if j < (n - 1): return max(0, i - 1), j + 1 else: return i + 1, j mask = [] x, y = 0, 0 for v in range(n * n): mask.append((y, x)) # Inverse: mask[y][x] = v if (x + y) & 1: x, y = move(x, y) else: y, x = move(y, x) return mask
def base_integer(val, base=2): """Convert base n val as integer to integer.""" assert isinstance(val, str), 'val must be str' return float(int(val, base))
def date_and_notes(s): """Parse (birth|death) date and notes; returns a tuple in the form (date, notes).""" s = s.strip() if not s: return (u'', u'') notes = u'' if s[0].isdigit() or s.split()[0].lower() in ('c.', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'ca.', 'circa', '????,'): i = s.find(',') if i != -1: notes = s[i+1:].strip() s = s[:i] else: notes = s s = u'' if s == '????': s = u'' return s, notes
def samples_to_tensors(paths): """Return processed sample data based on the collected paths. Args: paths (list[dict]): A list of collected paths. Returns: dict: Processed sample data, with keys * undiscounted_returns (list[float]) * success_history (list[float]) * complete (list[bool]) """ success_history = [ path['success_count'] / path['running_length'] for path in paths ] undiscounted_returns = [path['undiscounted_return'] for path in paths] # check if the last path is complete complete = [path['dones'][-1] for path in paths] samples_data = dict(undiscounted_returns=undiscounted_returns, success_history=success_history, complete=complete) return samples_data
def compose_update(table, fields): """Compose update query string for migrated table. Arguments --------- table : str Real table name. fields : str List of table fields. Returns ------- str Query string with real table name. However, it can contain placeholders for field values. """ query = 'UPDATE {} SET {}'.format(table, fields) return query
def in_list(item,List): """ Report True if item is in list """ try: i = List.index(item) return True except ValueError: return False
def parse_res_to_dict(response): """ Checks if response is a list. If it is list, converts it to an object with an 'items' field that has the list as value. Finally, returns the object Otherwise, returns response """ if type(response) is list: return { "items": response } else: return response
def format_dollar(value: float) -> str: """ Return a proper 2 decimal currency value :param value: Currency amount :return: currency value string """ return f"{value:0.2f}"
def average_particle_energy(integrated_energy_flux,integrated_number_flux): """Calculate the average particle energy (eV) for output from above function (only valid if same channel set used for energy and number flux)""" #Calculate average energy in electron-volts eavg = (integrated_energy_flux/1.6e-19/1000)/integrated_number_flux #mW/m^2->eV/m^2 return eavg
def print_demon(demon_dict): """This will print text describing a new demon""" output = f""" Tremble at the sight of {demon_dict["name"].capitalize()}! Behold, {demon_dict["feature_1"].lower()} and {demon_dict["feature_2"].lower()}. This {demon_dict["affinity"].lower()} demon has a {demon_dict["aspect"].lower()} aspect. This demon desires {demon_dict["desire"].lower()} above all else! """ return output
def _GetSupportedApiVersions(versions, runtime): """Returns the runtime-specific or general list of supported runtimes. The provided 'versions' dict contains a field called 'api_versions' which is the list of default versions supported. This dict may also contain a 'supported_api_versions' dict which lists api_versions by runtime. This function will prefer to return the runtime-specific api_versions list, but will default to the general list. Args: versions: dict of versions from app.yaml or /api/updatecheck server. runtime: string of current runtime (e.g. 'go'). Returns: List of supported api_versions (e.g. ['go1']). """ if 'supported_api_versions' in versions: return versions['supported_api_versions'].get( runtime, versions)['api_versions'] return versions['api_versions']
def get_service(service): """ Get the service name. If the product attribute it set then use it otherwise use the name attribute. """ if service is None: name = '' banner = '' else: name = service.attrib.get('product', None) if name is None: name = service.attrib.get('name', '') banner = service.attrib.get('banner', '') return name, banner
def get_column_letter(column_index): """ Returns the spreadsheet column letter that corresponds to a given index (e.g.: 0 -> 'A', 3 -> 'D') Args: column_index (int): Returns: str: The column index expressed as a letter """ if column_index > 25: raise ValueError("Cannot generate a column letter past 'Z'") uppercase_a_ord = ord("A") return chr(column_index + uppercase_a_ord)
def getPeriodWinner(homescore, awayscore): """ Function to determine periodwinner """ if (homescore==awayscore): return 'draw' elif (homescore>awayscore): return 'home' elif (homescore<awayscore): return 'away' else: return None
def checkDifferences(new, old): """ Check the old and new CRC dicts to see if there's been an update Parameters new : dict The most recent CRC openings old : dict The previous CRC openings Returns CRCUpdates : str The formatted string in Markdown """ CRCUpdates = "" # If there is any update to be made if (new != old): if (bool(new)): # Check all keys in the new dict for three situations: 1) It's a new key, so a new timeslot opened # 2) It's a new value, so somehow the timeslot changed # 3) Nothing has changed for key in (new.keys()): if key in old: # Check value to see only if change in number of spots if (new[key] > old[key]): CRCUpdates += "New Openings: {0}, {1} --> {2} spots open.\n\n".format(key, old[key], new[key]) else: # Add key to update CRCUpdates += "New Date: {0}, {1} spots open.\n\n".format(key, new[key]) # Adding formatting & double checking string isn't empty if (CRCUpdates != ""): CRCUpdates = "UPDATES TO CRC 1ST FLOOR:\n{0}\n[CRC Website](https://b.gatech.edu/2ErPqzW)".format(CRCUpdates) return CRCUpdates
def check_device(device): """ This function is called to check if a device id is valid. """ uuid = device.get('Device-Id') if not uuid: return False return True
def dot(vec1, vec2): """ Return the dot product of vec1 and vec2 """ return vec1[0]*vec2[0] + vec1[1]*vec2[1]
def isWordGuessed(secretWord: str, lettersGuessed: list) -> bool: """ secretWord: the word the user is guessing. lettersGuessed: letters that have been guessed so far returns: True if all the letters of secretWord are in lettersGuessed; False otherwise. """ return set(lettersGuessed).issuperset(secretWord)
def parse_slice(value): """ Parses a `slice()` from string, like `start:stop:step`. """ if value: parts = value.split(':') if len(parts) == 1: # slice(stop) parts = [None, parts[0]] # else: slice(start, stop[, step]) else: # slice() parts = [] return slice(*[int(p) if p else None for p in parts])
def get_allowed_tokens_from_config(config, module='main'): """Return a list of allowed auth tokens from the application config""" env_variable_name = 'DM_API_AUTH_TOKENS' if module == 'callbacks': env_variable_name = 'DM_API_CALLBACK_AUTH_TOKENS' return [token for token in config.get(env_variable_name, '').split(':') if token]
def _avg_bright(colour): """Returns avg brightness of three colours written by anthony luo """ r, g, b = colour return (r + g + b) / 3
def get_config_value(config_dict, key, default=None): """Get configuration value or default value from dictionary. Usable for dictionaries which can also contain attribute 'default' Order of preference: * attribute value * value of 'default' attribute * value of provided default param """ val = config_dict.get(key) if val is None: val = config_dict.get("default", default) return val
def julian_day(year, month=1, day=1, julian_before=None): """Given a calendar date, return a Julian day integer. Uses the proleptic Gregorian calendar unless ``julian_before`` is set to a specific Julian day, in which case the Julian calendar is used for dates older than that. """ # Support months <1 and >12 by overflowing cleanly into adjacent years. y, month = divmod(month - 1, 12) year = year + y month += 1 # See the Explanatory Supplement to the Astronomical Almanac 15.11. janfeb = month <= 2 g = year + 4716 - janfeb f = (month + 9) % 12 e = 1461 * g // 4 + day - 1402 J = e + (153 * f + 2) // 5 mask = 1 if (julian_before is None) else (J >= julian_before) J += (38 - (g + 184) // 100 * 3 // 4) * mask return J
def _xbm(h): """X bitmap (X10 or X11)""" if h.startswith(b'#define '): return 'xbm'
def envs_to_exports(envs): """ :return: line with exports env variables: export A=B; export C=D; """ exports = ["export %s=%s" % (key, envs[key]) for key in envs] return "; ".join(exports) + ";"
def zendesk_ticket_url(zendesk_ticket_uri, ticket_id): """Return the link that can be stored in zendesk. This handles the trailing slach being present or not. """ # handle trailing slash being there or not (urljoin doesn't). return '/'.join([zendesk_ticket_uri.rstrip('/'), str(ticket_id)])
def CtoFtoC_Conversion(inputTemp, outputTempType, isReturn): """This method converts to Celsius if given a Farhaniet and vice versa. inputTemp = The input temperature value. outputTempType = Type of output temperature required. isReturn = Whether output is required in return.""" if outputTempType == 1: outputTemp = (inputTemp - 32) * 5 / 9; else: outputTemp = (9 * inputTemp / 5) + 32; if isReturn: return outputTemp; else: print(outputTemp, outputTempType); exit();
def three_loops(array: list) -> int: """ Uses three loops to get the max sum subarray """ lenght = len(array) max_sum = array[0] for start in range(lenght): for end in range(start, lenght): current_sum = sum(array[start : end + 1]) if current_sum > max_sum: max_sum = current_sum return max_sum
def get_setting_name_and_refid(node): """Extract setting name from directive index node""" entry_type, info, refid = node['entries'][0][:3] return info.replace('; setting', ''), refid
def find_first_feature(tree): """Finds the first feature in a tree, we then use this in the split condition It doesn't matter which feature we use, as both of the leaves will add the same value Parameters ---------- tree : dict parsed model """ if 'split' in tree.keys(): return tree['split'] elif 'children' in tree.keys(): return find_first_feature(tree['children'][0]) else: raise Exception("Unable to find any features")
def generate_thumbnail_html(path_to_thumbnail): """Generates HTML code for image thumbnail.""" return '<img src="{}">'.format( path_to_thumbnail )
def _priority_key(pep8_result): """Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation. """ priority = [ # Fix multiline colon-based before semicolon based. 'e701', # Break multiline statements early. 'e702', # Things that make lines longer. 'e225', 'e231', # Remove extraneous whitespace before breaking lines. 'e201', # Shorten whitespace in comment before resorting to wrapping. 'e262' ] middle_index = 10000 lowest_priority = [ # We need to shorten lines last since the logical fixer can get in a # loop, which causes us to exit early. 'e501', ] key = pep8_result['id'].lower() try: return priority.index(key) except ValueError: try: return middle_index + lowest_priority.index(key) + 1 except ValueError: return middle_index
def end_game(_game): """ Will show a end game screen and thank the player. Args: _game: Current game state Returns: Returns false to end game loop """ print("Thank you for playing") return False
def clean_id(post_id: str) -> str: """ Fixes the Reddit ID so that it can be used to get a new object. By default, the Reddit ID is prefixed with something like `t1_` or `t3_`, but this doesn't always work for getting a new object. This method removes those prefixes and returns the rest. :param post_id: String. Post fullname (ID) :return: String. Post fullname minus the first three characters. """ return post_id[post_id.index("_") + 1 :]
def dot2d(v0, v1): """Dot product for 2D vectors.""" return v0[0] * v1[0] + v0[1] * v1[1]
def get_error_messages(data): """ Get messages (ErrorCode) from Response. :param data: dict of datas :return list: Empty list or list of errors """ error_messages = [] for ret in data.get("responses", [data]): if "errorCode" in ret: error_messages.append( "{0}: {1}".format(ret["errorCode"], ret.get("message")) ) return error_messages
def func_guard(input_str, chars_to_replace=['*', '/']): """ Return a string with chars illegal in variable names replaced. :param str input_str: string to be replaced. :param list chars_to_replace: list of illegal chars. """ for c in chars_to_replace: input_str = input_str.replace(c, '_') return input_str
def calculate_nfft(samplerate, winlen): """Calculates the FFT size as a power of two greater than or equal to the number of samples in a single window length. Having an FFT less than the window length loses precision by dropping many of the samples; a longer FFT than the window allows zero-padding of the FFT buffer which is neutral in terms of frequency domain conversion. :param samplerate: The sample rate of the signal we are working with, in Hz. :param winlen: The length of the analysis window in seconds. """ window_length_samples = winlen * samplerate nfft = 1 while nfft < window_length_samples: nfft *= 2 return nfft
def unescape_tabs_newlines(s: str) -> str: """ Reverses :func:`escape_tabs_newlines`. See also https://stackoverflow.com/questions/4020539. """ if not s: return s d = "" # the destination string in_escape = False for i in range(len(s)): c = s[i] # the character being processed if in_escape: if c == "r": d += "\r" elif c == "n": d += "\n" elif c == "t": d += "\t" else: d += c in_escape = False else: if c == "\\": in_escape = True else: d += c return d
def isServerAvailable(serverName): """Checks to see if the specified OPC-HDA server is defined, enabled, and connected. Args: serverName (str): The name of the OPC-HDA server to check. Returns: bool: Will be True if the server is available and can be queried, False if not. """ print(serverName) return True
def bubble_sort_optimized(container = []): """ Bubble sort with second optimization. Description ---------- From wikipedia: This allows us to skip over a lot of the elements, resulting in about a worst case 50% improvement in comparison count. Performance cases: Worst : O(n^2) - 50% Average : O(n^2) Best case : O(n) Parameters ---------- container : a Python mutable list of values which has implemented __len__, __getitem__ and __setitem__. Returns ------- container : Sorted container Examples ---------- >>> bubble_sort_optimized([7,1,2,6,4,2,3]) [1, 2, 2, 3, 4, 6, 7] >>> bubble_sort_optimized(['a', 'c', 'b']) ['a', 'b', 'c'] """ # setting up variables length = len(container) while length >= 1: changed_times = 0 for i in range(1, length): if container[i - 1] > container[i]: container[i - 1], container[i] = container[i], container[i - 1] changed_times = i length = changed_times return container
def rotmap(start): """ dict[char,char]: Map chars (from start to start+26) to rotated characters. """ ints = range(start,start+26) rots = ( start+i%26 for i in range( 13, 13 +26) ) return dict( zip( map( chr,ints ),map( chr,rots ) ) )
def get_pipeline_version(pipeline_version): """pipeline version """ if pipeline_version: return pipeline_version else: return "current"
def awesome_streamlit_hack(filename: str) -> str: """We need this when running this file via the 'exec' statement as a part of the awesome-streamlit.org gallery""" if filename == "<string>": return "gallery/notebook_style/notebook_style.py" return filename
def relative(tag): """ A shortcut method for accessing the namespace of the XML file; Python 2.7 or later implements xml.etree.ElementTree.register_namespace(prefix, uri) for this task. """ return r"""{http://purl.org/atom/ns#}%s""" % tag
def _IsInstanceRunning(instance_info): """Determine whether an instance is running. An instance is running if it is in the following Xen states: running, blocked, paused, or dying (about to be destroyed / shutdown). For some strange reason, Xen once printed 'rb----' which does not make any sense because an instance cannot be both running and blocked. Fortunately, for Ganeti 'running' or 'blocked' is the same as 'running'. A state of nothing '------' means that the domain is runnable but it is not currently running. That means it is in the queue behind other domains waiting to be scheduled to run. http://old-list-archives.xenproject.org/xen-users/2007-06/msg00849.html A dying instance is about to be removed, but it is still consuming resources, and counts as running. @type instance_info: string @param instance_info: Information about instance, as supplied by Xen. @rtype: bool @return: Whether an instance is running. """ allowable_running_prefixes = [ "r--", "rb-", "-b-", "---", ] def _RunningWithSuffix(suffix): return [x + suffix for x in allowable_running_prefixes] # The shutdown suspend ("ss") state is encountered during migration, where # the instance is still considered to be running. # The shutdown restart ("sr") is probably encountered during restarts - still # running. # See Xen commit e1475a6693aac8cddc4bdd456548aa05a625556b return instance_info in _RunningWithSuffix("---") \ or instance_info in _RunningWithSuffix("ss-") \ or instance_info in _RunningWithSuffix("sr-") \ or instance_info == "-----d"
def inverse_gamma_sRGB(ic): """Inverse of sRGB gamma function. (approx 2.2)""" c = ic/255.0 if ( c <= 0.04045 ): return c/12.92 else: return pow(((c+0.055)/(1.055)),2.4)
def nulls(x): """ Convert values of -1 into None. Parameters ---------- x : float or int Value to convert Returns ------- val : [x, None] """ if x == -1: return None else: return x
def document_contains_text(docbody): """Test whether document contains text, or is just full of worthless whitespace. @param docbody: (list) of strings - each string being a line of the document's body @return: (integer) 1 if non-whitespace found in document; 0 if only whitespace found in document. """ found_non_space = 0 for line in docbody: if not line.isspace(): # found a non-whitespace character in this line found_non_space = 1 break return found_non_space
def extension_supported(extension_name, extensions): """Determine if nova supports a given extension name. Example values for the extension_name include AdminActions, ConsoleOutput, etc. """ for extension in extensions: if extension.name == extension_name: return True return False
def get_input_shapes_map(input_tensors): """Gets a map of input names to shapes. Args: input_tensors: List of input tensor tuples `(name, shape, type)`. Returns: {string : list of integers}. """ input_arrays = [tensor[0] for tensor in input_tensors] input_shapes_list = [] for _, shape, _ in input_tensors: dims = None if shape: dims = [dim.value for dim in shape.dims] input_shapes_list.append(dims) input_shapes = { name: shape for name, shape in zip(input_arrays, input_shapes_list) if shape } return input_shapes
def generateNums(function, lower, upper): """Apply function to 1-... generating a list of elements within 'lower' and 'upper' limits (inclusive).""" print("Generating list for function " + function.__name__) numList = [] i = 0 num = 0 while num <= upper: num = function(i) if num >= lower and num <= upper: numList.append(num) i += 1 return numList
def double_quote(text): """double-quotes a text""" return '"{}"'.format(text)
def text_from_file(file): """ If the 'file' parameter is a file-like object, return its contents as a string. Otherwise, return the string form of 'file'. """ try: s = file.read() return s except AttributeError: return str(file)
def get_device_mapping(gpu_id): """ Reload models to the associated device. Reload models to the associated device. """ origins = ['cpu'] + ['cuda:%i' % i for i in range(8)] target = 'cpu' if gpu_id < 0 else 'cuda:%i' % gpu_id return {k: target for k in origins}
def tabla(letras): """Funcion que se encarga de crear la tabla de codificacion""" mensaje_cifrado = [] banco = {"F": 'A', "G": 'B', "H": 'C', "I": 'D', "J": 'D', "K": 'E', "L": 'A', "M": 'B', "N": 'C', "O": 'D', "P": 'E', "Q": 'A', "R": 'B', "S": 'C', "T": 'D', "U": 'E', "V": 'A', "W": 'B', "X": 'C', "Y": 'D', "Z": 'E'} # Letra de cada fila relacionada con una letra columna for letra in letras: # Se toma cada letra de la cadena if letra == "A" or letra == "B" or letra == "C" or letra == "D" or letra == "E": mensaje_cifrado.append("A" + letra) # En el primer caso las letras fila concuerdan con las letras columna elif letra == "F" or letra == "G" or letra == "H" or letra == "H" or letra == "I" or letra == "J" or letra == "K": mensaje_cifrado.append("B" + banco[letra]) elif letra == "L" or letra == "M" or letra == "N" or letra == "O" or letra == "P": mensaje_cifrado.append("C" + banco[letra]) elif letra == "Q" or letra == "R" or letra == "S" or letra == "T" or letra == "U": mensaje_cifrado.append("D" + banco[letra]) elif letra == "V" or letra == "W" or letra == "X" or letra == "Y" or letra == "Z": mensaje_cifrado.append("E" + banco[letra]) return "".join(mensaje_cifrado)
def convert_bytes(num): """ This function will convert bytes to MB, GB """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.1f %s" % (num, x) num /= 1024.0
def list_restack(stack, index=0): """Returns the element at index after moving it to the top of stack. >>> x = [1, 2, 3, 4] >>> list_restack(x) 1 >>> x [2, 3, 4, 1] """ x = stack.pop(index) stack.append(x) return x
def momentOfInertia(m_r_touple_list): """ Sample Input [(mass1, radius1), ..., (mass2, radius2)] Variables: mass = mass radius = perpendicular distance from axis of rotation Usage: the higher the moment of inertia, the more difficult it is to change the state of the body's rotation""" I = sum([m*r**2 for m,r in m_r_touple_list]) return I
def normalize(deg): """Adjusts deg between 0-360""" while deg < 0.0: deg += 360.0 while deg >= 360.0: deg -= 360.0 return deg
def filter_underscores(items: list) -> list: """ Filters all items in a list that starts with an underscore :param items: The items to filter. :return:The filtered items. """ return [item for item in items if not item.split('/')[-1].startswith('_')]
def _is_message(raw_data): """ returns the message that occured in a measurement or False """ for identifier in ("high", "low", "cal", "err", "--"): if identifier in raw_data.lower(): return True return False
def bws(t: int, tstart: int, tend: int, alpha: int) -> float: """Bounded-window scheduling function. This function returns 1.0 for `t <= tstart`, 0.0 for `tend <= t`, and `\lambda^{\alpha}` for `tstart < t < tend`, where `\lambda = \frac{tend - t}{tend - tstart}`. """ # assert 0 <= tstart < tend # assert 0 <= alpha t = min(max(t, tstart), tend) multiplier = (float(tend - t) / float(tend - tstart)) ** alpha return multiplier
def rules_to_tuples(rules_dicts): """ Transform generated rule dicts to tuples :param rules_dict: :return: >>> rulez = [{(('isokoskelo',), ('sinisorsa',)): (0.956, 0.894, 1.013, 0.952)}] >>> rules_to_tuples(rulez) [(('isokoskelo',), ('sinisorsa',), 0.956, 0.894, 1.013, 0.952)] """ return [list(f.items())[0][0] + list(f.items())[0][1] for f in rules_dicts]
def sanitize_licenses(detailed_list, license_name) -> list: """ This will remove any packages that contain a license that was already verified. Args: detailed_list(list): List of the detailed packages generated by PackageList instance. license_name(str): Name of the license to be checked. Returns: Sanitized detailed_list. """ for package in detailed_list: if len(package['licenses']) > 0: package['licenses'] = [ value for value in package['licenses'] if value != license_name] return detailed_list
def _s_suffix(num): """Simplify pluralization.""" if num > 1: return 's' return ''
def can_monitor(message): """ Determine if the user who sent the message is a race monitor. Returns False if monitor status is indeterminate, e.g. message was sent by a bot instead of a user. """ return message.get('is_monitor', False)
def get_sign(charge: int) -> str: """Get string representation of a number's sign. Args: charge (int): The number whose sign to derive. Returns: sign (str): either '+', '-', or '' for neutral. """ if charge > 0: return '+' elif charge < 0: return '-' else: return ''
def fillcompanyrow(table, companynumber, window): """ :param table: :param companynumber: :param window: :return: """ sqlstring = 'SELECT * from Company WHERE ID = ? ; ' try: # print('fillcompanyrow sqlstring, companynumber =>', sqlstring, companynumber) companyrow = table.readrows(sqlstring, companynumber) # print('fillcompanyrow companyrow =>', companyrow, companynumber) window.FindElement('_COMPANYNUMBER_').Update(companyrow[0][0]) window.FindElement('_COMPANYNAME_').Update(companyrow[0][1]) window.FindElement('_WEBADDRESS_').Update(companyrow[0][2]) window.FindElement('_STREETADDRESS1_').Update(companyrow[0][3]) window.FindElement('_STREETADDRESS2_').Update(companyrow[0][4]) window.FindElement('_CITY_').Update(companyrow[0][5]) window.FindElement('_STATE_').Update(companyrow[0][6]) window.FindElement('_ZIPCODE_').Update(companyrow[0][7]) window.FindElement('_NOTES_').Update(companyrow[0][8]) window.FindElement('_PHONE_').Update(companyrow[0][9]) return companynumber except: print('fillcompanyrow FAILED') return None
def form_to_grade_assignment(form): """Creates a grade dict from an assignment form.""" grade_id = '{student}-{assignment}-{course}'.format(**form) grade = {'_id': grade_id, 'student': form['student'], 'assignment': form['assignment'], 'course': form['course'], } if form['filename']: grade['filename'] = form['filename'] scores = {int(k[5:]): float(v) for k, v in form.items() if k.startswith('score')} scores = sorted(scores.items()) grade['scores'] = [v for _, v in scores] return grade
def __create_input_remove_video_order(orders): """remove video order""" remove_orders = [] for order in orders: input = { "TableName": "primary_table", "Key": {"PK": {"S": order["PK"]}, "SK": {"S": order["SK"]}}, } remove_orders.append({"Delete": input}) print("remove video order setted") return remove_orders
def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ return len(dna1) > len(dna2)
def __one_both_closed(x, y, c = None, l = None): """convert coordinates to zero-based, both strand, open/closed coordinates. Parameters are from, to, is_positive_strand, length of contig. """ return x - 1, y
def mgmt_if_entry_table_state_db(if_name): """ :param if_name: given interface to cast :return: MGMT_PORT_TABLE key """ return b'MGMT_PORT_TABLE|' + if_name
def validate_ftp_inputs(server_name, search_path, user_name, passwd): """Validate the given input before proceeding with FTP transaction. Arguments: server_name : Name of the FTP server where the files to be transfered search_path : Local folder path which needs to be synced with the given FTP server user-name : User Name of FTP server to connect passwd : Password of FTP server to connect Returns: True : If server_name and search_path is valid (no empty) False : If anyone server_name or search_path is not valid """ if (len(server_name) <= 0) or (len(search_path) <= 0): print("server_name is empty") return False # It doesn't work quite well at this point. # if(len(user_name) <= 0) or (len(passwd) <= 0): # user_name = passwd = "anonymous" print("server_name: {0}, search_path: {1}, user_name: {2}, password: {3}".format(server_name, search_path, user_name, passwd)) return True
def line_break(text, line_len=79, indent=1): """ Split some text into an array of lines. Enter: text: the text to split. line_len: the maximum length of a line. indent: how much to indent all but the first line. Exit: lines: an array of lines. """ lines = [text.rstrip()] while len(lines[-1]) > line_len: pos = lines[-1].rfind(' ', 0, line_len) if pos < 0: pos = line_len lines[-1:] = [lines[-1][:pos].rstrip(), ' '*indent+lines[-1][ pos:].strip()] return lines
def playlist_json(tracks): """Generate a JSON List of Dictionaries for Each Track.""" for i, track in enumerate(tracks): tracks[i] = { "title": track[0], "artist": track[1], "explicit": track[2], } return tracks
def prod_cart(in_list_1: list, in_list_2: list) -> list: """ Compute the cartesian product of two list :param in_list_1: the first list to be evaluated :param in_list_2: the second list to be evaluated :return: the prodotto cartesiano result as [[x,y],..] """ _list = [] for element_1 in in_list_1: for element_2 in in_list_2: _list.append([element_1,element_2]) return _list
def _jce_invert_salt_half(salt_half): """ JCE's proprietary PBEWithMD5AndTripleDES algorithm as described in the OpenJDK sources calls for inverting the first salt half if the two halves are equal. However, there appears to be a bug in the original JCE implementation of com.sun.crypto.provider.PBECipherCore causing it to perform a different operation: for (i=0; i<2; i++) { byte tmp = salt[i]; salt[i] = salt[3-i]; salt[3-1] = tmp; // <-- typo '1' instead of 'i' } The result is transforming [a,b,c,d] into [d,a,b,d] instead of [d,c,b,a] (verified going back to the original JCE 1.2.2 release for JDK 1.2). See source (or bytecode) of com.sun.crypto.provider.PBECipherCore (JRE <= 7) and com.sun.crypto.provider.PBES1Core (JRE 8+): """ salt = bytearray(salt_half) salt[2] = salt[1] salt[1] = salt[0] salt[0] = salt[3] return bytes(salt)
def is_tamil_unicode_value(intx: int): """ Quickly check if the given parameter @intx belongs to Tamil Unicode block. :param intx: :return: True if parameter is in the Tamil Unicode block. """ return (intx >= (2946) and intx <= (3066))
def AddEscapeCharactersToPath(path): """ Function to add escape sequences for special characters in path string. """ return path.replace("(", "\\(").replace(" ", "\\ ").replace(")", "\\)")
def get_gene_universe( genes_file ): """Builds a unique sorted list of genes from gene file""" if isinstance( genes_file, str ): genes_file = open( genes_file, 'r' ) return set( [ l.strip() for l in genes_file ] )
def get_xmlns_string(ns_set): """Build a string with 'xmlns' definitions for every namespace in ns_set. Args: ns_set (iterable): set of Namespace objects """ xmlns_format = 'xmlns:{0.prefix}="{0.name}"' return "\n\t".join([xmlns_format.format(x) for x in ns_set])
def _integrate(function, Lambda): """ Performs integration by trapezoidal rule """ # Variable definition for Area Area = 0 # loop to calculate the area of each trapezoid and sum. for i in range(1, len(Lambda)): #the x locations of the left and right side of each trapezpoid x0 = Lambda[i] x1 = Lambda[i-1] """ 'dx' will be the variable width of the trapezoid """ dx = abs(x1 - x0) """ TRAPEZOIDAL RULE """ """ Area of each trapezoid """ Ai = dx * (function[i] + function[i-1])/ 2. """ Cumulative sum of the areas """ Area += Ai return Area
def sum_list(nums): """ >>> sum_list([1, 2, 3]) 6 >>> sum_list([10, 200, 33, 55]) 298 """ idx = 0 total = 0 while idx < len(nums): total += nums[idx] idx += 1 return total
def is_duplicate(title, movies): """Returns True if title is within movies list.""" for movie in movies: if movie.lower() == title.lower(): return True return False
def get_periodic_interval(current_time, cycle_length, rec_spacing, n_rec): """Used for linear interpolation between periodic time intervals. One common application is the interpolation of external forcings that are defined at discrete times (e.g. one value per month of a standard year) to the current time step. Arguments: current_time (float): Time to interpolate to. cycle_length (float): Total length of one periodic cycle. rec_spacing (float): Time spacing between each data record. n_rec (int): Total number of records available. Returns: :obj:`tuple` containing (n1, f1), (n2, f2): Indices and weights for the interpolated record array. Example: The following interpolates a record array ``data`` containing 12 monthly values to the current time step: >>> year_in_seconds = 60. * 60. * 24. * 365. >>> current_time = 60. * 60. * 24. * 45. # mid-february >>> print(data.shape) (360, 180, 12) >>> (n1, f1), (n2, f2) = get_periodic_interval(current_time, year_in_seconds, year_in_seconds / 12, 12) >>> data_at_current_time = f1 * data[..., n1] + f2 * data[..., n2] """ locTime = current_time - rec_spacing * 0.5 + \ cycle_length * (2 - round(current_time / cycle_length)) tmpTime = locTime % cycle_length tRec1 = 1 + int(tmpTime / rec_spacing) tRec2 = 1 + tRec1 % int(n_rec) wght2 = (tmpTime - rec_spacing * (tRec1 - 1)) / rec_spacing wght1 = 1.0 - wght2 return (tRec1 - 1, wght1), (tRec2 - 1, wght2)
def sieve_of_eratosthenes(end): """Enumerates prime numbers below the given integer `end`. Returns (as a tuple): - `is_prime`: a list of bool values. If an integer `i` is a prime number, then `is_prime[i]` is True. Otherwise `is_prime[i]` is False. - `primes`: a list of prime numbers below `end`. """ if end <= 1: raise ValueError("The integer `end` must be greater than one") is_prime = [True for _ in range(end)] is_prime[0] = False is_prime[1] = False primes = [] for i in range(2, end): if is_prime[i]: primes.append(i) for j in range(2 * i, end, i): is_prime[j] = False return is_prime, primes
def cpn(prev_list, prev_level, curr_index, curr_div, curr_mod): """ Calculate previous neighbours """ largest_mod = max(2 * prev_level - 1, 0) if prev_level == 1: # No calculation needed, it only has 1 element, and every other element sees it return prev_list[0] else: if curr_div > 0: # The first case needs a value from the end of the previous list if curr_mod == largest_mod: # Corner value return prev_list[curr_index - 2*(curr_div+1)] elif curr_mod == 0: # Needs two neighbours corner = curr_index - 1 - 2*(curr_div) return sum(prev_list[corner: corner+2]) elif curr_mod == largest_mod - 1: # Needs two neighbours corner = curr_index + 1 - 2*(curr_div + 1) return sum(prev_list[corner-1: corner+1]) # Other cases need three neighbours prev_max = curr_index - 2 * (curr_div) return sum(prev_list[prev_max - 2: prev_max + 1]) else: if curr_mod == 0: # First element return prev_list[-1] + prev_list[0] elif curr_mod == 1: # Second element return prev_list[-1] + sum(prev_list[0:2]) elif curr_mod == largest_mod - 1: # One before the right corner corner = curr_mod - 1 return sum(prev_list[corner-1: corner+1]) elif curr_mod == largest_mod: # Corner value first_corner = curr_mod - 2 return prev_list[first_corner] # Three neighbours prev_max = curr_index return sum(prev_list[prev_max - 2: prev_max + 1])
def to_int(n): """Converts a string to an integer value. Returns None, if the string cannot be converted.""" try: return int(n) except ValueError: return None
def repr_args(obj, *args, **kwargs): """ Return a repr string for an object with args and kwargs. """ typename = type(obj).__name__ args = ['{:s}'.format(str(val)) for val in args] kwargs = ['{:s}={:s}'.format(name, str(val)) for name, val in kwargs.items()] return '{:s}({:s})'.format(typename, ', '.join(args + kwargs))
def get_percentage(old, new): """Gets percentage from old and new values Args: old (num): old value new (num): new value Returns: number: Percentage, or zero if none """ try: return 100 * (old - new) / old except ZeroDivisionError: return 0
def import_object(name): """Imports an object by name. import_object('x.y.z') is equivalent to 'from x.y import z'. >>> import tornado.escape >>> import_object('os.path') is os.path True >>> import_object('os.path.dirname') is os.path.dirname True """ parts = name.split('.') obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0) return getattr(obj, parts[-1])
def _is_closing_message(commit_message: str) -> bool: """ Determines for a given commit message whether it indicates that a bug has been closed by the corresponding commit. Args: commit_message: the commit message to be checked Returns: whether the commit message closes a bug or not """ # only look for keyword in first line of commit message first_line = commit_message.partition('\n')[0] return any( keyword in first_line.split() for keyword in ['fix', 'Fix', 'fixed', 'Fixed', 'fixes', 'Fixes'] )
def _parse_incident_energy(incident_energy): """Turn command line arguments into proper `info` items for the `incident_energy`. """ if not incident_energy: return None incident_energy = incident_energy.lower() if incident_energy in ('350', '350gev'): return '350gev' elif incident_energy in ('200', '200gev'): return '200gev' else: return None
def returnBackwardsString(random_string): """Reverse and return the provided URI""" return "".join(reversed(random_string))