// Unsave saves a link or comment using OAuth.
171529
func (o *OAuthSession) Unsave(v Voter, category string) error {
	// Build form for POST request.
	form := url.Values{
		"id":       {v.voteID()},
		"category": {category},
	}
	var u interface{}

	err := o.postBody("https://oauth.reddit.com/api/unsave", form, u)
	if err != nil {
		return err
	}
	return nil
}
885041
func (aug *AuthUserGroup) Save(db XODB) error {
	if aug.Exists() {
		return aug.Update(db)
	}

	return aug.Insert(db)
}
1085044
func UnLockUnsafe(path string, key []byte) ([]byte, error) {
	key = append(key, pad...)
	naclKey := new([keySize]byte)
	copy(naclKey[:], key[:keySize])
	nonce := new([nonceSize]byte)
	in, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	copy(nonce[:], in[:nonceSize])
	configbytes, ok := secretbox.Open(nil, in[nonceSize:], nonce, naclKey)
	if !ok {
		return nil, errors.New("Could not decrypt the config file. Wrong password?")
	}

	return configbytes, nil

}
723144
func (s *storage) SaveAuthorize(data *osin.AuthorizeData) error {
	token, err := s.convertToAuthorizeToken(data)
	if err != nil {
		return err
	}
	_, err = s.authorizetoken.Create(token)
	return err
}
1346787
func (m *SnapshotMetadata) save() error {
	// This is not safe for concurrent access.
	// Exported methods will deal with locking.
	jsonData, err := json.Marshal(m.snapshotMetadata)
	if err != nil {
		glog.Errorf("Error encoding metadata to json: %s", err)
		return ErrInvalidMetadata
	}
	return ioutil.WriteFile(m.path, jsonData, 0644)
}
104606
func (inst *Instagram) Save() error {
	home := os.Getenv("HOME")
	if home == "" {
		home = os.Getenv("home") // for plan9
	}
	return inst.Export(filepath.Join(home, ".goinsta"))
}
452182
func (f *File) Save() error {
	if f.Filename == "" {
		return ErrNoFilenameSupplied
	}
	return f.Write(f.Filename)
}
1179310
func (st *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
	s, _ := context.Get(r, contextKey(session.Name())).(*xormSession)

	// delete if max age is < 0
	if session.Options.MaxAge < 0 {
		if s != nil {
			if _, err := st.e.Delete(&xormSession{
				ID:        session.ID,
				tableName: st.opts.TableName,
			}); err != nil {
				return err
			}
		}
		http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
		return nil
	}

	data, err := securecookie.EncodeMulti(session.Name(), session.Values, st.Codecs...)
	if err != nil {
		return err
	}
	now := util.TimeStampNow()
	expire := now.AddDuration(time.Second * time.Duration(session.Options.MaxAge))

	if s == nil {
		// generate random session ID key suitable for storage in the db
		session.ID = strings.TrimRight(
			base32.StdEncoding.EncodeToString(
				securecookie.GenerateRandomKey(sessionIDLen)), "=")
		s = &xormSession{
			ID:          session.ID,
			Data:        data,
			CreatedUnix: now,
			UpdatedUnix: now,
			ExpiresUnix: expire,
			tableName:   st.opts.TableName,
		}
		if _, err := st.e.Insert(s); err != nil {
			return err
		}
		context.Set(r, contextKey(session.Name()), s)
	} else {
		s.Data = data
		s.UpdatedUnix = now
		s.ExpiresUnix = expire
		if _, err := st.e.ID(s.ID).Cols("data", "updated_unix", "expires_unix").Update(s); err != nil {
			return err
		}
	}

	// set session id cookie
	id, err := securecookie.EncodeMulti(session.Name(), session.ID, st.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, sessions.NewCookie(session.Name(), id, session.Options))

	return nil
}
1145831
func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
	// Generate an encoded cookie value with the CSRF token.
	encoded, err := cs.sc.Encode(cs.name, token)
	if err != nil {
		return err
	}

	cookie := &http.Cookie{
		Name:     cs.name,
		Value:    encoded,
		MaxAge:   cs.maxAge,
		HttpOnly: cs.httpOnly,
		Secure:   cs.secure,
		Path:     cs.path,
		Domain:   cs.domain,
	}

	// Set the Expires field on the cookie based on the MaxAge
	// If MaxAge <= 0, we don't set the Expires attribute, making the cookie
	// session-only.
	if cs.maxAge > 0 {
		cookie.Expires = time.Now().Add(
			time.Duration(cs.maxAge) * time.Second)
	}

	// Write the authenticated cookie to the response.
	http.SetCookie(w, cookie)

	return nil
}
85511
func (s *Storage) SaveAuthorize(data *osin.AuthorizeData) (err error) {
	userId, ok := data.UserData.(uint)
	if !ok {
		return errors.New("cannot assert user_id is uint")
	}

	var authorize service.Authorize
	copier.Copy(&authorize, &data)
	authorize.UserId = userId
	authorize.Client = data.Client.GetId()

	if !dbconn.DB.NewRecord(authorize) {
		return errors.New("authorize already exist")
	} else if err := dbconn.DB.Create(&authorize).Error; err != nil {
		return err
	} else if dbconn.DB.NewRecord(authorize) {
		return errors.New("authorize was not created")
	}
	return nil
}
566357
func (p *Pixbuf) Save(filename, savetype string, options ...string) *glib.Error {
	if len(options)%2 != 0 {
		argumentPanic("Save options must be even (key and value)")
	}

	pfilename := C.CString(filename)
	defer cfree(pfilename)
	psavetype := C.CString(savetype)
	defer cfree(psavetype)

	klen := len(options) / 2
	keys := C.makeCstrv(C.int(klen + 1))
	vals := C.makeCstrv(C.int(klen + 1))
	for i := 0; i < klen; i++ {
		C.setCstr(keys, C.int(i), C.CString(options[2*i]))
		C.setCstr(vals, C.int(i), C.CString(options[2*i+1]))
	}
	C.setCstr(keys, C.int(klen), nil)
	C.setCstr(vals, C.int(klen), nil)
	defer func() {
		for i := 0; i < klen; i++ {
			cfree(C.getCstr(keys, C.int(i)))
			cfree(C.getCstr(vals, C.int(i)))
		}
		C.freeCstrv(keys)
		C.freeCstrv(vals)
	}()

	var err *C.GError
	C.gdk_pixbuf_savev(p.GPixbuf, pfilename, psavetype, keys, vals, &err)
	if err != nil {
		return glib.ErrorFromNative(unsafe.Pointer(err))
	}
	return nil
}
352319
func (r *Response) Save(fileName string) error {
	return ioutil.WriteFile(fileName, r.Body, 0644)
}
1233468
func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter,
	session *Session) error {
	encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
		s.Codecs...)
	if err != nil {
		return err
	}
	http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options))
	return nil
}
229247
func (ag *AuthGroup) Save(db XODB) error {
	if ag.Exists() {
		return ag.Update(db)
	}

	return ag.Insert(db)
}
250357
func (s *OAuth2Storage) SaveAccess(accessData *osin.AccessData) error {
	var clientID uint64
	var err error
	if clientID, err = strconv.ParseUint(accessData.Client.GetId(), 10, 64); err != nil {
		return errors.New("Invalid Client ID")
	}

	if err = s.isValidScope(accessData.Scope); err != nil {
		return fmt.Errorf("Saving Access: " + err.Error())
	}

	var accessDataIDPtr sql.NullInt64
	if accessData.AccessData != nil {
		var father OAuth2AccessData
		if err = Db().Model(OAuth2AccessData{}).Where(&OAuth2AccessData{AccessToken: accessData.AccessData.AccessToken}).Scan(&father); err != nil {
			return errors.New("Error fetching parent Access Data ID")
		}

		accessDataIDPtr.Int64, accessDataIDPtr.Valid = int64(father.ID), true
	}

	// required to fill the foreign key
	var authorizeDataIDPtr sql.NullInt64
	if accessData.AuthorizeData != nil {
		var authorizeData OAuth2AuthorizeData
		if err = Db().Model(OAuth2AuthorizeData{}).Where(&OAuth2AuthorizeData{Code: accessData.AuthorizeData.Code}).Scan(&authorizeData); err != nil {
			return fmt.Errorf("SaveAccess: can't load authorize data with code: %s", accessData.AuthorizeData.Code)
		}

		authorizeDataIDPtr.Int64, authorizeDataIDPtr.Valid = int64(authorizeData.ID), true
	}

	tx := Db().Begin()

	var refreshTokenFK sql.NullInt64

	oauthAccessData := &OAuth2AccessData{
		AccessDataID:    accessDataIDPtr,
		AccessToken:     accessData.AccessToken,
		AuthorizeDataID: authorizeDataIDPtr,
		ClientID:        clientID,
		//CreatedAt:       accessData.CreatedAt, <- dbms handled
		ExpiresIn:   uint64(accessData.ExpiresIn),
		RedirectURI: accessData.RedirectUri,
		Scope:       accessData.Scope,
		UserID:      accessData.UserData.(uint64)}

	if accessData.RefreshToken != "" {
		// Create refresh token
		var newRefreshToken OAuth2RefreshToken
		newRefreshToken.Token = accessData.RefreshToken
		if err := tx.Create(&newRefreshToken); err != nil {
			tx.Rollback()
			return err
		}
		refreshTokenFK.Int64 = int64(newRefreshToken.ID)
		refreshTokenFK.Valid = true
	}

	// Put refresh token id, into OAuth2AccessData.refreshtoken fk
	oauthAccessData.RefreshTokenID = refreshTokenFK

	if err := tx.Create(oauthAccessData); err != nil {
		tx.Rollback()
		return err
	}

	if err := tx.Commit(); err != nil {
		return err
	}

	return nil
}
1177003
func (w *wrappedWAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
	var writeEnts []raftpb.Entry
	for _, ent := range ents {
		data, err := encryption.Encrypt(ent.Data, w.encrypter)
		if err != nil {
			return err
		}
		writeEnts = append(writeEnts, raftpb.Entry{
			Index: ent.Index,
			Term:  ent.Term,
			Type:  ent.Type,
			Data:  data,
		})
	}

	return w.WAL.Save(st, writeEnts)
}
45027
func (w *wrapper) Save() error {
	w.mut.Lock()
	defer w.mut.Unlock()

	fd, err := osutil.CreateAtomic(w.path)
	if err != nil {
		l.Debugln("CreateAtomic:", err)
		return err
	}

	if err := w.cfg.WriteXML(fd); err != nil {
		l.Debugln("WriteXML:", err)
		fd.Close()
		return err
	}

	if err := fd.Close(); err != nil {
		l.Debugln("Close:", err)
		return err
	}

	events.Default.Log(events.ConfigSaved, w.cfg)
	return nil
}