content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def fnCalculate_Bistatic_Coordinates(a,B): """ Calculate the coordinates of the target in the bistatic plane A,B,C = angles in the triangle a,b,c = length of the side opposite the angle Created: 22 April 2017 """ u = a*math.cos(B); v = a*math.sin(B); return u,v
cc1dce6ef0506b987e42e3967cf36ea7b46a30d7
3,641,400
def _fn_lgamma_ ( self , b = 1 ) : """ Gamma function: f = log(Gamma(ab)) >>> f = >>> a = f.lgamma ( ) >>> a = f.lgamma ( b ) >>> a = lgamma ( f ) """ return _fn_make_fun_ ( self , b , Os...
62183327967840e26dfc009c2357de2c31171082
3,641,401
def convolve_smooth(x, win=10, mode="same"): """Smooth data using a given window size, in units of array elements, using the numpy.convolve function.""" return np.convolve(x, np.ones((win,)), mode=mode) / win
b41edf8c0d58355e28b507a96b129c4720412a81
3,641,402
def _conditional(Xnew, feat, kern, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False, Lm=None): """ Multioutput conditional for an independent kernel and shared inducing features. Same behaviour as conditional with non-multioutput kernels. The covariance matrices used to calculate t...
5158eb93f30fdac14bafb959e63cd8ad26fc45a7
3,641,403
import array def descent(x0, fn, iterations=1000, gtol=10**(-6), bounds=None, limit=0, args=()): """A gradient descent optimisation solver. Parameters ---------- x0 : array-like n x 1 starting guess of x. fn : obj The objective function to minimise. iterations : int Ma...
ec132e7857cf4a941c54fc5db9085bdf013fb7a2
3,641,404
def count_teams_for_party(party_id: PartyID) -> int: """Return the number of orga teams for that party.""" return db.session \ .query(DbOrgaTeam) \ .filter_by(party_id=party_id) \ .count()
07373325dd7d7ab21ef0cb1145d37b2d85292358
3,641,405
def num_series(datetime_series) -> pd.Series: """Return a datetime series with numeric values.""" return datetime_series(LENGTH)
4d208bfbae5f3e7263663d06102aa0b290f4fd4e
3,641,406
import re def obtain_ranks(outputs, targets, mode=0): """ outputs : tensor of size (batch_size, 1), required_grad = False, model predictions targets : tensor of size (batch_size, ), required_grad = False, labels Assume to be of format [1, 0, ..., 0, 1, 0, ..., 0, ..., 0] mode == 0: rank from ...
72fc737d72fe0d6d3ff4e08a5a16acf05e0e88cb
3,641,407
from typing import Dict from typing import Any def sample_a2c_params(trial: optuna.Trial) -> Dict[str, Any]: """ Sampler for A2C hyperparams. """ lr_schedule = trial.suggest_categorical("lr_schedule", ["linear", "constant"]) learning_rate = trial.suggest_loguniform("learning_rate", 1e-5, 1) n_...
f9f966f3c41a32a15253ba612d94e1254a586e86
3,641,408
def location_parser(selected_variables, column): """ Parse the location variable by creating a list of tuples. Remove the hyphen between the start/stop positions. Convert all elements to integers and create a list of tuples. Parameters: selected_variables (dataframe): The dataframe contain...
106f669269276c37652e92e62eb8c2c52dfe7637
3,641,409
import torch import math def get_qmf_bank(h, n_band): """ Modulates an input protoype filter into a bank of cosine modulated filters Parameters ---------- h: torch.Tensor prototype filter n_band: int number of sub-bands """ k = torch.arange(n_band).reshape(-1, 1) ...
87e8cf3b0d85a6717cce9dc09f7a0a3e3581e498
3,641,410
import math def compare_one(col, cons_aa, aln_size, weights, aa_freqs, pseudo_size): """Compare column amino acid frequencies to overall via G-test.""" observed = count_col(col, weights, aa_freqs, pseudo_size) G = 2 * sum(obsv * math.log(obsv / aa_freqs.get(aa, 0.0)) for aa, obsv in observ...
910431062ac9ddef467d4818d3960385a2d4392b
3,641,411
def open(uri, mode='a', eclass=_eclass.manifest): """Open a Blaze object via an `uri` (Uniform Resource Identifier). Parameters ---------- uri : str Specifies the URI for the Blaze object. It can be a regular file too. The URL scheme indicates the storage type: * carray: Ch...
c0a5069f5d7f39c87aae5af361df86b6f4fc4189
3,641,412
def create_df(dic_in, cols, input_type): """ Convert JSON output from OpenSea API to pandas DataFrame :param dic_in: JSON output from OpenSea API :param cols: Keys in JSON output from OpenSea API :param input_type: <TBD> save the columns with dictionaries as entries seperately :return: Cleaned D...
7b6a9445c956cc5d2850516d4c7dc2208b7391f7
3,641,413
def file_updated_at(file_id, db_cursor): """ Update the last time the file was checked """ db_cursor.execute(queries.file_updated_at, {'file_id': file_id}) db_cursor.execute(queries.insert_log, {'project_id': settings.project_id, 'file_id': file_id, 'log_ar...
bb0ec859c249b96e3ed066c3664e792100f5f23c
3,641,414
def action_to_upper(action): """ action to upper receives an action in pddl_action_representation, and returns it in upper case. :param action: A action in PddlActionRepresentation :return: PddlActionRepresentation: The action in upper case """ if action: action.name = action.name.uppe...
e9266ad79d60a58bf61d6ce81284fa2accbb0b8d
3,641,415
from lvmspec.qa.qa_frame import QA_Frame import os def load_qa_frame(filename, frame=None, flavor=None): """ Load an existing QA_Frame or generate one, as needed Args: filename: str frame: Frame object, optional flavor: str, optional Type of QA_Frame Returns: ...
5c8b7d279d98ddb76c6ca54a53779d88d27dab3b
3,641,416
from typing import Type from typing import Dict from typing import Any def generate_model_example(model: Type["Model"], relation_map: Dict = None) -> Dict: """ Generates example to be included in schema in fastapi. :param model: ormar.Model :type model: Type["Model"] :param relation_map: dict wit...
1aafb069ff129453f9012de79d09c326224ceb5b
3,641,417
def compare_folder(request): """ Creates the compare folder path `dione-sr/tests/data/test_name/compare`. """ return get_test_path('compare', request)
b78bc261373d47bd3444c24c54c57a600a3855ad
3,641,418
def _get_param_combinations(lists): """Recursive function which generates a list of all possible parameter values""" if len(lists) == 1: list_p_1 = [[e] for e in lists[0]] return list_p_1 list_p_n_minus_1 = _get_param_combinations(lists[1:]) list_p_1 = [[e] for e in lists[0]] list_...
b4903bea79aebeabf3123f03de986058a06a21f4
3,641,419
def system_mass_spring_dumper(): """マスバネダンパ系の設計例""" # define the system m = 1.0 k = 1.0 c = 1.0 A = np.array([ [0.0, 1.0], [-k/m, -c/m] ]) B = np.array([ [0], [1/m] ]) C = np.eye(2) D = np.zeros((2,1),dtype=float) W = np.diag([1.0, 1.0]) ...
8a054753d7bbaa06b7217ce98d38074122d41f32
3,641,420
def explore_voxel( start_pos: tuple, masked_atlas: ma.MaskedArray, *, count: int = -1, ) -> int: """Explore a given voxel. Ask Dimitri for more details. Seems like this is a BFS until a voxel with a different value is found or the maximal number of new voxels were seen. Parameters...
d2f73562497a325a42a0322f3aba9be995809a24
3,641,421
import requests def get_green_button_xml( session: requests.Session, start_date: date, end_date: date ) -> str: """Download Green Button XML.""" response = session.get( f'https://myusage.torontohydro.com/cassandra/getfile/period/custom/start_date/{start_date:%m-%d-%Y}/to_date/{end_date:%m-%d-%Y}/f...
2ed71202a40214b75007db7b16d5c1806ae35406
3,641,422
def calculateSecFromEpoch(date,hour): """ Calculates seconds from EPOCH """ months={ '01':'Jan', '02':'Feb', '03':'Mar', '04':'Apr', '05':'May', '06':'Jun', '07':'Jul', '08':'Aug', '09':'Sep', '10':'Oct', '11':'Nov', '12':'Dec' } year=YEAR_PREFIX+date[0:2] month=months[date[2:4]] day=d...
29adf78dbe795c70cb84f66b1dc249674869c417
3,641,423
def star_noise_simulation(Variance, Pk, nongaussian = False): """simulates star + noise signal, Pk is hyperprior on star variability and flat at high frequencies which is stationary noise""" Pk_double = np.concatenate((Pk, Pk)) phases = np.random.uniform(0, 2 * np.pi, len(Pk)) nodes0 = np.sqrt(Pk_double...
5ccc89f455b7347c11cac36abead172b352f7b9c
3,641,424
from datetime import datetime import time def get_seq_num(): """ Simple class for creating sequence numbers Truncate epoch time to 7 digits which is about one month """ t = datetime.datetime.now() mt = time.mktime(t.timetuple()) nextnum = int(mt) retval = nextnum % 10000000 return ...
34a2b3a7082d061987c7a0b67c91df040b86938c
3,641,425
import logging def get_packages_for_file_or_folder(source_file, source_folder): """ Collects all the files based on given parameters. Exactly one of the parameters has to be specified. If source_file is given, it will return with a list containing source_file. If source_folder is given, it will searc...
fc047dd10dfd18fc8efecb240d06aeb91686c0cb
3,641,426
def sanitize_tag(tag: str) -> str: """Clean tag by replacing empty spaces with underscore. Parameters ---------- tag: str Returns ------- str Cleaned tag Examples -------- >>> sanitize_tag(" Machine Learning ") "Machine_Learning" """ return tag.strip().rep...
40ac78846f03e8b57b5660dd246c8a15fed8e008
3,641,427
def _vmf_normalize(kappa, dim): """Compute normalization constant using built-in numpy/scipy Bessel approximations. Works well on small kappa and mu. """ num = np.power(kappa, dim / 2.0 - 1.0) if dim / 2.0 - 1.0 < 1e-15: denom = np.power(2.0 * np.pi, dim / 2.0) * i0(kappa) else: ...
24d22469a572e7ff4b7e1c918fce7001731cec2a
3,641,428
import urllib def twitter_map(): """ Gets all the required information and returns the start page or map with people locations depending on input """ # get arguments from url account = request.args.get('q') count = request.args.get('count') if account and count: # create map a...
54a37f91141e52d24f88214ea476a2f199c78674
3,641,429
def path_states(node): """The sequence of states to get to this node.""" if node in (cutoff, failure, None): return [] return path_states(node.parent) + [node.state]
21ed5eb98eca0113dd5f446066cd10df73665f10
3,641,430
def find_named_variables(mapping): """Find correspondance between variable and relation and its attribute.""" var_dictionary = dict() for relation_instance in mapping.lhs: for i, variable in enumerate(relation_instance.variables): name = relation_instance.relation.name field ...
0b9a78ca94b25e7a91fe88f0f15f8a8d408cb2fd
3,641,431
import urllib def attribute_formatter(attribute): """ translate non-alphabetic chars and 'spaces' to a URL applicable format :param attribute: text string that may contain not url compatible chars (e.g. ' 무작위의') :return: text string with riot API compatible url encoding (e.g. %20%EB%AC%B4%EC%9E%91%EC%9C%8...
6c6745a5cea9a3f6bcee8cbcedb7a1493372dc96
3,641,432
from typing import NoReturn import os def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn: """ Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation ...
ec2b5116a6cf23b41e0009e5a1ad810daf23bc5f
3,641,433
import json def maestro_splits(): """ Get list of indices for each split. Stolen from my work on Perceptual Evaluation of AMT Resynthesized. Leve here for reference. """ d = asmd.Dataset().filter(datasets=['Maestro']) maestro = json.load(open(MAESTRO_JSON)) train, validation, test = ...
119b033d3fd507b77bbb3d16d993237f8658b5f5
3,641,434
def get_choice_selectivity(trials, perf, r): """ Compute d' for choice. """ N = r.shape[-1] L = np.zeros(N) L2 = np.zeros(N) R = np.zeros(N) R2 = np.zeros(N) nL = 0 nR = 0 for n, trial in enumerate(trials): if not perf.decisions[n]: continue ...
f33593ad06bf3c54c950eda562a93e348320a5e1
3,641,435
def author_productivity(pub2author_df, colgroupby = 'AuthorId', colcountby = 'PublicationId', show_progress=False): """ Calculate the total number of publications for each author. Parameters ---------- pub2author_df : DataFrame, default None, Optional A DataFrame with the author2publication...
15c56b22cc9d5014fe4dcfab8be37a9e4b0ef329
3,641,436
def smoothed_epmi(matrix, alpha=0.75): """ Performs smoothed epmi. See smoothed_ppmi for more info. Derived from this: #(w,c) / #(TOT) -------------- (#(w) / #(TOT)) * (#(c)^a / #(TOT)^a) ==> #(w,c) / #(TOT) -------------- (#(w) * #(c)^a) / #(TOT)^(a+1)) ==> #(w,c) ...
e2f72c4169aee2f394445f42e4835f1b55f347c9
3,641,437
import six def encode(input, errors='strict'): """ convert from unicode text (with possible UTF-16 surrogates) to wtf-8 encoded bytes. If this is a python narrow build this will actually produce UTF-16 encoded unicode text (e.g. with surrogates). """ # method to convert surrogate pairs t...
525199690f384304a72176bd1eaeeb1b9cb30880
3,641,438
def forgot_password(request, mobile=False): """Password reset form. This view sends an email with a reset link. """ if request.method == "POST": form = PasswordResetForm(request.POST) valid = form.is_valid() if valid: form.save(use_https=request.is_secure(), ...
ea27378253a7ed1b98cb91fd52fe724e79f35e26
3,641,439
def rotation_components(x, y, eps=1e-12, costh=None): """Components for the operator Rotation(x,y) Together with `rotation_operator` achieves best memory complexity: O(N_batch * N_hidden) Args: x: a tensor from where we want to start y: a tensor at which we want to finish ...
79cec86425bce65ac92ce8cf9c720f98857d7e1a
3,641,440
def erode(np_image_bin, struct_elem='rect', size=3): """Execute erode morphological operation on binaryzed image Keyword argument: np_image_bin -- binaryzed image struct_elem: cross - cross structural element rect - rectangle structural element circ -- cricle structural element(...
4692b40555a8047d70ad8c4b33de636a0c6c87b0
3,641,441
from typing import Type from typing import Union from typing import Any import inspect def from_argparse_args( cls: Type[ParseArgparserDataType], args: Union[Namespace, ArgumentParser], **kwargs: Any ) -> ParseArgparserDataType: """Create an instance from CLI arguments. Eventually use varibles from OS env...
8d418557437dfc8f2522f4681cf31b9e81065e54
3,641,442
def setup_counter_and_timer(nodemap): """ This function configures the camera to setup a Pulse Width Modulation signal using Counter and Timer functionality. By default, the PWM signal will be set to run at 50hz, with a duty cycle of 70%. :param nodemap: Device nodemap. :type nodemap: INodeMap...
9874b17ce49aca766504891bd9828aad1e075e21
3,641,443
def concat(l1, l2): """ Join two possibly None lists """ if l1 is None: return l2 if l2 is None: return l1 return l1 + l2
9e87bead7eedc4c47f665808b9e0222437bc01b5
3,641,444
def get_model_data(n_samples=None, ratio=None): """ Provides train and validation data to train the model. If n_samples and ratio are not None, it returns data according to the ratio between v1 and v2. V1 is data comming from the original distribution of SIRD parameters, and V2 is data comming from ...
540706ca37decbf718fcedeef30beb235e98ded8
3,641,445
def skip(): """ Decorator for marking test function that should not be executed.""" def wrapper(fn): fn.__status__ = "skip" return fn return wrapper
0b966c306515073bfb52427b78c65822ee09a060
3,641,446
import os def upload_original_to(instance, filename): """ Return the path this file should be stored at. """ filename_base, filename_ext = os.path.splitext(filename) filename_ext = filename_ext.lower() origin_path = instance.release_agency_slug if '--' in instance.release_agency_slug: ag...
5dede23726ecb1ef06b4de1fb29d96b1f909f980
3,641,447
def _GetThumbnailType(destination_id): """Returns the thumbnail type for the destination with the id.""" destination_type = _GetDestinationType(destination_id) if destination_type == _DestinationType.HOTSPOT: return _ThumbnailType.PRETTY_EARTH else: return _ThumbnailType.GEOMETRY_OUTLINE
3452044aae2f9660084be46d840747089f271b1b
3,641,448
async def postAsync(text: str, *, url: str = "auto", config: ConfigOptions = ConfigOptions(), timeout: float = 30.0, retries: int = 3): """Alias function for AsyncHaste().post(...)""" return await AsyncHaste().post(text, url=url, config=config, timeout=timeout, retries=retries)
bfa5460ac6f469c123eb1bef6e2430f2251809c9
3,641,449
from typing import OrderedDict def gpu_load_acquisition_csv(acquisition_path, **kwargs): """ Loads acquisition data Returns ------- GPU DataFrame """ chronometer = Chronometer.makeStarted() cols = [ 'loan_id', 'orig_channel', 'seller_name', 'orig_interest_rate', 'orig_upb', 'orig...
fdc2281a6bc31547f60c9c8d8585cdc1d101d88f
3,641,450
def get_flows_src_dst_address_pairs(device, flow_monitor): """ Gets flows under flow_monitor and returns source and destination address pairs Args: device ('obj'): Device to use flow_monitor ('str'): Flow monitor name Raises: N/A Returns: [(...
61ffbe3e0e81acf8c408df7b5ca0f8ff9519f87b
3,641,451
def imthresh(im, thresh): """ Sets pixels in image below threshold value to 0 Args: im (ndarray): image thresh (float): threshold Returns: ndarray: thresholded image """ thresh_im = im.copy() thresh_im[thresh_im < thresh] = 0 return thresh_im
180dc1eba6320c21273e50e4cf7b3f28c786b839
3,641,452
import _winreg def set_serv_parms(service, args): """ Set the service command line parameters in Registry """ uargs = [] for arg in args: uargs.append(unicoder(arg)) try: key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, _SERVICE_KEY + service) _winreg.SetValueEx(key, _SERV...
90eb2ac8ea6e9a11b7ff8c266017fe027503f159
3,641,453
def isRenderNode(): # type: () -> bool """ Returns ------- bool """ return flavor() == 'Render'
b0d5799f755c9c6a72f851ad325b4d8ddf3dec70
3,641,454
def test_clean_data_contains_instance_value(): """ Test values from instances remain when not in data. """ data = {'first_name': 'John'} fields = ['job_title', 'first_name'] class Job(object): job_title = 'swamper' first_name = '' class Swamper(BaseSwamper): def bui...
d2c310cfd760ddea7241ccb469ae7cffdaf373ea
3,641,455
def wrap_application(app: App, wsgi: WSGICallable) -> WSGICallable: """Wrap a given WSGI callable in all active middleware.""" for middleware_instance in reversed(ACTIVE_MIDDLEWARES): wsgi = middleware_instance(app, wsgi) return wsgi
09574d87e241c19cae30c2db29ee1ed4744a0c68
3,641,456
def cal_rpn(imgsize, featuresize, scale, gtboxes): """ Args: imgsize: [h, w] featuresize: the size of each output feature map, e.g. [19, 19] scale: the scale factor of the base anchor to the feature map, e.g. [32, 32] gtboxes: ground truth boxes in the image, shape of [N, 4]. ...
19178b125024d213808a497a005336678589588f
3,641,457
def run(args): """This function is called by a user to recover or reset their primary one-time-password secret. This is used, e.g. if a user has changed their phone, or if they think the secret has been compromised, or if they have lost the secret completely (in which case they will need...
c81e533c7dead3fcda028ef85e566d290a85ec74
3,641,458
import time def adjust_price(iteration, current_price, global_start, last_tx_time): """ Function that decides to lower or increase the price, according to the time of previous transaction and the progress in reaching TARGET in TARGET_TIME. Args: iteration (int) - Number of previous suc...
f27f13e7b4a753d6b912ed1d795383f0d206b2ef
3,641,459
import copy def read_csv_batch(file: str, offset, cnt, **read_csv_params): """ Args: file: offset: cnt: read_csv_params: Returns: """ read_csv_params = copy(read_csv_params) if read_csv_params is None: read_csv_params = {} try: usecols = ...
cc6699db5b9ecae9706d52768c8a1dcd084062ea
3,641,460
def fault_ack_faults_by_dn(cookie, in_dns): """ Auto-generated UCSC XML API Method. """ method = ExternalMethod("FaultAckFaultsByDn") method.cookie = cookie method.in_dns = in_dns xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
532e925b560d02a0ed47d61f9aa721f55fc6b650
3,641,461
from typing import List def provides(name=None, needs: List[str] = None): """A shortcut for defining a factory function that also needs dependencies itself.""" if not needs: needs = [] def decorator(f): decorated = _needs(*needs)(f) set(name or f.__name__, decorated) r...
e28e8d5690b7fa53907864c6d17e199a491ccada
3,641,462
def clip_xyxy_to_image(x1, y1, x2, y2, height, width): """Clip coordinates to an image with the given height and width.""" x1 = np.minimum(width - 1.0, np.maximum(0.0, x1)) y1 = np.minimum(height - 1.0, np.maximum(0.0, y1)) x2 = np.minimum(width - 1.0, np.maximum(0.0, x2)) y2 = np.minimum(height - 1...
cf0fe5269afe2a5cbe94efb3221184f706fcb59d
3,641,463
import re def build_url(urlo, base, end, url_whitespace, url_case): """ Build and return a valid url. Parameters ---------- urlo A ParseResult object returned by urlparse base base_url from config end end_url from config url_wh...
b6fa39062502a7d862b17cd079de3c4cfa3720c4
3,641,464
def AnomalyDicts(anomalies, v2=False): """Makes a list of dicts with properties of Anomaly entities.""" bisect_statuses = _GetBisectStatusDict(anomalies) return [GetAnomalyDict(a, bisect_statuses.get(a.bug_id), v2) for a in anomalies]
ffa8e0f93245f49e0857a19d4e154d47f3dd7f16
3,641,465
import re def remove_links(txt: str): """ Remove weblinks from the text """ pattern = r'[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)' txt = re.sub(pattern, " ", txt) txt = re.sub('http|https', " ", txt) return txt
4ccaae84d12ab47e70482d15100ba2e60ef476e8
3,641,466
def timefn(fn): """Times a function and stores the result in LOG variables""" @wraps(fn) def inside(*args, **kwargs): start = timer() result = fn(*args, **kwargs) end = timer() gv.TIME_LOG += f'Fn : {fn.__name__} - {end - start}\n' return result return inside
8dddcd54489d2fb754d9c4de7bc1b084a10840e2
3,641,467
def get_tweet_stream(output_file, twitter_credentials): """ This function is given and returns a "stream" to listen to tweets and store them in output_file To understand how this function works, check it against the code of twitter_streaming in part00_preclass :param output_file: the file where the ret...
71a336b71760ef74e14b6472cb8f2a8510d9acb3
3,641,468
def conv3d_3x3(filters, stride=1, padding=1, kernel_initializer=None, bias_initializer=None, name=None): """3D convolution with padding.""" return keras.Sequential([ layers.ZeroPadding3D(padding), layers.Conv3D(filters, ...
f8035b8be1bf82385c31aa0810e7addd8027b5cd
3,641,469
def get_available_quests(user, num_quests): """Get the quests the user could participate in.""" quests = [] for quest in Quest.objects.exclude(questmember__user=user).order_by('priority'): if quest.can_add_quest(user) and not quest.completed_quest(user): quests.append(quest) ...
d1bdbe96dbd0b7fd5295ec43153249e7b93c7339
3,641,470
def height(): """ Default window height """ return get_default_height()
fab02ec1881d1c2ccda9f59e6a72d2990d815973
3,641,471
def no_adjust_tp_func_nb(c: AdjustTPContext, *args) -> float: """Placeholder function that returns the initial take-profit value.""" return c.curr_stop
6896b72c20c79156c97ba09ba87a1947c7df04d6
3,641,472
def inverse_theoretical_laser_position(y, a, b, c): """ theoretical angular position of the wire in respect to the laser position """ return np.pi - a - np.arccos((b - y) / c)
0ba87442954fd3bc832edec9adc082e1d2448347
3,641,473
def ad_roc(y_true, y_score): """ Compute ROC-curve. """ fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true, y_score, pos_label=1, drop_intermediate=False) return fpr, tpr, thresholds
db161f7099aab4e1d266ab2b0c8aac0b96076a49
3,641,474
import time import platform import subprocess def check_reachability(gateway): # from https://stackoverflow.com/questions/2953462/pinging-servers-in-python """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is ...
76580279cfc65f5a74015d63fb0eaccae9b8e141
3,641,475
import torch def greedy_decoding(baseline_transformer, src_representations_batch, src_mask, trg_field_processor, max_target_tokens=100): """ Supports batch (decode multiple source sentences) greedy decoding. Decoding could be further optimized to cache old token activations because they can't look ahead ...
dbdf636979f28ea09b261fd3947068d6e4e359ad
3,641,476
def _parse_cell_type(cell_type_arg): """ Convert the cell type representation to the expected JVM CellType object.""" def to_jvm(ct): return _context_call('_parse_cell_type', ct) if isinstance(cell_type_arg, str): return to_jvm(cell_type_arg) elif isinstance(cell_type_arg, CellType): ...
1afa4b2ed28d08ebc3526b8462673e5aa7f8a47f
3,641,477
def Ht(mu, q=None, t=None, pi=None): """ Returns the symmetric Macdonald polynomial using the Haiman, Haglund, and Loehr formula. Note that if both `q` and `t` are specified, then they must have the same parent. REFERENCE: - J. Haglund, M. Haiman, N. Loehr. *A combinatorial formula ...
d3a46458215417db0789d3601163e105c9712c75
3,641,478
def is_generic_alias_of(to_check, type_def): """ :param to_check: the type that is supposed to be a generic alias of ``type_def`` if this function returns ``True``. :param type_def: the type that is supposed to be a generic version of ``to_check`` if this function returns \ ``True``. ...
d09b255e9ff44a65565196dd6643564aea181433
3,641,479
def train_PCA(X,n_dims,model='pca'): """ name: train_PCA Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, ...
1909d154d778864c2eba0819e43a2bbcb260edbf
3,641,480
import os def find_song(hash_dictionary, sample_dictionary, id_to_song): """ Run our song matching algorithm to find the song :param hash_dictionary: :param sample_dictionary: :param id_to_song: :return max_frequencies, max_frequencies_keys: """ offset_dictionary = dict() for song_...
73ec2b2783dddd00c7a744af732737f6e6bce8b2
3,641,481
def phedex_url(api=''): """Return Phedex URL for given API name""" return 'https://cmsweb.cern.ch/phedex/datasvc/json/prod/%s' % api
a642cd138d9be4945dcbd924c7b5c9892de36baa
3,641,482
import csv def extract_emails(fname, email='Email Address', outfile="emails_from_mailchimp.txt", nofile=False, nolog=False, sort=True): """ Extract e-mail addresses from a CSV-exported MailChimp list. :param fname: the input .csv file :param email: the header of ...
1b4e5f60eacd4843e1c9ba6a72c866c52b5bd8d9
3,641,483
def continuations(tree, *, syntax, expander, **kw): """[syntax, block] call/cc for Python. This allows saving the control state and then jumping back later (in principle, any time later). Some possible use cases: - Tree traversal (possibly a cartesian product of multiple trees, with the curr...
333494e07462ee554701616c5069fa61c5f46841
3,641,484
import os def get_autotune_level() -> int: """Get the autotune level. Returns: The autotune level. """ return int(os.environ.get("BAGUA_AUTOTUNE", 0))
661fc4a7580fffdc7eef18ff7eb22e56ece2b468
3,641,485
def DNA_dynamic_pressure(y, r, h, yunits='kT', dunits='m', opunits='kg/cm^2'): """Estimate peak pynamic overpressure at range r from a burst of yield y using the the Defense Nuclear Agency 1kT standard free airburst overpressure, assuming an ideal surface. Many real-world surfaces are not ideal (most, in the opinio...
ac56c9d72c516658384ac313c64ba7ed1235e0ea
3,641,486
def revcumsum(U): """ Reverse cumulative sum for faster performance. """ return U.flip(dims=[0]).cumsum(dim=0).flip(dims=[0])
da147820073f5be9d00b137e48a28d726516dcd0
3,641,487
def http_trace_parser_hook(request): """ Retrieves the propagation context out of the request. Uses the honeycomb header, with W3C header as fallback. """ honeycomb_header_value = honeycomb.http_trace_parser_hook(request) w3c_header_value = w3c.http_trace_parser_hook(request) if honeycomb_header...
7c97ed82f22357d3867e8a504a30f3a857837bcf
3,641,488
import torch def format_attn(attention_tuples: tuple): """ Input: N tuples (N = layer num) Each tuple item is Tensor of shape Batch x num heads x from x to Output: Tensor of shape layer x from x to (averaged over heads) """ # Combine tuples into large Tensor, then avg return tor...
8d25d081992099835a21cdbefb406f378350f983
3,641,489
def fit_gaussian2d(img, coords, boxsize, plot=False, fwhm_min=1.7, fwhm_max=30, pos_delta_max=1.7): """ Calculate the FWHM of an objected located at the pixel coordinates in the image. The FWHM will be estimated from a cutout with the specified boxsize. Parameters ------...
c3e69f93fdf84c7f895f9cb01adf3e6a0aa3001d
3,641,490
def _ensure_aware(series, tz_local): """Convert naive datetimes to timezone-aware, or return them as-is. Args: tz_local (str, pytz.timezone, dateutil.tz.tzfile): Time zone for time which timestamps will be converted to. If the series already has local timezone info, it is returned as-is. ""...
fbb99be365a47507ae676fc90601d13cfa46832b
3,641,491
import os import pickle def one_mask(df, mask_type, sample_type, data, logger=None): """ return a vector of booleans from the lower triangle of a matching-matrix based on 'mask_type' :param df: pandas.DataFrame with samples as columns :param str mask_type: A list of strings to specify matching masks, or ...
cdb0305f716c9d0b9e1ab2c1e89f8dfbeb6d5504
3,641,492
def compute_epsilon(steps): """Computes epsilon value for given hyperparameters.""" if FLAGS.noise_multiplier == 0.0: return float('inf') orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64)) sampling_probability = FLAGS.batch_size / NB_TRAIN rdp = compute_rdp(q=sampling_probability, ...
8c998fdcafaac3c99a87b4020ae6959e64170d36
3,641,493
def extract_tumblr_posts(client, nb_requests, search_query, before, delta_limit): """Extract Tumblr posts with a given emotion. Parameters: client: Authenticated Tumblr client with the pytumblr package. nb_requests: Number of API request. search_query: Emotion to search for. ...
bff51bcdc945244a47a88d32139749dddf25f0cf
3,641,494
def total_curtailment_expression_rule(mod, g, tmp): """ **Expression Name**: GenVar_Total_Curtailment_MW **Defined Over**: GEN_VAR_OPR_TMPS Available energy that was not delivered There's an adjustment for subhourly reserve provision: 1) if downward reserves are provided, they will be called up...
9a1466dbbbc945b30c1df04dc86a2134b3d0659a
3,641,495
def transpose(m): """Compute the inverse of `m` Args: m (Matrix3): Returns: Matrix3: the inverse """ return Matrix3(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
843a4b9d52f7c15772957b7abe05ef8c32c8370b
3,641,496
def reverse_string(string): """Solution to exercise C-4.16. Write a short recursive Python function that takes a character string s and outputs its reverse. For example, the reverse of "pots&pans" would be "snap&stop". """ n = len(string) def recurse(idx): if idx == 0: ...
6d4472fb9c042939020e8b819b4c9b705afd1e60
3,641,497
def result_to_df(model, data, path: str = None, prediction: str = 'prediction', residual: str = 'residual') -> pd.DataFrame: """Create result data frame. Args: model (Union[NodeModel, StagewiseModel]): Model instance. data (MRData): Data object...
8b089569d628a0f89381240a133b21ae926da7f9
3,641,498
import re def auto(frmt, minV = None, maxV = None): """ Generating regular expressions for integer, real, date and time. :param format: format similar to C printf function (description below) :param min: optional minimum value :param max: optional maximum value :return: regular expression for...
a160b2c49baf875adb0a7949b8ea0e0e92dc936a
3,641,499