content
stringlengths
22
815k
id
int64
0
4.91M
def vm_parser(): """ Create a ArgumentParser. """ return create_vm_parser()
5,291,800
def mempool_assert_my_coin_id( condition: ConditionVarPair, unspent: CoinRecord ) -> Optional[Err]: """ Checks if CoinID matches the id from the condition """ if unspent.coin.name() != condition.var1: return Err.ASSERT_MY_COIN_ID_FAILED return None
5,291,801
def test_label(): """Test creating label object""" label = TextOverlay() assert label is not None
5,291,802
def delete_bucket(name: str, aws_auth: Dict[str, str] = {}) -> bool: """Delete an S3 bucket. Parameters ---------- name : str Name of the bucket to delete. aws_auth : Dict[str, str], optional Contains AWS credentials, by default {} Returns ------- bool True if ...
5,291,803
def init(self): """Initializes the Instrument object with values specific to DMSP IVM Runs once upon instantiation. Parameters ---------- self : pysat.Instrument This object """ logger.info(general.cedar_rules()) self.acknowledgements = general.cedar_rules() self.referenc...
5,291,804
def does_component_need_db(component): """Return whether the component needs DB to run tests. Useful to determine which components need a Postgres DB container to run the tests. :param component: standard component name :type component: str :return: True/False whether the component needs DB :...
5,291,805
def get_action_for_move( agent_position: Tuple[int, int], agent_direction: Grid4TransitionsEnum, next_agent_position: Tuple[int, int], next_agent_direction: int, rail: GridTransitionMap) -> Optional[RailEnvActions]: """ Get the action (if any) to move from a position and direction to another. TODO https://...
5,291,806
def has_normal_exit_message(output_string): """ does this output string have a normal exit message? """ pattern = ('The final electronic energy is' + app.one_or_more(app.WILDCARD) + 'This computation required') return apf.has_match(pattern, output_string, case=False)
5,291,807
def _vector(weights, u): """ Performs systematic resampling of a 1D array log weights. :param weights: The weights to use for resampling :type weights: torch.Tensor :return: Resampled indices :rtype: torch.Tensor """ n = weights.shape[0] probs = (torch.arange(n, dtype=u.dtype) + u) /...
5,291,808
def post_list(request, topic=None, cache_key='', extra_context=dict(), template_name="post_list.html"): """ Post listing. Filters, orders and paginates posts based on GET parameters. """ # The user performing the request. user = request.user # Parse the GET parameters for filtering information ...
5,291,809
def draw_camera_bbox3d_on_img(bboxes3d, raw_img, cam_intrinsic, img_metas, color=(0, 255, 0), thickness=1): """Project the 3D bbox on 2D plane and draw on input image...
5,291,810
def save_object(obj, filename): """save the object in a pickle file """ Path(filename).mkdir(parents=True, exist_ok=True) pickle.dump(obj, open( filename, "wb" ), pickle.HIGHEST_PROTOCOL)
5,291,811
def get(endpoint: str, parametros: dict = None) -> dict: """ Realiza um requisição HTTP do tipo GET para a API da Lomadee :param endpoint: Endpoint da requisição :type endpoint: str :param parametros: Parâmetros da requisição :type parametros: dict :return: Dados da Resposta :rtype: d...
5,291,812
def tool_shed_client(gi=None): """ Get an instance of the `ToolShedClient` on a given Galaxy instance. If no value is provided for the `galaxy_instance`, use the default provided via `load_input_file`. """ if not gi: gi = galaxy_instance() return ToolShedClient(gi)
5,291,813
def move_file_to_s3(local_filename, hash_digest, destination_filename): """Considered making this a celery task, but don't think the file created on `web` is available on `worker` so lets wait to see if we even need the async. """ s3_client = boto3.client('s3') try: response = s3_client.u...
5,291,814
def test_is_round_done_done(agg): """Test that is_round_done returns True in the corresponded case.""" round_num = 0 task_name = 'test_task_name' col1 = 'one' col2 = 'two' agg.assigner.get_all_tasks_for_round = mock.Mock(return_value=[task_name]) agg.assigner.get_collaborators_for_task = moc...
5,291,815
def create_commits_to_prs_mapping(linege, prs): """create a mapping from commits to the pull requests that the commit is part of """ commits_to_prs = {} # make a copy of this list to avoid side effects from calling this function my_prs = list(prs) commit_data = cache_commit_data(my_prs) ...
5,291,816
def users(ctx): """ List users. """ verbosity_level = ctx.obj[Context.VERBOSITY_LEVEL] app_configs = ctx.obj[Context.CONFIGS] client = GaroonClient( subdomain=app_configs[ConfigKey.SUBDOMAIN], basic_auth=app_configs[ConfigKey.BASIC_AUTH] ) matrix = [] has_next = True off...
5,291,817
def class_to_json(obj): """ function that returns dictionary description with simple data structure for JSON serialization of an object """ return obj.__dict__
5,291,818
def ITE(s, d1, d0, simplify=True, factor=False): """Factory function for Boolean If-Then-Else expression.""" s = Expression.box(s) d1 = Expression.box(d1) d0 = Expression.box(d0) expr = ExprITE(s, d1, d0) if factor: expr = expr.factor() elif simplify: expr = expr.simplify() ...
5,291,819
def key_generate(key_type=KEY_TYPE.SYMMETRIC, key_bit_length=KEY_BIT_LENGTH.L256BIT): """Generates a secure key or key generation parameters (or an Initialization Vector).""" key = _ctypes.c_void_p() _lib.yaca_key_generate(key_type.value, key_bit_length, _ctyp...
5,291,820
def is_allowed(yaml, ifname, iface_addresses, ip_interface): """Returns True if there is at most one occurence of the ip_interface (an IPv4/IPv6 prefix+len) in the entire config. That said, we need the 'iface_addresses' because VPP is a bit fickle in this regard. IP addresses from the same prefix/len c...
5,291,821
def string(text, is_return_null=False): """ sql字符串拼接专用函数 会在字符串两边添加'单撇号,用于生成数据库sql语句 :param text: 需要添加'的字符串 :param is_return_null: 是否返回null,是的话在字符串为空时返回null,否则返回'' :return: """ if not text is None and text != '': return "'" + str(text) + "'" elif not is_return_null: re...
5,291,822
def addDhcpHostEntry(dhcpGroup, hostEntry): """ Adds a host entry in the group section if not already there. Return True or False, depending on whether the entry was added or not. """ # Next we check if the host entry needs to be created. if dhcpGroup.contains(DhcpConfEntry.Type.Host, hostEntry...
5,291,823
def test_set_team_update(org): """Adding and removing members and repos to a team""" with requests_mock.Mocker() as mock: add_org_options(mock, DF.options()) add_org_teams(mock, DF.teams()) register_uri(mock, "DELETE", url="teams/team1id/repos/ORG_NAME/repo2") register_uri(mock, ...
5,291,824
def do_pack(): """Do_pack function""" today = datetime.datetime.now() file_local = 'versions/web_static_{}{}{}{}{}{}.tgz'.format(today.year, today.month, today.day, ...
5,291,825
def get_logistic_regression_dataset(dimension, num_samples_per_client, num_clients): """Creates logistic regression datset. Returns: A `(train, test)` tuple where `train` and `test` are `tf.data.Dataset` representing the test data of all clients. """ beta = tf.random.normal(shape = (dimension,...
5,291,826
def get_available_benchmark_files(): """ Returns a list of dicts containing metadata of the available benchmark files for tests on the nussl External File Zoo (EFZ) server (http://nussl.ci.northwestern.edu/). Each entry in the list is in the following format: .. code-block:: python { ...
5,291,827
def DecodeMappingPairs(MappingPairs): """Decode mapping pairs, return a list of (offset, length) tuples. In these tuples, both items refer to clusters. Sparse ranges have the offset item set to None. """ data_runs = [] i = 0 curr_offset = 0 while True: if i >= len(MappingPairs): ...
5,291,828
def to_time_major(tensor: tf.Tensor) -> tf.Tensor: """Transposes batch majored tensors to time major.""" dimensions = tf.nest.map_structure(lambda x: x.get_shape().ndims, tensor) def _transpose(value, dimension): if dimension > 1: # Swap the first dimension (batch) with the second (time) return t...
5,291,829
def copy_attributes(h5path, dset0, dsets): """Copy attributes from one h5 dataset to another.""" h5file = h5py.File(h5path, 'a') ds0 = h5file[dset0] for dset in dsets: ds = h5file[dset] ds.attrs['element_size_um'] = ds0.attrs['element_size_um'] for i, label in enumerate(ds0.att...
5,291,830
def find_code_blocks(html: str, tags: List[str]) -> List[CodeBlock]: """Build up code blocks of potentially many languages.""" blocks: List[CodeBlock] = [] regex_expression = '(<pre class="[a-z -]*"><code>|<pre><code>|</code></pre>)' parts = re.split(regex_expression, html) in_comment = True #...
5,291,831
def get_swap_targets(node): """ All pairs of columns that do not have the same types in every cell """ pairs = [] n_col = node.table.n_col for i in range(n_col): col_i = node.table.get_col(i) for j in range(i + 1, n_col): col_j = node.table.get_col(j) same = True...
5,291,832
def product (nums): """ get the product of numbers in an array. """ return functools.reduce(operator.mul, nums, 1)
5,291,833
def string_is_hex(color_str): """ Returns whether or not given string is a valid hexadecimal color :param color_str: str :return: bool """ if color_str.startswith('#'): color_str = color_str[1:] hex_regex1 = QRegExp('^[0-9A-F]{3}$', Qt.CaseInsensitive) hex_regex2 = QRegExp('^[0-...
5,291,834
def _get_parameters(kwargs): """ get the parameters for searching The format of input could be a name of parfile, a dictionary, or standard python function arguments. """ #check whether input parameters are surpportted _parameters_legal(kwargs) #read parfile and parameters if "parfil...
5,291,835
def internal_server_error(e): """ global exception demo :param e: :return: """ current_app.logger.debug('raise Exception debug') current_app.logger.info('raise Exception info') current_app.logger.warning('raise Exception warning') current_app.logger.error('raise Exception error') ...
5,291,836
def set_colors(dictionary): """ This function takes the values in a dictionary and attributes them an RGB color. :param dict dictionary: dictionary with variables to be attributed a color, as values. :return: Dictionary where 'dictionary' values are keys and random RGB colors are the values. """ ...
5,291,837
def GetSeries(ds,ThisOne,si=0,ei=-1,mode="truncate"): """ Returns the data, QC flag and attributes of a series from the data structure.""" # number of records if "nc_nrecs" in ds.globalattributes: nRecs = int(ds.globalattributes["nc_nrecs"]) else: nRecs = len(ds.series[ThisOne]["Data"]) ...
5,291,838
def weights_init(m): """ init random weights """ # if isinstance(m, nn.Conv2d): # nn.init.xavier_normal(m.weight.data) # m.bias.data.zero_() if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels ...
5,291,839
def many_constants(): """Generate Python code which includes >256 constants.""" return "".join(f'a = {i}\n' for i in range(300))
5,291,840
def face( draw, raw_strategy: Optional[SearchStrategy[dlib.full_object_detection]] = None, frame_strategy: Optional[SearchStrategy[Frame]] = None, landmarks_strategy: Optional[ SearchStrategy[Dict[FaceFeature, PointSequence]] ] = None, ) -> SearchStrategy[Face]: """Composite strategy to ...
5,291,841
def main() -> None: """Main entry point.""" logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("src_dir", type=str, help='Directory that stores zlib-ng source files') args = parser.parse_args() shutil....
5,291,842
def mosaic_register(outroot, refImage, diffPA): """ Register images for a mosaic. This only calculates the exact shifts between each image... it doesn't do the combining. @param outroot: The root for the output image. The resulting shifts will be written into a file called <outroot>.shifts @typ...
5,291,843
def USgraph_Random(N,L): """ Generates a connected ultra-short graph, random case. Generates a graph with shortest possible pathlength (largest possible efficiency) by adding edges randomly to an initial star graph. Reference and citation ^^^^^^^^^^^^^^^^^^^^^^ G. Zamora-López & R. Brassel...
5,291,844
def MakeText(): """ """ position = position_cursor(3, 999) attrs = dict(optional=0) comment = "Please be as specific as possible" output = deciphervimclips.element_factory(get_current_range(), elType="text", attrs=attrs, ...
5,291,845
def python_stdlib_dirs(): """ Returns (<stdlib-dir>, <sitepkg-dir>, <global-sitepkg-dir>). This exists because sysconfig.get_python_lib(standard_lib=True) returns something surprising when running a virtualenv python (the path to the global python standard lib directory, rather than the virtuale...
5,291,846
def iterate_args(args, command): """ arg can be: - command string - iterable of command parts """ for i, arg in enumerate(args): if i == 0 and isinstance(arg, str) and not command: # allow first argument in the form of a command # only split if not in she...
5,291,847
def remove_parentheses(s: str) -> str: """Returns the string without the parts in parentheses.""" while s != ( s:= re.sub( r"\([^(]*?\)", "", s ) ): pass return s
5,291,848
def import_examples_main(examples_pkg, original_sub, redone_sub, example_names): """ Import the main() function of sereral original and redone example modules. The main() functions are returned in two lists that contain the original main()s and the redone main()s respectively, and in the same order as ...
5,291,849
def main(): """ gameplay """ game_on = True Player = Robot(10, 10, 100) while game_on: command = user_prompt() if command == 'up': Player.move_up() elif command == 'left': Player.move_left() elif command == 'right': Player.move_right() ...
5,291,850
def _model_class_key(model_class: BaseModelParamsT) -> str: """Retrieves a model key from the model class.""" path = model_class.__module__ + '.' + model_class.__name__ # Removes model_registry from `...lingvo.jax.model_registry.`. prefix = _model_class_key.__module__.replace('.model_registry', '.') return pa...
5,291,851
def parse_file(file_name, out): """ Opens a single source code file and applies the changes to it. The function will output the modified source code into the given output stream. @param file_name The psth to the source code file relative to the current working directory @param out Output str...
5,291,852
def GetConformerRMS(mol, confId1, confId2, atomIds=None, prealigned=False): """ Returns the RMS between two conformations. By default, the conformers will be aligned to the first conformer of the molecule (i.e. the reference) before RMS calculation and, as a side-effect, will be left in the aligned state. Ar...
5,291,853
def create_csr(key, subject): """ Parameters ---------- key subject : CertificateSubject Returns ------- """ csb = x509.CertificateSigningRequestBuilder() # todo: is setting a name necessary? csr = csb.subject_name(subject.subject_name) try: csr.add_extension(s...
5,291,854
def covert_excel_list(path: str, sheet_name=None, fill_merged_cell=True) -> list: """ pandas 读取 excel 内容转换为 List :param path: 数据文件路径 :param sheet_name: sheet 名 :param fill_merged_cell: 是否填充合并的单元格,默认需要 :return: 数据列表 list[dict] """ return convert_data_file_2_list(path, pd.read_excel, sheet...
5,291,855
def test_gh_issue_3025(): """Github issue #3025 - improper merging of labels""" d = np.zeros((60,320)) d[:,:257] = 1 d[:,260:] = 1 d[36,257] = 1 d[35,258] = 1 d[35,259] = 1 assert ndimage.label(d, np.ones((3,3)))[1] == 1
5,291,856
def parse_docker_local_ports(docker_ports): """ Take a docker publish port formatted string and return the local port Args: docker_ports: string representation of a docker port publish format Returns: The parsed local port string """ if not isinstance(docker_ports, list): ...
5,291,857
def SelectComponent(ds, idxs): """ Select / reorder components from datapoints. Args: ds (DataFlow): input DataFlow. idxs (list[int]): a list of component indices. Example: .. code-block:: none dp: [c1, c2, c3] idxs: [2,1] output dp: [c3, c2] """ r...
5,291,858
def pytest_collection_modifyitems(config, items): """A pytest hook to modify the configuration and items to run.""" del config # Exit early if we have nothing to do. if not items: return # Fail early and verbosely if the flags cannot be accessed. This is a sign # that this file is being used incorrect...
5,291,859
def open_file(path: Path) -> NoReturn: """Opens the file using the system's default handler.""" if system() == "Linux": err = subprocess.run(["xdg-open", str(path.resolve())], shell=False) elif system() == "Windows": err = subprocess.run(["start", str(path.resolve())], shell=False) elif ...
5,291,860
def any_process_info_by_state(state): """ Return a copy of any process in state 'state' in database. """ info = random.choice([info for info in ProcessInfoDatabase if info['state'] == state]) return extract_process_info(info)
5,291,861
def entryfunc_namedtuple(buf: bytes, pos: array, globaloffset: int) -> Entry: """ Build a FASTQ entry as a namedtuple with attributes header, sequence, and quality. - buf: bytes-like object - pos: array of indices/positions in `buf` """ header = buf[(pos[0]+1):pos[1]] sequence = buf[po...
5,291,862
def generate_tiles(crs, zoom): """ Generate tiles for the manifest. """ #generate tiles tiles = [] #calculate bbox for input geometry if geom is none: for tile in mt.tiles(*DEFAULT_TILES, zoom, truncate=False): tile_id = f"{tile.z}_{tile.x}...
5,291,863
def url_unquote(quoted): """Perform URL percent decoding on *quoted*. Encapsulated because in Python 3 :func:`python:urllib.parse.unquote` works directly on Unicode strings, while in Python 2 the corresponding :func:`python:urllib.unquote` does not tolerate Unicode characters. """ if sy...
5,291,864
def _darknet_conv2d(inputs, params, attrs, prefix): """Process the convolution 2d operation.""" new_attrs = {} kernel = attrs.get('kernel') strides = attrs.get('stride', 1) pads = attrs.get('pad', 0) new_attrs['channels'] = attrs.get('num_filter') new_attrs['kernel_size'] = (kernel, kernel)...
5,291,865
def filter_emoji(desstr, restr=''): """ 过滤特殊表情,只保留中文、英文、数字 """ # 一个网名为【......】的网友,随机生成为6位的字符 if desstr == r'......': return make_random_string(6) cop = re.compile("[^\u4e00-\u9fa5^.^a-z^A-Z^0-9]") return cop.sub(restr, desstr)
5,291,866
def solve_gurobi(mu, nu, c, mtd=-1): """Base routine for calling gurobi solver """ m, n = c.shape M = Model("OT") M.setParam('OutputFlag', 0) M.setParam(GRB.Param.Method, mtd) s = gurobi_set_model(mu, nu, c, M) M.optimize() sx = M.getAttr("x", s) ans = np.array([sx[i, j] for ...
5,291,867
def test_getB_interfaces2(): """self-consistent test of different possibilities for computing the field""" src = magpy.magnet.Cuboid((1, 2, 3), (1, 2, 3)) src.move(np.linspace((0.1, 0.2, 0.3), (1, 2, 3), 10), start=-1) poso = [[(-1, -1, -1)] * 2] * 2 sens = magpy.Sensor(pixel=poso) B = magpy.get...
5,291,868
def dataset_for_train_test_split(X_train, X_test, Y_train, Y_test, threshold=1, multi_word_queries=False, scaler='standard'): """Make dataset from a train-test-split This function scales the input data und generates queries and query-weights from the training set vocabulary...
5,291,869
def stream_copy_to_stream(): """ Copies data from one stream to another""" raise NotImplementedError()
5,291,870
def get_site_mau_history_metrics(site, months_back): """Quick adaptation of `get_monthly_history_metric` for site MAU The `months_back` gets the previous N months back not including current month because we do not capture the current month until it is over. Meaning we wait until the next month to creat...
5,291,871
def diehard_pybites(): """Return a Stats namedtuple (defined above) that contains the user that made the most PRs (ignoring the users in IGNORE) and a challenge tuple of most popular challenge and the amount of PRs for that challenge. Calling this function on the dataset (held tempfile) should ...
5,291,872
def get_mapindex(res, index): """Get the index of the atom in the original molecule Parameters ---------- res : prolif.residue.Residue The residue in the protein or ligand index : int The index of the atom in the :class:`~prolif.residue.Residue` Returns ------- mapindex...
5,291,873
def predict(model, smis: Iterable[str], batch_size: int = 50, ncpu: int = 1, uncertainty: bool = False, scaler: Optional[StandardScaler] = None, use_gpu: bool = False, disable: bool = False): """Predict the target values of the given SMILES strings with the input model Parameters ...
5,291,874
def funcOnModels(f, models): """ If you have a big array of models, this function allows you to extract big arrays of model outputs. For example, suppose that you have a 2x5x20 nested list of models and you want to find the last critical temperature of each model. Then use >>> Tcrit = funcOnMod...
5,291,875
def main(): """ myList = putPrimeNumbersIntoList(10) print("myList= ") print(myList) squared_sum = sumSquaredList(myList) print("sumSquaredLists = ") print(squared_sum) """ jamMan()
5,291,876
def find_projection(Lm, Lb, Rm, Rb, ORIGINAL_SIZE, UNWARPED_SIZE, HozTop = 50, HozBottom = 0, porc = 0.3): """ Find projection surface parameters from lane lines Args: Lm: `float` linear regression slope of left lane line Lb: `float` linear regression y-intercept of left lane line ...
5,291,877
def tensors_from_dataset(dataset): """Converts a tf.data.Dataset to nested tf.Tensors.""" tensors = list(dataset) if tensors: return tf.nest.map_structure(lambda *tensors: tf.stack(tensors), *tensors) # Return empty tensors if the dataset is empty. shapes_dtypes = zip( tf.nest.flatten(dataset.output...
5,291,878
def test_res_dual(blob_bin, C): """Check LinearSVC is equivalent to sklearn for two-class case, dual=True. Parameters ---------- blob_bin : tuple pytest fixture. See blob_bin. C : float Inverse regularization parameter for the LinearSVC. """ # PRNG seed _seed = 7 # u...
5,291,879
def delete_file(filename: str) -> None: """ Deletes the given file. :param filename: Filename with path :return: None """ try: os.remove(filename) except OSError as e: # this would be "except OSError, e:" before Python 2.6 if e.errno != errno.ENOENT: # errno.ENOENT = no suc...
5,291,880
def gain_selection(waveform, charges, peak_time, threshold): """ Custom lst calibration. Update event.dl1.tel[telescope_id] with calibrated image and peakpos Parameters ---------- waveform: array of waveforms of the events charges: array of calibrated pixel charges peak_time: array of ...
5,291,881
def test_medication_7(base_settings): """No. 7 tests collection for Medication. Test File: medicationexample0303.json """ filename = base_settings["unittest_data_dir"] / "medicationexample0303.json" inst = medication.Medication.parse_file( filename, content_type="application/json", encoding=...
5,291,882
def magic_to_rdb(magic_input: str, input_file_path: str = "UNKNOWN") -> str: """ >>> print(magic_to_rdb('''RAM8 ... ---------------------------------------- ... P-diff distance to N-tap must be < 15.0um (LU.3) ... ---------------------------------------- ... 17.990um 21.995um 18.265um 22.995um ...
5,291,883
def minos_style(smerr): """Convert minos error to style""" return Struct( is_valid=good(smerr.is_valid, True), lower_valid=good(smerr.lower_valid, True), upper_valid=good(smerr.upper_valid, True), at_lower_limit=good(smerr.at_lower_limit, False), at_upper_limit=good(smerr...
5,291,884
def is_dummy_definition(definition: hou.HDADefinition) -> bool: """Check if this definition is a dummy definition. A dummy, or empty definition is created by Houdini when it cannot find an operator definition that it needs in the current session. :param definition: The definition to check. :return...
5,291,885
def float_to_uint8(x: np.ndarray[np.float32]) -> np.ndarray[np.uint8]: """Transforms an np.float32 image into a np.uint8 image Parameters ---------- x: np.array[np.float32] Input image of shape (width,height,channels) Returns ------- output: np.array[np.uint8] Output image ...
5,291,886
def transform_password(password_str): """Transform the password string into 32 bit MD5 hash :param password_str: <str> password in plain text; :return: <str> Transformed password fixed length """ h = MD5.new() h.update(password_str.encode()) return h.hexdigest()
5,291,887
def bootstrap_messages(context, *args, **kwargs): """ Show request messages in Bootstrap style """ return get_template("bootstrap_toolkit/messages.html").render(context)
5,291,888
def p_expression_group(p): """ expression : LPAREN expression RPAREN """ p[0] = p[2]
5,291,889
def get_combos(itr1, itr2): """Returns all the combinations of elements between two iterables.""" return [[x, y] for x in itr1 for y in itr2]
5,291,890
def uqcsbot(_uqcsbot: MockUQCSBot): """ Setup and tear-down steps to run around tests. """ # Anything before yield will be run before test # Initialise channels and users _uqcsbot.channels._initialise() _uqcsbot.users._initialise() yield _uqcsbot # Anything after yield will be run af...
5,291,891
def get_special_character_treatment(behavior='remove'): """ Provides the correct utility function for desired special character parsing :param behavior - the desired operation to perform on special characters :returns a utility function to apply to the string with special characters """ return {'re...
5,291,892
def _get_image_info_from_path(image_path: str) -> Tuple[str, str]: """Gets image info including sequence id and image id. Image path is in the format of '.../split/sequence_id/image_id.png', where `sequence_id` refers to the id of the video sequence, and `image_id` is the id of the image in the video sequence....
5,291,893
def exhaustive_search(f, template, candidate_field, verbose=False): """Applies f(template, candidate) to every candidate in candidate_field.""" if not verbose: logger.disabled = True min_f, min_i, min_j, count = np.inf, 0, 0, 0 logger.debug(candidate_field.shape) logger.debug(template.shap...
5,291,894
def compute_new_world_origin(poses, method): """ Computes the origin of the new world coordinate system (W2) given N pose matrices. Each of the N pose matrices can transform a point from a camera coordinate system to a arbitrary world coordinate system (W1). In this function, we want to comp...
5,291,895
def assert_len_eq(l): """Check all lists in a list are equal length""" # Sanity check max_len = max(len(p) for p in l) for i, p in enumerate(l): assert len( p ) == max_len, "Length check failed!\nl[{}] has {} elements != {} ({!r})\n{!r}".format( i, len(p), max_len...
5,291,896
def exit_on_lost(state): """Watch for connection events and exit if disconnected.""" _LOGGER.debug('ZK connection state: %s', state) if state == states.KazooState.LOST: _LOGGER.info('Exiting on ZK connection lost.') utils.sys_exit(-1)
5,291,897
def _build_forward_graph(model, single_gpu_build_func): """Construct the forward graph on each GPU.""" all_loss_gradients = {} # Will include loss gradients from all GPUs # Build the model on each GPU with correct name and device scoping for gpu_id in range(cfg.NUM_GPUS): with c2_utils_NamedCud...
5,291,898
def numpy_compiler(model): """Take a triflow model and return optimized numpy routines. Parameters ---------- model: triflow.Model: Model to compile Returns ------- (numpy function, numpy function): Optimized routine that compute the evolution equations and their ja...
5,291,899