content
stringlengths
22
815k
id
int64
0
4.91M
def cached_property_named(name, kls=_internal_jit_attr, use_cls_setattr=False): """ variation of `cached_property`, just with the ability to explicitly set the attribute name Primarily of use for when the functor it's wrapping has a generic name ( `functools.partial` instances for example). Example...
5,346,200
def remix(tracks, n_tracks=50, n_steps=60): """Return new tracks generated by remixing given tracks""" time_step = int( np.round(next(dt for dt in sorted(tracks["Time"].diff()) if dt > 0) * 60) ) print( "Generating {} steps from {} steps {}s apart.".format( n_tracks * n_steps...
5,346,201
def prohibition_served_recently(**args) -> tuple: """ Returns TRUE if the prohibition was served within the previous 3 days; otherwise returns FALSE """ date_served_string = args.get('date_of_service') config = args.get('config') delay_days = int(config.DAYS_TO_DELAY_FOR_VIPS_DATA_ENTRY) ...
5,346,202
def test_check_family_equal_unicode_encodings(mada_ttFonts): """ Fonts have equal unicode encodings ? """ from fontbakery.profiles.cmap import com_google_fonts_check_family_equal_unicode_encodings as check from fontbakery.constants import WindowsEncodingID print('Test PASS with good family.') # our reference...
5,346,203
def project_api(request): """ 创建项目接口 """ if not request.user.has_perm('home_application.can_add_project'): return render(request, '403.html') if request.method == 'POST': groupId=request.POST.get('group-id','') projectName=request.POST.get('project-name','') ...
5,346,204
def impute_missing_values(model, observed_time_series, parameter_samples, include_observation_noise=False): """Runs posterior inference to impute the missing values in a time series. This method computes the posterior marginals `p(latent...
5,346,205
def grad_z(y, z, axis=0): """ Compute the vertical gradient "z" can be an array same size as y, or vector along the first axis of "y" Takes the derivative along the dimension specified by axis(=0) """ Nz = z.shape[0] # Reshape the y variable y = y.swapaxes(0, axis) #assert y.shape...
5,346,206
def wang_ryzin_reg(h, Xi, x): """ A version for the Wang-Ryzin kernel for nonparametric regression. Suggested by Li and Racine in [1] ch.4 """ return h ** abs(Xi - x)
5,346,207
def _removeBackrefs( senderkey): """Remove all back-references to this senderkey""" try: signals = connections[senderkey] except KeyError: signals = None else: items = signals.items() def allReceivers( ): for signal,set in items: for item in set: yield item for receiver in allReceivers(): _...
5,346,208
def get_all_input_values(corpus_weights): """ Returns all relevant input values """ azerty = get_azerty() letters = get_letters() characters = get_characters() keyslots = get_keyslots() similarity_c_c = get_character_similarities() similarity_c_l = get_character_letter_similarities(...
5,346,209
def bulk_rename(doctype, rows=None, via_console = False): """Bulk rename documents :param doctype: DocType to be renamed :param rows: list of documents as `((oldname, newname), ..)`""" if not rows: frappe.throw(_("Please select a valid csv file with data")) if not via_console: max_rows = 500 if len(rows) >...
5,346,210
def parse_file( input_file, output_file, xsd_file, xpaths, excludepaths, delete_xml, block_size, file_info, ): """ :param input_file: input file :param output_file: output file :param xsd_file: xsd file :param xpaths: whether to parse a specific xml path :param ex...
5,346,211
def mag_to_flux_AB(mag, mag_err): """Calculate flux in erg s-1 cm-2 Hz-1.""" flux = 10 ** (-.4 * (mag + 48.6)) flux_err = abs(-.4 * flux * sp.log(10) * mag_err) return flux, flux_err
5,346,212
def add_count_records(df, count_type): """Add count records for the count type.""" log(f'Adding {DATASET_ID} count records for {count_type}') has_count = pd.to_numeric(df[count_type], errors='coerce').notna() df = df.loc[has_count, :].copy() df[count_type] = df[count_type].astype(int) df['count_...
5,346,213
def rasterizeTimesliceMultipleDays(timeslices_range: dict, perform_rasterization): """ Rasterize timeslices over multiple days while keeping consistent color scheme across rasters timeslices_range shall for each day contain a dictioanry with keys: - timeslices - startTime - endTime - imageP...
5,346,214
def django_admin_navtree(request, context): """show menu""" if request and request.user.is_staff: coop_cms_navtrees = context.get('coop_cms_navtrees', None) or [] tree_class = get_navtree_class() admin_tree_name = "{0}_{1}".format(get_model_app(tree_class), get_model_name(tree_class)) ...
5,346,215
def get_pos_tags(student_comment: str) -> pd.DataFrame: """Get the POS (part of speech) tags for each of the words in the student comments Keyword arguments student_comment -- a spacy.tokens.doc.Doc object """ # Count how many of each pos tags are in each comment pos_tags ...
5,346,216
def compute_descriptor_digest(fields, descriptors, entry, flavor): """ (details of the parser – private API) Plugs into our consumer to compute extra "digest" fields that expose the (micro-)descriptor's (micro-)digest, enabling us to easily fetch associated entries within a consensu...
5,346,217
def main(): """The Main Function.""" parser = argparse.ArgumentParser() parser.add_argument("-v", "--validation", type=int, default=1, help="turn on to cal the index") parser.add_argument("-d", "--dataset", type=str, default="3T3", help="choose mode") parser.add_argument("--n_model", type=int, default=1, hel...
5,346,218
def add_auth(instance): """Add authentication to VM.""" if not instance: sys.exit(click.style("Need to provide an instance to before " "we can add authentication.", fg="red")) if instance.provider == 'vmware' and instance.vmx is None: sys.exit(click.style("Need...
5,346,219
def test_docker_registry_htpasswd_list( docker_registry_htpasswd_list: List[Path], docker_registry_password_list: List[str], docker_registry_username_list: List[str], pdrf_scale_factor: int, ): """Test that a htpasswd can be provided.""" for i in range(pdrf_scale_factor): assert docker_r...
5,346,220
def get_axis(array, axis, slice_num): """Returns a fixed axis""" slice_list = [slice(None)] * array.ndim slice_list[axis] = slice_num slice_data = array[tuple(slice_list)].T # transpose for proper orientation return slice_data
5,346,221
def test_integrity(param_test): """ Test integrity of function """ # open result file f = open(os.path.join(param_test.path_output, 'ernst_angle.txt'), 'r') angle_result = float(f.read()) f.close() # compare with GT if abs(angle_result - param_test.angle_gt) < param_test.thr...
5,346,222
def expand_name_df(df,old_col,new_col): """Takes a dataframe df with an API JSON object with nested elements in old_col, extracts the name, and saves it in a new dataframe column called new_col Parameters ---------- df : dataframe old_col : str new_col : str Returns ------- df...
5,346,223
def image_rpms_remove_if_exists(rpmlist): """ `image.rpms_remove_if_exists(["baz"])` removes `baz.rpm` if exists. Note that removals may only be applied against the parent layer -- if your current layer includes features both removing and installing the same package, this will cause a build failure. """ re...
5,346,224
def expand_set(mySet): """ pass in a set of genome coords, and it will 'expand' the indels within the set by adding +/- 3 bp copies for each one """ returnSet = [] for entry in mySet: l0 = [] l1 = [] try: sub0 = entry.split('-')[0] # split on `-` sub1 = entry.split('-')[1] # this guy is good sub00 ...
5,346,225
def trapezoid(t, depth, bigT, littleT): """Trapezoid shape for model INPUT: t - [float] vector of independent values to evaluate trapezoid model depth - [float] depth of trapezoid bigT - [float] full trapezoid duration littleT - [float] 'ingress/egress' durati...
5,346,226
def destroy(ctx, config, name, force): """Destroy a machine.""" name = drifter.commands.validate_name(ctx, name) # Destroy the named machine only if name: _destroy(ctx, config, name, force) return # Destroy all machines for machine in drifter.commands.list_machines(config): ...
5,346,227
def clean_username(username=''): """ Simple helper method to ensure a username is compatible with our system requirements. """ return ('_').join(re.findall(r'[a-zA-Z0-9\-]+', username))[:USERNAME_MAX_LENGTH]
5,346,228
def hy_compile(tree, module_name, root=ast.Module, get_expr=False): """ Compile a HyObject tree into a Python AST Module. If `get_expr` is True, return a tuple (module, last_expression), where `last_expression` is the. """ body = [] expr = None if not isinstance(tree, HyObject): ...
5,346,229
def make_expt_parser(): """ Parses arguments from the command line for running experiments returns args (argparse NameSpace) """ parser = argparse.ArgumentParser( description='energy_py dict expt parser' ) # required parser.add_argument('expt_name', default=None, type...
5,346,230
def user_dss_clients(dss_clients, dss_target): """ Fixture that narrows down the dss clients to only the ones that are relevant considering the curent DSS target. Args: dss_clients (fixture): All the instanciated dss client for each user and dss targets dss_target (fixture): The considered ...
5,346,231
def build_log(x: np.ndarray) -> np.ndarray: """ Logarithmic expansion. :param x: features :return: augmented features """ expanded = np.ones((x.shape[0], 1)) expanded = np.hstack((expanded, np.nan_to_num(np.log(x)))) return expanded
5,346,232
def print_pqr(args, pqr_lines, header_lines, missing_lines, is_cif): """Print PQR-format output to specified file .. todo:: Move this to another module (io) :param argparse.Namespace args: command-line arguments :param [str] pqr_lines: output lines (records) :param [str] header_lines: header l...
5,346,233
def all_multibert_finetune_glue(m:Manager, task_name:str='MRPC')->BertGlue: """ Finetune milti-lingual base-BERT on GLUE dataset Ref. https://github.com/google-research/bert/blob/master/multilingual.md """ refbert=all_fetch_multibert(m) refglue=all_fetchglue(m) vocab=mklens(refbert).bert_vocab.refpath gl...
5,346,234
def hash_eth2(data: Union[bytes, bytearray]) -> Hash32: """ Return SHA-256 hashed result. Note: this API is currently under active research/development so is subject to change without a major version bump. Note: it's a placeholder and we aim to migrate to a S[T/N]ARK-friendly hash function in ...
5,346,235
def read_data(data_dir="../main/datasets/", data_file=DATA_FILE): """Returns the data, in order infos, items, orders""" with zipfile.ZipFile(data_dir+DATA_FILE) as z: dfs = [] for name in ["infos", "items", "orders"]: dfs.append(pd.read_csv(z.open(f"1.0v/{name}.csv"), sep="|")) r...
5,346,236
def get_sprints(root_project_id, rally_number=None): """Get list of sprint projects. Args: root_project_id: Synapse Project ID with admin annotations, including the sprint table ID. rally_number: An integer rally number. If None, return sprints ...
5,346,237
async def cmd_viewdb(self, message, scopes): """ `$!_viewdb [scopes...]` : Displays the current database state If scopes are provided, then only show the requested scopes """ async with DBView() as db: if scopes is None or not len(scopes): await self.send_message( ...
5,346,238
def prep_bbox(sess, logits_scalar, x, y, X_train, Y_train, X_test, Y_test, img_rows, img_cols, channels, nb_epochs, batch_size, learning_rate, rng, phase=None, binary=False, scale=False, nb_filters=64, model_path=None, adv=0, delay=0, eps=0.3): """ Define and train a mo...
5,346,239
def out_of_bounds(maze: Array, x: int, y: int): """ Return true if x, y is out of bounds """ w, h = maze.shape is_x_out = (x < 0) + (x >= w) is_y_out = (y < 0) + (y >= h) return is_x_out + is_y_out
5,346,240
def run_test(test_name, module_dict, print_test_case=False, display=None): """Run a given test.""" import test_parser import test_classes for module in module_dict: setattr(sys.modules[__name__], module, module_dict[module]) test_dict = test_parser.TestParser(test_name + ".test").parse() ...
5,346,241
def cache_set(apollo_client, name, val): """ 保存数据到redis :return: """ r = redis_handler(apollo_client) try: res = r.set(name=name, value=json.dumps(val)) except Exception as e: logger.error("Storage {} to cache failed!{}".format(name, e.__str__())) retu...
5,346,242
def guess_pyramid(data): """If shape of arrays along first axis is strictly decreasing. """ # If the data has ndim and is not one-dimensional then cannot be pyramid if hasattr(data, 'ndim') and data.ndim > 1: return False size = np.array([np.prod(d.shape, dtype=np.uint64) for d in data]) ...
5,346,243
def __clear_archive_file(model_context): """ Remove any binaries already in the archive file. :param model_context: the model context :raises DiscoverException: if an error occurs while removing the binaries """ _method_name = '__clear_archive_file' __logger.entering(class_name=_class_name, ...
5,346,244
def test_object_properties_match_xml(person_xml, mini_mock): """ Test the object is modified to include attributes for elements from the XML tree. """ tree = etree.fromstring(person_xml) # Set up some blank object attributes. person0 = mini_mock() person0.nickname = None person0.fir...
5,346,245
def test_interdependency_constrained(): """ Test a model with interdependent components, and with constraints which depend on the Model's output. This is done in the MatrixSymbol formalism, using a Tikhonov regularization as an example. In this, a matrix inverse has to be calculated and is used ...
5,346,246
def create_menu(menu_items, parent=None): """ Create the navigation nodes based on a passed list of dicts """ nodes = [] for menu_dict in menu_items: try: label = menu_dict['label'] except KeyError: raise ImproperlyConfigured( "No label specifi...
5,346,247
def imsave(f, img): """Save an image to file. :param string|file f: Filename or file-like object. :param numpy.ndarray img: Image to save. Of shape (M,N) or (M,N,3) or (M,N,4). """ # Ensure we use PIL so we can guarantee that imsave will accept file-like object as well as filename skio.imsave(f...
5,346,248
def find_contact(name): """Selects existing contact details based on the provided name.""" # Uses the LIKE operator to perform case insensitive searching. Also allows # for the use of the % and _ wildcards. conn = sqlite3.connect('contacts.db') c = conn.cursor() c.execute('SELECT contact_id, nam...
5,346,249
def get_tg_ids(db): """Obtain a list of recognized Telegram user IDs. Args: db: Database connector Returns: Query results for later iteration """ return db.query(QUERY_TG_IDS)
5,346,250
async def _casino( ctx: commands.Context, bet: int = None, # type: ignore number_of_games: int = 1 ) -> None: """ Casino, generates lines with sectors depending on <number of games> (last argument, default: 1). :param ctx: commands.Context :param bet: Bet of the user, but i...
5,346,251
def solve_with_log(board, out_fname): """Wrapper for solve: write log to out_fname""" log = [] ret = solve(board, log) with open(out_fname, 'w') as f: f.write(json.dumps({'model': log}, indent=4)) return ret
5,346,252
def discrepancy(sample, bounds=None): """Discrepancy. Compute the centered discrepancy on a given sample. It is a measure of the uniformity of the points in the parameter space. The lower the value is, the better the coverage of the parameter space is. Parameters ---------- sample : array_...
5,346,253
def rz(psi, r): """ Wrapper for ERFA function ``eraRz``. Parameters ---------- psi : double array r : double array Returns ------- r : double array Notes ----- The ERFA documentation is below. - - - - - - e r a R z - - - - - - Rotate an r-matrix abou...
5,346,254
def VisualizeCollapsedGraph(trace, node_names, edges, fuzzy): """ Visualize the collapsed graph and save the output. @params trace: the trace for which to visualize a collapsed graph @params node_names: names for the collapsed nodes @params edges: list of edges connecting the nodes """ # get...
5,346,255
def _get_ticklabels(band_type, kHz, separator): """ Return a list with all tick labels for octave or third octave bands cases. """ if separator is None: import locale separator = locale.localeconv()['decimal_point'] if band_type == 'octave': if kHz is True: tickl...
5,346,256
def test_scrapping(): """ Function that will test if the data was scrapped successfully """ scrapper = Scrapper() scrapped_data = scrapper.scrape_fb_page("nous.sommes.les.ingenieurs", 5) assert len(scrapped_data) > 0 assert len(scrapped_data[0]["text"]) > 0
5,346,257
def SpearmanP(predicted, observed): """abstracts out p from stats.spearmanr""" if np.isnan(np.min(predicted)) or np.isnan(np.min(observed)): return np.asarray([np.nan]) coef, p = stats.spearmanr(np.squeeze(predicted).astype(float), np.squeeze(observed).astype(float)) return p
5,346,258
def get_zebra_route_type_by_name(route_type='BGP'): """ Returns the constant value for Zebra route type named "ZEBRA_ROUTE_*" from its name. See "ZEBRA_ROUTE_*" constants in "ryu.lib.packet.zebra" module. :param route_type: Route type name (e.g., Kernel, BGP). :return: Constant value f...
5,346,259
def preprocess(arr): """Preprocess image array with simple normalization. Arguments: ---------- arr (np.array): image array Returns: -------- arr (np.array): preprocessed image array """ arr = arr / 255.0 arr = arr * 2.0 - 1.0 return arr
5,346,260
def remove_const(type): """removes const from the type definition If type is not const type, it will be returned as is """ nake_type = remove_alias(type) if not is_const(nake_type): return type else: return nake_type.base
5,346,261
def populate_institute_form(form, institute_obj): """Populate institute settings form Args: form(scout.server.blueprints.institutes.models.InstituteForm) institute_obj(dict) An institute object """ # get all other institutes to populate the select of the possible collaborators insti...
5,346,262
def test_output_overview_path(output, tmpdir): """Testing if overview HTML file path is created correctly.""" expected_path = os.path.join(tmpdir, "overview.html") actual_path = output.overview_file() assert actual_path == expected_path
5,346,263
def closestMedioidI(active_site, medioids, distD): """ returns the index of the closest medioid in medioids to active_site input: active_site, an ActiveSite instance medioids, a list of ActiveSite instances distD, a dictionary of distances output: the index of the ActiveSite close...
5,346,264
def watchPoint(filename, lineno, event="call"): """whenever we hit this line, print a stack trace. event='call' for lines that are function definitions, like what a profiler gives you. Switch to 'line' to match lines inside functions. Execution speed will be much slower.""" seenTraces: Dict[Any...
5,346,265
def no_op_job(): """ A no-op parsl.python_app to return a future for a job that already has its outputs. """ return 0
5,346,266
def identity(dim, shape=None): """Return identity operator with appropriate shape. Parameters ---------- dim : int Dimension of real space. shape : int (optional) Size of the unitary part of the operator. If not provided, U is set to None. Returns ------- id : P...
5,346,267
def configure_checkout_session(request): """ Configure the payment session for Stripe. Return the Session ID. Key attributes are: - mode: payment (for one-time charge) or subscription - line_items: including price_data because users configure the donation price. TODOs ...
5,346,268
def load_schemas(): """Return all of the schemas in this directory in a dictionary where the keys are the filename (without the .json extension) and the values are the JSON schemas (in dictionary format) :raises jsonschema.exceptions.SchemaError if any of the JSON files in this directory are not val...
5,346,269
def load_separator( model_str_or_path: str = "umxhq", targets: Optional[list] = None, niter: int = 1, residual: bool = False, wiener_win_len: Optional[int] = 300, device: Union[str, torch.device] = "cpu", pretrained: bool = True, filterbank: str = "torch", ): """Separator l...
5,346,270
def transform_datetime(date_str, site): """ 根据site转换原始的date为正规的date类型存放 :param date_str: 原始的date :param site: 网站标识 :return: 转换后的date """ result = None if site in SITE_MAP: if SITE_MAP[site] in (SiteType.SINA, SiteType.HACKERNEWS): try: time_int = int(d...
5,346,271
def ParseEventsForTTLs(eventsFileName, TR = 2.0, onset = False, threshold = 5.0): """ Parses the events file from Avotec for TTLs. Use if history file is not available. The events files does not contain save movie start/stops, so use the history file if possible @param eventsFileName: name of events file from avot...
5,346,272
def test_tile_valid_pan(landsat_get_mtl, monkeypatch): """ Should work as expected """ monkeypatch.setattr(landsat8, "LANDSAT_BUCKET", LANDSAT_BUCKET) landsat_get_mtl.return_value = LANDSAT_METADATA tile_z = 8 tile_x = 71 tile_y = 102 data, mask = landsat8.tile(LANDSAT_SCENE_C1, t...
5,346,273
def _to_native_string(string, encoding='ascii'): """Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. """ if isinstance(string, str): out = string ...
5,346,274
def load(path: str) -> model_lib.Model: """Deserializes a TensorFlow SavedModel at `path` to a `tff.learning.Model`. Args: path: The `str` path pointing to a SavedModel. Returns: A `tff.learning.Model`. """ py_typecheck.check_type(path, str) if not path: raise ValueError('`path` must be a non-...
5,346,275
def plot_feature_importance(obj, top_n=None, save_path=None): """ 输出LGBM模型的feature importance,并绘制条形图 Parameters ---------- obj: lgbm object or DataFrame 训练好的Lightgbm模型,或是已经计算好的feature importan DataFrame top_n: int, default None 展示TOP N的变量,若不填则展示全部变量,为保证显示效果,建议当变量个数多于30个时进行限制 ...
5,346,276
def plot_pr(precision, recall, area, name, dst_dir=None): """Plotting ROC curve. Arguments: tpr {list} -- a list of numpy 1D array for true positive rate fpr {list} -- a list of numpy 1D array for false positive rate area {list} -- a list of floats for area under curve name {str...
5,346,277
def parameters_from_object_schema(schema, in_='formData'): """Convert object schema to parameters.""" # We can only extract parameters from schema if schema['type'] != 'object': return [] properties = schema.get('properties', {}) required = schema.get('required', []) parameters = [] ...
5,346,278
def env_vars(request): """Sets environment variables to use .env and config.json files.""" os.environ["ENV"] = "TEST" os.environ["DOTENV_FILE"] = str(DOTENV_FILE) os.environ["CONFIG_FILE"] = str(CONFIG_FILE) os.environ["DATABASE_URL"] = get_db_url() return True
5,346,279
def any_toggle_enabled(*toggles): """ Return a view decorator for allowing access if any of the given toggles are enabled. Example usage: @toggles.any_toggle_enabled(REPORT_BUILDER, USER_CONFIGURABLE_REPORTS) def delete_custom_report(): pass """ def decorator(view_func): @w...
5,346,280
def moguls(material, height, randomize, coverage, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=True, bf=True, optimize=True, xtraParams=defaultXtraParams): """moguls(material, radius, randomize, det, [e0=20.0], [withPoisson=True], [nTraj=defaultNumTraj], [dose = 120.0], [sf=True], [bf=...
5,346,281
def link_datasets(yelp_results, dj_df, df_type="wages"): """ (Assisted by Record Linkage Toolkit library and documentation) This functions compares the Yelp query results to database results and produces the best matches based on computing the qgram score. Depending on the specific database table c...
5,346,282
def hello(): """Say Hello, so that we can check shared code.""" return b"hello"
5,346,283
def copytree(src, dst, symlinks=False, ignore=None): """ Credit: http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth """ for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) ...
5,346,284
def loglog_mean_lines(x, ys, axis=0, label=None, alpha=0.1): """ Log-log plot of lines and their mean. """ return _plot_mean_lines(partial(plt.loglog, x), ys, axis, label, alpha)
5,346,285
def read_lines_from_shapefile(fpath): """ Read coordinates of cutting line segments from a ESRI Shapefile containing line features. Parameters ---------- fpath Name of a file containing coordinates of cutting lines Returns -------- list ...
5,346,286
def generate_identifier(endpoint_description: str) -> str: """Generate ID for model.""" return ( Config.fdk_publishers_base_uri() + "/fdk-model-publisher/catalog/" + sha1(bytes(endpoint_description, encoding="utf-8")).hexdigest() # noqa )
5,346,287
def test_instant_memory_statistics(): """ Test the instant memory statistics. """ stats = instant_memory_statistics() # test bounds (percent) assert type(stats) is float assert stats >= 0 assert stats <= 100
5,346,288
def depthFirstSearch(problem): """Search the deepest nodes in the search tree first.""" stack = util.Stack() # Stack used as fringe list stack.push((problem.getStartState(),[],0)) return genericSearch(problem,stack)
5,346,289
def parse_cli_args() -> argparse.Namespace: """ Parse arguments passed via Command Line Interface (CLI). :return: namespace with arguments """ parser = argparse.ArgumentParser(description='Algorithmic composition of dodecaphonic music.') parser.add_argument( '-c', '--config_path...
5,346,290
def create_app(): """ Method to init and set up the Flask application """ flask_app = MyFlask(import_name="dipp_app") _init_config(flask_app) _setup_context(flask_app) _register_blueprint(flask_app) _register_api_error(flask_app) return flask_app
5,346,291
def read_file(filename=""): """reads text file""" with open(filename, mode='r', encoding='utf-8') as a_file: print(a_file.read(), end='') a_file.close()
5,346,292
def find_consumes(method_type): """ Determine mediaType for input parameters in request body. """ if method_type in ('get', 'delete'): return None return ['application/json']
5,346,293
def preprocess(text): """ Simple Arabic tokenizer and sentencizer. It is a space-based tokenizer. I use some rules to handle tokenition exception like words containing the preposition 'و'. For example 'ووالدته' is tokenized to 'و والدته' :param text: Arabic text to handle :return: list of tokenized sen...
5,346,294
def login(client, password="pass", ): """Helper function to log into our app. Parameters ---------- client : test client object Passed here is the flask test client used to send the request. password : str Dummy password for logging into the app. Return ------- post re...
5,346,295
def define_dagstermill_solid( name, notebook_path, input_defs=None, output_defs=None, config_schema=None, required_resource_keys=None, output_notebook=None, output_notebook_name=None, asset_key_prefix=None, description=None, tags=None, ): """Wrap a Jupyter notebook in a s...
5,346,296
def barycorr(eventfile,outfile,refframe,orbit_file,output_folder): """ General function to perform the barycenter corrections for a Swift event file eventfile - path to the event file. Will extract ObsID from this for the NICER files. outfile - path to the output event file with barycenter corrections ...
5,346,297
def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor: """De-normalizes LAFs from scale to image scale. B,N,H,W = images.size() MIN_SIZE = min(H,W) [a11 a21 x] [a21 a22 y] becomes [a11*MIN_SIZE a21*MIN_SIZE x*W] [a21*MIN_SIZE a22*MIN_SI...
5,346,298
def project_main(GIS_files_path, topath): """ This main function reads the GIS-layers in GIS_files_path and separates them by raster and vector data. Projects the data to WGS84 UMT37S Moves all files to ../Projected_files Merges the files named 'kV' to two merged shape file of Transmission and Medium Vo...
5,346,299