content
stringlengths
22
815k
id
int64
0
4.91M
def gauss(x, a, b, c): """ generate a Gaussian function Parameters ---------- x : array like x coordinates. a : float amplitude (centeral height). b : float center. c : float sigma. Returns ------- y y = Gaussian(x | a, b, c). ""...
56,300
def replace_urls(text, filler='<url>'): """Replaces URLs in text with `f' {filler}'`. Potentially induces duplicate whitespaces. Includes punctuation in websites (which is not really a problem, because URLs on Twitter are rendered as https://t.co/randomnum). The regex doesn't account for what's ...
56,301
def test_revault_network_securing(revault_network): """Profile the securing of 10 vaults on a dummy network.""" revault_network.deploy(10, 5, 2, csv=12) vaults = [] for amount in range(10): vaults.append(revault_network.fund((amount + 1) / 100)) revault_network.secure_vaults(vaults)
56,302
def create_signature_v2( api_key, method, host, path, secret_key, get_params=None ) -> Dict[str, str]: """ 创建签名 :param get_params: dict 使用GET方法时附带的额外参数(urlparams) :return: """ sorted_params = [ ("accessKey", api_key), ("signatureMethod", "HmacSHA256"), ...
56,303
def test_ensemble_builder_nbest_remembered(fit_ensemble, ensemble_backend, dask_client): """ Makes sure ensemble builder returns the size of the ensemble that pynisher allowed This way, we can remember it and not waste more time trying big ensemble sizes """ fit_ensemble.side_effect = MemoryError ...
56,304
def solution(X, A): """Find the earliest time that a frog can jump to position X. In order to reach X, a leaf must be present at every position from 1 to X. Args: X (int): The position that the frog must reach. A (list): A list of integers from 1 to X, where A[k] represents a leaf ...
56,305
def apply_unary_rules(grammar, chart, i, j): """Add parses to chart cell (i, j) by applying unary rules.""" # Note that the last line of this method can add new parses to chart[(i, # j)], the list over which we are iterating. Because of this, we # essentially get unary closure "for free". (However, if...
56,306
def is_charmcraft_running_in_managed_mode(): """Check if charmcraft is running in a managed environment.""" managed_flag = os.getenv("CHARMCRAFT_MANAGED_MODE", "n") return distutils.util.strtobool(managed_flag) == 1
56,307
def moments_get_orientation(m): """Returns the orientation in radians from moments. Theta is the angle of the principal axis nearest to the X axis and is in the range -pi/4 <= theta <= pi/4. [1] 1. Simon Xinmeng Liao. Image analysis by moments. (1993). """ theta = 0.5 * math.atan( (2 *...
56,308
def load_sklearn_bc_dataset(): """ Helper to load sklearn dataset into a pandas dataframe Returns: pd.DataFrame: X and y combined """ dataset = load_breast_cancer() df = pd.DataFrame(data=pd.np.c_[dataset['data'], dataset['target']], columns=(dataset['feature_names...
56,309
def get_select_form_layout(id, options, label, description): """Creates a select (dropdown) form with provides details Parameters ----------- id: str id of the form options: list options to show label: str label of the select dropdown bar description: str lon...
56,310
def test_distribution(column): """Assert that the distribution method and file are created.""" atom = ATOMClassifier(X10_str, y10, random_state=1) pytest.raises(ValueError, atom.distribution, columns="Feature 3") df = atom.distribution(columns=column) assert len(df) == 11
56,311
def visualise_sampling_grid(X_sampled, gridsize=3): """Show how herding algorithm samples the datapoints Using X_sampled, which is the original design matrix with rows permuted such that X_sampled[i] is the i'th row chosen by the sampling algorithm. This enables calculating X_sampled by arbitrary algor...
56,312
def serialize_ip_block(block): """ Serialize an IP block to protobuf string. Args: block (ipaddress.ip_network): object to serialize Returns: serialized (bytes): serialized object """ proto = IPBlock( version=_ip_version_int_to_proto(block.version), net_address=b...
56,313
def pTile(percent, imageData, numberOfPixels, edgePixels, file): """ Applies p-tile method of automatic thresholding to find the best threshold value and then apply that to the image to create a binary image. :param percent: of non zero pixels to be over the threshold :param imageData: input image a...
56,314
def copy_and_add_dataset_source(entity, dataset_label, dataset_type, original_source_location, move=False): """Copies the dataset to the entity location and then adds as Dataset. If the original_source_location is a file object, then it just read()s from the handle and writes to destination. If...
56,315
def extract_features(chunk: ms.Chunk, bounds: list[Bounds]): """ Extract subsets of a chunk's dense point cloud using a given list of bounding boxes. param: chunk: The input chunk. type: chunk. Metashape.Chunk param: bounds: A list of bounds type: bounds: List[Bounds] """ # Make the dir...
56,316
def DeWeWriteCAN(nBoardNo, CanFrameList): """Dewe write CAN""" if f_dewe_write_can is not None: n_real_frame_count = c_int() n_frame_count = len(CanFrameList) p_can_frames = (BOARD_CAN_FRAME * n_frame_count)() i = 0 for CanFrame in CanFrameList: p_can_frames[...
56,317
def get_article_case(article, word): """Determines the correct article casing based on the word casing""" return article.capitalize() if word[0].istitle() else article
56,318
def learn(logger, device, env, nenv, number_timesteps, network, optimizer, save_path, save_interval, ob_scale, gamma, grad_norm, timesteps_per_batch, ent_coef, vf_coef): """ Paper: Mnih V, Badia A P, Mirza M, et al. Asynchronous methods for deep ...
56,319
def calc_DM(seg): """ Computes NON-SIGNED Distance Map of input ground truth image or volume using scipy function. In case seg is 3D volume, it separately computes 2D DM fo each single slice. Args: seg: 2D or 3D binary array to compute the distance map Returns: res: distance map ...
56,320
def get_valid0(cfg: Config): """ Simple network with all inputs and all outputs used. Configuration: 0 1 / | 2 \ / \ | -1 -2 -3 """ # Create a dummy genome genome = Genome( key=0, num_outputs=cfg.genome.num_outputs, ...
56,321
def get_dependents_auto(tensor: tf.Tensor, candidates: List[tf.Tensor]) -> List[tf.Tensor]: """Return the nodes in `candidates` that `tensor` depends on. Args: tensor (): candidates (): """ try: dependent_ops = all_parents(tensor.op) except RuntimeError as error: rai...
56,322
def gram_matrix(input_tensor): """ Computes the outer-product of the input tensor x. Input: - x: input tensor of shape [H,W,C]. We reshape it to [C (H, W)] Returns: Tensor of shape [C,C] corresponding to the Gram matrix Your code goes here """ channels = int(input_t...
56,323
def false_positive_rate(context, positive_class, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a multiclass false positive rate. The result of this function repres...
56,324
def register_root_routes(app: Flask, static_digest: FlaskStaticDigest): """Register the root routes blueprint.""" def set_static_digest() -> None: g.static_digest = static_digest ROOT_BLP.before_request(set_static_digest) if app.config.get("DEBUG", False): # add cache busting for debu...
56,325
def start_proc(proc, body): """Start individual process as specified in startClusterReq command. proc - the process object in the message body - the whole message """ f = proc['file'] (key_based, user, pwd, key_file) = get_cred(f['hostName'], body) with produce_ABClusterHost(f['hostName'], ...
56,326
def check_missing_pictures(document: Document, args: Args) -> List[Issue]: """Check that all pictures files linked in the document exist.""" issues = [] markdown_picture_re = re.compile(r"\s*\!\[.*\]\((.*)\)") for number, line in enumerate(document.lines): match = markdown_picture_re.match(line...
56,327
def inspect_da_matrix(da_matrix, results_dir="../results", save=False, perfs_corr=False, algos_corr=False, tasks_corr=False, sort_algos=True, ): """Inspect DA matrix. Plot the mean and std of the performance of each algorithm. Plot cluster map for: - pe...
56,328
def _load_mesh(path: str): """Loads mesh data from numpy file. Args: path (str): Path to data file Returns: data (np.ndarray): Scaled data (NHWC) """ with open(path, "rb") as f: mesh = np.einsum("abcde->deabc", sio.loadmat(f)["im"]) flattened_mesh = mesh.reshape((-1,) +...
56,329
def configure(filename="tuf.interposition.json", parent_repository_directory=None, parent_ssl_certificates_directory=None): """The optional parent_repository_directory parameter is used to specify the containing parent directory of the "repository_directory" specified in a configurati...
56,330
def get_script_folder_name(): """Returns the folder where Enso commands are found. This function is responsible for ensuring that this folder exists: it must not return a path that is not present! It is expected to place this folder in some platform-specific logical location.""" return xdg.BaseDirect...
56,331
def CDLHOMINGPIGEON(equity, start=None, end=None): """Homing Pigeon :return: """ opn = np.array(equity.hp.loc[start:end, 'open'], dtype='f8') high = np.array(equity.hp.loc[start:end, 'high'], dtype='f8') low = np.array(equity.hp.loc[start:end, 'low'], dtype='f8') close = np.array(equity.hp....
56,332
def deep_convert_to_plain_dict(an_odict): """ Recursively convert `an_odict` and any of its dictionary subelements from `collections.OrderedDict`:py:class: to plain `dict`:py:class: .. note:: This is naive, in that it will not properly handle dictionaries with recursive object references. ...
56,333
def put_message(message): """ Builds an indexing requests for a message, then sends the request to be queued """ try: _queue_index_request( index=message['meniscus']['tenant'], doc_type=message['meniscus']['correlation']['pattern'], document=message) e...
56,334
def mie(r, eps, sig, m=12, n=6): """Mie pair potential. """ prefactor = (m / (m - n)) * (m / n)**(n / (m - n)) return prefactor * eps * ((sig / r) ** m - (sig / r) ** n)
56,335
def dpn_conv1x1(in_channels, out_channels, stride=1): """ 1x1 version of the DPN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple...
56,336
def main(cli_args): """Main function""" multi_evergreen = MultiEvergreen(cli_args) try: multi_evergreen.parse_options() except OptionError as err: multi_evergreen.parser.print_usage(file=sys.stderr) sys.stderr.write(err) sys.exit(1) try: multi_evergreen.exec...
56,337
def buildTeams(league): """ This function builds the Team objects for each team in the league """ league.teams = {} # Create an empty teams dictionary matchupData = league.matchupData print("Current Week:",league.currentWeek) print('Buildin...
56,338
def test_atomic_date_time_max_inclusive_2_nistxml_sv_iv_atomic_date_time_max_inclusive_3_4(mode, save_output, output_format): """ Type atomic/dateTime is restricted by facet maxInclusive with value 2003-03-09T02:00:23. """ assert_bindings( schema="nistData/atomic/dateTime/Schema+Instance/NIS...
56,339
def _conv2d_legalize(attrs, inputs, arg_types): """Legalizes Conv2D op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output ...
56,340
def smooth_good_regions_repeatedly(blob_id, repeated_smoothings=5, spine_order=SPINE_ORDER, spine_window=SPINE_WINDOW, time_order=TIME_ORDER, time_window=TIME_WINDOW, ...
56,341
def clear_console(): """ Clears console output """ os.system("cls||clear")
56,342
def start( subparser: argparse._SubParsersAction = None, args: argparse.Namespace = None ): """Forward to /start?config={config} Args: subparser (argparse._SubParsersAction, optional): Parser for command 'start'. Defaults to None. args (argparse.Namespace, optional): ...
56,343
def mean_filter(dem, kernel_radius): """Applies mean filter (low pass filter) on DEM. Kernel radius is in pixels. Kernel size is 2 * kernel_radius + 1. It uses matrix shifting (roll) instead of convolutional approach (works faster). It returns mean filtered dem as numpy.ndarray (2D numpy array).""" radi...
56,344
def increment_values(d): """ (dict with number values) -> NoneType Increase each value in d by 1. """ for k in d: d[k] = d[k] + 1
56,345
def _members_geom_lists(relation_val, footprints): """ Add relation members' geoms to lists. Parameters ---------- relation_val : dict members and tags of the relation footprints : dict dictionary of all footprints (including open and closed ways) Returns ------- tu...
56,346
def test_init_eval(): """Test initalising Eval class""" Eval()
56,347
def hits_numpy(G,normalized=True): """Return HITS hubs and authorities values for nodes. The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. Parameters ----------- G : g...
56,348
def branches(context, directory='migrations', verbose=False): """Show current branch points""" config = _get_config(directory) if alembic_version >= (0, 7, 0): command.branches(config, verbose=verbose) else: # pragma: no cover command.branches(config)
56,349
def InputFunc(): """ InputFunc [This Function is used to take declare input.] Returns: [int]: [windowSize] [int]: [dataBits] [int]: [Timeout] """ dataStr = '1010010011' dataStr = " ".join(dataStr) windowSize = 4 # Makes the input string to a list dataBits = [...
56,350
def httpResponse(graph, uri): """HTTP response: FAIR metadata in RDF and JSON-LD formats""" accept_header = request.headers.get('Accept') fmt = 'turtle' # default RDF serialization mime_types = { 'text/turtle': 'turtle', 'application/rdf+xml': 'xml', 'application/ld+json': 'json...
56,351
def reaction( func=None, # type: Optional[Callable[[_BO, Action, Phase], None]] priority=None, # type: Optional[int] ): # type: (...) -> Union[CustomReaction, ReactionDecorator] """ Decorates an object's method into a custom reaction. Reaction methods are called automatically when an action pr...
56,352
def delete_report(repo, username=None, namespace=None): """Delete a report from a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() if form.validate_on_submit(): report = flask.request.form.get("report") reports = repo.reports if report not in reports: ...
56,353
def downloadmodel(model_label=None, targetdir=None): """ Query Zenodo and retrieve version-specific model parameter files and metadata """ global modelOptions if targetdir is not None: tempDir = targetdir else: tempDir = SCOPEMODELS_DATADIR ## By default, download models to the cancerscope/data directory, not...
56,354
def plot_epoch_cv(callback_path, tasks, xirt_params, outpath, show=False): # pragma: no cover """Do a QC plot of the metrics and losses for all tasks across the epochs (over all cvs). Args: callback_path: str, path to the callback logs tasks: ar-like, list of tasks that were used as identifier...
56,355
def fuzzifier_determ(D: int, N: int) -> float: """The function to determ the fuzzifier paramter of fuzzy c-means """ return 1 + (1418 / N + 22.05) * D**(-2) + (12.33 / N + 0.243) * D**(-0.0406 * math.log(N) - 0.1134)
56,356
def test_exception_requests_inalid_str(api): """Test raised exception as string follow expected pattern.""" with pytest.raises(ApiError) as execinfo: url = f"{api.xyzconfig.config['url']}/hub/invalid" resp = requests.get(url) raise ApiError(resp) assert str(execinfo.value).startswith...
56,357
def check_sentence(s: str, annotations, is_foreign=False): """Check whether a given single sentence gets the specified annotations when checked""" def check_sent(sent): assert sent is not None if sent.tree is None and not is_foreign: # If the sentence should not parse, call ...
56,358
def _is_paired(ordered_list: List[int]) -> bool: """Check whether values are paired in ordered_list.""" consecutive_comparison = [ t == s for s, t in zip(ordered_list, ordered_list[1:]) ] return (all(consecutive_comparison[0::2]) & (not any(consecutive_comparison[1::2])))
56,359
def MPC_SetDisturbanceTrigger(operation: DisturbanceOperation, trigger: NfcTrigger, delay: float = 0, count: int = 1) -> None: """Selects the trigger condition starting the disturbance Parameters ---------- operation : DisturbanceOperation ...
56,360
def rgb_to_gray(image, three_channels=False): """Converts a 3 channel RGB image to a 1 channel grayscale image. Args: image: Rank 3 float32 tensor containing 1 image -> [height, width, 3] with pixel values varying between [0, 1]. Returns: image: A single channel grayscale image -> [image, hei...
56,361
def get_largest_partition_size(ns, device): """ Returns size of the largest free region (in blocks), which can accommodate a partition on given device. There must be partition table present on this device. :type device: LMIInstance/CIM_StorageExtent or string :param device: Device which should...
56,362
def test_six_sum_series_code_wars(): """Function that emulates test.assert_equals(series_sum(6), "1.63") from code wars.""" from sum_terms import series_sum assert series_sum(6) == '1.63'
56,363
def create_stereo_point_cloud_folder(sensor_folder): """Create a folder for point clouds genereated using the stereo depth images, if it does not exist. Args: sensor_folder (str): Path to the sensor folder. Returns: stereo_point_cloud_folder (str): Path to the created point cloud ...
56,364
def steps(number): """ Count steps needed to get to 1 from provided number. :param number int - the number provided. :return int - the number of steps taken to reach 1. """ if number < 1: raise ValueError("Provided number is less than 1.") steps = 0 while number != 1: s...
56,365
def labs(**kwargs): """ Change plot title, axis labels and legend titles. Parameters ---------- kwargs : dict A list of new name-value pairs where name should be an aesthetic, e.g. title='Plot title' or aesthetic='Scale label'. Returns ------- `FeatureSpec` or `FeatureS...
56,366
def nested_dict_values(d): """ Extracts all values from a nested dictionary """ listvals = list(nested_dict_gen(d)) listvals_unwrapped = [] for l in listvals: if type(l) == list or type(l) == np.ndarray: for ll in l: listvals_unwrapped.append(ll) else:...
56,367
def load_model(model, load_from, load_dict={}): """loads the weights of a model from a folder. :param model: torch model :type model: torch.nn.module :param load_from: either a filename or a folder where a list of weights are stored :type load_from: str :param load_dict: dict of other ...
56,368
def test_report_add_verb_not_tracked(analog_log): """Log entries with non-tracked verbs are ignored.""" report = Report(verbs=['GET', 'POST'], status_codes=['20', 404]) report.add( path='/foo/bar', verb='PUT', status=205, time=0.1, upstream_time=0.09, body_byt...
56,369
def _get_sr_pod_grid(success_ratio_spacing=0.01, pod_spacing=0.01): """Creates grid in SR-POD space SR = success ratio POD = probability of detection M = number of rows (unique POD values) in grid N = number of columns (unique success ratios) in grid :param success_ratio_spacing: Spacing betw...
56,370
def _chk_string(arg, func_name, arg_index): """argがStringValueか調べる。""" if not isinstance(arg, StringValue): raise ArgumentIsNotStringException("%s is not String." % arg.value, func_name, arg_index, arg.line, arg.pos)
56,371
async def all_upcoming_broadcasts( seconds: Optional[int] = None, ) -> Set[TextChannel]: """All upcoming broadcast channels that have yet to be announced. If minutes are given, then it will only mention the events comming up in the given number of minutes. """ channels = set() now = arrow.utcnow...
56,372
def jd2iso(jd): """Convert a Julian date into an ISO 8601 date string representation""" return astropy.time.Time(jd, format='jd', scale=time_scale, precision=0).iso
56,373
def MakeOnnxInputsOutputs(name, elem_type, shape, **kwargs): """Wrapper for creating onnx graph inputs or outputs name, # type: Text elem_type, # type: TensorProto.DataType shape, # type: Optional[Sequence[int]] """ if elem_type is None: elem_type = onnx_pb.TensorProto.UNDEFI...
56,374
def geom_lst_to_gdf(lst): """Convert geometry or geometry list to gdf. Args: lst (geometry|list(geometry)): The geometry or geometries. Returns: gpd.GeoDataFrame: The geodataframe. """ if not isinstance(lst, list): lst = [lst] return gpd.GeoDataFrame( {'ge...
56,375
def download(args): """ Download a data export job using a request id. """ try: export_request = api.get(args.id)[0] dest = args.dest utils.download(export_request, dest) except Exception as err: logging.error('Download failed with exception:\n{}'.format(err)) ...
56,376
def build_get_enum_valid_request( **kwargs # type: Any ): # type: (...) -> HttpRequest """Get enum array value ['foo1', 'foo2', 'foo3']. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. :return: Returns an :class:`~azure.core...
56,377
async def test_exception_bad_trigger(hass, calls, caplog): """Test for exception on event triggers firing.""" await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": {"trigger": {"platform": DOMAIN, "oops"...
56,378
def ks_2samp(data1, data2): """ Computes the Kolmogorov-Smirnov statistic on 2 samples. This is a two-sided test for the null hypothesis that 2 independent samples are drawn from the same continuous distribution. Parameters ---------- a, b : sequence of 1-D ndarrays two arrays of sam...
56,379
def list_shows(): """ return all the shows """ shows = ShowRun.query.all() ret = [] for show in shows: ret.append({'show_id': show.id, 'show_date': show.created_date, 'show_status': show.status.name}) return jsonify({'date': ret})
56,380
def _replace_spec_toks(mthd: str, spec_toks: Dict[str, str]) -> str: """ Performs the replacement of special tokens by the original ones """ spec_toks = spec_toks.copy() # Add special tokenizer tokens -> deleted for code analysis spec_toks['<bos>'] = "" spec_toks['<eos>'] = "" spec_toks[...
56,381
def redirect_to_user_chat(markup: ReplyKeyboardMarkup): """ Clean the bot commands from the group chat and send the message to a user. Args: markup: ReplyKeyboardMarkup Returns: None or Calls decorated function if in the user's chat. """ def decorator(func): ...
56,382
def test_get_python_name_from_path(path, expected_module_name, prefix): """The actual module name matches the expected module name""" actual_module_name = get_python_name_from_path(prefix + path) assert actual_module_name == expected_module_name
56,383
def run_intcode(memory, input_list): """Run an Intcode program from memory and return the result""" instr_ptr = 0 input_ptr = 0 output = None while instr_ptr < len(memory): instruction = memory[instr_ptr] digits = list_digits(instruction) # extract opcode opcode_pair...
56,384
def feature_table_describe(name: str, project: str): """ Describe a feature table """ feast_client = Client() # type: Client ft = feast_client.get_feature_table(name=name, project=project) if not ft: print(f'Feature table with name "{name}" could not be found') return prin...
56,385
def get_kubeflow_value( tfx_value: Union[int, float, str, Text]) -> Optional[pipeline_pb2.Value]: """Converts TFX/MLMD values into Kubeflow pipeline Value proto message.""" if tfx_value is None: return None result = pipeline_pb2.Value() if isinstance(tfx_value, int): result.int_value = tfx_value ...
56,386
def save_wav_file(filename, wav_data, sample_rate): """Saves audio sample data to a .wav audio file. Args: filename: Path to save the file to. wav_data: 2D array of float PCM-encoded audio data. sample_rate: Samples per second to encode in the file. """ with tf.Session(graph=tf.Graph()) as sess: ...
56,387
def AddEllipticalArc(self, x, y, width, height, theta, dtheta, clockwise=False): """ Draws an arc of an ellipse within bounding rect (x,y,w,h) from startArc to endArc (in degrees, relative to the horizontal line of the eclipse)""" # compute the cubic bezier and add that to the path by calling AddCurveToPoi...
56,388
def read_parquet( path, engine: str = "auto", columns=None, storage_options: StorageOptions = None, use_nullable_dtypes: bool = False, **kwargs, ): """ Load a parquet object from the file path, returning a DataFrame. Parameters ---------- path : str, path object or file-like...
56,389
def calculate_cis_nominal(genotypes_t, phenotype_t, residualizer=None, return_af=True): """ Calculate nominal associations genotypes_t: genotypes x samples phenotype_t: single phenotype residualizer: Residualizer object (see core.py) """ p = phenotype_t.reshape(1,-1) r_nominal_t, genoty...
56,390
def get_ver(): """Read out the version number of the radio""" return radio_get_ver_fn()
56,391
def test_delete_node_with_links(mocker): """Test delete existing node with links.""" m = mocker.Mock(status_code=200, json=mocker.Mock(return_value={})) mocker.patch("requests.get", return_value=m) added_node_id_a = ( "ed01ebfbc9eb5bbea545af4d01bf5f1071661840480439c6e5babe8e080e41aa") added_node_id_b = ...
56,392
def get_entities_list(token, aiid): """Returns a list of all entities for an AI""" return fetch_api('/entities/{aiid}', token=token, aiid=aiid)
56,393
def read_P23_from_sequence(file): """ read P2 and P3 from a sequence file calib_cam_to_cam.txt """ P2 = None P3 = None with open(file, 'r') as f: for line in f.readlines(): if line.startswith("P_rect_02"): data = line.split(" ") P2 = np.array([floa...
56,394
def openConnection(): """ Method that starts a connection with the database :return: the driver for the connection """ connection = nj.GraphDatabase.driver( uri=URI, auth=nj.basic_auth(USER, PASSWORD)) return connection
56,395
def resource_view_attrs(raml_resource, singular=False): """ Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource siblings and dynamic children if exist. Collected methods are then translated to `nefertari.view.BaseView` method names, each of which is use...
56,396
def publisher( n , iter , task_queue ): """ 使用线程处理任务发生的原因是有可能iter是一个yield函数迭代器,内容可能会非常多。 """ try: for obj in iter: if type( obj ) is not tuple: raise RuntimeError( '任务迭代器应该返回元组对象[%r]' % obj ) if len( obj ) != 3: raise RuntimeError( '任务迭...
56,397
def total(inarray, axis, type='meanclip'): """ Collapse 2-D array in one dimension. .. note:: MYTOTAL routine from ACS library. Examples -------- >>> collapsed_array = total(inarray, 1, type='median') Parameters ---------- inarray : array_like Input 2-D array. axis : ...
56,398
def check_rack_shape_match(source_shape, target_shape, row_count, col_count, translation_behaviour=None): """ Checks whether two rack shape match the given rack transfer or translation behaviour. :Note: One-to-one translations can not be discovered ...
56,399