content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch from typing import Optional def camera_to_image_space( points: torch.Tensor, focal_x: float, focal_y: float, center_x: float, center_y: float, flip_h: bool = True, height: Optional[int] = None, device: Optional[torch.device] = None, _validate_args: bool = True ) -> torch.Tensor: """Tr...
60417fcfa657a5a40e8e3fde8212c1d0faba9dd8
3,623,000
def _compute_average_ranks( matrix, threshold=0.001, precision=4, higher_is_better=True, ): """Compute the average rank of each method. Input ----- matrix : pd.DataFrame Rows are datasets, columns are methods, and values are the compared metric. threshold : float The...
466ff3a3c7562d4e503de9de7af26b50408c6d92
3,623,001
def get_devices(db: Session, skip: int = 0, limit: int = 100): """ Get Device list (default: up to 100 devices) """ return ( db.query(models.Device) .order_by(asc(models.Device.id)) .offset(skip) .limit(limit) .all() )
d1076c1038c1ffcd9a60b5205d310688a69e6107
3,623,002
def _swap_log_prob_and_maybe_grads( pre_swap_replica_results, post_swap_replica_states, inner_kernel, ): """Swap 'target_log_prob' and maybe 'grads_target_log_prob'. After swapping states, the log probs for replicas need to be evaluated at the new points, then tempered. The easiest way to do this is ...
71cb2b05bb4aed15ff32106975f7e1b83bb2101c
3,623,003
def shapes_to_labels_masks(img_shape, shapes, label_name_to_value): """Converting shapes in json generated by Labelme to masks and class ids Args: img_shape: Size of mask (height, width) shapes: list of labels and points [{"label":"mouse", "points": [[x1,y1], [x2,y2]...]}, ...
36fbdf7a62ae0a834573bf4d6c148418026fd276
3,623,004
def read_gpm(infile): """ READ_GPM Read HDF5 GPM file with these parameters: - dataQuality - landSurfaceType - flagPrecip - flagBB - heightBB - widthBB - qualityBB - typePrecip - qualityTypePrecip - zFactorCorrected It will reverse direction along the beam for re...
995361838c4a2ea22ffb0040fb62fffeab254a3b
3,623,005
import re import socket def get_host_name() -> str: """Get the host name. :return: A string value. """ return re.sub(r"\.(?:local|lan)", "", socket.gethostname())
225889a0bf40943ef962903551bde85fd2729ac8
3,623,006
def read_data(data_path): """This function reads in the histogram data from the provided path and returns a pandas dataframe """ gwas_df = pd.read_csv(data_path) return gwas_df
034a65ac32613ae52187bf715151ec026cb63e00
3,623,007
def fix_hyphen_commands(raw_cli_arguments): """Update options to match their module names with underscores.""" for i in ['gen-sample', 'run-python', 'run-stacker']: raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i] raw_cli_arguments.pop(i) return raw_cli_arguments
cbc420547f1d3a04787d059aa09eb0199df82dba
3,623,008
from typing import Tuple def pspnet(input_size: int, num_classes: int, loss, channels: int = 3) -> Tuple[Model, str]: """ Pyramid Scene Parsing Network https://arxiv.org/abs/1612.01105 https://hszhao.github.io/projects/pspnet/ https://github.com/Vladkryvoruchko/PSPNet-Keras-tensorflow """ ...
ec16ceb1a7572551605c96dcc39934ea75190a0f
3,623,009
def get_data_types(nb_sensors): """ What should be the data type for each sensor (1 - integer, 2 - float) Input nb_sensors -> how many sensors (int) Output data_type_per_sensor -> list of data types for each sensor """ print("Choose data type for each sensor: 1-integer / 2-floa...
f3133d415f1d6c8448fec57a1f14fb88d697107d
3,623,010
from typing import Sequence from typing import Union def cpgrid_to_rg( volume: xr.Dataset, xyzcorn_df: pd.DataFrame, mapping_dims: Sequence[str] = ("xline", "iline"), depth_dim: Union[str, None] = None, buffer: int = 0, srate: float = 0.1, client: Union[None, Client] = None, ) -> xr.Datase...
4b860df568ad74d348dfc1e00895582c7b15becb
3,623,011
def get_trip_walking(origin, destin): """ Return trip data between two pois, by default mode of travel is driving """ myconfig_walking = RequestConfig(app.config['OSRM_WALK_ADDRESS']) # service for mode walking coord_start = [float(item) for item in origin] coord_finish = [float(item) for i...
4a548b1ad5b2eaae9177e83bc60472046a57a333
3,623,012
from typing import List def confidence_threshold(boxes: List[DetectionBox]) -> List[DetectionBox]: """ Filter a list of boxes with a given confidence threshold. :param boxes: A list of boxes. :return: A list of boxes with confidences higher than the threshold. """ return [box for box in boxes ...
17256a2c9b89ce249c7f326715854a1ed60e061e
3,623,013
def get_linear_regression_id(linear_regression): """Returns a linearregression/id. """ return get_resource(c.LINEAR_REGRESSION_PATH, linear_regression)
2ffee0afbb4feae3bac94d2c075ec8a59a08e599
3,623,014
import os def _get_appdata_dir(): """Return the path to the Windows AppData directory""" if "%AppData%" in os.environ: return pth.join(os.environ["%AppData%"], "vaayu") return None
dbcfe0aecfeb060a33ee852f861c859f0cb3289e
3,623,015
from mvpa2.clfs.base import Classifier from mvpa2.base.state import ClassWithCollections import sys def sweepargs(**kwargs): """Decorator function to sweep over a given set of classifiers Parameters ---------- clfs : list of `Classifier` List of classifiers to run method on Often some unit...
e82a28a8c2ab298cb54f9291102338f534bf3928
3,623,016
import logging def transform_rays_model_cdf_mixture(list_rays, coef_components=1): """ compute the mixture model and transform it into cumulative distribution :param list(list(int)) list_rays: list ray features (distances) :param int coef_components: multiplication for number of components :return an...
c2cdd81901f4c7a61986e0272dc8bc7f34a7ed6e
3,623,017
from typing import Optional def swaption_vol_smile(asset: Asset, expiration_tenor: str, termination_tenor: str, pricing_date: Optional[GENERIC_DATE] = None, benchmark_type: str = None, floating_rate_tenor: str = None, clearing_house: str = None, loc...
0f25c409c76e76b37afb3e337a02bca88f24142e
3,623,018
def retry(freq=3, retry_callback=None): """ 装饰器,为函数添加此装饰器当函数抛出异常时会对函数重新调用,重新调用次数取决于freq指定的参数 :param freq: 重试次数 :param retry_callback: 重试时回调执行的函数 :return: 原函数返回值 """ def decorator(func): def wrap(*args, **kwargs): now_freq = 1 while True: tr...
0536b56e9b5260e78e3858c143c3845ccab3e53f
3,623,019
def models(draw, states=None, spread_probs=None, modalities=None): """Define search strategy for generating unilateral models""" graph = draw(graphs(max_size=4)) model = Unilateral(graph) if states is not None: num_lnls = len(model.lnls) model.state = draw( hynp.arrays(dtype...
9d1cd1052ae1d4e0b0d728b564d0c718ec68a3d1
3,623,020
from google.appengine.ext.go import execute_go_cgi def ExecuteCGI(config, root_path, handler_path, cgi_path, env, infile, outfile, module_dict, exec_script=ExecuteOrImportScript, exec...
42ee71aaabd9aba77d9403b7cffcabbbdc13d991
3,623,021
def read_line_offset(file, offset): """ Seek to offset in file, read a line and return the line and new offset """ fp = open(file, "r") fp.seek(offset, 0) line = fp.readline() offset = fp.tell() fp.close() return (line, offset)
429d592cf44e1f287eea5a67302a78473eb2362f
3,623,022
def load_config(stream, config_globals): """Load a configuration file and generate importer and exporter classes. Args: stream: Stream containing config YAML. config_globals: Dict to use to reference globals for code in the config. Returns: BulkloaderEntry Raises: InvalidConfiguration: If the...
ee0d5158a8aca7d65dc3045b5a4763159b17b1a2
3,623,023
def endpoint_api_abort(): """ Serves an API endpoint, non-gracefully emergency aborting what is being done now. """ machine_worker_process.kill() return jsonify({'status': "OK"})
6403f1b235ffebd71b1a209574d92e7c3b685b1b
3,623,024
def test_get_username_return_none(entered_username, monkeypatch, config): """Prompt for username when it's not in keyring.""" class FailKeyring: @staticmethod def get_credential(system, username): return None monkeypatch.setattr(auth, "keyring", FailKeyring()) assert auth.R...
c8701617e0098ccd5d25e0ff893498edc3f20b19
3,623,025
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 os def get_ab_path(): """ Find the location of the ab (apache benchmark) program """ for name in ['ab', 'ab2', 'ab.exe', 'ab2.exe']: path = os.path.join(os.path.split(HTTPD)[0], name) if os.path.exists(path): return quote_if_space(path) return None
3c0327f92f0bfd73c1e48b5ca113fd10ec1f1e82
3,623,033
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
import os def get_credentials(): """ Retrieve the credentials. Return: credentials. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') credential_path = os.path.join(credential_dir, 'gmail-python-email-send.json') credentials = None ...
9655fb004b68850cb6c680daf180e0cdb804bfb3
3,623,045
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
import typing from pathlib import Path import tempfile import subprocess import os def align( wav_path: str, text: str, model_path: typing.Optional[typing.Union[Path, str]] = None, julius_path: typing.Union[Path, str] = "/usr/bin/julius", ) -> typing.List[typing.Tuple[int, int, str]]: """Get the f...
d08a9a9f4d37c04ec1826c97c831cb7c81003819
3,623,064
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
import os def init_model(config, net, optimizer=None): """ load model from checkpoint or pretrained_model """ checkpoints = config.get('checkpoints') if checkpoints and optimizer is not None: assert os.path.exists(checkpoints + ".pdparams"), \ "Given dir {}.pdparams not exist."...
0cb37585fc59f24360330cc00810cf06c19c5b24
3,623,072
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
import os import sys def create_empty_folder_setup(fold, name, author=None, description=None, url=None, durl=None, version="0.1", subversion="0"): """ Creates a quick empty shell for a new project. @param fold location @param name name of the proj...
6ff2a096971481dfa95c4967ea925214569340ba
3,623,075
import logging import traceback def record_apply(domain_name): """ example jdata: {u'record_ttl': u'1800', u'record_type': u'CNAME', u'record_name': u'test4', u'record_status': u'Active', u'record_data': u'duykhanh.me'} """ #TODO: filter removed records / name modified records. try: jdata...
b4e8a4bb68b764e808197ad8858f68483530fa46
3,623,076
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 warnings def deprecated(message): """Deprecated function decorator.""" def wrapper(fn): def deprecated_method(*args, **kargs): warnings.warn(message, DeprecationWarning, 2) return fn(*args, **kargs) # TODO: use decorator ? functools.wrapper ? deprecated_...
96dfafbfc889d415449ba23b5d7746775b5a03ba
3,623,078
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 os def which(cmd): """ Returns full path to a executable. Args: cmd (str): Executable command to search for. Returns: (str) Full path to command. None if it is not found. Example:: full_path_to_python = which("python") """ def is_exe(fp): return ...
db7d9f79d0a7d7f9673d181fb4fb1f0d00aa6fab
3,623,091
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