content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def safe_apply(s: pd.Series, fn) -> pd.Series: """nan以外にのみapply""" return s.apply(lambda x: x if pd.isnull(x) else fn(x))
4728d07d8d7f17b05bdf1c867c1f4e35e9225a43
53,900
def flex_colormesh_plot_vs_xy(xvals, yvals, zvals, ax=None, normalize=False, log=False, save_name=None, **kw): """ Add a rectangular block to a color plot using pcolormesh. xvals and yvals should be single vectors with values for the two sweep ...
918480e8eccd58089f27e5792b9d24b03c0c1b9f
53,901
import hashlib import json def param_to_hash(param_dict): """Generate a hash for a fixed hyperparameter setting""" config_hash = hashlib.md5(json.dumps(param_dict, sort_keys=True).encode("utf-8")).hexdigest() return config_hash
5302000372023af0d2ea44ca3e5497741cd84e58
53,902
def evaluate_utterance_sample(sample, model, max_generation_length, name="", gold_forcing=False, metrics=None, total_num=-1, ...
9b582dd18370417ce3a45d34158e2cc95c994ce6
53,903
def lower(series): """Transform all text to lowercase.""" return series.str.lower()
fd8f443ff8cb27700bceed3a2b2843befbc932a3
53,904
def sleep(delay, loop=None): """ Suspends the current task, allowing other tasks to run. Parameters ---------- delay : `float` The time to block sleep in seconds. loop : `None` or ``EventThread``, Optional The event loop to which the returned `future` will be bound to. If no...
d33aacac10ac10ecf4fa7dc064ffe084bec22e14
53,905
def multihead_self_attention_incremental(query_antecedent, prev_k, prev_v, step_num, name="multihead_attention"): """Incremental self-attention (one decod...
941c6918893060e480642daf1089073813ff0d56
53,906
from openff.toolkit.typing.engines.smirnoff import ForceField from typing import Optional from typing import Tuple import copy import numpy def system_subset( parameter_key: ParameterGradientKey, force_field: "ForceField", topology: "Topology", scale_amount: Optional[float] = None, ) -> Tuple["openmm....
5e3923b1498b5b813622110a0ea49968d00e274f
53,907
import torch def tensor_to_numpy(data): """Transform torch tensort arrays to numpy arrays.""" if hasattr(data, 'detach'): data = data.detach() if type(data) is torch.Size: return np.array(data) return data.cpu().numpy()
e0ebabae325b46cc75a81a6c74a9521bd944681f
53,908
from typing import Tuple import json def request_state_access(state_id: UUID) -> Tuple[Response, int]: """Traverse through the state object linked to the given UUID and look for data ids. Then attempt to load the data into the current session to verify access. :param state_id: The id associated with t...
9537b31dbf64c04609449fd03ad8ae4031db9085
53,909
def get_default_resolution_attribute(attribute_name, default_value=None): """ Internal function that returns value of the given attribute of the default resolution Maya node :param attribute_name: str, name of the attribute to get :param default_value: object, value that is returned if the attribute doe...
db3f11f55f4d68e269a0b3cd8b41dd80c3a5365b
53,910
import sys def make_collision_tester(test_method='vdw', test_scale=1.122462048309373): """ Create a function that will test atom overlap based on separation and atomic radii. """ # OH NO MY CAPSLOCK GOT STUCK! test_method = test_method.lower() if test_method == 'cvdw': if _SCIPY...
ec8d7c90055d692ef6f105b0de190ca893f6f803
53,911
import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon import os import sys def runAsAdmin(cmdLine=None, wait=True): """ Attempt to relaunch the current script as an admin using the same command line parameters. WARNING: t...
cd2853f25f2bf72c916b6301557996255047c7ee
53,912
import sys import logging def parse_args(prog): """Parse the command line. Parse the command line, set the program state and return a list of functions to be called for the program's operation, determined from the command line arguments. Args: prog (State): program's state. Returns:...
3a69d3c67981a344ebdc07e520915a1d710083d5
53,913
import os def get_file_references(abs_nb_path, version): """Gets a list of files referenced either in Markdown fenced code blocks or in HTML comments from the notebook. Expands patterns expressed in gitignore syntax (https://git-scm.com/docs/gitignore). Returns the fully expanded list of filenames rel...
b9d24d1d9545311c1c149640517b1c10c48a4288
53,914
async def resolve_subscription_user(event, info, id): """Resolver function for user subscriptions""" user = event["user"] mutation = MutationEnum(event["mutation"]).value return {"user": user, "mutation": mutation}
c2337c93f8ef5eaae0e6dfa5edc40705973911a3
53,915
def _install(pkgs, pkg_manager): """Return instructions to install system packages.""" installers = { 'apt': _apt_install, 'yum': _yum_install, } if pkg_manager not in installers.keys(): raise ValueError( "package manager '{}' not recognized".format(pkg_manager)) ...
81556b5795e1ed2c846411fbe0fa3faccede8395
53,916
def gsutil_command(arguments, *args, parallel=True, **kwargs): """Executes a gsutil command with |arguments| and returns the result.""" if environment.get('FUZZ_OUTSIDE_EXPERIMENT'): logger.info('FUZZ_OUTSIDE_EXPERIMENT set, not running \'gsutil %s\'.', ' '.join(arguments)) r...
d6bc542d24be72500491c077d7fe2aa21678b27a
53,917
def parse_account(s): """ parse entity and account string """ return s.strip().split('.')
acb14bd71a670e67b306f022792702dc2677539a
53,918
import scipy def sbm_adjmat(cluster_sizes, prob_mat_q, directed=False, self_loops=False): """ Generate a graph from the stochastic block model. The list cluster_sizes gives the number of vertices inside each cluster and the matrix Q gives the probability of each edge between pairs of clusters. F...
704293eb57cbe0b841a9957b591a6dd96f98ea0a
53,919
def distribution(Data, N, kernel=False, ccdf=True): """ This function calculates the pdf and ccdf of Data, either by histogram or by gaussian kernels. N: If histogram is used, N is the number of bins to separate the data into. If kernel is used, N gives the number of data points. ccdf: if true, retu...
8f5d32abd3475b37e61420938f326657728756b3
53,920
import torch def to_pil_image(pic, mode=None): """Convert a tensor or an ndarray to PIL Image. See :class:`~torchvision.transforms.ToPIlImage` for more details. Args: pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. mode (`PIL.Image mode`_): color space and pixel depth of...
cfc2fd887c9da9d473db8e7dee1cae5194da244b
53,921
import uuid from typing import Optional from typing import Dict from typing import Any async def update_issue_pr( db_session: Session, repo_id: uuid.UUID, comments_url: str, terminal_hash: Optional[str] = None, entry_id: Optional[str] = None, comments: Optional[Dict[str, Any]] = None, ) -> Git...
deb7d6916a0e5d740c1797f40f9c15eb1c4d7333
53,922
def uniqPeptides(peptFile): """ create a fasta-file of non-redundant peptide sequences from peptFile. (return: path to created file) peptFile: peptide sequences (fasta-format) """ outfile = os.path.dirname(peptFile) + "/uniq_" + os.path.basename(peptFile) newls = [] peps = [] n_peps = 0 print "reading pept...
cf008bca2a1e643e20837d8c5386e8d7e64e3ecd
53,923
import logging import pkg_resources def run_phenorank(omim_obs, phenotypes_obs=None, nperm=1000, r=0.1, ni=20, gene_mask=None, include_h=True, include_m=True, dir_data="data_phenorank", filename_output="~"): """ run the main PhenoRank function Args: omim_obs: OMIM ID for the disease of interest phenoty...
8a240c22fd6bc1690df4b9a54339ae1380db73fe
53,924
def http_404_view(request, *args, **kwargs): """View for HTTP 404 page.""" response = render(request, "system/404.html", {}) response.status_code = 404 return response
db2f82b30b838bcdb59c3315d34a783055fddae3
53,925
import collections def isEquivalentData(values1, values2): """ Determines if two values are equivalent :param Iterable/object values1, values2: :return bool: """ if cell_types.isStr(values1) and cell_types.isStr(values2): result = values1 == values2 elif isinstance(values1, collections.Iterable) \ ...
6b2f8d98f04d4a4a18bad25e42283fb7afb5b6ba
53,926
import os def init(): """ Initializes module :param dev: bool, Whether tpDcc-core is initialized in dev mode or not """ logger = create_logger() # Get DCC loader module dcc_loader_module = core_dcc.get_dcc_loader_module() logger.info('DCC loader module found: "{}"'.format(dcc_loader_m...
fa92313a7905c9c4a90b3ce6c84a4a435cf954a9
53,927
def default_errorhandler(error): """ Handler function for a logging all errors """ APP.logger.exception() return {'message': error.message}, 500
faa53ba4e65c11a43b64577034936986075bcbff
53,928
import torch def chunk_rays(rays,start,delta): """ rays: a dictionary """ rays_chunk = {} for k,v in rays.items(): if torch.is_tensor(v): v = v.view(-1, v.shape[-1]) rays_chunk[k] = v[start:start+delta] return rays_chunk
8015d1d69b77e2a7fab6b33d30a104982aedfa9c
53,929
import socket def _get_my_ip(): """Return the actual ip of the local machine. This code figures out what source address would be used if some traffic were to be sent out to some well known address on the Internet. In this case, a Google DNS server is used, but the specific address does not matter...
6ed019bf007386d1427b4bf874e6aaf71f44e706
53,930
def _sph2cartMTX(vizMTX): """Converts the spherical vizMTX data to named tuple containing .xs/.ys/.zs. Parameters ---------- vizMTX : array_like [180 x 360] matrix that hold amplitude information over phi and theta Returns ------- V : named_tuple Contains .xs, .ys, .zs cart...
a983021fa8a0ade0fe1d695fc723751ae0973499
53,931
def string_to_TaskStatusCode(status): """Converts the given Mesos status string to an integer :param status: The status as a string :type status: string :returns: The status as an integer :rtype: int """ return mesos_pb2.TaskState.Value(status)
32d8a95d479fc08485fef1292b8229c59632fd62
53,932
def concat_data_chunks(*args): """Concatenates data-chunks together based on their keys.""" data_chunk = DataChunk() for k in args[0]: data_chunk[k] = [] for arg in args: for k, v in arg.items(): data_chunk[k].append(v) for k, v in data_chunk.items(): data_chun...
465eef76106a71ba0b2246e16c584be0262890e3
53,933
def normalize_job_id(job_id): """Convert the job id into job_id, array_id.""" job_id = job_id.split('.')[0] if '[' in job_id: job_id, array_id = job_id.split('[') job_id = job_id.strip('[]') array_id = array_id.strip('[]') if not array_id: array_id = None else...
6eb83b54f8a0cec8c094372a5e5446334a1863c3
53,934
def get_ingredient(name): """Find an ingredient by its name. Args: name (string): The name of the ingredient. Returns: IngredientDto: The ingredient with the given name, or None. """ ingredient_entity = IngredientEntity.query.filter_by(name=name).first() if ingredient_entity is...
606fa9cbcb5c80afebab05ba8e8283a18c81d0bd
53,935
def get_ydim(da, errors="warn", **kwargs): """Get the dimension of Y type It is a simple call to :func:`get_dims` with ``dim_types="y"`` Parameters ---------- da: xarray.DataArray Array to scan positions: str Default position per type starting from the end. {errors} kwa...
70e4b7f24f0b31f0d9da9e6c584e880ba15094db
53,936
def create_import_data_json(import_data_dict, event_tree): """ create_import_data_json: This function converts data in event tree into json format. Parameters: import_data_dict: This parameter holds the event tree data event_tree: This parameter holds the event tree data @see #gener...
2a8745e9fbe387afd63c912d860b0a762770394a
53,937
import scipy def power_split(y, x, x_max, n): """ Computes the indexes corresponding to equal integral values for a function y and x values :param y: function value array :param x: function x values array :param x_max: maximum x value :param n: number of integral bins :return: indexes of t...
98207f6eb29601a681b2d7ac39077b21250305ed
53,938
import random def select_ip_from_network(network): """ Randomly selects an IP address from a particular network :param network: Network from which to select the IP address :return: IP address as integer from network """ max_address = network.address | ((1 << (32 - network.prefix)) - 1) ret...
7356b6cedd5bc78933484e0cba9a8f84d1507b07
53,939
def ONE_OR_MORE(*grammar, **kwargs): """ This is a synonym for ``REPEAT(*grammar, min=1)`` """ kwargs.update(min=1, max=None) return REPEAT(*grammar, **kwargs)
704125e64e948361641bf28b235f80560454966e
53,940
def kwtype_to_annotation(kw): """Convert type to a KnownType""" data = {} for name, type in kw.items(): if isinstance(type, str) and ',' in type: for x in type.split(','): data[_clean_name(x.strip())] = _get_type(name) else: data[_clean_name(name)] = ...
ed50e6bccdfcc2c1f121e71437a45ae6180e7b24
53,941
def parse_extinst_instruction(lexer, set_id): """Parse instruction field of OpExtInst instruction.""" assert set_id.inst.op_name == 'OpExtInstImport' _, tag = lexer.get_next_token(peek=True) if tag == 'INT': return parse_literal_number(lexer) elif tag == 'NAME': token, _ = lexer.get_...
48fd7103fc87be4581a16c17d840e4c6adef5b42
53,942
import json import requests def query(query, experiment_id, host, verify_cert=True): """ Query the MDML for an example of the data structure that your query will return. This is aimed at aiding in development of FuncX functions for use with the MDML. Parameters ---------- query : list Des...
3080ab6322a2756fdc6cb4da8ccc81b96154cbb4
53,943
import os def load_from_dumps_or_extract(track_ids_requested: set[int], dump_dir=DIR_FEATURES_V1) -> dict[int, list[np.ndarray]]: """ Loads features from dump batches or extracting them from audio :param track_ids_requested: :param dump_dir: :return: """ tracks_features: dict[int, list[np....
03f3968de44e95578754e98c6461f7dae883052b
53,944
def interlock(word_list, word): """Checks whether a word contains two interleaved words. word_list: list of strings word: string """ evens = word[::2] odds = word[1::2] return in_bisect(word_list, evens) and in_bisect(word_list, odds)
001652981626b4f24af2f3c4acf155e76f68412c
53,945
from sudachipy import dictionary, tokenizer def try_sudachi_import(split_mode="A"): """SudachiPy is required for Japanese support, so check for it. It it's not available blow up and explain how to fix it. split_mode should be one of these values: "A", "B", "C", None->"A".""" try: split_mode = ...
d0bc779bc3c7d45d8e573f8382ba57cb92074be3
53,946
def ask_type(question, ans_type, loop=True): """ Used to ask and assert that the response to the question will be an integer :param question: what to ask :return: the result, of type specified """ answer = ask(question) if loop: # Loops until the user while loop: ...
33f0eef3e3173e74a713cfc3b2de985d69495b45
53,947
def unload_nodenet(nodenet_uid): """ Unload the nodenet. Deletes the instance of this nodenet without deleting it from the storage Arguments: nodenet_uid """ if not nodenet_uid in nodenets: return False if nodenets[nodenet_uid].world: nodenets[nodenet_uid].wo...
aae97308c825cbf0b3f4a5b002ac75856ce41088
53,948
def verifyBundleStructure(expected, actual, currentPath): """ Function to verify if an uploaded bundle follows IBM defined structure @param expected the JSON representation of the IBM defined structure @param actual the JSON representation of the actual structure of the uploaded bundle @p...
c758d132950986c5cdb97ceb9e34fe99cd21e8bc
53,949
def fix_coordinates(df, cols): """ For coordinate column which require fixing, we it here """ to_fix_or_not_cols = check_if_coordinates_colums_need_fixing(df=df, cols=cols) if to_fix_or_not_cols: fix_col = to_fix_or_not_cols["c...
e16aaace0f5dbeb3645f86b3112d8de81e45bedb
53,950
import os def attemptFileClear(fName,later): """ Attempts to remove the file. If not possible, store it in "later". @ In, fName, string, name of file to remove @ In, later, list, list of files to remove later @ Out, later, list, list of files to remove later """ try: os.remove(fName) exce...
208dcce6ffa1a6de65a93f0b14befe019ddb20c6
53,951
from .pyicu import segment from .multi_cut import segment from .newmm import mmcut as segment from .longest import segment from .pylexto import segment from .deepcut import segment from .wordcutpy import segment def word_tokenize(text, engine='newmm',whitespaces=True): """ :param str text: the text to be tokeni...
96260aa4ea57a19a904a17d5e8a7968b605042e0
53,952
def choose_best_seqs(dist_matrix, all_genes, groups, medoid): """ Defines the medoid of a distance matrix :param dist_matrix: The numpy array (symmetrical) distance matrix :param groups: sp -> groups of genes :param all_genes: A list of the row/colnames of the distance matrix :param medoid: the ...
da68a172732f42a2781673c26034ccb26f7bfff9
53,953
def get_dataset_info_dict(debug): """Get dictionary of dataset info.""" def _tfds_fns(ds_name): fns = [ x # pylint:disable=g-complex-comprehension for s in ('train', 'validation', 'test') for x in audio_to_embeddings_beam_utils._tfds_filenames(ds_name, s)] # pylint:disable=protected-ac...
fe29c10d18abb13715b9e5ae9f08f8544b50dfe0
53,954
def oracle_service_def(): """ Provides the Docker service definitions for running an instance of Oracle Express Edition, result is converted to YAML file and then used to create a Docker compose file. Note this assumes the existence of a container image named 'oracle/database:18.4.0-xe' in a registry th...
f68c340a71f795630578ac6a689a620cf96e895a
53,955
def get_kmsauth_config(region, bless_config): """ Return the kmsauth config values for a given AWS region Args: region (str): the AWS region code (e.g., 'us-east-1') bless_config (BlessConfig): config from BlessConfig Retruns: A dict of configuation values """ alias_code = bl...
c8fcc4ab0a125f1ed068a865872d3421280b21ab
53,956
def get_utility_command_execution_order(name): """ Should the given utility command be executed before or after the payload? :param name: utility name (string). :return: execution order constant (UTILITY_BEFORE_PAYLOAD or UTILITY_AFTER_PAYLOAD) """ # example implementation if name == 'moni...
301deca503fc890322363d1c8c9f2e6ff9ff9af3
53,957
def bytes_feature(value): """Returns a bytes_list from a string / byte.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
7a58a45509749c0633e648096d199359872e9919
53,958
import time def int_product(size=DEF_MATRIX, rep=DEF_REP): """ Returns the execution time of performing a product of random integer matrices. Parameters ---------- size : int The dimension of the square matrices that will be used in the operation. ...
5b898de1a719060701b250bd6982c0994c2e18f0
53,959
from typing import Tuple from typing import cast def get_hedgehog_hyperparams(**overrides) -> Tuple: """ Get parameters for Hedgehog agent. If some parameter is not specified in overrides, then it takes a default value. :param overrides: Parameters coming from JSON file. :return: (ac_params, wk_p...
4a063f3f14f4c0f44e09f30ffc34d1cd52ff1865
53,960
def project_waveforms(waveforms, method='pca', selection=None, catalogueconstructor=None, **params): """ """ if selection is None: waveforms2 = waveforms else: waveforms2 = waveforms[selection] if waveforms2.shape[0] == 0: return None, None, None ...
ff23fddfa122524ffc8c895ba8c1db879e22f6e7
53,961
def high_low_estimator(high, low, window): """ Estimates volatility using Parkinson's method :param high: a series of high prices :param low: a series of low prices :param window: length of the rolling estimation window :return: volatility estimate """ log_high_low = np.log(high / low) ...
bab9ecc9a17e72d38c1a6c7bd4f7ef302b818459
53,962
from typing import Optional def process_possible_repo(repo: PossibleRepo) -> Optional[Result]: """Process the given possible repo.""" try: slave = Slave(repo) result = slave.run() if result is None: logger.error("Slave returned None result.") return result excep...
33990c5c1ea7b9f283cb4ca2fce4acb31e74e77c
53,963
def replace_decorator(node, capture, filename): """ Replaces usage of ``@slowTest`` with ``@pytest.mark.slow_test`` """ return utils.rewrite_decorator(node, DECORATOR, MARKER)
12200443d5683c06fe1703277c23974f632ea55c
53,964
def GetPercentage(number, total): """Returns the float percentage that a number is of a total.""" if not number: return 0 return float(number) / total * 100
46e2a5b2b4a3fa648792a461852f84e886810a7f
53,965
def _store_path(path, ctx, imports): """Given a path, prepend the workspace name as the zappent directory""" # It feels like there should be an easier, less fragile way. if path.startswith("../"): # External workspace, for example # '../protobuf/python/google/protobuf/any_pb2.py' st...
5713f8c6ca5471ec6a4bb5b352a199dc004286fc
53,966
def generate_grammar_rule(ops, inner_rule_name, rule_name, alias_prefix): """ Generates one grammar rule for ops with same priority. """ # every op produce a match for non-terminal # op key used as alias matches = [] plain_ops = {} if inner_rule_name is not None: matches.ap...
716a14a32c10d4223f7baa25de86f12897437e9b
53,967
def create_custom_program_attribute(driver): """Creates a custom text attribute for a program object Args: driver (lib.base.CustomDriver) """ modal = dashboard.AdminDashboard(driver) \ .select_custom_attributes() \ .select_programs() \ .add_new_custom_attribute() test_utils.ModalNewPr...
3b562889b54fc8e9618ee0411ccdf3644f110669
53,968
import re def parse_billing_code_col(s:str): """Split billing code into separate fields for code_type and code. E.g., 'MSDRG .... 001'.""" l:list = s.split() if 'MS-DRG' in s: code_type, code = l[0], l[4] elif re.search('CPT|HCPCS', s): code_type, code = l[0], l[1] else: co...
78865842a457c0226184ace94334d0934a0e0a5c
53,969
def munsell_colour_to_munsell_specification(munsell_colour: str) -> NDArray: """ Retrieve a normalised *Munsell* *Colorlab* specification from given *Munsell* colour. Parameters ---------- munsell_colour *Munsell* colour. Returns ------- :class:`numpy.ndarray` Norma...
693d64e6d4ebd19d775186be6ec57f019e46c550
53,970
def predict(market,profit,hold,cur_profit_present,stop): """ 一个极其简单的示例策略,如果空仓则买入,如果有仓位就卖出 """ if hold==0: return {'if_buy':1} else: return {'if_buy':0}
53ae9a2b1e4017b9d8ac79c8e058ed5881934f9e
53,971
from typing import List def inject_params(lines: str, params: dict) -> List[str]: """Replace placeholders with parameters. Args: lines: A file content including placeholders (`{{ ... }}`). params: A mapping a name of placeholders to a value. Returns: A file content replaced plac...
74614fb6cdf8ba85cf057920db22e7bf5854c288
53,972
def load_depth(file): """ Load a depth map from file Parameters ---------- file : str Depth map filename (.npz or .png) Returns ------- depth : np.array [H,W] Depth map (invalid pixels are 0) """ if file.endswith('npz'): return np.load(file)['depth'] ...
9b1a672143980424b09ad5d483d032dfbdde3211
53,973
def close_story(request): """Close an open story. --- story_id: in: path type: string required: true """ auth_context = auth_context_from_request(request) # Only available to Owners for now. if not auth_context.is_owner(): raise PolicyUnauthorizedError("Only Own...
26a28846f19b665b599d5e2ef00f486be6e226c7
53,974
def parthandler(parttype, params=()): """decorator that register a function as a bundle2 part handler eg:: @parthandler('myparttype', ('mandatory', 'param', 'handled')) def myparttypehandler(...): '''process a part of type "my part".''' ... """ def _decorator(fu...
511ebba63b65639d72bac62080e19ddb2dbd0c91
53,975
def get_field_instance(field_name: str) -> FieldInstance: """ Return a FieldInstance object for the given field name. Args: field_name: The name of the field to get a FieldInstance for. Returns: A FieldInstance object for the given field name. """ info = _FIELD_INFO_MAP[field_n...
fc5bbd61d58e15f817eda554f12e5429f99fab02
53,976
def DetermineLocaleType(locale_str): """Determines the locale 'type' for a given locale name. Returns: (string) Always one of the following strings, 'world' If the locale name refers to the world. 'country' If the locale name looks like a country ID. 'region' If the locale name ...
52ac86d8e011d9d01b6f31ed6a27d535a55b26a4
53,977
def m_to_recruitment(seq, args=None): """ 返回bool值0/1 :param seq: 任意值 :param args: 可不传 传时seq==args为1 :return: 0/1 example: :seq '11' :args '00' :return 0 """ if seq: seq = "统招" else: seq = "非统招"...
983e41ec210e8708605016477e1457b237693af4
53,978
def spread_segment_wise(starts, input_data): """ Generalized version of :func:`spread_residue_wise()` for residues and chains. Parameters ---------- starts : ndarray, dtype=int The sorted start indices of segments. Includes exclusive stop, i.e. the length of the corresponding ...
2d99f76a0c05a9cde44af3ef4b56c585b7d04c68
53,979
def get_model(instance): """Get model by instance.""" return instance._meta.model
e386449ecd49d5874fb704c683c17d4492ea6f6c
53,980
def encode(bananaFactory, obj): """ Banana encode an object using L{banana.Banana.sendEncoded}. @param bananaFactory: A no-argument callable which will return a new, unconnected protocol instance to use to do the encoding (this should most likely be a L{banana.Banana} instance). @param...
40204f4bf93d115e0fa10f09587a2a891a30f6a6
53,981
def crossSpecgram(x, y, NFFT=256, Fs=2, detrend=mlab.detrend_none, window=mlab.window_hanning, noverlap=0, pad_to=None, sides='default', scale_by_freq=None) : """ Use matplotlib.mlab function, _spectral_helper, to calculate cross power between x and y in short time bins. USAGE: Pxy,freqs,t=crossSpe...
b2ac6372a2c2f442314d721693636656e90fe49d
53,982
def force_slashend(path): """ Return ``path`` suffixed with ``/`` (path is unchanged if it is already suffixed with ``/``). """ if not path.endswith('/'): path = path + '/' return path
2e2be0dbb88fb380e581f49af532ea7b5724d918
53,983
def masked_dense(inputs, units, num_blocks=None, exclusive=False, kernel_initializer=None, reuse=None, name=None, *args, # pylint: disable=keyword-arg-before-vararg **kwargs): """A ...
06ac07a15b08dc56c0ff4c119772ded5e483966f
53,984
from typing import Tuple import re def cell_to_num(x: str) -> Tuple[int, int]: """Converts a cell to a row, column index :param x: Name of the cell (e.g. A2) :type x: str :return: Row, column index :rtype: tuple """ regex = re.compile("([A-Z]*)([0-9]*)") output = regex.search(x) ...
6ad2b0b2d33e65a790a13f580f546bf2655a5dec
53,985
def line_path_error_function(x, y, xerr, yerr, xa=-inf, xb=inf, samplefac=10): """Compute the probability that the data points actually lie along a line given the x and y value of the data point, the errors on the data, and the line parameters. If desired, compute only for the segment extending from xa ...
4673f952552e9d429a808c0f3c0520a93f2450ea
53,986
def scoreboard(self: Client) -> ScoreboardProxy: """Delegates to a :py:class:`mcipc.rcon.be.commands.scoreboard.ScoreboardProxy` """ return ScoreboardProxy(self, 'scoreboard')
6c7c48a656fb5cc3c8e9d27f8deecb13767ce906
53,987
import os import glob def find_hooks(file_prefix): """ Find all files in subdirectories whose names start with <file_prefix> """ file_pattern = os.path.dirname(__file__) + '/*/' + file_prefix + "*.py" module_paths = [f for f in glob.glob(file_pattern) if os.path.isfile(f)] module_paths.sort()...
bca73c4b04ca32dd036422ef08a494cb44179e4b
53,988
def apply_key_map(new_record: dict, old_record: dict, key_ref: dict): """ Apply key mapping between two records based on a key reference. Example: Given `key_ref`: `{'column1':'column2'}`. Extracts values from `old_record['column1']` to `new_record['column2']`. Parameters ---------- ...
8dbe68f182c1f0a425a1908a00e71214e4d186e3
53,989
def spe_to_fst(A, B, C, D): """ Takes in a rule of form A->B/C_D and creates an FST from that rule. Following are the types of rules covered by this generator: * a / b -> c_d (ex. qwertcaduiop -> qwertcbduiop) * TODO: a / b -> #_c (ex. aceuio -> bceuio) * TODO: a / b -> c_#...
cdba3f35d9669915a75c39c625f8a4d7144dfb3b
53,990
def semantic_segmentation_labelling(img, label_config): """One-hot encoder for semantic segmentation problem Parameters ---------- img : ndarray Batched input image data of size (batch_size, image_size, image_size, 1) label_config : dict Label contained into the dataset Returns...
aa559a2f13a4195305e67e28e616983037d8df87
53,991
def attack(y, k, s, m, a, c): """ Recovers the states associated with the outputs from a truncated linear congruential generator. More information: Frieze, A. et al., "Reconstructing Truncated Integer Variables Satisfying Linear Congruences" :param y: the sequential output values obtained from the trunc...
3a2f9bbc1fb08af25c46ef1501f8784a7101e90b
53,992
def inverse_odds(x, epsilon=EPSILON): """ Calculate probability from odds, and regularize returned probability to range [epsilon, 1-epsilon] :param x: odds value :return: probability value """ p = x/(1+x) p = np.minimum(np.maximum(p, epsilon), 1 - epsilon) return p
10a14cefdd9a3af98729cfbb8c762485bfac6e2b
53,993
def below_threshold(mat, threshold): """ :param mat: input image :param threshold: threshold value :return: values above the threshold are set to zero, and values less than or equal to the threshold are unchanged """ return cv2.threshold(mat, threshold, 0, cv2.THRESH_TOZERO_INV)[1]
181057c6585a81bb32b0990b7fe5a6dc07e20b81
53,994
def read_pip(): """ Read and Return the pip dependencies """ datei = open('requirements.txt','r') output_stream = [] for zeile in datei: zeile = zeile.replace("\n", "") output_stream.append(zeile) datei.close() return output_stream
9b21b52fe702d77e1372cb9afbf985ac1e8ec914
53,995
from typing import Sequence def interpret_quantity(value, expect_sequence): """Interpret a value as a pint Quantity via pisa.ureg Parameters ---------- value : scalar, Quantity, or sequence interpretable as Quantity expect_sequence : bool Specify `True` if you expect a sequence of quantit...
1b28f9b8f10f8eb79b67bd534ba105ac6399eb9d
53,996
def either_sqrt(num): """What if we want to send some custom error message back instead of just giving back an inscrutable Nothing? We can use the Either Monad!""" if num < 0: return either.Either.Left( "You can't take the square root of a negative number!") else: return eith...
0d0ec05b61bac26669899dc791e6713937430b5a
53,997
import sys def zclude(bed, other, exclude=True): """ Include or exclude intervals from bed that overlap other. If exclude is True: new = bedtools intersect -v -a bed -o other """ if other is None: return bed n_orig = sum(1 for _ in nopen(bed)) tmp = mktemp() if exclude: ...
473d9f932ca7f9aef7116ca8fb5cab0eb7cf5635
53,998
def psy_ta_rh(tdb, rh, patm=101325): """ Calculates psychrometric values of air based on dry bulb air temperature and relative humidity. For more accurate results we recommend the use of the the Python package `psychrolib`_. .. _psychrolib: https://pypi.org/project/PsychroLib/ Parameters -...
568b1bced541ec16c2490825838f4a8c80ef8a26
53,999