content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def cdgmm(A, B, inplace=False): """Complex pointwise multiplication. Complex pointwise multiplication between (batched) tensor A and tensor B. Parameters ---------- A : tensor A is a complex tensor of size (B, C, M, N, 2). B : tensor B is a compl...
c3a65ec03339edd0defe723fc860ff9f54495eda
29,125
def InvocationStartEncKeyVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartEncKeyVector(builder, numElems)
c00609da890986ff4cf5c30f246459342b9d60bd
29,126
from functools import reduce def dynamic_partial_sum_product( sum_op, prod_op, factors, eliminate=frozenset(), plate_to_step=dict() ): """ Generalization of the tensor variable elimination algorithm of :func:`funsor.sum_product.partial_sum_product` to handle higer-order markov dimensions in additi...
a08298f1440c212310cc3298629e27743325c9ca
29,127
def range_to_number(interval_str): """Converts "X-Y" -> "X".""" if not '-' in interval_str: return int(interval_str) # If first character is -, X is a negative number if interval_str.startswith('-'): number = '-' + interval_str.split('-')[1] else: number = interval_str.split...
562031503241cc37b1b6df5dd657f2f2d90b79a3
29,128
import warnings def load_wav_file_with_wavio( file_path, sample_rate, mono=True, resample_type="kaiser_best" ): """Load a 24-bit wav audio file as a floating point time series. Significantly faster than load_sound_file.""" wavio_obj = wavio.read(str(file_path)) samples = wavio_obj.data actual...
a1b7896e8ac4b9b5833c3ca25776295deb56839e
29,129
def as_cidr(cr: CidrRepr) -> Cidr: """ Returns a strict network address expressed as in CIDR form: either a string, expressing the network address as ``"<network number><zeros>/<mask bits>"``, or as a ``Cidr`` object, which is returned unaltered. """ if isinstance(cr, _BaseNetwork): return c...
7d6d40c7269619f6189ea1cee940ed4d33eadb1f
29,131
from vivofoundation import get_triples def get_authorship(authorship_uri): """ Given a URI, return an object that contains the authorship it represents """ authorship = {'authorship_uri':authorship_uri} triples = get_triples(authorship_uri) try: count = len(triples["results"]["bindings...
83a1d6a763e16d43c7c83f65f7f3ad11afd5506e
29,132
def Init(): """ Инициализации важных переменных """ # Получаем список листов, их Id и название spreadsheet = service.spreadsheets().get(spreadsheetId = spreadsheet_id).execute() sheetList = spreadsheet.get('sheets') sheetUsers = sheetList[0]['properties']['sheetId'] sheetSW = sheetList[1]['p...
917f2ec6f5d39260ed89c546695e7cd2839bc7b6
29,133
def Nlam_to_Flam(wave, zeropoint, zp_min=5.0, zp_max=30.0): """ The factor that when multiplied into N_lam converts to F_lam, i.e. S_lam where S_lam \equiv F_lam/N_lam Parameters ---------- wave (`numpy.ndarray`_): Wavelength vector for zeropoint zeropoint (`numpy.ndarray`_): zero...
843560dde9e4ec6d2781e4179ca047d00c5e3abc
29,134
def base64_values_validate(name, description, color_set): """Ensures the string wasn't maliciously fabricated to feed corrupted data into the app, even if the b64 code itself successfully decoded into a valid string.""" if custom_palette_name_validate(name) or custom_palette_description_validate(description...
878a5cdf20bcc380a8e81afc47e40592eb4db030
29,135
def isIndepFromTarget(df, attr, x): """ Determiner si un attr est independant de target :df: dataframe choisit :attr: l'argument choisit a etudier :x: seuil :retourner true si n attr est independant de target """ obs=[[], []] ref=[] for t in df.itertuples(): dic=t._asdict...
7bad7b227f3c7af5413ad9778870c44c7844bf6a
29,136
def read_docs_md(filename, root=None): """ Retrieves an apidoc markdown file to be implemented in swagger_auto_schema :param(str) root: root base dir, settings.BASE_DIR as default :param(str) filename: the filename to be retrieved without the .md file type :return: the content of the md file, None i...
e888e1df91b4154fb9d67f6268da76ab2028f780
29,137
def unrotate(points, posor): """Rotate the matrix of column vectors points according to posor, i.e., from absolute coordinates to camera coordinates""" rot_matrix = calc_rot_matrix(posor) return rot_matrix.I * points
58066c958da982d035792997eaff00bfc573d2d1
29,138
def exp_tail(d, x): """Tail of the exponential series starting at d. Needed in the set sampler. Parameters ---------- d: int x: float Returns ------- float """ result = exp(x) # Subtract the _first _d terms. for i in range(d): result -= (pow(x, i) / factorial(i...
48ac3da79e293451d42c5d55196863e27ed3b3e1
29,139
def check_projects_scores(request, hackathon_id): """ When a judge submits the score, check if all projects in the Hackathon were scored by all the judges in all the categories by comparing the number of objects in HackProjectScore for each projects to the required number of objects. If all project...
edfb52db396a984e10a437a1b6561a3e493d9e0e
29,140
def get_path(obj, path, default=None): """Get the value at any depth of a nested object based on the path described by `path`. If path doesn't exist, `default` is returned. Args: obj (list|dict): Object to process. path (str|list): List or ``.`` delimited string of path describing ...
c72cd428979a3f39214c57346aa345087a0248c7
29,144
def get_label_set_args(): """ Add arguments specific to the "Label Set" experiment. Return ArgParser object. """ cmd = get_general_args() cmd = get_explainer_args(cmd) cmd.add('--in_dir', type=str, default='output/influence_set/') cmd.add('--out_dir', type=str, default='output/label_set...
d08e59452ba7afdd8a478f589366e9ba219abb18
29,145
def literal_label(lit): """ Invent a nice label name for the given literal """ return '{}_{}'.format(lit.function.name, lit.name)
14a22d989ee9f07e00e66d1340b946d385d677fd
29,146
from typing import Optional def key(element: DOMElement) -> Optional[str]: """ Retrieve the key of a particular :class:`.DOMElement` in its parent element, if it can be referred to by a key (i.e. if it its parent element is a :class:`collections.abc.Mapping`). :param element: A DOM element :retur...
f7ac059faa2023f88bad386a3d28e44a44c4259d
29,147
def absolute_reverse(view_name, query_kwargs=None, args=None, kwargs=None): """Like django's `reverse`, except returns an absolute URL. Also add query parameters.""" relative_url = reverse(view_name, kwargs=kwargs) url = website_util.api_v2_url(relative_url, params=query_kwargs) return url
11fc1bdc7be40fbbd462570f70f9fe77a5b4777f
29,148
def convert(chinese): """converts Chinese numbers to int in: string out: string """ numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无':90} ...
c08b9e01f0981afd09d2d9537ec1e98f2af46c06
29,149
def method_not_raises(UnexpectedException): """A decorator that ensures that the underlying function does not raise the UnexpectedException""" @Decorators.decorator def method_not_raises(target, *args, **kwargs): return not_raises(UnexpectedException, target, *args, **kwargs) return method_not_r...
f5267acedcd7bebec7d0cae998635c03c95e2eb8
29,150
def create_random_data(n_randoms, stomp_map): """Function for creating randomly positioned unknown objects on the considerd geomometry. These is used for normalizing the output PDF and properly estimating the "zero point" of the correlation amplitude. The code returns a spatially searchable quad tree of...
c3c73e358d767e46064400d9b48e99a79b7bcfea
29,151
def mobilenetv1(): """Handler da página inicial do modelo de Mobilenet V1 :return: """ return render_template("mobilenetv1.html")
edf8cb04c715c4ce0d3c70883813fb11d0640a19
29,153
def move(board): """Queries the user to move. Returns false if the user puts in an invalid input or move, returns true if the move was successful""" start_input = input("MOVE WHICH PIECE? ") if not start_input.isdigit(): return False start = int(start_input) if start not in board or board...
3377b4f349c9519eff4ede707d10e08038e9d7fc
29,154
import re def _read_reaction_kinetic_law_from_sbml(reaction, mass_reaction, f_replace, **kwargs): """Read the SBML reaction kinetic law and return it. Warnings -------- This method is intended for internal use only. """ mass_rid = mass_reaction.id sbml_species = ( list(reaction.g...
ea800e5b7ccde7dbc87c11066176f963e0367256
29,155
def _total_probe_count_without_interp(params, probe_counts): """Calculate a total probe count without interpolation. This assumes that params are keys in the datasets of probe_counts. The result of ic._make_total_probe_count_across_datasets_fn should give the same count as this function (if params are...
0973e667dbf1fc3bdf476791cbf709549230f94b
29,156
from typing import Any import math def make_divisible(x: Any, divisor: int): """Returns x evenly divisible by divisor.""" return math.ceil(x / divisor) * divisor
bfbcfb334777a6c7214f16aa0fadd56906e2b7bc
29,158
def one_vehicle_xml(): """Emulates a XML response for 1 vehicle trajectory""" STREAM = b'<INST nbVeh="1" val="2.00"><CREATIONS><CREATION entree="Ext_In" id="1" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS><TRAJ abs="25.00" acc="0.00" dst="25.00" id="0" ord="0.00" tron="Zone_001" type="VL" vit="25.00...
792cfb5895fd033c40a4cdbf6e79083c865d0093
29,160
def select_data(all_tetrode_data, index): """ Select tetrode data by trial indices. :param all_tetrode_data: (list of 4d numpy arrays) each of format [trial, 1, neuron + tetrode, time] :param index: (1d numpy array) trial indices :return: (list of 4d numpy arrays) selected subset of tetrode data ...
5a883771ef499e0b82e0d3ac5b86550180760e13
29,161
from datetime import datetime def normalize(ds_train, ds_cv, ds_test): """ Normalization of datasets Parameters ---------- ds_train: Dataset Training set ds_cv: Dataset Cross-validation set ds_test: Dataset Test set Returns ------- norm_train: Dataset ...
ad6731096e1081f3ff764ec055d4d3035a40ecbe
29,162
def generate_sequential(num_users=100, num_items=1000, num_interactions=10000, concentration_parameter=0.1, order=3, random_state=None): """ Generate a dataset of user-item interactions where ...
1a9a23fda9c17d5b7085d860986aab78368a4408
29,163
def expand(fluid, pfinal, eta): """Adiabatically expand a fluid to pressure pfinal, using a turbine with isentropic efficiency eta.""" h0 = fluid.enthalpy_mass() s0 = fluid.entropy_mass() fluid.set(S = s0, P = pfinal) h1s = fluid.enthalpy_mass() isentropic_work = h0 - h1s actual_work = i...
acf8cd63684ccf3c41c38cc631d66b4bc143c5c6
29,164
def ADOSC( frame, fast=3, slow=10, high_col="high", low_col="low", close_col="close", vol_col="Volume", ): """Chaikin A/D oscillator""" return _frame_to_series( frame, [high_col, low_col, close_col, vol_col], talib.ADOSC, fast, slow )
61b4959407d68fce2023a135253e02aa7e3428fc
29,165
def op_scr( gep: pd.DataFrame, gross_tp: pd.DataFrame, ul_exp: float, bscr: float ): """ SCR Op Risk module Inputs: - Gross EP last 12m and 12m prior - Gross TP: BEL should be positive - BSCR """ op_premiums = 0.04 * (gep.at['life_all', 'gep_last12m'] - ...
fc1455e5ad7d4da92068b18b80a0ce929b5a9a50
29,166
def parse_voyager_sclk(sclk, planet=None): """Convert a Voyager clock string (FDS) to a numeric value. Typically, a partition number is not specified for FDS counts. However, if it is, it must be compatible with the planetary flyby. The partition number is 2 for Jupiter and Saturn, 3 for Uranus, and 4 ...
237695d43fe17af4f1d7fb704c01ab925099e663
29,167
def format_url(url): """ Formats url by adding 'http://' if necessary and deleting 'www.' :param url: ulr to article or domain :return: formatted url e.g. the following urls: 'http://www.google.pl/', 'google.pl/', 'google.pl/', 'www.google.pl/', 'http://google.pl/...
a9d99b3ad73efb2d79931e9f0d75b1ea557fc6f4
29,168
def append(arr, values, axis=None): """Append to the end of an array along axis (ravel first if None) """ arr = asanyarray(arr) if axis is None: if arr.ndim != 1: arr = arr.ravel() values = ravel(values) axis = arr.ndim-1 return concatenate((arr, values), axis=axi...
9654f761bd7437840e355abc7b881e3dbe6dd260
29,169
def volo_d4_448(pretrained=False, **kwargs): """ VOLO-D4 model, Params: 193M """ model_args = dict(layers=(8, 8, 16, 4), embed_dims=(384, 768, 768, 768), num_heads=(12, 16, 16, 16), **kwargs) model = _create_volo('volo_d4_448', pretrained=pretrained, **model_args) return model
c7e51cf1af050d79d5c31ef1b7aa107d6eac9c27
29,170
from functools import reduce def rec_hasattr(obj, attr): """ Recursive hasattr. :param obj: The top-level object to check for attributes on :param attr: Dot delimited attribute name Example:: rec_hasattr(obj, 'a.b.c') """ try: ...
b1a9b12f54abb93202a5b41c950f761986307170
29,171
def find_svos(tokens): """ Extracts all the subject-verb objects in a list of tokens. :param tokens: the parsed list. :return: a list of the subject verb objects. """ svos = [] verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"] for verb in verbs: subs, ve...
1ece330f828dcf54d1a010127b583327b24aa682
29,172
def def_axiom(arg1): """ def-axiom rule prove propositional tautologies axioms. for reason that prove need propositional logic decision procedure, currently use proofterm.sorry """ # Ts = analyze_type(arg1) # if IntType in Ts: # pt = refl(arg1).on_rhs( # top_conv(rewr_con...
ccf2b1a4ca57a96a09772d1f17c11ba345e62a31
29,173
def not_shiptoast_check(self, message): """Checks whether the message object is not in a shiptoast chat.""" if (message.channel.id in self.settings["shiptoast"]) or (message.channel.name in self.settings["shiptoast"]): return False else: return True
b951ee6be9d9173065f340eda08e997b83964fe4
29,174
def jaccard_distance_loss(y_true, y_pred, smooth=100): """ Jaccard = (|X & Y|)/ (|X|+ |Y| - |X & Y|) = sum(|A*B|)/(sum(|A|)+sum(|B|)-sum(|A*B|)) """ intersection = tf.reduce_sum(tf.math.abs(y_true * y_pred), axis=-1) sum_ = tf.reduce_sum(tf.math.abs(y_true) + tf.math.abs(y_pred), axis=-1...
3ed1236856bc911210f19882a03c107f82450996
29,175
def unshare_document(token, docid, userid): """ Unshares a document from another user. :param token: The user JWT token. :type token: str :param docid: The DocID of the document. :type docid: str :param userid: The UserID of the user to be unshared fr...
c79479d93ee687dece0d60137d8837a17c306fca
29,177
import copy import torch def AlterNChannels(layer2alter_id, new_n_channels, old_model): """ Function to increase number of channels Args: layer2alter_id: layer to change new_n_channels: number of channels for the altered layer old_model: model before mutation Returns: ...
a6e02739eddd5c1de572f303b580bcd9c72a272a
29,178
def generate_bins(bins, values=None): """Compute bin edges for numpy.histogram based on values and a requested bin parameters Unlike `range`, the largest value is included within the range of the last, largest value, so generate_bins(N) with produce a sequence with length N+1 Arguments: bins (...
2d448746658193b8dd6c3ac3ef27418b37116a93
29,179
def makeRollAnswerStr( roll_res, mention_str ): """Formats an answer string depending on the roll result. If provided with an invalid roll result, returns 'None'.""" answer = None if roll_res == None: answer = "Invalid dice expression !" elif len(roll_res)==2: #either threshold or success ro...
940f43b5592ff0da6d941bcb13b100c8fb2a590e
29,180
import math def ECSPower(min, max, size): """ on modélise l'eau du réseau comme une fonction sinusoidale de période annuelle cette fonction est complètement calée sur un fichier météo qui commence au 1er janvier mais qui peut être pluriannuel min : température minimale d'injection de l'eau d...
c8f2422bfc066fc2e87caa3d2d87b07d0f1e4335
29,181
from typing import Dict from typing import Any def __create_notification(title: str, content: str) -> Dict[str, Any]: """ Creates a notification "object" from the given title and content. :params title: The title of the notification. :params content: The content of the notification. :returns A di...
484abcc2afcb8f726811e36516572bc5c302a415
29,182
def readme(): """Read and patch README.""" readme_text = read('README.rst') # PyPI does not accept :class: references. return readme_text.replace(':class:`base64io.Base64IO`', '``base64io.Base64IO``')
bad97b377022ec15e0dc0c0c3bcb984924dce216
29,183
def generator_dcgan(noise_dim, img_source_dim,img_dest_dim, bn_mode,deterministic,pureGAN,inject_noise,wd, model_name="generator_dcgan"): """DCGAN generator based on Upsampling and Conv2D Args: noise_dim: Dimension of the noise input img_dim: dimension of the image output bn_mode: keras...
9d8d481fc9688b30fd3b9ffdb5914a61291b56b7
29,184
def emg21(peak_index, x_pos, amp, init_pars=pars_dict, vary_shape_pars=True, index_first_peak=None): """ Hyper-EMG(2,1) lmfit model (single-peak fit model with two exponential tails on the left and one exponential tail on the right) Parameters ---------- peak_index : int Inde...
9e35deb35806aa1da1c70080a0eb0e5af022fe53
29,186
def _wait_and_retry(provider, job_id, poll_interval, retries, job_descriptor, summary): """Wait for job and retry any tasks that fail. Stops retrying an individual task when: it succeeds, is canceled, or has been retried "retries" times. This function exits when there are no tasks running ...
fc0f78d1ceb9d4d26dbf7b92fedc2de33a4ac4e9
29,187
def summarize_2_dual_3(package_list): """ Given list of packages, return counts of (py3-only, dual-support, py2-only) """ py3 = 0 dual = 0 py2 = 0 for pkg in package_list: if pkg['status'] == 'py3-only': py3 += 1 elif pkg['status'] in PY2_STATUSES: dua...
6a863b456a71fd51e1ac2744424a42495413778f
29,188
def isPTSF(p, T=[]): """ >>> from common.production import Production >>> p = Production(['A'], [['\\"a\\"', '\\"b\\"'],['\\"cde\\"']]) >>> isPTSF(p) True >>> p = Production(['A'], [['\\"a\\"', '\\"b\\"'],['\\"cde\\"']]) >>> isPTSF(p, ['a', 'b', 'c', 'd', 'e']) True >>> p = Product...
13f1ed36bb93035490fde33dad3840fe8b98c263
29,191
def new_getvalue( state, name, p): """ Called every time a node value is used in an expression. It will override the value for the current step only. Returns random values for the node states """ global TARGETS value = util.default_get_value( state, name, p ) if name in TARGETS: ...
30b6abacaf478936663b94c45fc2bb3951706299
29,192
def informe_ministerios(): """ Listado de personas """ check_edit_or_admin() roles = db.session.query(Rol).filter(Rol.tipo_rol == 'M')\ .join(relacion_miembros_roles, relacion_miembros_roles.c.id_rol == ...
3dddb4756a092faaa8b6f191f93e22787fb7e38d
29,194
def merge_regions_and_departments(regions, departments): """Merge regions and departments in one DataFrame. The columns in the final DataFrame should be: ['code_reg', 'name_reg', 'code_dep', 'name_dep'] """ return pd.merge(left=regions[["code", "name"]], right=departments[['regi...
0852df4d8ace31a74397ad88140336dbdf9488d2
29,195
import json def updateResourceJsons(swagger,examplesDict,dirName): """ Update the Resource JSON file to include examples in other folder """ try: # Iterate through all resources in the output folder for id in range(len(swagger['tags'])): resourceName = swagger['tags'][id]['...
3d9a7a31e3875bb7c56d8dfbd26ca5b73039101b
29,196
def sign(x): """Sign function. :return -1 if x < 0, else return 1 """ if x < 0: return -1 else: return 1
aae4fcf8fcfafca63593e908c264c08107640ec6
29,197
def set_default_dataseg(*args): """ set_default_dataseg(ds_sel) Set default value of DS register for all segments. @param ds_sel (C++: sel_t) """ return _ida_segregs.set_default_dataseg(*args)
e1f988537cb9eb0518fe5467d07d5487f3f8c440
29,198
def get_sms_history(key: str): """ Get SMS history. :param str key: Authentication key. :return: List of SMSHistoryItems. """ session = get_session(key) url = f"{SITE_BASE_URL}/index.php?page=10&lang=en" response = session.get(url) pages = bs(response.text, "html.parser").find_all...
ed6f4a4a63d90fc91e25baa92179c220783f78b2
29,199
def core_rotd(sym_factor, flux_file_name, stoich): """ Writes the string that defines the `Core` section for a variational reaction-coordinate transition-state theory model of a transition state for a MESS input file by formatting input information into strings a filling Mako template. ...
6213ec9da79340738142ccd76ffbab3d30470d36
29,200
def last_gen(genobj): """ 迭代一个生成器对象,返回最后一个元素 :param genobj: :return: """ for i in genobj: last_e = i return last_e
04e7cc57bf6406832cacaa04aa01b2ec877307df
29,201
def get_section_name_mapping(lattice): """.""" lat = lattice[:] section_map = ['' for i in range(len(lat))] # find where the nomenclature starts counting and shift the lattice: start = _pyaccel.lattice.find_indices(lat, 'fam_name', 'start')[0] b1 = _pyaccel.lattice.find_indices(lat, 'fam_name',...
52a8352f6e8747ee6f6f9a1c85b34f551fd04dad
29,202
import math def from_quaternion(quaternions, name=None): """Converts quaternions to Euler angles. Args: quaternions: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "euler_from_quaternion". Returns: ...
4f00f734599699aaadf5c66a1f8e1457321bd689
29,203
def is_polygonal(n, num): """ Predicate for if num is a n-gonal number. Works for all n >= 3 and num >= 1. """ if n < 3 or num < 1: return False t = int((sqrt(8*num*(n-2) + (n-4)**2) + (n-4)) / (2 * (n-2))) return poly(n, t) == num
f3abde644544c05da17faeb9891916428b265602
29,204
def map2pix(geoTransform, x, y): """ transform map coordinates to local image coordinates Parameters ---------- geoTransform : tuple, size=(6,1) georeference transform of an image. x : np.array, size=(m), ndim={1,2,3}, dtype=float horizontal map coordinate. y : np.array, size=(m...
bd044a4ec6d1b97f304086c21d18485b70afbee2
29,205
def checkmarkers(tubemarker, tubechecker): """Check for required markers in each tube The tube-specific markers that are to be merged are desceribed in constants.py Args: tubemarker: required markers for that tube tubechecker: markers in the given tube that needs to be validated Retu...
5004a9158db93164dbcf024d6e06d832bf35cf30
29,207
def _in_Kexp(z): """ Returns true if z is in the exponential cone """ alpha, beta, delta = z if ((beta > 0) and (delta > 0) and (np.log(delta) >= np.log(beta) + alpha / beta)) \ or ((alpha <= 0) and (np.abs(beta) < 1e-12) and (delta >= 0)): return True else: retur...
19e57dbb10e420ead5ce02e9801cd1e087f3afad
29,208
def split_blocks(bytestring, block_size): """Splits bytestring in block_size-sized blocks. Raises an error if len(string) % blocksize != 0. """ if block_size == 1: return map(b_chr, bytearray(bytestring)) rest_size = len(bytestring) % block_size if rest_size: raise ValueError(...
f85caf419de35c75d5d920d531519b2f641cc7b3
29,209
def put_newest_oldest_files(f, author, path_earliest_latest, n_files, is_newest): """Write a report of files that were least recently changed by `author` (`is_newest` is False), or was first most least recently changed by `author` in current revision. f: file handle to write to path_earlies...
19aa6a9f45d41f04d72b5699ac1599a2b8c2aa28
29,210
def pearson_correlation(trajectory_data): """ Calculates the Pearson Correlation Matrix for node pairs Usage: node_correlation, node_variance, node_average = pearson_correlation(trajectory_data) Arguments: trajectory_data: multidimensional numpy array; first index (rows) correspond to ti...
c12f4a4fd0959424e6ccfd66c55046a0bcc93cdb
29,211
from typing import Optional def upper_band(df: 'Dataframe', metric_col: str, rolling_window: Optional[int] = 20) -> pd.DataFrame: """Calculates the lower bound of a stock's price movements. Args: df: the dataframe to append a column onto metric_col: the column to calculate over (usually the '...
f831e95ca2027ccedf787178dc630e7e60403ce3
29,214
import torch def reparametisation_trick(mu, log_var, device): """ :param mu: The mean of the latent variable to be formed (nbatch, n_z) :param log_var: The log variance of the latent variable to be formed (nbatch, n_z) :param device: CPU or GPU :return: latent variable (nbatch, n_z) """ n...
9cb646132f49fa79b6a8690d10fd188968931978
29,215
async def prefix_wrapper_async_callable(prefix_factory, re_flags, message): """ Function to execute asynchronous callable prefix. This function is a coroutine. Parameters ---------- prefix_factory : `async-callable` Async callable returning the prefix. re_flags : `int` ...
d09499b4808a24bb643ae904a46049e89c77b7f3
29,217
def draw_mask(img0, img1, mask, size=14, downscale_ratio=1): """ Args: img: color image. mask: 14x28 mask data. size: mask size. Returns: display: image with mask. """ resize_imgs = [] resize_imgs.append(cv2.resize( img0, (int(img0.shape[1] * downscale_rat...
82149bd4fb9a313f76e029fb3234e6aff32cad2e
29,218
def sine_data_generation(no, seq_len, dim): """Sine data generation. Args: - no: the number of samples - seq_len: sequence length of the time-series - dim: feature dimensions Returns: - data: generated data """ # Initialize the output data = list() # Generate sine ...
1d363cce8788b62f84ab3fd05b11ff98cf5719a3
29,220
def apply_wilcoxon_test(wide_optimal, dep_var, OVRS_NAMES, alpha): """Performs a Wilcoxon signed-rank test""" pvalues = [] for ovr in OVRS_NAMES: mask = np.repeat(True, len(wide_optimal)) pvalues.append( wilcoxon( wide_optimal.loc[mask, ovr], wide_optimal.loc[mas...
a1a219c7b1bb6f917da11e5fe35c6992ccc60a8c
29,221
import torch def get_accuracy(targets, outputs, k=1, ignore_index=None): """ Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or ...
df7f60f37abd9e85b63ca616fb086b84a6ae17d9
29,222
def cameraPs2Ts(cameraPOs): """ convert multiple POs to Ts. ---------- input: cameraPOs: list / numpy output: cameraTs: list / numpy """ if type(cameraPOs) is list: N = len(cameraPOs) else: N = cameraPOs.shape[0] cameraT_list = [] for _cameraPO in ...
10d6fb11a244eded26b4c9b989e88c131832357b
29,223
def dimerization_worker(primer_1, primer_2): """ Returns the total number of complementary bases and the longest run of complementary bases (weighted by HYBRID_SCORES), the median length of all runs and the array of complementary bases. """ p1 = [set(AMB[i]) for i in primer_1] p2 = [set(AMB[i])...
6bd1fd8a990c35f8cd0cde134714c9d4a19cfdb1
29,224
from skimage import img_as_ubyte def load_dataset(ds, elsize=[], axlab='', outlayout='', dtype='', dataslices=None, uint8conv=False): """Load data from a proxy and select/transpose/convert/....""" slices = get_slice_objects(dataslices, ds.shape) data = slice_dataset(ds,...
8ccbc4d3c42bcf0861daec23b7b2410b91b89c5c
29,225
import copy def _interpret_err_lines(err_specs, ncols, names=None): """Give list of column names from the READ SERR and TERR commands Parameters ---------- err_specs : dict ``{'serr': [n0, n1, ...], 'terr': [n2, n3, ...]}`` Error specifications for symmetric and two-sided errors n...
a3ba0960a3711b30c46e8fc75237786d5297f5eb
29,226
def mro_hasattr(cls: type, attr: str) -> bool: """Check if an attribute exists in a type's class hierarchy Args: cls (type): The type attr (str): The attribute Returns: bool: True if has the attribute. Raises: TypeError: Not called on a type """ if not isinsta...
cfc41693e3d3321bcb63dae079abf2e768f97905
29,227
def get_channel_number_from_frequency(frequency): """gets the 802.11 channel for a corresponding frequency in units of kilohertz (kHz). does not support FHSS.""" try: return _20MHZ_CHANNEL_LIST.get(frequency, "Unknown") except KeyError: return "Unknown"
0867a458e98a5a97b3d8925aeeee14f6f5af58a5
29,228
def fetch_single_minutely_equity(code, start, end): """ 从本地数据库读取单个股票期间分钟级别交易明细数据 **注意** 交易日历分钟自9:31~11:30 13:01~15:00 在数据库中,分钟级别成交数据分日期存储 Parameters ---------- code : str 要获取数据的股票代码 start_date : datetime-like 自开始日期(包含该日) end_date : datetime-like ...
cc125997fe2f0313295732235b1df2e886d3fcad
29,230
def method2(): """Provide an examples of doc strings that are too long. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. """ # noqa W505: doc line too long (127 > 100 characters) (auto-generated noqa) return 7
689c50c2cfb62d39cd35eec125813830c6068fdb
29,232
def get_parent_compartment_ocid(teamname): """ Retrieves the OCID for the compartment based on the team name (assuming the model of root -- team -- individual structure of compartments. Args: teamname (str): name of the team level compartment Returns: str: The OCId or None - None is only returne...
bec0bb1d98bb8da0c4e670efebcaa6adcfb8d494
29,233
def set_recommended_watch_points(session_id): """Set recommended watch points.""" body = _read_post_request(request) request_body = body.get('requestBody') if request_body is None: raise ParamMissError('requestBody') set_recommended = request_body.get('set_recommended') reply = _wrap_re...
81f37e60ba108c2b59c79271342153ea8879697a
29,235
def epochJulian2JD(Jepoch): """ ---------------------------------------------------------------------- Purpose: Convert a Julian epoch to a Julian date Input: Julian epoch (nnnn.nn) Returns: Julian date Reference: See JD2epochJulian Notes: e.g. 1983.99863107 converts into 2445700.5 Inverse of ...
2738940ad390f979317177984c9120b34fa7d2af
29,236
def GetHighlightColour(): """ Gets the default highlight color. :rtype: :class:`wx.Colour` """ if wx.Platform == '__WXMAC__': if CARBON: if wx.VERSION < (2, 9, 0, 0, ''): # kThemeBrushButtonPressedLightHighlight brush = wx.Brush(wx.BLACK) ...
1654393d9b5f3d5ea610c9dae9706d04d7f37d54
29,238
import inspect def get_classes(mod): """Return a list of all classes in module 'mod'""" return [ key for key, _ in inspect.getmembers(mod, inspect.isclass) if key[0].isupper() ]
be04546650a6243a3abfe4053a4dcaa9d71f85d7
29,241
import struct def ustring_to_string(ptr, length=None): """Convert a pointer to UTF-16 data into a Python string encoded with utf-8. ptr and length are both gdb.Value objects. If length is unspecified, will guess at the length.""" error_message = '' if length is None: length, error_message...
9981d15eb26816fbc7f2cb0e3cac99b4d738c25a
29,242
import logging def handle_outgoing(msg): """ Should return a requeue flag, so if it returns True, the message will be requeued and processed again immediately, and if it returns False, it will not be queued again. """ def onerror(): logging.exception("Exception while processing SMS %s"...
4b189ef37965ff5725a77af615b52bc019df5910
29,243
def add_entry(ynew: float, s: float, s2: float, n: int, calc_var: bool): """Adds an entry to the metrics, s, s2, and n. s: previous value of sum of y[] s2: previous value of sum of y[]*y[] n: previous number of entries in the metric """ n = n + 1 s = s + ynew s2 = s2 + ynew * ynew ...
8aed2d9f5acb85273b1a152b0747156e49f1ebdc
29,244
def get_conversion_dict(conversion_name): """Retrieves a hard-coded label conversion dictionary. When coarsening the label set of a task based on a predefined conversion scheme like Penn Treebank tags to Universal PoS tags, this function provides the map, out of a fixed list of known maps addressed by a keyw...
9137a50e2f9900abf6d60b51c8bc44e67f13df86
29,245
import scipy def discount_cumsum(x, discount): """ magic from rllab for computing discounted cumulative sums of vectors. input: vector x, [x0, x1, x2] output: [x0 + discount * x1 + discount^2 * x2, x1 + discount * x2, x2] """ return...
82bcb686840191b7cef650b30e14308393331fa2
29,246
def compute_rgb_scales(alpha_thres=0.9): """Computes RGB scales that match predicted albedo to ground truth, using just the first validation view. """ config_ini = configutil.get_config_ini(FLAGS.ckpt) config = ioutil.read_config(config_ini) # First validation view vali_dir = join(config_in...
44341b8c878ca02179ded0a3cc1c173f1eaea009
29,247