content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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 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
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
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
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 _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
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
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
def freeze_loop(src, start, end, loopStart, loopEnd=None): """ Freezes a range of frames form start to end using the frames comprended between loopStart and loopEnd. If no end frames are provided for the range or the loop, start frames will be used instead. """ core = vs.get_core() if loopE...
67284a264ada601dbd01c30c1bf32f48ad9eb9d8
3,656,700
def timevalue(cflo, prate, base_date=0, utility=None): """ Computes the equivalent net value of a generic cashflow at time `base_date` using the periodic interest rate `prate`. If `base_date` is 0, `timevalue` computes the net present value of the cashflow. If `base_date` is the index of the last e...
704f6988d1995a8602314df08d1dcfbed549f1ed
3,656,701
def munge(examples, multiplier, prob, loc_var, data_t, seed=0): """ Generates a dataset from the original one :param examples: Training examples :type examples: 2d numpy array :param multiplier: size multiplier :type multiplier: int k :param prob: probability of swapping values :type prob: ...
339d5cafedb8abd6094cde81004c5056a3830d26
3,656,702
def is_interested_source_code_file(afile): """ If a file is the source code file that we are interested. """ tokens = afile.split(".") if len(tokens) > 1 and tokens[-1] in ("c", "cpp", "pl", "tmpl", "py", "s", "S"): # we care about C/C++/perl/template/python/assembly source code files ...
9bd77dc3b530262cc2bf8a32c0d050ea30077030
3,656,703
def recursively_extract(node, exfun, maxdepth=2): """ Transform a html ul/ol tree into a python list tree. Converts a html node containing ordered and unordered lists and list items into an object of lists with tree-like structure. Leaves are retrieved by applying `exfun` function to the html nodes...
cc5732a786579172dda31958ad2bd468a4feef81
3,656,705
import math def group_v2_deconv_decoder(latent_tensor, output_shape, hy_ncut=1, group_feats_size=gin.REQUIRED, lie_alg_init_scale=gin.REQUIRED, lie_alg_init_type=gin.REQUIRED, ...
c098852a7d3e85be944494de74810e021d7fd106
3,656,706
def UncertaintyLossNet(): """Creates Uncertainty weighted loss model https://arxiv.org/abs/1705.07115 """ l1 = layers.Input(shape=()) l2 = layers.Input(shape=()) loss = UncertaintyWeightedLoss()([l1, l2]) model = Model(inputs=[l1, l2], outputs=loss) return model
5a6553edc321a6e307848e261692541cedea4ebb
3,656,708
from typing import Iterable import logging from pathlib import Path def inject_signals( frame_files: Iterable[str], channels: [str], ifos: [str], prior_file: str, n_samples: int, outdir: str, fmin: float = 20, waveform_duration: float = 8, snr_range: Iterable[float] = [25, 50], ): ...
204aca5dee78e885191907890fc064503ff61f57
3,656,709
async def lyric(id: int, endpoint: NeteaseEndpoint = Depends(requestClient)): """ ## Name: `lyric` > 歌词 --- ### Required: - ***int*** **`id`** - Description: 单曲ID """ return await endpoint.lyric(id=id)
331c0bced7bbd2523426522286a85f3cc6a3a29f
3,656,710
def get_body(m): """extract the plain text body. return the body""" if m.is_multipart(): body = m.get_body(preferencelist=('plain',)).get_payload(decode=True) else: body = m.get_payload(decode=True) if isinstance(body, bytes): return body.decode() else: return body
7980c1471a0a09c793cb8124066a97caac21ae0d
3,656,711
def density(mass, volume): """ Calculate density. """ return mass / volume * 1
53b1f76ba66695a9cd72be9186bcc374ee11f53b
3,656,713
from typing import Union from typing import Callable import torch def get_augmenter(augmenter_type: str, image_size: ImageSizeType, dataset_mean: DatasetStatType, dataset_std: DatasetStatType, padding: PaddingInputType = 1. / 8., ...
7b065d9bd7c9bc2cf3c0aa2fdf105c714df24705
3,656,715
def query(limit=None, username=None, ids=None, user=None): """# Retrieve Workspaces Receive a generator of Workspace objects previously created in the Stark Bank API. If no filters are passed and the user is an Organization, all of the Organization Workspaces will be retrieved. ## Parameters (option...
bc22336c7c76d549144e43b6d6c46793b1feedf9
3,656,716
def _add_output_tensor_nodes(net, preprocess_tensors, output_collection_name='inferece_op'): """ Adds output nodes for all preprocess_tensors. :param preprocess_tensors: a dictionary containing the all predictions; :param output_collection_name: Name of collection to add output tensors to. :return: ...
cdbb2b69a795bcc74925cce138e9d73bc4737276
3,656,717
def f_prob(times, lats, lons, members): """Probabilistic forecast containing also a member dimension.""" data = np.random.rand(len(members), len(times), len(lats), len(lons)) return xr.DataArray( data, coords=[members, times, lats, lons], dims=["member", "time", "lat", "lon"], ...
43fe73abb5667b0d29f36a4ee73e8d8ec1943ad0
3,656,718
def dunning_total_by_corpus(m_corpus, f_corpus): """ Goes through two corpora, e.g. corpus of male authors and corpus of female authors runs dunning_individual on all words that are in BOTH corpora returns sorted dictionary of words and their dunning scores shows top 10 and lowest 10 words :par...
324b0bb5e5f83451ca47cefed908cdd6dbc47c33
3,656,719
from typing import Optional from typing import Callable def get_int(prompt: Optional[str] = None, min_value: Optional[int] = None, max_value: Optional[int] = None, condition: Optional[Callable[[int], bool]] = None, default: Optional[int] = None) -> int: """Gets an i...
c6ea07b495330c74bd36523cf12dd3e208926ea5
3,656,723
def make_stream_callback(observer, raw, frame_size, start, stop): """ Builds a callback function for stream plying. The observer is an object which implements methods 'observer.set_playing_region(b,e)' and 'observer.set_playing_end(e)'. raw is the wave data in a str object. frame_size is the number of by...
c29f7998f848c51af57e42c92a62f80c7a0c2e70
3,656,724
import torch def predictCNN(segments, artifacts, device:torch.device = torch.device("cpu")): """ Perform model predictions on unseen data :param segments: list of segments (paragraphs) :param artifacts: run artifacts to evaluate :param device: torch device :return category predictions """ ...
27ebdccaecd675104c670c1839daf634c142c640
3,656,725
import re def transform_url(url): """Normalizes url to '[email protected]:{username}/{repo}' and also returns username and repository's name.""" username, repo = re.search(r'[/:](?P<username>[A-Za-z0-9-]+)/(?P<repo>[^/]*)', url).groups() if url.startswith('git@'): return url, username, repo r...
8d6e7d903d7c68d2f4fb3927bd7a02128cc09caf
3,656,726
from typing import Optional def prettyprint(data: dict, command: str, modifier: Optional[str] = '') -> str: """ Prettyprint the JSON data we get back from the API """ output = '' # A few commands need a little special treatment if command == 'job': command = 'jobs' if 'data' in ...
727a59b22b2624fec56e685cc3b84f065bbfeffd
3,656,727
def kmor(X: np.array, k: int, y: float = 3, nc0: float = 0.1, max_iteration: int = 100, gamma: float = 10 ** -6): """K-means clustering with outlier removal Parameters ---------- X Your data. k Number of clusters. y Parameter for outlier detection. Increase this to make ...
5ffa55d45d615586971b1ec502981f1a7ab27cbe
3,656,728
def turnout_div(turnout_main, servo, gpo_provider): """Create a turnout set to the diverging route""" turnout_main.set_route(True) # Check that the route was set to the diverging route assert(servo.get_angle() == ANGLE_DIV) assert(gpo_provider.is_enabled()) return turnout_main
542a747cc7f4cdc78b7ad046b0c4ce4a0a3cd33d
3,656,730
def num_jewels(J: str, S: str) -> int: """ Time complexity: O(n + m) Space complexity: O(n) """ jewels = set(J) return sum(stone in jewels for stone in S)
f1a9632a791e3ef94699b566da61e27d9dc46b07
3,656,731
import socket def internet(host="8.8.8.8", port=53, timeout=3): """ Host: 8.8.8.8 (google-public-dns-a.google.com) OpenPort: 53/tcp Service: domain (DNS/TCP) """ try: socket.setdefaulttimeout(timeout) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) logger.info(...
773f490baec40bf548ed2f13d1d1094c78b33366
3,656,732
import logging def map_family_situation(code): """Maps French family situation""" status = FamilySituation mapping = { "M": status.MARRIED.value, "C": status.SINGLE.value, "V": status.WIDOWED.value, "D": status.DIVORCED.value, "O": status.PACSED.value, } if ...
ae5ac0c9ffadb31d25825e65fcb81d6ea9b0115f
3,656,733
def transform(x, channels, img_shape, kernel_size=7, threshold=1e-4): """ ---------- X : WRITEME data with axis [b, 0, 1, c] """ for i in channels: assert isinstance(i, int) assert i >= 0 and i <= x.shape[3] x[:, :, :, i] = lecun_lcn(x[:, :, :, i], ...
c66725795585ea26dc9622ce42133a4a2f1445a8
3,656,734
import functools def delete_files(files=[]): """This decorator deletes files before and after a function. This is very useful for installation procedures. """ def my_decorator(func): @functools.wraps(func) def function_that_runs_func(self, *args, **kwargs): # Inside the de...
09652e9dd527b6ae43cf47deb2eaf460de51552e
3,656,735
def add_note(front, back, tag, model, deck, note_id=None): """ Add note with `front` and `back` to `deck` using `model`. If `deck` doesn't exist, it is created. If `model` doesn't exist, nothing is done. If `note_id` is passed, it is used as the note_id """ model = mw.col.models.byName(model...
e45528705dbd658dcb708259043f4a4b590e884b
3,656,737
def indices_to_one_hot(data, nb_classes): #separate: embedding """Convert an iterable of indices to one-hot encoded labels.""" targets = np.array(data).reshape(-1) return np.eye(nb_classes)[targets]
36fdf0dbad51ae6d64c1a6bf783f083013686e40
3,656,738
from rdkit.Chem import rdMolTransforms def translateToceroZcoord(moleculeRDkit): """ Translate the molecule to put the first atom in the origin of the coordinates Parameters ---------- moleculeRDkit : RDkit molecule An RDkit molecule Returns ------- List List with the...
cbe17cf023791517c01b0e52c11dde65532ab6d0
3,656,739
def standardize(mri): """ Standardize mean and standard deviation of each channel and z_dimension slice to mean 0 and standard deviation 1. Note: setting the type of the input mri to np.float16 beforehand causes issues, set it afterwards. Args: mri (np.array): input mri, shape (dim_x, dim...
9c0847d1618023d83cdec48a1c43aae6efc1116f
3,656,740
def current_floquet_kets(eigensystem, time): """ Get the Floquet basis kets at a given time. These are the |psi_j(t)> = exp(-i energy[j] t) |phi_j(t)>, using the notation in Marcel's thesis, equation (1.13). """ weights = np.exp(time * eigensystem.abstract_ket_coefficients) weights = we...
60fdb845fc026bf3a109f05945b251a224b12092
3,656,741
def summary(): """ DB summary stats """ cur = get_cur() res = [] try: cur.execute('select count(study_id) as num_studies from study') res = cur.fetchone() except: dbh.rollback() finally: cur.close() if res: return Summary(num_studies=res['num_studies...
e0159452df1909626d523896f1c2735fb4fc3e75
3,656,742
def rotate_affine(img, rot=None): """Rewrite the affine of a spatial image.""" if rot is None: return img img = nb.as_closest_canonical(img) affine = np.eye(4) affine[:3] = rot @ img.affine[:3] return img.__class__(img.dataobj, affine, img.header)
4a06c286dcfc0832558c74f2cbce54d6e8d7a2d4
3,656,744
import math def validate_ttl(options): """ Check with Vault if the ttl is valid. :param options: Lemur option dictionary :return: 1. Boolean if the ttl is valid or not. 2. the ttl in hours. """ if 'validity_end' in options and 'validity_start' in options: ttl = math.floor(...
83d7d323ae4b3db28f41879f630982d24515fcb1
3,656,745