content
stringlengths
22
815k
id
int64
0
4.91M
def _add_paths(G, paths, bidirectional=False): """ Add a list of paths to the graph as edges. Parameters ---------- G : networkx.MultiDiGraph graph to add paths to paths : list list of paths' tag:value attribute data dicts bidirectional : bool if True, create bi-dire...
51,600
def construct_policy( bucket_name: str, home_directory: str, ): """ Create the user-specific IAM policy. Docs: https://docs.aws.amazon.com/transfer/latest/userguide/ custom-identity-provider-users.html#authentication-api-method """ return { 'Version': '2012-10-17', 'Stat...
51,601
def read_b2fgmtry(fileloc): """ Modified from omfit_solps.py """ with open(fileloc, 'r') as f: tmp = f.read() tmp = tmp.replace('\n', ' ') tmp = tmp.split("*c") tmp = [[f for f in x.split(' ') if f] for x in tmp] m = {'int': int, 'real': float, 'char': str} b2fgmtry = {} ...
51,602
def random_rotation_matrix(rand=None, key=None): """Return uniform random rotation matrix. rand: array like Three independent random variables that are uniformly distributed between 0 and 1 for each returned quaternion. """ return quaternion_matrix(random_quaternion(rand, key))
51,603
def package(application_dir='.'): """Deploys the user application and pylambder on AWS. When this function finishes the AWS is ready to accept requests.""" application_dir = Path(application_dir) os.makedirs(application_dir / ARTIFACTS_DIR, exist_ok=True) _package(application_dir)
51,604
def vea_create(context, values, session=None): """Creates a new VEA instance in the Database""" # If we weren't given a session, then we need to create a new one if not session: session = nova_db_sa_api.get_session() # Create a Transaction around the insert in the Database with session.begin...
51,605
def run() -> None: """Main entrypoint for auto_cli, run an app and command based on sys.argv""" if len(sys.argv) < 2: _print_and_quit( "Did not understand command.\nUsage: ac <app> <command> [paramaters]" ) app = sys.argv[1] run_command(app, sys.argv[2:])
51,606
def test_1000(docs_path): """_prune_data_table()""" eml_path = docs_path / EX_4_PATH eml_el = get_eml_etree_by_path(eml_path) dex.eml_subset._prune_data_table(eml_el, EX_4_PKG_PATH) log.debug(f'eml_el="{dex.util.get_etree_as_pretty_printed_xml(eml_el)}"')
51,607
def binned_power(imap,bin_edges=None,binner=None,fc=None,modlmap=None,imap2=None,mask=1): """Get the binned power spectrum of a map in one line of code. (At the cost of flexibility and reusability of expensive parts)""" from orphics import stats shape,wcs = imap.shape,imap.wcs modlmap = enmap.m...
51,608
def batch_to_dict(batch): """ Batch file contains two columns: FULL/PATH/TO/SAMPLE_bin.13.fa SAMPLE_bin.13 Create a dict with [sample_bin_name] = ["Tigname1", "Tigname2"] :param batch: full path to batch file :return batch_dict: dict described above :return bin_list: list of bin names "...
51,609
def test_get_all_cam_ids(veri): """ Test VeriDataset.get_distinct_cams_by_car_id() """ instantiated_class = veri[0] TEST_CAMS = [1, 2, 3] for test_cam, cam in zip(TEST_CAMS, sorted(instantiated_class.get_all_cam_ids())): assert test_cam == cam
51,610
def md_link(name: str, url: str) -> str: """Makes strings easier to read when defining markdown links.""" return f"[{name}]({url})"
51,611
def extract_uhs(dstore, what): """ Extracts uniform hazard spectra. Use it as /extract/uhs/mean or /extract/uhs/rlz-0, etc """ oq = dstore['oqparam'] mesh = get_mesh(dstore['sitecol']) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() dic = {} for kind, hcurves in getters.PmapGetter(d...
51,612
def geocode_presidents(town): """ Returns a list of all intersections where a numbered street crosses a street named after the corresponding president ("1st and Washington", etc.) Each item in the resulting list is a tuple, with item[0] holding the name of the intersection ("1st and Washi...
51,613
def args(): """ 命令行参数以及说明 """ parser = argparse.ArgumentParser() parser.add_argument('-r', '--read', dest='read', help='input conpany file path') parse_args = parser.parse_args() # 参数为空 输出--help命令 if parse_args.read is None: parser.print_help() os._exit(0) ...
51,614
def _check_numeric(*, check_func, obj, name, base, func, positive, minimum, maximum, allow_none, default): """Helper function for check_float and check_int.""" obj = check_type(obj, name=name, base=base, func=func, allow_none=allow_none, default=default) if obj is No...
51,615
def cli(args, cook_url=None, flags=None, stdin=None, env=None, wait_for_exit=True): """Runs a CLI command with the given URL, flags, and stdin""" url_flag = f'--url {cook_url} ' if cook_url else '' other_flags = f'{flags} ' if flags else '' cp = sh(f'{command()} {url_flag}{other_flags}{args}', stdin, en...
51,616
def cleanup(sender=None, dictionary=None): """Perform a platform-specific cleanup after the test.""" return True
51,617
def _pushsyncphase(pushop): """synchronise phase information locally and remotely""" unfi = pushop.repo.unfiltered() cheads = pushop.commonheads # even when we don't push, exchanging phase data is useful remotephases = pushop.remote.listkeys('phases') if (pushop.ui.configbool('ui', '_usedassubre...
51,618
def load_release_darwin_x64_appletv_settings(conf): """ Setup all compiler and linker settings shared over all darwin_x64_appletv configurations for the 'release' configuration """ conf.load_darwin_x64_appletv_common_settings() # Load additional shared settings conf.load_release_cryengine_s...
51,619
def turn_on(hass, entity_id): """Set input_boolean to True.""" hass.services.call(DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id})
51,620
def dB2(N,s,ρ=0.5,seed=0): """ Get random numbers for two correlated rBergomi processes, each having N paths and s steps. """ np.random.seed(0) # Following assumes orthogonal variance components equivalent rn = np.random.normal(size=(N,6*s)) # In what follows the 3 indices correspond to ...
51,621
def karaoke_perceptual_metric(reference_timestamps, estimated_timestamps): """Metric based on human synchronicity perception as measured in the paper "User-centered evaluation of lyrics to audio alignment" [#lizemasclef2021] The parameters of this function were tuned on data collected through a user Karaok...
51,622
def buildTraceback(frames, modules): """ Build a chain of mock traceback objects from a serialized Error (or other exception) object, and return the head of the chain. """ last = None first = None for func, fname, ln in frames: fname = modules.get(fname.split('/')[-1], fname) ...
51,623
def deployment_update(uuid, values): """Update a deployment by values. :param uuid: UUID of the deployment. :param values: dict with items to update. :raises DeploymentNotFound: if the deployment does not exist. :returns: a dict with data on the deployment. """ return get_impl().deployment_...
51,624
def test_formamidinesulfinic_acid_canonicalization2(): """formamidinesulfinic acid tautomer""" assert canonicalize_tautomer_smiles('N=C(N)S(=O)O') == 'N=C(N)S(=O)O'
51,625
def navigate_part_two(commands: List[Tuple[str, int]]) -> Tuple[int, int]: """Navigate and return the horizontal position and depth.""" horizontal: int = 0 depth: int = 0 aim: int = 0 for command, units in commands: if command == 'forward': horizontal += units depth ...
51,626
def f(x): """ :rtype: object """ pass
51,627
def _generate_events_for_day(date): """Generates events for a given day.""" # Use date as seed. seed = int(time.mktime(date.timetuple())) Faker.seed(seed) random_state = random.RandomState(seed) # Determine how many users and how many events we will have. n_users = random_state.randint(lo...
51,628
def _hessian_vector_product(fun, argnum=0): """Builds a function that returns the exact Hessian-vector product. The returned function has arguments (*args, vector, **kwargs). Note, this function will be incorporated into autograd, with name hessian_vector_product. Once it has been this function can be ...
51,629
def check_for_tags(*tag_args, msg="Inkluderar inte någon av de givna taggarna"): """ Compares the user tags and the test_case tags to see which tests should be be ran. """ def skip_function(): """ replaces test_cases so they are skipped """ raise SkipTest(msg) de...
51,630
def find_n_max_vals(list_, num): """Function searches the num-biggest values of a given list of numbers. Returns the num maximas list and the index list wrapped up in a list. """ li_ = list_.copy() max_vals = [] #the values max_ind = []# the index of the value, can be used to get the param...
51,631
def color_burn(im1, im2): """Darkens the backdrop color to reflect the source color. The color burn formula is defined as: if(Cb == 1) B(Cb, Cs) = 1 else if(Cs == 0) B(Cb, Cs) = 0 else B(Cb, Cs) = 1 - min(1, (1 - Cb) / Cs) See the W3C document: ...
51,632
def de_register_callbacks(): """ De-registers callback function. :return: None """ callbacks = pm.optionVar.get(CALLBACK_KEY) pm.optionVar[CALLBACK_KEY] = ' ' if callbacks: callback_ids = [int(callback_id) for callback_id in callbacks.split()] for callback_id in callback_id...
51,633
def runGodot(command_args): """Runs godot with the command args given (a list) Returns a string of the output or None""" try: byte_string = subprocess.check_output(command_args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: return # convert to a string and return return byte_str...
51,634
def G_2_by_2(a, b, c, d, williams=1, directional=1): """G test for independence in a 2 x 2 table. Usage: G, prob = G_2_by_2(a, b, c, d, willliams, directional) Cells are in the order: a b c d a, b, c, and d can be int, float, or long. williams is a boolean stating whether to do t...
51,635
def list_command(ctx): """ List jobs known to the jobstore. """ with Halo(text="Loading list...", spinner="dots", color="magenta") as spinner: job_list = ctx.obj.scheduler.list_jobs() spinner.color = "green" if ctx.obj.json_output: spinner.stop() ctx.obj.con.print...
51,636
def test_elapsed_duration(monkeypatch): """ . """ @counter_wrapper def duration(interval: float): """ . """ return interval monkeypatch.setattr(print_utils, "current_unix_timestamp", lambda: 123) monkeypatch.setattr(print_utils, "readable_duration", duration...
51,637
def solve(y1,y2) : """ solve SIS lens equation with y1,y2 : relative source position with respect to the lens return : phi,x image position in polar coordinate as arrays of length 2 or 4 """ eq = lambda phi : eq2(phi,y1,y2) step = 0.1 phiTest = np.arange(0,2*np.pi+step,step) test = eq...
51,638
def makeNme(segID: int, N, CA, C, O, geo: NmeGeo) -> Residue: """Creates a NME capping residue""" res = makeGly(segID, N, CA, C, O, geo) res.resname = "NME" return res
51,639
def compose_image_meta(image_id, image_shape, window, active_class_ids): """Takes attributes of an image and puts them in one 1D array. image_id: An int ID of the image. Useful for debugging. image_shape: [height, width, channels] window: (y1, x1, y2, x2) in pixels. The area of the image where the real...
51,640
def run_episode_generic(env: Env, action_value_generator: Callable[[Any, int], Tuple[List[float], float]], max_length: int, max_len_reward: Union[int, None], action_selector: ptan.actions.ActionSelector = ptan.actions.ArgmaxActionSelector(), ...
51,641
def sobjects_metadata_resource(client: Client): """Return resource representing SObject metadata.""" path = f"{client.resources['sobjects']}" @resource class SObjectMetadataResource: """...""" def __init__(self, name): self.name = name @query async def des...
51,642
def makeDrinkInfo(rec_id): """ Permet de dresser les infos de la boissons passees en argument :param arg1: id de la boissons (recette) :type arg1: int :return: le nom, prix et les informations utiles (alcool, chaud ou froid) de la boissons :rtype: Json """ price = calculePriceRec(rec_id) nom = recupNameRec...
51,643
def get_vars(host): """ parse ansible variables - defaults/main.yml - vars/main.yml - molecule/${MOLECULE_SCENARIO_NAME}/group_vars/all/vars.yml """ base_dir, molecule_dir = base_directory() file_defaults = "file={}/defaults/main.yml name=role_defaults".format(base_dir) file...
51,644
def get_smem_args(smem_args, params): """ return a dict with kernel instance specific size """ result = smem_args.copy() if 'size' in result: size = result['size'] if callable(size): size = size(params) elif isinstance(size, str): size = replace_param_occurren...
51,645
def run_suite(suite_id,taskid=None): """ :param suite_id: :return: None test case status enum: {"0":"全部未执行","1":"全部失败","2":"成功","3":"部分失败"} """ # get one test suite inst = TestSuite.objects.filter(id=suite_id).first() serial = SerialTestSuite(instance=inst, many=False) data = serial....
51,646
def test_labels(): """ Test invalid arguments to chart components """ gg = ggplot(df, aes(x='x', y='y')) gg = gg + geom_point() gg = gg + xlab('xlab') gg = gg + ylab('ylab') gg = gg + ggtitle('title') assert gg.labels['x'] == 'xlab' assert gg.labels['y'] == 'ylab' assert gg....
51,647
def check_actual_routes(): """"Compares the number of routes in the results excel and the actual routes evt filteren op countries """ from math import isnan from Europe_utils import country_code_from_name, country_names #Load the analysis file analysis_file = config['paths']['data'] / 'Ove...
51,648
def fork_procs(variant_arg: Optional[Iterable[T]] = None, variant_args: Optional[Iterable[Sequence]] = None) \ -> Callable[[Callable], process.Handle]: """ A decorate to create and fork multiple processes """ procs_dec = procs(variant_arg, variant_args) def decorator(fn: Callable) -> proce...
51,649
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns:ocs ...
51,650
def test_css_id(): """Verify the id attribute can be set on the fieldset.""" form = FieldsetForm() form.helper = FormHelper() form.helper.layout = Layout(Fieldset(css_id="new_id")) assert parse_form(form) == parse_contents(RESULT_DIR, "css_id.html")
51,651
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre): """detector and beam are dxtbx objects, mosflm_beam_centre is a tuple of mm coordinates. supports 2-theta offset detectors, assumes correct centre provided for 2-theta=0 """ return set_slow_fast_beam_centre_mm(detector, beam, mosflm...
51,652
def _visualize(ax, data, labels, centers): """ 将模型结果可视化 """ colors = ["#82CCFC", "k"] if labels is None: ax.scatter(data[:, 0], data[:, 1]) else: ax.scatter(data[:, 0], data[:, 1], c=[colors[i] for i in labels], marker="o", alpha=0.6) ax.scatter(centers[:, 0], cen...
51,653
def test_time_until_next_event_for_time_of_day_event_listener( default_time_of_day_event_listener, freezer, ): """Test that the correct number of seconds until next period is correct.""" work_monday = datetime(year=2018, month=2, day=12, hour=10) freezer.move_to(work_monday) assert default_time_...
51,654
async def connect(): """Ouvre la connexion au serveur PC Minecraft. Returns: ``True`` (la connexion a réussi) ou ``False`` (la connexion a échoué) Le *screen* Unix sur lequel tourne le serveur et le chemin d'accès (relatif ou abolu) aux logs actuels générés par le serveur sont lus par cett...
51,655
def getNumColors(path): """ Detect the number of colors in the supplied image (Only up to 8 colors not including the background) NOTE: This feature is experimental and may not work well for ALL images """ im = Image.open(path) # Resize to reduce processing time w, h = im.size wS...
51,656
def reduce_precision_np(x, npp): """ Reduce the precision of image, the numpy version. :param x: a float tensor, which has been scaled to [0, 1]. :param npp: number of possible values per pixel. E.g. it's 256 for 8-bit gray-scale image, and 2 for binarized image. :return: a tensor representing image...
51,657
def multi_dut_argument(func) -> Callable[..., Union[Optional[str], Tuple[Optional[str]]]]: """ Used for parse the multi-dut argument according to the `count` amount. """ @functools.wraps(func) def wrapper(*args, **kwargs): return parse_multi_dut_args(_COUNT, func(*args, **kwargs)) retu...
51,658
def connectJoint(*args, **kwargs): """ This command will connect two skeletons based on the two selected joints. Returns: None """ pass
51,659
def AddMacsecPreSharedKeyStartTimeForAddKey(parser): """Adds keyName flag to the argparse.ArgumentParser.""" parser.add_argument( '--start-time', required=False, default=None, help="""\ A RFC3339 timestamp on or after which the key is valid. startTime can be in the future. If the...
51,660
def create_post(sourcedir, targetdir): """Creates a single post from the specified source directory in the specified target directory""" (date, meta) = read_date_and_meta(sourcedir) # if no date could be determined, the post can not be created if date is None: print_dir_abort('no date determined') return con...
51,661
def ts2wws(C): """ Convert a stiffness tensor into a skew notation stiffness matrix """ Cv = zeros(3,6) for i in range(3): for j in range(6): ma = skew_mults[i] mb = mandel_mults[j] Cv[i,j] = C[skew_inds[i] + mandel[j]] * ma * mb return Cv
51,662
def testdata(): """ Simple fixture to return reference data :return: """ class TestData(): def __init__(self): self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data') def fn(self, fn): return os.path.join(self.datadir, fn) d...
51,663
def _get_oauth2_client_id_and_secret(settings_instance): """Initializes client id and client secret based on the settings""" secret_json = getattr(django.conf.settings, 'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None) if secret_json is not None: return _load_client_secrets(secret...
51,664
def print_irreg_form(form,lemma,affix): """Print entry of irregs.tab file encoding an exception to a regular inflectional rule.""" print(f"{form} {affix} {lemma}")
51,665
def configure_parser(parser): """ Configure parser for this action. """ qisys.parsers.worktree_parser(parser) group = parser.add_argument_group("qisrc snapshot options") group.add_argument("snapshot_path", nargs="?", help="Path to the output snapshot file. " + ...
51,666
def buildTranslation(lang): """Finds the file corresponding to 'lang' builds up string_cache. If the file is not valid, does nothing. Errors encountered during the process are silently ignored. Returns string_cache.""" global string_cache fName = os.path.join(langPath, lang + ".trn") if os.a...
51,667
def lpp_transform(X, V, ncomp=2): """ Args: -------------- X: n x d. Data matrix V: d x m. Each column of V is a LPP direction. ncomp (<= m <= d): The dimension of transformed data Returns: -------------- tr_X: n x ncomp """ _, m...
51,668
def test_get_barcode_2(): """ Test get barcode with barcode present """ cv2.setNumThreads(0) bar_manager = BarCodeManager() barcode_info_extracted, text, _ = bar_manager.get_barcode_info(soap_joe) assert barcode_info_extracted is False assert text is '' cv2.setNumThreads(-1)
51,669
def U_net(optimizer, activation, metrics): """ Parameters: - optimizer (String): Keras optimizer to use - activation (String): Keras layer activation function to use in hidden layers - metrics to use for model evaluation Returns: (Model) a compiled U-net designed for binary segmentatio...
51,670
def create_environment(env_name='', stacked=False, representation='extracted', rewards='scoring', enable_goal_videos=False, enable_full_episode_videos=False, render=False, ...
51,671
def self_biosample_id(): """本人的样品编号""" return SELF_BIOSAMPLE_ID
51,672
def exp_process_image_20(img): """Get multiprocess experiment.""" return process_image( img, imgclf.ImageClassifier(), segments_no=20, sample_size=100, random_seed=42)
51,673
def get_lol_version(): """ Get current League of Legends version """ versions = json.loads(requests.get( "https://ddragon.leagueoflegends.com/api/versions.json").text) # reformats from 10.14.5 to 10.14 latest = ".".join(versions[0].split(".")[:2]) return latest
51,674
def retrieve_domain_name(module, client, name): """ Retrieve domain name by provided name :return: Result matching the provided domain name or an empty hash """ resp = None try: resp = backoff_get_domain_name(client, name) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'...
51,675
def create_BIP122_uri(chain_id, resource_type, resource_identifier): """ See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki """ if resource_type not in {BLOCK, TRANSACTION}: raise ValueError("Invalid resource_type. Must be one of 'block' or 'transaction'") elif not is_block...
51,676
def test_init_env(): """Test client intialization from API key stored in env var""" key = 'test_key_env' os.environ["GIFTBIT_API_KEY"] = key client = GiftbitClient() assert client.api_key == key
51,677
def draw_down(x, y, threshold, timeout): """ Draws the line down. :param x: X coordinate of click :param y: Y coordinate of click :param threshold: pixel gradient threshold :param timeout: timeout (sec) :return: Y coordinate where pixel gradient is hit """ y_position = y while y_...
51,678
def read_read_basis(input_string): """ """ pattern = ('ReadBasis' + one_or_more(SPACE) + capturing(LOGICAL)) block = _get_functional_form_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None return keyword
51,679
def _Ipr7ConfigRead(config): """Extracts DPA and grants from IPR7 config JSON. Args: config: A JSON dictionary. Returns: A tuple (dpas, grants) where: dpas: a list of objects of type |dpa_mgr.Dpa|. grants: a list of |data.CbsdGrantInfo|. """ if 'portalDpa' in config: dpa_tag = 'port...
51,680
def pack(a: ArrayLike, ox: int, oy: int, wx: int, wy: int, sx: int, sy: int, px: int = 0, py: int = 0, is_column: bool = True) -> ShapeletsArray: """ Reverses the :obj:`~shapelets.compute.unpack` operation For a thorough explanation of this method, consult the `ArrayFire documentation <https://arr...
51,681
def test_multiple_choice_buttons_multiple_selectable( run_gui, dummy_button_definition, dummy_multi_choice ): """3 buttons should be shown and they should all be individually selectable.""" text_box, question_defn = dummy_multi_choice question_defn = replace(question_defn, allow_multiple=True,) mul...
51,682
def maybe_create_token_network( token_network_proxy: TokenNetworkRegistry, token_proxy: CustomToken ) -> TokenNetworkAddress: """ Make sure the token is registered with the node's network registry. """ block_identifier = token_network_proxy.rpc_client.get_confirmed_blockhash() token_address = token_prox...
51,683
def rmsprop(grad, init_params, callback=None, num_iters=100, step_size=0.1, gamma=0.9, eps=10**-8): """Root mean squared prop: See Adagrad paper for details.""" flattened_grad, unflatten, x = flatten_func(grad, init_params) avg_sq_grad = np.ones(len(x)) for i in range(num_iters): g ...
51,684
def parse_transceiver_dom_sensor(output_lines): """ @summary: Parse the list of transceiver from DB table TRANSCEIVER_DOM_SENSOR content @param output_lines: DB table TRANSCEIVER_DOM_SENSOR content output by 'redis' command @return: Return parsed transceivers in a list """ res = [] p = re.co...
51,685
def test_image_file_link_bad_extension_markdown_cell( rich_notebook_output: RichOutput, remove_link_ids: Callable[[str], str] ) -> None: """It does not render an image link when extension is unknown.""" bad_extension_path = __file__ markdown_cell = { "cell_type": "markdown", "id": "acade...
51,686
def test_worship_song_fields(): """`WorshipSong` holds info about songs in a worship.""" WorshipSong.insert_many( [(1, 1, 1), (2, 1, 2), (3, 1, 3)], fields=[WorshipSong.id, WorshipSong.worship, WorshipSong.song], ).execute() q = ( Song.select() .join(WorshipSong) ...
51,687
def get_excerpt(post): """Returns an excerpt between ["] and [/"] post -- BBCode string""" match = _re_excerpt.search(post) if match is None: return "" excerpt = match.group(0) excerpt = excerpt.replace(u'\n', u"<br/>") return _re_remove_markup.sub("", excerpt)
51,688
def dropblock(net, is_training, keep_prob, dropblock_size, data_format='channels_first'): """DropBlock: a regularization method for convolutional neural networks. DropBlock is a form of structured dropout, where units in a contiguous region of a feature map are dropped together. DropBlock works bet...
51,689
def enumerate_det_id(n_dets, freq=39, band='LF1'): """ Generator for looping through detector names. Not very smart, only for basic testing. Args: n_dets (int): number of detector names to make freq (int): detector freqency band (str): detector band Returns: SO form...
51,690
def main(): """ Main Program """ args = get_args() random_str = ( "".join(sorted(string.ascii_letters + string.punctuation)) if not args.alphanumeric else "".join(sorted(string.ascii_letters)) ) random.seed(args.seed) out_fh = open(args.output, "wt") if args.output else...
51,691
def convert_multi_output_classifier_converter( scope: Scope, operator: Operator, container: ModelComponentContainer): """ Converts a *MultiOutputClassifier* into *ONNX* format. """ if OnnxSequenceConstruct is None: raise RuntimeError( "This converter requires opset>=11.") ...
51,692
def certify(String, cert, password): """check a certificate for a string""" return certificate(String, password) == cert
51,693
def is_same_float(a, b, tolerance=1e-09): """Return true if the two floats numbers (a,b) are almost equal.""" abs_diff = abs(a - b) return abs_diff < tolerance
51,694
def generate_grid_speed(method, shape, speed_range): """Generate a speed distribution according to sampling method. Parameters ---------- method : str Method for generating the speed distribution. shape : tuple Shape of grid that the speed distribution should be defined on. spee...
51,695
def _find_elf_deps_iter(elf: ELFFile, origin: str, root: str = '/') \ -> Iterator[Tuple[str, str]]: """Iterates over the dependencies of an ELF file Backend of :func:`find_elf_deps_iter`. :param elf: Elf file to parse :param origin: Directory containing the ELF binary (real path as provided ...
51,696
def common_atoms(cycle1, cycle2): """ INPUT: two cycles with type: list of atoms OUTPUT: a set of common atoms """ set1 = set(cycle1) set2 = set(cycle2) return set1.intersection(set2)
51,697
def getstate(ctx, # Mandatory main parameter force): """The GetClusterState API method enables you to indicate if a node is part of a cluster or not. The three states are:""" """Available: Node has not been configured with a cluster name.""" """Pending: Node is pending for a specific n...
51,698
def ffprobe_json(media_file): """Uses ffprobe to extract media information returning json format. Arguments: media_file: media file to be probed. Returns: json output of media information. return code indicating process result. """ ff = 'ffprobe -v quiet -print_format json...
51,699