content
stringlengths
22
815k
id
int64
0
4.91M
def planck_spec_lambda(T, lammin, lammax, showfig=True, returnspec=False): """ Generates a Planck spectrum in terms of wavelength, i.e., B_lambda(T). Inputs: T - temperature in K lammin - minimum wavelength in m lammax - maximum wavelength in m showfig - show the fi...
79,200
def fast_gen(generator, cond): """generate with padded input""" p = generator.compute_padding_values()[0] cond = jnp.pad(cond, [(0, 0), (p, p), (0, 0)], mode="reflect") return generator(cond)
79,201
def redirect(location): """our redirect does not delete cookies and headers like bottle.HTTPResponse does; it is considered a success, not failure""" response.headers["Location"] = str(location) raise HTTP(303)
79,202
def computeJz(bx, by, bx_err, by_err, conf_disambig, bitmap, nx, ny): """function: computeJz This function computes the z-component of the current. In discretized space like data pixels, the current (or curl of B) is calculated as the integration of the field Bx and By along the circumference of the ...
79,203
def hw5ode3(t, x): """Function containing the third ODE (Van der Pol’s equation with \\eta = 2). - **parameters**, **types**, **return** and **return types**:: :param t: current time :param x: state at current time :type t: np.float :type x: np.array[float] :return: Derivative of state at current time :...
79,204
def test_properties(): """Tests that elbow and knee can be used interchangeably.""" kn = KneeLocator( x, y_concave_inc, curve_nature="concave", curve_direction="increasing" ) assert kn.knee == kn.elbow assert kn.norm_knee == kn.norm_elbow # pytest compares all elements in each list. ...
79,205
def write_refkey_to_file(refkey_file, password, key_pem, key_der, cert, encode_format): # pylint: disable=too-many-arguments """ Write reference key into file :param refkey_file: File name to store reference key :param password: Password for encryption of pkcs12 reference key :param key_pem: Refere...
79,206
def plot_learning_curve(sample_sizes, learning_curves, curve_labels, xscale='log', ax=None): """ Plot the learning curve. Parameters ---------- sample_sizes : array The sample sizes in which the classifier is run. learning_curves : array List of learning_cur...
79,207
def quantumvolume(nbits=6, measure=True): """ This is a nbit quantum volume circuit reference: https://qiskit.org/textbook/ch-quantum-hardware/measuring-quantum-volume.html """ qubit_lists = [list(range(0, nbits))] qv_circs, qv_circs_nomeas = qv.qv_circuits(qubit_lists, 1) if measure...
79,208
def get_frontend_dir() -> Path: """Get the frontend directory.""" if LOCAL_APP_DIR.exists(): logger.info("Using local DEVELOPMENT frontend directory.") return LOCAL_APP_DIR elif GLOBAL_FRONTEND_DIR.exists(): logger.info("Using global frontend directory.") return GLOBAL_FRONTE...
79,209
def modify_changelog(): """Change first line of the changelog to markdown Heading 1. This modification makes sure that in the pdf build, changelog is a new chapter. """ with open('src_copy/src/CHANGES.md', 'r') as file: data = file.readlines() data[0] = "# Changelog" with open('sr...
79,210
def test_local_source_dir(gearman_worker): """ Verify the source directory exists for a local directory transfer """ return_val = [] source_dir = build_source_dir(gearman_worker) logging.debug("Source Dir: %s", source_dir) if not os.path.isdir(source_dir): return_val.append({"part...
79,211
def count_umis_per_cell( reads, csv, cell_barcode_pattern, molecular_barcode_pattern, min_umi_per_cell, barcodes_significant_umis_file): """Writes to csv the barcodes and number of umis, and to good_barcodes the barcodes with greater than or equal to min_umi_per_c...
79,212
def demo(): # pragma: no cover """Run the demo.""" if len(sys.argv) == 1: runs = 5 else: runs = int(sys.argv[1]) for i in range(0, runs + 1): kwpbar.pbar(i, runs) time.sleep(1) kwpbar.erase_pbar()
79,213
def save_vocs(vocs_dict, filePath=None): """ Write VOCS dictionary to a JSON file. If no filePath is given, the name is chosen from the 'name' key + '.json' """ if filePath: name = filePath else: name = vocs_dict['name'] + '.json' with open(name, 'w') as outfile: js...
79,214
def mnist(missingness="mcar", thr=0.2): """ Loads corrupted MNIST Parameters ---------- missingness: ('mcar', 'mar', 'mnar') Type of missigness you want in your dataset th: float between [0,1] Percentage of missing data in generated data Returns ------- numpy.ndarray ...
79,215
def doit( h5_filename=None, output_h5_filename=None, ufmf_filenames=None, kalman_filename=None, start=None, stop=None, view=None, erode=0, save_images=False, save_image_dir=None, intermediate_thresh_frac=None, final_thresh=None, stack_N_images=None, stack_N_images...
79,216
def ai(): """Build and push your model docker images""" pass
79,217
def classify_chains(table, output, se_model_path, me_model_path, raw_out=None, rejected=None, annot_threshold=0.5): """Entry point.""" # global VERBOSE # set verbosity level # VERBOSE = True if args.verbose else False verbose("Loading dataset...") df = pd.rea...
79,218
def datos_resumen(fecha): """ Extrae los datos resumen de la página 2 del PDF """ pdf=f"{pdfdir}{dt.datetime.strftime(fecha,'%y%m%d')}_cam_covid19.pdf" try : doc=fitz.open(pdf) except : return print(pdf) fecha_str=f"20{pdf[-22:-20]}-{pdf[-20:-18]}-{pdf[-18:-16]}" ...
79,219
def zigzag(root: Node): """ ZigZag traverse: Print node left to right and right to left, alternatively. """ flag = 0 height_tree = height(root) for h in range(1, height_tree + 1): if flag == 0: print_left_to_right(root, h) flag = 1 else: ...
79,220
def run_images(tags): """Run a list of docker images, in background.""" print "### Running images ###" return [run_image(tag) for tag in tags]
79,221
def config_update(verbose=False, delete_objects=False): """sync configuration with data from YAML-formatted stdin""" import yaml import sys new_config = yaml.safe_load(sys.stdin) # print new_config domains = new_config.get('domains', []) tracked_domains = set() for domain_config in domai...
79,222
def _transitive_proto_descriptor_sets_impl(ctx): """Implementation of transitive_proto_descriptor_sets rule. Args: ctx: The rule context. Returns: All transitive proto descriptor files as default output. """ gathered = _gather_transitive_protos_deps(ctx.attr.deps) descriptors = gat...
79,223
def is_timelength_timedelta( timelength: typing.Any, ) -> TypeGuard[spec.TimelengthTimedelta]: """return bool of whether input is TimelengthTimedelta""" return isinstance(timelength, datetime.timedelta)
79,224
def hef_command(s, *args): """ Create fully qualified HEF command (add prefix and postfix the CRC). :param s: command string """ return build_command('3', s, *args)
79,225
def list_folder(): """List a folder. Return a dict mapping unicode filenames to FileMetadata|FolderMetadata entries. """ path = DROPBOX_PROJECT_PATH try: res = dbx.files_list_folder(path) except dropbox.exceptions.ApiError as err: return {} else: return res.entri...
79,226
def genomic_del1_free_text_lse(genomic_del1_free_text, genomic_del1_free_text_seq_loc): """Create a test fixture for genomic del LSE.""" _id = "ga4gh:VA.DdtLZ_d22R0O0VU020WcCLvNhXNZtU2j" genomic_del1_free_text["variation_id"] = _id genomic_del1_free_text["variation"] = { ...
79,227
def min(iterable): """ min() overwrites python built-in, checks if all constants and computes np.min() in that case """ if not any(isinstance(elem, Expression) for elem in iterable): return np.min(iterable) return Minimum(iterable)
79,228
def mode(x: Union[List[float], np.ndarray]) -> float: """Calculate the mode of a list of numbers. Args: x: List or Numpy array. Returns: Mode. Examples: >>> mode(x=[1., 2., 3., 4., 5.]) 2.0 >>> mode(x=[1., 2., 3., 3., 4., 5.]) 3.0 >>> mode(x=[1....
79,229
def mapping(): """ This is the mapping submission page. """ title = 'Perform Mapping' jwt_csrf_token = (get_jwt() or {}).get("csrf") form = FileUploadForm() # TODO: change nemascan_container_url = 'https://github.com/AndersenLab/dockerfile/tree/nemarun/nemarun' nemascan_github_url = 'http...
79,230
def topic_scores(run_scores): """ Use this function for a dictionary that contains the topic scores for each measure outputted by trec_eval. @param run_scores: The run scores of the previously evaluated run. @return: Dictionary containing the topic scores for every measure outputted by trec_eval. "...
79,231
def p_suffix_specifiers_option(p): """ suffix_specifiers_option : TYPE_QUALIFIER """ qualifier = p[1] p[0] = qualifier
79,232
def _make_args(args_list, session, fw_props): """ Converts the given list of arguments into a list (args) and a dictionary (kwargs). All arguments with an assignment are put into kwargs, others in args. :param args_list: The list of arguments to be treated :param session: The current shell sess...
79,233
def create_profile(name, node): """ Create a :class:`Profiler` for the Iteration/Expression tree ``node``. The following code sections are profiled: :: * The whole ``node``; * A sequence of perfectly nested loops that have common :class:`Iteration` dimensions, but possibly differe...
79,234
def jaccard(pred: np.ndarray, target: np.ndarray, eps: float = 1e-7) -> np.ndarray: """ Calculate Jaccard coefficient Args: pred (np.ndarray): predicted masks of shape [B, H, W] target (np.ndarray): target masks of shape [B, H, W] eps (float): smooth value Returns: np.n...
79,235
def drawBoard(board): # Draw background of board. """There are four steps to drawing the board:""" MAINSURF.fill(BGCOLOR) pygame.draw.rect(MAINSURF, BOARDBGCOLOR, (XMARGIN, YMARGIN, BOARDWIDTH * SPACESIZE, BOARDHEIGHT * SPACESIZE)) """First, we fill the entire window (that is, the MAINSURF Surface ...
79,236
async def user_groups_ids(aiopg_engine: Engine) -> Iterator[List[int]]: """Inits groups table and returns group identifiers""" cols = ("gid", "name", "description", "type", "thumbnail", "inclusion_rules") data = [ (34, "john.smith", "primary group for user", "PRIMARY", None, {}), ( ...
79,237
def has_prefix(sub_s, d): """ :param sub_s: :return: """ for key in d: if key.startswith(sub_s): return True
79,238
def slow_closest_pair(cluster_list): """ Compute the distance between the closest pair of clusters in a list (slow) Input: cluster_list is the list of clusters Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters cluster_list[idx1] and cluster_list[idx2] have m...
79,239
def requires_true(attrs=[]): """ This decorator is used to require that a certain set of class attributes are set to True. Otherwise it will trigger a WebUIError. """ return _requires_value(True, attrs)
79,240
def get_sys_fs_mount() -> str: """find the default sysfs mount point""" try: if os.path.exists(MTAB): with open(MTAB, mode='r') as mtab: mounts: ty.Set[str] = set() for line in mtab.readlines(): segments = line.split() i...
79,241
def _get_ext_suffix(): """Get the suffix for compiled extensions""" dist_suffix = distutils.sysconfig.get_config_var("EXT_SUFFIX") if dist_suffix is None: dist_suffix = distutils.sysconfig.get_config_var("SO") return dist_suffix
79,242
def _runFIRST(struct, dir): """Args: struct: path to structural image dir: path to directory in which FIRST will be run """ _weak_mkdir(dir) nameroot, _ = _splitExts(struct) struct = op.abspath(struct) pwd = os.getcwd() os.chdir(dir) cmd = 'run_first_all -i {} -o {}'.f...
79,243
def explicit_k(obj): """explicit_k solver. Used to compute one time step of systems with x-dependent thermal contuctivity. """ x = copy.copy(obj.temperature) # computes for i in range(1, obj.num_points - 1): eta = obj.dt / (2. * obj.rho[i] * obj.Cp[i] * obj.dx * obj.dx) ...
79,244
def glacier_plot(x, bed, model, mb_model, init_flowline): """This function plots the glacier outline of a model. The bedrock, the equilibrium line altitude, labeled axes and a legend are added. Parameters ---------- x : ndarray distance along glacier bed : ndarray the glacier be...
79,245
def run(): """Requirements for Task 1D""" # Build list of stations stations = build_station_list() # Part 1 rivers = rivers_with_station(stations) # calls function defined in geo print (len(rivers), "rivers have at least 1 station. First 10 -", sorted(rivers)[:10]) # Part 2 rivers_st...
79,246
def get_wikidata_desc(wikidata_id): """Return the image for the Wikidata item with *wikidata_id*. """ dapp = urllib.parse.urlencode({'action':'wbgetentities','ids':get_wikidata_id(wikidata_id),'languages':'de'}) query_string = "https://www.wikidata.org/w/api.php?" + dapp res = requests.get(query_string)...
79,247
def bayesdb_generator_modelnos(bdb, generator_id): """Return list of model numbers associated with given `generator_id`.""" sql = ''' SELECT modelno FROM bayesdb_generator_model AS m WHERE generator_id = ? ORDER BY modelno ASC ''' return [row[0] for row in bdb.sql_execute...
79,248
def create_folders(): """ Creates folder for saving data (profile, post or group) according to current driver url Changes current dir to target_dir :return: target_dir or None in case of failure """ folder = os.path.join(os.getcwd(), "data") utils.create_folder(folder) os.chdir(folder) ...
79,249
def format_terminal_call(cmd: List[str]) -> str: """ Format commands to/from the terminal for readability :param cmd: List of strings much like sys.argv :return: Formatted string used for display purposes """ return ' '.join(cmd).replace("--", " \\ \n\t--")
79,250
def plot_attribution(a, a_display=None, title=None, ylabel='', conf_level=0.95): """Produce a plot of the ensemble forecasts Returns ---------- plt object """ a = a.reset_index(drop=True) if type(a) is not pd.core.frame.DataFrame: raise Exception('a, the attribution data...
79,251
def process_first_section(section_text, filename, context): """Special treatment for the first top-level section of a Vim doc file.""" output = [] hits, misses = 0, 0 output.append("[discrete]") output.append("== First section") mark_unprocessed_text_start(output, context) for c, line in enu...
79,252
def evaluate_and_log_bleu(estimator, bleu_source, bleu_ref, vocab_file_path): """Calculate and record the BLEU score.""" subtokenizer = tokenizer.Subtokenizer(vocab_file_path) uncased_score, cased_score = translate_and_compute_bleu( estimator, subtokenizer, bleu_source, bleu_ref) tf.logging.info("Bleu s...
79,253
def isSameCapacityAndSpeed(drives,raids): """ Check if all the HDDs in the RAID container have the same capacity and speed. Return True if so, if not return an error message. """ if len(raids) <= 0: return True else: slots = raids[0]['sas_id'].split(',') drivesOnRAID = fi...
79,254
def is_decimal(value: Optional[str]) -> Tuple[bool, Optional[Decimal]]: """ none is not a numeric value, otherwise try to parse it by float function """ if value is None: return False, None try: v = float(value) return True, Decimal(v) except ValueError: return False, None
79,255
def collect_data(current_venv): """Record data for the report.""" # data = {} # data[current_venv.name] = { # "name": current_venv.name, # "path": current_venv.path.strpath, # } # data[current_venv.name].update(current_venv.env_log.reportlog.dict) console.print(current_venv.env_l...
79,256
def load_config_file(file_path: str) -> Dict: """ Load a YAML config file. Uses UnsafeLoader :rtype: Dict """ with open(file_path, 'r') as yaml_file: cfg = yaml.load(yaml_file, Loader=yaml.UnsafeLoader) return cfg
79,257
def remove_zero_area(shape, properties, fid, zoom): """ All features get a numeric area tag, but for points this is zero. The area probably isn't exactly zero, so it's probably less confusing to just remove the tag to show that the value is probably closer to "unspecified". """ # remove the...
79,258
def get_w(roll_mat_csr, sale_usd): """ """ # Calculate the total sales in USD for each item id: total_sales_usd = sale_usd.groupby( ['id'], sort=False)['sale_usd'].apply(np.sum).values # Roll up total sales by ids to higher levels: weight2 = roll_mat_csr * total_sales_usd r...
79,259
def create_style_file(path, minify=False): """ Write the CSS style sheet to the given path. @param path: path to write to @type path: L{str} @param minify: if nonzero, minify content @type minify: L{str} """ css = STYLE_CONTENT if minify: css = minify_css(css) create...
79,260
def build_data(Config): """ Procedure to build data Args: Config: defines attributes needed in the function Returns: creates vocab files from the datasets """ # Generators train = Dataset(words_filename=Config.source_path, tags_filename=Config.source_tgt_path) # test ...
79,261
def is_latin_square(row_length: int, array: str) -> bool: """Return whether array is a latin square.""" # check horizontally row = 1 column = 0 numbers = [] for index, digit in enumerate(array): # check for new row if index % row_length == 0: row += 1 col...
79,262
def convert_to_JSON(graph): """Converts an igraph into a D3-compatible json file :returns a json Object """ nodes = [] for node in graph.vs: nodes.append({'id': node['name'], 'label': node['label'], 'size': node['totalCred'], ...
79,263
def spin_the_roulette() -> str: """ Returns one of 'red', 'black', 'green' in random, using the ROULETTE_COLORS chances. """ return random.choice(ROULETTE_COLORS)
79,264
def root_mean_square_f(a, axis=None, weights=None, masked=False): """The RMS along the specified axes. :Parameters: a: array-like Input array. Not all missing data axis: `int`, optional Axis along which to operate. By default, flattened input is used. ...
79,265
def format_links( links, decimals=4, headers=False, delimiter=None, ): """Generates a summary table for a hit cluster. Args: hits (list): collection of Hit objects decimals (int): number of decimal points to show show_headers (bool): show column headers in output ...
79,266
def _apply_slice(data, s): """ Apply slice s (given as a string) to the data. Parameters ---------- data : np.array The data to be sliced. s : str A string representation of the slice, e.g. '[...]', '[0, :]', etc. Returns ------- np.array The sliced data. ...
79,267
def FindPriorRanges(xs, num_points, num_stderrs=3.0, median_flag=False): """Find ranges for mu and sigma with non-negligible likelihood. xs: sample num_points: number of values in each dimension num_stderrs: number of standard errors to include on either side Returns: sequence of mus, sequence...
79,268
def do_popen(command, log=True, force_en_env=False): """Connect via Popen and log the result.""" if force_en_env: # force an english environment force_en_env = os.environ.copy() force_en_env['LC_ALL'] = 'C' stdout, stderr = Popen(command, stdout=PIPE, stderr=PIPE, env=force_en_env).comm...
79,269
def defense(): """ Uses defenses against various attack strategies. """ pass
79,270
def manage_log_files(): """ Function to manage the number of log files in the current working directory. """ # List to store all filenames in the current working directory. general_filenames_list = [] # List to store the filenames for log files. log_filenames_list = [] # Get the list o...
79,271
def split_color_string(color_string): """Split a ``color_string`` by whitespace into a list of it's ``components``. """ if not color_string: return [] return [thing for thing in regexes["whitespace"].split(color_string) if thing]
79,272
def ask_for_confirmation(title, message): """Ask the user to finally remove title from the Kodi library""" return xbmcgui.Dialog().yesno(heading=title, line1=message)
79,273
def checa_colisao(player, bolas, stats): """Responde a colisoes entre o player e a bola""" # Remove a bola caso a bola e o player tenham colidido collisions = pygame.sprite.spritecollide(player, bolas, True, pygame.sprite.collide_mask) for bola in bolas.sprites(): if bola.rect.y >= 600: ...
79,274
def new(owner, name, token, group_id): """ Создает нового бота """ year = datetime.datetime.now().year bot_path = Path(name) src_path = Path(name) / "src" os.makedirs(str(src_path)) with open(bot_path / "LICENSE", "w+") as file: file.write(MIT.format(owner=owner, year=year)) ...
79,275
def test_provider_configuration_save_button(bundle_content, provider_config_page): """Test provider configuration save button""" (selected_opts, prop_types), _ = bundle_content _test_save_configuration_button( provider_config_page, group_name=GROUP_NAME if CONFIG_USE_GROUP in selected_opts e...
79,276
def main(): """Parse args and run desired commands""" common_parser = argparse.ArgumentParser(add_help=False) common_parser.add_argument('--aws-profile', default='raster-vision', help='AWS profile to use for launching the' 'builder EC2 insta...
79,277
def read_print_loop(): """Run a read-print loop for Scheme expressions.""" while True: try: src = buffer_input() while src.more_on_line: expression = scheme_read(src) print(repr(expression)) except (SyntaxError, ValueError) as err: ...
79,278
def serpentine(rows, columns): """ Make a serpentine pattern """ rows = range(rows) columns = range(columns) pos = [] for column in columns: for row in rows: pos.append((row,column)) rows.reverse() return pos
79,279
def test_MatrixMult(par): """Dot-test and inversion for MatrixMult operator """ np.random.seed(10) G = np.random.normal(0, 10, (par['ny'], par['nx'])).astype('float32') + \ par['imag']*np.random.normal(0, 10, (par['ny'], ...
79,280
def check_case1(maxlen: int): """Test when the transition is terminal state.""" done_index = 0 n_step_buffer = generate_dummy_buffer(maxlen, done_index) reward, next_state, _ = get_n_step_info(n_step_buffer, gamma=1) assert reward == done_index assert next_state == done_index + 1
79,281
def _identity_metric_nested(name, input_tensors): """Create identity metrics for a nested tuple of Tensors.""" update_ops = [] value_tensors = [] for tensor_number, tensor in enumerate(nest.flatten(input_tensors)): value_tensor, update_op = _identity_metric_single( name="{}_{}".format(name, tensor_n...
79,282
def cmd_logout(fb): """logout from the freebase service %prog logout deletes the login cookies """ fb.cookiejar.clear(domain=fb.service_host.split(':')[0])
79,283
def lenient_chain_to_quadratic(chain, target_adjacency, chain_strength): """Determine the quadratic biases that induce the given chain. Args: chain (iterable): The variables that make up a chain. target_adjacency (dict/:class:`networkx.Graph`): Should be a dict of the f...
79,284
def detect_faces_server(gcs_uri: str): """Detects faces in a video.""" client = videointelligence.VideoIntelligenceServiceClient() # Configure the request config = videointelligence.FaceDetectionConfig( include_bounding_boxes=True, include_attributes=True ) context = videointelligence....
79,285
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Return a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit val...
79,286
def parse(content: str) -> GherkinDocument: """ Parse the content of a file to an AST. """ parser = Parser() try: parse_result = parser.parse(StringOnlyTokenScanner(content)) except ParserError as e: raise InvalidInput(e) from e try: result = converter.structure(par...
79,287
def pql_tables(state: State): """Returns a table of all the persistent tables in the database. The resulting table has two columns: name, and type. """ names = state.db.list_tables() values = [(name, state.db.import_table_type(name, None)) for name in names] tuples = [sql.Tuple(T.list[T.string]...
79,288
def process_area(con=None, area=None, callback=None, tmp_ext=None, folder_path=None, frm="GTiff", minimum_area=0.5, parallel_jobs=1): """ TODO: maak iets waarmee het asynchroon kan draaien? TODO: callback functie maken ipv hier in dit script draaien This function processes splits up the processing of la...
79,289
def speedups() -> bool: """ Speedups are now enabled by default if they are available. You can check if speedups are enabled with the enabled attribute. """ from shapely import speedups return speedups.enabled
79,290
def dijkstra_directed(graph, start): """ Arguments: <graph> is a graph object, where edges have integer <weight> attributes, and <start> is a vertex of <graph>. Action: Uses Dijkstra's algorithm to compute all vertex distances from <start> in <graph>, and assigns these values to the vertex a...
79,291
def graph_to_filenames(graph,root,masks,indir,prefix): """ Generate a list of filenames for the sequences of nested taxids from a root. """ filenames = defaultdict(list) def descend(root): """ Iteratively descend from a root to generate a list of filenames unless the child t...
79,292
def expandPhEDExNode(target): """ _expandPhEDExNode_ If pulling a TFC from the PhEDEx DS, its wrapped in a top level <phedex> node, this routine handles that extra node if it exists """ while True: report, node = (yield) sentPhedex = False for subnode in node.children: ...
79,293
def _dask_or_eager_func(name, eager_module=np, list_of_args=False, n_array_args=1): """Create a function that dispatches to dask for dask array inputs.""" if has_dask: def f(*args, **kwargs): if list_of_args: dispatch_args = args[0] else: ...
79,294
def crop_data(data, box_width=200, center=None, data_only=True, wcs=None, **kwargs): """Return a cropped portion of the image Shape is a box centered around the middle of the data Args: data (`numpy.array`): Array of data. box_width (int, optional): Size of box width in pixels, defaults to...
79,295
def load_star_image(): # pragma: no cover """Load an optical image with stars. Returns ------- hdu : `~astropy.io.fits.ImageHDU` Image HDU Examples -------- .. plot:: :include-source: from photutils import datasets hdu = datasets.load_star_image() ...
79,296
def build_huffman_tree(list_hufftrees): """ 构造huffman树 """ while len(list_hufftrees) > 1: # 1. 按照 weight 对 huffman 树进行从小到大的排序 list_hufftrees.sort(key=lambda x: x.get_wieght()) # 2. 挑出weight 最小的两个huffman编码树 temp1 = list_hufftrees[0] temp2 = list_hufftrees[1] ...
79,297
def split_data(data, prob): """splits the data into fractions [prob, 1-prob]""" results = [], [] for row in data: results[0 if random.random() < prob else 1].append(row) return results
79,298
def change_dir(monkeypatch): """Set current dir to the path of `scaffold` project""" scaffold_path = pkg_resources.resource_filename(init.__name__, "scaffold") monkeypatch.chdir(scaffold_path) cwd = pathlib.Path(scaffold_path).absolute().__str__() if cwd not in sys.path: monkeypatch.syspath...
79,299