content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def dfs_category_dictionary(categories, categories_df, parentId, count): """ dfs predefined predefined hierarchical categories. :param categories: each topic's predefined hierarchical categories. :param categories_df: dataframe stroes data :param parentId: id of parent categories :param count: ...
469c3cf66751f070d8affeb3f7270d353461c969
686,651
def append_hdr(hdr, keys=None, values=None, item=0): """Apend/change parameters to fits hdr. Can take list or tuple as input of keywords and values to change in the header Defaults at changing the header in the 0th item unless the number the index is givien, If a key is not found it adds it to ...
7baa1f201ca85c63e68b31da8e1770055542b149
686,652
import subprocess import os def tck2connectome_collection(tck_file, node_files, tck_weights_file = None, assign_all_mask_img = None, nthreads = 8, CLOBBER = False): """ :param tck_file: :param node_files: :param tck_weights_file: :param assign_all_mask_img: if not None, then we change the call...
df86b0cf4e3fceac749455d5a6701f853fdbd843
686,653
def _calculate_ranges(config, start, stop): """Calculate which part of a give range should belong to which process Parameters ---------- config : DistributedConfiguration object holding information about the parallel environment of quantarhei start : int start of the inte...
45e2360b993d2366db53d74dd7cc8e983164196c
686,654
import torch def inv_quad_chol_lower(x,L,y): """ Computes x (L L^T) y x : (m x n) L : (n x n) y : (n x k) """ m = x.shape[0] if m == 1: xy = torch.cat([x.reshape(-1,1),y],dim=1) return torch.triangular_solve(xy,L,upper=False)[0].prod(dim=1).sum(dim=0).re...
5f89775b2c735c71e904562a110a1d550e9d7665
686,655
import re def get_original_image_link(url): """ Parse the image URL to cut off the 150x150 from the RSS feed Args: url (str): The image URL Returns: str: The updated URL if it matches the regex, else the original URL """ match = re.match(r"^(?P<prefix>.+)-150x150\.(?P<suffix>...
31b9a0e42b1a1852e2afe974aa0b799e266cd4cd
686,656
def rgb_to_hex(rgb_color: tuple) -> str: """ Convert rgb color to hex example: (255, 255, 255) to #FFFFFF :param rgb_color: :return: """ r, g, b = rgb_color return '#%02x%02x%02x' % (r, g, b)
a382d69fb4d12c6ae977fa30b4e097d4da675840
686,657
def encode(bytedata): """Convert a bytestring into a zerocoded bytestring""" i = 0 l = len(bytedata) c = 0 start = 0 while i < l: if c > 255 or (bytedata[i] != 0 and c != 0): bytedata = bytedata[:start+1] + bytes((c,)) + bytedata[i:] i = i - c + 1 l = ...
60ad0c98a47e8369b7ca5f309dd2995135916a0d
686,658
def __operator(x, w, c, noise): """ Operator is used to generate artificial datasets :param w: :param c: :param noise: :return: """ return x * w + c + noise
72d9bebb752ad53e40341ec9592defed4c62fcd9
686,659
import requests import json def create_order(): """ crea una nueva orden con 1 o más productos disponibles para el usuario """ url = "https://old.arkadu.com/api/shop/order/create/" headers = { "Content-Type": "application/json", "Authorization": "Bearer vUQzaKhCo9LpPfBAeAetUFQv...
eeae6d4ca324a00f5b4040c9ca390a9f564146f1
686,663
def _slugify(value: str) -> str: """ Converts the value to a slugified version reducing the str down to just alpha-numeric values and removing white-space :param value: value as a str :return: slugified version of the value """ return ''.join(s for s in value if s.isalnum()).lower()
dd0e28381f1033c4fea9bb4b368a715f2ba132fe
686,664
def sort_nodes_by_priority(g): """ Sort node ids in ascending order of priority. :param g: a game graph. :return: the node ids sorted in ascending order of priority. """ # x is a key of the dictionary a value (1, 4) means player 1, priority 4 # we return the node id, sorted by priority incr...
3018606b8bb49c217b106f957b47c41f4680b22c
686,665
def notcontains(value, arg): """ Test whether a value does not contain any of a given set of strings. `arg` should be a comma-separated list of strings. """ for s in arg.split(','): if s in value: return False return True
d7d2b5bf4b3b28b771083677b0817537cdeea455
686,666
def get_min_amount(exchange_id, symbol): """Get Min Amount.""" exchange = eval("ccxt.{0}()".format(exchange_id)) exchange.load_markets() return float(exchange.markets[symbol]["limits"]["amount"]["min"])
17d216ebaa1f8f7cbacf8bc49ce27ef6a878a317
686,667
def parse_duration(s): """ s: <number>[<s|m|h|d|y>] Returns the number of seconds """ try: if s[-1].isdigit(): return float(s) n, unit = float(s[0:-1]), s[-1].lower() if unit == 's': return n if unit == 'm': return n * 60 if...
2510c481c2a8a8d6f62d6a6e799b5b2fd453e07c
686,668
def power_time_series(series, scalar): """ Multiply a series by itself X times where X is a scalar """ s = str(series) return f"multiply([{','.join([s for _ in range(scalar)])}])"
1d76ccf684d5ed2380be6cf3f7dad846b36f1733
686,669
def TraceAgent(agent): """Wrap the agent's program to print its input and output. This will let you see what the agent is doing in the environment.""" old_program = agent.program def new_program(percept): action = old_program(percept) print('{} perceives {} and does {}'.format(agent, pe...
ef6c2bdf48e16645f8374e85a19b2060ca450537
686,670
def to_dict(object): """RETURN : None if unable to convert to dict""" return dict(object)
b5c94fe320ecfc8aebbcfa6503127a14049e6b13
686,671
from typing import Type import functools import logging def ignore_an_error(error_to_ignore: Type[Exception]): """Decorator used to ignore a specific error for a blocking function Parameters ---------- error_to_ignore : Type[Exception] The type of the error to be ignored """ def deco...
64f4b548e4a82a0e72efe3b7d9ab46b276f4bee6
686,672
import os def detect_window_system(): """Try to detect the running window system""" if os.getenv('WAYLAND_DISPLAY') is not None and os.getenv('GDK_BACKEND') is None: return "wayland" elif os.getenv('DISPLAY') is not None: return "x11" else: return None
06e46aa6e710766e11dd8a836b601b12b383909b
686,673
def model_to_str(model): """ Args: model (:obj:`Model`): model Returns: :obj:`str`: string representation of model """ str = model.id for annotation in model.annotations: str += '\n {}: {}:{}'.format(annotation.relationship, annotation.namespace, annotation.id) retu...
3d0c57ea17afdedd251cb9db8127fbbe707e3103
686,675
def ok_handler(state_mode="SOFT", count_num=1, action_threshold=3, crit_happens=True): """Handler for when OK. Usualy nothing to do when it is all OK.""" return False
415f2708c57512c14803e50fefea887d264fddf8
686,676
def format_champion_lore(lore): """ :type lore: champion.Lore """ return { 'body': lore.body, 'quote': lore.quote, 'quote_author': lore.quote_author, }
1b64b59962b1e394f0e6ba388558b121f738b0dc
686,678
import torch def knns_dist(xyz1, xyz2, k, device): """ Parameters ---------- samples: Number of points in xyz1 xyz1: B * N * 6 xyz2: B * N * 6 k: number of points in xyz2 which are least distant to xyz1 Returns ---------- k number of...
860492c8b9fb559b8e39262a93dbad5db4317f60
686,679
def _is_ros_binary_type(field_type): """ Checks if the field is a binary array one, fixed size or not list(bytearray(de(encoded_data))) _is_ros_binary_type("uint8") >>> False _is_ros_binary_type("uint8[]") >>> True _is_ros_binary_type("uint8[3]") >>> True _is_ros_binary_type("char") ...
fbbcbd515fc398560a53546ca8ed7a2555556bc1
686,680
def is_valid_id(id): """Check if id is valid. """ parts = id.split(':') if len(parts) == 3: group, artifact, version = parts if group and artifact and version: return True return False
c81ff28cbca39e601ddc7ea0786db0e62779096a
686,681
def eval_and_or(pred, gold): """ Args: Returns: """ pred_ao = pred['where'][1::2] gold_ao = gold['where'][1::2] pred_ao = set(pred_ao) gold_ao = set(gold_ao) if pred_ao == gold_ao: return 1, 1, 1 return [len(pred_ao), len(gold_ao), 0]
19781ef78f265200f07042f401270a962cbac053
686,682
import os def smart_hostname(settings_dict): """ By default, use the listen address and port as server name. Use the "HEROKU_APP_NAME" environment variable if present. :param settings_dict: :return: """ if "HEROKU_APP_NAME" in os.environ: return "https://%s.herokuapp.com/" % os.en...
472b3d19141a273a4bb2b316b927555efb732a1c
686,683
import sys def _get_select_expression_for_custom_type(source_column, name, data_type): """ Internal method for calling functions dynamically """ current_module = sys.modules[__name__] function_name = "_generate_select_expression_for_" + data_type try: function = getattr(current_module, functio...
191f97f8d7f92b704efec4131da7a243e9a93296
686,684
def STD_DEV_SAMP(*expression): """ Calculates the sample standard deviation of the input values. Use if the values encompass a sample of a population of data from which to generalize about the population. See https://docs.mongodb.com/manual/reference/operator/aggregation/stdDevSamp/ for more details...
cfd4b27cf75e014f8c7debda0dfd97dfa118d7b9
686,685
import collections def define_all_variables(): """ A routine to declare the variables of interest in an ordered dictionary of the form variable, table :return: an ordered dictionary of all variables """ """ A copy of all vars as normal dictionary for reference all_vars_dict = {'ta...
2e3a2d647f3fcc54bf2b56e600baba6593313a21
686,686
def misclassification_percentage(y_true, y_pred): """ Returns misclassification percentage ( misclassified_examples / total_examples * 100.0) """ misclassified_examples = list(y_true == y_pred).count(False) * 1. total_examples = y_true.shape[0] return (misclassified_examples / total_examples) * 100.0
262057b506ea3e3edbefc9bc019f36b67b485ee1
686,687
import socket def int_to_ip(ip): """Convert 32-bit integer to an IP""" return socket.inet_ntoa(ip.to_bytes(4, 'big'))
4263848279ba9dd5b45c04ede7ac20e38ab9dd60
686,688
def create_menu(restaurant): """ Creates a dictionary representation of a new menu item and adds it to the menu. Parameters: menu (list): A list of dictionaries, each representing a restaurant item item (str): A string with the name of a new menu item price (float): A flot with the ...
b117eab71e3865034f46ac9dd753b3766e2f93db
686,689
from typing import Iterable def _unique(*args: Iterable) -> list: """Return a list of all unique values, in order of first appearance. Args: args: Iterables of values. Examples: >>> _unique([0, 2], (2, 1)) [0, 2, 1] >>> _unique([{'x': 0, 'y': 1}, {'y': 1, 'x': 0}], [{'z':...
5d43dfa3d13b04b40c2ae37fac25df44d4d37295
686,691
def linear_function(m, x, b): """ A linear function of one variable x with slope m and and intercept b. """ return m * x + b
f61b62d36314483029a3f668a8aaa2b98b1a765c
686,692
import functools def dgetattr(obj, name, is_dict=False): """ get deep attribute operates the same as getattr(obj, name) but can use '.' for nested attributes e.g. dgetattr(my_object, 'a.b') would return value of my_object.a.b """ atr = dict.__getitem__ if is_dict else getattr names = name....
0bde83bf68c031d7ea27bb42ffde6c9f751b94fa
686,693
import os def find_ray_stater_script(): """Find location of script used to start Ray nodes.""" dir_path = os.path.dirname(os.path.realpath(__file__)) return f"{dir_path}/raystarter.py"
60f145af5e279140e8e5496df64ff0dd2144eb48
686,694
def pyimpl_tuple_getitem(data, item): """Implement `getitem`.""" return data[item]
38db771d7825ebb79b617ce7d7a3f0880992e2c6
686,695
def correct_name_case(name): """ Previously we had to modify the case; this function is a no-op now """ return name
525ffffbd8549da074924d6e37ed2f2b7c94d1b6
686,696
import time def wait_for(condition_function): """ Helper method """ start_time = time.time() while time.time() < start_time + 10: if condition_function: return True else: time.sleep(0.1) raise Exception( 'Timeout waiting for {}' .form...
b2574a05b3cddb50a9e78c96e3f2c8032c2e3617
686,697
def resolving_power(W,D_o): """Calulates the Reosultion of the telescope Args: W (float): Wavelength of light recieved (nm) D_o (float): Diameter of Objective/Aperture (mm) Returns: float: Resolving power of the telescope (:math: `P_R`) (arc-sec) Note: This fun...
7e2de8ac27a37cc9f0630070e060be8b760802fd
686,699
def get(isamAppliance, check_mode=False, force=False): """ Get management ssl certificate information """ return isamAppliance.invoke_get("Get management ssl certificate information", "/isam/management_ssl_certificate/")
30699523d4b9d213f0d2e5abec65f7852adf8c49
686,700
import json from pathlib import Path def get_total_epochs(save_path, run, last_gen): """ Compute the total number of performed epochs. Parameters ---------- save_path: str path where the ojects needed to resume evolution are stored. run : int curre...
a9f046640b2502ae5057ab9cfc88ea37d895863e
686,701
def filter_same_tokens(tokens): """ Function for filtering repetitions in tokens. :param tokens: list with str List of tokens for filtering. :return: Filtered list of tokens without repetitions. """ if not isinstance(tokens, list): raise TypeError for token in toke...
bb489aea2dd7c05b2c359555fcc8e7f619859d0c
686,702
def is_last_page(page): """ Проверяет, что на странице уже пустой список объектов (она последняя) :param page: страница :return: bool """ return bool(len(page.xpath('//div[@class="with-pad"]')))
5873a3df9b3698b18f176d9eda17796436299fcc
686,703
import json def loads(json_str): """Load an object from a JSON string""" return json.loads(json_str)
2a6d810349e99db6f5169b9e50df7f070f3de70a
686,704
def newton(number): """ Newton's method for square root, according to Copilot """ global test_num test_num = 0 x = number / 2 while True: y = (x + number / x) / 2 if y == x: return y x = y
8a62518a4594ef7fcbaed02381e03cc5b484c1c6
686,705
def count_violations_lead_like(molecular_weight, slogp, num_rotatable_bonds): """http://zinc.docking.org/browse/subsets/ Teague, Davis, Leeson, Oprea, Angew Chem Int Ed Engl. 1999 Dec 16;38(24):3743-3748. """ n = 0 if molecular_weight < 250 or molecular_weight > 350: n += 1 if slogp > 3...
42e0602f830c833a0055c471e882203a9f33189e
686,706
def tag_case(tag, uppercased, articles): """ Changes a tag to the correct title case while also removing any periods: 'U.S. bureau Of Geoinformation' -> 'US Bureau of Geoinformation'. Should properly upper-case any words or single tags that are acronyms: 'ugrc' -> 'UGRC', 'Plss Fabric' -> 'PLSS Fabr...
2447453964d16db201fa63aa14053e5e2d25ebe7
686,707
def say_hello(): """Return simple "Hello" Greeting.""" html = "<html><body><h1>Hello</h1></body></html>" return html
a06e112594419bf8152e872c879c7f87b6867f08
686,708
def link_album(album_id): """Generates a link to an album Args: album_id: ID of the album Returns: The link to that album on Spotify """ return "https://open.spotify.com/album/" + album_id
dbca10b94c22e46b494ed98152db5bba754ee28e
686,709
def fetch_seq_pygr(chr, start, end, strand, genome): """Fetch a genmoic sequence upon calling `pygr` `genome` is initialized and stored outside the function Parameters ---------- chr : str chromosome start : int start locus end : int end locuse strand : str ...
9c104af76cc32d0f90437c4c9e9d389af7c75640
686,710
import csv def load_state_id_mapping(): """ Return a mapping of <state name, state id>. """ MAPPING_CSV = "./locations_state.csv" with open(MAPPING_CSV) as f: reader = csv.reader(f) state_id_mapping = {} # Skip the header next(reader) for row in r...
551d318f5eabd231a9a04a20c2f69b92f43349ea
686,711
import pkg_resources import csv def formal_cities(reverse=False): """ Get a dictionary that maps all Backpage city names to their presentable, formal names. Returns: dictionary of Backpage city names mapped to formal city names """ output = {} fname = pkg_resources.resource_filename(__name__, 'resour...
ccc1565a5bf6d38a2ac365ab20adcb63f9e37fff
686,712
def compute_metrics(y_true, y_pred, metrics): """ Computation of a given metric Parameters ---------- y_true: True values for y y_pred: Predicted values for y. metrics: metric Chosen performance metric to measure the model capabilities. Returns ------- d...
19f07ead2c728ff86cc1b2879f4abe196a567575
686,713
def centerOfGravity( array ): """ Vypočítá ze zadaých bodů jejich těžiště. Parametry: ---------- array: list Pole s body. Vrací: ----- list Pole s X- a Y-ovou souřadnicí těžiště. """ sum_X = 0 sum_Y = 0 # Sečte X-ové a Y-ové souřadnice ...
a5ef7714b0ea97258530ba3d2d6d0483ca82623a
686,714
def rk4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. y is the initial value for y x is the initial value for x dx is the difference in x (e.g. the time step) f is a callable function (y, x) that you supply to compute dy/dx for the specified values. """ k1 = dx * f(y...
73e83f0d3818f0db3b0a3c657d256e27c13bae1e
686,715
from typing import Dict from typing import Any def add_parser_options(options: Dict[str, Dict[str, Any]], parser_id: str, parser_options: Dict[str, Dict[str, Any]], overwrite: bool = False): """ Utility method to add options for a given parser, to the provided options structure :par...
ad0e43abce2a7c41ac39da759e42f0b228cf5343
686,716
from typing import List def distributed_axial(w:float, L:float, l1:float, l2:float) -> List[float]: """ Case 6 from Matrix Analysis of Framed Structures [Aslam Kassimali] """ Fa = w/(2*L) * (L-l1-l2) * (L-l1+l2) Fb = w/(2*L) * (L-l1-l2) * (L+l1-l2) return [Fa, Fb]
18608713f411998e390e8af26fa01a9be499774b
686,720
import argparse def parse_args() -> argparse.ArgumentParser: """ Parse command line arguments to enable script-like running of KNC-Live Returns: arrgparser object """ parser = argparse.ArgumentParser(description=__doc__) # Enable command line arguments parser.add_argument('--proc...
159ac9434afd002e0ac55e7084f80c978326dfb7
686,721
from datetime import datetime def parse_time(time_string): """Parse a time string from the config into a :class:`datetime.time` object.""" formats = ['%I:%M %p', '%H:%M', '%H:%M:%S'] for f in formats: try: return datetime.strptime(time_string, f).time() except ValueError: ...
8ff237f980ed69c2293cd2893f56182ce1dea8b8
686,722
from typing import IO def compute_toplevel_cmd(file: IO[str], computeMode: str = 'DefaultCompute', expr: str = ''): """Compute the normal form, whole file. """ return ('compute_toplevel', {'file': file, 'expr': expr, 'computeMode': computeMode})
858bc49bac87eab8acd54f9ed0f83ed820e0ab42
686,723
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: List of dictionaries. Structured data with the following schema: [ { "command": string, "...
709235db574f65ab8845ae3e5d6f206b6d8ef585
686,724
def _get_ciphers_from_sockets(brokers): """Obtain ciphers currently used by pykafka BrokerConnections""" ciphers = set() for b in brokers.values(): ciph = b._connection._socket.cipher() if ciph is not None: ciphers.add(ciph[0]) return ','.join(ciphers)
bea3a4d9baf55e3aab4f793299352566880df7d1
686,725
def cosine_sim(x, y): """Cosine similarity between all the image and sentence pairs. Assumes x and y are l2 normalized""" return x.mm(y.t())
c250b87087d9efc33bc2a09a1030b7d4b92f1edd
686,726
from typing import Dict def format_link_object(url: str, text: str) -> Dict[str, str]: """ Formats link dictionary object. """ return {"href": url, "text": text}
ca6f45f98f878517b8ff7795269a0084caeda252
686,727
def provenanceRule(scModel, edgeTuples): """ :param scModel: :param edgeTuples: :return: @type scModel: ImageProjectModel """ bases = set() for node in scModel.getNodeNames(): nodedata = scModel.getGraph().get_node(node) if nodedata['nodetype'] == 'final': ba...
c73336cbe6cbd395b380e1fd9dd9bfcbbeb66617
686,728
def move(position, roll): """Simple math.""" new_position = position + (roll * 2) return new_position
9e6a71e4801370cf7bd9209880452e0b70e1d7d9
686,729
from typing import List import sys def _argmin(lst: List[float]) -> int: """ returns index of min element. Don't want to bring in numpy dependency for that """ min_val = sys.float_info.max min_idx = -1 for i, x in enumerate(lst): if x < min_val: min_idx = i ...
c02ae9eab349017454b0bbaa793e4ecbd5a8713b
686,730
import unicodedata def ispunct(token): """Is the token a punctuation""" return all(unicodedata.category(char).startswith('P') for char in token)
eb7f458dccccdd9a350a00a37ed2d41f110a500c
686,731
def mul(args): """ Multiply the all the numbers in the list Args(list): A list of number Return(int or float): The computing result """ result = 1 for num in args: result *= num return result
38d650088195b9826a964511beef50108bf9bdff
686,732
import base64 def ddb_to_json(ddb_item): """Convert a DDB item to a JSON-compatible format. For now, this means encoding any binary fields as base64. """ json_item = ddb_item.copy() for attribute in json_item: for value in json_item[attribute]: if value == "B": ...
bd24925e685db8c1096473ffbfcfb3329a4c55fc
686,733
import pwd def valid_user(username): """ Returns True if the username given is a valid username on the system """ try: if username and pwd.getpwnam(username): return True except KeyError: # getpwnam returns a key error if entry isn't present return False re...
542764751abc0b353dbce53b4d6beeb2464496d5
686,734
import time def datetime_to_timestamp(a_date): """Transform a datetime.datetime to a timestamp microseconds are lost ! :type a_date: datetime.datetime :rtype: float """ return time.mktime(a_date.timetuple())
6bdddfdcff92bae2ad60a678f8001f2bb55c8706
686,735
import os def get_path_or_none(new_path, xtal, dict_input, dict_key): """ Get a path or none - for loader :param new_path: :param xtal: :param suffix: :return: """ if dict_key in dict_input: suffix = dict_input[dict_key] else: print("Key - " + dict_key + " not in di...
f04f16d30a57141f4dc443539c6aa9378264a036
686,736
import logging import sys def _find_console_stream_handler(logger): """Find a StreamHandler that is attached to the logger that prints to the console.""" for handler in logger.handlers: if isinstance(handler, logging.StreamHandler) and handler.stream in (sys.stderr, sys.stdout): return logger return N...
0801f90ba6d2f8c6c5a23c68096008c4886e0561
686,737
import asyncio async def check_address(host: str, port: int = 80, timeout: int = 2) -> bool: """ Async version of test if an address (IP) is reachable. Parameters: host: str host IP address or hostname port : int HTTP port number Returns ------- awaitable bool "...
e08da38636c66a59948adc4fa08132f9f7438db9
686,738
from datetime import datetime def time_since(value): """ :param value: 1分钟内 刚刚 :return: """ if not isinstance(value, datetime): return value now = datetime.now() timestamp = (now-value).total_seconds() if timestamp < 60: return "刚刚" elif timestamp >= 60 and times...
b446756775b1ae32899c1449a50cd90a3e474c34
686,739
def convert_distance(val, old_scale="meter", new_scale="centimeter"): """ Convert from a length scale to another one among meter, centimeter, inch, feet, and mile. Parameters ---------- val: float or int Value of the length to be converted expressed in the original scale. old_scale...
46cac6149753a2231e040c2507b71bbc23a3f607
686,740
def get_cell_connection(cell, pin): """ Returns the name of the net connected to the given cell pin. Returns None if unconnected """ # Only for subckt assert cell["type"] == "subckt" # Find the connection and return it for i in range(1, len(cell["args"])): p, net = cell["args"]...
3fd2b9bb5df7818d3cd47323890d210ff88eb27a
686,741
def safeCreate(folder, id, portal_type): """ return folder[id], create it it does not exisit """ if not id in folder.objectIds(): folder.invokeFactory(portal_type, id) return getattr(folder, id)
663b4b6f26e1e2a0adb1836d444a549c07210056
686,742
import re def nest(text, nest): """ Indent documentation block for nesting. Args: text (str): Documentation body. nest (int): Nesting level. For each level, the final block is indented one level. Useful for (e.g.) declaring structure members. Returns: str: Indente...
a985409bae7177295368ad472c63ba0ea972375d
686,743
from typing import Union import time def time_format(seconds: float, format_='%H:%M:%S') -> Union[str, float]: """ Default format is '%H:%M:%S' >>> time_format(3600) '01:00:00' """ # this because NaN if seconds >= 0 or seconds < 0: time_ = time.strftime(format_, time.gmtime(abs(s...
41116e13c2e93255b0e2512a9fad69bca020ed69
686,744
def firstline(text): """:firstline: Any text. Returns the first line of text.""" try: return text.splitlines(True)[0].rstrip('\r\n') except IndexError: return ''
f211d9088b2ae0f600929066f44a489e9f8d2a6d
686,745
def validate_identifier(key: str): """Check if key starts with alphabetic or underscore character.""" key = key.strip() return key[0].isalpha() or key.startswith("_")
8eb04927e53a71a3e1f9475503e44d034dd3350f
686,746
def signal_from_cmd(cmd, alt_names=None): """ Get signal name from command string :param cmd: str :param alt_names: dict {name_in_cmd: name_in_file} :return: str """ alt_names = {} if alt_names is None else alt_names cmd_split = cmd.split() signal = 'signal' for signal in cmd_spl...
4859c94d6c434528036b469fd52dd718a5dc5836
686,747
import struct def _single_byte_from_hex_string(h): """Return a byte equal to the input hex string.""" try: i = int(h, 16) if i < 0: raise ValueError except ValueError: raise ValueError("Can't convert hex string to a single byte") if len(h) > 2: raise ValueEr...
59a08cb8dafc96e4ee0234ef14c8ca849595aa50
686,748
def mean(num_list): """ Computes the mean of a list of numbers Parameters ---------- num_list : list List of number to calculate mean of Returns ------- mean : float Mean value of the num_list """ # Check that input is of type list if not isinstance(num_li...
7932b52a44515ec118f67365609b979452aee0eb
686,749
def select_columns(df, col_names): # Tested [N] """ Select only the columns that appears in the train set Args: df (dataframe): Test dataframe col_names (list): List of all desired column names. Returns: df (dataframe): Original dataframe with only selected columns """ ...
6c95f1e20ed4b7f8f41762cdfa024a73285008df
686,750
def get_correct_spelling(blob): """ returns correct spelling :param text: :return: """ return blob.correct()
eeb3e4d31e5321c00afa88e2eec3fcb262005890
686,751
import csv def get_rows(input_tsv): """Parse input CSV into list of rows Keyword arguments: input_tsv -- input TSV containing study metadata Returns _csv.reader -- content of input file """ tsv_rows = csv.reader(open(input_tsv, 'r'), delimiter='\t') return tsv_rows # see tsv2xml....
f2dffa7bcf7f0f4a1e3b48fc443ae489d06429cd
686,752
import time def time_stamp(time_str: str = "", time_format: str = "%Y-%m-%d %H:%M:%S") -> float: """ time str -> time stamp """ if not len(time_str): return time.time() return time.mktime(time.strptime(time_str, time_format))
d78ace2d1b557f5d66b21f8bef2250a7a9ccfc30
686,753
import torch def get_local_median(tensor, window_size=50, dim=-1): """Return local median """ n = tensor.size(dim) median = [] with torch.no_grad(): for i in range(n): index = torch.tensor(range(max(0, i-window_size//2), min(n, i+window_size//2+1)), device=tensor.device) ...
14888a6edd61689db8ce4a3a334474b5d5391755
686,755
def get_queue(conn, queue_name): """ Create a queue with the given name, or get an existing queue with that name from the AWS connection. """ return conn.get_queue(queue_name)
3984ef179cfc74336067e217795308ed4768e736
686,756
import toml def get_config(conf_file): """ get config """ with open(conf_file,"r") as fileh: config = toml.loads(fileh.read()) return config
652c8d4b066362c10f3f955875d7d557454ef916
686,757
def method004(): """Create a test fixture for MOA method:004.""" return { "id": "method:004", "label": "Clinical interpretation of integrative molecular profiles to guide precision cancer medicine", # noqa: E501 "url": "https://www.biorxiv.org/content/10.1101/2020.09.22.308833v1", ...
53ccf23f21cb358cdaec02e6a251fca988601f60
686,758
def check_reversibility(reaction): """ Return: - *forward* if reaction is irreversible in forward direction - *backward* if reaction is irreversible in the rbackward (reverse) direction - *reversible* if the reaction is reversible - *blocked* if the reactions is blocked """ if (react...
8a3047f85a640457e39762f22916ad6c8d47d183
686,759
def transform_calendar(ds, timedim="time", calendarname="proleptic_gregorin"): """Transforms calendar of time index in xarray dataset""" ds[timedim].attrs['calendar'] = calendarname return ds
e59a0f1662e270df8457989db87bbda5b4847506
686,760
def exception_handler(func): """ Exception handler for user input in functions """ def inner_function(*args, **kwargs): while True: try: return func(*args, **kwargs) except Exception as e: return "ERROR!" return inner_function
8adf4e6071f927b96797bea7cdccd0122eaba376
686,762