Create an object through sqlalchemy

        :param dict data: the data validated by marshmallow
        :param dict view_kwargs: kwargs from the resource view
        :return DeclarativeMeta: an object from sqlalchemy
509645
def create_object(self, data, view_kwargs):
        
        self.before_create_object(data, view_kwargs)

        relationship_fields = get_relationships(self.resource.schema, model_field=True)
        nested_fields = get_nested_fields(self.resource.schema, model_field=True)

        join_fields = relationship_fields + nested_fields

        obj = self.model(**{key: value
                            for (key, value) in data.items() if key not in join_fields})
        self.apply_relationships(data, obj)
        self.apply_nested_fields(data, obj)

        self.session.add(obj)
        try:
            self.session.commit()
        except JsonApiException as e:
            self.session.rollback()
            raise e
        except Exception as e:
            self.session.rollback()
            raise JsonApiException("Object creation error: " + str(e), source={'pointer': '/data'})

        self.after_create_object(obj, data, view_kwargs)

        return obj
1129608
def get_data_for_model(self, args, kwargs):
        
        kwargs_from_invocation = self.get_raw_data()
        args_from_invocation = deque(self.path_args)

        defaults = kwargs
        values = args + list(kwargs.keys())

        output = {}

        raw = False
        for i, field in enumerate(values):
            ## going through each bit of data that the model needs
            ## `field` here is the name of each needed var.

            # the 'default' value that may be defined in the model.
            # this variable might be a string or int or might even be a primitive object.
            # NotImplemented here is used as to preserve if a default value is None.
            # it is used here as a sort of MetaNone.
            default_defined_in_model = defaults.get(field, NotImplemented)
            
            # the value in kwarg arguments such as --values and GET params
            from_data_kwargs = kwargs_from_invocation.get(field, None)

            # The value that will end up being used.
            value_to_use = None

            if default_defined_in_model == RAW_INVOCATION_ARGS:
                # flag that the RAW_INVOCATION_ARGS primitive has been invoked
                # used later to suppress errors for unused program args
                # when this primitive is invoked, all positional args are invalid. 
                raw = True

            if type(default_defined_in_model) == GiottoPrimitive:
                value_to_use = self.get_primitive(default_defined_in_model.name)
            elif from_data_kwargs:
                value_to_use = from_data_kwargs
            elif not raw and args_from_invocation:
                value_to_use = args_from_invocation.popleft()
            elif default_defined_in_model is not NotImplemented:
                value_to_use = default_defined_in_model
            else:
                raise InvalidInvocation("Data Missing For Program. Missing: %s" % field)
            
            output[field] = value_to_use

        if args_from_invocation and not raw:
            msg = "Too many arguments. Program `%s` takes %s arguments, %s given" % (
                self.program.name, len(args) + len(kwargs), len(args_from_invocation)
            )
            raise InvalidInvocation(msg)

        return output
343110
def create(self, data, **kwargs):
        
        self.client.post(self.url, data=data)
110746
def create_view(operations, operation):
    
    operations.execute("CREATE VIEW %s AS %s" % (
        operation.target.name,
        operation.target.sqltext
    ))
903509
def create_from_name_and_dictionary(self, name, datas):
        
        parameter = ObjectParameter()
        self.set_common_datas(parameter, name, datas)

        if "optional" in datas:
            parameter.optional = to_boolean(datas["optional"])
        if "type" in datas:
            parameter.type = str(datas["type"])
        if "generic" in datas:
            parameter.generic = to_boolean(datas["generic"])

        return parameter
1056049
def create_model_instance(self, data):
        
        return self.model(
            session_key=self._get_or_create_session_key(),
            session_data=self.encode(data),
            expire_date=self.get_expiry_date(),
        )
361686
def create_view(self, callback, method, request=None):
        
        view = super(WaldurSchemaGenerator, self).create_view(callback, method, request)
        if is_disabled_action(view):
            view.exclude_from_schema = True

        return view
452096
def use_schema(schema, list_view=False, locations=None):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            use_args_wrapper = parser.use_args(schema, locations=locations)
            # Function wrapped with use_args
            func_with_args = use_args_wrapper(func)
            ret = func_with_args(*args, **kwargs)
            # Serialize and jsonify the return value
            return jsonify(schema.dump(ret, many=list_view).data)

        return wrapped

    return decorator
799405
def create(self, **kwargs):
        

        response = self.ghost.execute_post('%s/' % self._type_name, json={
            self._type_name: [
                kwargs
            ]
        })

        return self._model_type(response.get(self._type_name)[0])
8477
def create(self, **kwargs):
        
        obj = self.model(**kwargs)
        meta = obj.get_meta()
        meta.connection = get_es_connection(self.es_url, self.es_kwargs)
        meta.index=self.index
        meta.type=self.type
        obj.save(force=True)
        return obj
175686
def make_objects(self, meta, data, related_fields=None):
        '''
'''
        make_object = meta.make_object
        related_data = []
        if related_fields:
            for fname, fdata in iteritems(related_fields):
                field = meta.dfields[fname]
                if field in meta.multifields:
                    related = dict(fdata)
                    multi = True
                else:
                    multi = False
                    relmodel = field.relmodel
                    related = dict(((obj.id, obj) for obj in
                                    self.make_objects(relmodel._meta, fdata)))
                related_data.append((field, related, multi))
        for state in data:
            instance = make_object(state, self)
            for field, rdata, multi in related_data:
                if multi:
                    field.set_cache(instance, rdata.get(str(instance.id)))
                else:
                    rid = getattr(instance, field.attname, None)
                    if rid is not None:
                        value = rdata.get(rid)
                        setattr(instance, field.name, value)
            yield instance
1202143
def create_data_and_metadata_from_data(self, data: numpy.ndarray, intensity_calibration: CalibrationModule.Calibration=None, dimensional_calibrations: typing.List[CalibrationModule.Calibration]=None, metadata: dict=None, timestamp: str=None) -> DataAndMetadata.DataAndMetadata:
        
        return self.create_data_and_metadata(numpy.copy(data), intensity_calibration, dimensional_calibrations, metadata, timestamp)
644392
function createFromMetadata (connector, modelsMetadata) {
    if (!connector || !modelsMetadata) {
      throw new Error('Please provide both connector and metadata so Arrow could create models')
    }

    const loadModels = connector.config.generateModels

    return Object.keys(modelsMetadata).reduce(function (previousModels, modelName) {
      const persistModels = connector.config.persistModels
      if (loadModels && loadModels.indexOf(modelName) === -1) {
        return previousModels
      }
      const metadata = modelsMetadata[modelName]
      metadata.autogen = !!connector.config.modelAutogen
      metadata.generated = true
      metadata.connector = connector.name
      metadata.name = modelName

      dataValidator.validate(metadata, metadataSchema)

      if (persistModels) {
        utils.saveModelSync(createModelName(connector, modelName), metadata, connector.modelDir)
      } else {
        previousModels[modelName] = Arrow.createModel(createModelName(connector, modelName), metadata)
      }
      return previousModels
    }, {})
  }
1077740
function ViewModel(view, data, key, opts) {
	var vm = this;

	vm.view = view;
	vm.data = data;
	vm.key = key;

	if (opts) {
		vm.opts = opts;
		vm.cfg(opts);
	}

	var out = isPlainObj(view) ? view : view.call(vm, vm, data, key, opts);

	if (isFunc(out))
		{ vm.render = out; }
	else {
		vm.render = out.render;
		vm.cfg(out);
	}

	vm.init && vm.init.call(vm, vm, vm.data, vm.key, opts);
}
1269315
def _create_sqlite_metatable(self):
        
        sys.stderr.write("Indexing schema. This will take a second...")
        rows_to_insert = []
        tables = [row[0] for row in self.cur.execute("select name from sqlite_master where type='table';")]
        for table in tables:
            for row in self.cur.execute("pragma table_info('{0}')".format(table)):
                rows_to_insert.append((table, row[1], row[2]))
        # find for table and column names
        self.cur.execute("drop table if exists tmp_dbpy_schema;")
        self.cur.execute("create temp table tmp_dbpy_schema(table_name varchar, column_name varchar, data_type varchar);")
        for row in rows_to_insert:
            self.cur.execute("insert into tmp_dbpy_schema(table_name, column_name, data_type) values('{0}', '{1}', '{2}');".format(*row))
        self.cur.execute("SELECT name, sql  FROM sqlite_master where sql like '%REFERENCES%';")

        # find for foreign keys
        self.cur.execute("drop table if exists tmp_dbpy_foreign_keys;")
        self.cur.execute("create temp table tmp_dbpy_foreign_keys(table_name varchar, column_name varchar, foreign_table varchar, foreign_column varchar);")
        foreign_keys = []
        self.cur.execute("SELECT name, sql  FROM sqlite_master ;")
        for (table_name, sql) in self.cur:
            rgx = "FOREIGN KEY \(\[(.*)\]\) REFERENCES \[(.*)\] \(\[(.*)\]\)"
            if sql is None:
                continue
            for (column_name, foreign_table, foreign_key) in re.findall(rgx, sql):
                foreign_keys.append((table_name, column_name, foreign_table, foreign_key))
        for row in foreign_keys:
            sql_insert = "insert into tmp_dbpy_foreign_keys(table_name, column_name, foreign_table, foreign_column) values('{0}', '{1}', '{2}', '{3}');"
            self.cur.execute(sql_insert.format(*row))

        self.con.commit()
        sys.stderr.write("finished!\n")
702585
def create_default_views(self, create_datastore_views=False):
        # type: (bool) -> None
        
        package = deepcopy(self.data)
        if self.resources:
            package['resources'] = self._convert_hdxobjects(self.resources)

        data = {'package': package, 'create_datastore_views': create_datastore_views}
        self._write_to_hdx('create_default_views', data, 'package')
1314872
def create_app():
    
    
    # Setup Flask app and app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Initialize Flask extensions
    db = SQLAlchemy(app)                            # Initialize Flask-SQLAlchemy

    # Define the User data-model. Make sure to add flask_user UserMixin !!!
    class User(db.Model, UserMixin):
        __tablename__ = 'users'
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50, collation='NOCASE'), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')

        # User information
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')
        first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')
        last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')

        # Relationship
        user_emails = db.relationship('UserEmail')


    # Define UserEmail DataModel.
    class UserEmail(db.Model):
        __tablename__ = 'user_emails'
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

        # User email information
        email = db.Column(db.String(255, collation='NOCASE'), nullable=False, unique=True)
        email_confirmed_at = db.Column(db.DateTime())
        is_primary = db.Column(db.Boolean(), nullable=False, default=False)

        # Relationship
        user = db.relationship('User', uselist=False)


    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db, User, UserEmailClass=UserEmail)        # Register the User data-model
    user_manager = UserManager(db_adapter, app)     # Initialize Flask-User

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p>This page can be accessed by anyone.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('member_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users
    @app.route('/members')
    @login_required                                 # Use of @login_required decorator
    def member_page():
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p>This page can only be accessed by authenticated users.</p><br/>
                <p><a href={{ url_for('home_page') }}>Home page</a> (anyone)</p>
                <p><a href={{ url_for('member_page') }}>Members page</a> (login required)</p>
            {% endblock %}
            """)

    return app