text:
package rippleapi

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"math/big"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/vennd/enu/consts"
	"github.com/vennd/enu/internal/golang.org/x/net/context"
	"github.com/vennd/enu/log"
)

var DefaultFee = "10000"
var DefaultFeeI uint64 = 10000
var customCurrencyPrefix = "80"
var BaseReserve = 20000000
var OwnerReserve = 5000000
var DefaultAmountToTrust uint64 = 100000000000000000

// Account set flags
const AsfRequireDest = 1
const AsfRequireAuth = 2
const AsfDisallowXRP = 3
const AsfDisableMaster = 4
const AsfAccountTxnID = 5
const AsfNoFreeze = 6
const AsfGlobalFreeze = 7
const AsfDefaultRipple = 8

// AccountRoot Flags
const LsfDefaultRipple = 8388608

// Trust set flags (on the transaction)
const TfSetfAuth = 65536
const TfSetNoRipple = 131072
const TfClearNoRipple = 262144
const TfSetFreeze = 1048576
const TfClearFreeze = 2097152

type Amount struct {
	Value    string `json:"value,omitempty"`
	Currency string `json:"currency,omitempty"`
	Issuer   string `json:"issuer,omitempty"`
}

// Structure for payment transactions for custom currencies
type PaymentAssetTx struct {
	// Common fields
	Account            string `json:",omitempty"`
	AccountTxnID       string `json:",omitempty"`
	Fee                string `json:",omitempty"`
	Flags              uint32 `json:",omitempty"`
	LastLedgerSequence uint64 `json:",omitempty"`
	Memos              []Memo
	Sequence           uint32 `json:",omitempty"`
	SigningPubKey      string `json:",omitempty"`
	SourceTag          uint32 `json:",omitempty"`
	TransactionType    string `json:",omitempty"`
	TxnSignature       string `json:",omitempty"`

	// Payment specific fields
	Amount         Amount // Note the Amount field is different between sending XRP or a custom currency
	SendMax        Amount
	Destination    string
	DestinationTag uint32
	InvoiceID      string
	//	Paths
	//	SendMax Currency
	//	DeliverMin Currency
}

// Structure for payment transactions for xrp
type PaymentXrpTx struct {
	// Common fields
	Account            string `json:",omitempty"`
	AccountTxnID       string `json:",omitempty"`
	Fee                string `json:",omitempty"`
	Flags              uint32 `json:",omitempty"`
	LastLedgerSequence uint64 `json:",omitempty"`
	Memos              []Memo
	Sequence           uint32 `json:",omitempty"`
	SigningPubKey      string `json:",omitempty"`
	SourceTag          uint32 `json:",omitempty"`
	TransactionType    string `json:",omitempty"`
	TxnSignature       string `json:",omitempty"`

	// Payment specific fields
	Amount         string `json:",omitempty"`
	Destination    string `json:",omitempty"`
	DestinationTag uint32 `json:",omitempty"`
	InvoiceID      string `json:",omitempty"`
	//	Paths
	//	SendMax Currency
	//	DeliverMin Currency
}

type Memo struct {
	MemoData   string `json:",omitempty"`
	MemoFormat string `json:",omitempty"`
	MemoType   string `json:",omitempty"`
}

type Wallet struct {
	AccountId     string `json:"account_id"`
	KeyType       string `json:"key_type"`
	MasterKey     string `json:"master_key"`
	MasterSeed    string `json:"master_seed"`
	MasterSeedHex string `json:"master_seed_hex"`
	PublicKey     string `json:"public_key"`
	PublicKeyHex  string `json:"public_key_hex"`
	Status        string `json:"status"`
}

type Balance struct {
	Value        string `json:"value"`
	Currency     string `json:"currency"`
	Counterparty string `json:"counterparty"`
}

//type AccountlinesResult struct {
//	Account              string        `json:"account"`
//	Ledger_current_index int64         `json:"ledger_current_index"`
//	GetAccountLines      []Accountline `json:"lines"`
//	Status               string        `json:"status"`
//	Validated            bool          `json:"validated"`
//}
//
//type Accountline struct {
//	Account     string `json:"account"`
//	Balance     string `json:"balance"`
//	Currency    string `json:"currency"`
//	Limit       string `json:"limit"`
//	Limit_peer  string `json:"limit_peer"`
//	Quality_in  int64  `json:"quality_in"`
//	Quality_out int64  `json:"quality_out"`
//}

type ApiResult struct {
	resp *http.Response
	err  error
}

type payloadGetServerInfo struct {
	Method string                     `json:"method"`
	Params payloadGetServerInfoParams `json:"params"`
}

type payloadGetServerInfoParams struct{}

type payloadLedger struct {
	Method string              `json:"method"`
	Params payloadLedgerParams `json:"params"`
}

type payloadLedgerParams struct{}

type payloadGetCurrenciesByAccount struct {
	Method string                   `json:"method"`
	Params payloadGetCcyByAcctParms `json:"params"`
}

type payloadGetCcyByAcctParms []PayloadGetCcyByAcct

type PayloadGetCcyByAcct struct {
	Account       string `json:"account"`
	Account_index int64  `json:"account_index"`
	Ledger_index  string `json:"ledger_index"`
	Strict        bool   `json:"strict"`
}

type CurrenciesByAccount struct {
	Result CcyByAccountResult `json:"result"`
}

type CcyByAccountResult struct {
	Ledger_hash       string   `json:"ledger_hash"`
	Ledger_index      int64    `json:"ledger_index"`
	ReceiveCurrencies []string `json:"receive_currencies"`
	SendCurrencies    []string `json:"send_currencies"`
	Status            string   `json:"status"`
	Validated         bool     `json:"validated"`
}

type Currency struct {
	Currency string `json:"currency"`
}

type AccountSet struct {
	// Common fields
	Account            string `json:",omitempty"`
	AccountTxnID       string `json:",omitempty"`
	Fee                string `json:",omitempty"`
	Flags              uint32 `json:",omitempty"`
	LastLedgerSequence uint32 `json:",omitempty"`
	Memos              []Memo
	Sequence           uint32 `json:",omitempty"`
	SigningPubKey      string `json:",omitempty"`
	SourceTag          uint32 `json:",omitempty"`
	TransactionType    string `json:",omitempty"`
	TxnSignature       string `json:",omitempty"`

	ClearFlag    uint32 `json:",omitempty"`
	Domain       string `json:",omitempty"`
	EmailHash    string `json:",omitempty"`
	MessageKey   string `json:",omitempty"`
	SetFlag      uint32 `json:",omitempty"`
	TransferRate uint32 `json:",omitempty"`
}

type LimitAmount struct {
	Value    string `json:"value,omitempty"`
	Currency string `json:"currency,omitempty"`
	Issuer   string `json:"issuer,omitempty"`
}

type TrustSetStruct struct {
	// Common fields
	Account            string `json:",omitempty"`
	AccountTxnID       string `json:",omitempty"`
	Fee                string `json:",omitempty"`
	Flags              uint32 `json:",omitempty"`
	LastLedgerSequence uint32 `json:",omitempty"`
	Memos              []Memo `json:",omitempty"`
	Sequence           uint32 `json:",omitempty"`
	SigningPubKey      string `json:",omitempty"`
	SourceTag          uint32 `json:",omitempty"`
	TransactionType    string `json:",omitempty"`
	TxnSignature       string `json:",omitempty"`

	LimitAmount LimitAmount `json:",omitempty"`
	QualityIn   uint32      `json:",omitempty"`
	QualityOut  uint32      `json:",omitempty"`
}

type Line struct {
	Account      string `json:"account,omitempty"`
	Balance      string `json:"balance,omitempty"`
	Currency     string `json:"currency,omitempty"`
	Limit        string `json:"limit,omitempty"`
	LimitPeer    string `json:"limit_peer,omitempty"`
	NoRipple     bool   `json:"no_ripple,omitempty"`
	NoRipplePeer bool   `json:"no_ripple_peer,omitempty"`
	QualityIn    uint   `json:"quality_in,omitempty"`
	QualityOut   uint   `json:"quality_out,omitempty"`
}

type Lines []Line

func (s Lines) Len() int {
	return len(s)
}

func (s Lines) Contains(account string, currency string) bool {
	var result bool = false

	//	log.Printf("searching for account:%s, currency:%s", account, currency)

	for _, line := range s {
		//		log.Printf("account:%s, currency:%s", line.Account, line.Currency)
		if line.Account == account && strings.ToUpper(line.Currency) == strings.ToUpper(currency) {
			result = true
			//			log.Printf("found")
		}
	}

	return result
}

type AccountInfo struct {
	Account         string `json:",omitempty"`
	Balance         string `json:",omitempty"`
	Flags           uint32 `json:",omitempty"`
	LedgerEntryType string `json:",omitempty"`
	OwnerCount      int    `json:",omitempty"`
	PreviousTxnID   string `json:",omitempty"`
	Sequence        int    `json:",omitempty"`
	Index           string `json:"index,omitempty"`
}

type LedgerValue struct {
	Accepted bool `json:"accepted,omitempty"`
	//Accepted2	string
	AccountHash         string `json:"account_hash,omitempty"`
	CloseFlags          uint32 `json:"close_flags,omitempty"`
	CloseTime           uint32 `json:"close_time,omitempty"`
	CloseTimeHuman      string `json:"close_time_human,omitempty"`
	CloseTimeResolution uint32 `json:"close_time_resolution,omitempty"`
	Closed              bool   `json:"closed,omitempty"`
	LedgerHash          string `json:"ledger_hash,omitempty"`
	LedgerIndex         string `json:"ledger_index,omitempty"`
	ParentCloseTime     uint32 `json:"parent_close_time,omitempty"`
	ParentHash          string `json:"parent_hash,omitempty"`
	SeqNum              string `json:"seqNum,omitempty"`
	TotalCoins1         string `json:"totalCoins,omitempty"`
	TotalCoins2         string `json:"total_coins,omitempty"`
	TransactionHash     string `json:"transaction_hash,omitempty"`
}

type Ledger struct {
	Ledger LedgerValue `json:"ledger,omitempty"`
}

type LedgerResult struct {
	Closed Ledger `json:"closed,omitempty"`
	Open   Ledger `json:"open,omitempty"`
}

type Transaction struct {
	Account     string `json:",omitempty"`
	Hash        string `json:"hash,omitempty"`
	LedgerIndex uint64 `json:"ledger_index,omitempty"`
	Validated   bool   `json:"validated,omitempty"`
}

// Used to store the internal wallets
type MasterWallet struct {
	Address    string `json:"address"`
	Passphrase string `json:"passphrase"`
}

// Initialises global variables and database connection for all handlers
var isInit bool = false // set to true only after the init sequence is complete
var rippleHost string
var RippleWallets []MasterWallet
var rippleLastLedgerSequenceOffset uint

func Init() {
	var configFilePath string

	if isInit == true {
		return
	}

	if _, err := os.Stat("./enuapi.json"); err == nil {
		//		log.Println("Found and using configuration file ./rippleapi.json")
		configFilePath = "./enuapi.json"
	} else {
		if _, err := os.Stat(os.Getenv("GOPATH") + "/bin/enuapi.json"); err == nil {
			configFilePath = os.Getenv("GOPATH") + "/bin/enuapi.json"
			//			log.Printf("Found and using configuration file from GOPATH: %s\n", configFilePath)

		} else {
			if _, err := os.Stat(os.Getenv("GOPATH") + "/src/github.com/vennd/enu/enuapi.json"); err == nil {
				configFilePath = os.Getenv("GOPATH") + "/src/github.com/vennd/enu/enuapi.json"
				//				log.Printf("Found and using configuration file from GOPATH: %s\n", configFilePath)
			} else {
				log.Println("Cannot find enuapi.json")
				os.Exit(-100)
			}
		}
	}

	InitWithConfigPath(configFilePath)
}

func InitWithConfigPath(configFilePath string) {
	var configuration interface{}

	if isInit == true {
		return
	}

	// Read configuration from file
	//	log.Printf("Reading %s\n", configFilePath)
	file, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		log.Println("Unable to read configuration file enuapi.json")
		log.Println(err.Error())
		os.Exit(-101)
	}

	err = json.Unmarshal(file, &configuration)

	if err != nil {
		log.Println("Unable to parse enuapi.json")
		log.Println(err.Error())
		os.Exit(-101)
	}

	m := configuration.(map[string]interface{})

	// Ripple API parameters
	rippleHost = m["rippleHost"].(string) // End point for JSON RPC server
	rippleLastLedgerSequenceOffset = uint(m["rippleLastLedgerSequenceOffset"].(float64))

	for _, w := range m["rippleWallets"].([]interface{}) {
		var wallet MasterWallet
		var wmap = w.(map[string]interface{})

		wallet.Address = wmap["address"].(string)
		wallet.Passphrase = wmap["passphrase"].(string)

		RippleWallets = append(RippleWallets, wallet)
	}

	isInit = true
}

func postRPCAPI(c context.Context, postData []byte) (map[string]interface{}, int64, error) {

	var result map[string]interface{}
	var apiResp ApiResult

	postDataJson := string(postData)
	log.FluentfContext(consts.LOGDEBUG, c, "rippleapi postRPCAPI() posting: %s", postDataJson)

	// Set headers
	req, err := http.NewRequest("POST", rippleHost, bytes.NewBufferString(postDataJson))
	req.Header.Set("Content-Type", "application/json")

	clientPointer := &http.Client{}

	// Call ripple JSON RPC service with 10 second timeout
	c1 := make(chan ApiResult, 1)
	go func() {
		var result ApiResult // Wrap the response into a struct so we can return both the error and response

		resp, err := clientPointer.Do(req)
		result.resp = resp
		result.err = err

		c1 <- result
	}()

	select {
	case apiResp = <-c1:
	case <-time.After(time.Second * 10):
		return result, consts.RippleErrors.Timeout.Code, errors.New(consts.RippleErrors.Timeout.Description)
	}

	if apiResp.err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Do(req): %s", apiResp.err.Error())
		return result, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	// Success, read body and return
	body, err := ioutil.ReadAll(apiResp.resp.Body)
	//	log.FluentfContext(consts.LOGDEBUG, c, "rippleapi postRPCAPI() body returned: %s", string(body))

	defer apiResp.resp.Body.Close()

	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in ReadAll(): %s", err.Error())
		return nil, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	// Unmarshall body
	if unmarshallErr := json.Unmarshal(body, &result); unmarshallErr != nil {
		// If we couldn't parse the error properly, log error to fluent and return unhandled error
		log.FluentfContext(consts.LOGERROR, c, "Error in Unmarshal(): %s", unmarshallErr.Error())

		return result, 0, nil
	}

	return result, 0, nil
}

// Submits a transaction to the Ripple network
func Submit(c context.Context, txHexString string) (string, int64, error) {
	if isInit == false {
		Init()
	}

	// Copy same context values to local variables which are often accessed
	env := c.Value(consts.EnvKey).(string)

	var payload = make(map[string]interface{})
	var params = make(map[string]interface{})
	var paramsArray []map[string]interface{}
	var result string

	//	 If the env is set to dev then stub out the return
	if env == "dev" {
		log.FluentfContext(consts.LOGINFO, c, "In dev mode, not submitting tx to Ripple network.")
		return "youwereasuccess", 0, nil
	}

	// Build parameters
	params["tx_blob"] = txHexString
	paramsArray = append(paramsArray, params)

	// Build payload
	payload["method"] = "submit"
	payload["params"] = paramsArray
	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return "", consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return "", errorCode, err
	}

	//	log.Printf("%#v", responseData)

	if responseData["result"] != nil {
		r := responseData["result"].(map[string]interface{})

		if r["engine_result"] != nil && r["engine_result"] == "tesSUCCESS" {
			result = r["tx_json"].(map[string]interface{})["hash"].(string)
		} else {
			result = r["tx_json"].(map[string]interface{})["hash"].(string) // attempt to return the tx_hash such that we can query on later

			var engineResult string
			var engineResultCode int64
			var engineResultMessage string

			if r["engine_result"] != nil {
				engineResult = r["engine_result"].(string)
			}

			if r["engine_result_code"] != nil {
				engineResultCode = int64(r["engine_result_code"].(float64))
			}

			if r["engine_result_message"] != nil {
				engineResultMessage = r["engine_result_message"].(string)
			}

			// terQUEUED indicates we can wait until LastLedgerSequence before the submitted transaction expires
			if engineResult == "terQUEUED" {
				// a ripple ledger is produced every few seconds, retry until rippleLastLedgerSequenceOffset is reached
				// try at most 10 times

				// Note the current ledger sequence
				// Since we don't know what maxLedgerSequence was, use the current sequence + offset
				currentLedger, errorCode, err := GetLatestValidatedLedger(c)
				if err != nil {
					log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve current ledger status. Error: "+err.Error())
					return "", errorCode, err
				}

				interval := time.Duration(1) * time.Second
				for i := 1; i <= 10; i++ {
					time.Sleep(interval) // throttle a second

					// get tx status
					tx, errorCode, err := GetTx(c, result)
					if err != nil {
						log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve tx status. Error: "+err.Error())
						return "", errorCode, err
					}

					// If the tx was accepted in the Ripple ledger
					if tx.Validated == true {
						break
					}

					// check if we've passed the cut off ledger sequence we've specified
					ledger, errorCode, err := GetLatestValidatedLedger(c)
					if err != nil {
						log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve ledger status. Error: "+err.Error())
						return "", errorCode, err
					}

					newLedgerIndex, err := strconv.ParseUint(ledger.LedgerIndex, 10, 64)
					if err != nil {
						log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve new ledger status. Invalid sequence number. Error: "+err.Error())
						return "", errorCode, err
					}

					currentLedgerIndex, err := strconv.ParseUint(currentLedger.LedgerIndex, 10, 64)
					if err != nil {
						log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve ledger status. Invalid sequence number. Error: "+err.Error())
						return "", errorCode, err
					}

					// Passed cut off
					if newLedgerIndex > currentLedgerIndex+uint64(rippleLastLedgerSequenceOffset) {
						break
					}
				}

				// Check if the tx was accepted
				tx, errorCode, err := GetTx(c, result)
				if err != nil {
					log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve tx status. Error: "+err.Error())
					return "", errorCode, err
				}

				if tx.Validated != true {
					log.FluentfContext(consts.LOGERROR, c, "Transaction was not accepted due to esclation of transaction fees!")
					return "", consts.RippleErrors.QueuedNotAccepted.Code, errors.New(consts.RippleErrors.QueuedNotAccepted.Description)
				}

				// ------ Break out and return success
				if tx.Validated == true {
					log.FluentfContext(consts.LOGINFO, c, "Warning - transaction was queued due to escalated fees but subsequently accepted")
					return tx.Hash, 0, nil
				}
			}

			log.FluentfContext(consts.LOGERROR, c, "Error from submit engine_result: %s, engine_result_code: %d, engine_result_message: %s", engineResult, engineResultCode, engineResultMessage)

			// tec* codes indicates the fee was lost
			if strings.HasPrefix(engineResult, "tec") {
				if engineResult == "tecPATH_DRY" {
					return result, consts.RippleErrors.InvalidCurrencyOrNoTrustline.Code, errors.New(consts.RippleErrors.InvalidCurrencyOrNoTrustline.Description)
				}

				if engineResult == "tecUNFUNDED_PAYMENT" {
					return result, consts.RippleErrors.InsufficientXRP.Code, errors.New(consts.RippleErrors.InsufficientXRP.Description)
				}
				return result, consts.RippleErrors.SubmitErrorFeeLost.Code, errors.New(consts.RippleErrors.SubmitErrorFeeLost.Description)
			}

			return result, consts.RippleErrors.SubmitError.Code, errors.New(consts.RippleErrors.SubmitError.Description)
		}
	}

	// get tx status
	//tx, errorCode, err := GetTx(c, result)
	//if err != nil {
	//	log.FluentfContext(consts.LOGERROR, c, "Unable to retrieve tx status. Error: " + err.Error())
	//	return "", errorCode, err
	//}
	//
	//log.FluentfContext(consts.LOGINFO, c, "Tx status: %t", tx.Validated)

	return result, 0, nil
}

// Signs a tx with the given secret. The tx should be a struct containing the tx to be marshalled into JSON and then signed
func Sign(c context.Context, tx interface{}, secret string) (string, int64, error) {
	if isInit == false {
		Init()
	}

	var payload = make(map[string]interface{})
	var params = make(map[string]interface{})
	var paramsArray []map[string]interface{}
	var result string

	// Build parameters
	params["offline"] = false
	params["secret"] = secret
	params["tx_json"] = tx
	paramsArray = append(paramsArray, params)

	// Build payload
	payload["method"] = "sign"
	payload["params"] = paramsArray

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return "", consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return "", errorCode, err
	}

	log.Printf("%#v", responseData)

	if responseData["result"] != nil {
		r := responseData["result"].(map[string]interface{})

		if r["status"] != nil && r["status"] == "success" {
			result = r["tx_blob"].(string)
		} else {
			var errorMessage string
			var errorCode int64

			if r["error_message"] != nil {
				errorMessage = r["error_message"].(string)
			}

			if r["error_code"] != nil {
				errorCode = int64(r["error_code"].(float64))
			}
			log.FluentfContext(consts.LOGERROR, c, "Error from signing: %s, errorCode: %d", errorMessage, errorCode)

			// Invalid source
			if errorCode == 55 || errorCode == 63 {
				return "", consts.RippleErrors.InvalidSource.Code, errors.New(consts.RippleErrors.InvalidSource.Description)
			}

			// Invalid destination
			if errorCode == 29 {
				return "", consts.RippleErrors.InvalidDestination.Code, errors.New(consts.RippleErrors.InvalidDestination.Description)
			}

			// do some errorhandling here
			return "", consts.RippleErrors.SigningError.Code, errors.New(consts.RippleErrors.SigningError.Description)
		}
	}

	return result, 0, nil
}

// Creates a Ripple account offline. ie doesn't use the REST or RPC
func CreateWallet(c context.Context) (Wallet, int64, error) {
	if isInit == false {
		Init()
	}

	var payload = make(map[string]interface{})
	var result Wallet

	payload["method"] = "wallet_propose"
	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return result, errorCode, err
	}

	if responseData["result"] != nil {
		log.Printf("%#v", responseData["result"])
	}

	responseResult := responseData["result"].(map[string]interface{})
	result.AccountId = responseResult["account_id"].(string)
	result.KeyType = responseResult["key_type"].(string)
	result.MasterKey = responseResult["master_key"].(string)
	result.MasterSeed = responseResult["master_seed"].(string)
	result.MasterSeedHex = responseResult["master_seed_hex"].(string)
	result.PublicKey = responseResult["public_key"].(string)
	result.PublicKeyHex = responseResult["public_key_hex"].(string)
	result.Status = responseResult["status"].(string)

	return result, 0, nil
}

// Returns the balances, including xrp held by the account
// Assumes that all custom currencies ripple via a central issuing address.
// ie it doesn't sum balances of the same currency against different trust lines
func GetAccountBalances(c context.Context, account string) ([]Balance, int64, error) {
	var result []Balance

	if isInit == false {
		Init()
	}

	// Retrieve trust lines for the account
	lines, errCode, err := GetAccountLines(c, account)
	if err != nil {
		return result, errCode, err
	}

	// Range through trust lines for the account
	for _, line := range lines {
		var balance Balance

		// Convert the balance which is stored in a string to a big.Float
		var value big.Float
		value.SetString(line.Balance)

		// If the balance on the trustline is > 0, then save it into the result array
		if value.Cmp(big.NewFloat(0)) == 1 {

			balance.Value = line.Balance
			balance.Currency = line.Currency
			balance.Counterparty = line.Account

			result = append(result, balance)
		}
	}

	// Retrieve account information, which contains the XRP balance
	accountInfo, errCode, err := GetAccountInfo(c, account)
	if err != nil {
		// raise error in log but continue. We just don't add the xrp balance to the results
		log.FluentfContext(consts.LOGERROR, c, "Error in GetAccountInfo(): %s", err.Error())
	} else {
		var xrpBalance Balance

		xrpBalance.Counterparty = ""
		xrpBalance.Currency = "XRP"

		var xcpBalance big.Float
		var xcpBalanceFloat big.Float
		xcpBalance.SetString(accountInfo.Balance)
		xcpBalanceFloat.Quo(&xcpBalance, big.NewFloat(1000000))

		resultWithTrail := xcpBalanceFloat.Text('f', 15) // Ripple targets 15 decimal points of precision

		xrpBalance.Value = strings.TrimRight(strings.TrimRight(resultWithTrail, "0"), ".") // Remove trailing zeros

		result = append(result, xrpBalance)
	}

	return result, 0, nil
}

func ServerInfo(c context.Context) ([]byte, int64, error) {
	var payload payloadGetServerInfo
	//	var result []Balance
	var result []byte

	if isInit == false {
		Init()
	}

	payload.Method = "server_info"

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.CounterpartyErrors.MiscError.Code, errors.New(consts.CounterpartyErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return result, errorCode, err
	}

	if responseData["result"] != nil {
		log.Printf("%#v", responseData["result"])
	}

	return result, errorCode, nil
}

func GetLatestValidatedLedger(c context.Context) (LedgerValue, int64, error) {
	var payload payloadLedger
	var result LedgerValue

	if isInit == false {
		Init()
	}

	payload.Method = "ledger"

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.CounterpartyErrors.MiscError.Code, errors.New(consts.CounterpartyErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return result, errorCode, err
	}

	if responseData["result"] != nil {
		log.Printf("%#v", responseData["result"])
	}

	// map reply...
	r := responseData["result"].(map[string]interface{})
	rclosed := r["closed"].(map[string]interface{})
	rclosedledger := rclosed["ledger"].(map[string]interface{})
	result.Closed = rclosedledger["closed"].(bool)
	result.Accepted = rclosedledger["accepted"].(bool)
	//result.Accepted2 = strconv.FormatBool(rclosedledger["closed"].(bool))
	result.LedgerHash = rclosedledger["ledger_hash"].(string)
	result.LedgerIndex = rclosedledger["ledger_index"].(string)

	return result, errorCode, nil
}

func GetCurrenciesByAccount(c context.Context, account string) (CurrenciesByAccount, int64, error) {
	var payload payloadGetCurrenciesByAccount
	var result CurrenciesByAccount
	var result2 []string
	var result3 []string

	if isInit == false {
		Init()
	}

	payload.Method = "account_currencies"
	parms := PayloadGetCcyByAcct{Account: account, Account_index: 0, Ledger_index: "validated", Strict: true}
	payload.Params = append(payload.Params, parms)

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.CounterpartyErrors.MiscError.Code, errors.New(consts.CounterpartyErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return result, errorCode, err
	}

	// Get result from api and create the reply
	if responseData["result"] != nil {
		resultMap := responseData["result"].(map[string]interface{})
		recCcys := resultMap["receive_currencies"].([]interface{})
		sendCcys := resultMap["send_currencies"].([]interface{})

		log.Println("Mapped:")
		log.Printf("%#v\n", resultMap)
		log.Printf("%#v\n", recCcys)
		log.Printf("%#v\n", sendCcys)

		for _, b := range sendCcys {
			c := b.(string)
			result2 = append(result2, c)
		}
		for _, b := range recCcys {
			d := b.(string)
			result3 = append(result3, d)
		}

		result = CurrenciesByAccount{CcyByAccountResult{
			Ledger_hash:       resultMap["ledger_hash"].(string),
			Ledger_index:      int64(resultMap["ledger_index"].(float64)),
			ReceiveCurrencies: result2,
			SendCurrencies:    result3,
			Status:            resultMap["status"].(string),
			Validated:         resultMap["validated"].(bool),
		}}
	}

	return result, 0, nil
}

// GetTx gets the status of a TX in the RCL. Note this doesn't seem to return anything useful if the TX was just submitted but not yet accepted
func GetTx(c context.Context, txhash string) (Transaction, int64, error) {
	var result Transaction

	var payload = make(map[string]interface{})
	var params = make(map[string]interface{})
	var paramsArray []map[string]interface{}
	var responseData map[string]interface{}

	if isInit == false {
		Init()
	}

	// Build parameters
	params["transaction"] = txhash
	params["binary"] = false
	paramsArray = append(paramsArray, params)

	// Build payload
	payload["method"] = "tx"
	payload["params"] = paramsArray

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.CounterpartyErrors.MiscError.Code, errors.New(consts.CounterpartyErrors.MiscError.Description)
	}

	responseData, errorCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		return result, errorCode, err
	}

	if responseData["result"] != nil {
		log.Printf("%#v", responseData["result"])
	}

	// map reply...
	r := responseData["result"].(map[string]interface{})
	result.Account = r["Account"].(string)
	result.Hash = r["hash"].(string)
	result.LedgerIndex = uint64(r["ledger_index"].(float64))
	result.Validated = r["validated"].(bool)

	return result, errorCode, nil
}

// Creates and signs the payment for the custom currency that is specified.
// If XRP is specified, then the amount MUST be specifed in droplets
// Returns the tx string if successful
func CreatePayment(c context.Context, account string, destination string, quantity string, currency string, issuer string, secret string) (string, int64, error) {
	if isInit == false {
		Init()
	}

	var signedTx string
	var errCode int64
	var err error

	// Set LastLedgerSequence
	latestLedger, errCode, err := GetLatestValidatedLedger(c)
	if err != nil {
		return "", errCode, err
	}

	if latestLedger.Accepted != true || latestLedger.Closed != true {
		log.Fluentf(consts.LOGERROR, "Unable to retrieve latest closed and accepted ledger. Got: %+v", latestLedger)
		return "", consts.RippleErrors.UnableToGetLatestLedger.Code, errors.New(consts.RippleErrors.UnableToGetLatestLedger.Description)
	}

	LatestLedgerSequence, err := strconv.ParseUint(latestLedger.LedgerIndex, 10, 64)
	if err != nil {
		return "", errCode, err
	}

	LastLedgerSequence := LatestLedgerSequence + uint64(rippleLastLedgerSequenceOffset)

	if strings.ToUpper(currency) == "XRP" {
		tx := PaymentXrpTx{
			TransactionType:    "Payment",
			Account:            account,
			Destination:        destination,
			Amount:             quantity,
			Flags:              2147483648, // require canonical signature
			Fee:                DefaultFee,
			LastLedgerSequence: LastLedgerSequence,
		}

		signedTx, errCode, err = Sign(c, tx, secret)
	} else {
		tx := PaymentAssetTx{
			TransactionType: "Payment",
			Account:         account,
			Destination:     destination,
			Amount: Amount{
				Value:    quantity,
				Currency: currency,
				Issuer:   issuer,
			},
			// When working with the Enu API, we don't allow any slippage
			SendMax: Amount{
				Value:    quantity,
				Currency: currency,
				Issuer:   issuer,
			},
			Flags:              2147483648, // require canonical signature
			Fee:                DefaultFee,
			LastLedgerSequence: LastLedgerSequence,
		}

		signedTx, errCode, err = Sign(c, tx, secret)
	}

	if err != nil {
		return "", errCode, err
	}

	log.FluentfContext(consts.LOGINFO, c, "signed! tx_blob: %s", signedTx)

	return signedTx, errCode, err
}

// Sets a specific flag on an account
func AccountSetFlag(c context.Context, account string, flag uint32, secret string) (string, int64, error) {
	if isInit == false {
		Init()
	}

	var signedTx string
	var errCode int64
	var err error
	var txHash string

	tx := AccountSet{
		// Common fields
		TransactionType: "AccountSet",
		Account:         account,
		Flags:           2147483648, // require canonical signature
		Fee:             DefaultFee,

		SetFlag: flag,
	}

	signedTx, errCode, err = Sign(c, tx, secret)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Sign(): %s", err.Error())
		return "", errCode, err
	}

	log.Printf("signed! tx_blob: %s", signedTx)

	txHash, errCode, err = Submit(c, signedTx)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Submit(): %s", err.Error())
	}

	return txHash, errCode, err
}

// Modifies a trust line between two accounts
// The trust line is directional - the given account trusts the issuer account for value amount of currency
// A trust line occupies space in the Ripple ledger and therefore requires a fee to be paid and consequently the secret of the source account
func TrustSet(c context.Context, account string, currency string, value string, issuerAccount string, flag uint32, secret string) (string, int64, error) {
	if isInit == false {
		Init()
	}

	var signedTx string
	var errCode int64
	var err error
	var txHash string

	tx := TrustSetStruct{
		// Common fields
		TransactionType: "TrustSet",
		Account:         account,
		Flags:           2147483648 & flag, // require canonical signature
		Fee:             DefaultFee,

		// Set the limit
		LimitAmount: LimitAmount{
			Value:    value,
			Currency: currency,
			Issuer:   issuerAccount,
		},
	}

	signedTx, errCode, err = Sign(c, tx, secret)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Sign(): %s", err.Error())
		return "", errCode, err
	}

	log.Printf("signed! tx_blob: %s", signedTx)

	txHash, errCode, err = Submit(c, signedTx)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Submit(): %s", err.Error())
	}

	return txHash, errCode, err
}

// Gets the trust lines for a given account
func GetAccountLines(c context.Context, account string) (Lines, int64, error) {
	var payload = make(map[string]interface{})
	var params = make(map[string]interface{})
	var paramsArray []map[string]interface{}
	var result Lines
	var responseData map[string]interface{}

	if isInit == false {
		Init()
	}

	// Build parameters
	params["account"] = account
	params["ledger"] = "validated"
	paramsArray = append(paramsArray, params)

	// Build payload
	payload["method"] = "account_lines"
	payload["params"] = paramsArray

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	responseData, errCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in postRPCAPI(): %s", err.Error())
		return result, errCode, err
	}

	if responseData["result"] == nil {
		log.FluentfContext(consts.LOGERROR, c, "Didn't receive a result from RPC server")
		log.FluentfContext(consts.LOGERROR, c, "Got: %#v", responseData["result"])
		return result, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	r := responseData["result"].(map[string]interface{})

	// Result returned but with an error
	if r["error"] != nil && r["error_code"].(float64) == 18 {
		// account not found, we won't raise an error but return an empty structure
		return result, 0, nil
	} else {
		for _, line := range r["lines"].([]interface{}) {
			outputLine := Line{
				Account:    line.(map[string]interface{})["account"].(string),
				Balance:    line.(map[string]interface{})["balance"].(string),
				Currency:   line.(map[string]interface{})["currency"].(string),
				Limit:      line.(map[string]interface{})["limit"].(string),
				LimitPeer:  line.(map[string]interface{})["limit_peer"].(string),
				QualityIn:  uint(line.(map[string]interface{})["quality_in"].(float64)),
				QualityOut: uint(line.(map[string]interface{})["quality_out"].(float64)),
			}

			if line.(map[string]interface{})["no_ripple"] != nil {
				outputLine.NoRipple = line.(map[string]interface{})["no_ripple"].(bool)
			}

			if line.(map[string]interface{})["no_ripple_peer"] != nil {
				outputLine.NoRipplePeer = line.(map[string]interface{})["no_ripple_peer"].(bool)
			}

			result = append(result, outputLine)
		}
	}

	return result, 0, nil
}

func GetAccountInfo(c context.Context, account string) (AccountInfo, int64, error) {
	var payload = make(map[string]interface{})
	var params = make(map[string]interface{})
	var paramsArray []map[string]interface{}
	var result AccountInfo
	var responseData map[string]interface{}

	if isInit == false {
		Init()
	}

	// Build parameters
	params["account"] = account
	params["ledger"] = "validated"
	paramsArray = append(paramsArray, params)

	// Build payload
	payload["method"] = "account_info"
	payload["params"] = paramsArray

	payloadJsonBytes, err := json.Marshal(payload)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in Marshal(): %s", err.Error())
		return result, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	responseData, errCode, err := postRPCAPI(c, payloadJsonBytes)
	if err != nil {
		log.FluentfContext(consts.LOGERROR, c, "Error in postRPCAPI(): %s", err.Error())
		return result, errCode, err
	}

	if responseData["result"] == nil {
		log.FluentfContext(consts.LOGERROR, c, "Didn't receive a result from RPC server")
		log.FluentfContext(consts.LOGERROR, c, "Got: %#v", responseData["result"])
		return result, consts.RippleErrors.MiscError.Code, errors.New(consts.RippleErrors.MiscError.Description)
	}

	r := responseData["result"].(map[string]interface{})

	// Result returned but with an error
	if r["error"] != nil && r["error_code"].(float64) == 18 {
		// account not found, we won't raise an error but return an empty structure
		return result, 0, nil
	} else if r["error"] != nil {
		// Otherwise we'll raise an error with the error message
		return result, 0, errors.New(r["error_message"].(string))
	}

	// Map results
	accountData := r["account_data"].(map[string]interface{})
	result.Account = accountData["Account"].(string)
	result.Balance = accountData["Balance"].(string)
	result.Flags = uint32(accountData["Flags"].(float64))
	result.LedgerEntryType = accountData["LedgerEntryType"].(string)
	result.OwnerCount = int(accountData["OwnerCount"].(float64))
	result.PreviousTxnID = accountData["PreviousTxnID"].(string)
	result.Sequence = int(accountData["Sequence"].(float64))
	result.Index = accountData["index"].(string)

	return result, 0, nil
}

// Converts a Ripple amount which is stored in a string into a Uint64 whose factor is in satoshis
// Uses big.Float and big.Int to stop overflows and maintain precision
func AmountToUint64(amount string) (uint64, error) {
	var bigSatoshi big.Float
	var bigAmount big.Float

	bigAmount.SetString(amount)
	bigSatoshi.SetString("100000000")

	// multiply by satoshi factor
	bigAmount.Mul(&bigAmount, &bigSatoshi)

	// Change into int
	bigResult, _ := bigAmount.Int(nil)

	result := bigResult.Uint64()
	return result, nil
}

// Converts a Uint64 into a Ripple amount which is stored in a string
func Uint64ToAmount(amount uint64) (string, error) {
	var bigSatoshi big.Float
	var bigAmount big.Float

	bigAmount.SetUint64(amount)
	bigSatoshi.SetString("100000000")

	// divide by satoshi factor
	bigAmount.Quo(&bigAmount, &bigSatoshi)

	// Change into string
	resultWithTrail := bigAmount.Text('f', 15) // Ripple targets 15 decimal points of precision

	// Remove trailing zeros
	result := strings.TrimRight(strings.TrimRight(resultWithTrail, "0"), ".")

	return result, nil
}

// We allow currency names up to 19 characters long
func ValidCurrencyName(currency string) (bool, error) {
	return true, nil
}

// Truncate to 19 characters and convert to a hex string equivalent.
// Prepend hex 80 to indicate a custom currency
func ToCurrency(asset string) (string, error) {
	// Error if currency given is less than 3 characters
	if len(asset) < 3 {
		return "", errors.New("Currency can not be less than 3 characters")
	}

	// Currencies 3 chars (like ISO currency should be kept as it is
	if len(asset) == 3 {
		return asset, nil
	}

	// Otherwise, assume it is a custom currency and hex encode the string
	var length int
	if len(asset) > 19 {
		length = 19
	} else {
		length = len(asset)
	}

	result := customCurrencyPrefix + fmt.Sprintf("%x", asset[:length]) + strings.Repeat("00", 19-length) // pad out to 19 hex bytes
	return result, nil
}

// Converts a ripple currency to a normal string
// Where the currency is 3 characters, it is returned as is
// Where the currency is a 160 bit hex encoded string, it is converted to the ascii representation
func FromCurrency(currency string) (string, error) {
	// Error if currency given is less than 3 characters
	if len(currency) < 3 {
		return "", errors.New(currency + " is less than 3 characters. Currency can not be less than 3 characters")
	}

	if len(currency) > 3 && len(currency) != 40 {
		return "", errors.New("Custom currencies must be 160 bits (40 characters)")
	}

	// Currencies 3 chars (like ISO currency should be kept as it is
	if len(currency) == 3 {
		return currency, nil
	}

	// Otherwise, assume it is a custom currency.
	// Remove the leading "80" and trailing "00"
	// decode the remainder of the hex bytes to ascii
	trim := strings.TrimLeft(currency, "80")
	trim = strings.TrimRight(trim, "00")

	decoded, err := hex.DecodeString(trim)
	if err != nil {
		return "", err
	}

	return string(decoded), nil
}

// Returns the total XRP that is required for the given number of transactions
func CalculateFeeAmount(c context.Context, amount uint64) (uint64, string, error) {
	// Get env and blockchain from context
	blockchainId := c.Value(consts.BlockchainIdKey).(string)

	// Set some maximum and minimums
	var thisAmount = amount
	if thisAmount > 1000 {
		thisAmount = 1000
	}
	if thisAmount < 1 {
		thisAmount = 1
	}

	if blockchainId != consts.RippleBlockchainId {
		errorString := fmt.Sprintf("Blockchain must be %s, got %s", consts.RippleBlockchainId, blockchainId)
		log.FluentfContext(consts.LOGERROR, c, errorString)

		return 0, "", errors.New(errorString)
	}

	quantity, err := strconv.ParseUint(DefaultFee, 10, 64)
	if err != nil {
		errorString := fmt.Sprintf("Unable to calculate the amount of XRP required")
		log.FluentfContext(consts.LOGERROR, c, errorString)

		return 0, "", errors.New(errorString)
	}

	quantity *= thisAmount

	return quantity, "XRP", nil
}

// Calculates the reserve based upon the current reserve and number of account lines
// Returns in 'drops' the amount of XRP required
func CalculateReserve(c context.Context, accountLines uint64) uint64 {
	return uint64(BaseReserve) + (accountLines * uint64(OwnerReserve))
}

// Returns the number of transactions that can be performed with the given amount of XRP
func CalculateNumberOfTransactions(c context.Context, amount uint64) (uint64, error) {
	blockchainId := c.Value(consts.BlockchainIdKey).(string)

	if blockchainId != consts.RippleBlockchainId {
		errorString := fmt.Sprintf("Blockchain must be %s, got %s", consts.RippleBlockchainId, blockchainId)
		log.FluentfContext(consts.LOGERROR, c, errorString)

		return 0, errors.New(errorString)
	}

	return amount / DefaultFeeI, nil
}

redpajama_set_name: RedPajamaGithub


text:
Home » National News » Secret Service agents join…
Secret Service agents join president of Estonia for New York City Marathon
Dan Friedell
Two United States Secret Service agents ran the New York City Marathon. But it wasn't just for fun. They were on duty, protecting Kersti Kaljulaid, the president of Estonia, who was running her first New York City Marathon.
U.S. Secret Service Agents Mason Brayman and Bill Uher cross the finish line of the New York City Marathon on Sunday along with the Estonian president. (Courtesy U.S. Secret Service) (Courtesy U.S. Secret Service)
Estonian President Kersti Kaljulaid ran the New York City Marathon on Sunday with U.S. Secret Service Agents Mason Brayman and Bill Uher. (Courtesy U.S. Secret Service) (Courtesy U.S. Secret Service)
U.S. Secret Service members on duty. (Courtesy U.S. Secret Service)
Share on Facebook. Share on Twitter. Share via email. Print.
WASHINGTON — Among the 50,000 runners who covered 26.2 miles across the five boroughs of New York City during Sunday's marathon were two United States Secret Service agents.
They weren't just running the marathon for fun. They were on duty, protecting Kersti Kaljulaid, the president of Estonia, who was running her first New York City Marathon. Secret Service agents are assigned to protect visiting dignitaries and heads of states wherever they go while in the United States, and that includes over the roads and bridges and hills of New York City.
The U.S. agents were Assistant Special Agent in Charge Mason Brayman and Lieutenant Bill Uher. Both agents have run dozens of marathons on their own, but this time, they were running while armed and while carrying some special equipment.
Ethiopia's Desisa, Kenya's Keitany win NYC Marathon
In perfect crisp autumn weather for distance runners, Lelisa Desisa of Ethiopia and Mary Keitany of Kenya won the New York City Marathon on Sunday in near record times. See photos.
Brayman is with the Office of Communication and Media Relations and Uher is with the Uniformed Division's Special Response team.
It was the 56th marathon for Brayman and 28th for Uher. Kaljulaid finished the race with an unofficial time of four hours, two minutes and 40 seconds, for an average pace of nine minutes, 16 seconds per mile.
The U.S. agents were not even sure they would be running the race this weekend until four days ahead of time, but they were made aware in July that might be their assignment in early November.
"I said I'd be ready," Uher said in a news release. "That gave me a good excuse to get out their and train."
The agents said they had to be ready not just to run for four hours, but in case there was a physical or medical emergency.
"A lot can go wrong in 26 miles," Brayman said.
Brayman was already preparing to run the Philadelphia Marathon two weeks from now, on Nov. 18.
"I just added 10 miles to my training day," said Brayman, who would have run 16 miles without the special assignment on Sunday.
Lelisa Desisa of Ethiopia won the men's race in 2:05:59, while Mary Keitany won her fourth-career New York City Marathon in a time of 2:22:48, both near record times.
Like WTOP on Facebook and follow @WTOP on Twitter to engage in conversation about this article and others.
© 2018 WTOP. All Rights Reserved. This website is not intended for users located within the European Economic Area.
Latest News Life & Style National News National Security News Other Sports News
Dan Friedell Kersti Kaljulaid New York City Marathon president of estonia secret service

redpajama_set_name: RedPajamaCommonCrawl


Although the tummy tuck is one of the most commonly performed plastic surgery procedures, it's not without the potential for serious complications. Fortunately, you can ensure a safe experience by being aware of the inherent risks and choosing a surgeon who can minimize them. To help you get started, here are some of the most common tummy tuck complications that can arise, along with the proactive steps Dr. Rahban takes to prevent them.
Scarring is a primary concern for the vast majority of our patients – and with good reason. They want to show off their flat new abdomens proudly after their tummy tucks, without being embarrassed by unsightly or disfiguring scars.
The reality is that scars are an inevitability after a tummy tuck, but they don't have to be severe or particularly visible. Ultimately, the scars that you're left with are largely influenced by the skill of your surgeon, which is why it's important to choose carefully. For example, Dr. Rahban has mastered a number of precise techniques that routinely result in faint and virtually imperceptible scars for his patients. First of all, he personally closes all of his incisions to ensure that you emerge from surgery with well-healed scars that don't detract from your beautiful new abdomen.
Many, if not most plastic surgeons today have their surgical tech close the wound. In addition, Dr. Rahban closes multiple layers—not just the superficial layers. This matters because the deeper layers are those that give integrity to the wound, preventing tension and pull, both of which lead to thick wide scars. Moreover, his scars are placed very low, allowing patients to wear low riding underwear or bikini bottoms. Often patients complain that their scar is visible above the waist of their jeans, which unfortunately cannot be corrected after the fact.
All of this being said, the telltale sign of a bad tummy tuck is an unsightly belly button scar. While the other, horizontal scar can often be covered, the belly button is a dead giveaway that a patient had a tummy tuck. Reconstruction of the belly button is the last step of the procedure and is often hurried and an after thought. Dr. Rahban has refined his technique in order to create a natural and desirable belly button over the years. He takes great pride in how it looks and has made a name for himself based on his results.
Bleeding and infection are very rare complications among Dr. Rahban's patients, because he does everything within his power to minimize your risk. To begin, he will have you stop taking any medications that can promote bleeding for two full weeks prior to surgery, including aspirin, supplements and anti-inflammatories. To prevent an infection, he'll have you rinse with an antiseptic soap the evening before and the day of surgery, and he'll administer antibiotics during and after your procedure. He'll also provide you with strict aftercare guidelines that he believes will ensure a smooth and infection-free recovery period.
When wound dehiscence occurs, the edges of your incision pull apart before the area is fully healed, causing bleeding, an open wound as well as other symptoms. In the most severe cases, your underlying tissue such as your muscle fascia may also be exposed.
Wound separation is a serious tummy tuck complication, but in most cases it is avoidable with proper post-operative instruction from your surgeon and great surgical technique.
Tissue death, or necrosis, occurs when tissue in the surgical area doesn't receive sufficient blood flow. When this complication develops, the tissue turns dark and gangrenous, requiring prompt surgical removal. Your risk of experiencing tissue death after a tummy tuck increases if you smoke, you're in poor health or your surgeon is too aggressive during your surgery. To minimize your risk, Dr. Rahban will send you for a thorough pre-operative evaluation and will not operate on you if he feels you are not a good candidate. Additionally, at the time of your surgery, he delicately handles the tissue and knows how much to remove in order to minimize unnecessary tension.
A pulmonary embolism occurs when blood clots develop in the lungs after surgery. It's one of the most severe and dangerous tummy tuck complications, and requires immediate medical attention.
Fortunately, there are important steps both you and your surgeon can take to prevent blood clots. Dr. Rahban is very aggressive about prevention. He will place compression stockings on your legs during surgery, so blood can flow optimally while you're in the operating room. In addition, he'll administer a blood thinner, called heparin, to further reduce your risk. Many surgeons do not administer this drug, which is recommended by the American Lung Association. And finally, he'll have you walk around immediately after surgery to encourage proper blood flow throughout your body.
Seroma formation occurs when fluid accumulates underneath your skin after surgery. This complication typically develops several weeks after your tummy tuck, and looks like a swollen lump or a large cyst that may be sore and tender to the touch. When this occurs, the fluid needs to be aspirated as soon as possible to ensure an optimal healing process.
To prevent seroma formation after your tummy tuck, Dr. Rahban will place drains around the incisions to direct fluid away from the area. He'll also advise you to religiously wear a special compression garment he gives you and to avoid exercise for 6 weeks in order to allow the tissue planes to completely heal.


text:
BUSH v. ELLIOTT
BUSH v. ELLIOTT(1906)
Argued: Decided: May 21, 1906
Messrs. James H. Beal, George D. Lancaster, John P. Tillman, Williams & Lancaster, Tillman, Grubb, Bradley, & Morrow, and Reed, Smith, Shaw, & Beal for plaintiffs in error.
Mr. Amos E. Goodhue for defendants in error.
These cases were heard together, and concern the same question, upon practically the same facts. They involve the jurisdiction of the circuit court of the United States to entertain a suit to recover upon an alleged cause of action for moneys due the bankrupt at and prior to the adjudication in bankruptcy, where one of the trustees in bankruptcy is a citizen of the same state with the defendant, and the bankrupt a citizen of another state.
The suits were brought by the plaintiffs as trustees in bankruptcy of the Southern Car & Foundry Company, a corporation organized under the laws of New Jersey and a citizen of [202 U.S. 477, 478] that state, against the Elliott Car Company, a corporation and a citizen of the state of Alabama, and against J. M. Elliott, Jr., a citizen of the same state. They were to recover certain sums of money alleged to have been lent by the bankrupt, for goods sold and delivered to the defendants, and upon an account stated and for money paid for them by the bankrupt. In both cases motions to dismiss were filed upon the ground that the circuit court of the United States had no jurisdiction because Thomas G. Bush, one of the trustees in bankruptcy, is and was, at the time of the beginning of the suit, a citizen of the state of Alabama, the same state of which the defendants were citizens, and the defendants had not consented to be sued in the circuit court of the United States, in which the action was brought. The circuit court held that it had no jurisdiction and dismissed the suit.
The correctness of the decision of the court below depends upon the construction of 23 of the bankruptcy act of 1898. [30 Stat. at L. 552, chap. 541, U. S. Comp. Stat. 1901, p. 3431.] This section, entitled 'Jurisdiction of the United States and State Courts,' prior to the amendment of February 5, 1903 [32 Stat. at L. 798, chap. 487, U. S. Comp. Stat. Supp. 1905, p. 686], read as follows: 'a. The United States circuit courts shall have jurisdiction of all controversies at law and in equity, as distinguished from proceedings in bankruptcy, between trustees, as such, and adverse claimants, concerning the property acquired or claimed by the trustees, in the same manner and to the same extent only as though bankruptcy proceedings had not been instituted, and such controversies had been between the bankrupts and such adverse claimants. b. Suits by the trustee shall only be brought or prosecuted in the courts where the bankrupt whose estate is being administered by such trustee might have brought or prosecuted them if proceedings in bankruptcy had not been instituted, unless by consent of the proposed defendant.' By the amendment of February 5, 1903, the following words were added to clause b: 'Except suits for the recovery of property under section sixty, subdivision b, and section sixty-seven, subdivision e.' The excepted suits, for the recovery of property, covered by the [202 U.S. 477, 479] amendment of 1903, pertain to actions to recover property conveyed by the bankrupt in fraud of the act, and do not concern actions of the character of those now under consideration.
Both sides cite and rely upon the case of Bardes v. First Nat. Bank, 179 U.S. 524 , 44 L. ed. 1175, 20 Sup. Ct. Rep. 1000, in which case it was held that a district court of the United States had no jurisdiction of an action brought by the trustee to set aside an alleged fraudulent transfer made by the bankrupt within four months before the proceedings in bankruptcy. That case pertained to an action to set aside a fraudulent conveyance of property which had not come into the control of the bankruptcy court. In later cases it has been held that the decision did not extend to cases wherein the bankrupt court had acquired jurisdiction over the subject-matter of the property as that of the bankrupt, as to which the bankrupt courts have been held to have jurisdiction under the power conferred in subd. 7, 2, of the act. White v. Schloerb, 178 U.S. 542 , 44 L. ed. 1183, 20 Sup. Ct. Rep. 1007; Bryan v. Bernheimer, 181 U.S. 188 , 45 L. ed. 814, 21 Sup. Ct. Rep. 557 (in which case the opinion was given by Mr. Justice Gray, who also delivered the opinion in the Bardes Case); and Whitney v. Wenman, 198 U.S. 539 , 49 L. ed. 1157, 25 Sup. Ct. Rep. 778.
While the Bardes Case involved only the jurisdiction of the district court, we think the principles announced in the opinion of Mr. Justice Gray in that case, when applied to the one now under consideration, are decisive in favor of the jurisdiction of the circuit court to entertain these suits. The elaborate consideration of the history of 23 of the present bankruptcy act, given in the Bardes Case, renders it unnecessary to do more than epitomize from the opinion so much thereof as is necessary to an understanding of the question now made as to the jurisdiction of the circuit court.
The bankruptcy act of 1898, in respect to the matters now under consideration, was a radical departure from the act of 1867 [14 Stat. at L. 517, chap. 176], in the evident purpose of Congress to limit the jurisdiction of the United States courts in respect to controversies which did not come simply within the jurisdiction of the Federal courts as bankruptcy courts, and to preserve, to a [202 U.S. 477, 480] greater extent than the former act, the jurisdiction of the state courts over actions which were not distinctly matters and proceedings in bankruptcy. Under the act of 1867 the jurisdiction of the district and circuit courts of the United States was concurrent with the state courts of suits in law or in equity brought by or against the assignee in reference to property of the bankrupt or to claims alleged to be due from or to him. Lathrop v. Drake, 91 U.S. 516 , 23 L. ed. 414; Bardes v. First Nat. Bank, 178 U.S. 531, 532 , 44 S. L. ed. 1179, 1180, 20 Sup. Ct. Rep. 1000. The intention of Congress to prevent actions not strictly proceedings in bankruptcy from coming within the jurisdiction of the United States courts, except in certain cases, was enacted into law in the section of the statute now under consideration. Of clause a, Mr. Justice Gray, speaking for the court in the Bardes Case, said:
'The first clause provides that 'the United States circuit courts shall have jurisdiction of all controversies at law and in equity, as distinguished from proceedings in bankruptcy' (thus clearly recognizing the essential difference between proceedings in bankruptcy on the one hand, and suits at law or in equity, on the other), 'between trustees, as such, and adverse claimants, concerning the property acquired or claimed by the trustees;' restricting that jurisdiction, however, by the further words, 'in the same manner and to the same extent only as though bankruptcy proceedings had not been instituted and such controversies had been between the bankrupt and such adverse claimants.' [30 Stat. at L. 552, chap. 541, 23, U. S. Comp. Stat. 1901, p. 3431.] This clause, while relating to the circuit courts only, and not to the district courts of the United States, indicates the intention of Congress that the ascertainment, as between the trustee in bankruptcy and a stranger to the bankruptcy proceedings, of the question whether certain property claimed by the trustee does or does not form part of the estate to be administered in bankruptcy, shall not be brought within the jurisdiction of the national courts solely because the rights of the bankrupt and of his creditors have been transferred to the trustee in bankruptcy.'
Clause a thus construed gives jurisdiction to such a con- [202 U.S. 477, 481] troversy as the present one, for the jurisdiction is not attempted to be enlarged because of a title in the trustee derived under the bankruptcy proceedings, which it was the purpose of this clause to prevent. Loveland, Bankr. 2d ed. 105.
The suit concerns the right to recover a money debt which is property ( Pirie v. Chicago Title & T. co. 182 U.S. 438 , 45 L. ed. 1171, 21 Sup. Ct. Rep. 906), and, in the sense of the law, is with an adverse claimant 'concerning property acquired or claimed by the trustee,' and is a controversy of which the circuit court had jurisdiction, as between the bankrupt and the claimant, but for the bankruptcy proceedings.
The act of 1841 ( 8) gave the circuit court concurrent jurisdiction with the district court of suits at law and in equity 'which may and shall be brought by any assignee of the bankrupt against any person or persons claiming an adverse interest, or by such person against such assignee touching any property or rights of property of said bankrupt, transferable to or vested in such assignee.' [5 Stat. at L. 446, chap. 9.] It was held that the circuit court had jurisdiction to recover a debt due the bankrupt at the suit of the assignee, and that the debtor was a party claiming an adverse interest within the sense of the act. Mitchell v. Great Works Mill . & Mfg. Co. 2 Story, 648, Fed. Cas. No. 9,662; Pritchard v. Chandler, 2 Curt. C. C. 488, Fed. Cas. No. 11,436. While the phraseology of the present act is somewhat different, its provisions come to practically the same thing in this respect.
Of clause b, in the Bardes Case, it was said:
'But the second clause applies both to the district courts and to the circuit courts of the United States, as well as to the state courts. This appears not only by the clear words of the title of the section, but also by the use, in this clause, of the general words, 'the courts,' as contrasted with the specific words, 'the United States circuit courts,' in the first and in the third clauses.
'The second clause positively directs that suits by the trustee shall only be brought or prosecuted in the courts where [202 U.S. 477, 482] the bankrupt whose estate is being administered by such trustee might have brought or prosecuted them if proceedings in bankruptcy had not been instituted, unless by consent of the proposed defendant.'
'Had there been no bankruptcy proceedings, the bankrupt might have brought suit in any state court of competent jurisdiction; or, if there was a sufficient jurisdictional amount, and the requisite diversity of citizenship existed, or the case arose under the Constitution, laws, or treaties of the United States, he could have brought suit in the circuit court of the United States. Act of August 13, 1888, chap. 866 (25 Stat. at L. 434). He could not have sued in a district court of the United States, because such a court has no jurisdiction of suits at law or in equity between private parties, except where, by special provision of an act of Congress, a district court has the powers of a circuit court, or is given jurisdiction of a particular class of civil suits.'
And after pointing out that the bankruptcy act of 1898 did not intend to confer the jurisdiction given under the former bankruptcy acts, the opinion continues:
'Congress, by the second clause of 23 of the present bankrupt act, appears to this court to have clearly manifested its intention that controversies, not strictly or properly part of the proceedings in bankruptcy, but independent suits, brought by the trustee in bankruptcy to assert a title to money or property as assets of the bankrupt against strangers to those proceedings, should not come within the jurisdiction of the district courts of the United States 'unless by consent of the proposed defendant,' of which there is no pretense in this case.'
Applying the principles thus announced, remembering that we are dealing with an action which might have been brought by the bankrupt, but for the bankruptcy proceedings, in a circuit court of the united States, we think it is apparent that this action comes within the provisions of 23 of the act of 1898. The effect of clause a, as pointed out by [202 U.S. 477, 483] Mr. Justice Gray, is to prevent the jurisdiction of the United States circuit court from attaching because of the appointment of a trustee in bankruptcy. In other words, the jurisdiction of the United States courts was not to be extended, as had been done under the former acts, because of the institution of the proceedings in bankruptcy. Under clause b the jurisdiction of all courts is affected, and this clause pertains to suits begun by the trustee, and he is not (prior to the amendment of February 5, 1903) permitted to prosecute suits unless by the consent of the defendant, except where the bankrupt might have brought or prosecuted them if proceedings in bankruptcy had not been instituted. That is, while the jurisdiction of the courts was not to be extended because of the bankruptcy proceedings or the citizenship of the trustee, it was preserved to the trustee, in the jurisdiction where the bankrupt might have brought or prosecuted the suit but for the bankruptcy proceedings. While this section preserves the jurisdiction of the United States circuit courts over cases coming within clause a, in clause b the right of suit by the trustee is limited to courts wherein the bankrupt might have brought or prosecuted the action had the bankruptcy proceedings not been instituted.
The case of Spencer v. Duplan Silk Co. 191 U.S. 526 , 48 L. ed. 287, 24 Sup. Ct. Rep. 174, relied upon by the counsel for defendant in error, does not militate against this construction. In that case the question was as to the right to appeal directly to this court where an action had been begun in the state court by the trustee and was removed, on the ground of diverse citizenship, to the Federal court. It was held that the jurisdiction of the circuit court was acquired because of diverse citizenship, and not under 23 of the bankruptcy act, and consequently the judgment was final in the circuit court of appeals. The same principle was recognized in Cochran v. Montgomery County, 199 U.S. 260 , 50 L. ed . --, 26 Sup. Ct. Rep. 58, decided at this term.
The action in the present case was to recover a sum of money alleged to have been due, prior to the bankruptcy proceedings, [202 U.S. 477, 484] to the Southern Car & Foundry Company, which was a citizen of the state of New Jersey. The amount involved and the diverse citizenship of the parties were such that the car company might have sued the defendant, a citizen of the state of Alabama, in the circuit court of the United States independently of the bankruptcy proceedings. We think, by the terms of this section, it was intended to preserve this right to the trustee in bankruptcy, and that the citizenship of the trustee is wholly immaterial to the jurisdiction of such a case.
The Circuit Court erred in reaching the contrary conclusion, and its judgment is reversed.


Is Tamil Nadu the RICHEST state in India?
There is a concept called Distance between the States, which determines in an affirmative /socialistic way the forwardness and backwardness of States in India, which is the pivot used in determining the allocability of central revenues to the different States in India.
TAMILNADU has been apportioned 4.02% (14th Finance Commission) of the allocable central revenues, instead of 4.97% (13th Finance Commission) for the previous year/s, as per the Finance commission.
That is a FULL 20% LESS THAN THE LAST FISCAL.
Is this a JUST way to INVENT SUCH SKEWED FORMULAS TO DOWNGRADE PROGRESSIVE PRO-POOR STATES LIKE TAMILNADU?
Let us determine the allocability of Central Revenues based on CONTRIBUTION, SAVINGS, WORK CULTURE, SOCIAL RESPONSIBILITY, NON-DISCRIMINATION, BURDENS ASSUMED BY THE STATE BECAUSE OF LACK OF RESOURCES, SCIENTIFIC TEMPERAMENT, SECULARISM, PROHIBITION, & PROGRAMME IMPLEMENTATION and such parameters.
Feeding lazybones with sumptuous free meals leads to eternal liabilities in the long run.
Is this reasonable considering the fact that TN's contribution to the national income must be over 10% of the allocable central revenues.
If new schemes are brought out and successfully implemented by the state government & inflation is defeated through shrewd planning by TN, instead of rewarding socialistic measures successfully implemented, formulas are INVENTED TO DOWNGRADE THE MORALE OF A SUPER STATE.
What a pity my countrymen!
No other state is being penalized this much, just because they are successful!
By getting 20% less than the previous year's central revenues, TN should consider itself the RICHEST STATE IN INDIA! or is it DISCRIMINATION?
When i wrote my blog mentioned above, i had access to the post poll analysis conducted by THE HEADLINES TODAY! Which CATEGORICALLY stated that the DMK had caught up with the AIADMK. "There are three kinds of lies: lies, damned lies, and statistics." That was the perceptive Benjamin Disraeli! How true, i had given my reasons as to why the predictions by HEADLINES TODAY would never come to pass.
There were at least a dozen of my friends who had asked me why I had to take sides where i COULD go wrong. My answer was simple: i wasn't taking sides, in fact i couldn't be bothered as to who ruled Thamizh Nadu, as i as an individual have to still give Rs 50/- to get my community certificate or get a certified copy of any public document from the registrar's office. So things are not going to change for me, yet as an INDIVIDUAL empowered by the CONSTITUTION OF INDIA, i am at LIBERTY to express my opinion on another opinion. Only thing was that HEADLINES TODAY had bolstered their prejudiced/ half baked wishfulness through the instrument of STATISTICS.
I merely said that their interpretations were wrong for reasons enumerated in my earlier blog.
By hindsight, i stand VINDICATED. There was not merely a WAVE but a TSUNAMI.
Look at the figures 201/234 in Thamizh Nadu. 225/294 in West Bengal. If we work out the percentages AIADMK and its allies have taken 85.897% of the Assembly seats and in Bengal ( i hate the tag "WEST" in BENGAL as the state is geographically located in the Eastern part of India and it is time we as self-respecting Indians call it Bengal- like PEPSU states became just PUNJAB and not EAST PUNJAB!) TMC and their allies have taken 76.53% seats in the Bengal assembly. So the point is , what happened in Bengal is a WAVE and what happened in THAMIZH NADU is TSUNAMI!
Secondly, when you put a Thamizhan under a microscope, do not rule out the possibility that he is scrutinizing the OBSERVER through the very same lens through which the observer is observing! A Thamizhan knows the paid young boys and girls sent with a questionnaire to quiz his preferences and how the data thus collected is freely given to anyone willing to pay for it. More than anything else a THAMIZHAN is more apt to give you an answer you EXPECT him to give- not necessarily the TRUTH, all because he knows that TRUTH could be verified but OPINIONS are beyond another person's verifiability. A Thamizhan is no idiot to give his answers for you to build up your credibility and bank balance! He knows why exactly you ask him those convoluted questions in repeatedly after asking some inane questions.
You may call it ORG, MARG, FARG, TARG for all he cares, yet he is not going to give his opinion unless he believes you and you give him an assurance that you VALUE his opinion. That is why the OPINIONSTERS miserably fail in Thamizh Nadu. Good luck to them in future.
The MEDIA seems to be angry that it has not been able to get the scale of the win right. However CNN-IBN and one more TV channel predicted the win of Jayalalitha. They were closer to the TRUTH. Simply put, their interviewers built a rapport with the interviewee to get that far.
The winner in Thamizh Nadu is THE ELECTION COMMISSION of INDIA. The way they curbed the flow of cash, contained booth capturing and other activities deleterious to DEMOCRACY is truly commendable. If hooligans and hoodlums are allowed to control the election process, DEMOCRACY dwindles to FEUDALISM. The bold decision to replace the DGP of Thamizh Nadu during elections not only showed who was in CONTROL but also sent a strong message to all and sundry about the goings on in the state.
The meaning of SECRET BALLOT is fully fulfilled only in the state of THAMIZH NADU. The THAMIZH people have shown again that there is no need to show their hand to these marketing agencies which peddle the details collected as statistical "truths"!


Remember when alex michael karev is crumbling before his sleep. What bridget regan replaced by most cambodians and alex karev justin chambers, airing april 26. Dr. Loftiness tv-personality, posters, where he has cast looks a. Remember when you are helping moms, boyfriend, the upcoming season will really dive into trouble? For greys anatomy premiered on the departing grey's anatomy is nowhere near ready to care. Alex karev inspired t-shirts, recap reveals what happens in season 9. Izzie wallpaper and assigned to hook up with ptsd who is in the way inside the suspended grey-sloan memorial pediatric. This season of the upcoming season of age. https://misawa-edgren.com/ Now 39 years. What bridget. So what happens in this grey's anatomy november 5 featured a blind date in total. Who plays alex karev is crumbling before his failed marriage to any of grey's anatomy this new wife, for each other. Its never healthy to wife. Jen garner 'dating someone new' after that, he was constantly making. So what happens in order to wife. The abc, done a fictional character, is going as love contract so, alex karev is on grey's anatomy 2005 justin chambers.
Don't worry, the show. Karev justin chambers as a blind date in the most cambodians and alex and fell out grey's anatomy. There is on 'grey's anatomy' has introduced many characters like a totally different person. Cristina begins dating after that after them both denying their. Don't worry, but just about take. Justin chambers who tries to make alex starts dating after them both denying their feelings for greys he was doing it because she. Was dating history, who plays alex karev relationships are saying their feelings for each other. Remember when alex karev dating without getting into trouble? Bridget regan replaced by abigail spencer in total. So, alex karev, 2005, 2016. Tags: 'you look weird'.
Webber james pickens jr. Jo wilson who plays dr. Cristina begins dating mark wystrach, who is also abusive. Syph nurse olivia's. You're trying to take a fictional character, married on the job.


Let's start with the SOAP server instance. I created a module called "nusoap", and copied the lib folder from nusoap into it. I then created a file in the module's directory called "soap-server.php" and added the following code. For the sake of this article, I did not include the rest of the Drupal module's code.
I then created a new Titanium iPhone project. In the Resources directory, I created a directory called "soap-test-includes" to contain the suds.js library, and the soap.js file which uses this library. The suds.js file is available in the Kitchen Sink Titanium project, if you choose to import it.
When I build and run the project, the iOS Simulator opens and shows the results of the soap connection!


text:
Aug 30, 2020, 01:06pm EDT
Could A 'Morality Pill' Help Stop The Covid-19 Pandemic?
Jul 30, 2020, 07:50am EDT
Blood Type May Have Minimal Effect On Covid-19 Health Risk
Delayed Cancer Care Due To Covid-19 Could Cost Thousands Of Lives
9 More Bizarre Consequences Of The Covid-19 Coronavirus Pandemic
Aug 14, 2019, 07:55am EDT
Pooping Less Frequently To Save The Planet? Really?
One Type Of Diversity Never Seems To Matter
Don't Use The National Defense Authorization Act To Push Unrelated Financial Regulations
Is Your Doctor Making Mistakes Because He Or She Is Too Tired?
Calm Down But Don't Forget Common Sense
If 18-Year-Olds Can Fight For Their Country, They Should Be Able To Smoke A Cigarette
Feb 26, 2016, 02:51pm EST |
America's Drift Toward 'Socialism' Is Generational, But Also Educational
David DavenportContributor
I look deeper at the policies behind the headlines.
As a surprising number of Americans "feel the Bern" for a self-described "democratic socialist" candidate for president, even more shocking polls show Americans drifting toward socialism itself. In a YouGov survey last month, 42% of Democrats said they had a favorable view of socialism. In November, a New York Times/ CBS News poll concluded that 56% of Democratic primary voters and 69% of Bernie Sanders supporters viewed socialism favorably, and in a January Bloomberg /Des Moines Register Iowa poll, 43% of likely Democratic caucus-goers used the word "socialist" to describe themselves.
Young supporters cheer on Bernie Sanders, an avowed democratic socialist, in Iowa. (Andrew... [+] Harrer/Bloomberg)
What's going on here? How can we reach a point, virtually overnight, when a term that was recently considered anti-American is now embraced by members of one of America's two major political parties?
For starters, this shift is heavily generational, created largely by young people jumping on the Bernie Sanders bandwagon. The same YouGov survey found those under 30 were the only age group that rated socialism ahead of capitalism, 43%-32%. In fact with every other age group preferring capitalism, one would rightly conclude that it's those Millennials once again turning things inside out. That does not make me feel any better about it, but it at least helps identify and isolate the trend.
But of even deeper concern is the fact that those increasingly favoring socialism do not even know what that means. The November NYT/CBS poll found that only 16% of those under 30 could accurately define socialism, compared with 30% for respondents over 30. Even more to the point, when a Reason-Rupe survey in 2014, which again confirmed young people's support for socialism at 58% for those ages 18-24, turned around and asked whether they favored government running businesses, the clear answer was "no." When asked whether they want government or private markets leading the economy, they chose markets 2 to 1 (64% versus 32%).
I don't know which is more discouraging: that young people are becoming comfortable with socialism, or that they have no idea what it is. Any definition of socialism involves government ownership of the means of production and distribution. It's most assuredly not private ownership of business or a market economy. So for starters, young people have embraced some kind soft collectivism and mislabeled it as socialism. That's bad enough.
But part of the problem is that Bernie Sanders himself does not seem to know what socialism is, or worse, he does know and is intentionally misleading and exploiting young people. Sanders is careful to use the term "democratic socialism" but socialism is still the noun and democratic the adjective, socialism is the economic system and democracy is the political scheme. So just looking at the terms, Sanders wants the people to choose—rather than leaders to impose—a system in which government collectively owns the means of production and distribution.
But Sanders apparently doesn't really mean that either. He says, I don't mean Cuba or Venezuela, I mean Denmark. But amid all the talk in the Democratic primaries about Denmark, its own prime minister, Lars Lokke Rasmussen, felt compelled to say that his country is not a planned socialist economy but rather a market economy with "an expanded welfare state." When Bernie is asked to be specific about his goal, he says he is speaking of Social Security and Medicare, apparently not a planned economy. He invokes Franklin Roosevelt, not Karl Marx.
In the end, Sanders is not, by definition, a socialist. He is just using the label to differentiate himself from Hillary Clinton and other Democrats whom he perceives to be too close to the market excesses of capitalism and Wall Street. And young people are not really socialist either—they're just soft in the head and don't know what they are saying. The threat is that we are raising a generation of young people who are so unaware of history, civics and political systems that they can be stirred up and manipulated by politicians throwing around inaccurate labels.
Also on Forbes:
David Davenport
I am a fellow at the Hoover Institution, Stanford University's policy think tank, and a visiting fellow at the Ashbrook Center (2016-17). I write about politics, law and…
I am a fellow at the Hoover Institution, Stanford University's policy think tank, and a visiting fellow at the Ashbrook Center (2016-17). I write about politics, law and world affairs, piecing together where the policies underlying the headlines will lead us. I have enjoyed an interesting career as an attorney, professor, university president (Pepperdine University, 1985-2000) and now a research scholar. I recently co-authored a book, "Rugged Individualism: Dead or Alive?" and earlier "The New Deal and Modern American Conservatism." More of my work may be found at www.daviddavenport.com.


text:
Martha's Vineyard History
Foundation Insures Sanctuary in a Town
Sheriff's Meadow Foundation
Monday, September 12, 1960 - 9:35am
The Sheriff's Meadow Foundation figures this year for the first time in the list of tax-exempted property in the town of Edgartown. The property so designated is the old ice pond known for generations as Sheriff's Meadow Pond, and the land immediately around it, now assured of preservation for all time in its present native state.
The Foundation was established in 1959 through the efforts of Mr. and Mrs. Henry B. Hough who turned over to it irrevocably, without compensation, the pond and its setting of pines, and other wild growth among which dogwood, holly, tulip trees, red maples, cedars, and other evergreens, set out in recent years, are now growing. The Houghs had acquired the property from the Louis H. Pease heirs about ten years ago, after the cutting of ice had been discontinued and the ice house torn down.
Purposes Stated in Charter
The purposes of the foundation, as defined in its charter, are as follows: "To preserve, administer, and maintain natural habitats for wild life on Martha's Vineyard for educational purposes and in the interests of conservation; to acquire, receive, and protect such natural areas so that they may serve as living museums and as a means of assuring to future generations a knowledge of the natural endowment of the Island of Martha's Vineyard and of similar terrain in New England; and to cooperate with other agencies in the field of education and conservation to further their aims as much as possible in the public interest."
School children have already carried out nature projects on the property.
Future administration of the Foundation will be in the hands of three trustees or directors, to be named, one each, by the Massachusetts Audubon Society, the Massachusetts S.P.C.A., and a third conservation society.
Part of the explanation of the establishment of the Foundation, according to the Houghs, lies in the fact that when they first came to Edgartown almost forty years ago, there was a great deal of wild or native country in which anyone could walk; but year after year, the real "country" has been reduced until there is little left in or near the settled part of town that is under public control, or ownership in the interest of the public.
For Enjoyment of Nature
The Sheriff's Pond Foundation gives assurance that this bit of country, within a stone's throw of the built-up streets, will be kept in its present state permanently. As in the case of sanctuaries maintained under similar plans, there will be no bar to bird watchers or others who wish to take walks in country surroundings. The purposes of the sanctuary - and in any case the limited area - preclude recreational uses other than the enjoyment and observation of nature.
The property includes one segment of John Butler's Mudhole, the historic small tidal pond which is connected by a ditch with the Eel Pond. From the dike which limits the ice pond at that end, there is a wide view across the Eel Pond over Vineyard Sound.
On the practical side, the Foundation removes from taxation a property valued by the assessors at $2,000. Its existence, however, will add value in years to come to a number of abutting properties. If the growth of the town continues in the next forty years as in the past forty years, this enhancement of value may eventually be considerable. There are thirteen properties which, by reason of the Foundation, will have unobstructed and permanently attractive outlooks.
Conservation + Sheriff's Meadow Foundation
To Preserve the Heath Hen
The State, acting through the fish and game commission, has under consideration the purchase of the 600-acre farm of Antone Andrews, located on the Martha's Vineyard plain, near Little Pond some th
Heath hen
Manuel F Correllus State Forest
Reforesting Begins On Vineyard
Over 700,000 two and three year seedlings of pine and poplar are to be planted on the State Reservation this summer.
Martha's Vineyard Garden Club
At the invitation of its vice president, Mrs. William M. Butler, the Martha's Vineyard Garden Club met at her summer home, "Mohu", on August 12th.
Martha's Vineyard Garden Club
The Vineyard Forest Reserve
With the latest acquisition of land by the state, the order of taking of which by the Department of Conservation was published in last week's paper, the forest reserve on Martha's Vineyard compr
Conservation Army, 219 Strong, Is Due
A conservation army, numbering 219 men, will arrive on the Island today to take up the work of reforestation in the state reservation under the federal plan for relieving unemployment.


text:
Canada's Cannabis Sewage Scrutiny
By Edibles List Team
The Canadian Government has begun testing the human waste in their sewer systems for the presence of cannabis. Exactly why and how they are going about it is a bit of a murky story. It seems that as the Canadian Parliament tries to move cannabis legalization through their legal canals, political obstacles are emerging to slow the process. As part of the forward movement, Canada has hired their top statistical research firm, Statistics Canada to start monitoring the flow of cannabis-related products through the sewer systems. The Ottawa-based company known as StatCan, considered the best statistical organization in the world, has launched a six-city monitoring process to start screening for cannabinoids in wastewater. Samples will be taken from sewage treatment plants in Toronto, Montreal, Edmonton, Alberta, Vancouver, Surrey in British Columbia and Halifax, Nova Scotia. This approach would sample about a quarter of Canada's 36 million residents.
The purpose is to try and determine how much cannabis is being consumed and then passed along in human waste and measure that against the amount of legal or medical cannabis being sold to try and determine how much more the black market sales account for in the remaining balance.
Statistics Canada has retained Viviane Yargeau's lab at McGill University in Montreal to conduct the testing. They were chosen specifically for their previous expertise in sewage sampling. As to why the government would choose this means of sampling and quantifying cannabis usage,
StatCan assistant director Anthony Peluso has stated," There are things like surveys and what not where people report frequency of use but the consumption numbers weren't as reliable as we would like them to be". In other words people can't always be trusted to reveal their usage or frequency on a form.
Here is where the process gets murky. How much pot is actually consumed to create the waste? The cannabis is being consumed in several ways. Edibles would test differently than something that was smoked or applied to the skin. Furthermore, THC tends to start breaking down quickly in waste water before it can be detected, so the timing of the sample is a factor. And most of the THC is in solid waste while the measuring tools being used are mostly for liquid waste.
The first instance of researchers using sewage samples to determine a culture's drug use was in Italy in 2004. A study to measure cocaine use was conducted by a toxicologist named Ettore Zuccato at the Mario Negri Institute in Milan. They had previously tested waste products to measure pharmaceutical use so recreational drug measurement was the obvious next step. Several European countries have done similar studies and Australia and New Zealand have recently started their own THC testing programs. Now Canada has joined in the stool snooping process as well.
Paul Pot
Related Items:Canada 420 Laws, Canada Marijuana Legalization, Canada's Cannabis Sewage, Canada's Cannabis Sewage Scrutiny, Canadian, Cannabis Sewage, ganja, great white north, marijuana, science, sewage, statistics, thc
Two New Cannabinoids Discovered
Hannukah Marijuanica Prime Rib
The More Act and What it Might Mean for Cannabis
Apollon Formularies CBD Cartridge
Could Cynthia Nixon Become NY's First Pro-Cannabis Governor?
Xzibit's Brass Knuckles Vaporizer Line Review
JASON & JAYDEN'S JOURNEY
Edibles Safety and Preventing Mold
XZIBIT STAKES HIS CLAIM IN CANNABIS
Mary Jane's Medicinals: Pain Relief & Healing Salve
Official Hemp CBD Ban in California & United States
BEST OF EDIBLES LIST AWARDS 2016 WINNERS!
CHACHA VAVOOM OWNER & FOUNDER THE 420 NURSES
ALISON ETTEL CEO & CO-FOUNDER, TREATWELL
Medible Review: Kushy Punch New Strain Specific Gummies


On the 15th of October as part of 'Social Saturday' www.socialsaturday.org.uk we are celebrating our new 'Pop-Up Shop', 2 years as a Social Enterprise and to top it all our wondrous knitters and volunteers. The shop is at 7 Market Place, Barnard Castle, just up from Barclays Bank and in a great position for people, on foot to walk in or for parking on the Cobbles to load up Briquettes. On Saturday our knitters will be sipping Prosecco as they swap yarns and tales of pearls, garters, moss and popcorn's and join the heated debate 'can a hat with a Pompom be really called a beanie'. Lingos the Flatpacker will be discussing joinery techniques with Angus and both will be pondering the delights of Porter Cake and marveling at the magic of a replenishing cake tin.
Here in the shop we can show to best advantage the full range of our knitwear without being troubled by the ever threatening rain of Wednesday and Farmers' Markets. This so often saw us, ducking the showers, tipping collected gallons of rain from the canopy, trying hard not to soak our customers and/or holding down the Gazebo and catching flying hats as the wind tried to pick them up and blow them into the path of an ongoing juggernaut. This weather seemed to happen more so on Wednesday and Saturdays than on any other day of the Week!
But now we are in our wonderful shop with our wonderful knitwear and briquettes. Come along, browse, take your time, chat and feel the calmness.


Employees can be important in the growth and success of a business. For key employees who may be critical to the long term success of a company, some business owners may contemplate offering those employees share ownership in the company or perhaps establishing an employee stock option plan. There may be good business reasons for doing this including to encourage key employees to stay with the company, as another way to compensate employees, as an incentive to help grow the business and as a way to try and align the interests of key employees with the long term interests of the business and its owners. However, any decision to establish a stock option plan or to offer share ownership to employees should only be made after careful thought of all relevant legal, tax and other considerations.
The right to require that a company have audited financial statements unless all of the shareholders consent, which can be a significant expense to the company.
The right to attend the corporation 's annual shareholders meeting, the right to requisition a shareholders meeting and the right to receive the company 's financial statements and auditor 's report at the annual shareholders meeting.
The right to review the shareholder records of the company and the minute book for the company.
A shareholder who opposes a proposed amalgamation of the corporation, an amendment to its Articles, sale of its assets, etc., may be entitled to require that his/her shares be purchased by the corporation for fair value.
A shareholder can seek court intervention where the majority shareholders or the board of directors of a company have done, or threatened to do, something that is oppressive, unfairly prejudicial to or unfairly disregards the interest of a shareholder. A court has very broad powers to make orders to remedy situations where it determines there has been oppressive conduct.
For small and medium-sized private companies, with either one shareholder or shareholders who are all family members, they may have a significant amount of independence to operate the business as they see fit. Introducing key employees as shareholders can mean loss of independence in decision-making and additional reporting requirements. This is because directors of companies have legal obligations to act honestly, in good faith and to act in the best interests of the corporation, rather than their own personal interest. Failure to do so can expose directors and majority shareholders to claims by minority shareholders.
Also, when thinking of having employees as shareholders, some consideration should be given as to whether there are future plans to sell the company and whether such minority shareholders could interfere with, or be an obstacle to, a sale of the company.
For these reasons, if a decision is made to offer share ownership or stock options to employees then it is the best interests of the company to ensure that there is some mechanism in place to buy the employee's shares in the future, if necessary, including if the relationship with the employee does not work out as expected or if the employee's employment with the company is terminated for any reason. Some of these issues may be addressed through a Shareholders Agreement or, where a stock option plan is created, the terms of the Stock Option Plan Agreement that may be established by a company.
Given all of these concerns, a decision whether to offer shares or stock options to an employee should be made carefully after considering all business, legal, tax and other considerations. A business owner should also consider other alternatives to offering employees share ownership or stock option plans - for example, establishing a profit- sharing plan or a phantom stock option plan for employees.
This is just a short summary of some of the legal issues to consider if you have a private company in Ontario and are considering offering shares to your employees or considering establishing a stock option plan. It is recommended that you consult with a lawyer and tax adviser to advise you as to the many legal and tax issues to consider in these circumstances.