content
stringlengths
22
815k
id
int64
0
4.91M
def ax2cu(ax): """Axis angle pair to cubochoric vector.""" return Rotation.ho2cu(Rotation.ax2ho(ax))
21,000
def test_transfer( stubbed_sender, stubbed_receiver_token_account_pk, stubbed_sender_token_account_pk, test_token ): # pylint: disable=redefined-outer-name """Test token transfer.""" expected_amount = 500 assert_valid_response( test_token.transfer( source=stubbed_sender_token_accoun...
21,001
def print_menu(): """Display a table with list of tasks and their associated commands. """ speak("I can do the following") table = Table(title="\nI can do the following :- ", show_lines = True) table.add_column("Sr. No.", style="cyan", no_wrap=True) table.add_column("Task", style="yellow") ...
21,002
def test_cancel_user_bad_token_no_email(app, session): """Ensure a token without an email subject is rejected.""" u = auth_service.register_user(session, 'test@jadetree.io', 'hunter2JT', 'Test User') token = auth_service.encodeJwt( app, subject=auth_service.JWT_SUBJECT_CANCEL_EMAIL, ) ...
21,003
def download_and_store( feed_url: Text, ignore_file: Optional[Text], storage_path: Text, proxy_string: Optional[Text], link: urllib.parse.ParseResult) -> Dict: """Download and store a link. Storage defined in args""" # check if the actual url is in the ignore file. If so...
21,004
def define_genom_loc(current_loc, pstart, p_center, pend, hit_start, hit_end, hit_strand, ovl_range): """ [Local] Returns location label to be given to the annotated peak, if upstream/downstream or overlapping one edge of feature.""" all_pos = ["start", "end"] closest_pos, dmin = distance_to_peak_center(...
21,005
def define_macro(preprocessor: Preprocessor, name: str, args: List[str], text: str) -> None: """Defines a macro. Inputs: - preprocessor - the object to which the macro is added - name: str - the name of the new macro - args: List[str] - List or arguments name - text: str - the text the command prints. Occurences ...
21,006
def actp(Gij, X0, jacobian=False): """ action on point cloud """ X1 = Gij[:,:,None,None] * X0 if jacobian: X, Y, Z, d = X1.unbind(dim=-1) o = torch.zeros_like(d) B, N, H, W = d.shape if isinstance(Gij, SE3): Ja = torch.stack([ d, o, o, o, ...
21,007
def teardown_module(module): """ Delete necessary files. """ os.chdir("..") rmtree("temp_utilities", ignore_errors=True)
21,008
def isPalindrome(s): """Assumes s is a str Returns True if s is a palindrome; False otherwise. Punctuation marks, blanks, and capitalization are ignored.""" def toChars(s): s = s.lower() letters = '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': letters =...
21,009
def find_make_workdir(subdir, despike, spm, logger=None): """ generates realign directory to query based on flags and if it exists and create new workdir """ rlgn_dir = utils.defaults['realign_ants'] if spm: rlgn_dir = utils.defaults['realign_spm'] if despike: rlgn_dir = utils.de...
21,010
def _SendChangeSVN(options): """Send a change to the try server by committing a diff file on a subversion server.""" if not options.svn_repo: raise NoTryServerAccess('Please use the --svn_repo option to specify the' ' try server svn repository to connect to.') values = _ParseSen...
21,011
def compute_irs(ground_truth_data, representation_function, random_state, diff_quantile=0.99, num_train=gin.REQUIRED, batch_size=gin.REQUIRED): """Computes the Interventional Robustness Score. Args: ground_truth_data: GroundTruthDa...
21,012
def Grab_Pareto_Min_Max(ref_set_array, objective_values, num_objs, num_dec_vars, objectives_names=[], create_txt_file='No'): """ Purposes: Identifies the operating policies producing the best and worst performance in each objective. Gets called automatically by processing_reference...
21,013
def edist(x, y): """ Compute the Euclidean distance between two samples x, y \in R^d.""" try: dist = np.sqrt(np.sum((x-y)**2)) except ValueError: print 'Dimensionality of samples must match!' else: return dist
21,014
def figure(fnum=None, pnum=(1, 1, 1), title=None, figtitle=None, doclf=False, docla=False, projection=None, **kwargs): """ http://matplotlib.org/users/gridspec.html Args: fnum (int): fignum = figure number pnum (int, str, or tuple(int, int, int)): plotnum = plot tuple tit...
21,015
def start_wifi(): """Start a new WIFI connection if none is found.""" if not _wifi.is_connected(): display.show(["Connecting wifi."]) if not _wifi.connect(): error("NO INTERNET!")
21,016
def allsec_preorder(h): """ Alternative to using h.allsec(). This returns all sections in order from the root. Traverses the topology each neuron in "pre-order" """ #Iterate over all sections, find roots roots = root_sections(h) # Build list of all sections sec_list = [] for r in ro...
21,017
def get_func_bytes(*args): """get_func_bytes(func_t pfn) -> int""" return _idaapi.get_func_bytes(*args)
21,018
def test_givens(seed, dtype): """ Tests that when the Givens factors produced by `solve._compute_givens_rotation` are applied to a two-vector `v = (a, b)` via `solve._apply_ith_rotation`, the result is `h = (||v||, 0)` up to a sign. """ np.random.seed(seed) v = np.random.randn(2).astype(dtype) v = jnp.a...
21,019
def balanced_accuracy(y_true, y_score): """Compute accuracy using one-hot representaitons.""" if isinstance(y_true, list) and isinstance(y_score, list): # Online scenario if y_true[0].ndim == 2 and y_score[0].ndim == 2: # Flatten to single (very long prediction) y_true = ...
21,020
def main(): """ The main function of the program. First, the input parameters are collected and validated. Then the repayments information are computed and returned. """ locale.setlocale(locale.LC_ALL, 'en_gb') # Changes the locale settings to deal with pounds market_file, loan_amount = _get_inp...
21,021
async def get_weather(weather): """ For .weather command, gets the current weather of a city. """ if not OWM_API: await weather.reply( f"`{JAVES_NNAME}:` **Get an API key from** https://openweathermap.org/ `first.`") return APPID = OWM_API if not weather.pattern_match.grou...
21,022
def read_table(source, columns=None, nthreads=1, metadata=None, use_pandas_metadata=False): """ Read a Table from Parquet format Parameters ---------- source: str or pyarrow.io.NativeFile Location of Parquet dataset. If a string passed, can be a single file name or di...
21,023
def preprocess_img(image, segnet_stream='fstream'): """Preprocess the image to adapt it to network requirements Args: Image we want to input the network in (W,H,3) or (W,H,4) numpy array Returns: Image ready to input to the network of (1,W,H,3) or (1,W,H,4) shape Note: This is re...
21,024
def redefine_colors(color_map, file=sys.stdout): """Redefine the base console colors with a new mapping.""" _redefine_colors(color_map, file)
21,025
def benchmark_step(config): """Utility function to benchmark speed of 'stepping', i.e. recurrent view. Unused for main train logic""" pl.seed_everything(config.train.seed, workers=True) model = SequenceLightningModule(config) model.setup() model.to("cuda") print("Num Parameters: ", sum(p.numel(...
21,026
def confirm_buildstream_installed(): """Confirms that BuildStream is installed, so it can be run using subprocess.run""" if not shutil.which("bst"): # shutil.which will return None, if licensecheck isn't installed echo("Error, BuildStream does not seem to be installed.") echo("(bst_licen...
21,027
def _load_announce_signal_handlers() -> None: """Import modules containing handlers so they connect to the corresponding signals. """ from .announce import connections
21,028
def _export_cert_from_task_keystore( task, keystore_path, alias, password=KEYSTORE_PASS): """ Retrieves certificate from the keystore with given alias by executing a keytool in context of running container and loads the certificate to memory. Args: task (str): Task id of container t...
21,029
def eta_expand( path: qlast.Path, stype: s_types.Type, *, ctx: context.ContextLevel, ) -> qlast.Expr: """η-expansion of an AST path""" if not ALWAYS_EXPAND and not stype.contains_object(ctx.env.schema): # This isn't strictly right from a "fully η expanding" perspective, # but for...
21,030
def NBAccuracy(features_train, labels_train, features_test, labels_test): """ compute the accuracy of your Naive Bayes classifier """ from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score # create classifier clf = GaussianNB() # fit the classifier on the trainin...
21,031
async def test_write_diff_file(snapshot, tmp_path): """ Test that a diff file is written correctly. """ (tmp_path / "history").mkdir() with open(TEST_DIFF_PATH, "r") as f: diff = json.load(f) await write_diff_file(tmp_path, "foo", "1", diff) path = tmp_path / "history" / "foo_1.j...
21,032
def _remove(ctx, config, remote, debs): """ Removes Debian packages from remote, rudely TODO: be less rude (e.g. using --force-yes) :param ctx: the argparse.Namespace object :param config: the config dict :param remote: the teuthology.orchestra.remote.Remote object :param debs: list of pac...
21,033
def loadPlugin(filename : str): """Loads the given Python file as a FSLeyes plugin. """ # strip underscores to handle e.g. __init__.py, # as pkg_resources might otherwise have trouble name = op.splitext(op.basename(filename))[0].strip('_') modname = 'fsleyes_plugin_{}'.format(name) mod =...
21,034
def main(): """Command line entry point""" opt_short = 'c:dvVh' opt_long = ['config=', 'debug' , 'verbose', 'version', 'help'] try: opts, args = getopt.getopt(sys.argv[1:], opt_short, opt_long) except getopt.GetoptError, e: fatal(e) options = { 'config_file': None, ...
21,035
def verify(body): # noqa: E501 """verify Verifies user with given user id. # noqa: E501 :param body: User id that is required for verification. :type body: dict | bytes :rtype: UserVerificationResponse """ if connexion.request.is_json: body = VerifyUser.from_dict(connexion.reques...
21,036
def load_interface(interface_name, data): """ Load an interface :param interface_name: a string representing the name of the interface :param data: a dictionary of arguments to be used for initializing the interface :return: an Interface object of the appropriate type """ if interface_name n...
21,037
def labotter_in(client: BaseClient): """らぼいん!""" msg = "らぼいんに失敗したっぽ!(既に入っているかもしれないっぽ)" user_id = client.get_send_user() flag, start_time = labo_in(user_id) if flag: msg = "らぼいんしたっぽ! \nいん時刻: {}".format(start_time) client.post(msg)
21,038
def as_observation_matrix(cnarr, variants=None): """Extract HMM fitting values from `cnarr`. For each chromosome arm, extract log2 ratios as a numpy array. Future: If VCF of variants is given, or 'baf' column has already been added to `cnarr` from the same, then the BAF values are a second row/column ...
21,039
def test_generate_stl(): """Check generator builds all STL files""" root = "tests/test_data/model" gen = Generator(root) tw = TreeWalker(root, "scad", None) tw.clean("stl") gen.process_all("stl") assert os.path.isfile(os.path.join(root, "wing/wing.stl"))
21,040
def get_full_word(*args): """get_full_word(ea_t ea) -> ulonglong""" return _idaapi.get_full_word(*args)
21,041
def full_setup(battery_chemistry): """This function gets the baseline vehicle and creates modifications for different configurations, as well as the mission and analyses to go with those configurations.""" # Collect baseline vehicle data and changes when using different configuration settings vehicle ...
21,042
def sph_yn_exact(n, z): """Return the value of y_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E4 . """ zm = mpmathify(z) s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1)) s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(...
21,043
def f_bis(n1 : float, n2 : float, n3 : float) -> str: """ ... cf ci-dessus ... """ if n1 < n2: if n2 < n3: return 'cas 1' elif n1 < n3: return 'cas 2' else: return 'cas 5' elif n1 < n3: return 'cas 3' elif n2 < n3: return 'c...
21,044
def calc_B_effective(*B_phasors): """It calculates the effective value of the magnetic induction field B (microTesla) in a given point, considering the magnetic induction of all the cables provided. Firstly, the function computes the resulting real and imaginary parts of the x and y magnetic induc...
21,045
def elision_count(l): """Returns the number of elisions in a given line Args: l (a bs4 <line>): The line Returns: (int): The number of elisions """ return sum([(1 if _has_elision(w) else 0) for w in l("word")])
21,046
def test_enhanced_list_method(service2): """ service2 implements an enhanced list_example_models method using a custom "list" method name. """ container = service2.container record_1 = {'id': 1, 'name': 'Bob Dobalina'} # write through the service with entrypoint_hook( container...
21,047
def get_final_df(model, data): """ This function takes the `model` and `data` dict to construct a final dataframe that includes the features along with true and predicted prices of the testing dataset """ # if predicted future price is higher than the current, # then calculate the true futur...
21,048
def read_fragment_groups(input_string,natoms,num_channels): """ read in the fragment groups for each channel """ inp_line = _get_integer_line(input_string,'FragmentGroups',natoms) assert inp_line is not None out=' '.join(inp_line) return out
21,049
def _assertVolume(volume: float) -> None: """ Check if the volume in between 0.0 to 1.0 """ if volume < 0.0 or 1.0 < volume: raise InvalidVolumeError(volume)
21,050
def save(program, model_path, protocol=4, **configs): """ :api_attr: Static Graph This function save parameters, optimizer information and network description to model_path. The parameters contains all the trainable Tensor, will save to a file with suffix ".pdparams". The optimizer information con...
21,051
def did_discover_device(odrive, logger, app_shutdown_token): """ Handles the discovery of new devices by displaying a message and making the device available to the interactive console """ serial_number = odrive.serial_number if hasattr(odrive, 'serial_number') else "[unknown serial number]" ...
21,052
def retrain_different_dataset(index): """ This function is to evaluate all different datasets in the model with one function call """ from utils.helper_functions import load_flags data_set_list = ["Peurifoy"] # data_set_list = ["Chen"] # data_set_list = ["Yang"] #data_set_list = ...
21,053
def pad_tile_on_edge(tile, tile_row, tile_col, tile_size, ROI): """ add the padding to the tile on the edges. If the tile's center is outside of ROI, move it back to the edge Args: tile: tile value tile_row: row number of the tile relative to its ROI tile_col: col number of the tile relative to its...
21,054
def move_away_broken_database(dbfile: str) -> None: """Move away a broken sqlite3 database.""" isotime = dt_util.utcnow().isoformat() corrupt_postfix = f".corrupt.{isotime}" _LOGGER.error( "The system will rename the corrupt database file %s to %s in order to allow startup to proceed", ...
21,055
def calc_kfold_score(model, df, y, n_splits=3, shuffle=True): """ Calculate crossvalidation score for the given model and data. Uses sklearn's KFold with shuffle=True. :param model: an instance of sklearn-model :param df: the dataframe with training data :param y: dependent value :param n_...
21,056
def obter_forca (unidade): """Esta funcao devolve a forca de ataque da unidade dada como argumento""" return unidade[2]
21,057
def get_default_configuration(cookiecutter_json: CookiecutterJson) -> Dict[str, str]: """ Get the default values for the cookiecutter configuration. """ default_options = dict() for key, value in cookiecutter_json.items(): if isinstance(value, str) and "{{" not in value: # ignore templated ...
21,058
def test_normalize_attribute_name(name): """Test the attribute name normalization.""" normalized = normalize_attribute_name(name) assert ( normalized.isidentifier() ), f'Attribute "{name}" was not normalized to a valid identifier! (Normalized: "{normalized}")' assert not iskeyword( n...
21,059
def random_nodes_generator(num_nodes, seed=20): """ :param int num_nodes: An Integer denoting the number of nodes :param int seed: (Optional) Integer specifying the seed for controlled randomization. :return: A dictionary containing the coordinates. :rtype: dict """ np.random.seed(seed) ...
21,060
def OpenDocumentTextMaster(): """ Creates a text master document """ doc = OpenDocument('application/vnd.oasis.opendocument.text-master') doc.text = Text() doc.body.addElement(doc.text) return doc
21,061
def draw_cell(cell, color=COLOR.GREEN.value): """ 绘制一个像素点 :param cell: 像素点位置 :param color: 像素点颜色 """ (x, y) = cell x = x * CELL_SIZE y = y * CELL_SIZE outer_rect = pygame.Rect(x, y, CELL_SIZE, CELL_SIZE) padding_rect = pygame.Rect(x + 2, y + 2, CELL_SIZE - 4, CELL_SIZE - 4...
21,062
def get_visible_desktops(): """ Returns a list of visible desktops. The first desktop is on Xinerama screen 0, the second is on Xinerama screen 1, etc. :return: A list of visible desktops. :rtype: util.PropertyCookie (CARDINAL[]/32) """ return util.PropertyCookie(util.ge...
21,063
def get_env_string(env_key, fallback): """ reads boolean literal from environment. (does not use literal compilation as far as env returns always a string value Please note that 0, [], {}, '' treats as False :param str env_key: key to read :param str fallback: fallback value :rtype: str ...
21,064
def spherical_noise( gridData=None, order_max=8, kind="complex", spherical_harmonic_bases=None ): """Returns order-limited random weights on a spherical surface. Parameters ---------- gridData : io.SphericalGrid SphericalGrid containing azimuth and colatitude order_max : int, optional ...
21,065
def rollback_command(): """Command to perform a rollback fo the repo.""" return Command().command(_rollback_command).require_clean().require_migration().with_database()
21,066
def circumcenter(vertices): """ Compute the circumcenter of a triangle (the center of the circle which passes through all the vertices of the triangle). :param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the space)). :returns: The tr...
21,067
def run(): """Run example for Doc-2-Vec method and IMDB dataset.""" log.info('START') data = {'test-neg.txt': 'TEST_NEG', 'test-pos.txt': 'TEST_POS', 'train-neg.txt': 'TRAIN_NEG', 'train-pos.txt': 'TRAIN_POS', 'train-unsup.txt': 'TRAIN_UNS'} data = {join(IMDB_MERGED_PATH, k): v f...
21,068
def testing_submodules_repo(testing_workdir, request): """Initialize a new git directory with two submodules.""" subprocess.check_call(['git', 'init']) # adding a commit for a readme since git diff behaves weird if # submodules are the first ever commit subprocess.check_call(['touch', 'readme.txt']...
21,069
def get_ROC_curve_naive(values, classes): """ Naive implementation of a ROC curve generator that iterates over a number of thresholds. """ # get number of positives and negatives: n_values = len(values); totalP = len(np.where(classes > 0)[0]); totalN = n_values - totalP; min_v...
21,070
def worker(path, opt): """Worker for each process. Args: path (str): Image path. opt (dict): Configuration dict. It contains: crop_size (int): Crop size. step (int): Step for overlapped sliding window. thresh_size (int): Threshold size. Patches whose size is ...
21,071
def RobotNet(images,dropout): """ Build the model for Robot where it will be used as RobotNet. Args: images: 4-D tensor with shape [batch_size, height, width, channals]. dropout: A Python float. The probability that each element is kept. Returns: Output tensor with the computed ...
21,072
def cvReleaseMemStorage(*args): """cvReleaseMemStorage(PyObject obj)""" return _cv.cvReleaseMemStorage(*args)
21,073
def run_config_filename(conf_filename): """ Runs xNormal using the path to a configuration file. """ retcode = os.system("\"%s\" %s" % (path, conf_filename)) return retcode
21,074
def test_fetchjson_with_destination_int_old(mock_s3): """Test outKey still works for backwards compatibility.""" mock_body = Mock() bunch_of_bytes = bytes(json.dumps([1, 2, 3]), 'utf-8') mock_body.read.return_value = bunch_of_bytes mock_s3.side_effect = [{'Body': mock_body}] context = Context(...
21,075
def GetCommitsInOrder( repo: git.Repo, head_ref: str = "HEAD", tail_ref: typing.Optional[str] = None) -> typing.List[git.Commit]: """Get a list of all commits, in chronological order from old to new. Args: repo: The repo to list the commits of. head_ref: The starting point for iteration, e.g. t...
21,076
def sell(): """Sell shares of stock""" # return apology("TODO") if request.method == 'GET': return render_template('sell_stock.html') else: symbol = request.form['symbol'] shares = int(request.form['shares']) return sell_stock(Symbol=symbol, Shares=shares, id=session['use...
21,077
def return_sw_checked(softwareversion, osversion): """ Check software existence, return boolean. :param softwareversion: Software release version. :type softwareversion: str :param osversion: OS version. :type osversion: str """ if softwareversion is None: serv = bbconstants.SE...
21,078
def apply( f: tp.Callable[..., None], obj: A, *rest: A, inplace: bool = False, _top_inplace: tp.Optional[bool] = None, _top_level: bool = True, ) -> A: """ Applies a function to all `to.Tree`s in a Pytree. Works very similar to `jax.tree_map`, but its values are `to.Tree`s instead of...
21,079
def test_equality_inverse(): """Return not equal if the addresses are different""" loc_1 = 'http://example.com/foo_bar.html' loc_2 = 'http://example.com/bar_foo.html' assert URL(loc_1) != URL(loc_2)
21,080
def cv_data_gen(ad_sc, ad_sp, mode='loo'): """ This function generates cross validation datasets Args: ad_sc: AnnData, single cell data ad_sp: AnnData, gene spatial data mode: string, support 'loo' and 'kfold' """ genes_array = np.array(list(set(ad_sc.var.index.values))) i...
21,081
def test_dedup_access_contiguous(): """ A test where there is a non-square shape that, based on whether contiguity is prioritized, might give different results. Subset is: j 6543 21012 3456 _____ ____| |____ 2 | | | | 1 | | | | 0 i |__...
21,082
def run(): """ 主程序入口 :return: None """ GFWeather().run()
21,083
def imageSearch(query, top=10): """Returns the decoded json response content :param query: query for search :param top: number of search result """ # set search url query = '%27' + parse.quote_plus(query) + '%27' # web result only base url base_url = 'https://api.datamarket.azure.com/Bi...
21,084
def pack_inputs(inputs): """Pack a list of `inputs` tensors to a tuple. Args: inputs: a list of tensors. Returns: a tuple of tensors. if any input is None, replace it with a special constant tensor. """ inputs = tf.nest.flatten(inputs) outputs = [] for x in inputs: if x is None...
21,085
def entries_as_dict(month_index): """Convert index xml list to list of dictionaries.""" # Search path findentrylist = etree.ETXPath("//section[@id='month-index']/ul/li") # Extract data entries_xml = findentrylist(month_index) entries = [to_entry_dict(entry_index_xml) for entry_ind...
21,086
def resnet50(): """Constructs a ResNet-50 model. """ return Bottleneck, [3, 4, 6, 3]
21,087
def build_service_job_mapping(client, configured_jobs): """ :param client: A Chronos client used for getting the list of running jobs :param configured_jobs: A list of jobs configured in Paasta, i.e. jobs we expect to be able to find :returns: A dict of {(service, instance): last_chronos_job} ...
21,088
def _validate_labels(labels, lon=True): """ Convert labels argument to length-4 boolean array. """ if labels is None: return [None] * 4 which = 'lon' if lon else 'lat' if isinstance(labels, str): labels = (labels,) array = np.atleast_1d(labels).tolist() if all(isinstance(...
21,089
def copy_template(template, new_file, name): """ Args: template: The absolute path to the template. new_file: The absolute path to the new file. name: The name of the new project Returns: None """ if os.path.isfile(new_file): print("Warning: The file {}, wa...
21,090
def files_all(args): """Executes all the files commands from individual databases""" for name in [k.name() for k in args.modules]: parsed = args.parser.parse_args([name, 'files']) parsed.func(parsed)
21,091
def celsius_to_fahrenheit(temperature_C): """ converts C -> F """ return temperature_C * 9.0 / 5.0 + 32.0
21,092
def _parse_date_time(date): """Parse time string. This matches 17:29:43. Args: date (str): the date string to be parsed. Returns: A tuple of the format (date_time, nsec), where date_time is a datetime.time object and nsec is 0. Raises: ValueError: if the date form...
21,093
def _output(line, lines, stream=None): """Internal function: Add line to output lines and optionally print to stream.""" lines.append(line) if stream: print(line, file=stream)
21,094
def parsed_user(request, institute_obj): """Return user info""" user_info = { 'email': 'john@doe.com', 'name': 'John Doe', 'location': 'here', 'institutes': [institute_obj['internal_id']], 'roles': ['admin'] } return user_info
21,095
def lastFromUT1(ut1, longitude): """Convert from universal time (MJD) to local apparent sidereal time (deg). Inputs: - ut1 UT1 MJD - longitude longitude east (deg) Returns: - last local apparent sideral time (deg) History: 2002-08-05 ROwen First version, loosely base...
21,096
def get_dataset(opts): """ Dataset And Augmentation """ train_transform = transform.Compose([ transform.RandomResizedCrop(opts.crop_size, (0.5, 2.0)), transform.RandomHorizontalFlip(), transform.ToTensor(), transform.Normalize(mean=[0.485, 0.456, 0.406], ...
21,097
def strip_translations_header(translations: str) -> str: """ Strip header from translations generated by ``xgettext``. Header consists of multiple lines separated from the body by an empty line. """ return "\n".join(itertools.dropwhile(len, translations.splitlines()))
21,098
def test_safety_interlock_during_init(switch_driver, caplog): """ to check if a warning would show when initialize the instrument with a module in safety interlock state. This test has to be placed first if the scope is set to be "module". """ msg = [ x.message for x in caplog.get_record...
21,099