content
stringlengths
22
815k
id
int64
0
4.91M
def update_metric(task, metric, results): """ Update metric arrording to the task. """ pred = np.array(results[0]) label = np.array(results[1]) loss = np.array(results[2]) if task == 'pretrain': cross_entropy = np.array(results[3]) metric.update(pred, label, cross_entropy) ...
5,337,100
def hxlvalidate_main(args, stdin=STDIN, stdout=sys.stdout, stderr=sys.stderr): """ Run hxlvalidate with command-line arguments. @param args A list of arguments, excluding the script name @param stdin Standard input for the script @param stdout Standard output for the script @param stderr Standar...
5,337,101
def fix_bayes_factor(bayes_factor): """ If one of the bayes factors is 'inf' we get a string instead of a tuple back. This is hacky but fixes that. """ # Maximum cut off for Bayes factor value max_bf = 1e12 if type(bayes_factor) == str: bayes_factor = bayes_factor.split(",") ...
5,337,102
def save_model(model_dir, cur_time, model, name): """save a single model""" filename = os.path.join(model_dir, "{}_{}.h5") model.save_weights(filename.format(cur_time, name))
5,337,103
def load_config_vars(target_config, source_config): """Loads all attributes from source config into target config @type target_config: TestRunConfigManager @param target_config: Config to dump variables into @type source_config: TestRunConfigManager @param source_config: The other config @retur...
5,337,104
def test__eq___dict__nested_data(nested_data): """ Test equality for stub. """ actual = nested_data.copy() assert actual == nested_data
5,337,105
def parse_and_save(local_file_location): """ Iterate through given local xml file line by line and write to default csv location :param local_file_location: str :return: void """ context = eTree.iterparse(local_file_location) for event, element in context: if event == "end" and eleme...
5,337,106
def fiebelkorn_binning(x_trial, t_trial): """ Given accuracy and time-points, find the time-smoothed average accuracy Parameters ---------- x_trial : np.ndarray Accuracy (Hit: 1, Miss: 0) of each trial t_trial : np.ndarray The time-stamp of each trial Returns ------- ...
5,337,107
def get_fastest_while_jump(condition:str, jump_tag:str, verdicts: list) -> list: """Verdicts like ["while", "a", "<", "10"] """ result = [] jumpables = ("===", ) + tuple(INVERT_TABLE.keys()) if len(verdicts) == 2: result.append(F"jump-if {jump_tag} {verdicts[1]} != false") elif verdicts[2] i...
5,337,108
def test_run_analysis(noise_dataset): """Test that run_analysis runs. """ X, y = noise_dataset run_analysis(X, y, [2, 3], [1, 2, 3], [0, 1, 2], 2, 3)
5,337,109
async def test_misc_upgrade_ledger_with_old_auth_rule( docker_setup_and_teardown, pool_handler, wallet_handler, get_default_trustee ): """ set up 1.1.50 sovrin + 1.9.0 node + 1.9.0 plenum + 1.0.0 plugins stable to fail (upgrade to 1.1.52 sovrin) set up 1.9.0~dev1014 node + 1.9.0~dev829 plenum m...
5,337,110
def ChangeUserPath(args): """Function to change or create the user repository path. This is where all the user's data is stored.""" global user_datapath if user_datapath: sys.stdout.write("Current user_datapath is: %s\n" % user_datapath) elif savedpath: sys.stdout.write("Saved user...
5,337,111
def absolute_path_without_git(directory): """ return the absolute path of local git repo """ return os.path.abspath(directory + "/..")
5,337,112
def find_template(fname): """Find absolute path to template. """ for dirname in tuple(settings.TEMPLATE_DIRS) + get_app_template_dirs('templates'): tmpl_path = os.path.join(dirname, fname) # print "TRYING:", tmpl_path if os.path.exists(tmpl_path): return tmpl_path ra...
5,337,113
def create_hcp_sets(skeleton, side, directory, batch_size, handedness=0): """ Creates datasets from HCP data IN: skeleton: boolean, True if input is skeleton, False otherwise, side: str, 'right' or 'left' handedness: int, 0 if mixed ind, 1 if right handed, 2 if left handed directory:...
5,337,114
def rtrim(n): """Returns a transform that removes the rightmost n points """ def t(xarr, yarr, *args): return (xarr[:-n], yarr[:-n]) + args t.__name__ = b'rtrim({})'.format(n) return t
5,337,115
def analyze_avg_prof_quality_by_department(dict_cursor, departmentID, campus): """ >>> analyze_avg_prof_quality_by_department(dict_cursor, 'CSC', 'St. George') CSC enthusiasm 3.95 course_atmosphere 3.90 ... (This is not complete) """ return __anal...
5,337,116
def audit(environ): """Check a wmt-exe environment. Parameters ---------- environ : dict Environment variables. Returns ------- str Warnings/errors. """ from os import linesep messages = [] for command in ['TAIL', 'CURL', 'BASH']: messages.append(...
5,337,117
def parse_to_json(data_str): """ Convert string to a valid json object """ json_obj_list = [] obj = data_str.split('%') for record in obj: attributes = re.split(',', record) data = json.dumps(attributes) data = re.sub(r':', '":"', data) data = re.sub(r'\[', '{',...
5,337,118
def plot_ROC( y_test: pd.Series, y_prob: pd.Series, model_name: str, output_folder: str='/mnt/data/figures', save_plot: bool=True): """Plot one ROC curve""" # Instantiate fpr = dict() tpr = dict() roc_auc = dict() # Calculate x and y for ROC-curve fpr, tpr, _ = roc_cur...
5,337,119
def calculate_elbo(model, X, recon_X): """ Compute the ELBO of the model with reconstruction error and KL divergence.. """ rec_loss = - np.sum(X * np.log(1e-8 + recon_X) + (1 - X) * np.log(1e-8 + 1 - recon_X), 1) mu, logvar = model.transform(X) kl = -0.5 * np.sum(1 + l...
5,337,120
def dice_loss(pred, target): """ Dice Loss based on Dice Similarity Coefficient (DSC) @param pred: torch.tensor, model prediction @param target: torch.tensor, ground truth label """ return 1 - dice_coeff(pred, target)
5,337,121
def parse(transaction): """ Parses Bitcoin Transaction into it's component parts""" byteStringLength = 2 # Version version = struct.unpack('<L', transaction[0:4*byteStringLength].decode("hex"))[0] offset = 4*byteStringLength # print "Version is: " + str(version) # Inputs varLength, inp...
5,337,122
def get_version(): """Get project version """ version_file_path = os.path.join( os.path.dirname(__file__), 'spowtd', 'VERSION.txt') with open(version_file_path) as version_file: version_string = version_file.read().strip() version_string_re = re.compile('[0-9.]+') ...
5,337,123
def get_related_items_by_type(parser, token): """Gets list of relations from object identified by a content type. Syntax:: {% get_related_items_by_type [content_type_app_label.content_type_model] for [object] as [varname] [direction] %} """ tokens = token.contents.split() if len(tokens) no...
5,337,124
def stitch_valleys(valley_list): """Returns a stitched list of valleys to extract seq from.""" valley_collection = utils.LocusCollection(valley_list, 1) stitched_valley_collection = valley_collection.stitch_collection() loci = [] regions = [] for valley in stitched_valley_collection.get_loci(): ...
5,337,125
def kepoutlier(infile, outfile=None, datacol='SAP_FLUX', nsig=3.0, stepsize=1.0, npoly=3, niter=1, operation='remove', ranges='0,0', plot=False, plotfit=False, overwrite=False, verbose=False, logfile='kepoutlier.log'): """ kepoutlier -- Remove or replace statistical ...
5,337,126
def no_gcab_namespace(name, *args): """ Mock gi.require_version() to raise an ValueError to simulate that GCab bindings are not available. We mock importing the whole 'gi', so that this test can be run even when the 'gi' package is not available. """ if name.startswith("gi"): m = mo...
5,337,127
def _start_beamtime( PI_last, saf_num, experimenters=[], wavelength=None, test=False ): """function for start a beamtime""" # check status first active_beamtime = glbl.get('_active_beamtime') if active_beamtime is False: raise xpdAcqError("It appears that end_beamtime may have been " ...
5,337,128
def logger(module_name: str): """Инициализация и конфигурирования логгера""" logging.basicConfig( level=logging.INFO, format='[%(levelname)s][%(asctime)s] %(name)s: %(message)s' ) return logging.getLogger(module_name)
5,337,129
def cast(op_name: str, expr: Expr, in_xlayers: List[XLayer]) -> XLayer: """ Conversion of Relay 'clip' layer Relay ----- Type: tvm.relay.op.clip Ref: https://docs.tvm.ai/langref/relay_op.html Parameters: - a (relay.Expr) The input tensor. - a_min (float) ...
5,337,130
def __generation_dec(n: int, m: int, x_min: np.array, x_max: np.array) -> np.matrix: """ :param n: num rows in returned matrix :param m: num cols in returned matrix :param x_min: float array, min possible nums in cols of returned matrix :param x_max: float array, max possible nums in cols of returne...
5,337,131
def create_queue(domains, main_domains): """ 创建首次探测的任务队列 """ for i, d in enumerate(domains): queue.put((d,main_domains[i]))
5,337,132
def apply_tariff(kwh, hour): """Calculates cost of electricity for given hour.""" if 0 <= hour < 7: rate = 12 elif 7 <= hour < 17: rate = 20 elif 17 <= hour < 24: rate = 28 else: raise ValueError(f'Invalid hour: {hour}') return rate * kwh
5,337,133
def _compound_smiles(compound: reaction_pb2.Compound) -> str: """Returns the compound SMILES, if defined.""" for identifier in compound.identifiers: if identifier.type == identifier.SMILES: return identifier.value return ""
5,337,134
def convert_pdf_to_txt(pdf, startpage=None): """Convert a pdf file to text and return the text. This method requires pdftotext to be installed. Parameters ---------- pdf : str path to pdf file startpage : int, optional the first page we try to convert Returns ------- ...
5,337,135
def cross_correlizer(sample_rate, max_itd, max_frequency): """ Convenience function for creating a CrossCorrelizer with appropriate parameters. sample_rate : the sample rate of the wav files to expect. max_itd : the maximum interaural time difference to test. max_fre...
5,337,136
def log_angle_distributions(args, pred_ang, src_seq): """ Logs a histogram of predicted angles to wandb. """ # Remove batch-level masking batch_mask = src_seq.ne(VOCAB.pad_id) pred_ang = pred_ang[batch_mask] inv_ang = inverse_trig_transform(pred_ang.view(1, pred_ang.shape[0], -1)).cpu().detach().num...
5,337,137
def save_token(token: str) -> None: """Store the token in the cache.""" cachedir = Path(platformdirs.user_cache_dir(APP_NAME)) tokencache = cachedir / "token" tokencache.parent.mkdir(exist_ok=True) tokencache.write_text(token)
5,337,138
def batchmark(avatar_list_path: str, getchu_data_path: str, list_output_path: str, avatar_output_path: str) -> None: """ :return: """ years = utils.get_release_years_hot_map(avatar_list_path, getchu_data_path) with open(avatar_list_path) as fin: avatar_path = fin.readlines() avatar_path = list(map(lamb...
5,337,139
def close_sessions(tsm: SMContext): """ Resets and Closes all the NI-SCOPE instruments sessions from the pinmap file associated with the Semiconductor Module Context. Args: tsm (SMContext): TestStand semiconductor module context """ sessions = tsm.get_all_niscope_sessions() for sess...
5,337,140
def plot_precision_recall_at_k( predicate_df, idx_flip, max_k=100, give_random=True, give_ensemble=True ): """ Plots precision/recall at `k` values for flipped label experiments. Returns an interactive altair visualisation. Make sure it is installed beforehand. Arguments: predicate_df: the...
5,337,141
def has_permissions( permissions: int, required: List[Union[int, BasePermission]] ) -> bool: """Returns `True` if `permissions` has all required permissions""" if permissions & Administrator().value: return True all_perms = 0 for perm in required: if isinstance(perm, int): ...
5,337,142
def input_to_stations(inout_folder,file_in,file_out,forced_stations=[],v=0): """ Convert DiFX/.input into CorrelX/stations.ini. Parameters ---------- inout_folder : str path to folder containing .input file, and where newly created stations.ini file will be placed. file_in : str ...
5,337,143
def mat_to_xyz(mat: NDArrayFloat) -> NDArrayFloat: """Convert a 3D rotation matrix to a sequence of _extrinsic_ rotations. In other words, 3D rotation matrix and returns a sequence of Tait-Bryan angles representing the transformation. Reference: https://en.wikipedia.org/wiki/Euler_angles#Rotation_matr...
5,337,144
def get_user_gravatar(user_id): """ Gets link to user's gravatar from serializer. Usage:: {% get_user_gravatar user_id %} Examples:: {% get_user_gravatar 1 %} {% get_user_gravatar user.id %} """ try: user = User.objects.get(pk=user_id) except User.DoesNo...
5,337,145
def natural_key(s): """Converts string ``s`` into a tuple that will sort "naturally" (i.e., ``name5`` will come before ``name10`` and ``1`` will come before ``A``). This function is designed to be used as the ``key`` argument to sorting functions. :param s: the str/unicode string to convert. ...
5,337,146
def read_ValidationSets_Sources(): """Read and return ValidationSets_Sources.csv file""" df = pd.read_csv(data_dir + 'ValidationSets_Sources.csv',header=0, dtype={"Year":"str"}) return df
5,337,147
def igcd_lehmer(a, b): """Computes greatest common divisor of two integers. Euclid's algorithm for the computation of the greatest common divisor gcd(a, b) of two (positive) integers a and b is based on the division identity a = q*b + r, where the quotient q and the remainder r are in...
5,337,148
def init(start): """Initializes n.""" global n n = start print "Input is", n
5,337,149
def delete_records(connection): """Delete comment record.""" execute_query(connection, delete_comment)
5,337,150
def regular_polygon_area_equivalent_radius(n, radius=1.0): """ Compute equivalent radius to obtain same surface as circle. \theta = \frac{2 \pi}{n} r_{eqs} = \sqrt{\frac{\theta r^2}{\sin{\theta}}} :param radius: circle radius :param n: number of regular polygon segments :return...
5,337,151
def get_dashboard_list(project_id=None, page=1, page_size=25, token_info=None, user=None): """Get a list of dashboards :param project_id: Filter dashboards by project ID :type project_id: str :param user_id: Filter dashboards by user ID :type user_id: str :param limit: Limit the dashboards ...
5,337,152
def test_non_iterable_relations(): """Test that ValueError is raised if link data has a non-iterable object for relations. 1. Create a link parser for a dictionary with non-iterable relations. 2. Try to call parse_relations method. 3. Check that ValueError is raised. 4. Check the error message. ...
5,337,153
def get_download_link(url, quality_type=2, get_dlink_only=True, is_merge=False, is_remain=True): """ 获取视频链接 :param url: 源地址 :param quality_type:分辨率类型(1: lowChapters 2: chapters 3: chapters2 4: chapters3 5: chapters4) :param get_dlink_only: 是否仅获取链接 :param is_merge: 是否合并分段视频 :param is_remain: ...
5,337,154
def create_document(Content=None, Requires=None, Attachments=None, Name=None, VersionName=None, DocumentType=None, DocumentFormat=None, TargetType=None, Tags=None): """ Creates a Systems Manager (SSM) document. An SSM document defines the actions that Systems Manager performs on your managed instances. For more...
5,337,155
def set(launcher, command): """Set a launcher""" config.launchers.writable[launcher] = command config.launchers.write()
5,337,156
def _ssim(X, Y, filter, K=(0.01, 0.03)): """ Calculate ssim index for X and Y""" K1, K2 = K # batch, channel, [depth,] height, width = X.shape C1 = K1 ** 2 C2 = K2 ** 2 filter = filter.to(X.device, dtype=X.dtype) mu_x = gaussian_filter(X, filter) mu_y = gaussian_filter(Y, filter) ...
5,337,157
def get_all_messages(notification_queue, **kwargs): """ Get all messages on the specified notification queue Variables: complete_queue => Queue to get the message from Arguments: None Data Block: None Result example: [] # List of messages """ resp_lis...
5,337,158
def ssa_reconstruct(pc, v, k): """ from Vimal Series reconstruction for given SSA decomposition using vector of components :param pc: matrix with the principal components from SSA :param v: matrix of the singular vectors from SSA :param k: vector with the indices of the components to be reconstr...
5,337,159
def loadImtoolrc(imtoolrc=None): """ Locates, then reads in IMTOOLRC configuration file from system or user-specified location, and returns the dictionary for reference. """ # Find the IMTOOLRC file. Except as noted below, this order # matches what ximtool and ds9...
5,337,160
def get_theo_joints_pm(W, b, beta): """calculate the theoretical state distribution for a Boltzmann machine """ N = len(b) joints = [] states = get_states(N) for s in states: joints.append(np.exp(-1. * get_energy(W, b, (2. * s - 1.), beta))) joints /= np.sum(joints) return j...
5,337,161
def tail(the_file: BinaryIO, lines_2find: int = 20) -> list[bytes]: """ From http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail """ lines_found: int = 0 total_bytes_scanned: int = 0 the_file.seek(0, 2) bytes_in_file: int = the_file.tell() wh...
5,337,162
def add_device_tag_command(client, args): """ Command to add tag to an existing admin devices entry """ site, concentrator, map = get_site_params() transmitter_id = args.get('transmitter_id') tag = args.get('tag') result = client.add_device_tag(site=site, concentrator=concentrator, map=map, ...
5,337,163
def CommaSeparatedFloats(sFloatsCSV): """Read comma-separated floats from string. [sFloatsCSV]: string, contains comma-separated floats. <retval>: list, floats parsed from string. """ return [float(sFloat) for sFloat in sFloatsCSV.replace(" ","").split(",")]
5,337,164
def merge_channels(image_list): """ Merge channels of multiple scalar ANTsImage types into one multi-channel ANTsImage ANTsR function: `mergeChannels` Arguments --------- image_list : list/tuple of ANTsImage types scalar images to merge Returns ------- ANTsIma...
5,337,165
def get_var(name: str, options: dict) -> str: """ Returns the value from the given dict with key 'INPUT_$key', or if this does not exist, key 'key'. """ return options.get('INPUT_{}'.format(name)) or options.get(name)
5,337,166
def get_filenames(is_training, data_dir, num_files=1014): """Return filenames for dataset.""" if is_training: return [ os.path.join(data_dir, "train-%05d-of-01014" % i) for i in range(num_files) ] else: return [ os.path.join(data_dir, "validation-%05d-of-00128...
5,337,167
def clear_reaction_role_message(message: discord.Message, emoji: typing.Union[discord.Emoji, str]): """ Removes the message for a reaction role :param message: Message that has the reaction role :param emoji: Emoji for the reaction role """ global guilds, raw_settings combo_id = str(messag...
5,337,168
def create_txt_response(name, txt_records): """ Returns an RRSet containing the 'txt_records' as the result of a DNS query for 'name'. This takes advantage of the fact that an Answer object mostly behaves like an RRset. """ return dns.rrset.from_text_list(name, 60, "IN", "TXT", txt_records)
5,337,169
def test_crps_gaussian_on_test_set(supply_test_set): """Test CRPS on the test set for some dummy values.""" assert np.abs(crps_gaussian(*supply_test_set) - 0.59080610693) < 1e-6
5,337,170
def FatalTimeout(max_run_time): """ContextManager that exits the program if code is run for too long. This implementation is fairly simple, thus multiple timeouts cannot be active at the same time. Additionally, if the timeout has elapsed, it'll trigger a SystemExit exception within the invoking code, ultim...
5,337,171
def bit_xor(*arguments): """ Bitwise XOR function. """ return ast.BitXor(*arguments)
5,337,172
def create_compile_order_file(project_file, compile_order_file, vivado_path=None): """ Create compile file from Vivado project """ print( "Generating Vivado project compile order into %s ..." % abspath(compile_order_file) ) if not exists(dirname(compile_order_file)): mak...
5,337,173
def test_uncollectable_incref(testdir): """ Test with the Yagot plugin enabled for uncollectable objects and uncollectable object produced with increased reference count. """ test_code = """ import sys import gc import yagot import test_leaky def test_leak(): l1 = [1, 2]...
5,337,174
def remove_r(file_new, file_old, file_save): """从file_new文件中去除file_old中的重复行,并将结果保存在file_save文件中。 注意文件读取时的编码转换。 """ file_dir = _temp_file_path file_new = os.path.join(_temp_file_path, file_new) file_old = os.path.join(_temp_file_path, file_old) file_save = os.path.join(_temp_file_path, file_s...
5,337,175
def get_chromiumdir(platform, release): """ Args: platform (str): a sys.platform str Returns: str: path to Chromium User Data Directory http://www.chromium.org/user-experience/user-data-directory """ if platform == 'darwin': chromedir = os.path.expanduser( '...
5,337,176
def make_ts_scorer( score_func, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs, ): """Make a scorer from a performance metric or loss function. This factory function wraps scoring functions for use in `~sklearn.model_selection.GridSearchCV` and `~sklearn.model_selection.cros...
5,337,177
def pfas(x): """Parse a JSON array of PFA expressions as a PFA abstract syntax trees. :type x: open JSON file, JSON string, or Pythonized JSON :param x: PFA expressions in a JSON array :rtype: list of titus.pfaast.Expression :return: parsed expressions as a list of abstract syntax trees """ ...
5,337,178
def overlap(x, y, a, b): """Finds the overlap of (x, y) and (a, b). Assumes an overlap exists, i.e. y >= a and b >= x. """ c = clamp(x, a, b) d = clamp(y, a, b) return c, d
5,337,179
def topological_sort(g): """ Returns a list of vertices in directed acyclic graph g in topological order. """ ready = [] topo = [] in_count = {} for v in g.vertices(): in_count[v] = g.degree(v, outgoing=False) if in_count[v] == 0: # v has no constraints, i.e no incomin...
5,337,180
def probability_of_failure_in_any_period(p, n): """ Returns the probability that a failure (of probability p in one period) happens once or more in n periods. The probability of failure in one period is p, so the probability of not failing is (1 - p). So the probability of not failing o...
5,337,181
def stage_1(transformed_token_list): """Checks tokens against ngram to unigram dictionary""" dict_data = pd.read_excel(v.stage_1_input_path, sheet_name=v.input_file_sheet_name) selected_correct_token_data = pd.DataFrame(dict_data, columns=v.stage_1_input_file_columns) transformed_state_1 = [] for se...
5,337,182
def _perform_sanity_checks(config, extra_metadata): """ Method to perform sanity checks on current classification run. :param config: dirbs config instance :param extra_metadata: job extra metadata dict obj :return: bool (true/false) """ curr_conditions = [c.as_dict() for c in config.condit...
5,337,183
def get_key_from_id(id : str) -> str: """ Gets the key from an id. :param id: :return: """ assert id in KEYMAP, "ID not found" return KEYMAP[id]
5,337,184
def CreateFromDict(registration_dict): """Returns the content of the header file.""" template = string.Template("""\ // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated b...
5,337,185
def cmu_indic(corpus_dir: Pathlike, output_dir: Pathlike): """CMU Indic data preparation.""" prepare_cmu_indic(corpus_dir, output_dir=output_dir)
5,337,186
def controller_add_raw_commands_not_privileged(): """ This view allows a client to send a raw command to a CISCO device in not privileged EXEC mode :return: <dict> result of the operation. check documentation for details """ # TODO: convert print screens to app.logger.debug("message") pri...
5,337,187
def static_message_fixture(tmpdir_factory, prefix, message, suffix): """A fixture which provides a static message.""" filename = tmpdir_factory.mktemp('data').join('static_message.txt').strpath file_contents = "{0}{1}{2}".format(prefix, message, suffix) with open(filename, 'w') as f: f.write(f...
5,337,188
def entropy_image(filename,bins=30): """ extracts the renyi entropy of image stored under filename. """ img = cv2.imread(filename,0)/255.0 # gray images p,_ = np.histogram( img, range=[0.0,1.0],bins=bins ) return -np.log(np.dot(p,p)/(np.sum(p)**2.0))
5,337,189
def satisfies_constraint(kel: dict, constraint: dict) -> bool: """Determine whether knowledge graph element satisfies constraint. If the constrained attribute is missing, returns False. """ try: attribute = next( attribute for attribute in kel.get("attributes", None) or ...
5,337,190
def static_unroll(core, input_sequence, initial_state, time_major=True): """Performs a static unroll of an RNN. An *unroll* corresponds to calling the core on each element of the input sequence in a loop, carrying the state through:: state = initial_state for t in range(len(input_sequence)): ...
5,337,191
def setup_argparse(parser: argparse.ArgumentParser) -> None: """Main entry point for subcommand.""" subparsers = parser.add_subparsers(dest="case_cmd") setup_argparse_list(subparsers.add_parser("list", help="List cases.")) setup_argparse_list_import( subparsers.add_parser("list-import-info", he...
5,337,192
def getElementByClass(className: str, fileName: str) -> List[Tuple[int, str]]: """Returns first matching tag from an HTML/XML document""" nonN: List[str] = [] with open(fileName, "r+") as f: html: List[str] = f.readlines() for line in html: nonN.append(line.replace("\n", "")) ...
5,337,193
def sms_outbound_gateway(): """ SMS Outbound Gateway selection for the messaging framework """ # CRUD Strings s3.crud_strings["msg_sms_outbound_gateway"] = Storage( label_create = T("Create SMS Outbound Gateway"), title_display = T("SMS Outbound Gateway Details"), title_list = T("SM...
5,337,194
def write_graph(g, json_file): """Write networkx graph to JSON. :param g: networkx graph :type networkx.Graph :param json_file: path to dump JSON graph :type: string """ d = nx.readwrite.json_graph.node_link_data(g) with open(json_file, 'w') as f: json.dump(d, f) return
5,337,195
def _insert_volume(_migration, volume_number, volume_obj): """Find or create the corresponding volume, and insert the attribute.""" volumes = _migration["volumes"] volume_obj = deepcopy(volume_obj) volume_obj["volume"] = volume_number volumes.append(volume_obj) return volume_obj
5,337,196
def create_vnet(credentials, subscription_id, **kwargs): """ Create a Batch account :param credentials: msrestazure.azure_active_directory.AdalAuthentication :param subscription_id: str :param **resource_group: str :param **virtual_network_name: str :param **subnet_na...
5,337,197
def to_inorder_iterative(root: dict, allow_none_value: bool = False) -> list: """ Convert a binary tree node to depth-first in-order list (iteratively). """ node = root node_list = [] stack = [] while node or len(stack) > 0: if node: stack.append(node) # push a node into...
5,337,198
def test_plaintext_and_anoncrypt_raises_error(alice): """Test specifying both plaintext and anoncrypt raises an error.""" with pytest.raises(ValueError): alice.pack({"test": "test"}, plaintext=True, anoncrypt=True)
5,337,199