content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_wu_bound_strong(lipschitz_constant, gamma, n_samples, batch_size, verbose=True): """ compute the bound in the strongly convex case basically copied from https://github.com/tensorflow/privacy/blob/1ce8cd4032b06e8afa475747a105cfcb01c52ebe/tensorflow_privacy/privacy/bolt_on/optimizers.py ""...
120650fe3ac2460f592f784f734d678a423ce4eb
53,200
async def init_wiki(): """ Async-creates the wiki object and sets its .soup to actual JSON. return: gbfwiki.wiki wiki """ wiki = Wiki() await wiki._init() return wiki
d0313a5c70266d291d89b188b95ea1ff866a315d
53,201
from typing import Union from typing import List import sys import json def main(argv: Union[List[str], None] = None) -> int: """Drive the lookup.""" error, message, strings = verify_request(argv) if error: print(message, file=sys.stderr) return error command, config = strings wi...
c7bdf4c226cb4e57b1a8364d909c7b9c3028deba
53,202
def shrink_ss(inputs_, theta_, q): """ Special shrink that does not apply soft shrinkage to entries of top q% magnitudes. :inputs_: TODO :thres_: TODO :q: TODO :returns: TODO """ abs_ = tf.abs(inputs_) thres_ = tf.contrib.distributions.percentile( abs_, 100.0-q, axi...
1d857ef9effbec8492d075d574d69dff066ba1c3
53,203
def pig_latin(wrd): """Returns the Pig Latin version of a word. For words that begin with a consonant, take the consonant/consonant cluster and move it to the end of the word, adding the suffix 'ay' to the end of the word. For words that begin with a vowel, leave the word as is and add the suffix ...
2eba5f4aaff1391e60f4097e526539d5b486c9bd
53,204
from typing import List from typing import Optional def select_config( configs: List[cconfig.Config], index: Optional[int], start_from_index: Optional[int], ) -> List[cconfig.Config]: """ Select configs to run based on the command line parameters. :param configs: list of configs :param in...
5cb5f2f44867aa2d5c662fb13b4e19e2fe737da7
53,205
def parse_units(units_str): """ Extract and parse the units Extract the bounds over which the expression is assumed to apply. Parameters ---------- units_str Returns ------- Examples -------- >>> parse_units('Widgets/Month [-10,10,1]') ('Widgets/Month', (-10,10,1)) ...
18f35a06aedfc9d026cfa70a1217b0b5b0420ca5
53,206
def _read_method(schema): """Add a write method for named schema to a class. """ def func( self, filename=None, data=None, add_node_labels=True, combine_on='index', use_uids=True, **kwargs): # Use generic write class to write data. df0 ...
65aaa9f3137506699cc50570932993d9f34796e1
53,207
from typing import List def mark_nb_animals_neighbors(neighbors: List[List[int]], w: int, h: int, nb_animals: int, animal_type: str) \ -> ClausesBase: """ Permet d'ajouter des contraintes concernant le nombre d'animaux autour d'une cellule :param neighbors: Liste des cordonnées des cellules voisin...
43c2a784dd3223861e5b08018322c567d32abd55
53,208
def predict_next_daterange(dateranges, min_probability=0.8): """ Takes a list of dateranges (start, end) and tries to predict the next daterange in the list. See :func:`predict_next_value` for more information. """ return predict_next_value( values=dateranges, min_probability=min_...
424bbb677f512cfdbfdd127bf5eae990590a2dd9
53,209
import shutil import os def delete_nodenet(nodenet_uid): """Unloads the given nodenet from memory and deletes it from the storage. Simple unloading is maintained automatically when a nodenet is suspended and another one is accessed. """ if nodenet_uid in nodenets: unload_nodenet(nodenet_uid) ...
2c4d889ba3a13a5a84478b6be289ebc894a8d125
53,210
import torch def resize_activations(v, so): """ Resize activation tensor 'v' of shape 'si' to match shape 'so'. :param v: :param so: :return: """ si = list(v.size()) so = list(so) assert len(si) == len(so) and si[0] == so[0] # Decrease feature maps. if si[1] > so[1]: ...
9e2cc25cbc5b31b986e3486d6c66dd24ac5c36c8
53,211
import torch def show_model(model:nn.Module): """ Render graphviz representation of neural network model """ hl_graph = hl.build_graph(model, torch.zeros([1, 3, 224, 224])) hl_graph.theme = hl.graph.THEMES["blue"].copy() return hl_graph
98b6deee208ee9cba23c42b19937f9e0aca26764
53,212
def seg_pixel_accuracy_nd(label_imask, pred_imask, vague_idx=-1, use_vague=False, macro_average=True, empty_result=0.0): """ The segmentation pixel accuracy (for MXNet nd-arrays). ...
7da093ef624dee07fd335021ae2317d53583e612
53,213
import wave def record_audio(record_len, filename): """ records an audio clip from the default input device @params: length: the length of recorded audio [seconds] filename: the ouput filename """ try: CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNEL...
9b9b4ea57f56fe97a40e7e4f620765779de903be
53,214
import importlib import inspect def getCoursesFromModels(): """This method imports and inspects Models.py file and adds name of its classes to the list. User class is skipped so it is not added into list of courses. Returns: list: List of string names of classes in Models.py file. """ co...
fd3685ca68e98afd9384ad0711e43ac68e02c94d
53,215
def format_message(article_dict): """ From a dictionary of randomly selected articles, create and format a message string. """ msg = "" for subject in article_dict: url = article_dict[subject][1] abstract, authors = get_abstract(url) msg = msg + "<h2>" + subject + "</h2>...
dfb5008eefb67017a359d0aa452b40414acf21c7
53,216
from datetime import datetime def lock_nqueuedjobs(cur, nrows): """ Function to lock first N rows for futher processing :param nrows: :return: lock_time """ lock_time = datetime.now().strftime(defaultDatetimeFormat) lquery = """UPDATE atlas_pandabigmon.art_results_queue SE...
b81721e27b8dd28020110e7d689bc4d0302093ee
53,217
def extract_seed(path, key): """ Scrape the 5-character seed from the path and return it as an integer. :param path: path to the tsv file containing results :param key: substring preceding the seed, "batch-train" for splits, seed-" for shuffles """ try: i = path.find(key) + len(key) ...
c5073ad43e8a966aba5382894490aa6cbc871271
53,218
from datetime import datetime def UTC2JD1JD2(epoch: datetime.datetime): """ :param epoch: :return: """ return astropyTime(epoch, format='datetime', scale='ut1').jd1, astropyTime(epoch, format='datetime', scale='ut1').jd2
5183af2730130ee7e28434f67071ba6b0e232692
53,219
import sympy as sym def test_solver(): """Check 1st order convergence rate.""" m = 4; b = 0.1 s = lambda u: 2*u f = lambda v: b*v def ode(u): """Return source F(t) in ODE for given manufactured u.""" print 'ode:', m*sym.diff(u, t, 2), f(sym.diff(u,t)), s(u) return m*sym.di...
b7b8eaba059b832d3cfc175cffcd310b49f649e1
53,220
def spawn(n): """ Spawn a list of SeedSequence from the global seed sequence. Parameters ---------- n : int Number of seed sequences to spawn Returns ------- seed_seq : list List of spawned seed sequences """ return _GLOBAL_SEED_SEQ.spawn(n)
109b374607e0fdcb52f117c5176ea918f633ad14
53,221
from typing import Tuple from typing import Any import dis import inspect import sys import warnings import types import io import contextlib def compile(code: list, consts: list, names: list, varnames: list, func_name: str = "<unknown, compiled>", arg_count: int = 0, kwarg_defaults: Tuple[Any...
6c2834d075f4c78073d74068b3b25c10ace90edd
53,222
def get_certificates(country=None): """ This function retrieves all the data stored in `certificates.csv` file, which previously was retrieved from Investing.com. Since the resulting object is a matrix of data, the certificate's data is properly structured in rows and columns, where columns are the ce...
4bf7984ab8b9856039ae4f012868558000ee206c
53,223
def f_t(x_tm1, potential_function, parameters, dt, **kwargs): """ NOTE : parameters should reflect potential function at time t (not t-1) compute f_t(x_tm1) = x_tm1 + 0.5 * dt * forcet(x_tm1) = mu arguments x_tm1 : np.array(N) positions at time t-1 potential_function : funct...
8903b5ce003832c1dadaca24cd539c03ec828984
53,224
def get_neighbor_dict_from_table(db, table_name): """ returns a dict with bgp neighbor ip as key and neighbor name as value :param table_name: config db table name :param db: config_db """ neighbor_dict = {} neighbor_data = db.get_table(table_name) try: for entry in neighbor_data...
17d8230956c36db8c79bd98f0eec63320b6e77d0
53,225
def french_to_english(french_text): """This function translates text in french to english""" if french_text == "": return "" english_text = language_translator.translate(text=french_text, model_id='fr-en').get_result() english_text = english_text.get("translations")[0].get("translation") re...
6d50828cb5dd9dd964f41b3427597107130e87aa
53,226
import re def highlight_cycles(dot_stream, cycle_list): """Highlight the include cycles in red.""" for cycle in cycle_list: cycle_edges = determine_cycle_edges(cycle) for edge in cycle_edges: regex = fr'([<"]{edge[0]}[">] -> [<"]{edge[1]}[">])' match = re.search(regex,...
e6aba9c3c920ec5680d1fdd29625401a36f9462e
53,227
def find_role_similarity(roles, i, j, parameters=None): """ Calculate a number of similarity between different roles Parameters ------------- roles List of roles i Index of the first role j Index of the second role parameters Parameters of the algorithm ...
6fc669c0537907b0442d7db959db5ad6fd2feb5a
53,228
def histogram_matching(mov_scan, ref_scan, histogram_levels=2048, match_points=100, set_th_mean=True): """ Histogram matching following the method developed on Nyul et al 2001 (ITK implementation) inputs: - mov_scan: np.array cont...
9f4149ffd56470044f3603750b34f445a915dcdc
53,229
def configure_vrrp(module, csv_data): """ Method to configure VRRP L3. :param module: The Ansible module to fetch input parameters. :param csv_data: String containing vrrp data passed from csv file. :return: Output string of configuration. """ output = '' vnet_name = get_global_vnet_name...
be6787a282f747b107d50fc869093c612a38f971
53,230
def update_priorities(repo, username=None, namespace=None): """Update the priorities of a project.""" repo = flask.g.repo form = pagure.forms.ConfirmationForm() error = False if form.validate_on_submit(): weights = [ w.strip() for w in flask.request.form.getlist("p...
6f93aea172c5457068ee01e18c98b03e7ae7406b
53,231
from typing import Union def find_post(url: str) -> Union[Album, None]: """Find post with twitter id in the url Args: url (str): twitter url Returns: Union[Album, None]: Album """ return Album.first(F['source.url'].regex(r'https://twitter.com/.*/status/' + url.split('/')[-1]))
76f5fc8b130c09bcfceacca6c0905e03d0c548d3
53,232
import html def serialize_categories_ical(category_ids, user, event_filter=True, event_filter_fn=None, update_query=None): """Export the events in a category to iCal. :param category_ids: Category IDs to export :param user: The user who needs to be able to access the events :param event_filter: A SQL...
86c1f209b16a6a246edebcff71a327bc2db7dfe3
53,233
def process_intf_counters_rest_output(data, single_port=False): """ Author: Jagadish Chatrasi (jagadish.chatrasi@broadcom.com) :param data: :type dict: :param single_port: :type bool: :return: :rtype: """ ret_val = [] try: if single_port: actaul_data = dat...
282a905a6d0c40c8eb90564dda9c86699b15a914
53,234
import re def create_attribute(name, snake_case=True): """ Gets an attribute name from the enum and convert it to snake_case, by default, or to CamelCase """ # Removes any hyphens or dots from the name, substituting by an underscore name_normalized = re.sub('[-.]', '_', name) if snake_case...
a337e386af1a1ea735612d310618ce8ebf40f679
53,235
def preprocessing_fn(inputs): """Preprocesses Covertype Dataset.""" outputs = {} # Scale numerical features for key in features.NUMERIC_FEATURE_KEYS: outputs[features.transformed_name(key)] = tft.scale_to_z_score( _fill_in_missing(inputs[key])) # Generate vocabularies and maps categorical featu...
81fb7b301f447e7b31a31fa6c174d0821992fe18
53,236
import tokenize def build_model(gridsearch=False): """ Create a classification model :param gridsearch: bool. Activate GridSearch, default = False :return: pipeline """ # Create pipeline with Classifier moc = MultiOutputClassifier(RandomForestClassifier()) pipeline = Pipeline([ ...
ce4c7a6a1afc58957884e1e4073247c42ca7b8ac
53,237
import pickle def get_cells_to_calculate_variance(file_path, percentage_of_extreme_cells=15): """ Get a list of cells to use to calculate the methylation and variance In this case we have a list of all cells that might be possible and the avg methylation and variance of them and we want to take the pe...
c151b03cb873f179eb946dd12f6a286aeea8e7a3
53,238
def device_smart_capabilities(device): """Returns SMART capabilities of the given device. Args: device: (Device) Device in question. Returns: (tuple): tuple containing: (bool): True whenever SMART is available, False otherwise. (bool): True whenever SMART is enable...
b3f3ea1908fd75808d9b73ee77a69dfb503cda04
53,239
def slice_arrays(arrays, start=None, stop=None): """ Function extracted from Keras - check keras.utils.generic_utils for the original version. Slices an array or list of arrays. This takes an array-like, or a list of array-likes, and outputs: - arrays[start:stop] if `arrays` is an array-lik...
841a645ff866e0e811291d416037263f38035d12
53,240
def test_with_exit(exit_code): """ We parametrize over the first few exit codes to ensure they are all handled the same. `utils.with_exit` should always raise, even in the case where `foo` ran successfully (`exit_code==0`). """ @utils.with_exit def foo(): return exit_code with pytes...
fe7ed64616f54058241098cfda2f038af16c4fc8
53,241
import gzip def load_data_sample(fn): """ :param fn: :return: samples: 1D: n_docs, 2D: n_utterances, 3D: elem=(time, speaker_id, addressee_id, response, ... , label) """ samples = [] sample = [] with gzip.open(fn, 'rb') as gf: for line in gf: line = line.rstrip().split(...
6f6828a60767a1ac1674ad5abbe519b1d1b18df0
53,242
def calc_buckets( start: float, upper_bound: float, /, *, increment_ratio: float = 1.20 ) -> tuple[float, ...]: """Calculate histogram buckets on a logarithmic scale.""" # See https://amplitude.com/blog/2014/08/06/optimal-streaming-histograms # for more details. result: list[float] =...
541fdb81b150a81d24b515acaf53365afb4b62b4
53,243
def ximp(N, i, real=False, polar=False, show_x=False, v=1, unwrap=False, get=False): """Impulse(s); form e.g. square wave""" if not isinstance(i, (list, tuple, np.ndarray)): i = [i] i = [(idx if idx >= 0 else N + idx) for idx in i] x = np.array([(v if n in i else 0) for n in range(N)]) ...
fe5af063eb73674d755621e356cd3c25e92c7fc8
53,244
import torch def quantizer(forward_number=None, backward_number=None, forward_rounding="stochastic", backward_rounding="stochastic", clamping_grad_zero=False, backward_hooks=[]): """ Creates a quantization function to support quantizing forward and backward process differently. ...
5985d64c31d4ef42ae1c4cc0ed5ccf322f20c75e
53,245
def dumpinfo(id0): """ print various infos on the idb file """ def ftstring(ft): if 0 < ft < len(filetypelist): return "%02x:%s" % (ft, filetypelist[ft]) return "%02x:unknown" % ft def decodebitmask(fl, bitnames): l = [] knownbits = 0 for bit, name in enu...
7afe394022107261a3ce660d76247e876b5c9f0f
53,246
def is_size_lower_or_equal(size_a: str, size_b: Size): """Returns true if size_a is lower or equal than size_b""" return int(size_a) <= int(size_b.get_value(Unit.MebiByte))
89966dfee96489daf64942b4c36ab9a395c787a6
53,247
def from_hexpoints(s): """Parses a string from its codepoints as hex. Given a string containing one or more code points (as hex values), parse it to a a string. For example, the input "006E 006F" produces output "no". """ return "".join([chr(int(cp, 16)) for cp in s.split()])
55b5088d000cf90059ca93d7e3895aee043d554e
53,248
def hamming_distance(s1, s2): """ Defines the minimum number of substitutions required to change one string into another. """ if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal lenght.") return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
5228ec015a87797860075e18a955a47236e03460
53,249
import inspect import torch def get_pure_function(fcn) -> PureFunction: """ Get the pure function form of the function or method ``fcn``. Arguments --------- fcn: function or method Function or method to be converted into a ``PureFunction`` by exposing the hidden parameters affect...
54994a04e5cf925c0dcd7cab876c1ceb631b071a
53,250
def img_brighten(img, factor): """ Increase the brightness of the input img :param img: input img :param factor: the degree of increasing the brightness :return: output img """ img2 = img * factor img2 = np.clip(img2, 0, 255) return img2
80b6d6529213ce13aacce9da979208600c247778
53,251
def choose_random_action(all_actions: int) -> int: """ Chooses one of the possible actions in the environment randomly Parameters ---------- all_actions: int number of all possible actions available Returns ------- int random action number """ return np.random.r...
777f30f48152857011eac4818b3c3e6b2485dc33
53,252
from typing import List def generate_equi_width_buckets(quantiles: List[float], finite_min: float, finite_max: float, total_count: float, num_buckets: int) -> List[Bucket]: """Generate buc...
f7704bd2449553607187c1dadf6a2c5c204a764a
53,253
def turnover_knee(f, log10_A, gamma, lfb, lfk, kappa, delta): """ Generic turnover spectrum with a high-frequency knee. :param f: sampling frequencies of GWB :param A: characteristic strain amplitude at f=1/yr :param gamma: negative slope of PSD around f=1/yr (usually 13/3) :param lfb: log10 tra...
c01b634b5a4a6603b6e77244b0b57f30afba119e
53,254
def basicFitness(individual, env): """ The trivial case, where fitness is just the result of passing through the environment. """ return individual.result
7d108bac92ce390699b66e1ead5b08080856c5be
53,255
def map_reward(const=1.0) -> MapReward: """ Factory for map_reward argument in GPMultiFidelitySearcher. """ def const_minus_x(x): return const - x return MapReward(forward=const_minus_x, reverse=const_minus_x)
37cfbe67b791f0bd566744054f74c657efda2e5b
53,256
import time import socket import errno def check_for_daemon(limit=10, delay=0.1, timeout=0.1, port=TCP_GIT_PORT): """Check for a running TCP daemon. Defaults to checking 10 times with a delay of 0.1 sec between tries. Args: limit: Number of attempts before deciding no daemon is running. dela...
9f1d4f378e1b08c6af2de92dcfd78ce77d5cc23f
53,257
import os def get_acknowledgements(): """Returns a list of individuals who are acknowledged on the ``about`` page. The list is generated by reading in the contents of the ``jwql`` ``README`` file. In this way, the website will automatically update with updates to the ``README`` file. Return...
c0d869a111638ca9b0dd6086a98780f50b539211
53,258
def comb_extend(comb, minv, maxv): """Extend the comb to minv and maxv""" # TODO should this truncate if minv>minc or maxc>maxc # print y_comb # Find sort order of comb, convert to ascending reversed = False if comb[0] > comb[-1]: comb.reverse() reversed = True # Find min and...
6c21e857c74b7a3ab94a366e869869372e3e9592
53,259
def evaluate_recall(gt_rels, gt_boxes, gt_classes, pred_rels, pred_boxes, pred_classes, rel_scores=None, cls_scores=None, iou_thresh=0.5, phrdet=False): """ Evaluates the recall :param gt_rels: [#gt_rel, 3] array of GT relations :param gt_boxes: [#gt_box, 4] array...
3cc53b481643b4fd4dfbbc4b41b15b0fa5e2adf1
53,260
import os def solution_name() -> str: """ Get the Solution Name from environment variable :return: the solution name """ return os.environ["SOLUTION_NAME"]
a43b79ac9ad39b22ab65de02ec6845f3058e259e
53,261
def not_found(arg): """Page not found.""" return render_template('404.html', title='404 error.', message='Page Not Found')
12147889561a182abbb03f517cc6f642a9cc9cd2
53,262
def mte_unobserved( X, Y, b0, b1_b0, prop_score, bandwidth, gridsize, startgrid, endgrid ): """ This function computes the unobserved component of the MTE in MTE = mte_x + *mte_u*, where *mte_u* depends on the unobserved esistance to treatment u_D. Parameters ---------- X: pandas.DataFr...
e77a44e8aff584c4c649c2da167d09afff27eccc
53,263
def wavepacket(m, x0, p0): """Generates normalized Gaussian wavepacket in position and momentum space. Parameters ---------- m : int Number of planck cells in one direction. x0 : float Initial x-coordinate of localized wavepacket in position space. p0 : float Initial...
d4bd5894609039ca44b99412d0e732bea11d5c2c
53,264
def make_key_with_salt(seed, salt): """generates a key from a given seed, returns the key and a salt Args: seed Returns: signing key, a salt Raises: assertion failure if the signature is not verified """ ecdsa_seed = hash_256(seed + salt) secexp = randrange_from_se...
2b262f96768f6ec1566590836f55ac531336b44e
53,265
def find_missing_integer(arr): """ Find the first missing integer in unsorted array of integers """ # segregate integers, with negative (including zero) on right and positives # on left left = 0 right = len(arr) - 1 while left < right: if arr[left] > 0: left += 1 ...
d31b5a42ed9bd43d7d036098e8491b4b839c5873
53,266
def break_weights(weights): """ Breaks the weights for the different nodes :param weights: :return: """ bias_node_hidden = weights[4:6] bias_node_hidden = np.reshape(bias_node_hidden, (2, 1)) bias_node_output = np.reshape(weights[8], (1, 1)) weights_input = weights[0:4] weights...
2f77feab5cd083553c4b6b4f8600f1f3646381b9
53,267
def get_movies(genre: str): """Get first N movies in the specified genre.""" with MongoClient(uri) as client: movie_collection = client[DB][MSG_COLLECTION] msg_list = movie_collection.find({"genres": genre}).limit(100) movie_title_list = [] for msg in msg_list: movie_...
795fc4b4595e92686efa190b4ba2933aeaed4451
53,268
def apply_all_transformations(df): """Apply all feature transformations.""" df["age_quantile"] = compute_age_quantile(df, 5) df["competition_open"] = compute_competition_open(df) df["count"] = df.groupby("store")[["date"]].transform("cumcount") df["open_lag_1"] = compute_open_lag(df) df["open_la...
e14c3aa9f79c851085daf75e269dcea9bec7a87b
53,269
def _lcmv_source_power(info, forward, noise_cov, data_cov, reg=0.01, label=None, picks=None, pick_ori=None, rank=None, verbose=None): """Linearly Constrained Minimum Variance (LCMV) beamformer. Calculate source power in a time window based on the provided data ...
265a1a7a2e8e70ff4142288c0dbd484b2e36321c
53,270
def summary(d): """ Generate a summary message of the dictionary. :param d: A dictionary to summary. :return: A string as summary message. """ msg_list = [] for key, value in d.items(): msg = '- {}: '.format(key) if isinstance(value, np.ndarray): msg += 'shape {...
26139ed6fa1617fb28fab0b515e00deb054fb8d6
53,271
def get_folding_command(cand, obs): """ get_folding_command(cand, obs): Return a command for prepfold for folding the subbands using an obs_info instance, and a candidate instance that describes the observations and searches. """ # Folding rules are based on the facts th...
5b770aad1eff747e790c6ac8af61a773e11efb08
53,272
import re import argparse def valid_labels_regex(arg_value, pat=re.compile(r"^all|random|([a-z|0-9|,|\.]+)|([a-z|0-9|\.]+-[a-z]+-[1-9]-[0-9]-[1-9]-[c|h],?)+$")): """Get the params regex.""" if not pat.match(arg_value): raise argparse.ArgumentTypeError return arg_value
7f278654cf7c1630ce6751aaacfa85d0b08e65cb
53,273
def execute(context: cli.CommandContext) -> Response: """ """ response = context.response project = cauldron.project.internal_project if not project: return response.fail( code='NO_OPEN_PROJECT', message='No project is open. Unable to refresh' ).console( ...
44fc1a8df66e586769fee21727978cf30034ab8c
53,274
def get_username(strategy, user=None, *args, **kwargs): """Sets the `username` argument. If the user exists already, use the existing username. Otherwise generate username from the `new_uuid` using the `helusers.utils.uuid_to_username` function. """ storage = strategy.storage if not user: ...
2c3f15ae156641ed26b5fa55d8208002716ebf43
53,275
import http def uptest_latest(request): """ Look up most recent test run and redirect to its record in the API. """ runs = models.TestRun.objects.filter(end__isnull=False).order_by('-start') if not runs: return http.HttpResponseNotFound() url = reverse('api_dispatch_detail', ...
8b5b047c7db820a0aa288d1478af1b2554da6dc2
53,276
def one_to_three(one_letter): """ Convert a one letter code amino acid to a three letter code. """ assert one_letter.upper() in "FLSYCWPHERIMTNKVADQG*U", "Error, %s is not a valid amino acid" % one_letter AA = { "I": "Ile", "V": "Val", "L": "Leu", "F": "Phe", ...
6554ff9063824f348a512e28df3dc936073d1355
53,277
def get_video_frame(video_path, frame_number): """ Obtain numpy array corresponding to a particular video frame in video_path :param video_path: local path to mp4 file :param frame_number: video frame to be returned :return: numpy array corresponding to frame of interest. Dimensions are (1024, 1280...
05fc204829b648ab51315d1901f52805948e9fc0
53,278
import time def float_product(size=DEF_MATRIX, rep=DEF_REP): """ Returns the execution time of performing a product of random real matrices. Parameters ---------- size : int The dimension of the square matrices that will be used in the operation. ...
0826058fd3ba971001a512c02e506bc759f9bf52
53,279
def _empty_frozen_http_headers() -> HttpHeaders: """Used for the 'default_factory' of the 'NodeConfig.headers'""" return HttpHeaders().freeze()
7e0f323fd463901f6b2f46f53719a6db2232461a
53,280
def reorder_evals(ev,times): """ Parameters ---------- evals : 2D numpy array containing a series of eigenvalues. times : 1D numpy array containing the corresponding times Returns ------- newev : 2D numpy array with continuous (along dim=0) eigenvalues """ evals = ev....
27e33caa4d235ca27b5d2f2764cbae314c310e82
53,281
import types def get_public_members(): """Get public members in :mod:`bezier` package. Also validates the contents of ``bezier.__all__``. Returns: list: List of all public members **defined** in the main package (i.e. in ``__init__.py``). Raises: ValueError: If ``__all__`` h...
4e5a7d5173c0c4a9c1024428e95ef21e1386e37e
53,282
import hashlib def sha256_hash(stream, block_size=65536): """ Calculates a sha256 hash for the contents of the provided stream. :param stream: The stream of the content where to calculate the hash for. :type stream: IOStream :param block_size: The amount of bytes that are read each time. :typ...
f18c170c961c651301ee9b4bfd8d526a05e199ef
53,283
def central_time(sqrIR: np.ndarray, tstamp: np.ndarray) -> np.ndarray: """ Room parameter. Parameters ---------- sqrIR : np.ndarray Squared room impulsive response. tstamp : np.ndarray Time stamps of each IR sample. Returns ------- central_time : np.ndarray ...
f307c77e0069c6feec7a3e8cc272b59bd022c1b9
53,284
def get_html_fields(fields): """ Converts a fields table with mandatory keywords type, text, id and partially optional keywords value, allowed_values, checked and help into html input lines. The tal in the templates has become too complicated therefore the python code handles most of the condition...
9269d26a86892791d5ef4847546600d629c8f7c6
53,285
def GetAccessTokenIfEnabled(account=None, scopes=None, allow_account_impersonation=True): """Returns the access token of the given account or the active account. If credentials have been disabled via properties, this will return None. Otherwise it return th...
3540e5f05712430c6cca0a50d43f09495e876861
53,286
from datetime import datetime def plot_drifters(ax, DATA, DRIFT_OBJS=None, color='red', cutoff=24, zorder=15): """Plot a drifter track from ODL Drifter observations. :arg time_ind: Time index (current drifter position, track will be visible up until this point, ex. 'YYYY-mmm-dd HH:MM:SS', format is f...
c3398ce48bc2b61a3fe4933e72a8d72da97c3530
53,287
from typing import List import math def quaternion_from_angle_axis( angle: float, axis: np.ndarray, axis_normalized: bool = False ) -> List[float]: """Gets a quaternion from an angle and an axis. For more information, check `this Wikipedia page <https://en.wikipedia.org/wiki/Conversion_between_quatern...
71379e483ae35ebf18d6a692bd961dc29487ca4b
53,288
def _overlaps(existing, new): """Check whether existing diff op shares a key with the new diffop, and if they also have the same op type. """ if not existing: return False existing = existing[-1] # Only need to check last op! if existing.op == new.op: if existing.key == new.key:...
0edc849ea2cbdf1f840a4239a0088d42692ec79a
53,289
def A000121(n: int) -> int: """Give Number of representations of n as a sum of Fibonacci numbers. (1 is allowed twice as a part). a(0) = 1; for n >= 1, a(n) = A000119(n) + A000119(n-1). - Peter Munn, Jan 19 2018 """ if n == 0: return 1 return A000119[n] + A000119[n - 1]
3bc565ab2c971bfbe4af46f69d700489da1e8654
53,290
import logging def fetch_cordis_organisations(): """Fetch cordis organisations""" logging.info("Fetching cordis organisations") orgs = pd.read_csv( "https://cordis.europa.eu/data/cordis-h2020organizations.csv", delimiter=";" ) orgs.columns = [camel_to_snake(c) for c in orgs.columns] o...
2bb1efa5fd61ed9c165935d3981e8b7193595729
53,291
import ipaddress def set_proxy_facts(facts): """ Set global proxy facts Args: facts(dict): existing facts Returns: facts(dict): Updated facts with missing values """ if 'common' in facts: common = facts['common'] if 'http_proxy' in common or 'https_...
922131a20bc5d9d0fa1fd09cf3d728388f169d7f
53,292
def run_program(memory, inputs): """Execute the successive instructions of the program""" instr_ptr = 0 output = [] while True: (opcode, modes) = parse_opcode(memory[instr_ptr]) if opcode == 99: # Program end break elif opcode in [1, 2]: # 1 = Addition, 2 = Multi...
004b4f5df2b6b97697e6a3cbb80f1e2787efdddc
53,293
def load_image(filename, color=True): """ Load an image converting from grayscale or alpha as needed. Parameters ---------- filename : string color : boolean flag for color format. True (default) loads as RGB while False loads as intensity (if image is already grayscale). Ret...
41b9e18cdc481c38abd685796b3ee942bf19ae7f
53,294
def choose_file(): """Opens a file chooser and returns selected filepath""" root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() logger.debug("Choosen filepath: %s", file_path) return(file_path)
0a7524086666cf7518a29706490e9dc7b181894e
53,295
def build_pixel_sample_scale_display(node: hou.RopNode) -> str: """Build a label to display the adjusted pixel samples. :param node: The node to build the display for. :return: The display scale. """ samples = node.evalParmTuple("vm_samples") sample_scale = node.evalParm("ip_sample_scale") ...
677d13c374f174a790989bd46eb7ea3f66d0e9dc
53,296
from typing import Dict from typing import Any import os def _parse_args() -> Dict[str, Any]: """ Parse the command line parameters into a Config object. Aborts on error. :return: the parsed arguments """ args = docopt.docopt(USAGE, version=VERSION, options_first=True) source_dir = args["SRC...
9db4d924402c2d60c7d2b0c2d2913489e576d27f
53,297
import copy def test_oauth_logout(app, mockservice_url): """Verify that logout via the Hub triggers logout for oauth services 1. clears session id cookie 2. revokes oauth tokens 3. cleared session id ensures cached auth miss 4. cache hit """ service = mockservice_url service_cookie_na...
de3383a0c85c4c5f502c15f59b1f2694641e279e
53,298
def get_metadata_from_attributes(Object, skip_attributes = None, custom_classes = None): """ Get metadata dict from attributes of an object. Parameters ---------- Object : object from which the attributes are. skip_attributes : list, optional If given, these attributes are...
0c6eacae223ea94e128ff5b507fcaa5a71034c38
53,299