content
stringlengths
22
815k
id
int64
0
4.91M
def slowness_to_velocity(slowness): """ Convert a slowness log in µs per unit depth, to velocity in unit depth per second. Args: slowness (ndarray): A value or sequence of values. Returns: ndarray: The velocity. """ return 1e6 / np.array(slowness)
18,600
def SingleDetectorLogLikelihoodModelViaArray(lookupNKDict,ctUArrayDict,ctVArrayDict, tref, RA,DEC, thS,phiS,psi, dist,det): """ DOCUMENT ME!!! """ global distMpcRef # N.B.: The Ylms are a function of - phiref b/c we are passively rotating # the source frame, rather than actively rotating the b...
18,601
def monitor(ctx, config, mon_csv, gdal_frmt, date_frmt, ndv=0): """Command line interface to handle monitoring of new imagery. This program will not pre-process the data, which is done in yatsm.process_modis. This program will calculate the change probabilities in time-sequential order for all images i...
18,602
def manualcropping(I, pointsfile): """This function crops a copy of image I according to points stored in a text file (pointsfile) and corresponding to aponeuroses (see Args section). Args: I (array): 3-canal image pointsfile (text file): contains points' coordinates. Pointsfile must ...
18,603
def prepare_time_micros(data, schema): """Convert datetime.time to int timestamp with microseconds""" if isinstance(data, datetime.time): return int(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE + data.second * MCS_PER_SECOND + data.microsecond) else: return data
18,604
def get_configs_path_mapping(): """ Gets a dictionary mapping directories to back up to their destination path. """ return { "Library/Application Support/Sublime Text 2/Packages/User/": "sublime_2", "Library/Application Support/Sublime Text 3/Packages/User/": "sublime_3", "Library/Preferences/IntelliJIdea2018...
18,605
def plot_sample_variation_polar(annots_df_group, **kwargs): """ Function: plot polar coordinate values of R3, R4, T3, T4, T3' positions of wild-type flies of a specific age. bundles from one sample are plotted together on the same subplot. Inputs: - annots_df_group: DataFrame group. Processed annotation infor...
18,606
def num_from_bins(bins, cls, reg): """ :param bins: list The bins :param cls: int Classification result :param reg: Regression result :return: computed value """ bin_width = bins[0][1] - bins[0][0] bin_center = float(bins[cls][0] + bins[cls][1]) / 2 return bin...
18,607
def main(): """Main loop.""" options, args = parse_options() verbose = options.verbose if verbose: LOG.logger.setLevel(logging.DEBUG) else: LOG.logger.setLevel(logging.INFO) LOG.info('Cleaning stale locks from %s' % FLAGS.lock_path) utils.cleanup_file_locks() LOG.info('F...
18,608
def rotate90(matrix: list) -> tuple: """return the matrix rotated by 90""" return tuple(''.join(column)[::-1] for column in zip(*matrix))
18,609
def get_aspect(jdate, body1, body2): """ Return the aspect and orb between two bodies for a certain date Return None if there's no aspect """ if body1 > body2: body1, body2 = body2, body1 dist = distance(long(jdate, body1), long(jdate, body2)) for i_asp, aspect in...
18,610
def create_rollout_policy(domain: Simulator, rollout_descr: str) -> Policy: """returns, if available, a domain specific rollout policy Currently only supported by grid-verse environment: - "default" -- default "informed" rollout policy - "gridverse-extra" -- straight if possible, otherwise turn...
18,611
def get_event_details(event): """Extract event image and timestamp - image with no tag will be tagged as latest. :param dict event: start container event dictionary. :return tuple: (container image, last use timestamp). """ image = str(event['from'] if ":" in event['from'] else event['from'] + ":la...
18,612
def add_extra_vars_rm_some_data(df=None, target='CHBr3', restrict_data_max=False, restrict_min_salinity=False, # use_median_value_for_chlor_when_NaN=False, # medi...
18,613
def cvCreateMemStorage(*args): """cvCreateMemStorage(int block_size=0) -> CvMemStorage""" return _cv.cvCreateMemStorage(*args)
18,614
def copyJSONable(obj): """ Creates a copy of obj and ensures it is JSONable. :return: copy of obj. :raises: TypeError: if the obj is not JSONable. """ return json.loads(json.dumps(obj))
18,615
def get_eez_and_land_union_shapes(iso2_codes: List[str]) -> pd.Series: """ Return Marineregions.org EEZ and land union geographical shapes for a list of countries. Parameters ---------- iso2_codes: List[str] List of ISO2 codes. Returns ------- shapes: pd.Series: Shapes ...
18,616
def putrowstride(a,s): """ Put the stride of a matrix view object """ t=getType(a) f={'mview_f':vsip_mputrowstride_f, 'mview_d':vsip_mputrowstride_d, 'mview_i':vsip_mputrowstride_i, 'mview_si':vsip_mputrowstride_si, 'mview_uc':vsip_mputrowstride_uc, 'mview...
18,617
def list_tracked_stocks(): """Returns a list of all stock symbols for the stocks being tracker""" data = read_json("stockJSON/tracked_stocks.json") return list(data.keys())
18,618
def startStream(redisHost="localhost", visualSourceName="local_cam"): """ startStream streaming the frames into redis stream Args: redisHost (str, optional): Redis Hostname URL/IP. Defaults to "localhost". visualSourceName (str, optional): visual data source name. Defaults to "local_webcam"...
18,619
def bettorbar(ax, *args, **kwargs): """A better error bar function. Adds kwargs: elinestyle, ecolor Attempts to set zorder to be the same for all lines""" mplkwargs = kwargs.copy() mplkwargs.pop('ecolor', None) mplkwargs.pop('elinestyle', None) err = ax.errorbar(*args, **mplkwargs) color = kwargs.get('ecolor', ...
18,620
def min_max_two(first, second): """Pomocna funkce, vrati dvojici: (mensi ze zadanych prvku, vetsi ze zadanych prvku). K tomu potrebuje pouze jedno porovnani.""" return (first, second) if first < second else (second, first)
18,621
def expand_pin_groups_and_identify_pin_types(tsm: SMContext, pins_in): """ for the given pins expand all the pin groups and identifies the pin types Args: tsm (SMContext): semiconductor module context from teststand pins_in (_type_): list of pins for which information needs to be expanded i...
18,622
def multi_ways_balance_merge_sort(a): """ 多路平衡归并排序 - 多用于外部排序 - 使用多维数组模拟外部存储归并段 - 使用loser tree来实现多路归并 - 归并的趟数跟路数k成反比,增加路数k可以调高效率 :param a: :return: """ SENTRY = float('inf') # 哨兵,作为归并段的结尾 leaves = [] # 每个归并段中的一个元素构成loser tree的原始序列 b = [] # 输出归并段,此实现中简化为以为数组。实际情况下也需要对输出分...
18,623
def inner_cg_rhs(rhs, u, v, EHs, tau): """Compute right hand side for inner CG method ``rhs = u^n + tau * (div_h v^{n+1} + EHs)`` Args: rhs (gpuarray): Right hand side. u (gpuarray): u. v (gpuarray): v. EHs (gpuarray): EHs. tau (float): tau. """ inner_cg_rhs...
18,624
def check_instance_of(value, types, message = None): """ Raises a #TypeError if *value* is not an instance of the specified *types*. If no message is provided, it will be auto-generated for the given *types*. """ if not isinstance(value, types): if message is None: message = f'expected {_repr_types...
18,625
def create_input_metadatav1(): """Factory pattern for the input to the marshmallow.json.MetadataSchemaV1. """ def _create_input_metadatav1(data={}): data_to_use = { 'title': 'A title', 'authors': [ { 'first_name': 'An', ...
18,626
def create_job(title: str = Body(None, description='The title of the codingjob'), codebook: dict = Body(None, description='The codebook'), units: list = Body(None, description='The units'), rules: dict = Body(None, description='The rules'), debriefing: dict = ...
18,627
async def finalize( db, pg: AsyncEngine, subtraction_id: str, gc: Dict[str, float], count: int, ) -> dict: """ Finalize a subtraction by setting `ready` to True and updating the `gc` and `files` fields. :param db: the application database client :param pg: the PostgreSQL AsyncEn...
18,628
def find_path(a, b, is_open): """ :param a: Start Point :param b: Finish Point :param is_open: Function returning True if the Point argument is an open square :return: A list of Points containing the moves needed to get from a to b """ if a == b: return [] if not is_open(b): ...
18,629
def view_skill_api(): """ General API for skills and posts """ dbsess = get_session() action = request.form["action"] kind = request.form["kind"] if kind == "post": if action == "read": post = models.Post.get_by_id(dbsess, int(request.form["post-id"])) if not post: ...
18,630
def current_team() -> None: """Print the team currently authenticated against.""" client: Client = _load_client() print(client.default_team)
18,631
def _plot_raw_time(value, params): """Deal with changed time value""" info = params['info'] max_times = params['n_times'] / float(info['sfreq']) - params['duration'] if value > max_times: value = params['n_times'] / info['sfreq'] - params['duration'] if value < 0: value = 0 if pa...
18,632
def custom_swagger_client(func: Callable) -> None: """ Allows client to customize a SwaggerClient, so that they can leverage the default request handler. """ get_abstraction().client = func()
18,633
def check_match(candidate_smiles, gen): """ If A is a substructure of B and B is a substructure of A then the two must be isomorphic. Does that make sense? That's the logic I used! """ candidate = MolFromSmiles(candidate_smiles) for m in test_set: if m.HasSubstructMatch(candidate) and candidate.HasSubstructMatc...
18,634
def read_event(suppress=False): """ Blocks until a keyboard event happens, then returns that event. """ queue = _queue.Queue(maxsize=1) hooked = hook(queue.put, suppress=suppress) while True: event = queue.get() unhook(hooked) return event
18,635
def save_new_playlist(uid=None): """Gets and saves a New Playlist to a specific user""" # Creates a new playlist if uid: playlist = create_playlist_user(uid) else: playlist = create_playlist_general() # Connects and write into DataBase db = connection_database() collection ...
18,636
def part_1(data): """Part 1""" start = time.perf_counter() # CODE HERE legality = [check_line(line) for line in data] points = [POINTS[CLOSINGS.index(c)] for _,c in legality if c is not None] end = time.perf_counter() # OUTPUT HERE print(f'total={sum(points)}') print(f'elapsed = {...
18,637
def rotations(it): """ rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """ l = list(it) for i in range(len(l)): yield iter(l) l = l[1:]+[l[0]]
18,638
def searchCVE(service, version): """Return a list of strings""" re.search url = "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword="+service+"+"+version res = requests.get(url) soup = BeautifulSoup(res.content, "lxml") listCVE = [] for elt in soup.find_all('a', attrs={'href' : re.compile("^/cgi-bin/")}): list...
18,639
def config_from_args(args) -> config.TestConfig: """Convert args read from cli to config""" return config.TestConfig(program=args.p, test_dir=args.d, verifier=args.v, break_on_error=args.b == 'true', ...
18,640
def create_eulerian_path(graph_augmented, graph_original, start_node=None): """ Args: graph_augmented (networkx graph): graph w links between odd degree nodes created from `add_augmenting_path_to_graph`. graph_original (networkx graph): orginal graph created from `create_networkx_graph_from_edgelist` ...
18,641
def build_json( spec_filename: str, package_name: str, dist_path: str, format_: PackageFormat = PackageFormat.NONE, ) -> None: """ Create an OpenAlchemy distribution package with the SQLAlchemy models. The package can be uploaded to, for example, PyPI or a private repository for distrib...
18,642
def get_default_plugins_folder(): """ :returns: Default location for the plugins folder. :rtype: str """ return path.join(get_install_folder(), "plugins")
18,643
def py_write_qr(image_name): """Write QR code image file (internal method).""" uid = uuid.uuid4() randStr = uid.hex[:4] img = qrcode.make(image_name) m = re.search('/([^/]+?)/.+?$', image_name) filename = m.group(1) + "_" + randStr + '.png' img.save(str(filename)) combine_images.ma...
18,644
def importFromDotSpec(spec): """ Import an object from an arbitrary dotted sequence of packages, e.g., "a.b.c.x" by splitting this into "a.b.c" and "x" and calling importFrom(). :param spec: (str) a specification of the form package.module.object :return: none :raises PygcamException: if the im...
18,645
def usgs_graphite_call(*, resp, year, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param resp: df, response from url call :param year: year :return: pandas dataframe of original source data """ df_raw_data = pd.io.excel.read_excel(io.B...
18,646
def test_unicode_display_name(executed_docstring_source): """ >>> import allure >>> @allure.title(u"Лунтик") >>> def test_unicode_display_name_example(): ... pass """ assert_that(executed_docstring_source.allure_report, has_test_case("test_unicode_display_name_example",...
18,647
def test_regrid_bilinear_2(): """Test bilinear regridding option 'bilinear-2'""" cube_in, cube_out_mask, _ = define_source_target_grid_data() regrid_bilinear = RegridLandSea(regrid_mode="bilinear-2",)(cube_in, cube_out_mask) expected_results = np.array( [ [0.5, 0.8, 1.1, 1.4, 1.7, ...
18,648
def _gen_np_divide(arg1, arg2, out_ir, typemap): """generate np.divide() instead of / for array_expr to get numpy error model like inf for division by zero (test_division_by_zero). """ scope = arg1.scope loc = arg1.loc # g_np_var = Global(numpy) g_np_var = ir.Var(scope, mk_unique_var("$np_g_...
18,649
def add_yfull( kit: Optional[str] = Option(None, "--kit", "-k", help = "The kit number."), group: Optional[str] = Option(None, "--group", help = "The group within which the sample clusters."), ancestor: Optional[str] = Option(None, "--ancestor", help = "The earliest known patrilineal ancestor."), country: Optional[...
18,650
def pseudo_volume_watson(eos, r, temp, press_eos, rho_eos, a_mix, b_mix, desired_phase): """ Calculates a pseudo volume based on the algorithm described by Watson (2018) in thesis "Robust Simulation and Optimization Methods for Natural Gas Liquefaction Processes" Available at https://dspace.mit.edu/hand...
18,651
def test_hook_manager_can_call_hooks_defined_in_specs( hook_specs, hook_name, hook_params ): """Tests to make sure that the hook manager can call all hooks defined by specs.""" cli_hook_manager = CLIHooksManager() hook = getattr(cli_hook_manager.hook, hook_name) assert hook.spec.namespace == hook_sp...
18,652
def layer_norm(x, axes=1, initial_bias_value=0.0, epsilon=1e-3, name="var"): """ Apply layer normalization to x Args: x: input variable. initial_bias_value: initial value for the LN bias. epsilon: small constant value to avoid division by zero. scope: scope or name for the LN...
18,653
def P2D_p(df, attr): """ Calcul de la probabilité conditionnelle P(target | attribut). *les parametres: df: dataframe avec les données. Doit contenir une colonne nommée "target". attr: attribut à utiliser, nom d'une colonne du dataframe. *le return: de type dictionnaire de dictionnai...
18,654
def save_examples(logdir = None): """save examples of true and false positives to help visualize the learning""" if logdir is None: return input_map = {} for error_type in ['false_negatives', 'false_positives','true_positives', 'true_negatives']: #load the names of the files ...
18,655
def has_entries(*keys_valuematchers, **kv_args): """Matches if dictionary contains entries satisfying a dictionary of keys and corresponding value matchers. :param matcher_dict: A dictionary mapping keys to associated value matchers, or to expected values for :py:func:`~hamcrest.core.core.i...
18,656
def main(): """ Main function """ # Print all Flags to confirm parameter settings print_flags() if not os.path.exists(FLAGS.data_dir): os.makedirs(FLAGS.data_dir) # Run the training operation train()
18,657
def giou_loss(y_true: TensorLike, y_pred: TensorLike, mode: str = 'giou') -> tf.Tensor: """ Args: y_true: true targets tensor. The coordinates of the each bounding box in boxes are encoded as [y_min, x_min, y_max, x_max]. y_pred: predictions tensor. The co...
18,658
def generate_one_frame( df_dict: dict, tag_list: list, fig, up_to_index, time_column, batch_ids_to_animate: list, animation_colour_assignment, show_legend=False, hovertemplate: str = "", max_columns=0, ) -> List[Dict]: """ Returns a list of dictionaries. Each entry in...
18,659
def invite_contributor_post(node, **kwargs): """API view for inviting an unregistered user. Performs validation, but does not actually invite the user. Expects JSON arguments with 'fullname' (required) and email (not required). """ fullname = request.json.get('fullname').strip() email = request.jso...
18,660
def upload_file(data_bucket): """Upload a file to an S3 object""" try: file_path = 'synthea_data/' current_directory = pathlib.Path(file_path) for current_file in current_directory.iterdir(): s3_resource.meta.client.upload_file( str(current_file), data_bucket...
18,661
def requires_roles(*roles): """ """ def wrapper(f): @wraps(f) def wrapped(*args, **kwargs): try: if current_user.role.name not in roles: abort(403) except AttributeError: pass return f(*args, **kwargs) ...
18,662
def home(request): """ Homepage, user must login to view """ context = { 'posts': BlogPost.objects.all().order_by('-date'), #Get all event announcement blog posts 'master': MasterControl.objects.get(identifier="MASTER") #Get the master control object } return render(request, 'b...
18,663
def user_login_success(request): """ Success login page """ return core.render(request, 'login/login-conf.html')
18,664
def use_scope() -> Scope: """Get the current ASGI scope dictionary""" return use_websocket().scope
18,665
def test_TODO(): """TODO(github.com/ChrisCummins/ProGraML/issues/5): Short summary of test.""" assert migrate_graph_database
18,666
def save_emails_to_file(emails, filename, reason): """Save a list of emails to a file in the current working directory. Keyword arguments: emails -- list of Email objects to be saved to file. filename -- the filename to save unsent emails to. reason -- the text or exception reason the emails couldn...
18,667
def test_json(): """Basic integration test for run_benchmark.py. It runs full benchmarking process for arbitrarily chosen parameters. """ build_configuration = { "db_bench": { "repo_url": project_path, "commit": "HEAD", "env": {}, }, "pmemkv":...
18,668
def test_delete_all(collection): """ Testing the 'delete_many' method to remove all :param collection: pytest fixture that returns the collection :return: """ collection['tiny'].delete_many({}) c = collection['tiny'].find({}) assert c.count() == 0
18,669
def cli(method, *kargs, **arguments): """Simulates testing a hug cli method from the command line""" collect_output = arguments.pop('collect_output', True) command_args = [method.__name__] + list(kargs) for name, values in arguments.items(): if not isinstance(values, (tuple, list)): ...
18,670
def set_start_stop_from_input(spiketrains): """ Sets the start :attr:`t_start`and stop :attr:`t_stop` point from given input. If one nep.SpikeTrain objects is given the start :attr:`t_stop `and stop :attr:`t_stop` of the spike train is returned. Otherwise the aligned times are returned, which a...
18,671
def less(data_str): """Pretty print JSON and pipe to less.""" p = Popen('less', stdin=PIPE) p.stdin.write(data_str.encode()) p.stdin.close() p.wait() return True
18,672
def get_extensions(f, v): """ Get a dictionary which maps each extension name to a bool whether it is enabled in the file Parameters ---------- f : an h5py.File or h5py.Group object The object in which to find claimed extensions v : bool Verbose option Returns -...
18,673
def init_parser(): """ initialize argument parser for S1 processing utilities """ parser = argparse.ArgumentParser() parser.add_argument('-t', '--transform', action='store_true', help='transform the final DEM to UTM coordinates') parser.add_argument('-l', '--logfiles', action='store_true', help=...
18,674
async def remove_device(ws_client, device_id, config_entry_id): """Remove config entry from a device.""" await ws_client.send_json( { "id": 5, "type": "config/device_registry/remove_config_entry", "config_entry_id": config_entry_id, "device_id": device_id,...
18,675
def deco_inside_ctx_method_self(target): """decorator: wrap a class method inside a `with self: ...` context""" def tgt(self, *args, **kwargs): with self: return target(self, *args, **kwargs) return tgt
18,676
def c_get_mechanism_info(slot, mechanism_type): """Gets a mechanism's info :param slot: The slot to query :param mechanism_type: The type of the mechanism to get the information for :returns: The result code, The mechanism info """ mech_info = CK_MECHANISM_INFO() ret = C_GetMechanismInfo(C...
18,677
def test_reset(cli_runner: CliRunner) -> None: """Test set vin.""" assert not os.path.exists(os.path.expanduser(CREDENTIAL_PATH)) result = cli_runner.invoke(__main__.main, f"set --locale {TEST_LOCALE}") assert result.exit_code == 0 assert os.path.exists(os.path.expanduser(CREDENTIAL_PATH)) # R...
18,678
def make_legend(names, colors): """ Make a list of legend handles and colours :param names: list of names :param colors: list of colors :return: list of matplotlib.patches.Patch objects for legend """ legend_elements = [] for idx, name in enumerate(names): el = Patch(color=color...
18,679
def create_fuku_table(conn): """ Creacion de tabla de usuarios, numeros""" try: cur = conn.cursor() cur.execute(CREATE_TABLE_FUKU_QUERY) cur.close() except mysql.connector.Error as e: logger.error(e)
18,680
def optimize(iterable): """ Yields a simplified sequence of patch operations from iterable. """ iterable = check_stream(iterable) header = next(iterable) yield header lastItem = next(iterable) if isinstance(lastItem, ops.SourceCopy) and lastItem.offset == 0: # SourceCopy is copying from the start of the fi...
18,681
def create_visitor_id(visitor_id, options): """Creates new VisitorId""" if not visitor_id: visitor_id = VisitorId() if not options: options = {} device_id = options.get("device_id") visitor = options.get("visitor") if not visitor_id.tnt_id: visitor_id.tnt_id = device_id...
18,682
def validate_crc(response: str, candidate: str) -> bool: """Calculates and validates the response CRC against expected""" expected_crc = '{:04X}'.format(crc(response)) return expected_crc == candidate.replace('*', '')
18,683
def z_gate(): """ Pauli z """ return torch.tensor([[1, 0], [0, -1]]) + 0j
18,684
def numpy_ewma(data, window): """ :param data: :param window: :return: """ alpha = 1 / window scale = 1 / (1 - alpha) n = data.shape[0] scale_arr = (1 - alpha) ** (-1 * np.arange(n)) weights = (1 - alpha) ** np.arange(n) pw0 = (1 - alpha) ** (n - 1) mult = data * pw0 * s...
18,685
def read(home_dir=os.path.expanduser('~')): """Read user profile from .pgdocs config""" outfile = config_file(home_dir) # create empty file and return empty profile with empty sessions if not os.path.exists(outfile): open(outfile, "w").close() return Profile([]) with open(config_fil...
18,686
def tagged_sha256(tag: bytes, msg: bytes) -> bytes: """ Compute a tagged hash as defined in BIP-340. This is useful for creating a message hash and achieving domain separation through an application-specific tag. This function returns SHA256(SHA256(tag)||SHA256(tag)||msg). :param tag: tag ...
18,687
def validate_blacklist(password): """ It does not contain the strings ab, cd, pq, or xy """ for blacklisted in ['ab', 'cd', 'pq', 'xy']: if blacklisted in password: return False return True
18,688
def get_mobilenet(model, method, num_classes): """Returns the requested model, ready for training/pruning with the specified method. :param model: str :param method: full or prune :param num_classes: int, num classes in the dataset :return: A prunable MobileNet model """ ModuleInjection.pru...
18,689
def test_network_firmware_auth_exception(switch_vendor, get_firmware_dell): """Test that the `canu report network firmware` command catches auth exception.""" with runner.isolated_filesystem(): switch_vendor.return_value = "dell" get_firmware_dell.side_effect = ssh_exception.NetmikoAuthenticatio...
18,690
def f(x): """Squares something""" time.sleep(10) return x * x
18,691
def get_added_after( fetch_full_feed, initial_interval, last_fetch_time=None, filter_args=None ): """ Creates the added_after param, or extracts it from the filter_args :param fetch_full_feed: when set to true, will limit added_after :param initial_interval: initial_interval if no :param last_fe...
18,692
def gdf_lineStrings(): """Construct a gdf that contains two LineStrings.""" ls_short = LineString([(13.476808430, 48.573711823), (13.506804, 48.939008), (13.4664690, 48.5706414)]) ls_long = LineString([(13.476808430, 48.573711823), (11.5675446, 48.1485459), (8.5067847, 47.4084269)]) a_list = [(0, ls_sh...
18,693
def createFormattedDir(source, dirname, batchSize = 128, cleanDir=False, verbose=True): """Given a source that supports __len__ and __getitem__, and a directory that's empty, create a formatted directory that's then used by BatchDataset. This only needs to be run once, so it's a utility. Adjust batchSize so two ...
18,694
def runnify( async_function: Callable[T_ParamSpec, Coroutine[Any, Any, T_Retval]], backend: str = "asyncio", backend_options: Optional[Dict[str, Any]] = None, ) -> Callable[T_ParamSpec, T_Retval]: """ Take an async function and create a regular (blocking) function that receives the same keyword ...
18,695
def _binary_stdio(): """Construct binary stdio streams (not text mode). This seems to be different for Window/Unix Python2/3, so going by: https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin NOTE: this method is borrowed from python-language-server: https://github.com...
18,696
def _get_properties(rsp: Dict[Text, Any]) -> Iterable[CdProperty]: """ Retrieve key properties to be passed onto dynatrace server. """ return [ CdProperty("Status", rsp.get("status", "N/A")), CdProperty("Entry point", rsp.get("entryPoint", "N/A")), CdProperty("Available memory Mb", rsp.g...
18,697
async def test_api_key_flunks_bad_email(): """api_key() rejects an obviously malformed email address""" # But only the most obvious cases involving misplaced '@' or lack of '.' bad_addrs = ['f@@ey', '56b7165e4f8a54b4faf1e04c46a6145c'] for addr in bad_addrs: path_params = {'email': addr} ...
18,698
def factors(n): """Yield the factors of n in ascending order.""" rtn = isqrt(n) smalls = list(filter(lambda k: n % k == 0, range(1, rtn + 1))) larges = [n // k for k in smalls] if rtn * rtn == n: smalls.pop() yield from smalls yield from reversed(larges)
18,699