text:
package model

import (
	"time"

	"github.com/evergreen-ci/evergreen/model/pod"
	"github.com/evergreen-ci/utility"
	"github.com/pkg/errors"
)

// APIPodEnvVar is the model for environment variables in a container.
type APIPodEnvVar struct {
	Name   *string `json:"name"`
	Value  *string `json:"value"`
	Secret *bool   `json:"secret"`
}

// APICreatePod is the model to create a new pod.
type APICreatePod struct {
	Name           *string              `json:"name"`
	Memory         *int                 `json:"memory"`
	CPU            *int                 `json:"cpu"`
	Image          *string              `json:"image"`
	RepoUsername   *string              `json:"repo_username"`
	RepoPassword   *string              `json:"repo_password"`
	EnvVars        []*APIPodEnvVar      `json:"env_vars"`
	OS             APIPodOS             `json:"os"`
	Arch           APIPodArch           `json:"arch"`
	WindowsVersion APIPodWindowsVersion `json:"windows_version"`
	Secret         *string              `json:"secret"`
	WorkingDir     *string              `json:"working_dir"`
}

type APICreatePodResponse struct {
	ID string `json:"id"`
}

// ToService returns a service layer pod.Pod using the data from APIPod.
func (p *APICreatePod) ToService() (interface{}, error) {
	envVars, secrets := p.splitEnvVars()

	os, err := p.OS.ToService()
	if err != nil {
		return nil, err
	}
	arch, err := p.Arch.ToService()
	if err != nil {
		return nil, err
	}
	winVer, err := p.WindowsVersion.ToService()
	if err != nil {
		return nil, err
	}

	return pod.Pod{
		ID: utility.RandomString(),
		Secret: pod.Secret{
			Value:  utility.FromStringPtr(p.Secret),
			Exists: utility.FalsePtr(),
			Owned:  utility.TruePtr(),
		},
		Status: pod.StatusInitializing,
		TimeInfo: pod.TimeInfo{
			Initializing: time.Now(),
		},
		TaskContainerCreationOpts: pod.TaskContainerCreationOptions{
			Image:          utility.FromStringPtr(p.Image),
			RepoUsername:   utility.FromStringPtr(p.RepoUsername),
			RepoPassword:   utility.FromStringPtr(p.RepoPassword),
			MemoryMB:       utility.FromIntPtr(p.Memory),
			CPU:            utility.FromIntPtr(p.CPU),
			OS:             *os,
			Arch:           *arch,
			WindowsVersion: *winVer,
			EnvVars:        envVars,
			EnvSecrets:     secrets,
			WorkingDir:     utility.FromStringPtr(p.WorkingDir),
		},
	}, nil
}

// splitEnvVars splits its environment variables into its non-secret and secret
// environment variables.
func (p *APICreatePod) splitEnvVars() (envVars map[string]string, secrets map[string]pod.Secret) {
	envVars = make(map[string]string)
	secrets = make(map[string]pod.Secret)

	for _, envVar := range p.EnvVars {
		if utility.FromBoolPtr(envVar.Secret) {
			secrets[utility.FromStringPtr(envVar.Name)] = pod.Secret{
				Name:   utility.FromStringPtr(envVar.Name),
				Value:  utility.FromStringPtr(envVar.Value),
				Exists: utility.FalsePtr(),
				Owned:  utility.TruePtr(),
			}
		} else {
			envVars[utility.FromStringPtr(envVar.Name)] = utility.FromStringPtr(envVar.Value)
		}
	}

	return envVars, secrets
}

// APIPod represents a pod to be used and returned from the REST API.
type APIPod struct {
	ID                        *string                            `json:"id"`
	Status                    APIPodStatus                       `json:"status"`
	Secret                    APIPodSecret                       `json:"secret"`
	TaskContainerCreationOpts APIPodTaskContainerCreationOptions `json:"task_container_creation_opts"`
	TimeInfo                  APIPodTimeInfo                     `json:"time_info"`
	Resources                 APIPodResourceInfo                 `json:"resources"`
}

// BuildFromService converts a service-layer pod model into a REST API model.
func (p *APIPod) BuildFromService(dbPod *pod.Pod) error {
	p.ID = utility.ToStringPtr(dbPod.ID)
	var status APIPodStatus
	if err := status.BuildFromService(dbPod.Status); err != nil {
		return errors.Wrap(err, "building status from service")
	}
	p.Status = status
	p.Secret.BuildFromService(dbPod.Secret)
	p.TimeInfo.BuildFromService(dbPod.TimeInfo)
	p.TaskContainerCreationOpts.BuildFromService(dbPod.TaskContainerCreationOpts)
	p.Resources.BuildFromService(dbPod.Resources)
	return nil
}

// ToService converts a REST API pod model into a service-layer model.
func (p *APIPod) ToService() (*pod.Pod, error) {
	s, err := p.Status.ToService()
	if err != nil {
		return nil, errors.Wrap(err, "converting status to service")
	}
	taskCreationOpts, err := p.TaskContainerCreationOpts.ToService()
	if err != nil {
		return nil, errors.Wrap(err, "converting task container creation options to service")
	}
	secret := p.Secret.ToService()
	timing := p.TimeInfo.ToService()
	resources := p.Resources.ToService()
	return &pod.Pod{
		ID:                        utility.FromStringPtr(p.ID),
		Status:                    *s,
		Secret:                    secret,
		TaskContainerCreationOpts: *taskCreationOpts,
		TimeInfo:                  timing,
		Resources:                 resources,
	}, nil
}

// APIPodStatus represents a pod's status.
type APIPodStatus string

const (
	PodStatusInitializing   APIPodStatus = "initializing"
	PodStatusStarting       APIPodStatus = "starting"
	PodStatusRunning        APIPodStatus = "running"
	PodStatusDecommissioned APIPodStatus = "decommissioned"
	PodStatusTerminated     APIPodStatus = "terminated"
)

// BuildFromService converts a service-layer pod status into a REST API pod
// status.
func (s *APIPodStatus) BuildFromService(ps pod.Status) error {
	var converted APIPodStatus
	switch ps {
	case pod.StatusInitializing:
		converted = PodStatusInitializing
	case pod.StatusStarting:
		converted = PodStatusStarting
	case pod.StatusRunning:
		converted = PodStatusRunning
	case pod.StatusDecommissioned:
		converted = PodStatusDecommissioned
	case pod.StatusTerminated:
		converted = PodStatusTerminated
	default:
		return errors.Errorf("unrecognized pod status '%s'", ps)
	}
	*s = converted
	return nil
}

// ToService converts a REST API pod status into a service-layer pod status.
func (s *APIPodStatus) ToService() (*pod.Status, error) {
	if s == nil {
		return nil, errors.New("nonexistent pod status")
	}
	var converted pod.Status
	switch *s {
	case PodStatusInitializing:
		converted = pod.StatusInitializing
	case PodStatusStarting:
		converted = pod.StatusStarting
	case PodStatusRunning:
		converted = pod.StatusRunning
	case PodStatusDecommissioned:
		converted = pod.StatusDecommissioned
	case PodStatusTerminated:
		converted = pod.StatusTerminated
	default:
		return nil, errors.Errorf("unrecognized pod status '%s'", *s)
	}
	return &converted, nil
}

// APIPodTaskContainerCreationOptions represents options to apply to the task's
// container when creating a pod.
type APIPodTaskContainerCreationOptions struct {
	Image          *string                 `json:"image,omitempty"`
	RepoUsername   *string                 `json:"repo_username,omitempty"`
	RepoPassword   *string                 `json:"repo_password,omitempty"`
	MemoryMB       *int                    `json:"memory_mb,omitempty"`
	CPU            *int                    `json:"cpu,omitempty"`
	OS             APIPodOS                `json:"os,omitempty"`
	Arch           APIPodArch              `json:"arch,omitempty"`
	WindowsVersion APIPodWindowsVersion    `json:"windows_version,omitempty"`
	EnvVars        map[string]string       `json:"env_vars,omitempty"`
	EnvSecrets     map[string]APIPodSecret `json:"env_secrets,omitempty"`
	WorkingDir     *string                 `json:"working_dir,omitempty"`
}

// BuildFromService converts service-layer task container creation options into
// REST API task container creation options.
func (o *APIPodTaskContainerCreationOptions) BuildFromService(opts pod.TaskContainerCreationOptions) {
	o.Image = utility.ToStringPtr(opts.Image)
	o.RepoUsername = utility.ToStringPtr(opts.RepoUsername)
	o.RepoPassword = utility.ToStringPtr(opts.RepoPassword)
	o.MemoryMB = utility.ToIntPtr(opts.MemoryMB)
	o.CPU = utility.ToIntPtr(opts.CPU)
	o.OS.BuildFromService(&opts.OS)
	o.Arch.BuildFromService(&opts.Arch)
	o.WindowsVersion.BuildFromService(&opts.WindowsVersion)
	o.EnvVars = opts.EnvVars
	envSecrets := map[string]APIPodSecret{}
	for name, secret := range opts.EnvSecrets {
		var s APIPodSecret
		s.BuildFromService(secret)
		envSecrets[name] = s
	}
	o.EnvSecrets = envSecrets
	o.WorkingDir = utility.ToStringPtr(opts.WorkingDir)
}

// ToService converts REST API task container creation options into
// service-layer task container creation options.
func (o *APIPodTaskContainerCreationOptions) ToService() (*pod.TaskContainerCreationOptions, error) {
	os, err := o.OS.ToService()
	if err != nil {
		return nil, err
	}
	arch, err := o.Arch.ToService()
	if err != nil {
		return nil, err
	}
	winVer, err := o.WindowsVersion.ToService()
	if err != nil {
		return nil, err
	}
	envSecrets := map[string]pod.Secret{}
	for name, secret := range o.EnvSecrets {
		envSecrets[name] = secret.ToService()
	}
	return &pod.TaskContainerCreationOptions{
		Image:          utility.FromStringPtr(o.Image),
		RepoUsername:   utility.FromStringPtr(o.RepoUsername),
		RepoPassword:   utility.FromStringPtr(o.RepoPassword),
		MemoryMB:       utility.FromIntPtr(o.MemoryMB),
		CPU:            utility.FromIntPtr(o.CPU),
		OS:             *os,
		Arch:           *arch,
		WindowsVersion: *winVer,
		EnvVars:        o.EnvVars,
		EnvSecrets:     envSecrets,
		WorkingDir:     utility.FromStringPtr(o.WorkingDir),
	}, nil
}

type APIPodOS string

func (os *APIPodOS) BuildFromService(dbOS *pod.OS) {
	if os == nil || dbOS == nil {
		return
	}
	*os = APIPodOS(string(*dbOS))
}

func (os *APIPodOS) ToService() (*pod.OS, error) {
	if os == nil {
		return nil, nil
	}
	dbOS := pod.OS(*os)
	if err := dbOS.Validate(); err != nil {
		return nil, errors.Wrap(err, "invalid OS")
	}
	return &dbOS, nil
}

type APIPodArch string

func (a *APIPodArch) BuildFromService(dbArch *pod.Arch) {
	if a == nil || dbArch == nil {
		return
	}
	*a = APIPodArch(*dbArch)
}

func (a *APIPodArch) ToService() (*pod.Arch, error) {
	if a == nil {
		return nil, nil
	}
	dbArch := pod.Arch(*a)
	if err := dbArch.Validate(); err != nil {
		return nil, errors.Wrap(err, "invalid architecture")
	}
	return &dbArch, nil
}

type APIPodWindowsVersion string

func (v *APIPodWindowsVersion) BuildFromService(dbWinVer *pod.WindowsVersion) {
	if v == nil || dbWinVer == nil {
		return
	}
	*v = APIPodWindowsVersion(*dbWinVer)
}

func (v *APIPodWindowsVersion) ToService() (*pod.WindowsVersion, error) {
	if v == nil {
		return nil, nil
	}
	dbWinVer := pod.WindowsVersion(*v)
	// Empty Windows version is allowed since it's optional.
	if dbWinVer == "" {
		return &dbWinVer, nil
	}
	if err := dbWinVer.Validate(); err != nil {
		return nil, errors.Wrap(err, "invalid Windows version")
	}
	return &dbWinVer, nil
}

// APIPodResourceInfo represents timing information about the pod lifecycle.
type APIPodTimeInfo struct {
	Initializing     *time.Time `json:"initializing,omitempty"`
	Starting         *time.Time `json:"starting,omitempty"`
	LastCommunicated *time.Time `json:"last_communicated,omitempty"`
}

// BuildFromService converts service-layer resource information into REST API
// timing information.
func (i *APIPodTimeInfo) BuildFromService(info pod.TimeInfo) {
	i.Initializing = utility.ToTimePtr(info.Initializing)
	i.Starting = utility.ToTimePtr(info.Starting)
	i.LastCommunicated = utility.ToTimePtr(info.LastCommunicated)
}

// BuildFromService converts service-layer resource information into REST API
// timing information.
func (i *APIPodTimeInfo) ToService() pod.TimeInfo {
	return pod.TimeInfo{
		Initializing:     utility.FromTimePtr(i.Initializing),
		Starting:         utility.FromTimePtr(i.Starting),
		LastCommunicated: utility.FromTimePtr(i.LastCommunicated),
	}
}

// APIPodResourceInfo represents information about external resources associated
// with a pod.
type APIPodResourceInfo struct {
	ExternalID   *string                    `json:"external_id,omitempty"`
	DefinitionID *string                    `json:"definition_id,omitempty"`
	Cluster      *string                    `json:"cluster,omitempty"`
	Containers   []APIContainerResourceInfo `json:"containers,omitempty"`
}

// BuildFromService converts service-layer pod resource information into REST
// API pod resource information.
func (i *APIPodResourceInfo) BuildFromService(info pod.ResourceInfo) {
	i.ExternalID = utility.ToStringPtr(info.ExternalID)
	i.DefinitionID = utility.ToStringPtr(info.DefinitionID)
	i.Cluster = utility.ToStringPtr(info.Cluster)
	for _, container := range info.Containers {
		var containerInfo APIContainerResourceInfo
		containerInfo.BuildFromService(container)
		i.Containers = append(i.Containers, containerInfo)
	}
}

// ToService converts REST API pod resource information into service-layer
// pod resource information.
func (i *APIPodResourceInfo) ToService() pod.ResourceInfo {
	var containers []pod.ContainerResourceInfo
	for _, container := range i.Containers {
		containers = append(containers, container.ToService())
	}
	return pod.ResourceInfo{
		ExternalID:   utility.FromStringPtr(i.ExternalID),
		DefinitionID: utility.FromStringPtr(i.DefinitionID),
		Cluster:      utility.FromStringPtr(i.Cluster),
		Containers:   containers,
	}
}

// APIPodResourceInfo represents information about external resources associated
// with a container.
type APIContainerResourceInfo struct {
	ExternalID *string  `json:"external_id,omitempty"`
	Name       *string  `json:"name,omitempty"`
	SecretIDs  []string `json:"secret_ids,omitempty"`
}

// BuildFromService converts service-layer container resource information into
// REST API container resource information.
func (i *APIContainerResourceInfo) BuildFromService(info pod.ContainerResourceInfo) {
	i.ExternalID = utility.ToStringPtr(info.ExternalID)
	i.Name = utility.ToStringPtr(info.Name)
	i.SecretIDs = info.SecretIDs
}

// ToService converts REST API container resource information into service-layer
// container resource information.
func (i *APIContainerResourceInfo) ToService() pod.ContainerResourceInfo {
	return pod.ContainerResourceInfo{
		ExternalID: utility.FromStringPtr(i.ExternalID),
		Name:       utility.FromStringPtr(i.Name),
		SecretIDs:  i.SecretIDs,
	}
}

// APIPodSecret represents a secret associated with a pod returned from the REST
// API.
type APIPodSecret struct {
	Name       *string `json:"name,omitempty"`
	ExternalID *string `json:"external_id,omitempty"`
	Value      *string `json:"value,omitempty"`
	Exists     *bool   `json:"exists,omitempty"`
	Owned      *bool   `json:"owned,omitempty"`
}

// BuildFromService converts a service-layer pod secret into a REST API pod
// secret.
func (s *APIPodSecret) BuildFromService(secret pod.Secret) {
	s.Name = utility.ToStringPtr(secret.Name)
	s.ExternalID = utility.ToStringPtr(secret.ExternalID)
	s.Value = utility.ToStringPtr(secret.Value)
	s.Exists = secret.Exists
	s.Owned = secret.Owned
}

// ToService converts a REST API pod secret into a service-layer pod secret.
func (s *APIPodSecret) ToService() pod.Secret {
	return pod.Secret{
		Name:       utility.FromStringPtr(s.Name),
		ExternalID: utility.FromStringPtr(s.ExternalID),
		Value:      utility.FromStringPtr(s.Value),
		Exists:     s.Exists,
		Owned:      s.Owned,
	}
}

repository: JacobJohansen/evergreen

license_type: permissive

repo_name: JacobJohansen/evergreen

branch_name: refs/heads/main

extension: go


text:
@inproceedings{DBLP:conf/popl/JoshiLL12,
  author    = {Saurabh Joshi and
               Shuvendu K. Lahiri and
               Akash Lal},
  editor    = {John Field and
               Michael Hicks},
  title     = {Underspecified harnesses and interleaved bugs},
  booktitle = {Proceedings of the 39th {ACM} {SIGPLAN-SIGACT} Symposium on Principles
               of Programming Languages, {POPL} 2012, Philadelphia, Pennsylvania,
               USA, January 22-28, 2012},
  pages     = {19--30},
  publisher = {{ACM}},
  year      = {2012},
  url       = {https://doi.org/10.1145/2103656.2103662},
  doi       = {10.1145/2103656.2103662},
  timestamp = {Tue, 06 Nov 2018 11:07:43 +0100},
  biburl    = {https://dblp.org/rec/conf/popl/JoshiLL12.bib},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}

license: MIT

branch_name: refs/heads/master

extension: bib


text:
@article{blanco_se3_tutorial,
  title={A tutorial on se (3) transformation parameterizations and on-manifold optimization},
  author={Blanco, Jose-Luis},
  journal={University of Malaga, Tech. Rep},
  year={2010},
  url={http://ingmec.ual.es/~jlblanco/papers/jlblanco2010geometry3D_techrep.pdf}
}

@inproceedings{besl1992method,
  title={Method for registration of 3-D shapes},
  author={Besl, Paul J and McKay, Neil D},
  booktitle={Sensor fusion IV: control paradigms and data structures},
  volume={1611},
  pages={586--606},
  year={1992},
  organization={International Society for Optics and Photonics}
}

@inproceedings{censi2008icp,
  title={An ICP variant using a point-to-line metric},
  author={Censi, Andrea},
  booktitle={2008 IEEE International Conference on Robotics and Automation},
  pages={19--25},
  year={2008},
  organization={Ieee}
}

@inproceedings{segal2009generalized,
  title={Generalized-icp.},
  author={Segal, Aleksandr and Haehnel, Dirk and Thrun, Sebastian},
  booktitle={Robotics: science and systems},
  volume={2},
  number={4},
  pages={435},
  year={2009},
  organization={Seattle, WA}
}

@article{madsen2004methods,
  title={Methods for non-linear least squares problems},
  author={Madsen, Kaj and Nielsen, Hans Bruun and Tingleff, Ole},
  year={2004}
}

@inproceedings{kneip2014upnp,
  title={Upnp: An optimal o (n) solution to the absolute pose problem with universal applicability},
  author={Kneip, Laurent and Li, Hongdong and Seo, Yongduek},
  booktitle={European Conference on Computer Vision},
  pages={127--142},
  year={2014},
  organization={Springer}
}

@inproceedings{moreno2007accurate,
  title={Accurate Non-Iterative O(n) Solution to the PnP Problem},
  author={Moreno-Noguer, Francesc and Lepetit, Vincent and Fua, Pascal},
  booktitle={2007 IEEE 11th International Conference on Computer Vision},
  pages={1--8},
  year={2007},
  organization={IEEE}
}

@inproceedings{hesch2011direct,
  title={A direct least-squares (DLS) method for PnP},
  author={Hesch, Joel A and Roumeliotis, Stergios I},
  booktitle={2011 International Conference on Computer Vision},
  pages={383--390},
  year={2011},
  organization={IEEE}
}

@inproceedings{garro2012solving,
  title={Solving the pnp problem with anisotropic orthogonal procrustes analysis},
  author={Garro, Valeria and Crosilla, Fabio and Fusiello, Andrea},
  booktitle={2012 Second International Conference on 3D Imaging, Modeling, Processing, Visualization \& Transmission},
  pages={262--269},
  year={2012},
  organization={IEEE}
}

@ARTICLE{blanco2012amd,
    author = {Blanco, Jos{\'{e}}-Luis and Gonz{\'{a}}lez-Jim{\'{e}}nez, Javier and Fern{\'{a}}ndez-Madrigal, Juan-Antonio},
     month = {{{{{{aug}}}}}},
     title = {An alternative to the Mahalanobis distance for determining optimal correspondences in data association},
   journal = {IEEE Transactions on Robotics (T-RO)},
    volume = {28},
    number = {4},
      year = {2012},
       doi = {10.1109/TRO.2012.2193706}
}

@article{blanco2013robust,
  title={A robust, multi-hypothesis approach to matching occupancy grid maps},
  author={Blanco, Jose-Luis and Gonz{\'a}lez-Jim{\'e}nez, Javier and Fern{\'a}ndez-Madrigal, Juan-Antonio},
  journal={Robotica},
  volume={31},
  number={5},
  pages={687--701},
  year={2013},
  publisher={Cambridge University Press}
}

@article{neira2001data,
  title={Data association in stochastic mapping using the joint compatibility test},
  author={Neira, Jos{\'e} and Tard{\'o}s, Juan D},
  journal={IEEE Transactions on robotics and automation},
  volume={17},
  number={6},
  pages={890--897},
  year={2001},
  publisher={IEEE}
}

@article{blanco2008ekf,
  title={Derivation and implementation of a full 6d ekf-based solution to bearing-range slam},
  author={Blanco, Jose-Luis},
  journal={University of Malaga, Spain, Technical Report},
  url={https://ingmec.ual.es/~jlblanco/papers/RangeBearingSLAM6D.pdf},
  year={2008}
}

@article{fischler1981random,
  title={Random sample consensus: a paradigm for model fitting with applications to image analysis and automated cartography},
  author={Fischler, Martin A and Bolles, Robert C},
  journal={Communications of the ACM},
  volume={24},
  number={6},
  pages={381--395},
  year={1981},
  publisher={ACM New York, NY, USA}
}

@inproceedings{eliazar2004learning,
  title={Learning probabilistic motion models for mobile robots},
  author={Eliazar, Austin I and Parr, Ronald},
  booktitle={Proceedings of the twenty-first international conference on Machine learning},
  pages={32},
  year={2004}
}

@techreport{arras1998introduction,
  title={An introduction to error propagation: derivation, meaning and examples of equation CY= FX CX FXT},
  author={Arras, Kai O},
  year={1998},
  institution={ETH Zurich}
}

@book{thrun2005probabilistic,
  title={Probabilistic Robotics},
  author={Thrun, Sebastian and Burgard, Wolfram and Fox, Dieter},
  year={2005},
  publisher={MIT Press}
}

@inproceedings{ballardini2012effective,
  title={An effective 6DoF motion model for 3D-6DoF Monte Carlo Localization},
  author={Ballardini, Augusto L and F{\'u}rlan, A and Galbiati, A and Matteucci, Matteo and Sacchi, F and Sorrenti, Domenico G},
  booktitle={4th Workshop on Planning, Perception and Navigation for Intelligent Vehicles,(IROS)},
  pages={121--126},
  year={2012}
}

@article{horn1987closed,
  title={Closed-form solution of absolute orientation using unit quaternions},
  author={Horn, Berthold K.P.},
  journal={Journal of the Optical Society of America},
  volume={4},
  number={4},
  pages={629--642},
  year={1987},
  publisher={Optica Publishing Group}
}

repository: MRPT/mrpt

repo_name: MRPT/mrpt

branch_name: refs/heads/develop


text:
@article{pearce_data_2011,
	title = {Data sharing: not as simple as it seems},
	volume = {10},
	issn = {1476-069X},
	url = {http://www.ehjournal.net/content/10/1/107/abstract},
	doi = {10.1186/1476-069X-10-107},
	shorttitle = {Data sharing},
	abstract = {{ABSTRACT}: "In recent years there has been a major change on the part of funders, particularly in North America, so that data sharing is now considered to be the norm rather than the exception. We believe that data sharing is a good idea. However, we also believe that it is inappropriate to prescribe exactly when or how researchers should preserve and share data, since these issues are highly specific to each study, the nature of the data collected, who is requesting it, and what they intend to do with it. The level of ethical concern will vary according to the nature of the information, and the way in which it is collected - analyses of anonymised hospital admission records may carry a quite different ethical burden than analyses of potentially identifiable health information collected directly from the study participants. It is striking that most discussions about data sharing focus almost exclusively on issues of ownership (by the researchers or the funders) and efficiency (on the part of the funders). There is usually little discussion of the ethical issues involved in data sharing, and its implications for the study participants. Obtaining prior informed consent from the participants does not solve this problem, unless the informed consent process makes it completely clear what is being proposed, in which case most study participants would not agree. Thus, the undoubted benefits of data sharing doe not remove the obligations and responsibilities that the original investigators hold for the people they invited to participate in the study."},
	pages = {107},
	number = {1},
	journaltitle = {Environmental Health: A Global Access Science Source},
	author = {Pearce, Neil and Smith, Allan H},
	urldate = {2011-12-26},
	date = {2011-12-21},
	pmid = {22188646}
}

repository: pmean/build-website

repo_name: pmean/build-website


text:
@inproceedings{guan2016irps,
 author = {Bochen Guan and Jing Li},
 booktitle = {2016 IEEE International Reliability Physics Symposium (IRPS)},
 date = {2016-04},
 doi = {10.1109/IRPS.2016.7574621},
 issn = {},
 keywords = {conference, Monte Carlo methods,current fluctuations,electromagnetic interference,integrated circuit design,integrated circuit reliability,random noise,resistive RAM,telegraphy,Monte Carlo method,RRAM circuit reliability,RRAM compact model,RTN effect,current fluctuation,random telegraph noise,tunneling gap,Current measurement,Data models,Electron traps,Fluctuations,Integrated circuit modeling,Mathematical model,Switches,Compact model,RRAM,Random Telegraph Noise},
 month = {April},
 number = {},
 pages = {MY-5-1--MY-5-4},
 title = {A compact model for {RRAM} including random telegraph noise},
 volume = {},
 year = {2016}
}


text:
SUMMARY = "IPTables based firewall scripts"
HOMEPAGE = "http://rocky.eld.leidenuniv.nl/joomla/index.php?option=com_content&view=article&id=45&Itemid=63"

LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://gpl_license.txt;md5=11c7b65c4a4acb9d5175f7e9bf99c403"

SRCREV = "a96b81da4a9b619e4045805f5f13a1e982c95663"
SRC_URI = "git://github.com/arno-iptables-firewall/aif;branch=master;protocol=https"

S = "${WORKDIR}/git"

inherit systemd

do_install() {
	install -d ${D}${sysconfdir} ${D}${sbindir} ${D}${bindir} ${D}${systemd_unitdir}/system ${D}${sysconfdir}/init.d
	install -d ${D}${datadir}/arno-iptables-firewall ${D}${sysconfdir}/arno-iptables-firewall
	cp -r ${S}${sysconfdir}/arno-iptables-firewall ${D}${sysconfdir}/
	install -m 0755 ${S}${sysconfdir}/init.d/arno-iptables-firewall ${D}${bindir}
	install -m 0755 ${S}/bin/arno-iptables-firewall ${D}${sbindir}
	install -m 0755 ${S}/bin/arno-fwfilter ${D}${bindir}
	cp -r ${S}/share/arno-iptables-firewall/* ${D}${datadir}/arno-iptables-firewall
	cp -r ${S}/etc/arno-iptables-firewall/* ${D}${sysconfdir}/arno-iptables-firewall
	install -m 0644 ${S}/lib/systemd/system/arno-iptables-firewall.service ${D}${systemd_unitdir}/system
	sed -i -e 's%/usr/local/sbin%${bindir}%g' ${D}${systemd_unitdir}/system/arno-iptables-firewall.service
	sed -i -e 's%/usr/local/sbin%${sbindir}%g' ${D}${bindir}/arno-iptables-firewall
	sed -i -e 's%/usr/local%${exec_prefix}%g' ${D}${sysconfdir}/arno-iptables-firewall/firewall.conf
	sed -i -e 's%#!/bin/bash%#!/bin/sh%g' ${D}${bindir}/arno-fwfilter
	sed -i -e 's%#!/bin/bash%#!/bin/sh%g' ${D}${datadir}/arno-iptables-firewall/plugins/traffic-accounting-helper
	sed -i -e 's%#!/bin/bash%#!/bin/sh%g' ${D}${datadir}/arno-iptables-firewall/plugins/dyndns-host-open-helper
}

SYSTEMD_SERVICE:${PN} = "arno-iptables-firewall.service"
FILES:${PN} += "${systemd_unitdir}/system/arno-iptables-firewall.service"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_license_id: MIT

gha_language: BitBake

extension: bb


text:
package sdm630

import (
	"fmt"
	"log"
	"sort"
	"time"
)

type MeasurementCache struct {
	datastream     QuerySnipChannel
	meters         map[uint8]*Meter
	secondsToStore time.Duration
	verbose        bool
}

func NewMeasurementCache(meters map[uint8]*Meter, ds QuerySnipChannel, secondsToStore time.Duration, isVerbose bool) *MeasurementCache {
	return &MeasurementCache{
		datastream:     ds,
		meters:         meters,
		secondsToStore: secondsToStore,
		verbose:        isVerbose,
	}
}

func (mc *MeasurementCache) Consume() {
	for {
		snip := <-mc.datastream
		devid := snip.DeviceId
		// Search corresponding meter
		if meter, ok := mc.meters[devid]; ok {
			// add the snip to the meter's cache
			meter.AddSnip(snip)
			if mc.verbose {
				log.Printf("%s\r\n", meter.MeterReadings.Lastreading.String())
			}
		} else {
			log.Fatal("Snip for unknown meter received - this should not happen.")
		}
	}
}

func (mc *MeasurementCache) GetSortedIDs() []byte {
	var keys ByteSlice
	for k, _ := range mc.meters {
		keys = append(keys, k)
	}
	sort.Sort(keys)
	return keys
}

func (mc *MeasurementCache) GetLast(id byte) (*Readings, error) {
	if meter, ok := mc.meters[id]; ok {
		if meter.GetState() == METERSTATE_AVAILABLE {
			return &meter.MeterReadings.Lastreading, nil
		} else {
			return nil, fmt.Errorf("Meter %d is not available.", id)
		}
	} else {
		return nil, fmt.Errorf("No device with id %d available.", id)
	}
}

func (mc *MeasurementCache) GetMinuteAvg(id byte) (*Readings, error) {
	if meter, ok := mc.meters[id]; !ok {
		return nil, fmt.Errorf("No device with id %d available.", id)
	} else {
		if meter.GetState() == METERSTATE_AVAILABLE {
			measurements := meter.MeterReadings.Lastminutereadings
			lastminute := measurements.NotOlderThan(time.Now().Add(-1 *
				time.Minute))
			var err error
			var avg Readings
			for idx, r := range lastminute {
				if idx == 0 {
					// This is the first element - initialize our accumulator
					avg = r
				} else {
					avg, err = r.add(&avg)
					if err != nil {
						return nil, err
					}
				}
			}
			retval := avg.divide(float64(len(lastminute)))
			if mc.verbose {
				log.Printf("Averaging over %d measurements:\r\n%s\r\n",
					len(measurements), retval.String())
			}
			return &retval, nil
		} else { // !METERSTATE_AVAILABLE
			return nil, fmt.Errorf("Meter %d is not available.", id)
		}
	}
}

// Helper for dealing with Modbus device ids (bytes).
// ByteSlice attaches the methods of sort.Interface to []byte, sorting in increasing order.
type ByteSlice []byte

func (s ByteSlice) Len() int           { return len(s) }
func (s ByteSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s ByteSlice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }


text:
SUMMARY = "Statistics collector application"

LICENSE = "TI-TSPA"
LIC_FILES_CHKSUM = "file://LICENSE;md5=bb6bc27cd44417c389a180bd62f552a0"

PV = "1.0.4+git${SRCPV}"
PROTOCOL = "https"
BRANCH = "master"
SRCREV = "279bf455bc3dec69f374d46a8225687935f4323a"
SRC_URI = "git://git.ti.com/git/glsdk/statcol.git;protocol=${PROTOCOL};branch=${BRANCH}"

DEPENDS = "ti-rpmsg-char websocketd"
RDEPENDS:${PN} = "bash"

S = "${WORKDIR}/git"

EXTRA_OEMAKE += "SYSROOT=${STAGING_DIR_TARGET} CROSS_COMPILE=${TARGET_PREFIX}"

do_install() {
	DESTDIR=${D} make install
}

INSANE_SKIP:${PN} = "ldflags"

repository: rcn-ee/meta-arago

repo_name: rcn-ee/meta-arago


text:
SUMMARY = "PNG module for Python."
SECTION = "devel/python"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://LICENCE;md5=5b60f319c8cf51f825b4f40aadee3243"

SRC_URI[sha256sum] = "739c433ba96f078315de54c0db975aee537cbc3e1d0ae4ed9aab0ca1e427e2c1"

inherit pypi python_setuptools_build_meta


text:
if(NOT CONFIG_STANDALONE)
	SET(CONFIG_STACK_SIZE 2048 CACHE STRING "RTOS stack size.")
	SET(CONFIG_TASK_PRIO  8 CACHE STRING "Task priority.")
endif()

SET(HAVE_DEBUG False CACHE BOOL "Enable debug output.")
SET(CONFIG_BUILD_TESTS False CACHE BOOL "Build unit tests.")
SET(CONFIG_PIN_VECTOR False CACHE BOOL "Build a vector of pins the the GPIO chip.")

SET(CONFIG_SSD1306_128_64 True CACHE BOOL "SSD1306 in 128x64 mode")
SET(CONFIG_SSD1306_128_32 False CACHE BOOL "SSD1306 in 128x32 mode")
SET(CONFIG_SSD1306_96_16 False CACHE BOOL "SSD1306 in 96x16 mode")

repository: lwIoT/lwiot-core

repo_name: lwIoT/lwiot-core

extension: cmake


text:
/*
 * Copyright 2020 Mooltiverse
 *
 * 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 tools

import (
	"bytes"         // https://pkg.go.dev/bytes
	"io"            // https://pkg.go.dev/io
	"os"            // https://pkg.go.dev/os
	"path/filepath" // https://pkg.go.dev/path/filepath
	"strings"       // https://pkg.go.dev/strings

	ggit "github.com/go-git/go-git/v5"                             // https://pkg.go.dev/github.com/go-git/go-git/v5
	ggitconfig "github.com/go-git/go-git/v5/config"                // https://pkg.go.dev/github.com/go-git/go-git/v5
	ggitplumbing "github.com/go-git/go-git/v5/plumbing"            // https://pkg.go.dev/github.com/go-git/go-git/v5
	ggitobject "github.com/go-git/go-git/v5/plumbing/object"       // https://pkg.go.dev/github.com/go-git/go-git/v5
	ggittransport "github.com/go-git/go-git/v5/plumbing/transport" // https://pkg.go.dev/github.com/go-git/go-git/v5
	ggithttp "github.com/go-git/go-git/v5/plumbing/transport/http" // https://pkg.go.dev/github.com/go-git/go-git/v5
	ggitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"   // https://pkg.go.dev/github.com/go-git/go-git/v5
	ssh "golang.org/x/crypto/ssh"                                  // https://pkg.go.dev/golang.org/x/crypto/ssh

	gitutil "github.com/mooltiverse/nyx/modules/go/nyx/test/integration/git/util"
)

/*
A Git repository utility class used to test. This class is used to dynamically create a repository that can be used for tests
and exposes some high level methods and attributes.
*/
type Workbench struct {
	// The directory of backing Git repository. We need to store this as the Git implementation doesn't expose methods to retrieve it
	Directory string

	// The backing Git repository.
	Repository ggit.Repository
}

/*
Configures the given repository

Arguments are as follows:

  - repo the repository to configure
*/
func configureRepository(repo ggit.Repository) ggit.Repository {
	// set the repository configuration
	cfg, err := repo.Config()
	if err != nil {
		panic(err)
	}
	// the following user configuration has been added to avoid errors like "author field is required" during tests
	// in case this causes any issues it can be changed to anything or parametrized but for now this works
	cfg.User.Name = "John Doe"
	cfg.User.Email = "johndoe@example.com"
	err = repo.SetConfig(cfg)
	if err != nil {
		panic(err)
	}

	return repo
}

/*
Creates a Git repository instance.

Arguments are as follows:

  - directory the directory to create the repository in
  - bare if true the repository is initialized as a bare repository, otherwise it will have a work tree.
    If initialize is false this parameter is ignored.
  - initialize if true the repository has to be initialized, otherwise false.
*/
func newRepositoryWithInitializationAndSettings(directory string, bare bool, initialize bool) ggit.Repository {
	if initialize {
		repo, err := ggit.PlainInit(directory, bare)
		if err != nil {
			panic(err)
		}
		// set the repository configuration
		configureRepository(*repo)

		return *repo
	} else {
		repo, err := ggit.PlainOpen(directory)
		if err != nil {
			panic(err)
		}
		// set the repository configuration
		configureRepository(*repo)

		return *repo
	}
}

/*
Creates a new repository instance using the given backing git instance.

Arguments are as follows:

- dir the directory where the repository lives
- repo the backing git repository instance
*/
func newWorkbenchUsing(dir string, repo ggit.Repository) Workbench {
	return Workbench{Directory: dir, Repository: repo}
}

/*
Opens a new repository instance in the given directory.

Arguments are as follows:

  - directory directory the directory to open the repository in
*/
func NewWorkbenchIn(directory string) Workbench {
	return NewWorkbenchWithInitializationAndSettings(directory, false, false)
}

/*
Creates a Git instance on a new repository.

Arguments are as follows:

  - directory the directory to create the repository in
  - bare if true the repository is initialized as a bare repository, otherwise it will have a work tree.
    If initialize is false this parameter is ignored.
  - initialize if true the repository has to be initialized, otherwise false.
*/
func NewWorkbenchWithInitializationAndSettings(directory string, bare bool, initialize bool) Workbench {
	return newWorkbenchUsing(directory, newRepositoryWithInitializationAndSettings(directory, bare, initialize))
}

/*
Creates a new repository instance in a new temporary directory.

Arguments are as follows:

- initialize if true the new repository is also initialized
*/
func NewWorkbenchWithInitialization(initialize bool) Workbench {
	dir, err := os.MkdirTemp("", "nyx-test-workbench-")
	if err != nil {
		panic(err)
	}
	return NewWorkbenchWithInitializationAndSettings(dir, false, initialize)
}

/*
Returns a new basic authentication method object using the given user name and password.

Returns nil if both the given credentials are nil.

  - user the user name to use when credentials are required. It may be nil.
    When using single token authentication (i.e. OAuth or Personal Access Tokens)
    this value may be the token or something other than a token, depending on the remote provider.
  - password the password to use when credentials are required. It may be nil.
    When using single token authentication (i.e. OAuth or Personal Access Tokens)
    this value may be the token or something other than a token, depending on the remote provider.
*/
func getBasicAuth(user *string, password *string) ggittransport.AuthMethod {
	if user == nil && password == nil {
		return nil
	} else if user != nil && password == nil {
		return &ggithttp.BasicAuth{Username: *user}
	} else if user == nil && password != nil {
		return &ggithttp.BasicAuth{Password: *password}
	} else {
		return &ggithttp.BasicAuth{Username: *user, Password: *password}
	}
}

/*
Returns a new public key authentication method object using the given private key and passphrase.

Returns nil if both the given credentials are nil.

  - privateKey the SSH private key. If nil the private key will be searched in its default location
    (i.e. in the users' $HOME/.ssh directory).
  - passphrase the optional password to use to open the private key, in case it's protected by a passphrase.
    This is required when the private key is password protected as this implementation does not support prompting
    the user interactively for entering the password.
*/
func getPublicKeyAuth(privateKey *string, passphrase *string) ggittransport.AuthMethod {
	if privateKey != nil && "" != *privateKey {
		keyPassword := ""
		if passphrase != nil {
			keyPassword = *passphrase
		}
		// The key name is not relevant for us but it seems it must be 'git' for the underlying library,
		// as per https://github.com/src-d/go-git/issues/637
		publicKeys, err := ggitssh.NewPublicKeys("git", []byte(*privateKey), keyPassword)
		if err != nil {
			return nil
		}

		// disable host key checking
		publicKeys.HostKeyCallback = ssh.InsecureIgnoreHostKey()

		return publicKeys
	} else {
		// If no private key is passed just return a default auth method so that go-git will just load keys from their default
		// location (~/.ssh) and connect to ssh-agent (if available) by simply recognizing the remote repository
		// URL format (which must be SSH). See https://github.com/src-d/go-git/issues/550#issuecomment-323078245
		// Some other sources sugges to just return nil for using the default SSH client and settings
		authBuilder, err := ggitssh.DefaultAuthBuilder("keymaster")
		if err != nil {
			return nil
		}
		return authBuilder
	}
}

/*
Clones the repository at the given URI into the given directory.
This method allows using user name and password authentication (also used for tokens).

Arguments are as follows:

  - uri the URI of the repository to clone from
  - directory the directory to clone the repository in
  - user the user name to create when credentials are required. If this and password are both nil
    then no credentials is used. When using single token authentication (i.e. OAuth or Personal Access Tokens)
    this value may be the token or something other than a token, depending on the remote provider.
  - password the password to create when credentials are required. If this and user are both nil
    then no credentials is used. When using single token authentication (i.e. OAuth or Personal Access Tokens)
    this value may be the token or something other than a token, depending on the remote provider.
*/
func CloneIntoWithUserNameAndPassword(uri string, directory string, user *string, password *string) Workbench {
	options := &ggit.CloneOptions{URL: uri}
	auth := getBasicAuth(user, password)
	if auth != nil {
		options.Auth = auth
	}

	repo, err := ggit.PlainClone(directory, false, options)
	if err != nil {
		panic(err)
	}
	return newWorkbenchUsing(directory, *repo)
}

/*
Clones the repository at the given URI into the given directory.
This method allows using SSH authentication.

Arguments are as follows:

  - uri the URI of the repository to clone from
  - directory the directory to clone the repository in
  - privateKey the SSH private key. If nil the private key will be searched in its default location
    (i.e. in the users' $HOME/.ssh directory).
  - passphrase the optional password to use to open the private key, in case it's protected by a passphrase.
    This is required when the private key is password protected as this implementation does not support prompting
    the user interactively for entering the password.
*/
func CloneIntoWithPublicKey(uri string, directory string, privateKey *string, passphrase *string) Workbench {
	options := &ggit.CloneOptions{URL: uri}
	auth := getPublicKeyAuth(privateKey, passphrase)
	if auth != nil {
		options.Auth = auth
	}

	repo, err := ggit.PlainClone(directory, false, options)
	if err != nil {
		panic(err)
	}
	return newWorkbenchUsing(directory, *repo)
}

/*
Adds the given number of text files to the repository root directory. Files have content but they are not staged or committed.
Returns the collection of the new files.

Arguments are as follows:

- count the number of files to add
*/
func (w Workbench) AddRandomTextWorkbenchFiles(count int) []string {
	res := make([]string, count)

	for i := 0; i <= count; i++ {
		/*wt, err := w.Repository.Worktree()
		if err != nil {
			panic(err)
		}*/
		err := os.WriteFile(w.GetWorkingDirectory()+"/"+gitutil.RandomAlphabeticString(5, 7*i)+".txt", []byte(gitutil.RandomAlphabeticString(5, 13*i)), 0644)
		if err != nil {
			panic(err)
		}
	}

	return res
}

/*
Adds the repository in the given metadata directory to the configured remotes of this repository, using the given name.
This is only suitable for local repositories to be added as remotes to other local repositories.

Arguments are as follows:

- gitDir the Git metadata directory of the repository to add as remote
- name the name to use for the new remote repository in the local one
*/
func (w Workbench) AddRemote(gitDir string, name string) {
	_, err := w.Repository.CreateRemote(&ggitconfig.RemoteConfig{Name: name, URLs: []string{gitDir}})
	if err != nil {
		panic(err)
	}
}

/*
Commits the staged files with the given commit message.

Arguments are as follows:

- message the commit message
*/
func (w Workbench) Commit(message string) ggitobject.Commit {
	worktree, err := w.Repository.Worktree()
	if err != nil {
		panic(err)
	}
	commitHash, err := worktree.Commit(message, &ggit.CommitOptions{All: false})
	if err != nil {
		panic(err)
	}
	commit, err := w.Repository.CommitObject(commitHash)
	if err != nil {
		panic(err)
	}
	return *commit
}

/*
Creates a new branch if none with the given name exists yet and checks it out.
Watch out as there must be one commit before this command runs without error because the HEAD
ref may not be initialized yet.

Arguments are as follows:

-name the branch name
*/
func (w Workbench) Checkout(name string) {
	worktree, err := w.Repository.Worktree()
	if err != nil {
		panic(err)
	}
	// try to check it out if it already exists
	err = worktree.Checkout(&ggit.CheckoutOptions{Branch: ggitplumbing.NewBranchReferenceName(name), Create: false})
	if err != nil {
		// the branch does not exist yet, create it
		err = worktree.Checkout(&ggit.CheckoutOptions{Branch: ggitplumbing.NewBranchReferenceName(name), Create: true})
		if err != nil {
			panic(err)
		}
	}
}

/*
Returns the names of all branches in the repository.
*/
func (w Workbench) GetBranches() []string {
	res := []string{}
	branchesIterator, err := w.Repository.Branches()
	if err != nil {
		panic(err)
	}

	err = branchesIterator.ForEach(func(b *ggitplumbing.Reference) error {
		// also strip the "refs/heads/" from the branch name
		res = append(res, strings.Replace(b.Name().String(), "refs/heads/", "", 1))
		return nil
	})
	if err != nil {
		panic(err)
	}

	return res
}

/*
Returns the SHA-1 of the commit the given tag points to, if any, or nil otherwise.

Arguments are as follows:

- tag the tag to search the commit for
*/
func (w Workbench) GetCommitByTag(tag string) *string {
	tagReference, err := w.Repository.Tag(tag)
	if err != nil {
		return nil
	} else {
		annotatedTag, err := w.Repository.TagObject(tagReference.Hash())
		if err == nil {
			// it's an annotated tag, annotatedTag is valid
			s := annotatedTag.Target.String()
			return &s
		} else {
			// it's a lightweight tag, annotatedTag is not valid
			s := tagReference.Hash().String()
			return &s
		}
	}
}

/*
Returns the list of all commit SHAs by querying the repository starting from HEAD.
*/
func (w Workbench) GetCommitIDs() []string {
	commits := w.GetCommits()
	res := make([]string, len(commits))
	for i, c := range commits {
		res[i] = c.Hash.String()
	}
	return res
}

/*
Returns the list of all commits by querying the repository starting from HEAD.
*/
func (w Workbench) GetCommits() []ggitobject.Commit {
	res := []ggitobject.Commit{}
	ref, err := w.Repository.Head()
	if err != nil {
		panic(err)
	}
	commit, err := w.Repository.CommitObject(ref.Hash())
	if err != nil {
		panic(err)
	}

	for commit != nil {
		res = append(res, *commit)
		if len(commit.ParentHashes) > 0 {
			commit, err = w.Repository.CommitObject(commit.ParentHashes[0]) // follow the first parent upon merge commits
			if err != nil {
				commit = nil
				panic(err)
			}
		} else {
			commit = nil
		}
	}
	return res
}

/*
Returns the name of the current branch (the long version, without stripping the refs/heads/ prefix).
*/
func (w Workbench) getCurrentBranchLong() string {
	ref, err := w.Repository.Head()
	if err != nil {
		panic(err)
	}
	return ref.Name().String()
}

/*
Returns the name of the current branch.
*/
func (w Workbench) GetCurrentBranch() string {
	return strings.Replace(w.getCurrentBranchLong(), "refs/heads/", "", 1)
}

/*
Returns the collection of regular files in the repository root directory.
*/
func (w Workbench) GetFiles() []string {
	res := []string{}
	files, err := os.ReadDir(w.Directory)
	if err != nil {
		panic(err)
	}
	for _, file := range files {
		// avoid adding the ".git" directory (and any other directory)
		if !file.IsDir() {
			res = append(res, filepath.Join(w.Directory, file.Name()))
		}
	}

	return res
}

/*
Returns the Git metadata directory for the repository
*/
func (w Workbench) GetGitDirectory() string {
	// the underlying implementation doesn't give us this value, so let's just assume it's the '.git' directory inside the working directory
	return w.GetWorkingDirectory() + "/.git"
}

/*
Returns the number of entries in the repository index.
*/
func (w Workbench) GetIndexEntryCount() int {
	count := 0
	// the underlying implementation doesn't expose this value, so let's just count the objects in the repo
	objectsIterator, err := w.Repository.Objects()
	if err != nil {
		panic(err)
	}

	err = objectsIterator.ForEach(func(o ggitobject.Object) error {
		count++
		return nil
	})
	if err != nil {
		panic(err)
	}

	return count
}

/*
Returns the last commit in the current branch.
*/
func (w Workbench) GetLastCommit() ggitobject.Commit {
	ref, err := w.Repository.Head()
	if err != nil {
		panic(err)
	}
	commit, err := w.Repository.CommitObject(ref.Hash())
	if err != nil {
		panic(err)
	}
	return *commit
}

/*
Returns the SHA-1 ID of the last commit in the current branch.
*/
func (w Workbench) GetLastCommitID() string {
	return w.GetLastCommit().Hash.String()
}

/*
Returns the root commit.
*/
func (w Workbench) GetRootCommit() ggitobject.Commit {
	ref, err := w.Repository.Head()
	if err != nil {
		panic(err)
	}
	// the Log method doesn't let us follow the firt parent, so we need to go through all commits and stop at the end
	commit, err := w.Repository.CommitObject(ref.Hash())
	if err != nil {
		panic(err)
	}
	for len(commit.ParentHashes) > 0 {
		commit, err = w.Repository.CommitObject(commit.ParentHashes[0]) // always follow the first parent, ignore others, if any
		if err != nil {
			panic(err)
		}
	}
	return *commit
}

/*
Returns the SHA-1 ID of the root commit.
*/
func (w Workbench) GetRootCommitID() string {
	return w.GetRootCommit().Hash.String()
}

/*
Return a list of tag objects, resulting from a query to the underlying repository.
Keys are tag names (without prefix) and values are the tagged objects.
*/
func (w Workbench) GetTags() map[string]string {
	res := map[string]string{}
	tagsIterator, err := w.Repository.Tags()
	if err != nil {
		panic(err)
	}
	if err := tagsIterator.ForEach(func(ref *ggitplumbing.Reference) error {
		// in order to check if the tag has this commit as target we first need to figure out if it's annotated or lightweight
		tagObject, err := w.Repository.TagObject(ref.Hash())
		switch err {
		case nil:
			// it's an annotated tag
			res[strings.Replace(ref.Name().String(), "refs/tags/", "", 1)] = tagObject.Target.String()
		case ggitplumbing.ErrObjectNotFound:
			// it's a lightweight tag
			res[strings.Replace(ref.Name().String(), "refs/tags/", "", 1)] = ref.Hash().String()
		default:
			// Some other error occurred
			panic(err)
		}
		return nil
	}); err != nil {
		panic(err)
	}
	return res
}

/*
Commits merge the contents of the given branch into the current one creating a commit with the given message.

Arguments are as follows:

- fromBranch the name of the branch to merge from
- message the commit message
*/
func (w Workbench) Merge(fromBranch string, message string) ggitobject.Commit {
	// Merge is not supported by go-git so we need to run Git as an external command for that.
	var buffer bytes.Buffer

	gitutil.RunCommand([]string{"git", "merge", "-m", message, fromBranch}, []string{}, &w.Directory, &buffer)

	// to make sure the backing repository is up to date after calling the external command let's create a new instance
	repo, err := ggit.PlainOpen(w.Directory)
	if err != nil {
		panic(err)
	}
	w.Repository = *repo

	// now return the latest commit, which is the one made by the merge
	return w.GetLastCommit()
}

/*
Adds all the local changed files to the staging area, without committing.
*/
func (w Workbench) Stage() {
	w.StageGlob(".")
}

/*
Adds files matched by the given pattern to the staging area, without committing.

Arguments are as follows:

- pattern the pattern of the files to stage (i.e. '.' to stage anything)
*/
func (w Workbench) StageGlob(pattern string) {
	worktree, err := w.Repository.Worktree()
	if err != nil {
		panic(err)
	}
	err = worktree.AddWithOptions(&ggit.AddOptions{All: false, Path: "", Glob: pattern})
	if err != nil {
		panic(err)
	}
}

/*
Tags the given object with the given name.

Arguments are as follows:

- name the tag name
- message the tag message (used only for annotated tags, otherwise can be nil)
- target the object to tag
*/
func (w Workbench) TagObject(name string, message *string, target *ggitplumbing.Hash) ggitplumbing.Reference {
	var createTagOptions *ggit.CreateTagOptions = nil
	if message != nil {
		// create an annotated tag, pass a CreateTagOptions
		// when the message is nil we create a lightweight tag so CreateTagOptions needs to be nil
		createTagOptions = &ggit.CreateTagOptions{Message: *message}
	}
	ref, err := w.Repository.CreateTag(name, *target, createTagOptions)
	if err != nil {
		panic(err)
	}
	return *ref
}

/*
*
Tags the last commit with the given name.

Arguments are as follows:

- name the tag name
- message the tag message (used only for annotated tags, otherwise can be nil)
*/
func (w Workbench) Tag(name string, message *string) ggitplumbing.Reference {
	target := w.GetLastCommit().Hash
	return w.TagObject(name, message, &target)
}

/*
Returns the working directory for the repository
*/
func (w Workbench) GetWorkingDirectory() string {
	return w.Directory
}

/*
Prints repository informations to the given output stream.

Use this method like in this example:

var buf bytes.Buffer
workbench.PrintInfo(&buf)
fmt.Println(buf.String())

Arguments are as follows:

- out the stream to print the info to
*/
func (w Workbench) PrintInfo(out io.Writer) {
	gitutil.PrintRepositoryInfo(w.Directory, out, "")
}

/*
Pushes all commits to the default remote repository using no credentials.
*/
func (w Workbench) Push() {
	w.PushWithUserNameAndPassword(nil, nil)
}

/*
Pushes all commits to the default remote repository using the given credentials.

Arguments are as follows:

- user the optional user name to use when credentials are required.
- password the optional password to use when credentials are required.
*/
func (w Workbench) PushWithUserNameAndPassword(user *string, password *string) {
	w.PushToWithCredentials("origin", user, password)
}

/*
Pushes all commits to the given remote repository using no credentials.

Arguments are as follows:

- remote the remote repository to push to.
*/
func (w Workbench) PushTo(remote string) {
	w.PushToWithCredentials(remote, nil, nil)
}

/*
Pushes all commits to the given remote repository using the given credentials.

Arguments are as follows:

- remote the remote repository to push to.
- user the optional user name to use when credentials are required.
- password the optional password to use when credentials are required.
*/
func (w Workbench) PushToWithCredentials(remote string, user *string, password *string) {
	branchRefSpec := ggitconfig.RefSpec(w.getCurrentBranchLong() + ":" + w.getCurrentBranchLong())
	tagsRefSpec := ggitconfig.RefSpec("refs/tags/*:refs/tags/*") // this is required to also push tags
	pushOptions := ggit.PushOptions{RemoteName: remote, RefSpecs: []ggitconfig.RefSpec{branchRefSpec, tagsRefSpec}, Auth: getBasicAuth(user, password)}
	err := w.Repository.Push(&pushOptions)
	if err != nil {
		panic(err)
	}
}

/*
Replaces the content of all the files in the repository created using this workbench.
*/
func (w Workbench) UpdateAllWorkbenchFiles() {
	w.UpdateWorkbenchFiles(w.GetFiles())
}

/*
Replaces the content of the given files created using this workbench with new random content.

Arguments are as follows:

- files the collection of files to update
*/
func (w Workbench) UpdateWorkbenchFiles(files []string) {
	for i, f := range files {
		err := os.WriteFile(f, []byte(gitutil.RandomAlphabeticString(5, i*23)), 0644)
		if err != nil {
			panic(err)
		}
	}
}

repository: mooltiverse/nyx

repo_name: mooltiverse/nyx

gha_language: Java


text:
//  Copyright 2019 Jacques Marais
//
//  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 relapseviz

import (
	"bytes"
	"fmt"
	"io"
	"math/rand"
	"reflect"
	"strconv"
	"strings"

	"github.com/awalterschulze/gographviz"
	"github.com/jmarais/relapseviz/svg"
	"github.com/katydid/katydid/relapse"
	"github.com/katydid/katydid/relapse/ast"
	"github.com/katydid/katydid/relapse/types"
)

type translator struct {
	graph *gographviz.Graph
	full  bool
	r     *rand.Rand
}

func Translate(s string, full bool) (*gographviz.Graph, error) {
	g, err := relapse.Parse(s)
	if err != nil {
		return nil, err
	}
	return TranslateGrammar(g, full), nil
}

// Translate the given ast.Grammer to a graphviz Graph.
// 'full' traverse extra nodes which the relapse walker skips.
// The node names are generated from the ast type name while a edge
// name will be the fieldname of the edge source.
// The list of struct fields are also listed in the node under the name.
func TranslateGrammar(g *ast.Grammar, full bool) *gographviz.Graph {
	t := &translator{
		graph: gographviz.NewGraph(),
		full:  full,
		r:     rand.New(rand.NewSource(0)),
	}
	if err := t.graph.SetName("Relapse"); err != nil {
		panic(err)
	}
	if err := t.graph.SetDir(true); err != nil {
		panic(err)
	}
	nodeLabel := getTypeName(g)
	t.translate(g, nodeLabel, `root`)
	return t.graph
}

// Get the ast type name
func getTypeName(v interface{}) string {
	rv := reflect.ValueOf(v)
	typeName := rv.Type().String()
	ss := strings.Split(typeName, ".")
	return ss[len(ss)-1]
}

func (t *translator) translate(node interface{}, nodeName, suffix string) {
	nodeId := nodeName + suffix
	label := newLabel(nodeName)
	switch v := node.(type) {
	case *ast.Grammar:
		if v.After != nil {
			label.write(`\nAfter: \"`, v.After.String(), `\"`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if v.TopPattern != nil {
			t.down(nodeId, v.TopPattern, `TopPattern`)
		}
		for i, pdecl := range v.PatternDecls {
			nextNodeName := getTypeName(pdecl)
			suff := strconv.FormatUint(t.r.Uint64(), 10)
			t.addEdge(nodeId, nextNodeName+suff, map[string]string{attrLabel: fmt.Sprintf(`"%v[%d]"`, `PatternDecls`, i)})
			t.translate(pdecl, nextNodeName, suff)
		}
		if t.full {
			if v.After != nil {
				t.down(nodeId, v.After, `After`)
			}
		}
	case *ast.PatternDecl:
		if v.Hash != nil {
			label.write(`\nHash: `, v.Hash.String())
		}
		if v.Before != nil {
			label.write(`\nBefore: \"`, v.Before.String(), `\"`)
		}
		if v.Name != "" {
			label.write(`\nName: `, v.Name)
		}
		if v.Eq != nil {
			label.write(`\nEq: `, v.Eq.String())
		}
		if v.Pattern != nil {
			label.write(`\nPattern: `, `Pattern`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})

		if t.full {
			if v.Hash != nil {
				t.down(nodeId, v.Hash, `Hash`)
			}
			if v.Eq != nil {
				t.down(nodeId, v.Eq, `Eq`)
			}
			if v.Before != nil {
				t.down(nodeId, v.Before, `Before`)
			}
		}
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
	case *ast.Pattern:
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if v.Empty != nil {
			t.down(nodeId, v.Empty, `Empty`)
		}
		if v.TreeNode != nil {
			t.down(nodeId, v.TreeNode, `TreeNode`)
		}
		if v.LeafNode != nil {
			t.down(nodeId, v.LeafNode, `LeafNode`)
		}
		if v.Concat != nil {
			t.down(nodeId, v.Concat, `Concat`)
		}
		if v.Or != nil {
			t.down(nodeId, v.Or, `Or`)
		}
		if v.And != nil {
			t.down(nodeId, v.And, `And`)
		}
		if v.ZeroOrMore != nil {
			t.down(nodeId, v.ZeroOrMore, `ZeroOrMore`)
		}
		if v.Reference != nil {
			t.down(nodeId, v.Reference, `Reference`)
		}
		if v.Not != nil {
			t.down(nodeId, v.Not, `Not`)
		}
		if v.ZAny != nil {
			t.down(nodeId, v.ZAny, `ZAny`)
		}
		if v.Contains != nil {
			t.down(nodeId, v.Contains, `Contains`)
		}
		if v.Optional != nil {
			t.down(nodeId, v.Optional, `Optional`)
		}
		if v.Interleave != nil {
			t.down(nodeId, v.Interleave, `Interleave`)
		}
	case *ast.Empty:
		if v.Empty != nil {
			label.write(`\nEmpty: \"`, v.Empty.String(), `\"`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Empty != nil {
				t.down(nodeId, v.Empty, `Empty`)
			}
		}
	case *ast.TreeNode:
		if v.Name != nil {
			label.write(`\nName: `, v.Name.String())
		}
		if v.Colon != nil {
			label.write(`\nColon: `, v.Colon.String())
		}
		if v.Pattern != nil {
			label.write(`\nPattern: `, `Pattern`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if v.Name != nil {
			t.down(nodeId, v.Name, `Name`)
		}
		if t.full {
			if v.Colon != nil {
				t.down(nodeId, v.Colon, `Colon`)
			}
		}
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
	case *ast.Contains:
		if v.Dot != nil {
			label.write(`\nDot: `, v.Dot.String())
		}
		if v.Pattern != nil {
			label.write(`\nPattern: `, `Pattern`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Dot != nil {
				t.down(nodeId, v.Dot, `Dot`)
			}
		}
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
	case *ast.LeafNode:
		if v.Expr != nil {
			label.write(`\nExpr: `, `Expr`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if v.Expr != nil {
			t.down(nodeId, v.Expr, `Expr`)
		}
	case *ast.Concat:
		if v.OpenBracket != nil {
			label.write(`\nOpenBracket: `, v.OpenBracket.String())
		}
		if v.LeftPattern != nil {
			label.write(`\nLeftPattern: `, `LeftPattern`)
		}
		if v.Comma != nil {
			label.write(`\nComma: `, v.Comma.String())
		}
		if v.RightPattern != nil {
			label.write(`\nRightPattern: `, `RightPattern`)
		}
		if v.ExtraComma != nil {
			label.write(`\nComma: `, v.ExtraComma.String())
		}
		if v.OpenBracket != nil {
			label.write(`\nCloseBracket: `, v.CloseBracket.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.OpenBracket != nil {
				t.down(nodeId, v.OpenBracket, `OpenBracket`)
			}
		}
		if v.LeftPattern != nil {
			t.down(nodeId, v.LeftPattern, `LeftPattern`)
		}
		if t.full {
			if v.Comma != nil {
				t.down(nodeId, v.Comma, `Comma`)
			}
		}
		if v.RightPattern != nil {
			t.down(nodeId, v.RightPattern, `RightPattern`)
		}
		if t.full {
			if v.ExtraComma != nil {
				t.down(nodeId, v.ExtraComma, `ExtraComma`)
			}
			if v.CloseBracket != nil {
				t.down(nodeId, v.CloseBracket, `CloseBracket`)
			}
		}
	case *ast.Or:
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.LeftPattern != nil {
			label.write(`\nLeftPattern: `, `LeftPattern`)
		}
		if v.Pipe != nil {
			label.write(`\nPipe: `, v.Pipe.String())
		}
		if v.RightPattern != nil {
			label.write(`\nRightPattern: `, `RightPattern`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.LeftPattern != nil {
			t.down(nodeId, v.LeftPattern, `LeftPattern`)
		}
		if t.full {
			if v.Pipe != nil {
				t.down(nodeId, v.Pipe, `Pipe`)
			}
		}
		if v.RightPattern != nil {
			t.down(nodeId, v.RightPattern, `RightPattern`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
		}
	case *ast.And:
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.LeftPattern != nil {
			label.write(`\nLeftPattern: `, `LeftPattern`)
		}
		if v.Ampersand != nil {
			label.write(`\nAmpersand: `, v.Ampersand.String())
		}
		if v.RightPattern != nil {
			label.write(`\nRightPattern: `, `RightPattern`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.LeftPattern != nil {
			t.down(nodeId, v.LeftPattern, `LeftPattern`)
		}
		if t.full {
			if v.Ampersand != nil {
				t.down(nodeId, v.Ampersand, `Ampersand`)
			}
		}
		if v.RightPattern != nil {
			t.down(nodeId, v.RightPattern, `RightPattern`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
		}
	case *ast.ZeroOrMore:
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.Pattern != nil {
			label.write(`\nPattern: `, `Pattern`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		if v.Star != nil {
			label.write(`\nStar: `, v.Star.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
			if v.Star != nil {
				t.down(nodeId, v.Star, `Star`)
			}
		}
	case *ast.Reference:
		if v.At != nil {
			label.write(`\nAt: `, v.At.String())
		}
		if v.Name != "" {
			label.write(`\nName: `, v.Name)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.At != nil {
				t.down(nodeId, v.At, `At`)
			}
		}
	case *ast.Not:
		if v.Exclamation != nil {
			label.write(`\nExclamation: `, v.Exclamation.String())
		}
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.Pattern != nil {
			label.write(`\nPattern: `, `Pattern`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Exclamation != nil {
				t.down(nodeId, v.Exclamation, `Exclamation`)
			}
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
		}
	case *ast.ZAny:
		if v.Star != nil {
			label.write(`\nStar: `, v.Star.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Star != nil {
				t.down(nodeId, v.Star, `Star`)
			}
		}
	case *ast.Optional:
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.Pattern != nil {
			label.write(`\nPattern: `, `Pattern`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		if v.QuestionMark != nil {
			label.write(`\nQuestionMark: `, v.QuestionMark.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
		if t.full {

			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.Pattern != nil {
			t.down(nodeId, v.Pattern, `Pattern`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
			if v.QuestionMark != nil {
				t.down(nodeId, v.QuestionMark, `QuestionMark`)
			}
		}
	case *ast.Interleave:
		if v.OpenCurly != nil {
			label.write(`\nOpenCurly: `, v.OpenCurly.String())
		}
		if v.LeftPattern != nil {
			label.write(`\nLeftPattern: `, `LeftPattern`)
		}
		if v.SemiColon != nil {
			label.write(`\nSemiColon: `, v.SemiColon.String())
		}
		if v.RightPattern != nil {
			label.write(`\nRightPattern: `, `RightPattern`)
		}
		if v.ExtraSemiColon != nil {
			label.write(`\nExtraSemiColon: `, v.ExtraSemiColon.String())
		}
		if v.CloseCurly != nil {
			label.write(`\nCloseCurly: `, v.CloseCurly.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.OpenCurly != nil {
				t.down(nodeId, v.OpenCurly, `OpenCurly`)
			}
		}
		if v.LeftPattern != nil {
			t.down(nodeId, v.LeftPattern, `LeftPattern`)
		}
		if t.full {
			if v.SemiColon != nil {
				t.down(nodeId, v.SemiColon, `SemiColon`)
			}
		}
		if v.RightPattern != nil {
			t.down(nodeId, v.RightPattern, `RightPattern`)
		}
		if t.full {
			if v.ExtraSemiColon != nil {
				t.down(nodeId, v.ExtraSemiColon, `ExtraSemiColon`)
			}
			if v.CloseCurly != nil {
				t.down(nodeId, v.CloseCurly, `CloseCurly`)
			}
		}
	case *ast.Expr:
		if v.RightArrow != nil {
			label.write(`\nRightArrow: `, v.RightArrow.String())
		}
		if v.Comma != nil {
			label.write(`\nComma: `, v.Comma.String())
		}
		if v.Terminal != nil {
			label.write(`\nTerminal: `, `Terminal`)
		}
		if v.List != nil {
			label.write(`\nList: `, `List`)
		}
		if v.Function != nil {
			label.write(`\nFunction: `, `Function`)
		}
		if v.BuiltIn != nil {
			label.write(`\nBuiltIn: `, `BuiltIn`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.RightArrow != nil {
				t.down(nodeId, v.RightArrow, `RightArrow`)
			}
			if v.Comma != nil {
				t.down(nodeId, v.Comma, `Comma`)
			}
		}
		if v.Terminal != nil {
			t.down(nodeId, v.Terminal, `Terminal`)
		}
		if v.List != nil {
			t.down(nodeId, v.List, `List`)
		}
		if v.Function != nil {
			t.down(nodeId, v.Function, `Function`)
		}
		if v.BuiltIn != nil {
			t.down(nodeId, v.BuiltIn, `BuiltIn`)
		}
	case *ast.List:
		if v.Before != nil {
			label.write(`\nBefore: \"`, v.Before.String(), `\"`)
		}
		label.write(`\nType: `, types.Type_name[int32(v.Type)])
		if v.OpenCurly != nil {
			label.write(`\nOpenCurly: `, v.OpenCurly.String())
		}
		if v.Elems != nil {
			label.write(`\nElems: `, `Elems`)
		}
		if v.CloseCurly != nil {
			label.write(`\nCloseCurly: `, v.CloseCurly.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Before != nil {
				t.down(nodeId, v.Before, `Before`)
			}
			if v.OpenCurly != nil {
				t.down(nodeId, v.OpenCurly, `OpenCurly`)
			}
		}
		for i, e := range v.GetElems() {
			nextNodeName := getTypeName(e)
			suff := strconv.FormatUint(t.r.Uint64(), 10)
			t.addEdge(nodeId, nextNodeName+suff, map[string]string{attrLabel: fmt.Sprintf(`"%v[%d]"`, `Elems`, i)})
			t.translate(e, nextNodeName, suff)
		}
		if t.full {
			if v.CloseCurly != nil {
				t.down(nodeId, v.CloseCurly, `CloseCurly`)
			}
		}
	case *ast.Function:
		if v.Before != nil {
			label.write(`\nBefore: \"`, v.Before.String(), `\"`)
		}
		if v.Name != "" {
			label.write(`\nName: `, v.Name)
		}
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.Params != nil {
			label.write(`\nParams: `, `Params`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Before != nil {
				t.down(nodeId, v.Before, `Before`)
			}
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		for i, e := range v.GetParams() {
			nextNodeName := getTypeName(e)
			suff := strconv.FormatUint(t.r.Uint64(), 10)
			t.addEdge(nodeId, nextNodeName+suff, map[string]string{attrLabel: fmt.Sprintf(`"%v[%d]"`, `Params`, i)})
			t.translate(e, nextNodeName, suff)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
		}
	case *ast.BuiltIn:
		if v.Symbol != nil {
			label.write(`\nSymbol: `, v.Symbol.String())
		}
		if v.Expr != nil {
			label.write(`\nExpr: `, `Expr`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Symbol != nil {
				t.down(nodeId, v.Symbol, `Symbol`)
			}
		}
		if v.Expr != nil {
			t.down(nodeId, v.Expr, `Expr`)
		}
	case *ast.Terminal:
		if v.Before != nil {
			label.write(`\nBefore: \"`, v.Before.String(), `\"`)
		}
		if v.Literal != "" {
			label.write(`\nLiteral: `, strings.Replace(v.Literal, "\"", "\\\"", -1))
		}
		if v.DoubleValue != nil {
			label.write(`\nDoubleValue: `, strconv.FormatFloat(*v.DoubleValue, 'E', -1, 64))
		}
		if v.IntValue != nil {
			label.write(`\nIntValue: `, strconv.FormatInt(*v.IntValue, 10))
		}
		if v.UintValue != nil {
			label.write(`\nUintValue: `, strconv.FormatUint(*v.UintValue, 10))
		}
		if v.BoolValue != nil {
			label.write(`\nBoolValue: `, strconv.FormatBool(*v.BoolValue))
		}
		if v.StringValue != nil {
			label.write(`\nStringValue: `, *v.StringValue)
		}
		if v.BytesValue != nil {
			label.write(`\nBytesValue: `, string(v.BytesValue))
		}
		if v.Variable != nil {
			label.write(`\nVariable: `, `Variable`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Before != nil {
				t.down(nodeId, v.Before, `Before`)
			}
		}
		if v.Variable != nil {
			t.down(nodeId, v.Variable, `Variable`)
		}
	case *ast.Variable:
		name := types.Type_name[int32(v.Type)]
		label.write(`:\nType:`, name)
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
	case *ast.Keyword:
		if v.Before != nil {
			label.write(`\nBefore: \"`, v.Before.String(), `\"`)
		}
		if v.Value != "" {
			label.write(`\nValue: \"`, v.Value, `\"`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Before != nil {
				t.down(nodeId, v.Before, `Before`)
			}
		}
	case *ast.Space:
		for i, s := range v.Space {
			label.write(`\nSpace[`, strconv.Itoa(i), `]: \"`, s, `\"`)
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
	case *ast.NameExpr:
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if v.Name != nil {
			t.down(nodeId, v.Name, `Name`)
		}
		if v.AnyName != nil {
			t.down(nodeId, v.AnyName, `AnyName`)
		}
		if v.AnyNameExcept != nil {
			t.down(nodeId, v.AnyNameExcept, `AnyNameExcept`)
		}
		if v.NameChoice != nil {
			t.down(nodeId, v.NameChoice, `NameChoice`)
		}
	case *ast.Name:
		if v.Before != nil {
			label.write(`\nBefore: \"`, v.Before.String(), `\"`)
		}
		if v.DoubleValue != nil {
			label.write(`\nDoubleValue: `, strconv.FormatFloat(*v.DoubleValue, 'E', -1, 64))
		}
		if v.IntValue != nil {
			label.write(`\nIntValue: `, strconv.FormatInt(*v.IntValue, 10))
		}
		if v.UintValue != nil {
			label.write(`\nUintValue: `, strconv.FormatUint(*v.UintValue, 10))
		}
		if v.BoolValue != nil {
			label.write(`\nBoolValue: `, strconv.FormatBool(*v.BoolValue))
		}
		if v.StringValue != nil {
			label.write(`\nStringValue: `, *v.StringValue)
		}
		if v.BytesValue != nil {
			label.write(`\nBytesValue: `, string(v.BytesValue))
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
	case *ast.AnyName:
		if v.Underscore != nil {
			label.write(`\nUnderscore: `, v.Underscore.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Underscore != nil {
				t.down(nodeId, v.Underscore, `Underscore`)
			}
		}
	case *ast.AnyNameExcept:
		if v.Exclamation != nil {
			label.write(`\nExclamation: `, v.Exclamation.String())
		}
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.Except != nil {
			label.write(`\nExcept: `, `Except`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.Exclamation != nil {
				t.down(nodeId, v.Exclamation, `Exclamation`)
			}
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.Except != nil {
			t.down(nodeId, v.Except, `Except`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
		}
	case *ast.NameChoice:
		if v.OpenParen != nil {
			label.write(`\nOpenParen: `, v.OpenParen.String())
		}
		if v.Left != nil {
			label.write(`\nLeft: `, `Left`)
		}
		if v.Pipe != nil {
			label.write(`\nPipe: `, v.Pipe.String())
		}
		if v.Right != nil {
			label.write(`\nRight: `, `Right`)
		}
		if v.CloseParen != nil {
			label.write(`\nCloseParen: `, v.CloseParen.String())
		}
		t.addNode(nodeId, map[string]string{attrLabel: label.finish()})
		if t.full {
			if v.OpenParen != nil {
				t.down(nodeId, v.OpenParen, `OpenParen`)
			}
		}
		if v.Left != nil {
			t.down(nodeId, v.Left, `Left`)

		}
		if t.full {
			if v.Pipe != nil {
				t.down(nodeId, v.Pipe, `Pipe`)
			}
		}
		if v.Right != nil {
			t.down(nodeId, v.Right, `Right`)
		}
		if t.full {
			if v.CloseParen != nil {
				t.down(nodeId, v.CloseParen, `CloseParen`)
			}
		}
	default:
		panic(fmt.Sprintf(`unknown ast node of type "%T" and value "%v"`, v, v))
	}
}

var attrLabel = string(gographviz.Label)

func (t *translator) down(nodeId string, to interface{}, edgeLabelName string) {
	nextNodeName := getTypeName(to)
	suffix := strconv.FormatUint(t.r.Uint64(), 10)
	t.addEdge(nodeId, nextNodeName+suffix, map[string]string{attrLabel: edgeLabelName})
	t.translate(to, nextNodeName, suffix)
}

func (t *translator) addNode(name string, attr map[string]string) {
	if err := t.graph.AddNode(t.graph.Name, name, attr); err != nil {
		panic(err)
	}
}

func (t *translator) addEdge(from, to string, attr map[string]string) {
	if err := t.graph.AddEdge(from, to, true, attr); err != nil {
		panic(err)
	}
}

type label struct {
	b *strings.Builder
}

func newLabel(name string) *label {
	b := &strings.Builder{}
	b.WriteString(`"`)
	b.WriteString(name)
	return &label{b}
}

func (l *label) write(ss ...string) {
	for _, s := range ss {
		l.b.WriteString(s)
	}
}

func (l *label) finish() string {
	l.b.WriteString(`"`)
	return l.b.String()
}

func WriteSVG(graph *gographviz.Graph, w io.Writer) error {
	pp := svg.MassageDotSVG()
	return pp(bytes.NewReader([]byte(graph.String())), w)
}

repository: jmarais/relapseviz

repo_name: jmarais/relapseviz


text:
%
% <%= projectName %>
% <%= projectUrl %>
% Licensed under <%= license %> License
%

@book{Perrin,
    author = "Daniel Perrin",
    title = "La suite logistique et le chaos",
    year = "2008",
    publisher = "IREM"
}

repository: LeoColomb/generator-latex

repo_name: LeoColomb/generator-latex

gha_language: JavaScript


text:
% This file was created with JabRef 2.3.1.
% Encoding: Cp1252

@article{Numa,
	author = {Daniel Weiß},
	title = {Numerische Mathematik für die Fachrichtungen Informatik und Ingenieurwesen},
	year = {2015},
}

@article{KrylowUnterraumWiki,
	title={Krylow-Unterraum-Verfahren},
	url = {https://de.wikipedia.org/wiki/Krylow-Unterraum-Verfahren},
}

@misc{HiFlow3,
	title={HiFlow3},
	url = {http://www.hiflow3.org/},
}

@misc{MFEM,
	title = {MFEM},
	url = {http://mfem.org/},
}

@misc{Deal.II,
	title = {Deal.II},
	url = {https://www.dealii.org/},
}

@misc{Feel++,
	title = {Feel++},
	url = {http://www.feelpp.org/},
}

@misc{Libmesh,
	title = {Libmesh},
	url = {http://libmesh.github.io/},
}

@article{FiniteElemente,
	author = {Braess, Dietrich},
	year = {2007},
	title = {Finite Elemente : Theorie, schnelle Löser und Anwendungen in der Elastizitätstheorie}
}

@article{RechnerstrukturenVL,
	author = {Prof. Dr. Wolfgang Karl},
	year = {2015},
	title = {Vorlesung Rechnerstrukturen}
}

@article{SoftwareEngineeringPP,
	year = {2016},
	title = "Software Engineering für moderne parallele Plattformen",
	author = {Philip Pfaffe}
}

@misc{CUDAMixedPrecision,
	year= 2016,
	title = {Mixed-Precision Programming with CUDA 8},
	author = {Mark Harris},
	howpublished = {\url{https://devblogs.nvidia.com/parallelforall/mixed-precision-programming-cuda-8/}}
}

@misc{CUDAOptParallelReduction,
	title={Optimizing Parallel Reduction in CUDA},
	author={Mark Harris},
	howpublished={\url{http://developer.download.nvidia.com/compute/cuda/1.1-Beta/x86_website/projects/reduction/doc/reduction.pdf}}
}

@misc{ApproxComp,
	title={Approximate Computing: Application Analysis and Hardware Design.},
	author={Gennady Pekhimenko and Danai Koutra and Kun Qian}
}
@misc{SurveyApproxComp,
	title={A Survey of Techniques for Approximate Computing},
	author={Sparsh Mittal}
}
@misc{CompAsyncSync,
	title={Comparing Asynchronous and Synchronous Parallelization of the SMS-EMOA},
	author={Simon Wessing and Günter Rudolph and Dino A. Menges}
}
@misc{HighOrder,
	title={High-Order Methods for Convection-Dominated Nonlinear Problems Using Multilevel Techniques},
	 author={Francesca Iacono}
}
@misc{CudaToolkit,
	title={CUDA Toolkit Documentation},
	author={NVIDIA},
	howpublished={\url{https://developer.nvidia.com/cuda-toolkit}}
}

@article{Benzi2002,
	doi = {10.1006/jcph.2002.7176},
	url = {https://doi.org/10.1006%2Fjcph.2002.7176},
	year  = {2002},
	month = {nov},
	publisher = {Elsevier {BV}},
	volume = {182},
	number = {2},
	pages = {418--477},
	author = {Michele Benzi},
	title = {Preconditioning Techniques for Large Linear Systems: A Survey},
	journal = {Journal of Computational Physics}
}

@misc{EingebetteteSystemeVL1,
	title={Eingebettete Systeme I},
	author={Lars Bauer}
}
@misc{IntelXeonPhi,
	title={Intel Xeon Phi Produktreihe},
	author={Intel},
	howpublished={\url{http://www.intel.de/content/www/de/de/processors/xeon/xeon-phi-detail.html}}
}


text:
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: drand/info.proto

/*
Package drand is a reverse proxy.

It translates gRPC into RESTful JSON APIs.
*/
package drand

import (
	"io"
	"net/http"

	"github.com/golang/protobuf/proto"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"github.com/grpc-ecosystem/grpc-gateway/utilities"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/status"
)

var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray

func request_Info_Group_0(ctx context.Context, marshaler runtime.Marshaler, client InfoClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
	var protoReq GroupRequest
	var metadata runtime.ServerMetadata

	msg, err := client.Group(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
	return msg, metadata, err

}

func request_Info_DistKey_0(ctx context.Context, marshaler runtime.Marshaler, client InfoClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
	var protoReq DistKeyRequest
	var metadata runtime.ServerMetadata

	msg, err := client.DistKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
	return msg, metadata, err

}

func request_Info_Home_0(ctx context.Context, marshaler runtime.Marshaler, client InfoClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
	var protoReq HomeRequest
	var metadata runtime.ServerMetadata

	msg, err := client.Home(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
	return msg, metadata, err

}

// RegisterInfoHandlerFromEndpoint is same as RegisterInfoHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterInfoHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
	conn, err := grpc.Dial(endpoint, opts...)
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			if cerr := conn.Close(); cerr != nil {
				grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
			}
			return
		}
		go func() {
			<-ctx.Done()
			if cerr := conn.Close(); cerr != nil {
				grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
			}
		}()
	}()

	return RegisterInfoHandler(ctx, mux, conn)
}

// RegisterInfoHandler registers the http handlers for service Info to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterInfoHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
	return RegisterInfoHandlerClient(ctx, mux, NewInfoClient(conn))
}

// RegisterInfoHandlerClient registers the http handlers for service Info
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "InfoClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "InfoClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "InfoClient" to call the correct interceptors.
func RegisterInfoHandlerClient(ctx context.Context, mux *runtime.ServeMux, client InfoClient) error {

	mux.Handle("GET", pattern_Info_Group_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
		ctx, cancel := context.WithCancel(req.Context())
		defer cancel()
		inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
		rctx, err := runtime.AnnotateContext(ctx, mux, req)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}
		resp, md, err := request_Info_Group_0(rctx, inboundMarshaler, client, req, pathParams)
		ctx = runtime.NewServerMetadataContext(ctx, md)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}

		forward_Info_Group_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)

	})

	mux.Handle("GET", pattern_Info_DistKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
		ctx, cancel := context.WithCancel(req.Context())
		defer cancel()
		inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
		rctx, err := runtime.AnnotateContext(ctx, mux, req)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}
		resp, md, err := request_Info_DistKey_0(rctx, inboundMarshaler, client, req, pathParams)
		ctx = runtime.NewServerMetadataContext(ctx, md)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}

		forward_Info_DistKey_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)

	})

	mux.Handle("GET", pattern_Info_Home_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
		ctx, cancel := context.WithCancel(req.Context())
		defer cancel()
		inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
		rctx, err := runtime.AnnotateContext(ctx, mux, req)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}
		resp, md, err := request_Info_Home_0(rctx, inboundMarshaler, client, req, pathParams)
		ctx = runtime.NewServerMetadataContext(ctx, md)
		if err != nil {
			runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
			return
		}

		forward_Info_Home_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)

	})

	return nil
}

var (
	pattern_Info_Group_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"api", "info", "group"}, ""))

	pattern_Info_DistKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"api", "info", "distkey"}, ""))

	pattern_Info_Home_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0}, []string{"api"}, ""))
)

var (
	forward_Info_Group_0 = runtime.ForwardResponseMessage

	forward_Info_DistKey_0 = runtime.ForwardResponseMessage

	forward_Info_Home_0 = runtime.ForwardResponseMessage
)

repository: nealmcb/drand

repo_name: nealmcb/drand


text:
package pgmb

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestWhereCreditOrArtistNameMatches(t *testing.T) {
	t.Run("with a match on artist_credit.name", func(t *testing.T) {
		acs, err := ArtistCredits(TESTDB).WhereCreditOrArtistNameMatches("Crosby, Stills & Nash").All()
		assert.Nil(t, err)
		assert.True(t, len(acs) > 0, "Expected at least 1 match for 'Crosby, Stills & Nash")
		assert.EqualValues(t, 1048685, acs[0].ID)
	})
}

repository: adlio/pgmb

repo_name: adlio/pgmb


text:
// Copyright 2021 Google LLC
//
// 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 mixins

import (
	"strings"

	"github.com/divVerent/aaaaxy/internal/engine"
	"github.com/divVerent/aaaaxy/internal/level"
	"github.com/divVerent/aaaaxy/internal/log"
)

// Settable implements the SetState handler for settable entities.
type Settable struct {
	State  bool
	Invert bool
}

// SetState changes the state of the entity.
func (s *Settable) SetState(originator, predecessor *engine.Entity, state bool) {
	s.State = state != s.Invert
}

// Init initializes the initial state of the entity.
func (s *Settable) Init(sp *level.Spawnable) error {
	s.Invert = sp.Properties["invert"] == "true" // Default false.
	s.State = s.Invert
	return nil
}

// stateSetter is an entity that contains this mixin.
type stateSetter interface {
	SetState(originator, predecessor *engine.Entity, state bool)
}

// SetStateOfEntity sets the state of an entity, if available.
// Returns whether the setting was successful.
func SetStateOfEntity(originator, predecessor *engine.Entity, of *engine.Entity, state bool) bool {
	setter, ok := of.Impl.(stateSetter)
	if !ok {
		return false
	}
	setter.SetState(originator, predecessor, state)
	return true
}

type TargetSelection []string

func ParseTarget(target string) TargetSelection {
	return TargetSelection(strings.Split(target, " "))
}

// SetStateOfTarget toggles the state of all entities of the given target name to the given state.
// Includes WarpZones too.
// Excludes the given entity (should be the caller).
func SetStateOfTarget(w *engine.World, originator, predecessor *engine.Entity, targets TargetSelection, state bool) {
	for _, target := range targets {
		if target == "" {
			continue
		}
		thisState := state
		if target[0] == '!' {
			thisState = !state
			target = target[1:]
		}
		if target == "" {
			continue
		}
		if target[0] == '=' {
			target = target[1:]
			var closest *engine.Entity
			for _, ent := range w.FindName(target) {
				if ent == predecessor {
					log.Fatalf("Should this even happen? An entity targeting itself? Name is %v.", target)
					continue
				}
				if closest == nil || closest.Rect.Delta(w.Player.Rect).Norm1() > ent.Rect.Delta(w.Player.Rect).Norm1() {
					closest = ent
				}
			}
			if closest != nil {
				if !SetStateOfEntity(originator, predecessor, closest, state) {
					log.Errorf("Tried to set state of a non-supporting entity: %T, name: %v", closest, target)
				}
			}
		} else {
			w.SetWarpZoneState(target, thisState)
			for _, ent := range w.FindName(target) {
				if ent == predecessor {
					log.Fatalf("Should this even happen? An entity targeting itself? Name is %v.", target)
					continue
				}
				if !SetStateOfEntity(originator, predecessor, ent, thisState) {
					log.Errorf("Tried to set state of a non-supporting entity: %T, name: %v", ent, target)
				}
			}
		}
	}
}

repository: isgasho/aaaaxy

repo_name: isgasho/aaaaxy


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/instancedattribs.dir/src/instancedattribs/instancedattribs.cpp.o"
  "bin/instancedattribs.pdb"
  "bin/instancedattribs"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/instancedattribs.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
package bundler

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/avarteqgmbh/rvm-cnb/rvm"
	"github.com/paketo-buildpacks/packit"
)

// InstallBundler install bundler in a given RVM environment
func InstallBundler(context packit.BuildContext, configuration Configuration, logger rvm.LogEmitter) (packit.BuildResult, error) {
	logger.Title("%s %s", context.BuildpackInfo.Name, context.BuildpackInfo.Version)
	logger.Process("default Bundler version: %s\n", bundlerVersion(context, configuration))

	bundlerLayer, err := context.Layers.Get("rvm-bundler", packit.LaunchLayer)
	if err != nil {
		return packit.BuildResult{}, err
	}

	logger.Process("Installing Bundler version '%s'", bundlerVersion(context, configuration))

	bundlerLayer.Metadata = map[string]interface{}{
		"version": bundlerVersion(context, configuration),
	}

	bundlerLayer.Build = true
	bundlerLayer.Cache = true
	bundlerLayer.Launch = true

	bundlerMajorVersion, err := strconv.Atoi(bundlerVersion(context, configuration)[:1])
	if err != nil {
		logger.Process("Failed to determine bundler major version")
		return packit.BuildResult{}, err
	}

	rubyGemsVersion := ""
	if bundlerMajorVersion == 1 {
		rubyGemsVersion = "3.0.8"
	}

	installRubyGemsUpdateSystemCmd := strings.Join([]string{
		"gem",
		"install",
		"-N",
		"rubygems-update",
	}, " ")
	if len(rubyGemsVersion) > 0 {
		installRubyGemsUpdateSystemCmd = strings.Join([]string{
			installRubyGemsUpdateSystemCmd,
			"-v",
			rubyGemsVersion,
		}, " ")
	}
	err = RunBashCmd(installRubyGemsUpdateSystemCmd, context)
	if err != nil {
		return packit.BuildResult{}, err
	}

	gemUpdateSystemCmd := strings.Join([]string{
		"gem",
		"update",
		"-N",
		"--system",
		rubyGemsVersion,
	}, " ")
	err = RunBashCmd(gemUpdateSystemCmd, context)
	if err != nil {
		return packit.BuildResult{}, err
	}

	gemCleanupCmd := strings.Join([]string{"gem", "cleanup"}, " ")
	err = RunBashCmd(gemCleanupCmd, context)
	if err != nil {
		return packit.BuildResult{}, err
	}

	err = InstallPuma(context, configuration, logger)
	if err != nil {
		return packit.BuildResult{}, err
	}

	gemInstallBundlerCmd := strings.Join([]string{
		"gem",
		"install",
		"-N",
		"--default",
		"bundler",
	}, " ")
	if bundlerVersion(context, configuration) != "" {
		gemInstallBundlerCmd = strings.Join([]string{
			gemInstallBundlerCmd,
			"-v",
			bundlerVersion(context, configuration),
		}, " ")
	}
	err = RunBashCmd(gemInstallBundlerCmd, context)
	if err != nil {
		return packit.BuildResult{}, err
	}

	err = configureBundlerPath(context, bundlerLayer, bundlerMajorVersion)
	if err != nil {
		return packit.BuildResult{}, err
	}

	bundleInstallCmd := strings.Join([]string{
		"bundle",
		"install",
	}, " ")
	err = RunBashCmd(bundleInstallCmd, context)
	if err != nil {
		return packit.BuildResult{}, err
	}

	bundleCleanCmd := strings.Join([]string{
		"bundle",
		"clean",
	}, " ")
	err = RunBashCmd(bundleCleanCmd, context)
	if err != nil {
		return packit.BuildResult{}, err
	}

	buildResult := packit.BuildResult{
		Plan: context.Plan,
		Layers: []packit.Layer{
			bundlerLayer,
		},
	}

	pumaProcess, err := CreatePumaProcess(context, configuration, logger)
	if err == nil && pumaProcess.Type == "web" && pumaProcess.Command != "" {
		buildResult.Processes = append(buildResult.Processes, pumaProcess)
	}
	return buildResult, nil
}

// RunBashCmd executes a command in an interactive BASH shell
func RunBashCmd(command string, context packit.BuildContext) error {
	logger := rvm.NewLogEmitter(os.Stdout)

	cmd := exec.Command("bash")
	cmd.Dir = context.WorkingDir
	cmd.Args = append(
		cmd.Args,
		"--login",
		"-c",
		strings.Join(
			[]string{
				"source",
				filepath.Join(os.ExpandEnv("$rvm_path"), "profile.d", "rvm"),
				"&&",
				command,
			},
			" ",
		),
	)
	cmd.Env = os.Environ()

	logger.Process("Executing: %s", strings.Join(cmd.Args, " "))

	stdoutPipe, _ := cmd.StdoutPipe()
	var stderrBuf bytes.Buffer
	cmd.Stderr = io.MultiWriter(&stderrBuf)

	if err := cmd.Start(); err != nil {
		logger.Process("Failed to start command: %s", cmd.String())
		logger.Break()
		return err
	}

	stdoutReader := bufio.NewReader(stdoutPipe)
	stdoutLine, err := stdoutReader.ReadString('\n')
	for err == nil {
		logger.Subprocess(stdoutLine)
		stdoutLine, err = stdoutReader.ReadString('\n')
	}
	err = cmd.Wait()

	if err != nil {
		logger.Process("Command failed: %s", cmd.String())
		logger.Process("Error status code: %s", err.Error())
		if len(stderrBuf.String()) > 0 {
			logger.Process("Command output on stderr:")
			logger.Subprocess(stderrBuf.String())
		}
		return err
	}

	logger.Break()

	return nil
}

func bundlerVersion(context packit.BuildContext, configuration Configuration) string {
	bundlerVersion := configuration.DefaultBundlerVersion
	for _, entry := range context.Plan.Entries {
		if entry.Name == "rvm-bundler" {
			bundlerVersion = fmt.Sprintf("%v", entry.Version)
		}
	}
	return bundlerVersion
}

func configureBundlerPath(context packit.BuildContext, bundlerLayer packit.Layer, bundlerMajorVersion int) error {
	cmdComponents := []string{"bundle", "config"}
	if bundlerMajorVersion > 1 {
		cmdComponents = append(cmdComponents, "set")
	}
	cmdComponents = append(cmdComponents, "--local", "path", bundlerLayer.Path)
	err := RunBashCmd(strings.Join(cmdComponents, " "), context)
	if err != nil {
		return err
	}
	return nil
}


text:
@article{roest_comparison_2019,
 author = {Roest, Annelieke M. and Vries, Ymkje Anna and Lim, Carmen C. W. and Wittchen, Hans‐Ulrich and Stein, Dan J. and Adamowski, Tomasz and Al‐Hamzawi, Ali and Bromet, Evelyn J. and Viana, Maria Carmen and Girolamo, Giovanni and Demyttenaere, Koen and Florescu, Silvia and Gureje, Oye and Haro, Josep Maria and Hu, Chiyi and Karam, Elie G. and Caldas‐de‐Almeida, José Miguel and Kawakami, Norito and Lépine, Jean Pierre and Levinson, Daphna and Medina‐Mora, Maria E. and Navarro‐Mateu, Fernando and O’Neill, Siobhan and Piazza, Marina and Posada‐Villa, José A. and Slade, Tim and Torres, Yolanda and Kessler, Ronald C. and Scott, Kate M. and Jonge, Peter and On behalf of the WHO World Mental Health Survey Collaborators},
 doi = {10.1002/da.22885},
 issn = {1091-4269, 1520-6394},
 journal = {Depression and Anxiety},
 language = {en},
 month = {June},
 number = {6},
 pages = {499--510},
 title = {A comparison of DSM‐5 and DSM‐IV agoraphobia in the World Mental Health Surveys},
 url = {https://onlinelibrary.wiley.com/doi/abs/10.1002/da.22885},
 urldate = {2021-03-27},
 volume = {36},
 year = {2019}
}


text:
@article{vazquez2013emperor,
  title={EMPeror: a tool for visualizing high-throughput microbial community data},
  author={V{\'a}zquez-Baeza, Yoshiki and Pirrung, Meg and Gonzalez, Antonio and Knight, Rob},
  journal={Gigascience},
  volume={2},
  number={1},
  pages={16},
  year={2013},
  publisher={BioMed Central},
  doi={10.1186/2047-217X-2-16}
}

@article{vazquez2017bringing,
  title={Bringing the dynamic microbiome to life with animations},
  author={V{\'a}zquez-Baeza, Yoshiki and Gonzalez, Antonio and Smarr, Larry and McDonald, Daniel and Morton, James T and Navas-Molina, Jose A and Knight, Rob},
  journal={Cell host \& microbe},
  volume={21},
  number={1},
  pages={7--10},
  year={2017},
  publisher={Elsevier},
  doi={10.1016/j.chom.2016.12.009}
}

gha_language: Python