content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def count_related_m2m(model, field): """Return a Subquery suitable for annotating a m2m field count.""" subquery = Subquery(model.objects.filter(**{"pk": OuterRef("pk")}).order_by().annotate(c=Count(field)).values("c")) return Coalesce(subquery, 0)
e772c8d55a1d9778077eaf9cbebfc51948361e1c
3,640,296
def create_car(sql: Session, car: CarsCreate): """ Create a record of car with its Name & Price """ new_car = Cars( Name=car.Name, Price=car.Price ) sql.add(new_car) sql.commit() sql.refresh(new_car) return new_car
33fda0b653950989bd1b61ae1ee689db05576877
3,640,297
import time def train(train_loader, model, criterion, optimizer, args, epoch): """Train process""" '''Set up configuration''' batch_time = AverageMeter() data_time = AverageMeter() am_loss = AverageMeter() vec_loss = AverageMeter() dis_loss = AverageMeter() ske_loss = AverageMeter() ...
fb83156f3915f34dd92d4060b62b77644dd65f8b
3,640,298
def coeff_modulus_192(poly_modulus_degree): """ Returns the default coefficients modulus for a given polynomial modulus degree. :param poly_modulus_degree: Polynomial modulus degree (1024, 2048, 4096, 8192, 16384, or 32768) :return: """ return seal.coeff_modulus_128(poly_modulus_degree)
fa606e19b0deb92e645fef85058146f91f06b012
3,640,300
def __add_statement(is_position: bool) -> Statement: """ Adds a new statement to the database :param is_position: True if the statement should be a position :return: New statement object """ db_statement = Statement(is_position=is_position) DBDiscussionSession.add(db_statement) DBDiscus...
9c5ac1b906ed87961aea50a309e605d7dc28ac38
3,640,301
def xgcd(a: int, b: int) -> tuple: """ Extended Euclidean algorithm. Returns (g, x, y) such that a*x + b*y = g = gcd(a, b). """ x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
3889038824447f65f5d99d5d2a6301d9717948fe
3,640,302
def correct_predictions(output_probabilities, targets): """ 计算与模型输出中的某些目标类匹配的预测数量 Args: output_probabilities: 不同输出类的概率张量 targets: 实际目标类的索引 Returns: 返回:“output_probabilities”中正确预测的数量 """ _, out_classes = output_probabilities.max(dim=1) correct = (out_classes == targets)...
0e39f3bfa00fc20334cf679aa77d89523a34454c
3,640,303
def get_base_url(url: str) -> str: """ Return base URL for given URL. Example: Return http://example.com for input http://example.com/path/path Return scheme://netloc """ url = format_url(url) parsed = parse_url(url) return'{uri.SCHEME}://{uri.NETLOC}/'.format(uri=parsed)
edeb5fa7c2ac1b06ed6f3ed9523e4324f21e6abf
3,640,304
def setup_tutorial(): """ Helper function to check correct configuration of tf and keras for tutorial :return: True if setup checks completed """ # Set TF random seed to improve reproducibility tf.set_random_seed(1234) if not hasattr(backend, "tf"): raise RuntimeError("This tutoria...
2310edce037d3f6fa8fd30b3fb28aaddfc9b941d
3,640,305
import re def split_value(s, splitters=["/", "&", ","]): """Splits a string. The first match in 'splitters' is used as the separator; subsequent matches are intentionally ignored.""" if not splitters: return [s.strip()] values = s.split("\n") for spl in splitters: spl = re.compile(...
a9227a4dcf4c49393e6c784337754d1e2b1d30b4
3,640,306
def smape(y_true: np.ndarray, y_pred: np.ndarray) -> float: """ Calculates symmetric mean absolute percentage error SMAPE Args: y_true (np.ndarray): Actual values Y y_pred (np.ndarray): Predicted values Y Returns: [float]: smape """ error = np.abs(y_true - y_pred) / (np...
33948539bfe13c4f9426bf0bf4c95fcea56a1da5
3,640,307
def dealwithtype( x, t ): """ return x and t as an array broadcast values if shape of x != shape of y and neither x or t are scalar """ x = np.asarray( x ) t = np.asarray( t ) if not x.shape and not t.shape: pass elif not x.shape: x = x*np.ones_like( t ) elif...
5bf440c084d0cf1012e2cdcdf8639d2ff6334e67
3,640,308
def format_img_size(img, C: FasterRcnnConfiguration): """ formats the image size based on config """ img_min_side = float(C.resize_smallest_side_of_image_to) (height, width, _) = img.shape if width <= height: ratio = img_min_side / width new_height = int(ratio * height) new_widt...
9233c92f48ee8c187695be9342f082d540e02a14
3,640,309
def build_tile_count_map(tile_counts): """Build a map from a tile key to a count.""" tile_count_map = defaultdict(int) for tile_count in tile_counts: tile = tile_count.tile tile_key = (tile.letter, tile.value, tile.is_blank) tile_count_map[tile_key] = tile_count.count return tile...
2b4f30e91224db92598925bd4d794d3e96092b07
3,640,310
import requests import json def get_uid_to_user(restful_url): """Gets uid -> user mapping from restful url""" query_url = restful_url + "/GetAllUsers" resp = requests.get(query_url) if resp.status_code != 200: logger.warning("Querying %s failed.", query_url) return {} data = json....
ebdaad0f129ecfdde3b18df4cd16f8e890879064
3,640,311
from typing import List def parse_text(text): """ Parse raw text format playlists, each line must contain a single. track with artist and title separated by a single dash. eg Queen - Bohemian Rhapsody :param str text: :return: A list of tracks """ tracks: List[tuple] = [] for line in...
1307d7ced966aa388e570456964c5921ac54ccca
3,640,312
from re import S def R_nl(n, l, r, Z=1): """ Returns the Hydrogen radial wavefunction R_{nl}. n, l .... quantum numbers 'n' and 'l' r .... radial coordinate Z .... atomic number (1 for Hydrogen, 2 for Helium, ...) Everything is in Hartree atomic units. Examples:: >>> from sym...
6102519a8d32e61cbdbb689c02f36b13b8c4b840
3,640,313
def entity_by_name(name): """Adapt Entity.name (not Entity.class_name!) to entity.""" entities = zope.component.getUtility( icemac.addressbook.interfaces.IEntities).getEntities(sorted=False) for candidate in entities: if candidate.name == name: return candidate raise ValueErr...
42f3d2ecf172db6b0a54590d1d983b563e8c4d52
3,640,314
def export_single_floor(floor): """exports a single floor """ return mt.Floor( *export_vertices(floor.Points), id=str(next_id()), ep_id=floor.Id, type=str(id_map(floor.Type.Id)))
874df1e1732cdc91092038fe2859ecea45bb836b
3,640,315
import torch def tensor_lab2rgb(input): """ n * 3* h *w """ input_trans = input.transpose(1, 2).transpose(2, 3) # n * h * w * 3 L, a, b = input_trans[:, :, :, 0:1], input_trans[:, :, :, 1:2], input_trans[:, :, :, 2:] y = (L + 16.0) / 116.0 x = (a / 500.0) + y z = y - (b / 200.0) ...
6c9ebdfba0a22661c479296a2be285d82a7ac85b
3,640,316
def thanos(planet: dict, finger: int) -> int: """ Thanos can kill half lives of a world with a snap of the finger """ keys = planet.keys() for key in keys: if (++finger & 1) == 1: # kill it planet.pop(key) return finger
5b6325297cb8f259c27b3eb7fa5618edd1486b9c
3,640,318
from typing import List def ordered_list_item_to_percentage(ordered_list: List[str], item: str) -> int: """Determine the percentage of an item in an ordered list. When using this utility for fan speeds, do not include "off" Given the list: ["low", "medium", "high", "very_high"], this function will r...
2aa1b0574664e53da6080ae4bc99d1f3c93fad96
3,640,319
def simple2tradition(line): """ 将简体转换成繁体 """ line = Converter('zh-hant').convert(line) return line
f934bd3c573274b0c2d8345493850335e0d7b6b7
3,640,320
def normalize_colors(colors): """ If colors are integer 8bit values, scale to 0 to 1 float value used by opengl :param colors: :return: """ if colors.dtype is not np.float32: colors = colors.astype(np.float32) / 255.0 return colors
5212d5678d9a2744fced474b19ee5099ee152158
3,640,321
def load_text_data(path, word_dict): """ Read the given path, which should have one sentence per line :param path: path to file :param word_dict: dictionary mapping words to embedding indices :type word_dict: WordDictionary :return: a tuple with a matrix of sentences and an array ...
bcb58019917b3972a12968cd9b9a563c27356e50
3,640,322
def dirty(graph): """ Return a set of all dirty nodes in the graph. """ # Reverse the edges to get true dependency return {n: v for n, v in graph.node.items() if v.get('build') or v.get('test')}
06835b52d7741716f1c67d951c0ab74758f476b4
3,640,323
def hangman(secret_word): """ secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before ...
91ff0b2ad0168d1c3a8dd15466ca2b15b4a9f557
3,640,324
def sin_potential(z): """Sin-like potential.""" z = tf.transpose(z) x = z[0] y = z[1] # x, y = z return 0.5 * ((y - w1(z)) / 0.4) ** 2 + 0.1 * tf.math.abs(x)
e95db66fc99acc3742e179af0ba557b2a81b4ec3
3,640,325
def erode_label(image_numpy, iterations=2, mask_value=0): """ For each iteration, removes all voxels not completely surrounded by other voxels. This might be a bit of an aggressive erosion. Also I would bet it is incredibly ineffecient. Also custom erosions in multiple dimensions look a lit...
7eb1ff92c8c4e75fa4b6ba88365adf50c9013fc8
3,640,326
def computeBFGridPoint(basis, U, gpi, gps): """ Compute the bilinear form for one grid point with the points stored in gps @param basis: basis of sparse grid function, @param U: list of distributions @param gpi: HashGridPoint @param gps: list of HashGridPoint """ n = len(gps) s =...
4898e16847c8cb8fc8af3ffa3f793c18f2088d79
3,640,328
from typing import Optional from typing import Collection from typing import Pattern from pathlib import Path from typing import List def list_files(commit: Optional[str] = None, pathspecs: Collection[PathOrStr] = (), exclude: Collection[Pattern[str]] = (), repo: Optional[...
8d96a41c5016b78a7e71654015fbfda50aa896d4
3,640,329
def sum_by_hexagon(df,resolution,pol,fr,to,vessel_type=[],gt=[]): """ Use h3.geo_to_h3 to index each data point into the spatial index of the specified resolution. Use h3.h3_to_geo_boundary to obtain the geometries of these hexagons Ex counts_by_hexagon(data, 8) """ if vessel_type: ...
883abde8562e093d44646e7db3795e22c6c918b8
3,640,330
def _ibp_sub(lhs, rhs): """Propagation of IBP bounds through a substraction. Args: lhs: Lefthand side of substraction. rhs: Righthand side of substraction. Returns: out_bounds: IntervalBound. """ return lhs - rhs
45ed06feea14275ddd64e1ec60727123db52a5cd
3,640,331
from typing import Mapping def toil_make_tool( toolpath_object: CommentedMap, loadingContext: cwltool.context.LoadingContext, ) -> Process: """ Emit custom ToilCommandLineTools. This factory funciton is meant to be passed to cwltool.load_tool(). """ if ( isinstance(toolpath_object...
25998d1a6941b8255e8baa5b83da3ef13c004cd7
3,640,332
import json import io def sentinel_s1(metadata): """ Parse metadata and return basic Item with rasterio.open('/Users/scott/Data/sentinel1-rtc/local_incident_angle.tif') as src: ...: metadata = src.profile ...: metadata.update(src.tags()) """ def get_datetime(metadata): ...
c96b40417bdb68224f72738291386b799325584c
3,640,333
def get_loc(data, attr={'lr_mult':'0.01'}): """ the localisation network in lenet-stn, it will increase acc about more than 1%, when num-epoch >=15 """ loc = mx.symbol.Convolution(data=data, num_filter=30, kernel=(5, 5), stride=(2,2)) loc = mx.symbol.Activation(data = loc, act_type='relu') l...
9216080263f5f9dde07eff96109d05ab4d583a08
3,640,334
def meanwave(signals): """ This function computes the meanwave of various signals. Given a set of signals, with the same number of samples, this function returns an array representative of the meanwave of those signals - which is a wave computed with the mean values of each signal's samples. ...
11a477fed2b3cdf03226545a9a02c4500c6f4634
3,640,335
def set_difficulty(): """Ask the difficult level and return the number of turns corresponding""" if input("Choose a difficulty level. Type 'easy' or 'hard': ").lower() == "easy": return EASY_TURNS else: return HARD_TURNS
746b01ca3e9ea22cd32b00fa923709ece2ee6a60
3,640,336
def delete_event_by_id(id, user_id): """Remove one event based on id.""" sql = "DELETE FROM events WHERE id = :id AND host_id = :user_id RETURNING title;" db.session.execute(sql, {"id": id, "user_id": user_id}) db.session.commit() return ["Event deleted."]
0e49df11f52574b89e96ff434c1e3b40130dbffc
3,640,337
def get_cmap_colors(cmap='jet',p=None,N=10): """ """ cm = plt.get_cmap(cmap) if p is None: return [cm(i) for i in np.linspace(0,1,N)] else: normalize = matplotlib.colors.Normalize(vmin=min(p), vmax=max(p)) colors = [cm(normalize(value)) for value in p] return colors
39073608961ab48e7b2ade6666b0107800825170
3,640,338
def reader_factory(load_from, file_format): """Select and return instance of appropriate reader class for given file format. Parameters __________ load_from : str or file instance file path or instance from which to read file_format : str format of file to be read Returns _...
b2379a0ff4b360989f68dcc412fa733011d17213
3,640,339
def scrape_with_selenium(chrome, chrome_webdriver, url, xpath_tup_list, timeout): """Scrape using Selenium and Chrome.""" result_dic = {} with SeleniumChromeSession(chrome=chrome, chrome_webdriver=chrome_webdriver) as driver: wait_conditions = [] for xpath_tup in xpath_tup_list: ...
a17a942cfd586765c01bf10af6247145d70a84a5
3,640,340
def take_element_screenshot(page_screenshot: Image.Image, bbox: Rectangle) -> Image.Image: """ Returns the cropped subimage with the coordinates given. """ w, h = page_screenshot.size if bbox.area == 0: raise ValueError(f"Rectangle {bbox} is degenerate") if bbox not in Rectangle(Point(...
2387ecf34c1ae4118e1021b0cf5649b8cd2947ce
3,640,341
def officeOfRegistrar_forward(request, id): """form to set receiver and designation of forwarded file """ context = {"track_id": id} return render(request, "officeModule/officeOfRegistrar/forwardingForm.html", context)
aaa237f75de98b45b477c5fc4542e12e6e257a5c
3,640,342
def vector_quaternion_arrays_allclose(vq1, vq2, rtol=1e-6, atol=1e-6, verbose=0): """Check if all the entries are close for two vector quaternion numpy arrays. Quaterions are a way of representing rigid body 3D rotations that is more numerically stable and compact in memory than other methods such as a 3x3...
d1f1bb82ce5570dce0c18f7c25798c8621badfa2
3,640,343
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ----...
1f46c1d5960a0d637116d7da847368d30440dd29
3,640,344
def autocorr_quad(w, f, t, method = 'direct'): """ Calculate the vacuum state autocorrelation function for propagation on a quadratic potential energy surface. Parameters ---------- w : array_like The harmonic frequency (in energy units) of each mode. f : array_like ...
3844cabc58e1fa2ca4b6f4e0a0709d3e1270b6d3
3,640,345
def add_project(body): """ POST /api/projects :param body: :return: """ try: return { 'title': 'Succeed to Create Project', 'detail': svcProject.add_project(body) }, 200 except Exception as e: raise DefaultError(title='Failed to Create Project'...
e65e72fc5a1702b3fb619012539c6695464fcf93
3,640,346
def new_client(user_id: str, session=DBSession) -> Client: """ from user_id get a miniflux client :param user_id: telegram chat_id :param session: database session class :type user_id: Union[int, str] :raise UserNotBindError: user not bind a miniflux account """ session = session() user...
1330ca2b4ee016a9a3e593ba4668380635a3b8e5
3,640,347
def builtin_divmod(a, b): """Divide two numbers and take the quotient and remainder.""" aa, bb = BType.commonize(a, b) dv, mv = divmod(aa.value, bb.value) d = type(aa)(dv) m = type(aa)(mv) return (d, m)
2e7af62cd58e7dd647be9650e554d0a7e2896ed9
3,640,349
def format_adjacency(G: nx.Graph, adj: np.ndarray, name: str) -> xr.DataArray: """ Format adjacency matrix nicely. Intended to be used when computing an adjacency-like matrix off a graph object G. For example, in defining a func: ```python def my_adj_matrix_func(G): adj = some_adj_...
e1ebe0bc1a42df03e5cc0a94cd600f8c937fedb4
3,640,350
def batch_local_stats_from_coords(coords, mask): """ Given neighborhood neighbor coordinates, compute bond distances, 2-hop distances, and angles in local neighborhood (this assumes the central atom has coordinates at the origin) """ one_hop_ds, two_dop_d_mat = batch_distance_metrics_from_coords...
d5268749bc79cc793d3476c66a44b326d96376c8
3,640,351
def resolve_sender_entities(act, lexical_distance=0): """ Given an Archive's activity matrix, return a dict of lists, each containing message senders ('From' fields) that have been groups to be probably the same entity. """ # senders orders by descending total activity senders = act.sum(0)....
5e4a510f5e56d6890168e0f32f8433826914cbee
3,640,352
from typing import List import tqdm import torch def ddpg( env: gym.Env, agent: ContinuousActorCriticAgent, epochs: int, max_steps: int, buffer_capacity: int, batch_size: int, alpha: float, gamma: float, polyak: float, act_noise: float, verbose: bool, ) -> List[float]: ...
688bd6ed521e476ac67017dd5781f1d337326e0c
3,640,353
def civic_eid26_statement(): """Create a test fixture for CIViC EID26 statement.""" return { "id": "civic.eid:26", "description": "In acute myloid leukemia patients, D816 mutation is associated with earlier relapse and poorer prognosis than wildtype KIT.", # noqa: E501 "direction": "sup...
bdad5e8d5f6fe063d43bb600bf4158fadc1f38ca
3,640,355
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # Use a dummy metaclass that replaces itself with the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, '_TemporaryCl...
eed3c63b6f86f1f3154449e32d94b396a519d523
3,640,356
import re def validate_user(username, minlen): """Checks if the received username matches the required conditions.""" if type(username) != str: raise TypeError("username must be a string") if minlen < 1: raise ValueError("minlen must be at least 1") """ Username should not be shor...
7d7ad86eccba2639158a9f5da9fb093f9f4abff9
3,640,357
def neg_mae_macro(y_trues, y_preds, labels, topics): """ As for absolute error, lower is better Thus use negative value in order to share the same interface when tuning dev data with other metrics """ return -mae_macro(y_trues, y_preds, labels, topics)
4e2a3df557e97dc49e1377d1006c58348c34bdaf
3,640,358
def clean_data(df): """Cleans the a dataset provided as a DataFrame and returns the cleaned DataFrame. Cleaning includes expanding the categories and cleaning them up. Args: df (DataFrame): Data, containing categories as a single column, as well as messages Returns: DataFrame: Cleaned...
1a8552a0ea99691ea94397737ac64f5c9261f66d
3,640,360
from typing import Mapping from typing import Any from typing import Optional def _validate_float(mapping: Mapping[str, Any], ref: str) -> Optional[SchemaError]: """ Validate the definition of a float value. :param mapping: representing the type definition to be validated :param r...
41c4725a66621addd6164a97549c35d47b1be27f
3,640,361
import typing def tokenize_document(document: str) -> typing.List[str]: """ Helper method to tokenize the document. :param document: The input document represented as a string. :return: A list of tokens. """ try: return nltk.tokenize.word_tokenize(document) except LookupError: ...
0380efbb2f243b14135b3232d9ae22158ba14747
3,640,362
def get_type_name_value(obj): """ Returns object type name from LLDB value. It returns type name with asterisk if object is a pointer. :param lldb.SBValue obj: LLDB value object. :return: Object type name from LLDB value. :rtype: str | None """ return None if obj is None else obj.GetTy...
c87a5acf7d8ef794eab97c90b82bbd9574fb0e2b
3,640,363
def fastqprint(fastq): """ Printing a fastq file """ for record in SeqIO.parse(fastq, "fastq"): print("%s %s" % (record.id, record.seq)) return seq1.reverse_complement()
9197da0e9c73f46b5aee8613de434e173a701fd0
3,640,364
from typing import Match def matchlist(page=1): """Respond with view for paginated match list.""" query = Match.query.order_by(Match.id.desc()) paginatedMatches = query.paginate(page, current_app.config['MATCHES_PER_PAGE'], False) return render_template('matchlist.html', matches=paginatedMatches.items...
e9f082e6acb513636b9db98996997991efbb79d8
3,640,367
def get_data(filename: str) -> pd.DataFrame: """ Create a dataframe out of south_sudan_data.csv """ df = pd.read_csv(filename) return df
bae9149ff8094abe916c0744c5f42735c5ee84ba
3,640,369
def digital_PCR( primer_mappings ): """ Makes a "digital" PCR by looking at the mappings of primers and predict which will produce products, and more important multiple products """ primer_names = sorted(primer_mappings.keys()) nr_primer_names = len( primer_names ) mappings = {} p...
296b69fd5eaf1fb95afc2fb07dd99e97d715376f
3,640,370
def database_find_user_salt(username:str)->str: """ Finds a users salt from there username Parameter: username (str): username selected by the user Returns: salt (str): The users salt from the database Example: >>> username = 'andrew' >>> database_find_user...
2c74e943a650a74eb6a7b71a7ac2e677891dbd63
3,640,371
from .. import sim def createSimulate(netParams=None, simConfig=None, output=False): """ Function for/to <short description of `netpyne.sim.wrappers.createSimulate`> Parameters ---------- netParams : <``None``?> <Short description of netParams> **Default:** ``None`` **Opti...
399866b8f0a2fd39235526c471327a9cf042603e
3,640,372
def lang_add(cursor, lang, trust): """Adds language for db""" if trust: query = 'CREATE TRUSTED LANGUAGE "%s"' % lang else: query = 'CREATE LANGUAGE "%s"' % lang cursor.execute(query) return True
f5a1ac9264efca070b4528505ee6bee6892b3e80
3,640,373
def interpolate( a_x, a_q2, padded_x, s_x, padded_q2, s_q2, actual_padded, ): """ Basic Bicubic Interpolation inside the subgrid Four Neighbour Knots selects grid knots around each query point to make the interpolation: 4 knots on the x axis and 4 knots on the q2 axis are needed for each point, ...
5e5ebda28acdc56a80eca102b39d15aca29ac648
3,640,374
from re import T def setting(): """ SMS settings for the messaging framework """ tablename = "%s_%s" % (module, resourcename) table = s3db[tablename] table.outgoing_sms_handler.label = T("Outgoing SMS handler") table.outgoing_sms_handler.comment = DIV(DIV(_class="tooltip", _title="%s|%s"...
0ecdb50499f22eb88e8a22d8295928c6208cff45
3,640,375
from typing import Callable def _cachegetter( attr: str, cachefactory: Callable[[], _CacheT] = WeakKeyDictionary, # WeakKewDict best for properties ) -> Callable[[_CIT], _CacheT]: """Returns a safer attrgetter which constructs the missing object with cachefactory May be used for normal metho...
b9d0d8d6ed1a2d3d9a2500326c996af94726ddc4
3,640,376
def format_time(time): """ It formats a datetime to print it Args: time: datetime Returns: a formatted string representing time """ m, s = divmod(time, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) return ('{:02d}d {:02d}h {:02d}m {:02d}s').format(int(d), int(h), int(m), int(s))
67c6404cbc5076358f9e85dc169e1d7b976b7d60
3,640,378
def egarch_recursion_python( parameters: Float64Array, resids: Float64Array, sigma2: Float64Array, p: int, o: int, q: int, nobs: int, backcast: float, var_bounds: Float64Array, lnsigma2: Float64Array, std_resids: Float64Array, abs_std_resids: Float64Array, ) -> Float64Arr...
74478c42d28a50a873834d6eb8207cc756d5fc03
3,640,379
def polpair_tuple2int(polpair, x_orientation=None): """ Convert a tuple pair of polarization strings/integers into an pol-pair integer. The polpair integer is formed by adding 20 to each standardized polarization integer (see polstr2num and AIPS memo 117) and then concatenating them. For exampl...
ac31db32b26a4abe8151f72409467d2a9db2d0b6
3,640,380
import warnings def compute_features(df): """Compute ReScore features.""" preds_dict = df_to_dict(df) rescore_features = [] spec_ids = [] charges = [] feature_names = [ "spec_pearson_norm", "ionb_pearson_norm", "iony_pearson_norm", "spec_mse_norm", "i...
ff68306022fdf75fe6ea19b055c33b2a333bc2d7
3,640,381
def collection_basic(commodities) -> CommodityCollection: """Returns a simple collection of commodities side effects testing.""" keys = ["9999_80_1", "9999.10_80_2", "9999.20_80_2"] return create_collection(commodities, keys)
6ef751225efd338ecd39282e75abdf7bd64e8e47
3,640,382
def percent_list(part_list, whole_list): """return percent of the part""" w = len(whole_list) if not w: return (w,0) p = 100 * float(len(part_list))/float(w) return (w,round(100-p, 2))
f9b3697c96c04c402972351e73395b7f7ed18350
3,640,384
def disp_calc_helper_NB(adata, min_cells_detected): """ Parameters ---------- adata min_cells_detected Returns ------- """ rounded = adata.raw.astype('int') if adata.raw is not None else adata.X lowerDetectedLimit = adata.uns['lowerDetectedLimit'] if 'lowerDetectedLimit' in ad...
2402446dca38d3b730fb0c11720151c38838341f
3,640,385
def print_results(request): """Renders the results url, which is a placeholder copy of the root url of query interface, where any results are rendered alongside the table headers. """ if request.method == "POST": form = MetadataForm(request.POST) if form.is_valid(): query_res...
77e0db699b3458ce69d56771a83586fab6a86b66
3,640,386
def capacity_rule(mod, g, p): """ The capacity of projects of the *gen_ret_bin* capacity type is a pre-specified number for each of the project's operational periods multiplied with 1 minus the binary retirement variable. """ return mod.gen_ret_bin_capacity_mw[g, p] \ * (1 - mod.GenRetBi...
ba4ccad8d620da084912a65a80793f54fb84b374
3,640,387
def block_deconv_k4s2p1_BN_RELU(in_channel_size, out_channel_size, leaky = 0): """ >>> block_deconv_k4s2p1_BN_RELU(13, 17, 0.02) Sequential( (0): ConvTranspose2d(13, 17, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False) (1): BatchNorm2d(17, eps=1e-05, momentum=0.1, affine=True, trac...
6d8f3b9f550a1b18599bf7b3439ad7dda2d316b8
3,640,389
import napari import numpy def demo_super_fast_representative_crop(image, crop_size=64000, display: bool = True): """ Demo for self-supervised denoising using camera image with synthetic noise """ Log.enable_output = True Log.set_log_max_depth(5) image = normalise(image.astype(numpy.float32))...
b5166027719fb3bee757af25cc532b9e9e2e2be7
3,640,390
def encrypt_uid(user): """Encrypts the User id for plain """ uid_xor = htk_setting('HTK_USER_ID_XOR') crypt_uid = int_to_base36(user.id ^ uid_xor) return crypt_uid
a425785f724cbc3e7459e38150b7a455ce1c1c6d
3,640,391
def createNewVarName(varType): """An helper function that returns a new name for creating fresh variables. """ createNewVarName.counter += 1 # return "v_{}_{}".format(varType.lower(), createNewVarName.counter) return "v_{}".format(createNewVarName.counter)
19efee0d0b9f3d100807034037b4aecfc6a11940
3,640,392
def initialize_parameters(n_a, n_x, n_y): """ Initialize parameters with small random values Returns: parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state...
bd420d9484143a1322c43aef6fd4441526bf5d2a
3,640,393
def secure_request(request, ssl: bool): """ :param ssl: :param request: :return: """ # request.headers['Content-Security-Policy'] = "script-src 'self' cdnjs.cloudflare.com ; " request.headers['Feature-Policy'] = "geolocation 'none'; microphone 'none'; camera 'self'" request.headers['Ref...
e1c19aa89930e6aeb1c548c24da374859987e090
3,640,394
def f_mean(data: pd.DataFrame, tags=None, batch_col=None, phase_col=None): """ Feature: mean The arithmetic mean for the given tags in ``tags``, for each unique batch in the ``batch_col`` indicator column, and within each unique phase, per batch, of the ``phase_col`` column. """ base_nam...
16f86d42a22aa2c5849ffeb1aa95a3a1dd0f342f
3,640,395
import random def AtariConvInit(kernel_shape, rng, dtype=jnp.float32): """The standard init for Conv laters and Atari.""" filter_height, filter_width, fan_in, _ = kernel_shape std = 1 / jnp.sqrt(fan_in * filter_height * filter_width) return random.uniform(rng, kernel_shape, dtype, minval=-std, maxval=std)
c7f12495c067fc34d9123659dfe91e0295358207
3,640,396
import urllib def scrape(url): """ Scrapes a url and returns the html using the proper User Agent """ UA = 'Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.2.9) Gecko/20100913 Firefox/3.6.9' urllib.quote(url.encode('utf-8')) req = urllib2.Request(url=url, headers={'U...
ce1aa7127532fef3408c45ebaa62a925672b0189
3,640,397
def _get_prefixed_values(data, prefix): """Collect lines which start with prefix; with trimming""" matches = [] for line in data.splitlines(): line = line.strip() if line.startswith(prefix): match = line[len(prefix):] match = match.strip() matches.append(m...
d0fe7ff11321ccbf06397963a303f0e79181ebba
3,640,398
def build_k5_graph(): """Makes a new K5 graph. Ref: http://mathworld.wolfram.com/Pentatope.html""" graph = UndirectedGraph() # K5 has 5 nodes for _ in range(5): graph.new_node() # K5 has 10 edges # --Edge: a graph.new_edge(1, 2) # --Edge: b graph.new_edge(2, 3) #...
ba19a5014f729bb0c3af3e528c8d37d02df84932
3,640,399
def bytes_to_msg(seq, standard="utf-8"): """Decode bytes to text.""" return seq.decode(standard)
5664d97b3fec5d119daa2171bcb431ca5a4b5f33
3,640,400
from tqdm.auto import tqdm from typing import Union import random import time import statistics def cross_validate( estimator, input_relation: Union[str, vDataFrame], X: list, y: str, metric: Union[str, list] = "all", cv: int = 3, pos_label: Union[int, float, str] = None, cutoff: float...
fc59bb42c9e776e91b455f5d79e762721246754d
3,640,401
def bonferroni_correction(pvals): """ Bonferroni correction. Reference: http://en.wikipedia.org/wiki/Bonferroni_correction """ n = len(pvals) return [min(x * n , 1.0) for x in pvals]
f57ffd6b77a0a74a61904334604d1cb0eb08f8ff
3,640,402
from itertools import accumulate, chain, repeat def make_fib(): """Returns a function that returns the next Fibonacci number every time it is called. >>> fib = make_fib() >>> fib() 0 >>> fib() 1 >>> fib() 1 >>> fib() 2 >>> fib() 3 >>> fib2 = make_fib() >>> ...
e546ce79c4b441418f5325b0ac5d7c3faf6ac35e
3,640,404
def render_injected(http_resp, extra_html): """ render_injected(http_resp, extra_html) -> HttpResponse Inject the extra html into the content of the http_resp. ``extra_html`` can be a string or an object with an ``html`` method/field. """ assert isinstance(http_resp, HttpResponse) if 'text/html' not in h...
a3f49419359a68ecc72f78f00ae3e4a18f4957d6
3,640,406
from unittest.mock import Mock from unittest.mock import patch def mock_gitlab_api_projects(save=None, mergerequests_list=None): """A pseudo mock""" def get(*args, **kwargs): project = Mock('gitlab.v4.objects.Project') project.save = save project.mergerequests = \ Mock('git...
52b48a0f9083a22fdafcfa3b797d6580967b1f02
3,640,408
def text_in_bytes(text, binary_data, encoding="utf-8"): """Return True of the text can be found in the decoded binary data""" return text in binary_data.decode(encoding)
e416057989c452718fa27b5f84286e347b986117
3,640,409
import json def make_auth(sub, tenant=None): """ Prepare an almost-valid JWT token header, suitable for consumption by our identity middleware (needs sub and optionally mender.tenant claims). The token contains valid base64-encoded payload, but the header/signature are bogus. This is enou...
c8f8896814d1571bb4bb54a5507eda19e5ffd46c
3,640,410