If the apphook config must be selected first, returns a fieldset with just the
         app config field and help text
        :param request:
        :param obj:
        :return:
964533
def get_fieldsets(self, request, obj=None):
        
        app_config_default = self._app_config_select(request, obj)
        if app_config_default is None and request.method == 'GET':
            return (_(self.app_config_selection_title),
                    {'fields': (self.app_config_attribute, ),
                     'description': _(self.app_config_selection_desc)}),
        else:
            return super(ModelAppHookConfig, self).get_fieldsets(request, obj)
1014032
def _get_apphook_field_names(model):
    
    from .models import AppHookConfig  # avoid circular dependencies
    fields = []
    for field in model._meta.fields:
        if isinstance(field, ForeignKey) and issubclass(field.remote_field.model, AppHookConfig):
            fields.append(field)
    return [field.name for field in fields]
2302
function(config){
        
        if(isString(config)){
            this.config.appBase = config;
        }else if(isObject(config)){// If the config object is provided
            this.config = Object.assign(this.config, config);
        }

        // If the app base isn't provided
        if(!this.config.appBase){
            this.config.appBase = utils.getAppLocalPath();
        }else if(this.config.appBase.length && this.config.appBase[this.config.appBase.length-1] !== '/'){
            this.config.appBase += '/';
        }

        // If the layouts list was passed in the config
        if(this.config.layouts && isObject(this.config.layouts)){
            Object.keys(this.config.layouts).forEach(key => {
                layouts.add(key, this.config.layouts[key]);
            });
        }

        // If the dev mode is on
        if(this.config.devMode === true){
            // Attach some shortcuts
            Application.on('ready', function(){

                // Ctrl+F12 to toggle the dev tools
                Shortcuts.register('CmdOrCtrl+F12', function(){
                    const window = windowManager.getCurrent();
                    if(window) window.toggleDevTools();
                });

                // Ctrl+R to reload the page
                Shortcuts.register('CmdOrCtrl+R', function(){
                    const window = windowManager.getCurrent();
                    if(window) window.reload();
                });

            });
        }

        // If a default setup is provided
        if(this.config.defaultSetup){
            this.setDefaultSetup(this.config.defaultSetup);
            delete this.config.defaultSetup;
        }
    }
1044404
function appRequest(params, cb) {
  params = params || {};
  var mbaasConf = params[constants.MBAAS_CONF_KEY];
  params[constants.MBAAS_CONF_KEY] = undefined;
  //Adding Mbaas Config Params
  var fullParams = _.extend(_.clone(params), mbaasConf);

  var invalidParamError = validateAppParams(fullParams);

  if (invalidParamError) {
    return cb(invalidParamError);
  }

  fullParams = _buildAppRequestParams(fullParams);

  return doFHMbaaSRequest(fullParams, cb);
}
1220083
def get_form(self, request, obj=None, **kwargs):
        
        defaults = {}
        if obj is None:
            defaults['form'] = self.add_form
        defaults.update(kwargs)
        return super(SettingsAdmin, self).get_form(request, obj, **defaults)
878605
def toggle_value(request, name):
    
    obj = service.system.namespace.get(name, None)
    if not obj or service.read_only:
        raise Http404
    new_status = obj.status = not obj.status
    if service.redirect_from_setters:
        return HttpResponseRedirect(reverse('set_ready', args=(name, new_status)))
    else:
        return set_ready(request, name, new_status)
949705
def parse_request(self):
        
        data = {}
        options = {}
        ### get data
        if request.headers['Content-Type'].startswith('application/json'):
            # data in JSON
            data = request.json
            assert data is not None #FIXME: better error than assertError ?
            if "options" in data:
                options = data["options"]
                del data["options"]
        else:
            # data in URL/post
            data = dict()
            data.update(request.form)
            data.update(request.args)
            for key, value in six.iteritems(data):
                if isinstance(value, list) and len(value) == 1:
                    data[key] = value[0]
            # manage config in url
            options = self._config_from_url()
        return data, options
435630
def autocomplete_view(self, request):
        
        query = request.GET.get('q', None)
        app_label = request.GET.get('app_label', None)
        model_name = request.GET.get('model_name', None)
        search_fields = request.GET.get('search_fields', None)
        object_pk = request.GET.get('object_pk', None)

        try:
            to_string_function = self.related_string_functions[model_name]
        except KeyError:
            to_string_function = lambda x: str(x)

        if search_fields and app_label and model_name and (query or object_pk):

            def construct_search(field_name):
                # use different lookup methods depending on the notation
                if field_name.startswith('^'):
                    fmt, name = "{}__istartswith", field_name[1:]
                elif field_name.startswith('='):
                    fmt, name = "{}__iexact", field_name[1:]
                elif field_name.startswith('@'):
                    fmt, name = "{}__search", field_name[1:]
                else:
                    fmt, name = "{}__icontains", field_name
                return fmt.format(name)

            model = apps.get_model(app_label, model_name)
            queryset = model._default_manager.all()
            data = ''
            if query:
                for bit in query.split():
                    or_queries = [
                        models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)})
                        for field_name
                        in search_fields.split(',')
                    ]
                    other_qs = QuerySet(model)
                    other_qs.query.select_related = queryset.query.select_related
                    other_qs = other_qs.filter(reduce(operator.or_, or_queries))
                    queryset = queryset & other_qs

                if self.autocomplete_limit:
                    queryset = queryset[:self.autocomplete_limit]

                data = ''.join([
                    '{}|{}\n'.format(to_string_function(f), f.pk)
                    for f
                    in queryset
                ])
            elif object_pk:
                try:
                    obj = queryset.get(pk=object_pk)
                except:
                    pass
                else:
                    data = to_string_function(obj)
            return HttpResponse(data)
        return HttpResponseNotFound()
719181
def app_model_id(obj):
    
    ct = ContentType.objects.get_for_model(obj)

    return '%s-%s-%s' % (ct.app_label, ct.model, obj.id)
381031
def init_app(self, app, url='/hooks'):
        
        app.config.setdefault('VALIDATE_IP', True)
        app.config.setdefault('VALIDATE_SIGNATURE', True)

        @app.route(url, methods=['POST'])
        def hook():
            if app.config['VALIDATE_IP']:
                if not is_github_ip(request.remote_addr):
                    raise Forbidden('Requests must originate from GitHub')

            if app.config['VALIDATE_SIGNATURE']:
                key = app.config.get('GITHUB_WEBHOOKS_KEY', app.secret_key)
                signature = request.headers.get('X-Hub-Signature')

                if hasattr(request, 'get_data'):
                    # Werkzeug >= 0.9
                    payload = request.get_data()
                else:
                    payload = request.data

                if not signature:
                    raise BadRequest('Missing signature')

                if not check_signature(signature, key, payload):
                    raise BadRequest('Wrong signature')

            event = request.headers.get('X-GitHub-Event')
            guid = request.headers.get('X-GitHub-Delivery')
            if not event:
                raise BadRequest('Missing header: X-GitHub-Event')
            elif not guid:
                raise BadRequest('Missing header: X-GitHub-Delivery')

            if hasattr(request, 'get_json'):
                # Flask >= 0.10
                data = request.get_json()
            else:
                data = request.json

            if event in self._hooks:
                return self._hooks[event](data, guid)
            else:
                return 'Hook not used\n'
1049135
def check(cls):
        
        attribs = [
            'app_version',
            'app_name',
            'config_file_path',
            'config_sep_str',
        ]
        for attrib in attribs:
            if getattr(cls, attrib) == 'not_set':
                raise IncompleteSetupError(f'elib_config setup is incomplete; missing: {attrib}')
219704
def get_fieldsets(self, request, obj=None):
        

        # some ugly business to remove freeze_date
        # from the field list
        general_module = {
            'fields': list(self.general_fields),
            'classes': ('module-general',),
        }

        default_fieldsets = list(self.fieldsets)
        if not request.user.has_perm('pages.can_freeze'):
            general_module['fields'].remove('freeze_date')
        if not request.user.has_perm('pages.can_publish'):
            general_module['fields'].remove('status')

        default_fieldsets[0][1] = general_module

        placeholder_fieldsets = []
        template = get_template_from_request(request, obj)
        for placeholder in get_placeholders(template):
            if placeholder.name not in self.mandatory_placeholders:
                placeholder_fieldsets.append(placeholder.name)

        additional_fieldsets = []

        # meta fields
        metadata_fieldsets = [f['name'] for f in self.metadata_fields]
        additional_fieldsets.append((_('Metadata'), {
            'fields': metadata_fieldsets,
            'classes': ('module-content', 'grp-collapse grp-closed'),
        }))
        additional_fieldsets.append((_('Content'), {
            'fields': placeholder_fieldsets,
            'classes': ('module-content',),
        }))

        return default_fieldsets + additional_fieldsets
1175525
def get_meta_attribute(self, param):
        
        return self._get_meta_value(param, getattr(self.app_config, param)) or ''
91573
def request_context(app, request):
    
    vars = {}
    if request.view_args is not None:
        vars.update(request.view_args)
    vars.update({
        "request": request,
        "GET": AttrDict(request.args.to_dict()),
        "POST" : AttrDict(request.form.to_dict()),
        "app": app,
        "config": app.config,
        "session": session,
        "g": g,
        "now": datetime.datetime.now,
        "utcnow": datetime.datetime.utcnow,
        "today": datetime.date.today})
    context = Context(vars)
    context.vars["current_context"] = context
    return context
1060913
def _get_fieldsets_post_form_or_formset(self, request, form, obj=None):
        
        base_fields = self.replace_orig_field(form.base_fields.keys())
        fields = base_fields + list(self.get_readonly_fields(request, obj))
        return [(None, {'fields': self.replace_orig_field(fields)})]
597120
def create_app():
    
    app = App.create_app(__name__)
    app.configure('.configs.settings')

    # yes, I should use blueprints; but I don't really care for such a small
    # toy app
    @app.route('/config')
    def get_config():
        """Get the current configuration of the app."""
        return jsonify(app.config)

    @app.route('/put_config', methods=['PUT'])
    def put_config():
        """Add to the current configuration of the app.

        Takes any JSON body and adds all keys to the configs with the provided
        values.
        """
        data = request.json()

        for key, val in data.items():
            app.config[key] = val

        return jsonify({'message': 'Config updated!'})

    return app
983409
def dispatch_request(self, *args, **kwargs):
        
        if self.validation:
            specs = {}
            attrs = flasgger.constants.OPTIONAL_FIELDS + [
                'parameters', 'definitions', 'responses',
                'summary', 'description'
            ]
            for attr in attrs:
                specs[attr] = getattr(self, attr)
            definitions = {}
            specs.update(convert_schemas(specs, definitions))
            specs['definitions'] = definitions
            flasgger.utils.validate(
                specs=specs, validation_function=self.validation_function)
        return super(SwaggerView, self).dispatch_request(*args, **kwargs)