content
stringlengths
22
815k
id
int64
0
4.91M
def xgboost_data_preparation(validation_list: list, dataframe: pd.DataFrame, target: np.array, key: str): """ xgboost data preparing for training The function transforms the data from a Pandas dataframe format to a xgboost-compatible format. :param list validation_list: The list that contains the data the...
5,293,400
def get_config_file(): """ Get config file. :return: config file for training or testing """ parser = argparse.ArgumentParser( description="parse key pairs into a dictionary for xt training or testing", usage="python train.py --config_file YAML_FILE OR " "python train.py --a...
5,293,401
def _url(url, params): """ Returns long url with parameters http://mydomain.com?param1=...&param2=... """ if params is not None and len(params) > 0: return url + "?" + urlencode(params) else: return url
5,293,402
def main(): """Call the plotting script via command line.""" cfg = get_cfg() logger.setLevel(cfg['log_level'].upper()) control_model = cfg['control_model'] exp_model = cfg['exp_model'] vsloc = exp_model + '_vs_' + control_model file_exp = os.path.join( os.path.dirname(os.path.dirna...
5,293,403
def UniProt_NCBI_TaxID_and_TaxName_for_autocomplete_UPS_FIN(fn_in, fn_out): """ e.g. of input file UP000464341 1408252 None bacteria 270 0 270 Escherichia coli R178 UP000000558 83334 ECO57 bacteria 5060 4 9234 Escherichia coli O157:H7 priority t...
5,293,404
def get_port() -> str: """Looks for ngrok processID. If found, scans the PID in `netstat` for an `activeListener` to skim the port number. Notes: Alternate is to run `echo {root_password} | sudo -S lsof -PiTCP -sTCP:LISTEN | grep ngrok` Returns: str: Local IP address and port numbe...
5,293,405
def create_raw(locks, cache_file, disk_file): """Make a raw copy of the disk from the image cache.""" if os.path.exists(disk_file): return util.execute(locks, 'qemu-img convert -t none -O raw %s %s' % (cache_file, disk_file))
5,293,406
def read_in_chunks(buffer, chunk_size=1024 * 1024.0 * 4): """Read a buffer in chunks. :param BytesIO buffer: a BytesIO object :param float | int chunk_size: the chunk size of each read """ while True: data = buffer.read1(chunk_size) if not data: break yield data
5,293,407
def dict_to_aiohttp_tuples( d: Dict[str, Union[str, int, List[Any]]] ) -> List[Tuple[Any, Any]]: """aiohttp doesn't like dictionaries where the values are arrays. In particular, passing in a mapping parses all of the values with _query_var: https://github.com/aio-libs/yarl/blob/3e63b31b414aa9e4756...
5,293,408
def shapeToZip(inShape, outZip=None, allFiles=True): """Packs a shapefile to ZIP format. arguments -inShape - input shape file -outZip - output ZIP file (optional) default: <inShapeName>.zip in same folder as inShape (If full path not specified, o...
5,293,409
def build_refined_triplane( dem_raster: Raster, refinement_feature: Shape, min_edge_length: float, max_edge_length: float, delta: float = 0.75, slope: float = 2.0, refine_dist: float = 0.5, verbose: bool = False, outfile: str = None, ): # boundary:np.ndarray, # feature:np.nda...
5,293,410
def write_config(config) -> None: """Write configuration file to save local settings.""" global conf_path with open(conf_path + '/wol_config.ini', 'w') as f: config.write(f)
5,293,411
def move(old_bucket=None, old_key=None, old_uri=None, new_bucket=None, new_key=None, new_uri=None): """ Creates a copy of an S3 object in a new location and deletes the object from the existing location. :param old_bucket: Source bucket :param old_key: Source key :param old_uri: An s3:// path conta...
5,293,412
def insert_content_tetml_line() -> None: """Store the parse result in the database table content_tetml_line.""" if not cfg.glob.setup.is_simulate_parser: cfg.glob.parse_result_page_lines[cfg.glob.JSON_NAME_NO_LINES_IN_PAGE] = cfg.glob.parse_result_no_lines_in_page cfg.glob.parse_result_page_lin...
5,293,413
def image_caption_correct(dataset, images_path): """Stream in images from a directory and pre-populate the text box with the model's predicted caption. The original caption is stored as "orig_caption", the potentially edited caption as "caption". """ encoder, decoder, vocab, transform = load_model()...
5,293,414
def init_stc( api: ApiType, logger: logging.Logger, install_dir: Optional[str] = None, rest_server: Optional[str] = None, rest_port: Optional[int] = 80, ) -> StcApp: """Helper function to create STC object. This helper supports only new sessions. In order to connect to existing session on L...
5,293,415
def ln(target, link_name, verbose=False, use_hard_link=False): """Create a link points to :attr:`target` with the name :attr:`LINK_NAME`""" if verbose: print("ln: %(link_name)r -> %(target)r"%locals()) if use_hard_link: try: os.link(target, link_name) except OSError as e:...
5,293,416
def searchterms(): """searchterms commands Usage: searchterms submit <dataset-spec> Submit the given datasets' for summary statistics (They are added to the queue for CKAN's task worker. where <dataset-spec> is one of: ...
5,293,417
def _check_import(package_name): """Import a package, or give a useful error message if it's not there.""" try: return importlib.import_module(package_name) except ImportError: err_msg = ( f"{package_name} is not installed. " "It may be an optional powersimdata requir...
5,293,418
def previous_slice(ax): """Go to the previous slice.""" volume = ax.volume ax.index = (ax.index - 1) % volume.shape[ax.dir] # wrap around using % p = re.compile(r'\d+\s\/') title = ax.get_title() ax.set_title(p.sub('{} /'.format(ax.index), title)) if ax.is_kriging: direction = (ax...
5,293,419
def _save_unique_conformer(ret, thy_info, cnf_save_fs, locs, saddle=False, zma_locs=(0,)): """ Save the conformer in the filesystem """ # Set the path to the conformer save filesystem cnf_save_path = cnf_save_fs[-1].path(locs) # Unpack the ret object and obtain the prog ...
5,293,420
def blobs_to_dict(blobs, img_shape, region_manager): """ outputs ground truth in a list of dicts like: {'0_angle_deg': 196.81771700655054, '0_major': 63.263008639602724, '0_minor': 14.99769235802676, '0_x': 637.36877076411963, '0_y': 616.56478405315613, '1_angle_deg': 242.37572022...
5,293,421
def get_tool_shed_repo_requirements(app, tool_shed_url, repositories=None, repo_info_dicts=None): """ Contact tool_shed_url for a list of requirements for a repository or a list of repositories. Returns a list of requirements, where each requirement is a dictionary with name and version as keys. """ ...
5,293,422
def metadata(draw): """The "cu102" in "torch==1.8.1+cu102".""" # https://www.python.org/dev/peps/pep-0440/#local-version-identifiers alphabet = string.ascii_letters + string.digits + ".-_" return draw(st.text(alphabet=alphabet, min_size=1))
5,293,423
def rand_sel(twt, plc): """probably select a tweet""" #FIXME
5,293,424
def _lowess_update_nn(x, cur_nn,i): """ Update the endpoints of the nearest neighbors to the ith point. Parameters ---------- x : iterable The sorted points of x-values cur_nn : list of length 2 The two current indices between which are the k closest points to x[i]. ...
5,293,425
def test_3scale_version_in_ui(login, navigator): """ Test: - Navigate to Dashboard - Assert that 3scale version is displayed and is correct """ dashboard = navigator.open(DashboardView) assert dashboard.threescale_version.is_displayed assert dashboard.threescale_version.text == f...
5,293,426
def getListConfiguration(request, params, visibility, order): """Returns the list data for the specified params. Args: visibility: determines which list will be used order: the order the data should be sorted in """ key_order, col_names = getKeyOrderAndColNames(params, visibility) conf_extra = para...
5,293,427
def compute_outcome_stats(df): """Compute statistics regarding the relative quanties of arrests, warnings, and citations""" n_total = len(df) n_warnings = len(df[df['stop_outcome'] == 'Written Warning']) n_citations = len(df[df['stop_outcome'] == 'Citation']) n_arrests = len(df[df['stop_outcome'] ==...
5,293,428
def print_syscalls(fileName): """ Print Syscall numbers for a provided file """ bv = BinaryViewType.get_view_of_file(fileName) calling_convention = bv.platform.system_call_convention if calling_convention is None: print('Error: No syscall convention available for {:s}'.format(bv.platform)) return register = c...
5,293,429
def main(): """ the program helps reflect the original image vertically. """ original_mt = SimpleImage('images/mt-rainier.jpg') original_mt.show() reflected = reflect('images/mt-rainier.jpg') reflected.show()
5,293,430
def set_muted_role(muted_role_id: str, guild_id: str, bot: Isaiah): """Sets the muted role for a guild. Parameters: muted_role_id: str - The new id for the muted role guild_id: str - The guild that the new muted role will be set in bot: Isaiah - The bot itself """ database_check(s...
5,293,431
def augment_data_sq(x, a, y, Theta): """ Augment the dataset so that the x carries an additional feature of theta Then also attach appropriate weights to each data point. Theta: Assume uniform grid Theta """ n = np.shape(x)[0] # number of original data points num_theta = len(Theta) wid...
5,293,432
def check_day_start(gtfs, desired_weekday): """ Assuming a weekly extract, gets the utc of the start of the desired weekday :param gtfs: :param day_start: :param desired_weekday: :return: """ day_start_add = 24 * 3600 day_start, _ = gtfs.get_day_start_ut_span() tz = gtfs.get_time...
5,293,433
def get_picasaweb_date(date_time): """Converts a date to PicasaWeb format (string). adjusted for 1/1/1970 or later (PicasaWeb does not recognize dates before 1/1/1970). Args: date_time: the datetime.datetime to convert Return: the date or 1/1/1970, in PicasaWeb format, whichever is late, or ...
5,293,434
def confirm( cfg: Configuration, msg: str, force: bool, default: bool = False, abort: bool = False, ) -> Any: """Wrapped click.confirm function to print to stderr.""" assert cfg.logger is not None if force: return force if cfg.output_format == 'human': click.echo(ms...
5,293,435
def dumps_bdd_as_code( roots, bdd, lang='python', renaming=None): """Return code that computes root values from bits. @param roots: `dict` that maps each "output" bit to a BDD that depends on "input" bits @param bdd: BDD manager @param renaming: `dict` that maps ...
5,293,436
def get_standard_name(uid): """ return CF standard name """ return dq.inx.uid[uid.vid].sn
5,293,437
def start(): """ This function simply kicks off the processing of input based on arguments passed on the command line. A file given as an argument is first searched for in the CWD/PWD then the filename is sought in the path specified with -p if one is given. """ want_parsed = False glob...
5,293,438
def get_null_reference_cdf( lowerlimit: np.float32, upperlimit: np.float32, numbins: int=1000, )->ModifiedECDF: """ This function will return a CDF to be used as a null reference. :param lowerlimit: lower bound for the CDF :param upperlimit: upperbound for the CDF :p...
5,293,439
def inverted_rgb(): """ Draws Woody with inverted colors """ amount_of_pixels = len(PPMViewer.img) # Sets this to the (tuples) for i in range (0, amount_of_pixels): x = list (PPMViewer.img[i]) # Gets the tuple, then inverts the color of each for j in range(0, 3): x[j] = 25...
5,293,440
def prompt(identifier) -> tuple: """Credential entry helper. Returns: Tuple of login_id, key """ login_id = input(f"API Login ID for {identifier}: ") key = getpass.getpass(f"API Transaction Key for {identifier}: ") return (login_id, key)
5,293,441
def _load_navigation(dataset: xr.Dataset, navigation_files: str): """Load navigation data from nmea, gpx or netcdf files. Returns the dataset with the added navigation data. Data from the navigation file are interpolated on the dataset time vector. Parameters ---------- dataset : Datas...
5,293,442
def write_to_image(): """Console script for xdr2img.""" base_parser = BaseArgs( "xvi2img reads folders, connects these to the underlying XDR files, and writes these to a directory " " in another medical imaging format." ) parser = argparse.ArgumentParser(parents=[base_parser], add_help=...
5,293,443
def make_trace_data_requests( session_: requests.Session, bbox: str, conf: any ) -> list[list[dict]]: """ Makes the actual calls to Mapillary API to pull trace data for a given bbox string. :param session_: requests.Session() to persist session across API calls :param bbox: String representation of...
5,293,444
def rotation_3d_in_axis(points, angles, axis=0): """Rotate points by angles according to axis. Args: points (torch.Tensor): Points of shape (N, M, 3). angles (torch.Tensor): Vector of angles in shape (N,) axis (int, optional): The axis to be rotated. Defaults to 0. Raises: ...
5,293,445
def upgrade(): """Upgrade database schema and/or data, creating a new revision.""" op.add_column( 'objects_without_revisions', sa.Column('modified_by_id', sa.Integer, nullable=True) ) # It's possible that the table already contains some records added by # previous migration scripts. # We need ...
5,293,446
def AddDeprecatedNodePoolNodeIdentityFlags(parser): """Adds node identity flags to the given parser. This is a wrapper around AddNodeIdentityFlags for (GA) node-pools, as it provides node-pool-1 as the example and uses non-deprecated scopes behavior. Args: parser: A given parser. """ AddNodeIdentityFl...
5,293,447
def test_commands_by_name(): """Test default output of spack commands.""" out = commands() assert out.strip().split('\n') == sorted(spack.cmd.all_commands())
5,293,448
def _bgc_(args): """ Run background models """ def _run_(r): cmd = "python2.7 models/bgc.py -r {r} -ev {ev} -s {s} -e {e} -v -fr {fr}".format(r=r, ev=args.event.strftime("%Y-%m-%dT%H:%M"), s=args.start.strftime("%Y-%m-%dT%H:%M"), ...
5,293,449
def load_cabins() -> List[Cabin]: """ Load cabins from yaml file """ cabins = [] cabin_data = utils.get_cabin_data() for cabin in cabin_data: cabins.append(Cabin(cabin["class"], cabin["quality"])) return cabins
5,293,450
def get_bod_class_start_quarter_after(term): """ Return the datetime object of the beginning of the first instruction day in the term after the give year and quarter. Only the summer full term is relevant. """ nterm = get_term_after(term) if nterm is None: return None return nter...
5,293,451
def display(conn: Connection) -> None: """Display Game of Life in the terminal Parameters ---------- conn: Connection Multiprocess pipe mainly used for receiving game of life states. The first value read from the pipe is the frame delay. Subsequent reads yield the game state. W...
5,293,452
def trigger_request(): """ Callback for IFTTT trigger bunq_request """ try: data = request.get_json() print("[trigger_request] input: {}".format(json.dumps(data))) if "triggerFields" not in data or \ "account" not in data["triggerFields"]: print("[trigger_req...
5,293,453
def test_event_itemprops(client): """Verify the correct item properties are included in the rendered page. A Event should have: - Name - URL - Starting Date """ name = Name.objects.create(name='test event', name_type=Name.EVENT, begin='2500-01-...
5,293,454
def test_exist_users(db, session): # pylint: disable=unused-argument """Verify that the exist_user() work correctly.""" # add a notification for user user_id = 'notf-user' request_id = 223 request_type = 'registration' request_status = 3 message = 'this is a test notification' notificat...
5,293,455
def get_managed_environment_log_path(): """Path for charmcraft log when running in managed environment.""" return pathlib.Path("/tmp/charmcraft.log")
5,293,456
def DevoilerVerrousLieu(vals,elements): """Reveal Psyche Locks""" vals["postcode"] = '#TAP MODIFY\n"PSYCHE LOCKS REVEAL!"\n' vals["postcode"]+="#"+repr(elements)
5,293,457
def get_chromsizes(bwpath): """ TODO: replace this with negspy Also, return NaNs from any missing chromosomes in bbi.fetch """ chromsizes = bbi.chromsizes(bwpath) chromosomes = natsorted(chromsizes.keys()) chrom_series = pd.Series(chromsizes)[chromosomes] return chrom_series
5,293,458
def bridge_add_interface(bridge, newif): """Add an interface to a bridge :param bridge: the name of the bridge :param newif: the name of the interface to add """ processutils.execute('brctl', 'addif', bridge, newif)
5,293,459
def image_small_bokeh(an_image, a_title): """an_image is a skimage gray image""" rgb = cv2.cvtColor(img_as_ubyte(an_image),cv2.COLOR_GRAY2RGB) rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA) rgba_flipped = rgba[::-1, :] p = bokeh.plotting.figure(plot_width=256, plot_height=160, tools='box_zoom', title=a_title) ...
5,293,460
def create_volume_type_settings(volume_type): """ Returns a VolumeTypeSettings object :param volume_type: a SNAPS-OO VolumeType object """ control = None if volume_type.encryption: if (volume_type.encryption.control_location == ControlLocation.front_end.value): ...
5,293,461
def parse(repo, oauth_token): """ Parses and extracts cmd from `Testfile`. :param repo: Name of the cloned repository. :type repo: string :param oauth_token: Authoprization token for the user. :type oauth_token: string :return CMD: Dictonary of extracted commands. :rtype: JSON """ pa...
5,293,462
def plot_contour(model, xrange=[0, 1], yrange=[0, 1], settings=None, standard=2.01): """Create a contour plot over given bounds from model provided. :param model: An object containing a 'predict' function returning a value. :type model: Object """ if settings is None: ...
5,293,463
def change_state(display, window, state): """ :type display: Display :type window: Window :type state: int """ event_type = get_atom(display, 'WM_CHANGE_STATE') mask = X.SubstructureRedirectMask data = [state, 0, 0, 0, 0] event = protocol.event.ClientMessage( window=window, ...
5,293,464
def plot_3d_surface(axes, image, xdata=None, ydata=None, samples=None, clim=None, axlim='auto', **kwargs): """ Plot 2D image data as 3d surface :param axes: matplotlib figure or subplot axes, None uses current axe :param image: 2d array image data :param xdata: array data, 2d or 1d :param ydata:...
5,293,465
def per_ds(clz: type(Trace)): """A class annotation which will convert regular traces into dataset-sensitive traces. Args: clz: The base class to be converted. Returns: A dataset aware version of the class. Note that if the annotated class instance has a 'per_ds' member variable wh...
5,293,466
def get_gpu_capability() -> tuple[float, ...]: """Gives CUDA capability for each GPU""" with _nvml(): handles = _get_device_handles() return *map(py3nvml.nvmlDeviceGetCudaComputeCapability, handles),
5,293,467
def reconnecting_sftp(hostname: str, username: Optional[str] = None, password: Optional[str] = None, port: Optional[int] = None, private_key_file: Optional[Union[str, pathlib.Path]] = None, connect_timeout: Opt...
5,293,468
def install_local(packages, dev=False, **kwargs): """Install local packages and save to dependency. :arg list[str] packages: List of package name. :arg bool dev: If true then save to development depedency. Otherwise, save to production dependency. :arg dict kwargs: Other arguments are sent ...
5,293,469
def pp_2(node, indentation): """"Lisp Style indentation, i.e. xxx yyy zzz """ if isinstance(node, TreeText): return node.unicode_ if len(node.children) <= 2: return "(" + " ".join(pp_flat(c) for c in node.children) + ")" my_arg_0 = "(" + pp_flat...
5,293,470
def player_model_fixture(db_mock=Mock(), **kwargs): """ Get a player model fixture which can be manipulated at will All values passed will be set to the player fixture param unittest.mock db_mock: The mock object to use for the database object inside the player model """ p = Player(offline=True...
5,293,471
def to_romaji(w): """カタカナ・ひらがなをローマ字書きに変換する 一般的なローマ字ではなく、IMEでの単体文字入力となる形に変換して予測候補を出しやすくする ref: http://developers.linecorp.com/blog/?p=367 """ def ctoromaji(c): c = c.group(0) # if RE_HIRAGANA.search(c): # c = chr(ord(c)+96) if c in ROMAJI_DICT: return ...
5,293,472
def setup_faiss_index(embedding_dim: int) -> faiss.Index: """Returns a simple `IndexFlatIP` FAISS index with a vector dimension size of `embedding_dim` and an ID map for cosine similarity searching. """ index = faiss.IndexFlatIP(embedding_dim) index = faiss.IndexPreTransform(faiss.NormalizationTrans...
5,293,473
def mm_init_guess(runprops): """This function will produce the initial guess used in multimoon. Input: runprops- All run properties for the code. Will include the name of the init_guess dataframe csv file. Returns: params_df - A parameters dataframe with the same column n...
5,293,474
def register_argparse_parameters(parser): """Add command-line arguments corresponding to parameters""" for parameter in USER_PARAMS_CHANS + USER_PARAMS_FREQS: # Note: does NOT set default=. Defaults are resolved only after # processing both command-line arguments and config files. parser...
5,293,475
def add_ixn_decreases_phosphorylation(graph, ixn): """Adds an interaction that represents the chemical decreasing the phosphorylation of a protein :param pybel.BELGraph graph: A BEL graph :param pyctd.manager.models.ChemGeneIxn ixn: A chemical-gene interaction :return: The hash of the added edge :r...
5,293,476
def set_wm_window_opacity(window, opacity): """ Sets the opacity of the current window. N.B. If your window manager uses decorations, you'll typically want to pass your client's *parent* window to this function. :param window: A window identifier. :param opacity: A float between 0 and 1 inclu...
5,293,477
def test_rfx_glm(): """ Smoke test for RFX GLM. """ result = ibma.rfx_glm(pytest.con_data, pytest.mask_img, null='theoretical', n_iters=None) assert isinstance(result, nimare.base.meta.MetaResult)
5,293,478
def parse_price_url(r): """ 解析重定向url, 构造价格的url :param r: post返回的response :return: """ jsonobj = r.json() price_url = jsonobj['data']['redirectUrl'] # price_url 的格式是/pc/index.html#/inquiry/6534929115267980857 # 截取url的inquiry后面的部分6534929115267980857 # TODO:存在无报价的情况 i...
5,293,479
def defer(fn, delay): """Defer a function call after a set period of time has elapsed (in seconds) Parameters ---------- fn : a callable that takes no args delay : int | float the time delay in seconds to wait before calling fn Returns ------- DeferRef a reference to th...
5,293,480
def test_build_result_vulnerable(): """Test building the result for a vulnerable host.""" host = u"92.222.10.88" ports = [22, 80, 443] scanner = MockPortScanner() result = scanner.build_result_vulnerable(host, ports) scan_result = result["scan"] for port in ports: assert "script" ...
5,293,481
def proactive(ARG_defaultname: str="file"): """Use this function *before* generating data. Parameters ---------- ARG_defaultname : str, default is "file" The filename to save the data under, assuming the user does not choose another name. Returns ------- savebool : bool If ...
5,293,482
def _is_authorized(vdc): """Check if the user is authorized through BasicAuth or API Keys. """ auth_header = request.headers.get("Authorization") if auth_header: # Get vdc name and password from request Authorization header with Basic type name, password = parse_auth(auth_header) ...
5,293,483
def compute_distances_matrix(positions, max_distance, pixel_size=None): """Calculates Mutual Closest Neighbour distances between all channels and returns the values as """ module_logger.info('Computing distances between spots') if len(positions) < 2: raise Exception('Not enough dimensions to do...
5,293,484
def _extract_graph_summary(graph_def): """Extracts useful information from the graph and returns them.""" name_to_input_name = {} # Keyed by the dest node name. name_to_node = {} # Keyed by node name. # Keeps track of node sequences. It is important to still output the # operations in the original order. ...
5,293,485
async def test_async_setup_entry(hass): """Test a successful setup entry.""" await init_integration(hass) state = hass.states.get("weather.home") assert state is not None assert state.state != STATE_UNAVAILABLE assert state.state == "sunny"
5,293,486
def _compute_rank_down(start_nodes): """ Compute the rank of the down stream nodes. Args: start_nodes (list[NodeGraphQt.BaseNode]): (Optional) the start nodes of the graph. Returns: dict{NodeGraphQt.BaseNode: node_rank, ...} """ nodes_rank = {} for node in start...
5,293,487
def delete_old_avatar_on_update(sender, instance, **kwargs): """ Delete the old image file in the :model:`home.UserProfile` instance when a new image is uploaded. """ if hasattr(instance, "_current_avatar"): if instance._current_avatar: if instance._current_avatar.path not in ins...
5,293,488
def generate_timestamp(expire_after: float = 30) -> int: """ :param expire_after: expires in seconds. :return: timestamp in milliseconds """ return int(time.time() * 1000 + expire_after * 1000)
5,293,489
def radius_of_gyration(positions, user): """ Returns the radius of gyration, the *equivalent distance* of the mass from the center of gravity, for all visited places. [GON2008]_ References ---------- .. [GON2008] Gonzalez, M. C., Hidalgo, C. A., & Barabasi, A. L. (2008). Understanding i...
5,293,490
def evaluate_manufactured_solution_result_at_step(filename,dof,list_of_functions,step=-1,meshname='connect1',rtol=1e-5): """ ======================================================= | evaluate_manufactured_solution_result_at_step | ======================================================= Evalua...
5,293,491
def test_loan_history_without_asset(): """Tests the API endpoint to query loan history without asset""" params = {"asset": "", "recvWindow": 1000} client.loan_history.when.called_with(**params).should.throw(ParameterRequiredError)
5,293,492
def make_strided_slice_1d_exhaustive_tests(options): """Make a set of exhaustive tests for 1D strided_slice.""" test_parameters = [ # 1-D Exhaustive { "dtype": [tf.float32], "index_type": [tf.int32], "input_shape": [[3]], "begin": [[-2], [-1], [0], [1], [2]], ...
5,293,493
def get_available_devices_num(): """get available devives num.""" env_dic = os.environ try: return int(env_dic.get('DEVICE_TOTAL_NUM').lower()) if env_dic.get('DEVICE_TOTAL_NUM') else 1 except NameError as e: logging.error(e) return 1
5,293,494
def b64e(s): """b64e(s) -> str Base64 encodes a string Example: >>> b64e("test") 'dGVzdA==' """ return base64.b64encode(s)
5,293,495
def login(request): """登录视图""" if request.session.get('is_login',None): logger.info(request) return redirect("/index/") if request.method == "POST": login_form = UserForm(request.POST) message = "请检查填写的内容!" if login_form.is_valid(): username = login_form.c...
5,293,496
def setup_platform(hass, config, add_devices, discovery_info=None): """ Set up the Visonic Alarm platform. """ hub.update() visonic_alarm = VisonicAlarm(hass) add_devices([visonic_alarm]) # Create an event listener to listen for changed arm state. # We will only fetch the events from the API on...
5,293,497
def purge_queues(force=False, queues=None): """Purge the given queues.""" current_queues.purge(force=force, queues=queues) click.secho( 'Queues {} have been purged.'.format( queues or current_queues.queues.keys()), fg='green' )
5,293,498
def pipeline_send_op(node, destination, comm, stream=None, ctx=None): """Make a new instance of PipelineSendOp and call the instance. Parameters: ---- node : Node The Node to be send. destination : scalar value The gpu index for destination. Returns: ---- A new Node ins...
5,293,499