content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def parse_print_dur(print_dur): """ Parse formatted string containing print duration to total seconds. >>> parse_print_dur(" 56m 47s") 3407 """ h_index = print_dur.find("h") hours = int(print_dur[h_index - 2 : h_index]) if h_index != -1 else 0 m_index = print_dur.find("m") min...
7b1a29f31ba38e7d25b4dca9600d4be96a1da3ac
39,814
def skin(image_path, thres=500): """ Extract the skin and create a mesh. Parameters ---------- image_path: str the MRI image we want to extract the skin. thres: int the skin threshold. Returns ------- actor: vtkActor one actor handling the surface. """ #...
1e514ec97e903332dcb7b076a131ef0d52b6719c
39,815
def Contract_CloneComboLegs(dst, src): """Contract_CloneComboLegs(Contract::ComboLegListSPtr & dst, Contract::ComboLegListSPtr const & src)""" return _swigibpy.Contract_CloneComboLegs(dst, src)
ba19c03fd0892d9e19bbf5bbb021b191915203be
39,816
from datetime import datetime def read_datetext(sPathTxt_): """ Return date array from text file sPathTxt. """ lstD = [datetime.date(*[int(s) for s in l.strip().split('.')]) for l in open(sPathTxt_, 'r').readlines()] return np.array(lstD)
ef8ff8e940b9dc73d2ff322ff2fb2ccf845292aa
39,817
def welcoming(): """ Welcoming for user """ return(""" ************************************************* ** ** ** Welcome to speech emotion recognition! ** ** ** ********...
b3bcd19adda9cc8aa9678e823d1e524ba36f80af
39,818
def report_threadpool_stats(threadpool, prefix="threadpool"): """Report stats about a given threadpool.""" def report(): return {prefix + ".working": len(threadpool.working), prefix + ".queue": threadpool.q.qsize(), prefix + ".waiters": len(threadpool.waiters), ...
6a3e66c813b7754f02416e91b68a27084b8b1504
39,819
def Calc_Hot_Pixels(ts_dem,QC_Map, water_mask, NDVI,NDVIhot_low,NDVIhot_high,Hot_Pixel_Constant): """ Function to calculates the hot pixels based on the surface temperature and NDVI """ for_hot = np.copy(ts_dem) for_hot[NDVI <= NDVIhot_low] = np.nan for_hot[NDVI >= NDVIhot_high] = np.nan fo...
fd25495001d24aef4a6a134245986901c16049f6
39,820
def _find_vlan(mac, domain_interfaces): """ Given a mac address and a collection of domains and their network interfaces, find the domain that is assigned the interface with the desired mac address. Parameters ---------- mac : str The MAC address. domain_interfaces : dict ...
c4f667dd80146de83157e8966cb34e5867457397
39,821
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start<br/>" f"/api/v1.0/start/end" )
1ef135fbebbf8ad7f64b6096635550304b819e87
39,822
from typing import Dict def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]: """Split equations into differential algebraic and algebraic only""" dae = [] alg = [] for eq in ca.vertsplit(eqs): if ca.depends_on(eq, dx): dae.append(eq) else: alg.append(eq) ...
a1b7d72eeae6597047c641f036857a162d162bc9
39,824
def CalScore(names_d, daily_d, once_intime=2, once_late=1.5, twice_intime=1, twice_late=0.5): """ Calculate daily score. """ due = daily_d["due"] due = parse(due, settings={'TIMEZONE': 'US/Eastern'}) actions = daily_d["actions"] for act in actions: if act["type"]=="ad...
4c044c10cd086b49716f1e618ddb1070944384cd
39,825
def test_average_pool_4(op_tester): """ The Identity case """ d1 = np.random.rand(4, 256, 6, 6).astype(np.float16) def init_builder(builder): i1 = builder.addInputTensor(d1) o = builder.aiOnnx.averagepool([i1], kernel_shape=[1, 1], ...
4b6a4da15830adef1fd23536e721fe115843d4e3
39,826
import numpy def insert_dummies_on_linear_atoms(geo, lin_idxs=None, gra=None, dist=1., tol=5.): """ Insert dummy atoms over linear atoms in the geometry. :param geo: the geometry :type geo: automol molecular geometry data structure :param lin_idxs: the i...
06219b3b070a58e01ea6cfe881d7b6fa8b32748b
39,828
import time def get_times(T, dt, ex_in_rate, ns, input_intensity, stop_between=0): """Return computation times for numpy and tensorflow models for networks with n neuron for n in ns""" # Storage vectors for computation times tf_build_times = np.empty((len(ns), 1), dtype=np.float32) np_build_ti...
5eeea894c1bdbc4ecc594e4b598ad1163ddf8c8b
39,829
def SO( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-07-12", **kwargs ) -> Graph: """Retu...
2a597f4311796b97257b7715f65ce0f63d24f595
39,830
import collections import json def parse_peptides(tumfile, normfile, prefix, suffix): """ This module takes in a peptides file and squashes it into the minimum number of peptides required to describe the potential neo-immunopeptidome. It's main function is to take transcript-level mutation calls and ...
e708c5fc63078f3913472740933feb792ea8701d
39,831
def get_prefixer(prefix: str, resolver: UrlResolver = lambda x: x) -> UrlResolver: """Returns a `UrlResolver` that prefixes otherwise invalid URLs with `prefix`. """ def prefixer(url: str) -> str: url = resolver(url) if url.startswith("http"): return url return prefi...
53334bbcfbcc5e5ca479c5f84ff6f5adb0d5f5b7
39,834
def NASNetLarge( input_shape=None, include_top=True, weights="imagenet", input_tensor=None, pooling=None, classes=1000, ): """ ImageNet ๋ชจ๋“œ์—์„œ, NASNet ๋ชจ๋ธ์„ ์ธ์Šคํ„ด์Šคํ™”ํ•ฉ๋‹ˆ๋‹ค. ์„ ํƒ์ ์œผ๋กœ ImageNet์—์„œ ์‚ฌ์ „ ํŠธ๋ ˆ์ด๋‹๋œ ๊ฐ€์ค‘์น˜๋ฅผ ๋กœ๋“œํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋ธ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ์ดํ„ฐ ํ˜•์‹ ๊ทœ์น™์€ Keras ๊ตฌ์„ฑ `~/.keras/keras.json`์— ์ง€์ •๋œ ๊ทœ์น™์ž…๋‹ˆ๋‹ค. ์ฐธ๊ณ  : ๊ฐ Ke...
fcb8ac7e9156c685ac5149e3ed97fcdc3484bcf3
39,835
def entityAttrsGet(_id): """ Responds to GET requests sent to the /v1/entities/<_id>/attrs API endpoint. """ accepted, content_type = hiascdi.process_headers(request) if accepted is False: return hiascdi.respond( 406, hiascdi.confs["errorMessages"][str(406)], "application/js...
b140b6bf921c7a4f74df2f9cef973bd769e00867
39,836
from typing import Union def r_to_oxd( r: Union[np.ndarray, xr.DataArray, float], r_min: float = 0.852, r_max: float = 6.65, instrument_factor: float = 0.171, ): """ Convert ratios to OxD Parameters ---------- r r_min r_max instrument_factor Returns ------- ...
ac4699c02927addbc7955608fffa12df7c10a63a
39,837
def box_utils_expand_boxes(boxes, scale): """Expand an array of boxes by a given scale.""" w_half = (boxes[:, 2] - boxes[:, 0]) * .5 h_half = (boxes[:, 3] - boxes[:, 1]) * .5 x_c = (boxes[:, 2] + boxes[:, 0]) * .5 y_c = (boxes[:, 3] + boxes[:, 1]) * .5 w_half *= scale h_half *= scale b...
3ef6be9d33c255bf1f2202540d95e3f7f81faf66
39,838
def get_regions(): """Get list of all AWS regions""" client = boto3.client("ec2") response = client.describe_regions() regions = [region["RegionName"] for region in response["Regions"]] return regions
e8052e59262a2af091f2587e9c58fdd92c4826e7
39,841
def prepare_labels(cells: list, root_labels: str, root_images: str) -> np.ndarray: """ Convinience for label load. Takes a list of cells (the naming is used to refer to the fact that we often use minipics of cells from tables - they need not be cells. Just any list of strings such that the strings are ...
f5a8f1dc65c05b9803104bc99c4fcfbdc6974e0e
39,843
import functools def which(exe): """ Decorator wrapper for salt.utils.path.which """ def wrapper(function): @functools.wraps(function) def wrapped(*args, **kwargs): if salt.utils.path.which(exe) is None: raise CommandNotFoundError( "The ...
a21b2e91ba44a9ded71cac439f25e00af65bef25
39,844
def st_grep_on_off(what, to_find_on=None, to_find_off=None, n=1, rev=False, verbose=False): """ filter a list of strings for groups delimited by "on" /"off" input: list of strings output: list of strings use n to select how many groups to return warning: does not accept word_only yet! """ line...
90f1e190114e750c1317f72e9e8fc5218b4c8853
39,845
def tests(): """ Make these Unittests for each function. """ tests_list = [ 'assertNotEqual', 'assertEqual' ] return tests_list
cdba4e6293df2231640d6896a5104791cdf073be
39,846
def view(request): """ A minimal view for use in testing. """ return HttpResponse("Content.")
2cb59d2cc4e136f1760186bd41aa1852a0d1fdc0
39,847
def prodtab_321(): """ produces angular distance from [3,2,2] plane with other planes up to (321) type """ listangles_321 = [anglebetween([3, 2, 1], elemref) for elemref in LISTNEIGHBORS_321] return np.array(listangles_321)
f1c6c4e62ec3a274561966042a7f3f2331ea39f6
39,848
from operator import add def gradient_step(v: Vector, gradient: Vector, step_size: float) -> Vector: """Moves `step_size` in the `gradient` direction from `v`""" assert len(v) == len(gradient) step = scalar_multiply(step_size, gradient) return add(v, step)
9894976ccb06423dcfcfc491314dee1c97a33c00
39,849
def _inactiveplayers(): """ Scrape DB to find players who are not on active rosters. """ rosters = _activerosters() dbrosters = _eidset() # players not in rosters scrape but in db. notactive = dbrosters.difference(rosters) return notactive
12bd8c7ba27992a856b9e02eefc51395662f0e21
39,850
def logoutHttpMethods(request,*args,**kwargs): """ ๆณจ้”€ :param request: :param args: :param kwargs: :return: """ logout(request) return response_success()
14480c529bb13a6ed85af9ae0b600f9720231027
39,851
def isPostCSP(t, switch=961986575.): """ Given a GALEX time stamp, return TRUE if it corresponds to a "post-CSP" eclipse. The actual CSP was on eclipse 37423, but the clock change (which matters more for calibration purposes) occured on 38268 (t~=961986575.) :param t: The time stamp...
2b731ec0bb06ce08d2a36137e3d48563e5cb0c11
39,852
def build_wheels(dist_dir, pip_wheel_args): """build wheels using pip wheel command line tool""" args = ["pip", "wheel", "--wheel-dir", dist_dir] + pip_wheel_args spawn(args) return dist_dir
5b7cd19cc4cf6bf400d54f0dd01b65b88f64c0c7
39,853
def taoyuan_water_supply_network_1(): """ Real Name: TaoYuan Water Supply Network 1 Original Eqn: 0 Units: m3 Limits: (None, None) Type: constant primary design assumes zero in this model, which means does not consider the impact of this pipeline. """ return 0
ee1d3c739d55fce93edfce77890d9abc6a96ed92
39,854
from typing import OrderedDict def convert_trsp_index(geneDictNonCoding, df, TR_index_dict): """ take input geneDict and output a single transcript for each gene use transcript slices defined in TR_index_dict for noncoding genes, take the longest transcripts There are ~7 snoRNAs that have multiple noncoding ...
8c9af2e10e3e25305e660c23d2b9c7d738283eb1
39,855
def menunode_fieldfill(caller, raw_string, **kwargs): """ This is an EvMenu node, which calls itself over and over in order to allow a player to enter values into a fillable form. When the form is submitted, the form data is passed to a callback as a dictionary. """ # Retrieve menu info - taken...
f08fdbfdd57a4383b51b23a60c1c59df1638df50
39,856
def scaleBenchmarks(runLength, benchmark='design'): """ Set the design and stretch values of the number of visits, area of the footprint, seeing values, FWHMeff values, skybrightness, and single visit depth (based on SRD values). Scales number of visits for the length of the run, relative to 10 years. ...
b31a6719bb788fed8f6c1da768eee0cbf925c8d3
39,857
from unittest.mock import patch def patch_validate_gpg_sig(return_value): """ Mocks the InsightsUploadConf.validate_gpg_sig method so it returns the given validation result. """ def decorator(old_function): patcher = patch("insights.client.collection_rules.InsightsUploadConf.validate_gpg_sig",...
f1cdf8605718c197fad7dec53113ef0d7ba17c39
39,859
def _ncac_to_stubs(ncac): """ Vector const & center, Vector const & a, Vector const & b, Vector const & c ) { Vector e1( a - b); e1.normalize(); Vector e3( cross( e1, c - b ) ); e3.normalize(); Vector e2( cross( e3,e1) ); M.col...
67dc2475d04ddb660949aebbb5273f48fd6f8761
39,860
def constructBayesNet(gameState): """ Question 1: Bayes net structure Construct an empty Bayes net according to the structure given in the project description. There are 5 kinds of variables in this Bayes net: - a single "x position" variable (controlling the x pos of the houses) - a singl...
1fff7cc9c1cdef09242372be6d9fc5908ee70642
39,861
def __cocoseg_to_binary(seg, height, width): """ COCO style segmentation to binary mask :param seg: coco-style segmentation :param height: image height :param width: image width :return: binary mask """ if type(seg) == list: rle = cocomask.frPyObjects(seg, height, width) ...
3735eb59838b3bb8816d306a4be273442f425b50
39,863
import uuid def get_a_uuid() -> str: """Gets a base 64 uuid Returns: The id that was generated """ r_uuid = str(uuid.uuid4()) return r_uuid
20e87638c3718b4b75ffc48cf980216120edaea8
39,864
from pathlib import Path def cookiecutter_cache_path(template): """ Determine the cookiecutter template cache directory given a template URL. This will return a valid path, regardless of whether `template` :param template: The template to use. This can be a filesystem path or a URL. :ret...
cbdc72195bf47fb1bb91368ac2bbca3890775a60
39,865
def libtree(lib): """Generates a filesystem-like directory tree for the files contained in `lib`. Filesystem nodes are (files, dirs) named tuples in which both components are dictionaries. The first maps filenames to Item ids. The second maps directory names to child node tuples. """ root = ...
9d76fa201036ba5a8c05605b914ddbf83c4b2e83
39,866
def generate_comic_html(comic={}): """Generates part HTML for the qotd supplied""" return """ <h3>Dilbert by Scott Adams -</h3> <a href="{0}"><img alt="{1} - Dilbert by Scott Adams" src="{2}"></a> """.format(comic['url'], comic['title'], comic['image'])
6003abddbe7b8f3ca281787b09d92b42907669fb
39,867
def get_cloudify_endpoint(_ctx): """ ctx.endpoint collapses the functionality for local and manager rest clients. :param _ctx: the NodeInstanceContext :return: endpoint object """ if hasattr(_ctx._endpoint, 'storage'): return _ctx._endpoint.storage return _ctx._endpoint
37ac79f564626399bd940d4c9d9fd9fb8417c424
39,868
from typing import Dict from typing import Any def some_invoice(full_invoice_data: Dict[str, Any]) -> Invoice: """Returns some `Invoice`.""" return Invoice(**full_invoice_data)
4cf1a8ce0c32d217392cc4a621bda5f1956656c3
39,869
def order_by(field, desc=False): """ Allows ordering of results. You may only ever order a collection's results once in a given request. For example:: # sort results by Instances group client.linode.instances(order_by(Instance.group)) :param field: The field to order results by. Must ...
9b4c000a261d315da132b1d721242bd646eabc95
39,870
def new_post(): """NEW-POST page which allows users to create new blog posts.""" form = PostForm() if form.validate_on_submit(): post = Post( user=current_user, title=form.data.get("title"), body=form.data.get("body") ) db.session.add(post) db.session.commit() ...
beb75ff7349b7a3bfbaa73c9e22506055d20689f
39,871
def qsin(dataset, ssb=1, **kwargs): """ Equivalent to :meth:`sp`, with pow = 2 (squared sine bell apodization window). See Also -------- em, gm, sp, sine, sinm, hamming, triang, bartlett, blackmanharris """ return sp(dataset, ssb=ssb, pow=2, **kwargs)
6a58c48e7f8afe49f5a0a48e0169aae2217ff970
39,872
def standardize_smiles(smiles): """Return a standardized canonical SMILES string given a SMILES string. Note: This is a convenience function for quickly standardizing a single SMILES string. It is more efficient to use the :class:`~molvs.standardize.Standardizer` class directly when working with many molec...
dd05ce98f2deb9a24dfe93a37c2b556ba9dfdb8e
39,873
import random def geraPalavraAleatรณria(): """ Funรงรฃo que retorna uma string a partir da lista de palavras global """ global palavras return random.choice(palavras)
a6482c865a3ebd8229e85826359186b63e348af0
39,874
def get_iphot_line(iphot, linenum, lcobject, iphotlinechars=338): """ This gets a random iphot line out of the file iphot. """ iphotf = open(iphot, 'rb') filelinenum = iphotlinechars*linenum if filelinenum > 0: iphotf.seek(filelinenum - 100) else: iphotf.seek(filelinenum) ...
4ca9aa58f915bef8264316614ab9b73e733bbdb3
39,875
import logging import platform def get_sys_cards(): """This function retrieves the system cards using nvsmi for linux and windows; macOS support is in the works. :return: returns a tuple containing the in `gpu_ratios_min` and actual `gpu_ratios`; the difference being that the latter is sorted in asce...
14ba62996e7833dd85d573392db64de75f110cc6
39,876
def get_initial_density(xgrid, ygrid): """ Initialize a "relatively" random density profile. Please see notebook for visualization :param xgrid: :param ygrid: :return: """ xm, ym = np.meshgrid(xgrid, ygrid, indexing="ij") x0 = np.random.uniform(0.5 * xgrid.min(), 0.0) y0 = np.random...
cac62af297acf4903e4a5a9e7d505431015070dc
39,877
def get_vendors(ven): """ Input arguments for function = tuple Coverts tuple into a list. I know, it is silly. Input example: get_vendors(("Neste", "Circle K")) Output example: ['Neste', 'Circle K'] """ vendors_list = list(ven) return vendors_list
7703a1efc2f6cb329f8c15dc4df19a966d3c4197
39,878
def delete_all_closed(bot, update, session, user): """Delete all closed polls of the user.""" for poll in user.polls: if poll.closed: session.delete(poll) return i18n.t('deleted.closed_polls', locale=user.locale)
eca0cf8726cdde29eb999053e4e3b2564e6e0e3f
39,879
def BS_call(S, K, r, sigma, T): """Define a function of Black_Scholes for call option(without dividend) """ d1 = (np.log(S / K) + (r + 0.5 * np.power(sigma, 2))* T) / sigma / np.sqrt(T) d2 = d1 - sigma*np.sqrt(T) C = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2) return C
10c14dab21d33fed801654194ef1d209027d2c67
39,880
def publish_checklist(request, checklist_id): # for "messages", refer https://stackoverflow.com/a/61603003/6543250 """if user cannot retract upvote, then this code be uncommented if Upvote.objects.filter(user=User.objects.filter(username=username).first(), checklist=Checklist.objects.get(id=checklist_id)):...
ec215711b1219174e7a6117f84a947ac69d4c707
39,881
def get_menu_items(soup): """Return a dictionary of key menu-items and value prices""" items = clean(soup.find_all(class_="menu-item__name")) # has tags prices = clean(soup.find_all(class_="menu-item__price")) # has tags menu_items = dict(zip(items, prices)) # zip into dict with item:price retu...
7d73fb3210ae67ce9a7055be3fc8fc7bd318addc
39,882
def only_max(sim, rtrv, y, y_hat, y_lrn, y_ex, ex_counts, n_ex, n_y, sim_pars): """ Only the most similar exemplar has a non-zero learning rate, which is constant. Notes ----- This is the form of learning assumed by Ghirlanda (2015) when showing the equivalence between exemplar and RW famil...
2790d3af3cd6a786776af44a2a33bdf1c00492a3
39,883
def analyse_book(gutenberg_file): """Takes a text file from the Gutenberg Project, returns a list of words in book that are not in word_list""" result = [] word_usage.clear() fin = open(gutenberg_file) remove_header(fin) for line in fin: if '*** END OF' in line: break ...
efabc433e749a525b141614d1c0045f0997cc04c
39,884
def is_format(fid): """ Check the raw file for frequency base """ first = fid.readline() first = first.strip().split('/') first = first[0].split(',') if float(first[5]) == 50.0 or float(first[5]) == 60.0: return True else: return False
7eeefbacad859afb6e179c530aec41d90f6c5bb1
39,885
def load_raw_ens_data(data_dir): """ Loads raw ensemble [time, ens, station] """ rg = Dataset(data_dir + 'data_interpolated_00UTC.nc') ens = rg.variables['t2m_fc'][:] return ens
6a8ab674b942f501cfce9b33189af13f2d3692c2
39,887
from typing import Any from datetime import datetime def stringify_mongovalues(v: Any): """ Mostly the values are fine, but at least datetime needs handled. Also need to handle datetimes embedded in dicts, so use recursion to get them. """ if type(v) == datetime: return v.isoformat() e...
27349086a58681f0d06ce795b3792cc4e25e97fc
39,888
def ftp_quit(): """ Quit session """ f_quit = FTP.quit() return f_quit
83987196f3ad9b8d11d11ab2ea8088291b0e048f
39,890
def multi_pred(exe, gw, gf, program, y_pred, seq, batch_size, \ n_his, n_pred, step_idx, dynamic_batch=True): """multi step prediction""" pred_list = [] for i in gen_batch( seq, min(batch_size, len(seq)), dynamic_batch=dynamic_batch): # Note: use np.copy() to avoid the modificat...
de41c95b0667aa8ce1dc411ae2c09c73711f2e3d
39,891
def max_gram_basis(op_labels, dataset, max_length=0): """ Compute a maximal set of basis circuits for a Gram matrix. That is, a maximal set of strings {S_i} such that the gate strings { S_i S_j } are all present in dataset. If max_length > 0, then restrict len(S_i) <= max_length. Parameters ...
8d104f91ee70b6a9db74f80edfbc9d5de8e3a3f3
39,892
import click def create_cli() -> click.Command: """Build and return an instance of `queso`. # Returns cli (click.Command): contains both built-in and custom commands. """ @click.group(name="queso", cls=CustomCommandsGroup) @version_option("-v", "-V", "--version") def cli(): pass ...
8046490563aa137af74825890c9228f489ee179f
39,893
def nodeSetAdd(nset, newNSet, op): """ Adds newNSet to the nset using operation op. nset : the currrent nodes set (or None). newNSet : the new nodes set. op : the operation type. Returns : the combined nodes set or None if an error occurs. """ return xmlsecmod.nodeSetAdd(nset, ne...
438d72ec7e89c252c4eb9d14a9d03fb7ac35d341
39,894
def to_web_mercator(x_lon, y_lat): """ Converts lat, long into web mercator. Needed for tiletanic. """ if abs(x_lon) >= 180 and abs(y_lat) > 90: print 'Invalid coordinate values for conversion' return None num = x_lon * 0.017453292519943295 x = 6378137.0 * num a = y_lat * 0.01745329...
1268844a8d4eacb95e6608309e1a97c140a7b6eb
39,895
def down_sample(df, target): """ Fixes imbalanced dataset by down-sampling Parameters ---------- df : pandas.DataFrame target : name of the target column in df Returns ------- downsampled_df : pandas.DataFrame """ dfs = [] target_value_counts = df[target].value_counts()...
dbf3288f838fe46c308279f9aef0f6db7422632e
39,896
from operator import add def mean1(m): """mean(m) returns the mean along the first dimension of m. Note: if m is an integer array, integer division will occur. """ return add.reduce(m)/len(m)
79acbc4cdf1750a82d9d223207de47d5ddcb1302
39,898
import math def H_cond(X, Y, bins): """ Calculates the conditional entropy of X depending on Y. If X and Y are already discretised, set \ref bins to the amount of bins, aka states of X and Y. If X and Y are not discretised, \ref bins will be used, to diskretise X and Y into \ref bins states @para...
a67f639f319aa0fad3fe3a1aeef824c3b81ffe91
39,899
def drop_semantic_duplicates( student_comments: pd.Series ) -> pd.Series: """Remove the duplicate comments based on the comment's semantics, e.g. "I was waiting for 1 hour." and "I waited for 1 hour." are orthographically different, but the semantically the same, so one will be removed ...
7b5ba13e96e33b041d1ef22733a4db3c8f5c6954
39,900
def _clip_bounds(bbox, filename): """Clip input fiona-compatible vector file to input bounding box. :param bbox: Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds. :param filename: Input name of file containing vector data in a format compatible with fiona. :returns: Shapel...
81e79e092dcc59741f446ff44e9ba46b5967425d
39,902
from registration_backend.backend import JotleafBackend def register(request): """ AJAX user registration """ backend = JotleafBackend() if request.method == 'GET': return _new_api_403() data = request.POST.copy() if not backend.registration_allowed(request): return { ...
b6e5e45eef5011ce42c4a573e9837cc25911ad71
39,904
from typing import Dict def create_mapper(df: pd.DataFrame, field_name: str) -> Dict: """ๆŒ‡ๅฎšใ—ใŸ DataFrame ใฎ field_name ใ‚’ๅˆฉ็”จใ—ใŸใ‚ซใƒฉใƒผ็”จใƒžใƒƒใƒ‘ใƒผใ‚’่ฟ”ใ™ Args: df (pd.DataFrame): ๅฏพ่ฑกใจใ™ใ‚‹ใƒ‡ใƒผใ‚ฟใƒ•ใƒฌใƒผใƒ  field_name (str): ใ‚ซใƒฉใƒผใ‚’่ชฟๆ•ดใ™ใ‚‹ใƒ‡ใƒผใ‚ฟๅˆ—ๅ Returns: Dict: ่ชฟๆ•ดใ—ใŸใƒžใƒƒใƒ‘ใƒผ """ mapper = linear_cmap( field_name...
a1dec5a33c0a90d99dc63f8e4c28b5a4af30f06c
39,905
import torch def _ssim_torch(raw_tensor: torch.Tensor, dst_tensor: torch.Tensor, window_size: int, gaussian_kernel_window: np.ndarray) -> float: """PyTorch implements the SSIM (Structural Similarity) function, which only calculates single-channel data Args: ...
3fbd1e18c63a62b880f149f3548f35bf68d54a44
39,906
def create_joint_on_center(): """ Creates a new joint on center of the selected objects or components """ selection = maya.cmds.ls(sl=True) if not selection: return maya.cmds.joint(n='joint#') # if maya.cmds.objectType(selection[0]) != 'mesh': # raise NotImplementedError('Cente...
7fc402c0e97966ee8f52a526be89080d5a1e15a9
39,907
def filter_instances(project): """Filter EC2 instances based on Project tag""" if project: filters = [{'Name': 'tag:Project', 'Values': [project]}] ec2_instances = ec2.instances.filter(Filters=filters) else: ec2_instances = ec2.instances.all() return ec2_instances
9f9eb69a3e80b446074b16db1a018bf067cdda15
39,910
import json def plugin_poll(handle): """ Poll readings from the modbus device and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a reading in a JSON document, as a Python d...
e60fd3e01fb2c23a06e1f261795c9afa2054168c
39,911
from typing import List from typing import Any def validate_unity(unity_permutation: List[Any]) -> bool: """Checks that the input permutation is the unity permutation, i.e., an object s of type List[List[int], float, bool] such that * s[0][0] > -1, * s[0][i] < s[0][j] for i < j, * s[1] = 1.0, and...
6ee49a342c058c2122f58dae715881e7a4228091
39,912
def gf_TC(f, K): """Returns trailing coefficient of `f`. """ if not f: return K.zero else: return f[-1]
d09c0bb3a29cce379a598055e7ea781ff6f6f673
39,913
def shared_podcast_episode_query(user): """ Shared query set for PodcastEpisodesViewSet and RecentPodcastEpisodesViewSet """ return ( PodcastEpisode.objects.filter(published=True, podcast__published=True) .prefetch_related( Prefetch("offered_by", queryset=LearningResourceOff...
dd42159e36f94186bc9ed033c6e01356ab0967a7
39,915
import base64 def convert_image( png_image_base64: str, jpeg_image_quality: int = IMAGE_QUALITY_JPEG ) -> str: """ Convert an image from PNG to JPEG, encoded in Base64. (Semi-)transparent pixels are replaced with (semi-)white pixels in the output JPEG image. Args: png_image_base64: P...
8133da5aee63b35b016bde5c09e44aeb05be1a09
39,917
def merge(*args): """ Merge multiple frame states together """ if not args: return create() s = {arg['identifier'] for arg in args} if len(s) != 1: raise ValueError("Expected identifiers, got %s" % str(s)) children = defaultdict(list) for arg in args: for child in arg['ch...
cf1f4bc54583769f621cc8fdb98aaffe64d75cb7
39,918
def int64_counter(urn, metric, ptransform=None, pcollection=None, labels=None): # type: (...) -> metrics_pb2.MonitoringInfo """Return the counter monitoring info for the specifed URN, metric and labels. Args: urn: The URN of the monitoring info/metric. metric: The payload field to use in the monitoring ...
0f9d05861e923239d25af837aa8d33e8be31fec4
39,919
import six def _to_binary_string_py3(text): """ Converts a string to a binary string if it is not already one. Returns a str in Python 2 and a bytes in Python3. Do not use directly, use to_binary_string instead. """ if isinstance(text, six.binary_type): return text elif isinstance...
393962a4a8e1c0def3a402122be59363572ed6cc
39,920
def get_log_info(prefix='', rconn=None): """Return info log as a list of log strings, newest first. On failure, returns empty list""" if rconn is None: return [] # get data from redis try: logset = rconn.lrange(prefix+"log_info", 0, -1) except: return [] if logset: ...
d333fbeaff754e352a0b84c10f4d28e148badfa0
39,921
def get_hidden_status(data): """ ไฝฟ็”จGaussian HMMๅฏนๆ•ฐๆฎ่ฟ›่กŒๅปบๆจก๏ผŒๅนถๅพ—ๅˆฐ้ข„ๆต‹ๅ€ผ """ cols = ["r_5", "r_20", "a_5", "a_20"] model = GaussianHMM(n_components=3, covariance_type="full", n_iter=1000, random_state=2010) model.fit(data[cols]) hidden_status = model.predict(data[cols]) retu...
a30ea507c261d44bfdf89ed6911db8c2a82666a0
39,922
def N_interrupts(): """(read-only) Number of interruptions this bus per year""" return lib.Bus_Get_N_interrupts()
9974c75574222e11f284c52f7f0e600477258b4c
39,923
def strip_parameter(context, param): """ A template tag to remove the specified parameter from the url string. If there are no parameter left, it returns the bare url (without any parameters or ?-mark) """ query = context["request"].GET.copy() query.pop(param) if len(query): r...
8bfa38f79743fa66ea3e8e966a8577753cbdfe32
39,924
def get_center_radius(ra, dec, logger=logger): """Get a list of RA and DEC coordinates and returns the center and the search radius.""" center_ra = (np.max(ra) + np.min(ra))/2 center_dec = (np.max(dec) + np.min(dec))/2 radius = np.max([np.max(ra) - np.min(ra), np.max(dec) - np.m...
990216ef19f51791a71a9f32cdd4beb2e0a5f353
39,925
def calculate_health(package_name, package_version=None, verbose=False, no_output=False): """ Calculates the health of a package, based on several factors :param package_name: name of package on pypi.python.org :param package_version: version number of package to check, optional - defaults to latest ve...
46029e7563ca0ebb4ac1349b85734786998a1c25
39,926
def _df_to_array(instances): """ Transform inputs into arrays Parameters ---------- instances : DataFrame, Series or array Input data Returns ------- instances : array Transformed features """ if isinstance(instances, pd.DataFrame): return instances.valu...
f0112ef718d4075eda4f041a46d5feaf3e2103d3
39,927
def S2(Scat, Source, phi, theta): """Function compute :math:`S_2` component of scattered FarField defined as Eq:III.111 of B&B. :math:`S_2 = \sum_{n=1}^\\infty \sum_{m=-n}^{n} \\frac{2n+1}{n(n+1)} \\Big[ a_n g_{n,TM}^m \\tau_n^{|m|} \\big(\cos (\\theta) \\big) + m i b_n g_{n,TE...
b8a83e40e606f11aed53dfb045e4c69cd58f8354
39,928
def text_to_html(string): """Take text as input and return html that renders nicely. For example replace newlines with '<br/>' This was built for use in reminder emails, please check for effects there if you are updating it.""" string = "<html><body>" + string + "</body></html>" string = string...
86cbbc0d35bc994450bb16e989264f96c992aaa3
39,929
def spacecraft_vel(deltaw, deltan, deltar, dij, vmap): """ function to calculate pixel-wise spacecraft velocities for Sunpy map Based on Haywood et al. (2016) and described in Ervin et al. (2021) - In Prep. Parameters ---------- deltaw: float, array relative westward position of pixel ...
78c2acffc4f14c3f707cc50e1594ad7012bc1b08
39,930
import types def task__package_mkdir_iso_root() -> types.TaskDict: """Create the packages root directory on the ISO.""" return targets.Mkdir( directory=constants.REPO_ROOT, task_dep=['_iso_mkdir_root'] ).task
5625b04905dff0905ba34a4021d7a9c349bbce0a
39,931