content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_stable(A, domain='z'): """Determines if a linear state-space model is stable from eigenvalues of `A` Parameters ---------- A : ndarray(n,n) state matrix domain : str, optional {'z', 's'} 'z' for discrete-time, 's' for continuous-time state-space models returns ------...
8b073fa021b0f50363d4f5f1a7bf3722a62ae71b
3,640,700
def email_sent_ipn(path: str) -> tuple: """ **email_sent_ipn** Delivered ipn for mailgun :param path: organization_id :return: OK, 200 """ # NOTE: Delivered ipn will end up here if path == "delivered": pass elif path == "clicks": pass elif path == "op...
4bbfed4f86916ddc2b68ade0c8739e25a562bbda
3,640,701
import sys def decode(path: str) -> str: """ utility fct to encode/decode """ return path.encode(sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding)
9e75e04928e7df4646feaed85a799a137693fa77
3,640,702
import json def load_posts_view(request): """Load posts view, handles asynchronous queries to retrieve more posts. """ if request.method == 'GET': results, start = get_more_posts(request.GET) json_result = json.dumps({'posts': results, 'start': start ...
832f2a04b23eb78ad25ad7db2d3cabfdaa61b075
3,640,703
def create_dataset(m, timestep, var='all', chunks=(10, 300, 300)): """ Create xarray Dataset from binary model data for one time step. This also incorporates all model grid information and dimensions, regardless of the variable selected. Parameters ---------- m : LLCRegion Model cla...
02dd6a4e7ff520e5ae65c7a3a9e3bd2b92d58629
3,640,704
def fetchnl2bash(m:Manager, shuffle:bool=True)->DRef: """ FIXME: Unhardcode '3rdparty'-based paths """ allnl=fetchlocal(m, path=join('3rdparty','nl2bash_essence','src','data','bash','all.nl'), sha256='1db0c529c350b463919624550b8f5882a97c42ad5051c7d49fbc496bc4e8b770', mode='asis', output=[promise...
d99376bbe2dbc2250281eccb9b5d7108cf9f9c84
3,640,705
def mummer_cmds_four(path_file_four): """Example MUMmer commands (four files).""" return MUMmerExample( path_file_four, [ "nucmer --mum -p nucmer_output/file1_vs_file2 file1.fna file2.fna", "nucmer --mum -p nucmer_output/file1_vs_file3 file1.fna file3.fna", "n...
65262a16f47b952796f79dcb9bba37c5dcbaed0b
3,640,706
def Exponweibull(a=1, c=1, scale=1, shift=0): """ Expontiated Weibull distribution. Args: a (float, Dist) : First shape parameter c (float, Dist) : Second shape parameter scale (float, Dist) : Scaling parameter shift (float, Dist) : Location parameter """ dist = core...
64871830101df96f8148ef6ee0b8735813793306
3,640,707
def authed_request_for_id(gplus_id, request): """Adds the proper access credentials for the specified user and then makes an HTTP request.""" # Helper method to make retry easier def make_request(retry=True): token = get_access_token_for_id(gplus_id) request.headers['Authorization'] = 'Bear...
f727cc818fd3d5b70fba80b00dfb09cf1f182275
3,640,708
def _bool_method_SERIES(op, name, str_rep): """ Wrapper function for Series arithmetic operations, to avoid code duplication. """ def na_op(x, y): try: result = op(x, y) except TypeError: if isinstance(y, list): y = lib.list_to_object_array(y) ...
d6dec673d9a0f8384c3510bdda449f8e4157c96e
3,640,709
def get_playlist_by_id(playlist_id): """ Returns a playlist by playlist id """ return Playlist.query.filter(Playlist.playlist_id == playlist_id).first()
28fd295a5d096b1da40391193e6333cc48b14ea2
3,640,710
def section_cfield(xs, x_a, c_field, rmax = 60e3): """ extract a section of a sound speed transcet for use in xmission calculation """ x_i = np.bitwise_and(x_a >= xs, x_a <= xs + rmax) return x_a[x_i], c_field[:, x_i]
c4c213293f7aee7735a9a6209f671aae6d8e3989
3,640,711
def shared_dropout(shape, use_noise, trng, value): """ Shared dropout mask (pervasive dropout) :param shape: :param use_noise: :param trng: :param value: :return: """ return tensor.switch(use_noise, trng.binomial(shape, p=value, n=1, ...
51373285b3c708cedd1ebf2a613237deaa7b6dab
3,640,712
def setup_flow_assembler(gb, method, data_key=None, coupler=None): """Setup a standard assembler for the flow problem for a given grid bucket. The assembler will be set up with primary variable name 'pressure' on the GridBucket nodes, and mortar_flux for the mortar variables. Parameters: gb: G...
6e1baaf91e06679ef760932f6ae27e0c606e4f21
3,640,713
def get_article(article_id: str, db: Session = Depends(deps.get_db), current_user: schemas.UserVerify = Depends( deps.get_current_user)) -> JSONResponse: """ Return Single Article""" data = crud_articles.get_article(article_id=article_id, db=db) if data is None: r...
e78af6052b112c5da5811a0c92fe462743bb5c7e
3,640,714
def _get_sp_instance(): """Create an spotify auth_manager and check whether the current user has a token (has been authorized already). If the user has a token, then they are authenticated -- return their spotipy instance. If the user does not have a token, then they are not authenticated -- raise an ex...
b2117c709169192626efdf2b699a9a1c2c501ecc
3,640,715
def get_func_global(op_type, dtype): """Generate function for global address space Used as `generator(op_type, dtype)`. """ op = getattr(dppy.atomic, op_type) def f(a): op(a, 0, 1) return f
72816c78bc36f7aa630551ae161fa0870acefe36
3,640,716
def klucb(x, d, div, upperbound, lowerbound=-float("inf"), precision=1e-6): """The generic klUCB index computation. Input args.: x, d, div: KL divergence to be used. upperbound, lowerbound=-float('inf'), precision=1e-6, """ l = max(x, lowerbound) u = upperbound while...
82aa51e248568d201e0d9d5621bf043532df8572
3,640,717
def convert_pk_to_index(pk_tuples, indices): """ For a list of tuples with elements referring to pk's of indices, convert pks to 0-index values corresponding to order of queryset :param pk_tuples: list of tuples [(row_pk, col_pk), ... ] :param indices: list of querysets :return: list of tuples [...
81837ded50d4cd086b9330ea5c709fb3bd93ca0f
3,640,718
from typing import Union def device_path_to_str(path: Union[bytes, str]) -> str: """ Converts a device path as returned by the fido2 library to a string. Typically, the path already is a string. Only on Windows, a bytes object using an ANSI encoding is used instead. We use the ISO 8859-1 encoding t...
76d0d3d50e978d998ef68e0c509c3933f94778d9
3,640,719
def empirical(X): """Compute empirical covariance as baseline estimator. """ print("Empirical") cov = np.dot(X.T, X) / n_samples return cov, np.linalg.inv(cov)
67c8c1f42590ee6c8d56f5f1e53253c5eff74376
3,640,720
def emitir_extrato(contas, numero_conta, movimentacoes, data_inicial): """ Retorna todas as movimentações de <movimentacoes> feitas pela conta com o <numero_conta> a partir da <data_inicial> """ historico_movimentacoes = [] if numero_conta in contas: minhas_movimentacoes = movimentac...
0caa46aaed0ccfa506f8caa9b82625649d116ce1
3,640,721
def wavelength_to_energy(wavelength): """ Converts wavelength (A) to photon energy (keV) """ return 12.39842/wavelength
4e2d11f2de8ed4890df5d885801cd492644817d8
3,640,722
def calculate_hash_512(filepath, verbose): """ SHA512 Hash Digest """ if verbose: print 'Calculating hash...' sha512_hash = hashlib.sha512() with open(filepath, 'rb') as f: statinfo = os.stat(filepath) block_size = 100 * (2**20) #Magic number: 100 * 1MB blocks ...
4bf153275d9791112f39d3629e9cc94f54177dc4
3,640,723
def _crop_after_rotation(im, angle, xres, yres, surroundings): """Crop image to the bounding box of bite's surroundings. Arguments: im: PIL.Image, rotated map part angle: by which the map has been rotated, in degrees (counterclockwise) xres: width of one tile in pixels yres: height of one tile...
eeeda2c5c8d868e813a67584c72561560409e1b3
3,640,724
import copy def get_custom_scorer(metric, gib=True, needs_proba=False, needs_threshold=False): """Get a scorer from a str, func or scorer. Scorers used by ATOM have a name attribute. Parameters ---------- metric: str, func or scorer Name, metric or scorer to get ATOM's scorer from. ...
a698798302ec0ed7ad469b76d6893e85e669905e
3,640,725
def julian_day(t='now'): """ Wrap a UTC -> JD conversion from astropy. """ return Time(parse_time(t)).jd
fa2f0d707798227e8e7f67b21cf2e4dc42308093
3,640,726
from typing import Counter def add_stop_words(dataframe: pd.DataFrame, k_words: int) -> list: """ Получить список стоп-слов, которые наиболее часто встречаются в документе :param dataframe: :param k_words: кол-во наиболее часто повторяющихся уникальных слов :return: """ ...
3ca7fbe1221b55e2a072d49f01c553af1786ca8f
3,640,727
import torch def get_batch(data_iterator): """Build the batch.""" # Items and their type. keys = ['text', 'types', 'labels', 'is_random', 'loss_mask', 'padding_mask'] datatype = torch.int64 # Broadcast data. data = next(data_iterator) if data_iterator is not None else None data_b = mpu.b...
fad3b181c685e3e57fa185c1eb790517536527ec
3,640,728
import os def outcomes_by_resected_lobe(directory='L:\\', filename='All_Epilepsy_Ops_CROSSTAB_Statistics_YAY_2019.xlsx', lobes=['T Lx', 'T Lesx']): """ Creates the list of Gold_standard post-operative ILAE 1 at all follow up years MRNs in patients who had only specific lobe r...
30c35d288beadc15be31d19bab8f8ce7e28ee599
3,640,729
def pool(sparkdf, start_column, end_column, var): """ Generate pools and calculate maximum var unpooled. :param sparkdf: Input Spark dataframe. :param start_column: Start time column name. :param end_column: End time column name. :param var: Variable for which to calculate metric. :return: A...
913094bebc6f91ad023d83186084d858a7332531
3,640,730
def jwt_response_payload_handler(token, user=None, request=None): """ 自定义jwt返回 def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={'request': request}).data } :param token: :param...
972f4cbd39d9bd049fcd7a99bfc168e6c825572a
3,640,731
import requests def query_yelp_lookup(biz_id): """ Lookup resturant using id """ headers = {'Authorization': ('Bearer ' 'w5JFtwCUKq05GlSpm8cKo51dBYDQ6r9tyzo-qRsKt4wDyB5' '_ro6gW5gnG9hS6bvnNHNxOQLHfw7o_9S1e86nkvgcU7DQI_' 'sM6GVt9rqcq_rRYKtagQrexuH0zsU0WXYx')} ur...
ab2087d42833f0092229870ab3208a24bd041b95
3,640,732
def dashboard(request, condition='recent'): """Dashboard""" post_count = settings.DASHBOARD_POST_COUNT comment_count = settings.DASHBOARD_COMMENT_COUNT if condition == 'recent': order = '-id' elif condition == 'view': order = '-view_count' elif condition == 'like': order...
fc5422bf580a4608e921b7d59caf7f0ea58a50fd
3,640,733
def read_manifest(path): """Read dictionary of workflows from the Packal manifest.xml file.""" workflows = {} tree = ET.parse(path) root = tree.getroot() for workflow in root: data = {"packal": True} for child in workflow: if child.tag == "short": data["de...
8f91126f4a48c0b1af357487ffe791ba790c7745
3,640,734
def _load_v1_txt(path): """Parses a SIF V1 text file, returning numpy arrays. Args: path: string containing the path to the ASCII file. Returns: A tuple of 4 elements: constants: A numpy array of shape (element_count). The constant associated with each SIF element. centers: A n...
9f7ea3f0059ef3688cc962e9836a558debebf80f
3,640,735
def split_model_name(model): """ Split model names by _ Takes into account packages with _ and processor types with _ """ model = model[:-3].replace('.', '_') # sort by key length so that nertagger is checked before tagger, for example for processor in sorted(ending_to_processor.keys(), key...
305a70899eb8eb3c5beca4c7e7403010a008a80d
3,640,736
from .divine1983 import JupiterD4Field from .distributions import DG83Distribution from .integrate import FormalRTIntegrator from .synchrotron import NeuroSynchrotronCalculator def dg83_setup( ghz = 95, lat_of_cen = 10, cml = 20, n_alpha = 10, n_E = 10, E0 = 0.1, ...
94aea682df900d600e922ff560109255e2b69ac7
3,640,737
def compute() -> int: """ Returns the sum of all numbers whose sum of the factorials of all digits add up to the number itself. >>> compute() 40730 """ return sum( num for num in range(3, 7 * factorial(9) + 1) if sum_of_digit_factorial(num) == num )
c2460158eb7d32142b4f59801bdc307a0ba1d4ff
3,640,738
import heapq def dijkstra(matrix, start=None, end=None): """ Implementation of Dijkstra algorithm to find the (s,t)-shortest path between top-left and bottom-right nodes on a nxn grid graph (with 8-neighbourhood). NOTE: This is an vertex variant of the problem, i.e. nodes carry weights, not edges. ...
96338e6c65e1ff88025971361e2b36c0f1efe2af
3,640,739
def is_finally_visible_segm(*args): """is_finally_visible_segm(segment_t s) -> bool""" return _idaapi.is_finally_visible_segm(*args)
9050bd583208824859e71e84f02169237b3ac9f2
3,640,740
from vivofoundation import vivo_sparql_query def make_course_dictionary(debug=False): """ Make a course dictionary from VIVO contents. Key is course number such as ABF2010C. Value is URI. """ query = """ SELECT ?x ?label ?coursenum WHERE { ?x a ufVivo:Course . ?x ufVivo:cours...
cfe014f41aeac18116f6650cb2cb8b1200469eb9
3,640,741
def get_undisbursed_principal(loan): """Gets undisbursed principal""" principal = frappe.get_value("Microfinance Loan", loan, "loan_principal") if not principal: raise frappe.DoesNotExistError("Loan: {} not found".format(loan)) return principal - get_disbursed(loan)
7829b93eb1e6298e8640290c94b2b2aacb0de8bd
3,640,742
def northing_and_easting(dictionary): """ Retrieve and return the northing and easting strings to be used as dictionary keys Parameters ---------- dictionary : dict Returns ------- northing, easting : tuple """ if not 'x' and 'y' in dictionary.keys(): northing = 'l...
2f41d8b681d27f6ef29265c1945591ea18bba79f
3,640,743
import sys def decode_path(name): """ Attempt to decode path with correct encoding """ return name.decode(sys.getfilesystemencoding())
14da12b60c1f734e59ee5daec249c3658f3a23e4
3,640,744
import os import pickle def save_account(account): """ Function that serializes the account such that it can be saved. """ root_dir = "./accounts/"+account.name+"/" if not os.path.exists(root_dir): os.makedirs(root_dir) with open(root_dir+account.name, "wb+") as f: pickle....
08e0253764695dd71e767190c70dd32189839988
3,640,745
import math def affine(p, scale, theta, offset): """ Scale, rotate and translate point """ return arcpy.Point((p.X * math.cos(theta) - p.Y * math.sin(theta)) * scale.X + offset.X, (p.X * math.sin(theta) + p.Y * math.cos(theta)) * scale.Y + offset.Y)
2d1cd34ed94ee0c4e7ecbb786510c0165b9fca9d
3,640,746
def GetMarkedPos(slot): """ Get marked position @param slot: slot number: 1..1024 if the specifed value is <= 0 range, IDA will ask the user to select slot. @return: BADADDR - the slot doesn't contain a marked address otherwise returns the marked address """ curlo...
2c6fc7bac4a389c0cafd119fbef537e135b7f745
3,640,747
def elslib_CylinderParameters(*args): """ * parametrization P (U, V) = Location + V * ZDirection + Radius * (Cos(U) * XDirection + Sin (U) * YDirection) :param Pos: :type Pos: gp_Ax3 :param Radius: :type Radius: float :param P: :type P: gp_Pnt :param U: :type U: float & :param...
5fa697d09866747be2ef98b1b913b7aeb59fcf79
3,640,748
def totaled_no_review_url(cc, sql_time_specification): # pragma: no cover """Counts the number of commits with no review url in a given timeframe Args: cc(cursor) sql_time_specification(str): a sql command to limit the dates of the returned results Return: count(in...
027f49b13316ecb36eed3e7dde880848b261e3b4
3,640,749
import warnings def is_sat(formula, solver_name=None, logic=None, portfolio=None): """ Returns whether a formula is satisfiable. :param formula: The formula to check satisfiability :type formula: FNode :param solver_name: Specify the name of the solver to be used :type solver_name: string :...
9121747de68aa531c7c7e9c9f683cd1f1518e54b
3,640,750
import math def bounds(*tile): """Returns the bounding box of a tile Parameters ---------- tile : Tile or tuple May be be either an instance of Tile or 3 ints (X, Y, Z). Returns ------- LngLatBbox """ tile = _parse_tile_arg(*tile) xtile, ytile, zoom = tile Z2 = ...
ed2eb5865d21033029ddfcdd133663c9d222687d
3,640,751
from typing import Tuple def http(func: str, arg: Tuple[str]) -> int: """Summary. Args: func (str): Path to a function. arg (Tuple[str]): Description Returns: int: Description """ return ERGO_CLI.http(func, *list(arg))
1e46eefa4101ff63d2d3851bacbfd472e1d3c7ce
3,640,752
import time def isMWS_bhb(primary=None, objtype=None, gaia=None, gaiaaen=None, gaiadupsource=None, gaiagmag=None, gflux=None, rflux=None, zflux=None, w1flux=None, w1snr=None, maskbits=None, gnobs=None, rnobs=None, znobs=None, gfracmasked=None, rfra...
1a4f4287263ee64497ebdf882cbe3b782840b8f3
3,640,753
def bernpoly(n, z): """ Evaluates the Bernoulli polynomial `B_n(z)`. The first few Bernoulli polynomials are:: >>> from sympy.mpmath import * >>> mp.dps = 15 >>> for n in range(6): ... nprint(chop(taylor(lambda x: bernpoly(n,x), 0, n))) ... [1.0] ...
60da6461246e48f8b5ff7172f7d244c59b9ad7ed
3,640,754
def sort(obs, pred): """ Return sorted obs and pred time series' """ obs = obs.sort_values(ascending=True) pred = pred.sort_values(ascending=True) return obs,pred
11c44c1fd605611a2722321b3c3d58a822b9c643
3,640,755
import random def random_point_of_triangle(vertices): """Compute a random point of the triangle with given vertices""" p, q, r = vertices pq = q-p pr = r-p while True: x = random.random() y = random.random() if x + y <= 1: return p + pq*x + pr*y
ba3bf9183ddae4a16561a06b6f2455ce0ede6c8f
3,640,756
import time def get_minutes(hour:str) -> int: """ Get total number of minutes from time in %H:%M . Args: hour (str): String containing time in 24 hour %H:%M format Returns: int: Returns total number of minutes """ t = time.strptime(hour, '%H:%M') minutes = t[3] * 60 + t[4] ...
069835bdb6b0919d6206e0379a1933986ad2d5bd
3,640,757
from typing import Tuple import logging def get_rotation_scale_from_transformation(matrix: np.array) -> Tuple[np.array,np.array] : """ This function breaks the given transformation matrix into a Rotation matrix and a Scale matrix as described in "As-Rigid-As-Possible Shape Interpolation" by Alexa et al ...
c48ed5d1e880c7caf79e009bfeb84c95de8007e3
3,640,758
def calc_check_digit(number): """Calculate the check digit.""" weights = (7, 9, 8, 6, 5, 4, 3, 2) check = sum(w * int(n) for w, n in zip(weights, number)) % 11 return str((10 - check) % 9 + 1)
eec82a1e6cec8baf513db16e672294df79ce4b9f
3,640,759
import json def leave_studygroup(request): """ Remove a student from the list of participants of a study group. """ body = json.loads(request.body) group_id = body['id'] token = body['token'] rcs = Student.objects.get(token=token).rcs group = Studygroup.objects.get(id=group_id) p...
705c63640c11485dc68ce69d7757642a84c5798c
3,640,760
def list_revisions_courses(request_ctx, course_id, url, per_page=None, **request_kwargs): """ List the revisions of a page. Callers must have update rights on the page in order to see page history. :param request_ctx: The request context :type request_ctx: :class:RequestContext :param c...
c6ef2cd08b1a98c5204dd0e6a52b55ef57dbc78a
3,640,761
def snr2Ivar(flux, snr): """ Estimate the inverse variance given flux and S/N. Parameters ---------- flux : scalar or array of float Flux of the obejct. snr : scalar or array of float Signal to noise ratio """ return 1.0 / ((flux / snr) ** 2.0)
91c76cd942a8f37f57a227ccb35cf4968a16193b
3,640,762
def revision_to_cashflows(rev, end_date): """Converts a revision to a list of cashflows end_date -- the date from which we want to stop computing """ if rev.end_date is not None: end_date = next_month(rev.end_date) result = [] for first_of_month in first_of_month_range(rev.start_date, en...
51778e5c389420101d3ef6afab0e28b6aa708689
3,640,763
def filter_verified_user(path, community_user_dataFrame,verified_user_file,sep = ',',header = None): """ 根据已经认证的用户文件,过滤到保留社区中的认证用户。 :param path:认证用户文件的保存路径。 :param community_user_dataFrame:社区用户数据框,两列,列名(user_id, community_id)。 :param verified_user_file:认证用户的文件,为CSV文件,格式为(user_id, is_verified, name),...
a571f72000e0a52e8f5aa0d5ae61cd07e2d7189d
3,640,764
from datetime import datetime def calculate(series): """ :param series: a list of lists of [[(),()], [(),()]] for every swc tube in the pixel :return: """ # gets every dates tuple in the list dates = [t for t, v in series] # define the dates as a set ds = set(dates[0]) # get the i...
136fa5fd72bad6c1cb2938e25adc44d768caf43b
3,640,765
from typing import Tuple def load_dataset(filename: str) -> Tuple[np.ndarray, np.ndarray]: """ Load dataset for comparing the Gaussian Naive Bayes and LDA classifiers. File is assumed to be an ndarray of shape (n_samples, 3) where the first 2 columns represent features and the third column the class ...
15b6c7422fa397e13fc19de2a1e7681b73e3638c
3,640,766
import csv def readCSV(name,shape = [None], delimiter = ","): """ Lectura de archivo csv name Devuelve matriz con los datos y cabecera """ data = [] with open(name, 'r') as f: reader = csv.reader(f,delimiter = delimiter) for row in reader: data.append(row[slice(*sha...
789341daf51b2f1e92086a42698ea0fef1130505
3,640,767
from gdata.media import Category def build_category(category): """Build a single-item list of a YouTube category. This refers to the Category of a video entry, such as "Film" or "Comedy", not the atom/gdata element. This does not check if the category provided is valid. Keyword arguments: category: St...
6906e30fcf1d72d7842ec5d7381a12842a9ded3e
3,640,768
def all(event, context): """ retrieves all experiment results from redis params: - namespace (optional) - scope (optional, comma-separated list of experiments) """ r = _redis() namespace = event.get('namespace', 'alephbet') scope = event.get('scope') if scope: ...
583cc6a0101fbb6ef1ca12d6ddcfe76626bdd8dd
3,640,769
import os import time def wait_for_save(filename, timeout=5): """Waits for FILENAME to update, waiting up to TIMEOUT seconds. Returns True if a save was detected, and False otherwise. """ modification_time = os.path.getmtime(filename) start_time = time.time() while time.time() < start_time + t...
fa65a638188d32dba9904bb19e2327f5b0390996
3,640,770
def check_submodule_update(job, position): """ Checks to see if certain submodules have been updated and post a comment to the PR if so. """ output = get_output_by_position(job, position) modules = find_in_output(output, "CIVET_CLIENT_SUBMODULE_UPDATES") if not modules: return False ...
ca6772b516fca899d6196cea47aa4185d958ec48
3,640,771
def _compute_subseq_errors_direct(series, weights): """ Subsequence errors (using one pass formulation) :param Array{Float64,1} series :param Array{Float64,1} weights The subsequence errors is: $$\begin{align} E[i,j] &= Q[i,j] - \frac{S[i,j]^2}{W[i,j]} \end{align}$$ Were W, S, ...
d8083b2b19102d51ee10baf2907890663f1d2b82
3,640,772
def preprocess_dataframe(data): """Helper method to preprocess the dataframe. Creates new columns for year,month,recalls and percentage change. Limits the date range for the experiment (these data are trustworthy).""" data['recalls'] = data['doc_count'] + 1 data.drop(columns=['product', 'Unnam...
f6670cac1319108c88ee9ee409ce0ecdd1eca746
3,640,773
def is_solution(x:int, y:int) -> bool: """Returns try if (x, y) is a solution.""" # x and y are the values in a sequence of 15 terms of the following form: # xxxxyxxxxxyxxxx # x must be a positive integer if x <= 0: return False # y must be a negative integer if y >= 0: re...
5e620fc390f6a79fd25d00c8c8b51d0af788d48c
3,640,774
def load_crl(file): # type: (AnyStr) -> CRL """ Load CRL from file. :param file: Name of file containing CRL in PEM format. :return: M2Crypto.X509.CRL object. """ with BIO.openfile(file) as f: cptr = m2.x509_crl_read_pem(f.bio_ptr()) return CRL(cptr, 1)
d711503c78edbb722189d7a06340ab9f719f853f
3,640,775
def clean_and_lemmatize(text): """ Clean and lemmatize the text of a Tweet Returns: cleaned_text (string): The cleaned and lemmatized text. """ wnl = WordNetLemmatizer() # NLTK lemmatizer converted_tweet = clean_and_tokenize( text) # cleans the text and tokenize it ...
0635e08aca69191d77ad652dcf752254fbfc2ea6
3,640,776
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding Arguments: in_planes {int} -- Number of channels in the input image out_planes {int} -- Number of channels produced by the convolution Keyword Arguments: stride {int or tuple, option...
1f55153bb35dd56b7cca2b00e13a0f4e5a963248
3,640,777
def task_finish(request, pk): """タスクを完了するAPI :param request: :param pk: :return: """ task = get_object_or_404(models.Task, pk=pk) prev_task = task.get_prev_task() if prev_task is None or prev_task.can_continue(): task.status = '99' task.updated_user = request.user ...
b995edd022e27b6101c9c79874af4fc78a01afe2
3,640,778
import sys import argparse def add_parser(subparsers): """Add reduction parser""" parser = subparsers.add_parser( 'reduce', aliases=['red'], help="""Reduce games""", description="""Create reduced game files from input game files.""") parser.add_argument( '--input', '-i', metavar='<...
d1629ba58fd17f89b6f8646b92a251fbcdba0a67
3,640,779
def fine_tune(): """recreates top model architecture/weights and fine tunes with image augmentation and optimizations""" # reconstruct vgg16 model model = Sequential() model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height))) model.add(Convolution2D(64, 3, 3, activation='relu', ...
69982c739927fca8f1c8e3779a7358a7fc646a5f
3,640,780
def normalize(a, seqlength=None, rv=None): """ Normalize the VSA vector :param a: input VSA vector :param seqlength: Optional, for BSC vectors must be set to a valid. :param rv: Optional random vector, used for splitting ties on binary and ternary VSA vectors. :return: new VSA vector """ ...
ef8ec307add55a56be5991bb13579bc989726d3c
3,640,781
def MACD(df, n_fast, n_slow): """Calculate MACD, MACD Signal and MACD difference :param df: pandas.DataFrame :param n_fast: :param n_slow: :return: pandas.DataFrame """ EMAfast = pd.Series(df['Close'].ewm(span=n_fast, min_periods=n_slow).mean()) EMAslow = pd.Series(df['Close'].ewm...
368f80feb27bd67a387b0b9abb652d53205d22ac
3,640,782
def ecef2map(xyz, spatialRef): """ transform 3D cartesian Earth Centered Earth fixed coordinates, to map coordinates (that is 2D) in a projection frame Parameters ---------- xyz : np.array, size=(m,3), float np.array with 3D coordinates, in WGS84. In the following form: [[x, y, z], ...
f7177912c931cfe6c2cee5737ed6bd2afedeba08
3,640,783
def dis2speed(t, dis): """ Return speed in distance travelled per hour. Args: t (datetime64[ms]): 1D array with time. dis (float ): 1D array with distance travelled. Returns: float: 1D array with speed data. """ # divide by one hour (=3600 x 1...
4dae87509ad44604949f1d3f925f3b28947b9952
3,640,784
def default_context(plugin, context): """ Return the default context for plugins rendered with a template, which simply is a single variable named ``plugin`` containing the plugin instance. """ return {"plugin": plugin}
5f7a88c02b6c11a150197e50a5be1847cba422b0
3,640,785
def get_model_from_key(model_name): """ Gets the model from a given key. param: model_name: name of model return: object """ _known_models = {} #populate for klass in Model.__subclasses__(): _known_models[klass.__name__] = klass for sub in klass._...
488c52635bfdf10c79936b0f33b84d0222d1ae5b
3,640,786
def default_fields( coll_id=None, type_id=None, entity_id=None, width=12, **kwargs): """ Returns a function that accepts a field width and returns a dictionary of entity values for testing. The goal is to isolate default entity value settings from the test cases. """ def_label = kwar...
1670f95a8e95f84ca5f08aab8ee0a8effb1e6f76
3,640,787
import traceback def predict_using_broadcasts(feature1, feature2, feature3, feature4): """ Scale the feature values and use the model to predict :return: 1 if normal, -1 if abnormal 0 if something went wrong """ prediction = 0 x_test = [[feature1, feature2, feature3, feature4]] try: ...
4f766002e11fbe34f3479769db752c0df08b2df5
3,640,788
import torch def make_positions(tensor, padding_idx, left_pad): """Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored, but it is necessary to specify whether padding is added on the left side (left_pad=True) or right side (left...
8e65c68daae2e40710c777d6e74f048b8b0ad547
3,640,789
def teq(state, *column_values): """Tag-Equals filter. Expects, that a first row contains tags and/or metadata Tag row is ignored in comparison, but prepended to the result (in order to maintain the first row in the results). Accepts one or more column-value pairs. Keep only rows where value in the column eq...
7fd2786dcbe8705b48081c6bc96dcdc7452e35d3
3,640,790
def adjust_labels(data_y, dataset, pred_type='actions'): """ Transforms original labels into the range [0, nb_labels-1] :param data_y: numpy integer array Sensor labels :param pred_type: string, ['gestures', 'locomotion', 'actions', 'tasks'] Type of activities to be recognized :retu...
1d201a20a8865cd505c0ee6b5385622a0ae28817
3,640,791
def is_str_or_bytes(x): """ True if x is str or bytes. This doesn't use rpartial to avoid infinite recursion. """ return isinstance(x, (str, bytes, bytearray))
ff4bf19177ffe62f24713e077824e48ec45f8587
3,640,792
def _type_convert(new_type, obj): """ Convert type of `obj` to `force`. """ return new_type(obj)
fc47c100508d41caa7ffc786746b58e3d6f684e2
3,640,793
def create_tokenizer(corpus_file, vocab_size): """Create a tokenizer from a corpus file Args: corpus_file (Pathlib path): File containng corpus i.e. all unique words for vocab_size (int): Vocabulary size of the tokenizer Returns: hugging_face tokenizer: Byte pair tokenizer used to ...
6de30b057d920d650f065af0f9083130fbb6df77
3,640,794
def get_readings(tag): """Get sensor readings and collate them in a dictionary.""" try: enable_sensors(tag) readings = {} # IR sensor readings["ir_temp"], readings["ir"] = tag.IRtemperature.read() # humidity sensor readings["humidity_temp"], readings["humidity"] =...
481aae840d9ab41995086e3ef98c500abf4ec82e
3,640,795
import binascii def digita_gw(request): """ Digita GW endpoint implementation """ identifier = request.data['DevEUI_uplink']['DevEUI'] apsen = core.models.apartment_sensor_models.ApartmentSensor.objects.get_or_create(identifier=identifier)[0] payload = binascii.unhexlify(request.data['DevEUI_u...
e6bf45c92ea61278dd47e52ed945e91aa514d21b
3,640,796
def resize_img(_img, maxdims=(1000, 700)): """ Resize a given image. Image can be either a Pillow Image, or a NumPy array. Resizing is done automatically such that the entire image fits inside the given maxdims box, keeping aspect ratio intact :param _img: :param maxdims: :return: """ tr...
54716e4ce030a675a0655b06d7121d4c38bd7c43
3,640,797
def natural_key(s): """Converts string ``s`` into a tuple that will sort "naturally" (i.e., ``name5`` will come before ``name10`` and ``1`` will come before ``A``). This function is designed to be used as the ``key`` argument to sorting functions. :param s: the str/unicode string to convert. ...
d0eb51bdd3e7c6caa5b13c38269bc9c07e3834d2
3,640,798
import os import re def query_props(path): """ Extracts a QueryProps object from a file name. :param path: Path to a query file :return: QueryProps of the file """ basename = os.path.basename(path) match = re.match(r''' (?P<topic>[^-]+?) (\s*-\s*) (?P<contributor>[...
d91406d724f98db063c5f2fe54ec4d5bd5ed325c
3,640,799