content
stringlengths
22
815k
id
int64
0
4.91M
def collect_targets_from_attrs(rule_attrs, attrs): """Returns a list of targets from the given attributes.""" result = [] for attr_name in attrs: _collect_target_from_attr(rule_attrs, attr_name, result) return [target for target in result if is_valid_aspect_target(target)]
5,348,900
def quit(*modules): """Quit the given module.""" if len(modules) == 0: modules = (sdl2.SDL_INIT_EVERYTHING,) for module in modules: try: sdl2.SDL_QUIT(module) except: pass
5,348,901
def extract_codes(text: str) -> Tuple[str, ...]: """Extract names of warnings from full warning text.""" match = CODES_PAT.search(text) if not match: raise ValueError("No warning code found") return tuple(match.group(1).split(","))
5,348,902
def task_list(request, pk): """ View to get task list based on user list for forms """ user_model = User.objects.filter(is_staff=False) task_model = Task.objects.filter(user=pk) user_detail = User.objects.get(pk=pk) query = request.GET.get('q') if query: task_model = task_m...
5,348,903
def load_credentials(): """ load_credentials :return: dict """ with open("credentials.json", "r", encoding="UTF-8") as stream: content = json.loads(stream.read()) return content
5,348,904
def get_utm_string_from_sr(spatialreference): """ return utm zone string from spatial reference instance """ zone_number = spatialreference.GetUTMZone() if zone_number > 0: return str(zone_number) + 'N' elif zone_number < 0: return str(abs(zone_number)) + 'S' else: re...
5,348,905
def messages_count(name): """ Get message count for queue curl -X GET -H 'Accept: application/json' http://localhost:8080/queues/C13470112/msgs/count curl -X GET -H 'Accept: application/json' 83.212.127.232:8080/queues/C13470112/msgs/count """ conn = get_conn() queue = conn.get_queue(name) count = queue.count...
5,348,906
def return_intersect(cameraList): """ Calculates the intersection of the Camera objects in the *cameraList*. Function returns an empty Camera if there exists no intersection. Parameters: cameraList : *list* of *camera.Camera* objects A list of cameras from the camera.Camera class, e...
5,348,907
def get_returned_attr_set_node(tree): """ Get the NODE_ATTR_SET containing the attributes which are returned by the module """ # TODO: fix HACK, currently we assume the node containing `imports` is the returned attr set # but this may not always be the case? imports_node = get_imports_node...
5,348,908
def choose_time_format_method(expression,format): """ :Summary: strftime("%s") is not a valid string formatting method in python, therefore it works on linux servers but not windows. To handle this, this function checks for python version and decides what conversion method to use. the "format" param...
5,348,909
def import_measurements(task, subject, gsrn, session): """ Imports measurements for a single MeteringPoint, and starts a start_submit_measurement_pipeline() pipeline for each of the newly imported measurements. :param celery.Task task: :param str subject: :param str gsrn: :param sqlalch...
5,348,910
def main(): """run synergy commands """ # args MODEL_DIR = sys.argv[1] MODEL = sys.argv[2] INFER_DIR = sys.argv[3] OUT_DIR = sys.argv[4] motifs_file = "{}/motifs.sig/motifs.adjust.diff.rna_filt.dmim/summary/ggr.pwms_patterns_summary.txt".format( INFER_DIR) bash_script = "/dat...
5,348,911
def add_agg_series_to_df( df: pandas.DataFrame, grouped_levels: List[str], bottom_levels: List[str] ) -> pandas.DataFrame: """ Add aggregate series columns to wide dataframe. Parameters ---------- df : pandas.DataFrame Wide dataframe containing bottom level series. grouped_levels : ...
5,348,912
def conv_relu_pool_forward(x, w, b, conv_param, pool_param): """ Convenience layer that performs a convolution, a ReLU, and a pool. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer - pool_param: Parameters for the pooling layer...
5,348,913
def avg_pixelwise_var(images_seen: np.int16): """ Computes the variance for every pixel p across all images, resulting in a matrix holding the variance for eack pixel p, then calculates the average of that variance across all pixels. This allows us to compensate for different fov sizes. Note: images...
5,348,914
def test_wrong_patterns_in_values( code, first, second, assert_errors, parse_ast_tree, default_options, ): """Testing safe in patterns.""" tree = parse_ast_tree(code.format(first, second)) visitor = ImplicitBoolPatternsVisitor(default_options, tree=tree) visitor.run() asser...
5,348,915
def main(ip_address: str, count: int = 3): """ Ping IP_ADDRESS """ status = ping_ip(ip_address, count) if status: typer.secho(f"ICMP reply received from address {ip_address}", fg="green") else: typer.secho(f"No ICMP reply received from address {ip_address}", fg="red")
5,348,916
def get_r2_matrix(ts): """ Returns the matrix for the specified tree sequence. This is computed via a straightforward Python algorithm. """ n = ts.get_sample_size() m = ts.get_num_mutations() A = np.zeros((m, m), dtype=float) for t1 in ts.trees(): for sA in t1.sites(): ...
5,348,917
def load_or_run(filepath, fun, *args, **kwargs): """ 계산된 결과 파일이 있으면 로딩하고, 없으면 계산후 저장 ex) res = load_or_run('file_loadorsave', funlongtime, ...., force=False) :param filepath: :param fun: :param force: :return: """ force = kwargs.pop('force', False) compress = kwargs.pop('comp...
5,348,918
def main(): """ Find the common kmers between the two input files """ args = get_args() file1 = args.file1.read().split() file2 = args.file2.read().split() words1 = count_kmers(file1, args.kmer) words2 = count_kmers(file2, args.kmer) common = set(words1).intersection(set(words2)) for wor...
5,348,919
def init_build_env(): """ Cleans and initializes the build environment. """ BUILD_DIR.rmtree() if not BUILD_DIR.exists(): BUILD_DIR.makedirs() if not BUILD_WORK_DIR.exists(): BUILD_WORK_DIR.makedirs() # FIXME - maybe a full tree not needed? for subdir in ('RPMS', 'SPECS', 'SOURCE...
5,348,920
def seq2seq_output_ids_to_file(output_ids, trg_vocab, out_file): """ Devectorize and Detokenize the translated token ids and write the translations to a text file """ output_tokens = devectorize(output_ids.tolist(), trg_vocab.id2tok, tr...
5,348,921
def omdb_title( api_key: str, id_imdb: str = None, media: str = None, title: str = None, season: int = None, episode: int = None, year: int = None, plot: str = None, cache: bool = True, ) -> dict: """ Looks up media by id using the Open Movie Database. Online docs: http:...
5,348,922
def get_status(addr): """Get the current status of a minecraft server. addr -- server address Returns an mcstatus object. """ server = MinecraftServer.lookup(addr) try: return server.status() except Exception: return None
5,348,923
def calculate_losses(estimator, input_fn, labels): """Get predictions and losses for samples. The assumptions are 1) the loss is cross-entropy loss, and 2) user have specified prediction mode to return predictions, e.g., when mode == tf.estimator.ModeKeys.PREDICT, the model function returns tf.estimator.Esti...
5,348,924
def text_cleaning(value, stopwords=None): """Applies the four cleaning funtions to a value. Turns value into string, makes lowercase, strips trailing and leading spaces, and removes digits, punctuation, and stopwords Args: value (str): string to be cleaned Returns: str_out (s...
5,348,925
def calc_pts_lag(npts=20): """ Returns Gauss-Laguerre quadrature points rescaled for line scan integration Parameters ---------- npts : {15, 20, 25}, optional The number of points to Notes ----- The scale is set internally as the best rescaling for a line scan ...
5,348,926
def APPEND(*ext, **kw): """Decorator to call XDWAPI with trailing arguments *ext. N.B. Decorated function must be of the same name as XDWAPI's one. """ def deco(api): @wraps(api) def func(*args, **kw): args = list(args) if "codepage" in kw: args.a...
5,348,927
def stations_within_radius(stations, centre, r): """Returns a list of all stations (type MonitoringStation) within radius r of a geographic coordinate x.""" stations_inside_radius = [] for station, distance in stations_by_distance(stations, centre): # Check if distance is inside the requried radius...
5,348,928
def manage_topseller(request, template_name="manage/marketing/topseller.html"): """ """ inline = manage_topseller_inline(request, as_string=True) # amount options amount_options = [] for value in (10, 25, 50, 100): amount_options.append({ "value": value, "selecte...
5,348,929
def create_stabil_mat(problem): """Using the stabilization material stub make it the true material.""" from sfepy.base.base import dict_to_struct, debug from sfepy.fem.functions import Function # Identity map... ns = {'p' : 'p', 'q' : 'q', 'u' : 'u', 'b' : 'b', 'v' : 'v', 'fluid...
5,348,930
def embedded_services(request: FixtureRequest) -> Optional[str]: """ Enable parametrization for the same cli option """ return getattr(request, 'param', None) or request.config.getoption('embedded_services', None)
5,348,931
def vigenere(plaintext,cypher): """Implementation of vigenere cypher""" i = 0 cyphertext = "" for character in plaintext: n = ord(cypher[i%len(cypher)].lower())-97 new_char = rot_char(character, n) cyphertext += new_char if new_char != ' ': i += 1 ret...
5,348,932
def get_local_unit_slip_vector_SS(strike, dip, rake): """ Compute the STRIKE SLIP components of a unit slip vector. Args: strike (float): Clockwise angle (deg) from north of the line at the intersection of the rupture plane and the horizontal plane. dip (float): Angle (degrees) ...
5,348,933
def caWaitStable(pvs, values, vallo, valhi, **kwargs): """read pvs and wait until the std less than epsilon Parameters ----------- pvs : list or tuple. A list of PVs values : list or tuple. Same size as elemfld vallo : list or tuple with low boundary values. valhi : list or tuple with high ...
5,348,934
def get_country_code(country_name): """Gets the code of the country given its name""" for code, name in COUNTRIES.items(): if name == country_name: return code
5,348,935
def build_model(cfg, train_cfg=None, test_cfg=None): """Build model.""" if train_cfg is None and test_cfg is None: return build(cfg, MODELS) else: return build(cfg, MODELS, dict(train_cfg=train_cfg, test_cfg=test_cfg))
5,348,936
def send_plot_convergence(results, experiment=None, channel_name='convergence'): """Logs skopt plot_convergence figure to neptune. Image channel `convergence` is created and the output of the plot_convergence function is first covented to `neptune.Image` and then sent to neptune. Args: res...
5,348,937
def find_instruction_type(opcode: str) -> InstructionType: """Finds instruction type for object instruction Parameters ---------- opcode : str opcode of instruction in hex Returns ------- InstructionType type of instruction using InstructionType enum """ # R type in...
5,348,938
def gen_tier_id(inst, id_base, tier_type=None, alignment=None, no_hyphenate=False): """ Unified method to generate a tier ID string. (See: https://github.com/goodmami/xigt/wiki/Conventions) """ # In order to number this item correctly, we need to decide how many tiers of the same type # there are. ...
5,348,939
def create_temporary_file(filename, contents=""): """ Decorator for constructing a file which is available during a single test and is deleted afterwards. Example usage:: @grader.test @create_temporary_file('hello.txt', 'Hello world!') def hook_test(m): ...
5,348,940
def find_post_translational_modifications(filter=None, page=0, pageSize=100): # noqa: E501 """Find values for an specific property, for example possible taxonomy values for Organism property # noqa: E501 :param filter: Keyword to filter the list of possible values :type filter: str :param page: Nu...
5,348,941
def random_vector(A, b): """ Generates a random vector satisfying Ax <= b through rejection sampling. """ dimension = A.shape[1] not_feasible = True while not_feasible == True: config.reject_counter = config.reject_counter + 1 if config.reject_counter == config.milestone: ...
5,348,942
def mapi(mapper: Callable[[TSource, int], TResult]) -> Projection[TSource, TResult]: """Returns an observable sequence whose elements are the result of invoking the mapper function and incorporating the element's index on each element of the source.""" from .transform import mapi return mapi(mapper...
5,348,943
def game_to_screen(position): """ Converts coordinates from game view into screen coordinates for mouse interaction """ return (GAME_LEFT + position[0], GAME_TOP + position[1])
5,348,944
def get_graph_params(filename, nsize=1): """Load and process graph adjacency matrix and upsampling/downsampling matrices.""" data = np.load(filename, encoding='latin1') A = data['A'] U = data['U'] D = data['D'] U, D = scipy_to_pytorch(A, U, D) A = [adjmat_sparse(a, nsize=nsize) for a in A] ...
5,348,945
def register_task(kind, task_class, override=False): """ Register a new task implementation with the execution system """ if kind in _task_registry and not override: raise KeyError('Task of type %s is already defined and ' 'override is False') _task_registry[kind] = t...
5,348,946
async def list_trainers_pokemon(message): """Lists all Pokemon caught by a trainer Command from discord: p!ka list p!ka - Bot command prefix list - Specifies to list all Pokemon caught by trainer """ await list_pokemon(message.message, registered_trainers, sqlite_conn)
5,348,947
def _(dbmodel, backend): """ get_backend_entity for DummyModel DbComputer. DummyModel instances are created when QueryBuilder queries the Django backend. """ from . import computers djcomputer_instance = djmodels.DbComputer( id=dbmodel.id, uuid=dbmodel.uuid, name=dbmodel....
5,348,948
def persist(key, value): """ Write into ini file """ parser.set(SECTION, key, value) with open(INI_FILE, 'w') as f: parser.write(f)
5,348,949
def retrieve(filename, conf, return_format='dict', save_to_local=False, delete_remote=False, timeout=60): """Retrieving Processed Session File from server via sFTP 1. Get xml file string from server and return object 2. If save_to_local, save to local file system Args: filename: filename of fi...
5,348,950
def test_Minimal(): """Test the Minimal strategy.""" # Try to load the confounds, whithout PCA reduction conf = lc.Minimal() assert conf.strategy == ["high_pass", "motion", "wm_csf", "non_steady_state"] assert hasattr(conf, "global_signal") == False conf.load(file_confounds) assert isinstan...
5,348,951
def get_simulate_func_options( params, options, method="n_step_ahead_with_sampling", df=None, n_simulation_periods=None, ): """Rewrite respy's get_simulation_function such that options can be passed and therefore the seed be changed before any run. Documentation is adapted from :func:`re...
5,348,952
def read_xspec_log_files(es_dir, out_rel_name, boot_num=2): """ Read in all XSPEC log files (with chatter set to 4) that were generated in sed_fit_bootstrap.sh, and append each bootstrap iteration's values to its sed_pars.Parameter. Parameters ---------- es_dir : str The directory w...
5,348,953
def transformLimits(*args, **kwargs): """ The transformLimits command allows us to set, edit, or query the limits of the transformation that can be applied to objects. We can also turn any limits off which may have been previously set. When an object is first created, all the transformation limits are o...
5,348,954
def get_host_user_and_ssh_key_path(instance_name, project, zone): """Return a tuple of (hostname, username and ssh_key_path).""" output = api.local( 'gcloud compute ssh --project "%s" --zone "%s" %s --dry-run' % (project, zone, instance_name), capture=True) print output m = re.match('/usr/bin...
5,348,955
def TDataStd_TreeNode_Find(*args): """ * class methods working on the node =================================== Returns true if the tree node T is found on the label L. Otherwise, false is returned. :param L: :type L: TDF_Label & :param T: :type T: Handle_TDataStd_TreeNode & :rtype: bool ...
5,348,956
def make_group_corr_mat(df): """ This function reads in each subject's aal roi time series files and creates roi-roi correlation matrices for each subject and then sums them all together. The final output is a 3d matrix of all subjects roi-roi correlations, a mean roi-roi correlation matrix and a roi-r...
5,348,957
def get_tradedate(begin, end): """ get tradedate between begin date and end date Params: begin: str,eg: '1999-01-01' end: str,eg: '2017-12-31' Return: pd.DataFrame """ try: conn = pymysql.connect(**config) cursor = conn.cursor() ...
5,348,958
def collect_tweet(update: Update, context: CallbackContext) -> int: """Tweet caption collection for tweet without attachments""" logger.info("'{update.message.text}' tweet type selected") update.message.reply_text("Enter the tweet") return TWEET
5,348,959
def get_unhandled_crictical_errors(req:HttpRequest, n:int): """ Preprocess errors before injection and gets `n` unhandled errors Typical Return Value if `n` errors were found... {"es":[ { "id": "192.168.1.51", "title":"hey there" } ] ...
5,348,960
def ADO_mappings(N, K, level_cutoff): """ ADO (auxilary density operators) are indexed by a N by (K + 1) matrix consisting of non-negative integers. ADO_mappings calculates all possible matrices "ado_index" of size N by (K+1) where np.sum(m) < level_cutoff Parameters ---------- N : int...
5,348,961
def f_beta(precision, recall, beta): """ Returns the F score for precision, recall and a beta parameter :param precision: a double with the precision value :param recall: a double with the recall value :param beta: a double with the beta parameter of the F measure, which gives more or less weight to...
5,348,962
def convert_image_to_dicom(image_file): """Read an image file, convert it to Dicom and return the file path""" # Load pixel array from image. img = Image.open(image_file) if ('RGB' == img.mode) or ('RGBA' == img.mode): # Assuming greyscale image, keep only one channel. pix = np.array(im...
5,348,963
def get_highly_variable_genes( adata, normalized_counts_per_cell=10000, min_counts=3, min_cells=3, min_gene_vscore_pctl=85, ): """ Get highly variable genes. We assume that data preprocessing are already done, like removing low quality cells. It first perform count normalization, th...
5,348,964
async def sysdetails(sysd): """ For .sysd command, get system info using neofetch. """ if not sysd.text[0].isalpha() and sysd.text[0] not in ("/", "#", "@", "!"): try: fetch = await asyncrunapp( "neofetch", "--stdout", stdout=asyncPIPE, ...
5,348,965
def get_cfg(existing_cfg, _log): """ generates """ _sanity_check(existing_cfg, _log) import ntpath, os, yaml with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream: try: ret = yaml.load(stream)...
5,348,966
def download_alphafold_cif( proteins: list, out_folder: str, out_format: str = "{}.cif", alphafold_cif_url: str = 'https://alphafold.ebi.ac.uk/files/AF-{}-F1-model_v1.cif', timeout: int = 60, verbose_log: bool = False, ) -> tuple: """ Function to download .cif files of protein structures...
5,348,967
def test_staff_user_cannot_create_youth_profile_if_profile_does_not_exist( rf, staff_user_gql_client, mocker, profile_api_response ): """Creating a youth profile will query Helsinki profile for the given profile id.""" mocker.patch.object(ProfileAPI, "fetch_profile", return_value={"id": ""}) profile_id ...
5,348,968
def test_show_tables(): """ Tests show tables command. """ ret = {} ret["stdout"] = "bad_hosts" ret["retcode"] = 0 mock_cmd = MagicMock(return_value=ret) with patch.dict(pf.__salt__, {"cmd.run_all": mock_cmd}): res = pf.show("tables") mock_cmd.assert_called_once_with( ...
5,348,969
def secret_age_check(cache: dict, awsAccountId: str, awsRegion: str, awsPartition: str) -> dict: """[SecretsManager.1] Secrets over 90 days old should be rotated""" secret = list_secrets(cache=cache) for secrets in secret["SecretList"]: secretArn = str(secrets["ARN"]) secretName = str(secret...
5,348,970
def _gecko_path(): """Either get the executable or raise an error""" if sys.platform == "win32": return os.path.join(PCKG_PATH, "win32", "geckodriver.exe") if sys.platform == 'linux': return os.path.join(PCKG_PATH, "linux", "geckodriver") if sys.platform == 'darwin': return os.pa...
5,348,971
def generate_makefiles(target_config, verbose, parts, tracing): """ Generate the makefiles to build everything. target_config is the target configuration. verbose is set if the output is to be displayed. parts is the number of parts the generated code should be split into. tracing is set if the genera...
5,348,972
def readShort(f): """Read 2 bytes as BE integer in file f""" read_bytes = f.read(2) return struct.unpack(">h", read_bytes)[0]
5,348,973
def get_color(thing): """Get color for thing. :param thing: Thing to get color for. :return: Color tuple if rule exists otherwise None. """ for rule in _COLOR_RULES: color = rule(thing) if color is not None: return color return None
5,348,974
def build_table(infos): """ Builds markdown table. """ table_str = '| ' for key in infos[0].keys(): table_str += key + ' | ' table_str += '\n' table_str += '| ' for key in infos[0].keys(): table_str += '--- | ' table_str += '\n' for info in infos: table_str += ...
5,348,975
def notify_telegram(title, content, token=None, chat=None, mention_user=None, **kwargs): """ Sends a telegram notification and returns *True* on success. The communication with the telegram API might have some delays and is therefore handled by a thread. """ # test import import telegram # noqa...
5,348,976
def convert_to_dapr_duration(td: timedelta) -> str: """Converts date.timedelta to Dapr duration format. Args: td (datetime.timedelta): python datetime object. Returns: str: dapr duration format string. """ total_minutes, secs = divmod(td.total_seconds(), 60.0) hours, mins = di...
5,348,977
def test_main_ls(): """ If the ls command is issued, check the appropriate function is called. """ mock_serial = mock.MagicMock() mock_class = mock.MagicMock() mock_class.__enter__.return_value = mock_serial with mock.patch( "microfs.ls", return_value=["foo", "bar"] ) as mock_ls,...
5,348,978
def get_slot(handler_input, slot_name): # type: (HandlerInput, AnyStr) -> Optional[Slot] """Return the slot information from intent request. The method retrieves the slot information :py:class:`ask_sdk_model.slot.Slot` from the input intent request for the given ``slot_name``. More information on t...
5,348,979
def password_to_key( hash_implementation: Callable[[bytes], TDigestable], padding_length: int ) -> Callable[[bytes, bytes], bytes]: """ Create a helper function to convert passwords to SNMP compliant keys according to :rfc:`3414`. >>> hasher = password_to_key(hashlib.sha1, 20) >>> key = hasher(...
5,348,980
def categorize_tag_key_characters(OSM_FILE = "data\\round_rock.xml", category = 'Summary'): """Categorizes attributes into those with: all lower character, all lower after colon(:), containing special/problem characters and all all others that were not listed in above which inc...
5,348,981
def rotate_left(value, count, nbits, offset): """ Rotate a value to the left (or right) @param value: value to rotate @param count: number of times to rotate. negative counter means rotate to the right @param nbits: number of bits to rotate @param offset: offset of the first b...
5,348,982
def set_categories(categories): """ Take a dictionary mapping video category IDs to name and retrieval time. All items are stored into cache node 'videoCategories', but for the ones with a retrieval time too long ago, the v3 API is queried before. """ timestamp = time.time() idlist = [cid fo...
5,348,983
def geo_to_string(value): """ Convert geo objects to strings, because they don't support equality. """ if isinstance(value, list): return [geo_to_string(x) for x in value] if isinstance(value, dict): result = {} for dict_key, dict_value in value.iteritems(): result[dict_key] = geo_to_string(dict_value) ...
5,348,984
def setMaxSharedMemory(): """ Check and verify that the kernel.shmmax kernel parameter is above 35mb """ # First verify that kernel.shmmax is not set and is below the requested value. logging.debug("loading %s", basedefs.FILE_SYSCTL) txtHandler = utils.TextConfigFileHandler(basedefs.FILE_SYSCTL)...
5,348,985
def magma_dposv_gpu(uplo, n, nhrs, a_gpu, lda, b_gpu, ldb): """ Solve linear system with positive semidefinite coefficient matrix. """ uplo = _uplo_conversion[uplo] info = c_int_type() status = _libmagma.magma_dposv_gpu(uplo, n, nhrs, int(a_gpu), lda, int(...
5,348,986
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description="I'm a snitch", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('FILE1', help='Input file 1', metavar='FILE', ...
5,348,987
def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: `404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ t = loader.get_template(template_name) # You need to create a 404.html template. r...
5,348,988
def test_create_new_file_version__use_existing_file_handle(mocker, syn): """Verify the behavior of create_new_file_version when we can use an existing file handle""" key = _MigrationKey('syn123', _MigrationType.FILE, 1, None, None) from_file_handle_id = 1234 to_file_handle_id = 4321 storage_locatio...
5,348,989
def load_data(filename): """ Load shopping data from a CSV file `filename` and convert into a list of evidence lists and a list of labels. Return a tuple (evidence, labels). evidence should be a list of lists, where each list contains the following values, in order: - Administrative, an int...
5,348,990
def instance_mock(cls, request, name=None, spec_set=True, **kwargs): """ Return a mock for an instance of *cls* that draws its spec from the class and does not allow new attributes to be set on the instance. If *name* is missing or |None|, the name of the returned |Mock| instance is set to *request....
5,348,991
def plot_data(y): """ y is a 1D vector """ x = np.arange(y.size) _ = plt.plot(x, y, 'o')
5,348,992
def auto_fp16(apply_to=None, out_fp32=False): """Decorator to enable fp16 training automatically. This decorator is useful when you write custom modules and want to support mixed precision training. If inputs arguments are fp32 tensors, they will be converted to fp16 automatically. Arguments other than...
5,348,993
def get_loci_score(state, loci_w, data_w, species_w, better_loci, species_counts, total_individuals, total_species, individuals): """ Scoring function with user-specified weights. :param state: :param loci_w: the included proportion of loci from the original data se...
5,348,994
def make_per_cell_fastqs( reads, outdir, channel_id, output_format, cell_barcode_pattern, good_barcodes_filename): """Write the filtered cell barcodes in reads from barcodes_with_significant_umi_file fastq.gzs to outdir Parameters ---------- reads...
5,348,995
def _find_app(settings, app): """Looks for an installed application in the user's local $PATH. Raises an ImportError if the application is not found. """ # Save in settings name = app['name'].lower() settings[name] = None # Retrieve local paths split_token = ';' if mh.__iswin__ else '...
5,348,996
def plot_roc_curve(data, cls_name, title='ROC curve'): """ :param data: list [(fpr, tpr), (), ...] :param cls_name: tuple of names for each class :param title: plot title :return: """ def cal_auc(tpr, fpr): return np.trapz(tpr, fpr) def plot_single_curve(fpr, tpr, cls_ind): ...
5,348,997
def train(elastic_coordinator, train_step, state): """ This is the main elastic data parallel loop. It starts from an initial 'state'. Each iteration calls 'train_step' and returns a new state. 'train_step' has the following interface: state, worker_stats = train_step(state) ...
5,348,998
def make_animation(data_list, **kwargs): """ Creates an animation from list of McStasData objects Parameters ---------- data_list : list of McStasData List of McStasData objects for animation Keyword arguments ----------------- filename : str Filename for saving...
5,348,999