content
stringlengths
22
815k
id
int64
0
4.91M
def base_checkout_total( subtotal: TaxedMoney, shipping_price: TaxedMoney, discount: Money, currency: str, ) -> TaxedMoney: """Return the total cost of the checkout.""" zero = zero_taxed_money(currency) total = subtotal + shipping_price - discount # Discount is subtracted from both gross...
5,353,600
def if_statement(lhs='x', op='is', rhs=0, _then=None, _else=None): """Celery Script if statement. Kind: _if Arguments: lhs (left-hand side) op (operator) rhs (right-hand side) _then (id of sequence to execute on `then`) _else (id of sequence to execute on `el...
5,353,601
def add_next_open(df, col='next_open'): """ 找出下根K线的开盘价 """ df[col] = df[CANDLE_OPEN_COLUMN].shift(-1) df[col].fillna(value=df[CANDLE_CLOSE_COLUMN], inplace=True) return df
5,353,602
def validate_args(args): """Validate command line arguments.""" if args.target == 'druid_deployment': assert args.master_desired_count is not None, \ "Druid master desired count must be specified" assert args.zookeeper_desired_count is not None, \ "Druid zookeeper desired...
5,353,603
def connectToSerial(dev): """connectToSerial("/path/to/device") connects to specific serial port""" console.connectToSerial(dev)
5,353,604
def seasons_used(parameters): """ Get a list of the seasons used for this set of parameters. """ seasons_used = set([s for p in parameters for s in p.seasons]) # Make sure this list is ordered by SEASONS. return [season for season in SEASONS if season in seasons_used]
5,353,605
def get_polyphyletic(cons): """get polyphyletic groups and a representative tip""" tips, taxonstrings = unzip(cons.items()) tree, lookup = make_consensus_tree(taxonstrings, False, tips=tips) cache_tipnames(tree) names = {} for n in tree.non_tips(): if n.name is None: continu...
5,353,606
def _Install(launcher_vm, booter_template_vm): """Installs benchmark scripts and packages on the launcher vm.""" launcher_vm.InstallCli() # Render boot script on launcher server VM(s) context = _BuildContext(launcher_vm, booter_template_vm) launcher_vm.RenderTemplate(data.ResourcePath(_BOOT_TEMPLATE), _BOOT_P...
5,353,607
def find_closest_integer_in_ref_arr(query_int: int, ref_arr: NDArrayInt) -> Tuple[int, int]: """Find the closest integer to any integer inside a reference array, and the corresponding difference. In our use case, the query integer represents a nanosecond-discretized timestamp, and the reference array repre...
5,353,608
def saver_for_file(filename): """ Returns a Saver that can load the specified file, based on the file extension. None if failed to determine. :param filename: the filename to get the saver for :type filename: str :return: the associated saver instance or None if none found :rtype: Saver """...
5,353,609
def test_create_model_custom_folds(load_pos_and_neg_data): """test custom fold in create_model""" exp = TimeSeriesExperiment() setup_fold = 3 exp.setup( data=load_pos_and_neg_data, fold=setup_fold, fh=12, fold_strategy="sliding", verbose=False, ) ########...
5,353,610
def prepare_axes(ax, naxes): """ set up the axes """ ax.set_frame_on(False) ax.set_ylim(-0.15, 1.1) xmax = 1.02*(naxes-1) ax.set_xlim((-0.30, xmax)) ax.set_yticks([]) ax.set_yticklabels([]) ax.set_xticklabels([]) ax.set_xticks([])
5,353,611
def make(context, name): """Create an object in a registered table class. This function will be stored in that object, so that the new table object is able to create new table objects in its class. !!! hint This is needed when the user wants to insert new records in the table. Parameters ...
5,353,612
def cofilter(function, iterator): """ Return items in iterator for which `function(item)` returns True. """ results = [] def checkFilter(notfiltered, item): if notfiltered == True: results.append(item) def dofilter(item): d = maybeDeferred(function, item) d....
5,353,613
def download_dataset(dataset_name='mnist'): """ Load MNIST dataset using keras convenience function Args: dataset_name (str): which of the keras datasets to download dtype (np.dtype): Type of numpy array Returns tuple[np.array[float]]: (train images, train labels), (test images...
5,353,614
def __listen_for_requests_events(node_id, success, measurement: str = 'locust_requests') -> Callable: """ Persist request information to influxdb. :param node_id: The id of the node reporting the event. :param measurement: The measurement where to save this point. :param success: Flag the info to a...
5,353,615
def test_find_next_htr(routing_grid: PyRoutingGrid, lay: int, coord: int, w_ntr: int, mode: Union[RoundMode, int], even: bool, expect: int) -> None: """Check that find_next_htr() works properly.""" ans = routing_grid.find_next_htr(lay, coord, w_ntr, mode, even) assert ans == expect
5,353,616
def create_trigger_function_sql( *, audit_logged_model: Type[Model], context_model: Type[Model], log_entry_model: Type[Model], ) -> str: """ Generate the SQL to create the function to log the SQL. """ trigger_function_name = f"{ audit_logged_model._meta.db_table }_log_change" conte...
5,353,617
def p_relop_neq(p: yacc.YaccProduction): """REL_OP : NEQ_COMPARISON""" p[0] = {'code': '!='}
5,353,618
def add_nop_conv_after(g, value_names): """Add do-nothing depthwise Conv nodes after the given value info. It will\\ take the given names as the inputs of the new node and replace the inputs\\ of the following nodes. :param g: the graph\\ :param value_names: a list of string which are the names of ...
5,353,619
def reorder_by_first(*arrays): """ Applies the same permutation to all passed arrays, permutation sorts the first passed array """ arrays = check_arrays(*arrays) order = np.argsort(arrays[0]) return [arr[order] for arr in arrays]
5,353,620
def machine_save_handler(sender, **kwargs): """ Send value of channel to Websocket Server whenever Machine saved. """ from api.serializers import MachineSerializer instance = kwargs.pop('instance') serialized = MachineSerializer(instance) body = serialized.data url = 'http://localhost:1984/machines...
5,353,621
def embedding_weights(mesh, vocab_dim, output_dim, variable_dtype, name="embedding", ensemble_dim=None, initializer=None): """Embedding weights.""" if not ensemble_dim: ensemble_di...
5,353,622
def get_db() -> Generator: """ endpointからアクセス時に、Dependで呼び出しdbセッションを生成する エラーがなければ、commitする エラー時はrollbackし、いずれの場合も最終的にcloseする """ db = None try: db = SessionLocal() yield db db.commit() except Exception: if db: db.rollback() fin...
5,353,623
def generiraj_emso(zenska): """Funkcija generira emso stevilko""" rojstvo = random_date_generator(julijana_zakrajsek) # Odstranim prvo števko leta emso_stevke = rojstvo[:4] + rojstvo[5:] if zenska: # Malce pretirana poenostavitev zadnjih treh cifer, lahko se zgodi da pridejo iste + zanemarja...
5,353,624
def send_metric(name, distance, points): """Send person's stats to Datadog over HTTP API""" metrics = [{ 'metric': 'sportid.workout.distance', 'points': [float(distance)], 'tags': ['name:' + name], 'host': environ.get('HOST', ''), 'type': 'gauge' }, { 'metric': 'sportid.workout.points', ...
5,353,625
def setup_logging(config_path): """Setup logging configuration """ if os.path.isfile(config_path): with open(config_path, "rt") as f: config = yaml.safe_load(f.read()) for handler_name, handler_conf in config["handlers"].items(): if "filename" not in handler_conf.key...
5,353,626
def update_bad_replicas_history(dids, rse_id, session=None): """ Update the bad file replicas history. Method only used by necromancer :param dids: The list of DIDs. :param rse_id: The rse_id. :param session: The database session in use. """ for did in dids: # Check if the replica ...
5,353,627
def process_message(data): """ @keyword *prod change:* `^kevin.*prod change*(\\n|\|){2}` *kevin* _[]_ *prod change* _[]_ * _|[user]|[summary title]|[|more details]_ @summary instead of switching context to jira just to make a silly change to ST2, have kevin make the prod change @see *prod change:* _...
5,353,628
def pdf_markov2(x, y, y_offset=1, nlevels=3): """ Compute the empirical joint PDF for two processes of Markov order 2. This version is a bit quicker than the more general pdf() function. See the docstring for pdf for more info. """ y_offset = np.bool(y_offset) # out = np.ones((nlevels,)*6...
5,353,629
def add_vertex(graph, vertex): """ Raise Exception if sometsing gone wrong and vertex is not added """ assert isinstance(vertex, str) gr = PillowGraph(StringToAdjListDict(graph.AdjList)) gr.add_vertex(vertex) graph.AdjList = str(gr.AdjList) graph.save()
5,353,630
def cvt_dotted_as_name(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """dotted_as_name: dotted_name ['as' NAME]""" assert ctx.is_REF, [node] dotted_name = xcast(ast_cooked.DottedNameNode, cvt(node.children[0], ctx.to_BARE())) if len(node.children) == 1: # `import os.path` creates a binding fo...
5,353,631
def train( model, data, epochs=10, batch_size=100, lr=0.001, lr_decay_mul=0.9, lam_recon=0.392, save_dir=None, weights_save_dir=None, save_freq=100, ): """Train a given Capsule Network model. Args: model: The CapsuleNet model to train. data: The dataset t...
5,353,632
def test_actor_for_edge_expiration(setup): # type: (SetupTest) -> None """Test choice of actor ID when expiring an edge. Our current audit log model has no concept of a system-generated change and has to map every change to a user ID that performed that change. We previously had a bug where we would t...
5,353,633
def txn_replay(session_filename, txn, proxy, result_queue, request_session): """ Replays a single transaction :param request_session: has to be a valid requests session""" req = txn.getRequest() resp = txn.getResponse() # Construct HTTP request & fire it off txn_req_headers = req.getHeaders() ...
5,353,634
def check_if_recipe_skippable(recipe, channels, repodata_dict, actualname_to_idname): """ check_if_recipe_skippable ========================= Method used to check if a recipe should be skipped or not. Skip criteria include: - If the version of the recipe in the channel repodata is greater t...
5,353,635
def ensure_csv_detections_file( folder: types.GirderModel, detection_item: Item, user: types.GirderUserModel ) -> types.GirderModel: """ Ensures that the detection item has a file which is a csv. Attach the newly created .csv to the existing detection_item. :returns: the file document. TODO: mo...
5,353,636
def hello(name=None): """Assuming that name is a String and it checks for user typos to return a name with a first capital letter (Xxxx). Args: name (str): A persons name. Returns: str: "Hello, Name!" to a given name, or says Hello, World! if name is not given (or passed as an empty String...
5,353,637
def main(): """ """ #file = open( "jbc.p", "rb" ) #jbc = pickle.load(file) #file.close() # file = open( "stffmtx.p", "rb" ) neq = pickle.load(file) iband = pickle.load(file) #stf = pickle.load(file) file.close() # elements = pickle.load(open( "memb.p", "rb" )) jbc...
5,353,638
def computePCA(inputMatrix, n_components=None): """Compute Principle Component Analysis (PCA) on feature space. n_components specifies the number of dimensions in the transformed basis to keep.""" pca_ = PCA(n_components) pca_.fit(inputMatrix) return pca_
5,353,639
def tag(repo, subset, x): """The specified tag by name, or all tagged revisions if no name is given. Pattern matching is supported for `name`. See :hg:`help revisions.patterns`. """ # i18n: "tag" is a keyword args = getargs(x, 0, 1, _("tag takes one or no arguments")) cl = repo.changelog ...
5,353,640
def save_imgs(output_image_dir, dataloader): """Saves a grid of generated imagenet pictures with captions""" target_dir = os.path.join(output_image_dir, "imgs/") if not os.path.isdir(target_dir): os.makedirs(target_dir) i = 0 for (imgs, _, _) in dataloader: imgs = imgs.cpu().numpy()...
5,353,641
def _embed_json(service, targetid): """ Returns oEmbed JSON for a given URL and service """ return d.http_get(_OEMBED_MAP[service] % (urlquote(targetid),)).json()
5,353,642
def test_helling(): """Test de functie helling in bereken.py.""" assert bereken.helling(np.array([0, 0]), np.array([1, 0])) == 0.0 assert bereken.helling(np.array([0, 0]), np.array([1, 1])) == 45.0 assert bereken.helling(np.array([0, 0]), np.array([-1, -1])) == 45.0 assert bereken.helling(np.array(...
5,353,643
def is_blank(s): """Returns True if string contains only space characters.""" return re.search(reNonSpace, s) is None
5,353,644
def persistTeamData(teamData): """ Creates a dataframe containing the project ids and the members matched to that project """ if connection.is_connected(): cursor = connection.cursor() for row in teamData.index: sql = "INSERT INTO Team(ProjectId, ProjectName, \ Memb...
5,353,645
def remove_invalid_chars_from_passage(passage_text): """ Return a cleaned passage if the passage is invalid. If the passage is valid, return None """ # Check if any of the characters are invalid bad_chars = [c for c in passage_text if c in INVALID_PASSAGE_CHARACTERS] if bad_chars: for b in set(bad_chars): p...
5,353,646
def fallback_humanize(date, fallback_format=None, use_fallback=False): """ Format date with arrow and a fallback format """ # Convert to local timezone date = arrow.get(date).to('local') # Set default fallback format if not fallback_format: fallback_format = '%Y/%m/%d %H:%M:%S' #...
5,353,647
def questbackup(cfg, server): """Silly solution to a silly problem.""" if server not in cfg['servers']: log.warning(f'{server} has been misspelled or not configured!') elif 'worldname' not in cfg['servers'][server]: log.warning(f'{server} has no world directory specified!') elif 'questi...
5,353,648
def find_file_in_pythonpath( filename, subfolder='miri', walkdir=False, path_only=False): """ Find a file matching the given name within the PYTHONPATH. :Parameters: filename: str The name of the file to be located. subfolder: str, optional (defaul...
5,353,649
def driveForward(self, distance : float, speed : float = 50): """Moves Cozmo forward or backwards. Arguments: distance: A float representing the distance in millimeters for cozmo to travel. - Positive: Moves Cozmo forward. - Negative: Moves Cozmo backward. speed: A float...
5,353,650
def set_tpu_info(params): """Docs.""" logging.info('Retrieve TPU information') tpu_init = tf.tpu.initialize_system() tpu_shutdown = tf.tpu.shutdown_system() with common_utils.get_session(params, isolate_session_state=True) as sess: topology_proto = sess.run(tpu_init) topology = tpu_lib.topology.Topolo...
5,353,651
def min_column_widths(rows): """Computes the minimum column width for the table of strings. >>> min_column_widths([["some", "fields"], ["other", "line"]]) [5, 6] """ def lengths(row): return map(len, row) def maximums(row1, row2) : return map(max, row1, row2) return reduce(maximums, map(len...
5,353,652
def entities(address_book): """Get the entities utility.""" return zope.component.getUtility(IEntities)
5,353,653
def generate_dataset_file_url(client, filepath): """Generate url for DatasetFile.""" if not client: return try: if not client.project: return project = client.project except ValueError: from renku.core.management.migrations.models.v9 import Project m...
5,353,654
def _check_attrs(obj): """Checks that a periodic function/method has all the expected attributes. This will return the expected attributes that were **not** found. """ missing_attrs = [] for attr_name in _REQUIRED_ATTRS: if not hasattr(obj, attr_name): missing_attrs.append(attr_...
5,353,655
def stats(human=False): """ Print repository statistics. @param human (bool) Whether to output the data in human-readable format. """ stat_data = admin_api.stats() if human: click.echo( 'This option is not supported yet. Sorry.\nUse the `/admin/stats`' ' endp...
5,353,656
def _chunk_noise(noise): """Chunk input noise data into valid Touchstone file rows.""" data = zip( noise["freq"], noise["nf"], np.abs(noise["rc"]), np.angle(noise["rc"]), noise["res"], ) for freq, nf, rcmag, rcangle, res in data: yield freq, nf, rcmag, rca...
5,353,657
def test_TSclassifier(): """Test TS Classifier""" covset = generate_cov(40, 3) labels = np.array([0, 1]).repeat(20) assert_raises(TypeError, TSclassifier, clf='666') clf = TSclassifier() clf.fit(covset, labels) assert_array_equal(clf.classes_, np.array([0, 1])) clf.predict(covset) c...
5,353,658
def create_table(): """ If table does not exist, Table is create. If exists, return error. Error is caught in try/except loop. :return: """ sql_command = """ CREATE TABLE IF NOT EXISTS data_table ( postId INTEGER, id INTEGER PRI...
5,353,659
def test_dataset_info(): """Read raster metadata and return spatial info.""" info = utils.get_dataset_info(asset1) assert info["geometry"] assert info["properties"]["path"] assert info["properties"]["bounds"] assert info["properties"]["datatype"] assert info["properties"]["minzoom"] == 7 ...
5,353,660
def archive(context: Context, images: List[ImageName], archive: str): """Operates on docker-save produced archives.""" ctx = get_context_object(context) ctx["images"] = images ctx["imagesource"] = ArchiveImageSource(archive=Path(archive)) verify(context)
5,353,661
def _create_admin_user(keystone, admin_email, admin_password): """Create admin user in Keystone. :param keystone: keystone v2 client :param admin_email: admin user's e-mail address to be set :param admin_password: admin user's password to be set """ admin_tenant = keystone.tenants.find(name='ad...
5,353,662
def TokenStartBlockElement(block): """ `TokenStartBlockElement` is used to denote that we are starting a new block element. Under most circumstances, this token will not render anything. """ return { "type": "SpaceCharacters", "data": "", "_md_type": mdTokenTypes["TokenStartB...
5,353,663
def parse_json(json_path): """ Parse training params json file to python dictionary :param json_path: path to training params json file :return: python dict """ with open(json_path) as f: d = json.load(f) return d
5,353,664
def compute_statistic(specify_db_path=None): """ """ # 初始化redis实例 RedisCtx.get_instance().host = settings.Redis_Host RedisCtx.get_instance().port = settings.Redis_Port MetricsAgent.get_instance().initialize_by_dict(metrics_dict) # 获取日志文件们所在的路径 db_path, logs_path = Index.get_log_pat...
5,353,665
def test_encode_decode_uuid_should_succeed(n: int) -> None: """Tests andom uuid encoding for n times""" for seq in range(1, n+1): x = uuid.uuid4() encoded = encode(x) decoded = decode(encoded) assert x == decoded
5,353,666
def cut_tails(fastq, out_dir, trimm_adapter, trimm_primer, hangF, hangR): """ The functuion ... Parameters ---------- reads : str path to ... out_dir : str path to ... hang1 : str Sequence ... hang2 : str Sequence ... Returns ------- ...
5,353,667
def incidentReports( draw: Callable[..., Any], new: bool = False, event: Optional[Event] = None, maxNumber: Optional[int] = None, beforeNow: bool = False, fromNow: bool = False, ) -> IncidentReport: """ Strategy that generates :class:`IncidentReport` values. """ automatic: Option...
5,353,668
def define_vectorized_funcs(): """ Defines vectorized versions of functions from uncertainties.umath_core. Some functions have their name translated, so as to follow NumPy's convention (example: math.acos -> numpy.arccos). """ this_module = sys.modules[__name__] # NumPy does not always use...
5,353,669
def load_spelling(spell_file=SPELLING_FILE): """ Load the term_freq from spell_file """ with open(spell_file, encoding="utf-8") as f: tokens = f.read().split('\n') size = len(tokens) term_freq = {token: size - i for i, token in enumerate(tokens)} return term_freq
5,353,670
def NotP8(): """ Return the matroid ``NotP8``. This is a matroid that is not `P_8`, found on page 512 of [Oxl1992]_ (the first edition). EXAMPLES:: sage: M = matroids.named_matroids.P8() sage: N = matroids.named_matroids.NotP8() sage: M.is_isomorphic(N) False ...
5,353,671
def kill(proc): """Kills |proc| and ignores exceptions thrown for non-existent processes.""" try: if proc and proc.pid: os.kill(proc.pid, signal.SIGKILL) except OSError: pass
5,353,672
def eqv(var_inp): """Returns the von-mises stress of a Field or FieldContainer Returns ------- field : ansys.dpf.core.Field, ansys.dpf.core.FieldContainer The von-mises stress of this field. Output type will match input type. """ if isinstance(var_inp, dpf.core.Field): return _...
5,353,673
def sort(array: list[int]) -> list[int]: """Counting sort implementation. """ result: list[int] = [0, ] * len(array) low: int = min(array) high: int = max(array) count_array: list[int] = [0 for i in range(low, high + 1)] for i in array: count_array[i - low] += 1 for j in range(1,...
5,353,674
def build_updated_figures( df, colorscale_name ): """ Build all figures for dashboard Args: - df: census 2010 dataset (cudf.DataFrame) - colorscale_name Returns: tuple of figures in the following order (datashader_plot, education_histogram, income_histogram, ...
5,353,675
def authorization(self, name, pasw, pages, screen, edu_lects, std_lects, dt): """ This method checks if user credentials are valid through server. :param self: It is for handling class structure. :param name: It is username. :param pasw: It is password. :param pages: It is list of pages. :pa...
5,353,676
def create_tcp(sip, pjsip, nmapped): """ Creates a 'transport-tcp' section in the pjsip.conf file based on the following settings from sip.conf: tcpenable tcpbindaddr (or bindaddr) """ protocol = 'tcp' bind, section = get_bind(sip, pjsip, protocol) if not bind: return s...
5,353,677
def sacct(): """ Wrapper around the slurm "sacct" command. Returns an object, and each property is the (unformatted) value according to sacct. Would also work with .e.g: # with open("/home/Desktop/sacct.txt", "r") as file: :return: SacctWrapper object, with attributes based on the output of sa...
5,353,678
def get_or_else_optional(optional: Optional[_T], alt_value: _T) -> _T: """ General-purpose getter for `Optional`. If it's `None`, returns the `alt_value`. Otherwise, returns the contents of `optional`. """ if optional is None: return alt_value return optional
5,353,679
def main(): """ Starts the crawler with user-provided CLI arguments """ parser = argparse.ArgumentParser( description="A crawler for gathering Maven coordinates and put them in a Kafka topic.") parser.add_argument("--m", default=MVN_URL, type=str, help="The URL of Maven repositories") p...
5,353,680
def create_dic(udic): """ Create a glue dictionary from a universal dictionary """ return udic
5,353,681
def information_gain_w_posterior(): """ Make a table/plot which estimates the mutual information (K-L divergence) between two distributions. The distributions are approximated by the MCMC samples. The information gain H = /int P(X) log_2( P(X) / pi(X) ) where P(X) is the posterior, and pi(X) is the...
5,353,682
def get_isotopes(loop): """ Given a text data loop, usually the very last one in the save frame, find and return the isotopes for naming. Example output: [ '15N', '1H' ] """ # = = = Catch random error in giving the saveFrame instead loop = loop_assert(loop, 'get_isotopes') # For entries like...
5,353,683
def select_user(query_message, mydb): """ Prompt the user to select from a list of all database users. Args: query_message - The messages to display in the prompt mydb - A connected MySQL connection """ questions = [ inquirer.List('u', message=query_messa...
5,353,684
def runTool(plugin_name, config_dict=None, user=None, scheduled_id=None, caption=None, unique_output=True): """Runs a tool and stores this "run" in the :class:`evaluation_system.model.db.UserDB`. :type plugin_name: str :param plugin_name: name of the referred plugin. :type config_dict: dict or meta...
5,353,685
def generate_abl_contract_for_lateral_stage( lateral_stage: LateralProgressionStage, parent_blinding_xkey: CCoinExtKey, start_block_num: int, creditor_control_asset: CreditorAsset, debtor_control_asset: DebtorAsset, bitcoin_asset: BitcoinAsset, first_stage_input_descriptor: Optional[Blinding...
5,353,686
def setUpModule(): """Stub in get_db and reset_db for testing the simple db api.""" base.db_api = qonos.db.sqlalchemy.api base.db_api.configure_db()
5,353,687
def create_connection(language): """ a function to create sqlite3 connections to db, it retries 100 times if connection returned an error Args: language: language Returns: sqlite3 connection if success otherwise False """ try: # retries for i in range(0, 100): ...
5,353,688
def force_norm(): """perform normalization simulation""" norm = meep.Simulation(cell_size=cell, boundary_layers=[pml], geometry=[], resolution=resolution) norm.init_fields() source(norm) flux_inc = meep_ext.add_flux_plane(norm,...
5,353,689
def search(coordinates): """Search for closest known locations to these coordinates """ gd = GeocodeData() return gd.query(coordinates)
5,353,690
def get_all_apis_router(_type: str, root_path: str) -> (Path, Path): """Return api files and definition files just put the file on folder swagger.""" swagger_path = Path(root_path) all_files = list(x.name for x in swagger_path.glob("**/*.yaml")) schemas_files = [x for x in all_files if "schemas" in x] ...
5,353,691
def get_cached_patches(dataset_dir=None): """ Finds the cached patches (stored as images) from disk and returns their paths as a list of tuples :param dataset_dir: Path to the dataset folder :return: List of paths to patches as tuples (path_to_left, path_to_middle, path_to_right) """ if dataset...
5,353,692
def complex_mse(y_true: tf.Tensor, y_pred: tf.Tensor): """ Args: y_true: The true labels, :math:`V \in \mathbb{C}^{B \\times N}` y_pred: The true labels, :math:`\\widehat{V} \in \mathbb{C}^{B \\times N}` Returns: The complex mean squared error :math:`\\boldsymbol{e} \in \mathbb{R}^...
5,353,693
def expand_not(tweets): """ DESCRIPTION: In informal speech, which is widely used in social media, it is common to use contractions of words (e.g., don't instead of do not). This may result in misinterpreting the meaning of a phrase especially in the case of negations. ...
5,353,694
def parse_filter_kw(filter_kw): """ Return a parsed filter keyword and boolean indicating if filter is a hashtag Args: :filter_kw: (str) filter keyword Returns: :is_hashtag: (bool) True, if 'filter_kw' is hashtag :parsed_kw: (str) parsed 'filter_kw' (lowercase, without '#', ......
5,353,695
def get_branch_index(BRANCHES, branch_name): """ Get the place of the branch name in the array of BRANCHES so will know into which next branch to merge - the next one in array. """ i = 0 for branch in BRANCHES: if branch_name == branch: return i else: i = i + ...
5,353,696
def prettify_save(soup_objects_list, output_file_name): """ Saves the results of get_soup() function to a text file. Parameters: ----------- soup_object_list: list of BeautifulSoup objects to be saved to the text file output_file_name: entered as string with quotations an...
5,353,697
def determine_required_bytes_signed_integer(value: int) -> int: """ Determines the number of bytes that are required to store value :param value: a SIGNED integer :return: 1, 2, 4, or 8 """ value = ensure_int(value) if value < 0: value *= -1 value -= 1 if (value >> 7) == ...
5,353,698
def scrape_cvs(): """Scrape and return CVS data.""" page_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/web...
5,353,699