content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime 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 h...
14e4200c2277e48792fd4d02f0126293a82a9ba8
16,200
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]...
e1b57204e6fd9fe2839e4fb2e7230dd0f8854841
16,201
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) ...
f2f742cc1e969b4b60394148508cbb9cacaa3cfc
16,202
import math 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...
e242823df263f1cee28409ef3f984f9b3066dad5
16,203
import torch 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 laye...
2e24af14d05802bac69b65a225ce284b5a7785e7
16,204
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...
f2c09fac89e0b0c9f9894869bb559ce61bca942a
16,205
import subprocess 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]: ...
63a903a7a7a7f99c2d6bcd36329a07845dd327d5
16,206
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
e3b2c1c613f5ae2f20b2b9a8e6e343348be845df
16,207
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 ...
ee293672d74de5f0e1de0ff25c806fa10327c71c
16,208
import pytz def timezone_by_tzvar(tzvar): """Convert a WWTS tzvar to a tzdata timezone""" return pytz.timezone(city_by_tzvar(tzvar))
0bc4d634ca5fcc55ceed062ae06fbe2eefb6c11a
16,209
import json 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...
1821eba9f2144ac5e9b6b9a4c5c8d935b3dd5e08
16,210
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...
b2968f6ff3cde324711f84a5b449fbab92cc22fa
16,211
import six 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 fiel...
2946a8869cac26737f6c5b6234ce0320cfdf5bcf
16,212
def get_session_maker(): """ Return an sqlalchemy sessionmaker object using an engine from get_engine(). """ return sessionmaker(bind=get_engine())
2f1a500cf799910f98e7821582cb78d063eeb273
16,213
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...
580c789a6eb2ad03bcbdefd8e5f27b0c6a239f32
16,214
import traceback import sys def get_error_info(): """Return info about last error.""" msg = "{0}\n{1}".format(str(traceback.format_exc()), str(sys.exc_info())) return msg
539a26f0a6bd6b733aa6e6ff1325faac6a32be12
16,215
import requests 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 : st...
e69ec11f75676a94134f4541b421391367ab1e3c
16,216
import yaml 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("/...
6a2575af4fe54caed7ce812d3fc2a876424912f7
16,217
import os 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_...
e26252740c2c64b581d4be56e25086216bc36e1b
16,218
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...
1aea3915680b3c74422cbd7648fd920719dd3cc8
16,219
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...
db97dfb88d4fa253351e149dacf68a9fa3043072
16,220
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(...
3c18bbe6b4b6a0562719d4992d6937d60f6bc114
16,221
from typing import Tuple import os 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 ...
292497e6228e858e98b69350fb6507a0346efd16
16,222
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...
fbe1e89282ebdf7b4977bee295e2cac7735bd652
16,223
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...
7bebd68d76aa51c5965f5850731c47b220871a0b
16,224
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...
16cc188b367200c317119348d9440d57faa322a9
16,225
def is_any(typeref: irast.TypeRef) -> bool: """Return True if *typeref* describes the ``anytype`` generic type.""" return isinstance(typeref, irast.AnyTypeRef)
75ca055529fea35dfeb2519c3de61bf3739ce1f7
16,226
from typing import Union 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 wit...
44a8bb29dcd2ba0e2e5970aff1eab94b85a34c13
16,227
import logging 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.Formatt...
a0c005c39af9d24d7198790cf0cfe31a1b6395a0
16,228
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...
f2c0dd14e9193b9fa3ae3ea87689e90d9eb2c1bc
16,229
import re 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 ...
48b421d965e9b7f337a1f58c3665643eba514a7c
16,230
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)
ad7737321d9f0fc8461129b0153f40da2d75dc70
16,231
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...
39c60bf6a9fbf18f4d5ba3af609fed53771bd817
16,232
import os 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
7589e8c5f2a42013cb391cf2d10ad3a9f9cb46ed
16,233
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 ...
512def08ef2fe35cdd80ba7eb92f30b73aef1782
16,234
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...
07cf792fb3bd0ed5a1185986fb3154cb645b2a75
16,235
def check_integer_sign(value): """ :param value: :return: """ return value >= 0
0ab012b62bf7b12ecabea8d1a4538bb30e197e07
16,236
import torch 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)
4c13b123fe6f5a17c3cd2ee673c54de331af7b23
16,237
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...
1b51b84e9f22a1b0e0c2bb578a2011c1b8f725e2
16,238
import os 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, '...
65fa856c2561cf54a4cc10dbf380f3c2fc5b97d3
16,239
def listSplit(aList, n): """将一个列表以n个元素为一个单元进行均分,返回嵌套列表""" return [aList[i:i+n] for i in range(0,len(aList),n)]
936d4ff5b3bbbc39c57c01dc6a12e42b7dc6e0de
16,240
import json 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.appen...
7635525efbdab8e22c21019f8de9cc74a83c9c2a
16,241
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
b717c6f42c8f0ae0c68c97647a33e77aec2f1508
16,242
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)
9258dac1261e24d3cc5e58030147ce693fbd0356
16,243
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 ...
99c1c3fd35db4bb22c2c37aba48ddb7049ec26fa
16,244
from typing import Dict 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
9e3f72568cf25ac864c1add2989c8e1cb064661d
16,245
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 ...
2e3c6ec6a312016785affbc71c5c2f178a0ecd84
16,246
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}'
e3f86a7e7f276ceff4eb662a3f5bc364b4d10ea3
16,247
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); ...
0c08541fd5c551c5a2ca1afb598adfc627c06286
16,248
import logging 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:...
f4b3a04b18735320968513666ad5901a68e5a492
16,249
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...
29aeb5af69257a9c762bccc45c09e68d0799174c
16,250
import argparse def setup_argparse(parser: argparse.ArgumentParser) -> None: """Setup argument parser for ``cubi-tk org-raw check``.""" return OrganizeCommand.setup_argparse(parser)
fefbb3fd16905f353f9d6f98c3631024ca3e4e78
16,251
from typing import List import random 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 p...
4e8dd96fc42a8a1a1feb7c1c3dad42892e060425
16,252
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...
c80e34443c4e39a96496eca5867333800b0208c5
16,253
from typing import Dict from typing import Any from typing import Tuple from typing import Optional import re 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...
74a80fb69fdebb35c86830f54344fc770ad91cd4
16,254
import tempfile 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) ...
3e7419185ab3c3581ea24227c204fd207b113b1e
16,255
def get_active_users(URM, popular_threshold=100): """ Get the users with activity above a certain threshold :param URM: URM on which users will be extracted :param popular_threshold: popularty threshold :return: """ return _get_popular(URM, popular_threshold, axis=1)
6b05e1a4288e00903ce9b396407c4e3547402710
16,256
def default_data_to_device( input, target=None, device: str = "cuda", non_blocking: bool = True ): """Sends data output from a PyTorch Dataloader to the device.""" input = input.to(device=device, non_blocking=non_blocking) if target is not None: target = target.to(device=device, non_blocking=n...
8dafddbd52b54a576ddc67d7d79af4372fbd57dc
16,257
def _get_diff2_data(request, ps_left_id, ps_right_id, patch_id, context, column_width, tab_spaces, patch_filename=None): """Helper function that returns objects for diff2 views""" ps_left = models.PatchSet.get_by_id(int(ps_left_id), parent=request.issue.key) if ps_left is None: return Http...
47aef66544acec7d57125f3c7c0f8edb385ba150
16,258
def vec_add(iter_a, iter_b): """element wise addition""" if len(iter_a) != len(iter_b): raise ValueError return (a + b for a, b in zip(iter_a, iter_b))
f3e5bf50d61cfe518ee8b0eb838503a7f054baa8
16,259
def run(): """ Read inputs into a dictionary for recursive searching """ for line in inputs: # Strip the trailing "." and split container, rest = line[:-1].split(" contain ") # Strip the trailing " bags" container = container[:-5] contained = [] for bag in rest.sp...
c3b565efbb923562c13955d808cf6ac2f09b616b
16,260
def _get_prolongation_coordinates(grid, d1, d2): """Calculate required coordinates of finer grid for prolongation.""" D2, D1 = np.broadcast_arrays( getattr(grid, 'vectorN'+d2), getattr(grid, 'vectorN'+d1)[:, None]) return np.r_[D1.ravel('F'), D2.ravel('F')].reshape(-1, 2, order='F')
6534c456413cd062f9c35c14f5d9b57b1aba6c12
16,261
import os from functools import cmp_to_key def get_sorted_filediffs(filediffs, key=None): """Sorts a list of filediffs. The list of filediffs will be sorted first by their base paths in ascending order. Within a base path, they'll be sorted by base name (minus the extension) in ascending order. ...
dfd7fe9436bc59f5949dca838f82af01d14bfe83
16,262
def get_info(obj): """ get info from account obj :type obj: account object :param obj: the object of account :return: dict of account info """ if obj: return dict(db_instance_id=obj.dbinstance_id, account_name=obj.account_name, account_status=o...
c654ab1bdb4b4bf20223172dae450e1e7e6a52b9
16,263
def vlookup(x0, vals, ind, approx=True): """ Equivalent to the spreadsheet VLOOKUP function :param vals: array_like 2d array of values - first column is searched for index :param x0: :param ind: :param approx: :return: """ if isinstance(vals[0][0], str): x0 = str(x0)...
59ee6ecd7c001bf6cf3f03ad678d93eda33f5e21
16,264
def matmul(a00, a10, a01, a11, b00, b10, b01, b11): """ Compute 2x2 matrix mutiplication in vector way C = A*B C = [a00 a01] * [b00 b01] = [c00 c01] [a10 a11] [b10 b11] [c10 c11] """ c00 = a00*b00 + a01*b10 c10 = a10*b00 + a11*b10 c01 = a00*b01 + a01*...
d34506cc8099cbbf8b7a9e1eb9d4d068d768ebac
16,265
import collections import random def random_sample_with_weight_and_cost(population, weights, costs, cost_limit): """ Like random_sample_with_weight but with the addition of a cost and limit. While performing random samples (with priority for higher weight) we'll keep track of cost If cost exceeds the ...
637afd1c0e83bbda879f41bd15feb0f65b238fb3
16,266
def hardnet68ds(pretrained=False, **kwargs): """ # This docstring shows up in hub.help() Harmonic DenseNet 68ds (Depthwise Separable) model pretrained (bool): kwargs, load pretrained weights into the model """ # Call the model, load pretrained weights model = hardnet.HarDNet(depth_wise=True, arc...
5167b79f8effdb9a4b94e9d0a7902f35468a1d8b
16,267
def get_config(): """Base config for training models.""" config = ml_collections.ConfigDict() # How often to save the model checkpoint. config.save_checkpoints_steps: int = 1000 # Frequency fo eval during training, e.g. every 1000 steps. config.eval_frequency: int = 1000 # Total batch size for training....
67dfe8aff3f1a3e660d9debccc181690ea561ae2
16,268
def slave_addresses(dns): """List of slave IP addresses @returns: str Comma delimited list of slave IP addresses """ return ', '.join(['{}:53'.format(s['address']) for s in dns.pool_config])
e293442272496f02a58055dd778ecfe875124ccd
16,269
def processAndLabelStates(role, states, reason, positiveStates=None, negativeStates=None, positiveStateLabelDict={}, negativeStateLabelDict={}): """Processes the states for an object and returns the appropriate state labels for both positive and negative states. @param role: The role of the object to process states f...
23be0c7d943961f756a02abea98c51500f92b00f
16,270
def shape_for_stateful_rnn(data, batch_size, seq_length, seq_step): """ Reformat our data vector into input and target sequences to feed into our RNN. Tricky with stateful RNNs. """ # Our target sequences are simply one timestep ahead of our input sequences. # e.g. with an input vector "wherefor...
431eb54acc9bfe2281a3a863335eb135f050f47e
16,271
import time import tqdm def setup_features(dataRaw, label='flux', notFeatures=[], pipeline=None, verbose=False, resample=False, returnAll=None): """Example function with types documented in the docstring. For production level usage: All scaling and transformations must be done with resp...
7c1fb86dc66d97610bd1d22ef65ccb88e105dd92
16,272
from typing import List from typing import Any def plot_marginal_effects(model: ModelBridge, metric: str) -> AxPlotConfig: """ Calculates and plots the marginal effects -- the effect of changing one factor away from the randomized distribution of the experiment and fixing it at a particular level. ...
f68c72d54e4e8ff1011ae6daec8a00ab30069d78
16,273
def _client_row_class(client: dict) -> str: """ Set the row class depending on what's in the client record. """ required_cols = ['trust_balance', 'refresh_trigger'] for col in required_cols: if col not in client: return 'dark' try: if client['trust_balance'] > clien...
cd5ebd8fd64c7d994d6803df473cd317af65e9ac
16,274
def num2ord(place): """Return ordinal for the given place.""" omap = { u'1' : u'st', u'2' : u'nd', u'3' : u'rd', u'11' : u'th', u'12' : u'th', u'13' : u'th' } if place in omap: return place + omap[place] elif place.isdigit(): ...
3552257bba134ac00ed8c68d72bf5c947424b2e7
16,275
from typing import Type def _get_dist_class( policy: Policy, config: AlgorithmConfigDict, action_space: gym.spaces.Space ) -> Type[TFActionDistribution]: """Helper function to return a dist class based on config and action space. Args: policy: The policy for which to return the action ...
08c09b876d5c2797d517a87957049c34939aee3a
16,276
def expectation_values(times, states, operator): """expectation values of operator at times wrt states""" def exp_value(state, operator, time): if len(state.shape) == 2: #DensityMatrix return np.trace(np.dot(state, operator(time))) else: #Stat...
4c18fa3b2ad7bec01f8f833ade59fe90315724ec
16,277
def compute_f_all(F1,fft_size,windowing,dtype_complex,F_frac=[],F_fs=[],F_refs=[],freq_channel=0,\ F_first_sample=[],F_rates=[],F_pcal_fix=[],F_side=[],F_ind=[],F_lti=[]): """ Compute FFTs for all stations (all-baselines-per-task mode), and correct for fractional sample correction (linear ...
d9a4838347e498472228992dc77d08d44ed01c6e
16,278
import http def bookmark(request): """ Add or remove a bookmark based on POST data. """ if request.method == 'POST': # getting handler model_name = request.POST.get('model', u'') model = django_apps.get_model(*model_name.split('.')) if model is None: # inva...
32743894345e170d6d0efc427f3be0fb8d24b044
16,279
def start_nodenetrunner(nodenet_uid): """Starts a thread that regularly advances the given nodenet by one step.""" nodenets[nodenet_uid].is_active = True if runner['runner'].paused: runner['runner'].resume() return True
7511f217beb64936d403a5f5472036206f446c90
16,280
def transform_coordinates_3d(coordinates, RT): """ Input: coordinates: [3, N] RT: [4, 4] Return new_coordinates: [3, N] """ if coordinates.shape[0] != 3 and coordinates.shape[1]==3: coordinates = coordinates.transpose() coordinates = np.vstack([coordinates, np.on...
8a31f97bddd1c84a21d4b396e877c2b327e6890b
16,281
def _get_misclass_auroc(preds, targets, criterion, topk=1, expected_data_uncertainty_array=None): """ Get AUROC for Misclassification detection :param preds: Prediction probabilities as numpy array :param targets: Targets as numpy array :param criterion: Criterion to use for scoring on misclassifica...
282ef66926092e99a62003152daccf733913b6c2
16,282
from typing import Iterable from typing import List def flatten(l: Iterable) -> List: """Return a list of all non-list items in l :param l: list to be flattened :return: """ rval = [] for e in l: if not isinstance(e, str) and isinstance(e, Iterable): if len(list(e)): ...
2d2202c21e6da7064491d55d5519c259d10f42c0
16,283
def create_note(dataset_id, fhir_store_id, note_id): # noqa: E501 """Create a note Create a note # noqa: E501 :param dataset_id: The ID of the dataset :type dataset_id: str :param fhir_store_id: The ID of the FHIR store :type fhir_store_id: str :param note_id: The ID of the note that is b...
396f81b4a6035a9f295faebdd1aa313131d0da2b
16,284
def load_credential_from_args(args): """load credential from command Args: args(str): str join `,` Returns: list of credential content """ if ',' not in args: raise file_path_list = args.split(',') if len(file_path_list) != 2: raise if not file_path_list...
4f2e0b1e57ee3baaeb1bab3dc0e7e3874aaeec7c
16,285
def encode(string: str, key: str) -> str: """ Encode string using the Caesar cipher with the given key :param string: string to be encoded :param key: letter to be used as given shift :return: encoded string :raises: ValueError if key len is invalid """ if len(key) > 1: raise Val...
ddba41c5efc01df06290cd6496ef8eb54dbb28be
16,286
def compile_binary(binary, compiler, override_operator=None, **kw): """ If there are more than 10 elements in the `IN` set, inline them to avoid hitting the limit of \ the number of query arguments in Postgres (1<<15). """ # noqa: D200 operator = override_operator or binary.operator if operato...
1798ded35c12d6a3bf2e5edc34dcf11ff70ce697
16,287
from typing import Callable from typing import Iterable from typing import Iterator import itertools def flat_map( fn: Callable[[_T], Iterable[_S]], collection: Iterable[_T] ) -> Iterator[_S]: """Map a function over a collection and flatten the result by one-level""" return itertools.chain.from_iterable(m...
a1a09611f920078cb25a23279004acd00ac23142
16,288
def create_vector_clock(node_id, timeout): """This method builds the initial vector clock for a new key. Parameters ---------- node_id : int the id of one node in the cluster timeout : int the expire timeout of the key Returns ------- dict the vector clock as di...
ed6df0e7e493d448f52e5fe47b55df8a1de94543
16,289
def ParseStateFoldersFromFiles(state_files): """Returns list of StateFolder objects parsed from state_files. Args: state_files: list of absolute paths to state files. """ def CreateStateFolder(folderpath, parent_namespace): del parent_namespace # Unused by StateFolder. return state_lib.StateFolde...
c70421da1f193ca2dc86f12e7cffd84a1011af22
16,290
def spectral_norm(inputs, epsilon=1e-12, singular_value="left"): """Performs Spectral Normalization on a weight tensor. Details of why this is helpful for GAN's can be found in "Spectral Normalization for Generative Adversarial Networks", Miyato T. et al., 2018. [https://arxiv.org/abs/1802.05957]. Args: ...
eb6961e984fbb8eb5c3d807faa7fa6d016c011b5
16,291
def rs_for_staff(user_id): """Returns simple JSON for research studies in staff user's domain --- tags: - User - ResearchStudy operationId: research_studies_for_staff parameters: - name: user_id in: path description: TrueNTH user ID, typically subject or staff ...
9d36a02cc4909e336730fb27b3bcfe284bcd5d82
16,292
from typing import Mapping from typing import Any import tqdm def from_hetionet_json( hetionet_dict: Mapping[str, Any], use_tqdm: bool = True, ) -> BELGraph: """Convert a Hetionet dictionary to a BEL graph.""" graph = BELGraph( # FIXME what metadata is appropriate? name='Hetionet', ve...
34db6048369945964c61aa4297164458f576a786
16,293
import re import click def validate_memory(_ctx, _param, value): """Validate memory string.""" if value is None: return None if not re.search(r'\d+[KkMmGg]$', value): raise click.BadParameter('Memory format: nnn[K|M|G].') return value
c050863a974c08ccc18fdaa2f03388c8f6674835
16,294
def BlockAvg3D( data , blocksize , mask ): """ 3-D version of block averaging. Mainly applicable to making superpixel averages of datfile traces. Not sure non-averaging calcs makes sense? mask is a currently built for a 2d boolean array of same size as (data[0], data[1]) where pixels to be averaged a...
4c0c9cb60c80f47289e7bff3e50ae3e39dd31c63
16,295
def build(buildconfig: BuildConfig, merge_train_and_test_data: bool = False): """Build regressor or classifier model and return it.""" estimator = buildconfig.algorithm.estimator() if merge_train_and_test_data: train_smiles, train_y = buildconfig.data.get_merged_sets() else: train_smile...
9a98f15ae9b966e42cda848169b38a651e727205
16,296
import databrowse.support.dummy_web_support as db_web_support_module import databrowse.support.handler_support as handler_support_module import os def GetXML(filename, output=OUTPUT_ELEMENT, **params): """ Get the XML representation of a file, as produced by the Databrowse library Arguments: filena...
369a14f950371711c032805b74b8b640f1b4af66
16,297
def stellar_radius(M, logg): """Calculate stellar radius given mass and logg""" if not isinstance(M, (int, float)): raise TypeError('Mass must be int or float. {} type given'.format(type(M))) if not isinstance(logg, (int, float)): raise TypeError('logg must be int or float. {} type given'.fo...
2afbd991c7461d7861370f18d90df840569da857
16,298
def set_plus_row(sets, row): """Update each set in list with values in row.""" for i in range(len(sets)): sets[i].add(row[i]) return sets
87f448dc3199c8d3137d5811dd184b3d2bd7cbe3
16,299