content
stringlengths
22
815k
id
int64
0
4.91M
def plot_multiple_countplots(df, cols): """ Definicion del procedimiento plot_multiple_countplots: Procedimiento para plottear variable numéricas Parametros ---------- df: Pandas Dataframe Dataframe que contiene las variables numéricas cols:...
5,313,600
def credentials(): """Retrieves credentials""" username = os.environ.get('OS_USERNAME') password = os.environ.get('OS_PASSWORD') tenant_name = os.environ.get('OS_TENANT_NAME') auth_url = os.environ.get('OS_AUTH_URL') if not all((username, password, tenant_name, auth_url)): sys.stderr.w...
5,313,601
def CNOT_like_PTM(idx): """ Returns the pauli transfer matrix for gates of the cnot like class (q0) --C1--•--S1-- --C1--•--S1------ | -> | (q1) --C1--⊕--S1-- --C1--•--S1^Y90-- """ assert(idx < 5184) idx_0 = idx % 24 idx_1 = (idx // 24...
5,313,602
def _random_binary_string_matrix(rows, cols, max_length): """Returns a list of lists of random strings""" return [[_random_binary_string_gen(max_length) for _ in range(cols)] for _ in range(rows)]
5,313,603
def test_get_scenario_missing(client): """GET missing system-of-systems model """ response = client.get('/api/v1/scenarios/does_not_exist') data = parse_json(response) assert data['error']['SmifDataNotFoundError'] == ["scenario 'does_not_exist' not found"]
5,313,604
def test_spline_transformer_periodicity_of_extrapolation(knots, n_knots, degree): """Test that the SplineTransformer is periodic for multiple features.""" X_1 = np.linspace((-1, 0), (1, 5), 10) X_2 = np.linspace((1, 5), (3, 10), 10) splt = SplineTransformer( knots=knots, n_knots=n_knots, degree...
5,313,605
def emit_webhook(client, url, job_id="test", worker_id=None, signal="new_judgments", unit_state="finalized", treatment="t10", by_get=True): """ :param client: :param url: (str) relative path to target api :param job_id: (str) :param worker_id: (str) :param signal: (new_judgments|unit_complete) ...
5,313,606
def comment_list_view(request, slug): """ Get post comments from a server Selects the post instance matching the comment slug and then gets all displayed comments that match that post instance. Then we pass the objects we want to use into the serializer. The serializer will take that informati...
5,313,607
def cos(x): """ Takes the cosine of a DualNumber object and returns a DualNumber object with updated value and derivatives. """ x = DualNumber.promote(x) output = x.promote(np.cos(x.value)) # real part of the first parent distributes for k1 in x.derivatives: output.derivativ...
5,313,608
def get_defense_strategy(arg_dict, dataset_name, strategy_name, strategy_gpu_id, defense_desc, metric_bundle, field): """Take the strategy name and construct a strategy object.""" return built_in_defense_strategies[strategy_name]( arg_dict, dataset_name, strategy_gpu_id, defense...
5,313,609
def get_role_description(role: str) -> str: """Gets the description for a role. Args: role (str): The programmatic role name. Returns: str: The corresponding role description from the game-info json. """ return game_info_json['roles'][role.lower()]['description']
5,313,610
def _wait_for_server(port: int, timeout: float = 5.0) -> None: """Wait until a server accepts connections on the specified port.""" deadline = time.time() + timeout while True: socket_timeout = deadline - time.time() if socket_timeout < 0.0: assert False, f"Server did not start o...
5,313,611
def pairwise_phase_pattern(module, window_type='voronoi', from_absolute=True, project_phases=False, full_window=False, sign='regular', length_unit='cm', palette=None): """ Convenience function to plot nice pairwise phase patterns ...
5,313,612
def centtoinch(cents): """Cents to inch.""" return .3937*cents
5,313,613
def load_image(folder, test): """Load the data for a single letter label.""" image_files = glob.glob(folder + "*[0-9].tif") dataset = np.ndarray(shape=(len(image_files), FLAGS.image_size, FLAGS.image_size), dtype=np.float32) mask_train = [] print(folder) num_images = 0 for image_f...
5,313,614
def test_retry_queue_does_not_resend_removed_messages(mock_matrix, retry_interval_initial): """ Ensure the ``RetryQueue`` doesn't unnecessarily re-send messages. Messages should only be retried while they are present in the respective Raiden queue. Once they have been removed they should not be sent ag...
5,313,615
def sim_model_s1_b(n_sims: int, seed: int): """ Same as model A, but now it has spatial effects ("between-neighborhood counfounders", as they talk about in https://journals.sagepub.com/doi/10.1177/0081175013490188, but look at the other Gelman et al. paper on adding structure to MRP). """ # For ...
5,313,616
def to_pickle(graph: BELGraph, path: Union[str, BinaryIO], protocol: int = pickle.HIGHEST_PROTOCOL) -> None: """Write this graph to a pickle file. Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable pickle, choose 0, 1, or 2. :param graph: ...
5,313,617
def get_log_p_k_given_omega_int_analytic(k_train, k_bnn, interim_pdf_func): """Evaluate the log likelihood, log p(k|Omega_int), using kernel density estimation (KDE) on training kappa, on the BNN kappa samples of test sightlines Parameters ---------- k_train : np.array of shape `[n_train]` ...
5,313,618
def test_ignore_ledger_actions_in_accountant(rotkehlchen_api_server): """Test that ignored ledger actions are correctly ignored by the accountant""" accountant = rotkehlchen_api_server.rest_api.rotkehlchen.accountant ledger_actions_list = [ LedgerAction( identifier=1, timesta...
5,313,619
def test_pypiproxy_patch_applied(): """ Test the PyPIProxy.setup() patch was applied, and sys.path returned to normal """ env = reset_env() result = env.run('python', '-c', "import pip; print(pip.backwardcompat.urllib2.urlopen.__module__)") #if it were not patched, the result would be 'urllib2'...
5,313,620
def PySeqIter_Check(space, op): """Return true if the type of op is PySeqIter_Type. """ raise NotImplementedError
5,313,621
def LeakyReLU(a=0.33): """ Leaky rectified linear unit with different scale :param a: scale :return: max(x, a*x) """ import theano.tensor as T def inner(x): return T.switch(x < a*x, a*x, x) return inner
5,313,622
def get_top_element_count(mol, top): """ Returns the element count for the molecule considering only the atom indices in ``top``. Args: mol (Molecule): The molecule to consider. top (list): The atom indices to consider. Returns: dict: The element count, keys are tuples of (elem...
5,313,623
def load_data(filename, start=0.0, end=1.0, include_profiles=False): """ Wrapper function to load data from a file. Args: filename: The path of the file to load the data from. start: Fractional position from which to start reading the data. end: Fractional position up to which to re...
5,313,624
def query_spf(domain: str) -> str: """ takes in a domain as a string and trys to find a spf with a query, if it finds one it returns the spf record if not returns an empty string. """ q = query(domain,'TXT') if not q: return "" for txtd in q.rrset: if txtd.strings[0].decode('utf-...
5,313,625
def str_wire(obj): """Returns a string listing the edges of a wire.""" s = [] edges = obj.Edges() edge_count = len(edges) if edge_count == 1: s.append("Wire (1x Edge)\n") else: s.append("Wire (%dx Edges) " % (edge_count)) s.append("length:") s.append(_str_value(wi...
5,313,626
def run_model(model_input, resmap, ID, full_output=False): """ run model Parameters ---------- 'model_inputs' (dictionary): contains inputdata, interference flag, logit flag, candidate model parameters for species response curves, threshold flag, number of input variables...
5,313,627
def calculate_approximate_ci( xs: np.ndarray, ratios: np.ndarray, confidence_ratio: float ) -> Tuple[float, float]: """ Calculate approximate confidence interval based on profile. Interval bounds are linerly interpolated. Parameters ---------- xs: The ordered parameter values al...
5,313,628
def doctest_bad(x,y=1,**k): """A function whose doctest we need to skip. >>> 1+1 3 """ print('x:',x) print('y:',y) print('k:',k)
5,313,629
def test_ok_missing_discharge_rate(schema: Type[BaseModel], data: Dict[str, Any]): """ Test that a discharge rate is optional for a schema """ schema(**data)
5,313,630
def safe_update_last_login(sender, user, **kwargs): """ Identical to Django's built-in handler except that we gracefully handle database failures. tl;dr logging in should not fail when a db is read-only """ try: update_last_login(sender, user, **kwargs) except DatabaseError as exc: ...
5,313,631
def get_logger(level=logging.INFO, quite=False, debug=False, to_file=''): """ This function initialises a logger to stdout. :param level: logging level (DEBUG / INFO / WARNING / CRITICAL) :param quite: if mute logging :param debug: if debug mode :param to_file: log file path :return: logger ...
5,313,632
def SetupRoot(root_vm, leaf_vms): """Connect a root node to a list of leaf nodes. Args: root_vm: A root vm instance. leaf_vms: A list of leaf vm instances. """ fanout_args = ' '.join(['--leaf=%s' % i.internal_ip for i in leaf_vms]) root_server_bin = oldisim_dependencies.Bina...
5,313,633
def transform_means(means, size, method='sigmoid'): """ Transforms raw parameters for the index tuples (with values in (-inf, inf)) into parameters within the bound of the dimensions of the tensor. In the case of a templated sparse layer, these parameters and the corresponding size tuple deascribe only...
5,313,634
def pull_if_not_exist(region: str=None, registry_prefix: str=None, repo: str=None, tag: str=None): """ Pull the image from the registry if it doesn't exist locally :param region: :param registry_prefix: :param repo: :param tag: :return: """ output = get_stdout('''{docker} images {re...
5,313,635
def _remove_junk(plaintext, language): """ """ if language in {"zh", "ja", "fa", "iw", "ar"}: return plaintext lines = plaintext.splitlines() lines = [l for l in lines if re.findall(MEANINGFUL, l) or not l.strip() or l.startswith("<meta")] out = "\n".join(lines).strip() + "\n" out = ...
5,313,636
def test_digital_product_view(client, digital_content_url): """Ensure a user (anonymous or not) can download a non-expired digital good using its associated token and that all associated events are correctly generated.""" url = digital_content_url.get_absolute_url() response = client.get(url) f...
5,313,637
def model_parallel_is_initialized(): """Check if model and data parallel groups are initialized.""" if _TENSOR_MODEL_PARALLEL_GROUP is None or _PIPELINE_MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None: return False return True
5,313,638
def CV_IS_IMAGE(*args): """CV_IS_IMAGE(CvArr img) -> int""" return _cv.CV_IS_IMAGE(*args)
5,313,639
def list_program_seasons(plugin, item_id, program_id, **kwargs): """ Build programs listing - Season 1 - ... """ resp = urlquick.get(URL_VIDEOS % program_id) json_parser = json.loads(resp.text) for program_season_datas in json_parser["show"]["seasonNumbers"]: program_season_name...
5,313,640
def fingerprint(samp): """A memory-efficient algorithm for computing fingerprint when wid is large, e.g., wid = 100 """ wid = samp.shape[1] d = np.r_[ np.full((1, wid), True, dtype=bool), np.diff(np.sort(samp, axis=0), 1, 0) != 0, np.full((1, wid), True, dtype=bool)...
5,313,641
def ldns_rr_list_compare(*args): """LDNS buffer.""" return _ldns.ldns_rr_list_compare(*args)
5,313,642
def at_least_one_shift_each(cur_individual): """ checks if there is at least one of each shift: 01, 10, 11 """ num_entrega = 0 num_recogida = 0 num_dual = 0 while cur_individual: shift = cur_individual[:2] cur_individual = cur_individual[2:] if shift == '01': num_...
5,313,643
def generate_validate_yaml_for_python( artifact_name, top_level_imports, allowed=None, exclude_files=None, verbose=0, ): """Generate a validation YAML file from an artifact that is a python package. This function works in two stages. 1. It uses a default set of globs for python install...
5,313,644
def search_strings(i): """Search configuration for config k, v's Calls Checks module""" print("\n") print(f"{'Class:':>15} {i.get('name')}") print(f"{'Prematch:':>15} {i.get('prematch')}") print("---------------------------") MatchType.is_any(i.get('any')) for key in i.get('match', ...
5,313,645
def near_points(px, qx, r, pxtree=None, qxtree=None): """ Finds points in qx that are within a distance r of any point in px Parameters: px, required, float(np, dim), coordinates of px qx, required, float(nq, dim), coordinates of py r, required, float, radius of closeness ...
5,313,646
def test_with_base_date_and_num_runs_and_execution_date_outside(admin_client, runs, endpoint): """ Tests view with base_date and num_runs and execution-date URL parameters. Scenario: change the base date and num runs and press "Go", the selected execution date is outside the new range. Should only s...
5,313,647
def copy_dir_contents(src, dest, exit_code=ExitCode.FAILURE): """ Copy the contents of the source directory to the destination directory. """ # Make sure the source directory exists if not os.path.isdir(src): printerr(f"Error: {src} must be a directory") sys.exit(exit_code) # Cre...
5,313,648
def batch_dtype(observation_space, action_space): """Returns a batch dtype for the provided observation and action spaces. Args: observation_space -- the observation space action_space -- the action space Returns a complex numpy dtype for the batch """ states_dtype = np.dtype((obse...
5,313,649
def fix_texture_file_nodes(nodes=lib._no_val, file_path=None, dry_run=False): """For fixing previous bad implementations on texture management """ args = (nodes, ) if nodes is not lib._no_val else () with capsule.ref_edit_unlock(): # This context is for unlocking colorSpace for node in ...
5,313,650
def runQuery(tStart, tStop): """ Get all the rows from all the events within the time period of _tStart_ and _tStop_. :param tStart: start of the time period :param tStop: stop of the time period :return: an array of all the events between _tStart_ and _tStop_ """ mariadb_connection = mariad...
5,313,651
def test__firewall__proto__invalid_type_nagative_fuzz(value): """Test invalid, unconstrained values for proto - should throw.""" with patch("qsm.dom0.lib.run", return_value=None, autospec=True): with patch("qsm.dom0.exists_or_throws", return_value=True, autospec=True): with pytest.raises(Ass...
5,313,652
def get_aware_utc_now(): """Create a timezone aware UTC datetime object from the system time. :returns: an aware UTC datetime object :rtype: datetime """ utcnow = datetime.utcnow() utcnow = pytz.UTC.localize(utcnow) return utcnow
5,313,653
def test_start_db(): """ Start the database, and assuming that no errors occur, the simple test will return be correct. """ NauticalDatabase().run() assert True
5,313,654
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]: """Iterates a response JSON yielding data point by point. Can be used with both regular and chunked responses. By default, returns just a plain list of values representing each point, without column names, or other metadata...
5,313,655
def evaluation(board: chess.Board, deciding_agent): """ Basic heuristic. :param board: The current state of the game The current state of the game :param deciding_agent: The identity of the "good" agent. :return: Heuristic value for the state """ # Define 1 for myself and -1 for rival: ...
5,313,656
def calculate_temperature(T0, setpoint, K, omega, Tvar): """ Calculate temperature according to the following formula: :math:`T_{output} = T_{var} exp^{-(t - t_0)/K} sin(ω t) + T_{setpoint}` """ t = time.monotonic() return ((Tvar * np.exp(-(t - T0) / K) * np.sin(omega ...
5,313,657
def test_GBL_tau_star(): """Test tau_* against GB&L astro-ph/9812125v3. tau_* is a quantity used in optical_depth_instant. """ z = 1.0 # Fully ionized H and He x_ionH = 1.0 x_ionHe = 2.0 cosmo = {} cosmo['omega_M_0'] = numpy.array([[0.3],[0.6],[1.0]]) cosmo['omega_lambda_0'] =...
5,313,658
def test_regrid_nearest_2_multi_realization(tmp_path): """Test nearest-2 neighbour regridding""" kgo_dir = acc.kgo_root() / "regrid" kgo_path = kgo_dir / "nearest_2/kgo_multi_realization.nc" input_path = kgo_dir / "landmask/global_cutout_multi_realization.nc" target_path = kgo_dir / "landmask/ukvx_l...
5,313,659
def nodes_visited_for_seq_ref(distance, max_array, min_array, list_parent_node): """ """ boolean_grp = np_logical_and(np_less_equal(distance, max_array), np_greater(distance, min_array)) count_visited_nodes = np_sum(boolean_grp) not_boolean_grp = np_logical_not(boo...
5,313,660
def get_config_class() -> Type[BaseSettings]: """ Dynamically imports and returns the Config class from the current service. This makes the script service repo agnostic. """ # get the name of the microservice package with subprocess.Popen( args=[GET_PACKAGE_NAME_SCRIPT], stdout=s...
5,313,661
def bdc_plot_datasets(datasets, zoom = 4, layout=Layout(width='600px', height='600px')): """Plot Dataset tiles """ bbox = get_bounds(datasets, datasets[0].crs) bbox_pol = shapely.wkt.loads(bbox.wkt) project = partial( pyproj.transform, pyproj.Proj(datasets[0].crs.crs_str), ...
5,313,662
def test_design_matrix_artifacts(): """Test the creation of artifact regressors.""" hrf = glm.IdentityHRF() design = pd.DataFrame(dict(condition=["one", "two"], onset=[5, 10])) X1 = glm.DesignMatrix(design, hrf, 15) nt.assert_equal(X1.artifact_submatrix, None) artifac...
5,313,663
def read_xnli(dir_path, lang, split, spm_path=None) -> Tuple[List[List[str]], List[str]]: """ Reads XNLI data. :param dir_path: the path to the xnli folder :param lang: the language :param split: the split of the data that should be read (train, test, val) :param spm_path: path to sentencepiece ...
5,313,664
def indexation(obj, key): """:yaql:operator indexer Returns value of attribute/property key of the object. :signature: obj[key] :arg obj: yaqlized object :argType obj: yaqlized object, initialized with yaqlize_indexer equal to True :arg key: index name :argType key: keyword :re...
5,313,665
def test_attributes(): """Create a dict of NSWC attributes.""" yield { "revision_id": 1, "hardware_id": 1, "Cac": 0.0, "Calt": 0.0, "Cb": 0.0, "Cbl": 0.0, "Cbt": 0.0, "Cbv": 0.0, "Cc": 0.0, "Ccf": 0.0, "Ccp": 0.0, "C...
5,313,666
def h2o_H2OFrame_cor(): """ Python API test: h2o.frame.H2OFrame.cor(y=None, na_rm=False, use=None) """ python_lists = np.random.uniform(-1,1, (10,2)) python_lists2 = 0.5*python_lists[:,0]-0.3*python_lists[:,1] python_list3 = python_lists[:,0] h2oframe = h2o.H2OFrame(python_obj=python_lists) ...
5,313,667
def convert_output_key(name): """ Convert output name into IE-like name :param name: output name to convert :return: IE-like output name """ if not isinstance(name, tuple): return name if len(name) != 2: raise Exception('stats name should be a string name or 2 elements tuple ' ...
5,313,668
def collection(identifier: str): """Get a collection. --- tags: - collection parameters: - name: prefix in: path description: The identifier of the collection required: true type: string example: 0000001 - name: format description: The file type in:...
5,313,669
def tensor_shape_proto(output_size): """ The shape of this tensor. """ return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in output_size])
5,313,670
def check_raises(physical_line, filename): """Check raises usage N354 """ ignored_files = ["./tests/unit/test_hacking.py", "./tests/hacking/checks.py"] if filename not in ignored_files: if re_raises.search(physical_line): return (0, "N354 ':Please use ':rai...
5,313,671
def eval_expr(src, env=None, **kwargs): """ Similar to eval_ast, but receives expression as a string and variables as keyword arguments. """ env = {} if env is None else env env.update(kwargs) return eval_ast(parser(src), env)
5,313,672
def do_parser_test(arguments): """Parser test option.""" print("genie: congratulations! you found the hidden parser test option!") print(arguments)
5,313,673
def tasksInView(): # pragma: no cover """Iterate over all the tasks in view.""" return filter(isTask, itemsInView())
5,313,674
def in_polygon(point, polygon): """Simple wrapper on the within method of shapely points Params: point (POINT) a shapely point object polygon (POLYGON) a shapely polygon object (the target overlap area) Returns: (bool) whether or not the point is within polygon expressed as a boolean "...
5,313,675
def move_file(source: Path, dest: Path): """Moves source photo file to destination path. Args source: Source image file path dest: Destination directory path """ dest.mkdir(mode=0o777, parents=True, exist_ok=True) try: #shutil.copy2(str(source), str(dest)) #shut...
5,313,676
def p_relational_expression(p): """relational_expression : shift_expression | relational_expression LT shift_expression | relational_expression GT shift_expression | relational_expression LE shift_expression | relational_expression GE shift_expression | relational_expression IS type | relational_expression...
5,313,677
def sort_points(points:list) -> list: """ Returns a list of point tuples equivalent to points, but sorted in order by ascending x coordinate. >>> sort_points([(5,4),(2,3)]) [(2,3),(5,4)] >>> sort_points([(1,1),(3,2),(2,3)]) [(1,1),(2,3),(3,2)] >>> sort_points([(99,120),(0,10),(200,...
5,313,678
def validate_overwrite_different_input_output(opts): """ Make sure that if overwrite is set to False, the input and output folders are not set to the same location. :param opts: a namespace containing the attributes 'overwrite', 'input', and 'output' :raises ValidationException: if 'input' ...
5,313,679
def _add_advices(target, advices): """Add advices on input target. :param Callable target: target from where add advices. :param advices: advices to weave on input target. :type advices: routine or list. :param bool ordered: ensure advices to add will be done in input order """ interceptio...
5,313,680
def NASNetMobile(input_shape=None, include_top=True, weights='imagenet', input_tensor=None, pooling=None, classes=1000): """Instantiates a Mobile NASNet model in ImageNet mode. Optionally loads weights pre-trained on ImageNet. N...
5,313,681
def dcn_resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: pretrained_model = model_zoo.load_url(model_urls['resnet1...
5,313,682
def preprocessing(text): """Exclude punctuations and digits from text.""" text = process_tweets(text) text = text.lower() exclude = string.punctuation + string.digits for i in exclude: text = text.replace(i, "") return text
5,313,683
def OutputEventData(revision, event_dict, dest_dir): """Outputs event data to a local text file to be graphed. Args: revision: The string revision number associated with the event data. event_dict: A dict which maps a description to an array of tuples representing event data to be graphed. dest...
5,313,684
def iter_traceback_frames(tb, config=None): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ max_frames = config.stack_trace_limit if config else -1 if not max_frames: return frames = [] while tb:...
5,313,685
def test_instantion(): """Can successfully instantiate an empty linked list """ assert BinarySearchTree()
5,313,686
def parse_patter(pats: typing.List[str]) -> typing.Tuple[typing.List[str], typing.List[str]]: """ 分析匹配项 ======== /xx/ # 只匹配根目录下文件夹 xx/ # 匹配所有的文件夹 /xx # 只匹配根目录下文件 xx # 匹配所有的文件 !xx # 除xx之外 ========= /xx/ => xx + xx/** xx/ => xx + xx/** + **/xx + **/...
5,313,687
def index(): """Job Status Index.""" return render_template('fts_index.html')
5,313,688
def createNiftiTestFiles(shouldValidate: bool = True): """ Create base 3D NIfTI1 file all others are created from """ convertDicomFileToNifti(test_dicomPath, test_3DNifti1Path) nifti1_3D = nib.load(test_3DNifti1Path) # Extract the TR time, then eliminate pixel dimension data past 3rd # dime...
5,313,689
def clean(c): """Runs all clean sub-tasks""" pass
5,313,690
def is_downloaded(folder,path_): """[check if the .html file exists] Args: folder ([folder in which is placed the book]): [description] path_ ([type]): [path of the .html page] Returns: [type]: [description] """ if not os.path.exists(folder): os.makedirs(folder) ...
5,313,691
def calc_brownian_displacement(dt, viscosity, particle_diameter, temperature): """ Calculate brownian motion characteristic displacement per dt """ kb = 1.3806e-23 # (J/K) Boltzmann constant dx = np.sqrt(2*kb*temperature*dt/(3*np.pi*viscosity*particle_diameter)) return dx
5,313,692
def manhattan_distance(v1, v2, norm=False): """ return ||v1 - v2||_1 """ v1, v2 = check_pairwise_vector(v1, v2, norm) diff = v1 - v2 K = np.abs(diff).sum() return K
5,313,693
def read_data_submit(ftdi, buf, size): """ read_data_submit(context ftdi, unsigned char * buf, int size) -> transfer_control Reads data from the chip. Does not wait for completion of the transfer nor does it make sure that the transfer was successful. Use libusb 1.0 asynchronous API. Parame...
5,313,694
def set_spines(ax, plot_params): """ Sets spines of the shift graph to be invisible if chosen by the user Parameters ---------- ax: Matplotlib ax Current ax of the shift graph plot_parms: dict Dictionary of plotting parameters. Here `invisible_spines` is used """ spines ...
5,313,695
def update_user(id): """Method to handle update a user""" try: data = request.get_json() or {} user = Authentication() response = user.update_user(id, data) return response except KeyError: return ({"Error": "An error occured"})
5,313,696
def _normalize_resources(resources): """ Exclude any resources that have `/facebook` in the path as these are internal and require internal FB infra. Only applies to resources specified in the `dict` format Will also go ahead an invert the dictionary using `_invert_dict` """ if resources and ty...
5,313,697
def prune_stats(stats, big_stats, threshold): """Prune statistics dict for efficiency of max() The frequency of a symbol pair never increases, so pruning is generally safe (until we the most frequent pair is less frequent than a pair we previously pruned) big_stats keeps full statistics for when we need...
5,313,698
def process_file(fn, coverage, percentage, multiple, debug): """ Determine whether there was adequate coverage of bases in this file. NOTE: Returns True if the run was OK. :param fn: :param coverage: :param percentage: :param multiple: :param debug: :return: """ metadata_ende...
5,313,699