content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import yaml import re def yml_remove_releaseNote_record(file_path, current_server_version): """ locate and remove release notes from a yaml file. :param file_path: path of the file :param current_server_version: current server GA version :return: True if file was changed, otherwise False. """ ...
48a6f68642a094dd07a0daa13a78d11991a2aa5c
31,336
from typing import Union def calculate_z_score( data: Union[MultimodalData, UnimodalData, anndata.AnnData], n_bins: int = 50, ) -> np.array: """Calculate the standardized z scores of the count matrix. Parameters ----------- data: ``MultimodalData``, ``UnimodalData``, or ``anndata.AnnData`` ob...
df510bea5d475690ee234c1f92c6a9cb5bfab308
31,337
def encode(*args, **kwargs): """ A helper function to encode an element. @param args: The python data to be encoded. @kwarg encoding: AMF encoding type. One of L{ENCODING_TYPES}. @return: A L{util.BufferedByteStream} object that contains the data. """ encoding = kwargs.pop('encoding', DEFAU...
41fd8c725643826a9e74dfdd59607f5bc6eda5c3
31,338
from typing import Tuple def fenergy_symmetric_bar( work_ab: ArrayLike, work_bc: ArrayLike, uncertainty_method: str = "BAR", ) -> Tuple[float, float]: """BAR for symmetric periodic protocols. Args: work_ab: Measurements of work from first half of protocol. work_bc: Measurements of...
569f694cd9a2ea58ef929230e5eb4fc399229e57
31,339
def mod_arr_fit(ktp_dct, mess_path, fit_type='single', fit_method='dsarrfit', t_ref=1.0, a_conv_factor=1.0, inp_param_dct=None): """ Routine for a single reaction: (1) Grab high-pressure and pressure-dependent rate constants from a MESS output file (2)...
aacb366b2b826b8ffaaae620ee531ce7cb7e0339
31,341
from typing import Union from typing import Sequence from typing import List def _choose_image_ids(selected: Union[None, int, Sequence[int]], available: List[int]) -> List[int]: """Choose which image ids to load from disk.""" # Load all. if selected is None: return available # Load...
2f12c0f840ec4daede35ac3f65e745ad8681c19a
31,342
import mite as m2 import M2kinter as m2 def _open_file(name, mode): """ Opens a file in the specified mode. If the mite or M2kinter module is available the path given is not absolute, the writepath or datapath (depending on the specified mode) is searched first. """ if not name: raise ...
4aee4a2a54e5f9bd1ba72810b72deb50d0f69d54
31,343
def canonical_message_builder(content, fmt): """Builds the canonical message to be verified. Sorts the fields as a requirement from AWS Args: content (dict): Parsed body of the response fmt (list): List of the fields that need to go into the message Returns (str): canonical mes...
41a5e61cea00348c43675e373acb3cdcb311a762
31,344
import random def get_random_image(shape): """ Expects something like shape=(480,640,3) :param shape: tuple of shape for numpy array, for example from my_array.shape :type shape: tuple of ints :return random_image: :rtype: np.ndarray """ if random.random() < 0.5: r...
6ac0a627ce6f125b269584cb0694c6b26bb5e23d
31,345
import torch def evaluate(model, val_loader, device): """ model: CNN networks val_loader: a Dataloader object with validation data device: evaluate on cpu or gpu device return classification accuracy of the model on val dataset """ # evaluate the model model.eval() # context-manage...
f5b738117a2c73d666718acaeff83f8856294db9
31,346
def estimateInharmonicity(inputFile = '../../sounds/piano.wav', t1=0.1, t2=0.5, window='hamming', M=2048, N=2048, H=128, f0et=5.0, t=-90, minf0=130, maxf0=180, nH = 10): """ Function to estimate the extent of inharmonicity present in a sound Input: inputFile (string): wa...
f3d8d78b3e565b69e72f435b5afdef7a6f6a28fd
31,347
import attr def _get_default_secret(var, default): """ Get default or raise MissingSecretError. """ if isinstance(default, attr.Factory): return attr.NOTHING elif isinstance(default, Raise): raise MissingSecretError(var) return default
debece74ea410589a0330dac9aaf2e57796c2001
31,348
import copy def merge_similar_bounds(json_data: dict, file_names: list, bounds_list: list) -> dict: """Finds keys in a dictionary where there bounds are similar and merges them. Parameters ---------- json_data : dict Dictionary data from which the data informations were extracted from. fi...
314d6501e887d7a52d2aed054583188be992c1ed
31,349
import base64 def is_base64(s): """Return True if input string is base64, false otherwise.""" s = s.strip("'\"") try: if isinstance(s, str): sb_bytes = bytes(s, 'ascii') elif isinstance(s, bytes): sb_bytes = s else: raise ValueError("Argument mus...
6ce7bc4ddc79d5d50acce35f7995033ffb7d364a
31,350
def get_coco(opt, coco_path): """Get coco dataset.""" train_dataset = CenterMultiPoseDataset(opt, split = 'train') # custom dataset val_dataset = CenterMultiPoseDataset(opt, split = 'val') # custom dataset opt.val_interval = 10 return train_dataset, val_dataset
c78e07bff16053ce1c4c9a8246750f938159f3b6
31,351
def _get_output_columns(nodes, context): """Get the output columns for a list of SqlNodes. Args: nodes: List[SqlNode], the nodes to get output columns from. context: CompilationContext, global compilation state and metadata. Returns: List[Column], list of SqlAlchemy Columns to outp...
9c8c45311ca03892eaf4e82bbb592af6137eb0a6
31,352
from typing import final def notif(message): """ docstring """ #message= mess.text #print(message) #print(type(message)) query= str(message).split(',') #print(query) if(len(query)==2): #print(eval(query[1])) list_str= final.ajio_care.find_stock(eval(query[0]),eval(q...
5791165d8ac9fe582090de2f6a4831f2da3039ee
31,353
def float32(x): """Returns a 32-bit floating point representation of the input. Only defined for basic scalar types.""" return np.float32(x)
a63d595a1d9a1949183a8303b0258779082278c7
31,355
from pathlib import Path def collect_test_names(): """ " Finds all test names in `TEST_DATA_DIR` which have are valid, i.e. which have both a C file and associated gcc AST json """ test_data_dir_path = Path(TEST_DATA_DIR) c_files = test_data_dir_path.glob("*.c") ast_files = test_data_dir_p...
c34609264f460c66d8ea85a456901e0f1daca84f
31,356
def read_from_file(filename): """Read from a file located at `filename` and return the corresponding graph object.""" file = open(filename, "r") lines = file.readlines() file.close() # Check if it is a graph or digraph graph_or_digraph_str = lines[0].strip() if len(lines) > 0 else None if ...
86879facbef971541fabe95ef9430480931ef986
31,357
from quaternion.calculus import spline_definite_integral as sdi def inner_product(t, abar, b, axis=None, apply_conjugate=False): """Perform a time-domain complex inner product between two waveforms <a, b>. This is implemented using spline interpolation, calling quaternion.calculus.spline_definite_integra...
c675ee377a73e0858ad078bce47b5e41120b8d0b
31,358
from typing import List def build_datamodel(good_pbks: List[str], is_supply: bool) -> DataModel: """ Build a data model for supply and demand (i.e. for offered or requested goods). :param good_pbks: the list of good public keys :param is_supply: Boolean indicating whether it is a supply or demand dat...
35b450039e6401a80fc03c61e771eb433bfab693
31,359
def tryReduceOr(sig, val): """ Return sig and val reduced by | operator or None if it is not possible to statically reduce expression """ m = sig._dtype.all_mask() if not val.vldMask: return val if val._isFullVld(): v = val.val if v == m: return val ...
4be6cb3ebf3792859745ed474151e0b748f4d479
31,360
def get_mod_from_id(mod_id, mod_list): """ Returns the mod for given mod or None if it isn't found. Parameters ---------- mod_id : str The mod identifier to look for mod_list : list[DatRecord] List of mods to search in (or dat file) Returns ------- DatRecord or Non...
1fac309e4dfadea6da34946eb695f77cbbd61f92
31,361
def resize(image): """ Resize the image to the input shape used by the network model """ return cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA)
315b43be9fc33740466fb6671119fbc97a2c853a
31,362
def exp_f(name): """"Similar to E but trains to full 3001 epochs""" print("e82 but with seq length 2000 and 5 appliances and learning rate 0.01 and train and validation on all 5 houses") source = RealApplianceSource( filename='/data/dk3810/ukdale.h5', appliances=[ ['fridge freeze...
fceb234feb9848e6a2618e4f5433345265d1b839
31,363
def indices_2_one_hot(indices, n): """ Converts a list of indices into one hot codification :param indices: list of indices :param n: integer. Size of the vocabulary :return: numpy array with shape (len(indices), n) """ one_hot = np.zeros((len(indices), n), dtype=np.int8) for i in range...
c74864bf23cbd56dbc9de12f250570b9df9cdf8c
31,364
from typing import Set def extract_tables(query: str) -> Set[Table]: """ Helper function to extract tables referenced in a query. """ return ParsedQuery(query).tables
cb48448b09f9aac90a85ca2bd7011f32fcbe6e6f
31,365
def master_operation(matrix): """ Split the initial matrix into tasks and distribute them among slave operations """ workers = MPI.COMM_WORLD.Get_size() accumulator = [] task_queue = [] if not matrix[0][0]: task_queue.append([(0, 0)]) while True: sent_workers = [] ...
c936abd299cd0181138f4f4c87a5cf306be06c7a
31,366
def _weight_mean_color(graph, src, dst, n): """Callback to handle merging nodes by recomputing mean color. The method expects that the mean color of `dst` is already computed. Parameters ---------- graph : RAG The graph under consideration. src, dst : int The vertices in `graph...
13fe474363578f704dfe8e16be725628a6e3ca5f
31,367
def predict(model, pTestSet, pModelParams, pNoConvertBack): """ Function to predict test set Attributes: model -- model to use testSet -- testSet to be predicted conversion -- conversion function used when training the model """ #copy the test set, before invalidated rows and...
4d6aa09bc1223732d73ea7f37aed2ccc28e879b3
31,368
def poisson_log_likelihood(x, log_rate): """Compute the log likelihood under Poisson distribution. log poisson(k, r) = log(r^k * e^(-r) / k!) = k log(r) - r - log k! log poisson(k, r=exp(l)) = k * l - exp(l) - lgamma(k + 1) Args: x: binned spike count data. log_rate: The (log...
dc797090efceb4266a90e89125fb5a9acc5b2da7
31,369
import math def distance(point1, point2): """ Return the distance between two points.""" dx = point1[0] - point2[0] dy = point1[1] - point2[1] return math.sqrt(dx * dx + dy * dy)
7605d98e33989de91c49a5acf702609272cf5a68
31,370
import math def order_of_magnitude(value): """ Returns the order of magnitude of the most significant digit of the specified number. A value of zero signifies the ones digit, as would be the case in [Number]*10^[Order]. :param value: :return: """ x = abs(float(value)) offset = 0 ...
53a4b1be76199864fee69d4333049fb1f2371e46
31,372
def compute_discounted_R(R, discount_rate=1): """Returns discounted rewards Args: R (1-D array): a list of `reward` at each time step discount_rate (float): Will discount the future value by this rate Returns: discounted_r (1-D array): same shape as input `R` but the valu...
50a18277e749faa73c725217824091a71d00f991
31,373
def setup_dom_for_char(character, create_dompc=True, create_assets=True, region=None, srank=None, family=None, liege_domain=None, create_domain=True, create_liege=True, create_vassals=True, num_vassals=2): """ Creates both a PlayerOrNpc instan...
3c806c560e0691440bc7d7399467eecb563745f0
31,374
def cumulative_sum(t): """ Return a new list where the ith element is the sum of all elements up to that position in the list. Ex: [1, 2, 3] returns [1, 3, 6] """ res = [t[0]] for i in range(1, len(t)): res.append(res[-1] + t[i]) return res
14b2ef722f72e239d05737a7bb7b3a6b3e15305f
31,375
from typing import Tuple def update_documents_in_collection(resource) -> Tuple[Response, int]: """Endpoint for updating multiple documents.""" try: collection_name = services.check_resource_name(resource) request_args = request.args.copy() filters = ["_projection", "_sort", "_limit",...
743b7bf3c3d2be765da181b5fbceef3309f91b48
31,377
def generate_prior_data(Pi, a_prior, b_prior): """Return column data sources needed to generate prior distribution.""" # Prior probability distribution n = 1000 x = np.linspace(0, 1, n) dist = beta(a_prior, b_prior) p = dist.pdf(x) # Arrays for the area under the curve patch xs = np.hs...
1bce66203f0b3ad6ab74fb346a81ec15ff2b7d63
31,378
def InteractionFingerprintAtomic(ligand, protein, strict=True): """Interaction fingerprint accomplished by converting the molecular interaction of ligand-protein into bit array according to the residue of choice and the interaction. For every residue (One row = one residue) there are eight bits which re...
ecdfc34e5c6cb5c5ca3fcf008629b1d3face158c
31,379
from typing import Union def add_subject_conditions( data: pd.DataFrame, condition_list: Union[SubjectConditionDict, SubjectConditionDataFrame] ) -> pd.DataFrame: """Add subject conditions to dataframe. This function expects a dataframe with data from multiple subjects and information on which subject ...
7475af9b13685604678b4d566e9b2daa4f6f82ef
31,380
def chinese_remainder(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder(5,1,7,3) 31 penjelasan : 31 adalah nomor yang paling kecil ketika dibagi dengan 5 kita dapat hasil bagi 1 ketika dibagi dengan 7 kita dapat hasil bagi 3 """ (x, y) = extended_euclid(n1, n2) m...
e98882790c9c4bdd1e23f1d9b49d7a30ddaf7e81
31,381
from typing import Iterable def query_factorize_industry_df(factorize_arr, market=None): """ 使用match_industries_factorize可以查询到行业所对应的factorize序列, 使用factorize序列即组成需要查询的行业组合,返回行业组合pd.DataFrame对象 eg: 从美股所有行业中找到中国企业的行业 input:ABuIndustries.match_industries_factorize('中国', market=EMarketTargetType.E_...
7060336e59b54d87f061a6163367b22c056edb6a
31,383
import yaml def rbac_assign_roles(email, roles, tenant=None): """assign a list of roles to email""" tstr = " -tenant=%s " % (tenant) if tenant else "" roles = ",".join(roles) rc = run_command("%s user-role -op assign -user-email %s -roles %s %s" % ( g_araalictl_path, email, roles,...
27bc4835052fd3e6c5e2660ab47c12b49ff426ef
31,384
def haversine_np(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) Reference: https://stackoverflow.com/a/29546836/7657658 https://gist.github.com/mazzma12/6dbcc71ab3b579c08d66a968ff509901 """ lon1, la...
ace51c2e9e93a42270f669d4b8d48ce87ff660d6
31,385
import re def extract_current_step(current_status_string): """ Attempts to extract the current step numeric identifier from the given status string. Returns the step number or None if none. """ # Older format: `Step 12 :` # Newer format: `Step 4/13 :` step_increment = re.search(r"Step ([0-9]+)...
8bbee5b13140394e3e04021eccd43d2b4c3b4c14
31,387
import warnings def unique1d(ar1, return_index=False, return_inverse=False): """ Find the unique elements of an array. Parameters ---------- ar1 : array_like This array will be flattened if it is not already 1-D. return_index : bool, optional If True, also return the indices a...
8ac57d97079d60215dc96fd33d1f176129445662
31,388
def login_required(func): """ Decorator check required login and active user :param func: :return: """ @wraps(func) def decorated_view(*args, **kwargs): if current_app.login_manager._login_disabled: return func(*args, **kwargs) elif not current_user.is...
894d162a8fd50c0e4fba810c0f575865994ba00e
31,389
def prepare_statement(template, values): """Correctly escape things and keep as unicode. pyscopg2 has a default encoding of `latin-1`: https://github.com/psycopg/psycopg2/issues/331""" new_values = [] for value in values: adapted = adapt(value) adapted.encoding = 'utf-8' new_val...
68af78444da86cdf73f74f84f5c7f0743b591e5c
31,390
def addgroup(request): """Add group form.""" return render( request, 'addgroup.htm', context={}, )
dce8da2641b35bbdb1062463e9bc954b70c9d1d2
31,391
def cached_function_method_signature(ctx: MethodSigContext) -> CallableType: """Fixes the `_CachedFunction.__call__` signature to be correct. It already has *almost* the correct signature, except: 1. the `self` argument needs to be marked as "bound"; 2. any `cache_context` argument should be r...
7b1b9893afe4f1e723eed7894b0adf9221c24d1d
31,392
def load_valid_data_full(): """ load validation data from disk """ hdf5_file_valid = h5py.File(HDF5_PATH_VALID, "r") data_num_valid = hdf5_file_valid["valid_img"].shape[0] images_valid = np.array(hdf5_file_valid["valid_img"][:]) # your test set features labels_valid = np.array(hdf5_file_val...
bc586424e6fc2669107c7548220461a089bbad16
31,393
import json def import_slab_structures(filename): """Read 2D water structures from file and return a dictionary of it. Parameters ---------- filename : str Filename of the file containing the bulk structures Returns ------- filedict : dict Dictionary of the structures ...
d6ca4d5c7b5c264d55cd26f638dfb4ec34bce259
31,394
import re def handle_email(text): """Summary Args: text (TYPE): Description Returns: TYPE: Description """ return re.sub(r'(\w+@\w+)', Replacement.EMAIL.value, text)
c96e3f5791394d5200c309e5ea1a285aae85a3df
31,395
def LowerCustomDatatypes(): """Lower custom datatypes. See tvm::datatypes::Registry for more information on adding custom datatypes. Returns ------- fpass : tvm.ir.transform.Pass The result pass """ return _ffi_api.LowerCustomDatatypes()
cb55a578a3daabf6e95a64bc95ba75643d2f14bd
31,396
import typing def apply_if_or_value( maybe_value: typing.Optional[typing.Any], operation: typing.Callable[[typing.Any], typing.Any], fallback_value: typing.Any, ) -> typing.Any: """Attempt to apply operation to maybe_value, returning fallback_value if maybe_value is None. Almost a convenience...
fe67fbc1b71ed22fa3da516df82a72cb64e30f33
31,397
import torch def make_pyg_dataset_from_dataframe( df: pd.DataFrame, list_n: list, list_e: list, paired=False, mode: str = "all" ) -> list: """Take a Dataframe, a list of strings of node features, a list of strings of edge features and return a List of PyG Data objects. Parameters ---------- d...
267787c7b527a92421fa7e83ca75bf2a8083ec2a
31,398
def ucfirst(string: str): """Return the string with the first character in upper case.""" return _change_first_case(string, upper=True)
4f52744dc62f4db7437451de3120691bbb184298
31,399
def gumbel_softmax(log_pi, tau=0.1, axis=1): """Gumbel-Softmax sampling function. This function draws samples :math:`y_i` from Gumbel-Softmax distribution, .. math:: y_i = {\\exp((g_i + \\log\\pi_i)/\\tau) \\over \\sum_{j}\\exp((g_j + \\log\\pi_j)/\\tau)}, where :math:`\\tau` is a tem...
91751a5bd8069c71de5dbe9f2cbbc7757daff140
31,400
def has_active_lease(storage_server, storage_index, now): """ :param allmydata.storage.server.StorageServer storage_server: A storage server to use to look up lease information. :param bytes storage_index: A storage index to use to look up lease information. :param float now: The curre...
544b17489bc766a15bf2eca5cddab55c1bf473dd
31,401
def MXfunc(A, At, d1, p1): """ Compute P^{-1}X (PCG) y = P^{-1}*x """ def matvec(x): return p1 * x N = p1.shape[0] return LinearOperator((N, N), matvec=matvec)
c2c1d6361756779f9318a9356251c8ba1a610057
31,403
from ._filter import filter_ from typing import Callable def filter(predicate: Predicate[_T]) -> Callable[[Observable[_T]], Observable[_T]]: """Filters the elements of an observable sequence based on a predicate. .. marble:: :alt: filter ----1---2---3---4---| [ filter(i: i>2) ...
b56f4ed6e770d9b623362cca92a791d7f1ef5fa7
31,404
def scb_to_unit(scb): """Convert codes used by Statistics Sweden to units used by the NAD GIS files.""" scbform = 'SE/' + '{:0<9}'.format(scb) if scbform in g_units.index: return g_units.loc[scbform, 'G_unit'] else: return 0
1c878492bb0bb4e8c7b7874097c86fa8bbc93329
31,405
def img_to_square(im_pic): """ 把图片处理成正方形 :param im_pic: :return: """ w, h = im_pic.size if w >= h: w_start = (w - h) * 0.618 box = (w_start, 0, w_start + h, h) region = im_pic.crop(box) else: h_start = (h - w) * 0.618 box = (0, h_start, w, h_start + w)...
ae672ea715cb982272eddaff0417d4f64926894c
31,407
from typing import List def load_sentence( filename: str, with_symbol: bool=True ) -> List[str]: """コーパスをロードする。""" if with_symbol: tokens = [ list(sent.split()) + [config.END_SYMBOL] for sent in (_.strip() for _ in open(filename)) ] else: tokens = [ ...
3f494b740a4ed157f163329de8cc0568e5541cdc
31,408
def to_str(bytes_or_str): """ The first function takes a bytes or str instance and always returns a str. """ if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value
4a73559039501764a00e697c092d20426949058d
31,409
def configure_ampliseq(request): """View for ampliseq.com importing stuff""" ctx = get_ctx_ampliseq(request) return render_to_response( "rundb/configure/ampliseq.html", ctx, context_instance=RequestContext(request) )
90cdd14de158efc79b5cad11feaa115878469866
31,410
import struct def _copy(s): """Creates a new set from another set. Args: s: A set, as returned by `sets.make()`. Returns: A new set containing the same elements as `s`. """ return struct(_values = dict(s._values))
b505af5037d0aa889aa8ed707eaf69d572e54f84
31,411
import random def particle_movement_x(time): """ Generates a random movement in the X label Parameter: time (int): Time step Return: x (int): X position """ x = 0 directions = [1, -1] for i in range(time): x = x + random.choice(directions) return x
0dff68080dbfd56997cffb1e469390a1964a326f
31,412
def find_match_characters(string, pattern): """Find match match pattern string. Args: params: string pattern Returns: Raises: """ matched = [] last_index = 0 if not string or not pattern: return matched if string[0] != pattern[0]: return matc...
6d3bc3844c20584038e41c22eeead7325031b647
31,413
from typing import Union def columnwise_normalize(X: np.ndarray) -> Union[None, np.ndarray]: """normalize per column""" if X is None: return None return (X - np.mean(X, 0)) / np.std(X, 0)
24b5995a5b36738e1c9eecf427fdb4ed83d43145
31,415
def line_intersect(a1, da, b1, db): """ compute intersection of infinetly long lines """ dba = np.array(a1) - np.array(b1) da_perpendicular = perp(da) num = np.dot(da_perpendicular, dba) denom = np.dot(da_perpendicular, db) dist_b = (num / denom) return dist_b*db + b1
5be8211d3f31d7984820349dfbbb1e05592287a4
31,417
def sequence_(t : r(e(a))) -> e(Unit): """ sequence_ :: (Foldable r, Monad e) => r (e a) -> e () Evaluate each monadic action in the structure from left to right, and ignore the results. For a version that doesn't ignore the results see sequence. As of base 4.8.0.0, sequence_ is just sequenceA...
85c36cc767f60eaccd8d91cdc4d14ca2370069f7
31,418
import re def param_validated(param, val): """Return True if matches validation pattern, False otherwise""" if param in validation_dict: pattern = validation_dict[param] if re.match(rf'{pattern}', val) is None: log.error("Validation failed for param='%s', " "v...
4359b20437e8cfd21b82b5952cc1c9026e6dca13
31,419
def remove_keys_from_array(array, keys): """ This function... :param array: :param keys: :return: """ for key in keys: array.remove(key) return array
3143b8e42eb1e1b2f5818a254bcec3631c30f5ea
31,420
def create_tree_data(codepage, options, target_node, pos): """Create structure needed for Dijit Tree widget """ tree_nodes = [] for opt in options: code = opt['code'] cp = codepage + code add_tree_node(tree_nodes, cp, code+"-"+opt['label'], cp) tree_data = { ...
fededfc4bc3e39860221783459d324a15f16d081
31,421
def detect_octavia(): """ Determine whether the underlying OpenStack is using Octavia or not. Returns True if Octavia is found in the region, and False otherwise. """ try: creds = _load_creds() region = creds['region'] for catalog in _openstack('catalog', 'list'): ...
265e01730cfc2b7e1870c0364ddb4cd5d7c4b336
31,422
def add_cache_control_header(response): """Disable caching for non-static endpoints """ if "Cache-Control" not in response.headers: response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" return response
06f3f4a7259076be535b4ea0ca719a13e9e665a0
31,423
from typing import List def clean_new_import_aliases( import_aliases: List[ImportAlias], ) -> List[ImportAlias]: """Clean up a list of import aliases.""" # Sort them cleaned_import_aliases = sorted(import_aliases, key=lambda n: n.evaluated_name) # Remove any trailing commas last_name = cleaned...
5f0b25798f353c999d325125e80c9ccb67b5afec
31,424
def _format_td(timedelt): """Format a timedelta object as hh:mm:ss""" if timedelt is None: return '' s = int(round(timedelt.total_seconds())) hours = s // 3600 minutes = (s % 3600) // 60 seconds = (s % 60) return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
071f25c3c8cfc75cacf2fedc7002527897362654
31,425
def add_quad_reaction_node(graph, rxn): """ Adds a "Quad Reaction Node" (QRN) group of nodes to a graph, and connects them to the correct compound nodes. The QRN consists of two nodes constituting the intended forward direction of the reaction and two nodes constituting the reverse direction. Each ...
360e7c4e74ed58da9b85548c4d217e3d1f40150b
31,426
def matrixFilter(np_image_2D, np_mask): """ Processing filtering with given matrix Keyword argument: np_image_2D -- two dimensional image(grayscale or single color channel) np_mask -- mask matrix as numpy array Return: np_image_fil -- image as numpy 2D array, after specified filtering ...
422de6c4c539ceb154827d511127f1b120519a2a
31,428
def batch_split_axis(batch, n_split): """Reshapes batch to have first axes size equal n_split.""" x, y = batch n = x.shape[0] n_new = n / n_split assert n_new == int(n_new), ( "First axis cannot be split: batch dimension was {} when " "n_split was {}.".format(x.shape[0], n_split)) n_new = int(n_...
0f413e40961b15b64bf118b2daa012e853dbc294
31,429
def right_align(value, length): """ :param value: string to right align :param length: the number of characters to output (spaces added to left) :return: """ if length <= 0: return u"" value = text(value) if len(value) < length: return (" " * (length - len(value))) + va...
de8c42734b094514ebd45c2cb5517da806ec74b8
31,430
import yaml from pathlib import Path def test_disable_functions_as_notebooks(backup_spec_with_functions): """ Tests a typical workflow with a pieline where some tasks are functions """ with open('pipeline.yaml') as f: spec = yaml.safe_load(f) spec['meta']['jupyter_functions_as_notebooks']...
f5e5c8cc687a64d4c7593ef571e181d6cf4d27ce
31,431
def generate_users_data(users): """ Generate users' rows (assuming the user's password is the defualt one) :param users: :return: """ headers = ['שם משתמש', 'סיסמה'] rows = [[user.username, DEFAULT_TEAM_USER_PASSWORD] for user in users] rows.insert(0, headers) return rows
c6d9ef03b3b28c31f59627be574c4d20328b5d82
31,433
def ListToMatrix(lv): """ Convert a list of 3 or 4 ``c4d.Vector`` to ``c4d.Matrix``. """ if not isinstance(lv, list): raise TypeError("E: expected list of vectors, got %r" % type(lv)) m = len(lv) if not isinstance(lv[0], c4d.Vector): raise TypeError("E: expected list elements of type c4...
b60e1f62d250ce1f7c8ef2772755c3a3ce878395
31,434
def loadEpithelium(name): """Returns an epithelium from a CSV file with the given name. Precondition: name exists and it's in CSV format""" assert type(name) == str, "name isn't a string" recs = [] text = open(name) i = 0 for line in text: if i > 0: recs.append(loadRecept...
01e0c613faa71dbc77be650c3eba1f5006966f9e
31,435
def focal_attention(query, context, use_sigmoid=False, scope=None): """Focal attention layer. Args: query : [N, dim1] context: [N, num_channel, T, dim2] use_sigmoid: use sigmoid instead of softmax scope: variable scope Returns: Tensor """ with tf.variable_scope(scope or "attention", reus...
27f480b8911b3ff1a4367af6b7d5b9a549d24653
31,436
def format_float(x): """ Pretty formatting for floats """ if pd.isnull(x): return " ." else: return "{0:10.2f}".format(x)
9f3cdc0ab41bc69807d178e1c4a56abec0ac6fab
31,437
def random_points_and_attrs(count, srs_id): """ Generate Random Points and attrs (Use some UTM Zone) """ points = generate_utm_points(count, srs_id) rows = [] for p in points: rand_str = ''.join(choice(ascii_uppercase + digits) for _ in range(10)) rand_bool = bool(randint(0, 1)) ...
1dcdbb376f91d75c33baf40275a047393bf13fd5
31,438
from typing import Union from typing import List def trimap(adata, **kwargs) -> Union[Axes, List[Axes], None]: """\ Scatter plot in TriMap basis. Parameters ---------- {adata_color_etc} {edges_arrows} {scatter_bulk} {show_save_ax} Returns ------- If `show==False` a :class...
e3294c689e9081813c6e1defecdf20918dc02b8b
31,439
import collections def quantile(arg, quantile, interpolation='linear'): """ Return value at the given quantile, a la numpy.percentile. Parameters ---------- quantile : float/int or array-like 0 <= quantile <= 1, the quantile(s) to compute interpolation : {'linear', 'lower', 'higher', ...
42e53b43d7ea580616d82fea4bdc08260de3b661
31,440
def random_new(algo=RNG_CMWC): """Return a new Random instance. Using ``algo``. Args: algo (int): The random number algorithm to use. Returns: Random: A new Random instance using the given algorithm. """ return tcod.random.Random(algo)
f6eef62d3eb483dbcb85d420262cf411d6934790
31,441
def get_kth_value(unsorted, k, axis=-1): """ Args: unsorted: numpy.ndarray of any dimensionality. k: int Returns: kth values along the designated axis. """ indices = np.argpartition(unsorted, k, axis=axis)[..., :k] k_smallests = np.take_along_axis(unsorted, indices, axis=...
ab787a89c04d390424749916a6ec7958efcc931e
31,442
def rdc_transformer( local_data, meta_types, domains, k=None, s=1.0 / 6.0, non_linearity=np.sin, return_matrix=False, ohe=True, rand_gen=None, ): # logger.info('rdc transformer', k, s, non_linearity) """ Given a data_slice, return a transformation of the features data...
420e0ca3dfedf23434cb1f2ee500a2d0f8969f52
31,443
async def get_layer_version(compatible_runtime=None,layer_name=None,version=None,opts=None): """ Provides information about a Lambda Layer Version. """ __args__ = dict() __args__['compatibleRuntime'] = compatible_runtime __args__['layerName'] = layer_name __args__['version'] = version _...
57319a257b4e15e2d7ab2d14bfc43718967ea7e2
31,445
from typing import Optional from typing import List def get_header_names(header_annotation_names: Optional[List[str]], doc: Optional[str] = None, docs: Optional[List[str]] = None): """Get a list of header annotations and a dictionary for renamed annotations.""" # Get ...
e011af009e350e0ddbd5b18d19eb45816a7e8d6c
31,446
def data_index(data, key): """Indexing data for key or a list of keys.""" def idx(data, i): if isinstance(i, int): return data[i] assert isinstance(data, dict) if i in data: return data[i] for k, v in data.items(): if str(k) == str(i): ...
f2b6d18bcd83eb0ffd9b355643e79b40459d8d6a
31,447
def calculate_misfit(da): """ For each force orientation, extracts minimum misfit """ misfit = da.min(dim=('origin_idx', 'F0')) return misfit.assign_attrs({ 'best_force': _min_force(da) })
3dcba853b2e30d9fb5d3cbf96cfa6a00760335a6
31,448