content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def radial_integration(IM, radial_ranges=None): """ Intensity variation in the angular coordinate. This function is the :math:`\\theta`-coordinate complement to :func:`abel.tools.vmi.angular_integration` Evaluates intensity vs angle for defined radial ranges. Determines the anisotropy parameter fo...
72fe848731b7386f43820ce71d2ba6153d24b129
3,623,026
import warnings def CytOpT(xSource, xTarget, labSource, labTarget=None, thetaTrue=None, method=None, eps=1e-04, nIter=4000, power=0.99, stepGrad=10, step=5, lbd=1e-04, nItGrad=10000, nItSto=10, cont=True, monitoring=False, minMaxScaler=True, thresholding=True): """ CytOpT algorith...
f0047e30f682a5062ddfaf8409941475e1bf2fba
3,623,027
from datetime import datetime import re def get_sessions(subj, date=None, one=None): """ Download and load in training data for a specfied subject. If a date is given it will load data from the three (or as many are available) previous sessions up to the specified date, if not it will load data from t...
919e514d2aa23292352c013b82fc431dd6370d5c
3,623,028
def crossproduct(first, other=FreeCAD.Vector(0,0,1)): """crossproduct(Vector,Vector) - returns the cross product of both vectors. If only one is specified, cross product is made with vertical axis, thus returning its perpendicular in XY plane""" if isinstance(first,FreeCAD.Vector) and isinstance(other,Free...
0d74566a911a25d3e955e3c81116a3a97e8518b6
3,623,029
import yaml def read_yaml(yaml_file): """Read YAML file and handle errors.""" try: with open(yaml_file) as f: data = yaml.load(f, Loader=yaml.FullLoader) except yaml.scanner.ScannerError as e: raise util.SparvErrorMessage("An error occurred while reading the configuration file:...
77f71f5bc455d748a70d2522971ba3d396fe0155
3,623,030
def editProfileView(request): """Pulls up an editable profile, with previously inputted values placed already in the form. """ profile_context = {} form = EditProfile() submitted = False if 'username' in request.session and request.method == 'POST': form = EditProfile(request.POST) ...
8878cd5934adaf90545d7847fdd1d95418dd7a0e
3,623,031
def long_short_backtest( pred, topk=50, deal_price=None, shift=1, open_cost=0, close_cost=0, trade_unit=None, limit_threshold=None, min_cost=5, subscribe_fields=[], extract_codes=False, ): """ A backtest for long-short strategy :param pred: The trading sig...
9bea632a39f88e85ae1f6cd0a09649dbdd64673d
3,623,032
import torch def opt_v1(matrix: torch.Tensor, ternary: bool, skip: int = 1) -> torch.Tensor: # type: ignore """ Implement the algorithm to find v1 for least squares 2-bit and ternary algorithm. Args: matrix: A 2D tensor ternary: whether to do ternary optimization skip: increment ...
cb76283dfdae7c7415165f48c387d85d94d66c39
3,623,034
def calculate_bmi(weight, height): """ Calculates BMI given the weight and height as float """ bmi = (weight / (height * height)) * 703.0 return bmi
8495b11598e50516dca80965d5063df92aa78f40
3,623,035
def _jss_shutdown(data): """Return a formatted Slack message for the 'JSSShutdown' event. :param dict data: The ``event`` data from a Jamf Pro webhook. :returns: Formatted Slack message. :rtype: dict """ text = 'The Jamf Pro web app *{}* has initiated a shutdown.'.format( data['jssUrl'...
bdf63a604a1bed16a5991182dc6009654a7cc0a0
3,623,036
import time import json def load_from_json(json_filename: str) -> dict: """ Loads data from file of filetype .json and returns the data as a chunk pack (dict), containing the items from the json file. When loading data from the json file instead of csv, the chunk pack is simply a dict of the j...
3c7a715b51b638394580084ed6202b89b3482f52
3,623,037
def get_table_countrydata(regressors, specification, data): """ Can generate the regression table 5 Inputs: - regressors: array of column names - specification: dictionary with column names - data: data frame (regiondata) Returns: container (pandas data frame with regres...
946b33c6ddc8c438998f3ada8293ab1eb1694c1a
3,623,038
import re def get_task_factor(task_name, overrides, override_type, factor): """Check for task override and return factor.""" for task_override in overrides.get(override_type, []): if re.compile(task_override["task"]).match(task_name): return task_override["factor"] return factor
eb58f291c5a21a9974b9f7d4bce739bdc99d5f89
3,623,039
from typing import Callable from typing import Any from typing import List def map_list(func: Callable[[Any], Any]=default_function(1)): """Applies a function to every element of a list and returns the resulting list. :param Callable func: The function to apply. :input List[Any] data: The input list....
c5d0c31c578bd107e807f083c0c346fde6c9f1ef
3,623,040
def argstr(arg): # pragma: no cover """ Return string representation of a function argument. :param object arg: Argument object. Differs between Python versions. :return: String name of argument. """ if isinstance(arg, str): return arg if 'id' in arg._fields: return arg.id ...
565349fc4a1fb9b28e8333a44893925cea9e72d9
3,623,041
def example_alt_alleles_indices(example): """Gets an iterable of the alt allele indices in example.""" return deepvariant_pb2.CallVariantsOutput.AltAlleleIndices.FromString( example.features.feature['alt_allele_indices/encoded'] .bytes_list.value[0]).indices
d8f363f071f3d7ce868528764b25926fc08267e9
3,623,042
def task_tweet_todays_job(): """ Tweets latest jobs from Indeed. """ """ from hub.models import IndeedJob consumer_key = settings.TWITTER_CONSUMER_KEY consumer_secret = settings.TWITTER_CONSUMER_SECRET access_token = settings.TWITTER_ACCESS_TOKEN access_token_secret = settings.TWITT...
12e42f746fa119f33b587261a425aedac0c6def8
3,623,043
import warnings def variable_step_roots(x0, func, dxmax=1, verbosity=False, root_niter_max_=1000, root_tolerance=1e-6): """ """ itera = True dx = dxmax factor = 1 residual = func(x0) xi = x0 + dx ii = 1 while itera: residual0 = residual residual = func(xi) ...
60635771a379d7b0ccf3fca7e2341322dd65ca35
3,623,044
def get_silhouette(model): """ Get silhouette score from model :param model: Topic_Model object :return: silhouette score """ if model.method == 'LDA': return #LDA dosen't have a silhouette score lbs = model.cluster_model.labels_ vec = model.vec[model.method] return silhouett...
b66d765c2345cff21c11c9bc27b2118ff929b071
3,623,046
def num_zeros_init(num): """ Counts the number of zeros at the beginning of the number 'num'. """ iszero = True num_zeros = 0 i = 0 while iszero == True and (i != len(num)-1): if num[i] == "0": num_zeros += 1 elif num[i] != ...
42b58491e003269c0b51160dd20a777a9dc2198d
3,623,047
import inspect def getargspec(callable_): """ Return an Argspec for any callable object :param callable_: a callable object :type callable_: ``Callable`` :return: argspec for the callable :rtype: ``ArgSpec`` """ if not callable(callable_): raise ValueError("{} is not callable...
5f242a545e983e931958bdead4eff179d654c110
3,623,048
import numpy def pmat76(date1, date2): """ Wrapper for ERFA function ``eraPmat76``. Parameters ---------- date1 : double array date2 : double array Returns ------- rmatp : double array Notes ----- The ERFA documentation is below. - - - - - - - - - - e r a P...
d95a0368a0fba9d0279d7f7ee9656afca5cb9eab
3,623,049
def getresulthandle(whichresult, options=None): """get the filehandle of the result""" filepath = options2filename(whichresult, options=options) if whichresult in ("htm", "sql"): return getfilehandle(filepath, mode="rb") else: return getfilehandle(filepath)
39f43dc6f7ee7d903fd8d6a71be53c0522dd98ce
3,623,050
def downsample(img, scale, border='REFLECT'): """Bicubical downsample via **CONV2D**. Using PIL's kernel. Args: img: a tf tensor of 2/3/4-D. scale: n or 1/n. `n` must be integer >= 2. border: padding mode. Recommend to 'REFLECT'. """ kernel, s = weights_downsample(scale) if s == 1: return img...
8f41a85147f8158d915a6deb9f66d56eb1894857
3,623,051
def getDistance(sensor): """Return the distance of an obstacle for a sensor.""" # Special case, when the sensor doesn't detect anything, we use an # infinite distance. if sensor.getValue() == 0: return float("inf") return 5.0 * (1.0 - sensor.getValue() / 1024.0)
68ff9e0c8c4dd7687e328d3b9c4634677cfe25cd
3,623,052
def fit_svmrbf(X_train, y_train, seed=1): """ Fit an SVM-RBF with pre-selected hyperparameters. """ clf = SVC(C=10, gamma=0.01, kernel="rbf", probability=True, random_state=seed) clf.fit(X_train, y_train) return clf
aec52c95b327c304161238cc01b965e9f4d00b79
3,623,053
def test_path_and_query_parameters( arg1, arg2, ): """ Use same arg name as the one in path for receiving path args For those args which names not matched path arg names, will be parsed as query parameter ```python from django_mini_fastapi import Path @api.get('/test_path_and_query_par...
72823f5fa66065171c36329f6b05e61a710fa065
3,623,054
def get_residue_count(array): """ Get the amount of residues in an atom array (stack). The count is determined from the `res_id` and `chain_id` annotation. Each time the residue ID or chain ID changes, the count is incremented. Special rules apply to hetero residues. Parameters ---...
ca92531cdae9353a7902a04f4aa9a5e72b6f0248
3,623,055
def build_output_actions(acl_table, output_dict): """Implement actions to alter packet/output.""" output_actions = [] output_port = None ofmsgs = [] # rewrite any VLAN headers first always vlan_actions = rewrite_vlan(acl_table, output_dict) if vlan_actions: output_actions.extend(vlan...
7c4faf3bcafe1570e49279aa2906603901732efc
3,623,056
def _bond_capacities(rgr): """ the number of electron pairs available for further pi-bonding, by bond """ atm_unsat_vlc_dct = _atom_unsaturated_valences(rgr) def _pi_capacities(bnd_key): return min(map(atm_unsat_vlc_dct.__getitem__, bnd_key)) bnd_keys = list(_bond_keys(rgr)) bnd_caps =...
1a8976ecea20c698d26b6bfaea035fde8c979785
3,623,057
import re def GENERIC_MAX(segment_pattern, lenv=None, renv=None): """Takes the regex pattern for segments being examined for deletion, and a pair of lists indicating their deletion environment,, and returns a function that will count how many times a segment of that class is deleted from an input to a...
d729cb96850397a36b687d2b43c487b3670f7c56
3,623,058
def find_group_delay(attrs_dict): """Determine group delay from tables Args: attrs_dict (dict): dictionary of topspin acquisition parameters Returns: float: Group delay. Number of points FID is shifted by DSP. The ceiling of this number (group delay rounded up) is the number of points shou...
fa8fffaa78f95ef8cff2733cf819a1212f714f13
3,623,059
from typing import List from typing import Tuple def decompositions_bis(n : int) -> List[Tuple[int, int, int]]: """Précondition : n >= 0 Retourne la liste des triangles sur l'intervalle [1;n].""" return [(i, j, i+j) for i in range(1, n+1) for j in range(1, n+1) if i+j<=n]
85c185be6d1cf84773c067b16ac2d11d69de5766
3,623,060
import logging import time def check_subs(client): """ Checks that all Subscriptions have been received""" wcount = 0 while wcount < 10: for t in client.topic_ack: wcount += 1 if t[2] == 0: logging.info("subscription to " + str(t[0]) + " not acknowledged") ...
95892066b9da2a530a28f06a7e5804fdee7e65d0
3,623,061
def preprocess(vocab, data_fp): """ Preprocess data """ orig = [] prep = [] # Read data with open(data_fp, "r") as data_file: for cnt, word in enumerate(data_file): # End of sentence if not word.split(): orig.append(word.strip()) ...
456b4771d08f43ff87e826afcdcda2e6fef9f17b
3,623,062
from .interfaces import create_port as new_create_port def create_port(port_data, verify_port=True, conn=None): """ :param port_data: <dict> dict matching Port() :param verify_port: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert ...
28324bd86f89fc4f27cda06a7fc59c156b0fd29d
3,623,063
def read_nrattle_ctl(fpath): """Read an nrattle control file.""" lines = list(fpath.open()) lines = [line for line in lines if line[0] != "!"] d = {k: lines.pop(0) for k in ["revision", "prefix"]} d["freq_count"], d["freq_max"] = split_line(lines.pop(0), [int, float]) d["out_depth"] = split_lin...
01032c478db2004b32efe95dedeb8e4ab31bba7f
3,623,065
def paragraphs(text): """Split a given text into paragraphs. Args: text (str) Returns: iterator """ return filter( lambda line: len(unspace(line)) > 0, text.split("\n"))
585154156840d654a92731f40488130e77ff35a8
3,623,066
def init_multicomponent_source( sky_coord, frame, observations, obs_idx=0, flux_percentiles=None, thresh=1.0, symmetric=True, monotonic=True, ): """Initialize multiple components See `MultiComponentSource` for a description of the parameters """ try: iter(observat...
11673e3a2060a0938bb98f4bcf2ab8151aab3dad
3,623,067
def get_document(args): """ Метод для получения данных о документах :param args: :return: """ provider = Provider() answer = provider.get_document(args) return answer
b5a0ba8f12b2a1c0f7c1b1418074544a768d4e71
3,623,068
def convert_not_constraint(converter: 'pcc.ConstraintConverter', constraint: pamlt.Not): """ Convert a paml_time.NotConstraint into the pysmt equivalent """ clause = converter.convert_constraint(constraint.constrained_elements) return pysmt.shortcuts.Not(clause)
dfb3c71fed343acfb00daadee5323d2dd6a7df30
3,623,069
def authenticate(request): """ GET: Will return the JSON authenticated user if any, otherwise the login HTML form. POST: Same, but will try to authenticate the user with the provided data. """ return ajax_authenticate(request, from_api=True)
3b3b26132e8ef30a23c78e1edf92a6fa81b89a19
3,623,070
from typing import List def parse_jndi_proto_and_path(jndi: str, jndi_parts: JNDIParts) -> JNDIParts: """Split JNDI string into components.""" try: colon_split = jndi.split(":") protocol: str = colon_split[1] slash_split: List[str] = jndi.split("/") host_port = slash_split[2] ...
1b34b7a78ac1bceb977eff70ac0e80d08af12704
3,623,071
def vap_volume(temp,pres): """Calculate water vapour specific volume. Calculate the specific volume of water vapour using the IAPWS-97 formulation. :arg float temp: Temperature in K. :arg float pres: Pressure in Pa. :returns: Specific volume in m3/kg. """ v = vap_g(0,1,temp,pre...
4060562928dc8c57794da5b935df3fba9722b982
3,623,073
def repair_rate(f, params): """ Default unscaled repair rate (no Gamma0). Uses gamman = params[1], R = params[2] """ return np.exp(-params[1]*f)/params[2]
2b1fcaffffb71da6d77afac8071cceee53cb7d9a
3,623,074
def Get_Items(filename): """Convert plain text to class string""" L = [] with open(filename, 'r') as file: items = file.readlines() for line in items: L.append(line[:-1]) return L
8b579dcfb8df21de68a05a8dad4d7aff06951f64
3,623,077
import math def circles_intersection(x_a, y_a, r_a, x_b, y_b, r_b): """ Returns the point of intersection of two circkes :param x_a: x coordinate of the center of first circle :param y_a: y coordinate of the center of first circle :param r_a: radius of first circle :param x_b: x coordinate of ...
dc504bbe970c83bf1caf7727613ecaa44c1c818e
3,623,079
import re def doxy_coverage_badge(filepath): """...""" with open(filepath) as f: linelist = f.readlines() text = "doxy-coverage" for l in reversed(linelist): match = re.match(DOXY_COVERAGE_PATTERN, l) if match: value = int(match.group('value')) break ...
1084ee0abc0662f27831d31f8c0993542b0d5231
3,623,080
def readShapefileTable(shapefile): """ read in the datatable captured within the shapefile properties shapefile: (dir) a path to the ESRI .shp shapefile """ #cent_df = gpd.read_file(shapefile) shp = fiona.open(shapefile) centroid = [eachpol['properties'] for eachpol in shp] cent_df ...
f0938af7e70b47d39918b62d30939f17edf194cc
3,623,081
def missing_translation(lang, message=None): """Return an explanation if a language is not supported at all or if the translation is missing, to be used as a message for a ValuError which is raised in that case. """ if lang not in SUPPORTED: return 'Language {0!r} not supported!'.format(lang...
c31b59d39eb5228bd82a6353cd1c9e8110712dd8
3,623,082
def get_grade_map(): """ Defines a mapping of Fontainebleau grades to integer values """ grade_map = { '6B': 0, # V4 '6B+': 0, # V4 '6C': 1, # V5 '6C+': 1, # V5 '7A': 2, # V6 '7A+': 3, # V7 '7B': 4, # V8 '7B+': 4, # V8 '7C': 5, ...
1137d7c21b18556ce69db635314c968024b3394b
3,623,083
def gaussian_kl_divergence(mean, ln_var, reduce='sum'): """Computes the KL-divergence of Gaussian variables from the standard one. Given two variable ``mean`` representing :math:`\\mu` and ``ln_var`` representing :math:`\\log(\\sigma^2)`, this function calculates the KL-divergence in elementwise manner...
e90ba96ce210464d5b44f13a5a92557f21c81e6b
3,623,084
def conflict_error(e): """Flask error handler for Conflict exceptions""" return json_error(409, "Conflict", str(e))
357eab6bd5b6a589e5731a98122255b5f88b5241
3,623,085
def get_topics(input_file, judgements): """ Reads topics in the NTCIR-10 Math, NTCIR-11 Math-2, and NTCIR-12 MathIR format from an XML file. Note ---- Topics are returneed in the order in which they appear in the XML file. Parameters ---------- input_file : Path The path to an ...
12e4378ff22194b229164e0a4e4762102bcc30fe
3,623,086
def get_target_oligo_2(left_pos, right_pos, genome, homology = 90, attB_dir = '+', attB_fwd_seq = 'ggcttgtcgacgacggcggtctccgtcgtcaggatcat', attB_lock = False, verbose = False): """ Given a set of parameters, get an ORBIT oligo that targets the lagging strand. Left and right positions are absolute genomic c...
a80efa2a59f393d7125b313a0e447464afa7e135
3,623,087
import profile def signup(request): """ Create a new user with the given credentials. GET parameters: html turn on the HTML version of the API POST parameters (JSON): username: user's name email: user's e-mail password: ...
62112679e75ae9b552d4941a2690c034059c9c74
3,623,088
def preprocess_observation(observation_dict, amt_nodes=21, amt_features=9): """Preprocesses an observation dictionary to feature- and adjacency matrices. :param observation_dict: The observation dictionary returned by the "TreeObsForRailEnv"- observation builder. :param amt_nod...
16921cecf13ebf689ab75e6beed994509d08c7c3
3,623,089
import hashlib def init_aes(shared_secret, nonce): """ Initialize AES instance :param hex shared_secret: Shared Secret to use as encryption key :param int nonce: Random nonce :return: AES instance :rtype: AES """ " Shared Secret " ss = hashlib.sha512(unhexlify(shared_se...
6211975ff7e8daaf275988fc95b6f8a92a0e5d29
3,623,090
import time import urllib import json def getHackerNewsItem(item_id): """Get an 'item' as specified in the HackerNews v0 API.""" time.sleep(0.2) item_json_link = "https://hacker-news.firebaseio.com/v0/item/" + item_id + ".json" try: with urllib.request.urlopen(item_json_link) as item_json: ...
76039e6c30c0aafbea6b91a25da07bd8841206c9
3,623,092
def fix_line(line): """ Apply all the fixes to one line from the DIFF.tsv file """ line = line.strip() if line.startswith('#LOC'): return "#LOC\tSVTYPE\tDIFF\tFIXED" loc, svtype, instr_orig = line.split('\t') instructions = parse_instr_set(instr_orig, loc) if upper(svtype) == 'A...
3d925bfe1f09c6281b68c7b8228240f9b2e3d4f5
3,623,093
from typing import Optional def get_spot_fleet(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpotFleetResult: """ Resource Type definition for AWS::EC2::SpotFleet """ __args__ = dict() __args__['id'] = id if opts is None: opts ...
0c5131070cf5c0b77ff0e303c8ba96902625b62b
3,623,094
def factory_invoice_reference(invoice_id: int, invoice_number: str = '10021'): """Return Factory.""" return InvoiceReference(invoice_id=invoice_id, status_code=InvoiceReferenceStatus.ACTIVE.value, invoice_number=invoice_number).save()
c7a0ab1173802faa9c1de1b6fd0efe9fe3a24d6a
3,623,095
import glob import logging def read_folder(folder): """ Parameters ---------- folder : string Path to a folde with *.inkml files. Returns ------- list : Objects of the type HandwrittenData """ # Core Library modules recordings = [] for filename in natsorte...
bf3c28887d789f5e547a6bcd26c0709a32aa0e26
3,623,096
def trainingdb_show_training(request, item_container, veranst_iq_id): """ zeigt Einzelveranstaltung der Fortbildungsdatenbank """ item = get_veranstaltung_by_iq_id(veranst_iq_id) if item == None: return show_error(request, item_container, _('Falsche Veranstaltungsnummer'), _(u'<p>Zu...
849447fd6da0ba312d5830f401ebfd732213cc12
3,623,097
def merge_frames(header, frames): """ Merge frames into original lengths Examples -------- >>> merge_frames({'lengths': [3, 3]}, [b'123456']) [b'123', b'456'] >>> merge_frames({'lengths': [6]}, [b'123', b'456']) [b'123456'] """ lengths = list(header['lengths']) if not frames: ...
bb78647b2a6bb3f94525a61ebad07ae0abc543c9
3,623,098
import time def populate_last_id(conn_str, search_path, id_name): """Populate study id maps from dcc_pedsnet. :param str conn_str: database connection string :param str search_path: PostgreSQL schema search path :param str id_name: name of the id :returns: Tru...
f73b72e6d29c861541ab07f2e328fd843aa5eb31
3,623,099
def memcached(func): """Use memcached to cache the results of a function. Must have the memcached server running. """ def wrapper(key, *args, **kwargs): value = memcached_client().get(key) if value is None: value = func(key, *args, **kwargs) memcached_client().s...
2723d8dbd06ad0bd73ab6bb76f24fdad4f8b91d3
3,623,101
def __virtual__(): """ Only works on Windows systems with PyWin32 installed """ if not salt.utils.platform.is_windows(): return False, "Module win_service: module only works on Windows." if not HAS_WIN32_MODS: return False, "Module win_service: failed to load win32 modules" ret...
121b5124219eb6a604598e57c21f13d7e7f866ae
3,623,102
from bs4 import BeautifulSoup import re def parse_html(mail): """ Parser for HTML part of message """ link = "" soup = BeautifulSoup(mail, "lxml") # print(soup.prettify()) for item in soup.find_all('a'): link = re.findall(match_regex, str(item.get('href'))) if len(link) != ...
d8f7a2731b33650c17b48c153b540ede9c39b451
3,623,103
def clamp(input, min, max): """ Return an attribute that represents the given input clamped in the range [min, max]. All inputs can be either attributes or values. """ return _createUtilityAndReturnOutput('clamp', input=input, min=min, max=max)
6f143529c336fdcbfa75e98dd97ccf391b5ec776
3,623,104
import collections import random def train_pmi(dataset, initial_cutoff=0.5, alpha=0.75, margin=1.0, max_iter=15, batch_size=256): """ Train a dict mapping pairs of ASJP sounds/chars to their PMI scores on word pairs using the EM algorithm with the specified parameters. The first arg should be a Datas...
33f38aec39732e7d94458d4d9cc3ebebd2791a28
3,623,106
def to_category(category_reference, fuzzy=True): """ Coerces a category, category name or category id to a BuiltInCategory. >>> from rpw.utils.coerce import to_category >>> to_category('OST_Walls') BuiltInCategory.OST_Walls >>> to_category('Walls') BuiltInCategory.OST_Walls >>> to_category(...
ae70bf78eb883cf44948c7f1af7b84291a098790
3,623,107
def get_class_mapping(super_mode: str): """ Mapping mode into integer :param super_mode: before, after & both :return: """ class_mapping = ['none', 'replace'] if super_mode == 'both': class_mapping.extend(['before', 'after']) else: class_mapping.append(super_mode) ret...
33e1f40c600f68b6ea760ec9340d04555ecae463
3,623,108
def permissions_required(permissions, login_url=None): """ Decorator that checks if a user has the given permissions. Accepts a list or tuple of lists of permissions (see check_permissions documentation). If the user is not logged in and the test fails, she is redirected to a login page. If the ...
179e8e34674b57b3c2278924c80cfa2c937afce2
3,623,110
def auth(opts, whitelist=None): """ Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader """ return LazyLoader( _module_dirs(opts, "auth"), opts, tag="auth", whitelist=whitelist, pack={"__salt__": minion_mods(opts)},...
b562ac7c6893e3accc18ceb8fe03870e21f4258f
3,623,111
def preprocess_data(dfs, target): """ For each df in dictionary the number of columns is reduced to number of features. Features get scaled using preprocessing.scale() Arguments: dfs(dict) - dictionary with monthly fixtures target(str) - market to predict, three markets get handled: "e...
b7d5c329f6678acb800ee89b4c591fd494224894
3,623,112
def mlp(inputs, mlp_hidden=[], mlp_nonlinearity=tf.nn.relu, regularizer=None, scope=None): """Define an MLP.""" with tf.variable_scope(scope or 'Linear'): mlp_layer = len(mlp_hidden) res = inputs for l in range(mlp_layer): res = mlp_nonlinearity(linear(res, mlp_hidden[l], scope='l'+str(l), regular...
88f51bbc54b4b5c12d2aeb702158f9aba25f13c4
3,623,113
import socket def get_banner(): """Get the ``banner`` that will be signed in :meth:`adb_shell.adb_device.AdbDevice.connect` / :meth:`adb_shell.adb_device_async.AdbDeviceAsync.connect`. Returns ------- bytearray The hostname, or "unknown" if it could not be determined """ try: ...
9babf7db8d4177b427f46c0785b899c79ba2691c
3,623,114
def tweets_for_search(*args): """ Tweets for a search query. """ return tweets_for(QUERY_TYPE_SEARCH, args)
9b2a7a828da3fca036433b4c150bd52bcaa33915
3,623,115
def rol(value, count): """A rotate-left instruction in Python""" for y in range(count): value *= 2 if (value > 0xFFFFFFFFFFFFFFFF): value -= 0x10000000000000000 value += 1 return value
ac6f4efee5d806201a04f83921bca47ac6e42ee8
3,623,117
def power(**kwargs): """ Powers on/off key fob. Optional arguments: - value (bool): Power on or off. """ return client.send_sync(_msg_pack(_handler="power", **kwargs))
7b7e956ebe2b7c44b4cb9cd83524090befbcc036
3,623,118
import time import decimal def collatz(num): """ :type num: int; :param num: start number, any positive integer; :return [start number, [following_numbers], steps, time]; """ num_original = num following_nums = [] step = 0 start = time.time() while num != 1: # print(str...
82427afa292d9f7581a0964482d08e454b9012e5
3,623,119
def bubble_sort(vals): """Sort the given array using bubble sort.""" for i in range(len(vals) - 1): for j in range(len(vals) - i - 1): if vals[j] > vals[j + 1]: vals[j], vals[j + 1] = vals[j + 1], vals[j] return vals
ee0286dd53da0fbfc508fa1c26dbf913ba8f92ce
3,623,120
def create_labels(features_end, prediction_start, prediction_end, conn, output = False): """ Generate a list of labels and return the table as a dataframe. Parameters ---------- features_end prediction_start prediction_end conn: obj Returns ------- df_labels: Da...
ccf218f686664051dce572a8b45e7d32feff1246
3,623,121
def latex_print(expr): """Prints a tensor expression in Latex.""" # my_strs = copy(defaults) # my_strs["dot"] = "%s %s" # my_strs["inverse"] = "{%s}^{-1}" # my_strs["name_attr"] = "latex" # my_strs["transpose"] = "{%s}^t" # my_strs["pow"] = "{%s}^{%s}" # my_strs["div_under_one"] = "{%s}^{-1}" #...
88f5705362f14abc0136be10ff6fe95d1589690e
3,623,122
import numpy def clean(grid, distances): """ Given a list of boxes and the distances between each pair, returns a new list of boxes and distances, by removing the boxes that are not on land, as well as the -empty- distances referring to these boxes. Args: grid: A m*n list of boxes dis...
41e88d68a69b23a3fb90fb43deb8b44564df781e
3,623,123
def public_byte_prefix(is_test): """Address prefix. Returns b'\0' for main network and b'\x6f' for testnet""" return b'\x6f' if is_test else b'\0'
3ecc4fe0cbbd8dee1a91f90e0112d9be3184fc73
3,623,125
from typing import Dict import gzip import tqdm def map_refseq_to_uniprot() -> Dict[str, str]: """ Reads the RefSeq_UniProt_collab file and maps RefSeq IDs to UniProt IDs. :return: dictionary of refseq: uniprot """ ref_up_mapping = {} with gzip.open(osp.join(DATA, 'gene_refseq_uniprotkb_collab...
decc8bd6e5ce9cb44770cde75a505e9d4f541e65
3,623,126
async def character_search(bot, context): """Searches for characters with the given list of tags.""" tags = [_clean_text_wrapper(it) for it in context.arguments] cursor = data.db_select( bot, from_arg='characters', where_arg='tags @> %s', input_args=[tags], additional='ORDER BY clean_name AS...
56c32cc21ec2e0e5aa5142d3e03c4599f498f2dc
3,623,127
def global_synchronization_enabled(): """Checks if we should synchronize objects via hooks. We shouldn't run these hooks if integration to IssueTracker turned off or it was called by import request. We can detect that it was called by import via trying to get request. Import calls doesn't have requests. "...
080d8137c584dad2ae98b29a7b1c1c4834bc9627
3,623,128
from typing import Any import dataclasses def is_template_like(obj: Any) -> bool: """Check whether the given object is template-like. Currently this includes templates and dataclasses. """ return is_template(obj) or dataclasses.is_dataclass(obj)
584e645c3991985ca827b880ffd19824871c2ec7
3,623,129
def get_resource_ignore_params(params): """Helper method to determine which parameters to ignore for actions :returns: A list of the parameter names that does not need to be included in a resource's method call for documentation purposes. """ ignore_params = [] for param in params: ...
02d805f9bc62e8aa47830e459adc044c8f70858a
3,623,130
from functools import reduce def Rotation3DMatrix(Xangle=0,Yangle=0,Zangle=0): """ unit: degree [0,360] """ Xangle = np.pi*Xangle/180 Yangle = np.pi*Yangle/180 Zangle = np.pi*Zangle/180 Rx = np.array([[1,0,0], [0,np.cos(Xangle),-np.sin(Xangle)], ...
df61864b8318e8d7982e1e97b0956d6fbacbb6b1
3,623,131
from typing import Callable def sum(x: Callable[[AbstractRow], R | None]) -> AggregateSpecification: """Compute the sum of `x`, with an empty column summing to NULL. Parameters ---------- x A column getter. """ return AggregateSpecification(Sum, x)
48d18d0c5617acccc43a357a27a9c7fb2de416c3
3,623,132
def camera_to_world_frame(x, R, T): """ Args x: Nx3 points in camera coordinates R: 3x3 Camera rotation matrix T: 3x1 Camera translation parameters Returns xcam: Nx3 points in world coordinates """ xcam = R.T.dot(x.T) + T # rotate and translate return xcam.T
15a340becccd5679b2aac63ee133468deec6cb1e
3,623,133
def left_multiplied_unitary_solution(C, R, c, verify=False): """ Find portfolio in a rather indirect way ... useful for checking min w^t R C w subject to w^t c == 1 """ C_prime, H, c_prime = left_multiplied_unitary_problem(C=C, R=R) u = scaled_unitary_problem_solution(C=C_prime, c=c_prime) ...
aed065dc5946ca693d9a50ffdef1f136e553c509
3,623,134
def find_job(schedd=None, attr_list=None, **constraints): """Query the condor queue for a single job matching the constraints Parameters ---------- schedd : `htcondor.Schedd`, optional open scheduler connection attr_list : `list` of `str` list of attributes to return for each job, ...
e527f0de3a26a693f32fdcbc1ac3559e0f61d9d9
3,623,135
import json def _json_read(filename): """Read a json into a dict.""" with open(filename) as file: return json.load(file)
84187d2a2281d2725adb8dae903253bdcd41e2b9
3,623,136
def get_flagged_cells(gameboard): """This is another example that is written through the use of a cell class.""" flagged_cells = [] for cell in gameboard: if cell.is_flagged(): flagged_cells.append(cell) return flagged_cells # consider def copy_string(a1, a2) # vs def copy_string(source, destination) ...
362cd976f92584274bd94420485c7ecaabc371ce
3,623,137
def addLists(list1, list2): """Add lists together by value. i.e. addLists([1,1], [2,2]) == [3,3].""" # Find big list and small list blist, slist = list(list2), list(list1) if len(list1) > len(list2): blist, slist = slist, blist # Overlay small list onto big list for i, b in enumerate(sl...
f5469dab8fd2c62d2d3ffed253803c1a3d343281
3,623,138