content
stringlengths
22
815k
id
int64
0
4.91M
def write_changes(changes_file, changes): """Write SVs and SNPs to a file""" with open(changes_file, "w") as outfile: header = "\t".join(["type", "ref_idx", "alt_idx", "size", "ref", "alt", "\n"]) outfile.write(header) for change in changes: change...
5,352,900
def lambda_handler(event, context): """ Lambda entry-point """ news_link = "https://news.ok.ubc.ca/feed/" news_items = [] filtered_news_items = [] response_items = get_news_items_from_web(news_link) if len(response_items) == 0: return {"status": "No items in RSS Feed"} # It...
5,352,901
def read_photons(photonfile, ra0, dec0, tranges, radius, verbose=0, colnames=['t', 'x', 'y', 'xa', 'ya', 'q', 'xi', 'eta', 'ra', 'dec', 'flags']): """ Read a photon list file and return a python dict() with the expected format. :param photonfile: Name of ...
5,352,902
def normElec(surf, electrode, normdist, NaN_as_zeros=True): """ Notes ----- When `normway` is a scalar, it takes the normal of the points of the mesh which are closer than `normway`. However, some points have a normal of (0, 0, 0) (default assigned if the vertex does not belong to any triangle)....
5,352,903
def filter_sources(sources, release): """Check if a source has already been consumed. If has not then add it to sources dict. """ source, version, dist, arch = parse_release(release) if source not in sources.keys(): sources[source] = {version: {dist: [arch]}} return True elif ver...
5,352,904
async def train(model, *args: Union[BaseSource, Record, Dict[str, Any]]): """ Train a machine learning model. Provide records to the model to train it. The model should be already instantiated. Parameters ---------- model : Model Machine Learning model to use. See :doc:`/plugins/df...
5,352,905
def get_os(): """ if called in powershell returns "powershell" if called in cygwin returns "cygwin" if called in darwin/osx returns "osx" for linux returns "linux" """ env = os.environ p = platform.system().lower() terminal = p operating_system = p if p == 'windows': ...
5,352,906
def setup_model_and_optimizer(args): """Setup model and optimizer.""" print ("setting up model...") model = get_model(args) print ("setting up optimizer...") optimizer = get_optimizer(model, args) print ("setting up lr scheduler...") lr_scheduler = get_learning_rate_scheduler(optimizer, arg...
5,352,907
def ensure_str(origin, decode=None): """ Ensure is string, for display and completion. Then add double quotes Note: this method do not handle nil, make sure check (nil) out of this method. """ if origin is None: return None if isinstance(origin, str): return origi...
5,352,908
def verdi_config_set(ctx, option, value, globally, append, remove): """Set an AiiDA option. List values are split by whitespace, e.g. "a b" becomes ["a", "b"]. """ from aiida.manage.configuration import Config, ConfigValidationError, Profile if append and remove: echo.echo_critical('Cannot...
5,352,909
def restore( collection: str, id: Union[str, int, Dict[str, Any]] ) -> Optional[Dict[str, Any]]: """Restrieve cached data from database. :param collection: The collection to be retrieved. Same name as API commands. :type collection: str :param id: The unique identifier for a particular collection. ...
5,352,910
def encode_bits(data, number): """Turn bits into n bytes of modulation patterns""" # 0000 00BA gets encoded as: # 128 64 32 16 8 4 2 1 # 1 B B 0 1 A A 0 # i.e. a 0 is a short pulse, a 1 is a long pulse #print("modulate_bits %s (%s)" % (ashex(data), str(number))) shift = number-...
5,352,911
def compute_session_changes(session, task=None, asset=None, app=None): """Compute the changes for a Session object on asset, task or app switch This does *NOT* update the Session object, but returns the changes required for a valid update of the Session. Args: session (dict): The initial sessi...
5,352,912
def _tf_get_negs( all_embed: "tf.Tensor", all_raw: "tf.Tensor", raw_pos: "tf.Tensor", num_neg: int ) -> Tuple["tf.Tensor", "tf.Tensor"]: """Get negative examples from given tensor.""" if len(raw_pos.shape) == 3: batch_size = tf.shape(raw_pos)[0] seq_length = tf.shape(raw_pos)[1] else: ...
5,352,913
def remove(store_config, shardid): # FIXME require config instead """Remove a shard from the store. Args: store_config: Dict of storage paths to optional attributes. limit: The dir size limit in bytes, 0 for no limit. use_folder_tree: Files organized in a fo...
5,352,914
def init_db(path: Union[str, 'os.PathLike'] = db_constants.DB_PATH) -> Optional[sqlite3.dbapi2.Connection]: """Initialises the DB. Returns a sqlite3 connection, which will be passed to the db thread. """ # TODO: change saving version from float to string def db_layout(cursor: sqlite3.dbapi2.Cursor)...
5,352,915
def load_pdb(path): """ Loads all of the atomic positioning/type arrays from a pdb file. The arrays can then be transformed into density (or "field") tensors before being sent through the neural network. Parameters: path (str, required): The full path to the pdb file being voxelized. ...
5,352,916
def confusion_matrix_cli( test_statistics: Union[str, List[str]], ground_truth_metadata: str, **kwargs: dict ) -> None: """Load model data from files to be shown by confusion_matrix. # Inputs :param test_statistics: (Union[str, List[str]]) path to experiment test statistics...
5,352,917
def test_proton_model(): """ test import """ from ..sherpa_models import PionDecay model = PionDecay() model.ampl = 1e36 model.index = 2.1 # point calc output = model.calc([p.val for p in model.pars], energies) # integrated output = model.calc([p.val for p in model.pars]...
5,352,918
def validate_workspace( workspace_option: str, available_paths: List[str] = list(WORKSPACE_PATHS.values()) ) -> str: """Validate and return workspace. :param workspace_option: A string of the workspace to validate. :type workspace_option: string :param available_paths: A list of the available works...
5,352,919
def compileShaders(self): """Loads the vertex/fragment shader source code, and creates a :class:`.GLSLShader` program. """ if self.shader is not None: self.shader.destroy() vertSrc = shaders.getVertexShader( 'glvolume') fragSrc = shaders.getFragmentShader('glrgbvolume') textures ...
5,352,920
def __filter_handler(query_set, model, params): """ Handle user-provided filtering requests. Args: query_set: SQLAlchemy query set to be filtered. model: Data model from which given query set is generated. params: User-provided filter params, with format {"query": [...], ...}. ...
5,352,921
def split_data_set(data_set, axis, value): """ 按照给定特征划分数据集,筛选某个特征为指定特征值的数据 (然后因为是按该特征进行划分了,该特征在以后的划分中就不用再出现,所以把该特征在新的列表中移除) :param data_set: 待划分的数据集,格式如下,每一行是一个list,list最后一个元素就是标签,其他元素是特征 :param axis: 划分数据集的特征(特征的序号) :param value: 需要返回的特征的值(筛选特征的值要等于此值) :return: >>>myDat ...
5,352,922
def get_ast(target_func_or_module): """ See :func:``bettertimeit`` for acceptable types. :returns: an AST for ``target_func_or_module`` """ if isinstance(target_func_or_module, ast.AST): return target_func_or_module if not isinstance(target_func_or_module, (six.st...
5,352,923
def enumerate_spans(sentence: List[T], offset: int = 0, max_span_width: int = None, min_span_width: int = 1, filter_function: Callable[[List[T]], bool] = None) -> List[Tuple[int, int]]: """ Given a sentence, return all token spans w...
5,352,924
def test_fetch_fraction_timestamp(conn_cnx): """Additional fetch timestamp tests. Mainly used for SnowSQL which converts to string representations.""" PST_TZ = "America/Los_Angeles" converter_class = SnowflakeConverterSnowSQL sql = """ SELECT '1900-01-01T05:00:00.000Z'::timestamp_tz(7), '1900-0...
5,352,925
def fixed_mu(mu, data, qty, comp='muAI', beads_2_M=1): """ """ return fixed_conc(mu*np.ones([len(data.keys())]), data, qty, comp=comp, beads_2_M=beads_2_M)
5,352,926
def error_nrmse(y_true, y_pred, time_axis=0): """ Computes the Normalized Root Mean Square Error (NRMSE). The NRMSE index is computed separately on each channel. Parameters ---------- y_true : np.array Array of true values. If must be at least 2D. y_pred : np.array Array of pr...
5,352,927
def test_normalization_2d(): """test for Normalization2D""" # TODO: Because the expected behaviour of this layer is somehow confusing for me now
5,352,928
def main(): """ Compute binary scores for target words. """ # Get the arguments args = docopt("""Compute binary scores for taget words. Usage: binary.py <path_distances> <path_output> <thres_percentage> binary.py <path_distances> <path_targets> <path_output> <thres_percent...
5,352,929
def show(font_size=20): """ Display a figure. """ plt.rcParams.update({'font.size': font_size}) plt.show()
5,352,930
def is_valid_file(parser, arg): """ Function used to check if a valid VLC path was given. """ if not os.path.exists(arg): parser.error( f"The filepath {arg} does not exist! Be sure to include quotes around the path, view help for more info." )
5,352,931
def test_get_checksum_not_in_cache(tmp_path): """Test the checksum cache_dict.""" assert cache_dict == {} file_path = tmp_path / 'space.js' file_path.write_text('punkcat') get_checksum(file_path) assert str(file_path) in cache_dict
5,352,932
def load(ctx: Context, opts: LoadOptions): """Plugin that loads data packs and resource packs.""" for config, pack in zip([opts.resource_pack, opts.data_pack], ctx.packs): for pattern in [config] if isinstance(config, str) else config: for path in glob(str(ctx.directory / pattern)): ...
5,352,933
def rmdir_empty(f): """Returns a count of the number of directories it has deleted""" if not f.is_dir(): return 0 removable = True result = 0 for i in f.iterdir(): if i.is_dir(): result += rmdir_empty(i) removable = removable and not i.exists() else: ...
5,352,934
def delete_suggester(DomainName=None, SuggesterName=None): """ Deletes a suggester. For more information, see Getting Search Suggestions in the Amazon CloudSearch Developer Guide . See also: AWS API Documentation :example: response = client.delete_suggester( DomainName='string', ...
5,352,935
def generic_exception_json_response(code): """ Turns an unhandled exception into a JSON payload to respond to a service call """ payload = { "error": "TechnicalException", "message": "An unknown error occured", "code": code } resp = make_response(jsonify(pa...
5,352,936
def UnN(X, Z, N, sampling_type, kernel="prod"): """Computes block-wise complete U-statistic.""" def fun_block(x, z): return Un(x, z, kernel=kernel) return UN(X, Z, N, fun_block, sampling_type=sampling_type)
5,352,937
def delete_card(request): """Delete card""" return delete_container_element(request)
5,352,938
def build_estimator(tf_transform_dir, config, hidden_units=None): """Build an estimator for predicting the tipping behavior of taxi riders. Args: tf_transform_dir: directory in which the tf-transform model was written during the preprocessing step. config: tf.contrib.learn.RunConfig defining the runt...
5,352,939
def get_plot_grid_size(num_plots, fewer_rows=True): """ Returns the number of rows and columns ideal for visualizing multiple (identical) plots within a single figure Parameters ---------- num_plots : uint Number of identical subplots within a figure fewer_rows : bool, optional. Default...
5,352,940
def note_view(): """Display a grid of notes and options to manipulate those notes or create new notes.""" # attempt to retrieve notes from previous run and print to screen os.system('clear') try: note_list = retrieve_notes() print_grid(note_list) options = [ '✎ Make a...
5,352,941
def check_source(module): """ Check that module doesn't have any globals. Example:: def test_no_global(self): result, line = check_source(self.module) self.assertTrue(result, "Make sure no code is outside functions.\\nRow: " + line) """ try: source = module.__...
5,352,942
def _create_lagged_variable_panel(df, col, id_col="TICKER", num_lags=1): """ Note: inplace """ new_name = varname_to_lagged_varname(col, num_lags=num_lags) df[new_name] = df.groupby(id_col)[col].shift(num_lags)
5,352,943
def pre_processing(X): """ Center and sphere data.""" eps = 1e-18 n = X.shape[0] cX = X - np.mean(X, axis=0) # centering cov_mat = 1.0/n * np.dot(cX.T, cX) eigvals, eigvecs = eigh(cov_mat) D = np.diag(1./np.sqrt(eigvals+eps)) W = np.dot(np.dot(eigvecs, D), eigvecs.T) # whitening matrix ...
5,352,944
def task_grid(): """Grid classifier.""" for mode, sl in product(MODES, SAMPLELISTS): paths = dwi.paths.Paths(mode) lesioninfo = defaultdict(list) for c, s, l in dwi.dataset.iterlesions(str(paths.samplelist(sl))): c, l, lt = c.num, l.index + 1, l.location lesioninf...
5,352,945
def get_as_tags(bundle_name, extension=None, config="DEFAULT", attrs=""): """ Get a list of formatted <script> & <link> tags for the assets in the named bundle. :param bundle_name: The name of the bundle :param extension: (optional) filter by extension, eg. "js" or "css" :param config: (optiona...
5,352,946
def _init_tables(app): """Creates sql lite tables""" if not os.path.exists(_db_filename(app)): pkdlog('creating user oauth database') _db.create_all()
5,352,947
def psql(statement, timeout=30): """Execute a statement using the psql client.""" LOG.debug('Sending to local db: {0}'.format(statement)) return execute('psql', '-c', statement, timeout=timeout)
5,352,948
def devpiserver_get_credentials(request): """Search request for X-Remote-User header. Returns a tuple with (X-Remote-User, '') if credentials could be extracted, or None if no credentials were found. The first plugin to return credentials is used, the order of plugin calls is undefined. """ ...
5,352,949
def vader_sentiment( full_dataframe, grading_column_name, vader_columns=COLUMN_NAMES, logger=config.LOGGER ): """apply vader_sentiment analysis to dataframe Args: full_dataframe (:obj:`pandas.DataFrame`): parent dataframe to apply analysis to grading_column_name ...
5,352,950
def _reload(name="pynrc"): """ Simple reload function to test code changes without restarting python. There may be some weird consequences and bugs that show up, such as functions and attributes deleted from the code still stick around after the reload. Although, this is even true with ``importlib.r...
5,352,951
def _overlayPoints(points1, points2): """Given two sets of points, determine the translation and rotation that matches them as closely as possible. Parameters ---------- points1 (numpy array of simtk.unit.Quantity with units compatible with distance) - reference set of coordinates points2 (numpy ar...
5,352,952
def return_request(data): """ Arguments: data Return if call detect: list[dist1, dist2, ...]: dist = { "feature": feature } Return if call extract: list[dist1, dist2, ...]: dist = { "confidence_score": predict p...
5,352,953
def test_successful_association_validation_2(): """This test adds another host to make sure that associations with no count specified in the profile are handled correctly.""" test_associations = [{ 'type': 'Document', 'name': 'blahblah.txt' }, { 'type': 'Document', 'name': 'b...
5,352,954
def test_validate_payload_with_invalid_payload(): """ Test if validate_payload raises ValidationError when validation of payload failes. """ message = CallResult( unique_id="1234", action="Heartbeat", payload={'invalid_key': True}, ) with pytest.raises(ValidationErro...
5,352,955
def test_after_space(): """Test procedure for after_space""" print('Testing after_space') # Test case 1 s = currency.after_space('Hello World') introcs.assert_equals('World',s) # Test case 2 s = currency.after_space(' Hello World') introcs.assert_equals('Hello World',s) # Test cas...
5,352,956
def get_recent_messages_simple(e: TextMessageEventObject): """ Command to get the most recent messages with default count. This command has a cooldown of ``Bot.RecentActivity.CooldownSeconds`` seconds. This command will get the most recent ``Bot.RecentActivity.DefaultLimitCountDirect`` messages withou...
5,352,957
def parse_systemctl_units(stdout:str, stderr:str, exitcode:int) -> dict: """ UNIT LOAD ACTIVE SUB DESCRIPTION mono-xsp4.service loaded active...
5,352,958
def resnet_model_fn(is_training, feature, label, data_format, params): """Build computation tower (Resnet). Args: is_training: true if is training graph. feature: a Tensor. label: a Tensor. data_format: channels_last (NHWC) or channels_first (NCHW). params: params for the model to...
5,352,959
def permutate_touched_latent_class(untouched_classes, class_info_np, gran_lvl_info): """untouch certain class num latent class, permute the rest (reserve H(Y))""" # get untouched instance index untouched_instance_index = [] for i in untouched_classes: index = np.where(class_info_np == i)[0] ...
5,352,960
def setup(c, editable=True, version='3.8'): """Setup development environment """ print('Creating conda environment...') c.run(f'conda create --name scaffold python={version} --force --yes') print('Installing package...') flag = '--editable' if editable else '' conda.run_in_env(c, f'pip insta...
5,352,961
def get_interarrival_times(arrival_times, period_start): """ Given a list of report dates, it returns the list corresponding to the interrival times. :param arrival_times: List of arrival times. :return: List of inter-arrival times. """ interarrival_times = [] for position, created_date in ...
5,352,962
def _indexOp(opname): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ def wrapper(self, other): func = getattr(self.view(np.ndarray), opname) return func(other) return wrapper
5,352,963
def safe_log(a): """ Return the element-wise log of an array, checking for negative array elements and avoiding divide-by-zero errors. """ if np.any([a < 0]): raise ValueError('array contains negative components') return np.log(a + 1e-12)
5,352,964
def parse_treepath(k=23): """Parse treepath results""" results = {} treepath_file = "treepath.k{}.csv".format(k) if not os.path.isfile(treepath_file): print("No treepath results found", file=sys.stderr) return with open(treepath_file, 'rb') as f: f.readline() # skip header ...
5,352,965
def test_patch_passport() -> None: """ Ignored fields: {"uuid", "internal_id", "is_in_db", "featured_in_int_id"}. Send anything, nothing will be changed """ token = login() passport_patch = { "uuid": "fake", "internal_id": "fake", "passport_short_url": "new_url", "is_...
5,352,966
def test_alphabet_as_string_violation( assert_errors, assert_error_text, parse_ast_tree, code, prefix, default_options, ): """Testing that the strings violate the rules.""" tree = parse_ast_tree('{0}"{1}"'.format(prefix, code)) visitor = WrongStringVisitor(default_options, tree=tree...
5,352,967
def test_set_default_temperature_rise(): """should return the default capacitance for the selected subcategory ID.""" assert inductor._set_default_temperature_rise(1, 1) == 10.0 assert inductor._set_default_temperature_rise(1, 3) == 30.0 assert inductor._set_default_temperature_rise(2, 1) == 10.0
5,352,968
def _set_quota(user, quota): """Set the quota of the user to the given value, and restore the old value when exit""" oldquota = seafilerpc.get_user_quota(user) if seafilerpc.set_user_quota(user, quota) < 0: raise RuntimeError('failed to change user quota') assert seafilerpc.get_user_quota(user) ...
5,352,969
def deduplicate( timeseries: List[TimeseriesEntry], margins: Dict[str, float] = {}, ) -> List[TimeseriesEntry]: """ Remove duplicates from the supplied `timeseries`. Currently the deduplication relies on `timemseries` being formatted according to how data is stored in `Weather.series.values()`. The fun...
5,352,970
def build_windows_subsystem(profile, make_program): """ The AutotoolsDeps can be used also in pure Makefiles, if the makefiles follow the Autotools conventions """ # FIXME: cygwin in CI (my local machine works) seems broken for path with spaces client = TestClient(path_with_spaces=False) client....
5,352,971
def monitor_service(exported_metric, url, csv_filename, sleep_amount, max_records): """Monitor selected service and export retrieved metrics into CSV file.""" # Try to open new file for writing. with open(csv_filename, 'w') as csvfile: # Initialize CSV writer. writer = csv.writer(csvfile, qu...
5,352,972
def make_batch_keys(args, extras=None): """depending on the args, different data are used by the listener.""" batch_keys = ['objects', 'tokens', 'target_pos'] # all models use these if extras is not None: batch_keys += extras if args.obj_cls_alpha > 0: batch_keys.append('class_labels')...
5,352,973
def init_dic_OP(universe_woH, dic_atname2genericname, resname): """Initialize the dictionary of result (`dic_op`). Initialize also the dictionary of correspondance between residue number (resid) and its index in dic_OP (`dic_corresp_numres_index_dic_OP`). To calculate the error, we need to first avera...
5,352,974
def magic_split(value: str, sep=",", open="(<", close=")>"): """Split the value according to the given separator, but keeps together elements within the given separator. Useful to split C++ signature function since type names can contain special characters... Examples: - magic_split("a,b,c", se...
5,352,975
def update_group_annotation(name=None, annotation_name=None, x_pos=None, y_pos=None, angle=None, opacity=None, canvas=None, z_order=None, network=None, base_url=DEFAULT_BASE_URL): """Update Group Annotation Updates a group annotation, changing the given properties. Args: ...
5,352,976
def _extract_properties(properties_str): """Return a dictionary of properties from a string in the format ${key1}={value1}&${key2}={value2}...&${keyn}={valuen} """ d = {} kv_pairs = properties_str.split("&") for entry in kv_pairs: pair = entry.split("=") key = urllib.parse.unquo...
5,352,977
def first_fail_second_succeed(_: Any, context: Any) -> str: """ Simulate Etherscan saying for the first time 'wait', but for the second time 'success'. """ context.status_code = 200 try: if first_fail_second_succeed.called: # type: ignore return '{ "status": "1", "result" : "Pass - Veri...
5,352,978
def get_ipsw_url(device, ios_version, build): """Get URL of IPSW by specifying device and iOS version.""" json_data = fw_utils.get_json_data(device, "ipsw") if build is None: build = fw_utils.get_build_id(json_data, ios_version, "ipsw") fw_url = fw_utils.get_firmware_url(json_data, build) ...
5,352,979
def cvt_video2img(src_folder, dst_folder,fps=5,wh_size=(720,500), exclusion_range=580, pre_trim_sec=10,duration=30,extension='mp4'): """ exclusion_range: This arg define exclusion area to prevents the overlapping of same event situation. pre_trim_sec: This arg define how long set t...
5,352,980
def check_input_dir(input_dir: Path, contained_dirs: List[str] = None, contained_files: List[str] = None): """Check if the input_dir contains all the contained_dirs and contained_files.""" if not input_dir.is_dir(): raise Exception("{} is not an existed directory.".format(input_dir.absolute())) if n...
5,352,981
async def test_combine(dut): """Test the Combine trigger.""" # gh-852 async def coro(delay): await Timer(delay, "ns") tasks = [await cocotb.start(coro(dly)) for dly in [10, 30, 20]] await Combine(*(t.join() for t in tasks))
5,352,982
def escape_parameter(value: Any) -> str: """ Escape a query parameter. """ if value == "*": return value if isinstance(value, str): value = value.replace("'", "''") return f"'{value}'" if isinstance(value, bytes): value = value.decode("utf-8") return f"'{v...
5,352,983
def customAction(pcap): """对一个 session 中的每一个 packet 进行匿名化的处理 Args: pcap: 每一个 packet 文件 """ src_ip = "0.0.0.0" src_ipv6 = "0:0:0:0:0:0:0:0" src_port = 0 src_mac = "00:00:00:00:00:00" dst_ip = "0.0.0.0" dst_ipv6 = "0:0:0:0:0:0:0:0" dst_port = 0 dst_mac = "00:00:00:00:...
5,352,984
def subplot3D(ax, code_azi, code_ele, ant_azi_num, ant_ele_num): """A beamforming pattern of uniform rectangular array""" thetas = np.linspace(0, 2*math.pi, 100, endpoint=False) betas = np.linspace(-math.pi/2, math.pi/2, 50) values = np.zeros((len(betas), len(thetas)), dtype=np.float32) for i, beta ...
5,352,985
def Get_Query(Fq): """ Get_Query """ Q = "" EoF = False Ok = False while True: l = Fq.readline() if ("--" in l) : # skip line continue elif l=="": EoF=True break else: Q += l if ";" in ...
5,352,986
def get_path_segments(url): """ Return a list of path segments from a `url` string. This list may be empty. """ path = unquote_plus(urlparse(url).path) segments = [seg for seg in path.split("/") if seg] if len(segments) <= 1: segments = [] return segments
5,352,987
def get_config_file(c: typing.Union[str, ConfigFile, None]) -> typing.Optional[ConfigFile]: """ Checks if the given argument is a file or a configFile and returns a loaded configFile else returns None """ if c is None: # See if there's a config file in the current directory where Python is being...
5,352,988
def get_logger(tag: str) -> Logger: """ Produces logger with given message tag which will write logs to the console and file stored in LOG_FILE_PATH directory :param tag: tag for messages of the logger :return: logger object """ logger = logging.getLogger(tag) logger.setLevel(logging.DE...
5,352,989
def get_index(): """Redirects the index to /form """ return redirect("/form")
5,352,990
def print_letter(letter): """Prints a letter. The input variable is the index of the letter to print. The letters from A to Z are indexed at 0 (so A=0, B=1, etc). There are currently 2 addition special 'characters'. 26 will 'print' a space 27 will execute a 'new line' You are free to add any...
5,352,991
def create_init_db(dbpath=_NBSEARCH_DB_PATH, clear=False): """Create and initialise database.""" if clear and os.path.exists(dbpath): os.remove(dbpath) db = sqlite_utils.Database(dbpath) create_tables(db)
5,352,992
def _register_network(network_id: str, chain_name: str): """Register a network. """ network = factory.create_network(network_id, chain_name) cache.infra.set_network(network) # Inform. utils.log(f"registered {network.name_raw} - metadata") return network
5,352,993
def cli(*args, **kwargs): """Execute scripts on a device via a serial port.""" # print(f"args = {args}, kwargs = {kwargs}") if kwargs["debug_mode"]: import debugpy print(f"Debugging is enabled, listening on: {DEBUG_ADDR}:{DEBUG_PORT}.") debugpy.listen(address=(DEBUG_ADDR, DEBUG_PO...
5,352,994
def test_adjust_inv_sigmoid_cutoff_half(): """Verifying the output with expected results for inverse sigmoid correction with cutoff equal to half and gain of 10""" image = np.arange(0, 255, 4, np.uint8).reshape((8, 8)) expected = np.array([ [253, 253, 252, 252, 251, 251, 250, 249], [249,...
5,352,995
def run_cmd(command: Cmd, cmd_parameters: Dict[str, str], workdir: str): """Run a single command.""" cmdline = command.cmd.format(**cmd_parameters) print('Running: {}'.format(cmdline)) start_time = datetime.datetime.now() proc = subprocess.Popen(cmdline, shell=True, cwd=workdir, text=True, stdout=su...
5,352,996
def file(base_path, other_path): """ Returns a single file """ return [[Path(base_path), Path(other_path)]]
5,352,997
def get_md_resource(file_path): """Read the file and parse into an XML tree. Parameters ---------- file_path : str Path of the file to read. Returns ------- etree.ElementTree XML tree of the resource on disk. """ namespaces = Namespaces().get_namespaces(keys=('gmd'...
5,352,998
def fmin_style(sfmin): """convert sfmin to style""" return Struct( is_valid=good(sfmin.is_valid, True), has_valid_parameters=good(sfmin.has_valid_parameters, True), has_accurate_covar=good(sfmin.has_accurate_covar, True), has_posdef_covar=good(sfmin.has_posdef_covar, True), ...
5,352,999