AJAX GET handler for xeditable queries asking for field choice lists.
512273
def get_ajax_xeditable_choices(self, request, *args, **kwargs):
        
        field_name = request.GET.get(self.xeditable_fieldname_param)
        if not field_name:
            return HttpResponseBadRequest("Field name must be given")

        queryset = self.get_queryset()
        if not self.model:
            self.model = queryset.model

        # Sanitize the requested field name by limiting valid names to the datatable_options columns
        from datatableview.views import legacy
        if isinstance(self, legacy.LegacyDatatableMixin):
            columns = self._get_datatable_options()['columns']
            for name in columns:
                if isinstance(name, (list, tuple)):
                    name = name[1]
                if name == field_name:
                    break
            else:
                return HttpResponseBadRequest("Invalid field name")
        else:
            datatable = self.get_datatable()
            if not hasattr(datatable, 'config'):
                datatable.configure()
            if field_name not in datatable.config['columns']:
                return HttpResponseBadRequest("Invalid field name")

        field = self.model._meta.get_field(field_name)
        choices = self.get_field_choices(field, field_name)
        return HttpResponse(json.dumps(choices))
1352825
function(dataObj) {
        var queryList = [];

        _.each(dataObj, function(value, name) {
            if (!_.isString(value) && !_.isNumber(value)) {
                value = JSON.stringify(value);
            }
            value = encodeURIComponent(unescape(value));
            if (value) {
                queryList.push(name + '=' + value);
            }
        });

        return queryList.join('&');
    }
77327
def parse_querystring(self, req, name, field):
        """"""
        return core.get_value(req.params, name, field)
479805
def ajax_submit(self):
        

        # Get AR required fields (including extended fields)
        fields = self.get_ar_fields()

        # extract records from request
        records = self.get_records()

        fielderrors = {}
        errors = {"message": "", "fielderrors": {}}

        attachments = {}
        valid_records = []

        # Validate required fields
        for n, record in enumerate(records):

            # Process UID fields first and set their values to the linked field
            uid_fields = filter(lambda f: f.endswith("_uid"), record)
            for field in uid_fields:
                name = field.replace("_uid", "")
                value = record.get(field)
                if "," in value:
                    value = value.split(",")
                record[name] = value

            # Extract file uploads (fields ending with _file)
            # These files will be added later as attachments
            file_fields = filter(lambda f: f.endswith("_file"), record)
            attachments[n] = map(lambda f: record.pop(f), file_fields)

            # Process Specifications field (dictionary like records instance).
            # -> Convert to a standard Python dictionary.
            specifications = map(
                lambda x: dict(x), record.pop("Specifications", []))
            record["Specifications"] = specifications

            # Required fields and their values
            required_keys = [field.getName() for field in fields
                             if field.required]
            required_values = [record.get(key) for key in required_keys]
            required_fields = dict(zip(required_keys, required_values))

            # Client field is required but hidden in the AR Add form. We remove
            # it therefore from the list of required fields to let empty
            # columns pass the required check below.
            if record.get("Client", False):
                required_fields.pop('Client', None)

            # Contacts get pre-filled out if only one contact exists.
            # We won't force those columns with only the Contact filled out to
            # be required.
            contact = required_fields.pop("Contact", None)

            # None of the required fields are filled, skip this record
            if not any(required_fields.values()):
                continue

            # Re-add the Contact
            required_fields["Contact"] = contact

            # Missing required fields
            missing = [f for f in required_fields if not record.get(f, None)]

            # If there are required fields missing, flag an error
            for field in missing:
                fieldname = "{}-{}".format(field, n)
                msg = _("Field '{}' is required".format(field))
                fielderrors[fieldname] = msg

            # Process valid record
            valid_record = dict()
            for fieldname, fieldvalue in record.iteritems():
                # clean empty
                if fieldvalue in ['', None]:
                    continue
                valid_record[fieldname] = fieldvalue

            # append the valid record to the list of valid records
            valid_records.append(valid_record)

        # return immediately with an error response if some field checks failed
        if fielderrors:
            errors["fielderrors"] = fielderrors
            return {'errors': errors}

        # Process Form
        actions = ActionHandlerPool.get_instance()
        actions.queue_pool()
        ARs = OrderedDict()
        for n, record in enumerate(valid_records):
            client_uid = record.get("Client")
            client = self.get_object_by_uid(client_uid)

            if not client:
                actions.resume()
                raise RuntimeError("No client found")

            # get the specifications and pass them to the AR create function.
            specifications = record.pop("Specifications", {})

            # Create the Analysis Request
            try:
                ar = crar(
                    client,
                    self.request,
                    record,
                    specifications=specifications
                )
            except (KeyError, RuntimeError) as e:
                actions.resume()
                errors["message"] = e.message
                return {"errors": errors}
            # We keep the title to check if AR is newly created
            # and UID to print stickers
            ARs[ar.Title()] = ar.UID()
            for attachment in attachments.get(n, []):
                if not attachment.filename:
                    continue
                att = _createObjectByType("Attachment", client, tmpID())
                att.setAttachmentFile(attachment)
                att.processForm()
                ar.addAttachment(att)
        actions.resume()

        level = "info"
        if len(ARs) == 0:
            message = _('No Samples could be created.')
            level = "error"
        elif len(ARs) > 1:
            message = _('Samples ${ARs} were successfully created.',
                        mapping={'ARs': safe_unicode(', '.join(ARs.keys()))})
        else:
            message = _('Sample ${AR} was successfully created.',
                        mapping={'AR': safe_unicode(ARs.keys()[0])})

        # Display a portal message
        self.context.plone_utils.addPortalMessage(message, level)

        # Automatic label printing
        bika_setup = api.get_bika_setup()
        auto_print = bika_setup.getAutoPrintStickers()
        if 'register' in auto_print and ARs:
            return {
                'success': message,
                'stickers': ARs.values(),
                'stickertemplate': bika_setup.getAutoStickerTemplate()
            }
        else:
            return {'success': message}
1168836
function(req, res) {
            var updateJson = {};
            var updateSelector = {};

            //Request database structure
            lastQry = connection.query('SHOW COLUMNS FROM ??', req.params.table , function (err, columns) {
                if (err) return sendError(res,err.code);

                //Check if the request is provided an select value
                if (typeof req.params.id === "undefined") {
                    return sendError(res,'Please specify an selector value for the fields ');
                } else {
                    updateSelector.value = req.params.id;
                    updateSelector.field = findPrim(columns,req.query[settings.paramPrefix + 'field']);
                }

                //If the user only wants to update files
                if( Object.keys(req.body).length == 0) {
                    req.body = req.files;
                }
                var value;
                var iterator = function (i) {
                    if (i >= columns.length || (typeof req.body.length === "undefined" && typeof req.files.length !== "undefined")) {
                        if(JSON.stringify(updateJson) !== '{}') {
                            updateIntoDB();
                        } else {
                            return sendError(res,'No Data received!');
                        }
                        return;
                    }
                    var dbField = columns[i];
                    var field = dbField.Field;
                    //Check if the current checked field is set
                    if(typeof req.body[field] !== "undefined" || (dbField.Default == 'FILE' && typeof req.files[field] !== "undefined") ) {
                        //First check if the field is required
                        if(dbField.Null == 'NO' && dbField.Extra != 'auto_increment') {
                            value = checkIfSentvaluesAreSufficient(req,dbField);
                            if(value !== false) {
                                updateJson[field] = value;
                                iterator(i + 1);
                            } else {
                                return sendError(res,"Not all 'NOT NULL' fields are filled ("+ field +" is missing)");
                            }
                        }  else {
                            //Check for not required fields
                            //Skip auto_incremented fields
                            if(dbField.Extra === 'auto_increment') {
                                iterator(i + 1);
                            } else {
                                //Check if the field was provided by the client
                                var defined = false;
                                if(dbField.Default == "FILE") {
                                    if(req.files.hasOwnProperty(dbField.Field)) {
                                        defined = true;
                                    }
                                } else {
                                    if(typeof req.body[field] !== "undefined") {
                                        defined = true;
                                    }
                                }

                                //If it was provided, check if the values are okay
                                if(defined) {
                                    value = checkIfSentvaluesAreSufficient(req,dbField);
                                    if(value !== false) {
                                        updateJson[field] = value;
                                        iterator(i + 1);
                                    } else {
                                        if(dbField.Default == "FILE") {
                                            return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
                                        } else {
                                            return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
                                        }
                                    }
                                } else {
                                    //If not, don't mind
                                    iterator(i + 1);
                                }
                            }
                        }
                    } else {
                        iterator(i + 1);
                    }
                };

                iterator(0); //start the async "for" loop

                function updateIntoDB() {
                    //Yaaay, alle Tests bestanden gogo, insert!
                    lastQry = connection.query('UPDATE ?? SET ? WHERE ?? = ?', [req.params.table , updateJson, updateSelector.field, updateSelector.value] , function (err) {
                        if (err) return sendError(res,err.code);
                        sendSuccessAnswer(req.params.table , res, req.params.id, updateSelector.field);

                    });
                }
            });
        }
558834
def query_string(context, **kwargs):
    """"""
    params = context["request"].GET.copy()

    for key, value in list(kwargs.items()):
        params[key] = value

    return "?" + params.urlencode()
629669
def get(self, request, *args, **kwargs):
        

        # 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.__dict__:
            # Get name from the form
            field_prefix = form_class.Meta.field_prefix
        else:
            # Get name from the class
            field_prefix = str(form_class).split("'")[1].split(".")[-1]
        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 properly support form independency
        form.add_prefix = lambda fields_name, field_prefix=field_prefix: "%s_%s" % (field_prefix, fields_name)
        if '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 = formelement._meta.model._meta.get_field(linkerfield).related_query_name()
                    queryset = getattr(self.object, related_name)
                    if modelfilter:
                        queryset = queryset.filter(eval("Q(%s)" % (modelfilter)))
                    get_method = getattr(queryset, 'get', None)
                    if get_method:
                        instance = 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 formelement.Meta.__dict__:
                    # Get name from 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)
                formobj.form_name = form.form_name

                # Excluded 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_prefix = lambda fields_name, field_prefix=field_prefix: "%s_%s" % (field_prefix, fields_name)
                formobj.scope_prefix = field_prefix

            # Save fields to the list
            if groups:
                for field in formobj:
                    fields.append(field)
            else:
                # Add the form to the list of 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=position_form_default))
1075122
def get_xeditable_form_kwargs(self):
        
        kwargs = {
            'model': self.get_queryset().model,
        }
        if self.request.method in ('POST', 'PUT'):
            kwargs.update({
                'data': self.request.POST,
            })
        return kwargs
121465
def options_td(record_or_name_or_array, hide_destroy = false)
      items = []
      items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array))
      items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_destroy
      list = content_tag(:ul, convert_to_list_items(items))
      content_tag(:td, list, :class => "options")
    end
1365461
function() {
            this.xhr = $.ajax(_.extend({}, {
                "type":     this.options.method,
                "url":      this.options.url,
                "data":     this.options.params,
                "dataType": this.options.dataType,
                "context":  this,
                "success":  function(data) {
                    logging.debug("Result for request ", this.options);
                    this.trigger("done", data);
                },
                "error": function(xhr, textStatus, errorThrown) {
                    logging.error("Error for request ", this.options);
                    this.trigger("error", {
                        'status': textStatus,
                        'error': errorThrown,
                        'content': xhr.responseText,
                        'xhr': xhr
                    });
                }
            }, this.options.options));
            return this;
        }
974764
function(query) {
        var q = rql2es(_.rql(query)),
            mapFn = q.fields ?
                          function(x) { return x.fields; } 
                        : function(x) { return x._source; };
        return ajax('POST', this._url + '/_search', q)
            .then(function(result) {
                return result.hits.hits.map(mapFn);
            });
    }
1339054
def hook_get_queryset(self, changelist, request):
        """"""
        changelist.check_field_exists(self.pid_field)
        self.pid = self.get_pid_from_request(changelist, request)
        changelist.params[self.pid_field] = self.pid
415628
function(form, options) {
      var values = {}
        , i
        , j
        , input
        , inputs
        , option
        , value;

      if (v.isJqueryElement(form)) {
        form = form[0];
      }

      if (!form) {
        return values;
      }

      options = options || {};

      inputs = form.querySelectorAll("input[name], textarea[name]");
      for (i = 0; i < inputs.length; ++i) {
        input = inputs.item(i);

        if (v.isDefined(input.getAttribute("data-ignored"))) {
          continue;
        }

        var name = input.name.replace(/\./g, "\\\\.");
        value = v.sanitizeFormValue(input.value, options);
        if (input.type === "number") {
          value = value ? +value : null;
        } else if (input.type === "checkbox") {
          if (input.attributes.value) {
            if (!input.checked) {
              value = values[name] || null;
            }
          } else {
            value = input.checked;
          }
        } else if (input.type === "radio") {
          if (!input.checked) {
            value = values[name] || null;
          }
        }
        values[name] = value;
      }

      inputs = form.querySelectorAll("select[name]");
      for (i = 0; i < inputs.length; ++i) {
        input = inputs.item(i);
        if (v.isDefined(input.getAttribute("data-ignored"))) {
          continue;
        }

        if (input.multiple) {
          value = [];
          for (j in input.options) {
            option = input.options[j];
             if (option && option.selected) {
              value.push(v.sanitizeFormValue(option.value, options));
            }
          }
        } else {
          var _val = typeof input.options[input.selectedIndex] !== 'undefined' ? input.options[input.selectedIndex].value : /* istanbul ignore next */ '';
          value = v.sanitizeFormValue(_val, options);
        }
        values[input.name] = value;
      }

      return values;
    }
624534
def _querystring(self):
        """"""

        kw = {}
        for key in self.KNOWN_QUERY_OPTIONS:
            val = getattr(self, key)
            if val is not None:
                kw[key] = val
        return kw
694296
function processData(res, data, options) {
  const handlers = Object.assign({}, deserializers, options.deserializers);
  const contentType = res.headers['content-type'];
  const types = typeof contentType === 'string' ? contentType.split(';') : [];

  // if there are no content types, return the data unmodified
  if (!types.length) {
    return data;
  }

  return types.reduce((d, type) => {
    try {
      const t = type.toLocaleLowerCase().trim();
      const handler = handlers[t];

      if (d instanceof Error || typeof handler !== 'function') {
        return d;
      }
      return handler(d);
    } catch (error) {
      return error;
    }
  }, data);
}
469199
function () {
        var that = this,
            fullQuery = that.extendedCurrentValue(),
            currentValue = that.el.val(),
            resolver = $.Deferred();

        resolver
            .done(function (suggestion) {
                that.selectSuggestion(suggestion, 0, currentValue, { hasBeenEnriched: true });
                that.el.trigger('suggestions-fixdata', suggestion);
            })
            .fail(function () {
                that.selection = null;
                that.el.trigger('suggestions-fixdata');
            });

        if (that.isQueryRequestable(fullQuery)) {
            that.currentValue = fullQuery;
            that.getSuggestions(fullQuery, { count: 1, from_bound: null, to_bound: null })
                .done(function (suggestions) {
                    // data fetched
                    var suggestion = suggestions[0];
                    if (suggestion) {
                        resolver.resolve(suggestion);
                    } else {
                        resolver.reject();
                    }
                })
                .fail(function () {
                    // no data fetched
                    resolver.reject();
                });
        } else {
            resolver.reject();
        }
    }
448264
function getFormFields(form) {
  // Grab all fields that are enabled, and return them as an array.
  // If enabled, remove that property and apply the field name.
  var fields = Object.keys(form.fields).reduce(function (result, fieldKey) {
    var field = _.clone(form.fields[fieldKey]);

    if (!field.enabled) {
      return result;
    }

    // Append the field to field order in case it's not present.
    if (form.fieldOrder.indexOf(fieldKey) === -1) {
      form.fieldOrder.push(fieldKey);
    }

    field.name = fieldKey;
    delete field.enabled;

    result.push(field);

    return result;
  }, []);

  // Sort fields by the defined fieldOrder.
  // Fields that are not in fieldOrder will be placed at the end of the array.
  fields.sort(function (a, b) {
    var indexA = form.fieldOrder.indexOf(a.name);
    var indexB = form.fieldOrder.indexOf(b.name);

    if (indexA === -1) {
      return 0;
    }

    if (indexB === -1) {
      return -1;
    }

    if (indexA > indexB) {
      return 1;
    }

    if (indexA < indexB) {
      return -1;
    }

    return 0;
  });

  return fields;
}