content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def instancemethod(f): """Decorator to indicate that the method is a method of an instance rather than a model.""" @wraps(f) def f_wrapped(self, *args, **kw_args): if not self.instantiated: # Attempt to automatically instantiate. self = self() return f(self, *arg...
a0f5e6eb65df69809d02e217e0f37cbc81734c51
3,607,200
def _principal_from_token(token): """Determine a principal from a JWT Args: token: The JWT Returns: Brewtils principal if JWT is valid, None otherwise """ try: decoded = jwt.decode( token, key=brew_view.config.auth.token.secret, algorithm...
df908c5d5186f035c8e2fc26bcf1ef1eeccb4f17
3,607,201
def email_attendees(request, slug): """Send email to event attendees.""" event = get_object_or_404(Event, slug=slug) attendees = event.attendees.all() if request.method == 'POST': email_form = EmailUsersForm(attendees, request.POST) if email_form.is_valid(): statsd.incr('eve...
4c7731e619aba6952bd2767a52ab47dc82ebe0ec
3,607,202
from typing import Tuple from typing import Union def json_types(max_size: int = 5, *, max_leaves: int = 25) -> st.SearchStrategy: """ Return a recursive stategie for generating JSON type-hints inputs Arguments: max_size: maximum size of the lists and dicts created max_leaves: maximum num...
f6108973a7cb8818a390a3ba4ac1f08b6cc83390
3,607,203
def one(n = 10): """ a strange function with an ambiguous name Parameters ---------- :param n: int the number of points to test """ sum = 0.0 for i in range(n): denom = 1.0 sum += 1/n return sum
2b8ce5aa198ad1139165fbabf02b89f2d9f7cf73
3,607,204
def SInverse(box, output): """Apply S-box number 'box' in reverse to 4-bit bitstring 'output' and return a 4-bit bitstring (the input) as the result.""" return SBoxBitstringInverse[box%8][output]
ad33cbb10ce7db13710d3beb62e97ac063e45f84
3,607,205
import subprocess def perform_auth_restart(): """When called this will perform an authorized restart. Before trying to perform an authorized restart it checks to see if the machine supports the feature. If supported it will then look for the defined plist containing a key called RecoveryKey. It will u...
14adfed73be67b136751f99dcc4018ea13dcd9e7
3,607,206
from typing import Dict def exposure(population: np.ndarray = None) -> Dict[int, int]: """Returns dict of index: count of individuals Args: population (np.ndarray): the population Returns: Dict[int, int]: key is index, value is count of lineup Examples: >>> fittest_populatio...
55d112b049efdb9982d26dbd92d423e6adfb12d7
3,607,207
def allcorner(samples, labels, axes, weights=None, span=None, smooth=0.02, color="grey", qcolor=None, show_titles=False, hist_kwargs={"alpha": 0.5, "histtype": "stepfilled"}, hist2d_kwargs={}, max_n_ticks=3, label_kwargs={"fontsize": 12}, tick_kwargs={"labelsize":...
885f14994508e822892d139874da8582b1f7bee1
3,607,208
def PersistentPickler(persistent_id, *args, **kwargs): """ Returns a :class:`Pickler` that will use the given ``persistent_id`` to get persistent IDs. The remainder of the arguments are passed to the Pickler itself. This covers the differences between Python 2 and 3 and PyPy/zodbpickle. """ ...
114a6a6454005336ecdad89b2b26605fc58b4e3e
3,607,209
def isFactGroup(arg: str) -> bool: """Function to determine whether a string is a registered fact group """ if arg in RegisteredFactGroups.keys(): return True return False
2a6511d25aa8c6f95ba4f92362cb14cb36a8c20d
3,607,210
def infection_rate_asymptomatic_self_30(): """ Real Name: b'infection rate asymptomatic self 30' Original Eqn: b'Infected asymptomatic 30*Susceptible 30*contact infectivity asymptomatic self 30*(social distancing policy SWITCH self 30\\\\ *social distancing policy 30+(1-social distancing policy SWITCH self ...
9c837aac9d5b01d226d0615b38e89d39cfba7be6
3,607,211
from typing import Tuple import torch from typing import List def long_tensor_2d(shape: Tuple[int, int], fill_value: int = 0) -> torch.Tensor: """Return a new 2d torch.LongTensor with size according to shape. The values of this tensor will be fill_value.""" outer = torch.jit.annotate(List[List[int]], []) ...
c1aaeb01058b9153c31e911f31eae6217f03eb64
3,607,212
def five_twos_simple(): """Five Twos going only left to right, operations: +-*/^""" global N N = [] global S S = [] def five_twos_inner(val,sq,depth): if depth == 5: if int(val) == val and val >= 0: N.append(int(val)) S.appen...
38aeea1d325f7db6975d13411c3958bbe4ee6d1c
3,607,213
def _pad_digits(text: str) -> str: """A str method with hacks to support better lexicographic ordering. The output strings are not intended to be human readable. The returned string will have digit-runs zero-padded up to at least 8 digits. That way, instead of 'a10' coming before 'a2', 'a000010' will ...
7e842669747919a3bbc9fd40e45a4bfc7641cc3a
3,607,214
from typing import List def get_missing_settings(settings_class) -> List[str]: """Used to validate required settings. Verifies that all attributes which don't start with ``_`` and aren't named in ``_optional_settings`` are not set to None. Args: settings_class: The global settings class to v...
efbb2dc3078fc5221e8ce327b078d42eff167d65
3,607,215
def generate_coverage_config(args): # type: (TestConfig) -> str """Generate code coverage configuration for tests.""" if data_context().content.collection: coverage_config = generate_collection_coverage_config(args) else: coverage_config = generate_ansible_coverage_config() return cove...
276058105dfae112e5f8908fbd297ae8203909df
3,607,216
def _check_equal_list(iterator): """ Check that all elements in list are equal """ return len(set(iterator)) <= 1
94bd94a203819965d95105e7f978ecb496ce97bc
3,607,217
import re def error_052_category_in_article(text): """Fix all wrong categories and return (new_text, fixed_errors_count) tuple.""" ignore_filter = re.compile(r"""( <noinclude>.*?</noinclude>| <onlyinclude>.*?</onlyinclude>| <includeonly>.*?</includeonly> )""", re.I | re.DOTALL | re...
1d21a2e49b0a3684a54ad0c0d4153fe771b9f4f7
3,607,218
import hashlib import os def calc_firmware_sha(file): """ Open firmware image file and calculate file size Pad file size to a multiple of 64 bytes Calculate SHA256 hash of the padded contents """ with open(file, 'rb') as firmware: firmware.seek(0, 2) size = firmware.tell() ...
17e0ce8c6c8d2e8cdb5b9bc259087bc4677924ca
3,607,219
from typing import Dict from typing import Any def format_date_and_target( df_input: pd.DataFrame, date_col: str, target_col: str, config: Dict[Any, Any], load_options: Dict[Any, Any], ) -> pd.DataFrame: """Formats date and target columns of input dataframe. Parameters ---------- ...
a610da8098f54fda4a17dba000498249056aa7fa
3,607,220
import json def diagnose(message_value): """ do diagnose based on message's value Args: message_value (dict): info of diagnose. e.g.: { "username": "admin", "host_id": "host1", "tree_name": "tree2", "tree_content": {} ...
db207230d7e275cf13cab096e4a277f9ee724090
3,607,221
def standard_timeseries_reader(*args, **kwargs): """ Wrapper for :any:`standard_time_series_reader` """ return standard_time_series_reader(*args, **kwargs)
254e7a63619a649cd327bc8cf4d0506e45a6e42b
3,607,222
def jam_solver(graph, loads, timeout=None): """ an ensemble solver for the routing problem. :param graph network available for routing. :param loads: dictionary with load id and preferred route. Example: loads = {1: [1, 2, 3], 2: [3, 2, 1]} :param timeout: None, float or int timeout in millis...
ddc6cfab546f2c8aa531b1568495d05591580076
3,607,223
def save_plot(code, elem): """Converts matplotlib plots to tikz code. If elem has either the plt attribute (format: plt=width,height) or the attributes width=width and/or height=height, the figurewidth and -height are set accordingly. If none are given, a height of 4cm and a width of 6cm is used as...
8d2f2ecb6b750eff98d1e17ce553f1613d411216
3,607,224
import re def createCogList(args): """Returns an Autovivification of the COGs in the MLTreeMap COG list file, and a list of output text precursors based on the analysis type.""" cog_list = Autovivify() text_of_analysis_type = Autovivify() alignment_set = args.reftree kind_of_cog = '' # F...
4c80ed3078af52afe20e44f568cacf06cbcbabd7
3,607,225
def _load_permissions_from_database(user): """Calculate permissions based on DB queries""" permissions = {} with benchmark("load_permissions > load default permissions"): load_default_permissions(permissions) with benchmark("load_permissions > load bootstrap admins"): load_bootstrap_admin(user, permi...
e9568d124eb8df73dbfc5d09223639ecca62bb5a
3,607,226
def get_valuation_method(item_code): """get valuation method from item or default""" val_method = frappe.db.get_value('Item', item_code, 'valuation_method') if not val_method: val_method = frappe.db.get_value(None, "valuation_method") or "FIFO" return val_method
974812dd4fbeb1aac28186347c8aadba5a103391
3,607,227
import os def write(solution, output_filename='', path='', skip_thermo=False, skip_transport=False ): """Writes Cantera solution object to Chemkin-format file. Parameters ---------- solution : cantera.Solution Model to be written output_filename : str, optional ...
a10e73efbdf2549a543d20e20f07e847ab37ee95
3,607,228
def find_layer(model, layer_class): """ Find all layers in model that are instances of layer_class """ layers = [] for layer in model.layers: if isinstance(layer, layer_class): layers.append(layer) elif hasattr(layer, "layers"): # search in nested layers ...
d240d916f26e087edb7ccef8006b91b9c539bd76
3,607,229
from aoikprojectstarter.mediator import main_wrap def main(args=None): """ Program main function. This function does three things: - Prepare `sys.path` so that program users do not need set up PYTHONPATH. - Check whether dependency packages have been installed. - Call the mediator module t...
f821f35781dd9d18a32eab0d7fb3ddc874ef572e
3,607,230
def create(customer: schema.CustomerCreate, db=Depends(get_db)): """ create a new customer a new customer is always active by default :param customer:the new customer to create :param db: database session (injected) :return: the new customer with is id """ customer_db = model.Customer(...
8ac398eaea5bb14a246d3bfc3e2c33a5c23c20e1
3,607,231
import os def pid(): """ Returns the pid of the rethinkdb server. """ db_pid = None if os.path.exists(conf.get('db_pid')): with open(conf.get('db_pid')) as fin: db_pid = int(fin.readline()) return db_pid
1c3b41e5f841b4d148472eaf90ec5f5022a3e2fc
3,607,232
from typing import Dict from typing import Any import logging def _search_dashboard(*, search_term: str, page_index: int, search_type: str) -> Dict[str, Any]: """ Call the search service endpoint and return matching results Search service logic defined here: https://github.com/lyft/amundsensearchlibra...
84472de88914696e8ff3fffe4d1687526b626a3a
3,607,233
def __bestMatch__(matches, # list negMass, # float pmz, # pandas.Series negRT, # float prt, # pandas.Series parameters # LFParameters ): # type: (...) -> int """Return the index of 'ma...
75650f8dddbae46066d37d829f5cbc30cf91eae8
3,607,234
def patch_goods(goods): """ Updates or creates a goods """ req = request.get_json() if goods in stock: for k, v in req.items(): stock[goods][k] = v res = make_response(jsonify({"message": "goods updated"}), 200) return res stock[goods] = req res = make_response(jsonify({"message": "goods created"}), 201) ...
3d6577b25b975e000961dd5748d2757379bec829
3,607,235
import importlib def connect(settings): """ Connect to a database. """ driver = importlib.import_module(settings.pop("driver", "sqlite3")) return driver.connect(**settings)
cd186b3210b1ec012539dfc4a5306834dc9bf058
3,607,236
def count_reads_per_sample(file): """ Count the reads for each sample from the original fasta file """ samples={} for line in catch_open(file): if line.startswith(">"): try: sample, read = line.replace(">","").split(SAMPLE_READ_DELIMITER) except ValueError: ...
114b1ff9a010b84d39600c32ea6fe5aa61941d42
3,607,237
def user_model(username): """Return a user model""" return { 'username': username, 'scope': 'basic', }
c629dbca8673eb740b1fddcfcddb588930cb1fa9
3,607,238
def check_norm_state(modules, train_state): """Check if norm layer is in correct train state.""" for mod in modules: if isinstance(mod, _BatchNorm): if mod.training != train_state: return False return True
82387d78a53c5435bed25da542fbef9a68d6a785
3,607,239
def getJ1939ProtocolDescription(protocol : int) -> str: """ Returns a description of the protocol selected with protocol arg. Feed the result of RP1210Config.getJ1939FormatsSupported() into this function to get a description of what the format means. Honestly, I don't see anyone ever using thi...
a52c48930d45c04f0570689620d2b01783f27e38
3,607,240
import json import subprocess def nvme_id_ctrl(device): """Identify controller.""" command = "sudo nvme id-ctrl {0} -o json".format(device) id_ctrl = json.loads( subprocess.run( command, shell=True, check=True, text=True, capture_output=True ).stdout ) return id_ctrl
40d739bb00b474cf27d0839fe421ec39a324c7ed
3,607,241
def parse_images(images): """ Parses list of available images into Image objects. Arguments: images : dictionary of images Returns: parsed_images : dictionary of parsed images """ parsed_images = {} for image_name, image_info in images.items(): name = image_info["Na...
e56651093f7f983bb3dfbe8d9ea6f890b5a969b6
3,607,242
def in_region(pos, regions): """Find whether a position is included in a region. Parameters ---------- pos : int DNA base position. regions : list of tuples List of (start, end) position integers. Returns ------- bool True if the position is within an of the reg...
07154584fe3fadf93f16bf858810e4484828eb31
3,607,243
def extract_products_as_tuple(dataset): """Return names of all products as a sorted tuple. Products are chosen using ``allocatable_production``.""" return tuple(sorted([exc['name'] for exc in allocatable_production(dataset)]))
60ef29347312931b1dc44789cda85e2e6246d7cf
3,607,244
import sys def _implementation_version(): """Return implementation version.""" return ''.join(map(str, sys.version_info[:2]))
ccc6150871b0efcf6cd9281c5297cd53483ab307
3,607,245
def _hue_process_transition_time(transition_seconds): """ Transition time is in 1/10th seconds and cannot exceed MAX_TRANSITION_TIME. """ # Max transition time for Hue is 900 seconds/15 minutes return min(9000, transition_seconds * 10)
69f822d2836fef91206e2845d6d3bbd7623c03fc
3,607,246
import base64 def add_tasks(taskq_service, task_dict): """ Allow readding of multiple tasks across multiple queues. The task_dict is a dictionary with tasks for each queue, keyed by queue name. Tasks themselves can be dicts like those received from GetTasks() or Task instances. :param tas...
a834bfb52da4a5602f10bd3bed223457e8d046c1
3,607,247
def SEQ2HP(seq, HP_dic, occ=[], nuc_type=[], T=0): """ Given sequence, dictionary of HP(e.g. {A-A: [HP], oct: [HP...HP],...}), occupancy(e.g. [1, 500 , 789]), nucleosome type at each occupancy(e.g. ['oct','tet','hex']), and temperature. Return the HPs associate with the given sequence. """ seqstep =...
026bf83ae472e92ed449cf6d4d53ba1afae3b941
3,607,248
def _get_observations(token, transmart_url, study, concept_path): """ Given full concept path (as returned from tm 1.2 rest-api /concepts) return dict of patient_id : value :param token: :param transmart_url: :param study: :param concept_path: :return: """ obs = {} conce...
32956aa2b7c7dd03dd053745e3e18e13a9f833c5
3,607,249
def _get_jitclass_for_dtype(dtype, upper): """ Get the correct jitclass of NbTriMatrixBase for the data type and triangle. """ if upper: return _UPPER_JITCLASS_BY_TYPE[dtype] else: return _LOWER_JITCLASS_BY_TYPE[dtype]
3446028aaf0553200c51196e717f06c2ac91abfc
3,607,250
def parseLibraryLogicData(data, srcFile="?"): """Parses the data of a library logic file.""" if len(data) < 9: printExit("Library logic file {} is missing required fields (len = {} < 9)".format(srcFile, len(data))) versionString = data[0]["MinimumRequiredVersion"] scheduleName = data[...
f9983d00252a88bfb7e3371450ac3879460da244
3,607,251
def get_catalog() -> dict: """Returns the catalog of to be tested algorithms, input and output. :return: **TODO: TBD** """ input_file_paths = get_input_file_paths() return { 'copy': [(input_file_paths[0], 'sha256:015d60fac720421198c39bc637e25435188085d83911e790e734fb2bfdc99032'), ...
34282db296dd3d65805a02cd48abd7924e116cb2
3,607,252
def _add_replication(bucket_name: str, study_id: str): """ Configures a second bucket with `-dr` suffix and replicates the primary bucket to it. Adds a lifecycle policy to the dr bucket to immediately roll data into glacier for cold storage """ if not settings.FEAT_STUDY_BUCKETS_REPLICATION_...
afbb5e7a9490906988dc5115eb3b59b54f2bd98c
3,607,253
def main_top(): """ Present the top menu page """ return render_template("main.html")
e0ca4bc2e89cc9e4aab6c1ffc3ffcfc51cdbc8af
3,607,254
def extract_kpt_vectors_dense(tensor, kpts_t): """ Dense version of get_entries. :param tensor: Tensor to extract from [b, c, h, w] :param kpts_t: Tensor with indexes (x, y) in channels as [b, 2, h, w] :return: Tensor entries as [b, c, h, w] """ b, c, h, w = tensor.shape kpts = kpts_t.v...
9c62e13e0373ea91bed4b9d8bbcaabe9b1164f04
3,607,255
def bow(s: np.ndarray) -> str: """ Converts array to bag of words string (this is how we represent a sparse state into a pandas table). @param s: word counts over vocabulary @return: string representation """ i, = np.where(s > 0) return ':'.join(map(str, i))
4389b86bfd047753939a5300ca567dee6fec350b
3,607,256
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
5b2dc4ee5e35ce06094c658f3555b251226821c9
3,607,257
def main(): """Does the job""" keep = True photos = request_photos() page = 1 t = False while keep is True: p = next(photos, False) if p is False: photos = request_photos(page + 1) continue trial = Photo.objects(flickr=p["id"]).first() p...
428dba0ea0b1e52d4f63e2a9adff9a3d583ca95d
3,607,258
def length_average_f(x_arr, f_arr, Lx, dx=0): """ Take length average of f(x) with respect to x (from x[0] to x[-1]). Numerical integration is performed using trapezoidal rule. """ Nx = size(f_arr) if dx>0: return (dx/Lx)*(sum(f_arr) - 0.5*(f_arr[0] + f_arr[-1])) else: re = 0. ...
086a50259bb762b0023c7aaaefa68e159d72a27b
3,607,259
import re def re_sub_replace(pattern,string,repace_symbols=('-','_'),group_name=1): """ 当re.sub(pattern,repl,string)内置的repl = "g<1>" 不能满足替换需求的时候, 比如需要将group目标内的文字中的某个符号替换掉, 使用的时候要注意替换代码内的sub replace符号 :param pattern : re pattern :param string : original string """ def replace_match(match...
7a6b2f27ce73f6c8b316ab424362eb8383fff273
3,607,260
def generate_hgvs(prefix: str = "c") -> str: """Generates a random hgvs string from a small sample.""" if prefix == "p": # Subset of 3-letter codes, chosen at random. amino_acids = [ "Ala", "Leu", "Gly", "Val", "Tyr", "Met",...
3a18afbe5687d1566d9994866771ae8b91367460
3,607,261
import six def zero_lpad(number, length): """ Fill 0 on the left of number :param number: number to be padded :param length: length of result string :return: """ if six.PY3: return str(number).ljust(length, '0') return '{number:0>{length}}'.format(number=number, length=length)
d8682249a7094e2c0de9ff015df3c1c7525b7427
3,607,262
import logging import sys def get_handler(): """ Gets the handler to manage the output of the logger, default: stdout """ handler = logging.StreamHandler(sys.stdout) # TODO: read from a config file, or env var, and override the default formatter. # IE: logging.FileHandler(filename='/path/to/fi...
99e3972433665a4c91b92e3418f0f233771971ab
3,607,263
import sys def _normalize_docstring(docstring): """Normalizes the docstring. Replaces tabs with spaces, removes leading and trailing blanks lines, and removes any indentation. Copied from PEP-257: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation Args: docstri...
1f362835e59d32c883a373e4c49ddb10729e55eb
3,607,264
def _len_guards(M: int) -> bool: """Handle small or incorrect window lengths""" if int(M) != M or M < 0: raise ValueError('Window length M must be a non-negative integer') return M <= 1
1a181779821570edea6eb08739fd9065de445e80
3,607,265
def get_files(dataset_name): """Retrieve list of files in `dataset_name`. Arguments: - `dataset_name`: name of the dataset """ data = das_client(("file dataset={0:s} system=dbs3 detail=True | "+ "grep file.name, file.nevents > 0").format(dataset_name), ...
55c389b28b488e3d1b221fd0156463fbf7b05752
3,607,266
def line0(x,a): """ Straight line through origin: a*x Parameters ---------- x : float or array_like of floats independent variable a : float first parameter Returns ------- float function value(s) """ return a*x
247a9ac56418ec34089bab0d9a914c69eb216f31
3,607,267
def score_nxgraphs(nx_graphs, truth, verbose=False): """nx_graphs: a list of networkx graphs, with node feature hit_id each graph is a track""" total_tracks = len(nx_graphs) new_df = graphs_to_df(nx_graphs) matched = truth.merge(new_df, on='hit_id', how='inner') tot_truth_weight = np.sum(matche...
c5f67bbd7cac7e023cada56f02e7601762a64259
3,607,268
import os def load_lena(): """Function to read lena image from resources directory. Returns: Loaded lena image as uint8 NumPy array. """ dir_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources') lena_path = os.path.join(dir_path, 'lena.jpeg') return cv2.im...
3fb6e648fee775a53390ebb91b5bfa1596aabd46
3,607,269
import sys def blur_filter(img_name, filter_type, kernel_size=3): """ ぼかしフィルタ Parameters ---------- img_name : numpy.ndarray 入力画像 filter_type : str フィルタのタイプ average, gauss kernel_size : int カーネルのサイズ Return ------- blur_img : numpy.ndarray ...
bd6cb347afd311311249100b1c28f4bef4b4bf9b
3,607,270
from app.main import main from app.auth import auth def create_app(config_name): """ creates an instances of the application and passes the config name, i.e development or production, the will then pick the environments from the configuration classes in config """ app = Flask(__name__) ...
5e44acddb66fac44dc03da49ec695de161e3b5c2
3,607,271
def pushCategory(category): """Used to insert a new category to the table Returns the ID of the pushed Category ----FOR INTERNAL USE ONLY----""" queryString="INSERT INTO Categories(Category_Name) VALUES('%s')" % category cur=executeQueryWithHandling(queryString) print "%s categeory pushed!"...
d2a4edbf48e68056ceedfc4b2d1caec41d718cdd
3,607,272
import os def drawbot(): """Shows drawbot status and functions.""" form = PgUploadForm() if form.validate_on_submit(): file = request.files.get('file') if file: filename = secure_filename(form.file.data.filename) file.save(os.path.join(current_app.config['APP_DIR'],...
27f341887521450c4642b0043fe6532d1505f9d9
3,607,273
import os def load_data(datapath=None, survey="LSMS", country="uganda", standardize=True, permute=False, seed=42): """Load satellite imagery features and survey targets. Args: datapath : str or None (default: None) country ...
0f59b8daae5d6fd0d6080822d396b4218fb0d02f
3,607,274
def neutralize(row_vectors: pd.DataFrame) -> pd.DataFrame: """ Orthogonally project row vectors onto subspace orthogonal to all ones. (In other words, we demean each row). If the rows of `row_vectors` represent dollar positions, then this operation will dollar neutralize each row. :param row_...
2ab08d21929c6e9c38f7b3d261f2e3be8e4a191a
3,607,275
import os import sys import json def main(args): """ Main entry point for program :param args: command line arguments usually :py:const:`sys.argv` :return: 0 for success otherwise failure :rtype: int """ desc = """ Running gene enrichment against Integrated Query Takes fi...
32eec64154f873027ace063300b6415ff493acc1
3,607,276
def create_validator(contract, force_optional=False): """ Factory pattern for creating custom validator in the style of WTForms. This function takes the contract needed to validate against and returns a ``Form`` object that can perform the validation according to validation rules in the contract. ...
ca5208ad16e5d52aab58beedf514018eef6edc34
3,607,277
def get_state(obj): """Return a State object given an object. Useful for testing.""" str = dumps(obj) return StateUnpickler(BytesIO(str)).load()
ca690595810feb313eacd2c7c4d7ffc100214b4a
3,607,278
import os import shlex def read(fname): """ Read and process a RESPY initialization file. """ # Check input assert os.path.exists(fname) # Initialization dict_, group = {}, None with open(fname) as in_file: for line in in_file.readlines(): # Split line l...
0775987bbc2e34fb9d545a00af35513749b80ecc
3,607,279
def median(image): """The median pixel value""" return np.median(image)
16c50e1d3869847136365a2f654bdd14af4412dc
3,607,280
def list_ecriture_tag(db, ecriture_id=None): """ List ecriture for tag """ filter = {} filter = App.get_filter(request.query.filter) sort = App.get_sort(request.query.sort) tags = db.query(EcritureTag.id, Tag.nom, Tag.valeur, EcritureTag....
adc470a24fb56715b4e500c32b325ac19e66f8bf
3,607,281
def wishlist(request, template="shop/wishlist.html", form_class=AddProductForm, extra_context=None): """ Display the wishlist and handle removing items from the wishlist and adding them to the cart. """ if not settings.SHOP_USE_WISHLIST: raise Http404 skus = request.wishli...
9fa770098227d26cb75a06a5691284b6d9cb3816
3,607,282
import logging def _GolintFile(path, _, debug): """Returns result of running golint on |path|.""" # Try using golint if it exists. try: cmd = ['golint', '-set_exit_status', path] return _LinterRunCommand(cmd, debug) except cros_build_lib.RunCommandError: logging.notice('Install golint for addition...
25d8d21ea6281c232e3b7c37f348e77d20ffb42e
3,607,283
def classic_mode_cpcs(request, hmc_session): # noqa: F811 # pylint: disable=redefined-outer-name,unused-argument """ Pytest fixture representing the set of CPCs in classic mode, from the set of all CPCs defined in the HMC definition file. Because the `hmc_session` parameter of this fixture is agai...
2ba0496573463f8b554e1ecbe57876e63ffce9da
3,607,284
import json def to_json(msg): """Pretty-print a dict as a JSON string Use Unicode and 2-space indents. """ return json.dumps(msg, ensure_ascii=False, indent=2)
e10bf04ce54482f1892aa7a7452a7004024ea6d4
3,607,285
def get_sorted_index(array, reverse_order=False): """ get the order of the index of a one dimensions array @reverse_order: True, large->small False, small->large """ dtype = [('index', 'i4'), ('value', 'f8')] data = np.array([(i, array[i]) for i in range(len(array))], dtype ...
a4690583a7973f08873f086a126fa859a6514a4a
3,607,286
def show_saved_playlist(): """ Displays list of saved playlists """ playlists = crud.get_saved_playlists(crud.get_user_by_email(session['EMAIL']).user_id) playlist_ids = crud.get_user_playlist_ids(crud.get_user_by_email(session['EMAIL']).user_id) playlists_and_playlist_ids = helper.create_dict_playlist...
59945734789c5feeb3c3080562b2aee27b716d8e
3,607,287
def get_scores(events): """ {game_id : quarter, secs, a_pts, h_pts, status} """ ids = u.get_ids(events) links = [bm.BOV_SCORES_URL + game_id for game_id in ids] raw = g.reqs_json(links) scores_dict = {g_id: score(j) for g_id, j in raw.items()} return scores_dict
8b0dbda56f275302488f4062a0ece44bf9e49343
3,607,288
def read_style_dict(cfg): """Return dict of styles read from config dict. Sections in style file are set as top-level keys of the returned dict. """ style = {} # update all settings with any global settings. if 'global' in cfg: cfg_global = cfg.pop('global') for rc_dict in style...
cbbbb4f68e71fa82f028cc512698184a45c88cc8
3,607,289
import math import logging import time def wait_on_app(port): """ Waits for the application hosted on this machine, on the given port, to respond to HTTP requests. Args: port: Port where app is hosted on the local machine Returns: True on success, False otherwise """ retries = math.ceil(START...
04e6150fe4ff5e889df79367098a9ef9b3aaf3cd
3,607,290
def get_min_and_max_velocity_values(velocities) : """ Повертає min та max значення швидкості у вигляді кортежу """ return (velocities.min(), velocities.max())
f9a2995bec07d129c34581d55a070a4004b8436c
3,607,291
import nipype.interfaces.utility as util def process_segment_map(wf_name, use_ants, use_priors, use_threshold, use_erosion): """This is a sub workflow used inside segmentation workflow to process probability maps o...
1c50f7986de367ff56b147107be456ba571a959d
3,607,292
from typing import Iterable def get_needed_vars(*entries: str) -> Iterable[str]: """ Parses all used variables from a string """ results = set() for entry in entries: variables = VARIABLE_IDENTIFIER.findall(entry) # will return tuples: (with surrounding %s, without) results.update([match[...
725414ad843da47cf76daf35606cf95cc694db1f
3,607,293
def shape(a): """the shape of a matrix""" _rows = len(a) _cols = len(a[0]) if a else 0 return _rows, _cols
79c32a5f09ecbea4849929a3f6f627068198953f
3,607,294
def read_txt_file(file, is_list): """ @summary - read from a test file. @description - method will read from a text file and either return it as a string or a list. If is_list is True the delimiter that will split the text file apart is ';' and '...
cad2d80c107f165cb55b23cb71f88c228146e475
3,607,295
import os import json import tqdm def read_examples_from_file(data_dir, mode, task_type): """Read a SQuAD json file into a list of SquadExample.""" assert mode in ['train', 'dev'] if task_type == "squad2": input_file = os.path.join(data_dir, f"{mode}-v2.0.json") elif task_type=="squad": ...
c8d319ee0464744f7edadde4a6ec7dd95af965d5
3,607,296
def compare_dictionaries(dict1, dict2): """ Recursively compare two dictionaries. :return: True if exactly the same, False if not """ if len(dict1) != len(dict2): return False for key in dict1: try: val1, val2 = dict1[key], dict2[key] if val1 != val2: #...
c700874e6a1f7c0911607675570a750279c47616
3,607,297
def Table(*args, **kw): """A schema.Table wrapper/hook for dialect-specific tweaks.""" test_opts = {k: kw.pop(k) for k in list(kw) if k.startswith("test_")} kw.update(table_options) if exclusions.against(config._current, "mysql"): if ( "mysql_engine" not in kw and "mys...
70928cfcb77bd21dda090043b657eded4fe0b00a
3,607,298
import logging def deploy_model(bigquery_client: bigquery.Client, model_id: str, machine_type: str = 'n1-standard-2', location: str = 'europe-west4') -> aiplatform.Model: """Creates an endpoint and deploys Vertex AI Tabular AutoML model. Args: bigquery_clien...
e0fbc60875b32fada33ae3a35a072cd047f6a371
3,607,299