content
stringlengths
22
815k
id
int64
0
4.91M
def get_metric(run_id, metric_id): """ Get a specific Sacred metric from the database. Returns a JSON response or HTTP 404 if not found. Issue: https://github.com/chovanecm/sacredboard/issues/58 """ data = current_app.config["data"] # type: DataStorage dao = data.get_metrics_dao() metr...
64,600
def test_pivot_funcs_df_merge(_create_pivot, join_type, test_case): """Test calling function with DF input attributes.""" func = getattr(getattr(test_case.entity, test_case.provider), test_case.pivot_func) # Test DF input val = enumerate(test_case.value.keys()) in_df = pd.DataFrame(val, columns=["id...
64,601
def make_more_vivid(image): """Modify the saturation and value of the image.""" hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) hue, saturation, value = cv2.split(hsv) saturation = np.array(saturation * 1.2, dtype=np.uint16) saturation = np.array(np.clip(saturation, 0, 255), dtype=np.uint8) value...
64,602
def get_image_bookmark(caller, config, hide, start_page=1, end_page=0, tag=None, use_image_tag=False): """Get user's image bookmark""" br = caller.__br__ total_list = list() i = start_page offset = 0 limit = 48 member_id = br._myId total_bookmark_count = 0 encoded_tag = '' while...
64,603
def tokenize_program(lines): """Tokenizes a program consisting of multiple lines.""" addr = 0x801 for line in lines: # Skip lines that entirely consist of other whitespace, # though we want to keep this for actual program lines if not line.strip(): continue # ign...
64,604
def plugDst(srcPlug): """ Return the destinations of a connected source plug. If the source is unconnected, returns None. """ pass
64,605
def test_base_init_db_should_use_parameters_over_env_variables(mongo_client): """ Tests mongodb connection is setup with values from function parameters rather then environment variables """ os.environ["MONGODB_HOST"] = "wronghost" os.environ["MONGODB_PORT"] = "00000" os.environ["DATABASE_NA...
64,606
def clean_and_analyze_data(): """processing collected data: 1. MBEW table (valuation data) 2. prepares final dataFrame object with additional columns 3. populate valuation type columns 4. MBEWH table (previous period valuation data) 5. EKPO table (Purchasing documents data) 6. ISEG table (Op...
64,607
def capacity_cost_rule(mod, g, p): """ """ return mod.DRNew_Cost[g, p]
64,608
def test_validate_parse_all(): """Read all logfiles from configuration.""" log_dict = {"l1": Path("./app1.log"), "l2": Path("./custom/appl.log")} result = logtailor.validate_log(True, "", log_dict) assert result == [log_dict["l1"], log_dict["l2"]]
64,609
def syncronize_syncs(method_name, config, sync_name=None, host_name=None): """use the config to push paths to hosts syncronize syncs by pulling or pushing sync's paths to hosts if None used as host_name with push method, sync syncronized with all hosts, but in pull method it start syncing sync ...
64,610
def download_files(msg): """ 下载多媒体附件 """ filename = '_'.join([msg['User']['RemarkName'] or msg['User']['NickName'], ut.timestamp2str(msg['CreateTime']), msg['FileName']]) full_filename = os.path.join(st.downloads_dir, filename) msg['Text'](full_filename) itchat.send('@%s@%s' % ('img' if msg...
64,611
def Vc_methods(CASRN): """Return all methods available to obtain Vc for the desired chemical. Parameters ---------- CASRN : str CASRN, [-] Returns ------- methods : list[str] Methods which can be used to obtain Vc with the given inputs. See Also -------- Vc ...
64,612
def get_builtin_specs(): """ Produces a list of all available specs :return: """ # get list of available dicts, assuming the _ separates name_version specs = [s.stem.split("_") for s in Path(pkg_specs_dir()).glob("*.yml")] # gives us list of tuples with valid combinations valid_specs =...
64,613
def get_term_count_list(term, term_field="text_xml", limit=opasConfig.DEFAULT_LIMIT_FOR_SOLR_RETURNS, offset=0, term_order="index", wildcard_match_limit=4): """ Returns a list of matching terms, and the number of articles with that term. Args: term (str): Term or comma separated list of terms ...
64,614
def create_fann_train_from_csv(csv_fname, train_fname, sections, all_species): """ takes the csv file saved by the leaf collection and creates FANN training data from it. """ # format 'binomial nomenclature: [leaf measurements] imported_data = {} total_leaves = 0 # read and parse the csv...
64,615
def RHS_func(t, y_flat, mc_inst): """RHS function for the ODEs, get's called in ivp.solve_ivp""" reimport_numerical_libs("RHS_func") # constraint on values lower, upper = (0.0, 1.0) # bounds for state vars # grab index of OOB values so we can zero derivatives (stability...) too_low = y_flat ...
64,616
def __get_last_successive_rg_area(df: DataFrame, rg_field_name, area=RGAreaTagValue.GREEN): """ 获取最后一段颜色为area的连续区域 @param df: @param rg_field_name: @param area: @return: """ # TODO 全红或者全绿需要处理 if df[df[rg_field_name] != area].shape[0] == 0: return df.copy().reset_index(drop=Tr...
64,617
def cli(): """ Hi! This is a small command line tool called `pim` for making it easy to publish Python packages. If you're just getting started with a new project, you'll want to call `pim init` to initialize a project from inside a new folder. If you already have a project you want to publish, y...
64,618
def test_jwt_auth_wrong_try_refresh( client, settings, mocked_jwt_auth, not_auth_response): """Assert that on authentication error the refresh_access_token method of JWTAuth gets called.""" client.settings = settings client.auth = mocked_jwt_auth assert not client.auth.refresh_access_toke...
64,619
def pretty_print_attention_t2t(attention_probs, input_tree, target_tree, threshold=0.1): """ Display the parts of the tree focused on at each iteration by the attention mechanism at each step of the generation of the target sequence. This function was designed for the identity dataset, where the ...
64,620
def extract_item_text(item_text_elmt: bs4.Tag) -> str: """Extract the text content of an item.""" fins = '' for tag in item_text_elmt.contents: if tag.name != 'div': # since we're using the raw string representation, which would include # named and numeric character reference...
64,621
def get_optimizer( beta1: float, beta2: float, eps: float, lr: float, model: BaseModel, wd: float, ) -> torch.optim.AdamW: """Get AdamW optimizer. Parameters ---------- beta1: float First coefficient of gradient moving average. beta2: float Second coefficient of gradient moving average. ...
64,622
def __importanceFromDset(): """ computes the importance map for a whole dataset """ from contextlib import ExitStack import h5py from console_progressbar import ProgressBar DATASET_PREFIX = "D:/VolumeSuperResolution-InputData/" DSET = "gt-rendering-ejecta-v2-test.hdf5" OUTPUT = "gt-...
64,623
def get_cached_tags(userkey): """ Fail-safe way to get the cached tags for `userkey` """ try: return all_tags[userkey] except KeyError: return []
64,624
def parse_config( raw_config: Dict[str, Any] ) -> Tuple[Optional[InfestorConfiguration], List[str], List[str]]: """ Checks if the given configuration is valid. If it is valid, returns (True, []) else returns (False, [<warnings>, ...], [<error messages>, ...]). """ warn_messages: List[str] = [] ...
64,625
def gps2dyr(time): """ Converte GPS time to decimal years. """ #return Time(time, format='gps').decimalyear return Time(time, format='gps').datetime
64,626
def main(): """Run all info-gathering scripts Note: cifsfixer isn't run because the info-gathering is a side effect of the actual purpose of that script. We might want to move the info-gathering to a separate script, but for now it is OK. So... cifsfixer is run separately by another cronjob. "...
64,627
def surface_carre(arete): """ fonction qui calcule et renvoie la surface d'un carré :param arête: la longueur d'un des côtés du carré :type arete: int ou float :return: la surface du carré dans l'unité (au carré) de celle d'arete :rtype: int ou float """ return arete*arete
64,628
def notify_ifttt(message, title=None, link=None, key=None): """Send notification via IFTTT Parameters ---------- message : str title : str, optional link : str, optional key : str, optional API key for IFTTT. If not set, imports the environmental variable IFTTT_WEBHOOK_KEY....
64,629
def encode(gene, size=SIZE, k=K, h=H, HASH_MAX=sys.maxsize + 1): """Creates a bloom filter. Used to encode a genetic sequence. Args: gene: A string holding all or part of a DNA sequence. size: The size of the bloom filter. Set to the default size if no size is given. k: The ...
64,630
def build_xml_stream(xml_tags_fragment="", xml_items_fragment=""): """Formats the boilerplate XML template with the provided fragment for top level tags.""" return StringIO( xml_stream_header + xml_tags_fragment + xml_items_fragment + xml_stream_footer )
64,631
def task_status(request, task_id=None, data=None): """ Returns (:http:get:`GET </task/(task_id)/status>`) task status and task result. .. http:get:: /task/(task_id)/status :DC-bound?: * |dc-no| :Permissions: * |UserTask| :Asynchronous?: * |async-...
64,632
def frob_options_into_tests(suite, options): """ Make sure 'options' is available as a class variable to all of the tests. This is a horrible hack, but saves a lot of typing. """ for test in suite._tests: if isinstance(test, unittest.suite.TestSuite): # recursively itera...
64,633
def getOptions(): """ Function to pull in arguments """ parser = argparse.ArgumentParser(description="Reads a FASTQ file and calculates position bias.") parser.add_argument("-i", "--input", dest="fname", action='store', required=True, help="Name of input FASTQ file [Required]") parser.add_argument("-o",...
64,634
def format_inline_cite(entry_list, citation_manager): """Return string, formatted in-text citation (allows *multiple* citations). `entry_list` : list entries to be formatted `citation_manager` : CitationManager instance handles name formatting :note: need the entry formatter bc its determines the field of the...
64,635
def populate_datafile_directory(expt_id, storage_box, force_update=False): """ For DataFiles that were ingested without a value for the `directory` field, take the base path from the associated DataFileObject.uri and use it as the `directory` field. Filters by StorageBox name. Example: ...
64,636
def WY_to_Q(W, YH): """ Retrieves Q from its WY representation. """ m = W.shape[0] Id = jnp.eye(m, dtype=W.dtype) return B_times_Q_WY(Id, W, YH)
64,637
def compare_identifier(device): """ Compare device canonical name to the Pure Storage identifier. Args: device (string): Device canonical names. (See below for examples) Returns: pure_devices (list): List of confirmed Pure Storage backed devices. """ # Examples of valid device cano...
64,638
def register(): """ Registration method reflects that taught on the CI Task Manager project. Checks the entered registration details for an existing username and email and responds accordingly. If the values are unique; creates new database entry for the user and logs them in as the session user. ...
64,639
def gen_pipeline_test_baseline(ds_name='cifar10', tfds_path='', size_batch=100, size_buffer_cpu=5, dataset_cache=False, num_parallel_calls=-1): """ :param ds_name: dataset name for tensorflow datasets ...
64,640
def show(): """Display (like in IPython.display.dispay(...) the current figure""" gcf() # make sure we have something.. display(gcc())
64,641
def wait(layout, episodes_found): # type: (Layout, List[BaseInfo]) -> None """ Warten auf Tastatureingabe des Users. """ keyboard.add_hotkey('m', lambda: move_files(layout, episodes_found)) keyboard.add_hotkey('r', lambda: move_files(layout, episodes_found, rename_only=True)) keyboard.wait('...
64,642
def defer(orig: Union[TNone, dict], parent: Union[TNone, dict], *, info: MutationInfo, ) -> dict: """ Merge two dictionaries. defers conflicting values to another merger. """ output = {} orig_: dict = NULL.default_none(orig, {}) parent_: dict = NULL.d...
64,643
def pickle_matpower_cases(case_paths, case_format=2): """ Parses the MATPOWER case files at the given paths and pickles the resulting Case objects to the same directory. """ import pylon.io if isinstance(case_paths, basestring): case_paths = [case_paths] for case_path in case_paths...
64,644
def _confirm_webpage(url: str) -> bool: """ A function that confirms the existence of a webpage before the object is created """ response = requests.get(url=url, allow_redirects=True) code = response.status_code return True if code == 200 else False
64,645
def _transform_masks(y, transform, data_format=None, **kwargs): """Based on the transform key, apply a transform function to the masks. More detailed description. Caution for unknown transorm keys. Args: y: `labels` of ndim 4 or 5 transform: one of {`deepcell`, `disc`, `watershed`, `centro...
64,646
def set_cors_uri(cors_uri=None): """ Returns list of allowed domains for System Manager Role Method: POST Parameters: cors_uri [string] Valid URL. Path not included. e.g. http://localhost:8000 Path: /api/method/castlecraft.services.settings.set_cors_uri Error: 403 Response: ``` { "message": [ "https...
64,647
def send_tweet(in_list): """Receive a list of new devices. Send a tweet for each.""" with open('credentials.json') as json_file: creds = json.load(json_file) twit_creds = creds['twitter'] consumer_key = twit_creds['consumer_key'] consumer_secret = twit_creds['consumer_secret'] access_t...
64,648
def DRP_interleaver(K, w, r, s, p): """Inputs: K = interleaver size w = write dither vector, must be a factor of K r = read dither vector, must be a factor of K s = RP interleaver start index, must be in [0,K-1] p = RP interleaver, must be relatively prime to K Returns DRP interleaver """ # DRP interleaver par...
64,649
def get_face_coordinates(vertex, faces, K_max='None'): """ computes the face_cooridinates used for surface Loss Input: vertex = (N x 3) faces = (F x 3) triangle mesh Output: face_cooridnates = (NxKx9) where K is the max numbers of neighbours. Each row lists vertex coordinates for...
64,650
def get_config(infile=None, configspec=None, *args, **kwargs): """Get configuration from a file.""" if configspec is None: configspec = cfg.split("\n") return Config(infile, configspec=configspec, *args, **kwargs)
64,651
def remove_short_cycles(data, min_length=2): """ Remove cycles with length smaller than `min_length`. Notes ----- Modifies `cycles`, `cycles_lengths` attributes of `data`. """ ii = np.where(data.cycles_lengths >= min_length)[0] data.cycles = data.cycles[ii] data.cycles_lengths = dat...
64,652
def BuildDebugInfoResponse( name, servers = [], items = [] ): """Build a response containing debugging information on a semantic completer: - name: the completer name; - servers: a list of DebugInfoServer objects representing the servers used by the completer; - items: a list of DebugInfoItem objects for ad...
64,653
def envs_irm_S(X_train, X_test, T_train, y_train, E, number_environments): """Compute the environments variable required by the InvariantRiskMinimization class for IRM_S / IRM_1 Args: - X_train: training features - X_test: test features - T_train: training treatment - y_train: training observed...
64,654
def test_read_partial_data(casino_cross_section): """ Tests for method :py:meth:`read_partial_data`. """ atomic_number = 6 assert atomic_number not in casino_cross_section.partial_functions casino_cross_section.read_partial_data(atomic_number) assert atomic_number in casino_cross_section.pa...
64,655
def delete_department(id): """ Delete a Department by id :param id: id of deleting Department """ department = Department.query.get_or_404(id) db.session.delete(department) db.session.commit()
64,656
def plot_sfc_winds_skt(lonu, latu, u, v, lont, latt, t, mode): """ Plot filled contours overlayed with contours and vectors Input ------- lonu = lon values extracted from wind dataset (1-D) latu = lat values extracted from wind dataset (1-D) u = U-wind at surface, shape = lonu X latu ...
64,657
def netaddr(host_ip, prefix): """Return network address and subnet mask.""" ip_address = host_ip + '/' + prefix try: ip_net = ipaddress.ip_network(ip_address, False) output = {'network_address': str(ip_net.network_address), 'network_mask': str(ip_net.netmask), ...
64,658
def timeout(duration): """Rewrite a coroutine to operate on a strict timeout""" def rewrite(fn): async def wrapper1(*args, **kwargs): try: return await fn(*args, **kwargs) except asyncio.CancelledError: pass async def wrapper2(*args, **kwa...
64,659
def data_preparation(config, save=False): """Split the dataset by :attr:`config['split_strategy']` and call :func:`dataloader_construct` to create corresponding dataloader. Args: config (Config): An instance object of Config, used to record parameter information. save (bool, optional): If `...
64,660
def app(n, p): """ Parameters ---------- n Order p Dimension of the problem (number of input pi number in the pyVPLM case) Returns Approximates the solution for big n and p ------- """ # c = -0.0027*p + 0.147 return int(p**n/(fact(n) + 1))
64,661
def bit_count(bin_name, bit_offset, bit_size): """Creates a bit_count_operation to be used with operate or operate_ordered. Server returns an integer count of all set bits starting at bit_offset for bit_size bits. Args: bin_name (str): The name of the bin containing the map. bit_offset (in...
64,662
def change_message_from_percent(percent_change: Union[str, int, float]) -> str: """Creates a change message from given percentage change. percent_change will be: - "-" in case the last data point was missing - 0 (int) in case there was no change - positive value (int/float) in case ther...
64,663
def infer_type(value: Any) -> DataType: """Infers a trino type from the given python value. """ if isinstance(value, bool): return boolean() if isinstance(value, int): return infer_integral(value) if isinstance(value, float): return double() if isinstance(value, Decimal):...
64,664
def load_trajectory_to_npy(filename, name="", begin=0, end=None, stride=None): """ Loads the trajectory into four numpy arrays containing: * the number of particles per frame (shape=(n_frames,)) * the positions of the particles for each frame (shape=(n_frames, max_n_particles_per_frame, 3)) * the t...
64,665
def recurse(gentle_output, audio_file, anchor_length): """ Recursively align the unaligned segments of a given Gentle output. Parameters ---------- gentle_output : list of Word objects outputted by previous Gentle run audio_file : PyDub object representing the entire audio file anchor_lengt...
64,666
def close_connection(): """ Function to close the connection to the remote server """ global _remote_client _remote_client.close() _remote_client = None
64,667
def test_custom_metric_passed_to_bootstrap_compute( PM_da_initialized_1d, PM_da_control_1d ): """Test custom metric in bootstrap_perfect_model.""" comparison = "e2c" dim = "init" np.random.seed(42) actual = bootstrap_perfect_model( PM_da_initialized_1d, PM_da_control_1d, ...
64,668
async def test_generate_startlist_for_event_contestants_bib_not_unique( client: _TestClient, mocker: MockFixture, token: MockFixture, event: dict, format_configuration: dict, raceclasses: List[dict], raceplan_interval_start: dict, contestants: List[dict], request_body: dict, ) -> Non...
64,669
def set_mute_indicator(mute_indicator, enabled): """Toggle the provided source""" if not mute_indicator: return source = obs.obs_get_source_by_name(mute_indicator) if not source: dprint(f'Error! Could not get source {mute_indicator}') return obs.obs_source_set_enabled(sourc...
64,670
def get_released_versions(package_name): """ Fetches the released versions & datetimes of the specified Python package. Examples -------- >>> get_released_versions("scikit-learn") {'0.10': '2012-01-11T14:42:25', '0.11': '2012-05-08T00:40:14', ...} """ url = "https://pypi.python.org/pypi...
64,671
def _raise(ex): """Exception as function""" raise ex
64,672
def test_run(): """Run with a rectangle, cross and circle""" object_set = cellprofiler_core.object.ObjectSet() labels = numpy.zeros((10, 20), int) labels[1:9, 1:5] = 1 labels[1:9, 11] = 2 labels[4, 6:19] = 2 objects = cellprofiler_core.object.Objects() objects.segmented = labels obje...
64,673
def total_loss_function(c_image,s_image,g_image,alpha,beta): """ Args: c_image_path (str): To take the content image path s_image_path (str): To take the style image path g_image_path (str): To take the generate image path Returns: int: The totoal loss...
64,674
def cartesian_to_spherical(x, y, z): """ Convert cartesian coordinates to spherical in the form (theta, phi[, r]) with the origin remaining at the center of the original spherical coordinate system. """ r = np.sqrt(x**2 + y**2 + z**2) #theta = np.arccos(z / r) theta = np.arctan2(y, x) p...
64,675
def logistic(z: np.ndarray, a: float, b: float) -> np.ndarray: """ Compute logistic function Inputs: a: exponential parameter b: exponential prefactor z: numpy array; domain Outputs: f: numpy array of floats, logistic function """ den = 1.0 + b * np.exp(-...
64,676
def get_diamond_predicted_domains(predicted_domains, protein_accession): """Retrieve the CAZyme domains predicted by DIAMOND, from the overview.txt file. :param predicted_domains: list of strings, each string contains a unique CAZyme domain prediction :param protein_accession: str Return list of Cazym...
64,677
def review(): """ user wants to toggle a paper in his library """ # make sure user is logged in if not g.user: return 'NO' # fail... (not logged in). JS should prevent from us getting here. idvv = request.form['pid'] # includes version if not isvalidid(idvv): return 'NO' # fail, malformed id. weir...
64,678
async def find_busy_consumers(engine): """Returns a list of busy consumers that can be used to run.""" Consumer = namedtuple('Consumer', ['ip', 'status', 'port', 'job_chunk_id']) try: async with engine.acquire() as connection: query = sa.text(''' SELECT ip, status, port,...
64,679
def mlp_missing_biology_occurrences(): """ Function to identify occurrences that should also be biology but are missing from biology table :return: returns a list of occurrence object ids. """ result_list = [] # Initialize result list # Biology occurrences should be all occurrences that are ite...
64,680
def print_anycli(**kwargs): """ List the number of deployed scripts on remote device :param kwargs: keyword value: value to display :return: display the result of AnyCLI :Example: result = cli(url=base_url, auth=s, command="show vlan") print_anycli(result) """ value = kwargs...
64,681
def create_virus_total_headers_from_config(): """ Creates a dictionary called virus_total_headers that contains the formatted header needed to submit an query to VirusTotal. Requires an VirusTotal API Key to use. It is free to sign up for one but has restrictions on daily limits. Reads in th...
64,682
def add(existing_account_customer, new_account_customer, Session): """Add a second customer to the account of an existing customer.""" with Session() as session: # get existing account firstname, lastname = split_name(existing_account_customer) stmt = select(Account).join(Account.custom...
64,683
def query_builder(title, city, state): """This function will be called from view to build the search query """ # TODO the query body has to be in a separate json file in utils and not hard coded here # Also if you dont want to check city name against a full list of all cities you can use Fuzzy feature ...
64,684
def get_shape_not_match_message(shape_error_type, value): """ Function Description: get shape not match message Parameter: input:the value shape_error_type: the shape error type Return Value: not match message """ message = "" if shape_error_type == InputShape...
64,685
def extract_projstring(proj_string): """ Import an OSR supported projection string into a spatial reference object Parameters ---------- proj_string : string Projection String in some OSR supported format Returns ------- srs : object OSR spatial referenc...
64,686
def dump_items(file, iter_to_save, ensure_space=False, fun_err_space=None): """ Serialize one iterable in a single file >>> with open("test_items.tmp", "wb") as f: ... dump_items(f, ["a", "b", "c"]) :param file: file where dump :param iter_to_save: iterable with items to save :param en...
64,687
def test_wait_for_ssh(mock_ssh_running): """ Test the wait for ssh helper method """ fqdn = "127.0.0.1" # Setup Mock to test happy path mock_ssh_running.return_value = True ssh.wait_for_ssh(fqdn, timeout=.1, interval=0) assert mock_ssh_running.call_count == 1 # Setup Mock to test sad path...
64,688
def scrape_katportal_log(logfile, keystring): """Retrieve timestamps and values for a katportal log entry containing a particular string. Examples of logfile lines: [2020-06-19 19:31:43,347 - INFO - katportal_server.py:108] {'msg_channel': 'array_1:subarray_1_observation_acti...
64,689
def test_write_logs(api_client, ofa_admin): """Test endpoint consumption of arbitrary JSON to be logged.""" user = ofa_admin api_client.login(username=user.username, password="test_password") data = { "original_filename": "data_file.txt", "quarter": "Q1", "slug": uuid.uuid4(), ...
64,690
def show_bookmarks_related(context, title, url, object, description=""): """ Displays the bookmarks with counter. """ if not isinstance(object, models.Model): raise TypeError, "object must be a valid Model" if not url.startswith('http'): url = context['request'].build_absolute_...
64,691
def is_service(hass, entry): """check whether config entry is a service""" domain, service = entry.split(".")[0], ".".join(entry.split(".")[1:]) return hass.services.has_service(domain, service)
64,692
def state_to_th_vel(config: PendulumConfig, state: int) -> Tuple[float, float]: """Convert a state id to the angle and the angle velocity. Args: config (PendulumConfig) state (int) Returns: theta and vel_theta values. """ th_res, vel_res = config.theta_res, config.vel_res ...
64,693
def RemapParameters(metaTemplate, parametersLines, noOfAttributes): """Makes a pass over the metatemplate to re-number the parameters from the first line.""" oldtoNewParamMap = {} count = 0 for block in metaTemplate.blocks: for line in block.lines: for attribute in range(noOfAttribut...
64,694
def _dnorm(W, norm='ave'): """ Normalizes a symmetric kernel `W` Parameters ---------- W : (N, N) array_like Similarity array generated by `SNF` norm : str, optional Type of normalization to perform. Must be one of ['ave', 'gph']. Default: 'ave' Returns ...
64,695
def parse(html, path): """ parsing html content :param html - string with html content: :param path - strind with xpath query: :return: parsered lxml objects """ try: html_tree = lxml.html.fromstring(html) result = html_tree.xpath(path) except Exception: abort(500...
64,696
def image_loader(image_path: str, img_size: tuple = (128, 128)) -> Tensor: """ Loading and preprocessing an image :param image_path: path to image :param img_size: image size :return: image format torch.Tensor """ loader: transforms.Compose = transforms.Compose([ transforms.Resize(im...
64,697
def handle_property_import(prop): """ Every odml-ui property requires at least one default value according to its dtype, otherwise the property is currently broken. Further the properties are augmented with 'pseudo_values' which need to be initialized and added to each property. :param prop: im...
64,698
def slurm_parse_timestr(s): """ A slurm time parser. Accepts a string in one the following forms: # "days-hours", # "days-hours:minutes", # "days-hours:minutes:seconds". # "minutes", # "minutes:seconds", # "hours:minutes:seconds", Returns: Time in se...
64,699