_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33000
load_model
train
def load_model(file_path): """ Loads an ONNX model to a ProtoBuf object. :param file_path: ONNX file (full file name) :return: ONNX model. Example: :: from onnxmltools.utils import load_model onnx_model = load_model("SqueezeNet.onnx") """ if not path.exists(file_path)...
python
{ "resource": "" }
q33001
set_model_domain
train
def set_model_domain(model, domain): """ Sets the domain on the ONNX model. :param model: instance of an ONNX model :param domain: string containing the domain name of the model Example: :: from onnxmltools.utils import set_model_domain onnx_model = load_model("SqueezeNet.onnx...
python
{ "resource": "" }
q33002
set_model_version
train
def set_model_version(model, version): """ Sets the version of the ONNX model. :param model: instance of an ONNX model :param version: integer containing the version of the model Example: :: from onnxmltools.utils import set_model_version onnx_model = load_model("SqueezeNet.on...
python
{ "resource": "" }
q33003
set_model_doc_string
train
def set_model_doc_string(model, doc, override=False): """ Sets the doc string of the ONNX model. :param model: instance of an ONNX model :param doc: string containing the doc string that describes the model. :param override: bool if true will always override the doc string with the new value E...
python
{ "resource": "" }
q33004
ModelComponentContainer.add_initializer
train
def add_initializer(self, name, onnx_type, shape, content): ''' Add a TensorProto into the initializer list of the final ONNX model :param name: Variable name in the produced ONNX model. :param onnx_type: Element types allowed in ONNX tensor, e.g., TensorProto.FLOAT and TensorProto.STRI...
python
{ "resource": "" }
q33005
convert_tensor_float_to_float16
train
def convert_tensor_float_to_float16(tensor): ''' Convert tensor float to float16. :param tensor: TensorProto object :return tensor_float16: converted TensorProto object Example: :: from onnxmltools.utils.float16_converter import convert_tensor_float_to_float16 new_tensor = co...
python
{ "resource": "" }
q33006
_validate_metadata
train
def _validate_metadata(metadata_props): ''' Validate metadata properties and possibly show warnings or throw exceptions. :param metadata_props: A dictionary of metadata properties, with property names and values (see :func:`~onnxmltools.utils.metadata_props.add_metadata_props` for examples) ''' if ...
python
{ "resource": "" }
q33007
set_denotation
train
def set_denotation(onnx_model, input_name, denotation, target_opset, dimension_denotation=None): ''' Set input type denotation and dimension denotation. Type denotation is a feature in ONNX 1.2.1 that let's the model specify the content of a tensor (e.g. IMAGE or AUDIO). This information can be used by...
python
{ "resource": "" }
q33008
concatenate_variables
train
def concatenate_variables(scope, variables, container): ''' This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation. ''' # Check if it's possible to concatenate those inputs. ...
python
{ "resource": "" }
q33009
find_type_conversion
train
def find_type_conversion(source_type, target_type): """ Find the operator name for converting source_type into target_type """ if type(source_type) == type(target_type): return 'identity' elif type(target_type) == FloatTensorType: return 'imageToFloatTensor' else: raise V...
python
{ "resource": "" }
q33010
get_cool_off
train
def get_cool_off() -> Optional[timedelta]: """ Return the login cool off time interpreted from settings.AXES_COOLOFF_TIME. The return value is either None or timedelta. Notice that the settings.AXES_COOLOFF_TIME is either None, timedelta, or integer of hours, and this function offers a unified _ti...
python
{ "resource": "" }
q33011
get_credentials
train
def get_credentials(username: str = None, **kwargs) -> dict: """ Calculate credentials for Axes to use internally from given username and kwargs. Axes will set the username value into the key defined with ``settings.AXES_USERNAME_FORM_FIELD`` and update the credentials dictionary with the kwargs given ...
python
{ "resource": "" }
q33012
get_client_username
train
def get_client_username(request: AxesHttpRequest, credentials: dict = None) -> str: """ Resolve client username from the given request or credentials if supplied. The order of preference for fetching the username is as follows: 1. If configured, use ``AXES_USERNAME_CALLABLE``, and supply ``request, cr...
python
{ "resource": "" }
q33013
get_client_ip_address
train
def get_client_ip_address(request: HttpRequest) -> str: """ Get client IP address as configured by the user. The django-ipware package is used for address resolution and parameters can be configured in the Axes package. """ client_ip_address, _ = ipware.ip2.get_client_ip( request, ...
python
{ "resource": "" }
q33014
get_client_parameters
train
def get_client_parameters(username: str, ip_address: str, user_agent: str) -> dict: """ Get query parameters for filtering AccessAttempt queryset. This method returns a dict that guarantees iteration order for keys and values, and can so be used in e.g. the generation of hash keys or other deterministi...
python
{ "resource": "" }
q33015
get_query_str
train
def get_query_str(query: Type[QueryDict], max_length: int = 1024) -> str: """ Turns a query dictionary into an easy-to-read list of key-value pairs. If a field is called either ``'password'`` or ``settings.AXES_PASSWORD_FORM_FIELD`` it will be excluded. The length of the output is limited to max_lengt...
python
{ "resource": "" }
q33016
is_client_ip_address_whitelisted
train
def is_client_ip_address_whitelisted(request: AxesHttpRequest): """ Check if the given request refers to a whitelisted IP. """ if settings.AXES_NEVER_LOCKOUT_WHITELIST and is_ip_address_in_whitelist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and is_ip_address_in_...
python
{ "resource": "" }
q33017
is_client_ip_address_blacklisted
train
def is_client_ip_address_blacklisted(request: AxesHttpRequest) -> bool: """ Check if the given request refers to a blacklisted IP. """ if is_ip_address_in_blacklist(request.axes_ip_address): return True if settings.AXES_ONLY_WHITELIST and not is_ip_address_in_whitelist(request.axes_ip_addr...
python
{ "resource": "" }
q33018
is_client_method_whitelisted
train
def is_client_method_whitelisted(request: AxesHttpRequest) -> bool: """ Check if the given request uses a whitelisted method. """ if settings.AXES_NEVER_LOCKOUT_GET and request.method == 'GET': return True return False
python
{ "resource": "" }
q33019
get_client_cache_key
train
def get_client_cache_key(request_or_attempt: Union[HttpRequest, Any], credentials: dict = None) -> str: """ Build cache key name from request or AccessAttempt object. :param request_or_attempt: HttpRequest or AccessAttempt object :param credentials: credentials containing user information :return c...
python
{ "resource": "" }
q33020
AxesDatabaseHandler.user_login_failed
train
def user_login_failed( self, sender, credentials: dict, request: AxesHttpRequest = None, **kwargs ): # pylint: disable=too-many-locals """ When user login fails, save AccessAttempt record in database and lock user out if necessary. ...
python
{ "resource": "" }
q33021
AxesDatabaseHandler.user_logged_out
train
def user_logged_out(self, sender, request: AxesHttpRequest, user, **kwargs): # pylint: disable=unused-argument """ When user logs out, update the AccessLog related to the user. """ # 1. database query: Clean up expired user attempts from the database clean_expired_user_attempts...
python
{ "resource": "" }
q33022
AxesCacheHandler.user_login_failed
train
def user_login_failed( self, sender, credentials: dict, request: AxesHttpRequest = None, **kwargs ): # pylint: disable=too-many-locals """ When user login fails, save attempt record in cache and lock user out if necessary. :raises...
python
{ "resource": "" }
q33023
AxesMiddleware.update_request
train
def update_request(self, request: HttpRequest): """ Update given Django ``HttpRequest`` with necessary attributes before passing it on the ``get_response`` for further Django middleware and view processing. """ request.axes_attempt_time = now() request.axes_ip_ad...
python
{ "resource": "" }
q33024
AxesMiddleware.process_exception
train
def process_exception(self, request: AxesHttpRequest, exception): # pylint: disable=inconsistent-return-statements """ Exception handler that processes exceptions raised by the Axes signal handler when request fails with login. Only ``axes.exceptions.AxesSignalPermissionDenied`` exception is h...
python
{ "resource": "" }
q33025
AxesHandler.is_allowed
train
def is_allowed(self, request: AxesHttpRequest, credentials: dict = None) -> bool: """ Checks if the user is allowed to access or use given functionality such as a login view or authentication. This method is abstract and other backends can specialize it as needed, but the default implementation...
python
{ "resource": "" }
q33026
AxesHandler.is_blacklisted
train
def is_blacklisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or given credentials are blacklisted from access. """ if is_client_ip_address_blacklisted(request): return True return ...
python
{ "resource": "" }
q33027
AxesHandler.is_whitelisted
train
def is_whitelisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or given credentials are whitelisted for access. """ if is_client_ip_address_whitelisted(request): return True if is_cl...
python
{ "resource": "" }
q33028
AxesHandler.is_locked
train
def is_locked(self, request: AxesHttpRequest, credentials: dict = None) -> bool: """ Checks if the request or given credentials are locked. """ if settings.AXES_LOCK_OUT_AT_FAILURE: return self.get_failures(request, credentials) >= settings.AXES_FAILURE_LIMIT return...
python
{ "resource": "" }
q33029
reset
train
def reset(ip: str = None, username: str = None) -> int: """ Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. """ attempts = AccessAttempt.objects.all() if ip: attempts = attempts....
python
{ "resource": "" }
q33030
get_cool_off_threshold
train
def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ cool_off = get_cool_off() if cool_off is None: raise TypeError('Cool off threshold can not be calculated with settings.AXES_COOLOFF_TIME set to None')...
python
{ "resource": "" }
q33031
filter_user_attempts
train
def filter_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: """ Return a queryset of AccessAttempts that match the given request and credentials. """ username = get_client_username(request, credentials) filter_kwargs = get_client_parameters(username, request.axes_ip_a...
python
{ "resource": "" }
q33032
get_user_attempts
train
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet: """ Get valid user attempts that match the given request and credentials. """ attempts = filter_user_attempts(request, credentials) if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Getting all acc...
python
{ "resource": "" }
q33033
clean_expired_user_attempts
train
def clean_expired_user_attempts(attempt_time: datetime = None) -> int: """ Clean expired user attempts from the database. """ if settings.AXES_COOLOFF_TIME is None: log.debug('AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured') return 0 thr...
python
{ "resource": "" }
q33034
reset_user_attempts
train
def reset_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> int: """ Reset all user attempts that match the given request and credentials. """ attempts = filter_user_attempts(request, credentials) count, _ = attempts.delete() log.info('AXES: Reset %s access attempts from dat...
python
{ "resource": "" }
q33035
is_user_attempt_whitelisted
train
def is_user_attempt_whitelisted(request: AxesHttpRequest, credentials: dict = None) -> bool: """ Check if the given request or credentials refer to a whitelisted username. A whitelisted user has the magic ``nolockout`` property set. If the property is unknown or False or the user can not be found, ...
python
{ "resource": "" }
q33036
AxesProxyHandler.get_implementation
train
def get_implementation(cls, force: bool = False) -> AxesHandler: """ Fetch and initialize configured handler implementation and memoize it to avoid reinitialization. This method is re-entrant and can be called multiple times from e.g. Django application loader. """ if force or ...
python
{ "resource": "" }
q33037
AppConfig.initialize
train
def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.logging_initialized: return cls...
python
{ "resource": "" }
q33038
AxesBackend.authenticate
train
def authenticate(self, request: AxesHttpRequest, username: str = None, password: str = None, **kwargs: dict): """ Checks user lockout status and raise a PermissionDenied if user is not allowed to log in. This method interrupts the login flow and inserts error message directly to the ``...
python
{ "resource": "" }
q33039
DynamicSampler.results
train
def results(self): """Saved results from the dynamic nested sampling run. All saved bounds are also returned.""" # Add all saved samples (and ancillary quantities) to the results. with warnings.catch_warnings(): warnings.simplefilter("ignore") results = [('niter'...
python
{ "resource": "" }
q33040
randsphere
train
def randsphere(n, rstate=None): """Draw a point uniformly within an `n`-dimensional unit sphere.""" if rstate is None: rstate = np.random z = rstate.randn(n) # initial n-dim vector zhat = z / lalg.norm(z) # normalize xhat = zhat * rstate.rand()**(1./n) # scale return xhat
python
{ "resource": "" }
q33041
bounding_ellipsoid
train
def bounding_ellipsoid(points, pointvol=0.): """ Calculate the bounding ellipsoid containing a collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional The minimum volume occupied by a sing...
python
{ "resource": "" }
q33042
_bounding_ellipsoids
train
def _bounding_ellipsoids(points, ell, pointvol=0., vol_dec=0.5, vol_check=2.): """ Internal method used to compute a set of bounding ellipsoids when a bounding ellipsoid for the entire set has already been calculated. Parameters ---------- points : `~numpy.ndarray` with...
python
{ "resource": "" }
q33043
bounding_ellipsoids
train
def bounding_ellipsoids(points, pointvol=0., vol_dec=0.5, vol_check=2.): """ Calculate a set of ellipsoids that bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) A set of coordinates. pointvol : float, optional Volume rep...
python
{ "resource": "" }
q33044
_ellipsoid_bootstrap_expand
train
def _ellipsoid_bootstrap_expand(args): """Internal method used to compute the expansion factor for a bounding ellipsoid based on bootstrapping.""" # Unzipping. points, pointvol = args rstate = np.random # Resampling. npoints, ndim = points.shape idxs = rstate.randint(npoints, size=npoi...
python
{ "resource": "" }
q33045
UnitCube.sample
train
def sample(self, rstate=None): """ Draw a sample uniformly distributed within the unit cube. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the unit cube. """ if rstate is None: rstate = np.random re...
python
{ "resource": "" }
q33046
UnitCube.samples
train
def samples(self, nsamples, rstate=None): """ Draw `nsamples` samples randomly distributed within the unit cube. Returns ------- x : `~numpy.ndarray` with shape (nsamples, ndim) A collection of coordinates within the unit cube. """ if rstate is None...
python
{ "resource": "" }
q33047
Ellipsoid.scale_to_vol
train
def scale_to_vol(self, vol): """Scale ellipoid to a target volume.""" f = np.exp((np.log(vol) - np.log(self.vol)) / self.n) # linear factor self.expand *= f self.cov *= f**2 self.am *= f**-2 self.axlens *= f self.axes *= f self.vol = vol
python
{ "resource": "" }
q33048
Ellipsoid.major_axis_endpoints
train
def major_axis_endpoints(self): """Return the endpoints of the major axis.""" i = np.argmax(self.axlens) # find the major axis v = self.paxes[:, i] # vector from center to major axis endpoint return self.ctr - v, self.ctr + v
python
{ "resource": "" }
q33049
Ellipsoid.distance
train
def distance(self, x): """Compute the normalized distance to `x` from the center of the ellipsoid.""" d = x - self.ctr return np.sqrt(np.dot(np.dot(d, self.am), d))
python
{ "resource": "" }
q33050
Ellipsoid.randoffset
train
def randoffset(self, rstate=None): """Return a random offset from the center of the ellipsoid.""" if rstate is None: rstate = np.random return np.dot(self.axes, randsphere(self.n, rstate=rstate))
python
{ "resource": "" }
q33051
Ellipsoid.sample
train
def sample(self, rstate=None): """ Draw a sample uniformly distributed within the ellipsoid. Returns ------- x : `~numpy.ndarray` with shape (ndim,) A coordinate within the ellipsoid. """ if rstate is None: rstate = np.random re...
python
{ "resource": "" }
q33052
Ellipsoid.unitcube_overlap
train
def unitcube_overlap(self, ndraws=10000, rstate=None): """Using `ndraws` Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.""" if rstate is None: rstate = np.random samples = [self.sample(rstate=rstate) for i in range(ndraws)] ...
python
{ "resource": "" }
q33053
Ellipsoid.update
train
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, mc_integrate=False): """ Update the ellipsoid to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to ...
python
{ "resource": "" }
q33054
MultiEllipsoid.scale_to_vols
train
def scale_to_vols(self, vols): """Scale ellipoids to a corresponding set of target volumes.""" [self.ells[i].scale_to_vol(vols[i]) for i in range(self.nells)] self.vols = np.array(vols) self.expands = np.array([self.ells[i].expand for i in range(...
python
{ "resource": "" }
q33055
MultiEllipsoid.update
train
def update(self, points, pointvol=0., vol_dec=0.5, vol_check=2., rstate=None, bootstrap=0, pool=None, mc_integrate=False): """ Update the set of ellipsoids to bound the collection of points. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim...
python
{ "resource": "" }
q33056
RadFriends.scale_to_vol
train
def scale_to_vol(self, vol): """Scale ball to encompass a target volume.""" f = (vol / self.vol_ball) ** (1.0 / self.n) # linear factor self.expand *= f self.radius *= f self.vol_ball = vol
python
{ "resource": "" }
q33057
RadFriends.within
train
def within(self, x, ctrs, kdtree=None): """Check which balls `x` falls within. Uses a K-D Tree to perform the search if provided.""" if kdtree is None: # If no K-D Tree is provided, execute a brute-force # search over all balls. idxs = np.where(lalg.norm(ctrs...
python
{ "resource": "" }
q33058
RadFriends.overlap
train
def overlap(self, x, ctrs, kdtree=None): """Check how many balls `x` falls within. Uses a K-D Tree to perform the search if provided.""" q = len(self.within(x, ctrs, kdtree=kdtree)) return q
python
{ "resource": "" }
q33059
RadFriends.contains
train
def contains(self, x, ctrs, kdtree=None): """Check if the set of balls contains `x`. Uses a K-D Tree to perform the search if provided.""" return self.overlap(x, ctrs, kdtree=kdtree) > 0
python
{ "resource": "" }
q33060
RadFriends.update
train
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): """ Update the radii of our balls. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to bound. ...
python
{ "resource": "" }
q33061
SupFriends.scale_to_vol
train
def scale_to_vol(self, vol): """Scale cube to encompass a target volume.""" f = (vol / self.vol_cube) ** (1.0 / self.n) # linear factor self.expand *= f self.hside *= f self.vol_cube = vol
python
{ "resource": "" }
q33062
SupFriends.within
train
def within(self, x, ctrs, kdtree=None): """Checks which cubes `x` falls within. Uses a K-D Tree to perform the search if provided.""" if kdtree is None: # If no KDTree is provided, execute a brute-force search # over all cubes. idxs = np.where(np.max(np.abs(c...
python
{ "resource": "" }
q33063
SupFriends.update
train
def update(self, points, pointvol=0., rstate=None, bootstrap=0, pool=None, kdtree=None, mc_integrate=False): """ Update the half-side-lengths of our cubes. Parameters ---------- points : `~numpy.ndarray` with shape (npoints, ndim) The set of points to ...
python
{ "resource": "" }
q33064
sample_unif
train
def sample_unif(args): """ Evaluate a new point sampled uniformly from a bounding proposal distribution. Parameters are zipped within `args` to utilize `pool.map`-style functions. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. log...
python
{ "resource": "" }
q33065
sample_rwalk
train
def sample_rwalk(args): """ Return a new live point proposed by random walking away from an existing live point. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) Position of the initial sample. **This is a copy of an existing live point.** loglstar : float ...
python
{ "resource": "" }
q33066
Sampler.results
train
def results(self): """Saved results from the nested sampling run. If bounding distributions were saved, those are also returned.""" # Add all saved samples to the results. if self.save_samples: with warnings.catch_warnings(): warnings.simplefilter("ignore") ...
python
{ "resource": "" }
q33067
Sampler._beyond_unit_bound
train
def _beyond_unit_bound(self, loglstar): """Check whether we should update our bound beyond the initial unit cube.""" if self.logl_first_update is None: # If we haven't already updated our bounds, check if we satisfy # the provided criteria for establishing the first boun...
python
{ "resource": "" }
q33068
Sampler._empty_queue
train
def _empty_queue(self): """Dump all live point proposals currently on the queue.""" while True: try: # Remove unused points from the queue. self.queue.pop() self.unused += 1 # add to the total number of unused points self.nque...
python
{ "resource": "" }
q33069
Sampler._fill_queue
train
def _fill_queue(self, loglstar): """Sequentially add new live point proposals to the queue.""" # Add/zip arguments to submit to the queue. point_queue = [] axes_queue = [] while self.nqueue < self.queue_size: if self._beyond_unit_bound(loglstar): # Pr...
python
{ "resource": "" }
q33070
Sampler._get_point_value
train
def _get_point_value(self, loglstar): """Grab the first live point proposal in the queue.""" # If the queue is empty, refill it. if self.nqueue <= 0: self._fill_queue(loglstar) # Grab the earliest entry. u, v, logl, nc, blob = self.queue.pop(0) self.used += ...
python
{ "resource": "" }
q33071
Sampler._new_point
train
def _new_point(self, loglstar, logvol): """Propose points until a new point that satisfies the log-likelihood constraint `loglstar` is found.""" ncall, nupdate = 0, 0 while True: # Get the next point from the queue u, v, logl, nc, blob = self._get_point_value(log...
python
{ "resource": "" }
q33072
Sampler._remove_live_points
train
def _remove_live_points(self): """Remove the final set of live points if they were previously added to the current set of dead points.""" if self.added_live: self.added_live = False if self.save_samples: del self.saved_id[-self.nlive:] del...
python
{ "resource": "" }
q33073
Prior.update
train
def update(self, **kwargs): """Update `params` values using alias. """ for k in self.prior_params: try: self.params[k] = kwargs[self.alias[k]] except(KeyError): pass
python
{ "resource": "" }
q33074
Prior.sample
train
def sample(self, nsample=None, **kwargs): """Draw a sample from the prior distribution. :param nsample: (optional) Unused """ if len(kwargs) > 0: self.update(**kwargs) return self.distribution.rvs(*self.args, size=len(self), ...
python
{ "resource": "" }
q33075
Prior.inverse_unit_transform
train
def inverse_unit_transform(self, x, **kwargs): """Go from the parameter value to the unit coordinate using the cdf. """ if len(kwargs) > 0: self.update(**kwargs) return self.distribution.cdf(x, *self.args, loc=self.loc, scale=self.scale)
python
{ "resource": "" }
q33076
UnitCubeSampler.update_slice
train
def update_slice(self, blob): """Update the slice proposal scale based on the relative size of the slices compared to our initial guess.""" nexpand, ncontract = blob['nexpand'], blob['ncontract'] self.scale *= nexpand / (2. * ncontract)
python
{ "resource": "" }
q33077
UnitCubeSampler.update_hslice
train
def update_hslice(self, blob): """Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.""" nmove, nreflect = blob['nmove'], blob['nreflect'] ncontract = blob.get('ncontract', 0) fmove = (1. * nmove) / (nmove + nreflect + nco...
python
{ "resource": "" }
q33078
SingleEllipsoidSampler.update
train
def update(self, pointvol): """Update the bounding ellipsoid using the current set of live points.""" # Check if we should use the provided pool for updating. if self.use_pool_update: pool = self.pool else: pool = None # Update the ellipsoid. ...
python
{ "resource": "" }
q33079
MultiEllipsoidSampler.update
train
def update(self, pointvol): """Update the bounding ellipsoids using the current set of live points.""" # Check if we should use the pool for updating. if self.use_pool_update: pool = self.pool else: pool = None # Update the bounding ellipsoids. ...
python
{ "resource": "" }
q33080
RadFriendsSampler.update
train
def update(self, pointvol): """Update the N-sphere radii using the current set of live points.""" # Initialize a K-D Tree to assist nearest neighbor searches. if self.use_kdtree: kdtree = spatial.KDTree(self.live_u) else: kdtree = None # Check if we shou...
python
{ "resource": "" }
q33081
Results.summary
train
def summary(self): """Return a formatted string giving a quick summary of the results.""" res = ("nlive: {:d}\n" "niter: {:d}\n" "ncall: {:d}\n" "eff(%): {:6.3f}\n" "logz: {:6.3f} +/- {:6.3f}" .format(self.nlive, self.ni...
python
{ "resource": "" }
q33082
unitcheck
train
def unitcheck(u, nonperiodic=None): """Check whether `u` is inside the unit cube. Given a masked array `nonperiodic`, also allows periodic boundaries conditions to exceed the unit cube.""" if nonperiodic is None: # No periodic boundary conditions provided. return np.all(u > 0.) and np.a...
python
{ "resource": "" }
q33083
mean_and_cov
train
def mean_and_cov(samples, weights): """ Compute the weighted mean and covariance of the samples. Parameters ---------- samples : `~numpy.ndarray` with shape (nsamples, ndim) 2-D array containing data samples. This ordering is equivalent to using `rowvar=False` in `~numpy.cov`. ...
python
{ "resource": "" }
q33084
resample_equal
train
def resample_equal(samples, weights, rstate=None): """ Resample a new set of points from the weighted set of inputs such that they all have equal weight. Each input sample appears in the output array either `floor(weights[i] * nsamples)` or `ceil(weights[i] * nsamples)` times, with `floor` or `...
python
{ "resource": "" }
q33085
_get_nsamps_samples_n
train
def _get_nsamps_samples_n(res): """ Helper function for calculating the number of samples Parameters ---------- res : :class:`~dynesty.results.Results` instance The :class:`~dynesty.results.Results` instance taken from a previous nested sampling run. Returns ------- nsamps:...
python
{ "resource": "" }
q33086
reweight_run
train
def reweight_run(res, logp_new, logp_old=None): """ Reweight a given run based on a new target distribution. Parameters ---------- res : :class:`~dynesty.results.Results` instance The :class:`~dynesty.results.Results` instance taken from a previous nested sampling run. logp_new...
python
{ "resource": "" }
q33087
enum
train
def enum(enum_type='enum', base_classes=None, methods=None, **attrs): """ Generates a enumeration with the given attributes. """ # Enumerations can not be initalized as a new instance def __init__(instance, *args, **kwargs): raise RuntimeError('%s types can not be initialized.' % enum_type) ...
python
{ "resource": "" }
q33088
SendmailEmailAdapter.send_email_message
train
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via Flask-Sendmail. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body...
python
{ "resource": "" }
q33089
DBManager.add_user_role
train
def add_user_role(self, user, role_name): """Associate a role name with a user.""" # For SQL: user.roles is list of pointers to Role objects if isinstance(self.db_adapter, SQLDbAdapter): # user.roles is a list of Role IDs # Get or add role role = self.db_adap...
python
{ "resource": "" }
q33090
DBManager.find_user_by_username
train
def find_user_by_username(self, username): """Find a User object by username.""" return self.db_adapter.ifind_first_object(self.UserClass, username=username)
python
{ "resource": "" }
q33091
DBManager.find_user_emails
train
def find_user_emails(self, user): """Find all the UserEmail object belonging to a user.""" user_emails = self.db_adapter.find_objects(self.UserEmailClass, user_id=user.id) return user_emails
python
{ "resource": "" }
q33092
DBManager.get_user_and_user_email_by_id
train
def get_user_and_user_email_by_id(self, user_or_user_email_id): """Retrieve the User and UserEmail object by ID.""" if self.UserEmailClass: user_email = self.db_adapter.get_object(self.UserEmailClass, user_or_user_email_id) user = user_email.user if user_email else None e...
python
{ "resource": "" }
q33093
DBManager.get_user_and_user_email_by_email
train
def get_user_and_user_email_by_email(self, email): """Retrieve the User and UserEmail object by email address.""" if self.UserEmailClass: user_email = self.db_adapter.ifind_first_object(self.UserEmailClass, email=email) user = user_email.user if user_email else None else:...
python
{ "resource": "" }
q33094
DBManager.get_user_by_id
train
def get_user_by_id(self, id): """Retrieve a User object by ID.""" return self.db_adapter.get_object(self.UserClass, id=id)
python
{ "resource": "" }
q33095
DBManager.get_user_invitation_by_id
train
def get_user_invitation_by_id(self, id): """Retrieve a UserInvitation object by ID.""" return self.db_adapter.get_object(self.UserInvitationClass, id=id)
python
{ "resource": "" }
q33096
DBManager.get_user_roles
train
def get_user_roles(self, user): """Retrieve a list of user role names. .. note:: Database management methods. """ # For SQL: user.roles is list of pointers to Role objects if isinstance(self.db_adapter, SQLDbAdapter): # user.roles is a list of Role IDs ...
python
{ "resource": "" }
q33097
DBManager.save_user_and_user_email
train
def save_user_and_user_email(self, user, user_email): """Save the User and UserEmail object.""" if self.UserEmailClass: self.db_adapter.save_object(user_email) self.db_adapter.save_object(user)
python
{ "resource": "" }
q33098
DBManager.user_has_confirmed_email
train
def user_has_confirmed_email(self, user): """| Return True if user has a confirmed email. | Return False otherwise.""" if not self.user_manager.USER_ENABLE_EMAIL: return True if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return True db_adapter = self.db_adapter # ...
python
{ "resource": "" }
q33099
DBManager.username_is_available
train
def username_is_available(self, new_username): """Check if ``new_username`` is still available. | Returns True if ``new_username`` does not exist or belongs to the current user. | Return False otherwise. """ # Return True if new_username equals current user's username i...
python
{ "resource": "" }