content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compact_axis_angle_from_matrix(R): """Compute compact axis-angle from rotation matrix. This operation is called logarithmic map. Note that there are two possible solutions for the rotation axis when the angle is 180 degrees (pi). We usually assume active rotations. Parameters ---------- ...
a7493a5ed1c622b9cbec6e9f0771e62f7f4712e2
3,656,600
def _generate_IPRange(Range): """ IP range to CIDR and IPNetwork type Args: Range: IP range Returns: an array with CIDRs """ if len(Range.rsplit('.')) == 7 and '-' in Range and '/' not in Range: if len(Range.rsplit('-')) == 2: start_ip, stop_ip = Range.rspli...
d86f8db8e87313b12f35669ee25cc3f3d229c631
3,656,601
def is_dict_homogeneous(data): """Returns True for homogeneous, False for heterogeneous. An empty dict is homogeneous. ndarray behaves like collection for this purpose. """ if len(data) == 0: return True k0, v0 = next(iter(data.items())) ktype0 = type(k0) vtype0 = type(v0) i...
921e66639cd6a8584e99e14852158594b1001ef9
3,656,602
from typing import Union from typing import Callable from re import T from typing import Generator from typing import Any def translate(item: Union[Callable[P, T], Request]) -> Union[Generator[Any, Any, None], Callable[P, T]]: """Override current language with one from language header or 'lang' parameter. Can...
5042cc77efb1477444f8f9611055fb3e183cf3d3
3,656,603
def get_all(isamAppliance, check_mode=False, force=False, ignore_error=False): """ Retrieving the current runtime template files directory contents """ return isamAppliance.invoke_get("Retrieving the current runtime template files directory contents", "/mga/template_f...
9ff291b63471b57b110885c35939c8afe3d2f0d8
3,656,604
from sys import path def build_path(dirpath, outputfile): """ Build function """ #some checks if not path.exists(dirpath): print("Path does not exist!") return 1 if not path.isdir(dirpath): print("Path is not folder") return 1 #for now SQLite t...
01492296925a259873e327d8eae938710fe78f20
3,656,605
import os def _fix_importname(mname): """ :param mname: """ mname = os.path.normpath(mname) mname = mname.replace(".", "") mname = mname.replace("-", "") mname = mname.replace("_", "") mname = mname.replace(os.path.sep, "") mname = mname.replace(os.path.pathsep, "") return mn...
22f8ab56800a593502822a612c3f642e8cec22ea
3,656,606
def main(args, out, err): """ This wraps GURepair's real main function so that we can handle exceptions and trigger our own exit commands. This is the entry point that should be used if you want to use this file as a module rather than as a script. """ cleanUpHandler = BatchCaller(args.ve...
c506306a93804ab60c1a6805e9c53a0fd9dd7cfd
3,656,607
import requests import os import io def getSymbolData(symbol, sDate=(2000,1,1), adjust=False, verbose=True, dumpDest=None): """ get data from Yahoo finance and return pandas dataframe Parameters ----------- symbol : str Yahoo finanance symbol sDate : tuple , default (2000,1,1) ...
24e06e34e4f5a4705d59a2ffb32c767bbc25adcf
3,656,608
def generateLouvainCluster(edgeList): """ Louvain Clustering using igraph """ Gtmp = nx.Graph() Gtmp.add_weighted_edges_from(edgeList) W = nx.adjacency_matrix(Gtmp) W = W.todense() graph = Graph.Weighted_Adjacency( W.tolist(), mode=ADJ_UNDIRECTED, attr="weight", loops=False) # ig...
c171474bdd81456cbbc488b0a8cb826f881419ec
3,656,609
def exprvars(name, *dims): """Return a multi-dimensional array of expression variables. The *name* argument is passed directly to the :func:`pyeda.boolalg.expr.exprvar` function, and may be either a ``str`` or tuple of ``str``. The variadic *dims* input is a sequence of dimension specs. A dime...
6b65872029de938d37c9e968f696587e2a03ff8c
3,656,610
def cell_segmenter(im, thresh='otsu', radius=20.0, image_mode='phase', area_bounds=(0,1e7), ecc_bounds=(0, 1)): """ This function segments a given image via thresholding and returns a labeled segmentation mask. Parameters ---------- im : 2d-array Image to be segmente...
f9a8fa3c29cbb213ed67c3df93106a81f53ae985
3,656,611
from datetime import datetime def generate_report(start_date, end_date): """Generate the text report""" pgconn = get_dbconn('isuag', user='nobody') days = (end_date - start_date).days + 1 totalobs = days * 24 * 17 df = read_sql(""" SELECT station, count(*) from sm_hourly WHERE valid >= %s ...
f71b5ab58922b9018abc1868661f88c268de8f94
3,656,612
import pathlib def whole(eventfile,par_list,tbin_size,mode,ps_type,oversampling,xlims,vlines): """ Plot the entire power spectrum without any cuts to the data. eventfile - path to the event file. Will extract ObsID from this for the NICER files. par_list - A list of parameters we'd like to extract fr...
77b51cc8774bdb1b670e2a6b56a9cd65213f70de
3,656,613
def handle_postback(): """Handles a postback.""" # we need to set an Access-Control-Allow-Origin for use with the test AJAX postback sender # in normal operations this is NOT needed response.set_header('Access-Control-Allow-Origin', '*') args = request.json loan_id = args['request_token'] m...
59683921b7a21f50c2905c47c33036fd75ce54f4
3,656,614
def get_bb_bev_from_obs(dict_obs, pixor_size=128): """Input dict_obs with (B,H,W,C), return (B,H,W,3)""" vh_clas = tf.squeeze(dict_obs['vh_clas'], axis=-1) # (B,H,W,1) # vh_clas = tf.gather(vh_clas, 0, axis=-1) # (B,H,W) vh_regr = dict_obs['vh_regr'] # (B,H,W,6) decoded_reg = decode_reg(vh_regr, pixor_size...
d286ec0c3132c2dcb931cb941fd247810c0ce1cf
3,656,615
def get_hard_edges(obj): """ :param str obj: :returns: all hard edges from the given mesh in a flat list :rtype: list of str """ return [obj + '.e[' + str(i) + ']' for i, edgeInfo in enumerate(cmds.polyInfo(obj + '.e[*]', ev=True)) if edgeInfo.endswith('Hard\n')]
67de22469a38e55e88d21f1853280138795a04cb
3,656,616
def make_system(l=70): """ Making and finalizing a kwant.builder object describing the system graph of a closed, one-dimensional wire with l number of sites. """ sys = kwant.Builder() lat = kwant.lattice.chain() sys[(lat(x) for x in range(l))] = onsite sys[lat.neighbors()] = hopping return sys.finalized()
fa3d25933fd086519569cbb24ff77bf3c86c1303
3,656,617
from typing import Type from pathlib import Path from typing import Dict def _gen_test_methods_for_rule( rule: Type[CstLintRule], fixture_dir: Path, rules_package: str ) -> TestCasePrecursor: """Aggregates all of the cases inside a single CstLintRule's VALID and INVALID attributes and maps them to altered nam...
5a12d84bdcff039179ef9b9f1105e6beecccbf05
3,656,618
def evaluate_score_batch( predicted_classes=[], # list, len(num_classes), str(code) predicted_labels=[], # shape (num_examples, num_classes), T/F for each code predicted_probabilities=[], # shape (num_examples, num_classes), prob. [0-1] for each code raw_ground_truth_labels=[], # list(('dx1', 'dx2')...
314f94433704cc2986df9082a749caaf52738f08
3,656,619
def pair(data, color=None, tooltip=None, mark='point', width=150, height=150): """ Create pairwise scatter plots of all column combinations. In contrast to many other pairplot tools, this function creates a single scatter plot per column pair, and no distribution plots along the diagonal. Para...
ed712972e503795bbfaeac6844a225444d946018
3,656,620
import tqdm def gauss_kernel(model_cell, x, y, z, sigma=1): """ Convolute aligned pixels given coordinates `x`, `y` and values `z` with a gaussian kernel to form the final image. Parameters ---------- model_cell : :class:`~colicoords.cell.Cell` Model cell defining output shape. x : :c...
0ff61121fbf330e3e15862b82b0929ae3b8748f9
3,656,621
def get_configs_from_multiple_files(): """Reads training configuration from multiple config files. Reads the training config from the following files: model_config: Read from --model_config_path train_config: Read from --train_config_path input_config: Read from --input_config_path Returns: mode...
4f561235568667a6fe71d77c23769ea8878ebe20
3,656,622
def line_to_numbers(line: str) -> t.List[int]: """Split a spreadsneet line into a list of numbers. raises: ValueError """ return list(map(int, line.split()))
fce9af5e1c213fd91f0edf8d7fa5877f15374908
3,656,623
def bits_to_amps(bits): """helper function to convert raw data from usb device to amps""" return bits*BITS_TO_AMPS_SLOPE + BITS_TO_AMPS_Y_INTERCEPT
5653582987b6a7924c11f037badc1a61541c6ca2
3,656,624
import re def fields_to_dict(fields): """ FIXME: https://www.debuggex.com/r/24QPqzm5EsR0e2bt https://www.debuggex.com/r/0SjmBL55ySna0kFF https://www.debuggex.com/r/Vh9qvHkCV4ZquS14 """ result = {} if not fields or len(fields.strip()) == 0: return result # look_beh...
2e7ebc2e9277ef693498d04c731f309e17fd4501
3,656,625
import os import glob def get_font_paths(fonts_dir): """ Load font path recursively from a folder :param fonts_dir: folder contains ttf、otf or ttc format font :return: path of all fonts """ print('Load fonts from %s' % os.path.abspath(fonts_dir)) fonts = glob.glob(fonts_dir + '/**/*', recu...
bf6368f90023fd59d64d358e6dac919627feb9ab
3,656,626
def time_difference(t_early, t_later): """ Compute the time difference between t_early and t_later Parameters: t_early: np.datetime64, list or pandas series. t_later: np.datetime64, list or pandas series. """ if type(t_early) == list: t1 = np.array(t_early) elif type(t_early) ==...
0d4e6bac3aed2e5a2848c4289dadc92120a4f7a1
3,656,627
def conv2d_block(input_tensor, n_filters, kernel_size=3, batchnorm=True): """ Convolutional block with two convolutions followed by batch normalisation (if True) and with ReLU activations. input_tensor: A tensor. Input tensor on which the convolutional block acts. n_filters: An integer. Number of filters in...
8bb435ed1e091fff26d49290a8ca6d0c9c12ec67
3,656,628
def check_credentials(username): """ Function that check if a Credentials exists with that username and return true or false """ return Credentials.if_credential_exist(username)
8515bbc39afd003fc193cbb80c97f5f718657fa6
3,656,629
def rpc_category_to_super_category(category_id, num_classes): """Map category to super-category id Args: category_id: list of category ids, 1-based num_classes: 1, 17, 200 Returns: super-category id, 0-based """ cat_id = -1 assert num_classes in RPC_SUPPORT_CATEGORIES, \ ...
8056aea308f66a65a4135a6fc7f061873d990624
3,656,630
def setup_integration(): """Set up a test resource.""" print('Setting up a test integration for an API') return Integration(name='myapi', base_url='https://jsonplaceholder.typicode.com')
d2720db6ae520e21edc555ad0c899652c6584406
3,656,631
def secondsToHMS(intervalInSeconds): """converts time in seconds to a string representing time in hours, minutes, and seconds :param intervalInSeconds: a time measured in seconds :returns: time in HH:MM:SS format """ interval = [0, 0, intervalInSeconds] interval[0] = (inter...
b38d4b886eaabd1361c162b6b7f55e11493dfb60
3,656,632
import itertools def build_rdn(coords, r, **kwargs): """ Reconstruct edges between nodes by radial distance neighbors (rdn) method. An edge is drawn between each node and the nodes closer than a threshold distance (within a radius). Parameters ---------- coords : ndarray Coordina...
83f2d68fbb854e2ef25e03f5d58d6c96c02c0127
3,656,633
def find_layer(model, type, order=0): """ Given a model, find the Nth layer of the specified type. :param model: the model that will be searched :param type: the lowercase type, as it is automatically saved by keras in the layer's name (e.g. conv2d, dense) :param order: 0 by default (the first matc...
6d4e08c181900774b9e5666a11df9767f68a10ca
3,656,634
def _interpretable(model): # type: (Union[str, h2o.model.ModelBase]) -> bool """ Returns True if model_id is easily interpretable. :param model: model or a string containing a model_id :returns: bool """ return _get_algorithm(model) in ["glm", "gam", "rulefit"]
4ae73e5b7ed98b61b56920985128212e3051c789
3,656,635
def apply_pb_correction(obs, pb_sensitivity_curve, cutoff_radius): """ Updates the primary beam response maps for cleaned images in an ObsInfo object. Args: obs (ObsInfo): Observation to generate maps for. pb_sensitivity_curve: Primary beam se...
02ee2913ce781f4a02e85910c69cfe5b534e62f4
3,656,636
def makeLoadParams(args): """ Create load parameters for start load request out of command line arguments. Args: args (dict): Parsed command line arguments. """ load_params = {'target': {}, 'format': {'date_time': {}, 'boolean': {}}, ...
f1c0e9297775305c36acbb950bfc05e785bde87c
3,656,637
from hash import HashTable def empty_hash(): """Initialize empty hash table.""" test_hash = HashTable() return test_hash
02700169c89427af4d2db123e110ec383d9332eb
3,656,638
def denoise_sim(image, std, denoiser): """Simulate denoising problem Args: image (torch.Tensor): image tensor with shape (C, H, W). std (float): standard deviation of additive Gaussian noise on the scale [0., 1.]. denoiser: a denoiser instance (as in algorithms.denoiser). ...
216944b26c3ca0e04b8b5801766321fe60ee7e02
3,656,639
def _find_weektime(datetime, time_type='min'): """ Finds the minutes/seconds aways from midnight between Sunday and Monday. Parameters ---------- datetime : datetime The date and time that needs to be converted. time_type : 'min' or 'sec' States whether the time difference shoul...
2ed28166d239dabdc9f8811812e472810b10c7d7
3,656,640
from typing import List from typing import Tuple def linear_to_image_array(pixels:List[List[int]], size:Tuple[int,int]) -> np.ndarray: """\ Converts a linear array ( shape=(width*height, channels) ) into an array usable by PIL ( shape=(height, width, channels) ).""" a = np.array(pixels, dtype=np.uint8) sp...
431170c71a3d6464be5dd5b9d248b2866ba3ac6a
3,656,641
def stop_processes(hosts, pattern, verbose=True, timeout=60): """Stop the processes on each hosts that match the pattern. Args: hosts (list): hosts on which to stop the processes pattern (str): regular expression used to find process names to stop verbose (bool, optional): display comma...
898a358b5e61952d72be15eecb10b00ce8bd2efd
3,656,642
def field_as_table_row(field): """Prints a newforms field as a table row. This function actually does very little, simply passing the supplied form field instance in a simple context used by the _field_as_table_row.html template (which is actually doing all of the work). See soc/templates/soc/templatetags/_...
74d120e2a46ae8465832d98ddf02848b5b2cc936
3,656,643
def get_samples(select_samples: list, avail_samples: list) -> list: """Get while checking the validity of the requested samples :param select_samples: The selected samples :param avail_samples: The list of all available samples based on the range :return: The selected samples, verified """ # S...
e1c0c98697d2c504d315064cbdfbad379165d317
3,656,644
def createMemoLayer(type="", crs=4326, name="", fields={"id":"integer"}, index="no"): """ Créer une couche en mémoire en fonction des paramètres :param type (string): c'est le type de geometrie "point", "linestring", "polygon", "multipoint","multilinestring","multipolygon" :par...
713823d9b59b7c4ccf7bdd938a720d385629e02f
3,656,645
import json def load_templates(package): """ Returns a dictionary {name: template} for the given instrument. Templates are defined as JSON objects, with stored in a file named "<instrument>.<name>.json". All templates for an instrument should be stored in a templates subdirectory, made into a pa...
6213eb6e8b7be0bb7057da49d02fe495d7db6660
3,656,646
def get_count_matrix(args): """首先获取数据库中全部文档的id,然后遍历id获取文档内容,再逐文档 进行分词,生成计数矩阵。""" global DOC2IDX with DocDB(args.db_path) as doc_db: doc_ids = doc_db.get_doc_ids() DOC2IDX = {doc_id: i for i, doc_id in enumerate(doc_ids)} row, col, data = [], [], [] _count = partial(count, args) ...
6279666c6dfdf66dba13edfe57e55525de15d894
3,656,647
def communication_round(model, clients, train_data, train_labels, train_people, val_data, val_labels, val_people, val_all_labels, local_epochs, weights_accountant, individual_validation, local_operation): """ One round of communication between a 'server' and the 'clients'. Each client 'd...
f8a8ef93845e09394cea6a2f6077a0ae2dfaed18
3,656,648
import collections def _find_stop_area_mode(query_result, ref): """ Finds the mode of references for each stop area. The query results must have 3 columns: primary key, foreign key reference and number of stop points within each area matching that reference, in that order. :param...
e4677638b272e67d2ae21ee97f71f1f1700fd072
3,656,649
def get_all_funds_ranking(fund_type: str = 'all', start_date: str = '-1y', end_date: str = arrow.now(), sort: str = 'desc', subopts: str = '', available: str = 1): """Get all funds ranki...
55dd84c8f8830d6c60411de858a9aec1f14a30be
3,656,650
from typing import List from typing import Any from re import T def _conform_list(li: List[Any]) -> List[T]: """ Ensures that every element in *li* can conform to one type :param li: list to conform :return: conformed list """ conform_type = li[0].__class__ for i in li: if isinstan...
29131a9f5979318e0fc50408b67938ffbd56fa5a
3,656,651
def _255_to_tanh(x): """ range [0, 255] to range [-1, 1] :param x: :return: """ return (x - 127.5) / 127.5
a60a67ee489093292fc58136a8f01387482fb162
3,656,652
import os import re import sys def read_content(filename): """Read content and metadata from file into a dictionary.""" # Read file content. text = fread(filename) # Read metadata and save it in a dictionary. date_slug = os.path.basename(filename).split('.')[0] match = re.search('^(?:(\\d\\d\...
5337830593959e0bf29b4d369789120a265badfc
3,656,653
import torch def train_one_epoch(train_loader, model, criterion, optimizer, epoch, opt, num_train_samples, no_acc_eval=False): """ model training :param train_loader: train dataset loader :param model: model :param criterion: loss criterion :param optimizer: :param epoch: ...
5b5efd1292322090abcb795fc633638f478f0afa
3,656,654
import datetime def Write(Variable, f): """Function to Convert None Strings to Strings and Format to write to file with ,""" if isinstance(Variable, str) == False: if isinstance(Variable, datetime.datetime) == True: return f.write(f"{Variable.strftime('%Y-%m-%d')},") else: ...
9963c4117c7cc3f19d91331ed6c36e5733cffb56
3,656,655
def graphs_infos(): """ Build and return a JSON file containing some information on all the graphs. The json file is built with the following format: [ For each graph in the database : { 'graph_id': the id of the graph, 'name': the name of the graph, 'iso'...
ab6fee49188ad422e1e3a5e2763510ae791a840b
3,656,656
def collect_compare(left, right): """ returns a tuple of four lists describing the file paths that have been (in order) added, removed, altered, or left the same """ return collect_compare_into(left, right, [], [], [], [])
2a29d7b896fb037a8784e7c82794d9b67eb2924a
3,656,657
def _get_smallest_vectors(supercell, primitive, symprec): """ shortest_vectors: Shortest vectors from an atom in primitive cell to an atom in supercell in the fractional coordinates. If an atom in supercell is on the border centered at an atom in primitive and there are multiple vectors...
352d4e7ba9552fa4fe5abdb9eb45c4555dff603d
3,656,658
def root(): """Root endpoint that only checks if the server is running.""" return 'Server is running...'
ea9ecd1c736e9379795f361462ed54f464a4008b
3,656,659
def clone_model(model, **new_values): """Clones the entity, adding or overriding constructor attributes. The cloned entity will have exactly the same property values as the original entity, except where overridden. By default, it will have no parent entity or key name, unless supplied. Args: ...
ed668632c8917ad685b86fb5c71146be7c9b3b96
3,656,660
def learn_laterals(frcs, bu_msg, perturb_factor, use_adjaceny_graph=False): """Given the sparse representation of each training example, learn perturbation laterals. See train_image for parameters and returns. """ if use_adjaceny_graph: graph = make_adjacency_graph(frcs, bu_msg) graph = ...
68333bca0fc3231470268ece6478b372767a6648
3,656,661
def get_info(ingest_ldd_src_dir): """Get LDD version and namespace id.""" # look in src directory for ingest LDD ingest_ldd = find_primary_ingest_ldd(ingest_ldd_src_dir) # get ingest ldd version tree = ETree.parse(ingest_ldd[0]) root = tree.getroot() ldd_version = root.findall(f'.//{{{PDS_N...
92c4d6f8f18c4204d2a8483584b6f1409d9ee243
3,656,662
def generate_tfidf(corpus_df, dictionary): """Generates TFIDF matrix for the given corpus. Parameters ---------- corpus_df : pd.DataFrame The corpus dataframe. dictionary : gensim.corpora.dictionary.Dictionary Dictionary defining the vocabulary of the TFIDF. Returns -------...
6c5cd6b569010c69b446223a099cfd745d51ce6c
3,656,663
import os import logging import yaml def load_config_file(file_path, fallback_file_path): """Load YAML format configuration file :param file_path: The path to config file :type file_path: `str` :param fallback_file_path: The fallback path to config file :type fallback_file_path: `str` :return...
1c756b10892f1a6cffa78dd80852049061b7521d
3,656,664
from typing import Tuple from typing import Optional import torch def compute_mask_indices( shape: Tuple[int, int], padding_mask: Optional[torch.Tensor], mask_prob: float, mask_length: int, mask_type: str = "static", mask_other: float = 0.0, min_masks: int = 0, ...
8ecd84ca805112312d43bd8ba3f4c0aa3918800d
3,656,665
import matplotlib.pyplot as plt import numpy as np def _rankingmap_mpl(countrymasksnc, ranking, x, scenario=None, method='number', title='', label=''): """ countrymasksnc : nc.Dataset instance of countrymasks.nc ranking: Ranking instance method: "number" (default) or "value" """ if method not...
d0e7006d832408fcd77b8b0fe219a6e9faf478e5
3,656,666
from typing import Optional from typing import List from typing import Dict from typing import Any def fetch_data( property: Property, start_date: dt.date, *, end_date: Optional[dt.date] = None, dimensions: Optional[List[Dimension]] = None, ) -> List[Dict[str, Any]]: """Query Google Search Con...
cb871f6e269005db9a338c4bf75949b8ba9ea04a
3,656,667
import os def fileOpenDlg(tryFilePath="", tryFileName="", prompt=_translate("Select file to open"), allowed=None): """A simple dialogue allowing read access to the file system. :parameters: tryFilePath: string default file path on which to ...
932625c6779a5738c23ff340c448fb594d38c7ca
3,656,668
def inport(port_type, disconnected_value): """Marks this field as an inport""" assert port_type in port_types, \ "Got %r, expected one of %s" % (port_type, port_types) tag = "inport:%s:%s" % (port_type, disconnected_value) return tag
a9335d99b65a4944ef58f06b90f8978e7478ec13
3,656,669
def Align(samInHandle, fa, id, position, varId, refseq, altseq, mapq = 20): """ position is the left break point of the variants And the position should be 1-base for convenience. Because I use something like fa[id][position-1] to get bases from fa string """ if position < 1: raise Val...
aa7238f421472e1be24ce290ddd5c3b6f5e2cba4
3,656,670
def _empty_aggregate(*args: npt.ArrayLike, **kwargs) -> npt.ArrayLike: """Return unchaged array.""" return args[0]
c7f6ebc345517b10a3b65c5ac0f0bf060cdf7634
3,656,671
def kfpartial(fun, *args, **kwargs): """ Allows to create partial functions with arbitrary arguments/keywords """ return partial(keywords_first(fun), *args, **kwargs)
7f7dbbdf484e36c2734e47b448f081812cb8a326
3,656,672
def power_state_update(system_id, state): """Report to the region about a node's power state. :param system_id: The system ID for the node. :param state: Typically "on", "off", or "error". """ client = getRegionClient() return client( UpdateNodePowerState, system_id=system_id, ...
b05730fe9e45b3ee81adb7e8047b0b87e3bf7556
3,656,673
from typing import Any def build_post307_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: """Post redirected with 307, resulting in a 200 after redirect. See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code flow. ...
2c26cfed95a33fe700b83d7e1fa4eb93ef312721
3,656,674
def rm_ssp_storage(ssp_wrap, lus, del_unused_images=True): """Remove some number of LogicalUnits from a SharedStoragePool. The changes are flushed back to the REST server. :param ssp_wrap: SSP EntryWrapper representing the SharedStoragePool to modify. :param lus: Iterable of LU ElementWrappers or ...
0c61becd8f9e23ac269ef0546abb0857facd89de
3,656,675
def urp_detail_view(request, pk): """Renders the URP detail page """ urp = get_object_or_404(URP, pk=pk) ctx = { 'urp': urp, } # if user is logged in as a student, check if user has already applied if request.user.is_authenticated: if request.user.uapuser.is_student: ...
15e7e86cf2e47bccda52682bdf205e43d8a03f5f
3,656,676
import functools def squeeze_excite(input_name, squeeze_factor): """Returns a squeeze-excite block.""" ops = [] append = functools.partial(append_op, ops) append(op_name="se/pool0", op_type=OpType.AVG_POOL, input_kwargs={"window_shape": 0}, input_names=[input_name]) append(op_name...
907acc7f31db9ab4d70f976320fdd779b66b7160
3,656,677
def get_code_v2(fl = r'C:\Users\bogdan\code_seurat\WholeGenome_MERFISH\Coordinates_code_1000region.csv'): """ Given a .csv file with header this returns 2 dictionaries: tad_to_PR,PR_to_tad """ lst = [(ln[:-1].split(',')[0].replace('__','_'),['R'+R for R in ln[:-1].split(',')[3].split('--')]) for ln...
f5a9e1bbd1f404819a700ee43cff826333ce736c
3,656,678
from funcs.modeling_funcs import modeling_settings, generate_observation_ensemble def run_source_lsq(vars, vs_list=vs_list): """ Script used to run_source and return the output file. The function is called by AdaptiveLejaPCE. """ print('Read Parameters') parameters = pd.read_csv('../data/Param...
e43679a0808108560714e32def9399ce45a6bd8e
3,656,679
def finnegans_wake_unicode_chars(): """Data fixture that returns a string of all unicode characters in Finnegan's Wake.""" return '¤·àáãéìóôþŒŠŸˆ–—‘’‚“”‡…‹'
78205c9181545544a61ef1eab6c2f51d212dac13
3,656,680
from pathlib import Path import posixpath import os def get_upload(upload_key: UploadPath = Path(..., description="上传文件块位置")): """ 获取文件上传目录 :param upload_key: :return: """ root_path = posixpath.abspath(UPLOAD_PATH_DICT[upload_key]) def func(folder): path = security.safe_join(ro...
39d0d4055f2a9933b9578b74fb14d5fa637154f0
3,656,681
def kit(): # simpler version """Open communication with the dev-kit once for all tests.""" return usp.Devkit()
3001cbfeaf212e9a09e512c102eae6bffa263375
3,656,682
def givens_rotation(A): """Perform QR decomposition of matrix A using Givens rotation.""" (num_rows, num_cols) = np.shape(A) # Initialize orthogonal matrix Q and upper triangular matrix R. Q = np.identity(num_rows) R = np.copy(A) # Iterate over lower triangular matrix. (rows, cols) = np.tr...
207cadc90c7c4aab76c7422d314b5470ce17251a
3,656,683
from typing import Union from pathlib import Path from typing import Optional import json def lex_from_str( *, in_str: Union[str, Path], grammar: str = "standard", ir_file: Optional[Union[str, Path]] = None, ) -> JSONDict: """Run grammar of choice on input string. Parameters ---------- ...
5416bd56426012c56050a0dba2835385fa4177e5
3,656,684
def e() -> ProcessBuilder: """ Euler's number (e) :return: The numerical value of Euler's number. """ return process('e', )
f984b5de5a0b95109c9ec2fe5a2b30c880226b28
3,656,685
def get_or_create_anonymous_cart_from_token(token, cart_queryset=Cart.objects.all()): """Returns open anonymous cart with given token or creates new. :type cart_queryset: saleor.cart.models.CartQueryset :type token: string :rtype: Cart """ return cart...
8ffb1f64b77c97b260502f1d4c689e3a4edc4f36
3,656,686
import os def outcar_parser(request): """A fixture that loads OUTCAR.""" try: name = request.param except AttributeError: # Test not parametrized name = 'OUTCAR' testdir = os.path.dirname(__file__) outcarfile = testdir + '/' + name outcar = Outcar(file_path=outcarfile)...
5fe8b1ddb7f55e233104cec9a5be94624bc77ce9
3,656,687
from typing import Any def accept_data(x: Any) -> Any: """Accept any types of data and return it as convenient type. Args: x: Any type of data. Returns: Any: Accepted data. """ if isinstance(x, str): return x elif isinstance(x, list): return x elif i...
9862995eafb7015fc446466e2dbb7774be39f54b
3,656,688
def custom_model_template(model_type: str, target: str, result0: str, result1: str) -> str: """Template for feature behaviour reason generated from DICE Returns: str: behaviour """ if model_type == 'classifier': tipo = 'category' elif model_type == 'regressor': tipo = 'con...
bbd43a462f6d9d65984dbd242c7fe8a5d2be5e39
3,656,689
def merge_dict_list(merged, x): """ merge x into merged recursively. x is either a dict or a list """ if type(x) is list: return merged + x for key in x.keys(): if key not in merged.keys(): merged[key] = x[key] elif x[key] is not None: merged[key...
00685be39a0b1447c81ecd8de777ebab38aa9bfe
3,656,690
def is_ref(variant, exclude_alleles=None): """Returns true if variant is a reference record. Variant protos can encode sites that aren't actually mutations in the sample. For example, the record ref='A', alt='.' indicates that there is no mutation present (i.e., alt is the missing value). Args: variant:...
2c762bbf070f375b546f0902e3567ca5542cc774
3,656,691
def gomc_sim_completed_properly(job, control_filename_str): """General check to see if the gomc simulation was completed properly.""" job_run_properly_bool = False output_log_file = "out_{}.dat".format(control_filename_str) if job.isfile(output_log_file): # with open(f"workspace/{job.id}/{output...
20635ba94b5176298216ad5807e6428a5fb957c2
3,656,692
from typing import Union from typing import Optional def rv_precision( wavelength: Union[Quantity, ndarray], flux: Union[Quantity, ndarray], mask: Optional[ndarray] = None, **kwargs, ) -> Quantity: """Calculate the theoretical RV precision achievable on a spectrum. Parameters ---------- ...
91d6a741d992bd915549becd371d29b6634b92ef
3,656,693
def changenonetoNone(s): """Convert str 'None' to Nonetype """ if s=='None': return None else: return s
9f6af1580d8b47d2a7852e433f7ba8bbd5c7044d
3,656,694
def quaternion_2_rotation_matrix(q): """ 四元数转化为旋转矩阵 :param q: :return: 旋转矩阵 """ rotation_matrix = np.array([[np.square(q[0]) + np.square(q[1]) - np.square(q[2]) - np.square(q[3]), 2 * (q[1] * q[2] - q[0] * q[3]), 2 * (q[1] * q[3] + q[0] * q[2])], ...
f2e420a1e0b6838fb2ce5f9288842e1ae39134c9
3,656,695
def sum(mat, axis, target=None): """ Sum the matrix along the given dimension, where 0 represents the leading dimension and 1 represents the non-leading dimension. If a target is not prvided, a new vector is created for storing the result. """ m = _eigenmat.get_leading_dimension(mat.p_mat) n = _eigenmat....
426ba7b2673a52663e04d3c6f07fb2f4e001244b
3,656,696
from datetime import datetime def convert_created_time_to_datetime(datestring): """ Args: datestring (str): a string object either as a date or a unix timestamp Returns: a pandas datetime object """ if len(datestring) == 30: return pd.to_datetime(datestring) el...
2559d079b5b7174d192e3a5d9178701ae7080d3b
3,656,697
def identify_word_classes(tokens, word_classes): """ Match word classes to the token list :param list tokens: List of tokens :param dict word_classes: Dictionary of word lists to find and tag with the respective dictionary key :return: Matched word classes :rtype: list """ if w...
ca7aa602d19ac196321af19c42a60df415c7d115
3,656,698
from typing import List from typing import Tuple def find_connecting_stops(routes) -> List[Tuple[Stop, List[Route]]]: """ Find all stops that connect more than one route. Return [Stop, [Route]] """ stops = {} for route in sorted(routes, key=Route.name): for stop in route.stops(): ...
599e9e5d3fc0a6d0de84a58f1549da9423f35af3
3,656,699