content
stringlengths
22
815k
id
int64
0
4.91M
def getCommandLine() -> argparse.ArgumentParser: """Получить агрументы коммандной строки Returns: argparse.ArgumentParser: _description_ """ parser = argparse.ArgumentParser(description='Конвертация тестов с TFS в xml формат Testrail/TestIT') action = parser.add_subparsers(dest='action', re...
18,300
def listall(context, uri=None): """ *musicpd.org, music database section:* ``listall [URI]`` Lists all songs and directories in ``URI``. """ result = [] root_path = translator.normalize_path(uri) # TODO: doesn't the dispatcher._call_handler have enough info to catch # the e...
18,301
def send_task_to_executor(task_tuple: TaskInstanceInCelery) \ -> Tuple[TaskInstanceKey, CommandType, Union[AsyncResult, ExceptionWithTraceback]]: """Sends task to executor.""" key, _, command, queue, task_to_run = task_tuple try: with timeout(seconds=OPERATION_TIMEOUT): result = ...
18,302
def createPyarchFilePath(filePath): """ This method translates from an ESRF "visitor" path to a "pyarch" path: /data/visitor/mx415/id14eh1/20100209 -> /data/pyarch/2010/id14eh1/mx415/20100209 """ pyarchFilePath = None if isinstance(filePath, str): filePath = pathlib.Path(filePath) li...
18,303
def test_pre_create_undeploy_for_blue_green(m_stop, mock_filter_units, mock_undeploy): """ Should undeploy all versions for mode: red-green """ # Given: Deployment parameters deployment = _create_test_deployment_with_defaults_applied() deployment['dep...
18,304
def get_embed(input_data, vocab_size, embed_dim): """ Create embedding for <input_data>. :param input_data: TF placeholder for text input. :param vocab_size: Number of words in vocabulary. :param embed_dim: Number of embedding dimensions :return: Embedded input. """ # TODO: Implement Fun...
18,305
def geometries_from_bbox(north, south, east, west, tags): """ Create a GeoDataFrame of OSM entities within a N, S, E, W bounding box. Parameters ---------- north : float northern latitude of bounding box south : float southern latitude of bounding box east : float ea...
18,306
def test(): """测试用""" api = TestHlp() # 读取配置文件 print(api.loadConfig("Hsconfig.ini")) # 初始化 print(api.init()) # 连接服务器 print(api.connectServer())
18,307
def dBzdtAnalCircT(a, t, sigma): """ Hz component of analytic solution for half-space (Circular-loop source) Src and Rx are on the surface and receiver is located at the center of the loop. Src waveform here is step-off. .. math:: \\frac{\partial h_z}{\partial t} = -\\...
18,308
def download_files(dir_path: str, urls: List[str]) -> None: """ Asynchronous download, decompress files. :param dir_path: :param urls: :return: """ os.makedirs(dir_path, exist_ok=True) sema = asyncio.BoundedSemaphore(5) async def fetch_file(url): fname = url.split("/")[-1] ...
18,309
def count_increasing(ratings, n): """ Only considering the increasing case """ arr = [1] * n cnt = 1 for i in range(1, n): cnt = cnt + 1 if ratings[i - 1] < ratings[i] else 1 arr[i] = cnt return arr
18,310
def xxxputInHTMLdir(filename = 'test.py'): """ create a directory for the python file then put the pythonfile into it """ verbose=False HTMLdir = filename.replace('.py','') #newDir = makeHTMLdir(HTMLdir) shutil.copyfile(filename, HTMLdir+'/'+ filename) if verbose: print('putInHTM...
18,311
def load_train_data_frame(train_small, target, keras_options, model_options, verbose=0): """ ### CAUTION: TF2.4 Still cannot load a DataFrame with Nulls in string or categoricals! ############################################################################ #### TF 2.4 still cannot load tensor_slices...
18,312
def stat_float_times(space, newval=-1): """stat_float_times([newval]) -> oldval Determine whether os.[lf]stat represents time stamps as float objects. If newval is True, future calls to stat() return floats, if it is False, future calls return ints. If newval is omitted, return the current setting. """ state =...
18,313
def decorate(rvecs): """Output range vectors into some desired string format""" return ', '.join(['{%s}' % ','.join([str(x) for x in rvec]) for rvec in rvecs])
18,314
def test_atomic_g_year_max_exclusive_4_nistxml_sv_iv_atomic_g_year_max_exclusive_5_5(mode, save_output, output_format): """ Type atomic/gYear is restricted by facet maxExclusive with value 2030. """ assert_bindings( schema="nistData/atomic/gYear/Schema+Instance/NISTSchema-SV-IV-atomic-gYear-maxE...
18,315
def update_topic_collection_items(request_ctx, collection_item_id, topic_id, **request_kwargs): """ Accepts the same parameters as create :param request_ctx: The request context :type request_ctx: :class:RequestContext :param collection_item_id: (required) ID :type collection_it...
18,316
def test_graph_difference_more_non_isolated_relations_source(stub_graph_set, stub_relation_set): """ Tests graph_difference returns graph with expected nodes if source graph has non-isolated nodes which are not present in target catalog """ _, vals = stub_graph_set common_relation = Relation(name=rand_...
18,317
def initialize_client(conn): """ called when new client connect. if new connected client is not the first connected client, the send the initial weights to the new connected client :param conn: """ if detailed_output: print("connected clients: ", len(connectedclients)) if len(con...
18,318
def upsample(inputs, factor=(2, 2), interpolation='nearest'): """ Upsampling layer by factor Parameters ---------- inputs: Input tensor factor: The upsampling factors for (height, width). One integer or tuple of two integers interpolation: A string, one of [`nearest`, `bilinear`, 'b...
18,319
def write_cmake_var_file(base_path: Path, file_paths: list[str]): """Write CMake script of source files. Args: base_dir (Path): Base directory. file_paths (list[str]): Paths of source files. """ source_list_cmake_path = base_path / SOURCE_LIST_CMAKE_SUFFIX with open( str(so...
18,320
def root_mean_squared_error(*args, **kwargs): """ Returns the square-root of ``scikit-learn``'s ``mean_squared_error`` metric. All arguments are forwarded to that function. """ return np.sqrt(mean_squared_error(*args, **kwargs))
18,321
def launch_process(simulation, episode, epsilon, mode, return_dict): """ Method to launch the simulation depending on the simulation, episode, epsilon and mode. """ simulation.run(episode, epsilon) return_dict[mode] = simulation.stop()
18,322
def idwt2(Wimg, level=4): """ inverse 2d wavelet transform :param Wimg: 2d array wavelet coefficients :param level: int level of wavelet transform - image shape has to be multiples of 2**level :return: 2d array image """ coeffs = _from_img_to_coeffs(Wimg, levels=level) ...
18,323
def is_volume_encryption_enabled(audit_options): """Validate volume encryption is enabled in Cinder. Security Guide Check Name: Check-Block-09 :param audit_options: Dictionary of options for audit configuration :type audit_options: Dict :raises: AssertionError if the assertion fails. """ k...
18,324
def get_color(card): """Returns the card's color Args: card (webelement): a visible card Returns: str: card's color """ color = card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][2]").get_attribute("stroke") # both light and dark theme if (color...
18,325
def test_plugin_manager_duplicate_priorities(): """ Make sure that the plugin manager raises an exception when multiple different plugins define the same operator """ # Note, the plugin manager does not currently compare to make sure that the # two definitions are different before raising an er...
18,326
def setup_box(): """ Will install python and all libs needed to set up this box to run the examjam code. Eventually this needs to be more RPM based """ #place_pub_key() install_box_libraries() install_python() install_easy_install() install_python_dependancies()
18,327
def is_valid_path(parameters: Dict[str, Any]) -> bool: """Single "." chars and empty strings "" are excluded from path by urllib3. A path containing to "/" or "%2F" will lead to ambiguous path resolution in many frameworks and libraries, such behaviour have been observed in both WSGI and ASGI applicati...
18,328
def to_tensor(x): """ Arguments: x: an instance of PIL image. Returns: a float tensor with shape [3, h, w], it represents a RGB image with pixel values in [0, 1] range. """ x = np.array(x) x = torch.FloatTensor(x) return x.permute(2, 0, 1).unsqueeze(0).div(255...
18,329
def load_messier_catalog_images(path, img_size=None, disable_tqdm=False): """ Data loader for Messier catalog images. The images are available in `messier-catalog-images` repository of MiraPy organisation. :param path: String. Directory path. :param img_size: Final dimensions of the image. :par...
18,330
def load_stl10(data_dir, flatten=False, one_hot=True, normalize_range=False, whiten_pixels=True, border_pad_size=0): """ Large part of this loader and the associated functions has been inspired from, https://github.com/mttk/STL10/blob/master/stl10_input.py """ # path to the binary train file...
18,331
def fetch_data(fold_path): """Fetch data saving in fold path. Convert data into suitable format, using csv files in fold path. :param fold_path: String. The fold in which data files are saved. :return: training_data: Dataframe. Combined dataframe to create training data. testing_data:...
18,332
def add_chr_prefix(band): """ Return the band string with chr prefixed """ return ''.join(['chr', band])
18,333
def group_by_distance(iterable, distance=1): """group integers into non-overlapping intervals that are at most *distance* apart. >>> list( group_by_distance( (1,1,2,4,5,7) ) ) [(1, 3), (4, 6), (7, 8)] >>> list( group_by_distance( [] ) ) [] >>> list( group_by_distance( [3] ) ) [(3, 4)]...
18,334
def disable_text_recog_aug_test(cfg, set_types=None): """Remove aug_test from test pipeline of text recognition. Args: cfg (mmcv.Config): Input config. set_types (list[str]): Type of dataset source. Should be None or sublist of ['test', 'val'] Returns: cfg (mmcv.Config):...
18,335
def layer_svg(svg_bottom, svg_top, offset: list = [0.0, 0.0]): """ Adds one SVG over another. Modifies the bottom SVG in place. :param svg_bottom: The bottom SVG, in in xml.etree.ElementTree form :param svg_top: The top SVG, in in xml.etree.ElementTree form :param offset: How far to offset the top S...
18,336
def get_data_home(data_home=None): """Return a path to the cache directory for example datasets. This directory is then used by :func:`load_dataset`. If the ``data_home`` argument is not specified, it tries to read from the ``CF_DATA`` environment variable and defaults to ``~/cf-data``. """ ...
18,337
def main(username,password): """ Opens FacebookClient and chats with random person """ # Setup fb = FacebookClient(username,password) chatbot = cleverbot3.Session() # choose random "friend" to chat with chat_list = fb.browser.find_element(By.CSS_SELECTOR,"ul.fbChatOrderedList.clearfix") item...
18,338
def utxo_cmd(ctx, dry_run): """Get the node's current UTxO with the option of filtering by address(es)""" try: CardanoCli.execute(cmd=["cardano-cli", "query", "utxo"], dry_run=dry_run, include_network=True) except CardanoPyError as cpe: ctx.fail(cpe.message) return cpe.return_code
18,339
def intronator(exons): """ Builds introns from pairs of Exon objects in >exons<. sort_attr is used for ordering of introns. """ def _window(seq): """ Taken from https://docs.python.org/release/2.3.5/lib/itertools-example.html Returns a sliding window (of width n) over...
18,340
def parse_file(ifile, ofile, sra_data, out_dir, verbose=False): """ Parse the file and create a new metadata file. Writes everything to the directory SRA_Submission, including a set of fasta files, one per biosample. """ cols = {'bioproject_accession' : 0, 'biosample_accession' : 1, 'library_...
18,341
def delta_in_ms(delta): """ Convert a timedelta object to milliseconds. """ return delta.seconds*1000.0+delta.microseconds/1000.0
18,342
def test_dbus_getall_oom(dev, apdev): """D-Bus GetAll wpa_config_get_all() OOM""" (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0]) id = dev[0].add_network() dev[0].set_network(id, "disabled", "0") dev[0].set_network_quoted(id, "ssid", "test") res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks', ...
18,343
def getNodes(pattern="*", scene=None, useLists=False): """Return a dictionary of nodes where the name or id matches the ``pattern``. By default, ``pattern`` is a wildcard and it returns all nodes associated with ``slicer.mrmlScene``. If multiple node share the same name, using ``useLists=False`` (default beha...
18,344
def get_cls( query: Union[None, str, Type[X]], base: Type[X], lookup_dict: Mapping[str, Type[X]], lookup_dict_synonyms: Optional[Mapping[str, Type[X]]] = None, default: Optional[Type[X]] = None, suffix: Optional[str] = None, ) -> Type[X]: """Get a class by string, default, or implementation....
18,345
def selection_sort(data): """Sort a list of unique numbers in ascending order using selection sort. O(n^2). The process includes repeatedly iterating through a list, finding the smallest element, and sorting that element. Args: data: data to sort (list of int) Returns: sorted l...
18,346
def _conv(args, filter_size, num_features, bias, reuse, w_init=None, b_init=0.0, scope='_conv'): """convolution: Args: args: a Tensor or a list of Tensors of dimension 3D, 4D or 5D batch x n, Tensors. filter_size: int tuple of filter height and width. reuse: None/True, whether to reuse vari...
18,347
def make_bright_star_mask_in_hp(nside, pixnum, verbose=True, gaiaepoch=2015.5, maglim=12., matchrad=1., maskepoch=2023.0): """Make a bright star mask in a HEALPixel using Tycho, Gaia and URAT. Parameters ---------- nside : :class:`int` (NESTED) HEALPixel nside. ...
18,348
def _feature_normalization(features, method, feature_type): """Normalize the given feature vector `y`, with the stated normalization `method`. Args: features (np.ndarray): The signal array method (str): Normalization method. 'global': Uses global mean and standard deviation values ...
18,349
def get_constraint(name): """ Lookup table of default weight constraint functions. Parameters ---------- name : Constraint, None, str Constraint to look up. Must be one of: - 'l1' : L1 weight-decay. - 'l2' : L2 weight-decay. - 'l1-l2' : Combined L1-L2 weight-decay. - Constraint : A custom implementa...
18,350
def add_org_hooks(mock, values): """Add hooks for an organization The values passed is an array of dictionaries as generated by the factory """ url = os.path.join("orgs", ORG_NAME, "hooks") register_uri(mock, "GET", url=url, json=values)
18,351
def player_count(conn, team_id): """Returns the number of players associated with a particular team""" c = conn.cursor() c.execute("SELECT id FROM players WHERE team_id=?", (team_id,)) return len(c.fetchall())
18,352
def _RedisClient(address): """ Return a connection object connected to the socket given by `address` """ h1, h2 = get_handle_pair(conn_type=REDIS_LIST_CONN) c = _RedisConnection(h1) #redis_client = util.get_redis_client() redis_client = util.get_cache_client() ip, port = address chan...
18,353
def format_timedelta(value, time_format="{days} days, {hours2}:{minutes2}:{seconds2}"): """Format a datetie.timedelta. See """ if hasattr(value, 'seconds'): seconds = value.seconds + value.days * 24 * 3600 else: seconds = int(value) seconds_total = seconds minutes = int(math.flo...
18,354
def random_account_user(account): """Get a random user for an account.""" account_user = AccountUser.objects.filter(account=account).order_by("?").first() return account_user.user if account_user else None
18,355
def pytest_collection_modifyitems(session, config, items): """Called by pytest after collecting tests. The collected tests and the order in which they will be called are in ``items``, which can be manipulated in place. """ if not session.config.getoption("--skip"): return passed_set =...
18,356
def overwrite(main_config_obj, args): """ Overwrites parameters with input flags Args: main_config_obj (ConfigClass): config instance args (dict): arguments used to overwrite Returns: ConfigClass: config instance """ # Sort on nested level to override shallow items first args = dict(s...
18,357
def initInterpreter(model_path): """Initializes the tflite interpreter with the given tflite model""" global interpreter interpreter = tf.lite.Interpreter(model_path=model_path) interpreter.allocate_tensors() global input_details input_details = interpreter.get_input_details() global output_...
18,358
def max_delta(model, new_model): """Return the largest difference between any two corresponding values in the models""" return max( [(abs(model[i] - new_model[i])).max() for i in range(len(model))] )
18,359
def wiener_khinchin_transform(power_spectrum, frequency, time): """ A function to transform the power spectrum to a correlation function by the Wiener Khinchin transformation ** Input:** * **power_spectrum** (`list or numpy.array`): The power spectrum of the signal. * **frequency** (`lis...
18,360
def child_is_flat(children, level=1): """ Check if all children in section is in same level. children - list of section children. level - integer, current level of depth. Returns True if all children in the same level, False otherwise. """ return all( len(child) <= level + 1 or child...
18,361
def load_dataset(name, other_paths=[]): """Load a dataset with given (file) name.""" if isinstance(name, Dataset): return name path = Path(name) # First, try if you have passed a fully formed dataset path if path.is_file(): return _from_npy(name, classes=classes) # Go through ...
18,362
def isqrtcovresnet101b(**kwargs): """ iSQRT-COV-ResNet-101 model with stride at the second convolution in bottleneck block from 'Towards Faster Training of Global Covariance Pooling Networks by Iterative Matrix Square Root Normalization,' https://arxiv.org/abs/1712.01034. Parameters: ----------...
18,363
def get_data(name: str, level: int, max_level: int) -> str: """從維基頁面爬取資料 參數: name: 程式或節點名稱 level: 欲查詢的等級 回傳: 爬到的資料 """ reply_msg = [] for dataframe in read_html(generate_url(name)): if (max_level < dataframe.shape[0] < max_level + 3 and dataframe...
18,364
def is_processable(path: str, should_match_extension: str): """ Process scandir entries, copying the file if necessary """ if not os.path.isfile(path): return False filename = os.path.basename(path) _, extension = os.path.splitext(filename) if extension.lower() != should_match_exten...
18,365
def insert_data(context, data_dict): """ :raises InvalidDataError: if there is an invalid value in the given data """ data_dict['method'] = _INSERT result = upsert_data(context, data_dict) return result
18,366
def timestamp(): """Get the unix timestamp now and retuen it. Attention: It's a floating point number.""" import time timestamp = time.time() return timestamp
18,367
def _n64_to_datetime(n64): """Convert Numpy 64 bit timestamps to datetime objects. Units in seconds""" return datetime.utcfromtimestamp(n64.tolist() / 1e9)
18,368
def cycle(iterable): """Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. This function uses single dispatch. .. seealso:: :func:`itertools.cycle` """ return itertools.cycl...
18,369
def get_availability_zone(name=None,state=None,zone_id=None,opts=None): """ `.getAvailabilityZone` provides details about a specific availability zone (AZ) in the current region. This can be used both to validate an availability zone given in a variable and to split the AZ name into its compone...
18,370
def _recs_on_solr(recommendations, solr_index_backoff, solr_index_restore): """sees if we have auto soft commit increases and restores and makes recommendations accordingly""" if len(solr_index_backoff) > 0: for core in solr_index_backoff.keys(): data = solr_index_backoff[core] d...
18,371
def create_collection(CollectionId=None): """ Creates a collection in an AWS Region. You can add faces to the collection using the operation. For example, you might create collections, one for each of your application users. A user can then index faces using the IndexFaces operation and persist results in a...
18,372
def main(): """ main function for both public leaderboard evaluation and private leaderboard prediction """ print("Get ground truth data for 376 listed companies") true_df = make_true_df( DATA_PATH, start_date=None, cut_off_date=CUT_OFF_DATE, new_eval_period=BOOL_NEW...
18,373
def copy_wcs(wcs_source_file, wcs_target_file): """ Copy the WCS header keywords from the source file into the target file. """ hdr_src = fits.getheader(wcs_source_file) wcs_src = WCS(hdr_src) im = fits.open(wcs_target_file, 'update') im[0].header.update(wcs_src.to_header()) im.flush(ou...
18,374
def _add_u_eq(blk, uex=0.8): """Add heat transfer coefficent adjustment for feed water flow rate. This is based on knowing the heat transfer coefficent at a particular flow and assuming the heat transfer coefficent is porportial to feed water flow rate raised to certain power (typically 0.8) Args: ...
18,375
def test_parse_cpe_name_wfn(cpe, cpe_ret): """ Parse correct CPE_NAME data WFN formatted :return: """ ret = core._parse_cpe_name(cpe) for key, value in cpe_ret.items(): assert key in ret assert ret[key] == value
18,376
def find_process_in_list( proclist, pid ): """ Searches for the given 'pid' in 'proclist' (which should be the output from get_process_list(). If not found, None is returned. Otherwise a list [ user, pid, ppid ] """ for L in proclist: if pid == L[1]: return L r...
18,377
def solution(s, start_pos, end_pos): """ Find the minimal nucleotide from a range of sequence DNA. :param s: String consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence :param start_pos: array with the start indexes for the intervals to check :p...
18,378
def ExtremeSoundHandlerProcess(ExtremeQueue): """ Display text based on recieved Sound object """ y = Sound() # Dummy Sound object, see bottom of loop y.dB = "" while True: x = queue_get(ExtremeQueue) if x is not None and x.dB != y.dB: # If we got a sound and it's ...
18,379
def validate_address(value: str, context: dict = {}) -> str: """ Default address validator function. Can be overriden by providing a dotted path to a function in ``SALESMAN_ADDRESS_VALIDATOR`` setting. Args: value (str): Address text to be validated context (dict, optional): Validator c...
18,380
def select_images(img_dir, sample_size=150, random_seed=42): """Selects a random sample of image paths.""" img_paths = [] for file in os.listdir(img_dir): if file.lower().endswith('.jpeg'): img_paths.append(os.path.join(img_dir, file)) if sample_size is not None: if random_s...
18,381
def load_period_data(period): """ Load period data JSON file If the file does not exist and empty dictionary is returned. """ filename = os.path.join(PROTOCOL_DIR, PERIOD_FILE_TEMPLATE % period) if not os.path.exists(filename): return {} with open(filename, 'r', encoding='utf-8') ...
18,382
def _get_hg_repo(path_dir): """Parse `hg paths` command to find remote path.""" if path_dir == "": return "" hgrc = Path(path_dir) / ".hg" / "hgrc" if hgrc.exists(): config = ConfigParser() config.read(str(hgrc)) if "paths" in config: return config["paths"].g...
18,383
def clip_grad_norm(parameters, max_norm, norm_type=2): """Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Arguments: parameters (Iterable[Variable]): an iterabl...
18,384
def array_to_string(array, col_delim=' ', row_delim='\n', digits=8, value_format='{}'): """ Convert a 1 or 2D array into a string with a specified number of digits and delimiter. The reason this exists is that the basic nump...
18,385
def get_dp_logs(logs): """Get only the list of data point logs, filter out the rest.""" filtered = [] compute_bias_for_types = [ "mouseout", "add_to_list_via_card_click", "add_to_list_via_scatterplot_click", "select_from_list", "remove_from_list", ] for log in...
18,386
def assign_reports_to_watchlist(cb: CbThreatHunterAPI, watchlist_id: str, reports: List[Dict]) -> Dict: """Set a watchlist report IDs attribute to the passed reports. Args: cb: Cb PSC object watchlist_id: The Watchlist ID to update. reports: The Intel Reports. Returns: The Watchlist...
18,387
def visualize_filter( image, model, layer, filter_index, optimization_parameters, transformation=None, regularization=None, threshold=None, ): """Create a feature visualization for a filter in a layer of the model. Args: image (array): the image to be modified by the fea...
18,388
def porcentaje (cadena1, cadena2): """ (str),(str)-> (float) Programa para hallar el porcentaje de correspondiente a las cadenas >>> porcentaje("CG","GA") 50 >>> porcentaje("AT","GT") 0 >>> porcentaje ("AAAT","GCGA") 25 :param cadena1: primera cadena ingresada :param cade...
18,389
def subtraction(x, y): """ Subtraction x and y >>> subtraction(-20, 80) -100 """ assert isinstance(x, (int, float)), "The x value must be an int or float" assert isinstance(y, (int, float)), "The y value must be an int or float" return x - y
18,390
async def paste(text: str) -> str: """Return an online bin of given text.""" session = aiohttp.ClientSession() async with session.post("https://hasteb.in/documents", data=text) as post: if post.status == 200: response = await post.text() return f"https://hasteb.in/{response[...
18,391
def lr_step(base_lr, curr_iter, decay_iters, warmup_iter=0): """Stepwise exponential-decay learning rate policy. Args: base_lr: A scalar indicates initial learning rate. curr_iter: A scalar indicates current iteration. decay_iter: A list of scalars indicates the numbers of iteration when the lear...
18,392
def apo(coalg): """ Extending an anamorphism with the ability to halt. In this version, a boolean is paired with the value that indicates halting. """ def run(a): stop, fa = coalg(a) return fa if stop else fa.map(run) return run
18,393
def cat_sample(ps): """ sample from categorical distribution ps is a 2D array whose rows are vectors of probabilities """ r = nr.rand(len(ps)) out = np.zeros(len(ps),dtype='i4') cumsums = np.cumsum(ps, axis=1) for (irow,csrow) in enumerate(cumsums): for (icol, csel) in enumer...
18,394
def download_network(region, network_type): """Download network from OSM representing the region. Arguments: region {string} -- Location. E.g., "Manhattan Island, New York City, New York, USA" network_type {string} -- Options: drive, drive_service, walk, bike, all, all_private Retu...
18,395
def extract_text(text): """ """ l = [] res = [] i = 0 while i < len(text) - 2: h, i, _ = next_token(text, i) obj = text[h:i] l.append(obj) for j, tok in enumerate(l): if tok == b'Tf': font = l[j-2] fsize = float(l[j-1]) elif tok ==...
18,396
async def test_step_import(opp): """Test that the import step works.""" conf = { CONF_USERNAME: "user@host.com", CONF_PASSWORD: "123abc", } with patch( "openpeerpower.components.tile.async_setup_entry", return_value=True ), patch("openpeerpower.components.tile.config_flow.as...
18,397
def add_pruning_arguments_to_parser(parser): """Add pruning arguments to existing argparse parser""" parser.add_argument('--do_prune', action='store_true', help="Perform pruning when training a model") parser.add_argument('--pruning_config', type=str, default=...
18,398
def invokeRule(priorAnswers, bodyLiteralIterator, sip, otherargs, priorBooleanGoalSuccess=False, step=None, debug=False, buildProof=False): """ Continue invokation of rule using (given) prior answers and lis...
18,399