content
stringlengths
22
815k
id
int64
0
4.91M
def uninstall_cluster_logging(): """ Function to uninstall cluster-logging from the cluster * Deletes the project "openshift-logging" and "openshift-operators-redhat" """ # Validating the pods before deleting the instance pod_list = get_all_pods(namespace=constants.OPENSHIFT_LOGGING_NAME...
76,300
def uniquify(lst: List[T], key: Optional[Callable[[T], K]] = None) -> List[T]: """Remove duplicates in lst but preserve the order Args: lst: a sequence with possible duplicates key: a mapping from an element of lst to its identity (default lambda x: x) """ seen: Set[K] = set() resul...
76,301
def register_schema(regions: List[Region], providers: Dict[(Region, List[Provider])], db_name: str, schema_base: DeclarativeMeta, entity_type: EntityType = None): """ function for register schema,please declare them before register ...
76,302
def make_point_plot(x,y): """It plots the point chart of the data""" data_points = pd.DataFrame({'x': x.flatten(), 'y': y.flatten()}) chart = alt.Chart(data_points).mark_point(size=50, color='red',filled=True).encode( x="x", y="y" ) return chart
76,303
def test_tk_helper_as_item_missing_helper(): """Directly attempt access as item""" with pytest.raises(tk.HelperError): tk.h[u"nothere"]()
76,304
def single_source_shortest_path(graph, src): """ Act on Single Source Shortest Path and return path as dictionary, where each node is expanded to have its """ from algs20_graph.single_source_sp import dijkstra_sp (_, edge_to) = dijkstra_sp(graph, src) expanded = {} for n in graph.nodes(...
76,305
def printMainMenuHeader(internetStatus, returnObject, internetDataDictionary): """ :param internetStatus: True or False :param internetDataDictionary: {ping, downloadSpeed, uploadSpeed} :return: if no connection returns 'unknown' dictionary """ returnDictionary={ 'ping': 'unknown', ...
76,306
def busco_datasets(): """BUSCO dataset information :return: List containing information for each dataset available in file BUSCO_dataset.csv under data directory. .. seealso:: Additional information on BUSCO datasets available. - :doc:`BUSCO datasets <../../../data/BUSCO_datasets>` .. seealso:: ...
76,307
def aveThick(sit): """ Only calculates ave thickness for min and max time... no area weighting """ minSep = np.squeeze(np.apply_over_axes(np.nanmean,sit[:,9,:,:],(1,2))) minMar = np.squeeze(np.apply_over_axes(np.nanmean,sit[:,3,:,:],(1,2))) print '\nCompleted: Calculated average for Sept/Ma...
76,308
def get_module_version(): """This function gets the version number of the scripts and returns them in array form.""" modules = MODULE_LIST() scripts = [] for module in modules: if module.SCRIPT.public: if os.path.isfile('.'.join(module.__file__.split('.')[:-1]) + '.json') and module....
76,309
def BP(bp_state: BPState, temperature: float = 0.0) -> BeliefPropagation: """Function for generating belief propagation functions. Args: bp_state: Belief propagation state. temperature: Temperature for loopy belief propagation. 1.0 corresponds to sum-product, 0.0 corresponds to max-...
76,310
def whois_reg_date(whois): """ Fecha en la que fue registrado el sitio""" reg_date = [] try: reg_date = whois.creation_date if reg_date != None: if isinstance(reg_date, datetime.date): reg_date = reg_date elif len(reg_date) > 1: reg_dat...
76,311
def test_initialize(): """test_initialize.""" pass
76,312
def get_answer_indices_from_sentence(answer_text: str, sentence: str, loose_match: bool = False): """ first match is returned in match case Args: answer_text (str) sentence (str) loose_match (bool) : if True, regex also matches substrings Returns: None, if no match ...
76,313
def imdb_get_data(title, mtype, api_keys=[]): """This function fetches the poster url and other data related to Imdb movies from Google Custom Search JSON API.""" movie_title = title media_type = mtype gcsearch_api_key = api_keys[0] imdb_custom_search_id = api_keys[1] query = urllib.parse.q...
76,314
def nnlsfit(data, bvals, region=None): """ Implement Non Negative Fitting for IVIM Parameters ---------- data: array-like, 4D Matrix bvals: array-like region: array-like, [(x1,x2),(y1,y2),(z1,z2)] optional (default= None) Returns ------- d_star: 3D Matrix Th...
76,315
async def clear_thumb_nail(message: Message): """ delete thumbnail """ await message.edit("`processing ...`") if os.path.exists(Config.THUMB_PATH): os.remove(Config.THUMB_PATH) await SAVED_SETTINGS.find_one_and_delete({'_id': 'CUSTOM_THUMB'}) await message.edit("✅ Custom thumbnail de...
76,316
def check_if_scheduled_run(time_run: str = None, time_schedule: str = None) -> bool: """ Check if run was scheduled or started by user. Args: time_run (str, optional): The time the Flow was started. Defaults to None. time_schedule (str, optional): Scheduled time of Flow. Defaults to None. ...
76,317
def show_visual_results(x_fwd, x_inv, y_fwd, y_inv, disp_fields, show_visual=0, comet=None, fig_name=""): """ This function shows the results of input and output images and the displacement fields. :param x_fwd: an array of size (batch, 1, H, W, D) :param x_inv: an array of size ...
76,318
def test_anon_access_to_test1_account(account_user1): """verify that anonymous users can't access a users account :param account_user1: RDF_Document result of conftest.account_user1(). It's passed in automatically by py.test. """ resource_url = account_user1.default_subject() test_helper.resource_ac...
76,319
def controlled(gate): """Return a controlled quantum gate, given a quantum gate. If 'gate' operates on :math:`n` qubits, then the controlled gate operates on :math:`n+1` qubits, where the most-significant qubit is the control. Parameters ---------- gate : np.ndarray[complex] A quantum ...
76,320
def get_links(anumberscode): """ Finds CloudStor links for selected anumbers Args: `anumberscode`=list of anumbers Returns: `FilteredList`= list of corresponding links """ try: FileDirectory=pd.read_csv('https://geo.loop-gis.org/files/FileDirectory.csv',encoding = "ISO-88...
76,321
def passed_test(dtype, as_matrix, provide_C, trans_a, trans_b): """ Run one general matrix-matrix multiplication test. Arguments: dtype: either 'float64' or 'float32', the NumPy dtype to test as_matrix: True to test a NumPy matrix, False to test a NumPy ndarray provide_C: ...
76,322
def handler_500(request, exception=500, template_name='handler_500.html'): """ handler_500 自定义500错误 只有在Debug == False的时候生效 """ return render(request, template_name)
76,323
async def on_ready(): """http://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready""" await bot.change_presence(status=discord.Status.idle) print(f"Init {bot.user.name}-{bot.user.id}\nAPI version: {discord.__version__}\nbot version: {__version__}") await bot.change_presence(status=discord.Stat...
76,324
def re_repl_escape(s): """ Escape backreferences in a string, for the second arg of re.sub(). Parameters: s: the string to escape Dependencies: modules: re """ return re.sub(r'\\([1-9][0-9]?)', r'\\\\\1', s)
76,325
def test_authenticate_none(): """Test overriding auth.""" conf = GenericNamespace(password_file='.') assert PasslibAuthenticator(conf).authenticate(req('a', 'b'))
76,326
def get_x_vals(stats: dict, x_type: str, date_range: list[tuple]) -> list: """Gets the specified x value within a given date range.""" if x_type in X_OPTIONS.values() and x_type != X_OPTIONS[1]: return [round(stats[date][x_type]) for date in date_range] else: # Date return date_range
76,327
def allowed_file(filename): """判断filename是否有后缀以及后缀是否在app.config['ALLOWED_EXTENSIONS']中""" return '.' in filename and filename.rsplit( '.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
76,328
def create_resource_group( profile_credentials, subscription_id: str, location: str, resource_group_name: str ) -> ResourceGroup: """Creates resource group if it doesn't exist Args: profile_credentials : credentials from Azure login subscription_id (str): subscription you wish to use ...
76,329
def split_data(data, ratio, shuffle=1): """Split dataset according to ratio, larger split is first return""" n_exs = len(data[0]) split_pt = int(n_exs * ratio) splits = [[], []] for col in data: splits[0].append(col[:split_pt]) splits[1].append(col[split_pt:]) return tuple(splits...
76,330
def get_user_session_data(parent_folder, user_id, user_session_id): """ Combine accelerometer, gyroscope, and activity labels for a specific session of a user Note: Timestamps are ignored when joining accelerometer and gyroscope data. :param user_id: user id :param user_session_id: user session id ...
76,331
def test_create_html(): """Test creating the gallery.""" html = gallery_creator.create_html(TEST_IMG_DIR) html_length = len(html) logger.debug("HTML length {0}".format(html_length)) assert "<!DOCTYPE html>" in html
76,332
async def test_climate_thermostat_schedule_temporary_hold(hass): """Test a thermostat with the temporary schedule hold that is online.""" mock_thermostat = _get_mock_thermostat_schedule_temporary_hold() mock_nuheat = _get_mock_nuheat(get_thermostat=mock_thermostat) with patch( "homeassistant.co...
76,333
def jtag(tag): """ Helper to translate tag to serializable format""" return (tag[0].devanagari(strict_io=False), [t.devanagari(strict_io=False) for t in list(tag[1])])
76,334
def add_dctmask_config(cfg): """ Add config for DCT-Mask. """ # For MaskRCNNDCTHead cfg.MODEL.ROI_MASK_HEAD.DCT_VECTOR_DIM = 300 cfg.MODEL.ROI_MASK_HEAD.MASK_SIZE = 128 cfg.MODEL.ROI_MASK_HEAD.DCT_LOSS_TYPE = "l1" cfg.MODEL.ROI_MASK_HEAD.MASK_LOSS_PARA = 1.0
76,335
def progress_context( endpoint: IEndPoint, title: str, dir_cache: Optional[IDirCache], elapsed_time_key=None, ): """ Creates a progress context which submits $/customProgress notifications to the client. Automatically updates the progress based on a previous invocation for some acti...
76,336
def _nongeo_latlng2xy(lat_deg, lng_deg): """ """ lat = _DEG_TO_RAD * lat_deg lng = _DEG_TO_RAD * lng_deg # First, project to pseudo-mercator # https://en.wikipedia.org/wiki/Web_Mercator_projection#Formulas x_proj = _EPSG_3857_X_EXTENT / (2.0 * math.pi) * lng y_proj = _EPSG_3857_Y_EXTENT...
76,337
def read_file(file_path): """Reads a file contents given a file path""" file_contents = None with open(file_path) as f_desc: file_contents = f_desc.read() if not file_contents: raise CLIError('Could not read {}'.format(file_path)) return file_contents
76,338
def part_2a_namd_equilb_NPT_control_file_written(job): """General check that the namd_equilb_NPT_control_file (high temperature to set temp NAMD control file) is written.""" return namd_control_file_written(job, namd_equilb_NPT_control_file_name_str)
76,339
def start_service(service_name: str, computer: str): """Запускает службу""" subprocess.check_output( ["powershell", "-Command", f"""(Get-WmiObject -Class Win32_Service -Computer {computer} -filter "Name='{service_name}'").StartService()"""], )
76,340
def main(): """ Parsing command line parameters. Creating target matrix. Fitting an SGCN. Predicting edge signs and saving the embedding. """ args = parameter_parser() set_seed(args.seed) context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target) if args.devic...
76,341
def AutoLayoutModel( config_path: str, model_path: Optional[str] = None, label_map: Optional[Dict]=None, device: Optional[str]=None, extra_config: Optional[Union[Dict, List]]=None, ) -> "BaseLayoutModel": """[summary] Args: config_path (:obj:`str`): The path to the confi...
76,342
def assert_positive_negative_temporal_consistency(y, t, month_variance=1): """Helper function to assert malware-goodware temporal constraint (C2). In any given testing period, all testing objects must be from the time window under test. In the malware domain this constraint has often been violated so t...
76,343
def shape_small_first(shape): """sort a tuple so that the smallest entry is swapped to the beginning """ if len(shape) <= 2: # no changing dimensions if channel-dim is missing return shape smallest_dim = np.argmin(shape) if smallest_dim != 0: # assume that smallest dim is color channel ...
76,344
def reformat_cmplx_hoh(cmplx): """ get a complex has HoH and split it """ stoi = [] for cond in cmplx: tmp_stoi = io.makehashlist() tmp_prot_nr = [] for repl in cmplx[cond]: pks = {k: cmplx[cond][repl][k]["I"] for k in cmplx[cond][repl]} pks2 = io.make...
76,345
def filter_builtin(): """filter: Filter items using a function. Prefer list comprehension.""" return "{}ged top secret".format( ''.join(filter(lambda info: info not in 'open', "pentagone")))
76,346
def calculate_gold(*items): """Calculate gold for buying given items""" # access cost in the item dictionary get_cost = lambda x: x[0][x[1]]['cost'] # return sum of costs of all items return sum( # get cost of each item map(get_cost, # map items onto their categories ...
76,347
def skip_reload(cache_load_time: Optional[datetime.datetime], refresh_cache: bool) -> bool: """Skip reloading the cache?""" return abc_depoyment_map.skip_reload(cache_load_time, refresh_cache, REQUIRE_REFRESH_LIMIT)
76,348
def combined_bbox(layers): """ Returns a bounding box for ``layers`` or None if this is not possible. """ bboxes = [layer.bbox for layer in layers if layer.bbox is not None and layer.bbox.width > 0 and layer.bbox.height > 0] if not bboxes: return None lefts, tops, rights, ...
76,349
def import_codec(name: str): """ Import codec *name* and return the module. """ import delphin.codecs codecs = namespace_modules(delphin.codecs) fullname = codecs[name] return importlib.import_module(fullname)
76,350
def is_named(name): """ :samp:`Predicate for loose class-name detection.` :: f(cls) = cls.name == name or cls.qualified_name == name :param name: the class-name or qualified class-name in the detection :return: lambda for loose class-name detection """ return lambda cls: name == c...
76,351
def get_and_colleagues(ref_string): """ :param ref_string: :return: """ match = COLLEAGUES_PAT.search(ref_string) if match: andcolleagues = match.group('andcolleagues') return ref_string.find(andcolleagues), len(andcolleagues) return 0, 0
76,352
def app_factory(global_config, django_wsgi_application): """ Paste app factory that imports and returns the given WSGI applicaton. Args: global_config: The global paste configuration django_wsgi_application: The wsgi application to deploy as a dotted path Returns: The WSGI appl...
76,353
def fix_arn(arn): """Function that attempts to "canonicalize" the given ARN. This includes converting resource names to ARNs, replacing incorrect regions, account IDs, etc.""" if arn.startswith("arn:aws:lambda"): parts = arn.split(":") region = parts[3] if parts[3] in config.VALID_REGIONS el...
76,354
def ocr_extract(image_data: bytes, link: str, tld: str) -> list[str]: """Scan for all valid URLs from a given `image_data` bytes string Args: image_data (bytes): Bytes string of image to be scanned link (str): URL source of image to be scanned tld (str): Top Level Domain to scan for ...
76,355
def date_range(start, stop, step=datetime.timedelta(days=1)): """This function is similar to "normal" `range`, but it operates on dates instead of numbers. Taken from "Python Cookbook, 3rd ed.". """ while start < stop: yield start start += step
76,356
def route(route : dict[str : FunctionType], filter : FunctionType = lambda x : x): """Routes links in clisd.py""" last_link = None def route_link(e=None, page : str = None, _route : dict[str : FunctionType] = route): route = _route # Finds page to route in url if page: ...
76,357
def test_offset_consts(): """ Make sure librdkafka's logical offsets are available. """ assert confluent_kafka.OFFSET_BEGINNING == -2 assert confluent_kafka.OFFSET_END == -1 assert confluent_kafka.OFFSET_STORED == -1000 assert confluent_kafka.OFFSET_INVALID == -1001
76,358
def make_answer(): """Create the message to send""" # Create the message and set a subject msg = EmailMessage() msg["Subject"] = "A random image." try: # Choose an image attachement = IMG_FOLDER + "/" + rdm(IMG_FOLDER) # Attach the image to the email with open(attach...
76,359
def download_assets(stac_item: StacItem, save_directory: str, from_bucket: bool = False, nsl_id: str = None) -> List[str]: """ Download all the assets for a StacItem into a directory :param nsl_id: ADVANCED ONLY. Only necessary if more than one nsl...
76,360
def shake_128() -> HashAlgorithm: """ Convenience function to create hash algorithm object. """ return HashAlgorithm(HashAlgorithmId.SHAKE_128)
76,361
def update_action_effects_with_negated_counterparts(action: Action, negpreds): """ """ neweffects = [] for eff in action.effects: if not is_propositional_effect(eff): raise RepresentationError(f"Don't know how to update negated counterpart atoms for effect {eff}") atom = eff.ato...
76,362
def is_listlike(x: Any) -> bool: """Check whether `x` is list like, e.g., Tuple, List, or Numpy object. Parameters: ---------- x: A python object to check. Returns: ---------- `True` iff `x` is a list like sequence. """ return (isinstance(x, (list, tuple)))
76,363
def read_csv_results(conf): """ After all experiments have run, read in Rsquared and RMSE values for all jobs into dictionaries Args: conf: Settings object, containing fields where to find saved results, which are stored as CSVs Returns: Two dictionaries, for Rsq and RMSE, with entries ...
76,364
def datasetDataText(request, dataset_name): """ Returns data in text format for a specific dataset. """ # header_language = request.GET.get('header_language', None) # dataset = models.Datasets.objects.get(dataset_name = dataset_name) dataset_file_name = dataset.dataset_file_name # ...
76,365
def initialize_secrets(secrets: dict[str, Any]): """Initialize secrets.""" for file_name, content in secrets.items(): with (constants.SECRETS_VOLUME / file_name).open("wt") as stream: stream.write(content)
76,366
def order_detail(user_key, category_key, order_key): """ The page showing the details of a single order -Fetch a specific order including all steps (GET) It also handles PUT and DELETE of the order It also handles updates an existing order """ error = None editable = False order_deta...
76,367
def test_integrals_pkg_with_filtering(crd_file): """Filtering in packages and get the sum of the integrals.""" _, _, _, fname = crd_file shots_per_pkg = 1 max_ions_per_shot = 1 crd = CRDFileProcessor(Path(fname)) crd.spectrum_full() crd.packages(shots_per_pkg) crd.filter_max_ions_per_pk...
76,368
def distance_corr(X, Y): """ Computes the distance correlation between X and Y. Taken from pypi package dcor based on the paper: *Measuring and testing dependence by correlation of distances* by Gábor et Al (2007) Parameters ---------- X : numpy array like object where the rows correspon...
76,369
def pinyin_dict_affiche(request): """recevoir les valeurs des formulaires front-end via POST et transmission des informations pinyin analysées au front-end Args: request (QueryDict): les valeurs des formulaires front-end Returns: data_pinyin (JSON): informations...
76,370
def diff_sort(matrices, x, softmax=softmax): """ Approximate differentiable sort. Takes a set of bitonic sort matrices generated by bitonic_matrices(n), sort a sequence x of length n. Values may be distorted slightly but will be ordered. """ for l, r, map_l, map_r in matrices: a, b = l @ x,...
76,371
def searchwiki(txt, lang='en'): """ parse wiki data. """ input = [] for i in txt.split(): if i.startswith('-'): if len(i) != 3: continue else: lang = i[1:] continue input.append(i.strip().capitalize()) what = "_".join(input) url = u'http://%s....
76,372
def test(): """Runs the model on the test data.""" modelA.eval() modelB.eval() test_loss = [] errors = [] with torch.no_grad(): for batch_idx, data in enumerate(test_loader): data = data.permute(0, 3, 1, 2) dataA = data[:, modA].float().to(device1) dat...
76,373
def ifgcfg_exists(ifgcfg_id, version): """Return True if ifg-cfg exists.""" query = { "query": { "ids": { "values": [ifgcfg_id], } }, "fields": [] } index = "grq_{}_s1-gunw-ifg-cfg".format(version) result = query_es(query, index) r...
76,374
def find_built_exe( source, name ): """ Find an executable that was built in the repo :param source: The location of the exe's project, e.g. tools/convert :param name: The name of the exe, without any platform-specific extensions like .exe :return: The full path, or None, of the exe """ exe...
76,375
def calibration_image(file_name, coordinates): """calibrate a source image Arguments: file_name {int} -- image index coordiantes {list} -- list of coordinates for homography to plot """ prefix_length = 6 - len(str(file_name)) source = path_to_image + str(0)*prefix_length + str(file_...
76,376
def decompress(structure: Value): """ Performs decompression on the input value if the codec field has been set and is valid. If the data is being sent uncompressed already, will just reshape the data using the sizes specified in the dimension field. Parameters ---------- structure : Value ...
76,377
def main(): """" read Streitberg-1910-3645.tsv, link data to concepticon, write concepts.tsv """ # read file and clean column "sense" dfgot = pd.read_csv(in_path, sep="\t", usecols=["sense", "pos"]) dfgot["sense"] = [re.sub("[†\\d\\.\\*\\?\\~]", "", g) for g in dfgot.sense] # define...
76,378
def incubation_dist(t: np.ndarray) -> np.ndarray: """Incubation period as a log-normal PDF (Lauer et al., 2020). Args: t: np.array of days of incubation (i.e. days from infection to symptoms). Returns: Relative probability of the specified incubation time. """ mu = 1.621 sig = 0.418 rv = scipy.s...
76,379
def pid_from_context_or_data(value, context, **kwargs): """Get PID from marshmallow context.""" pid = (context or {}).get('pid') if pid is None: return value else: return pid.pid_value
76,380
def test_gev(shape): """ tests based on observations made by Friederichs, P., & Thorarinsdottir, T. L. (2012). Forecast verification for extreme value distributions with an application to probabilistic peak wind prediction. Environmetrics, 23(7), 579-594. :param shape: varying shape parameter :r...
76,381
def partial_build(src, lang, bsp_c3, opt_level, march, reporter): """ Compile source and return an object """ if lang == 'c3': srcs = [ relpath('..', 'librt', 'io.c3'), bsp_c3, io.StringIO(src)] o2 = c3c( srcs, [], march, opt_level=opt_level, ...
76,382
def clean_phoenix_2014_trans(prediction): """ Yutong I think the format of ground truth annotation is already well processed. Some parts of predicted gloss sequence might be processed using this func. e.g. combine single char with + """ prediction = prediction.strip() prediction = re.sub(r"_...
76,383
def ManagerFactory(name, superclass, qs=QuerySet): """Create a manager class, using the given superclass, and adding django_pg's specific behavior. """ # It's completely fine to use our custom manager for related fields, # and it's necessary, since we need to ensure that our custom queries # and...
76,384
def reaperstandalone(): """Standalone command for scanning repo.""" args = parse_args(desc="Remove obsolete lab images", component="reaper") wilford_grimly = Reaper( host=args.repo, path=args.path, owner=args.owner, name=args.name, keep_dailies=args.dailies, k...
76,385
def gfit1(xi,yi,m=5): """ moments around a peak (also) rely on number of pixels left and right of the peak. Masking optional """ print("GFIT1") ipeak = yi.argmax() xpeak = xi[ipeak] ypeak = yi[ipeak] print(ipeak,xpeak,ypeak) print(xi[ipeak-m:ipeak+m]) print(yi[ipeak-m:ipeak+m...
76,386
def log_stack(logger, level=logging.INFO, limit=None, frame=None): """ Display the current stack on ``logger``. This function is designed to be used during emission of log messages, so it won't call itself. """ if showing_stack.inside: return showing_stack.inside = True try: ...
76,387
def characteristic_matrix_p(lambda_, d, n, theta): """Compute the characteristic matrix M_j^p for a layer of a material stack and p-polarized light. Uses (4.49) to compute (4.55) from BYU optics book, edition 2015 Parameters ---------- lambda_ : `float` wavelength of light, microns d :...
76,388
def export_custom_keywords(sbox): """export with custom keywords""" sbox.build() wc_dir = sbox.wc_dir # 248=SVN_KEYWORD_MAX_LEN-7 where 7 is '$', 'Q', 'q', ':', ' ', ' ', '$' alpha_content = ('[$Qq: %s $ $Pp: %s $]\n' % (sbox.repo_url[:248], (sbox.repo_url + '/A/B/E/...
76,389
def nets_ib_by_bus_zone_with_boundary_branches( net, eq_type=None, separate_eqs=True, duplicated_boundary_bus_elements=True, **kwargs): """ INPUT: **net** - pandapower net - In net.bus.zone different zones must be given. OPTIONAL: **eq_type** (str, None) - If given, equivalent eleme...
76,390
def get_label_colours(num_class): """ return color code for visualizing affordance/object map """ all_label_colors = [] random.seed(255) for i in range(num_class): curr_color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)] all_label_colors.append(curr_c...
76,391
def timed(fn): """Simple timing decorator that stores the elapsed time as a string property called 'timed' to the fn. """ @wraps(fn) def _timer(*args, **kwargs): start = time.time() fn(*args, **kwargs) end = time.time() diff = end - start elapsed_time = f"[!]...
76,392
def get_column_letter(col_idx): """Convert a column number into a column letter (3 -> 'C') Right shift the column col_idx by 26 to find column letters in reverse order. These numbers are 1-based, and can be converted to ASCII ordinals by adding 64. """ # these indicies corrospond to A -> ZZZ ...
76,393
def get_default_cacheinfo(): """ Return default CacheInfo """ return __cacheinfos[__SECTION_CACHE_DEFAULT]
76,394
def show_values(pc, ax, fontsize=16, fmt="%.3f", **kw): """ For bar charts, show the value of the height of the bar. """ pc.update_scalarmappable() for p, color, value in zip( pc.get_paths(), pc.get_facecolors(), pc.get_array()): x, y = p.vertices[:-2, :].mean(0) if np.a...
76,395
def get_packets_for_flows(sub, flows): """ Get packets sent from a subscriber to match a set of flows Args: sub (SubscriberContext): subscriber to send packets towards flows ([FlowDescription]): list of flows to send matching packets to Returns: list of scapy packets to send ...
76,396
def lower_array(x1_arr, y1_arr, x2_arr, y2_arr): """function to find the lower bound of two curves(x1, y1), and (x2, y2) represented by two arrays. """ # special use: for the first comparison, if y1_arr is [], then y2_arr is passed to it x1_arr = np.asarray(x1_arr) x2_arr = np.asarray(x2_arr) y...
76,397
def main(): """ Computational Genomics Lab, Genomics Institute, UC Santa Cruz Toil vg DNA-seq pipeline DNA-seq fastqs are split, aligned to an indexed vg reference graph, and variant-called using the vg toolset. General usage: 1. Type "toil-vg generate-config": Produce an editable ...
76,398
def make_reconstruction_movie( ims, titles=None, n_rows=0, n_cols=0, save_file=None, frame_rate=15, dpi=100): """Produce movie with original video and reconstructed videos. `ims` and `titles` are corresponding lists; this data is plotted using a linear index, i.e. if n_rows = 2 and n_cols = 3 the i...
76,399