content
stringlengths
22
815k
id
int64
0
4.91M
def scan_album_folder(folder, file_list): """ Renames all files in a folder. If all the files in the folder have the same Year and Album metadata, the folder itself will be renamed to the format "[YEAR] ALBUM" """ folder_data = [] folder_counts = {'found': 0, 'renamed': 0, '...
35,600
def log(s): """ Log a single line at a time to avoid cluttering the output. In verbose mode, print everything and never clear. """ if VERBOSE: print(f"[outsource]: {s}") else: sys.stdout.write("\033[K") # clear print(f"[outsource]: {s}", end="\r")
35,601
def predict_with_inferer( images: Tensor, network, keys: List[str], inferer: Optional[SlidingWindowInferer] = None ) -> Dict[str, List[Tensor]]: """ Predict network dict output with an inferer. Compared with directly output network(images), it enables a sliding window inferer that can be used to handle ...
35,602
def split_data(line): """ method splits varibles on line """ data = list() arr = np.array([string for string in line.split(", ")], dtype=str) for _, item in enumerate(arr): word_parse = re.compile(r''' ((?<=:.)-*[0-9]+\.*[0-9]*)''', re.X) parts = word_parse.findall(item) ...
35,603
def show_outcome_group_global(request_ctx, id, **request_kwargs): """ :param request_ctx: The request context :type request_ctx: :class:RequestContext :param id: (required) ID :type id: string :return: Show an outcome group :rtype: requests.Response (with OutcomeGrou...
35,604
def md5sum(file: str) -> str: """ Create a strings with the md5 of a given file :param file: filename of the file whose md5 is computed for :return: md5 string """ md5_hash = hashlib.md5() with open(file, "rb") as file: content = file.read() md5_hash.update(content) digest...
35,605
def read_data(filetype, filename, prn): """Calls the appropriate position reader function based on the filetype.""" func_name = filetype + '_data' possibles = globals().copy() possibles.update(locals()) func = possibles.get(func_name) if func is None: raise NotImplementedError(func + ' i...
35,606
def test_successful_binary_file_input_output_to_file( identifier_name: str, use_header_guard: bool, binary_mode_flag: str, output_to_file_flag: str, output_filename: str, tmp_path: Path, ): """Test that a binary file can be read successfully and the correct header is generated and writte...
35,607
def processContours(contours: List[float], contourpoints: List[List[float]], frame: pims.frame.Frame, debug=False) -> Tuple[List[List[float]], pims.frame.Frame]: """Get bounding boxes for each contour. Parameters ---------- contours : List[float] List of contours to find bounding boxes for. ...
35,608
def simulate_games(num_games, switch, num_doors=3): """ Simulate a multiple game of the Monty Hall problem. Parameters: - num_games: Integer, the number of games you want to simulate. - switch: Boolean, whether or not your strategy is to switch doors after the reveal. ...
35,609
def prod(iterable:Iterable) -> Iterable: """math.prod support for Python versions < v3.8""" return functools.reduce(operator.mul, iterable, 1)
35,610
def compress_video(video_path): """ Compress video. :param video_path: Path to the video. :return: None. """ return subprocess.call(["gzip", video_path]) == 0
35,611
def trim_resource(resource): """ trim_resource """ return resource.strip(" \t\n\r/")
35,612
def main(): """ TODO: The function shows the original image and the one flipped vertically """ original_mt = SimpleImage('images/mt-rainier.jpg') original_mt.show() reflected = reflect('images/mt-rainier.jpg') reflected.show()
35,613
def wikipedia_request_page_from_geocoding(flatitude, flongitude): """ Get list of wikipedia page identifiers related to the specified geocode """ places_list = [] loc = "{}|{}".format(flatitude, flongitude) print(loc) parameters = { "action": "query", "list": "geosearch", ...
35,614
def globalBinarise(logger, img, thresh, maxval): """ This function takes in a numpy array image and returns a corresponding mask that is a global binarisation on it based on a given threshold and maxval. Any elements in the array that is greater than or equals to the given threshold will be...
35,615
def connect_to_db(schema='sys', database='', return_df=True): """Query database and fetch table data. Args: schema (str): MySQL table schema. Default to 'sys'. database (str): MySQL table name. Deafult to ''. return_df (bool): Condition to return the dataframe. """ load_dot...
35,616
def times_by_stencil(results): """Collects times of multiple results by stencils. Args: results: List of `Result` objects. Returns: A tuple of lists (stencils, times). """ stencils = results[0].stencils if any(stencils != r.stencils for r in results): raise ValueError('...
35,617
def get_bulk_and_slab(bulk, miller=[1,1,1], layers=4, vacuum=16): """Create a slab and conventional bulk cell from a bulk cell input Parameters ---------- bulk : pymatgen structure pymatgen structure of the bulk material miller : list list of miller indices layers : int ...
35,618
def test_build_ad_multiple_extensions(tmp_path): """Build an AD object with multiple extensions and check that we retrieve everything in the correct order after writing. """ shape = (4, 5) testfile = tmp_path / 'test.fits' ad = astrodata.create({}) for i in range(1, 4): nd = NDData(...
35,619
def gogogo_figure(ipympl, figsize, ax=None): """ gogogo the greatest function name of all """ if ax is None: if ipympl: with ioff: fig = figure(figsize=figsize) ax = fig.gca() else: fig = figure(figsize=figsize) ax = fig...
35,620
def unzip6(xs): """ unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f]) The unzip6 function takes a list of six-tuples and returns six lists, analogous to unzip. """ a = L[(i[0] for i in xs)] b = L[(i[1] for i in xs)] c = L[(i[2] for i in xs)] d = L[(i[3] for i in xs)] ...
35,621
def grep(lines=None,expr=None,index=False): """ Similar to the standard unit "grep" but run on a list of strings. Returns a list of the matching lines unless index=True is set, then it returns the indices. Parameters ---------- lines : list The list of string lines to check. e...
35,622
def get_table_map_from_text(sp: BeautifulSoup, keep_table_contents=True) -> Dict: """ Generate table dict only :param sp: :param keep_table_contents: :return: """ table_map = dict() for flt in sp.find_all('float'): try: if flt.name and flt.get('name') == 'table': ...
35,623
def tag_copier(path, cliargs): """This is the tag copier worker function. It gets a path from the Queue and searches index for the same path and copies any existing tags (from index2) Updates index's doc's tag and tag_custom fields. """ doclist = [] # doc search (matching path) in index fo...
35,624
def turn(speed, secs=None, radius=0, reverse=False): """ Makes the robot turn at the specified speed for the specified number of seconds. If seconds is a number > 0 the function will block (wait) until that time has elapsed and stop the motors If seconds is None then the speeds will be set and the funct...
35,625
def grainfromVertices(R=None,fname='shape.txt',mixed=False,eqv_rad=10.,rot=0.,radians=True,min_res=4): """ This function generates a mesh0 from a text file containing a list of its vertices in normalised coordinates over a square grid of dimensions 1 x 1. Centre = (0,0) coordinates must be of the form: ...
35,626
def snoop_task_log_handler(level=logging.DEBUG): """Context manager for a text log handler. This captures in memory the entire log of running its context. It's used to capture Task logs in the database. Args: level: log level, by default logging.DEBUG """ stream = StringIO() handle...
35,627
def get_block(blockidx, blocksz, obj): """ Given obj, a list, return the intersection of obj[blockidx*blocksz:(blockidx+1)*blocksz] and obj Ex: get_block(2, 100, range(250) returns [200, 201, ..., 249] """ if blockidx*blocksz > len(obj): return [] elif (blockidx+1)*blocksz > len(obj...
35,628
def AddTensors(workspace, init_net, blob_names): """add tensors""" for blob_name in blob_names: blob = workspace.FetchBlob(str(blob_name)) AddTensor(init_net, blob_name, blob)
35,629
def RDS(net,waves,coupons,p,size,seeds,posseed,poswave): """Conducts respondent-driven sampling Input: net: network, networkx graph waves: maximum number of waves, integer (use 0 with poswave=True for contract tracing) coupons: number of coupons per respondent, integer ...
35,630
def get_dataset_mrnet_args(parser, args=[]): """ Get all relevant parameters to handle the dataset -> here: MRNET """ # determine path if platform.system() == "Linux": path = "/home/biomech/Documents/OsteoData/MRNet-v1.0/" else: path = "C:/Users/Niko/Documents/data/MRNet-v1....
35,631
def update_fields(obj, **kwargs): """Updates only fields given in kwargs. """ for key, value in kwargs.items(): setattr(obj, key, value) obj.save(update_fields=kwargs.keys())
35,632
def convertImageToBase64(image): """ Convert image to base64 for transmission Args: image (obj): opencv image object Returns: (str): image encoded as base64 """ # im_arr: image in Numpy one-dim array format. _, im_arr = cv2.imencode('.jpg', image) im_bytes = im_arr.tobytes() return base64....
35,633
def anchor_inside_flags(flat_anchors, valid_flags, tsize, allowed_border=0): """Check whether the anchors are inside the border. Args: flat_anchors (torch.Tensor): Flatten anchors, shape (n, 2). valid_flags (torch.Tensor): An existing valid flags of anchors. tsize (int): Temporal size o...
35,634
def print_step_s____(info: str) -> None: """single print""" if not Debug: return _log("โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”") _log(ProgressMarkPrefix + info.replace('\n', '\nโ”ƒ')) _log("โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”")
35,635
def verify_callback_handlers(clazz): """Verifies that methods adding listener/callback have overload for specifying delivery thread.""" # Ignore UI packages which assume main thread skip = [ "animation", "view", "graphics", "transition", "widget", "webkit...
35,636
def args2command(*args): """ to convert positional arguments to string list """ try: assert None not in args assert "" not in args except: print("args:", args) raise(ValueError("None values not allowed in args!")) return [str(_).strip() for _ in args]
35,637
def parse_one(line: str) -> Tuple[Optional[str], List[str]]: """ Returns (first corruption char, remaining stack) """ stack = [] for c in line: if c in BRACKET_MAP.keys(): stack.append(c) continue expected = BRACKET_MAP[stack[-1]] if c != expected: ...
35,638
def load_callable_dotted_path(dotted_path, raise_=True, reload=False): """ Like load_dotted_path but verifies the loaded object is a callable """ loaded_object = load_dotted_path(dotted_path=dotted_path, raise_=raise_, reload=relo...
35,639
def get_engine(): """Helper method to grab engine.""" facade = _create_facade_lazily() return facade.get_engine()
35,640
def generate_diagonals(): """ Cะพะทะดะฐะตั‚ ัะปะพะฒะฐั€ัŒ ะดะธะฐะณะพะฝะฐะปะตะน ะฝะฐ ะบะพั‚ะพั€ั‹ะต ะผะพะดะตั‚ ะฒัั‚ะฐั‚ัŒ ะบะพะฝัŒ ะธ ะผะฐััะธะฒ ั ะฒะพะทะผะพะถะฝั‹ะผ ะบะพะปะธั‡ะตัั‚ะฒะพะผ ะฒะฐั€ะธะฐะฝั‚ะพะฒ ะดะพะนั‚ะธ ะฒ ะบะฐะถะดัƒ ั‚ะพั‡ะบัƒ ัั‚ะพะน ะดะธะฐะณะพะฝะฐะปะธ :return: ัะปะพะฒะฐั€ัŒ - ะณะดะต ะบะปัŽั‡ ัั‚ะพ ั‡ะธัะปะพ ะดะธะฐะณะพะฝะฐะปะธ ะฐ ะทะฝะฐั‡ะตะฝะธั, ัั‚ะพ ัะฟะธัะพะบ ะธะท ะฒะพะทะผะพะถะฝั‹ั… ัะฟะพัะพะฑะพะฒ ะดะพะฑั€ะฐั‚ัŒัั ะดะพ ั‚ะพั‡ะตะบ ะฝะฐ ัั‚ะพะน ะดะธะฐะณะพะฝะฐะปะธ ""...
35,641
def physical_rad_to_pix(im_prod: Union[Image, RateMap, ExpMap], physical_rad: Quantity, coord: Quantity, z: Union[float, int] = None, cosmo=None) -> Quantity: """ Another convenience function, this time to convert physical radii to pixels. It can deal with both angular and proper rad...
35,642
def conversation_type_frequency_distribution(convo): """ Returns the type frequency (unigram) distribution for the convo. Parameters ---------- convo : Conversation Returns ------- collections.Counter """ return reduce(lambda x, y: x + y, map(post_freq, convo.posts.values()))
35,643
def create_file(filename: str): """ Create the file filename and create any directories needed Args: filename: Path to the file to be created """ filename = os.path.expanduser(filename) if not path_is_read_writable(os.path.dirname(filename)): raise PermissionError(f"Insuffic...
35,644
def _cleanup_legacy_namespace(input_string): """ At some point in time, the ttml namespace was TTML_NAMESPACE_URI_LEGACY, then it got changed to TTML_NAMESPACE_URI. There are tons of those floating around, including our pre-dmr dfxps and ttmls files. The backend (this lib) can deal with both namespa...
35,645
def get_config_filename(args): """Tries to automatically set the config to use.""" if args.config is None: try: if args.varn == 'Blocking': args.config = 'plot_map_config_blocking' if args.varn == 'GeopotentialHeight': args.config = 'plot_map_confi...
35,646
def _err_to_json(key, *args): """Translate an error key to the full JSON error response""" assert (key in errors) code = errors[key][0] title = errors[key][1] detail = errors[key][2].format(*args) return json.dumps({ 'message': title, 'errors': [{ 'title': tit...
35,647
def multiref_represent(opts, tablename, represent_string = "%(name)s"): """ Represent a list of references @param opt: the current value or list of values @param tablename: the referenced table @param represent_string: format string to represent the records """ if not opts:...
35,648
def selected_cells(self): """Get the selected cells. Synchronous, so returns a list. Returns: A list of Cells. """ cells = [] generator = self.selected_cells_async() for chunk in generator: for value in chunk.cells: cells.append(value) return cells
35,649
def calc_annual_capital_addts_ferc1(steam_df, window=3): """ Calculate annual capital additions for FERC1 steam records. Convert the capex_total column into annual capital additons the `capex_total` column is the cumulative capital poured into the plant over time. This function takes the annual dif...
35,650
def status(): """Show status information for all available devices."""
35,651
async def async_upload_file(serialUID, filepath, upload_blockinfo): """ๅผ‚ๆญฅไธŠไผ ๆ–‡ไปถ""" ts = int(time.time() * 1000) # ่ฎก็ฎ—ๅˆ†็‰‡CRC32 data, crc32 = get_block_crc32(filepath, upload_blockinfo["startOffset"], upload_blockinfo["endOffset"]) upload_blockinfo['dataCRC32'] = crc32 # ๆ•ฐๆฎๅŠ ๅฏ†ๅ’Œ็ญพๅ request_data, sig...
35,652
def parse(parser_name=None, file_key=None, **kwargs): """Call the given parser and return parsed data It is possible to give file key instead of parser name. In that case the name of the parser will be read from the file list. TODO: This is the old style of running parsers, can be deleted when all par...
35,653
def grafico_barre_qualitative_risposta(X, y, qualitative, n_columns): """Grafico a barre della relazione tra qualitative e risposta""" n_var = len(qualitative) for i, var in enumerate(qualitative): ax = plt.subplot(math.ceil(n_var / n_columns), n_columns, i + 1) pd.concat([X[var], y], axis=...
35,654
async def remove(message: discord.Message, trigger: Annotate.Content): """ Remove user alias with the specified trigger. Use `*` to delete all. """ if trigger == "*": aliases.data[str(message.author.id)] = {} await aliases.asyncsave() await client.say(message, "**Removed all aliases.**")...
35,655
def create_cv_split(file_train, file_test, col_label='label', col_group=None, n_folds=5, splitter='skf', random_state=33): """ Parameters: splitter : str "kf", "skf", "gkf" Example: train_df, test_df = create_cv_split(os.path.join(args.data_dir, 'Train.csv'), ...
35,656
def get_scanner(hass, config): """Validate the configuration and return a Bbox scanner.""" scanner = BboxDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None
35,657
def _trim_name(image): """Remove the slash at the end of the filename.""" return image[:-1] if image[-1] == '/' else image
35,658
def check_for_pyd_so(file_path): """ Checks if a file with .pyd or .so extension exists """ return True if os.path.isfile(file_path+'.pyd') or os.path.isfile(file_path+'.so') else False
35,659
def load_data(data_file): """Loads data CSV into input and target ndarrays of shape (n_samples, features). Args: data_file (str): Local or remote CSV file containing data to load. Returns: ndarray: Input data of shape (n_samples, in_features). ndarray: Target data of shape (n_s...
35,660
def sines_sum(parameters: ndarray) -> Callable: """ Construct a sum of sines for given parameters. Parameters ---------- parameters : ndarray y0, amplitude1, frequency1, phase1, amplitude2, frequency2, phase2, ... Returns ------- function f(x) = amplitude1*sin(2*pi*freq...
35,661
def _divide_and_conquer_convex_hull(points): """ Notes: O(n * log(n)) Args: points: Returns: """ count = len(points) if count < 6: return Hull(_jarvis_convex_hull(points)) midpoint = count // 2 min_cloud, max_cloud = points[:midpoint], points[midpoint:] ...
35,662
def _parsed_method_to_method( parsed: Union[parse.UnderstoodMethod, parse.ImplementationSpecificMethod] ) -> Union[UnderstoodMethod, ImplementationSpecificMethod]: """Translate the parsed method into an intermediate representation.""" if isinstance(parsed, parse.ImplementationSpecificMethod): return...
35,663
def stop_docker(name=container_name, cid=None, let_fail=False): """Stop docker container with given name tag Parameters ---------- name: str name field which has been attached to the container we wish to remove cid: str container ID, if known let_fail: bool whether to ra...
35,664
def NS(namespace, tag): """ Generate a namespaced tag for use in creation of an XML file """ return '{' + XML_NS[namespace] + '}' + tag
35,665
def dump_requirements(nodes, strict=False): """Dump packages and their versions to a string. Format of the string is like a "requirements.txt":: # created with python-X.X package-1==1.2.3 package-2==2.3.4 :param nodes: List of ast nodes in a module. :param strict: If *True* th...
35,666
def non_contradiction_instance_2(person_list, place_list, n, vi_function=vi, not_vi_function=not_vi, Everyone_str="Everyone", ...
35,667
def init_args(parser): """ Add argument required to configure clocks. """ parser.add_argument('--freq', action='append', metavar="NAME=VALUE", help='Set the frequency of oscillator')
35,668
def load_w2v_model(w2v_path): """ Loads pretrained w2v model :param w2v_path: :return: """ return gensim.models.Word2Vec.load(w2v_path)
35,669
def derive_keys(token, secret, strategy): """Derives keys for MAC and ENCRYPTION from the user-provided secret. The resulting keys should be passed to the protect and unprotect functions. As suggested by NIST Special Publication 800-108, this uses the first 128 bits from the sha384 KDF for the obsc...
35,670
def bitinfo_holding_ts( track_addr: Optional[str] = None, track_coin: Optional[str] = None, timeframe: Optional[str] = "4h", sma: Optional[int] = 20, ): """Scrap the data from bitinfo and calculate the balance based on the resample frequency. track_addr (str): The address to track. track_coi...
35,671
def sharpe(p): """Sharpe ratio of the returns""" try: return p.mean()/p.std()*np.sqrt(252) except ZeroDivisionError: logging.error("Zero volatility, divide by zero in Sharpe ratio.") return np.inf
35,672
def create_manual_slab_ase(lattice='fcc', miller=None, host_symbol='Fe', latticeconstant=4.0, size=(1, 1, 5), replacements=None, decimals=10, pop_last_layers=0): """ Wraps ase.lattice lattices generators to create a slab having given lattice vectors directio...
35,673
def telephone(): """Generates random 10 digit phone numbers and returns them as a dictionary entry""" num = "" # for i in range(1, 11): num += str(rand.randint(0, 9)) if(i < 7 and i % 3 == 0): num += "-" return {"telephone":num}
35,674
def get_kline(symbol: str, end_date: [datetime, str], freq: str, start_date: [datetime, str] = None, count=None, fq: bool = False) -> List[RawBar]: """่Žทๅ–K็บฟๆ•ฐๆฎ :param symbol: ๅธๅฎ‰ๆœŸ่ดง็š„ไบคๆ˜“ๅฏน BTCUSDT/ETHUSDT :param start_date: ๅผ€ๅง‹ๆ—ฅๆœŸ :param end_date: ๆˆชๆญขๆ—ฅๆœŸ :param freq: K็บฟ็บงๅˆซ๏ผŒๅฏ้€‰ๅ€ผ ['1min', '5min', '30...
35,675
def test_get_formatted_as_type_bool_true_with_1_input(): """On get_formatted_as_type returns bool True with int 1 input.""" context = Context({'k1': True}) result = context.get_formatted_as_type(1, out_type=bool) assert isinstance(result, bool) assert result
35,676
def get_terms(properties, out_log, classname): """ Gets energy terms """ terms = properties.get('terms', dict()) if not terms or not isinstance(terms, list): fu.log(classname + ': No terms provided or incorrect format, exiting', out_log) raise SystemExit(classname + ': No terms provided or incorrect format') if...
35,677
def get_prefix(allow_base=False): """Get $CONDA_PREFIX as pathlib.Path object.""" confirm_active() prefix = Path(os.environ.get("CONDA_PREFIX")) if not allow_base and is_base_env(prefix): raise ImportError( "Base conda env detected, activate an environment before running this comma...
35,678
def handle_validate(bot, ievent): """ validate provided url or last url in log """ url = None if ievent.rest: url = ievent.rest else: if plugins.url: url = plugins.fetch("url").latest(bot, ievent) if not url: ievent.missing('<url>') ; return try: url = valid_url(url) except urllib2.HTTPErro...
35,679
def _decomp_MAMFile(srcfile, destfile=''): """ Superfetch file์ด๋‚˜ Prefetch file์˜ MAM ํฌ๋งท์˜ ์••์ถ•์„ ํ‘ผ๋‹ค. """ f = open(srcfile, 'rb') data = f.read() f.close() # ์••์ถ•๋œ ํŒŒ์ผ์ธ์ง€ ํ™•์ธํ•œ๋‹ค. """ MAX\x84 : Windows 8 ์ด์ƒ ์ˆ˜ํผํŒจ์น˜ ํŒŒ์ผ MAX\x04 : Windows 10 ํ”„๋ฆฌํŒจ์น˜ ํŒŒ์ผ """ id = data[0:3].decode('utf8') # MAM b1 = ...
35,680
def cg(A, b, x=None, tol=1e-10, verbose=0, f=10, max_steps=None): """ Parameters ---------- A: A matrix, or a function capable of carrying out matrix-vector products. """ n = b.size b = b.reshape(n) if x is None: x = np.zeros(n) else: x = x.reshape(n) if isinstan...
35,681
def test_run_ingest(db, mocker, clients, prep_file): """ Test the run_ingest function. """ client = clients.get("Administrator") mock_genomic_workflow = mocker.patch( "creator.ingest_runs.tasks.ingest_run" ".ingest_genomic_workflow_output_manifests" ) user = User.objects.firs...
35,682
def get_ase(f_file, p_insert_red, s_insert_red): """ Combine framework and insert atoms to one ase structure f_file : framework file name p_insert_red: positions of reduced inserted species s_insert_red: symbols of reduced inserted species """ struct = read(f_file) insert = Atoms...
35,683
def from_string(spec): """Construct a Device from a string. Args: spec: a string of the form /job:<name>/replica:<id>/task:<id>/device:CPU:<id> or /job:<name>/replica:<id>/task:<id>/device:GPU:<id> as cpu and gpu are mutually exclusive. All entries are optional. Returns: A Device. ...
35,684
def load_HDFS_data_timestamp_approach(input_path, time_delta_sec, timestamp_format, cached_workflow_path='data_df.csv', sep=',', encoding ='utf-8', cache_workflow=True): """ Downloads cached workflow data from csv file Args: input_path: path to cached workflow csv file time_...
35,685
def test_method(task_name, method_name, tempdir, image): """Test application of a method.""" import anndata task = getattr(openproblems.tasks, task_name) method = getattr(task.methods, method_name) adata = task.api.sample_dataset() openproblems.log.debug( "Testing {} method from {} task...
35,686
def pairwise_to_multiple(pwise, ref_seq, moltype, info=None): """ turns pairwise alignments to a reference into a multiple alignment Parameters ---------- pwise Series of pairwise alignments to ref_seq as [(non-refseq name, aligned pair), ...] ref_seq The sequence common...
35,687
def get_dashboard(title: str): """Get a dashboard by title""" dashboards = sdk.search_dashboards(title=title) if not dashboards: print(f"dashboard {title} was not found") return None return dashboards[0]
35,688
def set_juju_model(model_name): """Point environment at the given model. :param model_name: Model to point environment at :type model_name: str """ global CURRENT_MODEL os.environ["JUJU_MODEL"] = model_name CURRENT_MODEL = model_name
35,689
async def get_party(sid, ulist): """ Request party info to users in ulist """ async with sio.session(sid) as session: requester = session['user'] if requester in ulist: print(f"{requester} wants its own party. Igoring.") ulist.remove(requester) for user in ulist: ...
35,690
def upload_openmrs(sink: fhir_client.FhirClient, patient_bundle: bundle.Bundle, locations: Dict[str, str]): """Upload Patient history bundles to OpenMRS. For each bundle, we have to know the individual Patient, Encounters, and Observations resources before uploading as the OpenMRS FHIR Module...
35,691
def monitor(game_id: int, population: Population, debug: bool = False, duration: int = 0, genome: Genome = None, ): """Monitor a single run of the given genome that contains a single GRU-node.""" print("\n===> MONITORING GENOME <===\n") if genome i...
35,692
def translate_tensor(tensor, input_size=32, nt=2): """ Data augmentation function to enforce periodic boundary conditions. Inputs are arbitrarily translated in each dimension """ ndim = len(tensor[0,0, :].shape) t = input_size//nt t_vec = np.linspace(0, (nt-1)*t, nt).astype(int) for i in...
35,693
async def get_icon(ctx: commands.Context, *, member: discord.Member = None) -> None: """ Send the author's icon url to the channel :param member: (Optional) you can pass a member if you want to view this member's icon """ # This command is not allowed in #general if not client.helpers.can_exec...
35,694
def _get_job_resources(args): """Extract job-global resources requirements from input args. Args: args: parsed command-line arguments Returns: Resources object containing the requested resources for the job """ logging = param_util.build_logging_param( args.logging) if args.logging else None ...
35,695
def am_api_post_json(api_path, data): """ POST json to the Archivematica API :param api_path: URL path to request (without hostname, e.g. /api/v2/location/) :param data: Dict of data to post :returns: dict of json data returned by request """ am_url = os.environ["ARCHIVEMATICA_URL"] am_u...
35,696
def runtest_setup(item: pytest.Item) -> None: """Disable garbage collection before running tests.""" # Disable garbage collection gc.disable()
35,697
def collect_checkpoint_paths(checkpoint_dir): """ Generates a list of paths to each checkpoint file found in a folder. Note: - This function assumes, that checkpoint paths were written in relative. Arguments: checkpoint_dir (string): Path to the models checkpoint directory ...
35,698
def cosine_distance(input1, input2): """Computes cosine distance. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. Returns: torch.Tensor: distance matrix. """ input1_normed = F.normalize(input1, p=2, dim=1) input2_normed = F.no...
35,699