content
stringlengths
22
815k
id
int64
0
4.91M
def elastic(X, kernel, padding, alpha=34.0): # type: (Tensor, Tensor, int, float) -> Tensor """ X: [(N,) C, H, W] """ H, W = X.shape[-2:] dx = torch.rand(X.shape[-2:], device=kernel.device) * 2 - 1 dy = torch.rand(X.shape[-2:], device=kernel.device) * 2 - 1 xgrid = torch.arange(W, devi...
5,349,600
def fixture_make_bucket(request): """ Return a factory function that can be used to make a bucket for testing. :param request: The Pytest request object that contains configuration data. :return: The factory function to make a test bucket. """ def _make_bucket(s3_stub, wrapper, bucket_name, reg...
5,349,601
def prop_nodes(graph, nodes_generator, message_func='default', reduce_func='default', apply_node_func='default'): """Functional method for :func:`dgl.DGLGraph.prop_nodes`. Parameters ---------- node_generators : generator The generator...
5,349,602
def main(): """Start main loop.""" logger.info("Starting main loop") starttime = time.time() i = 1 dispatch_task("trigger_on_startup") dispatch_task("create_default_settings") while IS_RUNNING: # execute_next_task() interval_trigger.tick() # Sleep for exactly one s...
5,349,603
def get_member_struc(*args): """ get_member_struc(fullname) -> struc_t Get containing structure of member by its full name "struct.field". @param fullname (C++: const char *) """ return _ida_struct.get_member_struc(*args)
5,349,604
def pop(): """Check the first task in redis(which is the task with the smallest score) if the score(timestamp) is smaller or equal to current timestamp, the task should be take out and done. :return: True if task is take out, and False if it is not the time. """ task = connection.zrange(QUEUE_K...
5,349,605
def xml_to_dictform(node): """ Converts a minidom node to "dict" form. See parse_xml_to_dictform. """ if node.nodeType != node.ELEMENT_NODE: raise Exception("Expected element node") result = (node.nodeName, {}, []) # name, attrs, items if node.attributes != None: attrs = node.attribut...
5,349,606
def test_22(): # check pad_idseqs """ OhOh this fails seqs_token = [[ "Der", "Helmut", "Kohl", "speist", "Schweinshaxe", "mit", "Kohl", "in", "Berlin", "."]] """ targets = [[ "[PAD]", "[UNK]", "PER", "PER", "[UNK]", "[UNK]", "[UNK]", "[UNK]", "[UNK]", "LOC", "[UNK]"]] ...
5,349,607
def TranslateCoord(data, res, mode): """ Translates position of point to unified coordinate system Max value in each direction is 1.0 and the min is 0.0 :param data: (tuple(float, float)) Position to be translated :param res: (tuple(float, float)) Target resolution :param mode: (TranslationMode) Work mode. Availa...
5,349,608
def _get_mutator_plugins_bucket_url(): """Returns the url of the mutator plugin's cloud storage bucket.""" mutator_plugins_bucket = environment.get_value('MUTATOR_PLUGINS_BUCKET') if not mutator_plugins_bucket: logs.log_warn('MUTATOR_PLUGINS_BUCKET is not set in project config, ' 'skipping c...
5,349,609
def objectify_json_lines(path_buf_stream, from_string=False, fatal_errors=True, encoding=_DEFAULT_ENCODING, ensure_ascii=False, encode_html_chars=False, avoid_memory_pres...
5,349,610
def gll_int(f, a, b): """Integrate f from a to b using its values at gll points.""" n = f.size x, w = gll(n) return 0.5*(b-a)*np.sum(f*w)
5,349,611
def error404(request, exception): """View for 404 page.""" responses = open(os.path.join(BASE_DIR, 'CollaboDev/404_responses.txt')) responses = responses.read().split('\n') message = random.choice(responses) context = { 'message': message, 'error': exception } re...
5,349,612
def save_xp( path: Union[str, Path], consoles: Iterable[Console], compress_level: int = 9, ) -> None: """Save tcod Consoles to a REXPaint file. `path` is where to save the file. `consoles` are the :any:`tcod.console.Console` objects to be saved. `compress_level` is the zlib compression le...
5,349,613
def _get_remote_user(): """ Get the remote username. Returns ------- str: the username. """ return input('\nRemote User Name: ')
5,349,614
def parse_args(): """Parse the args.""" parser = argparse.ArgumentParser( description='example code to play with InfluxDB') parser.add_argument('--host', type=str, required=False, default='localhost', help='hostname influxdb http API') parser.add_a...
5,349,615
def main(args): """ Process the file created by the IDE into a log of builds, which it will put in the folder 'data'. By default it will look for the idea.log file in the default places for Android Studio versions 4.2 and 4.1. Pass an argument to look in a different place instead """ if args...
5,349,616
def generate_warm_starts(vehicle, world: TrafficWorld, x0: np.array, other_veh_info, params: dict, u_mpc_previous=None, u_ibr_previous=None): """ Generate a dictionar...
5,349,617
def test_setOwner_no_short_name_and_long_name_is_short(caplog): """Test setOwner""" anode = Node('foo', 'bar', noProto=True) with caplog.at_level(logging.DEBUG): anode.setOwner(long_name ='Tnt') assert re.search(r'p.set_owner.long_name:Tnt:', caplog.text, re.MULTILINE) assert re.search(r'p.s...
5,349,618
def setup_logging(verbosity: int) -> None: """ Process -v/--verbose, --logfile options """ # Log level logging.root.addHandler(bufferHandler) logging.root.setLevel(logging.INFO if verbosity < 1 else logging.DEBUG) _set_loggers(verbosity) logger.info('Verbosity set to %s', verbosity)
5,349,619
def nf_regnet_b4(pretrained=False, **kwargs): """ Normalization-Free RegNet-B4 `Characterizing signal propagation to close the performance gap in unnormalized ResNets` - https://arxiv.org/abs/2101.08692 """ return _create_normfreenet('nf_regnet_b4', pretrained=pretrained, **kwargs)
5,349,620
def test_process_mutation_workflow(): """Integration test to make sure workflow runs""" validfiles = pd.DataFrame( { "fileType": ['vcf', 'maf'], "path": ["path/to/vcf", "path/to/maf"] } ) database_mapping = pd.DataFrame( { "Database": ['vcf2maf...
5,349,621
async def amireallyalive(alive): """ For .alive command, check if the bot is running. """ await alive.edit("**Apun Zinda He Sarr. \nJarvis is in your service ^.^** \n`🇮🇳BOT Status : ` **☣Hot**\n\n" f"`My peru owner`: {DEFAULTUSER}\n\n" "`Telethon version:` **6.0.9**\...
5,349,622
def load_data_binary_labels(path: str) -> Tuple[pd.DataFrame, pd.DataFrame]: """Loads data from CSV file and returns features (X) and only binary labels meaning (any kind of) toxic or not""" df = pd.read_csv(path) X = df.comment_text.to_frame() y = df[config.LIST_CLASSES].max(axis=1).to_frame(name=...
5,349,623
def parse(html_url): """Parse.""" html = www.read(html_url) soup = BeautifulSoup(html, 'html.parser') data = {'paragraphs': []} content = soup.find('div', class_=CLASS_NAME_CONTENT) for child in content.find_all(): text = _clean(child.text) if child.name == 'h3': d...
5,349,624
def get_tp_algorithm(name: str) -> GenericTopologyProgramming: """ returns the requested topology programming instance """ name = name.lower() if name == "uniform_tp": return UniformTP() if name == "joint_tp": return JointTP() if name == "ssp_oblivious_tp": return SSPObliviou...
5,349,625
def get_first_job_queue_with_capacity(): """Returns the first job queue that has capacity for more jobs. If there are no job queues with capacity, returns None. """ job_queue_depths = get_job_queue_depths()["all_jobs"] for job_queue in settings.AWS_BATCH_QUEUE_WORKERS_NAMES: if job_queue_de...
5,349,626
def rotations(images, n_rot, ccw_limit, cw_limit): """ Rotates every image in the list "images" n_rot times, between 0 and cw_limit (clockwise limit) n_rot times and between 0 and ccw_limit (counterclockwise limit) n_rot times more. The limits are there to make sense of the data augmentation. E.g: Rotating an...
5,349,627
def num_range(num): """ Use in template language to loop through numberic range """ return range(num)
5,349,628
def datamodel_flights_column_names(): """ Get FLIGHTS_CSV_SCHEMA column names (keys) :return: list """ return list(FLIGHTS_CSV_SCHEMA.keys())
5,349,629
def create_tomography_circuits(circuit, qreg, creg, tomoset): """ Add tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography...
5,349,630
def _insert(filepath, line_start, lines): """Insert the lines to the specified position. """ flines = [] with open(filepath) as f: for i, fline in enumerate(f): if i == line_start: # detect the indent of the last not empty line space = '' ...
5,349,631
def filter_background(bbox, bg_data): """ Takes bounding box and background geojson file assumed to be the US states, and outputs a geojson-like dictionary containing only those features with at least one point within the bounding box, or any state that completely contains the bounding box. This te...
5,349,632
def rename_columns(table, mapper): """ Renames the table headings to conform with the ketos naming convention. Args: table: pandas DataFrame Annotation table. mapper: dict Dictionary mapping the headings of the input table to the stan...
5,349,633
def randrange(start, stop, step: Optional[Any]) -> int: """ The first form returns a random integer from the range [0, *stop*). The second form returns a random integer from the range [*start*, *stop*). The third form returns a random integer from the range [*start*, *stop*) in steps of *step*. For...
5,349,634
def get_round(year, match): """Get event number by year and (partial) event name A fuzzy match is performed to find the most likely event for the provided name. Args: year (int): Year of the event match (string): Name of the race or gp (e.g. 'Bahrain') Returns: The round numbe...
5,349,635
def parse_tuple(s: Union[str, tuple]) -> tuple: """Helper for load_detections_csv, to parse string column into column of Tuples.""" if isinstance(s, str): result = s.replace("(", "[").replace(")", "]") result = result.replace("'", '"').strip() result = result.replace(",]", "]") i...
5,349,636
def clean(tweet): """ clean tweet text by removing links, special characters using simple regex statements Parameters ---------- tweet : String Single Twitter message Returns ------- tokenized_tweet : List List of cleaned tokens derived from the input Twitter message """ ...
5,349,637
def predict(x, u): """ :param x: Particle state (x,y,theta) [size 3 array] :param u: Robot inputs (u1,u2) [size 2 array] :return: Particle's updated state sampled from the motion model """ x = x + motionModel(x, u) + np.random.multivariate_normal(np.zeros(3), Q) return x
5,349,638
def plot_multiple(datasets, method='scatter', pen=True, labels=None, **kwargs): """ Plot a series of 1D datasets as a scatter plot with optional lines between markers. Parameters ---------- datasets : a list of ndatasets method : str among [scatter, pen] pen : bool, optional, default: T...
5,349,639
def _scale_enum(anchor, scales): """ 列举关于一个anchor的三种尺度 128*128,256*256,512*512 Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) #返回宽高和中心坐标,w:16,h:16,x_ctr:7.5,y_ctr:7.5 ws = w * scales #[128 256 512] hs = h * scales #[128 256 512] anchor...
5,349,640
def metamodel_from_file(file_name, **kwargs): """ Creates new metamodel from the given file. Args: file_name(str): The name of the file with textX language description. other params: See metamodel_from_str. """ with codecs.open(file_name, 'r', 'utf-8') as f: lang_desc = f.re...
5,349,641
def _python(data): """Generate python in current directory Args: data (dict): simulation Returns: py.path.Local: file to append """ import sirepo.template import copy template = sirepo.template.import_module(data) res = pkio.py_path('run.py') res.write(template.pyt...
5,349,642
def load_hosts_conf(path='/etc/hosts'): """parse hosts file""" hosts = {} try: with open(path, 'r') as f: for line in f.readlines(): parts = line.strip().split() if len(parts) < 2: continue addr = ip_address(parts[0]) ...
5,349,643
def get_first_env(*args): """ Return the first env var encountered from list PLEASE NOTE: Always prefer using get_env, this helper is for app transitioning to a new config structure. Example: get_first_env('DB_NAME', 'DATABASE_NAME') """ for name in args: if name in os.envi...
5,349,644
def pick(df, isnotnull=None, **kwargs): """Function to pick row indices from DataFrame. Copied from kkpandas This method provides a nicer interface to choose rows from a DataFrame that satisfy specified constraints on the columns. isnotnull : column name, or list of column names, that...
5,349,645
def _waveform_distortion(waveform, distortion_methods_conf): """ Apply distortion on waveform This distortion will not change the length of the waveform. Args: waveform: numpy float tensor, (length,) distortion_methods_conf: a list of config for ditortion method. a method will ...
5,349,646
def raw(files = 'english-kjv'): """ @param files: One or more treebank files to be processed @type files: L{string} or L{tuple(string)} @rtype: iterator over L{tree} """ # Just one file to process? If so convert to a tuple so we can iterate if type(files) is str: files = (files,) ...
5,349,647
def grouper(n, iterable): """ Browse an iterator by chunk of n elements """ it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
5,349,648
def plot_with_lambdas(linewidth=2.0,image_extension='svg'): """ Function to plot F with lambduhs for various snapshots. Parameters ---------- linewidth : float, optional The font size of the lines in the plot. This is set to 2.0 by default. image_extension : string, optional Speci...
5,349,649
def _pad_returns(returns): """ Pads a returns Series or DataFrame with business days, in case the existing Date index is sparse (as with PNL csvs). Sparse indexes if not padded will affect the Sharpe ratio because the 0 return days will not be included in the mean and std. """ bdays = pd.dat...
5,349,650
def add_header(r): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes. """ r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" r.headers['Cache-Control'] = 'public...
5,349,651
def man_page(): """Print manual page-like help""" print(""" USAGE image_purge.py [OPTIONS] OPTIONS -d, --dry-run Report but don't delete any images. -h, --help Print a brief help. --man Print man page-like help. -v, --verbose Print information messages to...
5,349,652
def rename_photos(old_name, folder_path, taken_date, file_extension): """Function reaname photo files names to their dates""" new_name = folder_path + "/" + taken_date + "." + file_extension os.rename(old_name, new_name)
5,349,653
def pair_sorter(aln): """Get the alignment name and attributes for sorting.""" return ( aln.name, not aln.first_in_pair, aln.unmapped, aln.supplementary_alignment, aln.secondary_alignment)
5,349,654
def _read_input_from(input_from): """ Reads the labels from the input from. """ inputs = [] for input_from_line in input_from.splitlines(): # Skip if line is empty. if input_from_line.strip() == '': continue # Load file content print(f"::debug::Loading labels fr...
5,349,655
def project_to2d( pts: np.ndarray, K: np.ndarray, R: np.ndarray, t: np.ndarray ) -> np.ndarray: """Project 3d points to 2d. Projects a set of 3-D points, pts, into 2-D using the camera intrinsic matrix (K), and the extrinsic rotation matric (R), and extrinsic translation vector (t). Note that this ...
5,349,656
def abort_cannot_update(_id, _type): """Abort the request if the entity cannot be updated.""" abort(400, message="Cannot update {} {}. Please try again.".format(_type, _id))
5,349,657
def enditall(): """Terminate program""" sys.exit(0)
5,349,658
def uncontract_general(basis, use_copy=True): """ Removes the general contractions from a basis set The input basis set is not modified. The returned basis may have functions with coefficients of zero and may have duplicate shells. If use_copy is True, the input basis set is not modified. ...
5,349,659
def read_sd15ch1_images(root_dir, image_relative_path_seq, resize=None, color=False): """ WARNING ------- - All images must have the same shape (this is the case for the frames, and all models but the ones of the "01-origina...
5,349,660
def generate_features(plz_ags, boundary_type, int_buildings_path, pri_buildings_path): """ Scan all available PLZ/AGS in the region. Populate PLZ/AGS building objects with data from region OSM dump (Geofabrik) Args: plz_ags: list...
5,349,661
def is_private_bool(script_dict): """ Returns is_private boolean value from user dictionary object """ return script_dict['entry_data']['ProfilePage'][0]['graphql']['user']['is_private']
5,349,662
def manage_greylist(request): """ View for managing greylist. """ message = None if request.method == 'POST': form = GreylistForm(request.POST) if form.is_valid(): # Set details to empty string if blank new_greylisted_guest = form.save(commit=False) ...
5,349,663
def get_regions(): """Summary Returns: TYPE: Description """ client = boto3.client('ec2') region_response = client.describe_regions() regions = [region['RegionName'] for region in region_response['Regions']] return regions
5,349,664
def _is_ignored_read_event(request): """Return True if this read event was generated by an automated process, as indicated by the user configurable LOG_IGNORE* settings. See settings_site.py for description and rationale for the settings. """ if ( django.conf.settings.LOG_IGNORE_TRUSTED_SU...
5,349,665
def test_compiler_bootstrap_from_binary_mirror( install_mockery_mutable_config, mock_packages, mock_fetch, mock_archive, mutable_config, monkeypatch, tmpdir): """ Make sure installing compiler from buildcache registers compiler """ # Create a temp mirror directory for buildcache usage ...
5,349,666
def aten_embedding(mapper, graph, node): """ 构造embedding的PaddleLayer。 TorchScript示例: %inputs_embeds.1 : Tensor = aten::embedding(%57, %input_ids.1, %45, %46, %46) 参数含义: %inputs_embeds.1 (Tensor): 输出,embedding后的结果。 %57 (Tensor): weights。 %input_ids.1 (Tensor): 需要进行embeddi...
5,349,667
def build_drivers(compilation_commands, linker_commands, kernel_src_dir, target_arch, clang_path, llvm_link_path, llvm_bit_code_out, is_clang_build): """ The main method that performs the building and linking of the driver files. :param compilation_commands: Parsed compilation commands...
5,349,668
def _validate_opts(opts): """ Check that all of the types of values passed into the config are of the right types """ def format_multi_opt(valid_type): try: num_types = len(valid_type) except TypeError: # Bare type name won't have a length, return the name of...
5,349,669
async def from_string(input, output_path=None, options=None): """ Convert given string or strings to PDF document :param input: string with a desired text. Could be a raw text or a html file :param output_path: (optional) path to output PDF file. If not provided, PDF will be returned as string ...
5,349,670
def parse_tuple(tuple_string): """ strip any whitespace then outter characters. """ return tuple_string.strip().strip("\"[]")
5,349,671
def create_size(): """Create a new size.""" in_out_schema = SizeSchema() try: new_size = in_out_schema.load(request.json) except ValidationError as err: abort(400, {'message': err.messages}) try: db.session.add(new_size) db.session.commit() except IntegrityError...
5,349,672
def inject_snakefmt_config( ctx: click.Context, param: click.Parameter, config_file: Optional[str] = None ) -> Optional[str]: """ If no config file argument provided, parses "pyproject.toml" if one exists. Injects any parsed configuration into the relevant parameters to the click `ctx`. """ if c...
5,349,673
def test_screen_methods_exist(): """ Test that a couple of methods exist, but don't do anything. """ t = MockTurtle() t.screen.tracer() t.screen.update()
5,349,674
def sort_by_ctime(paths): """Sorts list of file paths by ctime in ascending order. Arg: paths: iterable of filepaths. Returns: list: filepaths sorted by ctime or empty list if ctime is unavailable. """ ctimes = list(map(safe_ctime, paths)) if not all(ctimes) or len(set(ctimes)...
5,349,675
def show(root=None, debug=False, parent=None): """Display Scene Inventory GUI Arguments: debug (bool, optional): Run in debug-mode, defaults to False parent (QtCore.QObject, optional): When provided parent the interface to this QObject. """ try: module....
5,349,676
def get_ospf_metric(device, destination_address): """Get OSPF metric Args: device (obj): Device object destination_address (str): Destination address """ out = device.parse('show route') # Example dictionary # "route-table": [ # { # ...
5,349,677
def telegram_tcp_blocking_all(ooni_exe, outfile): """ Test case where all POPs are TCP/IP blocked """ start_test("telegram_tcp_blocking_all") args = args_for_blocking_all_pop_ips() tk = execute_jafar_and_return_validated_test_keys(ooni_exe, outfile, args) assert tk["telegram_tcp_blocking"] == True ...
5,349,678
def get_episode_url(): """エピソードの配信URLを追加 Returns: [type]: [description] """ # フォームの値を取得 episode_num = "#"+request.form['episode_num'][0] print(episode_num) # 配信先一覧を取得 podcasts = Podcast.query.all() broadcasts = Broadcast.query.all() # 配信先 url broadcast_urls = {...
5,349,679
def autofs(): """Fixture data from /proc/mounts.""" data = "flux-support -rw,tcp,hard,intr,noacl,nosuid,vers=3,retrans=5 flux-support.locker.arc-ts.umich.edu:/gpfs/locker0/ces/g/nfs/f/flux-support\numms-remills -rw,tcp,hard,intr,noacl,nosuid,vers=3,retrans=5 umms-remills....
5,349,680
def flag_dims(flags): """Return flag names, dims, and initials for flags. Only flag value that correspond to searchable dimensions are returned. Scalars and non-function string values are not included in the result. """ dims = {} initials = {} for name, val in flags.items(): try...
5,349,681
def where(cmd, path=None): """ A function to wrap shutil.which for universal usage """ raw_result = shutil.which(cmd, os.X_OK, path) if raw_result: return os.path.abspath(raw_result) else: raise ValueError("Could not find '{}' in the path".format(cmd))
5,349,682
def to_stack(df, col, by, transform=None, get_cats=False): """ Convert columns of a dataframe to a list of lists by 'by' Args: df: col: by: transform: Returns: """ g = df.groupby(by) transform = _notransform if transform is None else transform x_data = [] ...
5,349,683
def dump_vfunc(path, vfunc_list, encoding="UTF-8"): """Dump vertical functions in Paradigm Echos VFUNC format to a file. Each passed VFUNC is a tuple with 4 elements: `inline`, `crossline`, `x` and `y`, where `x` and `y` are 1d `np.ndarray`s with the same length. For each VFUNC a block with the following s...
5,349,684
def detect_entry_signals(context): """ Place limit orders on 20 or 55 day breakout. """ for market in context.prices.items: context.price = context.prices[market].close[-1] if context.price > context.twenty_day_high[market]\ or context.price > context.fifty_five_day_high...
5,349,685
def makeSDEnum(name, val): # real signature unknown; restored from __doc__ """ makeSDEnum(name, val) Make a structured object out of an enumeration value """ pass
5,349,686
def entries_repr(entries: List[Metadata]) -> str: """ Generates a nicely formatted string repr from a list of Dropbox metadata. :param entries: List of Dropbox metadata. :returns: String representation of the list. """ str_reps = [ f"<{e.__class__.__name__}(path_display={e.path_display}...
5,349,687
def frequency_encode(dftrain, dftest, columnlist, output_type="include"): """ Frequency encode columns in columnlist. Parameters: dftrain: [DataFrame] train set dftest: [DataFrame] test set columnlist: [list] columns to encode. output_type: [str], default="include" will ...
5,349,688
def get_ranked_results(completed_rounds): """ For the rounds given in completed_rounds, calculate the total score for each team. Then all teams are sorted on total score and are given a ranking to allow for ex aequo scores. """ results = [] for team in QTeam.objects.all(): teamtotal = 0 ...
5,349,689
def setup_logging(loglevel): """Set up basic logging. Args: loglevel (int): minimum loglevel for emitting messages """ logformat = "[%(asctime)s] %(levelname)s:%(message)s" logging.basicConfig( level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S" )
5,349,690
def get_subgraphs(): """ Returns a list of lists. Each list is a subgraph (represented as a list of dictionaries). :return: A list of lists of dictionaries. """ subgraph_list = [c.get("color") for c in classes if c.get("color") is not None] subgraphs = [] # Add to subgraphs all the lists of...
5,349,691
def score(self, features): """ return score from ML models""" assert len(self._models) > 0, 'No valid prediction model' scores = list() for feature in features: # when feature list extraction fails if not feature: scores.append(-float('inf')) continue item...
5,349,692
def fromRGB(rgb): """Convert tuple or list to red, green and blue values that can be accessed as follows: a = fromRGB((255, 255, 255)) a["red"] a["green"] a["blue"] """ return {"red":rgb[0], "green":rgb[1], "blue":rgb[2]}
5,349,693
def computeTelescopeTransmission(pars, offAxis): """ Compute tel. transmission (0 < T < 1) for a given set of parameters as defined by the MC model and for a given off-axis angle. Parameters ---------- pars: list of float Parameters of the telescope transmission. Len(pars) should be 4. ...
5,349,694
def mean_iou( results, gt_seg_maps, num_classes, ignore_index, nan_to_num=None, label_map=dict(), reduce_zero_label=False, ): """Calculate Mean Intersection and Union (mIoU) Args: results (list[ndarray]): List of prediction segmentation maps. gt_seg_maps (list[ndarra...
5,349,695
def as_date_or_none(date_str): """ Casts a date string as a datetime.date, or None if it is blank. >>> as_date_or_none('2020-11-04') datetime.date(2020, 11, 4) >>> as_date_or_none('') None >>> as_date_or_none(None) None """ if not date_str: return None return dateut...
5,349,696
def guarantee_trailing_slash(directory_name: str) -> str: """Adds a trailling slash when missing Params: :directory_name: str, required A directory name to add trailling slash if missing Returns: A post processed directory name with trailling slash """ if not directory_...
5,349,697
def bc32encode(data: bytes) -> str: """ bc32 encoding see https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2020-004-bc32.md """ dd = convertbits(data, 8, 5) polymod = bech32_polymod([0] + dd + [0, 0, 0, 0, 0, 0]) ^ 0x3FFFFFFF chk = [(polymod >> 5 * (5 - i)) & 31 for i in ...
5,349,698
def read_all_reviews(current_user): """Reads all Reviews""" reviews = Review.query.all() if reviews: return jsonify({'Reviews': [ { 'id': review.id, 'title': review.title, 'desc': review.desc, 'reviewer': review.reviewer.use...
5,349,699