text:
/*
Copyright 2020 The pdfcpu Authors.

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 model

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types"
	"github.com/pkg/errors"
)

// Box is a rectangular region in user space
// expressed either explicitly via Rect
// or implicitly via margins applied to the containing parent box.
// Media box serves as parent box for crop box.
// Crop box serves as parent box for trim, bleed and art box.
type Box struct {
	Rect      *types.Rectangle // Rectangle in user space.
	Inherited bool             // Media box and Crop box may be inherited.
	RefBox    string           // Use position of another box,
	// Margins to parent box in points.
	// Relative to parent box if 0 < x < 0.5
	MLeft, MRight float64
	MTop, MBot    float64
	// Relative position within parent box
	Dim    *types.Dim   // dimensions
	Pos    types.Anchor // position anchor within parent box, one of tl,tc,tr,l,c,r,bl,bc,br.
	Dx, Dy int          // anchor offset
}

// PageBoundaries represent the defined PDF page boundaries.
type PageBoundaries struct {
	Media *Box
	Crop  *Box
	Trim  *Box
	Bleed *Box
	Art   *Box
	Rot   int // The effective page rotation.
}

// SelectAll selects all page boundaries.
func (pb *PageBoundaries) SelectAll() {
	b := &Box{}
	pb.Media, pb.Crop, pb.Trim, pb.Bleed, pb.Art = b, b, b, b, b
}

func (pb PageBoundaries) String() string {
	ss := []string{}
	if pb.Media != nil {
		ss = append(ss, "mediaBox")
	}
	if pb.Crop != nil {
		ss = append(ss, "cropBox")
	}
	if pb.Trim != nil {
		ss = append(ss, "trimBox")
	}
	if pb.Bleed != nil {
		ss = append(ss, "bleedBox")
	}
	if pb.Art != nil {
		ss = append(ss, "artBox")
	}
	return strings.Join(ss, ", ")
}

// MediaBox returns the effective mediabox for pb.
func (pb PageBoundaries) MediaBox() *types.Rectangle {
	if pb.Media == nil {
		return nil
	}
	return pb.Media.Rect
}

// CropBox returns the effective cropbox for pb.
func (pb PageBoundaries) CropBox() *types.Rectangle {
	if pb.Crop == nil || pb.Crop.Rect == nil {
		return pb.MediaBox()
	}
	return pb.Crop.Rect
}

// TrimBox returns the effective trimbox for pb.
func (pb PageBoundaries) TrimBox() *types.Rectangle {
	if pb.Trim == nil || pb.Trim.Rect == nil {
		return pb.CropBox()
	}
	return pb.Trim.Rect
}

// BleedBox returns the effective bleedbox for pb.
func (pb PageBoundaries) BleedBox() *types.Rectangle {
	if pb.Bleed == nil || pb.Bleed.Rect == nil {
		return pb.CropBox()
	}
	return pb.Bleed.Rect
}

// ArtBox returns the effective artbox for pb.
func (pb PageBoundaries) ArtBox() *types.Rectangle {
	if pb.Art == nil || pb.Art.Rect == nil {
		return pb.CropBox()
	}
	return pb.Art.Rect
}

// ResolveBox resolves s and tries to assign an empty page boundary.
func (pb *PageBoundaries) ResolveBox(s string) error {
	for _, k := range []string{"media", "crop", "trim", "bleed", "art"} {
		b := &Box{}
		if strings.HasPrefix(k, s) {
			switch k {
			case "media":
				pb.Media = b
			case "crop":
				pb.Crop = b
			case "trim":
				pb.Trim = b
			case "bleed":
				pb.Bleed = b
			case "art":
				pb.Art = b
			}
			return nil
		}
	}
	return errors.Errorf("pdfcpu: invalid box prefix: %s", s)
}

// ParseBoxList parses a list of box
func ParseBoxList(s string) (*PageBoundaries, error) {
	// A comma separated, unsorted list of values:
	//
	// m(edia), c(rop), t(rim), b(leed), a(rt)

	s = strings.TrimSpace(s)
	if len(s) == 0 {
		return nil, nil
	}
	pb := &PageBoundaries{}
	for _, s := range strings.Split(s, ",") {
		if err := pb.ResolveBox(strings.TrimSpace(s)); err != nil {
			return nil, err
		}
	}
	return pb, nil
}

func resolveBoxType(s string) (string, error) {
	for _, k := range []string{"media", "crop", "trim", "bleed", "art"} {
		if strings.HasPrefix(k, s) {
			return k, nil
		}
	}
	return "", errors.Errorf("pdfcpu: invalid box type: %s", s)
}

func processBox(b **Box, boxID, paramValueStr string, unit types.DisplayUnit) error {
	var err error
	if *b != nil {
		return errors.Errorf("pdfcpu: duplicate box definition: %s", boxID)
	}
	// process box assignment
	boxVal, err := resolveBoxType(paramValueStr)
	if err == nil {
		if boxVal == boxID {
			return errors.Errorf("pdfcpu: invalid box self assigment: %s", boxID)
		}
		*b = &Box{RefBox: boxVal}
		return nil
	}
	// process box definition
	*b, err = ParseBox(paramValueStr, unit)
	return err
}

// ParsePageBoundaries parses a list of box definitions and assignments.
func ParsePageBoundaries(s string, unit types.DisplayUnit) (*PageBoundaries, error) {
	// A sequence of box definitions/assignments:
	//
	// 	  m(edia): {box}
	//     c(rop): {box}
	//      a(rt): {box} | b(leed) | c(rop)  | m(edia) | t(rim)
	//    b(leed): {box} | a(rt)   | c(rop)  | m(edia) | t(rim)
	//     t(rim): {box} | a(rt)   | b(leed) | c(rop)  | m(edia)

	s = strings.TrimSpace(s)
	if len(s) == 0 {
		return nil, errors.New("pdfcpu: missing page boundaries in the form of box definitions/assignments")
	}
	pb := &PageBoundaries{}
	for _, s := range strings.Split(s, ",") {

		s1 := strings.Split(s, ":")
		if len(s1) != 2 {
			return nil, errors.New("pdfcpu: invalid box assignment")
		}

		paramPrefix := strings.TrimSpace(s1[0])
		paramValueStr := strings.TrimSpace(s1[1])

		boxKey, err := resolveBoxType(paramPrefix)
		if err != nil {
			return nil, errors.New("pdfcpu: invalid box type")
		}

		// process box definition
		switch boxKey {
		case "media":
			if pb.Media != nil {
				return nil, errors.New("pdfcpu: duplicate box definition: media")
			}
			// process media box definition
			pb.Media, err = ParseBox(paramValueStr, unit)

		case "crop":
			if pb.Crop != nil {
				return nil, errors.New("pdfcpu: duplicate box definition: crop")
			}
			// process crop box definition
			pb.Crop, err = ParseBox(paramValueStr, unit)

		case "trim":
			err = processBox(&pb.Trim, "trim", paramValueStr, unit)

		case "bleed":
			err = processBox(&pb.Bleed, "bleed", paramValueStr, unit)

		case "art":
			err = processBox(&pb.Art, "art", paramValueStr, unit)

		}

		if err != nil {
			return nil, err
		}
	}
	return pb, nil
}

func parseBoxByRectangle(s string, u types.DisplayUnit) (*Box, error) {
	ss := strings.Fields(s)
	if len(ss) != 4 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	f, err := strconv.ParseFloat(ss[0], 64)
	if err != nil {
		return nil, err
	}
	xmin := types.ToUserSpace(f, u)

	f, err = strconv.ParseFloat(ss[1], 64)
	if err != nil {
		return nil, err
	}
	ymin := types.ToUserSpace(f, u)

	f, err = strconv.ParseFloat(ss[2], 64)
	if err != nil {
		return nil, err
	}
	xmax := types.ToUserSpace(f, u)

	f, err = strconv.ParseFloat(ss[3], 64)
	if err != nil {
		return nil, err
	}
	ymax := types.ToUserSpace(f, u)

	if xmax < xmin {
		xmin, xmax = xmax, xmin
	}

	if ymax < ymin {
		ymin, ymax = ymax, ymin
	}

	return &Box{Rect: types.NewRectangle(xmin, ymin, xmax, ymax)}, nil
}

func parseBoxPercentage(s string) (float64, error) {
	pct, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return 0, err
	}
	if pct <= -50 || pct >= 50 {
		return 0, errors.Errorf("pdfcpu: invalid margin percentage: %s must be < 50%%", s)
	}
	return pct / 100, nil
}

func parseBoxBySingleMarginVal(s, s1 string, abs bool, u types.DisplayUnit) (*Box, error) {
	if s1[len(s1)-1] == '%' {
		// margin percentage
		// 10.5%
		// % has higher precedence than abs/rel.
		s1 = s1[:len(s1)-1]
		if len(s1) == 0 {
			return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
		}
		m, err := parseBoxPercentage(s1)
		if err != nil {
			return nil, err
		}
		return &Box{MLeft: m, MRight: m, MTop: m, MBot: m}, nil
	}
	m, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}
	if !abs {
		// 0.25 rel (=25%)
		if m <= 0 || m >= .5 {
			return nil, errors.Errorf("pdfcpu: invalid relative box margin: %f must be positive < 0.5", m)
		}
		return &Box{MLeft: m, MRight: m, MTop: m, MBot: m}, nil
	}
	// 10
	// 10 abs
	// .5
	// .5 abs
	m = types.ToUserSpace(m, u)
	return &Box{MLeft: m, MRight: m, MTop: m, MBot: m}, nil
}

func parseBoxBy2Percentages(s, s1, s2 string) (*Box, error) {
	// 10% 40%
	// Parse vert margin.
	s1 = s1[:len(s1)-1]
	if len(s1) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	vm, err := parseBoxPercentage(s1)
	if err != nil {
		return nil, err
	}

	if s2[len(s2)-1] != '%' {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	// Parse hor margin.
	s2 = s2[:len(s2)-1]
	if len(s2) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	hm, err := parseBoxPercentage(s2)
	if err != nil {
		return nil, err
	}
	return &Box{MLeft: hm, MRight: hm, MTop: vm, MBot: vm}, nil
}

func parseBoxBy2MarginVals(s, s1, s2 string, abs bool, u types.DisplayUnit) (*Box, error) {
	if s1[len(s1)-1] == '%' {
		return parseBoxBy2Percentages(s, s1, s2)
	}

	// 10 5
	// 10 5 abs
	// .1 .5
	// .1 .5 abs
	// .1 .4 rel
	vm, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}
	if !abs {
		// eg 0.25 rel (=25%)
		if vm <= 0 || vm >= .5 {
			return nil, errors.Errorf("pdfcpu: invalid relative vertical box margin: %f must be positive < 0.5", vm)
		}
	}
	hm, err := strconv.ParseFloat(s2, 64)
	if err != nil {
		return nil, err
	}
	if !abs {
		// eg 0.25 rel (=25%)
		if hm <= 0 || hm >= .5 {
			return nil, errors.Errorf("pdfcpu: invalid relative horizontal box margin: %f must be positive < 0.5", hm)
		}
	}
	if abs {
		vm = types.ToUserSpace(vm, u)
		hm = types.ToUserSpace(hm, u)
	}
	return &Box{MLeft: hm, MRight: hm, MTop: vm, MBot: vm}, nil
}

func parseBoxBy3Percentages(s, s1, s2, s3 string) (*Box, error) {
	// 10% 15.5% 10%
	// Parse top margin.
	s1 = s1[:len(s1)-1]
	if len(s1) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}
	tm := pct / 100

	if s2[len(s2)-1] != '%' {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	// Parse hor margin.
	s2 = s2[:len(s2)-1]
	if len(s2) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	hm, err := parseBoxPercentage(s2)
	if err != nil {
		return nil, err
	}

	if s3[len(s3)-1] != '%' {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	// Parse bottom margin.
	s3 = s3[:len(s3)-1]
	if len(s3) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err = strconv.ParseFloat(s3, 64)
	if err != nil {
		return nil, err
	}
	bm := pct / 100
	if tm+bm >= 1 {
		return nil, errors.Errorf("pdfcpu: vertical margin overflow: %s", s)
	}

	return &Box{MLeft: hm, MRight: hm, MTop: tm, MBot: bm}, nil
}

func parseBoxBy3MarginVals(s, s1, s2, s3 string, abs bool, u types.DisplayUnit) (*Box, error) {
	if s1[len(s1)-1] == '%' {
		return parseBoxBy3Percentages(s, s1, s2, s3)
	}

	// 10 5 15 				... absolute, top:10 left,right:5 bottom:15
	// 10 5 15 abs			... absolute, top:10 left,right:5 bottom:15
	// .1 .155 .1			... absolute, top:.1 left,right:.155 bottom:.1
	// .1 .155 .1 abs		... absolute, top:.1 left,right:.155 bottom:.1
	// .1 .155 .1 rel 		... relative, top:.1 left,right:.155 bottom:.1
	tm, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}

	hm, err := strconv.ParseFloat(s2, 64)
	if err != nil {
		return nil, err
	}
	if !abs {
		// eg 0.25 rel (=25%)
		if hm <= 0 || hm >= .5 {
			return nil, errors.Errorf("pdfcpu: invalid relative horizontal box margin: %f must be positive < 0.5", hm)
		}
	}

	bm, err := strconv.ParseFloat(s3, 64)
	if err != nil {
		return nil, err
	}
	if !abs && (tm+bm >= 1) {
		return nil, errors.Errorf("pdfcpu: vertical margin overflow: %s", s)
	}

	if abs {
		tm = types.ToUserSpace(tm, u)
		hm = types.ToUserSpace(hm, u)
		bm = types.ToUserSpace(bm, u)
	}
	return &Box{MLeft: hm, MRight: hm, MTop: tm, MBot: bm}, nil
}

func parseBoxBy4Percentages(s, s1, s2, s3, s4 string) (*Box, error) {
	// 10% 15% 15% 10%
	// Parse top margin.
	s1 = s1[:len(s1)-1]
	if len(s1) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}
	tm := pct / 100

	// Parse right margin.
	if s2[len(s2)-1] != '%' {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	s2 = s2[:len(s2)-1]
	if len(s2) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err = strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}
	rm := pct / 100

	// Parse bottom margin.
	if s3[len(s3)-1] != '%' {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	s3 = s3[:len(s3)-1]
	if len(s3) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err = strconv.ParseFloat(s3, 64)
	if err != nil {
		return nil, err
	}
	bm := pct / 100

	// Parse left margin.
	if s4[len(s4)-1] != '%' {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	s4 = s4[:len(s4)-1]
	if len(s4) == 0 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err = strconv.ParseFloat(s3, 64)
	if err != nil {
		return nil, err
	}
	lm := pct / 100

	if tm+bm >= 1 {
		return nil, errors.Errorf("pdfcpu: vertical margin overflow: %s", s)
	}
	if rm+lm >= 1 {
		return nil, errors.Errorf("pdfcpu: horizontal margin overflow: %s", s)
	}

	return &Box{MLeft: lm, MRight: rm, MTop: tm, MBot: bm}, nil
}

func parseBoxBy4MarginVals(s, s1, s2, s3, s4 string, abs bool, u types.DisplayUnit) (*Box, error) {
	if s1[len(s1)-1] == '%' {
		return parseBoxBy4Percentages(s, s1, s2, s3, s4)
	}

	// 0.4 0.4 20 20		... absolute, top:.4 right:.4 bottom:20 left:20
	// 0.4 0.4 .1 .1		... absolute, top:.4 right:.4 bottom:.1 left:.1
	// 0.4 0.4 .1 .1 abs	... absolute, top:.4 right:.4 bottom:.1 left:.1
	// 0.4 0.4 .1 .1 rel  	... relative, top:.4 right:.4 bottom:.1 left:.1

	// Parse top margin.
	tm, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return nil, err
	}

	// Parse right margin.
	rm, err := strconv.ParseFloat(s2, 64)
	if err != nil {
		return nil, err
	}

	// Parse bottom margin.
	bm, err := strconv.ParseFloat(s3, 64)
	if err != nil {
		return nil, err
	}

	// Parse left margin.
	lm, err := strconv.ParseFloat(s4, 64)
	if err != nil {
		return nil, err
	}
	if !abs {
		if tm+bm >= 1 {
			return nil, errors.Errorf("pdfcpu: vertical margin overflow: %s", s)
		}
		if lm+rm >= 1 {
			return nil, errors.Errorf("pdfcpu: horizontal margin overflow: %s", s)
		}
	}

	if abs {
		tm = types.ToUserSpace(tm, u)
		rm = types.ToUserSpace(rm, u)
		bm = types.ToUserSpace(bm, u)
		lm = types.ToUserSpace(lm, u)
	}
	return &Box{MLeft: lm, MRight: rm, MTop: tm, MBot: bm}, nil
}

func parseBoxOffset(s string, b *Box, u types.DisplayUnit) error {
	d := strings.Split(s, " ")
	if len(d) != 2 {
		return errors.Errorf("pdfcpu: illegal position offset string: need 2 numeric values, %s\n", s)
	}

	f, err := strconv.ParseFloat(d[0], 64)
	if err != nil {
		return err
	}
	b.Dx = int(types.ToUserSpace(f, u))

	f, err = strconv.ParseFloat(d[1], 64)
	if err != nil {
		return err
	}
	b.Dy = int(types.ToUserSpace(f, u))

	return nil
}

func parseBoxDimByPercentage(s, s1, s2 string, b *Box) error {
	// 10% 40%
	// Parse width.
	s1 = s1[:len(s1)-1]
	if len(s1) == 0 {
		return errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err := strconv.ParseFloat(s1, 64)
	if err != nil {
		return err
	}
	if pct <= 0 || pct > 100 {
		return errors.Errorf("pdfcpu: invalid percentage: %s", s)
	}
	w := pct / 100

	if s2[len(s2)-1] != '%' {
		return errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	// Parse height.
	s2 = s2[:len(s2)-1]
	if len(s2) == 0 {
		return errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	pct, err = strconv.ParseFloat(s2, 64)
	if err != nil {
		return err
	}
	if pct <= 0 || pct > 100 {
		return errors.Errorf("pdfcpu: invalid percentage: %s", s)
	}
	h := pct / 100
	b.Dim = &types.Dim{Width: w, Height: h}
	return nil
}

func parseBoxDimWidthAndHeight(s1, s2 string, abs bool) (float64, float64, error) {
	var (
		w, h float64
		err  error
	)

	w, err = strconv.ParseFloat(s1, 64)
	if err != nil {
		return w, h, err
	}
	if !abs {
		// eg 0.25 rel (=25%)
		if w <= 0 || w > 1 {
			return w, h, errors.Errorf("pdfcpu: invalid relative box width: %f must be positive <= 1", w)
		}
	}

	h, err = strconv.ParseFloat(s2, 64)
	if err != nil {
		return w, h, err
	}
	if !abs {
		// eg 0.25 rel (=25%)
		if h <= 0 || h > 1 {
			return w, h, errors.Errorf("pdfcpu: invalid relative box height: %f must be positive <= 1", h)
		}
	}

	return w, h, nil
}

func parseBoxDim(s string, b *Box, u types.DisplayUnit) error {
	ss := strings.Fields(s)
	if len(ss) != 2 && len(ss) != 3 {
		return errors.Errorf("pdfcpu: illegal dimension string: need 2 positive numeric values, %s\n", s)
	}
	abs := true
	if len(ss) == 3 {
		s1 := ss[2]
		if s1 != "rel" && s1 != "abs" {
			return errors.New("pdfcpu: illegal dimension string")
		}
		abs = s1 == "abs"
	}

	s1, s2 := ss[0], ss[1]
	if s1[len(s1)-1] == '%' {
		return parseBoxDimByPercentage(s, s1, s2, b)
	}

	w, h, err := parseBoxDimWidthAndHeight(s1, s2, abs)
	if err != nil {
		return err
	}

	if abs {
		w = types.ToUserSpace(w, u)
		h = types.ToUserSpace(h, u)
	}
	b.Dim = &types.Dim{Width: w, Height: h}
	return nil
}

func parseBoxByPosWithinParent(s string, ss []string, u types.DisplayUnit) (*Box, error) {
	b := &Box{Pos: types.Center}
	for _, s := range ss {

		ss1 := strings.Split(s, ":")
		if len(ss1) != 2 {
			return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
		}

		paramPrefix := strings.TrimSpace(ss1[0])
		paramValueStr := strings.TrimSpace(ss1[1])

		switch paramPrefix {
		case "dim":
			if err := parseBoxDim(paramValueStr, b, u); err != nil {
				return nil, err
			}

		case "pos":
			a, err := types.ParsePositionAnchor(paramValueStr)
			if err != nil {
				return nil, err
			}
			b.Pos = a

		case "off":
			if err := parseBoxOffset(paramValueStr, b, u); err != nil {
				return nil, err
			}

		default:
			return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
		}
	}
	if b.Dim == nil {
		return nil, errors.New("pdfcpu: missing box definition attr dim")
	}
	return b, nil
}

func parseBoxByMarginVals(ss []string, s string, abs bool, u types.DisplayUnit) (*Box, error) {
	switch len(ss) {
	case 1:
		return parseBoxBySingleMarginVal(s, ss[0], abs, u)
	case 2:
		return parseBoxBy2MarginVals(s, ss[0], ss[1], abs, u)
	case 3:
		return parseBoxBy3MarginVals(s, ss[0], ss[1], ss[2], abs, u)
	case 4:
		return parseBoxBy4MarginVals(s, ss[0], ss[1], ss[2], ss[3], abs, u)
	case 5:
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	return nil, nil
}

// ParseBox parses a box definition.
func ParseBox(s string, u types.DisplayUnit) (*Box, error) {
	// A rectangular region in userspace expressed in terms of
	// a rectangle or margins relative to its parent box.
	// Media box serves as parent/default for crop box.
	// Crop box serves as parent/default for trim, bleed and art box:

	// [0 10 200 150]		... rectangle

	// 0.5 0.5 20 20		... absolute, top:.5 right:.5 bottom:20 left:20
	// 0.5 0.5 .1 .1 abs	... absolute, top:.5 right:.5 bottom:.1 left:.1
	// 0.5 0.5 .1 .1 rel  	... relative, top:.5 right:.5 bottom:20 left:20
	// 10                 	... absolute, top,right,bottom,left:10
	// 10 5               	... absolute, top,bottom:10  left,right:5
	// 10 5 15            	... absolute, top:10 left,right:5 bottom:15
	// 5%         <50%      ... relative, top,right,bottom,left:5% of parent box width/height
	// .1 .5              	... absolute, top,bottom:.1  left,right:.5
	// .1 .3 rel         	... relative, top,bottom:.1=10%  left,right:.3=30%
	// -10                	... absolute, top,right,bottom,left enlarging the parent box as well

	// dim:30 30			... 30 x 30 display units, anchored at center of parent box
	// dim:30 30 abs		... 30 x 30 display units, anchored at center of parent box
	// dim:.3 .3 rel  		... 0.3 x 0.3 relative width/height of parent box, anchored at center of parent box
	// dim:30% 30%			... 0.3 x 0.3 relative width/height of parent box, anchored at center of parent box
	// pos:tl, dim:30 30	... 0.3 x 0.3 relative width/height of parent box, anchored at top left corner of parent box
	// pos:bl, off: 5 5, dim:30 30			...30 x 30 display units with offset 5/5, anchored at bottom left corner of parent box
	// pos:bl, off: -5 -5, dim:.3 .3 rel 	...0.3 x 0.3 relative width/height and anchored at bottom left corner of parent box

	s = strings.TrimSpace(s)
	if len(s) == 0 {
		return nil, nil
	}

	if s[0] == '[' && s[len(s)-1] == ']' {
		// Rectangle in PDF Array notation.
		return parseBoxByRectangle(s[1:len(s)-1], u)
	}

	// Via relative position within parent box.
	ss := strings.Split(s, ",")
	if len(ss) > 3 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	if len(ss) > 1 || strings.HasPrefix(ss[0], "dim") {
		return parseBoxByPosWithinParent(s, ss, u)
	}

	// Via margins relative to parent box.
	ss = strings.Fields(s)
	if len(ss) > 5 {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}
	if len(ss) == 1 && (ss[0] == "abs" || ss[0] == "rel") {
		return nil, errors.Errorf("pdfcpu: invalid box definition: %s", s)
	}

	abs := true
	l := len(ss) - 1
	s1 := ss[l]
	if s1 == "rel" || s1 == "abs" {
		abs = s1 == "abs"
		ss = ss[:l]
	}

	return parseBoxByMarginVals(ss, s, abs, u)
}

func (ctx *Context) addPageBoundaryString(i int, pb PageBoundaries, wantPB *PageBoundaries) []string {
	unit := ctx.UnitString()
	ss := []string{}
	d := pb.CropBox().Dimensions()
	if pb.Rot%180 != 0 {
		d.Width, d.Height = d.Height, d.Width
	}
	or := "portrait"
	if d.Landscape() {
		or = "landscape"
	}

	s := fmt.Sprintf("rot=%+d orientation:%s", pb.Rot, or)
	ss = append(ss, fmt.Sprintf("Page %d: %s", i+1, s))
	if wantPB.Media != nil {
		s := ""
		if pb.Media.Inherited {
			s = "(inherited)"
		}
		ss = append(ss, fmt.Sprintf("  MediaBox (%s) %v %s", unit, pb.MediaBox().Format(ctx.Unit), s))
	}
	if wantPB.Crop != nil {
		s := ""
		if pb.Crop == nil {
			s = "(default)"
		} else if pb.Crop.Inherited {
			s = "(inherited)"
		}
		ss = append(ss, fmt.Sprintf("   CropBox (%s) %v %s", unit, pb.CropBox().Format(ctx.Unit), s))
	}
	if wantPB.Trim != nil {
		s := ""
		if pb.Trim == nil {
			s = "(default)"
		}
		ss = append(ss, fmt.Sprintf("   TrimBox (%s) %v %s", unit, pb.TrimBox().Format(ctx.Unit), s))
	}
	if wantPB.Bleed != nil {
		s := ""
		if pb.Bleed == nil {
			s = "(default)"
		}
		ss = append(ss, fmt.Sprintf("  BleedBox (%s) %v %s", unit, pb.BleedBox().Format(ctx.Unit), s))
	}
	if wantPB.Art != nil {
		s := ""
		if pb.Art == nil {
			s = "(default)"
		}
		ss = append(ss, fmt.Sprintf("    ArtBox (%s) %v %s", unit, pb.ArtBox().Format(ctx.Unit), s))
	}
	return append(ss, "")
}

// ListPageBoundaries lists page boundaries specified in wantPB for selected pages.
func (ctx *Context) ListPageBoundaries(selectedPages types.IntSet, wantPB *PageBoundaries) ([]string, error) {
	pbs, err := ctx.PageBoundaries(selectedPages)
	if err != nil {
		return nil, err
	}
	ss := []string{}
	for i, pb := range pbs {
		if _, found := selectedPages[i+1]; !found {
			continue
		}
		ss = append(ss, ctx.addPageBoundaryString(i, pb, wantPB)...)
	}

	return ss, nil
}

// RemovePageBoundaries removes page boundaries specified by pb for selected pages.
// The media box is mandatory (inherited or not) and can't be removed.
// A removed crop box defaults to the media box.
// Removed trim/bleed/art boxes default to the crop box.
func (ctx *Context) RemovePageBoundaries(selectedPages types.IntSet, pb *PageBoundaries) error {
	for k, v := range selectedPages {
		if !v {
			continue
		}
		d, _, inhPAttrs, err := ctx.PageDict(k, false)
		if err != nil {
			return err
		}
		if pb.Crop != nil {
			if oldVal := d.Delete("CropBox"); oldVal == nil {
				d.Insert("CropBox", inhPAttrs.MediaBox.Array())
			}
		}
		if pb.Trim != nil {
			d.Delete("TrimBox")
		}
		if pb.Bleed != nil {
			d.Delete("BleedBox")
		}
		if pb.Art != nil {
			d.Delete("ArtBox")
		}
	}
	return nil
}

func boxLowerLeftCorner(r *types.Rectangle, w, h float64, a types.Anchor) types.Point {
	var p types.Point

	switch a {

	case types.TopLeft:
		p.X = r.LL.X
		p.Y = r.UR.Y - h

	case types.TopCenter:
		p.X = r.UR.X - r.Width()/2 - w/2
		p.Y = r.UR.Y - h

	case types.TopRight:
		p.X = r.UR.X - w
		p.Y = r.UR.Y - h

	case types.Left:
		p.X = r.LL.X
		p.Y = r.UR.Y - r.Height()/2 - h/2

	case types.Center:
		p.X = r.UR.X - r.Width()/2 - w/2
		p.Y = r.UR.Y - r.Height()/2 - h/2

	case types.Right:
		p.X = r.UR.X - w
		p.Y = r.UR.Y - r.Height()/2 - h/2

	case types.BottomLeft:
		p.X = r.LL.X
		p.Y = r.LL.Y

	case types.BottomCenter:
		p.X = r.UR.X - r.Width()/2 - w/2
		p.Y = r.LL.Y

	case types.BottomRight:
		p.X = r.UR.X - w
		p.Y = r.LL.Y
	}

	return p
}

func boxByDim(boxName string, b *Box, d types.Dict, parent *types.Rectangle) *types.Rectangle {
	w := b.Dim.Width
	if w <= 1 {
		w *= parent.Width()
	}
	h := b.Dim.Height
	if h <= 1 {
		h *= parent.Height()
	}
	ll := boxLowerLeftCorner(parent, w, h, b.Pos)
	r := types.RectForWidthAndHeight(ll.X+float64(b.Dx), ll.Y+float64(b.Dy), w, h)
	if d != nil {
		d.Update(boxName, r.Array())
	}
	return r
}

func ensureCropBoxWithinMediaBox(xmin, xmax, ymin, ymax float64, d types.Dict, parent *types.Rectangle) {
	if xmin < parent.LL.X || ymin < parent.LL.Y || xmax > parent.UR.X || ymax > parent.UR.Y {
		// Expand media box.
		if xmin < parent.LL.X {
			parent.LL.X = xmin
		}
		if xmax > parent.UR.X {
			parent.UR.X = xmax
		}
		if ymin < parent.LL.Y {
			parent.LL.Y = ymin
		}
		if ymax > parent.UR.Y {
			parent.UR.Y = ymax
		}
		if d != nil {
			d.Update("MediaBox", parent.Array())
		}
	}
}

func ApplyBox(boxName string, b *Box, d types.Dict, parent *types.Rectangle) *types.Rectangle {
	if b.Rect != nil {
		if d != nil {
			d.Update(boxName, b.Rect.Array())
		}
		return b.Rect
	}

	if b.Dim != nil {
		return boxByDim(boxName, b, d, parent)
	}

	mLeft, mRight, mTop, mBot := b.MLeft, b.MRight, b.MTop, b.MBot
	if b.MLeft != 0 && -1 < b.MLeft && b.MLeft < 1 {
		// Margins relative to media box
		mLeft *= parent.Width()
		mRight *= parent.Width()
		mBot *= parent.Height()
		mTop *= parent.Height()
	}
	xmin := parent.LL.X + mLeft
	ymin := parent.LL.Y + mBot
	xmax := parent.UR.X - mRight
	ymax := parent.UR.Y - mTop
	r := types.NewRectangle(xmin, ymin, xmax, ymax)
	if d != nil {
		d.Update(boxName, r.Array())
	}
	if boxName == "CropBox" {
		ensureCropBoxWithinMediaBox(xmin, xmax, ymin, ymax, d, parent)
	}
	return r
}

type boxes struct {
	mediaBox, cropBox, trimBox, bleedBox, artBox *types.Rectangle
}

func applyBoxDefinitions(d types.Dict, pb *PageBoundaries, b *boxes) {
	parentBox := b.mediaBox
	if pb.Media != nil {
		//fmt.Println("add mb")
		b.mediaBox = ApplyBox("MediaBox", pb.Media, d, parentBox)
	}

	if pb.Crop != nil {
		//fmt.Println("add cb")
		b.cropBox = ApplyBox("CropBox", pb.Crop, d, parentBox)
	}

	if b.cropBox != nil {
		parentBox = b.cropBox
	}
	if pb.Trim != nil && pb.Trim.RefBox == "" {
		//fmt.Println("add tb")
		b.trimBox = ApplyBox("TrimBox", pb.Trim, d, parentBox)
	}

	if pb.Bleed != nil && pb.Bleed.RefBox == "" {
		//fmt.Println("add bb")
		b.bleedBox = ApplyBox("BleedBox", pb.Bleed, d, parentBox)
	}

	if pb.Art != nil && pb.Art.RefBox == "" {
		//fmt.Println("add ab")
		b.artBox = ApplyBox("ArtBox", pb.Art, d, parentBox)
	}
}

func updateTrimBox(d types.Dict, trimBox *Box, b *boxes) {
	var r *types.Rectangle
	switch trimBox.RefBox {
	case "media":
		r = b.mediaBox
	case "crop":
		r = b.cropBox
	case "bleed":
		r = b.bleedBox
		if r == nil {
			r = b.cropBox
		}
	case "art":
		r = b.artBox
		if r == nil {
			r = b.cropBox
		}
	}
	d.Update("TrimBox", r.Array())
	b.trimBox = r
}

func updateBleedBox(d types.Dict, bleedBox *Box, b *boxes) {
	var r *types.Rectangle
	switch bleedBox.RefBox {
	case "media":
		r = b.mediaBox
	case "crop":
		r = b.cropBox
	case "trim":
		r = b.trimBox
		if r == nil {
			r = b.cropBox
		}
	case "art":
		r = b.artBox
		if r == nil {
			r = b.cropBox
		}
	}
	d.Update("BleedBox", r.Array())
	b.bleedBox = r
}

func updateArtBox(d types.Dict, artBox *Box, b *boxes) {
	var r *types.Rectangle
	switch artBox.RefBox {
	case "media":
		r = b.mediaBox
	case "crop":
		r = b.cropBox
	case "trim":
		r = b.trimBox
		if r == nil {
			r = b.cropBox
		}
	case "bleed":
		r = b.bleedBox
		if r == nil {
			r = b.cropBox
		}
	}
	d.Update("ArtBox", r.Array())
	b.artBox = r
}

func applyBoxAssignments(d types.Dict, pb *PageBoundaries, b *boxes) {
	if pb.Trim != nil && pb.Trim.RefBox != "" {
		updateTrimBox(d, pb.Trim, b)
	}

	if pb.Bleed != nil && pb.Bleed.RefBox != "" {
		updateBleedBox(d, pb.Bleed, b)
	}

	if pb.Art != nil && pb.Art.RefBox != "" {
		updateArtBox(d, pb.Art, b)
	}
}

// AddPageBoundaries adds page boundaries specified by pb for selected pages.
func (ctx *Context) AddPageBoundaries(selectedPages types.IntSet, pb *PageBoundaries) error {
	for k, v := range selectedPages {
		if !v {
			continue
		}
		d, _, inhPAttrs, err := ctx.PageDict(k, false)
		if err != nil {
			return err
		}
		mediaBox := inhPAttrs.MediaBox
		cropBox := inhPAttrs.CropBox

		var trimBox *types.Rectangle
		obj, found := d.Find("TrimBox")
		if found {
			a, err := ctx.DereferenceArray(obj)
			if err != nil {
				return err
			}
			if trimBox, err = rect(ctx.XRefTable, a); err != nil {
				return err
			}
		}

		var bleedBox *types.Rectangle
		obj, found = d.Find("BleedBox")
		if found {
			a, err := ctx.DereferenceArray(obj)
			if err != nil {
				return err
			}
			if bleedBox, err = rect(ctx.XRefTable, a); err != nil {
				return err
			}
		}

		var artBox *types.Rectangle
		obj, found = d.Find("ArtBox")
		if found {
			a, err := ctx.DereferenceArray(obj)
			if err != nil {
				return err
			}
			if artBox, err = rect(ctx.XRefTable, a); err != nil {
				return err
			}
		}

		boxes := &boxes{mediaBox: mediaBox, cropBox: cropBox, trimBox: trimBox, bleedBox: bleedBox, artBox: artBox}
		applyBoxDefinitions(d, pb, boxes)
		applyBoxAssignments(d, pb, boxes)
	}
	return nil
}

// Crop sets crop box for selected pages to b.
func (ctx *Context) Crop(selectedPages types.IntSet, b *Box) error {
	for k, v := range selectedPages {
		if !v {
			continue
		}
		d, _, inhPAttrs, err := ctx.PageDict(k, false)
		if err != nil {
			return err
		}
		ApplyBox("CropBox", b, d, inhPAttrs.MediaBox)
	}
	return nil
}

repository: pdfcpu/pdfcpu

repo_name: pdfcpu/pdfcpu


text:
package main

import (
	"github.com/vennekilde/gw2apidb/pkg/gw2api"
	"github.com/vennekilde/gw2apidb/pkg/orm"
	"github.com/vennekilde/gw2verify/internal/api"
	"github.com/vennekilde/gw2verify/internal/config"
	"github.com/vennekilde/gw2verify/pkg/history"
	"github.com/vennekilde/gw2verify/pkg/sync"
	"github.com/vennekilde/gw2verify/pkg/verify"
	"go.uber.org/zap"
)

func init() {
	logger, _ := zap.NewDevelopment()
	defer logger.Sync()
	_ = zap.ReplaceGlobals(logger)
	zap.L().Info("replaced zap's global loggers")
}

func main() {
	if config.Config().Debug {
		orm.DB().Debug()
		orm.DB().LogMode(true)
	}

	orm.DB().AutoMigrate(&gw2api.Account{}, &gw2api.TokenInfo{})
	orm.DB().AutoMigrate(&history.History{})
	orm.DB().AutoMigrate(&verify.ServiceLink{}, &verify.TemporaryAccess{})

	/*go func() {
		statistics.Collect()
		for range time.Tick(time.Minute * 5) {
			statistics.Collect()
		}
	}()*/

	go api.StartServer()

	gw2api := gw2api.NewGW2Api()
	go verify.BeginWorldLinksSyncLoop(gw2api)
	sync.StartAPISynchronizer(gw2api)
}

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: go


text:
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
  "C"
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_C
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/Bn.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/Bn.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/BnDrv.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/BnDrv.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/En.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/En.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/EnDrv.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/EnDrv.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/Fn.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/Fn.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/FnDrv.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/FnDrv.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/Lagrange.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/Lagrange.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/blend.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/blend.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/blendDrv.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/blendDrv.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/modeShape.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/modeShape.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/modeShapeDrv.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/modeShapeDrv.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/parDrv.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/parDrv.c.o"
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/uniformP.c" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/uniformP.c.o"
  )
set(CMAKE_C_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_C
  "DEBUG"
  "LINUX"
  "MPICH_SKIP_MPICXX"
  "OMPI_SKIP_MPICXX"
  "PARALLEL"
  )

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "."
  )
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/erpe8051/PHASTA_Forked/shapeFunction/src/TriShapeAndDrv.cc" "/home/erpe8051/PHASTA_Forked/debug_build/shapeFunction/src/CMakeFiles/shapeFunction.dir/TriShapeAndDrv.cc.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_CXX
  "DEBUG"
  "LINUX"
  "MPICH_SKIP_MPICXX"
  "OMPI_SKIP_MPICXX"
  "PARALLEL"
  )

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  "."
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")

repository: elpeters/phasta

repo_name: elpeters/phasta

extension: cmake


text:
DESCRIPTION = "DNS Resolver Library"
HOMEPAGE = "http://www.corpit.ru/mjt/udns.html"
PR = "r0"

SRC_URI = " \
	    http://www.corpit.ru/mjt/${PN}/${PN}_${PV}.tar.gz;name=udns \
        file://fix-cc-check.patch \
"
SRC_URI[udns.md5sum] = "78843added6f6b690bc6019ab8ef03c9"
SRC_URI[udns.sha256sum] = "cfc5f9b5387f96e48fc9c7aa5ef6511809e6c72c0df0d533cf150016816eaad2"

S = ${WORKDIR}/${PN}-${PV}

TARGET_CC_ARCH += "${LDFLAGS}"

# Package is using configure and Makefile.in, but not autotools in general ...

do_configure() {
	./configure --disable-ipv6
}

do_compile() {
    oe_runmake shared static
}

do_install() {
    oe_libinstall -so -a libudns ${D}${libdir}
    ln -s libudns.so.0 ${D}${libdir}/libudns_s.so
    install -d ${D}${includedir}
    install -m 0644 ${S}/udns.h ${D}${includedir}
}

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
//
// DISCLAIMER
//
// Copyright 2020 ArangoDB GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
//

package format

import (
	iam "github.com/arangodb-managed/apis/iam/v1"
)

// User returns a single user formatted for humans.
func User(x *iam.User, opts Options) string {
	return formatObject(opts,
		kv{"id", x.GetId()},
		kv{"name", x.GetName()},
		kv{"email", x.GetEmail()},
		kv{"created_at", formatTime(opts, x.GetCreatedAt(), "-")},
		kv{"last_login_at", formatTime(opts, x.GetLastLoginAt(), "-")},
		kv{"last_ip", x.GetLastIp()},
	)
}

// UserList returns a list of users formatted for humans.
func UserList(list []*iam.User, opts Options) string {
	return formatList(opts, list, func(i int) []kv {
		x := list[i]
		return []kv{
			kv{"id", x.GetId()},
			kv{"name", x.GetName()},
			kv{"email", x.GetEmail()},
			kv{"created_at", formatTime(opts, x.GetCreatedAt(), "-")},
			kv{"last_login_at", formatTime(opts, x.GetLastLoginAt(), "-")},
			kv{"last_ip", x.GetLastIp()},
		}
	}, false)
}


text:
@article{wang2018structural,
 author = {Wang, Xiuyi and Bernhardt, Boris C and Karapanagiotidis, Theodoros and De Caso, Irene and Alam, Tirso Rene del Jesus Gonzalez and Cotter, Zacharria and Smallwood, Jonathan and Jefferies, Elizabeth},
 journal = {NeuroImage},
 pages = {480--489},
 publisher = {Academic Press},
 title = {The structural basis of semantic control: Evidence from individual differences in cortical thickness},
 volume = {181},
 year = {2018}
}

repository: tkarapan/academic-kickstart

repo_name: tkarapan/academic-kickstart

extension: bib


text:
SUMMARY = "Standalone port/fork of Mednafen PSX to the Libretro API."
HOMEPAGE = "http://github.com/libretro/beetle-psx-libretro"
SECTION = "emulators"

LICENSE = "GPLv2 & LGPLv2.1"
LIC_FILES_CHKSUM = "file://COPYING;md5=6e233eda45c807aa29aeaa6d94bc48a2 \
		    "
FILESEXTRAPATHS_prepend := "${THISDIR}/${PN}:"

SRC_URI = "git://github.com/libretro/beetle-psx-libretro.git;protocol=https \
	   file://0001-Fix_compile_host_path.patch \
	   "

SRCREV = "${AUTOREV}"

S = "${WORKDIR}/git"

inherit autotools-brokensep

do_install() {
    install -d ${D}/usr/lib/libretro
    install -m 0755 mednafen_psx_libretro.so ${D}/usr/lib/libretro
}

FILES_${PN} += " /usr/lib/libretro/mednafen_psx_libretro.so"

repository: claneys/meta-libretro

repo_name: claneys/meta-libretro


text:
//----------------------------------------
// 代码由GenlibVcl工具自动生成。
// Copyright © ying32. All Rights Reserved.
//
//----------------------------------------

package vcl

import (
	. "github.com/ying32/govcl/vcl/api"
    . "github.com/ying32/govcl/vcl/types"
)

type TComboBox struct {
    IWinControl
    instance uintptr
}

func NewComboBox(owner IComponent) *TComboBox {
    c := new(TComboBox)
    c.instance = ComboBox_Create(CheckPtr(owner))
    return c
}

func ComboBoxFromInst(inst uintptr) *TComboBox {
    c := new(TComboBox)
    c.instance = inst
    return c
}

func ComboBoxFromObj(obj IObject) *TComboBox {
    c := new(TComboBox)
    c.instance = CheckPtr(obj)
    return c
}

func (c *TComboBox) Free() {
    if c.instance != 0 {
        ComboBox_Free(c.instance)
        c.instance = 0
    }
}

func (c *TComboBox) Instance() uintptr {
    return c.instance
}

func (c *TComboBox) IsValid() bool {
    return c.instance != 0
}

func TComboBoxClass() TClass {
    return ComboBox_StaticClassType()
}

func (c *TComboBox) AddItem(Item string, AObject IObject) {
    ComboBox_AddItem(c.instance, Item , CheckPtr(AObject))
}

func (c *TComboBox) Clear() {
    ComboBox_Clear(c.instance)
}

func (c *TComboBox) ClearSelection() {
    ComboBox_ClearSelection(c.instance)
}

func (c *TComboBox) DeleteSelected() {
    ComboBox_DeleteSelected(c.instance)
}

func (c *TComboBox) Focused() bool {
    return ComboBox_Focused(c.instance)
}

func (c *TComboBox) SelectAll() {
    ComboBox_SelectAll(c.instance)
}

func (c *TComboBox) CanFocus() bool {
    return ComboBox_CanFocus(c.instance)
}

func (c *TComboBox) FlipChildren(AllLevels bool) {
    ComboBox_FlipChildren(c.instance, AllLevels)
}

func (c *TComboBox) HandleAllocated() bool {
    return ComboBox_HandleAllocated(c.instance)
}

func (c *TComboBox) Invalidate() {
    ComboBox_Invalidate(c.instance)
}

func (c *TComboBox) Realign() {
    ComboBox_Realign(c.instance)
}

func (c *TComboBox) Repaint() {
    ComboBox_Repaint(c.instance)
}

func (c *TComboBox) ScaleBy(M int32, D int32) {
    ComboBox_ScaleBy(c.instance, M , D)
}

func (c *TComboBox) SetBounds(ALeft int32, ATop int32, AWidth int32, AHeight int32) {
    ComboBox_SetBounds(c.instance, ALeft , ATop , AWidth , AHeight)
}

func (c *TComboBox) SetFocus() {
    ComboBox_SetFocus(c.instance)
}

func (c *TComboBox) Update() {
    ComboBox_Update(c.instance)
}

func (c *TComboBox) BringToFront() {
    ComboBox_BringToFront(c.instance)
}

func (c *TComboBox) ClientToScreen(Point TPoint) TPoint {
    return ComboBox_ClientToScreen(c.instance, Point)
}

func (c *TComboBox) ClientToParent(Point TPoint, AParent IWinControl) TPoint {
    return ComboBox_ClientToParent(c.instance, Point , CheckPtr(AParent))
}

func (c *TComboBox) Dragging() bool {
    return ComboBox_Dragging(c.instance)
}

func (c *TComboBox) HasParent() bool {
    return ComboBox_HasParent(c.instance)
}

func (c *TComboBox) Hide() {
    ComboBox_Hide(c.instance)
}

func (c *TComboBox) Perform(Msg uint32, WParam uintptr, LParam int) int {
    return ComboBox_Perform(c.instance, Msg , WParam , LParam)
}

func (c *TComboBox) Refresh() {
    ComboBox_Refresh(c.instance)
}

func (c *TComboBox) ScreenToClient(Point TPoint) TPoint {
    return ComboBox_ScreenToClient(c.instance, Point)
}

func (c *TComboBox) ParentToClient(Point TPoint, AParent IWinControl) TPoint {
    return ComboBox_ParentToClient(c.instance, Point , CheckPtr(AParent))
}

func (c *TComboBox) SendToBack() {
    ComboBox_SendToBack(c.instance)
}

func (c *TComboBox) Show() {
    ComboBox_Show(c.instance)
}

func (c *TComboBox) GetTextBuf(Buffer string, BufSize int32) int32 {
    return ComboBox_GetTextBuf(c.instance, Buffer , BufSize)
}

func (c *TComboBox) GetTextLen() int32 {
    return ComboBox_GetTextLen(c.instance)
}

func (c *TComboBox) FindComponent(AName string) *TComponent {
    return ComponentFromInst(ComboBox_FindComponent(c.instance, AName))
}

func (c *TComboBox) GetNamePath() string {
    return ComboBox_GetNamePath(c.instance)
}

func (c *TComboBox) Assign(Source IObject) {
    ComboBox_Assign(c.instance, CheckPtr(Source))
}

func (c *TComboBox) DisposeOf() {
    ComboBox_DisposeOf(c.instance)
}

func (c *TComboBox) ClassType() TClass {
    return ComboBox_ClassType(c.instance)
}

func (c *TComboBox) ClassName() string {
    return ComboBox_ClassName(c.instance)
}

func (c *TComboBox) InstanceSize() int32 {
    return ComboBox_InstanceSize(c.instance)
}

func (c *TComboBox) InheritsFrom(AClass TClass) bool {
    return ComboBox_InheritsFrom(c.instance, AClass)
}

func (c *TComboBox) Equals(Obj IObject) bool {
    return ComboBox_Equals(c.instance, CheckPtr(Obj))
}

func (c *TComboBox) GetHashCode() int32 {
    return ComboBox_GetHashCode(c.instance)
}

func (c *TComboBox) ToString() string {
    return ComboBox_ToString(c.instance)
}

func (c *TComboBox) Align() TAlign {
    return ComboBox_GetAlign(c.instance)
}

func (c *TComboBox) SetAlign(value TAlign) {
    ComboBox_SetAlign(c.instance, value)
}

func (c *TComboBox) AutoComplete() bool {
    return ComboBox_GetAutoComplete(c.instance)
}

func (c *TComboBox) SetAutoComplete(value bool) {
    ComboBox_SetAutoComplete(c.instance, value)
}

func (c *TComboBox) AutoCompleteDelay() uint32 {
    return ComboBox_GetAutoCompleteDelay(c.instance)
}

func (c *TComboBox) SetAutoCompleteDelay(value uint32) {
    ComboBox_SetAutoCompleteDelay(c.instance, value)
}

func (c *TComboBox) AutoDropDown() bool {
    return ComboBox_GetAutoDropDown(c.instance)
}

func (c *TComboBox) SetAutoDropDown(value bool) {
    ComboBox_SetAutoDropDown(c.instance, value)
}

func (c *TComboBox) AutoCloseUp() bool {
    return ComboBox_GetAutoCloseUp(c.instance)
}

func (c *TComboBox) SetAutoCloseUp(value bool) {
    ComboBox_SetAutoCloseUp(c.instance, value)
}

func (c *TComboBox) BevelEdges() TBevelEdges {
    return ComboBox_GetBevelEdges(c.instance)
}

func (c *TComboBox) SetBevelEdges(value TBevelEdges) {
    ComboBox_SetBevelEdges(c.instance, value)
}

func (c *TComboBox) BevelInner() TBevelCut {
    return ComboBox_GetBevelInner(c.instance)
}

func (c *TComboBox) SetBevelInner(value TBevelCut) {
    ComboBox_SetBevelInner(c.instance, value)
}

func (c *TComboBox) BevelKind() TBevelKind {
    return ComboBox_GetBevelKind(c.instance)
}

func (c *TComboBox) SetBevelKind(value TBevelKind) {
    ComboBox_SetBevelKind(c.instance, value)
}

func (c *TComboBox) BevelOuter() TBevelCut {
    return ComboBox_GetBevelOuter(c.instance)
}

func (c *TComboBox) SetBevelOuter(value TBevelCut) {
    ComboBox_SetBevelOuter(c.instance, value)
}

func (c *TComboBox) Style() TComboBoxStyle {
    return ComboBox_GetStyle(c.instance)
}

func (c *TComboBox) SetStyle(value TComboBoxStyle) {
    ComboBox_SetStyle(c.instance, value)
}

func (c *TComboBox) Anchors() TAnchors {
    return ComboBox_GetAnchors(c.instance)
}

func (c *TComboBox) SetAnchors(value TAnchors) {
    ComboBox_SetAnchors(c.instance, value)
}

func (c *TComboBox) BiDiMode() TBiDiMode {
    return ComboBox_GetBiDiMode(c.instance)
}

func (c *TComboBox) SetBiDiMode(value TBiDiMode) {
    ComboBox_SetBiDiMode(c.instance, value)
}

func (c *TComboBox) CharCase() TEditCharCase {
    return ComboBox_GetCharCase(c.instance)
}

func (c *TComboBox) SetCharCase(value TEditCharCase) {
    ComboBox_SetCharCase(c.instance, value)
}

func (c *TComboBox) Color() TColor {
    return ComboBox_GetColor(c.instance)
}

func (c *TComboBox) SetColor(value TColor) {
    ComboBox_SetColor(c.instance, value)
}

func (c *TComboBox) DoubleBuffered() bool {
    return ComboBox_GetDoubleBuffered(c.instance)
}

func (c *TComboBox) SetDoubleBuffered(value bool) {
    ComboBox_SetDoubleBuffered(c.instance, value)
}

func (c *TComboBox) DragCursor() TCursor {
    return ComboBox_GetDragCursor(c.instance)
}

func (c *TComboBox) SetDragCursor(value TCursor) {
    ComboBox_SetDragCursor(c.instance, value)
}

func (c *TComboBox) DragKind() TDragKind {
    return ComboBox_GetDragKind(c.instance)
}

func (c *TComboBox) SetDragKind(value TDragKind) {
    ComboBox_SetDragKind(c.instance, value)
}

func (c *TComboBox) DragMode() TDragMode {
    return ComboBox_GetDragMode(c.instance)
}

func (c *TComboBox) SetDragMode(value TDragMode) {
    ComboBox_SetDragMode(c.instance, value)
}

func (c *TComboBox) DropDownCount() int32 {
    return ComboBox_GetDropDownCount(c.instance)
}

func (c *TComboBox) SetDropDownCount(value int32) {
    ComboBox_SetDropDownCount(c.instance, value)
}

func (c *TComboBox) Enabled() bool {
    return ComboBox_GetEnabled(c.instance)
}

func (c *TComboBox) SetEnabled(value bool) {
    ComboBox_SetEnabled(c.instance, value)
}

func (c *TComboBox) Font() *TFont {
    return FontFromInst(ComboBox_GetFont(c.instance))
}

func (c *TComboBox) SetFont(value *TFont) {
    ComboBox_SetFont(c.instance, CheckPtr(value))
}

func (c *TComboBox) ItemHeight() int32 {
    return ComboBox_GetItemHeight(c.instance)
}

func (c *TComboBox) SetItemHeight(value int32) {
    ComboBox_SetItemHeight(c.instance, value)
}

func (c *TComboBox) ItemIndex() int32 {
    return ComboBox_GetItemIndex(c.instance)
}

func (c *TComboBox) SetItemIndex(value int32) {
    ComboBox_SetItemIndex(c.instance, value)
}

func (c *TComboBox) MaxLength() int32 {
    return ComboBox_GetMaxLength(c.instance)
}

func (c *TComboBox) SetMaxLength(value int32) {
    ComboBox_SetMaxLength(c.instance, value)
}

func (c *TComboBox) ParentColor() bool {
    return ComboBox_GetParentColor(c.instance)
}

func (c *TComboBox) SetParentColor(value bool) {
    ComboBox_SetParentColor(c.instance, value)
}

func (c *TComboBox) ParentCtl3D() bool {
    return ComboBox_GetParentCtl3D(c.instance)
}

func (c *TComboBox) SetParentCtl3D(value bool) {
    ComboBox_SetParentCtl3D(c.instance, value)
}

func (c *TComboBox) ParentDoubleBuffered() bool {
    return ComboBox_GetParentDoubleBuffered(c.instance)
}

func (c *TComboBox) SetParentDoubleBuffered(value bool) {
    ComboBox_SetParentDoubleBuffered(c.instance, value)
}

func (c *TComboBox) ParentFont() bool {
    return ComboBox_GetParentFont(c.instance)
}

func (c *TComboBox) SetParentFont(value bool) {
    ComboBox_SetParentFont(c.instance, value)
}

func (c *TComboBox) ParentShowHint() bool {
    return ComboBox_GetParentShowHint(c.instance)
}

func (c *TComboBox) SetParentShowHint(value bool) {
    ComboBox_SetParentShowHint(c.instance, value)
}

func (c *TComboBox) PopupMenu() *TPopupMenu {
    return PopupMenuFromInst(ComboBox_GetPopupMenu(c.instance))
}

func (c *TComboBox) SetPopupMenu(value IComponent) {
    ComboBox_SetPopupMenu(c.instance, CheckPtr(value))
}

func (c *TComboBox) ShowHint() bool {
    return ComboBox_GetShowHint(c.instance)
}

func (c *TComboBox) SetShowHint(value bool) {
    ComboBox_SetShowHint(c.instance, value)
}

func (c *TComboBox) Sorted() bool {
    return ComboBox_GetSorted(c.instance)
}

func (c *TComboBox) SetSorted(value bool) {
    ComboBox_SetSorted(c.instance, value)
}

func (c *TComboBox) TabOrder() uint16 {
    return ComboBox_GetTabOrder(c.instance)
}

func (c *TComboBox) SetTabOrder(value uint16) {
    ComboBox_SetTabOrder(c.instance, value)
}

func (c *TComboBox) TabStop() bool {
    return ComboBox_GetTabStop(c.instance)
}

func (c *TComboBox) SetTabStop(value bool) {
    ComboBox_SetTabStop(c.instance, value)
}

func (c *TComboBox) Text() string {
    return ComboBox_GetText(c.instance)
}

func (c *TComboBox) SetText(value string) {
    ComboBox_SetText(c.instance, value)
}

func (c *TComboBox) TextHint() string {
    return ComboBox_GetTextHint(c.instance)
}

func (c *TComboBox) SetTextHint(value string) {
    ComboBox_SetTextHint(c.instance, value)
}

func (c *TComboBox) Visible() bool {
    return ComboBox_GetVisible(c.instance)
}

func (c *TComboBox) SetVisible(value bool) {
    ComboBox_SetVisible(c.instance, value)
}

func (c *TComboBox) StyleElements() TStyleElements {
    return ComboBox_GetStyleElements(c.instance)
}

func (c *TComboBox) SetStyleElements(value TStyleElements) {
    ComboBox_SetStyleElements(c.instance, value)
}

func (c *TComboBox) SetOnChange(fn TNotifyEvent) {
    ComboBox_SetOnChange(c.instance, fn)
}

func (c *TComboBox) SetOnClick(fn TNotifyEvent) {
    ComboBox_SetOnClick(c.instance, fn)
}

func (c *TComboBox) SetOnContextPopup(fn TContextPopupEvent) {
    ComboBox_SetOnContextPopup(c.instance, fn)
}

func (c *TComboBox) SetOnDblClick(fn TNotifyEvent) {
    ComboBox_SetOnDblClick(c.instance, fn)
}

func (c *TComboBox) SetOnDragDrop(fn TDragDropEvent) {
    ComboBox_SetOnDragDrop(c.instance, fn)
}

func (c *TComboBox) SetOnDragOver(fn TDragOverEvent) {
    ComboBox_SetOnDragOver(c.instance, fn)
}

func (c *TComboBox) SetOnDrawItem(fn TDrawItemEvent) {
    ComboBox_SetOnDrawItem(c.instance, fn)
}

func (c *TComboBox) SetOnEndDock(fn TEndDragEvent) {
    ComboBox_SetOnEndDock(c.instance, fn)
}

func (c *TComboBox) SetOnEndDrag(fn TEndDragEvent) {
    ComboBox_SetOnEndDrag(c.instance, fn)
}

func (c *TComboBox) SetOnEnter(fn TNotifyEvent) {
    ComboBox_SetOnEnter(c.instance, fn)
}

func (c *TComboBox) SetOnExit(fn TNotifyEvent) {
    ComboBox_SetOnExit(c.instance, fn)
}

func (c *TComboBox) SetOnKeyDown(fn TKeyEvent) {
    ComboBox_SetOnKeyDown(c.instance, fn)
}

func (c *TComboBox) SetOnKeyPress(fn TKeyPressEvent) {
    ComboBox_SetOnKeyPress(c.instance, fn)
}

func (c *TComboBox) SetOnKeyUp(fn TKeyEvent) {
    ComboBox_SetOnKeyUp(c.instance, fn)
}

func (c *TComboBox) SetOnMouseEnter(fn TNotifyEvent) {
    ComboBox_SetOnMouseEnter(c.instance, fn)
}

func (c *TComboBox) SetOnMouseLeave(fn TNotifyEvent) {
    ComboBox_SetOnMouseLeave(c.instance, fn)
}

func (c *TComboBox) SetOnStartDock(fn TStartDockEvent) {
    ComboBox_SetOnStartDock(c.instance, fn)
}

func (c *TComboBox) Items() *TStrings {
    return StringsFromInst(ComboBox_GetItems(c.instance))
}

func (c *TComboBox) SetItems(value IObject) {
    ComboBox_SetItems(c.instance, CheckPtr(value))
}

func (c *TComboBox) SelText() string {
    return ComboBox_GetSelText(c.instance)
}

func (c *TComboBox) SetSelText(value string) {
    ComboBox_SetSelText(c.instance, value)
}

func (c *TComboBox) Canvas() *TCanvas {
    return CanvasFromInst(ComboBox_GetCanvas(c.instance))
}

func (c *TComboBox) DroppedDown() bool {
    return ComboBox_GetDroppedDown(c.instance)
}

func (c *TComboBox) SetDroppedDown(value bool) {
    ComboBox_SetDroppedDown(c.instance, value)
}

func (c *TComboBox) SelLength() int32 {
    return ComboBox_GetSelLength(c.instance)
}

func (c *TComboBox) SetSelLength(value int32) {
    ComboBox_SetSelLength(c.instance, value)
}

func (c *TComboBox) SelStart() int32 {
    return ComboBox_GetSelStart(c.instance)
}

func (c *TComboBox) SetSelStart(value int32) {
    ComboBox_SetSelStart(c.instance, value)
}

func (c *TComboBox) DockSite() bool {
    return ComboBox_GetDockSite(c.instance)
}

func (c *TComboBox) SetDockSite(value bool) {
    ComboBox_SetDockSite(c.instance, value)
}

func (c *TComboBox) Brush() *TBrush {
    return BrushFromInst(ComboBox_GetBrush(c.instance))
}

func (c *TComboBox) ControlCount() int32 {
    return ComboBox_GetControlCount(c.instance)
}

func (c *TComboBox) Handle() HWND {
    return ComboBox_GetHandle(c.instance)
}

func (c *TComboBox) ParentWindow() HWND {
    return ComboBox_GetParentWindow(c.instance)
}

func (c *TComboBox) SetParentWindow(value HWND) {
    ComboBox_SetParentWindow(c.instance, value)
}

func (c *TComboBox) UseDockManager() bool {
    return ComboBox_GetUseDockManager(c.instance)
}

func (c *TComboBox) SetUseDockManager(value bool) {
    ComboBox_SetUseDockManager(c.instance, value)
}

func (c *TComboBox) Action() *TAction {
    return ActionFromInst(ComboBox_GetAction(c.instance))
}

func (c *TComboBox) SetAction(value IComponent) {
    ComboBox_SetAction(c.instance, CheckPtr(value))
}

func (c *TComboBox) BoundsRect() TRect {
    return ComboBox_GetBoundsRect(c.instance)
}

func (c *TComboBox) SetBoundsRect(value TRect) {
    ComboBox_SetBoundsRect(c.instance, value)
}

func (c *TComboBox) ClientHeight() int32 {
    return ComboBox_GetClientHeight(c.instance)
}

func (c *TComboBox) SetClientHeight(value int32) {
    ComboBox_SetClientHeight(c.instance, value)
}

func (c *TComboBox) ClientRect() TRect {
    return ComboBox_GetClientRect(c.instance)
}

func (c *TComboBox) ClientWidth() int32 {
    return ComboBox_GetClientWidth(c.instance)
}

func (c *TComboBox) SetClientWidth(value int32) {
    ComboBox_SetClientWidth(c.instance, value)
}

func (c *TComboBox) ExplicitLeft() int32 {
    return ComboBox_GetExplicitLeft(c.instance)
}

func (c *TComboBox) ExplicitTop() int32 {
    return ComboBox_GetExplicitTop(c.instance)
}

func (c *TComboBox) ExplicitWidth() int32 {
    return ComboBox_GetExplicitWidth(c.instance)
}

func (c *TComboBox) ExplicitHeight() int32 {
    return ComboBox_GetExplicitHeight(c.instance)
}

func (c *TComboBox) Floating() bool {
    return ComboBox_GetFloating(c.instance)
}

func (c *TComboBox) Parent() *TWinControl {
    return WinControlFromInst(ComboBox_GetParent(c.instance))
}

func (c *TComboBox) SetParent(value IWinControl) {
    ComboBox_SetParent(c.instance, CheckPtr(value))
}

func (c *TComboBox) AlignWithMargins() bool {
    return ComboBox_GetAlignWithMargins(c.instance)
}

func (c *TComboBox) SetAlignWithMargins(value bool) {
    ComboBox_SetAlignWithMargins(c.instance, value)
}

func (c *TComboBox) Left() int32 {
    return ComboBox_GetLeft(c.instance)
}

func (c *TComboBox) SetLeft(value int32) {
    ComboBox_SetLeft(c.instance, value)
}

func (c *TComboBox) Top() int32 {
    return ComboBox_GetTop(c.instance)
}

func (c *TComboBox) SetTop(value int32) {
    ComboBox_SetTop(c.instance, value)
}

func (c *TComboBox) Width() int32 {
    return ComboBox_GetWidth(c.instance)
}

func (c *TComboBox) SetWidth(value int32) {
    ComboBox_SetWidth(c.instance, value)
}

func (c *TComboBox) Height() int32 {
    return ComboBox_GetHeight(c.instance)
}

func (c *TComboBox) SetHeight(value int32) {
    ComboBox_SetHeight(c.instance, value)
}

func (c *TComboBox) Cursor() TCursor {
    return ComboBox_GetCursor(c.instance)
}

func (c *TComboBox) SetCursor(value TCursor) {
    ComboBox_SetCursor(c.instance, value)
}

func (c *TComboBox) Hint() string {
    return ComboBox_GetHint(c.instance)
}

func (c *TComboBox) SetHint(value string) {
    ComboBox_SetHint(c.instance, value)
}

func (c *TComboBox) Margins() *TMargins {
    return MarginsFromInst(ComboBox_GetMargins(c.instance))
}

func (c *TComboBox) SetMargins(value *TMargins) {
    ComboBox_SetMargins(c.instance, CheckPtr(value))
}

func (c *TComboBox) CustomHint() *TCustomHint {
    return CustomHintFromInst(ComboBox_GetCustomHint(c.instance))
}

func (c *TComboBox) SetCustomHint(value IComponent) {
    ComboBox_SetCustomHint(c.instance, CheckPtr(value))
}

func (c *TComboBox) ComponentCount() int32 {
    return ComboBox_GetComponentCount(c.instance)
}

func (c *TComboBox) ComponentIndex() int32 {
    return ComboBox_GetComponentIndex(c.instance)
}

func (c *TComboBox) SetComponentIndex(value int32) {
    ComboBox_SetComponentIndex(c.instance, value)
}

func (c *TComboBox) Owner() *TComponent {
    return ComponentFromInst(ComboBox_GetOwner(c.instance))
}

func (c *TComboBox) Name() string {
    return ComboBox_GetName(c.instance)
}

func (c *TComboBox) SetName(value string) {
    ComboBox_SetName(c.instance, value)
}

func (c *TComboBox) Tag() int {
    return ComboBox_GetTag(c.instance)
}

func (c *TComboBox) SetTag(value int) {
    ComboBox_SetTag(c.instance, value)
}

func (c *TComboBox) Controls(Index int32) *TControl {
    return ControlFromInst(ComboBox_GetControls(c.instance, Index))
}

func (c *TComboBox) Components(AIndex int32) *TComponent {
    return ComponentFromInst(ComboBox_GetComponents(c.instance, AIndex))
}


text:
#Mini2440 Erlang + Qt4 image
require mini2440-erlang-image.bb

DEPENDS += "qt4-embedded"

IMAGE_INSTALL += "qt4-embedded \
                  qt4-embedded-fonts \
                  qt4-embedded-plugin-mousedriver-tslib"

export IMAGE_BASENAME = "mini2440-erlang-qt4-image"


text:
package y${YEAR}m${MONTH}

// 每日一题 ${YEAR}${MONTH}${DAY}
//
//
// Link:
func () {
}

repository: yourtion/LeetCode

repo_name: yourtion/LeetCode


text:
package selftest

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/deliveroo/assert-go"
	"github.com/jackc/fake"
	"github.com/oliveagle/jsonpath"
	"github.com/pkg/errors"
)

// m is shorthand for an untyped map (i.e. a json object).
type m map[string]interface{}

type API struct {
	Username string
	Password string
	Token    string
}

func (a *API) Delete(t *testing.T, path string, body interface{}) *TestResponse {
	t.Helper()
	return a.do(t, http.MethodDelete, path, body)
}

func (a *API) Post(t *testing.T, path string, body interface{}) *TestResponse {
	t.Helper()
	return a.do(t, http.MethodPost, path, body)
}

func (a *API) Put(t *testing.T, path string, body interface{}) *TestResponse {
	t.Helper()
	return a.do(t, http.MethodPut, path, body)
}

func (a *API) Get(t *testing.T, path string) *TestResponse {
	t.Helper()
	req, err := http.NewRequest(http.MethodGet, url+path, nil)
	assert.Must(t, err)
	if a.Token != "" {
		req.Header.Set("x-todo-token", a.Token)
	}
	resp, err := http.DefaultClient.Do(req)
	assert.Must(t, err)
	return &TestResponse{resp: resp}
}

func (a *API) do(t *testing.T, httpMethod string, path string, body interface{}) *TestResponse {
	var reader io.Reader
	if body != nil {
		json, err := json.Marshal(body)
		assert.Must(t, err)
		reader = bytes.NewBuffer(json)
	}
	req, err := http.NewRequest(httpMethod, url+path, reader)
	assert.Must(t, err)
	if a.Token != "" {
		req.Header.Set("x-todo-token", a.Token)
	}
	resp, err := http.DefaultClient.Do(req)
	assert.Must(t, err)
	return &TestResponse{resp: resp}
}

func fakePassword() string {
	return fake.Password(8, 32, true, true, true)
}

func withAccount(t *testing.T, fn func(*API)) {
	t.Helper()
	api := &API{
		Username: "user-" + time.Now().Format(time.RFC3339Nano),
		Password: fakePassword(),
	}
	account := m{
		"username": api.Username,
		"password": api.Password,
	}
	resp := api.Post(t, "/account", account)
	resp.AssertStatusCode(t, 200)
	resp = api.Post(t, "/account/login", account)
	resp.AssertStatusCode(t, 200)
	api.Token = resp.JSONPathString(t, "token")
	fn(api)
}

type TestResponse struct {
	resp *http.Response
	body []byte
	json interface{}
}

func (r *TestResponse) AssertStatusCode(t *testing.T, want int) {
	t.Helper()
	if r.StatusCode() != want {
		t.Fatalf("unexpected status code, got %d, want %d:\n%s´", r.StatusCode(), want, r.JSONBody(t))
	}
}

func (r *TestResponse) BindBody(t *testing.T, val interface{}) {
	t.Helper()
	r.EnsureReadAll(t)
	if err := json.Unmarshal(r.body, val); err != nil {
		t.Fatalf("%s:\n%s", err, r.body)
	}
}

func (r *TestResponse) EnsureReadAll(t *testing.T) {
	t.Helper()
	if len(r.body) > 0 {
		return
	}
	defer r.resp.Body.Close()
	b, err := ioutil.ReadAll(r.resp.Body)
	assert.Must(t, err)
	r.body = b
	var data interface{}
	if err := json.Unmarshal(b, &data); err != nil {
		t.Fatal(errors.Wrap(err, "EnsureReadAll Unmarshal"))
	}
	r.json = data
}

type apiError struct {
	Error struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error"`
}

func (r *TestResponse) error(t *testing.T) apiError {
	t.Helper()
	r.EnsureReadAll(t)
	var e apiError
	assert.Must(t, json.Unmarshal(r.body, &e))
	return apiError{Error: e.Error}
}

// ErrorCode returns the value under the key 'code' in an Error object. Note
// this is NOT the response status code.
func (r *TestResponse) ErrorCode(t *testing.T) string {
	return r.error(t).Error.Code
}

func (r *TestResponse) ErrorMessage(t *testing.T) string {
	return r.error(t).Error.Message
}

func (r *TestResponse) JSONPathString(t *testing.T, path string) string {
	t.Helper()
	r.EnsureReadAll(t)
	if !strings.HasPrefix(path, "$.") {
		path = "$." + path
	}
	res, err := jsonpath.JsonPathLookup(r.json, path)
	if err != nil {
		t.Fatalf("%s:\n%s´", err, r.JSONBody(t))
	}
	s, ok := res.(string)
	if !ok {
		t.Fatalf("JSON path value %q is not a string", path)
	}
	return s
}

func (r *TestResponse) JSONPath(t *testing.T, path string) interface{} {
	t.Helper()
	r.EnsureReadAll(t)
	if !strings.HasPrefix(path, "$.") {
		path = "$." + path
	}
	res, err := jsonpath.JsonPathLookup(r.json, path)
	if err != nil {
		t.Fatalf("%s:\n%s´", err, r.JSONBody(t))
	}
	return res
}

func (r *TestResponse) JSONPathEqual(t *testing.T, path string, want interface{}) {
	t.Helper()
	r.EnsureReadAll(t)
	if !strings.HasPrefix(path, "$.") {
		path = "$." + path
	}
	res, err := jsonpath.JsonPathLookup(r.json, path)
	if err != nil {
		t.Fatalf("%s:\n%s´", err, r.JSONBody(t))
	}
	assert.Equal(t, res, want)
}

func (r *TestResponse) JSONBody(t *testing.T) string {
	t.Helper()
	r.EnsureReadAll(t)
	return string(r.body)
}

func (r *TestResponse) StatusCode() int {
	return r.resp.StatusCode
}

license: Unlicense

repository: deliveroo/todo-api

repo_name: deliveroo/todo-api

gha_license_id: Unlicense

gha_language: Go


text:
@inproceedings{lisena2018sparqltransformer,
  title={{Transforming the JSON Output of SPARQL Queries for Linked Data Clients}},
  author={Lisena, Pasquale and Troncy, Rapha\"{e}l},
  booktitle={WWW'18 Companion: The 2018 Web Conference Companion},
  location={Lyon, France},
  eventdate={2018-04-23/2018-04-27},
  year={2018},
  publisher={ACM},
  address={New York, NY, USA},
  numpages = {5},
  url={https://doi.org/10.1145/3184558.3188739},
  doi={10.1145/3184558.3188739}
 }

gha_language: JavaScript


text:
package lcm_calc

import (
	"math"
)

// gcd finds the greatest common denominator of two numbers.
func gcd(x, y int64) int64 {

	for y != 0 {
		x, y = y, x%y
	}

	return x
}

// LcmCalc finds the Least Common Multiple using the gcd function on an array of numbers.
func LcmCalc(numbers []int64) int64 {
	x := numbers[0]
	for _, y := range numbers {
		x = x * y / gcd(x, y)
	}

	return int64(math.Abs(float64(x)))

}

repository: Connexity-Ops/golearn

repo_name: Connexity-Ops/golearn

gha_license_id: MIT


text:
require libidl.inc

PR = "r1"

SRC_URI[md5sum] = "a75d2dbf3a3c66b567047c94245f8b82"
SRC_URI[sha256sum] = "1c9529f7245778a4f1422d6257d446b7c90a19c3b603b1a25db1669552c464b3"


text:
DESCRIPTION = "XFCE initscript"
LICENSE = "GPLv2"
LIC_FILES_CHKSUM = "file://COPYING;md5=751419260aa954499f7abaabaa882bbe"
SECTION = "x11"

SRC_URI = "file://xserver-xfce \
           file://gplv2-license.patch \
           file://xserver-xfce.service \
           file://xserver-xfce.conf \
           file://xserver-logrotate.conf \
"

S = "${WORKDIR}"

inherit allarch update-rc.d

INITSCRIPT_NAME = "xserver-xfce"
INITSCRIPT_PARAMS = "start 01 5 2 . stop 01 0 1 6 ."
INITSCRIPT_PARAMS_shr = "start 90 5 2 . stop 90 0 1 6 ."

do_install() {
    if ${@bb.utils.contains('DISTRO_FEATURES','sysvinit','true','false',d)}; then
        install -d ${D}${sysconfdir}/init.d
        install -d ${D}${sysconfdir}/default/
        install xserver-xfce ${D}${sysconfdir}/init.d
        install -m 0644 xserver-xfce.conf ${D}${sysconfdir}/default/xserver-xfce
    fi
    if ${@bb.utils.contains('DISTRO_FEATURES','systemd','true','false',d)}; then
        install -d ${D}${systemd_unitdir}/system
        install -m 0644 xserver-xfce.conf ${D}${sysconfdir}/default/xserver-xfce
        install -m 0644 ${WORKDIR}/xserver-xfce.service ${D}${systemd_unitdir}/system
    fi
    install -d ${D}${sysconfdir}/logrotate.d
    install -m 0644 xserver-logrotate.conf ${D}${sysconfdir}/logrotate.d/xserver.conf
}

# Get util-linux for su
RDEPENDS_${PN} = "xserver-common (>= 1.30) xinit xfce4-session util-linux"

FILES_${PN} += "${sysconfdir}/default/xserver-xfce"

SYSTEMD_SERVICE_${PN} = "xserver-xfce.service"

#RPROVIDES_${PN} = "xserver-nodm-init"
#RREPLACES_${PN} = "xserver-nodm-init"
RCONFLICTS_${PN} = "xserver-nodm-init"

repository: NIwkoe/meta-nilrt

repo_name: NIwkoe/meta-nilrt

branch_name: refs/heads/nilrt/master/sumo


text:
package types

// Runner type prelimiary struct for running stuff
type Runner struct {
	command string
	shell []string
}

// Command ...
func (r *Runner) Command() string {
	return r.command
}

// Shell ...
func (r *Runner) Shell() []string {
	return r.shell
}

// Init will initialize the runner (bash if no shell provided)
func (r *Runner) Init(shell []string, command string) error {
	if shell[0] != "" {
		r.shell = shell
	} else {
		r.shell = []string {"sh","-c"}
	}
	r.command = command

	return nil
}


text:
package peloton

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// GetSchedule returns scheduled workouts for an date range
func (c *Client) GetSchedule(category string, start, end int) (Schedule, error) {
	var s Schedule
	scheduleEndpoint := fmt.Sprintf("/api/v3/ride/live?content_provider=studio&browse_category=%s&exclude_complete=true&start=%v&end=%v", category, start, end)
	data, err := c.doRequest(http.MethodGet, scheduleEndpoint, nil)
	if err != nil {
		return s, err
	}
	err = json.Unmarshal(data, &s)
	if err != nil {
		return s, fmt.Errorf("failed to unmarshal schedule response, %w", err)
	}

	return s, nil
}

// GetUserSchedule returns authenticated users's schedule
func (c *Client) GetUserSchedule(category string, start, end int) ([]ScheduledWorkout, error) {
	var workouts []ScheduledWorkout
	s, err := c.GetSchedule(category, start, end)
	if err != nil {
		return workouts, nil
	}
	for _, d := range s.Data {
		if d.AuthedUserReservationID != nil {
			workouts = append(workouts, d)
		}
	}
	return workouts, nil
}

repository: ajbosco/rides

repo_name: ajbosco/rides

branch_name: refs/heads/main


text:
package processor

//
//

import (
	"fmt"

	mcapi "github.com/materials-commons/gomcapi"
	"github.com/materials-commons/mcetl/internal/spreadsheet/model"
)

// Creater holds the state needed to create the workflow on the server.
type Creater struct {
	// The project we are adding to
	ProjectID string

	// Name of the experiment to create
	Name string

	// Description of the experiment to create
	Description string

	// The created experiment's ID. This and ProjectID are needed
	// for many of the mcapi REST calls.
	ExperimentID string

	// Does the second column represent the parent column that points to other worksheets. This allows the user
	// to construct a workflow graph.
	HasParent bool

	// Total number of API calls made
	Count int

	// Counts by API call
	ByCallCounts map[string]int

	client *mcapi.Client
}

func NewCreater(projectID, name, description string, client *mcapi.Client) *Creater {
	return &Creater{
		ProjectID:    projectID,
		Name:         name,
		Description:  description,
		client:       client,
		ByCallCounts: make(map[string]int),
	}
}

// Apply implements the Process interface. This version creates the workflow on the server.
func (c *Creater) Apply(worksheets []*model.Worksheet) error {
	// 1. Create the experiment on the server to load the workflow into.
	if err := c.createExperiment(); err != nil {
		return nil
	}

	// 2. Create the workflow from the worksheets
	wf := newWorkflow()
	wf.HasParent = c.HasParent

	wf.constructWorkflow(worksheets)

	// 3. Walk through the workflow creating each of the steps.
	for _, wp := range wf.root {
		if err := c.createWorkflowSteps(wp); err != nil {
			// Even though there were errors the experiment loading is no longer "in progress", so
			// adjust its status. Ignore errors as there is nothing we can do if this fails.
			var _ = c.client.UpdateExperimentProgressStatus(c.ProjectID, c.ExperimentID, false)
			return err
		}
	}

	fmt.Println("Total calls:", c.Count)
	fmt.Printf("%#v\n", c.ByCallCounts)

	// Ignore error - doesn't really matter if this succeeds
	var _ = c.client.UpdateExperimentProgressStatus(c.ProjectID, c.ExperimentID, false)
	return nil
}

// createWorkflowSteps walks the list of steps for a particular workflow item creating the
// samples and processes.
func (c *Creater) createWorkflowSteps(wp *WorkflowProcess) error {
	if wp.Worksheet == nil {
		// Creating the sample
		if sample, err := c.createSample(wp.Samples[0]); err != nil {
			return err
		} else {
			wp.Out = append(wp.Out, sample)
		}
	} else {
		// Create the process if it doesn't already exist
		// 1. Find the input sample
		// 2. Create the process with that input sample and attr
		if wp.Process == nil {
			// Create the process
			p, err := c.createProcessWithAttrs(wp.Worksheet, wp.Samples[0].ProcessAttrs)
			if err != nil {
				return err
			}

			wp.Process = p

			// Add the samples to the process
			inputSamples := c.getInputSamples(wp)

			for _, sample := range inputSamples {
				worksheetSample := c.findSampleInWorksheet(sample.Name, wp.Worksheet.Samples)
				if s, err := c.addSampleAndFilesToProcess(wp.Process.ID, sample, worksheetSample); err != nil {
					return err
				} else {
					wp.Out = append(wp.Out, s)

					// Add measurements
					if worksheetSample != nil {
						if err := c.addMeasurements(wp.Process.ID, s.ID, s.PropertySetID, worksheetSample); err != nil {
							return err
						}
					}
				}
			}
		}

	}

	// Now walk all the WorkflowProcess steps that it sends samples into
	// and create those workflow steps. Do this by recursively calling
	// ourselves (createWorkflowSteps).
	for _, next := range wp.To {
		if err := c.createWorkflowSteps(next); err != nil {
			return err
		}
	}

	return nil
}

func (c *Creater) AddCount(what string) {
	value := c.ByCallCounts[what]
	value++
	c.ByCallCounts[what] = value
}

// createExperiment will create a new experiment in the given project
func (c *Creater) createExperiment() error {
	c.Count++
	c.AddCount("createExperiment")
	experiment, err := c.client.CreateExperiment(c.ProjectID, c.Name, c.Description, true)
	if err != nil {
		return err
	}

	c.ExperimentID = experiment.ID
	return nil
}

// createProcessWithAttrs will create a new process with the given set of process attributes.
func (c *Creater) createProcessWithAttrs(process *model.Worksheet, attrs []*model.Attribute) (*mcapi.Process, error) {
	c.Count++
	c.AddCount("createProcessWithAttrs")
	//return &mcapi.Process{}, nil
	setup := mcapi.Setup{
		Name:      "Conditions",
		Attribute: "conditions",
	}

	for _, attr := range attrs {
		if attr.Value != nil {
			p := mcapi.SetupProperty{
				Name:      attr.Name,
				Attribute: attr.Name,
				OType:     "object",
				Unit:      attr.Unit,
				Value:     attr.Value["value"],
			}
			setup.Properties = append(setup.Properties, &p)
		}
	}

	// The second process.Name is the process type. For ETL we set the type to the process name which is the
	// same as the worksheet name. Since there are a limited number of worksheets the assumption is that all
	// processe created from a particular worksheet are equivalent.
	return c.client.CreateProcess(c.ProjectID, c.ExperimentID, process.Name, process.Name, []mcapi.Setup{setup})
}

// createSample creates a new sample in the project on the server.
func (c *Creater) createSample(sample *model.Sample) (*mcapi.Sample, error) {
	c.Count++
	c.AddCount("createSample")
	return c.client.CreateSample(c.ProjectID, c.ExperimentID, sample.Name, nil)
}

// addMeasurements adds measurements from the model.Sample to the server side process and sample/property set.
// In the workflow a model.Sample contains all the measurements for a sample reference in the spreadsheet.
func (c *Creater) addMeasurements(processID string, sampleID, propertySetID string, sample *model.Sample) error {
	c.Count++
	c.AddCount("addMeasurements")
	//return nil
	attrs := c.createAttributeMeasurements(sample.Attributes)

	sm := mcapi.SampleMeasurements{
		SampleID:      sampleID,
		PropertySetID: propertySetID,
		Attributes:    attrs,
	}

	_, err := c.client.AddMeasurementsToSampleInProcess(c.ProjectID, c.ExperimentID, processID, false, sm)
	return err
}

// createAttributeMeasurements iterates over the list of sample attributes creating a single
// SampleProperty for each attribute and merging the other attributes that match that name
// as separate measurements of that attribute.
func (c *Creater) createAttributeMeasurements(attrs []*model.Attribute) []mcapi.SampleProperty {
	samplePropertiesMap := make(map[string]*mcapi.SampleProperty)
	for _, attr := range attrs {
		sp, ok := samplePropertiesMap[attr.Name]
		if !ok {
			sp = &mcapi.SampleProperty{Name: attr.Name}
			samplePropertiesMap[attr.Name] = sp
		}

		m := mcapi.Measurement{
			Unit:  attr.Unit,
			Value: attr.Value["value"],
			OType: "object",
		}

		sp.Measurements = append(sp.Measurements, m)
	}

	var sampleProperties []mcapi.SampleProperty

	for key := range samplePropertiesMap {
		sampleProperties = append(sampleProperties, *samplePropertiesMap[key])
	}

	return sampleProperties
}

// findSample finds the model.Sample that corresponds to the server side sample. Matching is based
// on name as each sample in the worksheets will have a unique name.
func (c *Creater) findSampleInWorksheet(sampleName string, samples []*model.Sample) *model.Sample {
	for _, sample := range samples {
		if sample.Name == sampleName {
			return sample
		}
	}

	return nil
}

func (c *Creater) findSampleFromServer(sampleName string, samples []*mcapi.Sample) *mcapi.Sample {
	for _, sample := range samples {
		if sample.Name == sampleName {
			return sample
		}
	}

	return nil
}

// addSampleAndFilesToProcess will add the sample and associated files to the process on the server. It hides the details
// of constructing the go-mcapi call.
func (c *Creater) addSampleAndFilesToProcess(processID string, sample *mcapi.Sample, worksheetSample *model.Sample) (*mcapi.Sample, error) {
	c.Count++
	c.AddCount("addSampleAndFilesToProcess")
	//return &mcapi.Sample{}, nil
	connect := mcapi.ConnectSampleAndFilesToProcess{
		ProcessID:     processID,
		SampleID:      sample.ID,
		PropertySetID: sample.PropertySetID,
		Transform:     true,
	}

	if worksheetSample != nil {
		for _, file := range worksheetSample.Files {
			f := mcapi.FileAndDirection{
				Path:      file.Path,
				Direction: "in",
			}
			connect.FilesByName = append(connect.FilesByName, f)
		}
	}
	s, err := c.client.AddSampleAndFilesToProcess(c.ProjectID, c.ExperimentID, false, connect)
	return s, err
}

func (c *Creater) addSamplesToProcess(processID string, samples []*mcapi.Sample) ([]*mcapi.Sample, error) {
	c.Count++
	c.AddCount("addSamplesToProcess")
	connect := mcapi.ConnectSamplesToProcess{
		ProcessID: processID,
		Transform: true,
	}

	for _, sample := range samples {
		s := mcapi.SampleToConnect{
			SampleID:      sample.ID,
			PropertySetID: sample.PropertySetID,
			Name:          sample.Name,
		}
		connect.Samples = append(connect.Samples, s)
	}

	updatedSamples, err := c.client.AddSamplesToProcess(c.ProjectID, c.ExperimentID, connect)
	if err != nil {
		return nil, err
	}

	// API call returns []mcapi.Sample, we need to return []*mcapi.Sample
	var transformUpdatedSamples []*mcapi.Sample
	for _, sample := range updatedSamples {
		transformUpdatedSamples = append(transformUpdatedSamples, &sample)
	}

	return transformUpdatedSamples, nil
}

// getInputSamples goes to the parent workflow processes and constructs the list
// of samples that are input into the workflow process (in this case the wp
// parameter).
func (c *Creater) getInputSamples(wp *WorkflowProcess) []*mcapi.Sample {
	var samples []*mcapi.Sample
	// A WorkflowProcess contains a pointer to its parent workflow processes, this allows
	// it to retrieve all samples from the parent workflow process steps.
	for _, parentWorkflow := range wp.From {
		samples = append(samples, parentWorkflow.Out...)
	}
	return samples
}

repository: materials-commons/mcetl

repo_name: materials-commons/mcetl


text:
if(OPENMP)
  # Clang does not (yet) support OpenMP.
  if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
    # Retain the help string associated with the OPENMP option
    # when updating it to disable use of OPENMP.
    get_property(HELP_STRING CACHE OPENMP PROPERTY HELPSTRING)
    set(OPENMP OFF CACHE BOOL "${HELP_STRING}" FORCE)
    message("-- Compiler is Clang, disabling OpenMP.")
    add_definitions(-DCERES_NO_THREADS)
  ELSE (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
    # Find quietly s/t as we can continue without OpenMP if it is not found.
    find_package(OpenMP QUIET)
    if(OPENMP_FOUND)
      message("-- Building with OpenMP.")
      add_definitions(-DCERES_USE_OPENMP)
      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
      if(UNIX)
        # At least on Linux, we need pthreads to be enabled for mutex to
        # compile.  This may not work on Windows or Android.
        find_package(Threads REQUIRED)
        add_definitions(-DCERES_HAVE_PTHREAD)
        add_definitions(-DCERES_HAVE_RWLOCK)
      endif()
    else()
      message("-- Failed to find OpenMP, disabling.")
      # Retain the help string associated with the OPENMP option
      # when updating it to disable use of OPENMP.
      get_property(HELP_STRING CACHE OPENMP PROPERTY HELPSTRING)
      set(OPENMP OFF CACHE BOOL "${HELP_STRING}" FORCE)
      add_definitions(-DCERES_NO_THREADS)
    endif()
  endif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
else()
  message("-- Building without OpenMP (disabling multithreading).")
  add_definitions(-DCERES_NO_THREADS)
endif()


text:
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.

package cockroachutil

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"errors"
	"net/url"
	"strings"
	"sync"
	"time"

	"github.com/spacemonkeygo/monkit/v3"
	"github.com/zeebo/errs"

	"storj.io/common/context2"
	"storj.io/private/dbutil"
	"storj.io/private/dbutil/pgutil"
	"storj.io/private/tagsql"
)

var mon = monkit.Package()

// CreateRandomTestingSchemaName creates a random schema name string.
func CreateRandomTestingSchemaName(n int) string {
	data := make([]byte, n)
	_, _ = rand.Read(data)
	return hex.EncodeToString(data)
}

// OpenUnique opens a temporary unique CockroachDB database that will be cleaned up when closed.
// It is expected that this should normally be used by way of
// "storj.io/private/dbutil/tempdb".OpenUnique() instead of calling it directly.
func OpenUnique(ctx context.Context, connStr string, schemaPrefix string) (db *dbutil.TempDatabase, err error) {
	if !strings.HasPrefix(connStr, "cockroach://") {
		return nil, errs.New("expected a cockroachDB URI, but got %q", connStr)
	}

	schemaName := schemaPrefix + "-" + CreateRandomTestingSchemaName(8)

	masterDB, err := tagsql.Open(ctx, "cockroach", connStr)
	if err != nil {
		return nil, errs.Wrap(err)
	}
	defer func() {
		err = errs.Combine(err, masterDB.Close())
	}()

	err = masterDB.PingContext(ctx)
	if err != nil {
		return nil, errs.New("Could not open masterDB at conn %q: %w", connStr, err)
	}

	_, err = masterDB.Exec(ctx, "CREATE DATABASE "+pgutil.QuoteIdentifier(schemaName))
	if err != nil {
		return nil, errs.Wrap(err)
	}

	cleanup := func(cleanupDB tagsql.DB) error {
		ctx := context2.WithoutCancellation(ctx)

		// HACKFIX: Set upper time limit for dropping the database.
		// This stall causes flakiness during CI and it's not
		// clear what's the cause.
		//
		// It's better to ignore the DROP than to prevent tests
		// from failing and causing wasted time.
		err := asyncTimeout(ctx, 15*time.Second, func(ctx context.Context) error {
			_, err := cleanupDB.Exec(ctx, "DROP DATABASE "+pgutil.QuoteIdentifier(schemaName))
			return err
		})

		// ignore timeout error
		if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
			err = nil
		}

		return errs.Wrap(err)
	}

	modifiedConnStr, err := changeDBTargetInConnStr(connStr, schemaName)
	if err != nil {
		return nil, errs.Combine(err, cleanup(masterDB))
	}

	sqlDB, err := tagsql.Open(ctx, "cockroach", modifiedConnStr)
	if err != nil {
		return nil, errs.Combine(errs.Wrap(err), cleanup(masterDB))
	}

	dbutil.Configure(ctx, sqlDB, "tmp_cockroach", mon)
	return &dbutil.TempDatabase{
		DB:             sqlDB,
		ConnStr:        modifiedConnStr,
		Schema:         schemaName,
		Driver:         "cockroach",
		Implementation: dbutil.Cockroach,
		Cleanup:        cleanup,
	}, nil
}

func changeDBTargetInConnStr(connStr string, newDBName string) (string, error) {
	connURL, err := url.Parse(connStr)
	if err != nil {
		return "", errs.Wrap(err)
	}
	connURL.Path = newDBName
	return connURL.String(), nil
}

// asyncTimeout starts fn in a goroutine and returns when it doesn't finish in the specified timeout.
func asyncTimeout(parentCtx context.Context, timeout time.Duration, fn func(context.Context) error) error {
	ctx, cancel := context.WithTimeout(parentCtx, timeout)
	defer cancel()

	var mu sync.Mutex
	var result error
	var finished bool

	// fn is called inside a goroutine, in case the context
	// hasn't been handled properly.
	go func() {
		defer cancel()
		err := fn(ctx)

		mu.Lock()
		result = err
		finished = true
		mu.Unlock()
	}()

	<-ctx.Done()

	mu.Lock()
	r := result
	if !finished {
		r = ctx.Err()
	}
	mu.Unlock()

	return r
}

repository: storj/private

repo_name: storj/private


text:
macro( as_group_sources curdir lib folder )
	file( GLOB children ${curdir}/* )
	foreach( child ${children} )
		if( IS_DIRECTORY ${child} )
			as_group_sources( ${child} ${lib} ${folder} )
		else()
			string( REPLACE ${PROJECT_SOURCE_DIR}/${folder}/${lib}/src "/" res ${curdir} )
			string( REPLACE "/" "\\" groupname ${res} )
      source_group( src\\${groupname} FILES ${child} )
    endif()
  endforeach()
endmacro()

macro( as_group_public_headers curdir lib )
	file( GLOB children ${curdir}/* )
	foreach( child ${children} )
		if( IS_DIRECTORY ${child} )
			as_group_public_headers( ${child} ${lib} )
		else()
			string( REPLACE ${PROJECT_SOURCE_DIR}/include/astateful/${lib} "/" res ${curdir} )
			string( REPLACE "/" "\\" groupname ${res} )
      source_group( header\\${groupname} FILES ${child} )
    endif()
  endforeach()
endmacro()

macro( as_group_private_headers curdir lib folder)
	file( GLOB children ${curdir}/* )
	foreach( child ${children} )
		if( IS_DIRECTORY ${child} )
			as_group_private_headers( ${child} ${lib} ${folder} )
		else()
			string( REPLACE ${PROJECT_SOURCE_DIR}/${folder}/${lib}/include "/" res ${curdir} )
			string( REPLACE "/" "\\" groupname ${res} )
      source_group( header\\${groupname} FILES ${child} )
    endif()
  endforeach()
endmacro()

macro( as_group_autogen_sources curdir lib )
	file( GLOB children ${curdir}/* )
	foreach( child ${children} )
		if( IS_DIRECTORY ${child} )
			as_group_autogen_sources( ${child} ${lib} )
		else()
			string( REPLACE ${CMAKE_BINARY_DIR}/autogen/src/${lib} "/" res ${curdir} )
			string( REPLACE "/" "\\" groupname ${res} )
      source_group( src\\${groupname} FILES ${child} )
    endif()
  endforeach()
endmacro()

macro( as_group_autogen_headers curdir lib )
	file( GLOB children ${curdir}/* )
	foreach( child ${children} )
		if( IS_DIRECTORY ${child} )
			as_group_autogen_headers( ${child} ${lib} )
		else()
			string( REPLACE ${CMAKE_BINARY_DIR}/autogen/include/autogen/${lib} "/" res ${curdir} )
			string( REPLACE "/" "\\" groupname ${res} )
      source_group( header\\${groupname} FILES ${child} )
    endif()
  endforeach()
endmacro()

repository: astateful/dyplat

repo_name: astateful/dyplat


text:
SRC_URI = "ftp://ftp.gnu.org/gnu/aspell/dict/en/aspell5-en-${PV}.tar.bz2"

include aspell-lang.inc

repository: BackupTheBerlios/openslug-svn

repo_name: BackupTheBerlios/openslug-svn


text:
package main

import (
	"encoding/json"
	"io/ioutil"
)

type MTGCollection map[string]MTGSet

type MTGSet struct {
	Name     string    `json:"name"`
	Code     string    `json:"code"`
	Released string    `json:"releaseDate"`
	Border   string    `json:"border"`
	Type     string    `json:"type"`
	Cards    []MTGCard `json:"cards"`
}

type MTGCard struct {
	Artist        string      `json:"artist"`
	Border        string      `json:"border"`
	Colors        []string    `json:"colors"`
	ConvertedCost float64     `json:"cmc"`
	Flavor        string      `json:"flavor"`
	HandModifier  int         `json:"hand"`
	Layout        string      `json:"layout"`
	LifeModifier  int         `json:"life"`
	Loyalty       int         `json:"loyalty"`
	ManaCost      string      `json:"manaCost"`
	MultiverseId  int         `json:"multiverseid"`
	Name          string      `json:"name"`
	Names         []string    `json:"names"`
	Number        string      `json:"number"`
	Power         string      `json:"power"`
	Rarity        string      `json:"rarity"`
	Rulings       []MTGRuling `json:"rulings"`
	Subtypes      []string    `json:"subtypes"`
	Supertypes    []string    `json:"supertypes"`
	Text          string      `json:"text"`
	Toughness     string      `json:"toughness"`
	Type          string      `json:"type"`
	Types         []string    `json:"types"`
	Watermark     string      `json:"watermark"`
}

type MTGRuling struct {
	Date string `json:"date"`
	Text string `json:"text"`
}

type MTGFormat struct {
	Name       string   `json:"name"`
	Sets       []string `json:"sets"`
	Banned     []Card   `json:"banned"`
	Restricted []Card   `json:"restricted"`
}

func LoadFormat(path string) (MTGFormat, error) {
	blob, err := ioutil.ReadFile(path)

	if err != nil {
		return MTGFormat{}, err
	}

	var format MTGFormat
	err = json.Unmarshal(blob, &format)

	if err != nil {
		return MTGFormat{}, err
	}
	return format, nil
}

func LoadCollection(path string) (MTGCollection, error) {
	blob, err := ioutil.ReadFile(path)

	if err != nil {
		return MTGCollection{}, err
	}

	var collection MTGCollection
	err = json.Unmarshal(blob, &collection)

	if err != nil {
		return MTGCollection{}, err
	}
	return collection, nil
}

repository: solomonhawk/deckbrew-api

repo_name: solomonhawk/deckbrew-api