code
stringlengths
1
18.2k
def context_processors_update(context, request): ''' Update context with context_processors from settings Usage: from codenerix.helpers import context_processors_update context_processors_update(context, self.request) ''' for template in settings.TEMPLATES: for context_processor in template['OPTIONS']['context_processo...
def append(self, filename_in_zip, file_contents): ''' Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip. ''' # Set the file pointer to the end of the file self.in_memory_zip.seek(-1, io.SEEK_END) # Get a handle to the in-memory zip in append mode zf = zipfile.ZipFile(self.in_me...
as having been created on Windows so that # Unix permissions are not inferred as 0000 for zfile in zf.filelist: zfile.create_system = 0 # Close the ZipFile zf.close() # Rewind the file self.in_memory_zip.seek(0) return self
def writetofile(self, filename): '''Writes the in-memory zip to a file.''' f = open(filename, "w") f.write(self.read()) f.close()
def sponsor_image_url(sponsor, name): """Returns the corresponding url from the sponsors images""" if sponsor.files.filter(name=name).exists(): # We avoid worrying about multiple matches by always # returning the first one. return sponsor.files.filter(name=name).first().item.url return ''
def sponsor_tagged_image(sponsor, tag): """returns the corresponding url from the tagged image list.""" if sponsor.files.filter(tag_name=tag).exists(): return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url return ''
def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins Clients Sellers %} ... {% else %} ... {% endifusergroup %} """ t...
requires at least 1 argument.") nodelist_true = parser.parse(('else', 'endifusergroup')) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse(tuple(['endifusergroup',])) parser.delete_first_token() else: nodelist_false = NodeList() return GroupCheckNode(groups, nodelist_true, nodelist_...
def OpenHandle(self): '''Gets a handle for use with other vSphere Guest API functions. The guest library handle provides a context for accessing information about the virtual machine. Virtual machine statistics and state data are associated with a particular guest library handle, so using one handle does not affect the...
= vmGuestLib.VMGuestLib_OpenHandle(byref(handle)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return handle
def CloseHandle(self): '''Releases a handle acquired with VMGuestLib_OpenHandle''' if hasattr(self, 'handle'): ret = vmGuestLib.VMGuestLib_CloseHandle(self.handle.value) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) del(self.handle)
def UpdateInfo(self): '''Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, minimize the number of calls to VMGuestLib...
calls. The vSphere Guest API does not implement internal locking around access with a handle.''' ret = vmGuestLib.VMGuestLib_UpdateInfo(self.handle.value) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
def GetSessionId(self): '''Retrieves the VMSessionID for the current session. Call this function after calling VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called, VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.''' sid = c_void_p() ret = vmGuestLib.VMGuestLib_GetSessionId(self.handle.value, ...
def GetCpuLimitMHz(self): '''Retrieves the upperlimit of processor use in MHz available to the virtual machine. For information about setting the CPU limit, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuLimitMHz(self.handle.value, byref(counter)) if ret != VMGUESTLIB_...
def GetCpuReservationMHz(self): '''Retrieves the minimum processing power in MHz reserved for the virtual machine. For information about setting a CPU reservation, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuReservationMHz(self.handle.value, byref(counter)) if ret !...
def GetCpuShares(self): '''Retrieves the number of CPU shares allocated to the virtual machine. For information about how an ESX server uses CPU shares to manage virtual machine priority, see the vSphere Resource Management Guide.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuShares(self.handle.value, byref(c...
def GetCpuStolenMs(self): '''Retrieves the number of milliseconds that the virtual machine was in a ready state (able to transition to a run state), but was not scheduled to run.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetCpuStolenMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: rai...
def GetCpuUsedMs(self): '''Retrieves the number of milliseconds during which the virtual machine has used the CPU. This value includes the time used by the guest operating system and the time used by virtualization code for tasks for this virtual machine. You can combine this value with the elapsed time (VMGuestLib_Get...
elapsedMs.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetCpuUsedMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetElapsedMs(self): '''Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value counts milliseconds, regardless of whether t...
the CPU time used by the virtual machine (VMGuestLib_GetCpuUsedMs) to estimate the effective virtual machine CPU speed. cpuUsedMs is a subset of this value.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetElapsedMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(r...
def GetHostCpuUsedMs(self): '''Undocumented.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetHostCpuUsedMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemKernOvhdMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemKernOvhdMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemMappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemMappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemPhysFreeMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysFreeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemPhysMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemSharedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSharedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemUnmappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUnmappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostMemUsedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostNumCpuCores(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostNumCpuCores(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetHostProcessorSpeed(self): '''Retrieves the speed of the ESX system's physical CPU in MHz.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostProcessorSpeed(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemActiveMB(self): '''Retrieves the amount of memory the virtual machine is actively using its estimated working set size.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemActiveMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemBalloonedMB(self): '''Retrieves the amount of memory that has been reclaimed from this virtual machine by the vSphere memory balloon driver (also referred to as the "vmmemctl" driver).''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemBalloonedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_E...
def GetMemBalloonMaxMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemBalloonMaxMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemBalloonTargetMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemBalloonTargetMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemLimitMB(self): '''Retrieves the upper limit of memory that is available to the virtual machine. For information about setting a memory limit, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemLimitMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_...
def GetMemLLSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemLLSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemMappedMB(self): '''Retrieves the amount of memory that is allocated to the virtual machine. Memory that is ballooned, swapped, or has never been accessed is excluded.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemMappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise V...
def GetMemOverheadMB(self): '''Retrieves the amount of "overhead" memory associated with this virtual machine that is currently consumed on the host system. Overhead memory is additional memory that is reserved for data structures required by the virtualization layer.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_G...
def GetMemReservationMB(self): '''Retrieves the minimum amount of memory that is reserved for the virtual machine. For information about setting a memory reservation, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemReservationMB(self.handle.value, byref(counter)) if ret...
def GetMemSharedMB(self): '''Retrieves the amount of physical memory associated with this virtual machine that is copy-on-write (COW) shared on the host.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSharedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)...
def GetMemSharedSavedMB(self): '''Retrieves the estimated amount of physical memory on the host saved from copy-on-write (COW) shared guest physical memory.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSharedSavedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibExcept...
def GetMemShares(self): '''Retrieves the number of memory shares allocated to the virtual machine. For information about how an ESX server uses memory shares to manage virtual machine priority, see the vSphere Resource Management Guide.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemShares(self.handle.value, b...
def GetMemSwappedMB(self): '''Retrieves the amount of memory that has been reclaimed from this virtual machine by transparently swapping guest memory to disk.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibExceptio...
def GetMemSwapTargetMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemSwapTargetMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemTargetSizeMB(self): '''Retrieves the size of the target memory allocation for this virtual machine.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemTargetSizeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemUsedMB(self): '''Retrieves the estimated amount of physical host memory currently consumed for this virtual machine's physical memory.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemUsedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return cou...
def GetMemZippedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemZippedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def GetMemZipSavedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetMemZipSavedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
def spev(t_int, C, deg, x, cov_C=None, M_spline=False, I_spline=False, n=0): """Evaluate a B-, M- or I-spline with the specified internal knots, order and coefficients. `deg` boundary knots are appended at both sides of the domain. The zeroth order basis functions are modified to ensure continuity at the right-hand bou...
way your functions do not have to start at zero. If you want to not include this, simply set the first coefficient in `C` to zero. Parameters ---------- t_int : array of float, (`M`,) The internal knot locations. Must be monotonic (this is NOT checked). C : array of float, (`M + deg - 1`,) The coefficients applied to t...
nonnegative int The polynomial degree to use. x : array of float, (`N`,) The locations to evaluate the spline at. cov_C : array of float, (`M + deg - 1`,) or (`M + deg - 1`, `M + deg - 1`), optional The covariance matrix of the coefficients. If a 1d array is passed, this is treated as the variance. If None, then the
uncertainty is not computed. M_spline : bool, optional If True, compute the M-spline instead of the B-spline. M-splines are normalized to integrate to unity, as opposed to B-splines which sum to unity at all points. Default is False (compute B-spline). I_spline : bool, optional If True, compute the I-spline instead of ...
the M-splines, and hence ensure curves are monotonic if all coefficients are of the same sign. Note that the I-splines returned will be of polynomial degree `deg` (i.e., the integral of what is returned from calling the function with `deg=deg-1` and `M_spline=True`. Default is False (compute B-spline or M-spline). n : ...
zeros are returned (i.e., the discontinuities are not included). Returns ------- `y` or (`y`, `cov_y`): The values (and possibly uncertainties) of the spline at the specified locations. """ C = scipy.asarray(C, dtype=float) t_int = scipy.asarray(t_int, dtype=float) if (t_int != scipy.sort(t_int)).any(): raise ValueErro...
dtype=float) if I_spline: # I_{i,k} = int_L^x M_{i,k}(u)du, so just take the derivative of the # underlying M-spline. Discarding the first coefficient dumps the "DC # offset" term. if cov_C is not None: cov_C = scipy.asarray(cov_C) if cov_C.ndim == 1: cov_C = cov_C[1:] elif cov_C.ndim == 2: cov_C = cov_C[1:, 1:] if n >...
M_spline=True, I_spline=False, n=n - 1 ) M_spline = True if n > 0: if M_spline: t = scipy.concatenate(([t_int[0]] * deg, t_int, [t_int[-1]] * deg)) C = (deg + 1.0) * ( C[1:] / (t[deg + 2:len(t_int) + 2 * deg] - t[1:len(t_int) + deg - 1]) - C[:-1] / (t[deg + 1:len(t_int) + 2 * deg - 1] - t[:len(t_int) + deg - 2])
) else: C = C[1:] - C[:-1] return spev( t_int, C, deg - 1, x, cov_C=cov_C, M_spline=True, I_spline=False, n=n - 1 ) if len(C) != len(t_int) + deg - 1: raise ValueError("Length of C must be equal to M + deg - 1!") # Append the external knots directly at the boundary: t = scipy.concatenate(([t_int[0]] * deg, t_int, [t_in...
different orders: B = scipy.zeros((deg + 1, len(t) - 1, len(x))) # NOTE: The first dimension is indexed by deg, and is zero-indexed. # Zeroth order: constant function d = 0 for i in xrange(deg, deg + len(t_int) - 2 + 1): # The second condition contains a hack to make the basis functions # continuous at the right-hand e...
x) & ( (x < t[i + 1]) | ((i == deg + len(t_int) - 2) & (x == t[-1])) ) B[d, i, mask] = 1.0 / (t[i + 1] - t[i]) if M_spline else 1.0 # Loop over other orders: for d in xrange(1, deg + 1): for i in xrange(deg - d, deg + len(t_int) - 2 + 1): if t[i +
d] != t[i]: v = (x - t[i]) * B[d - 1, i, :] if not M_spline: v /= t[i + d] - t[i] B[d, i, :] += v if t[i + d + 1] != t[i + 1]: v = (t[i + d + 1] - x) * B[d - 1, i + 1, :] if not M_spline: v /= t[i + d
+ 1] - t[i + 1] B[d, i, :] += v if M_spline and ((t[i + d] != t[i]) or (t[i + d + 1] != t[i + 1])): B[d, i, :] *= (d + 1) / (d * (t[i + d + 1] - t[i])) B = B[deg, 0:len(C), :].T # Now compute the I-splines, if needed: if I_spline: I = scipy.zeros_like(B) for
i in xrange(0, len(C)): for m in xrange(i, len(C)): I[:, i] += (t[m + deg + 1] - t[m]) * B[:, m] / (deg + 1.0) B = I y = B.dot(C) if cov_C is not None: cov_C = scipy.asarray(cov_C) # If there are no covariances, promote cov_C to a diagonal matrix if cov_C.ndim == 1: cov_C = scipy.diag(cov_C) cov_y = B.dot(cov_C).dot(B....
cov_y) else: return y
def parser(subparsers): "Build an argparse argument parser to parse the command line." # create the parser for the version subcommand. parser_version = subparsers.add_parser( 'version', help="Output the version of %(prog)s to the console.") parser_version.set_defaults(func=command_version) return parser_version
def wafer_form_helper(context, helper_name): ''' Find the specified Crispy FormHelper and instantiate it. Handy when you are crispyifying other apps' forms. ''' request = context.request module, class_name = helper_name.rsplit('.', 1) if module not in sys.modules: __import__(module) mod = sys.modules[module] class_ = g...
def page_menus(root_menu): """Add page menus.""" for page in Page.objects.filter(include_in_menu=True): path = page.get_path() menu = path[0] if len(path) > 1 else None try: root_menu.add_item(page.name, page.get_absolute_url(), menu=menu) except MenuError as e: logger.error("Bad menu item %r for page with slug %r." % ...
def redirect_profile(request): ''' The default destination from logging in, redirect to the actual profile URL ''' if request.user.is_authenticated: return HttpResponseRedirect(reverse('wafer_user_profile', args=(request.user.username,))) else: return redirect_to_login(next=reverse(redirect_profile))
def reviewed_badge(user, talk): """Returns a badge for the user's reviews of the talk""" context = { 'reviewed': False, } review = None if user and not user.is_anonymous(): review = talk.reviews.filter(reviewer=user).first() if review: context['reviewed'] = True context['review_is_current'] = review.is_current() return...
def beta_cdf_warp(X, d, n, *args): r"""Warp inputs that are confined to the unit hypercube using the regularized incomplete beta function. Applies separately to each dimension, designed for use with :py:class:`WarpingFunction`. Assumes that your inputs `X` lie entirely within the unit hypercube [0, 1]. Note that you ma...
when :math:`\beta < 1`. As a workaround, try mapping your data to not touch the boundaries of the unit hypercube. Parameters ---------- X : array, (`M`,) `M` inputs from dimension `d`. d : non-negative int The index (starting from zero) of the dimension to apply the warping to. n : non-negative int The derivative order...
to describe the warping, given as scalars. These are given as `alpha_i`, `beta_i` for each of the `D` dimensions. Note that these must ALL be provided for each call. References ---------- .. [1] J. Snoek, K. Swersky, R. Zemel, R. P. Adams, "Input Warping for Bayesian Optimization of Non-stationary Functions" ICML (2014...
* d + 1] if n == 0: return scipy.special.betainc(a, b, X) elif n == 1: # http://functions.wolfram.com/GammaBetaErf/BetaRegularized/20/01/01/ return (1 - X)**(b - 1) * X**(a - 1) / scipy.special.beta(a, b) else: # http://functions.wolfram.com/GammaBetaErf/BetaRegularized/20/02/01/ out = scipy.zeros_like(X) for k in rang...
k - 1.0) * (X / (1.0 - X))**k ) return -(1.0 - X)**(b - 1.0) * X**(a - n) * out / scipy.special.beta(a, b)
def linear_warp(X, d, n, *args): r"""Warp inputs with a linear transformation. Applies the warping .. math:: w(x) = \frac{x-a}{b-a} to each dimension. If you set `a=min(X)` and `b=max(X)` then this is a convenient way to map your inputs to the unit hypercube. Parameters ---------- X : array, (`M`,) `M` inputs from dime...
dimension to apply the warping to. n : non-negative int The derivative order to compute. *args : 2N scalars The remaining parameters to describe the warping, given as scalars. These are given as `a_i`, `b_i` for each of the `D` dimensions. Note that these must ALL be provided for each call. """ X = scipy.asarray(X, dty...
* d + 1] if n == 0: return (X - a) / (b - a) elif n == 1: return 1.0 / (b - a) * scipy.ones_like(X) else: return scipy.zeros_like(X)
def w_func(self, X, d, n): """Evaluate the (possibly recursive) warping function and its derivatives. Parameters ---------- X : array, (`M`,) The points (from dimension `d`) to evaluate the warping function at. d : int The dimension to warp. n : int The derivative order to compute. So far only 0 and 1 are supported. ""...
if isinstance(self.k, WarpedKernel): wX = self.k.w_func(wX, d, 0) return wX elif n == 1: wXn = self.w(X, d, n) if isinstance(self.k, WarpedKernel): wX = self.w_func(X, d, 0) wXn *= self.k.w_func(wX, d, n) return wXn else: raise ValueError("Derivative orders greater than one are not supported!")
def enforce_bounds(self, v): """Set `enforce_bounds` for both of the kernels to a new value. """ self._enforce_bounds = v self.k.enforce_bounds = v self.w.enforce_bounds = v
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.w.free_params = value[self.k.num_free_params:self.k.num_free_params + self.w.num_free_params]
def set_hyperparams(self, new_params): """Set the (free) hyperparameters. Parameters ---------- new_params : :py:class:`Array` or other Array-like New values of the free parameters. Raises ------ ValueError If the length of `new_params` is not consistent with :py:attr:`self.params`. """ new_params = scipy.asarray(new_p...
def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates blank versions of the form and its inline formsets. """ # Prepare base if 'pk' in kwargs: self.object = self.get_object() else: self.object = None form_class = self.get_form_class() # Get prefix if 'field_prefix' in form_class.Meta.__dic...
self.field_prefix = field_prefix # Build form form = self.get_form(form_class) # Find groups if 'groups' in dir(self): # Save groups groups = self.groups # Redefine groups inside the form form.__groups__ = lambda: groups # Initialize list of fields fields = [] else: groups = None # Add special prefix support to properl...
'autofill' not in dir(form.Meta): form.Meta.autofill = {} # For every extra form forms = [] position_form_default = 0 for (formelement, linkerfield, modelfilter) in self.forms: if formelement is None: formobj = form position_form_default = len(forms) else: # Locate linked element if self.object: related_name = formelem...
queryset.get() else: instance = queryset else: instance = None if 'autofill' in dir(formelement.Meta): formname = str(formelement).split('.')[-1].split("'")[0] for key in formelement.Meta.autofill: form.Meta.autofill['{}_{}'.format(formname, key)] = formelement.Meta.autofill[key] # Get prefix if 'field_prefix' in forme...
fields if 'exclude' not in formobj.Meta.__dict__: formobj.Meta.exclude = [linkerfield] elif linkerfield not in formobj.Meta.exclude: formobj.Meta.exclude.append(linkerfield) if linkerfield in formobj.fields: del(formobj.fields[linkerfield]) # Add special prefix support to properly support form independency formobj.add_...
forms forms.append(formobj) if position_form_default == 0: open_tabs = 1 else: open_tabs = 0 # Remember list of fields if groups: form.list_fields = fields # Add context and return new context return self.render_to_response(self.get_context_data(form=form, forms=forms, open_tabs=open_tabs, position_form_default=positio...
def post(self, request, *args, **kwargs): """ andles POST requests, instantiating a form instance and its inline formsets with the passed POST variables and then checking them for validity. """ # Prepare base if 'pk' in kwargs: self.object = self.get_object() else: self.object = None form_class = self.get_form_class() ...
list of fields else: # Get name from the class field_prefix = str(form_class).split("'")[1].split(".")[-1] self.field_prefix = field_prefix # Build the form form = self.get_form(form_class) # Find groups if 'groups' in dir(self): # Save groups groups = self.groups # Redefine groups inside the form form.__groups__ = lam...
properly support form independency form.add_prefix = lambda fields_name, field_prefix=field_prefix: "%s_%s" % (field_prefix, fields_name) # Check validation valid = form.is_valid() if (not valid) and ('non_field_errors' in dir(self)): errors = [element[5] for element in list(self.non_field_errors())[:-1]] elif form.err...
linkerfield, modelfilter) in self.forms: if formelement is None: formobj = form position_form_default = len(temp_forms) else: # Locate linked element if self.object: related_name = formelement._meta.model._meta.get_field(linkerfield).related_query_name() queryset = getattr(self.object, related_name) if modelfilter: que...
the form field_prefix = formelement.Meta.field_prefix else: # Get name from the class field_prefix = str(formelement).split("'")[1].split(".")[-1] self.field_prefix = field_prefix # Prepare form formobj = formelement(instance=instance, data=self.request.POST) formobj.form_name = form.form_name # Excluded fields if 'exc...
(field_prefix, fields_name) # Validate valid *= formobj.is_valid() # append error if not formobj.is_valid() and ('non_field_errors' in dir(formobj)): errors += [element[5] for element in list(formobj.non_field_errors())[:-1]] # Save fields to the list if groups: for field in formobj: # raise Exception (field.__dict__) ...
("validate" in dir(self)): validate_forms = [tform[0] for tform in temp_forms] errors = self.validate(*validate_forms) # valid = len(errors) == 0 valid = False if errors is None or len(errors) == 0: valid = True # Remember list of fields if groups: form.list_fields = fields forms = [] else: if validate_forms: forms = v...
open_tabs = 1 else: open_tabs = 0 # Check validation result if valid: # Everything is OK, call valid return self.form_valid(form, temp_forms) else: # Something went wrong, attach error and call invalid form.list_errors = errors return self.form_invalid(form, forms, open_tabs, position_form_default)
def form_valid(self, form, forms): """ Called if all forms are valid. Creates a Recipe instance along with associated Ingredients and Instructions and then redirects to a success page. """ if self.object: form.save() for (formobj, linkerfield) in forms: if form != formobj: formobj.save() else: self.object = form.save()...
def form_invalid(self, form, forms, open_tabs, position_form_default): """ Called if a form is invalid. Re-renders the context data with the data-filled forms and errors. """ # return self.render_to_response( self.get_context_data( form = form, forms = forms ) ) return self.render_to_response(self.get_context_data(form...