text:
/*
Package dynamodb provides a generic AWS DynamoDB implementation of godal.IGenericDao.

General guideline:

	- DAOs must implement IGenericDao.GdaoCreateFilter(string, IGenericBo) FilterOpt.
	- Row-mapper's function 'ColumnsList(table string) []string' must return all attribute names of specified table's primary key.

Guideline: Use GenericDaoDynamodb (and godal.IGenericBo) directly

	- Define a DAO struct that implements IGenericDao.GdaoCreateFilter(string, IGenericBo) FilterOpt.
	- Use a row-mapper whose 'ColumnsList(table string) []string' returns all attribute names of specified table's primary key.
	- Optionally, create a helper function to create DAO instances.

	import (
		//"github.com/aws/aws-sdk-go/aws"
		//"github.com/aws/aws-sdk-go/aws/credentials"
		//awsdynamodb "github.com/aws/aws-sdk-go/service/dynamodb"
		//"github.com/aws/aws-sdk-go/service/dynamodb/expression"

		"github.com/btnguyen2k/consu/reddo"
		"github.com/btnguyen2k/godal"
		godaldynamodb "github.com/btnguyen2k/godal/dynamodb"
		promdynamodb "github.com/btnguyen2k/prom/dynamodb"
	)

	type myGenericDaoDynamodb struct {
		*godaldynamodb.GenericDaoDynamodb
	}

	// GdaoCreateFilter implements godal.IGenericDao.GdaoCreateFilter.
	func (dao *myGenericDaoDynamodb) GdaoCreateFilter(table string, bo godal.IGenericBo) godal.FilterOpt {
		id := bo.GboGetAttrUnsafe(fieldId, reddo.TypeString)
		return &godal.FilterOptFieldOpValue{FieldName: fieldId, Operator: godal.FilterOpEqual, Value: id}
	}

	// newGenericDaoDynamodb is convenient method to create myGenericDaoDynamodb instances.
	func newGenericDaoDynamodb(adc *promdynamodb.AwsDynamodbConnect, tableName string) godal.IGenericDao {
		dao := &myGenericDaoDynamodb{}
		dao.GenericDaoDynamodb = godaldynamodb.NewGenericDaoDynamodb(adc, godal.NewAbstractGenericDao(dao))
		dao.SetRowMapper(&godaldynamodb.GenericRowMapperDynamodb{ColumnsListMap: map[string][]string{tableName: {fieldId}}})
		return dao
	}

	Since AWS DynamoDB is schema-less, GenericRowMapperDynamodb should be sufficient. However, it must be configured so that
	its function 'ColumnsList(table string) []string' returns all attribute names of specified table's primary key.

Guideline: Implement custom AWS DynamoDB business DAOs and BOs

	- Define and implement the business dao (Note: DAOs must implement IGenericDao.GdaoCreateFilter(string, IGenericBo) FilterOpt).
	- Optionally, create a helper function to create DAO instances.
	- Define functions to transform godal.IGenericBo to business BO and vice versa.

	import (
		//"github.com/aws/aws-sdk-go/aws"
		//"github.com/aws/aws-sdk-go/aws/credentials"
		//awsdynamodb "github.com/aws/aws-sdk-go/service/dynamodb"
		//"github.com/aws/aws-sdk-go/service/dynamodb/expression"

		"github.com/btnguyen2k/consu/reddo"
		"github.com/btnguyen2k/godal"
		godaldynamodb "github.com/btnguyen2k/godal/dynamodb"
		promdynamodb "github.com/btnguyen2k/prom/dynamodb"
	)

	// BoApp defines business object app
	type BoApp struct {
		Id            string                 `json:"id"`
		Description   string                 `json:"desc"`
		Value         int                    `json:"val"`
	}

	func (app *BoApp) ToGbo() godal.IGenericBo {
		gbo := godal.NewGenericBo()

		// method 1: populate attributes one by one
		gbo.GboSetAttr("id"  , app.Id)
		gbo.GboSetAttr("desc", app.Description)
		gbo.GboSetAttr("val" , app.Value)

		// method 2: transfer all attributes at once
		if err := gbo.GboImportViaJson(app); err!=nil {
			panic(err)
		}

		return gbo
	}

	func NewBoAppFromGbo(gbo godal.IGenericBo) *BoApp {
		app := BoApp{}

		// method 1: populate attributes one by one
		app.Id          = gbo.GboGetAttrUnsafe("id", reddo.TypeString).(string)
		app.Description = gbo.GboGetAttrUnsafe("desc", reddo.TypeString).(string)
		app.Value       = int(gbo.GboGetAttrUnsafe("val", reddo.TypeInt).(int64))

		// method 2: transfer all attributes at once
		if err := gbo.GboTransferViaJson(&app); err!=nil {
			panic(err)
		}

		return &app
	}

	// DaoAppDynamodb is AWS DynamoDB-implementation of business dao
	type DaoAppDynamodb struct {
		*godaldynamodb.GenericDaoDynamodb
		tableName string
	}

	// NewDaoAppDynamodb is convenient method to create DaoAppDynamodb instances.
	func NewDaoAppDynamodb(adc *promdynamodb.AwsDynamodbConnect, tableName string) *NewDaoAppDynamodb {
		dao := &DaoAppDynamodb{tableName: tableName}
		dao.GenericDaoDynamodb = godaldynamodb.NewGenericDaoDynamodb(adc, godal.NewAbstractGenericDao(dao))
		dao.SetRowMapper(&godaldynamodb.GenericRowMapperDynamodb{ColumnsListMap: map[string][]string{tableName: {"id"}}})
		return dao
	}

	Since AWS DynamoDB is schema-less, GenericRowMapperDynamodb should be sufficient. However, it must be configured so that
	its function 'ColumnsList(table string) []string' must return all attribute names of specified table's primary key.

See more examples in 'examples' directory on project's GitHub: https://github.com/btnguyen2k/godal/tree/master/examples

To create AwsDynamodbConnect instances, see package github.com/btnguyen2k/prom/dynamodb
*/
package dynamodb

import (
	"errors"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	awsdynamodb "github.com/aws/aws-sdk-go/service/dynamodb"
	"github.com/aws/aws-sdk-go/service/dynamodb/expression"
	"github.com/btnguyen2k/consu/reddo"
	"github.com/btnguyen2k/godal"
	"github.com/btnguyen2k/prom/dynamodb"
)

// GenericRowMapperDynamodb is a generic implementation of godal.IRowMapper for AWS DynamoDB.
//
// Implementation rules:
// 	 - ToRow        : transform godal.IGenericBo "as-is" to map[string]interface{}.
// 	 - ToBo         : expect input is a map[string]interface{}, or JSON data (string or array/slice of bytes), transforms input to godal.IGenericBo via JSON unmarshalling.
// 	 - ColumnsList  : look up column-list from a 'columns-list map' (AWS DynamoDB is schema-free but key-attributes are significant) and returns it.
//   - ToDbColName  : return the input field name "as-is".
//   - ToBoFieldName: return the input column name "as-is".
//
// Available: since v0.2.0
type GenericRowMapperDynamodb struct {
	// ColumnsListMap holds mappings of {table-name:[list of key attribute names]}
	ColumnsListMap map[string][]string
}

// ToRow implements godal.IRowMapper.ToRow.
//
// This function transforms godal.IGenericBo to map[string]interface{}. Field names are kept intact.
func (mapper *GenericRowMapperDynamodb) ToRow(_ string, bo godal.IGenericBo) (interface{}, error) {
	if bo == nil {
		return nil, nil
	}
	result := make(map[string]interface{})
	return result, bo.GboTransferViaJson(&result)
}

// ToBo implements godal.IRowMapper.ToBo.
//
// This function expects input to be a map[string]interface{}, or JSON data (string or array/slice of bytes), transforms it to godal.IGenericBo via JSON unmarshalling. Field names are kept intact.
func (mapper *GenericRowMapperDynamodb) ToBo(table string, row interface{}) (godal.IGenericBo, error) {
	if row == nil {
		return nil, nil
	}
	switch row.(type) {
	case *map[string]interface{}:
		// unwrap if pointer
		m := row.(*map[string]interface{})
		if m == nil {
			return nil, nil
		}
		return mapper.ToBo(table, *m)
	case map[string]interface{}:
		bo := godal.NewGenericBo()
		for k, v := range row.(map[string]interface{}) {
			bo.GboSetAttr(k, v)
		}
		return bo, nil
	case string:
		bo := godal.NewGenericBo()
		return bo, bo.GboFromJson([]byte(row.(string)))
	case *string:
		// unwrap if pointer
		s := row.(*string)
		if s == nil {
			return nil, nil
		}
		return mapper.ToBo(table, *s)
	case []byte:
		if row.([]byte) == nil {
			return nil, nil
		}
		bo := godal.NewGenericBo()
		return bo, bo.GboFromJson(row.([]byte))
	case *[]byte:
		// unwrap if pointer
		ba := row.(*[]byte)
		if ba == nil {
			return nil, nil
		}
		return mapper.ToBo(table, *ba)
	}

	v := reflect.ValueOf(row)
	for ; v.Kind() == reflect.Ptr; v = v.Elem() {
		// unwrap if pointer
	}
	switch v.Kind() {
	case reflect.Map:
		if v.IsNil() {
			return nil, nil
		}
		bo := godal.NewGenericBo()
		for iter := v.MapRange(); iter.Next(); {
			key, _ := reddo.ToString(iter.Key().Interface())
			bo.GboSetAttr(key, iter.Value().Interface())
		}
		return bo, nil
	case reflect.String:
		bo := godal.NewGenericBo()
		return bo, bo.GboFromJson([]byte(v.Interface().(string)))
	case reflect.Slice, reflect.Array:
		if v.Type().Elem().Kind() == reflect.Uint8 {
			// input is []byte
			zero := make([]byte, 0)
			arr, err := reddo.ToSlice(v.Interface(), reflect.TypeOf(zero))
			if err != nil || arr.([]byte) == nil || len(arr.([]byte)) == 0 {
				return nil, err
			}
			bo := godal.NewGenericBo()
			return bo, bo.GboFromJson(arr.([]byte))
		}
	case reflect.Interface:
		return mapper.ToBo(table, v.Interface())
	case reflect.Invalid:
		return nil, nil
	}
	return nil, fmt.Errorf("cannot construct godal.IGenericBo from input %v", row)
}

// ColumnsList implements godal.IRowMapper.ColumnsList.
//
// This function looks up column-list from a 'columns-list map' (AWS DynamoDB is schema-free but key-attributes are significant) and returns it.
func (mapper *GenericRowMapperDynamodb) ColumnsList(table string) []string {
	if result, ok := mapper.ColumnsListMap[table]; ok {
		return result
	}
	return nil
}

// ToDbColName implements godal.IRowMapper.ToDbColName.
//
// This function returns the input field name "as-is".
func (mapper *GenericRowMapperDynamodb) ToDbColName(_, fieldName string) string {
	return fieldName
}

// ToBoFieldName implements godal.IRowMapper.ToBoFieldName.
//
// This function returns the input column name "as-is".
func (mapper *GenericRowMapperDynamodb) ToBoFieldName(_, colName string) string {
	return colName
}

var (
	// GenericRowMapperDynamodbInstance is a pre-created instance of GenericRowMapperDynamodb that is ready to use.
	GenericRowMapperDynamodbInstance godal.IRowMapper = &GenericRowMapperDynamodb{}
)

/*--------------------------------------------------------------------------------*/

// NewGenericDaoDynamodb constructs a new AWS DynamoDB implementation of 'godal.IGenericDao'.
func NewGenericDaoDynamodb(dynamodbConnect *dynamodb.AwsDynamodbConnect, agdao *godal.AbstractGenericDao) *GenericDaoDynamodb {
	dao := &GenericDaoDynamodb{AbstractGenericDao: agdao, dynamodbConnect: dynamodbConnect}
	if dao.GetRowMapper() == nil {
		dao.SetRowMapper(GenericRowMapperDynamodbInstance)
	}
	return dao
}

// GenericDaoDynamodb is AWS DynamoDB implementation of godal.IGenericDao.
//
// Function implementations (n = No, y = Yes, i = inherited):
// 	 - (n) GdaoCreateFilter(tableName string, bo godal.IGenericBo) godal.FilterOpt
// 	 - (y) GdaoDelete(tableName string, bo godal.IGenericBo) (int, error)
// 	 - (y) GdaoDeleteMany(tableName string, filter godal.FilterOpt) (int, error)
// 	 - (y) GdaoFetchOne(tableName string, filter godal.FilterOpt) (godal.IGenericBo, error)
// 	 - (y) GdaoFetchMany(tableName string, filter godal.FilterOpt, sorting *godal.SortingOpt, startOffset, numItems int) ([]godal.IGenericBo, error)
// 	 - (y) GdaoCreate(tableName string, bo godal.IGenericBo) (int, error)
// 	 - (y) GdaoUpdate(tableName string, bo godal.IGenericBo) (int, error)
// 	 - (y) GdaoSave(tableName string, bo godal.IGenericBo) (int, error)
//
// Available: since v0.2.0
type GenericDaoDynamodb struct {
	*godal.AbstractGenericDao
	dynamodbConnect *dynamodb.AwsDynamodbConnect
}

// GetAwsDynamodbConnect returns the '*dynamodb.AwsDynamodbConnect' instance attached to this DAO.
func (dao *GenericDaoDynamodb) GetAwsDynamodbConnect() *dynamodb.AwsDynamodbConnect {
	return dao.dynamodbConnect
}

// SetAwsDynamodbConnect attaches a '*dynamodb.AwsDynamodbConnect' instance to this DAO.
func (dao *GenericDaoDynamodb) SetAwsDynamodbConnect(adc *dynamodb.AwsDynamodbConnect) *GenericDaoDynamodb {
	dao.dynamodbConnect = adc
	return dao
}

func (dao *GenericDaoDynamodb) extractKeysAttributes(table string, item dynamodb.AwsDynamodbItem) map[string]interface{} {
	cols := dao.GetRowMapper().ColumnsList(table)
	if cols == nil {
		return nil
	}
	keysAttrs := make(map[string]interface{})
	for _, k := range cols {
		keysAttrs[k] = item[k]
	}
	return keysAttrs
}

// toFilterMap translates a godal.FilterOpt to DynamoDB-compatible filter map.
func toFilterMap(filter godal.FilterOpt) (map[string]interface{}, error) {
	if filter == nil {
		return nil, nil
	}
	switch filter.(type) {
	case godal.FilterOptFieldOpValue:
		f := filter.(godal.FilterOptFieldOpValue)
		return toFilterMap(&f)
	case *godal.FilterOptFieldOpValue:
		f := filter.(*godal.FilterOptFieldOpValue)
		if f.Operator != godal.FilterOpEqual {
			return nil, fmt.Errorf("invalid operator \"%#v\", only accept FilterOptFieldOpValue with operator FilterOpEqual", f.Operator)
		}
		return map[string]interface{}{f.FieldName: f.Value}, nil
	case godal.FilterOptFieldIsNull:
		f := filter.(godal.FilterOptFieldIsNull)
		return toFilterMap(&f)
	case *godal.FilterOptFieldIsNull:
		f := filter.(*godal.FilterOptFieldIsNull)
		return map[string]interface{}{f.FieldName: nil}, nil
	case godal.FilterOptAnd:
		f := filter.(godal.FilterOptAnd)
		return toFilterMap(&f)
	case *godal.FilterOptAnd:
		f := filter.(*godal.FilterOptAnd)
		result := make(map[string]interface{})
		for _, inner := range f.Filters {
			innerF, err := toFilterMap(inner)
			if err != nil {
				return nil, err
			}
			for k, v := range innerF {
				result[k] = v
			}
		}
		return result, nil
	}
	return nil, fmt.Errorf("cannot build filter map from %T", filter)
}

/*----------------------------------------------------------------------*/

// GdaoDelete implements godal.IGenericDao.GdaoDelete.
func (dao *GenericDaoDynamodb) GdaoDelete(table string, bo godal.IGenericBo) (int, error) {
	return dao.GdaoDeleteWithContext(nil, table, bo)
}

// GdaoDeleteWithContext is AWS DynamoDB variant of GdaoDelete.
func (dao *GenericDaoDynamodb) GdaoDeleteWithContext(ctx aws.Context, table string, bo godal.IGenericBo) (int, error) {
	keyFilter, err := toFilterMap(dao.GdaoCreateFilter(table, bo))
	if err != nil {
		return 0, err
	}
	deleteInput, err := dao.dynamodbConnect.BuildDeleteItemInput(table, keyFilter, nil)
	if err != nil {
		return 0, err
	}
	deleteResult, err := dao.dynamodbConnect.DeleteItemWithInput(ctx, deleteInput.SetReturnValues("ALL_OLD"))
	numRows := 0
	if deleteResult != nil && deleteResult.Attributes != nil {
		numRows = 1
	}
	return numRows, err
}

// GdaoDeleteMany implements godal.IGenericDao.GdaoDeleteMany.
//   - table name format: <table_name>[:<index_name>]:
//       - table_name: name of the table to delete rows from.
//       - index_name: (optional) name of the table's index (local or global) to search for rows.
//
// This function uses "scan" operation by default, which is expensive! To force "query" operation, prefix the table name with character '@'.
func (dao *GenericDaoDynamodb) GdaoDeleteMany(table string, filter godal.FilterOpt) (int, error) {
	return dao.GdaoDeleteManyWithContext(nil, table, filter)
}

// BuildConditionBuilder transforms a godal.FilterOpt to expression.ConditionBuilder.
//
// Available since v0.5.1
func (dao *GenericDaoDynamodb) BuildConditionBuilder(tableName string, filter godal.FilterOpt) (*expression.ConditionBuilder, error) {
	if filter == nil {
		return nil, nil
	}
	rm := dao.GetRowMapper()
	if rm == nil {
		return nil, errors.New("row-mapper is required to build ConditionBuilder")
	}

	switch filter.(type) {
	case godal.FilterOptFieldOpValue:
		f := filter.(godal.FilterOptFieldOpValue)
		return dao.BuildConditionBuilder(tableName, &f)
	case *godal.FilterOptFieldOpValue:
		f := filter.(*godal.FilterOptFieldOpValue)
		exp := expression.Name(rm.ToDbColName(tableName, f.FieldName))
		switch f.Operator {
		case godal.FilterOpEqual:
			t := exp.Equal(expression.Value(f.Value))
			return &t, nil
		case godal.FilterOpNotEqual:
			t := exp.NotEqual(expression.Value(f.Value))
			return &t, nil
		case godal.FilterOpGreater:
			t := exp.GreaterThan(expression.Value(f.Value))
			return &t, nil
		case godal.FilterOpGreaterOrEqual:
			t := exp.GreaterThanEqual(expression.Value(f.Value))
			return &t, nil
		case godal.FilterOpLess:
			t := exp.LessThan(expression.Value(f.Value))
			return &t, nil
		case godal.FilterOpLessOrEqual:
			t := exp.LessThanEqual(expression.Value(f.Value))
			return &t, nil
		}
		return nil, fmt.Errorf("unknown filter operator: %#v", f.Operator)
	case godal.FilterOptFieldIsNull:
		f := filter.(godal.FilterOptFieldIsNull)
		return dao.BuildConditionBuilder(tableName, &f)
	case *godal.FilterOptFieldIsNull:
		f := filter.(*godal.FilterOptFieldIsNull)
		t := expression.Name(rm.ToDbColName(tableName, f.FieldName)).AttributeNotExists()
		return &t, nil
	case godal.FilterOptFieldIsNotNull:
		f := filter.(godal.FilterOptFieldIsNotNull)
		return dao.BuildConditionBuilder(tableName, &f)
	case *godal.FilterOptFieldIsNotNull:
		f := filter.(*godal.FilterOptFieldIsNotNull)
		t := expression.Name(rm.ToDbColName(tableName, f.FieldName)).AttributeExists()
		return &t, nil
	case godal.FilterOptAnd:
		f := filter.(godal.FilterOptAnd)
		return dao.BuildConditionBuilder(tableName, &f)
	case *godal.FilterOptAnd:
		f := filter.(*godal.FilterOptAnd)
		var result *expression.ConditionBuilder = nil
		for _, innerF := range f.Filters {
			innerResult, err := dao.BuildConditionBuilder(tableName, innerF)
			if err != nil {
				return nil, err
			}
			if result == nil {
				result = innerResult
			} else {
				t := result.And(*innerResult)
				result = &t
			}
		}
		return result, nil
	case godal.FilterOptOr:
		f := filter.(godal.FilterOptOr)
		return dao.BuildConditionBuilder(tableName, &f)
	case *godal.FilterOptOr:
		f := filter.(*godal.FilterOptOr)
		var result *expression.ConditionBuilder = nil
		for _, innerF := range f.Filters {
			innerResult, err := dao.BuildConditionBuilder(tableName, innerF)
			if err != nil {
				return nil, err
			}
			if result == nil {
				result = innerResult
			} else {
				t := result.Or(*innerResult)
				result = &t
			}
		}
		return result, nil
	}
	return nil, fmt.Errorf("cannot build filter from %T", filter)
}

// GdaoDeleteManyWithContext is is AWS DynamoDB variant of GdaoDeleteMany.
func (dao *GenericDaoDynamodb) GdaoDeleteManyWithContext(ctx aws.Context, table string, filter godal.FilterOpt) (int, error) {
	f, err := dao.BuildConditionBuilder(table, filter)
	if err != nil {
		return 0, err
	}
	tokens := strings.Split(table, ":")
	tableName := tokens[0]
	useScan := true
	if strings.HasPrefix(tableName, "@") {
		useScan = false
		tableName = strings.TrimPrefix(tableName, "@")
	}
	indexName := ""
	if len(tokens) > 1 {
		indexName = tokens[1]
	}
	count := 0
	callbackFunc := func(item dynamodb.AwsDynamodbItem, lastEvaluatedKey map[string]*awsdynamodb.AttributeValue) (b bool, e error) {
		keyFilter := dao.extractKeysAttributes(tableName, item)
		_, err := dao.dynamodbConnect.DeleteItem(ctx, tableName, keyFilter, nil)
		if err == nil {
			count++
		}
		return true, err
	}
	if useScan {
		err = dao.dynamodbConnect.ScanItemsWithCallback(ctx, tableName, f, indexName, nil, callbackFunc)
	} else {
		err = dao.dynamodbConnect.QueryItemsWithCallback(ctx, tableName, f, nil, indexName, nil, callbackFunc)
	}
	return count, err
}

// GdaoFetchOne implements godal.IGenericDao.GdaoFetchOne.
//   - keyFilter: filter that matches exactly one item by key.
func (dao *GenericDaoDynamodb) GdaoFetchOne(table string, keyFilter godal.FilterOpt) (godal.IGenericBo, error) {
	return dao.GdaoFetchOneWithContext(nil, table, keyFilter)
}

// GdaoFetchOneWithContext is is AWS DynamoDB variant of GdaoFetchOne.
func (dao *GenericDaoDynamodb) GdaoFetchOneWithContext(ctx aws.Context, table string, keyFilter godal.FilterOpt) (godal.IGenericBo, error) {
	if f, err := toFilterMap(keyFilter); err != nil {
		return nil, err
	} else if item, err := dao.dynamodbConnect.GetItem(ctx, table, f); err != nil {
		return nil, err
	} else {
		return dao.GetRowMapper().ToBo(table, item)
	}
}

// GdaoFetchMany implements godal.IGenericDao.GdaoFetchMany.
//   - table name format: <table_name>[:<index_name>[:<refetch-from-table:true/false>]]:
//       - table_name: name of the table to fetch data from.
//       - index_name: (optional) name of the table's index (local or global) to fetch data from.
//       - refetch-from-table: (optional) true/false - default: false; when fetching data from index, if 'false' only projected fields are returned,.
//         if 'true' another read is made to fetch the whole item from table (additional read capacity is consumed!)
//   - sorting will not be used as DynamoDB does not currently support custom sorting of queried items.
//
// This function uses "scan" operation by default, which is expensive! To force "query" operation, prefix the table name with character @.
// (Available since v0.5.2) Furthermore, prefix the table name with character ! to query "backward" instead of the default "forward" mode ("query" mode must be used).
func (dao *GenericDaoDynamodb) GdaoFetchMany(table string, filter godal.FilterOpt, sorting *godal.SortingOpt, startOffset, numItems int) ([]godal.IGenericBo, error) {
	return dao.GdaoFetchManyWithContext(nil, table, filter, sorting, startOffset, numItems)
}

var reTablePrefixDirectives = regexp.MustCompile(`^\W+`)
var reUseQuery = regexp.MustCompile(`^\W*@\W*\w+`)
var reQueryBackward = regexp.MustCompile(`^\W*!\W*\w+`)

// GdaoFetchManyWithContext is AWS DynamoDB variant of GdaoFetchMany.
func (dao *GenericDaoDynamodb) GdaoFetchManyWithContext(ctx aws.Context, table string, filter godal.FilterOpt, _ *godal.SortingOpt, startOffset, numItems int) ([]godal.IGenericBo, error) {
	f, err := dao.BuildConditionBuilder(table, filter)
	if err != nil {
		return nil, err
	}
	result := make([]godal.IGenericBo, 0)
	tokens := strings.Split(table, ":")
	tableName := tokens[0]
	useQuery := reUseQuery.FindString(table) != ""
	queryBackward := reQueryBackward.FindString(table) != ""
	tableName = reTablePrefixDirectives.ReplaceAllString(tableName, "")
	indexName := ""
	if len(tokens) > 1 {
		indexName = tokens[1]
	}
	refetchFromTable := false
	if len(tokens) > 2 {
		if refetchFromTable, err = strconv.ParseBool(tokens[2]); err != nil {
			refetchFromTable = false
		}
	}

	myOffset := -1
	myCounter := 0
	callbackFunc := func(item dynamodb.AwsDynamodbItem, lastEvaluatedKey map[string]*awsdynamodb.AttributeValue) (b bool, e error) {
		myOffset++
		if myOffset < startOffset {
			return true, nil
		}
		if refetchFromTable {
			pkAttrs := dao.extractKeysAttributes(tableName, item)
			if item, err = dao.dynamodbConnect.GetItem(ctx, tableName, pkAttrs); err != nil {
				return false, err
			}
		}
		gbo, err := dao.GetRowMapper().ToBo(table, item)
		if err != nil {
			return false, err
		}
		result = append(result, gbo)
		myCounter++
		if numItems > 0 && myCounter >= numItems {
			return false, nil
		}
		return true, nil
	}
	if useQuery {
		err = dao.dynamodbConnect.QueryItemsWithCallback(ctx, tableName, f, nil, indexName, nil, callbackFunc, dynamodb.AwsQueryOpt{ScanIndexBackward: aws.Bool(queryBackward)})
	} else {
		err = dao.dynamodbConnect.ScanItemsWithCallback(ctx, tableName, f, indexName, nil, callbackFunc)
	}

	return result, err
}

// GdaoCreate implements godal.IGenericDao.GdaoCreate.
func (dao *GenericDaoDynamodb) GdaoCreate(table string, bo godal.IGenericBo) (int, error) {
	return dao.GdaoCreateWithContext(nil, table, bo)
}

// GdaoCreateWithContext is is AWS DynamoDB variant of GdaoCreate.
func (dao *GenericDaoDynamodb) GdaoCreateWithContext(ctx aws.Context, table string, bo godal.IGenericBo) (int, error) {
	pkAttrs := dao.GetRowMapper().ColumnsList(table)
	if pkAttrs == nil || len(pkAttrs) == 0 {
		return 0, fmt.Errorf("cannot find primary-key attribute list for table [%s]", table)
	}
	item, err := dao.GetRowMapper().ToRow(table, bo)
	if err != nil {
		return 0, err
	}
	createResult, err := dao.dynamodbConnect.PutItemIfNotExist(ctx, table, item, pkAttrs)
	if createResult == nil && dynamodb.AwsIgnoreErrorIfMatched(err, awsdynamodb.ErrCodeConditionalCheckFailedException) == nil {
		return 0, godal.ErrGdaoDuplicatedEntry
	}
	return 1, err
}

// GdaoUpdate implements godal.IGenericDao.GdaoUpdate.
//
// Note: due to the nature of AWS DynamoDB, this function does not return godal.ErrGdaoDuplicatedEntry.
func (dao *GenericDaoDynamodb) GdaoUpdate(table string, bo godal.IGenericBo) (int, error) {
	return dao.GdaoUpdateWithContext(nil, table, bo)
}

// GdaoUpdateWithContext is is AWS DynamoDB variant of GdaoUpdate.
func (dao *GenericDaoDynamodb) GdaoUpdateWithContext(ctx aws.Context, table string, bo godal.IGenericBo) (int, error) {
	var keyFilter, itemMap map[string]interface{}
	var err error
	if keyFilter, err = toFilterMap(dao.GdaoCreateFilter(table, bo)); err != nil {
		return 0, err
	}
	var item interface{}
	var ok bool
	if item, err = dao.GetRowMapper().ToRow(table, bo); err != nil {
		return 0, err
	} else if itemMap, ok = item.(map[string]interface{}); !ok {
		return 0, fmt.Errorf("expected map[string]interface{} but received %T", item)
	}

	pkAttrs := dao.GetRowMapper().ColumnsList(table)
	if pkAttrs == nil || len(pkAttrs) == 0 {
		return 0, fmt.Errorf("cannot find primary-key attribute list for table [%s]", table)
	}
	for _, pk := range pkAttrs {
		// remove primary key attributes from update list
		delete(itemMap, pk)
	}
	condition := dynamodb.AwsDynamodbExistsAllBuilder(pkAttrs)
	if _, err = dao.dynamodbConnect.UpdateItem(ctx, table, keyFilter, condition, nil, itemMap, nil, nil); err != nil {
		err = dynamodb.AwsIgnoreErrorIfMatched(err, awsdynamodb.ErrCodeConditionalCheckFailedException)
		return 0, err
	}
	return 1, nil
}

// GdaoSave implements godal.IGenericDao.GdaoSave.
//
// Note: due to the nature of AWS DynamoDB, this function does not return godal.ErrGdaoDuplicatedEntry.
func (dao *GenericDaoDynamodb) GdaoSave(table string, bo godal.IGenericBo) (int, error) {
	return dao.GdaoSaveWithContext(nil, table, bo)
}

// GdaoSaveWithContext is is AWS DynamoDB variant of GdaoSave.
func (dao *GenericDaoDynamodb) GdaoSaveWithContext(ctx aws.Context, table string, bo godal.IGenericBo) (int, error) {
	pkAttrs := dao.GetRowMapper().ColumnsList(table)
	if pkAttrs == nil || len(pkAttrs) == 0 {
		return 0, fmt.Errorf("cannot find primary-key attribute list for table [%s]", table)
	}
	item, err := dao.GetRowMapper().ToRow(table, bo)
	if err != nil {
		return 0, err
	}
	_, err = dao.dynamodbConnect.PutItem(ctx, table, item, nil)
	return 1, err
}

gha_license_id: MIT


text:
package main

import (
	"fmt"
	"github.com/mrmorphic/hwio"
	"github.com/sameer/fsm/moore"
	"github.com/tarm/serial"
)

type SignInput struct {
	isGPIOAvailable bool
	gpio17, gpio27  hwio.Pin     // BCM Pin 17, 27 (https://pinout.xyz/)
	doorArduino     *serial.Port // A port for transferring data with the photoresistor sketch
}

func (si *SignInput) init() {
	if si.isGPIOAvailable { // Grab the pins if available
		var err error = nil
		si.gpio17, err = hwio.GetPin("gpio17")
		if err != nil {
			fmt.Println("gpio17 ", err)
			si.isGPIOAvailable = false
		}
		si.gpio27, err = hwio.GetPin("gpio27")
		if err != nil {
			fmt.Println("gpio27 ", err)
			si.isGPIOAvailable = false
		}
		if si.isGPIOAvailable {
			hwio.PinMode(si.gpio17, hwio.INPUT)
			hwio.PinMode(si.gpio27, hwio.INPUT)
		}
	}
	si.doorArduino = AcquireArduinoUID(16)
}

type SwitchState int

const (
	stateOpenNormal   SwitchState = iota // 0
	stateOpenForced                      // 1
	stateClosedForced                    // 2
)

func (si *SignInput) IsOpen() bool {
	// Logic to determine if the studio is likely open.
	isOpen := len(shifts.getMentorsOnDuty()) > 0
	// Now check the switch state. This is a DPDT switch with the states I (normal), II (force open), and O (force closed)
	switchValue := si.GetSwitchValue()
	if switchValue == stateOpenNormal {
		// Door open + normally open. If a mentor misses their shift & the door is closed, the sign will say
		// that the studio is closed.
		return isOpen && si.IsDoorOpen()
	} else if switchValue == stateOpenForced {
		// As long as the door is open, forced open will work. The door *must* be open just in case anyone accidentally
		// leaves it in forced open.
		return si.IsDoorOpen()
	} else {
		// Forced closed.
		return false
	}
}

func (si *SignInput) GetSwitchValue() SwitchState {
	if si.isGPIOAvailable {
		// Is this normal open?
		openOne, err := hwio.DigitalRead(si.gpio17)
		if err == nil {
			if openOne == hwio.HIGH { // It is indeed.
				return stateOpenNormal
			} else {
				// Is it actually forced open?
				openTwo, err := hwio.DigitalRead(si.gpio27)
				if err == nil {
					if openTwo == hwio.HIGH { // It is indeed.
						return stateOpenForced
					} else { // The only other possibility is forced closed.
						return stateClosedForced
					}
				} else {
					fmt.Println("gpio27 err ", err)
				}
			}
		} else {
			fmt.Println("gpio17 err ", err)
		}
	}
	// This will be returned if there are any errors. There's no way to really recover from fatal errors
	// like these without manual intervention, so it is safest to assume normal operation.
	return stateOpenNormal
}

const (
	doorSensorReq   = 4
	motionSensorReq = 8
	relayChange     = 16
	identReq        = 32
)

func (si *SignInput) IsDoorOpen() bool {
	var buf = make([]byte, 1)
	if si.doorArduino == nil {
		return true
	}
	si.doorArduino.Write([]byte{doorSensorReq}) // Send a request for photoresistor value
	bytesRead, err := si.doorArduino.Read(buf)
	// If we failed to read a value, assume either something is wrong with the hardware
	// i.e. the Arduino was unplugged. The mentor on duty can override the current value
	// by switching it to open override.
	if bytesRead == 0 || err != nil {
		return true
	}
	return buf[0] != 0 // 0 == false aka door closed
	// Add onto the average
	//doorMovingAverage.Add(float64(val))
	//return doorMovingAverage.Avg() > 200 // The door sees light on average
	// TODO: change this so a sudden 30% difference in the moving average will cause a state transition
	// TODO: remove the magic value of 200 because sometimes the sensor changes irreversably because people
	// mess with the arduino. Instead, we can make an assumption that no one will be in the room at 5/6AM and
	// use the sensor values at those times as "darkness".
}

func (si *SignInput) IsThereMotion() bool {
	var buf = make([]byte, 1)
	if si.doorArduino == nil {
		return false
	}
	si.doorArduino.Write([]byte{motionSensorReq})
	bytesRead, err := si.doorArduino.Read(buf)
	if bytesRead == 0 || err != nil {
		return false
	}
	return buf[0] != 0
}

var inputFunction = func() moore.InputFunction {
	input := &SignInput{}
	input.isGPIOAvailable = true
	input.init()
	return func() moore.Input {
		return input
	}
}()

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: go


text:
package dm03

import (
	"duel-masters/game/civ"
	"duel-masters/game/cnd"
	"duel-masters/game/family"
	"duel-masters/game/fx"
	"duel-masters/game/match"
)

// SparkleFlower ...
func SparkleFlower(c *match.Card) {

	c.Name = "Sparkle Flower"
	c.Power = 3000
	c.Civ = civ.Light
	c.Family = family.StarlightTree
	c.ManaCost = 4
	c.ManaRequirement = []string{civ.Light}

	c.Use(fx.Creature, func(card *match.Card, ctx *match.Context) {

		if _, ok := ctx.Event.(*match.UntapStep); ok {

			if match.ContainerHas(card.Player, match.MANAZONE, func(x *match.Card) bool { return x.Civ != civ.Light }) {
				card.RemoveCondition(cnd.Blocker)
			} else {
				card.AddCondition(cnd.Blocker, true, card.ID)
			}
		}

	})

}

repository: sindreslungaard/duel-masters

repo_name: sindreslungaard/duel-masters

gha_language: Go


text:
package ast

func unmarshalProgram(m M) *Program {
	p := &Program{}
	p.UnmarshalMap(m)

	return p
}

func unmarshalAttr(m M) *Attr {
	attr := &Attr{}
	attr.UnmarshalMap(m)

	return attr
}

func unmarshalSourceLocation(m M) *SourceLocation {
	sl := &SourceLocation{}
	sl.UnmarshalMap(m)

	return sl
}

func unmarshalPosition(m M) *Position {
	p := &Position{}
	p.UnmarshalMap(m)

	return p
}

func unmarshalIdentifier(m M) *Identifier {
	i := &Identifier{}
	i.UnmarshalMap(convertMap(m["id"]))

	return i
}

func unmarshalExtra(m M) *Extra {
	e := &Extra{}
	e.UnmarshalMap(m)

	return e
}

func unmarshalDeclaration(m M) Declaration {
	t := convertString(m["type"])
	var d Declaration
	switch t {
	case "VariableDeclaration":
		d = &VariableDeclaration{}
	default:
		panic("unsupport declaration type " + t)
	}

	d.UnmarshalMap(m)

	return d
}

func unmarshalExpressions(m []M) []Expression {
	var e []Expression
	for _, mm := range m {
		e = append(e, unmarshalExpression(mm))
	}

	return e
}

func unmarshalExpression(m M) Expression {
	t := convertString(m["type"])
	var e Expression
	switch t {
	case "Identifier":
		e = &Identifier{}
	case "StringLiteral":
		e = &StringLiteral{}
	case "CallExpression":
		e = &CallExpression{}
	case "MemberExpression":
		e = &MemberExpression{}
	default:
		panic("unsupport expression type " + t)
	}

	e.UnmarshalMap(m)

	return e
}

func unmarshalVariableDeclarator(m []M) []*VariableDeclarator {
	var d []*VariableDeclarator
	for _, mm := range m {
		dd := &VariableDeclarator{}
		dd.UnmarshalMap(mm)
		d = append(d, dd)
	}

	return d
}

func unmarshalStatements(m []M) []Statement {
	var s []Statement
	for _, mm := range m {
		s = append(s, unmarshalStatement(mm))
	}

	return s
}

func unmarshalStatement(m M) Statement {
	t := convertString(m["type"])
	var s Statement
	switch t {
	case "VariableDeclaration":
		s = &VariableDeclaration{}
	case "ExpressionStatement":
		s = &ExpressionStatement{}
	default:
		panic("unsupport statement type " + t)
	}

	s.UnmarshalMap(m)

	return s
}

func convertSliceMap(i interface{}) []M {
	var m []M
	for _, mm := range i.([]interface{}) {
		m = append(m, convertMap(mm))
	}

	return m
}

func convertMap(i interface{}) M {
	return M(i.(map[string]interface{}))
}

func convertString(i interface{}) string {
	return i.(string)
}

func convertInt(i interface{}) int {
	return int(i.(float64))
}

func convertBool(i interface{}) bool {
	return i.(bool)
}

repository: imkarma/godzilla

repo_name: imkarma/godzilla


text:
package downloader

// credits: https://golangcode.com/download-a-file-from-a-url/

import (
	"crypto/md5"
	"fmt"
	"io"
	"net/http"
	"os"
)

// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory.
func DownloadFile(email string, width string) error {
	md5 := getMd5FromMail(email)
	url := fmt.Sprintf("https://gravatar.com/avatar/%x?s=%s", md5, width)

	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	out, err := os.Create(email + "_" + width + ".png")
	if err != nil {
		return err
	}
	defer out.Close()
	_, err = io.Copy(out, resp.Body)
	return err
}

func getMd5FromMail(mail string) [16]byte {
	return md5.Sum([]byte(mail))
}


text:
require gstreamer.inc

SRC_URI[archive.md5sum] = "442bc3d37b8511a73379143e7531d726"
SRC_URI[archive.sha256sum] = "3bf4e46a186ee9a1f5e212aaf651d67cffb4f5f05345a7c99ae71d5d992be133"

SRC_URI += " \
             file://0001-add-GstQueryBuffers-query.patch \
             file://0002-gstevent-add-crop-event.patch \
             file://0003-basetransform-don-t-do-unnecessary-pad_alloc.patch \
"

EXTRA_OECONF += "ac_cv_func_register_printf_function=no"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
package xconfig

import (
	"fmt"
	"path/filepath"

	"github.com/xuperchain/xupercore/kernel/common/xutils"
	"github.com/xuperchain/xupercore/lib/utils"

	"github.com/spf13/viper"
)

type EnvConf struct {
	// Program running root directory
	RootPath string `yaml:"rootPath,omitempty"`
	// config file directory
	ConfDir string `yaml:"confDir,omitempty"`
	// data file directory
	DataDir string `yaml:"dataDir,omitempty"`
	// log file directory
	LogDir string `yaml:"logDir,omitempty"`
	// tls file directory
	TlsDir string `yaml:"tlsDir,omitempty"`
	// node key directory
	KeyDir string `yaml:"keyDir,omitempty"`
	// blockchain data directory
	ChainDir string `yaml:"chainDir,omitempty"`
	// engine config file name
	EngineConf string `yaml:"engineConf,omitempty"`
	// log config file name
	LogConf string `yaml:"logConf,omitempty"`
	// server config file name
	ServConf string `yaml:"servConf,omitempty"`
	// network config file name
	NetConf string `yaml:"netConf,omitempty"`
	// ledger config file name
	LedgerConf string `yaml:"ledgerConf,omitempty"`
	// metric switch
	MetricSwitch bool `yaml:"metricSwitch,omitempty"`
}

func LoadEnvConf(cfgFile string) (*EnvConf, error) {
	cfg := GetDefEnvConf()
	err := cfg.loadConf(cfgFile)
	if err != nil {
		return nil, fmt.Errorf("load env config failed.err:%s", err)
	}

	// 修改根目录。优先级：1:X_ROOT_PATH 2:配置文件设置 3:当前bin文件上级目录
	rt := xutils.GetXRootPath()
	if rt != "" {
		cfg.RootPath = rt
	}

	return cfg, nil
}

func GetDefEnvConf() *EnvConf {
	return &EnvConf{
		// 默认设置为当前执行目录
		RootPath:     xutils.GetCurRootDir(),
		ConfDir:      "conf",
		DataDir:      "data",
		LogDir:       "logs",
		TlsDir:       "tls",
		KeyDir:       "keys",
		ChainDir:     "blockchain",
		EngineConf:   "engine.yaml",
		LogConf:      "log.yaml",
		ServConf:     "server.yaml",
		NetConf:      "network.yaml",
		LedgerConf:   "ledger.yaml",
		MetricSwitch: false,
	}
}

func (t *EnvConf) GenDirAbsPath(dir string) string {
	return filepath.Join(t.RootPath, dir)
}

func (t *EnvConf) GenDataAbsPath(dir string) string {
	return filepath.Join(t.GenDirAbsPath(t.DataDir), dir)
}

func (t *EnvConf) GenConfFilePath(fName string) string {
	return filepath.Join(t.GenDirAbsPath(t.ConfDir), fName)
}

func (t *EnvConf) loadConf(cfgFile string) error {
	if cfgFile == "" || !utils.FileIsExist(cfgFile) {
		return fmt.Errorf("config file set error.path:%s", cfgFile)
	}

	viperObj := viper.New()
	viperObj.SetConfigFile(cfgFile)
	err := viperObj.ReadInConfig()
	if err != nil {
		return fmt.Errorf("read config failed.path:%s,err:%v", cfgFile, err)
	}

	if err = viperObj.Unmarshal(t); err != nil {
		return fmt.Errorf("unmatshal config failed.path:%s,err:%v", cfgFile, err)
	}

	return nil
}

repository: CodeCmn/xupercore

repo_name: CodeCmn/xupercore


text:
%% This BibTeX bibliography file was created using BibDesk.
%% http://bibdesk.sourceforge.net/

%% Created for lukas_wampfler at 2018-05-31 15:58:13 +0200

%% Saved with string encoding Unicode (UTF-8)

@article{DBLP:journals/corr/MostafazadehCHP16,
  author    = {Nasrin Mostafazadeh and
               Nathanael Chambers and
               Xiaodong He and
               Devi Parikh and
               Dhruv Batra and
               Lucy Vanderwende and
               Pushmeet Kohli and
               James F. Allen},
  title     = {A Corpus and Evaluation Framework for Deeper Understanding of Commonsense
               Stories},
  journal   = {CoRR},
  volume    = {abs/1604.01696},
  year      = {2016},
  url       = {http://arxiv.org/abs/1604.01696},
  archivePrefix = {arXiv},
  eprint    = {1604.01696},
  timestamp = {Wed, 07 Jun 2017 14:42:53 +0200},
  biburl    = {https://dblp.org/rec/bib/journals/corr/MostafazadehCHP16},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}

@article{eff_framework,
	Archiveprefix = {arXiv},
	Author = {Lajanugen Logeswaran and Honglak Lee},
	Bibsource = {dblp computer science bibliography, https://dblp.org},
	Biburl = {https://dblp.org/rec/bib/journals/corr/abs-1803-02893},
	Date-Modified = {2018-05-31 12:44:55 +0000},
	Eprint = {1803.02893},
	Journal = {CoRR},
	Timestamp = {Tue, 10 Apr 2018 20:50:05 +0200},
	Title = {An efficient framework for learning sentence representations},
	Url = {http://arxiv.org/abs/1803.02893},
	Volume = {abs/1803.02893},
	Year = {2018},
	Bdsk-Url-1 = {http://arxiv.org/abs/1803.02893}}

@inproceedings{pennington2014glove,
  author = {Jeffrey Pennington and Richard Socher and Christopher D. Manning},
  booktitle = {Empirical Methods in Natural Language Processing (EMNLP)},
  title = {GloVe: Global Vectors for Word Representation},
  year = {2014},
  pages = {1532--1543},
  url = {http://www.aclweb.org/anthology/D14-1162},
}

@InProceedings{mostafazadeh-EtAl:2016:N16-1,
  author    = {Mostafazadeh, Nasrin  and  Chambers, Nathanael  and  He, Xiaodong  and  Parikh, Devi  and  Batra, Dhruv  and  Vanderwende, Lucy  and  Kohli, Pushmeet  and  Allen, James},
  title     = {A Corpus and Cloze Evaluation for Deeper Understanding of Commonsense Stories},
  booktitle = {Proceedings of the 2016 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies},
  month     = {June},
  year      = {2016},
  address   = {San Diego, California},
  publisher = {Association for Computational Linguistics},
  pages     = {839--849},
  url       = {http://www.aclweb.org/anthology/N16-1098}
}

@inproceedings{Roemmele2017AnRB,
  title={An RNN-based Binary Classifier for the Story Cloze Test},
  author={Melissa Roemmele and Sosuke Kobayashi and Naoya Inoue and Andrew M. Gordon},
  year={2017}
}

@InProceedings{mostafazadeh-EtAl:2016:RepEval,
  author    = {Mostafazadeh, Nasrin  and  Vanderwende, Lucy  and  Yih, Wen-tau  and  Kohli, Pushmeet  and  Allen, James},
  title     = {Story Cloze Evaluator: Vector Space Representation Evaluation by Predicting What Happens Next},
  booktitle = {Proceedings of the 1st Workshop on Evaluating Vector-Space Representations for NLP},
  month     = {August},
  year      = {2016},
  address   = {Berlin, Germany},
  publisher = {Association for Computational Linguistics},
  pages     = {24--29},
  url       = {http://anthology.aclweb.org/W16-2505}
}

gha_language: Jupyter Notebook

extension: bib


text:
@article{2017arXivtriviaqa,
       author = {{Joshi}, Mandar and {Choi}, Eunsol and {Weld},
                 Daniel and {Zettlemoyer}, Luke},
        title = "{triviaqa: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension}",
      journal = {arXiv e-prints},
         year = 2017,
          eid = {arXiv:1705.03551},
        pages = {arXiv:1705.03551},
archivePrefix = {arXiv},
       eprint = {1705.03551},
}

repository: tensorflow/datasets

repo_name: tensorflow/datasets

gha_language: Python


text:
package cmd

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/driusan/dgit/git"
)

func CheckIgnore(c *git.Client, args []string) error {
	flags := flag.NewFlagSet("check-ignore", flag.ExitOnError)
	flags.SetOutput(flag.CommandLine.Output())
	flags.Usage = func() {
		flag.Usage()
		fmt.Fprintf(flag.CommandLine.Output(), "\n\nOptions:\n")
		flags.PrintDefaults()
	}

	quiet := false
	flags.BoolVar(&quiet, "quiet", false, "Don't output anything, just set exit status. This is only valid with a single pathname.")
	flags.BoolVar(&quiet, "q", false, "Alias for --quiet")
	verbose := false
	flags.BoolVar(&verbose, "verbose", false, "Also output details about the matching pattern (if any) for each given pathname.")
	flags.BoolVar(&verbose, "v", false, "Alias for --verbose")
	nonMatch := false
	flags.BoolVar(&nonMatch, "non-matching", false, "Show given paths which don’t match any pattern.")
	flags.BoolVar(&nonMatch, "n", false, "Alias for --non-matching.")

	stdin := false
	flags.BoolVar(&stdin, "stdin", false, "Read pathnames from the standard input, one per line, instead of from the command-line.")

	noIndex := false
	flags.BoolVar(&noIndex, "no-index", false, "Don’t look in the index when undertaking the checks.")

	machine := false
	flags.BoolVar(&machine, "z", false, "The output format is modified to be machine-parseable.")

	flags.Parse(args)
	args = flags.Args()

	if dir, err := os.Getwd(); err == nil && (dir == c.GitDir.String() || strings.HasPrefix(dir, c.GitDir.String()+"/")) {
		fmt.Fprintf(flag.CommandLine.Output(), "fatal: This operation must be run in a work tree\n")
		flags.Usage()
		os.Exit(128)
	}

	if machine && !stdin {
		fmt.Fprintf(flag.CommandLine.Output(), "fatal: -z only makes sense with --stdin\n")
		flags.Usage()
		os.Exit(128)
	}

	if !stdin && len(args) < 1 {
		fmt.Fprintf(flag.CommandLine.Output(), "fatal: no path specified\n")
		flags.Usage()
		os.Exit(128)
	} else if stdin && len(args) > 0 {
		fmt.Fprintf(flag.CommandLine.Output(), "fatal: cannot specify pathnames with --stdin\n")
		flags.Usage()
		os.Exit(128)
	} else if quiet && len(args) != 1 && !stdin {
		fmt.Fprintf(flag.CommandLine.Output(), "fatal: --quiet is only valid with a single pathname\n")
		flags.Usage()
		os.Exit(128)
	} else if quiet && verbose {
		fmt.Fprintf(flag.CommandLine.Output(), "fatal: cannot have both --quiet and --verbose\n")
		flags.Usage()
		os.Exit(128)
	}

	if !stdin {
		paths := make([]git.File, 0, len(args))

		// Assemble the list of files, checking for any invalid input
		for _, p := range args {
			f := git.File(p)
			if s, submodule, _ := f.IsInSubmodule(c); s {
				fmt.Fprintf(os.Stderr, "fatal: Pathspec '%v' is in submodule '%s'\n", p, submodule)
				os.Exit(128)
			}
			if i, _ := f.IsInsideSymlink(); i {
				fmt.Fprintf(os.Stderr, "fatal: pathspec '%v' is beyond a symbolic link\n", p)
				os.Exit(128)
			}

			paths = append(paths, git.File(p))
		}

		// Invoke the ignore routines directly, rather than relying on
		//  LsFiles because we need to be able to do things such as
		//  return non-matches and match details that aren't supported there.
		// Note that check-ignore has no choice but to use standard ignore
		//  patterns. There is no way to specify custom patterns on the command-line.
		standardIgnores, err := git.StandardIgnorePatterns(c, paths)
		if err != nil {
			return err
		}

		exitCode := 1

		for _, path := range paths {
			matches, err := git.MatchIgnores(c, standardIgnores, []git.File{path})
			if err != nil {
				return err
			}

			match := matches[0]

			// Zero out any match pattern if it's in the index and the no-index options was
			//  not specified.
			if !noIndex {
				entries, _ := git.LsFiles(c, git.LsFilesOptions{Cached: true, Others: false, ExcludeStandard: false}, []git.File{path})
				if len(entries) > 0 {
					match.IgnorePattern = git.IgnorePattern{}
				}
			}

			if match.Pattern != "" || nonMatch {
				if !quiet && !verbose {
					fmt.Printf("%s\n", match.PathName)
				} else if !quiet && verbose {
					fmt.Printf("%s\n", match)
				}

				if match.Pattern != "" {
					exitCode = 0
				}
			}
		}

		os.Exit(exitCode)
	} else {
		reader := bufio.NewReader(os.Stdin)
		exitCode := 1

		for {
			path := ""
			isEof := false

			if !machine {
				for {
					lineBytes, isPrefix, err := reader.ReadLine()
					path = path + string(lineBytes)
					if err == io.EOF {
						isEof = true
					}
					if !isPrefix {
						break
					}
				}
			} else {
				p, err := reader.ReadString(0)
				path = p
				if err == io.EOF {
					isEof = true
				}
			}

			if path == "" {
				os.Exit(1)
			}

			f := git.File(path)
			if s, submodule, _ := f.IsInSubmodule(c); s {
				fmt.Fprintf(os.Stderr, "fatal: Pathspec '%v' is in submodule '%s'\n", path, submodule)
				os.Exit(128)
			}
			if i, _ := f.IsInsideSymlink(); i {
				fmt.Fprintf(os.Stderr, "fatal: pathspec '%v' is beyond a symbolic link", path)
				os.Exit(128)
			}

			// Invoke the ignore routines directly, rather than relying on
			//  LsFiles because we need to be able to do things such as
			//  return non-matches and match details that aren't supported there.
			// Note that check-ignore has no choice but to use standard ignore
			//  patterns. There is no way to specify custom patterns on the command-line.
			standardIgnores, err := git.StandardIgnorePatterns(c, []git.File{git.File(path)})
			if err != nil {
				return err
			}

			matches, err := git.MatchIgnores(c, standardIgnores, []git.File{git.File(path)})
			if err != nil {
				return err
			}

			match := matches[0]

			// Zero out any match pattern if it's in the index and the no-index options was
			//  not specified.
			if !noIndex {
				entries, _ := git.LsFiles(c, git.LsFilesOptions{Cached: true, Others: false, ExcludeStandard: false}, []git.File{git.File(path)})
				if len(entries) > 0 {
					match.IgnorePattern = git.IgnorePattern{}
				}
			}

			if match.Pattern != "" || nonMatch {
				if !quiet && !verbose {
					fmt.Printf("%s", match.PathName.String())
					if !machine {
						fmt.Printf("\n")
					} else {
						os.Stdout.Write([]byte{0})
					}
				} else if !quiet && verbose && !machine {
					fmt.Printf("%s\n", match)
				} else if !quiet && verbose && machine {
					fmt.Printf("%s", match.Source)
					os.Stdout.Write([]byte{0})
					fmt.Printf("%s", match.LineString())
					os.Stdout.Write([]byte{0})
					fmt.Printf("%s", match.Pattern)
					os.Stdout.Write([]byte{0})
					fmt.Printf("%s", match.PathName)
				}

				if match.Pattern != "" {
					exitCode = 0
				}
			}

			if isEof {
				os.Exit(exitCode)
			}
		}
	}
	return nil
}

repository: driusan/dgit

repo_name: driusan/dgit


text:
@article{Harper2012hgy,
 abstract = {The Web Content Accessibility Guidelines (WCAG) 2.0 separate testing into both ``Machine'' and ``Human'' audits; and further classify ``Human Testability'' into ``Reliably Human Testable'' and ``Not Reliably Testable''; it is human testability that is the focus of this paper. We wanted to investigate the likelihood that ``at least 80% of knowledgeable human evaluators would agree on the conclusion'' of an accessibility audit, and therefore understand the percentage of success criteria that could be described as reliably human testable, and those that could not. In this case, we recruited twenty-five experienced evaluators to audit four pages for WCAG 2.0 conformance. These pages were chosen to differ in layout, complexity, and accessibility support, thereby creating a small but variable sample.

We found that an 80% agreement between experienced evaluators almost never occurred and that the average agreement was at the 70--75% mark, while the error rate was around 29%. Further, trained---but novice---evaluators performing the same audits exhibited the same agreement to that of our more experienced ones, but a reduction on validity of 6--13% ; the validity that an untrained user would attain can only be a conjecture. Expertise appears to improve (by 19%) the ability to avoid false positives. Finally, pooling the results of two independent experienced evaluators would be the best option, capturing at most 76% of the true problems and producing only 24% of false positives. Any other independent combination of audits would achieve worse results.

This means that an 80% target for agreement, when audits are conducted without communication between evaluators, is not attainable, even with experienced evaluators, when working on pages similar to the ones used in this experiment; that the error rate even for experienced evaluators is relatively high and further, that untrained accessibility auditors be they developers or quality testers from other domains, would do much worse than this.},
 address = {New York, NY, USA},
 author = {Brajnik, Giorgio and Yesilada, Yeliz and Harper, Simon},
 doi = {10.1145/2141943.2141946},
 issn = {1936-7228},
 journal = {ACM Trans. Access. Comput.},
 keywords = {Accessibility Guidelines,Evaluation,Web accessibility},
 month = {mar},
 number = {2},
 pages = {8:1----8:28},
 publisher = {ACM},
 title = {Is accessibility conformance an elusive property? A study of validity and reliability of WCAG 2.0},
 url = {http://www.simonharper.info/publications/Harper2012hgy.pdf},
 volume = {4},
 year = {2012}
}

repository: sharpic/academic-kickstart

repo_name: sharpic/academic-kickstart


text:
@article{sabeti_signal_2019,
 abstract = {Pulse oximetry is a noninvasive and low-cost physiological monitor that measures blood oxygen levels. While the noninvasive nature of pulse oximetry is advantageous, the estimates of oxygen saturation generated by these devices are prone to motion artifacts and ambient noise, reducing the reliability of such estimations. Clinicians combat this by assessing the quality of oxygen saturation estimation by visual inspection of the photo plethysmograph (PPG), which represents changes in pulsatile blood volume and is also generated by the pulse oximeter. In this paper, we propose six morphological features that can be used to determine the quality of the PPG signal and generate a signal quality index. Unlike many similar studies, this approach uses machine learning and does not require a separate signal, such as ECG, for reference. Multiple algorithms were tested against 46 30min PPG segments of patients with cardiovascular and respiratory conditions, including atrial fibrillation, hypoxia, acute heart failure, pneumonia, ARDS, and pulmonary embolism. These signals were independently annotated for signal quality by two clinicians, with the union of their annotations used as the ground-truth. Similar to any physiological signal recorded in a clinical setting, the utilized dataset is also unbalanced in favor of good quality segments. The experiments showed that a cost-sensitive Support Vector Machine (SVM) outperformed other tested methods and was robust to the unbalanced nature of the data. Though the proposed algorithm was tested on PPG signals, the methodology remains agnostic to the dataset used, and may be applied to any type of pulsatile physiological signal.},
 author = {Sabeti, Elyas and Reamaroon, Narathip and Mathis, Michael and Gryak, Jonathan and Sjoding, Michael and Najarian, Kayvan},
 copyright = {All rights reserved},
 doi = {10.1016/j.imu.2019.100222},
 file = {Sabeti et al. - 2019 - Signal quality measure for pulsatile physiological.pdf:/Users/Narathip/Zotero/storage/3JLKD97E/Sabeti et al. - 2019 - Signal quality measure for pulsatile physiological.pdf:application/pdf},
 issn = {23529148},
 journal = {Informatics in Medicine Unlocked},
 language = {en},
 pages = {100222},
 shorttitle = {Signal quality measure for pulsatile physiological signals using morphological features},
 title = {Signal quality measure for pulsatile physiological signals using morphological features: Applications in reliability measure for pulse oximetry},
 url = {https://linkinghub.elsevier.com/retrieve/pii/S2352914819301856},
 urldate = {2020-06-18},
 volume = {16},
 year = {2019}
}

repository: nreamaroon/academic-kickstart

repo_name: nreamaroon/academic-kickstart


text:
@misc{Bentov2014,
abstract = {We study cryptocurrency protocols that do not make use of {\{}$\backslash$em Proof of Work{\}}. Such protocols commonly rely on {\{}$\backslash$em Proof of Stake{\}}, i.e., on mechanisms that extend voting power to the stakeholders of the system. We offer analysis of existing protocols that have a substantial amount of popularity. We then present our novel pure {\{}$\backslash$em Proof of Stake{\}} protocols, and argue that the they help in mitigating problems that the existing protocols suffer from.},
archivePrefix = {arXiv},
arxivId = {1406.5694},
author = {Bentov, Iddo and Gabizon, Ariel and Mizrahi, Alex},
eprint = {1406.5694},
keywords = {blockchain building,consensus,proof-pf-stake},
mendeley-tags = {blockchain building,consensus,proof-pf-stake},
number = {240258},
pages = {1--10},
title = {{Cryptocurrencies without Proof of Work}},
url = {http://arxiv.org/pdf/1406.5694.pdf},
urldate = {2015-09-28},
year = {2014}
}
@misc{Bentov2013,
abstract = {We propose a new protocol for a cryptocurrency, that builds upon the Bitcoin protocol by combining its Proof of Work component with a Proof of Stake type of system. Our Proof of Activity (PoA) protocol offers good security against possibly practical future attacks on Bitcoin, and has a relatively low penalty in terms of network communication and storage space. We explore various attack scenarios and suggest remedies to potential vulnerabilities of the PoA protocol, as well as evaluate the performance of its core subroutine.},
author = {Bentov, Iddo and Lee, Charles and Mizrahi, Alex and Rosenfeld, Meni},
keywords = {bitcoin,proof of activity,proof of stake},
mendeley-tags = {bitcoin,proof of activity,proof of stake},
number = {3},
pages = {1--19},
title = {{Proof of Activity: Extending Bitcoin’s Proof of Work via Proof of Stake}},
url = {http://eprint.iacr.org/2014/452.pdf},
urldate = {2015-10-20},
volume = {42},
year = {2013}
}
@article{Bonneau2014,
abstract = {We formalize the use of Bitcoin as a source of publicly-verifiable randomness. As a side-effect of Bitcoin's proof-of-work-based consensus system, random values are broadcast every time new blocks are mined. We can derive strong lower bounds on the computational min-entropy in each block: currently, at least 68 bits of min-entropy are produced every 10 minutes, from which one can derive over 32 near-uniform bits using standard extractor techniques. We show that any attack on this beacon would form an attack on Bitcoin itself and hence have a monetary cost that we can bound, unlike any other construction for a public randomness beacon in the literature. In our simplest construction, we show that a lottery producing a single unbiased bit is manipulation-resistant against an attacker with a stake of less than 50 bitcoins in the output, or about US{\$}12,000 today. Finally, we propose making the beacon output available to smart contracts and demonstrate that this simple tool enables a number of interesting applications.},
author = {Bonneau, Joseph and Goldfeder, Steven and Clark, Jeremy},
file = {:home/kushti/.local/share/data/Mendeley Ltd./Mendeley Desktop/Downloaded/Bonneau, Clark, Goldfeder - Unknown - On Bitcoin as a public randomness source.pdf:pdf},
keywords = {bitcoin,public random beacon},
mendeley-tags = {bitcoin,public random beacon},
title = {{On Bitcoin as a public randomness source}},
url = {https://eprint.iacr.org/2015/1015.pdf},
year = {2014}
}
@misc{Bonneau2015,
abstract = {Bitcoin has emerged as the most successful cryptographic currency in history. Within two years of its quiet launch in 2009, Bitcoin grew to comprise billions of dollars of economic value despite only cursory analysis of the system’s design. Since then a growing literature has identified hidden-but-important properties of the system, discovered attacks, proposed promising alternatives, and singled out difficult future challenges. Meanwhile a large and vibrant open-source community has proposed and deployed numerous modifications and extensions. We provide the first systematic exposition Bitcoin and the many related cryptocurrencies or ‘altcoins.’ Drawing from a scattered body of knowledge, we identify three key components of Bitcoin’s design that can be decoupled. This enables a more insightful analysis of Bitcoin’s properties and future stability. We map the design space for numerous proposed modifications, providing comparative analyses for alternative consensus mechanisms, currency allocation mechanisms, computational puzzles, and key management tools. We survey anonymity issues in Bitcoin and provide an evaluation framework for analyzing a variety of privacy-enhancing proposals. Finally we provide new insights on what we term disintermediation protocols, which absolve the need for trusted intermediaries in an interesting set of applications. We identify three general disintermediation strategies and provide a detailed comparison.},
author = {Bonneau, Joseph (Stanford University) and Miller, Andrew (University of Maryland) and Clark, Jeremy (Concordia University) and Narayanan, Arvind (Princeton University) and Kroll, Joshua (Princeton University) and Felten, Edward (Princeton University)},
doi = {10.1109/SP.2015.14},
isbn = {978-1-4673-6949-7},
issn = {1081-6011},
keywords = {bitcoin,cryptocurrency},
mendeley-tags = {bitcoin,cryptocurrency},
title = {{SoK : Research Perspectives and Challenges for Bitcoin and Cryptocurrencies}},
url = {http://www.ieee-security.org/TC/SP2015/papers-archived/6949a104.pdf},
urldate = {2015-12-21},
year = {2015}
}
@misc{Davarpanah2015,
abstract = {Preface The NeuCoin Project hopes that this white paper will spark an honest, fact-based debate on the pros and cons of the two main systems used to provide security for peer-to-peer cryptocurrencies: proof-of-work and proof-of-stake. NeuCoin believes that its own proof-of-stake design fully solves the security and central-ization problems with earlier proof-of-stake coins, as well as the mounting cost and increasing centralization problems faced by proof-of-work systems. As such, NeuCoin is the first peer-to-peer cryptocurrency, regardless of technology, that is secure, cost-efficient and decentralized in the long run. The NeuCoin Project is inviting all members of the cryptocurrency community to make comments, suggest edits, and point out potential flaws in the paper. NeuCoin bounties will be rewarded by the NeuCoin Code foundation for all constructive input, both positive and critical (click here for details). Note that this paper does not discuss consensus algorithms based on trusted nodes (the systems used by Ripple and Stellar) because while that protocol has similar benefits to those of proof-of-stake, it requires users to trust third parties and beyond that, depends on trustworthy third parties to support the network by operating nodes, which may or may not happen over time. Also not covered in this paper is the enormous side benefit derived from not having to distribute the currency supply to proof-of-work miners to cover their operating costs. Capitalizing on this opportunity, NeuCoin distributes the currency strategically to all the participants who increase its utility and value. Please visit NeuCoin's wiki 1 for a summary of NeuCoin's distribution and user adoption plans. 1 neucoin.org/en/wiki 1 Abstract NeuCoin is a decentralized peer-to-peer cryptocurrency derived from Sunny King's Peercoin, which itself was derived from Satoshi Nakamoto's Bitcoin. As with Peercoin, proof-of-stake replaces proof-of-work as NeuCoin's consensus mechanism, effectively re-placing the operating costs of Bitcoin miners (electricity, computers) with the capital costs of holding the currency. Proof-of-stake also avoids proof-of-work's inherent tendency to-wards centralization resulting from competition for coinbase rewards among miners based on lowest cost electricity and hash power. NeuCoin increases security relative to Peercoin and other existing proof-of-stake cur-rencies in numerous ways, including: (1) incentivizing nodes to continuously stake coins over time through substantially higher mining rewards and lower minimum stake age; (2) abandoning the use of coin age in the mining formula; (3) causing the stake modifier pa-rameter to change over time for each stake; and (4) utilizing a client that punishes nodes that attempt to mine on multiple branches with duplicate stakes. This paper demonstrates how NeuCoin's proof-of-stake implementation addresses all commonly raised " nothing at stake " objections to generic proof-of-stake systems. It also reviews many of the flaws of proof-of-work designs to highlight the potential for an alter-nate cryptocurrency that solves these flaws.},
author = {Davarpanah, Kourosh and Kaufman, Dan and Pubellier, Ophelie},
keywords = {neucoin,proof-of-stake},
mendeley-tags = {neucoin,proof-of-stake},
title = {{NeuCoin: the First Secure, Cost-efficient and Decentralized Cryptocurrency}},
url = {http://www.neucoin.org/en/whitepaper/download},
urldate = {2015-12-15},
year = {2015}
}
@misc{Renesse,
abstract = {Cryptocurrencies, based on and led by Bitcoin, have shown promise as infrastructure for pseudonymous online payments, cheap remittance, trustless digital asset exchange, and smart contracts. However, Bitcoin-derived blockchain protocols have inherent scalability limits that trade-off between throughput and latency and withhold the realization of this potential. This paper presents Bitcoin-NG, a new blockchain protocol designed to scale. Based on Bitcoin's blockchain protocol, Bitcoin-NG is Byzantine fault tolerant, is robust to extreme churn, and shares the same trust model obviating qualitative changes to the ecosystem. In addition to Bitcoin-NG, we introduce several novel metrics of interest in quantifying the security and efficiency of Bitcoin-like blockchain protocols. We implement Bitcoin-NG and perform large-scale experiments at 15{\%} the size of the operational Bitcoin system, using unchanged clients of both protocols. These experiments demonstrate that Bitcoin-NG scales optimally, with bandwidth limited only by the capacity of the individual nodes and latency limited only by the propagation time of the network.},
archivePrefix = {arXiv},
arxivId = {1510.02037},
author = {Eyal, Ittay and Gencer, Adem Efe and Sirer, Emin Gun and van Renesse, Robbert},
eprint = {1510.02037},
keywords = {bitcoin,bitcoin-ng,blockchain scalability,cryptocurrency},
mendeley-tags = {bitcoin,bitcoin-ng,blockchain scalability,cryptocurrency},
title = {{Bitcoin-NG: A Scalable Blockchain Protocol}},
url = {http://arxiv.org/abs/1510.02037},
urldate = {2015-10-16},
year = {2015}
}
@misc{Garay2015,
abstract = {Bitcoin is the first andmost popular decentralized cryptocur- rency to date. In this work, we extract and analyze the core of the Bitcoin protocol, which we term the Bitcoin backbone, and prove two of its fun- damental properties which we call common prefix and chain quality in the static setting where the number of players remains fixed. Our proofs hinge on appropriate and novel assumptions on the “hashing power” of the adversary relative to network synchronicity; we show our results to be tight under high synchronization. Next, we propose and analyze applications that can be built “on top” of the backbone protocol, specifically focusing on Byzantine agreement (BA) and on the notion of a public transaction ledger. Regarding BA, we observe that Nakamoto’s suggestion falls short of solving it, and present a simple alternative which works assuming that the adversary’s hashing power is bounded by 1/3. The public transaction ledger captures the essence of Bitcoin’s operation as a cryptocurrency, in the sense that it guarantees the liveness and persistence of committed transactions. Based on this notion we describe and analyze the Bitcoin system as well as a more elaborate BA protocol, proving them secure assuming high net- work synchronicity and that the adversary’s hashing power is strictly less than 1/2, while the adversarial bound needed for security decreases as the network desynchronizes. 1},
author = {Garay, Juan and B, Aggelos Kiayias and Leonardos, Nikos},
booktitle = {Advances in Cryptology -EUROCRYPT 2015},
isbn = {978-3-662-46802-9},
keywords = {Bitcoin,Decentralized Consensus,Formal Modelling,PoW},
mendeley-tags = {Bitcoin,Decentralized Consensus,Formal Modelling,PoW},
pages = {281--310},
title = {{The Bitcoin Backbone Protocol: Analysis and Applications}},
urldate = {2015-10-11},
volume = {9057},
year = {2015}
}
@misc{King2012,
abstract = {A peer-to-peer crypto-currency design derived from Satoshi Nakamoto’s Bitcoin. Proof-of-stake replaces proof-of-work to provide most of the network security. Under this hybrid design proof-of-work mainly provides initial minting and is largely non-essential in the long run. Security level of the network is not dependent on energy consumption in the long term thus providing an energy- efficient and more cost-competitive peer-to-peer crypto-currency. Proof-of-stake is based on coin age and generated by each node via a hashing scheme bearing similarity to Bitcoin’s but over limited search space. Block chain history and transaction settlement are further protected by a centrally broadcasted checkpoint mechanism.},
author = {King, Sunny and Nadal, Scott},
booktitle = {Ppcoin.Org},
keywords = {peercoin,proof-of-stake},
mendeley-tags = {peercoin,proof-of-stake},
title = {{PPCoin: Peer-to-Peer Crypto-Currency with Proof-of-Stake}},
url = {http://ppcoin.org/static/ppcoin-paper.pdf},
urldate = {2015-12-14},
year = {2012}
}
@misc{Kondor2014,
abstract = {The possibility to analyze everyday monetary transactions is limited by the scarcity of available data, as this kind of information is usually considered highly sensitive. Present econophysics models are usually employed on presumed random networks of interacting agents, and only some macroscopic properties (e.g. the resulting wealth distribution) are compared to real-world data. In this paper, we analyze Bitcoin, which is a novel digital currency system, where the complete list of transactions is publicly available. Using this dataset, we reconstruct the network of transactions and extract the time and amount of each payment. We analyze the structure of the transaction network by measuring network characteristics over time, such as the degree distribution, degree correlations and clustering. We find that linear preferential attachment drives the growth of the network. We also study the dynamics taking place on the transaction network, i.e. the flow of money. We measure temporal patterns and the wealth accumulation. Investigating the microscopic statistics of money movement, we find that sublinear preferential attachment governs the evolution of the wealth distribution. We report a scaling law between the degree and wealth associated to individual nodes.},
archivePrefix = {arXiv},
arxivId = {1308.3892},
author = {Kondor, D{\'{a}}niel and P{\'{o}}sfai, M{\'{a}}rton and Csabai, Istv{\'{a}}n and Vattay, G{\'{a}}bor},
booktitle = {PLoS ONE},
doi = {10.1371/journal.pone.0086197},
eprint = {1308.3892},
isbn = {1932-6203},
issn = {1932-6203},
keywords = {bitcoin},
mendeley-tags = {bitcoin},
number = {2},
pages = {e86197},
pmid = {24505257},
title = {{Do the Rich Get Richer? An Empirical Analysis of the Bitcoin Transaction Network}},
urldate = {2015-12-20},
volume = {9},
year = {2014}
}
@misc{Kwon,
author = {Kwon, Jae},
keywords = {byzantine agreement,proof-of-stake,tendermint},
mendeley-tags = {byzantine agreement,proof-of-stake,tendermint},
pages = {1--10},
title = {{TenderMint : Consensus without Mining}},
url = {http://tendermint.com/docs/tendermint{\_}v04.pdf},
urldate = {2015-10-26}
}
@article{Luu,
abstract = {Cryptocurrencies like Bitcoin and the more recent Ethereum system allow users to specify scripts in transactions and con-tracts to support applications beyond simple cash transac-tions. In this work, we analyze the extent to which these systems can enforce the correct semantics of scripts. We show that when a script execution requires nontrivial com-putation effort, practical attacks exist which either waste miners' computational resources or lead miners to accept incorrect script results. These attacks drive miners to an ill-fated choice, which we call the verifier's dilemma, whereby rational miners are well-incentivized to accept unvalidated blockchains. We call the framework of computation through a scriptable cryptocurrency a consensus computer and de-velop a model that captures incentives for verifying com-putation in it. We propose a resolution to the verifier's dilemma which incentivizes correct execution of certain ap-plications, including outsourced computation, where scripts require minimal time to verify. Finally we discuss two dis-tinct, practical implementations of our consensus computer in real cryptocurrency networks like Ethereum.},
author = {Luu, Loi and Teutsch, Jason and Kulkarni, Raghav and Saxena, Prateek},
doi = {10.1145/2810103.2813659},
isbn = {9781450338325},
keywords = {Electronic Commerce—Cybercash,Ethereum,General— Security and protection,K44 [Computers And Society],consensus computer,cryptocurrency,digital cash Keywords Bitcoin,distributed consensus,ethereum,incentive compatibility,verifiable computation},
mendeley-tags = {distributed consensus,ethereum},
title = {{Demystifying Incentives in the Consensus Computer}},
url = {http://eprint.iacr.org/2015/702}
}
@misc{Miller2014a,
author = {Miller, Andrew and Jr, Jj LaViola},
booktitle = {UCF Tech Report. CS-TR-14-01.},
keywords = {Bitcoin,anonymous byzantine consensus,proof-of-work},
mendeley-tags = {Bitcoin,anonymous byzantine consensus,proof-of-work},
title = {{Anonymous Byzantine Consensus from Moderately-Hard Puzzles: A Model for Bitcoin}},
urldate = {2015-12-15},
year = {2014}
}
@misc{Miller2014,
abstract = {Bit coin is widely regarded as the first broadly successful e-cash system. An oft-cited concern, though, is that mining Bit coins wastes computational resources. Indeed, Bit coin's underlying mining mechanism, which we call a scratch-off puzzle (SOP), involves continuously attempting to solve computational puzzles that have no intrinsic utility. We propose a modification to Bit coin that repurposes its mining resources to achieve a more broadly useful goal: distributed storage of archival data. We call our new scheme Perm coin. Unlike Bit coin and its proposed alternatives, Perm coin requires clients to invest not just computational resources, but also storage. Our scheme involves an alternative scratch-off puzzle for Bit coin based on Proofs-of-Retrievability (PORs). Successfully minting money with this SOP requires local, random access to a copy of a file. Given the competition among mining clients in Bit coin, this modified SOP gives rise to highly decentralized file storage, thus reducing the overall waste of Bit coin. Using a model of rational economic agents we show that our modified SOP preserves the essential properties of the original Bit coin puzzle. We also provide parameterizations and calculations based on realistic hardware constraints to demonstrate the practicality of Perm coin as a whole.},
author = {Miller, Andrew and Juels, Ari and Shi, Elaine and Parno, Bryan and Katz, Jonathan},
booktitle = {2014 IEEE Symposium on Security and Privacy},
doi = {10.1109/SP.2014.37},
isbn = {978-1-4799-4686-0},
issn = {1081-6011},
keywords = {Bit coin mining,Bitcoin,Data mining,Investment,Online banking,Outsourcing,Peer-to-peer computing,Perm coin,Permacoin,Proof-of-Retrievability,Public key,archival data,blockchain scalability,computational puzzles,computational resources,cryptocurrency,data mining,data preservation,digital storage,distributed storage,e-cash system,electronic money,proofs-of-retrievability,rational economic agents,scratch-off puzzle},
mendeley-tags = {Proof-of-Retrievability,blockchain scalability,cryptocurrency},
pages = {475--490},
title = {{Permacoin: Repurposing Bitcoin Work for Data Preservation}},
url = {http://ieeexplore.ieee.org/lpdocs/epic03/wrapper.htm?arnumber=6956582},
urldate = {2015-09-11},
year = {2014}
}
@misc{Mills1991,
abstract = {The network time protocol (NTP), which is designed to distribute$\backslash$ntime information in a large, diverse system, is described. It uses a$\backslash$nsymmetric architecture in which a distributed subnet of time servers$\backslash$noperating in a self-organizing, hierarchical configuration synchronizes$\backslash$nlocal clocks within the subnet and to national time standards via wire,$\backslash$nradio, or calibrated atomic clock. The servers can also redistribute$\backslash$ntime information within a network via local routing algorithms and time$\backslash$ndaemons. The NTP synchronization system, which has been in regular$\backslash$noperation in the Internet for the last several years, is described,$\backslash$nalong with performance data which show that timekeeping accuracy$\backslash$nthroughout most portions of the Internet can be ordinarily maintained to$\backslash$nwithin a few milliseconds, even in cases of failure or disruption of$\backslash$nclocks, time servers, or networks},
author = {Mills, D.L.},
booktitle = {IEEE Transactions on Communications},
doi = {10.1109/26.103043},
isbn = {0090-6778},
issn = {0090-6778},
keywords = {ntp},
mendeley-tags = {ntp},
number = {10},
pages = {1482--1493},
title = {{Internet time synchronization: the network time protocol}},
urldate = {2015-11-06},
volume = {39},
year = {1991}
}
@misc{Nakamoto2008,
abstract = {A purely peer-to-peer version of electronic cash would allow online payments to be sent directly from one party to another without going through a financial institution. Digital signatures provide part of the solution, but the main benefits are lost if a trusted third party is still required to prevent double-spending. We propose a solution to the double-spending problem using a peer-to-peer network. The network timestamps transactions by hashing them into an ongoing chain of hash-based proof-of-work, forming a record that cannot be changed without redoing the proof-of-work. The longest chain not only serves as proof of the sequence of events witnessed, but proof that it came from the largest pool of CPU power. As long as a majority of CPU power is controlled by nodes that are not cooperating to attack the network, they'll generate the longest chain and outpace attackers. The network itself requires minimal structure. Messages are broadcast on a best effort basis, and nodes can leave and rejoin the network at will, accepting the longest proof-of-work chain as proof of what happened while they were gone.},
author = {Nakamoto, Satoshi},
keywords = {bitcoin,whitepaper},
mendeley-tags = {bitcoin,whitepaper},
title = {{Bitcoin: A peer-to-peer electronic cash system}},
url = {https://bitcoin.org/bitcoin.pdf},
urldate = {2015-10-21},
year = {2008}
}
@article{Eyal2014,
abstract = {The Bitcoin cryptocurrency records its transactions in a public log called the blockchain. Its security rests critically on the distributed protocol that maintains the blockchain, run by participants called miners. Conventional wisdom asserts that the protocol is incentive-compatible and secure against colluding minority groups, i.e., it incentivizes miners to follow the protocol as prescribed. We show that the Bitcoin protocol is not incentive-compatible. We present an attack with which colluding miners obtain a revenue larger than their fair share. This attack can have significant consequences for Bitcoin: Rational miners will prefer to join the selfish miners, and the colluding group will increase in size until it becomes a majority. At this point, the Bitcoin system ceases to be a decentralized currency. Selfish mining is feasible for any group size of colluding miners. We pro- pose a practical modification to the Bitcoin protocol that protects against selfish mining pools that command less than 1/4 of the resources. This threshold is lower than the wrongly assumed 1/2 bound, but better than the current reality where a group of any size can compromise the system.},
archivePrefix = {arXiv},
arxivId = {1311.0243},
author = {Eyal, Ittay and Emin, G},
doi = {10.1007/978-3-662-45472-5{\_}28},
eprint = {1311.0243},
file = {:home/kushti/.local/share/data/Mendeley Ltd./Mendeley Desktop/Downloaded/Eyal, Sirer - 2013 - Majority is not Enough Bitcoin Mining is Vulnerable.pdf:pdf},
isbn = {978-3-662-45471-8, 978-3-662-45472-5},
journal = {Financial Cryptography and Data Security},
keywords = {bitcoin,proof-of-work},
mendeley-tags = {bitcoin,proof-of-work},
month = {nov},
number = {Jan},
pages = {436--454},
title = {{Majority is not Enough : Bitcoin Mining is Vulnerable}},
url = {http://arxiv.org/pdf/1311.0243v1.pdf},
year = {2014}
}
@techreport{Andruiman2014,
author = {Andruiman},
file = {:home/kushti/Downloads/multibranch.pdf:pdf},
keywords = {blocktree,forging,pos crypto-currencies,simulation},
title = {{PoS forging algorithms: formal approach and multibranch forging}},
url = {https://github.com/ConsensusResearch/articles-papers/blob/master/multibranch/multibranch.pdf},
year = {2014}
}
@article{Andruiman2015,
author = {Andruiman},
file = {:home/kushti/Downloads/multistrategy.pdf:pdf},
keywords = {blocktree,forging,pos crypto-currencies,simulation,strategy},
title = {{PoS forging algorithms: multi-strategy forging and related security issues}},
url = {https://github.com/ConsensusResearch/articles-papers/blob/master/multistrategy/multistrategy.pdf},
year = {2015}
}
@misc{Buterin,
author = {Buterin, V.},
keywords = {proof-of-stake},
mendeley-tags = {proof-of-stake},
title = {{On Stake}},
url = {https://blog.ethereum.org/2014/07/05/stake/},
urldate = {2015-12-31},
year = {2014}
}
@misc{Poelstra,
author = {Poelstra, A.},
title = {{On Stake and Consensus}},
url = {https://download.wpsoftware.net/bitcoin/pos.pdf},
urldate = {2015-12-31},
year = {2015}
}
@misc{Buterina,
author = {Buterin, V.},
keywords = {buterin,proof-of-stake},
mendeley-tags = {buterin,proof-of-stake},
title = {{Proof of Stake: How I Learned to Love Weak Subjectivity - Ethereum Blog}},
url = {https://blog.ethereum.org/2014/11/25/proof-stake-learned-love-weak-subjectivity/},
urldate = {2015-12-31},
year = {2014}
}
@misc{Chepurnoy,
author = {Chepurnoy, Alexander},
title = {{Interactive Proof-of-Stake simulation tools}},
url = {https://github.com/kushti/common-pos},
urldate = {2015-12-31}
}
@article{Cachin2005,
author = {Cachin, Christian and Kursawe, Klaus and Shoup, Victor},
doi = {10.1007/s00145-005-0318-0},
issn = {0933-2790},
journal = {Journal of Cryptology},
keywords = {byzantine agreement},
mendeley-tags = {byzantine agreement},
month = {may},
number = {3},
pages = {219--246},
title = {{Random Oracles in Constantinople: Practical Asynchronous Byzantine Agreement Using Cryptography}},
volume = {18},
year = {2005}
}

repository: kushti/common-pos

repo_name: kushti/common-pos


text:
/**
 * Created by nstyladmin on 4/12/2015.
 */
(function() {
    'use strict';

    angular
        .module('app')
        // create a constant for languages so they can be added to both triangular & translate
        .run(function($state){
            $state.go('authentication-home', {reload: true, inherit: false});

        })
    ;
})();

repository: georgiachr/app-based-on-md

repo_name: georgiachr/app-based-on-md

extension: js


text:
/*
Copyright 2022 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package web

import (
	"net/http"

	"github.com/gravitational/trace"
	"github.com/julienschmidt/httprouter"

	"github.com/gravitational/teleport/api/client/proto"
	"github.com/gravitational/teleport/lib/httplib"
	usagereporter "github.com/gravitational/teleport/lib/usagereporter/web"
)

// createPreUserEventHandle sends a user event to the UserEvent service
// this handler is for on-boarding user events pre-session
func (h *Handler) createPreUserEventHandle(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
	var req usagereporter.CreatePreUserEventRequest
	if err := httplib.ReadJSON(r, &req); err != nil {
		return nil, trace.Wrap(err)
	}

	if err := req.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}

	client := h.cfg.ProxyClient

	typedEvent, err := usagereporter.ConvertPreUserEventRequestToUsageEvent(req)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	event := &proto.SubmitUsageEventRequest{
		Event: typedEvent,
	}

	err = client.SubmitUsageEvent(r.Context(), event)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return nil, nil
}

// createUserEventHandle sends a user event to the UserEvent service
// this handler is for user events with a session
func (h *Handler) createUserEventHandle(w http.ResponseWriter, r *http.Request, params httprouter.Params, sctx *SessionContext) (interface{}, error) {
	var req usagereporter.CreateUserEventRequest
	if err := httplib.ReadJSON(r, &req); err != nil {
		return nil, trace.Wrap(err)
	}

	if err := req.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}

	client, err := sctx.GetClient()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	typedEvent, err := usagereporter.ConvertUserEventRequestToUsageEvent(req)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	event := &proto.SubmitUsageEventRequest{
		Event: typedEvent,
	}

	err = client.SubmitUsageEvent(r.Context(), event)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return nil, nil
}

repository: gravitational/teleport

repo_name: gravitational/teleport


text:
DESCRIPTION = "(super)class for representing nodes in a tree"
SECTION = "libs"
LICENSE = "Artistic|GPLv1+"
RDEPENDS_${PN} += "perl-module-strict"
BBCLASSEXTEND = "native"

PR = "r1"

SRC_URI = "http://search.cpan.org/CPAN/authors/id/C/CO/COGENT/Tree-DAG_Node-${PV}.tar.gz;name=tree-dag-node-perl-${PV}"
SRC_URI[tree-dag-node-perl-1.06.md5sum] = "3b006f128bd1d8961fc57c466ffa05f2"
SRC_URI[tree-dag-node-perl-1.06.sha256sum] = "502570774dd3bf11345fb028ca4cdd79f04db12ee68a826f0c44e24da0e3db2a"

S = "${WORKDIR}/Tree-DAG_Node-${PV}"

inherit cpan

PACKAGE_ARCH = "all"


text:
package ginsta

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/pkg/errors"
)

func (g *Ginsta) PostsByID(ctx context.Context, id string) ([]*Post, error) {
	endpoint, _ := endpointPosts(id)

	body, err := g.request(
		ctx,
		g.client,
		endpoint,
		"",
		false,
	)
	if err != nil {
		return nil, err
	}

	var posts postsData
	err = json.Unmarshal(body, &posts)
	if err != nil {
		return nil, err
	}

	if posts.Status != "ok" {
		return nil, errors.New("failure parsing posts")
	}

	var respondPosts []*Post

	if len(posts.Data.User.EdgeOwnerToTimelineMedia.Edges) == 0 {
		return respondPosts, nil
	}

	var doNotTryDetails bool
	for _, item := range posts.Data.User.EdgeOwnerToTimelineMedia.Edges {
		post := &Post{
			ID:        item.Node.ID,
			Shortcode: item.Node.Shortcode,
			TakenAt:   time.Unix(item.Node.TakenAtTimestamp, 0).UTC(),
			Comment:   item.Node.EdgeMediaToComment.Count,
			Likes:     item.Node.EdgeMediaPreviewLike.Count,
			MediaURLs: []string{item.Node.DisplayURL},
			Video:     item.Node.IsVideo,
		}

		if len(item.Node.EdgeMediaToCaption.Edges) > 0 {
			post.Caption = item.Node.EdgeMediaToCaption.Edges[0].Node.Text
		}

		if (item.Node.Typename == "GraphSidecar" ||
			item.Node.Typename == "GraphVideo") && !doNotTryDetails {
			postDetailed, err := g.PostByShortcode(ctx, item.Node.Shortcode)
			if err != nil {
				doNotTryDetails = true
				fmt.Printf("failure loading post %s, post will have less metadata\n", item.Node.Shortcode)
			} else {
				post = postDetailed
			}
		}

		respondPosts = append(respondPosts, post)
	}

	return respondPosts, nil
}

type postsData struct {
	Data struct {
		User struct {
			EdgeOwnerToTimelineMedia struct {
				Count int `json:"count"`
				Edges []struct {
					Node struct {
						ID                 string `json:"id"`
						Typename           string `json:"__typename"`
						EdgeMediaToCaption struct {
							Edges []struct {
								Node struct {
									Text string `json:"text"`
								} `json:"node"`
							} `json:"edges"`
						} `json:"edge_media_to_caption"`
						Shortcode          string `json:"shortcode"`
						EdgeMediaToComment struct {
							Count int `json:"count"`
						} `json:"edge_media_to_comment"`
						CommentsDisabled bool  `json:"comments_disabled"`
						TakenAtTimestamp int64 `json:"taken_at_timestamp"`
						Dimensions       struct {
							Height int `json:"height"`
							Width  int `json:"width"`
						} `json:"dimensions"`
						DisplayURL           string `json:"display_url"`
						EdgeMediaPreviewLike struct {
							Count int `json:"count"`
						} `json:"edge_media_preview_like"`
						Owner struct {
							ID string `json:"id"`
						} `json:"owner"`
						ThumbnailSrc       string `json:"thumbnail_src"`
						ThumbnailResources []struct {
							Src          string `json:"src"`
							ConfigWidth  int    `json:"config_width"`
							ConfigHeight int    `json:"config_height"`
						} `json:"thumbnail_resources"`
						IsVideo bool `json:"is_video"`
					} `json:"node,omitempty"`
				} `json:"edges"`
			} `json:"edge_owner_to_timeline_media"`
		} `json:"user"`
	} `json:"data"`
	Status string `json:"status"`
}

repository: Seklfreak/ginsta

repo_name: Seklfreak/ginsta


text:
@inproceedings{lefrancois_egc_2017,
  title = {G\'{e}n\'{e}ration de {RDF} \`a partir de sources de donn\'{e}es aux formats h\'{e}t\'{e}rog\`{e}nes},
  author = {Lefran\c{c}ois, Maxime and Zimmermann, Antoine and Bakerally, Noorani},
  year = 2017,
  month = jan,
  address = {Grenoble, France},
  booktitle = {Actes de la 17\`{e}me conf\'{e}rence Extraction et Gestion des Connaissances (EGC'17)},
  url = {http://www.maxime-lefrancois.info/docs/LefrancoisZimmermannBakerally-EGC2017-Generation.pdf},
}

gha_language: Java


text:
package fann
/*
#cgo LDFLAGS: -lfann -lm
#include <fann.h>

static void cpFannTypeArray(fann_type* src, fann_type* dst, unsigned int n) {
	unsigned int i = 0;
	for(; i < n; i++)
		dst[i] = src[i];
}

static void get_train_input(struct fann_train_data* td, fann_type* dst, unsigned int pos, unsigned int ln) {
	cpFannTypeArray(td->input[pos], dst, ln);
}

static void get_train_output(struct fann_train_data* td, fann_type* dst, unsigned int pos, unsigned int ln) {
	cpFannTypeArray(td->output[pos], dst, ln);
}

*/
import "C"
import "unsafe"

func ReadTrainFromFile(filename string) (*TrainData) {
	var td TrainData

	cfn := C.CString(filename)
	defer C.free(unsafe.Pointer(cfn))

	td.object = C.fann_read_train_from_file(cfn)

	return &td
}

func (td *TrainData) Destroy() ( ) {
	C.fann_destroy_train(td.object)
}

func (td *TrainData) GetInput(i uint32) ([]FannType) {
	num := td.GetNumInput()
	input := make([]FannType, num)
	C.get_train_input(td.object, (*C.fann_type)(&input[0]), C.uint(i), C.uint(num))
	return input
}

func (td *TrainData) GetOutput(i uint32) ([]FannType) {
	num := td.GetNumOutput()
	output := make([]FannType, num)
	C.get_train_output(td.object, (*C.fann_type)(&output[0]), C.uint(i), C.uint(num))
	return output
}

func (td *TrainData) Shuffle() () {
	C.fann_shuffle_train_data(td.object)
}

func (ann *Ann) ScaleTrain(td *TrainData) () {
	C.fann_scale_train(ann.object, td.object)
}

func (ann *Ann) DescaleTrain(td *TrainData) ( ) {
	C.fann_descale_train(ann.object, td.object)
}

func (td *TrainData) Length() (uint32) {
	return uint32(C.fann_length_train_data(td.object))
}

func MergeTrainData(td1 *TrainData, td2 *TrainData) (*TrainData) {
	var td TrainData
	td.object = C.fann_merge_train_data(td1.object, td2.object)
	return &td
}

func (td* TrainData) Duplicate() (*TrainData) {
	var td_dup TrainData
	td_dup.object = C.fann_duplicate_train_data(td.object)
	return &td_dup
}

func (td* TrainData) Subset(pos uint32, length uint32) (*TrainData) {
	var td_sub TrainData
	td_sub.object = C.fann_subset_train_data(td.object, C.uint(pos), C.uint(length))
	return &td_sub
}

func (td *TrainData) GetNumInput() (uint32) {
	return uint32(C.fann_num_input_train_data(td.object))
}

func (td *TrainData) GetNumOutput() (uint32) {
	return uint32(C.fann_num_output_train_data(td.object))
}

func (td *TrainData) SaveTrain(filename string) () {
	cfn := C.CString(filename)
	defer C.free(unsafe.Pointer(cfn))
	C.fann_save_train(td.object, cfn)
}

func (td *TrainData) SaveTrainToFixed(filename string, decimal_point uint32) ( ) {
	cfn := C.CString(filename)
	defer C.free(unsafe.Pointer(cfn))

	C.fann_save_train_to_fixed(td.object, cfn, C.uint(decimal_point))
}

func (td *TrainData) ScaleInputTrainData(new_min FannType, new_max FannType) () {
	C.fann_scale_input_train_data(td.object, C.fann_type(new_min), C.fann_type(new_max))
}

func (td *TrainData) ScaleOutputTrainData(new_min FannType, new_max FannType) () {
	C.fann_scale_output_train_data(td.object, C.fann_type(new_min), C.fann_type(new_max))
}

func (td *TrainData) ScaleTrainData(new_min FannType, new_max FannType) () {
	C.fann_scale_train_data(td.object, C.fann_type(new_min), C.fann_type(new_max))
}

repository: segfault/go-fann

repo_name: segfault/go-fann


text:
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

include(${CMAKE_ROOT}/Modules/FindSWIG.cmake)

if (NOT COMMAND swig_add_library)
  macro (SWIG_ADD_LIBRARY name)
    set(options "")
    set(oneValueArgs LANGUAGE TYPE)
    set(multiValueArgs SOURCES)
    cmake_parse_arguments(_SAM "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})

    if (NOT DEFINED _SAM_LANGUAGE)
      message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing LANGUAGE argument")
    endif ()

    if (NOT DEFINED _SAM_SOURCES)
      message(FATAL_ERROR "SWIG_ADD_LIBRARY: Missing SOURCES argument")
    endif ()

    if (DEFINED _SAM_TYPE AND NOT _SAM_LANGUAGE STREQUAL "module")
      message(FATAL_ERROR "SWIG_ADD_LIBRARY: This fallback impl of swig_add_library supports the module type only")
    endif ()

    swig_add_module(${name} ${_SAM_LANGUAGE} ${_SAM_SOURCES})
  endmacro ()
endif (NOT COMMAND swig_add_library)

repository: apache/qpid-cpp

repo_name: apache/qpid-cpp

branch_name: refs/heads/main

extension: cmake


text:
@article{Litj12b,
 abstract = {Purpose:To determine the interpatient variability of prostate peripheral zone (PZ) apparent diffusion coefficient (ADC) and its effect on the assessment of prostate cancer aggressiveness.Materials and Methods:The requirement for institutional review board approval was waived. Intra- and interpatient variation of PZ ADCs was determined by means of repeated measurements of normal ADCs at three magnetic resonance (MR) examinations in a retrospective cohort of 10 consecutive patients who had high prostate-specific antigen levels and negative findings at transrectal ultrasonographically-guided biopsy. In these patients, no signs of PZ cancer were found at all three MR imaging sessions. The effect of interpatient variation on the assessment of prostate cancer aggressiveness was examined in a second retrospective cohort of 51 patients with PZ prostate cancer. Whole-mount step-section pathologic evaluation served as reference standard for placement of regions of interest on tumors and normal PZ. Repeated-measures analysis of variance was used to determine the significance of the interpatient variations in ADCs. Linear logistic regression was used to assess whether incorporating normal PZ ADCs improves the prediction of cancer aggressiveness.Results:Analysis of variance revealed that interpatient variability (1.2-2.0 Ã¯Â¿Â½ 10(-3) mm(2)/sec) was significantly larger than measurement variability (0.068 Ã¯Â¿Â½ 10(-3) mm(2)/sec Ã¯Â¿Â½ 0.027 [standard deviation]) (P = .0058). Stand-alone tumor ADCs showed an area under the receiver operating characteristic curve (AUC) of 0.91 for discriminating low-grade versus high-grade tumors. Incorporating normal PZ ADC significantly improved the AUC to 0.96 (P = .0401).Conclusion:PZ ADCs show significant interpatient variation, which has a substantial effect on the prediction of prostate cancer aggressiveness. Correcting this effect results in a significant increase in diagnostic accuracy.Ã¯Â¿Â½ RSNA, 2012.},
 author = {Litjens, G. and Hambrock, Thomas and Hulsbergen-van de Kaa, Christina and Barentsz, Jelle and Huisman, Henkjan},
 doi = {10.1148/radiol.12112374},
 file = {Litj12b.pdf:pdf\Łitj12b.pdf:PDF},
 journal = {Radiology},
 language = {english},
 medline-pst = {aheadofprint},
 month = {Aug},
 optgroups = {Prostate},
 optinstitution = {Department of Radiology, Radboud University Nijmegen Medical Centre, Geert Grooteplein 10, 6525 GA Nijmegen, the Netherlands.},
 optnote = {RADIOLOGY, DIAG, ProstateCancer},
 optnumber = {1},
 owner = {z908160},
 pages = {260-266},
 pii = {radiol.12112374},
 pmid = {22923722},
 timestamp = {2012.08.30},
 title = {Interpatient Variation in Normal Peripheral Zone Apparent Diffusion Coefficient: Effect on the Prediction of Prostate Cancer Aggressiveness},
 volume = {265},
 year = {2012}
}