content
stringlengths
22
815k
id
int64
0
4.91M
def cross_energy(sig, eps, mesh): """ Calcul de l'energie croisée des champs de contrainte sig et de deformation eps. """ return fe.assemble(fe.inner(sig, eps) * fe.dx(mesh))
46,800
def test_chain_id_cancel_or_replace_transaction(alice_wallet, bob_address): """Tests if the chainId has the right value for cancelled tx.""" receipt_cancelled = cancel_or_replace_transaction(alice_wallet, None) assert receipt_cancelled, "Cancel or replace transaction failed." tx_cancelled = alice_wallet...
46,801
def death_rate(row, log: ResultLog): """Check that deaths are <5% of test results""" n_pos, n_neg, n_deaths = row.positive, row.negative, row.death n_tot = n_pos + n_neg percent_deaths = 100.0 * n_deaths / n_tot if n_tot > 0 else 0.0 if n_tot > 100: if percent_deaths > 5.0: log...
46,802
def login(): """ 登录API :return: True: 登录成功; False: 登录失败 """ ctrl.BEING_LOG = True if check_login_status(): ctrl.BEING_LOG = False return True error_times = 0 while True: try: update_proxy() update_cookies() username = change_to...
46,803
def evaluate_cnn(image, net): """Run a fully convolutional CNN over the given image, returning feature layers and unaries.""" pass
46,804
def _check_store_version(store): """Clears 'store' if the version is too old or raises an error if the version is too new. """ if store["version"] < RUNTIME_INFO_FILE_VERSION: LOG.warn("Runtime file info version is old and will be ignored") store.clear() elif store["version"] > RUNTIME_INFO_FILE_VERSI...
46,805
def dismiss_alerts(): """ Dismiss the given list of alerts based on given filter """ ids = argToList(demisto.getArg('alert-id')) policies = argToList(demisto.getArg('policy-id')) payload = {'alerts': ids, 'policies': policies, 'dismissalNote': demisto.getArg('dismissal-note'), 'filter': {}} ...
46,806
def logout(): """Logout""" next_url = request.args.get('next') if 'next' in request.args else None # status = request.args.get('status') if 'status' in request.args else None # client_id = request.args.get('client_id') if 'client_id' in request.args else None logout_user() return redirect(next_u...
46,807
def test_tempai_with_closed_kan(): """ there was a bug where bot didn't handle tempai properly with closed kan which was viewed as open one and thus open hand """ table = Table() player = table.player tiles = string_to_136_array(man="56", pin="4444", sou="223789", honors="55") player.in...
46,808
def find_all(query, model, kwargs): """ Returns a query object that ensures that all kwargs are present. :param query: :param model: :param kwargs: :return: """ conditions = [] kwargs = filter_none(kwargs) for attr, value in kwargs.items(): if not isinstance(value, l...
46,809
def create_init_sql(replica_set_type, parser, override_dir): """ Create a init.sql file if needed Args: replica_type - Hostname prefix of the db host to be configured parser - A ConfigParser object of mysqld settings override_dir - Write to this directory rather than default """ if replica...
46,810
def write(topology, outfile): """Write a Gromacs topology to a filename or stream, from the given list of instructions""" if isinstance(outfile, str): outfile = open(outfile, 'w') natoms = len([inst for inst in topology if isinstance(inst, GmxTopAtom)]) aflen = len(str(natoms)) if afle...
46,811
def test_integrals_bg_corr_pkg(): """Background correction for defined integrals with packages.""" integrals = np.array([[10, np.sqrt(10)], [40, np.sqrt(40)]]) integrals_pkg = np.array([integrals]) int_names = np.array(["28Si", "29Si"]) int_ch = np.array([30, 40]) bgs = np.array([[1, np.sqrt(1)]...
46,812
def find_word(x, y, large_lst, word, row_col_lst): """ :param x: The x coordinate to pick from large_lst :param y: The y coordinate to pick from large_lst :param large_lst: A large list that accesses four lists :param word: (str) :param row_col_lst: Used to access the position of a letter that has been added (Avo...
46,813
def ot1dkl(x, y, M, epsilon, log=True, **kwargs): """General OT 2d function.""" if log: ot = ot1dkl_log else: ot = ot1dkl_ output = ot(x, y, M, epsilon, **kwargs) return output
46,814
def _download(url: str, save_path: str, filename: str): """Writes data from url to file.""" if os.path.exists(os.path.join(save_path, filename)): logger.info("File %s already downloaded" % (os.path.join(save_path, filename))) return r = urllib.request.urlopen(url) logger.info("Downloadi...
46,815
def normalize_element_without_regex(filter, field): """ mongomock does not support regex... """ if len(filter) > 0: filters = {field: { "$in": filter}} else: filters = {} print filters return filters
46,816
def _pad_random(m, new_rows, rand): """Pad a matrix with additional rows filled with random values.""" rows, columns = m.shape low, high = -1.0 / columns, 1.0 / columns suffix = rand.uniform(low, high, (new_rows, columns)).astype(REAL) return vstack([m, suffix])
46,817
def test_len_drops_symlinks_from_the_job_count_to_avoid_double_counting(proj): """ Test that __len__ has the correct behaviour when symlinks are present """ symlink = proj.basepath / "MotionCorr" / "relioncor2" symlink.symlink_to(proj.basepath / "MotionCorr" / "job002") sym_motioncorr = proj...
46,818
def quantize_sequences(sequences, alphabet): """Giving prescribing alphabet, quantize each caracter using index in alphabet in each sequence. input: sequences: [str] return: [[int]] """ print("quantizing sequences...") new_sequences = [] for sequence in sequences: ...
46,819
def load_CIFAR10(ROOT): """ load all of cifar """ xs = [] ys = [] for i in range(1,6): f = os.path.join(ROOT, 'data_batch_%d' % (i,)) X, Y = load_CIFAR_batch(f) xs.append(X) ys.append(Y) Xtr = np.concatenate(xs) Ytr = np.concatenate(ys) del X, Y """ Xt...
46,820
def test_kappa_RTA_aln_with_sigma(aln_lda): """Test RTA with smearing method by AlN.""" aln_lda.sigmas = [ 0.1, ] aln_lda.sigma_cutoff = 3 kappa = _get_kappa(aln_lda, [7, 7, 5]).ravel() np.testing.assert_allclose(aln_lda_kappa_RTA_with_sigmas, kappa, atol=0.5) aln_lda.sigmas = None ...
46,821
def test_common_error_retry(error_response, requests_mock, common_params, fake_properties_list): """Error once, check that we retry and not fail""" properties_response = [ {"name": property_name, "type": "string", "updatedAt": 1571085954360, "createdAt": 1565059306048} for property_name in fake_...
46,822
def main(args): """ Main entrypoint for merge_star_gene_counts. """ logger = get_logger("merge_star_gene_counts") logger.info( "Merging/Formatting {0} STAR gene counts files.".format(len(args.input)) ) process_files(args, logger)
46,823
def search(context, mpd_query): """ *musicpd.org, music database section:* ``search {TYPE} {WHAT} [...]`` Searches for any song that contains ``WHAT``. Parameters have the same meaning as for ``find``, except that search is not case sensitive. *GMPC:* - does not add quotes ar...
46,824
def get_camera_pose(camera_info): """ :param camera_info: :return: """ camera_pose = list() for sbj in camera_info.keys(): for i, cam in enumerate(camera_info[sbj]): camera_pose.append(cam.cam_orig_world.reshape(3)) return np.array(camera_pose)
46,825
def _plot_update_raw_proj(params, bools): """Helper only needs to be called when proj is changed""" inds = np.where(bools)[0] params['info']['projs'] = [copy.deepcopy(params['projs'][ii]) for ii in inds] params['proj_bools'] = bools params['projector'], _ = setup_proj(...
46,826
def my_dice_metric_hemp(label, pred): """ Converts dice score metric to tensorflow graph, only hemp Args: label: ground truth mask [batchsize, height, width, classes] pred: prediction mask [batchsize, height, width, classes] Returns: dice value as tensor """ return tf...
46,827
def largest_second_derivative_2d(gxx, gxy, gyy): """This function determines the largest eigenvalue and corresponding eigen vector of an image based on Gaussian derivatives. It returns the direction and magnitude of the largest second derivative. For lines, this direction will correspond to the normal vecto...
46,828
def schema_to_entity_names(class_string): """ Mapping from classes path to entity names (used by the SQLA import/export) This could have been written much simpler if it is only for SQLA but there is an attempt the SQLA import/export code to be used for Django too. """ if class_string is None or ...
46,829
def deprecated( reason: str, replacement: Optional[str], gone_in: Optional[str], feature_flag: Optional[str] = None, issue: Optional[int] = None, ) -> None: """Helper to deprecate existing functionality. reason: Textual reason shown to the user about why this functionality has ...
46,830
def csm_data(csm): """ Return the data field of the sparse variable. """ return csm_properties(csm)[0]
46,831
def plot_hypnogram(resampled_hypno, cycles=None, label="", fig=None, ax=None): """ Plot an aesthetically pleasing hypnogram with optional cycle markers. Parameters ---------- resampled_hypno : pd.DataFrame Hypnogram resampled to epoch time units. cycles : cycles : pd.DataFrame, optional...
46,832
def _scroll_screen(direction: int) -> Callable: """ Scroll to the next/prev group of the subset allocated to a specific screen. This will rotate between e.g. 1->2->3->1 when the first screen is focussed. """ def _inner(qtile): if len(qtile.screens) == 1: current = qtile.groups.i...
46,833
def _gate_altitude_data_factory(radar): """ Return a function which returns the gate altitudes. """ def _gate_altitude_data(): """ The function which returns the gate altitudes. """ try: return radar.altitude['data'] + radar.gate_z['data'] except ValueError: retur...
46,834
def watermark(n_teams, test_directory, output_dir, create_htaccess, cached_credentials=None): """ Main interface for watermarking documents Creates team codes, team watermarks, and output directory structure Will prompt if file already exists for team codes or output directory exists Arg...
46,835
def whitespaceify_hidden_markers(*lines: str) -> Iterable[str]: """Convert "//" markers at the start of a line to ' '""" for line in lines: if line.strip().startswith("//"): line = line.replace("//", " ", 1) yield line
46,836
def test_posix_message_queue_ee( monkeypatch: pytest.MonkeyPatch, is_dir: bool, ee_support: bool, engine: str, generate_config: Callable, ): """Confirm error messages related to missing ``/dev/mqueue/`` and ``podman``. Test using all possible combinations of container_engine, ee_support, an...
46,837
def RandHexColor(length=6): """Generates a random color using hexadecimal digits. Args: length: The number of hex digits in the color. Defaults to 6. """ result = [random.choice(HEX_DIGITS) for _ in range(length)] return '#' + ''.join(result)
46,838
def _backtest2(prediction, price, acct_num,): """ Cal daiy return in % form :param prediction: :param price: :param acct_num: :return: """ # starting net val for trading account mat = np.ones((acct_num, len(price))) # liquidate or build position time _idx = np.arange(len(pric...
46,839
def check_players(instance): """ Checks to see if any of the starting players have left. Args: instance: The GameInstance model for this operation. If a player has left the game, they are invited back and a ValueError is raised. Raises: ValueError if a player has left the game. """ if len(insta...
46,840
def test_launch_context_emit_events(): """Test emitting events in LaunchContext class.""" lc = LaunchContext() class MockEvent: name = 'MockEvent' assert lc._event_queue.qsize() == 0 mock_event = MockEvent() lc.emit_event_sync(mock_event) assert lc._event_queue.qsize() == 1 mo...
46,841
def gethostbyname_ex(*args,**kw): """gethostbyname_ex(host) -> (name, aliaslist, addresslist) Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number.""" pass
46,842
def load_yaml(yaml_file, encoding): """ Load the passed in yaml configuration file """ try: import yaml except (ImportError): raise Exception('unable to import YAML package. Can not continue.') global config parsed_config = yaml.load(codecs.open(yaml_file, 'r', encoding).read()) ...
46,843
def list_descendant(input_list): """Function that orders a list on descendant order using insertion sort Args: input_list ([type]): List with the values that we want to order Returns: list: The ordered list """ for i in range(1, len(input_list)): j = i-1 next_elemen...
46,844
async def chargify_invoices_csv(request: Request): """ Output Chargify invoices data. """ output = StringIO() writer = csv.writer(output) if not request.app['chargify_invoices_data']: raise Exception("data not loaded yet") writer.writerows(request.app['chargify_invoices_data']) ...
46,845
def generate_base_reference(header,waveform="cosine",period=24,phase=0,width=12): """ This will generate a waveform with a given phase and period based on the header, """ ZTs = header tpoints = np.zeros(len(ZTs)) coef = 2.0 * np.pi / float(period) w = float(width) * coef for i,ZT in...
46,846
def from_string(dlstr): """Factory method taking the string as appearing in FIELD input""" input_key = dlstr.split()[0].lower() for subcls in Interaction.__subclasses__(): if subcls.key == input_key: return subcls.from_string(dlstr) raise ValueError("No interaction available for ...
46,847
def assign_cat(plugin): """Assigns `fonts` module keywords to the `Warp` plugin.""" meta = [ [KEYWORD_MATHCAL, "Script (or calligraphy): 𝒜ℬ𝒞𝒶𝒷𝒸𝒜𝒞𝒶𝒷𝒸"], [KEYWORD_MATHBB, "Double-struck: 𝔸𝔹ℂ𝕒𝕓𝕔𝟙𝟚𝟛𝔸𝔹𝕒𝕓𝕔𝟙𝟚𝟛"], [KEYWORD_MATHFRAK, "Fraktur: 𝔄𝔅ℭ𝔞𝔟𝔠𝔄𝔅𝔞𝔟𝔠"], ...
46,848
def validate_next_payload(payload): """Confirms the payload has the fields required for ldap message transformation""" # TODO: Move these into an enum, share with outbound_sync required_field_data = "data" required_field_data_type = "data_type" required_field_provider_id = "provider_id" require...
46,849
def turn_on(hass, entity_id=None): """Turn on specified media player or all.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.services.call(DOMAIN, SERVICE_TURN_ON, data)
46,850
def config_func(config): """Configure the maintenance degrade notifier plugin""" collectd.debug('%s config function' % PLUGIN) for node in config.children: key = node.key.lower() val = node.values[0] if key == 'port': obj.port = int(val) collectd.info("%s co...
46,851
def get_holidays(startYear = 2018, endYear = 2025, countryCode = 'ZA'): """ Takes in a start and end date, and start and end year. Produces a dataframe with a daily date and columns: holiday - 'Y' for holiday holidayName - name of the holiday if holiday is 'Y' Returns a datafra...
46,852
def _testHeadCheckSum(header, tableDirectory): """ >>> header = dict(sfntVersion="OTTO") >>> tableDirectory = [ ... dict(tag="head", offset=100, length=100, checkSum=123, data="00000000"+struct.pack(">L", 925903070)), ... dict(tag="aaab", offset=200, length=100, checkSum=456), ... di...
46,853
def scoring(argv): """ For each task, load and fit the Learner with the support set and evaluate the submission performance with the query set. A directory 'scoring_output' is created and contains a txt file that contains the submission score and duration. Note that the former is the time el...
46,854
def write_out_tile_coverage_layer(country, technologies): """ Write out tile coverage layer to .shp. """ iso3 = country['iso3'] for technology in technologies: output = [] filename = 'baseline_tile_coverage_{}.csv'.format(technology) folder = os.path.join(DATA_PROCESSED, ...
46,855
def test_delete_files_dirs(monkeypatch, shutdown_future, shutdown): """Test delete_files_dirs(). :param monkeypatch: pytest fixture. :param shutdown_future: conftest fixture. :param bool shutdown: Test shutdown handling. """ order = list() monkeypatch.setattr(api, 'upload_delete', lambda _,...
46,856
def svn_ra_do_status(*args): """ svn_ra_do_status(svn_ra_session_t session, svn_ra_reporter2_t reporter, void report_baton, char status_target, svn_revnum_t revision, svn_boolean_t recurse, svn_delta_editor_t status_editor, void status_baton, apr_pool_t pool) -> svn_error_t ...
46,857
def clear_spaces(comp): """ 'A + D' -> 'A+D' """ r = '' for c in comp: if c != ' ': r += c return r
46,858
def _load_metabolite_linkouts(session, cobra_metabolite, metabolite_database_id): """Load new linkouts even ones that are pointing to previously created universal metabolites. The only scenario where we don't load a linkout is if the external id and metabolite is exactly the same as a previous linkout....
46,859
def gen_ascii_captcha(symbols, length=6, max_h=10, noise_level=0, noise_char="."): """ Return a string of the specified length made by random symbols. Print the ascii-art representation of it. Example: symbols = gen_ascii_symbols(input_file='ascii_symbols.txt', ...
46,860
def windows_create_dynamic_package(input_hat_binary_path, output_hat_path, hat_description): """Creates a Windows dynamic HAT package (.dll) from a static HAT package (.obj/.lib)""" # Confirm that this is a static hat library _, extension = os.path.splitext(input_hat_binary_path) if extension not in ["....
46,861
def mock_device_registry_devices(hass): """Create device registry devices so the device tracker entities are enabled.""" dev_reg = dr.async_get(hass) config_entry = MockConfigEntry(domain="something_else") for idx, device in enumerate( ( "68:A3:78:00:00:00", "8C:97:EA:00...
46,862
def get_app_name_cache_file(file_path: str) -> str: """Returns path to app name cache file""" return f'{file_path}.{APP_NAME_FILE_EXTENSION}'
46,863
def make_matrix_A(x_r, simulations, ξ, Δ_t=1, λ=1): """ Equation (9) from paper :param x_r: reference output :param simulations: simulation outputs :param t_Δ: the intervals between each observation (series or constant) :param ξ: squash control parameter :return: the position/trend matr...
46,864
def generate_markov_content(content): """ Generate Markov Content Parameters ---------- content : str Corpus to generate markov sequences from """ # Build the model. text_model = markovify.Text(content, state_size=3) # return randomly-generated sentence of no more than 280 chara...
46,865
def _quadratic_system_matrix(x): """ Create system matrix of a model with linear, quadratic and 1st-order 2-way interaction terms Parameters ---------- x : array_like, shape (n, m) Explanatory variable of n data points and m variables Returns ------- A : ndarray, sha...
46,866
def pytest_pycollect_makeitem(collector, name, obj): """A pytest hook to collect curio coroutines.""" if collector.funcnamefilter(name) and curio.meta.iscoroutinefunction(obj): item = pytest.Function.from_parent(collector, name=name) if "curio" in item.keywords: return list(collector...
46,867
def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False): """Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss). Positional arguments: seconds -- integer/float indicating seconds remaining. Keyword arguments: ...
46,868
def apply_Hc(C, A_L, A_R, Hlist): """ Compute C' via eq 16 of vumps paper (132 of tangent space methods). """ H, LH, RH = Hlist A_Lstar = np.conj(A_L) A_C = ct.rightmult(A_L, C) to_contract = [A_C, A_Lstar, A_R, np.conj(A_R), H] idxs = [(4, 1, 3), (6, 1, -1), (5, ...
46,869
def start_stream_processor(Name=None): """ Starts processing a stream processor. You create a stream processor by calling CreateStreamProcessor . To tell StartStreamProcessor which stream processor to start, use the value of the Name field specified in the call to CreateStreamProcessor . See also: AWS API ...
46,870
def make_basic_gui(container): """Create a basic GUI layout. Parameters ---------- container : RenderContainer Returns ------- ipywidgets.GridspecLayout """ import ipywidgets as ipyw element_controls = [ ipyw.HTML(value="<b>Elements</b>", layout=ipyw.Layout(align_self...
46,871
def multiprocessing_traceback(func): """A decorator for formatting exception traceback into a string to aid in debugging when using the ``multiprocessing`` module.""" import traceback, functools @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs...
46,872
def shared_libraries_are_available(): """ check if python was built with --enable-shared or if the system python (with dynamically linked libs) is in use default to guessing that the shared libs are not available (be conservative) """ # if detection isn't possible because sysconfig isn't availab...
46,873
def parse_middleware_mkdir_response(mkdir_resp): """ Parse a response from RpcMiddlewareMkdir. Returns (mtime in nanoseconds, inode number, number of writes) """ return (_ctime_or_mtime(mkdir_resp), mkdir_resp["InodeNumber"], mkdir_resp["NumWrites"])
46,874
def sleep_ms(ms) -> None: """延时指定毫秒,参数不能小于0。""" ...
46,875
def decorate_batch(batch, device='cpu'): """Decorate the input batch with a proper device Parameters ---------- batch : {[torch.Tensor | list | dict]} The input batch, where the list or dict can contain non-tensor objects device: str, optional 'cpu' or 'cuda' Raises: --...
46,876
def setup_platform(opp, config, add_devices, discovery_info=None): """Set up the StreamLabsWater mode sensor.""" client = opp.data[STREAMLABSWATER_DOMAIN]["client"] location_id = opp.data[STREAMLABSWATER_DOMAIN]["location_id"] location_name = opp.data[STREAMLABSWATER_DOMAIN]["location_name"] stream...
46,877
def get_config(filename: str = CONFIG_FILENAME) -> dict: """ Get config as a dictionary Parameters ---------- filename: str The filename with all the configuration Returns ------- dict A dictionary containing all the entries from the config YAML """ global conf...
46,878
def test_launching_ssh_with_fixed_port( mock_call: Mock, c8yserver: FixtureCumulocityAPI, env: Environment ): """Execute command via ssh client using a specific port""" @responses.activate def run(): serial = "ext-device-01" port = "1234" username = "admin" c8yserver.sim...
46,879
def make_d(opath, srcfilelist, prefile=None, ffile=None): """ Make dependency files for Fortran90 projects Parameters ---------- opath : str Relative output directory. Script assumes compilation into dirname(ffile)/opath srcfilelist : list of str File(s) with list(s) of ...
46,880
def partition_trace(vtrace): """partition a trace based on its types """ partition = {} for v in vtrace: vty = get_vt_type(v) if vty not in partition: partition[vty] = [] partition[vty].append(v) return partition
46,881
def save_mesh_ply(output_fname, verts, faces, vert_colors=None): """ Save a polygonal mesh in ascii PLY format Parameters ---------- output_fname : str filename to write to verts : array_like Vertices of the mesh. Shape = Nx3 faces : array_like Faces of the mesh. ...
46,882
def test_text_justify_bottom_right_and_top_left(region, projection): """ Print text justified at bottom right and top left. """ fig = Figure() fig.text( region=region, projection=projection, x=1.2, y=0.2, text="text justified bottom right", justify="BR...
46,883
def get_bench( lx: tuple[int, int, int], data_dir: Path, tests: list[str], comp_lvls: list[int] ) -> dict[str, pd.DataFrame]: """get writing benchmark HDF5 files to pandas dataframe""" data = { "write_dr": pd.DataFrame(index=comp_lvls, columns=tests), "read_dr": pd.DataFrame(index=comp_lvls...
46,884
def test_postorder(): """Graph from ../test/test_children.cpp, i.e. generate5""" parent = np.array([0, 0, 1, 2, 3, 0, 7, 8, 3, 8], dtype=np.int32) post_expect = np.array([5, 9, 6, 7, 8, 4, 3, 2, 1], dtype=np.int32) postord = tl.post_order(parent) assert postord.shape == post_expect.shape as...
46,885
def how_to(_: StateHandler) -> None: """How-To page of the search page""" st.markdown(""" ### How To Search Please select one of the search options on the left in the navigation bar. The following search options are available: ...
46,886
def custom_token(deploy_tester_contract, custom_token_params): """Deploy CustomToken contract""" return deploy_tester_contract( CONTRACT_CUSTOM_TOKEN, [], custom_token_params )
46,887
def parse_values(reports, criteria1, criteria2, steps, crit1_name, crit2_name, first=False, cpus=1): """ Description: Parse the 'reports' and create a sorted array of size n_structs following the criteria chosen by the user. """ info_reports = [ retrieve_report_data(report) for report i...
46,888
def read_bytes(n: int, reader: io.IOBase) -> bytes: """ Reads the specified number of bytes from the reader. It raises an `EOFError` if the specified number of bytes is not available. Parameters: - `n`: The number of bytes to read; - `reader`: The reader; Returns the bytes read. """ ...
46,889
def _format_full_payload(_json_field_name, _json_payload, _files_payload): """This function formats the full payload for a ``multipart/form-data`` API request including attachments. .. versionadded:: 2.8.0 :param _json_field_name: The name of the highest-level JSON field used in the JSON payload :type...
46,890
def convert_rows (rows): """Read a two-element tuple from a string. rows should be a string containing two integers separated by a comma, blank, or colon. The numbers may be enclosed in parentheses or brackets, but this is not necessary. Note: the row numbers are one indexed and inclusive, e.g. rows = "480, 544"...
46,891
def main(): """ Entry point for :mod:`.structure_gap`. Todo: Clean up code! """ print("PLOTTING OF ENERGY GAP AND HOMO/LUMO ENERGY") args = utility.structure_gap_input() root = utility.argcheck([sys.argv[0], args.prot], '.prot') try: f = open(args.prot, 'r') except...
46,892
def prepare_data(hsi_img=None, gnd_img=None, window_size=7, n_principle=3, batch_size=50, merge=False, ratio=[6, 2, 2]): """ Process the data from file path to splited train-valid-test sets; Binded in dataset_spectral and dataset_spatial respectively. Parameters ---------- ...
46,893
def make_output_dirs(model_name, dat, let): """ Generate output directories of the run corresponding to - model_name - dat - let 0 - output_dir 1 - samples_output_dir 2 - enkf_output_dir """ output_dir = (os.environ['HOME'] + "/shematOutputDir/" + model_name + ...
46,894
def mvresnet152(**kwargs): """Constructs a MVResNet-101 model. """ model = MVResNet(Bottleneck, [3, 8, 36, 3], **kwargs) return model
46,895
def _wer_compute(errors: Tensor, total: Tensor) -> Tensor: """Compute the word error rate. Args: errors: Number of edit operations to get from the reference to the prediction, summed over all samples total: Number of words overall references Returns: Word error rate score """ ...
46,896
def get_coordinator(): """Creates a coordinator and returns it.""" workflow_queue = Queue.Queue() complete_queue = Queue.Queue() coordinator = WorkflowThread(workflow_queue, complete_queue) coordinator.register(WorkflowItem, workflow_queue) return coordinator
46,897
def tocuda(vars: Any) -> Union[str, torch.Tensor]: """Convert tensor to tensor on GPU""" if isinstance(vars, torch.Tensor): return vars.cuda() elif isinstance(vars, str): return vars else: raise NotImplementedError("invalid input type {} for tocuda".format(type(vars)))
46,898
def get_logger(): """ Returns: logging.Logger """ logger = logging.getLogger('ds-toolkit') if not len(logger.handlers): logger.setLevel(logging.DEBUG) logger.addHandler(_get_console_handler()) return logger
46,899