content
stringlengths
22
815k
id
int64
0
4.91M
def HMA(df: pandas.DataFrame, period: int = 7, column: str = "positive") -> pandas.Series: """ HMA indicator is a common abbreviation of Hull Moving Average. The average was developed by Allan Hull and is used mainly to identify the current market trend. Unlike SMA (simple moving average) the curve of H...
5,298,700
def groups(count: int) -> None: """Generates fake user groups""" for _ in range(count): manager = User.query.get(randint(1, User.query.count())) group = Group(name=fake.sentence(), manager=manager) if manager: manager.join_group(group) db.session.add(group)...
5,298,701
def array_affine_coord(mask, affine): """Compute coordinates from a boolean array and an affine transform Parameters ---------- mask: nd array, input array, interpreted as a mask affine: (n+1, n+1) matrix, affine transform that maps the mask points to some embedding space ...
5,298,702
def openssl_sha256(message: bytes) -> bytes: """ Hash function for signature and public key generation This functions wraps a hashfunction in a way that it takes a byte-sequence as an argument and returns the hash of that byte-sequence Args: message: Byte-sequence to be hashed Returns: ...
5,298,703
def merge_shards(shard_data, existing): """ Compares ``shard_data`` with ``existing`` and updates ``shard_data`` with any items of ``existing`` that take precedence over the corresponding item in ``shard_data``. :param shard_data: a dict representation of shard range that may be modified by...
5,298,704
def config() -> Config: """Give the rest of the plugin access to shared configuration.""" if _CONFIG is None: raise RuntimeError("Plugin state not initialized; call set_config() before config()") return _CONFIG
5,298,705
def call_algo(args): """call method based on task""" if args.algo == 'bw': generate_black_white(args) elif args.algo == 'pad': pad_sort(args) elif args.algo == 'dens': generate_density(args) elif args.algo == 'test_int': test_integrate(args) elif args.algo == 'cro...
5,298,706
def densify(line, step): """ Given a line segment, return another line segment with the same start & endpoints, and equally spaced sub-points based on `step` size. All the points on the new line are guaranteed to intersect with the original line, and the first and last points will be the same. ...
5,298,707
def get_cell_types(cpath, tissue, connect=False, smooth=False): """ Prepare database and clusters for upcoming ranking calculations :param cpath: string :param tissue: string :param connect: boolean :param smooth: boolean :return: dictionary """ clusters = get_annotated_clusters(path...
5,298,708
async def _eqxdo(text): """Run xdotool against the display holding EverQuest""" return await _xdotool(await _eqdisplay(), text)
5,298,709
def obtener_catalogo_base(entidad_=None): """Utilidad para devolver el catalogo de cuentas.""" from cacao_accounting.database import Cuentas, Entidad if entidad_: ctas_base = Cuentas.query.filter(Cuentas.padre == None, Cuentas.entidad == entidad_).all() # noqa: E711 else: ctas_base = (...
5,298,710
def profile_model(file_path, model_name): """ Profile the model already constructed in the Tensorflow default graph. Args: file_path: (str) path to the file to save the profiling information. model_name: (str) some model identifying name. """ profile_opts = tf.profiler.ProfileOptionBui...
5,298,711
def normalize_image(image: np.array, mean: Tuple[float, float, float] = (0.485, 0.456, 0.406), std: Tuple[float, float, float] = (0.229, 0.224, 0.225), max_pixel_value: float = 255.0) -> np.ndarray: """ Normalize image (with default parameters for Imag...
5,298,712
def lesson(ctx): """ Gitutor lessons right on your terminal ! """ click.echo(welcome_message) selection = prompt_for_lesson() if selection: lesson_name = extract_lesson_name(selection['lesson']) click.echo(lessons[lesson_name]['content'])
5,298,713
def list_fuel_databases(short): """List fuel databases available in pyrolib""" data_dir_content = pkg_resources.resource_listdir("pyrolib", "data/fuel_db") data_dir_content.sort() print("----- pyrolib available database -----") for file in data_dir_content: if file.endswith(".yml"): ...
5,298,714
def similar(a, b): """ Checks if wordlists are *very* similar in a *very naive* way. :param a: set of words :param b: set of words :return: True if the word lists are similar """ count = 0 for w in a: if w in b: count += 1 return _almost(count, len(a), len(b))
5,298,715
def example(cls, dur=5, toprint=True, double=False): """ Execute the documentation example of the object given as an argument. :Args: cls: PyoObject class or string Class reference of the desired object example. If this argument is the string of the full path of an example ...
5,298,716
def classify(featureset, feature_selection, test_size): """ :param featureset: The entire set of features :param feature_selection: A list indicating the features to be used. E.g. ['Token Overlap', 'Word Embeddings'] :param Size of the test set (e.g. 0.2) :return: """ X_train, X_test, y...
5,298,717
def get_lines_to_display( flat_matches_dict: Dict[int, List[Match]], lines: List, nb_lines: int ) -> Set[int]: """ Retrieve the line indexes to display in the content with no secrets. """ lines_to_display: Set[int] = set() for line in sorted(flat_matches_dict): for match in flat_matches_dict[li...
5,298,718
def fetchsome(curs, size=20000): """Yes, I've read the Python Cookbook! :-)""" while 1: res = curs.fetchmany(size) if not res: break for r in res: yield r
5,298,719
def inFileDict(inFileList): """ generate a nested dictionary of the input files organized by sample and barcode in the format: dict[sample][barcodeGroup][dataType]=fileName """ outDict = {} for f in inFileList: sample = f.split('_')[-3].split('/')[-1] barcodes = f.split('_')[-2] ...
5,298,720
def delete_userprofile(sender, **kwargs): """Delete user profile.""" try: userprofile = kwargs["instance"] User.objects.filter(id=userprofile.user.id).delete() except ValueError as e: print('delete_userprofile %s' % e) pass
5,298,721
def update(i: int) -> None: """Update animiate. Args: i: frame number. """ p = np.linspace(0, 1, 1000) prior = np.zeros(1000) + 1 posterior = calculate_posterior( len(sampled_data[:i]), np.sum(sampled_data[:i]), prior, p ) conf_low, conf_high, conf_idx1, conf_id...
5,298,722
def unmount_shares(cluster, unmount_share_list): """Unmounts all shares in unmount_share_list on the given cluster :param cluster: The cluster model. :param unmount_share_list: list of shares to unmount """ client = manila.client() unmount_share_ids = (set(s['id'] for s in unmount_share_list)) ...
5,298,723
def calendar(request): """ View for visualizing on the Javascript calendar tool the current user's events """ todos = ToDoList.objects.filter(teacher=request.user) ls = Lessons.objects.filter(teacher=request.user) assignments = Assignments.objects.filter(a_class__teacher=request.user) retur...
5,298,724
def smi_tokenizer(smi): """ Tokenize a SMILES molecule or reaction """ import re pattern = "(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])" regex = re.compile(pattern) tokens = [token for token in regex.findall(smi)] assert smi ==...
5,298,725
def logout_user(ctx): """Logout from current user session.""" with service() as api: api.users().logout_user(ctx.obj.access_token()) click.echo('See ya mate!')
5,298,726
def test_new_pastebin_extended(): """ GIVEN a new Pastebin model WHEN a new Pastebin is created THEN check the title, content, syntax, user id and date are all correct """ pastebin = Pastebin("test title", "test content", "text", 2, datetime.utcnow(), "password") ass...
5,298,727
def disable_user(client, username): """ disables user in keystone. Takes: * keystone client object * username Returns True is succeeded, false if issues. """ try: desc = "disabled_at:%s" % time.strftime("%d.%m.%Y") uid = client.users.list(name=username)[0].id client.u...
5,298,728
def prepare_edge_fitting(country): """ """ folder = os.path.join(DATA_INTERMEDIATE, country['iso3']) core_edges_path = os.path.join(folder, 'network_existing', 'core_edges_existing.shp') if not os.path.exists(core_edges_path): input_path = os.path.join(folder, 'network', 'core_nodes.shp')...
5,298,729
def pairs2dm(pairs): """ Convert eigenpair entries into eigenvalue and density matrix pairs. """ return [(v, ket2dm(e)) for v, e in pairs]
5,298,730
def find_closest_vertex(desired_hop, available_vertices): """ Find the closest downstream (greater than or equal) vertex in availbale vertices. If nothing exists, then return -1. Keyword arguments: desired_hop -- float representing the desired hop location available_location -- np array of avai...
5,298,731
def mat_(path="~/.opticks/GMaterialIndexLocal.json"): """ Customized names to codes arranged to place more important materials at indices less than 0xF:: simon:~ blyth$ cat ~/.opticks/GMaterialIndexLocal.json { "ADTableStainlessSteel": "19", "Acrylic": "3", ...
5,298,732
def retry_query(gcs_client: storage.Client, bq_client: bigquery.Client, lock_blob: storage.Blob, failed_job_id: str, table: bigquery.TableReference, retry_attempt_cnt): """Retry a query that failed""" if retry_attempt_cnt > 1: # if this is not the first retry, truncate ov...
5,298,733
def test_method_dispatching_invalid_method(): """Test that getattr raises an attributeerror if we give it garbage.""" client = soundcloud.Client(client_id='foo') client.foo()
5,298,734
def add_model_components(m, d, scenario_directory, subproblem, stage): """ :param m: :param d: :return: """ def total_performance_standard_emissions_rule(mod, z, p): """ Calculate total emissions from all performance standard projects in performance standard zone ...
5,298,735
def parse_episode(episode_title: str) -> Tuple[Optional[int], Optional[int]]: """ parse episode from title :param episode_title: episode title :type episode_title: str :return: episode of start, episode count """ spare = None _ = _EPISODE_RANGE_ALL_ZH_1.findall(episode_title) if _ a...
5,298,736
def main() -> None: """Add/remove connections to Guacamole DB as necessary.""" # Parse command line arguments args = docopt.docopt(__doc__, version=__version__) # Validate and convert arguments as needed schema = Schema( { "--log-level": And( str, ...
5,298,737
def exp(x: VariableLike, *, out: Optional[VariableLike] = None) -> VariableLike: """Element-wise exponential. Parameters ---------- x: Input data. out: Optional output buffer. Returns ------- : e raised to the power of the input. """ return _call_cpp_fun...
5,298,738
def test_elastalk_conf_eq_neq(): """ Arrange: Instantiate two (2) `ElastalkConf` instances. Act: Compare the instances for inequality. Assert: The objects are not equal. """ one = ElastalkConf() two = ElastalkConf() assert one != two, "The objects should not be equal."
5,298,739
def test_singletask_sklearn_rf_ECFP_regression_API(): """Test of singletask RF ECFP regression API.""" X = np.random.rand(100, 5) y = np.random.rand(100,) dataset = dc.data.NumpyDataset(X, y) splitter = dc.splits.RandomSplitter() train_dataset, test_dataset = splitter.train_test_split(dataset) transform...
5,298,740
def _config_generator( local_config, min_iter=None, max_iter=None, warmup=False, callback=None, ): """Configuration generator. Turns the iterable config into a generator of config dictionaries. Args: local_config: The configuration dictionary. All values must be iterable. ...
5,298,741
def plot_chi_squared_map( fit, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None, as_subplot=False, units='arcsec', kpc_per_arcsec=None, figsize=(7, 7), aspect='equal', cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01, ...
5,298,742
def longest_ORF(dna): """ Finds the longest ORF on both strands of the specified DNA and returns it as a string #TAA TGA TAG >>> longest_ORF("ATGCGAATGTAGCATCAAA") ['ATGCTACATTCGCAT', 3, -1] >>> longest_ORF("AAAAAAAA") [''] """ lenlist = [] orflist = find_all_ORFs_both_strands(dn...
5,298,743
def update_file(): """更新""" data = request.form file_id = data.get('file_id', None) content = data.get('content', None) file = FileName.query.get(file_id) if not file: return jsonify({'code': '404'}) file.content = content db.session.commit() return jsonify({'code': '201', 'm...
5,298,744
def distribute_permissions(request): """ 权限分配 :param request: :return: """ user_id = request.GET.get('uid') # 业务中的用户表 user_model_class = import_string(settings.RBAC_USER_MODLE_CLASS) user_object = user_model_class.objects.filter(id=user_id).first() if not user_object: u...
5,298,745
def load_exec001_data(file_name): """Loads data from a saved MCC numpy trial file.""" with open(file_name, 'rb') as file: mcc = np.load(file) inc = np.load(file) prf = np.load(file) dem = np.load(file) return mcc, inc, prf, dem
5,298,746
def get_password(hostname: str, port: int = 1433, database: str = "MOSAIQ"): """Get password from keyring storage Parameters ---------- hostname : str The MSSQL server hostname port : int, optional The MSSQL server port, by default 1433 database : str, optional The MSSQL...
5,298,747
def get_guest_mailbox(mailbox_id): """ Return all guest mailboxes of mailbox with provided id """ return (guest_mailbox for guest_mailbox in get_mailbox_guests_query(mailbox_id))
5,298,748
def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret
5,298,749
def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. :param string: str :return: boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return is_valid
5,298,750
def get_vcf_allele(hgvs, genome, transcript=None): """Get an VCF-style allele from a HGVSName, a genome, and a transcript.""" chrom, start, end = hgvs.get_vcf_coords(transcript) _, alt = hgvs.get_ref_alt( transcript.tx_position.is_forward_strand if transcript else True) ref = get_genomic_sequenc...
5,298,751
def lr_grid( adata: AnnData, num_row: int = 10, num_col: int = 10, use_lr: str = "cci_lr_grid", radius: int = 1, verbose: bool = True, ) -> AnnData: """Calculate the proportion of known ligand-receptor co-expression among the neighbouring grids or within each grid Parameters -------...
5,298,752
def test_partial_match(): """ test that template successfully rejects a field that is superset of valid field """ import osxphotos photosdb = osxphotos.PhotosDB(PHOTOS_DB_CLOUD) for uuid in COMMENT_UUID_DICT: photo = photosdb.get_photo(uuid) rendered, notmatched = photo.render_template...
5,298,753
def shortview(ticker: str, other_args: List[str]): """ Plot price vs short volume over last year Parameters ---------- ticker: str Stock to plot for other_args : List[str] Argparse arguments """ parser = argparse.ArgumentParser( prog="shortview", add_help=False,...
5,298,754
def configure(options): """ ``grub.cfg`` templating """ command = 'asdf' print(command) if not __debug__: os.system(command)
5,298,755
def sort_file(file_to_sort): """Generic method to get HTML text from URL""" with open(file_to_sort) as file_to_sort_stream: lines = file_to_sort_stream.readlines() lines.sort() with open(file_to_sort, 'w') as file_to_sort_stream_sorted: for line in lines: file_to_sort_stream_...
5,298,756
def _read_amplifier_data(gain_filename, phase_filename, gain_offset=0): """ Gather frequency-dependent amplifier data from data files. Each data file should have columns for frequency, gain or phase data, and a third empty column. The gain should be in dB and the phase should be in degrees. Pa...
5,298,757
def oht_model( gw, oro, fsns, flns, shfl, lhfl ): """parameters; must be dimensioned as specified: gwi : gaussian weights (lat) oroi : orography data array (lat,lon) requires the lat and lon are attached coordinates of oro and that oro and the following variables are 2D arrays (lat,lon). f...
5,298,758
def partition_spmd_model_decode( mdl_params: InstantiableParams, init_key: PRNGKey, inputs_shape: NestedShapeDtypeStruct, ) -> Tuple[TrainState, TrainState, DecodeFn]: """Setup the SPMD model and return sharded decode step function. For partitioning inputs, it is assumed the `mdl_params` has a field ...
5,298,759
def format_mulenc_args(args): """Format args for multi-encoder setup. It deals with following situations: (when args.num_encs=2): 1. args.elayers = None -> args.elayers = [4, 4]; 2. args.elayers = 4 -> args.elayers = [4, 4]; 3. args.elayers = [4, 4, 4] -> args.elayers = [4, 4]. """ # defaul...
5,298,760
def expand_Hc(Hc): """Calculate the matricized quadratic operator that operates on the full Kronecker product. Parameters ---------- Hc : (r,s) ndarray The matricized quadratic tensor that operates on the compact Kronecker product. Here s = r * (r+1) / 2. Returns ------- ...
5,298,761
def get_best_paragraphs(data: pd.DataFrame, query: str, doc_id: str, sim, n_matching: int) -> List[Dict[str,str]]: """Retrieves the best paragraphs for expected doc using similarity model Args: data [pd.DataFrame]: data df with processed text at paragraph_id level for sent_index query [str]: que...
5,298,762
def set_or_clear_alarm_with_key_source_target(error_type, case, host, message): """ :param error_type: TsigBadTime, ZoneTransferFailed :param case: set/clear :param host: in ip address for example: 172.21.3.14 :param message: in string :return: "set" or "clear", keypair, error_t...
5,298,763
def get_word_stats(searchType, metaField): """ Return JSON with basic statistics concerning the distribution of a particular word form by values of one metafield. This function can be used to visualise word distributions across genres etc. If searchType == 'context', take into account the whole quer...
5,298,764
def run_val_nbeatsx(hyperparameters, Y_df, X_df, data_augmentation, random_validation, trials, trials_file_name): """ Auxiliary function to run NBEATSx for hyperopt hyperparameter optimization. Return a dictionary with loss and relevant information. """ # To not modify Y_df and X_df Y_df_scaled...
5,298,765
def make_a_note(note_list, display_note_view=True): """Prompts the user to make a new note by going through prompts for title and body uses the $EDITOR env variable... @param note_list: a ragged list of notes with the format: [[['note tile'], ['item 1'], ['item 2']], [['note title'], ['body of note random t...
5,298,766
def get_order_item_by_name(expand: Optional[str] = None, order_item_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOrderItemByNameResult: """ Repre...
5,298,767
def register(media, theme, target_theme_dir, original_path, filesystem) -> None: """Add this media to the storage. """ filesystem.ensure_folder_exists(filesystem.join(target_theme_dir, 'metainfo')) filesystem.ensure_folder_exists(filesyste...
5,298,768
def did_detect(tuple_list, entry_zones, exit_zones): """ Determine if objects are coming or going """ # print('alwaysai.py: did_detect: entry zones: {}'.format(entry_zones)) global ENTER_CALLBACK global EXIT_CALLBACK for object_id, prediction in tuple_list: box = prediction.box ...
5,298,769
def matmul_AT_B_A(a, b): """ Computes A.T * B * A, dealing automatically with sparsity and data modes. :param a: Tensor or SparseTensor with rank 2 or 3. :param b: Tensor or SparseTensor with rank 2 or 3. :return: Tensor or SparseTensor with rank = max(rank(a), rank(b)). """ at_b = matmul_AT...
5,298,770
def besselsimp(expr): """ Simplify bessel-type functions. This routine tries to simplify bessel-type functions. Currently it only works on the Bessel J and I functions, however. It works by looking at all such functions in turn, and eliminating factors of "I" and "-1" (actually their polar equi...
5,298,771
def test_base_statistic_calculation_with_sync_timestamp(): """Run the base statistic calculation test.""" from pydtk.io import BaseFileReader from pydtk.statistics import BaseStatisticCalculation path = 'test/records/rosbag_model_test/data/records.bag' reader = BaseFileReader() timestamps, data...
5,298,772
def print_exception(exception, message): """Print exception information to stderr. 'exception' is the exception instance. 'message' is the message for exception.""" print >> sys.stderr, message, ': %s' % exception print >> sys.stderr, '-' * 60 traceback.print_exc(file = sys.stderr) print >> ...
5,298,773
def run(): """Default Run Method""" return problem57(1000)
5,298,774
def elementwise_spatial_consistency_loss( input: Tensor, target: Optional[Tensor], pred: Tensor ) -> Tensor: """Apply elementwise weight and reduce loss between a batch of input and a batch of target. Args: input (Tensor): Original input shape [B, C, H, W]. target (Tensor, option...
5,298,775
def view_program_slides(eid): """ Creates the HTML slides for the songs associated with a program sheet. :param eid: The eid of the program for which the HTML slides are to be made. :type eid: int :returns: Renders the HTML slides. """ program = fill_program_information( pr...
5,298,776
def vigilante_kill(var, wrapper, message): """Kill someone at night, but you die too if they aren't a wolf or win stealer!""" target = get_target(var, wrapper, re.split(" +", message)[0], not_self_message="no_suicide") if not target: return orig = target target = try_misdirection(var, wrapper....
5,298,777
def register_implementation(card_view_flavor="simple", name=None): """Decorator for marking a function as implementation for an analysis function. :param card_view_flavor: defines how results for this function are displayed, see views.CARD_VIEW_FLAVORS :param name: human-readable name, default is to create...
5,298,778
def maybe_promote_current_user(): """Whitelist the current user if the user is on the whitelist.""" whitelist = g.queue.setting('whitelist').value if whitelist: entries = {} for entry in whitelist.split(','): entry = tuple(s.strip() for s in entry.split('(')) if len(e...
5,298,779
def get_attachment_model(): """ Returns the Attachment model that is active in this project. """ try: from .models import AbstractAttachment klass = django_apps.get_model(summernote_config["attachment_model"]) if not issubclass(klass, AbstractAttachment): raise Improp...
5,298,780
def get_date_effect_strategy(): """日历效应策略""" print("""根据天风证券研究表明,基金业绩在每年三月末具有较好的持续性,因此推荐在每年三月末测试日历效应策略""") funds = get_fund_ranking("gp") funds.extend(get_fund_ranking("hh")) funds.extend(get_fund_ranking("qdii")) funds = [f for f in funds if f["fundname"][-1] not in ["B", "C", "E", "H", "O"]] ...
5,298,781
def setup_scanner(hass, config: dict, see, discovery_info=None): """Set up the iCloud Scanner.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) account = config.get(CONF_ACCOUNTNAME, slugify(username.partition('@')[0])) icloudaccount = Icloud(hass, username, password, ac...
5,298,782
def parse_cluster_pubsub_numsub(res, **options): """ Result callback, handles different return types switchable by the `aggregate` flag. """ aggregate = options.get('aggregate', True) if not aggregate: return res numsub_d = {} for _, numsub_tups in res.items(): for chann...
5,298,783
def get_font(font_name, font_size): """ Tries to load the named font at the given size but falls back on default font if this is not possible. @return: The named font at the given size if possible. """ try: return ImageFont.truetype(font_name, font_size) except: #print sys.exc_i...
5,298,784
def convert_aux_to_base(new_aux: float, close: float): """converts the aux coin to the base coin Parameters ---------- new_base, the last amount maintained by the backtest close, the closing price of the coin Returns ------- float, amount of the last aux divided by the closin...
5,298,785
def _estimate_double_gaussian_parameters(x_data, y_data, fast_estimate=False): """ Estimate of double gaussian model parameters.""" maxsignal = np.percentile(x_data, 98) minsignal = np.percentile(x_data, 2) data_left = y_data[:int((len(y_data) / 2))] data_right = y_data[int((len(y_data) / 2)):] ...
5,298,786
def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): """Calculate a Sobel filter. Parameters ---------- %(input)s %(axis)s %(output)s %(mode_multiple)s %(cval)s Examples -------- >>> from scipy import ndimage, misc >>> import matplotlib.pyplot as plt >>...
5,298,787
def clone_model_with_weights(model_to_clone): """Clone keras model with weights.""" cloned_model = keras.models.clone_model(model_to_clone) cloned_model.set_weights(model_to_clone.get_weights()) return cloned_model
5,298,788
def write_plink( G, bed: Union[str, Path], bim: Optional[Union[str, Path]] = None, fam: Optional[Union[str, Path]] = None, row: str = "variant", verbose: bool = True, ): """ Write PLINK 1 binary files into a data array. A PLINK 1 binary file set consists of three files: - BED: ...
5,298,789
def fashion_mnist_load_data(): """Loads the Fashion-MNIST dataset. Returns: Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`. """ file_path = '/file/oi-d/home/person/datasets/fashion_mnist' with gfile.Open('/gzip{}/train-labels-idx1-ubyte.gz'.format(file_path), 'rb') as l...
5,298,790
def mk7z(): """ 创建7z包 Create 7z package :return: None """ return _mk7z()
5,298,791
def safe_str(obj): """ return the byte string representation of obj """ PY2=False basestring = str try: return str(obj) except UnicodeEncodeError: # obj is unicode mylogging("safe_str error", pr=True) return obj
5,298,792
def state_db(indicador="3102009001"): """Construct a State level DataFrame from INEGI API http://www.inegi.org.mx/desarrolladores/indicadores/apiindicadores.aspx """ #merge data from every state, create databases for each index: db_state, meta = INEGI(indicador=indicador,area="01") db_state.rese...
5,298,793
def makeTernaryOperator(cond: ExprType, left: ExprType, right: ExprType) -> TernaryOperator: """ Create a TernaryOperator :param cond: Condition. :param left: Left-hand side. :param right: Right-hand side. """ expr = TernaryOperator() expr.cond.CopyFrom(makeExpr(cond)) expr.left...
5,298,794
def load_cbmc_json(json_file, root): """Load json file produced by goto-analyzer --reachable-functions --json.""" json_data = parse.parse_json_file(json_file, fail=True, goto_analyzer=True) return parse_cbmc_json(json_data, root)
5,298,795
def get_coord(tic): """ Get TIC corrdinates Returns ------- TIC number """ try: catalog_data = Catalogs.query_object(objectname="TIC"+tic, catalog="TIC") ra = catalog_data[0]["ra"] dec = catalog_data[0]["dec"] return ra, dec except: print "ERROR: No gaia ID found for this TIC"
5,298,796
def get_cohort_users(tag_id): """ Returns user id list for cohort. Parameters ~~~~~~~~~~ cohort_name : string Name of cohort. """ conn = Connector(instance=conf.__cohort_data_instance__) ut_query = query_store[get_cohort_users.__query_name__] ut_...
5,298,797
def check_readthedocs_build(all_results, git_origin_url): """ Checks the Read the Docs build status and when last build ran. """ try: token = os.environ["READTHEDOCS_API_KEY"] except KeyError: logger.error("READTHEDOCS_API_KEY is missing in environment variables") pytest.skip...
5,298,798
def year_add(date, years): """Add number of years to date. >>> import datetime >>> year_add(datetime.datetime(2016, 2, 29), 1) datetime.date(2017, 2, 28) >>> year_add(datetime.date(2016, 2, 29), 1) datetime.date(2017, 2, 28) >>> year_add(datetime.date(2015, 2, 28), 1) datetime.date(2016...
5,298,799