content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def detect_version(conn): """ Detect the version of the database. This is typically done by reading the contents of the ``configuration`` table, but before that was added we can guess a couple of versions based on what tables exist (or don't). Returns ``None`` if the database appears uninitialized, ...
6429dbb1e1767cf6fd93c3fd240ce095f1b50ef7
6,979
def nIonDotBHmodel2(z): """Ionization model 2 from BH2007: constant above z=6. """ return ((z < 6) * nIonDotLowz(z) + (z >= 6) * nIonDotLowz(6))
438cdd69a229e445f8e313145e84ed11618ee2cb
6,980
def answer(input): """ >>> answer("1234") 1234 """ lines = input.split('\n') for line in lines: return int(line)
b9ce42d88a09976444563493a01741475dce67c5
6,981
def get_leading_states(contributions): """ Return state contributions, names as lists in descending order of contribution amount :param contributions: :return: """ contributions['state'] = contributions['clean_fips'].apply(get_state) states = contributions.groupby('state') state_sums = s...
7028f87ad7b106e267104dddebc2fe42546d3cfd
6,982
def contacts_per_person_normal_self_20(): """ Real Name: b'contacts per person normal self 20' Original Eqn: b'30' Units: b'contact/Day' Limits: (None, None) Type: constant b'' """ return 30
4a240066b2aefd8af2e19f174632e1bf854bf7d3
6,983
def __compute_partition_gradient(data, fit_intercept=True): """ Compute hetero regression gradient for: gradient = ∑d*x, where d is fore_gradient which differ from different algorithm Parameters ---------- data: DTable, include fore_gradient and features fit_intercept: bool, if model has int...
e987fc53b1f1ee8cc7a0ddbe83de23b1623b532e
6,984
def calc_nsd(x, n=21): """ Estimate Noise Standard Deviation of Data. Parameters ---------- x : 1d-ndarray Input data. n : int Size of segment. Returns ------- result : float Value of noise standard deviation. """ x_diff = np.diff(x, n=2) x_frag ...
23b0041fc1a9bde364828a0a94b12fc7292a391a
6,985
def deflection_from_kappa_grid_adaptive(kappa_high_res, grid_spacing, low_res_factor, high_res_kernel_size): """ deflection angles on the convergence grid with adaptive FFT the computation is performed as a convolution of the Green's function with the convergence map using FFT The grid is returned in th...
cc71b9bd35c5e09e45815cf578870c481a03b8ed
6,986
from params import pop_sizes def remove_sus_from_Reff(strain, data_date): """ This removes the inferred susceptibility depletion from the Reff estimates out of EpyReff. The inferred Reff = S(t) * Reff_1 where S(t) is the effect of susceptible depletion (i.e. a factor between 0 and 1) and Reff_1 is t...
9342896ff84507ecbe93b96a81b781ed6f8c336e
6,987
def word2bytes(word, big_endian=False): """ Converts a 32-bit word into a list of 4 byte values. """ return unpack_bytes(pack_word(word, big_endian))
9c208efc87bb830692771f3dacb1618a1d8d7da4
6,988
def statfcn(status, _id, _ret): """ Callback for libngspice to report simulation status like 'tran 5%' """ logger.warn(status.decode('ascii')) return 0
344210160227ae76470f53eecd43c913b9dec495
6,989
def decode_eventdata(sensor_type, offset, eventdata, sdr): """Decode extra event data from an alert or log Provide a textual summary of eventdata per descriptions in Table 42-3 of the specification. This is for sensor specific offset events only. :param sensor_type: The sensor type number from th...
7a90810657edd017b42f7f70a7a0c617435cb14f
6,990
def about_incumbent(branch_df): """ number of incumbent updates incumbent throughput: num_updates / num_nodes max_improvement, min_improvement, avg_improvement avg incumbent improvement / first incumbent value max, min, avg distance between past incumbent updates distance between last update...
309dd09a6fcad58064e98c79536ca73256fe3ac2
6,992
from typing import List def unique_chars(texts: List[str]) -> List[str]: """ Get a list of unique characters from list of text. Args: texts: List of sentences Returns: A sorted list of unique characters """ return sorted(set("".join(texts)))
02bc9ce28498bd129fdb68c2f797d138ca584490
6,993
def adaptive_max_pool1d(input, output_size): """Apply the 1d adaptive max pooling to input. Parameters ---------- input : dragon.vm.torch.Tensor The input tensor. output_size : Union[int, Sequence[int]] The target output size. Returns ------- dragon.vm.torch.Tensor ...
06556ea06ebe282bf24739d56ff016924a730c8b
6,994
def get_return_nb(input_value, output_value): """Get return from input and output value.""" if input_value == 0: if output_value == 0: return 0. return np.inf * np.sign(output_value) return_value = (output_value - input_value) / input_value if input_value < 0: return_...
fe9ef59feb7b4e9797a74258ecbf890171f6df59
6,995
def get_rocauc(val,num_iterations): """ Trains a logistic regression and calculates the roc auc for classifying products as >=4 stars """ recalls = np.zeros(num_iterations) precisions = np.zeros(num_iterations) f1s = np.zeros(num_iterations) roc_aucs = np.zeros(num_iterations) factory = lr_wrapper(val,featur...
d2b2ceae240db6c3ce474d74aea1ebd4d1ed9830
6,996
import torch def poly_edges_min_length(P, T, distFcn=norm): """ Returns the per polygon min edge length Parameters ---------- P : Tensor a (N, D,) points set tensor T : LongTensor a (M, T,) topology tensor Returns ------- Tensor the (T, M,) min edge length...
efa68aa752d0f3c1efc29a846f06e006bd8bceb9
6,999
def softmax(x): """A softmax implementation.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0)
3c8e38bf30304733e957cabab35f8fec1c5fba55
7,001
import logging def get_cazy_class_fam_genbank_records(args, session, config_dict): """GenBank acc query results from the local CAZyme database for CAZyme from specific classes/fams :param args: cmd-line argument parser :param session: open SQLite db session :param config_dict: dict, defines CAZy clas...
3f2d8f65f811be1de6b839753242e51457f8e03e
7,002
def assign_bias_ID(data, bias_params=None, bias_name='bias_ID', key_name=None, bias_model=None): """ Assign a value to each data point that determines which biases are applied to it. parameters: data: pointCollection.data instance bias_parameters: a list of parameters, each unique combinati...
8f2145b5efcd7b892b3f156e1e0c4ff59dac9d43
7,003
def check(s): """ :param s:str. the input of letters :return: bool. """ if len(s) == 7 and len(s.split(' ')) == 4: for unit in s.split(' '): if unit.isalpha(): return True
86e1270af299ba83b68d0dab9f8afc3fc5b7d7c5
7,004
def pyeval(*args): """ .. function:: pyeval(expression) Evaluates with Python the expression/s given and returns the result >>> sql("pyeval '1+1'") pyeval('1+1') ------------- 2 >>> sql("select var('test')") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ....
fa7febed8f25860eee497ce670dc9465526cbbc1
7,005
def with_hyperparameters(uri: Text): """Constructs an ImporterNode component that imports a `standard_artifacts.HyperParameters` artifact to use for future runs. Args: uri (Text): Hyperparameter artifact's uri Returns: ImporterNode """ return ImporterNode( instance_name='with_h...
e06cc33d043e6abd4a9ee30648f72dcea2ad1814
7,007
def update_user_controller(user_repository_spy): # pylint: disable=W0621 """montagem de update_user_controller utilizando spy""" usecase = UpdateUser(user_repository_spy, PasswordHash()) controller = UpdateUserController(usecase) return controller
474c2bf42c932d71181bebbf7096cd628ba6956a
7,008
def blockList2Matrix(l): """ Converts a list of matrices into a corresponding big block-diagonal one. """ dims = [m.shape[0] for m in l] s = sum(dims) res = zeros((s, s)) index = 0 for i in range(len(l)): d = dims[i] m = l[i] res[index:index + d, index:index + d] = m ...
b13a67cd203930ca2d88ec3cd6dae367b313ae94
7,009
def log_new_fit(new_fit, log_gplus, mode='residual'): """Log the successful refits of a spectrum. Parameters ---------- new_fit : bool If 'True', the spectrum was successfully refit. log_gplus : list Log of all previous successful refits of the spectrum. mode : str ('positive_re...
16761ca135efbdb9ee40a42cb8e9e1d62a5dc05e
7,010
def prepare_hr_for_compromised_credentials(hits: list) -> str: """ Prepare human readable format for compromised credentials :param hits: List of compromised credentials :return: Human readable format of compromised credentials """ hr = [] for hit in hits: source = hit.get('_source...
846144700d3fe21628306de5aff72a77d2cc9864
7,011
def red_bg(text): """ Adds a red background to the given text. """ return colorize(text, "\033[48;5;167m")
edc2741f3246de2c90c9722c4dbd2d813708fe90
7,012
def model_utils(decoy: Decoy) -> ModelUtils: """Get mock ModelUtils.""" return decoy.mock(cls=ModelUtils)
eb5d3eaf8f280086521209f62025e42fca7aec93
7,013
def getLeftTopOfTile(tilex, tiley): """Remember from the comments in the getStartingBoard() function that we have two sets of coordinates in this program. The first set are the pixel coordinates, which on the x-axis ranges from 0 to WINDOWWIDTH - 1, and the y-axis ranges from 0 to WINDOWHEIGHT - 1. Lembrando...
fad5a9df02b05e76ba62013a49d77941b71f6f5f
7,014
def count_str(text, sub, start=None, end=None): """ Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``. Optional arguments start and end are interpreted as in slice notation. :param text: The string to search :type text: ``str`` :param ...
1578f868a4f1a193ec9907494e4af613ca2a6d4d
7,015
def tanh(x, out=None): """ Raises a ValueError if input cannot be rescaled to a dimensionless quantity. """ if not isinstance(x, Quantity): return np.tanh(x, out) return Quantity( np.tanh(x.rescale(dimensionless).magnitude, out), dimensionless, copy=False )
3d86565fb512bfe6f8034dd7436b65c1c322cde6
7,016
from typing import Optional from typing import Sequence from pathlib import Path def epacems( states: Optional[Sequence[str]] = None, years: Optional[Sequence[int]] = None, columns: Optional[Sequence[str]] = None, epacems_path: Optional[Path] = None, ) -> dd.DataFrame: """Load EPA CEMS data from P...
79213c5adb0b56a3c96335c0c7e5cb1faa734752
7,017
from typing import Optional from typing import Tuple import logging def check_termination_criteria( theta: Optional[float], num_iterations: Optional[int] ) -> Tuple[float, int]: """ Check theta and number of iterations. :param theta: Theta. :param num_iterations: Number of iterations....
536cd70b8e8b04d828f0a4af1db96809ab607ff3
7,018
def verify_password(password, hash): """Verify if a hash was generated by the password specified. :password: a string object (plaintext). :hash: a string object. :returns: True or False. """ method = get_hash_algorithm(flask.current_app.config['HASH_ALGORITHM']) return method.verify(pass...
484ad9f2debbd8856b9b7fbdd2a7588f9a279f62
7,020
import re def _conversion_sample2v_from_meta(meta_data): """ Interpret the meta data to extract an array of conversion factors for each channel so the output data is in Volts Conversion factor is: int2volt / channelGain For Lf/Ap interpret the gain string from metadata For Nidq, repmat the gai...
e8cd2ea376bdb44ee999459ffcc28c4c4db39458
7,021
def read_split_csv(input_files, delimiter='\t', names=['src', 'dst'], dtype=['int32', 'int32']): """ Read csv for large datasets which cannot be read directly by dask-cudf read_csv due to memory requirements. This function takes large input split into smaller files (number of input_fi...
cd1f2ccd487cf808af1de6a504bc0f6a3a8e34a1
7,022
def _gnurl( clientID ): """ Helper function to form URL to Gracenote_ API service. :param str clientID: the Gracenote_ client ID. :returns: the lower level URL to the Gracenote_ API. :rtype: str """ clientIDprefix = clientID.split('-')[0] return 'https://c%s.web.cddbp.net/webapi/xml...
6d1935c8b634459892e4ec03d129c791b1d8a06a
7,023
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. js...
01d9ee3ec96b5a096758f60c2defe6c491d94817
7,024
def draw_bboxes(img,boxes,classes): """ Draw bounding boxes on top of an image Args: img : Array of image to be modified boxes: An (N,4) array of boxes to draw, where N is the number of boxes. classes: An (N,1) array of classes corresponding to each bounding box. Outputs: ...
6b60550206aaaa9e5033850c293e6c48a7b13e6d
7,025
def markdown(context, template_path): """ {% markdown 'terms-of-use.md' %} """ return mark_safe(get_markdown(context, template_path)[0])
ea6cb711c1a669ad7efdf277baab82ea2a65ba9c
7,026
def investorMasterGetSubaccAssetDetails(email, recvWindow=""): """# Query managed sub-account asset details(For Investor Master Account) #### `GET /sapi/v1/managed-subaccount/asset (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- email |STRING |...
7d4f4c5cbd069144319268dcb7235926e55f85d8
7,027
def ema_indicator(close, n=12, fillna=False): """EMA Exponential Moving Average via Pandas Args: close(pandas.Series): dataset 'Close' column. n_fast(int): n period short-term. fillna(bool): if True, fill nan values. Returns: pandas.Series: New feature generated. "...
9ddb20ddc6e0cc4b1f08a4e3347f719dbe84b55b
7,028
def u_glob(U, elements, nodes, resolution_per_element=51): """ Compute (x, y) coordinates of a curve y = u(x), where u is a finite element function: u(x) = sum_i of U_i*phi_i(x). Method: Run through each element and compute cordinates over the element. """ x_patches = [] u_patches = [] ...
2c9cabf97b9904d80043a0102c0ac8cd156388ae
7,030
def keyring_rgw_create(**kwargs): """ Create rgw bootstrap keyring for cluster. Args: **kwargs: Arbitrary keyword arguments. cluster_uuid : Set the cluster UUID. Defaults to value found in ceph config file. cluster_name : Set the cluster name. Defaults to "ce...
077a3536a6e1ce2e762b14d8fb046617136fe941
7,031
import pandas from datetime import datetime def read_tm224_data(filename: str, folder: str = None) -> pandas.DataFrame: """ Read data stored by Lakeshore TM224 temperature monitor software. Args: filename: string name of ".xls" file on disk folder: string location...
430e5a64b5b572b721177c5adce7e222883e4512
7,032
import json import logging def load_keypoints2d_file(file_path, njoints=17): """load 2D keypoints from keypoint detection results. Only one person is extracted from the results. If there are multiple persons in the prediction results, we select the one with the highest detection score. Args: file_path...
3cf5c8f2c236b3883e983c74e1ac23c78d256b0d
7,034
def utf8_bytes(string): """ Convert 'string' to bytes using UTF-8. """ return bytes(string, 'UTF-8')
8e5423d2b53e8d5fbeb07017ccd328236ef8bea5
7,035
def _get_value(session_browser, field): """Get an input field's value.""" return session_browser.evaluate_script('$("#id_%s").val()' % field)
7ed2d130b83af7e6fdb6cce99efb44846820585a
7,037
import functools def standarize_ms(datas, val_index, max=(2^32 - 1)): """ Standarize milliseconds lapsed from Arduino reading. Note: Only takes height for one circulation of ms from Arduino. datas: List of data readings val_index: Index of ms value in reading data entry max: ...
84bf498ff3c88b3415433fa9d5be7b6865b3216b
7,042
def corr_bias(x_data, y_data, yerr, pdz1_x, pdz1_y, pdz2_x, pdz2_y): """ Given a correlation measurement and associated PDZs, generate a model and fit as a bias to the measurement. Return: 1) the model [unbiased] (x and y float arrays) 2) best fit bias (float) 3) the bias PDF (x ...
255e1c5a67551deb19b91d247f5a913541d8f1da
7,043
def confidence_ellipse( x=None, y=None, cov=None, ax=None, n_std=3.0, facecolor="none", **kwargs ): """ Create a plot of the covariance confidence ellipse of `x` and `y` Parameters ---------- x, y : array_like, shape (n, ) Input data. cov : array_like, shape (2, 2) covarianc...
3965012ccdd1f6b71af4f169b812c384446ed76d
7,044
from typing import List def adapted_fields(type) -> List[Attribute]: """Return the attrs format of `fields()` for attrs and dataclasses.""" if is_dataclass(type): return [ Attribute( attr.name, attr.default if attr.default is not MISSING ...
cc6a799e06715cbd4e3219ea42aaeff2e4924613
7,046
from typing import get_args def get_parms(): """ Use get_args to get the args, and return a dictionary of the args ready for use in pump software. @see get_args() :return: dict: parms """ parms = {} args = get_args() for name, val in vars(args).items(): if val is not None:...
6ebdbee656fd216e5d8c66025029aa2d58641831
7,047
def make_led_sample(n_samples=200, irrelevant=0, random_state=None): """Generate random samples from the 7-segment problem. Parameters ---------- n_samples : int, optional (default=200) The number of samples to generate. irrelevant : int, optional (default=0) The number of irreleva...
7dab2595c0118ca2f08a99ded22047be164f1648
7,049
def handle_source_authorization_exception(e): """ Error handler: the data source requires authorisation This will be triggered when opening a private HDX dataset before the user has supplied their authorisation token. @param e: the exception being handled """ if e.message: flask.flash(e....
e2c736b301e229d61874bb3cfad13b86dc93e1d1
7,050
def findcosmu(re0, rp0, sublat, latc, lon): # considers latc to be plaentocentric latitudes, but sublat to be planetographic """Takes the equitorial and polar radius of Jupiter (re0, rp0 respectively), the sub-latitude of Jupiter, latitude and longitude (both in radians) to determine the "cos(mu)" of the ...
677adffb6f00e9e1119a71a660ee81d2893d4ef1
7,051
def RMS_energy(frames): """Computes the RMS energy of frames""" f = frames.flatten() return N.sqrt(N.mean(f * f))
10d366e771f629c6efda2faf1f752363dca63b0a
7,052
import urllib def is_blacklisted_url(url): """ Return whether the URL blacklisted or not. Using BLACKLIST_URLS methods against the URLs. :param url: url string :return: True if URL is blacklisted, else False """ url = urllib.parse.urlparse(url).netloc for method in WHITELIST_URL: ...
8a987c0bbce01d18da67b047aed0e680ce5fc661
7,053
def heading(yaw): """A helper function to getnerate quaternions from yaws.""" q = euler2quat(0.0, 0.0, yaw) quat = Quaternion() quat.w = q[0] quat.x = q[1] quat.y = q[2] quat.z = q[3] return quat
fcd05575257ef6cdc084cb2fde309aa48b5a2fb5
7,054
def check_login_required(view_func): """ A decorator that checks whether login is required on this installation and, if so, checks if the user is logged in. If login is required and the user is not logged in, they're redirected to the login link. """ def _check(*args, **kwargs): siteconf...
9f0b44f630a24649d87af0bd604a41b7b5b885de
7,055
def Str(*args): """(s1, s2, ...) -> match s1 or s2 or ...""" if len(args) == 1: return Str1(args[0]) return Expression.Alt(tuple(map(Str, args)))
41aece71a6a774db58028add5d60d8c9fed42dd3
7,056
def image_noise_gaussian(image): """ Adds Gaussian noise to the provided image """ float_img = image.astype(np.float) gauss = np.random.normal(0.0, 4.0, (IMG_SIZE, IMG_SIZE, IMG_CHANNELS)) gauss = gauss.reshape(IMG_SIZE, IMG_SIZE, IMG_CHANNELS).astype(np.float) result = float_img + gauss ...
0e5f5a83f7017d48e083a35bcb22cdf50ebb1006
7,057
from re import T def argsort(x: T.FloatTensor, axis: int = None) -> T.LongTensor: """ Get the indices of a sorted tensor. If axis=None this flattens x. Args: x: A tensor: axis: The axis of interest. Returns: tensor (of ints): indices of sorted tensor """ if axis ...
57e2e4d8c5a870c4ea382a02e19d0451dbe90704
7,058
def dirPickledSize(obj,exclude=[]): """For each attribute of obj (excluding those specified and those that start with '__'), compute the size using getPickledSize(obj) and return as a pandas Series of KBs""" return pd.Series({o:getPickledSize(getattr(obj, o))/1024. for o in dir(obj) if not np.any([o[:2]=='_...
d27b404f8c637aa7dd230126d3dbe9112240112c
7,059
from typing import Any def audit_log() -> Any: """ List all events related to the connected member. """ if "member_id" not in session: abort(404) return render_template( "audit_log.html", full_audit_log=fetch_audit_log(session["member_id"]), )
a5c95ac9c7e55212f8e308a9bf141468dc3a7626
7,060
def load_comparisonXL(method, evaluate="train", dropna=True): """Load comparison table.""" if evaluate == "test": e = "['Test']" elif evaluate == "in bag": e = "['In Bag']" elif evaluate == "out of bag": e = "['Out of Bag']" else: e = "['Train']" # Import methods...
56ff4d8c74ec88fc8b2f245706b7cf039334a76f
7,061
def verify_user_password(user: User, password: str) -> bool: """Verify User's password with the one that was given on login page.""" return pwd_context.verify(password, user.password)
43b25118e5ef3b89622acd7aa3276a1b18352674
7,062
def __valid_ddb_response_q(response): """private function to validate a given DynamoDB query response.""" if 'ResponseMetadata' in response: if 'HTTPStatusCode' in response['ResponseMetadata']: if response['ResponseMetadata']['HTTPStatusCode'] == 200: return True return F...
f4e71c4f5d058ba20013b3a405ffeff637e03ae8
7,063
def GetPipelineResultsPathInGCS(artifacts_path): """Gets a full Cloud Storage path to a pipeline results YAML file. Args: artifacts_path: string, the full Cloud Storage path to the folder containing pipeline artifacts, e.g. 'gs://my-bucket/artifacts'. Returns: A string representing the full Cloud ...
83b7c15f00679ff201c9a8b155102f36bb8e685c
7,064
def Pnm_p(n, m, x): """Eq:II.77 """ return lpmn(m, n, x)[1][-1, -1]
027cb169263853ede6d29a6760da981d30ef950b
7,065
def _remove_empty_subspace(subspaces, n_clusters, m, P, centers, labels, scatter_matrices): """ Check if after rotation and rearranging the dimensionalities a empty subspaces occurs. Empty subspaces will be removed for the next iteration. Therefore all necessary lists will be updated. :param subspaces: ...
473a509860b9708ee217f4f7b0a2718d1a3a7d7e
7,066
def _get_citekeys_action(elem, doc): """ Panflute action to extract citationId from all Citations in the AST. """ if not isinstance(elem, pf.Citation): return None manuscript_citekeys = global_variables["manuscript_citekeys"] manuscript_citekeys.append(elem.id) return None
74dec7a972f38c34040dc430b0c130b2a76784c2
7,067
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gra...
da85dee074f5bb15a13ea3d2c2fe105469c1ee90
7,068
def compute_neighbours_probability_matrix(n_matrix, src, d_matrix, sigma_neigh): """Compute neighbours' probability matrix. Parameters ----------- n_matrix : :py:class:`~numpy.ndarray` of :py:class:`~int`, shape (n_verts, n_neigh_max) The sets of neighbours. src : :py:class:`~numpy.ndarray...
2651ad650697266d7e0db5fdc55e176334fc3cb8
7,069
def ar_cosmap(inmap): """ Get the cosine map and off-limb pixel map using WCS. Generate a map of the solar disk that is 1 at disk center and goes radially outward as the cos(angle to LOS), which is = 2 at 60 degrees from LOS. Other outputs: - rrdeg: gives degrees from disk center - offlimb: ...
4365b0ef1134f117e5bc3396239cc1ba174f5009
7,070
def as_array(request: SubRequest) -> bool: """ Boolean fixture to support ExtensionDtype _from_sequence method testing. """ b = request.param assert isinstance(b, bool) return b
7a8b627769b8955ad4162a30be5ddc9b0ee76723
7,071
def gram_matrix(x): """Create the gram matrix of x.""" b, c, h, w = x.shape phi = x.view(b, c, h * w) return phi.bmm(phi.transpose(1, 2)) / (c * h * w)
11de97b67f3f8ecb7d7d009de16c1a5d153ab8ff
7,072
def open_file(path, mode): """ Attempts to open file at path. Tried up to max_attempts times because of intermittent permission errors on Windows """ max_attempts = 100 f = None for _ in range(max_attempts): try: f = open(path, mode) except PermissionError: ...
9217a1b66b2bb30895fe445fa4a50b5da5466391
7,074
import requests import json def get_sts_token(current_refresh_token): """ Retrieves an authentication token. :param current_refresh_token: Refresh token retrieved from a previous authentication, used to retrieve a subsequent access token. If not provided (i.e. on the initial authenticati...
b41c6658a4eb218771d6e908411ba3b54e4e13f3
7,075
async def device_climate_fan(device_climate_mock): """Test thermostat with fan device.""" return await device_climate_mock(CLIMATE_FAN)
1143adceacb610d18e1a26df4e24f715eb68917f
7,076
def make_training_config(args): """ Create training config by parsing args from command line and YAML config file, filling the rest with default values. Args args : Arguments parsed from command line. Returns config : Dictionary containing training configuration. """ # Parse the configuration file. config = {...
1902e0999336249a7feda1f0aa415f7d148a16ee
7,077
from typing import Tuple def _crown_relu_relaxer(inp: Bound) -> Tuple[LinFun, LinFun]: """Obtain the parameters of a linear ReLU relaxation as in CROWN. This relaxes the ReLU with the adaptive choice of lower bounds as described for CROWN-ada in https://arxiv.org/abs/1811.00866. Args: inp: Input to the ...
7e43e973adb65089a2eb35665c219911fc409446
7,078
import torch import time def run_single_measurement(model_name, produce_model, run_model, teardown, inp, criterion, extra_params, use_dtr, use_profiling): """ This function initializes a model and performs a single measurement of the model on the given input. While it might seem most reasonable to in...
a3765a88ccb10b3f0322f11f8205ecfdb7f98f38
7,079
def make_noise(fid, snr, decibels=True): """Given a synthetic FID, generate an array of normally distributed complex noise with zero mean and a variance that abides by the desired SNR. Parameters ---------- fid : numpy.ndarray Noiseless FID. snr : float The signal-to-noise ...
823c9fee2c1a696a38b6a27406f51a27185460c1
7,080
def viterbi(prob_matrix): """ find the most likely sequence of labels using the viterbi algorithm on prob_matrix """ TINY = 1e-6 # to avoid NaNs in logs # if prob_matrix is 1D, make it 2D if len(np.shape(prob_matrix)) == 1: prob_matrix = [prob_matrix] length = len(prob_...
50b28dcf7cedc75adb4a41cb9ccf2152af5f4b8f
7,081
def slsn_constraint(parameters): """ Place constraints on the magnetar rotational energy being larger than the total output energy, and the that nebula phase does not begin till at least a 100 days. :param parameters: dictionary of parameters :return: converted_parameters dictionary where the viola...
9fd4cc37c783aa1afdc816edbc88c45132fb4026
7,082
def grover_circuit(n,o,iter): """Grover Search Algorithm :param n: Number of qubits (not including ancilla) :param o: Oracle int to find :return qc: Qiskit circuit """ def apply_hadamard(qc, qubits,a=None) -> None: """Apply a H-gate to 'qubits' in qc""" for q in qubits: ...
fac61eda28a249e333dabd46c7d404603141c07c
7,083
def reference_cluster(envs, in_path): """ Return set of all env in_paths referencing or referenced by given in_path. >>> cluster = sorted(reference_cluster([ ... {'in_path': 'base', 'refs': []}, ... {'in_path': 'test', 'refs': ['base']}, ... {'in_path': 'local', 'refs': ['test']...
6398705dfb63c30de62b2eb900d88612e5144774
7,084
def scheme_apply(procedure, args, env): """Apply Scheme PROCEDURE to argument values ARGS in environment ENV.""" if isinstance(procedure, PrimitiveProcedure): return apply_primitive(procedure, args, env) elif isinstance(procedure, UserDefinedProcedure): new_env = make_call_frame(procedure, a...
14879f29a5e8c3c5b7d4d41be35730eb66dbdc66
7,085
def _validate_num_clusters(num_clusters, initial_centers, num_rows): """ Validate the combination of the `num_clusters` and `initial_centers` parameters in the Kmeans model create function. If the combination is valid, determine and return the correct number of clusters. Parameters ---------- ...
67d0be234a97c33eb742c70e8d6bb30be4608ab2
7,086
import mimetypes def urlinline(filename, mime=None): """ Load the file at "filename" and convert it into a data URI with the given MIME type, or a guessed MIME type if no type is provided. Base-64 encodes the data. """ infile = open(filename, 'rb') text = infile.read() infile.close() ...
4b8035944a7a25d5b3ce3bc8a8fbd0a4dd424447
7,087
def star_rating(new_rating=None, prev_rating=None): """ Generates the query to update the product's star ratings. Inc method is from https://docs.mongodb.com/manual/reference/operator/update/inc/ """ add_file = { 1: {"one_star": 1}, 2: {"two_stars": 1}, 3: {"three_stars": 1},...
e50f8271dbbb8c2722729cce6a8f036c851c4e95
7,089
def check_encoder(value: EncoderArg) -> EncoderFactory: """Checks value and returns EncoderFactory object. Returns: d3rlpy.encoders.EncoderFactory: encoder factory object. """ if isinstance(value, EncoderFactory): return value if isinstance(value, str): return create_encode...
5e23b483df8fbe190f1ac6ccf743bc783728adf8
7,090
import pathlib def allowed_task_name(name: str) -> bool: """Determine whether a task, which is a 'non-core-OSCAL activity/directory is allowed. args: name: the task name which is assumed may take the form of a relative path for task/subtasks. Returns: Whether the task name is allowed or ...
231d7a98f5d6b7059f5517283ec3bed35264050e
7,091
def get_ignored_classes(uppercase, lowercase, digit): """ get tuple of ignored classes based on selected classes :param uppercase: whether to keep uppercase classes :param lowercase: whether to keep lowercase classes :param digit: whether to keep digit classes :return: ...
2a2380f4f984feb42ce1de912739fd395a8422bd
7,092
import torch def unscaled_prediction_rmse(model, input_tensor, label_tensor, scalar, loading_length=0, return_loading_error=False, device=None): """ Prediction RMSE. :param model: model :param input_tensor: input tensor :param label_tensor: label tensor :param sc...
ea7b0e2c2fd022cc7bcb466057feacf5a1fbaa00
7,093
import copy def __copyList__(fromList, initialValues = None): """ Returns a copy of the provided list. Initial values must either be a single value, or a list of exactly the same size as the provided list. """ if __isListType__(fromList) is False: raise ValueError('The provided value to co...
9f126a10795132b5d2ddaeef552c6e5abd8680ba
7,094
import re def build_or_pattern(patterns, escape=False): """Build a or pattern string from a list of possible patterns """ or_pattern = [] for pattern in patterns: if not or_pattern: or_pattern.append('(?:') else: or_pattern.append('|') or_pattern.append(...
225cc20504a85342694e14ea76b9bf3ed8b6d11b
7,095