content
stringlengths
22
815k
id
int64
0
4.91M
def split_addresslines( lines ): """ Split up to 4 lines into appropiate fields (org, dept, street 1/2) """ data = { 'organisation': '', 'department': '', 'street_1': '', 'street_2': '', } if len(lines) == 0: pass elif len(lines) == 1: data['s...
71,200
def supported_format(): """ give supported formats """ if not bool(__supported_format__): modules = glob.glob(join(dirname(__file__), "*.py")) module_name = [Path(local_file) for local_file \ in modules if not '__init__' in local_file] # import module ...
71,201
def test_sample_shape_array_arguments_2d_sample_shape(rng_key, case): """Test the correctness of broadcasting when arguments can be arrays and sample size is not empty""" samples = MvNormal(case["mu"], case["covariance_matrix"]).sample( rng_key, case["sample_shape"] ) assert samples.shape ==...
71,202
def _make_edge_trace(graph_nx: nx.Graph, pos: dict) -> Scatter: """(HELPER) This function is a helper function to visualize_graph_with_attributes. Return a trace containing lines which represent edges between nodes given the position of nodes in pos. """ x_edges = [] y_edges = [] for edge...
71,203
def msgreply_save_handler(sender, instance, **kwargs): """ Handle sending notification to '@<user>' when reply messages. """ from_email = instance.from_email reply_msg = instance.message innerpub_msg = instance.reply_to to_user = '' m = re.match(at_pattern, reply_msg) if m: ...
71,204
def compare_misclf_pairwise(cfmat_array, class_labels, method_labels, out_path): """ Produces a cobweb plot comparing the the misclassfication rate of all feature sets for different pairwise classifications. Parameters ---------- cfmat_array class_labels method_labels out_path ...
71,205
def test_metrics_mappings_oas2(import_oas, oas): """Checks imported metrics - oas2""" if oas['type'] == 'oas3': pytest.skip("This testcase is oas2 only.") service = import_oas[3] metrics = service.metrics.list() mappings = service.proxy.list().mapping_rules.list() metr_number = 0 f...
71,206
def import_tnmr(path): """ Import tnmr data and return dnpdata object Args: path (str) : Path to .jdf file Returns: tnmr_data (object) : dnpdata object containing tnmr data """ attrs = import_tnmr_pars(path) values, coords, dims = import_tnmr_data(path) tnmr_data = dn...
71,207
def focal_loss( y_true, y_pred, alpha=[1-0.25, 0.25], gamma=2.0, from_logits=False ): """ Computes the multi-class focal loss, with class balancing parameter. Parameters ---------- y_true : tensor Targets of shape [num_targets...
71,208
def can_run_c_extension(name=None): """ Determine whether the given Python C extension loads correctly. If ``name`` is ``None``, tests all Python C extensions, and return ``True`` if and only if all load correctly. :param string name: the name of the Python C extension to test :rtype: bool ...
71,209
def _merge_surrogates(text): """Returns a copy of the text with all surrogate pairs merged""" return _decode_surrogatepass( text.encode("utf-16-le", _surrogatepass), "utf-16-le")
71,210
def findChessboards(imageDirectory): """ Calculates the object points and image points of chessboard images :param imageDirectory: the directory to look through for chessboard images :return: names of the files, the object points list, the image points list, resolution of the camera """ #out_fil...
71,211
def show_nums_to_user(): """ 093 Ask the user to enter five numbers. Sort them into order and present them to the user. Ask them to select one of the numbers. Remove it from the original array and save it in a new array. :return: new array with one (popped) item. """ arr, trigger = [], 5...
71,212
def player(board): """ Returns player who has the next turn on a board. """ if terminal(board): return elif board == initial_state(): return X else: no_of_X = 0 no_of_O = 0 for row in board: no_of_X += row.count("X") no_of_O += row....
71,213
def seq_type(seq): """ Determines whether a sequence consists of 'N's only (i.e., represents a gap) """ return 'gap' if set(seq.upper()) == {'N'} else 'bases'
71,214
def get_rows_and_columns(num_plots: int) -> Tuple[int, int]: """Get optimal number of rows and columns to display figures. Parameters ---------- num_plots : int Number of subplots Returns ------- rows : int Optimal number of rows. cols : int Optimal number of co...
71,215
def get_fixture_decorator(node: AnyFunctionDef) -> Union[ast.Call, ast.Attribute, None]: """ Returns a @pytest.fixture decorator applied to given function definition, if any. Return value is either: * ast.Call, if decorator is written as @pytest.fixture() * ast.Attribute, if decorator is written as...
71,216
def do__AcmeV2_AcmeOrder__acme_server_sync( ctx, dbAcmeOrder=None, authenticatedUser=None, ): """ :param ctx: (required) A :class:`lib.utils.ApiContext` instance :param dbAcmeOrder: (required) A :class:`model.objects.AcmeOrder` object to refresh against the server :param authenticatedUser: (...
71,217
def test5(mocked_function): """Pátý test se opět snaží zkombinovat fake a stub.""" # vytiskneme informaci o tom, zda se mockovaná funkce zavolala print("mocked function called: {c}".format(c=mocked_function.called)) print(application.function1()) # opět vytiskneme informaci o tom, zda se mockovaná f...
71,218
def static_equilibrium(topology, tmax=100, eta=1e-6, verbose=False, callback=None): """ Generate a form diagram in static equilibrium. Parameters ---------- topology : :class:`compas_cem.diagrams.TopologyDiagram` A topology diagram. tmax : ``int``, optional Maximum number of ite...
71,219
def chooselabelsubset(lst, n, method): """Chooses a subset of the given list, using the given method: start: from the beginning end: from the end random: randomly """ from random import shuffle # pick the the trainpos and trainneg sets def randindexes(lst): """R...
71,220
def create_logger() -> logging.Logger: """ Creates a logging object to be used for reports. """ # Gets a logger object with the name 'gol_logger' and sets the log level to INFO. # # Sets an absolute path log_path to the log file _Resources/gol.log, then runs # logging.FileHandler to set up a file h...
71,221
def s_quantifier(num, quantifier): """S quantifier.""" return quantifier_selector(num, quantifier, f'{quantifier}s')
71,222
def set_proxy(proxy): """Set HTTP/SOCKS proxy to requests/aiohttp""" _create_aiohttp_session() pr = { 'http': proxy, 'https': proxy } _requests_session.proxies.update(pr) _aiohttp_session.set_proxy(proxy) _proxy.proxy = proxy
71,223
def get_monitor_info_a(h_monitor): """ BOOL GetMonitorInfoA( HMONITOR hMonitor, LPMONITORINFO lpmi ); """ return __get_monitor_info(WINDLL.user32.GetMonitorInfoA, h_monitor)
71,224
def test_search(): """ >>> path = os.path.dirname(__file__) >>> packages = os.path.join(path, 'packages') >>> call('ido search pkg1 -i %s --nocolor' % packages) # doctest:+ELLIPSIS pkg1 <BLANKLINE> """
71,225
def test_create_stat_modifier(game_config, rom_data): """ Test the create_stat_modifier function """ for version in {FEVersions.FE6, FEVersions.FE7, FEVersions.FE8}: stat_mod = create_stat_modifier(game_config, rom_data, version) assert isinstance(stat_mod, VERSION_MAP["stat_mod"][version])
71,226
def textdeskew(image): """ Function that calculates a the rotation angle for documents that are already properly scanned. Using the angle, it tries to deskew. Useful in cases where there is no difference between foreground and background, and the document is properly scanned. """ gray = cv2.cvtColor(image, cv...
71,227
def group_arguments(seq, group=254): """ group the list into lists of 254 items each. This is due to argument restrictions in python. http://docs.djangoproject.com/en/dev/topics/http/urls/#patterns """ return (seq[pos:pos + group] for pos in range(0, len(seq), group))
71,228
def get_reduction_mask(inputs: List[Union[Chord, Key]], kwargs: Dict = None) -> List[bool]: """ Return a boolean mask that will remove repeated inputs when applied to the given inputs list as inputs[mask]. Parameters ---------- inputs : List[Union[Chord, Key]] A List of either Chord or ...
71,229
def generate_requirement_image( learn_guide_project, ): # pylint: disable=too-many-statements """Generate a single requirement image""" def make_line( requirement_name, position=(0, 0), icon=None, hidden=False, triangle_icon=None ): # pylint: disable=too-many-branches if triangle_icon...
71,230
def main(args): """load json file""" name_box_id = defaultdict(list) id_name = dict() with open(args.json_file_path, encoding='utf-8') as f: data = json.load(f) """generate labels""" images = data['images'] annotations = data['annotations'] real_names = os.listdir(args.images_di...
71,231
def resolve(hostname: str) -> Optional[str]: """ Get the IP address of a subdomain """ with contextlib.suppress(socket.gaierror): return socket.gethostbyname(hostname)
71,232
def get_researcher_allowed_studies(request: ResearcherRequest) -> List[Dict]: """ Return a list of studies which the currently logged-in researcher is authorized to view and edit. """ kwargs = {} if not request.session_researcher.site_admin: kwargs = dict(study_relations__researcher=request....
71,233
def fast_non_dominated_sort(values1, values2): """ Function to carry out NSGA-II's fast non dominated sort """ S = [[] for i in range(0, len(values1))] front = [[]] n = [0 for i in range(0, len(values1))] rank = [0 for i in range(0, len(values1))] for p in range(0, len(values1)): S[p] =...
71,234
def generate_list(n,idx_excl,n_rand): """ random_array = generate_list(n,idx_excl,n_rand) Generates a list Parameters ---------- n : INT, total number of samples idx_excl : 2D array, start,stop index for each seizure n_rand : INT, number of random samples Returns ------- 1D...
71,235
def run_face_swap(from_image, to_image, output_filename): """Switch faces between two input images using dlib and OpenCV.""" # Credits to https://github.com/spmallick/ try: img1 = read_url_or_local_image(from_image, im_format='cv2') img2 = read_url_or_local_image(to_image, im_format='cv2') ...
71,236
def _neighboring_points(o_index, i_index, e_len, f_len): """ A function that returns list of neighboring points in an alignment matrix for a given alignment (pair of indexes) """ result = [] if o_index > 0: result.append((o_index - 1, i_index)) if i_index > 0: result.append(...
71,237
def pose_estimate(event, context): """Perform human pose estimation.""" try: # Get image from the request picture, filename = fetch_input_image(event) image = load_image(picture) print('Loading model') model = Model(MODEL_PATH) print('Predicting pose')...
71,238
def CreateAssocVarPairs(rappor_metrics): """Yield a list of pairs of variables that should be associated. For now just do all (string x boolean) analysis. """ var_pairs = collections.defaultdict(list) for metric, var_list in rappor_metrics.iteritems(): string_vars = [] boolean_vars = [] # Separ...
71,239
def patch_tile(rgb_file, gt_file, patch_size, pad, overlap): """ Extract the given rgb and gt tiles into patches :param rgb_file: path to the rgb file :param gt_file: path to the gt file :param patch_size: size of the patches, should be a tuple of (h, w) :param pad: #pixels to be padded around e...
71,240
def function_tester(rng, func, ref_func, inputs, func_args=[], func_kwargs={}, atol_f=1e-6, atol_b=1e-3, atol_accum=1e-6, dstep=1e-3, backward=None, ctx=None, func_name=None, ref_grad=None, disable_half_test=False): """ Automatic testing of forward/backwar...
71,241
def show(x, y, xlabel="X", ylabel="Y", title=None): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are both numeric (SArray of int or f...
71,242
def read_text(unformatted_text: str) -> str: """Open text from the file or read it directly. Arguments: unformatted_text (str): path to a file OR inputed text Returns: str: reads and returns text as a string """ try: with open(unformatted_text, "rt") as f: # cre...
71,243
def regions(**kw_params): """ Get all available regions for the EC2 service. You may pass any of the arguments accepted by the VPCConnection object's constructor as keyword arguments and they will be passed along to the VPCConnection object. :rtype: list :return: A list of :class:`boto.ec2....
71,244
def read_from_txt(txt_file: str = "untitled.txt") -> list: """Opens a text file to get all words, called from outside the class instantiation""" with open(txt_file, "r") as words: lines = words.readlines() return [ line.split(".")[1].strip().upper() for line in lines ]
71,245
def extensionOP(extension): """ Get an extension's associated operator :param extension: the extension :return: the DAT source of extension or the internal parameters' comp or None if undetermined """ eop = None if isinstance(extension, ParCollection): # assume internal parameters eop = extension.stdswi...
71,246
def _integerize(json_data, word_to_id, dataset): """Transform words into integers.""" sequences = np.full((len(json_data), MAX_TOKENS_SEQUENCE[dataset]), word_to_id[PAD], np.int32) sequence_lengths = np.zeros(shape=(len(json_data)), dtype=np.int32) for i, sentence in enumerate(json_data): ...
71,247
def test_CD_diagram_wrong_input_float(): """ Testing the CD_diagram function with the wrong dataframe input (float) """ with pytest.raises(AttributeError): cd_diagram = saveCD(5.5)
71,248
def enqueue_getch(input_queue: Queue, kbhit: KBHit): """ Enqueue getch data from KBHit object """ while True: try: new_input = kbhit.getch() if new_input == '\x1b': raise ClientTerminationEvent elif new_input is not None: input_queue.pu...
71,249
def algo(coin): """ gets the coin implementation algorithm""" click.echo(algo_request_to_url(coin))
71,250
def snyk_report(): """ {'CVSSv3': 'CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H', 'alternativeIds': [], 'creationTime': '2019-10-22T12:22:54.665794Z', 'credit': ['Roman Burunkov'], 'cvssScore': 9.8, 'description': '## Overview\n' '\n' '[express-fileupl...
71,251
def pytest_addoption(parser): """ Pytest hook to add an option to the argument parser. :param parser: Parser for command line arguments and ini-file values. :type parser: :class:`Parser` """ PLUGIN.add_report_option(parser.addoption) group = parser.getgroup( "Force f...
71,252
def plot_pq_all(mean_arr, std_arr, label_list, title='QP_accu', metric='rmse', ax=None, colors=None, alpha=0.5): """Generate a summary QP plots with different methods. Args: mean_arr (np.ndarray): Mean performance of each method at a certain quantile, (#methods, #quantiles)....
71,253
def rechannel(channels): """A data node to rechannel data. Parameters ---------- channels : int or list The channel mapping. Receives ------ data : ndarray The original signal. Yields ------ data : ndarray The rechanneled signal. """ if channels...
71,254
def create_tag_documentation(rest_api_id, api_fns): """ Creates tag documentation for a given list of functions. """ for api_fn in api_fns: path = api_fn.path http_method = api_fn.http_method already_exists = _tag_documentation_exists(rest_api_id, path, http_method) if no...
71,255
def prepare_traveler_from_raw_data(trips: list): """ Construct a traveler by combining a list of single trips :param trips: :return: """ traveler_chekins = [] for trip in trips: traveler_chekins = traveler_chekins + generate_checkins(trip) return sorted(traveler_chekins, key=lamb...
71,256
def test_code_as_string(): """Test error with a string code.""" _err = TeslaException("dummy") assert not _err is None assert _err.code == "dummy" assert _err.message == "dummy"
71,257
def spglib_get_primitive(struct, **kwds): """Find primitive structure for given :class:`~pwtools.crys.Structure`. If `struct` is irreducible (is already a primitive cell), we return None, else a Structure. Uses spglib. Parameters ---------- struct : Structure **kwds : keywords ...
71,258
def plot_loss(n_epochs, train_loss, val_loss, filename): """Plot the losses of a training over the epochs. Parameters ---------- n_epochs : list of int The range of epochs of the training. train_loss : list of float The training loss. val_loss : list of float The validat...
71,259
async def async_query_for_ptr_with_proto(protocol, ips_to_lookup): """Send and receiver the PTR queries.""" time_outs = 0 query_for_ip = {} for ip in ips_to_lookup: req = async_generate_ptr_query(ip) query_for_ip[ip] = req.id try: await asyncio.wait_for( ...
71,260
def test_bucketing_with_specials(df): """Test that specials propogate.""" num_cols = ["LIMIT_BAL", "BILL_AMT1"] cat_cols = ["EDUCATION", "MARRIAGE"] X = df[num_cols + cat_cols] y = df["default"].values the_specials = {"LIMIT_BAL": {"=400000.0": [400000.0]}} bucketing_process = BucketingPro...
71,261
def fft_shift_phasor_2d(shape, offset, grad=False): """Return phasor array used to shift an array (in real space) by multiplication in fourier space. Parameters ---------- shape : (int, int) Length 2 iterable giving shape of array. offset : (float, float) Offset in array ele...
71,262
def get_ar(bbox): """ :param bbox: top left, right down :return: aspect ratio """ [x1, y1, x2, y2] = bbox return (y2 - y1) / (x2 - x1)
71,263
async def test_sensor_entity_disabled_when_null( hass, mock_config_entry_data, mock_config_entry ): """Test sensor disables data with null by default.""" api = get_mock_device() api.data.available_datapoints = [ "active_power_l2_w", "active_power_l3_w", "total_gas_m3", ] ...
71,264
def log_p_xi(meanLike, covarLike, xi): """ Calculate log-likelihood of a single xi, given its mean/covar after collapsing P(A | X_{-i}, Z) """ D = float(xi.shape[1]) ll = -(D / 2) * np.log(covarLike) ll -= (1 / (2 * covarLike)) * np.power(xi - meanLike, 2).sum() return ll.item()
71,265
def get_statsTable(dType, dFreq, df, dates_as_index=True, ptiles=None): """ Construct detailed tables with summary statistics. Parameters ___________ dType : str Dataset type of the portfolios. Possible choices are: * ``Returns`` * ``Factors`` * ``NumFir...
71,266
def has_parameter(param_key_matcher, param_value_matcher): """Check values of the stacks parameters.""" return StackParameterMatcher(wrap_matcher(param_key_matcher), wrap_matcher(param_value_matcher))
71,267
def get_run_files_from_formatter(run_id, formatter, **kwargs): """Get a set of files for a particular run Parameters ---------- run_id : `str` The number number we are reading formatter : `FilenameFormat` Object that constructs the file naem kwargs Passed to formatter ...
71,268
def create_assigment_rule(sbml_model: libsbml.Model, assignee_id: str, formula: str, rule_id: str = None, rule_name: str = None) -> libsbml.AssignmentRule: """Create SBML AssignmentRule Arguments: sb...
71,269
def regula_falsi(f: Function, xi: float, xf: float, tol: float, iter: bool = False) -> float: """ Regula Falsi ============ Regula falsi method to find a root of a function Parameters ---------- f : Function Function xi : float First point xf : float Sec...
71,270
def repl(): """ call this function to give you a pdb shell while the program is running. You will be dropped in the current context. """ def replFunc(): pdb.set_trace() replThread = Thread(target=replFunc) replThread.start()
71,271
def SelectCard(): # Method Description: """Selects A Card Using A Terminal As UI""" # Endless Loop Till User Enters A Valid Card Number while(True): # Prompt user to select card i= int(input("Please choose a card: ")) # If the position entered is correct if (i >...
71,272
def temperature_salinity_timeseries( temperature, salinity, colors, data_date, prediction, bloom_dates, titles, ): """Create a time series plot figure object showing temperature on the left axis and salinity on the right. """ fig = matplotlib.figure.Figure(figsize=(15, 4.25), facecolor=colors['bg'])...
71,273
def readCSVfile(fileName): """twitter_follower_yyyymmdd_hhMMss.csv を開く""" lines = pandas.read_csv(fileName, encoding="utf8") return lines
71,274
def test_transaction_rollback(db, commit_event, rollback_event): """Test that a rollback transaction rolls back.""" with db.transaction(rollback=True): db.add(AModel()) assert commit_event.call_count == 0 assert rollback_event.call_count == 1
71,275
def test_collated_task_dataset_sample_features_shape(collated_task_dataset): """Check CollatedTaskDataset.sample_features_shape return value.""" assert collated_task_dataset.sample_features_shape == ()
71,276
def return_testvideo_path(): """ returns Test video path """ path = "{}/Downloads/Test_videos/BigBuckBunny_4sec.mp4".format( tempfile.gettempdir() ) return os.path.abspath(path)
71,277
def validate_image_pull_credentials(image_pull_credentials): """ Validate ImagePullCredentialsType for Project Property: Environment.ImagePullCredentialsType """ VALID_IMAGE_PULL_CREDENTIALS = ("CODEBUILD", "SERVICE_ROLE") if image_pull_credentials not in VALID_IMAGE_PULL_CREDENTIALS: ...
71,278
def dynamic_import_st(module, backend): """Import ST models dynamically. Args: module (str): module_name:class_name or alias in `predefined_st` backend (str): NN backend. e.g., pytorch, chainer Returns: type: ST class """ model_class = dynamic_import(module, predefined_st....
71,279
def run_once(model, saver, summary_writer, summary_op): """Evaluates the latest model checkpoint. Args: model: Instance of ShowAndTellModel; the model to evaluate. saver: Instance of tf.train.Saver for restoring model Variables. summary_writer: Instance of FileWriter. summary_op: Op for generating ...
71,280
def num_bits(i): """Returns the number of bits in an unsigned integer.""" n = 0 while i: n += 1 i &= i - 1 return n
71,281
def do_nothing(*_): """Does nothing. For use with ``mock.patch``."""
71,282
def configure_username(device, username, pwd, encryption=0): """ Configure a user with a password Args: device (`obj`): Device object username (`str`): User name pwd ('str'): Password for the user encryption ('int',optional): Encryption level (Default 0 for cl...
71,283
def get_args(): """parse arguments :returns: parsed arguments """ #Command line arguments parser. Described as in their 'help' sections. parser = argparse.ArgumentParser(description="Replication of Zaremba et al. (2014).\ \n https://arxiv.org/abs/1409.2329") parser.add_argument("--layer...
71,284
def available_solvers(): """Returns a list of all available solvers. These can be used in :func:'optunity.make_solver'. """ return solver_registry.solver_names()
71,285
def coefficient_of_drag_adjusted(state, only_in_range=False): """ Calculate the coefficient of drag. The drag is calculated by a bilinear interpolation from values spaced evenly through Mach values and log10 Reynolds numbers. These values were initially computed from one of the other methods, but ...
71,286
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "192.168.1.123", CONF_MAC: "aabbccddeeff"}, )
71,287
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None): """Instantiates a placeholder tensor and returns it. # Arguments shape: Shape of the placeholder (integer tuple, may include `None` entries). ndim: Number of axes of the tensor. At least one of ...
71,288
def action_logging(f): """ Decorator to log user actions """ @functools.wraps(f) def wrapper(*args, **kwargs): with create_session() as session: if g.user.is_anonymous: user = 'anonymous' else: user = g.user.username log =...
71,289
def ClassifyWspecifier(wspecifier): """Interprets type / filenames / options for the given wspecifier. Args: wspecifier: A string indicating the wspecifier. Returns: (WspecifierType, archive_filename, script_filename, WspecifierOptions) for the given filename. Examples: ...
71,290
def canonicalize_instance_info(node): """ Convert what is returned from GCE into the butter standard format. """ return Instance( instance_id=node.uuid, public_ip=node.public_ips[0], private_ip=node.private_ips[0], state=node.state)
71,291
def get_track( track_id ): """Returns data of a track having `track_id` No request params. """ try: track = g.user.get_track( track_id ) data = { 'title' : track.title, 'path' : track.path, 'artist' : track.artist, ...
71,292
def _is_rule_exists(nat_rules, rule_type, original_ip, original_port, translated_ip, translated_port, protocol): """ check if we already have some rule with same properties """ # gatewayNatRule properties may be None or string # convert to str, bacause por...
71,293
def lsgan_loss_generator(prob_fake_is_real): """Computes the LS-GAN loss as minimized by the generator. Rather than compute the negative loglikelihood, a least-squares loss is used to optimize the discriminators as per Equation 2 in: Least Squares Generative Adversarial Networks Xudong Mao,...
71,294
def split_by_x(points): """Partitions an array of points into two by x-coordinate. All points with the same x-coordinate should remain on the same side of the partition. All points in the right partition should have strictly greater x-coordinates than all points in the left partition. >>> split_by_...
71,295
def dumps(*args, **kwargs): """ See :func:`json.dumps()`. """ kwargs["ensure_ascii"] = True kwargs["cls"] = _ExtendedJsonEncoder return json.dumps(*args, **kwargs)
71,296
def remove_quoted_text(line): """get rid of content inside quotes and also removes the quotes from the input string""" while line.count("\"") % 2 == 0 and line.count("\"") > 0: first = line.find("\"") second = line.find("\"", first+1) line = line[0:first] + line[second+1:] while ...
71,297
def ryu_from_jsondict(jsondict): """ Load a ryu object from a json dictionary jsondict: A dictionary loaded by json.load """ assert len(jsondict) == 1 for oftype, value in jsondict.items(): cls = getattr(parser, oftype) if issubclass(cls, parser.OFPFlowMod): value["d...
71,298
def test_meter(): """ Tests: * .reset() * .add() * .value() """ meter = meters.PrecisionRecallF1ScoreMeter() # tests the .reset() method, which happens to be called in initialization for key in ["tp", "fp", "fn"]: assert meter.tp_fp_fn_counts[key] == 0, \ ...
71,299