content
stringlengths
22
815k
id
int64
0
4.91M
async def chatidgetter(chat): """ Untuk .chatid, kembalikan ID obrolan yang Anda masuki saat itu. """ await chat.edit("ID Pesan: `" + str(chat.chat_id) + "`")
23,700
def python_to_json_syntax(dict_to_convert): """ Recursively update pythonic keys to JSON syntax in a dictionary and nested dictionaries if present. Args: dict_to_convert (dict): Dictionary with keys to convert from python to JSON syntax. """ for key, value in dict_to_conver...
23,701
def get_train_tags(force=False): """ Download (if needed) and read the training tags. Keyword Arguments ----------------- force : bool If true, overwrite existing data if it already exists. """ download_train_tags(force=force) return read_tags(train_tags_file_path)
23,702
def test_atomic_string_min_length_nistxml_sv_iv_atomic_string_min_length_1_2(mode, save_output, output_format): """ Type atomic/string is restricted by facet minLength with value 0. """ assert_bindings( schema="nistData/atomic/string/Schema+Instance/NISTSchema-SV-IV-atomic-string-minLength-1.xsd...
23,703
def select_own(ligands, decoys, scores): """Select ligand ids and decoy ids from full ranked ids.""" #scores format is full OUTDOCK line selected = set(ligands) selected.update(decoys) results = [] for scoreline in scores: #id = scoreline[extract_all.zincCol] #refer to correct column alw...
23,704
def create_app(): """ 生成FatAPI对象 :return: """ app = FastAPI( debug=settings.DEBUG, title=settings.PROJECT_NAME, # 项目名称 description=settings.DESCRIPTION, # 项目简介 docs_url=f"{settings.API_V1}/docs", # 自定义 docs文档的访问路径 redoc_url=f"{settings.API_V1}/redocs", # 禁...
23,705
def cmp_text_file(text, file): """returns True when text and file content are identical """ fh = open(file) ftext = fh.read() fh.close() return cmp(ftext, text)
23,706
def get_alignment_summary(seq_info): """ Determine the consensus sequence of an alignment, and create position matrix Definition of consensus: most common base represented at that position. """ consensus_sequence = [] position_matrix = [] for position in seq_info: #Ignore any ambi...
23,707
def update_tsr(tics, s_date, e_date): """this function adds a column in each ticker's stock data table for its tsr data within a given time period. """ db = db_connect() c = db.cursor() for tic_draft in tics: tic = tic_draft.lower() c.execute("ALTER TABLE table_%s ADD COLUMN tsr...
23,708
def calculate_pcx_chord_emission(impact_factor, Ti, w0, mu, Lnu, Vouter, rmax=40.0, nr=101, nlambda=2000, Lne=2.5, R_outer=35): """Calculates PCX emission with only the outer boundary spinning for a given impact factor Args: impact_factor (float): impact factor for chor...
23,709
def _get_variables(exp:Experiment, config: dict) -> dict: """Process the configuration's variables before rendering it""" return {key: value.format(exp=exp) for key, value in config.get("variables", {}).items()}
23,710
def func_calc_M(S): """ Use molecules structure/symbol to calculate molecular weight Parameter: S : structrue in a format: (atomType number) separated by '-' or blank space number of '-' and spaces does not matter precendent: '-' > blank space Examp...
23,711
def find_NN(ngbrof, ngbrin, distance_ULIM=NP.inf, flatten=False, parallel=False, nproc=None): """ ----------------------------------------------------------------------------- Find all nearest neighbours of one set of locations in another set of locations within a specified distance. ...
23,712
def index(request): """Magicaltastic front page. Plugins can register a hook called 'frontpage_updates_<type>' to add updates to the front page. `<type>` is an arbitrary string indicating the sort of update the plugin knows how to handle; for example, spline-forum has a `frontpage_updates_forum` h...
23,713
def fd_d1_o4_smoothend(var,grid,mat=False): """Centered finite difference, first derivative, 4th order using extrapolation to get boundary points var: quantity to be differentiated. grid: grid for var mat: matrix for the finite-differencing operator. if mat=False then it is created""" dx = grid[1]...
23,714
def find_node_pair_solutions(node_pairs, graph): """ Return path and cost for all node pairs in the path sets. """ node_pair_solutions = {} counter = 0 for node_pair in node_pairs: if node_pair not in node_pair_solutions: cost, path = dijkstra.find_cost(node_pair, graph) ...
23,715
def create_file(name, size, atime): """Create a file of given name, of size in bytes and access time atime.""" with open(name, "wb") as fo, open("/dev/zero", "r") as fi: ntodo = size while ntodo > 0: nwrite = min(ntodo, 2000) fo.write(fi.read(nwrite)) ntodo -=...
23,716
def run_e_live(): """Run e_live from cli.""" parser = ArgumentParser() parser.add_argument('action', help='action: "all", "name" or "number" of live ebuilds') print(e_live(parser.parse_args().action))
23,717
def get_step(a, b, marks=1): """Return a coordinate set between ``a`` and ``b``. This function returns a coordinate point between the two provided coordinates. It does this by determining the angle of the path between the two points and getting the sine and cosine from that angle. The returned coor...
23,718
def p_expression_integer_constant(parse): """ expression : INT """ parse[0] = our_ast.IntegerNode(parse[1])
23,719
def get_model_mask_neurons(model, layers): """ Defines a dictionary of type {layer: tensor} containing for each layer of a model, the binary mask representing which neurons have a value of zero (all of its parameters are zero). :param model: PyTorch model. :param layers: Tuple of layers on which app...
23,720
def outputStats(m, n, b, image): """ Output stats on the downsized images """ print("Downsized images are ({}, {})".format(m//b, n//b)) print("Block images are ({}, {})".format(m, n)) print("Average intensity at ({}, {}) is {:.2f}".format(m//4//b, n//4//b, image[m//4, n//4])) print("Average ...
23,721
def ValidateClusterVersion(cluster): """Validates the cluster version. Args: cluster: object, Anthos Multi-cloud cluster. Raises: UnsupportedClusterVersion: cluster version is not supported. MissingClusterField: expected cluster field is missing. """ version = _GetSemver(cluster) if versio...
23,722
def connection(): """Open a new connection or return the cached existing one""" try: existing_connection = GLOBAL_CACHE[CACHE_KEY_CONNECTION] except KeyError: new_connection = win32com.client.Dispatch(ADO_CONNECTION) new_connection.Provider = CONNECTION_PROVIDER new_connectio...
23,723
def getRigidAtoms(): """Returns atoms in rigid bodies in PDB""" atoms = [] fileName = pdbs[0] subprocess.call(["kgs_prepare.py", fileName]) f = open(fileName[:-4] + ".kgs.pdb", "r") lineList = f.readlines() f.close() if connectivity and not "CONECT" in lineList[-1]: with open(con...
23,724
def precision(theta,X,Y): """ accuracy function computes the accuracy of the logistic model theta on X with true target variable Y """ m = np.shape(X)[0] H = sigmoid(np.dot(X,theta)) H[H >= 0.5] = 1 H[H < 0.5] = 0 return np.sum(H == Y)/m
23,725
def test_get_voltage_extremes(): """ Tests the function "get_voltage_extremes" from heartRateMonitor.py :return: passes if correct voltage min and max values returned, fails o.w. """ from heartRateMonitor import get_voltage_extremes assert get_voltage_extremes([0.0, 0.3, 0.2, 0.6])[0] == pytest.app...
23,726
def get_converter(obj, coords=None, dims=None, chains=None): """Get the converter to transform a supported object to an xarray dataset. This function sends `obj` to the right conversion function. It is idempotent, in that it will return xarray.Datasets unchanged. Parameters ---------- obj : A ...
23,727
def timezone_by_tzvar(tzvar): """Convert a WWTS tzvar to a tzdata timezone""" return pytz.timezone(city_by_tzvar(tzvar))
23,728
def save_csv(csv_path: str, duplicates: pd.DataFrame) -> None: """Save a Pandas dataframe as a csv file.""" csv_file = os.path.join(csv_path, 'duplicates.csv') duplicates.to_csv(csv_file, index=False)
23,729
def fix_seed(seed: int): """Sets random seed everywhere.""" torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) random.seed(seed) np.random.seed(seed)
23,730
def group_recommend(request): """ Get or post file/directory discussions to a group. """ content_type = 'application/json; charset=utf-8' result = {} if request.method == 'POST': form = GroupRecommendForm(request.POST) if form.is_valid(): repo_id = form.cleaned_data[...
23,731
def test_cluster_ami(): """ This method return all cluster ami :return: """ assert len(tag_cluster_resources.cluster_ami()) >= 0
23,732
def easy_map(parser, token): """ The syntax: {% easy_map <address> [<width> <height>] [<zoom>] [using <template_name>] %} The "address" parameter can be an Address instance or a string describing it. If an address is not found a new entry is created in the database. """ width, height, z...
23,733
def pack_feed_dict(name_prefixs, origin_datas, paddings, input_fields): """ Args: name_prefixs: A prefix string of a list of strings. origin_datas: Data list or a list of data lists. paddings: A padding id or a list of padding ids. input_fields: A list of input fields dict. ...
23,734
def get_session_maker(): """ Return an sqlalchemy sessionmaker object using an engine from get_engine(). """ return sessionmaker(bind=get_engine())
23,735
def test_dimension_mismatch(): """Test that there's an exception if covar and noise matrices are mismatched""" with pytest.raises(DimensionMismatch): fan = FactorAnalysis.load_data_cov(A_SQ) fan.add_noise_cov(B_SQ)
23,736
def rescale_intensity(arr, in_range, out_range): """ Return arr after stretching or shrinking its intensity levels. Parameters ---------- arr: array input array. in_range, out_range: 2-tuple min and max intensity values of input and output arr. Returns ------- out: arra...
23,737
def get_error_info(): """Return info about last error.""" msg = "{0}\n{1}".format(str(traceback.format_exc()), str(sys.exc_info())) return msg
23,738
def call_oai_api(resumption_token): """ Request page of data from the Argitrop OAI API Parameters ---------- resumption_token : object (first page) or string or xml.etree.ElementTree.Element token returned by previous request. Returns ------- response_xml : string Respo...
23,739
def save_last_move_statistics(): """ Reads outputs of simulation CSV files. Saves CSV files for each experimental problem separately. Tasks: A, B, C, D and E Depths = 0, 1, 2, 3, 4 Saves files for each task and depth in separate files """ for letter in letters: directory ...
23,740
def setup_logger() -> None: """ Set up the logger instance. INFO to stderr """ logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.INFO) logger.addHandler(ch)
23,741
def save_pano_config(p): """ saves a panorama config file to the local disk from the session vars. :return: """ filename = get_filename(p) with open(filename, 'w') as yml_fh: yml_fh.write(yaml.dump(session[p + '_config'], default_flow_style=False)) return redirect("/export")
23,742
def append_source_filess(index_filename, source_files, driver): """This appends the paths to different source files to the temporary index file For example SRCSRV: source files --------------------------------------- c:\php-sdk\phpdev\vc15\x86\php-7.2.14-src\ext\pdo_sqlsrv\pdo_dbh.cpp*pdo_sqlsrv...
23,743
def is_transport(name): """Test if all parts of a name are transport coefficients For example, efe_GB, chie_GB_div_efi_GB are all composed of transport coefficients, but gam_GB and chiee_GB_plus_gam_GB are not. """ transport = True try: for part_name in extract_part_names(split_parts(na...
23,744
def blacken(session): """Run black code formater.""" session.install("black==19.3b0", "isort==4.3.21") files = ["noxfile.py", "winterbloom_ad_dacs"] session.run("black", *files) session.run("isort", "--recursive", *files)
23,745
def detect_moved_files(file_manifest, diff): """ Detect files that have been moved """ previous_hashes = defaultdict(set) for item in file_manifest['files']: previous_hashes[item['hash']].add(item['path']) diff_dict = make_dict(diff) # files with duplicate hashes are assumed to have the same conten...
23,746
def test_valid_version_upload(client, settings, repository, admin_user): """Test a valid version upload when enforcement is activated""" settings.LOCALSHOP_VERSIONING_TYPE = 'versio.version_scheme.Simple3VersionScheme' key = admin_user.access_keys.create(comment='For testing') auth = { 'HTTP_AU...
23,747
def test_declaration(): """ Test defining tables by declaration. """ class GeoAreaTable(TestTable): name = tables.Column() population = tables.Column() assert len(GeoAreaTable.base_columns) == 2 assert 'name' in GeoAreaTable.base_columns assert not hasattr(GeoAreaTable, 'na...
23,748
def decodecaps(blob): """decode a bundle2 caps bytes blob into a dictionary The blob is a list of capabilities (one per line) Capabilities may have values using a line of the form:: capability=value1,value2,value3 The values are always a list.""" caps = {} for line in blob.splitlines(...
23,749
def create_feature_columns() -> Tuple[list, list, list, list, list]: """ Returns: dense_feature_columns (list): 连续特征的feature_columns category_feature_columns (list): 类别特征的feature_columns target_feedid_feature_columns (list): 目标feed的feature_columns sequence_feature_columns (list)...
23,750
def an(pos=5): """ Alineamiento del texto. @pos: 1: Abajo izquierda 2: Abajo centro 3: Abajo derecha 4: Mitad derecha 5: Mitad centro 6: Mitad derecha 7: Arriba izquierda 8: Arriba centro 9: Arriba derecha """ apos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if pos not...
23,751
def applyLineWidth(shape, lineWidth): """ Applies the line width to the supplied shape node. :type shape: om.MObject :type lineWidth: float :rtype: None """ fnDagNode = om.MFnDagNode(shape) plug = fnDagNode.findPlug('lineWidth', False) plug.setFloat(lineWidth)
23,752
def propagate(node, region): """ Because KD Tree is built from the bottom up, we must propagate the regions properly from the top down once the tree has been constructed. """ if node is None: return node.region = region # "close off" the above area for below nodes if n...
23,753
def arista_output(accesslist): """Helper function to generate accesslist ouput appropriate for an Arista switch/router. This will eventually get rolled up into a output module or class.""" # I have studied the sacred texts from the merciless Trigger Dojo # TODO: this should be refactored, i...
23,754
def main(iterator): """ Given a line iterator of the bash file, returns a dictionary of keys to values """ values = {} for line in iterator: if not line.startswith('#') and len(line.strip()) > 0: match_obj = line_regex.search(line) if match_obj is not None: key, value = match_obj.gr...
23,755
def is_any(typeref: irast.TypeRef) -> bool: """Return True if *typeref* describes the ``anytype`` generic type.""" return isinstance(typeref, irast.AnyTypeRef)
23,756
def repeat_1d(inputs: tf.Tensor, count: Union[tf.Tensor, int], name="repeat_1d"): """Repeats each element of `inputs` `count` times in a row. '''python repeat_1d(tf.range(4), 2) -> 0, 0, 1, 1, 2, 2, 3, 3 ''' Parameters: inputs: A 1D tensor with shape [`size`] to...
23,757
def main(from_dir, to_dir, backup_start, frequency_interval, automatic_backup, upload_zip): """ A command line backup tool to keep your files stored at dropbox by using its API. It runs at given time intervals specified by the user and can perform automatic backups using cronjobs """ ...
23,758
def _calc_weights(df, asset_dict, weight_by): """ calculate weights for assets in asset_dict using weight_by method """ weight_by_choices = ('Equal', 'Sharpe Ratio', 'Annual Returns', 'Std Dev', 'Vola', 'DS Vola') assert weight_by in weight_by_choices, \ "Invalid weight_by ...
23,759
def create_logger(logfile=r"/tmp/tomoproc.log"): """Default logger for exception tracking""" logger = logging.getLogger("tomoproc_logger") logger.setLevel(logging.INFO) # create the logging file handler fh = logging.FileHandler(logfile) fh.setFormatter( logging.Formatter( '...
23,760
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool: """Set up the Twente Milieu components.""" async def update(call) -> None: """Service call to manually update the data.""" unique_id = call.data.get(CONF_ID) await _update_twentemilieu(opp, unique_id) opp.servic...
23,761
def parsePDCfile(fpath='data/CPTAC2_Breast_Prospective_Collection_BI_Proteome.tmt10.tsv'): """ Takes a PDC file ending in .tmt10.tsv or .itraq.tsv and creates tidied data frame with Gene, Patient, logratio and diffFromMean values Parameters ---------- fpath : chr, optional DESCR...
23,762
def ave(x): """ Returns the average value of a list. :param x: a given list :return: the average of param x """ return np.mean(x)
23,763
def information_gain(f1, f2): """ This function calculates the information gain, where ig(f1,f2) = H(f1) - H(f1|f2) Input ----- f1: {numpy array}, shape (n_samples,) f2: {numpy array}, shape (n_samples,) Output ------ ig: {float} """ ig = entropyd(f1) - conditional_entropy...
23,764
def main(): """ This is a hangman game which will generate a vocabulary to let the user guess. As the guess is wrong, user will lose one life. The game will end till the life to zero. """ answer = random_word() guess(answer)
23,765
def output_if_exists(filename): """Returns file name if the file exists Parameters ---------- filename : str File in question. Returns ------- str Filename. """ if os.path.exists(filename): return filename return None
23,766
def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int=-1, ) -> paddle.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: size (int): size of mask chunk_size (int): size of chunk ...
23,767
def main(argv): """ Main entry of this script. Parameters ------ argv: list of str Arguments received from the command line. """ annotation = np.genfromtxt('annotation.csv', dtype='int', delimiter=',', skip_header=1) detected = np.genfromtxt(...
23,768
def filtergt(gtfile, majorgtcount, outfile, chromorder): """ cnv with major genotype count larger than majorgtcount will be exclude """ gtdf = loadgtfile(gtfile, chromorder) newdf = filtergenotype(gtdf, majorgtcount) newdf.to_csv(outfile, sep='\t', index=False, float_format='%.2f', na_rep='NA')
23,769
def top_tags(request): """ Shows a list of the most-used Tags. Context:: object_list The list of Tags Template:: cab/top_tags.html """ return render_to_response('cab/top_tags.html', { 'object_list': Snippet.objects.top_item...
23,770
def check_integer_sign(value): """ :param value: :return: """ return value >= 0
23,771
def masks_empty(sample, mask_names): """ Tests whether a sample has any non-masked values """ return any(not torch.any(sample[name] != 0) for name in mask_names)
23,772
def quantize_factor(factor_data, quantiles=5, bins=None, by_group=False): """ Computes period wise factor quantiles. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single...
23,773
def load_all_dbs(database_dir): """Load and return a ShowDB and TrackerDB. Returns: showdb: ShowDatabse instance tracker: TrackerDatabase instance """ showdb = load_database(os.path.join(database_dir, '.showdb.json')) tracker = load_database(os.path.join(database_dir, '.tracker.jso...
23,774
def listSplit(aList, n): """将一个列表以n个元素为一个单元进行均分,返回嵌套列表""" return [aList[i:i+n] for i in range(0,len(aList),n)]
23,775
def sub(evm: Evm) -> None: """ Subtracts the top two elements of the stack, and pushes the result back on the stack. Parameters ---------- evm : The current EVM frame. Raises ------ StackUnderflowError If `len(stack)` is less than `2`. OutOfGasError If `...
23,776
def refs(request): """ Настройка назначения анализов вместе """ if request.method == "GET": rows = [] fraction = directory.Fractions.objects.get(pk=int(request.GET["pk"])) for r in directory.References.objects.filter(fraction=fraction).order_by("pk"): rows.append( ...
23,777
def transform(data): """replace the data value in the sheet if it is zero :param data: data set :return: data set without zero """ data_transformed = data.applymap(zero2minimum) return data_transformed
23,778
def findChildren(node, name): """Returns all the children of input node, with a matching name. Arguments: node (dagNode): The input node to search name (str): The name to search Returns: dagNode list: The children dagNodes """ return __findChildren(node, name, False)
23,779
def test_deposit_invalid_account(client, acc1_usd_deposit_transaction_factory): """`POST /transactions/deposit/interactive` fails with an invalid `account` parameter.""" acc1_usd_deposit_transaction_factory() response = client.post( DEPOSIT_PATH, { "asset_code": "USD", ...
23,780
def main(): """ Robot demo Loads all robots in an empty scene, generate random actions """ logging.info("*" * 80 + "\nDescription:" + main.__doc__ + "*" * 80) # Create empty scene settings = MeshRendererSettings(enable_shadow=False, msaa=False, texture_scale=0.5) s = Simulator(mode="gui_...
23,781
def get_process_rss(force_update=False, pid=None): """ <Purpose> Returns the Resident Set Size of a process. By default, this will return the information cached by the last call to _get_proc_info_by_pid. This call is used in get_process_cpu_time. <Arguments> force_update: Allows the caller ...
23,782
def doc_to_dict(doc) -> Dict: """Takes whatever the mongo doc is and turns into json serializable dict""" ret = {k: stringify_mongovalues(v) for k, v in doc.items() if k != "_id"} ret["_id"] = str(doc["_id"]) return ret
23,783
def add_srv_2cluster(cluster_name, srvjson): """ 添加服务到数据库 :param cluster_name: :param srvjson: :return: """ status = '' message = '' resp = {"status": status, "message": message} host_name = srvjson.get('host_name') service_name = srvjson.get('service_name') sfo_clu_node ...
23,784
def _add_left_zeros(number, iteration_digits): """Add zeros to the left side of the experiment run number. Zeros will be added according to missing spaces until iterations_digits are reached. """ number = str(number) return f'{"0" * (iteration_digits - len(number))}{number}'
23,785
def slack_webhook_mead_eval_intent(parent_details: Dict, webhook: str, template: str, base_dir: str) -> None: """Substitute a template message and post to slack :param parent_details: The context to use to replace values in the template. :param webhook: The webhook key :param template: The message. ...
23,786
def sharpdiff(y_true, y_pred): """ @param y_true: tensor of shape (batch_size, height, width, channels) @param y_pred: tensor of shape (batch_size, height, width, channels) @return: the sharpness difference as a scalar """ def log10(tensor): numerator = tf.math.log(tensor); ...
23,787
def admin_setfriend(): """ Set the friend state of a user """ uid = request.args.get("uid", "") state = request.args.get("state", "1") # Default: set as friend try: state = bool(int(state)) except Exception: return ( "<html><body><p>Invalid state string: '{0}'</p></body>...
23,788
def LF_CG_BICLUSTER_BINDS(c): """ This label function uses the bicluster data located in the A global network of biomedical relationships """ sen_pos = c.get_parent().position pubmed_id = c.get_parent().document.name query = bicluster_dep_df.query("pubmed_id==@pubmed_id&sentence_num==@sen_p...
23,789
def setup_argparse(parser: argparse.ArgumentParser) -> None: """Setup argument parser for ``cubi-tk org-raw check``.""" return OrganizeCommand.setup_argparse(parser)
23,790
def single_point_crossover(parents: List[Chromosome], probability: float = 0.7) -> List[Chromosome]: """ Make the crossover of two parents to generate two child. The crossover has a probability to be made. The crossover point is random. :param parents: selected parents :param probability: probabili...
23,791
def plot_evolution_of_density(lattice_grid_shape: Tuple[int, int] = (50, 50), initial_p0: float = 0.5, epsilon: float = 0.08, omega: float = 1.0, time_steps: int = 2500, ...
23,792
def setup_logging(): """ Sets up the logging for multiple processes. Only enable the logging for the master process, and suppress logging for the non-master processes. """ # Set up logging format. _FORMAT = "[%(levelname)s: %(filename)s: %(lineno)4d]: %(message)s" if du.is_master_proc(): ...
23,793
def main(): """Demonstrate the Anagram Generator.""" print('I can find all phrase anagrams given a word or phrase.\n' 'I\'m fun at parties.') # Print first 500 results. word = 'see shells' print(f'\nAnalyzing: {word}\n') anagram_phrases = anagram_generator(word) for i, phrase in en...
23,794
def test_get_instance_metrics_database_size_metrics(check): """ Test the function behaves correctly when `database_size_metrics` is passed """ expected = util.COMMON_METRICS expected.update(util.NEWER_92_METRICS) expected.update(util.DATABASE_SIZE_METRICS) res = check._get_instance_metrics(T...
23,795
def get_node_count(network=None, base_url=DEFAULT_BASE_URL): """Reports the number of nodes in the network. Args: network (SUID or str or None): Name or SUID of a network or view. Default is the "current" network active in Cytoscape. base_url (str): Ignore unless you need to specify...
23,796
def check_dataset_to_ref(dset, ref): """ Check that all data in Dataset is contained in the ref Dataset. """ # file format (these are not expected to match) assert dset.file_format == ref.file_format # global attributes dset_attributes = dset.ncattrs() ref_attributes = ref.ncattrs() for a...
23,797
def process_sample( sample: Dict[str, Any], relation_vocab: Dict[str, int], spacy_model: Any, tokenizer: Any, ) -> Tuple[Optional[Dict[str, Any]], Dict[str, int]]: """Processes WebRED sample and updates relation vocabulary. To process a raw WebRED example, we first extract subj and obj and remove t...
23,798
def transform_s3(key, bucket="songsbuckettest"): """ REMEBER TO DO DEFENSIVE PROGRAMMING, WRAP IN TRY/CATCH """ s3 = boto3.client('s3') # print("connection to s3 -- Test") with tempfile.NamedTemporaryFile(mode='wb') as tmp: s3.download_fileobj(bucket, key, tmp) try: ...
23,799