code
stringlengths
1
18.2k
bool, optional Set to True to return a tuple of (`tau`, `l_mat`), where `l_mat` is the matrix of length scales to match the shape of `tau`. Default is False (only return `tau`). Returns ------- r2l2 : :py:class:`Array`, (`M`,) Anisotropically scaled distances squared. l_mat : :py:class:`Array`, (`M`, `D`) The (`D`,) ar...
is True. """ l_mat = scipy.tile(self.params[-self.num_dim:], (tau.shape[0], 1)) tau_over_l = tau / l_mat tau_over_l[(tau == 0) & (l_mat == 0)] = 0.0 r2l2 = scipy.sum((tau_over_l)**2, axis=1) if return_l: return (r2l2, l_mat) else: return r2l2
def enforce_bounds(self, v): """Set `enforce_bounds` for both of the kernels to a new value. """ self._enforce_bounds = v self.k1.enforce_bounds = v self.k2.enforce_bounds = v
def free_param_bounds(self): """Returns the bounds of the free hyperparameters. Returns ------- free_param_bounds : :py:class:`Array` Array of the bounds of the free parameters, in order. """ return scipy.concatenate((self.k1.free_param_bounds, self.k2.free_param_bounds))
def free_param_names(self): """Returns the names of the free hyperparameters. Returns ------- free_param_names : :py:class:`Array` Array of the names of the free parameters, in order. """ return scipy.concatenate((self.k1.free_param_names, self.k2.free_param_names))
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 _compute_dk_dtau(self, tau, n): r"""Evaluate :math:`dk/d\tau` at the specified locations with the specified derivatives. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. n : :py:class:`Array`, (`D`,) Degree of derivative with respect to each dimension. Returns ------- dk_dta...
of the dimension # repeated a number of times equal to the order of derivative with # respect to that dimension. # Example: For d^3 k(x, y, z) / dx^2 dy, n would be [2, 1, 0] and # deriv_pattern should be [0, 0, 1]. For k(x, y, z) deriv_pattern is []. deriv_pattern = [] for idx in xrange(0, len(n)): deriv_pattern.exten...
= scipy.asarray(deriv_pattern, dtype=int) # Handle non-derivative case separately for efficiency: if len(deriv_pattern) == 0: return self._compute_k(tau) else: # Compute all partitions of the deriv_pattern: deriv_partitions = generate_set_partitions(deriv_pattern) # Compute the requested derivative using the multivaria...
def _compute_dk_dtau_on_partition(self, tau, p): """Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. p : list of :py:class:`Array` Each element is a block of the partition representing the deriva...
the specified locations. """ y, r2l2 = self._compute_y(tau, return_r2l2=True) # Compute the d^(|pi|)f/dy term: dk_dtau = self._compute_dk_dy(y, len(p)) # Multiply in each of the block terms: for b in p: dk_dtau *= self._compute_dy_dtau(tau, b, r2l2) return dk_dtau
def _mask_cov_func(self, *args): """Masks the covariance function into a form usable by :py:func:`mpmath.diff`. Parameters ---------- *args : `num_dim` * 2 floats The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`. """ # Have to do it in two cases to get the 1d unwrapped properly: if self.num_dim ...
def constant(X, n, mu, hyper_deriv=None): """Function implementing a constant mean suitable for use with :py:class:`MeanFunction`. """ if (n == 0).all(): if hyper_deriv is not None: return scipy.ones(X.shape[0]) else: return mu * scipy.ones(X.shape[0]) else: return scipy.zeros(X.shape[0])
def mtanh(alpha, z): """Modified hyperbolic tangent function mtanh(z; alpha). Parameters ---------- alpha : float The core slope of the mtanh. z : float or array The coordinate of the mtanh. """ z = scipy.asarray(z) ez = scipy.exp(z) enz = 1.0 / ez return ((1 + alpha * z) * ez - enz) / (ez + enz)
def mtanh_profile(X, n, x0, delta, alpha, h, b, hyper_deriv=None): """Profile used with the mtanh function to fit profiles, suitable for use with :py:class:`MeanFunction`. Only supports univariate data! Parameters ---------- X : array, (`M`, 1) The points to evaluate at. n : array, (1,) The order of derivative to compu...
Pedestal halfwidth alpha : float Core slope h : float Pedestal height b : float Pedestal foot hyper_deriv : int or None, optional The index of the parameter to take a derivative with respect to. """ X = X[:, 0] z = (x0 - X) / delta if n[0] == 0: if hyper_deriv is not None: if hyper_deriv == 0: return (h - b)
/ (2.0 * delta * (scipy.cosh(z))**2) * ( 1.0 + alpha / 4.0 * (1.0 + 2.0 * z + scipy.exp(2.0 * z)) ) elif hyper_deriv == 1: return -(h - b) * z / (2.0 * delta * (scipy.cosh(z))**2) * ( 1.0 + alpha / 4.0 * (1.0 + 2.0 * z + scipy.exp(2.0 * z)) ) elif hyper_deriv == 2: ez =
scipy.exp(z) enz = 1.0 / ez return (h - b) / 2.0 * z * ez / (ez + enz) elif hyper_deriv == 3: ez = scipy.exp(z) enz = 1.0 / ez return 0.5 * (1.0 + ((1.0 + alpha * z) * ez - enz) / (ez + enz)) elif hyper_deriv == 4: ez = scipy.exp(z) enz = 1.0 / ez return 0.5
* (1.0 - ((1.0 + alpha * z) * ez - enz) / (ez + enz)) else: raise ValueError("Invalid value for hyper_deriv, " + str(hyper_deriv)) else: return (h + b) / 2.0 + (h - b) * mtanh(alpha, z) / 2.0 elif n[0] == 1: if hyper_deriv is not None: if hyper_deriv == 0: return -(h - b) / (2.0 * delta**2.0 * (scipy.cosh(z))**2.0)
* ( alpha - (alpha * z + 2) * scipy.tanh(z) ) elif hyper_deriv == 1: return (h - b) / (2.0 * delta**2.0 * (scipy.cosh(z))**2.0) * ( 1.0 + alpha / 4.0 * (1.0 + 2.0 * z + scipy.exp(2.0 * z)) + z * (alpha - (alpha * z + 2) * scipy.tanh(z)) ) elif hyper_deriv == 2: return -(h - b)
/ (8.0 * delta * (scipy.cosh(z))**2.0) * ( 1.0 + 2.0 * z + scipy.exp(2.0 * z) ) elif hyper_deriv == 3: return -1.0 / (2.0 * delta * (scipy.cosh(z))**2.0) * ( 1.0 + alpha / 4.0 * (1.0 + 2.0 * z + scipy.exp(2.0 * z)) ) elif hyper_deriv == 4: return 1.0 / (2.0 * delta * (scipy.cosh(z))**2.0) * ( 1.0 +
alpha / 4.0 * (1.0 + 2.0 * z + scipy.exp(2.0 * z)) ) else: raise ValueError("Invalid value for hyper_deriv, " + str(hyper_deriv)) else: return -(h - b) / (2.0 * delta * (scipy.cosh(z))**2) * ( 1 + alpha / 4.0 * (1 + 2 * z + scipy.exp(2 * z)) ) else: raise NotImplementedError("Derivatives of order greater than 1 are not...
def linear(X, n, *args, **kwargs): """Linear mean function of arbitrary dimension, suitable for use with :py:class:`MeanFunction`. The form is :math:`m_0 * X[:, 0] + m_1 * X[:, 1] + \dots + b`. Parameters ---------- X : array, (`M`, `D`) The points to evaluate the model at. n : array of non-negative int, (`D`) The deri...
each dimension in `X`. *args : num_dim+1 floats The slopes for each dimension, plus the constant term. Must be of the form `m0, m1, ..., b`. """ hyper_deriv = kwargs.pop('hyper_deriv', None) m = scipy.asarray(args[:-1]) b = args[-1] if sum(n) > 1: return scipy.zeros(X.shape[0]) elif sum(n) == 0: if hyper_deriv is not N...
scipy.ones(X.shape[0]) else: raise ValueError("Invalid value for hyper_deriv, " + str(hyper_deriv)) else: return (m * X).sum(axis=1) + b else: # sum(n) == 1: if hyper_deriv is not None: if n[hyper_deriv] == 1: return scipy.ones(X.shape[0]) else: return scipy.zeros(X.shape[0]) return m[n == 1] * scipy.ones(X.shape[0])
def update_schedule_items(*args, **kw): """We save all the schedule items associated with this slot, so the last_update time is updated to reflect any changes to the timing of the slots""" slot = kw.pop('instance', None) if not slot: return for item in slot.scheduleitem_set.all(): item.save(update_fields=['last_updated...
next_slot.count(): # From the way we structure the slot tree, we know that # there's only 1 next slot that could have changed. for item in next_slot[0].scheduleitem_set.all(): item.save(update_fields=['last_updated'])
def make_diff(current, revision): """Create the difference between the current revision and a previous version""" the_diff = [] dmp = diff_match_patch() for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys())): # These exclusions really should be configurable if field == 'id' or field.endswith('_...
fatal error. # Log this? missing_field = False try: cur_val = current.field_dict[field] or "" except KeyError: cur_val = "No such field in latest version\n" missing_field = True try: old_val = revision.field_dict[field] or "" except KeyError: old_val = "No such field in old version\n" missing_field = True if missing_fi...
of the marker words # don't show up as differences diffs = [(dmp.DIFF_DELETE, old_val), (dmp.DIFF_INSERT, cur_val)] patch = dmp.diff_prettyHtml(diffs) elif isinstance(cur_val, Markup): # we roll our own diff here, so we can compare of the raw # markdown, rather than the rendered result. if cur_val.raw == old_val.raw: c...
actual field values diffs = dmp.diff_main(force_text(old_val), force_text(cur_val)) patch = dmp.diff_prettyHtml(diffs) the_diff.append((field, patch)) the_diff.sort() return the_diff
def compare_view(self, request, object_id, version_id, extra_context=None): """Actually compare two versions.""" opts = self.model._meta object_id = unquote(object_id) # get_for_object's ordering means this is always the latest revision. # The reversion we want to compare to current = Version.objects.get_for_object_ref...
}, "opts": opts, "compare_list_url": reverse("%s:%s_%s_comparelist" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(object_id),)), "diff_list": the_diff, } extra_context = extra_context or {} context.update(extra_context) return render(request, self.compare_template or self._get_template_list("co...
def comparelist_view(self, request, object_id, extra_context=None): """Allow selecting versions to compare.""" opts = self.model._meta object_id = unquote(object_id) current = get_object_or_404(self.model, pk=object_id) # As done by reversion's history_view action_list = [ { "revision": version.revision, "url": reverse...
return render(request, self.compare_list_template or self._get_template_list("compare_list.html"), context)
def grv(struct, position): ''' This function helps to convert date information for showing proper filtering ''' if position == 'year': size = 4 else: size = 2 if (struct[position][2]): rightnow = str(struct[position][0]).zfill(size) else: if position == 'year': rightnow = '____' else: rightnow = '__' return rightnow
def _setup(self, request): ''' Entry point for this class, here we decide basic stuff ''' # Get details from self info = model_inspect(self) self._appname = getattr(self, 'appname', info['appname']) self._modelname = getattr(self, 'modelname', info['modelname']) # Get user information if not hasattr(self, 'user'): self...
if 'no_render_as_foreign' not in self.extra_context: self.extra_context['no_render_as_foreign'] = []
def get_template_names(self): ''' Build the list of templates related to this user ''' # Get user template template_model = getattr(self, 'template_model', "{0}/{1}_{2}".format(self._appname.lower(), self._modelname.lower(), self.get_template_names_key)) template_model_ext = getattr(self, 'template_model_ext', 'html') ...
def get_context_data(self, **kwargs): ''' Set a base context ''' # Call the base implementation first to get a context context = super(GenBase, self).get_context_data(**kwargs) # Update general context with the stuff we already calculated if hasattr(self, 'html_head'): context['html_head'] = self.html_head(self.object)...
def dispatch(self, *args, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Get if this class is working as only a base render and List funcionality shouldn't be enabled onlybase = getattr(self, "onlybase", False) # REST not available when onlybase is enabled if not onlybase: # Check if this i...
in JSON if bool(self.request.META.get('HTTP_X_REST', False)): self.json = True if self.request.GET.get('json', self.request.POST.get('json', None)) is None: newget = {} newget['json'] = "{}" for key in self.request.GET: newget[key] = self.request.GET[key] self.request.GET = QueryDict('').copy() self.request.GET.update(...
to add an element if self.request.method == 'POST': target = get_class(resolve("{}/add".format(self.request.META.get("REQUEST_URI"))).func) target.json = True return target.as_view()(self.request) # Set class internal variables self._setup(self.request) # Deprecations deprecated = [('retrictions', '2016061000')] for (d...
hasattr(self, 'client_context'): self.client_context = {} # Attach user to the extra_context self.extra_context['user'] = self.user # Attach WS entry point and STATIC entry point self.extra_context['ws_entry_point'] = self.BASE_URL + getattr(self, "ws_entry_point", "{0}/{1}".format(self._appname, "{0}s".format(self._mo...
"{0}s".format(self._modelname.lower()))) self.extra_context['static_partial_summary'] = get_static(static_partial_summary_path, self.user, self.language, self.DEFAULT_STATIC_PARTIAL_SUMMARY, 'html', relative=True) static_app_row_path = getattr(self, 'static_app_row', "{0}/{1}_app.js".format(self._appname, "{0}s".format...
Default value for extends_base if hasattr(self, 'extends_base'): self.extra_context['extends_base'] = self.extends_base elif hasattr(self, 'extends_base'): self.extra_context['extends_base'] = self.extends_base # Get if this is a template only answer self.__authtoken = (bool(getattr(self.request, "authtoken", False))) ...
Calculate tabs if getattr(self, 'show_details', False): self.extra_context['tabs_js'] = json.dumps(self.get_tabs_js()) # Silence the normal execution from this class self.get_queryset = lambda: None self.get_context_data = lambda **kwargs: self.extra_context self.render_to_response = lambda context, **response_kwargs: ...
"errortxt": _("Not allowed, this kind of requests has been prohibited for this view!")} return HttpResponse(json.dumps(json_answer), content_type='application/json') # Initialize a default context self.__kwargs = kwargs self.__context = {} # Force export list self.export = getattr(self, 'export', self.request.GET.get('...
def get_queryset(self, raw_query=False): # Call the base implementation if not self.haystack: queryset = super(GenList, self).get_queryset() else: queryset = SearchQuerySet().models(self.model) # Optional tweak methods Mfields = None MlimitQ = None MsearchF = None MsearchQ = None if hasattr(self, '__fields__'): Mfields...
to our context and kwargs context = self.__context # Update kwargs if json key is present jsonquerytxt = self.request.GET.get('json', self.request.POST.get('json', None)) if jsonquerytxt is not None: # Decode json try: jsonquery = json.loads(jsonquerytxt) except json.JSONDecodeError as e: raise IOError("json argument i...
Get elementid elementid = jsondata.pop('elementid') else: listid = None elementid = None jsondata = {} jsonquery = {} # Build info for GenModel methods MODELINF = MODELINFO(self.model, self._appname, self._modelname, self._viewname, self.request, self.user, self.profile, jsonquery, Mfields, MlimitQ, MsearchF, MsearchQ,...
context['get'] = [] context['getval'] = {} for name in jsondata: struct = {} struct['name'] = name if name == 'rowsperpage': struct['value'] = self.default_rows_per_page elif name == 'page': struct['value'] = 1 elif name == 'pages_to_bring': struct['value'] = 1 else: struct['value'] = jsondata[name] context['get'].appe...
== 'i_distinct' or name == 'e_distinct': distinct = True else: if qobjects: qobjects &= limits[name] else: qobjects = limits[name] if qobjects: queryset = queryset.filter(qobjects) if hasattr(self, 'annotations'): if not self.haystack: # Prepare annotations if callable(self.annotations): anot = self.annotations(MODELIN...
by the user request try: filters_get = jsondata.get('filters', '{}') if type(filters_get) == dict: filters_by_struct = filters_get else: filters_by_struct = json.loads(str(filters_get)) except Exception: filters_by_struct = [] listfilters = {} # Autofilter system if self.autofiltering: listfilters.update(self.autoSearc...
# If there is something to filter, filter is not being changed and filter is known by the class try: value = int(value) except ValueError: pass except TypeError: pass # ORIG if (key in listfilters) and ((value>0) or (type(value) == list)): # V1 if (value and type(value) == int and key in listfilters) and ((value > 0) o...
(value and type(value) == int and key in listfilters) or ((value > 0) or (type(value) == list)): if value and key in listfilters: # Add the filter to the queryset rule = listfilters[key] # Get type typekind = rule[2] if type(typekind) == list: # Compatibility: set typekind and fv in the old fassion if type(value) == in...
queryset.filter(rule[1](fv)) typekind = 'select' elif typekind == 'select': # Get selected value from rule if type(value) == int: fv = rule[3][value - 1][0] queryset = queryset.filter(rule[1](fv)) elif typekind in ['multiselect', 'multidynamicselect']: # Get selected values from rule if type(value) in (list, tuple) and...
arguments fv = value queryset = queryset.filter(rule[1](fv)) elif typekind in ['checkbox', ]: fv = value queryset = queryset.filter(rule[1](fv)) else: raise IOError("Wrong typekind '{0}' for filter '{1}'".format(typekind, key)) # Save it in the struct as a valid filter filters_struct[key] = value # Rewrite filters_json...
if element['name'] not in ['filters']: struct = {} struct['name'] = element['name'] struct['value'] = element['value'] filters_get.append(struct) # Add filter_json struct = {} struct['name'] = 'filters' struct['value'] = filters_json filters_get.append(struct) context['filters_get'] = filters_get # Get the list of filt...
fassion choice = [_('All')] for value in typekind: choice.append(value[1]) # Decide the choosen field if key in filters_struct.keys(): value = int(filters_struct[key]) else: value = 0 typekind = 'select' argument = choice elif typekind == 'select': typevalue = listfilters[key][3] choice = [_('All')] for value in typeva...
choice as the command's argument argument = choice elif typekind in ['multiselect', 'multidynamicselect']: if typekind == 'multiselect': typevalue = listfilters[key][3] choice = [] for value in typevalue: choice.append({'id': value[0], 'label': value[1]}) else: choice = list(listfilters[key][3:]) choice[1] = reverse_la...
= choice elif typekind in ['daterange', 'input']: # Commands withouth arguments argument = None # Get the selected value if key in filters_struct.keys(): value = filters_struct[key] else: value = None elif typekind in ['checkbox']: # Commands withouth arguments argument = None # Get the selected value if key in filters...
'{1}'".format(typekind, key)) # Build filtertuple filtertuple = (key, listfilters[key][0], typekind, argument, value) # Save this filter in the corresponding list filters.append(filtertuple) # Save all filters context['filters'] = filters # Search filter button search_filter_button = jsondata.get('search_filter_button'...
while newlen != oldlen: oldlen = newlen search = search.replace(" ", " ") newlen = len(search) if len(search) > 0 and search[0] == ' ': search = search[1:] if len(search) > 0 and search[-1] == ' ': search = search[:-1] # Save in context context['search'] = search datetimeQ = None if len(search) > 0: # Get ID tid = None...
tid = search.split(":")[1].split(" ")[0] # Decide if it is what we expect try: tid = int(tid) except Exception: tid = None # Remove the token if tid: search = search.replace("id:%s" % (tid), '') search = search.replace(" ", " ") # Get PK tpk = None if 'pk:' in search: tpk = search.split(":")[1].split(" ")[0] # Decide i...
int(tpk) except Exception: tpk = None # Remove the token if tpk: search = search.replace("pk:%s" % (tpk), '') search = search.replace(" ", " ") # Spaces on front and behind if len(search) > 0 and search[0] == ' ': search = search[1:] if len(search) > 0 and search[-1] == ' ': search = search[:-1] searchs = {} # Autofilt...
# Fields to search in from the MODELINF tmp_search = MODELINF.searchQ(search) if type(tmp_search) == dict: searchs.update(tmp_search) else: searchs['autoSearchQ'] &= tmp_search qobjects = {} qobjectsCustom = {} for name in searchs: # Extract the token qtoken = searchs[name] if qtoken == 'datetime': # If it is a datetim...
== tuple: (query, func) = qtoken else: def lambdax(x): return x func = lambdax query = qtoken # If it is a string if search: for word in search.split(" "): # If there is a word to process if len(word) > 0: # Build the key for the arguments and set the word as a value for the Q search if word[0] == '-':
# If negated request # key="-{}".format(hashlib.md5(word[1:].encode()).hexdigest()) qdict = {'{}'.format(query): func(word[1:])} qtokens_element = ~Q(**qdict) else: # If positive request # key="-{}".format(hashlib.md5(word[1:].encode()).hexdigest()) qdict = {'{}'.format(query): func(word)} qtokens_element = Q(**qdict) ...
"): if word.split(":")[0] not in ['id', 'pk']: if word[0] == '-': negative = True else: negative = False qword = None for token in qobjects[word]: if qword: if negative: qword &= token else: qword |= token else: qword = token if qword: if qdata: qdata &= qword else: qdata = qword # Process ID/PK specific searches if ti...
= queryset.filter(pk=tpk) # Add custom Q-objects if qobjectsCustom: queryset = queryset.filter(qobjectsCustom) # Add word by word search Q-objects if qdata: queryset = queryset.filter(qdata) else: # Look for datetimeQ field searchs = MODELINF.searchQ(search) for name in searchs: if (searchs[name] == 'datetime'): dateti...
(1, 12, False) f['day'] = (1, 31, False) f['hour'] = (0, 23, False) f['minute'] = (0, 59, False) f['second'] = (0, 59, False) date_elements = [None, 'year', 'month', 'day', 'hour', 'minute', 'second'] # Get configuration of dates and set limits to the queryset for element in date_elements[1:]: value = jsondata.get(elem...
f['day'][2]: (g, lastday) = calendar.monthrange(f['year'][1], f['month'][1]) f['day'] = (f['day'][0], lastday, f['day'][2]) # Limits date_min = datetime.datetime(f['year'][0], f['month'][0], f['day'][0], f['hour'][0], f['minute'][0], f['second'][0]) date_max = datetime.datetime(f['year'][1], f['month'][1], f['day'][1],...
else: break # Get results from dates to set the new order exclusion = {} exclusion[datetimeQ] = None date_results = queryset.exclude(**exclusion).values_list(datetimeQ, flat=True) # Remove empty results (usefull when the date is allowed to be empty) if f['day'][0] != f['day'][1]: if f['month'][0] == f['month'][1]: date...
= {} # Save the deepness if deepness_index + 1 == len(date_elements): context['datefilter']['deepness'] = None else: context['datefilter']['deepness'] = date_elements[deepness_index + 1] context['datefilter']['deepnessback'] = [] context['datefilter']['deepnessinit'] = [] for element in get: if (not element['name'] in ...
Build the list of elements context['datefilter']['data'] = [] for element in date_results: # Save the data context['datefilter']['data'].append(element.timetuple()[deepness_index]) context['datefilter']['data'] = list(set(context['datefilter']['data'])) context['datefilter']['data'].sort() # Prepare the rightnow result...
month, "/", grv(f, 'year'), " ", grv(f, 'hour'), ":", grv(f, 'minute'), ":", grv(f, 'second')) else: rightnow = string_concat(grv(f, 'day'), "/", month, "/", grv(f, 'year')) context['datefilter']['rightnow'] = rightnow else: context['datefilter'] = None # Distinct # queryset=queryset.distinct() # Ordering field autofil...
= {} counter = 1 # Build the columns structure and the fields list context['columns'] = [] self.__fields = [] for value in fields: self.__fields.append(value[0]) # Auto build rules self.__autorules = self.autorules() for order in order_by_struct: name = list(order.keys())[0] lbl = None # use __autofields for ordering b...
direction = order[name] if lbl and not lbl.startswith('get_') and not lbl.endswith('_display'): name = lbl if direction == 'asc': order_by.append("%s" % (remove_getdisplay(name))) elif direction == 'desc': order_by.append("-%s" % (remove_getdisplay(name))) position[name] = counter counter += 1 if order_by: queryset = q...
{} for value in fields: # Get values if value[0]: name = value[0].split(":")[0] order_key = name type_field = self.get_type_field(value[0].split(":")[-1]) else: name = value[0] # not usable fields, example: fields.append((None, _('Selector'))) in airportslist hash_key = hashlib.md5(value[1].encode()).hexdigest() order_...
= None # filter column if len(value) > 4: filter_column = value[4] else: filter_column = None # Process ordering ordering = [] found = False for order in order_by_struct: subname = list(order.keys())[0] direction = order[subname] if order_key == subname: if direction == 'desc': direction = '' sort_class = 'headerSortUp...
= 'asc' found = True if direction == 'asc' or direction == 'desc': ordering.append({subname: direction}) if not found: ordering.append({order_key: 'asc'}) sort_class = '' # Save the ordering method sort[order_key] = {} sort[order_key]['id'] = name sort[order_key]['name'] = publicname sort[order_key]['align'] = align so...
sort[order_key]['ordering'] = json.dumps(ordering).replace('"', '\\"') if order_key in position: sort[order_key]['position'] = position[order_key] # Save ordering in the context if jsonquery is not None: context['ordering'] = order_by_struct # Build the columns structure and the fields list context['columns'] = [] for ...
self.autorules() # Columns self.__columns = ['pk'] # self.__columns = ['id'] self.__foreignkeys = [] for column in self.model._meta.fields: self.__columns.append(column.name) if column.is_relation: self.__foreignkeys.append(column.name) # Localfields self.__related_objects = [] for f in self.model._meta.related_objects...
fields_related_model = [] for rule in autorules_keys: found = False # name rule origin rule_org = rule # If rule is an alias rulesp = rule.split(":") if len(rulesp) == 2: (alias, rule) = rulesp else: alias = rule # If rule has a foreign key path (check first level attributes only, nfrule = no foreign rule) nfrule = rul...
self.model if len(nfrule) > 1: ruletmp = [] field_related_model = [] for n in nfrule: if model: for fi in model._meta.fields: if fi.name == n: found = True ruletmp.append(n) if fi.is_relation: model = fi.related_model field_related_model.append(fi.name) else: do_select_related = True model = None break if not found or ...
[x.name for x in self.model._meta.fields] or nfrule[0] == 'pk': found = True for fi in model._meta.fields: if fi.name == nfrule[0] and fi.is_relation: fields_related_model.append(nfrule[0]) if not self.haystack and (do_select_related or rule in self.__foreignkeys): # Compatibility with Django 1.10 if "__" in rule: quer...
"nunca" usaria .extra ni .value # no la elimino del todo por si hubiera algun fallo mas adelante, # y se tuviera que parametrizarse de algun otro modo ############################ # if nfrule not in self.__foreignkeys: if rule not in fields_related_model: # Save verifier name query_verifier.append(rule_org) # Save rena...
hasattr(self, 'annotations'): # Prepare annotations if callable(self.annotations): anot = self.annotations(MODELINF) else: anot = self.annotations # Process annotations for xnfrule in anot.keys(): found = True if xnfrule not in query_verifier: query_verifier.append(xnfrule) query_optimizer.append(xnfrule) if not found:...
alias '{}' is a foreign key from model '{}' inside app '{}'" elif rename in self.__columns: msg = "Invalid alias. The alias '{}' is a columns from model '{}' inside app '{}'" elif rename in self.__related_objects: msg = "Invalid alias. The alias '{}' is a related object from model '{}' inside app '{}'" raise Exception(...
# If we got the query_optimizer to optimize everything, use it # use_extra = False query_verifier.sort() autorules_keys.sort() if found and query_verifier == autorules_keys: # use_extra = True if query_renamed: # queryset=queryset.extra(select=query_renamed).values(*query_optimizer) queryset = queryset.annotate(**query...
-- autorules_keys: {} -- \ query_select_related: {} -- query_renamed: {} -- query_optimizer: {} | use_extra: {}| -- \ query: {} -- meta.fields: {} -- fields_related_model: {} -- query_verifier: {}\ -- ??? {} == {}".format( found, self.__foreignkeys, self.__columns, autorules_keys, query_select_related, query_renamed, q...
raw_query: return queryset else: # Check the total count of registers + rows per page total_rows_per_page = jsondata.get('rowsperpage', self.default_rows_per_page) pages_to_bring = jsondata.get('pages_to_bring', 1) if total_rows_per_page == 'All' or self.export: total_rows_per_page = queryset.count() paginator = Pagina...
1 total_rows_per_page = total_registers total_rows_per_page_out = _('All') total_pages = 1 else: total_rows_per_page = int(total_rows_per_page) # By default 10 rows per page total_rows_per_page_out = total_rows_per_page total_pages = int(total_registers / total_rows_per_page) if total_registers % total_rows_per_page: t...
1 if page_number < 1: page_number = 1 if page_number > total_pages: page_number = total_pages # Build the list of page counters allowed choice = {} c = self.default_rows_per_page chk = 1 while total_registers >= c: choice[c] = c if chk == 1: # From 5 to 10 c = c * 2 # Next level chk = 2 elif chk == 2: #
From 10 to 25 (10*2+10/2) c = c * 2 + int(c / 2) # Next level chk = 3 elif chk == 3: # From 25 to 50 c *= 2 chk = 1 # Don't give a too long choice if c > 2000: break # Add all choice in any case if settings.ALL_PAGESALLOWED: choice['All'] = _('All') # Save the pagination in
the structure context['rowsperpageallowed'] = choice context['rowsperpage'] = total_rows_per_page_out context['pages_to_bring'] = pages_to_bring context['pagenumber'] = page_number # Get the full number of registers and save it to context context['total_registers'] = total_registers if total_rows_per_page == 'All': # R...
None else: context['page_before'] = page_number-1 # Page after if page_number >= total_pages: context['page_after'] = None else: context['page_after'] = page_number+1 # Starting on register number context['start_register'] = (page_number-1)*total_rows_per_page+1 context['showing_registers'] = total_rows_per_page # Calc...
paginator.page(desired_page_number) desired_page_number += 1 except PageNotAnInteger: # If page is not an integer, deliver first page. regs += paginator.page(1) desired_page_number = 2 except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. if pages_to_bring == 1: regs += paginator.page(p...
range_fill = range(pages_to_bring-1) for p in range_fill: page_number += 1 context['pages'] += pages(paginator, page_number) else: context['pages'] = [] # Return queryset return regs