content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def mahalanobis(data, produce=None): """ Calculate mahalanobis distance on a matrix of column vectors. Assumes that rows are observations and columns are features. Parameters ---------- data : numpy array or pandas dataframe The data to calculate distances on (columns are variables...
b6dff6cfe12b4c44b6a97a6bd1f51a2250b7b63f
3,647,000
def text(el): """ Helper to get the text content of a BeautifulSoup item """ return el.get_text().strip()
7b34c77c79677a73cc66532fe6305635b1bdac43
3,647,001
def collect_DAC_pow(dig, IF_freq): """TODO: Desciption what I, the function, do""" return external_ATS9870_CS_VNA.collect_amp(dig, IF_freq)
42f649520b950357419c6c26d3d5426849855929
3,647,002
def get_sha512_manifest(zfile): """ Get MANIFEST.MF from a bar file. :param zfile: Open (!!!) ZipFile instance. :type zfile: zipfile.ZipFile """ names = zfile.namelist() manifest = None for name in names: if name.endswith("MANIFEST.MF"): manifest = name b...
7ef150bb3e89f8723649ee983085a413ec8a31df
3,647,003
def plot_heatmap(filename, xdata, ydata, binx, biny, title = None, xlabel = None, ylabel = None, dpi = 150, figsize = (10,10), tfont = 17, lfont = 14): """ Present variables as a 2D heatmap to correlate magnitude and direction. """ def get_bin_id(mybins, vv): for ibin in range(len(mybins)-1)...
3397bf2fc02932056411ef8addde264fa50b9ea5
3,647,004
def cmake_var_string(cmake_vars): """Converts a dictionary to an input suitable for expand_cmake_vars. Ideally we would jist stringify in the expand_cmake_vars() rule, but select() interacts badly with genrules. TODO(phawkins): replace the genrule() with native rule and delete this rule. Args: cmake_va...
3f0fb115c54f6ee1e0e923b67412e36ca56b2ea7
3,647,005
def scattering_transform1d(n_classes, sequence_length): """ Scattering transform """ log_eps = 1e-6 x_in = layers.Input(shape=(sequence_length)) x = Scattering1D(8, 12)(x_in) x = layers.Lambda(lambda x: x[..., 1:, :])(x) x = layers.Lambda(lambda x: tf.math.log(tf.abs(x) + log_eps))(x) x = layers.GlobalAveragePo...
53547918c5a0efa5c0e3766c770903b146eff19e
3,647,006
import zlib def addFileContent(session, filepath, source_file_name, content_hash, encoding): """ Add the necessary file contents. If the file is already stored in the database then its ID returns. If content_hash in None then this function calculates the content hash. Or if is avail...
fdd77f23151ed9627c5d9bbfb157839810c9655a
3,647,007
def model_fn_builder(num_labels, learning_rate, num_train_steps, num_warmup_steps): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" input_ids = featur...
570f5297fbcc57eaae1d08e9ee816207db707ffd
3,647,008
def to_numeric_df(kdf): """ Takes a dataframe and turns it into a dataframe containing a single numerical vector of doubles. This dataframe has a single field called '_1'. TODO: index is not preserved currently :param df: :return: a pair of dataframe, list of strings (the name of the columns ...
5eba4585ca55360bfff959b4f46580cc747e3f93
3,647,009
def FancyAnalyzer(expression=r"\s+", stoplist=STOP_WORDS, minsize=2, maxsize=None, gaps=True, splitwords=True, splitnums=True, mergewords=False, mergenums=False): """Composes a RegexTokenizer with an IntraWordFilter, LowercaseFilter, and StopFilter. >>> ana = FancyAn...
50fddbbdc22770b3a9b732bb328bf48c0407aafe
3,647,010
def find_res_shift(x_min, x_max, y_min, y_max, z_min, z_max, target_id, my_sites, res_two_three_dict, my_mols, color_list, button_list): """Function to find the relavant residue shifts""" print "FINDING MAX SHIFTS" max_shift = [] # Get the delta value delta = 5.0 # Filter residues to the ones wi...
d46a146071f5cd48ab1382d03ac4678cc2c301fd
3,647,011
def lookup(*getters): """Find data by provided parameters and group by type respectively""" getters = list(reversed(getters)) def wrap(struct): while getters: _type, getter = getters.pop() if _type == G_TYPE_KEY: struct = getter(struct) contin...
937a44e8366016cb136f0b40a91448b97c52357d
3,647,012
def compute_one(t, lhs, rhs, **kwargs): """ Join two pandas data frames on arbitrary columns The approach taken here could probably be improved. To join on two columns we force each column to be the index of the dataframe, perform the join, and then reset the index back to the left side's original...
c050fdeae2e354be3748984a32ad96b81593355b
3,647,013
def simulate(mat, det, e0=20.0, dose=defaultDose, withPoisson=True, nTraj=defaultNumTraj, sf=defaultCharFluor, bf=defaultBremFluor, xtraParams=defaultXtraParams): """simulate(mat,det,[e0=20.0],[withPoisson=True],[nTraj=defaultNumTraj],[dose=defaultDose],[sf=defaultCharFluor],[bf=defaultBremFluor],[xtraParams=defaul...
5ffdf63038fa2ba4305001f1b1ec5da0c13ebf3d
3,647,014
def link_match_family(link, family_name): """Checks whether the a link can be used in a given family. When this function is used with built-in family names, it tests whether the link name can be used with the given built-in family. If the family name is not known, we return True because the user is wor...
7d95556b5ff6537bc994d7b017263ced13d4efc0
3,647,015
import tqdm def auc(test_set, user_factors, subreddit_factors, subreddits, users): """ Returns the auc score on a test data set """ num_users = len(test_set) total = 0 # treat the signal as 1 as per the implicit bpr paper for subreddit, user, signal in tqdm.tqdm_notebook(test_set...
93179ede0fb84e7f491f147d1a356036d2908a2f
3,647,016
def convert_AST_to_expr(ast): """Creates expression from the AST.""" converter = ASTToInstrBlockConverter() instrs = converter.my_visit(ast) return instrs[0]
b4dca77c48cd0001a2f55c71a077a6b195a181ce
3,647,017
import time def add_data_from_api(service, repo, variable_type, keys): """Retrieves Github API data. Utilizes the function from github_api/github.py to do so. This function adds the retrieved variables directly to the data dictionary. Args: service (Service): Service object with API connection an...
32361d85fb92efd03b79f74f8db2e02a8fcd9866
3,647,018
def part1(data): """ >>> part1(read_input()) 0 """ return data
1482c41b112a3e74775e71c4aabbd588de2b6553
3,647,019
import torch def get_rectanguloid_mask(y, fat=1): """Get a rectanguloid mask of the data""" M = y.nonzero().max(0)[0].tolist() m = y.nonzero().min(0)[0].tolist() M = [min(M[i] + fat, y.shape[i] - 1) for i in range(3)] m = [max(v - fat, 0) for v in m] mask = torch.zeros_like(y) mask[m[0] : ...
0ff3ab25f2ab109eb533c7e4fafd724718dbb986
3,647,020
import re def colorize_output(output): """Add HTML colors to the output.""" # Task status color_output = re.sub(r'(ok: [-\w\d\[\]]+)', r'<font color="green">\g<1></font>', output) color_output = re.sub(r'(changed: [-\w\d\[\]]+)', r'<font...
80759da16262d850b45278faede4b60b7aa4a7c6
3,647,021
import argparse def parse_args(): """Parse command-line arguments""" parser = argparse.ArgumentParser( description='Stop a subjective evaluation without ' + 'destroying resources') parser.add_argument('--aws_api_key', help='The public API key for AWS') parser.add_argument( ...
661a9bdec94b88c06f6d4080ef20cc31f81901ff
3,647,022
def parse_user_date(usr_date: str) -> date: """ Parses a user's date input, prompts the user to input useful date data if user's date was invalid Args: usr_date : str, user input of date info. Should be in <yyyy/mm/dd> format Returns: valid datetime.date() object """ expected_len = len("yyyy/mm/dd") if usr...
10becdce6ef4fdc5606ce110b09e102c186dfc04
3,647,023
def up_sampling_block(x, n_filter, kernel_size, name, activation='relu', up_size=(2, 2)): """Xception block x => sepconv block -> sepconv block -> sepconv block-> add(Act(x)) => """ x = layers.UpSampling2D(size=up_size, name=name+'up')(x) if activation: x = layers.Activ...
001fdb6475da138bedfdb891af6e657e5ce6160c
3,647,024
def connected_components(graph): """ Connected components. @attention: Indentification of connected components is meaningful only for non-directed graphs. @type graph: graph @param graph: Graph. @rtype: dictionary @return: Pairing that associates each node to its connected component. ...
80c5bfc679c1dc274db6a3bf8f8becfa1fc99d4f
3,647,025
import typing def format_keyvals( entries: typing.Iterable[typing.Tuple[str, typing.Union[None, str, urwid.Widget]]], key_format: str = "key", value_format: str = "text", indent: int = 0 ) -> typing.List[urwid.Columns]: """ Format a list of (key, value) tuples. Args: ...
eb1769a3d7b47b6b4f24f02dcffd3639592c8dc6
3,647,026
def get_item_workdays(scorecard): """ Gets the number of days in this period""" supplier = frappe.get_doc('Supplier', scorecard.supplier) total_item_days = frappe.db.sql(""" SELECT SUM(DATEDIFF( %(end_date)s, po_item.schedule_date) * (po_item.qty)) FROM `tabPurchase Order Item` po_item, `tabPurchas...
cec620114ae784e5c272d41b6e1028175b466691
3,647,027
def load_data(ticker='SNAP', barSizeSetting='3 mins', what='TRADES'): """ loads historical tick data """ if what == 'TRADES': folder = '/home/nate/Dropbox/data/ib_full_adj/data/' elif what == 'ADJUSTED_LAST': folder = '/home/nate/Dropbox/data/ib_split_adj_only/data/' bss = barSi...
8ad01227131322f7780e75e1e72f89b1da3fef0b
3,647,028
def time_human(x): """ Gets time as human readable """ # Round time x = round(x, 2) for number, unit in [(60, "s"), (60, "min"), (24, "h"), (365, "days")]: if abs(x) < number: return f"{x:.2f} {unit}" x /= number return f"{x:.2f} years"
3f7f51ac7454e429fc30da64eed075aaf1f10b5b
3,647,029
from typing import Dict def transaction_json_to_binary_codec_form( dictionary: Dict[str, XRPL_VALUE_TYPE] ) -> Dict[str, XRPL_VALUE_TYPE]: """ Returns a new dictionary in which the keys have been formatted as CamelCase and standardized to be serialized by the binary codec. Args: dictionar...
94516b8418fc25d1966d6f5c969f9b4e411100ab
3,647,030
def conv3x3(in_planes, out_planes, stride=1, groups=1): """3x3 convolution with padding""" return nn.Conv1d(in_planes, out_planes, kernel_size=7, stride=stride, padding=3, bias=False, groups=groups)
90fa7549a2ba8722edab3712bac4d3af7fb5f2f2
3,647,031
def limit_sub_bbox(bbox, sub_bbox): """ >>> limit_sub_bbox((0, 1, 10, 11), (-1, -1, 9, 8)) (0, 1, 9, 8) >>> limit_sub_bbox((0, 0, 10, 10), (5, 2, 18, 18)) (5, 2, 10, 10) """ minx = max(bbox[0], sub_bbox[0]) miny = max(bbox[1], sub_bbox[1]) maxx = min(bbox[2], sub_bbox[2]) maxy = ...
fa5b7763b30442fba137814ac7b0336528c4540b
3,647,032
def _load_taxa_incorp_list(inFile, config): """Loading list of taxa that incorporate isotope. Parameters ---------- inFile : str File name of taxon list config : config object Returns ------- {library:[taxon1, ...]} """ taxa = {} with open(inFile, 'rb') as inFH: ...
d614f2be0c5ad4fa61d1d70915428324d7af97b4
3,647,033
def get_subsections(config: Config) -> t.List[t.Tuple[str, t.Dict]]: """Collect parameter subsections from main configuration. If the `parameters` section contains subsections (e.g. '[parameters.1]', '[parameters.2]'), collect the subsection key-value pairs. Otherwise, return an empty dictionary (i.e. ...
0cb022fb6ae192736186a519c6ffbcf9bcfdf541
3,647,034
def calc_psi(B, rev=False): """Calc Flux function (only valid in 2d) Parameters: B (VectorField): magnetic field, should only have two spatial dimensions so we can infer the symmetry dimension rev (bool): since this integration doesn't like going through undefined region...
80beea86346fadd7e96b82c1da6eba56bde597fd
3,647,035
def infer_printed_type(t): """Infer the types that should be printed. The algorithm is as follows: 1. Replace all constant types with None. 2. Apply type-inference on the resulting type. 3. For the first internal type variable that appears, find a constant whose type contains that variab...
1ad880fc92db2e64ba6ea81f7481efa99b0bd044
3,647,036
def bias_variable(shape): """ 返回指定形状的偏置量 :param shape: :return: """ b = tf.Variable(tf.constant(0.0, shape=shape)) return b
ff2bb945414508d1dfc1db0b028cf1feeebeb6d8
3,647,037
def drag_eqn(times,g,r): """define scenario and integrate""" param = np.array([ g, r]) hinit = np.array([0.0,0.0]) # initial values (position and velocity, respectively) h = odeint(deriv, hinit, times, args = (param,)) return h[:,0], h[:,1]
d79150dd894244c11fa882d62da2f33b1173c144
3,647,038
def virtual_potential_temperature_monc(theta, thref, q_v, q_cl): """ Virtual potential temperature. Derived variable name: th_v_monc Approximate form as in MONC Parameters ---------- theta : numpy array or xarray DataArray Potential Temperature. (K) thref : numpy array or xarr...
d4c3da0a5f4f2826edce53f610f8ba384845ebb2
3,647,039
def promote_user(username): """Give admin privileges from a normal user.""" user = annotator.credentials.find_one({'username': username}) if user: if user['admin']: flash("User {0} is already an administrator".format(username), 'warning') else: annotator.credentials.u...
6a938c341f152991741d35dfd1c693743c07f805
3,647,040
def slide_number_from_xml_file(filename): """ Integer slide number from filename Assumes /path/to/Slidefile/somekindofSlide36.something """ return int(filename[filename.rfind("Slide") + 5:filename.rfind(".")])
dcfbc322b30a39041ab15b8496f097a5a5329865
3,647,041
import io def massivescan(websites): """scan multiple websites / urls""" # scan each website one by one vulnerables = [] for website in websites: io.stdout("scanning {}".format(website)) if scanner.scan(website): io.stdout("SQL injection vulnerability found") v...
b2be56bf07d00c8839813d66acd337c75b9823ef
3,647,042
import re def is_strong_pass(password): """ Verify the strength of 'password' Returns a dict indicating the wrong criteria A password is considered strong if: 8 characters length or more 1 digit or more 1 symbol or more 1 uppercase letter or more 1 lowercase let...
bfd1832951ba3059d8c542fa0b9d708a2416a4d4
3,647,043
def plot_config(config, settings=None): """ plot_config: obj -> obj --------------------------------------------------------------- Sets the defaults for a custom experiment plot configuration object from configobj. The defaults are only set if the setting does not exist (t...
3b17e97c68bcec31856cb0dc4d7f3db4280a748f
3,647,044
import os def load_spectrogram(spectrogram_path): """Load a cante100 dataset spectrogram file. Args: spectrogram_path (str): path to audio file Returns: np.array: spectrogram """ if not os.path.exists(spectrogram_path): raise IOError("spectrogram_path {} does not exist"....
34c0db598558886ee48518a464dc90242b82d2f8
3,647,045
def evaluate_fN(model, NHI): """ Evaluate an f(N,X) model at a set of NHI values Parameters ---------- NHI : array log NHI values Returns ------- log_fN : array f(NHI,X) values """ # Evaluate without z dependence log_fNX = model.__call__(NHI) return log_fNX
e952a29fdf5864b26dc534140b2ccfb0b59fe24b
3,647,046
def generate_volume_data(img_data): """ Generate volume data from img_data. :param img_data: A NIfTI.get_data object, img_data[:][x][y][z] is the tensor matrix information of voxel (x,y,z)img_data: :return: vtkImageData object which stores volume render object. """ dims = [148, 190, 160] # siz...
b726d1484944a3f827cae836ca30cf8c7e81d493
3,647,047
def pipe(bill_texts_df): """ soup = bs(text, 'html.parser') raw_text = extractRawText(soup) clean_text = cleanRawText(raw_text) metadata = extract_metadata(soup) """ bill_texts_df['soup'] = \ bill_texts_df['html'].apply(lambda x: bs(x, 'html.parser')) bill_texts_df[...
73a8a850fa15f8ad33f9f823f9b2b4d6f808826b
3,647,048
def _as_static(data, fs): """Get data into the Pyglet audio format.""" fs = int(fs) if data.ndim not in (1, 2): raise ValueError('Data must have one or two dimensions') n_ch = data.shape[0] if data.ndim == 2 else 1 audio_format = AudioFormat(channels=n_ch, sample_size=16, ...
b76d4c49107f8b9679e975bd2ce114314289d181
3,647,049
def preprocess_data(cubes, time_slice: dict = None): """Regrid the data to the first cube and optional time-slicing.""" # Increase TEST_REVISION anytime you make changes to this function. if time_slice: cubes = [extract_time(cube, **time_slice) for cube in cubes] first_cube = cubes[0] # re...
82e851bda39a4ab7716c7b9cd6038743961d9faf
3,647,050
import base64 def password_to_str(password): """ 加密 :param password: :return: """ def add_to_16(password): while len(password) % 16 != 0: password += '\0' return str.encode(password) # 返回bytes key = 'saierwangluo' # 密钥 aes = AES.new(add_to_16(key), AES.M...
60a6d361d6de3c41d2a27cd24312006920ad1013
3,647,051
from src.Emails.checker.mailru import checker import re import requests def email_checker_mailru(request: Request, email: str): """ This API check email from mail.ru<br> <pre> :return: JSON<br> </pre> Example:<br> <br> <code> https://server1.majhcc.xyz/api/email/checker/mailru?emai...
2835439d3c7781efa0c244c881f42a404a8d3cad
3,647,052
from typing import Callable def guild_only() -> Callable: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.NoPrivateMessage` that is inherited...
40307b2a8672180b2a3532380f11b2701bcf0dd8
3,647,053
from typing import Union from typing import List from typing import Callable from typing import Any from typing import Sequence def make_lvis_metrics( save_folder=None, filename_prefix="model_output", iou_types: Union[str, List[str]] = "bbox", summarize_to_stdout: bool = True, evaluator_factory: C...
cbb3df8d8e9daa7976a7be7d6c0588e943aecd5e
3,647,054
def _calculate_cos_loop(graph, threebody_cutoff=4.0): """ Calculate the cosine theta of triplets using loops Args: graph: List Returns: a list of cosine theta values """ pair_vector = get_pair_vector_from_graph(graph) _, _, n_sites = tf.unique_with_counts(graph[Index.BOND_ATOM_INDICE...
3a3283a67c743b2bb7f7a9627e6847dcfc286276
3,647,055
def load_plugin(): """ Returns plugin available in this module """ return HostTestPluginCopyMethod_Firefox()
26df11d662b3d4f98a294df9c61841c1ab76e8fc
3,647,056
import logging def temp_url_page(rid): """ Temporary page where receipts are stored. The user, which visits it first, get the receipt. :param rid: (str) receipt id (user is assigned to receipt with this id) """ if not user_handler.assign_rid_user(rid, flask.session['username']): logging.w...
e5ebfe4602e427b4d96cdf1c0298057a5b472052
3,647,057
def extract_dependencies(content): """ Extract the dependencies from the CMake code. The `find_package()` and `pkg_check_modules` calls must be on a single line and the first argument must be a literal string for this function to be able to extract the dependency name. :param str content: The ...
d9f114695cb3622f4a8dbc23db3a97ed53b164ad
3,647,058
def _block(x, out_channels, name, conv=conv2d, kernel=(3, 3), strides=(2, 2), dilations=(1, 1), update_collection=None, act=tf.nn.leaky_relu, pooling='avg', padding='SAME', batch_norm=False): """Builds the residual blocks used in the discriminator in GAN. Args: x: The 4D input vector. ou...
21851730e1326b85023d88661da13020c37aa723
3,647,059
def createLaplaceGaussianKernel(sigma, size): """构建高斯拉普拉斯卷积核 Args: sigma ([float]): 高斯函数的标准差 size ([tuple]): 高斯核的大小,奇数 Returns: [ndarray]: 高斯拉普拉斯卷积核 """ H, W = size r, c = np.mgrid[0:H:1, 0:W:1] r = r - (H - 1) / 2 c = c - (W - 1) / 2 sigma2 = pow(sigma, 2....
aae788ba324a243691391a61b02e6a5f1b358c4e
3,647,060
import os def is_file_type(fpath, filename, ext_list): """Returns true if file is valid, not hidden, and has extension of given type""" file_parts = filename.split('.') # invalid file if not os.path.isfile(os.path.join(fpath, filename)): return False # hidden file elif filename.startswith('.'): ...
52213f023313e4edb5628fcebf47cb94bc2cfcbe
3,647,061
def xp_rirgen2(room, source_loc, mic_loc, c=340, fs=16000, t60=0.5, beta=None, nsamples=None, htw=None, hpfilt=True, method=1): """Generates room impulse responses corresponding to each source-microphone pair placed in a room. Args: room (numpy/cupy array) = room dimensions in meters, sha...
2528cf725df14febb20c5634fbe9acbeadfd5a46
3,647,062
import warnings def mean_bias_removal(hindcast, alignment, cross_validate=True, **metric_kwargs): """Calc and remove bias from py:class:`~climpred.classes.HindcastEnsemble`. Args: hindcast (HindcastEnsemble): hindcast. alignment (str): which inits or verification times should be aligned? ...
01155462155d9f718fa2a12053297903d47b6661
3,647,063
import requests def request_sudoku_valid(sudoku: str) -> bool: """valid request""" is_valid = False provider_request = requests.get(f"{base_url}/valid/{sudoku}") if provider_request.status_code == 200: request_data = provider_request.json() is_valid = request_data["result"] # TODO:...
274a6f3e617273d1a1d81777788865337d4d36ae
3,647,064
def index(): """ vista principal """ return "<i>API RestFull PARCES Version 0.1</i>"
8b8b963f75395df665bcf0283528c9641b3ea20e
3,647,065
def tag(dicts, key, value): """Adds the key value to each dict in the sequence""" for d in dicts: d[key] = value return dicts
ffcfda13845fb8b522e50211184104a11da50398
3,647,066
def openpairshelf(filename, flag='c', protocol=None, writeback=False): """Returns a ProteinPairDB object, with similar functionality to shelve.open()""" return ProteinPairDB(filename, flag, protocol, writeback)
886a474aa67f729461995fe5427d5f68b9db9fe0
3,647,067
def createUser(emailid, password, contact_no, firstname, lastname, category, address, description, company_url, image_url, con=None, cur=None, db=None): """ Tries to create a new user with the given data. Returns: - dict: dict object containing all user data, if query was successfull - Fals...
05dc71db991e126d43fd9ddd044f1cf65f3e97c1
3,647,068
import pathlib import subprocess import json import re def sensor_pull_storage(appname, accesskey, timestring, *,data_folder = None, ttn_version=3): """ Pull data from TTN via the TTN storage API. appname is the name of the TTN app accesskey is the full accesskey from ttn. For TTN V3, this is is the secret t...
704a039d23443d4ec45968596ec948237e9a2c29
3,647,069
async def discordView(cls:"PhaazebotWeb", WebRequest:ExtendedRequest) -> Response: """ Default url: /discord/view/{guild_id:\d+} """ PhaazeDiscord:"PhaazebotDiscord" = cls.BASE.Discord if not PhaazeDiscord: return await cls.Tree.errors.notAllowed(cls, WebRequest, msg="Discord module is not active") guild_id:st...
76f222bdd5164c23c95803d47fc1af48d89192e2
3,647,070
def update_max_braking_decel(vehicle, mbd): """ Updates the max braking decel of the vehicle :param vehicle: vehicle :param mbd: new max braking decel :type vehicle: VehicleProfile :return: Updated vehicle """ return vehicle.update_max_braking_decel(mbd)
dea3bf14ca14363246539fd81cf853cd2c0ad980
3,647,071
from scipy.spatial.distance import pdist, squareform def get_outlier_removal_mask(xcoords, ycoords, nth_neighbor=10, quantile=.9): """ Parameters ---------- xcoords : ycoords : nth_neighbor : (Default value = 10) quantile : (Default value = .9) Ret...
8d01088401405613696ced2dbbd9c03940417f10
3,647,072
def _kp(a, b): """Special case Kronecker tensor product of a[i] and b[i] at each time interval i for i = 0 .. N-1 It is specialized for the case where both a and b are shape N x m x 1 """ if a.shape != b.shape or a.shape[-1] != 1: raise(ValueError) N = a.shape[0] # take the outer pro...
b133557d88deac2d9357731d820de0522521d6f3
3,647,073
def strategy(history, alivePlayers, whoami, memory): """ history contains all previous rounds (key : id of player (shooter), value : id of player (target)) alivePlayers is a list of all player ids whoami is your own id (to not kill yourself by mistake) memory is None by default and t...
f211a0961269808d9a7b0a08758273d4a03b9136
3,647,074
def parse_fn(serialized_example: bytes) -> FeaturesType: """Parses and converts Tensors for this module's Features. This casts the audio_raw_pcm16 feature to float32 and scales it into the range [-1.0, 1.0]. Args: serialized_example: A serialized tf.train.ExampleProto with the features dict keys dec...
54e841987986027dc6d4d989fe6442ceecd022b8
3,647,075
import click def cli(ctx: click.Context) -> int: """ Method used to declare root CLI command through decorators. """ return 0
be5016c5c38f435b8a213a6ce39b5571aee809f1
3,647,076
def parse_clock(line): """Parse clock information""" search = parse(REGEX_CLOCK, line) if search: return int(search.group('clock')) else: return None
a4464c979d31bab463f949bec83da99e72af6ca6
3,647,077
import requests def block_latest(self, **kwargs): """ Return the latest block available to the backends, also known as the tip of the blockchain. https://docs.blockfrost.io/#tag/Cardano-Blocks/paths/~1blocks~1latest/get :param return_type: Optional. "object", "json" or "pandas". Default: "object". ...
a14fc3512138c1d15b32b09bd20ea03678964437
3,647,078
def get_courses(): """ Route to display all courses """ params = format_dict(request.args) if params: try: result = Course.query.filter_by(**params).order_by(Course.active.desc()) except InvalidRequestError: return { 'message': 'One or more parameter(s) does ...
6dcdcb5df4d0010661ffe92f55522638ae51a2b8
3,647,079
def zero_adam_param_states(state: flax.optim.OptimizerState, selector: str): """Applies a gradient for a set of parameters. Args: state: a named tuple containing the state of the optimizer selector: a path string defining which parameters to freeze. Returns: A tuple containing the new pa...
8a7cb65028866e4a7f3a03b589fa1bf5798a25e0
3,647,080
import scipy def leftFitNormal(population): """ Obtain mode and standard deviation from the left side of a population. >>> pop = np.random.normal(loc=-20, scale=3, size=15000) >>> mode, sigma = leftFitNormal(pop) >>> -22 < mode < -18 True >>> round(sigma) 3 >>> pop[pop > ...
28fbd93efa893dbb31e81d9875db97370f163716
3,647,081
from bs4 import BeautifulSoup def get_stock_market_list(corp_cls: str, include_corp_name=True) -> dict: """ 상장 회사 dictionary 반환 Parameters ---------- corp_cls: str Y: stock market(코스피), K: kosdaq market(코스닥), N: konex Market(코넥스) include_corp_name: bool, optional if True, returnin...
c8e0242e1ddfcc4f32514f131f3a9797694202c1
3,647,082
def evaluate_template(template: dict) -> dict: """ This function resolves the template by parsing the T2WML expressions and replacing them by the class trees of those expressions :param template: :return: """ response = dict() for key, value in template.items(): if key == 'qualifier': response[key] = [] ...
596516f9dfb81170212020cfb053339ddb49b716
3,647,083
def get_CommandeProduits(path, prefix='CP_',cleaned=False): """ Read CSV (CommandeProduits) into Dataframe. All relevant columns are kept and renamed with prefix. Args: path (str): file path to CommandeProduits.csv prefix (str): All relevant columns are renamed with prefix Returns: ...
18c5c7e375abcc57c2cfcbc4f2c58ecec5aecf59
3,647,084
def hist_equal(image, hist): """ Equalize an image based on a histogram. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. hist : af.Array - Containing the histogram o...
70aeeb1822752c2f7fb5085d761bb9b309d29335
3,647,085
def get_close_icon(x1, y1, height, width): """percentage = 0.1 height = -1 while height < 15 and percentage < 1.0: height = int((y2 - y1) * percentage) percentage += 0.1 return (x2 - height), y1, x2, (y1 + height)""" return x1, y1, x1 + 15, y1 + 15
78b65cdeeb4f6b3a526fd5dd41b34f35545f1e9d
3,647,086
def train_model(network, data, labels, batch_size, epochs, validation_data=None, verbose=True, shuffle=False): """ Train """ model = network.fit( data, labels, batch_size=batch_size, epochs=epochs, validation_data=validation_data, shuffle=s...
a2b093aef1b607cd34dd30e8c5f126e1efb3d409
3,647,087
def taoyuan_agrichannel_irrigation_transfer_loss_rate(): """ Real Name: TaoYuan AgriChannel Irrigation Transfer Loss Rate Original Eqn: 0 Units: m3/m3 Limits: (None, None) Type: constant Subs: None This is "no loss rate" version. """ return 0
9fd8a84ae79cbeaf8c8259da815f9322f27b253f
3,647,088
def lambda_handler(event, context): """ Find and replace following words and outputs the result. Oracle -> Oracle© Google -> Google© Microsoft -> Microsoft© Amazon -> Amazon© Deloitte -> Deloitte© Example input: “We really like the new security features of Google Cloud”. Expected ...
66dc2914dd04a2e265ed21542bd462b61344d040
3,647,089
def update_inv(X, X_inv, i, v): """Computes a rank 1 update of the the inverse of a symmetrical matrix. Given a symmerical matrix X and its inverse X^{-1}, this function computes the inverse of Y, which is a copy of X, with the i'th row&column replaced by given vector v. Parameters ---------- ...
c811dbf699d8f93fa2fa5b3f68c5b23cf4131e9f
3,647,090
import csv def read_barcode_lineno_map(stream): """Build a map of barcodes to line number from a stream This builds a one based dictionary of barcode to line numbers. """ barcodes = {} reader = csv.reader(stream, delimiter="\t") for i, line in enumerate(reader): barcodes[line[0]] = i ...
545a0d02dd76e774ba0de86431113ad9f36a098e
3,647,091
def match_in_candidate_innings(entry, innings, summary_innings, entities): """ :param entry: :param innings: innings to be searched in :param summary_innings: innings mentioned in the summary segment :param entities: total entities in the segment :return: """ entities_in_summary_inning =...
3551212f79c6ecb298ec6b55aa7b68213b950394
3,647,092
from typing import Optional from typing import Union from typing import Callable from typing import Any def checkpoint( name: Optional[str] = None, on_error: bool = True, cond: Union[bool, Callable[..., bool]] = False, ) -> Callable[[Callable], Any]: """ Create a checkpointing decorator. Args...
39bab1a33523c34b04a2ed7f2efd6467de63b27b
3,647,093
def return_int(bit_len, unsigned=False): """ This function return the decorator that change return value to valid value. The target function of decorator should return only one value e.g. func(*args, **kargs) -> value: """ if bit_len not in VALID_BIT_LENGTH_OF_INT: err = "Value of bit_le...
66121d389a389c6152fd4491ed8a698336e042a2
3,647,094
def get_integral_curve(f, init_xy, x_end, delta): """ solve ode 'dy/dx=f(x,y)' with Euler method """ (x, y) = init_xy xs, ys = [x], [y] for i in np.arange(init_xy[0], x_end, delta): y += delta*f(x, y) x += delta xs.append(x) ys.append(y) return xs, ys
0526643acd37b8d7c2646d3a21d54e9d9f16ef58
3,647,095
def compute_atime_posteriors(sg, proposals, global_srate=1.0, use_ar=False, raw_data=False, event_idx=None): """ compute the bayesian cross-correlation (logodds of signal under an AR noise model...
1029f57fe500ef6f08eec56ab34539d3f9a80637
3,647,096
def search4vowels(pharse :str) -> set: """"Return any vowels found in a supplied word.""" vowels = set('aeiou') return vowels.intersection(set(pharse))
8a45c50828b6ba8d173572ac771eb8fe5ddc5a42
3,647,097
def rsort(s): """Sort sequence s in ascending order. >>> rsort([]) [] >>> rsort([1]) [1] >>> rsort([1, 1, 1]) [1, 1, 1] >>> rsort([1, 2, 3]) [1, 2, 3] >>> rsort([3, 2, 1]) [1, 2, 3] >>> rsort([1, 2, 1]) [1, 1, 2] >>> rsort([1,2,3, 2, 1]) [1, 1, 2, 2, 3] ...
d9f67d713e55d50cd4468ad709f04c7bfea05c71
3,647,098
import os def xdg_data_home(): """Base directory where user specific data files should be stored.""" value = os.getenv('XDG_DATA_HOME') or '$HOME/.local/share/' return os.path.expandvars(value)
db4212def5e4760bbe1da762a74cf09a9ee40d78
3,647,099