text:
package gov.nih.nci.calims2.domain.administration.customerservice;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.IndexColumn;
import org.joda.time.DateTime;

import gov.nih.nci.calims2.domain.interfaces.DisplayableEntity;
import gov.nih.nci.calims2.domain.interfaces.EntityWithId;
import gov.nih.nci.calims2.domain.interfaces.EntityWithNotes;
/**
*
**/

@SuppressWarnings("deprecation")
@Entity
@Table(name = "SERVICE")

public class Service extends DisplayableEntity implements  EntityWithNotes {
/**
* An attribute to allow serialization of the domain objects.
*/
private static final long serialVersionUID = 1234567890L;
  /**
*
**/
  private DateTime endDate;
  /**
* Retrieves the value of the endDate attribute.
* @return endDate
**/

  @Column(name = "ENDDATE")
@org.hibernate.annotations.Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")

  public DateTime getEndDate() {
  return endDate;
  }
  /**
* Sets the value of endDate attribute.
* @param endDate .
**/
  public void setEndDate(DateTime
  endDate) {
  this.endDate = endDate;
  }
  /**
*
**/
  private Boolean isTemplate;
  /**
* Retrieves the value of the isTemplate attribute.
* @return isTemplate
**/

  @Column(name = "ISTEMPLATE", length = EntityWithId.COLUMNLENGTH)

  public Boolean getIsTemplate() {
  return isTemplate;
  }
  /**
* Sets the value of isTemplate attribute.
* @param isTemplate .
**/
  public void setIsTemplate(Boolean
  isTemplate) {
  this.isTemplate = isTemplate;
  }
  /**
*
**/
  private DateTime startDate;
  /**
* Retrieves the value of the startDate attribute.
* @return startDate
**/

  @Column(name = "STARTDATE")
@org.hibernate.annotations.Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")

  public DateTime getStartDate() {
  return startDate;
  }
  /**
* Sets the value of startDate attribute.
* @param startDate .
**/
  public void setStartDate(DateTime
  startDate) {
  this.startDate = startDate;
  }
  /**
*
**/
  private gov.nih.nci.calims2.domain.administration.customerservice.enumeration.ServiceStatus status;
  /**
* Retrieves the value of the status attribute.
* @return status
**/

  @Enumerated(EnumType.STRING)
@Column(name = "STATUS", length = EntityWithId.COLUMNLENGTH)

  public gov.nih.nci.calims2.domain.administration.customerservice.enumeration.ServiceStatus getStatus() {
  return status;
  }
  /**
* Sets the value of status attribute.
* @param status .
**/
  public void setStatus(gov.nih.nci.calims2.domain.administration.customerservice.enumeration.ServiceStatus
  status) {
  this.status = status;
  }

        /**
* An associated gov.nih.nci.calims2.domain.administration.customerservice.CustomerRequest object.
**/
        private gov.nih.nci.calims2.domain.administration.customerservice.CustomerRequest customerRequest;
        /**
* Retrieves the value of the customerRequest attribute.
* @return customerRequest
**/

        @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CUSTOMERREQUEST_FK")
@org.hibernate.annotations.ForeignKey(name = "SERVICCUSTOM_FK")

        public gov.nih.nci.calims2.domain.administration.customerservice.CustomerRequest getCustomerRequest() {
        return customerRequest;
        }

        /**
* Sets the value of customerRequest attribute.
* @param customerRequest .
**/
        public void setCustomerRequest(gov.nih.nci.calims2.domain.administration.customerservice.CustomerRequest customerRequest) {
        this.customerRequest = customerRequest;
        }

        /**
* An associated gov.nih.nci.calims2.domain.administration.customerservice.ServiceItem object.'s collection.
**/
        private Set<gov.nih.nci.calims2.domain.administration.customerservice.ServiceItem> serviceItemCollection = new HashSet<gov.nih.nci.calims2.domain.administration.customerservice.ServiceItem>();
        /**
* Retrieves the value of the serviceItemCollection attribute.
* @return serviceItemCollection
**/
        @OneToMany(fetch = FetchType.LAZY, mappedBy = "service")
@Fetch(FetchMode.SUBSELECT)

        public Set<gov.nih.nci.calims2.domain.administration.customerservice.ServiceItem> getServiceItemCollection() {
        return serviceItemCollection;
        }

        /**
* Sets the value of serviceItemCollection attribute.
* @param serviceItemCollection .
**/
        public void setServiceItemCollection(Set<gov.nih.nci.calims2.domain.administration.customerservice.ServiceItem> serviceItemCollection) {
        this.serviceItemCollection = serviceItemCollection;
        }

        /**
* An associated gov.nih.nci.calims2.domain.common.Document object.'s collection.
**/
        private Set<gov.nih.nci.calims2.domain.common.Document> documentCollection = new HashSet<gov.nih.nci.calims2.domain.common.Document>();
        /**
* Retrieves the value of the documentCollection attribute.
* @return documentCollection
**/
        @OneToMany(fetch = FetchType.LAZY, mappedBy = "service")
@Fetch(FetchMode.SUBSELECT)

        public Set<gov.nih.nci.calims2.domain.common.Document> getDocumentCollection() {
        return documentCollection;
        }

        /**
* Sets the value of documentCollection attribute.
* @param documentCollection .
**/
        public void setDocumentCollection(Set<gov.nih.nci.calims2.domain.common.Document> documentCollection) {
        this.documentCollection = documentCollection;
        }

        /**
* An associated gov.nih.nci.calims2.domain.administration.Organization object.
**/
        private gov.nih.nci.calims2.domain.administration.Organization organization;
        /**
* Retrieves the value of the organization attribute.
* @return organization
**/

        @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ORGANIZATION_FK")
@org.hibernate.annotations.ForeignKey(name = "SERVICORGANI_FK")

        public gov.nih.nci.calims2.domain.administration.Organization getOrganization() {
        return organization;
        }

        /**
* Sets the value of organization attribute.
* @param organization .
**/
        public void setOrganization(gov.nih.nci.calims2.domain.administration.Organization organization) {
        this.organization = organization;
        }

        private Set<gov.nih.nci.calims2.domain.common.Notes> notesCollection = new HashSet<gov.nih.nci.calims2.domain.common.Notes>();
        @IndexColumn(name="LIST_INDEX")
        @CollectionOfElements(fetch=FetchType.LAZY)
        @JoinTable(name="NOTES_SERVICE",joinColumns=@JoinColumn(name="ID_NOTES_SERVICE"))
        @ForeignKey(name="FK_NOTES_SERVICE")
        @Fetch(FetchMode.SUBSELECT)
        public Set<gov.nih.nci.calims2.domain.common.Notes> getNotesCollection() {
        return notesCollection;
        }
        public void setNotesCollection(Set<gov.nih.nci.calims2.domain.common.Notes> notesCollection) {
             this.notesCollection = notesCollection;
        }

        /**
* An associated gov.nih.nci.calims2.domain.common.Type object.
**/
        private gov.nih.nci.calims2.domain.common.Type type;
        /**
* Retrieves the value of the type attribute.
* @return type
**/
        @NotNull(message = "{NotNull.gov.nih.nci.calims2.domain.administration.customerservice.Service.type}")

        @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "TYPE_FK")
@org.hibernate.annotations.ForeignKey(name = "SERVICTYPE_FK")

        public gov.nih.nci.calims2.domain.common.Type getType() {
        return type;
        }

        /**
* Sets the value of type attribute.
* @param type .
**/
        public void setType(gov.nih.nci.calims2.domain.common.Type type) {
        this.type = type;
        }

}

redpajama_set_name: RedPajamaGithub


text:
import java.util.ArrayList;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class SkilledEmployee extends Employee{
    public ArrayList skillList = new ArrayList();

    public void setSkill(String skill) throws InvalidSkillException {
        boolean valid = false;
        if (skill == null || skill.length() < 5){
            valid = false;
        }
        else{
            valid = true;
        }
        if (!valid){
            throw new InvalidSkillException(skill+
                " is not valid for the "+this.getJobTitle()+" job.");
        }
        else {
            skillList.add(skill);
        }
    }

    public ArrayList getSkills(){
        return skillList;
    }

     public void print(){
         super.print();
        System.out.println("Employee has the following skills: ");
        for(Object obj : skillList){
            System.out.println("\t"+ obj);
        }
    }

}


text:
package os

import (
	"context"
	"crypto/rand"
	"errors"
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/google/gnxi/gnoi/os/pb"
	"github.com/google/gnxi/utils/mockos"
	mockosPb "github.com/google/gnxi/utils/mockos/pb"
	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"google.golang.org/protobuf/testing/protocmp"
)

// Equal checks if two data structures are equal, ignoring protobuf internal variables.
func Equal(x, y interface{}) bool {
	return cmp.Equal(x, y, protocmp.Transform(), cmpopts.IgnoreUnexported(Server{}), cmpopts.IgnoreUnexported(installResult{}), cmpopts.EquateErrors())
}

// Diff returns the diff between two data structures, ignoring protobuf internal variables.
func Diff(x, y interface{}) string {
	return cmp.Diff(x, y, protocmp.Transform(), cmpopts.IgnoreUnexported(Server{}), cmpopts.IgnoreUnexported(installResult{}), cmpopts.EquateErrors())
}

type installResult struct {
	res *pb.InstallResponse
	err error
}

type mockTransferStream struct {
	pb.OS_InstallServer
	response      chan *pb.InstallResponse
	errorReq      *pb.InstallRequest
	result        chan *pb.InstallResponse
	os            *mockos.OS
	forceTransfer bool
}

func (m mockTransferStream) Send(res *pb.InstallResponse) error {
	switch res.Response.(type) {
	case *pb.InstallResponse_Validated:
		m.result <- res
	case *pb.InstallResponse_InstallError:
		m.result <- res
	default:
		m.response <- res
	}
	return nil
}

func (m mockTransferStream) Recv() (*pb.InstallRequest, error) {
	if request := m.errorReq; request != nil {
		return request, nil
	}
	select {
	case res := <-m.response:
		switch res.Response.(type) {
		case *pb.InstallResponse_TransferProgress:
			return &pb.InstallRequest{Request: &pb.InstallRequest_TransferEnd{}}, nil
		case *pb.InstallResponse_TransferReady:
			var out []byte
			if m.os.MockOS.Padding != nil {
				out, _ = proto.Marshal(&m.os.MockOS)
			} else {
				out = make([]byte, receiveChunkSizeAck)
				rand.Read(out)
			}
			return &pb.InstallRequest{Request: &pb.InstallRequest_TransferContent{TransferContent: out}}, nil
		}
	default:
		var transferReq = &pb.TransferRequest{}
		if !m.forceTransfer {
			transferReq = &pb.TransferRequest{Version: m.os.MockOS.Version}
		}
		return &pb.InstallRequest{Request: &pb.InstallRequest_TransferRequest{TransferRequest: transferReq}}, nil
	}
	return nil, nil
}

func TestNewServer(t *testing.T) {
	test := struct {
		settings *Settings
		want     *Server
	}{
		settings: &Settings{
			FactoryVersion: "1.0.0a",
		},
		want: &Server{
			installToken: make(chan bool, 1),
			manager: &Manager{
				osMap:          map[string]bool{"1.0.0a": true},
				factoryVersion: "1.0.0a",
				runningVersion: "1.0.0a",
			},
		},
	}
	got := NewServer(test.settings)
	if !Equal(test.want, got) {
		t.Errorf("NewServer(%v): (-want +got):\n%s", test.settings, Diff(test.want, got))
	}
}

func TestTargetActivate(t *testing.T) {
	settings := &Settings{
		FactoryVersion:    "1",
		InstalledVersions: []string{"1.0.0a", "2.0.1c"},
	}
	server := NewServer(settings)
	tests := []struct {
		request *pb.ActivateRequest
		want    *pb.ActivateResponse
	}{
		{
			request: &pb.ActivateRequest{
				Version: "1.0.0a",
			},
			want: &pb.ActivateResponse{Response: &pb.ActivateResponse_ActivateOk{}},
		},
		{
			request: &pb.ActivateRequest{
				Version: "99.0a",
			},
			want: &pb.ActivateResponse{Response: &pb.ActivateResponse_ActivateError{
				ActivateError: &pb.ActivateError{Type: pb.ActivateError_NON_EXISTENT_VERSION},
			}},
		},
		{
			request: &pb.ActivateRequest{
				Version: "",
			},
			want: &pb.ActivateResponse{Response: &pb.ActivateResponse_ActivateError{
				ActivateError: &pb.ActivateError{Type: pb.ActivateError_NON_EXISTENT_VERSION},
			}},
		},
	}
	for _, test := range tests {
		got, _ := server.Activate(context.Background(), test.request)
		if !Equal(test.want.Response, got.Response) {
			t.Errorf("Activate(context.Background(), %s): (-want +got):\n%s", test.request, Diff(test.want.Response, got.Response))
		}
	}
}

func TestTargetVerify(t *testing.T) {
	tests := []struct {
		settings *Settings
		want     *pb.VerifyResponse
	}{
		{
			settings: &Settings{
				FactoryVersion: "1",
			},
			want: &pb.VerifyResponse{
				Version: "1",
			},
		},
	}
	for _, test := range tests {
		server := NewServer(test.settings)
		got, _ := server.Verify(context.Background(), &pb.VerifyRequest{})
		if !Equal(test.want, got) {
			t.Errorf("Verify(context.Background(), &pb.VerifyRequest{}): (-want +got):\n%s", Diff(test.want, got))
		}
	}
}

func TestTargetVerifyFail(t *testing.T) {
	tests := []struct {
		settings *Settings
		want     *pb.VerifyResponse
	}{
		{
			settings: &Settings{
				FactoryVersion: "1",
			},
			want: &pb.VerifyResponse{
				Version:               "1",
				ActivationFailMessage: "Failed to activate OS...",
			},
		},
	}
	for _, test := range tests {
		server := NewServer(test.settings)
		server.manager.activationFailMessage = "Failed to activate OS..."
		got, _ := server.Verify(context.Background(), &pb.VerifyRequest{})
		if !Equal(test.want, got) {
			t.Errorf("Verify(context.Background(), &pb.VerifyRequest{}): (-want +got):\n%s", Diff(test.want, got))
		}
	}
}

func TestTargetActivateAndVerify(t *testing.T) {
	test := struct {
		settings *Settings
		want     *pb.VerifyResponse
	}{
		settings: &Settings{
			FactoryVersion: "1",
		},
		want: &pb.VerifyResponse{
			Version:               "1",
			ActivationFailMessage: "Failed to activate OS...",
		},
	}
	server := NewServer(test.settings)
	server.manager.Install("1.0.1a", "Failed to activate OS...")
	server.Activate(context.Background(), &pb.ActivateRequest{Version: "1.0.1a"})
	got, _ := server.Verify(context.Background(), &pb.VerifyRequest{})
	if !Equal(test.want, got) {
		t.Errorf("Verify(context.Background(), &pb.VerifyRequest{}): (-want +got):\n%s", Diff(test.want, got))
	}
}

func TestTargetReceiveOS(t *testing.T) {
	buf := make([]byte, receiveChunkSizeAck)
	rand.Read(buf)
	oS := &mockos.OS{MockOS: mockosPb.MockOS{
		Version: "1.0.2a",
		Cookie:  "cookiestring",
		Padding: buf,
	}}
	oS.Hash()
	tests := []struct {
		name   string
		stream *mockTransferStream
		err    error
	}{
		{
			name: "sending TransferContent request",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				os:       oS,
			},
			err: nil,
		},
		{
			name: "sending unexpected request type",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				errorReq: &pb.InstallRequest{Request: &pb.InstallRequest_TransferRequest{}}, // Unexpected request after transfer begins.
				os:       oS,
			},
			err: cmpopts.AnyError,
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			test.stream.response <- &pb.InstallResponse{Response: &pb.InstallResponse_TransferReady{}}
			_, err := ReceiveOS(test.stream)
			if !Equal(test.err, err) {
				t.Errorf("ReceiveOS(stream): (-want +got):\n%s", Diff(test.err, err))
			}
		})
	}
}

func TestTargetInstall(t *testing.T) {
	buf := make([]byte, receiveChunkSizeAck)
	rand.Read(buf)
	oS := &mockos.OS{MockOS: mockosPb.MockOS{
		Version: "1.0.2a",
		Cookie:  "cookiestring",
		Padding: buf,
	}}
	oS.Hash()
	incompatibleOS := &mockos.OS{MockOS: mockosPb.MockOS{
		Version:      "1.0.2b",
		Cookie:       "cookiestring",
		Padding:      buf,
		Incompatible: true,
	}}
	incompatibleOS.Hash()
	factoryOS := &mockos.OS{MockOS: mockosPb.MockOS{
		Version: "1.0.0a",
		Cookie:  "cookiestring",
		Padding: buf,
	}}
	factoryOS.Hash()
	tests := []struct {
		name   string
		stream *mockTransferStream
		want   *installResult
	}{
		{
			name: "transfer compatible os with valid hash",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				os:       oS,
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_Validated{Validated: &pb.Validated{Version: oS.Version}}},
			},
		},
		{
			name: "send bad request instead of InstallRequest_TransferRequest",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				errorReq: &pb.InstallRequest{Request: nil}, // Unexpected request.
				os:       oS,
			},
			want: &installResult{
				err: errors.New("Failed to receive TransferRequest"),
			},
		},
		{
			name: "transferring already running os",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				os:       factoryOS,
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_Validated{Validated: &pb.Validated{Version: factoryOS.Version}}},
			},
		},
		{
			name: "transferring already installed os",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				os: &mockos.OS{MockOS: mockosPb.MockOS{
					Version: "1.0.3c",
				}},
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_Validated{Validated: &pb.Validated{Version: "1.0.3c"}}},
			},
		},
		{
			name: "transferring os with bad hash",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				os: &mockos.OS{MockOS: mockosPb.MockOS{
					Version: "1.0.2b",
					Cookie:  "cookiestring",
					Padding: buf,
					Hash:    []byte("BADHASH"),
				}},
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_InstallError{InstallError: &pb.InstallError{Type: pb.InstallError_INTEGRITY_FAIL}}},
			},
		},
		{
			name: "transferring os with incompatible field true",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				os:       incompatibleOS,
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_InstallError{InstallError: &pb.InstallError{Type: pb.InstallError_INCOMPATIBLE, Detail: "Unsupported OS Version"}}},
			},
		},
		{
			name: "transferring random bytes instead of os package",
			stream: &mockTransferStream{
				response: make(chan *pb.InstallResponse, 1),
				result:   make(chan *pb.InstallResponse, 1),
				os:       &mockos.OS{MockOS: mockosPb.MockOS{}},
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_InstallError{InstallError: &pb.InstallError{Type: pb.InstallError_PARSE_FAIL}}},
			},
		},
		{
			name: "force transferring os without version specified",
			stream: &mockTransferStream{
				response:      make(chan *pb.InstallResponse, 1),
				result:        make(chan *pb.InstallResponse, 1),
				os:            factoryOS,
				forceTransfer: true,
			},
			want: &installResult{
				res: &pb.InstallResponse{Response: &pb.InstallResponse_InstallError{
					InstallError: &pb.InstallError{Type: pb.InstallError_INSTALL_RUN_PACKAGE},
				}},
			},
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			server := NewServer(&Settings{FactoryVersion: "1.0.0a", InstalledVersions: []string{"1.0.3c"}})
			got := &installResult{
				err: server.Install(test.stream),
			}
			if !test.stream.forceTransfer {
				close(test.stream.result)
			}
			got.res = <-test.stream.result
			if !Equal(test.want, got) {
				t.Errorf("Install(stream pb.OS_InstallServer): (-want +got):\n%s", Diff(test.want, got))
			}
		})
	}
}

// TestMultipleInstalls tests for mutual exclusion in the install service.
func TestMultipleInstalls(t *testing.T) {
	t.Run("testing mutual exclusion in install service", func(t *testing.T) {
		buf := make([]byte, receiveChunkSizeAck)
		rand.Read(buf)
		oS := &mockos.OS{MockOS: mockosPb.MockOS{
			Version: "1.0.2a",
			Cookie:  "cookiestring",
			Padding: buf,
		}}
		oS.Hash()
		server := NewServer(&Settings{FactoryVersion: "1.0.0a"})
		s1 := &mockTransferStream{
			response: make(chan *pb.InstallResponse, 1),
			result:   make(chan *pb.InstallResponse, 1),
			os:       oS,
		}
		s2 := &mockTransferStream{
			response: make(chan *pb.InstallResponse, 1),
			result:   make(chan *pb.InstallResponse, 1),
			os:       oS,
		}
		go server.Install(s1)
		go server.Install(s2)
		s1res := <-s1.result
		s2res := <-s2.result
		expect := &pb.InstallResponse{Response: &pb.InstallResponse_InstallError{InstallError: &pb.InstallError{Type: pb.InstallError_INSTALL_IN_PROGRESS}}}

		if !Equal(expect, s1res) && !Equal(expect, s2res) || Diff(expect, s1res) == Diff(expect, s2res) {
			t.Errorf("Install(stream pb.OS_InstallServer): (-want +got):\n%s\n%s", Diff(expect, s1res), Diff(expect, s2res))
		}
	})
}


text:
/**
 * We need to have browserify-shim know about our (potenitally) digested blockly
 * file so that it properly exports Blockly. We do that by using glob to find the
 * file and then use that to dynamically create our browserify shim config.
 */
var glob = require('glob');

module.exports = {};
// get potentically digested file
var files = glob.sync(__dirname + '/../../build/package/js/blockly*.js');
if (files.length !== 1) {
  throw new Error('Expected 1 blockly file');
}
var blocklyFile = files[0];
module.exports[blocklyFile] = { exports: 'Blockly' };


text:
import os
import shutil
import ctypes
import sys
import re
import platform
import subprocess
import threading
import queue
import datetime
import time
import renderdoc as rd
from . import util
from . import testcase
from .logging import log
from pathlib import Path

def get_tests():
    testcases = []

    for m in sys.modules.values():
        for name in m.__dict__:
            obj = m.__dict__[name]
            if isinstance(obj, type) and issubclass(obj, testcase.TestCase) and obj != testcase.TestCase and not obj.internal:
                testcases.append(obj)

    testcases.sort(key=lambda t: (t.slow_test,t.__name__))

    return testcases

RUNNER_TIMEOUT = 90    # Require output every X seconds
RUNNER_DEBUG = False   # Debug test runner running by printing messages to track it

def _enqueue_output(process: subprocess.Popen, out, q: queue.Queue):
    try:
        for line in iter(out.readline, b''):
            q.put(line)

            if process.returncode is not None:
                break
    except Exception:
        pass

def _run_test(testclass, failedcases: list):
    name = testclass.__name__

    # Fork the interpreter to run the test, in case it crashes we can catch it.
    # We can re-run with the same parameters
    args = sys.argv.copy()
    args.insert(0, sys.executable)

    # Add parameter to run the test itself
    args.append('--internal_run_test')
    args.append(name)

    test_run = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

    output_threads = []

    test_stdout = queue.Queue()
    t = threading.Thread(target=_enqueue_output, args=(test_run, test_run.stdout, test_stdout))
    t.daemon = True  # thread dies with the program
    t.start()

    output_threads.append(t)

    test_stderr = queue.Queue()
    t = threading.Thread(target=_enqueue_output, args=(test_run, test_run.stderr, test_stderr))
    t.daemon = True  # thread dies with the program
    t.start()

    output_threads.append(t)

    if RUNNER_DEBUG:
        print("Waiting for test runner to complete...")

    out_pending = ""
    err_pending = ""

    while test_run.poll() is None:
        out = err = ""

        if RUNNER_DEBUG:
            print("Checking runner output...")

        try:
            out = test_stdout.get(timeout=RUNNER_TIMEOUT)
            while not test_stdout.empty():
                out += test_stdout.get_nowait()

                if test_run.poll() is not None:
                    break
        except queue.Empty:
            out = None  # No output

        try:
            err = None
            while not test_stderr.empty():
                if err is None:
                    err = ''
                err += test_stderr.get_nowait()

                if test_run.poll() is not None:
                    break
        except queue.Empty:
            err = None  # No output

        if RUNNER_DEBUG:
            if out is not None:
                print("Test stdout: {}".format(out))

            if err is not None:
                print("Test stderr: {}".format(err))
        else:
            if out is not None:
                out_pending += out
            if err is not None:
                err_pending += err

        while True:
            try:
                nl = out_pending.index('\n')
                line = out_pending[0:nl]
                out_pending = out_pending[nl+1:]
                line = line.replace('\r', '')
                sys.stdout.write(line + '\n')
                sys.stdout.flush()
            except:
                break

        while True:
            try:
                nl = err_pending.index('\n')
                line = err_pending[0:nl]
                err_pending = err_pending[nl+1:]
                line = line.replace('\r', '')
                sys.stderr.write(line + '\n')
                sys.stderr.flush()
            except:
                break

        if out is None and err is None and test_run.poll() is None:
            log.error('Timed out, no output within {}s elapsed'.format(RUNNER_TIMEOUT))
            test_run.kill()
            test_run.communicate()
            raise subprocess.TimeoutExpired(' '.join(args), RUNNER_TIMEOUT)

    if RUNNER_DEBUG:
        print("Test runner has finished")

    # If we couldn't get the return code, something went wrong in the timeout above
    # and the program never exited. Try once more to kill it then bail
    if test_run.returncode is None:
        test_run.kill()
        test_run.communicate()
        raise RuntimeError('INTERNAL ERROR: Couldn\'t get test return code')

    for t in output_threads:
        t.join(10)

        if t.is_alive():
            raise RuntimeError('INTERNAL ERROR: Subprocess output thread couldn\'t be closed')

    # Return code of 0 means we exited cleanly, nothing to do
    if test_run.returncode == 0:
        pass
    # Return code of 1 means the test failed, but we have already logged the exception
    # so we just need to mark this test as failed
    elif test_run.returncode == 1:
        failedcases.append(testclass)
    else:
        raise RuntimeError('Test did not exit cleanly while running, possible crash. Exit code {}'
                           .format(test_run.returncode))

def fetch_tests():
    output = subprocess.run([util.get_demos_binary(), '--list-raw'], stdout=subprocess.PIPE).stdout

    # Skip the header, grab all the remaining lines
    tests = str(output, 'utf-8').splitlines()[1:]

    # Split the TSV values and store
    split_tests = [ test.split('\t') for test in tests ]

    return { x[0]: (x[1] == 'True', x[2]) for x in split_tests }

def run_tests(test_include: str, test_exclude: str, in_process: bool, slow_tests: bool, debugger: bool):
    start_time = datetime.datetime.now(datetime.timezone.utc)

    rd.InitialiseReplay(rd.GlobalEnvironment(), [])

    # On windows, disable error reporting
    if 'windll' in dir(ctypes):
        ctypes.windll.kernel32.SetErrorMode(1 | 2)  # SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX

    # clean up artifacts and temp folder
    if os.path.exists(util.get_artifact_dir()):
        shutil.rmtree(util.get_artifact_dir(), ignore_errors=True)

    if os.path.exists(util.get_tmp_dir()):
        shutil.rmtree(util.get_tmp_dir(), ignore_errors=True)

    log.add_output(util.get_artifact_path("output.log.html"))

    for file in ['testresults.css', 'testresults.js']:
        shutil.copyfile(os.path.join(os.path.dirname(__file__), file), util.get_artifact_path(file))

    log.rawprint('<meta charset="utf-8"><!-- header to prevent output from being processed as html -->' +
                 '<body><link rel="stylesheet" type="text/css" media="all" href="testresults.css">' +
                 '<script src="testresults.js"></script>' +
                 '<script id="logoutput" type="preformatted">\n\n\n', with_stdout=False)

    plat = os.name
    if plat == 'nt' or 'Windows' in platform.platform():
        plat = 'win32'

    log.header("Tests running for RenderDoc Version {} ({})".format(rd.GetVersionString(), rd.GetCommitHash()))
    log.header("On {}".format(platform.platform()))

    log.comment("plat={} git={}".format(platform.platform(), rd.GetCommitHash()))

    driver = ""

    for api in rd.GraphicsAPI:
        v = rd.GetDriverInformation(api)
        log.print("{} driver: {} {}".format(str(api), str(v.vendor), v.version))

        # Take the first version number we get, but prefer GL as it's universally available and
        # Produces a nice version number & device combination
        if (api == rd.GraphicsAPI.OpenGL or driver == "") and v.vendor != rd.GPUVendor.Unknown:
            driver = v.version

    log.comment("driver={}".format(driver))

    log.print("Demos running from {}".format(util.get_demos_binary()))

    layerInfo = rd.VulkanLayerRegistrationInfo()
    if rd.NeedVulkanLayerRegistration(layerInfo):
        log.print("Vulkan layer needs to be registered: {}".format(str(layerInfo.flags)))
        log.print("My JSONs: {}, Other JSONs: {}".format(layerInfo.myJSONs, layerInfo.otherJSONs))

        # Update the layer registration without doing anything special first - if running automated we might have
        # granted user-writable permissions to the system files needed to update. If possible we register at user
        # level.
        if layerInfo.flags & rd.VulkanLayerFlags.NeedElevation:
            rd.UpdateVulkanLayerRegistration(True)
        else:
            rd.UpdateVulkanLayerRegistration(False)

        # Check if it succeeded
        reg_needed = rd.NeedVulkanLayerRegistration(layerInfo)

        if reg_needed:
            if plat == 'win32':
                # On windows, try to elevate. This will mean a UAC prompt
                args = sys.argv.copy()
                args.append("--internal_vulkan_register")

                for i in range(len(args)):
                    if os.path.exists(args[i]):
                        args[i] = str(Path(args[i]).resolve())

                if 'renderdoccmd' in sys.executable:
                    args = ['vulkanlayer', '--register', '--system']

                ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, ' '.join(args), None, 1)

                time.sleep(10)
            else:
                log.print("Couldn't register vulkan layer properly, might need admin rights")
                sys.exit(1)

        reg_needed = rd.NeedVulkanLayerRegistration(layerInfo)

        if reg_needed:
            log.print("Couldn't register vulkan layer properly, might need admin rights")
            sys.exit(1)

    os.environ['RENDERDOC_DEMOS_DATA'] = util.get_data_path('demos')

    testcase.TestCase.set_test_list(fetch_tests())

    testcases = get_tests()

    include_regexp = re.compile(test_include, re.IGNORECASE)
    exclude_regexp = None
    if test_exclude != '':
        exclude_regexp = re.compile(test_exclude, re.IGNORECASE)
        log.print("Running tests matching '{}' and not matching '{}'".format(test_include, test_exclude))
    else:
        log.print("Running tests matching '{}'".format(test_include))

    failedcases = []
    skippedcases = []
    runcases = []

    ver = 0

    if plat == 'win32':
        try:
            ver = sys.getwindowsversion().major
            if ver == 6:
                ver = 7  # Windows 7 is 6.1
        except AttributeError:
            pass

    for testclass in testcases:
        name = testclass.__name__

        instance = testclass()

        supported, unsupported_reason = instance.check_support()

        if not supported:
            log.print("Skipping {} as {}".format(name, unsupported_reason))
            skippedcases.append(testclass)
            continue

        if not include_regexp.search(name):
            log.print("Skipping {} as it doesn't match '{}'".format(name, test_include))
            skippedcases.append(testclass)
            continue

        if exclude_regexp is not None and exclude_regexp.search(name):
            log.print("Skipping {} as it matches '{}'".format(name, test_exclude))
            skippedcases.append(testclass)
            continue

        if not slow_tests and testclass.slow_test:
            log.print("Skipping {} as it is a slow test, which are not enabled".format(name))
            skippedcases.append(testclass)
            continue

        runcases.append((testclass, name, instance))

    for testclass, name, instance in runcases:
        # Print header (and footer) outside the exec so we know they will always be printed successfully
        log.begin_test(name)

        util.set_current_test(name)

        def do(debugMode):
            if in_process:
                instance.invoketest(debugMode)
            else:
                _run_test(testclass, failedcases)

        if debugger:
            do(True)
        else:
            try:
                do(False)
            except Exception as ex:
                log.failure(ex)
                failedcases.append(testclass)

        log.end_test(name)

    duration = datetime.datetime.now(datetime.timezone.utc) - start_time

    if len(failedcases) > 0:
        logfile = rd.GetLogFile()
        if os.path.exists(logfile):
            log.inline_file('RenderDoc log', logfile)

    log.comment("total={} fail={} skip={} time={}".format(len(testcases), len(failedcases), len(skippedcases), int(duration.total_seconds())))
    log.header("Tests complete summary: {} passed out of {} run from {} total in {}"
               .format(len(runcases)-len(failedcases), len(runcases), len(testcases), duration))
    if len(failedcases) > 0:
        log.print("Failed tests:")
    for testclass in failedcases:
        log.print("  - {}".format(testclass.__name__))

    # Print a proper footer if we got here
    log.rawprint('\n\n\n</script>', with_stdout=False)

    rd.ShutdownReplay()

    if len(failedcases) > 0:
        sys.exit(1)

    sys.exit(0)

def vulkan_register():
    rd.UpdateVulkanLayerRegistration(True)

def launch_remote_server():
    # Fork the interpreter to run the test, in case it crashes we can catch it.
    # We can re-run with the same parameters
    args = sys.argv.copy()
    args.insert(0, sys.executable)

    # Add parameter to run the remote server itself
    args.append('--internal_remote_server')

    # if we're running from renderdoccmd, invoke it properly
    if 'renderdoccmd' in sys.executable:
        # run_tests.py
        # --renderdoc
        # <renderdoc_path>
        # --pyrenderdoc
        # <pyrenderdoc_path>
        del args[1:6]
        args.insert(1, 'test')
        args.insert(2, 'functional')

    subprocess.Popen(args)
    return

def become_remote_server():
    rd.BecomeRemoteServer('localhost', None, None)

def internal_run_test(test_name):
    testcases = get_tests()

    log.add_output(util.get_artifact_path("output.log.html"))

    for testclass in testcases:
        if testclass.__name__ == test_name:
            globalenv = rd.GlobalEnvironment()
            globalenv.enumerateGPUs = False
            rd.InitialiseReplay(globalenv, [])

            log.begin_test(test_name, print_header=False)

            util.set_current_test(test_name)

            try:
                instance = testclass()
                instance.invoketest(False)
                suceeded = True
            except Exception as ex:
                log.failure(ex)
                suceeded = False

            logfile = rd.GetLogFile()
            if os.path.exists(logfile):
                log.inline_file('RenderDoc log', logfile)

            log.end_test(test_name, print_footer=False)

            rd.ShutdownReplay()

            if suceeded:
                sys.exit(0)
            else:
                sys.exit(1)

    log.error("INTERNAL ERROR: Couldn't find '{}' test to run".format(test_name))


text:
function showOrganisationUnitGroupDetails( context ) {
  jQuery.post('getOrganisationUnitGroup.action', { id: context.id },
    function( json ) {
      setInnerHTML('nameField', json.organisationUnitGroup.name);
      setInnerHTML('shortNameField', json.organisationUnitGroup.shortName);
      setInnerHTML('codeField', json.organisationUnitGroup.code);
      setInnerHTML('memberCountField', json.organisationUnitGroup.memberCount);
      setInnerHTML('idField', json.organisationUnitGroup.uid);

      showDetails();
    });
}

// -----------------------------------------------------------------------------
// Remove organisation unit group
// -----------------------------------------------------------------------------

function removeOrganisationUnitGroup( context ) {
  removeItem(context.id, context.name, confirm_to_delete_org_unit_group, 'removeOrganisationUnitGroup.action');
}

function openUpdateOrganisationUnitGroupForm( context ) {
  location.href = 'openUpdateOrganisationUnitGroup.action?id=' + context.id;
}


text:
<?php

namespace PharmaIntelligence\GstandaardBundle\Model;

use PharmaIntelligence\GstandaardBundle\Model\om\BaseGsGekoppeldeTekstenUitWciaTabel25Peer;

class GsGekoppeldeTekstenUitWciaTabel25Peer extends BaseGsGekoppeldeTekstenUitWciaTabel25Peer
{
}


text:
* Add the FORCE_QT_API environment variable to keep using the Qt
  bindings selected with the QT_API variable and avoid switching
  to the currently imported bindings. This allows to have
  applications that import PySide and PyQt bindings at the same
  time (which is possible if both bindings are compiled for the
  same Qt version).

### Issues Closed

* [Issue 195](https://github.com/spyder-ide/qtpy/issues/195) - Errors in the Qt3D modules with PySide2 5.12.4+ and Python 2 ([PR 196](https://github.com/spyder-ide/qtpy/pull/196))
* [Issue 192](https://github.com/spyder-ide/qtpy/issues/192) - Binding Selection Logic ([PR 194](https://github.com/spyder-ide/qtpy/pull/194))

In this release 2 issues were closed.

### Pull Requests Merged

* [PR 196](https://github.com/spyder-ide/qtpy/pull/196) - PR: Don't load Qt3D modules for buggy versions of PySide2 ([195](https://github.com/spyder-ide/qtpy/issues/195))
* [PR 194](https://github.com/spyder-ide/qtpy/pull/194) - PR: Add FORCE_QT_API environment variable ([192](https://github.com/spyder-ide/qtpy/issues/192))

In this release 2 pull requests were closed.

----

## Version 1.8.0 (2019-06-12)

### New features

* Add support for several Qt 3D modules.

### Issues Closed

* [Issue 172](https://github.com/spyder-ide/qtpy/issues/172) - Support for Qt3D ([PR 191](https://github.com/spyder-ide/qtpy/pull/191))

In this release 1 issue was closed.

### Pull Requests Merged

* [PR 191](https://github.com/spyder-ide/qtpy/pull/191) - PR: Add Qt 3D bindings ([172](https://github.com/spyder-ide/qtpy/issues/172))

In this release 1 pull request was closed.

----

## Version 1.7.1 (2019-05-05)

### Pull Requests Merged

* [PR 189](https://github.com/spyder-ide/qtpy/pull/189) - PR: Skip testing PyQt4 and PySide in Python 3.5
* [PR 188](https://github.com/spyder-ide/qtpy/pull/188) - PR: Trivial maintenance tweaks
* [PR 187](https://github.com/spyder-ide/qtpy/pull/187) - PR: Avoid deprecated "from collections import MutableMapping"

In this release 3 pull requests were closed.

----

## Version 1.7.0 (2019-03-16)

### New features

* Add support for QtCharts.

### Pull Requests Merged

* [PR 186](https://github.com/spyder-ide/qtpy/pull/186) - PR: Generate PyPI long description from README.md
* [PR 183](https://github.com/spyder-ide/qtpy/pull/183) - PR: Add QtCharts module support
* [PR 182](https://github.com/spyder-ide/qtpy/pull/182) - PR: Prevent warnings for equivalent APIs
* [PR 176](https://github.com/spyder-ide/qtpy/pull/176) - PR: Don't warn about bindings change if user did not specify a binding

In this release 4 pull requests were closed.

----

## Version 1.6 (2019-01-12)

### New features

* Add support for QtQuickWidgets.

### Issues Closed

* [Issue 178](https://github.com/spyder-ide/qtpy/issues/178) - Error when import QtCore.__version__ in PySide2 ([PR 180](https://github.com/spyder-ide/qtpy/pull/180))

In this release 1 issue was closed.

### Pull Requests Merged

* [PR 181](https://github.com/spyder-ide/qtpy/pull/181) - PR: Restore QWebEngineSettings for PySide2
* [PR 180](https://github.com/spyder-ide/qtpy/pull/180) - PR: Add QtCore.__version__ for PySide2 ([178](https://github.com/spyder-ide/qtpy/issues/178))
* [PR 179](https://github.com/spyder-ide/qtpy/pull/179) - PR: Add QtQuickWidgets

In this release 3 pull requests were closed.

----

## Version 1.5.2 (2018-10-20)

### Pull Requests Merged

* [PR 175](https://github.com/spyder-ide/qtpy/pull/175) - PR: Fix tests
* [PR 174](https://github.com/spyder-ide/qtpy/pull/174) - PR: Add support for PySide2.QtOpenGL

In this release 2 pull requests were closed.

----

## Version 1.5.1 (2018-09-18)

### Issues Closed

* [Issue 170](https://github.com/spyder-ide/qtpy/issues/170) - Can't catch PythonQtError ([PR 173](https://github.com/spyder-ide/qtpy/pull/173))

In this release 1 issue was closed.

### Pull Requests Merged

* [PR 173](https://github.com/spyder-ide/qtpy/pull/173) - PR: Make PythonQtError inherit from RuntimeError to be easily catchable ([170](https://github.com/spyder-ide/qtpy/issues/170))

In this release 1 pull request was closed.

----

## Version 1.5 (2018-08-25)

### New features

* Add support for QtLocation, QtMultimediaWidgets, QtQml, QtQuick,
  QtWebChannel, QtWebSockets and QtXmlPatterns.
* Raise an error when trying to use the wrong combination of macOS
  and Qt versions.

### Issues Closed

* [Issue 155](https://github.com/spyder-ide/qtpy/issues/155) - Add warnings for Qt 5.9 in macOS 10.9 and Qt 5.11 and macOS 10.11 ([PR 168](https://github.com/spyder-ide/qtpy/pull/168))
* [Issue 153](https://github.com/spyder-ide/qtpy/issues/153) - Shim PyQt5 ToPyDateTime for compatibility with PySide2 ([PR 169](https://github.com/spyder-ide/qtpy/pull/169))
* [Issue 123](https://github.com/spyder-ide/qtpy/issues/123) - Wrap QWebChannel module ([PR 157](https://github.com/spyder-ide/qtpy/pull/157))

In this release 3 issues were closed.

### Pull Requests Merged

* [PR 169](https://github.com/spyder-ide/qtpy/pull/169) - PR: Shim PyQt5 QDateTime.toPyDateTime to QDateTime.toPython for compatibility with PySide2 ([153](https://github.com/spyder-ide/qtpy/issues/153))
* [PR 168](https://github.com/spyder-ide/qtpy/pull/168) - PR: Raise error when trying to use the wrong combination of macOS and Qt versions ([155](https://github.com/spyder-ide/qtpy/issues/155))
* [PR 167](https://github.com/spyder-ide/qtpy/pull/167) - PR: Migrate to CircleCI 2.0
* [PR 163](https://github.com/spyder-ide/qtpy/pull/163) - PR: Add QtLocation
* [PR 162](https://github.com/spyder-ide/qtpy/pull/162) - PR: Update readme to remove funding appeal, harmonize with other readmes and minor fixes
* [PR 161](https://github.com/spyder-ide/qtpy/pull/161) - PR: Fix pyside2 wheels install
* [PR 157](https://github.com/spyder-ide/qtpy/pull/157) - PR: Add more Qt modules ([123](https://github.com/spyder-ide/qtpy/issues/123))

In this release 7 pull requests were closed.

----

## Version 1.4.2 (2018-05-06)

### Issues Closed

* [Issue 150](https://github.com/spyder-ide/qtpy/issues/150) - PySide2-5.11 alpha2 compatibility ([PR 151](https://github.com/spyder-ide/qtpy/pull/151))
* [Issue 144](https://github.com/spyder-ide/qtpy/issues/144) - ValueError: API 'QString' has already been set to version 1 at line 141 in __init__.py file. ([PR 152](https://github.com/spyder-ide/qtpy/pull/152))

In this release 2 issues were closed.

### Pull Requests Merged

* [PR 152](https://github.com/spyder-ide/qtpy/pull/152) - PR: Catch ValueError when trying to set sip API ([144](https://github.com/spyder-ide/qtpy/issues/144))
* [PR 151](https://github.com/spyder-ide/qtpy/pull/151) - PR: Add a preventive change for PySide-5.11a2 ([150](https://github.com/spyder-ide/qtpy/issues/150))
* [PR 149](https://github.com/spyder-ide/qtpy/pull/149) - PR: Use Qt official wheels to run tests for PySide2
* [PR 148](https://github.com/spyder-ide/qtpy/pull/148) - PR: Remove internal conda recipe

In this release 4 pull requests were closed.

----

## Version 1.4.1 (2018-04-28)

### New features

* Show a warning when QT_API is changed automatically by qtpy.

### Issues Closed

* [Issue 145](https://github.com/spyder-ide/qtpy/issues/145) - Raise a warning if QT_API value is changed automatically ([PR 146](https://github.com/spyder-ide/qtpy/pull/146))
* [Issue 142](https://github.com/spyder-ide/qtpy/issues/142) - On OSX qtpy applications are forcing discrete graphics ([PR 143](https://github.com/spyder-ide/qtpy/pull/143))

In this release 2 issues were closed.

### Pull Requests Merged

* [PR 147](https://github.com/spyder-ide/qtpy/pull/147) - PR: Add better compatibility with PySide2
* [PR 146](https://github.com/spyder-ide/qtpy/pull/146) - PR: Add a warning if API is changed automatically ([145](https://github.com/spyder-ide/qtpy/issues/145))
* [PR 143](https://github.com/spyder-ide/qtpy/pull/143) - PR: Avoid using PyQt5.Qt, which imports unneeded stuff and forces discrete GPU on OSX ([142](https://github.com/spyder-ide/qtpy/issues/142))

In this release 3 pull requests were closed.

----

## Version 1.4 (2018-03-11)

### New features

* Add support for QtHelp and QtSql
* Use already imported bindings

### Issues Closed

* [Issue 138](https://github.com/spyder-ide/qtpy/issues/138) - If one binding has already been imported, then qtpy should just use it ([PR 139](https://github.com/spyder-ide/qtpy/pull/139))
* [Issue 135](https://github.com/spyder-ide/qtpy/issues/135) - Add Wrapper for QtSql [feature request] ([PR 136](https://github.com/spyder-ide/qtpy/pull/136))
* [Issue 131](https://github.com/spyder-ide/qtpy/issues/131) - Methods missing from QStandardPaths when QT_API=pyqt4
* [Issue 127](https://github.com/spyder-ide/qtpy/issues/127) - Add Wrapper for QtHelp [feature request] ([PR 128](https://github.com/spyder-ide/qtpy/pull/128))

In this release 4 issues were closed.

### Pull Requests Merged

* [PR 140](https://github.com/spyder-ide/qtpy/pull/140) - PR: Pin PyQt5 to 5.9.2 in CircleCI because 5.10 is generating segfaults
* [PR 139](https://github.com/spyder-ide/qtpy/pull/139) - PR: If a Qt binding is already imported, then use it. ([138](https://github.com/spyder-ide/qtpy/issues/138))
* [PR 136](https://github.com/spyder-ide/qtpy/pull/136) - PR: Add QtSql wrapper (incl. test) ([135](https://github.com/spyder-ide/qtpy/issues/135))
* [PR 132](https://github.com/spyder-ide/qtpy/pull/132) - PR: Changes to QDesktop split
* [PR 128](https://github.com/spyder-ide/qtpy/pull/128) - PR: Add QtHelp Wrapper ([127](https://github.com/spyder-ide/qtpy/issues/127))

In this release 5 pull requests were closed.

----

## Version 1.3.1 (2017-08-21)

### Bugs fixed

**Issues**

* [Issue 129](https://github.com/spyder-ide/qtpy/issues/129) - Spurious cache files in PyPI tarball
* [Issue 119](https://github.com/spyder-ide/qtpy/issues/119) - Importing qtpy should not raise exceptions

In this release 2 issues were closed

**Pull requests**

* [PR 130](https://github.com/spyder-ide/qtpy/pull/130) - PR: No cache files included in the release tarball
* [PR 126](https://github.com/spyder-ide/qtpy/pull/126) - PR: Remove Quantified Code badge because the service doesn't exist anymore
* [PR 121](https://github.com/spyder-ide/qtpy/pull/121) - PR: Warn if QHeaderView deprecated methods are used

In this release 3 pull requests were merged

----

## Version 1.3 (2017-08-12)

### New features

* Add support for PySide2 and PyQt 4.6

### Bugs fixed

**Issues**

* [Issue 124](https://github.com/spyder-ide/qtpy/issues/124) - Typo in readme title
* [Issue 111](https://github.com/spyder-ide/qtpy/issues/111) - Update Readme for 1.3 release
* [Issue 110](https://github.com/spyder-ide/qtpy/issues/110) - Add tests for untested modules
* [Issue 101](https://github.com/spyder-ide/qtpy/issues/101) - Missing: QtOpenGL Module
* [Issue 89](https://github.com/spyder-ide/qtpy/issues/89) - QDesktopServices split into QDesktopServices and QStandardPaths
* [Issue 57](https://github.com/spyder-ide/qtpy/issues/57) - qInstallMessageHandler <-> qInstallMsgHandler
* [Issue 15](https://github.com/spyder-ide/qtpy/issues/15) - Feature Request: PySide2 support

In this release 7 issues were closed

**Pull requests**

* [PR 125](https://github.com/spyder-ide/qtpy/pull/125) - PR: Fix typo in Readme.
* [PR 117](https://github.com/spyder-ide/qtpy/pull/117) - PR: Add compatibility for the rename of qInstallMsgHandler to qInstallMessageHandler
* [PR 115](https://github.com/spyder-ide/qtpy/pull/115) - PR: Update Readme to reflect that we actually use the PySide2 layout
* [PR 114](https://github.com/spyder-ide/qtpy/pull/114) - PR: Update Readme to mention that we now support PySide2.
* [PR 113](https://github.com/spyder-ide/qtpy/pull/113) - PR: Add tests for Qtdesigner, QtNetwork, QtPrintSupport, QtSvg and QtTest.
* [PR 112](https://github.com/spyder-ide/qtpy/pull/112) - PR: Follow QStandardPaths location in Qt5 for PyQt4/PySide
* [PR 109](https://github.com/spyder-ide/qtpy/pull/109) - PR: Add a coveragerc file
* [PR 106](https://github.com/spyder-ide/qtpy/pull/106) - PR: Add support for PyQt 4.6
* [PR 102](https://github.com/spyder-ide/qtpy/pull/102) - PR: Add a new QtOpenGL module
* [PR 84](https://github.com/spyder-ide/qtpy/pull/84) - PR: Add PySide2 support

In this release 10 pull requests were merged

----

## Version 1.2.1 (2017/01/21)

### Bugs fixed

**Pull requests**

* [PR 98](https://github.com/spyder-ide/qtpy/pull/98) - PR: Don't use Travis to test macOS because it slows down the entire spyder-ide organization
* [PR 97](https://github.com/spyder-ide/qtpy/pull/97) - PR: Update Appveyor badge in Readme because of moving to an org account
* [PR 94](https://github.com/spyder-ide/qtpy/pull/94) - PR: Include test suite in sdist

In this release 3 pull requests were merged

----

## Version 1.2 (2017/01/08)

### New features

* Add support for QtMultimedia
* Use relative imports so its vendored more easily

### Bugs fixed

**Issues**

* [Issue 83](https://github.com/spyder-ide/qtpy/issues/83) - Include core doc files in PyPi releases
* [Issue 78](https://github.com/spyder-ide/qtpy/issues/78) - Request for a new bugfix release
* [Issue 75](https://github.com/spyder-ide/qtpy/issues/75) - Missing copyright headers
* [Issue 67](https://github.com/spyder-ide/qtpy/issues/67) - uic.loadUiType is missing
* [Issue 64](https://github.com/spyder-ide/qtpy/issues/64) - QHeaderView.setSectionResizeMode
* [Issue 49](https://github.com/spyder-ide/qtpy/issues/49) - QtMultimedia support

In this release 6 issues were closed

**Pull requests**

* [PR 93](https://github.com/spyder-ide/qtpy/pull/93) - Restore uic full namespace for PyQt5 and PyQt4
* [PR 92](https://github.com/spyder-ide/qtpy/pull/92) - Add missing copyright header in _patch/qheaderview.py
* [PR 91](https://github.com/spyder-ide/qtpy/pull/91) - Use star imports in QtSvg again instead of direct ones (reverts PR #55)
* [PR 88](https://github.com/spyder-ide/qtpy/pull/88) - PR: Add manifest
* [PR 74](https://github.com/spyder-ide/qtpy/pull/74) - Move QStringListModel to QtCore
* [PR 71](https://github.com/spyder-ide/qtpy/pull/71) - PR: Use relative imports so its vendored more easily
* [PR 65](https://github.com/spyder-ide/qtpy/pull/65) - Introduce renamed methods of QHeaderView in PyQt4 and PySide
* [PR 59](https://github.com/spyder-ide/qtpy/pull/59) - Don't install qtpy as a conda package in CircleCI
* [PR 58](https://github.com/spyder-ide/qtpy/pull/58) - Remove reference to how qtpy is pronounced in README
* [PR 55](https://github.com/spyder-ide/qtpy/pull/55) - PR: Add explicit imports to QtSvg module
* [PR 50](https://github.com/spyder-ide/qtpy/pull/50) - Add support for QtMultimedia

In this release 11 pull requests were merged

----

## Version 1.1.2 (2016-08-08)

### Bugfixes

**Pull requests**

* [PR 54](https://github.com/spyder-ide/qtpy/pull/54) - PR: Fix/ci
* [PR 53](https://github.com/spyder-ide/qtpy/pull/53) - PR: Move tests to module so they can be run when installed
* [PR 52](https://github.com/spyder-ide/qtpy/pull/52) - PR: Update readme
* [PR 51](https://github.com/spyder-ide/qtpy/pull/51) - PR: Add circle ci
* [PR 47](https://github.com/spyder-ide/qtpy/pull/47) - Remove PyQt variant symbols from QtCore
* [PR 46](https://github.com/spyder-ide/qtpy/pull/46) - del QtWidgets.QStyleOptionViewItemV4
* [PR 45](https://github.com/spyder-ide/qtpy/pull/45) - Allow QT_API values that are not completely in lower case

In this release 7 pull requests were merged

----

## Version 1.1.1 (2016-07-01)

### Bugfixes

**Pull requests**

* [PR 44](https://github.com/spyder-ide/qtpy/pull/44) - Make qtpy to set the QT_API environment variable

In this release 1 pull requests were merged

---

## Version 1.1 (2016-06-30)

### New features

* Make importing `qtpy` thread-safe
* Add a uic module to make loadUI work for PySide
* Add QtTest support for PySide

### Bugfixes

**Issues**

* [Issue 42](https://github.com/spyder-ide/qtpy/issues/42) - Wrong old PyQt4 version check
* [Issue 21](https://github.com/spyder-ide/qtpy/issues/21) - Patch QComboBox with PySide?
* [Issue 16](https://github.com/spyder-ide/qtpy/issues/16) - Add loadUI functionality

In this release 3 issues were closed

**Pull requests**

* [PR 43](https://github.com/spyder-ide/qtpy/pull/43) - Don't check PyQt version with qtpy's version for old PyQt versions
* [PR 41](https://github.com/spyder-ide/qtpy/pull/41) - `qtpy.__version__` should be QtPy version, not Qt version
* [PR 40](https://github.com/spyder-ide/qtpy/pull/40) - Mention qt-helpers in README.md, and add myself to AUTHORS.md
* [PR 39](https://github.com/spyder-ide/qtpy/pull/39) - Fix remaining segmentation fault that occurs with the patched QComboBox in PySide
* [PR 38](https://github.com/spyder-ide/qtpy/pull/38) - QtTest for PySide
* [PR 37](https://github.com/spyder-ide/qtpy/pull/37) - Automatically load custom widget classes when using PySide
* [PR 33](https://github.com/spyder-ide/qtpy/pull/33) - Ignore case for QT_API env variable in qtpy submodules
* [PR 32](https://github.com/spyder-ide/qtpy/pull/32) - Remove QItemSelectionModel from QtWidgets for PyQt4 and PySide
* [PR 31](https://github.com/spyder-ide/qtpy/pull/31) - Add compatibility for QItemSelectionModel
* [PR 29](https://github.com/spyder-ide/qtpy/pull/29) - Use ci-helpers (from Astropy) for CI and enable AppVeyor
* [PR 28](https://github.com/spyder-ide/qtpy/pull/28) - Make tests.py into proper unit test, and add Qt version info to pytest header
* [PR 27](https://github.com/spyder-ide/qtpy/pull/27) - Make sure loadUi is available
* [PR 25](https://github.com/spyder-ide/qtpy/pull/25) - Add patched version of QComboBox

In this release 13 pull requests were merged

---

## Version 1.0.2 (2016-06-02)

### New features

* Add a WEBENGINE constant to QtWebEngineWidgets, which is True if Qt 5 comes with the WebEngine module and False otherwise.

### Bugfixes

**Pull requests**

* [PR 24](https://github.com/spyder-ide/qtpy/pull/24) - Add constant to QtWebEngineWidgets to see if we are using WebEngine or WebKit
* [PR 23](https://github.com/spyder-ide/qtpy/pull/23) - Fix "Prefer `format()` over string interpolation operator" issue

In this release 2 pull requests were merged

---

## Version 1.0.1 (2016-04-10)

### Bugfixes

**Issues**

* [Issue 18](https://github.com/spyder-ide/qtpy/issues/18) - QIntValidator left in QtWidgets, should be in QtGui

In this release 1 issues were closed

**Pull requests**

* [PR 19](https://github.com/spyder-ide/qtpy/pull/19) - Import QIntValidator in QtGui and remove it from QtWidgets

In this release 1 pull requests were merged

----

## Version 1.0 (2016-03-22)

* Add QtWebEngineWidgets module for Qt 5.6. This module replaces the previous
  QtWebKit one.

* Import the right objects in QtGui, QtWidgets and QtCore

* Add a QtPrintSupport module

---

## Version 0.1.3 (2015-12-30)

* Add tests and continuous integration

## Version 0.1.2 (2015-03-01)

* First release


text:
import os
import pkg_resources

from twisted.python import log
from twisted.internet import reactor
from twisted.application import service

from twisted.web.server import Site
from twisted.web.static import File

from autobahn.websocket import WebSocketServerFactory, \
    WebSocketServerProtocol

from autobahn.resource import WebSocketResource, \
    HTTPChannelHixie76Aware

class EchoServerProtocol(WebSocketServerProtocol):

    def onMessage(self, msg, binary):
        self.sendMessage(msg, binary)

class EchoService(service.Service):

    """
    WebSocket Echo service - this runs a Twisted Web site with a WebSocket
    echo server running under path "/ws".
    """

    def __init__(self, port=8080, debug=False):
        self.port = port
        self.debug = debug

    def startService(self):

        factory = WebSocketServerFactory("ws://127.0.0.1:%d" % self.port, debug=self.debug)

        factory.protocol = EchoServerProtocol
        factory.setProtocolOptions(allowHixie76=True)  # needed if Hixie76 is to be supported

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws"
        root.putChild("ws", resource)

        # both under one Twisted Web Site
        site = Site(root)
        site.protocol = HTTPChannelHixie76Aware  # needed if Hixie76 is to be supported

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)

    def stopService(self):
        self.factory.stopFactory()
        self.site.stopFactory()
        self.listener.stopListening()


text:
import test from 'ava';
import tempWrite from 'temp-write';
import {pathExists} from 'path-exists';
import {execa} from 'execa';

test('trash file', async t => {
	const filename = tempWrite.sync('foo');
	await execa('./cli.js', [filename]);
	t.false(await pathExists(filename));
});

test('ignore rm flags', async t => {
	const filename = tempWrite.sync('foo');
	await execa('./cli.js', ['-rf', filename]);
	t.false(await pathExists(filename));
});


text:
package org.webrtc;

public class CallSessionFileRotatingLogSink {
  static {
    System.loadLibrary("jingle_peerconnection_so");
  }

  private long nativeSink;

  public static byte[] getLogData(String dirPath) {
    return nativeGetLogData(dirPath);
  }

  public CallSessionFileRotatingLogSink(
      String dirPath, int maxFileSize, Logging.Severity severity) {
    nativeSink = nativeAddSink(dirPath, maxFileSize, severity.ordinal());
  }

  public void dispose() {
    if (nativeSink != 0) {
      nativeDeleteSink(nativeSink);
      nativeSink = 0;
    }
  }

  private static native long nativeAddSink(
      String dirPath, int maxFileSize, int severity);
  private static native void nativeDeleteSink(long nativeSink);
  private static native byte[] nativeGetLogData(String dirPath);
}


text:
#include "gl/SkNativeSharedGLContext.h"
#include "gl/GrGLUtil.h"
#include <EGL/eglext.h>

SkNativeSharedGLContext::SkNativeSharedGLContext(GrGLNativeContext& nativeContext)
    : fContext(EGL_NO_CONTEXT)
    , fDisplay(nativeContext.fDisplay)
    , fSurface(EGL_NO_SURFACE)
    , fEGLImage(NULL)
    , fGrContext(NULL)
    , fGL(NULL)
    , fFBO(0)
    , fTextureID(0)
    , fDepthStencilBufferID(0) {
}

SkNativeSharedGLContext::~SkNativeSharedGLContext() {
    if (fGL) {
        SK_GL_NOERRCHECK(*this, DeleteFramebuffers(1, &fFBO));
        SK_GL_NOERRCHECK(*this, DeleteTextures(1, &fTextureID));
        SK_GL_NOERRCHECK(*this, DeleteRenderbuffers(1, &fDepthStencilBufferID));
    }
    SkSafeUnref(fGL);
    this->destroyGLContext();
    if (fGrContext) {
        fGrContext->Release();
    }
}

void SkNativeSharedGLContext::destroyGLContext() {
    if (fDisplay) {
        eglMakeCurrent(fDisplay, 0, 0, 0);

        if (fContext) {
            eglDestroyContext(fDisplay, fContext);
            fContext = EGL_NO_CONTEXT;
        }

        if (fSurface) {
            eglDestroySurface(fDisplay, fSurface);
            fSurface = EGL_NO_SURFACE;
        }

        //TODO should we close the display?
        fDisplay = EGL_NO_DISPLAY;
    }
}

const GrGLInterface* SkNativeSharedGLContext::createGLContext(const int width, const int height) {
    EGLint numConfigs;
    static const EGLint configAttribs[] = {
        EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_NONE
    };

    EGLConfig surfaceConfig;
    eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs);

    static const EGLint contextAttribs[] = {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    static const EGLint surfaceAttribs[] = {
        EGL_WIDTH, width,
        EGL_HEIGHT, height,
        EGL_NONE
    };
    fContext = eglCreateContext(fDisplay, surfaceConfig, EGL_NO_CONTEXT, contextAttribs);
    fSurface = eglCreatePbufferSurface(fDisplay, surfaceConfig, surfaceAttribs);

    eglMakeCurrent(fDisplay, fSurface, fSurface, fContext);

    const GrGLInterface* interface = GrGLCreateNativeInterface();
    if (!interface) {
        SkDebugf("Failed to create gl interface");
        this->destroyGLContext();
        return NULL;
    }
    return interface;
}

bool SkNativeSharedGLContext::init(int width, int height) {
    if (fGL) {
        fGL->unref();
        this->destroyGLContext();
    }

    fGL = this->createGLContext(width, height);
    if (fGL) {
        const GrGLubyte* temp;

        GrGLBinding bindingInUse = GrGLGetBindingInUse(this->gl());

        if (!fGL->validate(bindingInUse) || !fExtensions.init(bindingInUse, fGL)) {
            fGL = NULL;
            this->destroyGLContext();
            return false;
        }

        SK_GL_RET(*this, temp, GetString(GR_GL_VERSION));
        const char* versionStr = reinterpret_cast<const char*>(temp);
        GrGLVersion version = GrGLGetVersionFromString(versionStr);

        // clear any existing GL erorrs
        GrGLenum error;
        do {
            SK_GL_RET(*this, error, GetError());
        } while (GR_GL_NO_ERROR != error);

        SK_GL(*this, GenFramebuffers(1, &fFBO));
        SK_GL(*this, BindFramebuffer(GR_GL_FRAMEBUFFER, fFBO));
        SK_GL(*this, GenTextures(1, &fTextureID));
        SK_GL(*this, BindTexture(GR_GL_TEXTURE_2D, fTextureID));
        SK_GL(*this, TexImage2D(GR_GL_TEXTURE_2D, 0,
                                GR_GL_RGBA,
                                width, height, 0,
                                GR_GL_RGBA, GR_GL_UNSIGNED_BYTE,
                                NULL));
        SK_GL(*this, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_S, GR_GL_CLAMP_TO_EDGE));
        SK_GL(*this, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_WRAP_T, GR_GL_CLAMP_TO_EDGE));
        SK_GL(*this, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MAG_FILTER, GR_GL_LINEAR));
        SK_GL(*this, TexParameteri(GR_GL_TEXTURE_2D, GR_GL_TEXTURE_MIN_FILTER, GR_GL_LINEAR));
        SK_GL(*this, FramebufferTexture2D(GR_GL_FRAMEBUFFER,
                                          GR_GL_COLOR_ATTACHMENT0,
                                          GR_GL_TEXTURE_2D,
                                          fTextureID, 0));

        //Initilize EGLimageKHR for sharing texture between threads or processes
        EGLint eglImgAttrs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE, EGL_NONE };
        fEGLImage = eglCreateImageKHR(fDisplay, fContext, EGL_GL_TEXTURE_2D_KHR, (EGLClientBuffer)fTextureID, eglImgAttrs);

        SK_GL(*this, GenRenderbuffers(1, &fDepthStencilBufferID));
        SK_GL(*this, BindRenderbuffer(GR_GL_RENDERBUFFER, fDepthStencilBufferID));

        // Some drivers that support packed depth stencil will only succeed
        // in binding a packed format an FBO. However, we can't rely on packed
        // depth stencil being available.
        bool supportsPackedDepthStencil;
        if (kES2_GrGLBinding == bindingInUse) {
            supportsPackedDepthStencil = this->hasExtension("GL_OES_packed_depth_stencil");
        } else {
            supportsPackedDepthStencil = version >= GR_GL_VER(3,0) ||
                                         this->hasExtension("GL_EXT_packed_depth_stencil") ||
                                         this->hasExtension("GL_ARB_framebuffer_object");
        }

        if (supportsPackedDepthStencil) {
            // ES2 requires sized internal formats for RenderbufferStorage
            // On Desktop we let the driver decide.
            GrGLenum format = kES2_GrGLBinding == bindingInUse ?
                                    GR_GL_DEPTH24_STENCIL8 :
                                    GR_GL_DEPTH_STENCIL;
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             format,
                                             width, height));
            SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                                 GR_GL_DEPTH_ATTACHMENT,
                                                 GR_GL_RENDERBUFFER,
                                                 fDepthStencilBufferID));
        } else {
            GrGLenum format = kES2_GrGLBinding == bindingInUse ?
                                    GR_GL_STENCIL_INDEX8 :
                                    GR_GL_STENCIL_INDEX;
            SK_GL(*this, RenderbufferStorage(GR_GL_RENDERBUFFER,
                                             format,
                                             width, height));
        }
        SK_GL(*this, FramebufferRenderbuffer(GR_GL_FRAMEBUFFER,
                                             GR_GL_STENCIL_ATTACHMENT,
                                             GR_GL_RENDERBUFFER,
                                             fDepthStencilBufferID));
        SK_GL(*this, Viewport(0, 0, width, height));
        SK_GL(*this, ClearStencil(0));
        SK_GL(*this, Clear(GR_GL_STENCIL_BUFFER_BIT));

        SK_GL_RET(*this, error, GetError());
        GrGLenum status;
        SK_GL_RET(*this, status, CheckFramebufferStatus(GR_GL_FRAMEBUFFER));

        if (GR_GL_FRAMEBUFFER_COMPLETE != status ||
            GR_GL_NO_ERROR != error) {
            fFBO = 0;
            fTextureID = 0;
            fDepthStencilBufferID = 0;
            fGL->unref();
            fGL = NULL;
            this->destroyGLContext();
            return false;
        } else {
            return true;
        }
    }
    return false;
}

GrContext *SkNativeSharedGLContext::getGrContext() {
    if (fGrContext) {
        return fGrContext;
    } else {
        GrBackendContext p3dctx = reinterpret_cast<GrBackendContext>(this->gl());
        fGrContext = GrContext::Create(kOpenGL_GrBackend, p3dctx);
        if (fGrContext == NULL) {
            return NULL;
        }
        // No need to AddRef; the GrContext is created with refcount = 1.
        return fGrContext;
    }
}

GrGLSharedSurface SkNativeSharedGLContext::stealSurface() {
    if (fGL && fFBO) {
        SK_GL(*this, BindFramebuffer(GR_GL_FRAMEBUFFER, fFBO));
        SK_GL(*this, FramebufferTexture2D(GR_GL_FRAMEBUFFER,
                    GR_GL_COLOR_ATTACHMENT0,
                    GR_GL_TEXTURE_2D,
                    0,
                    0));
    }

    EGLImageKHR image = fEGLImage;
    fTextureID = 0;
    fSurface = NULL;
    return image;
}

void SkNativeSharedGLContext::makeCurrent() const {
    if (!eglMakeCurrent(fDisplay, fSurface, fSurface, fContext)) {
        SkDebugf("Could not set the context.\n");
    }
}

void SkNativeSharedGLContext::flush() const {
    this->makeCurrent();
    SK_GL(*this, Flush());
}


text:
---
layout:     post
title:      Quick And Dirty Game Events
date:       2015-01-24 14:14:29
summary:    Game events don't need to be complicated.
categories: GameDev
tags: 		  GameDev Events
---

In all forms of OO programming objects need to communicate with other objects, but we also try hard to keep dependencies down. In games we usually have a lot of objects that need to talk to each other. Imagine a player in a first person shooter. There could conceivably be a player object, a gun object, a health bar object, a ammo object, a power up object, an audio object etc. All these objects lead to dependencies.

Using events can help you decouple your code so that nothing depends on anything else (other than the system of events). There are many ways you can do event systems (and I doubt this will be the last time I talk about them here), this is a quick and dirty way of doing it.

### Lets Get Dirty

A quick and dirty event system can be baked right into your objects. Where the base game object class can contain _all_ the possible events. So when an event is fired, the implementing game object will only respond to an event if it defined the event method.

{% highlight cpp %}
class GameObject
{
public:

  // Event List //
  virtual void onCollision(GameObject &theOtherObject) {}
  virtual void onPlayerJump() {}
  virtual void onPlayerMove(const vec3 newPosition) {}

  // .. continue to list every event in this manor .. //

};

// Now for each object that needs to respond to a particular event
// override that particular event.

class AudioManager : public GameObject
{
  // .. class stuff ..
  void onPlayerJump() override { playAudio("jumpSound"); }
  void onPlayerMove() override { playAudio("walkSound"); }
}

class Player : public GameObject
{
  void onCollision() override { /* do collision logic */ }
}

{% endhighlight %}

Now that our objects know what todo when a particular event is fired. They need to be informed that such an event has occurred. This can change depending on your preference. How I've been doing it recently, is to send a lambda to the broadcast method. In fact you can actually call the update and render of the object using this method. This also gives you some added control if you wish to add extra things it.

{% highlight cpp %}
// The list of all the game objects that you use to update/render them.
class GameObjectList
{
  std::vector<GameObject*> allYourGameObjects;

public:

  // Update all game objects
  void updateGameObjects()
  {
    // We can use the event caller for this as well.
    broadcastEvent([](GameObject &obj) { obj.update();});
  }

  void broadcastEvent(std::function<void(GameObject&)> process)
  {
    for(auto &gameObj : allYourGameObjects)
    {
      process(*gameObj);
    }
  }
};

// Player sends an event when it moved.
class Player : public GameObject
{
  vec3 playerPos;

  void update()
  {
    if(input().pressedMoveKey())
    {
      playerPos += moveVec;

      allMyObjects.broadcastEvent([playerPos&](GameObject& obj) { obj.onPlayerMoved(playerPos); });
    }
  }
};

{% endhighlight %}

### Final Thoughts

This is really a quick slap method of doing game events, I would only recommend it for small projects. For bigger projects you don't want to be blindly sending events to all the objects in this manor. You might also want game objects to be able to respond to events, or swallow them so they don't propagate further.


text:
<?php

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\RateLimiter\RequestRateLimiterInterface;
use Symfony\Component\Lock\LockInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\Storage\CacheStorage;
use Symfony\Component\Security\Http\RateLimiter\DefaultLoginRateLimiter;

/**
 * @author Wouter de Jong <wouter@wouterj.nl>
 *
 * @internal
 */
class LoginThrottlingFactory implements AuthenticatorFactoryInterface
{
    public function getPriority(): int
    {
        // this factory doesn't register any authenticators, this priority doesn't matter
        return 0;
    }

    public function getKey(): string
    {
        return 'login_throttling';
    }

    /**
     * @param ArrayNodeDefinition $builder
     */
    public function addConfiguration(NodeDefinition $builder)
    {
        $builder
            ->children()
                ->scalarNode('limiter')->info(sprintf('A service id implementing "%s".', RequestRateLimiterInterface::class))->end()
                ->integerNode('max_attempts')->defaultValue(5)->end()
                ->scalarNode('interval')->defaultValue('1 minute')->end()
                ->scalarNode('lock_factory')->info('The service ID of the lock factory used by the login rate limiter (or null to disable locking)')->defaultNull()->end()
            ->end();
    }

    public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): array
    {
        if (!class_exists(RateLimiterFactory::class)) {
            throw new \LogicException('Login throttling requires the Rate Limiter component. Try running "composer require symfony/rate-limiter".');
        }

        if (!isset($config['limiter'])) {
            $limiterOptions = [
                'policy' => 'fixed_window',
                'limit' => $config['max_attempts'],
                'interval' => $config['interval'],
                'lock_factory' => $config['lock_factory'],
            ];
            $this->registerRateLimiter($container, $localId = '_login_local_'.$firewallName, $limiterOptions);

            $limiterOptions['limit'] = 5 * $config['max_attempts'];
            $this->registerRateLimiter($container, $globalId = '_login_global_'.$firewallName, $limiterOptions);

            $container->register($config['limiter'] = 'security.login_throttling.'.$firewallName.'.limiter', DefaultLoginRateLimiter::class)
                ->addArgument(new Reference('limiter.'.$globalId))
                ->addArgument(new Reference('limiter.'.$localId))
            ;
        }

        $container
            ->setDefinition('security.listener.login_throttling.'.$firewallName, new ChildDefinition('security.listener.login_throttling'))
            ->replaceArgument(1, new Reference($config['limiter']))
            ->addTag('kernel.event_subscriber', ['dispatcher' => 'security.event_dispatcher.'.$firewallName]);

        return [];
    }

    private function registerRateLimiter(ContainerBuilder $container, string $name, array $limiterConfig)
    {
        // default configuration (when used by other DI extensions)
        $limiterConfig += ['lock_factory' => 'lock.factory', 'cache_pool' => 'cache.rate_limiter'];

        $limiter = $container->setDefinition($limiterId = 'limiter.'.$name, new ChildDefinition('limiter'));

        if (null !== $limiterConfig['lock_factory']) {
            if (!interface_exists(LockInterface::class)) {
                throw new LogicException(sprintf('Rate limiter "%s" requires the Lock component to be installed. Try running "composer require symfony/lock".', $name));
            }
            if (!$container->hasDefinition('lock.factory.abstract')) {
                throw new LogicException(sprintf('Rate limiter "%s" requires the Lock component to be configured.', $name));
            }

            $limiter->replaceArgument(2, new Reference($limiterConfig['lock_factory']));
        }
        unset($limiterConfig['lock_factory']);

        if (null === $storageId = $limiterConfig['storage_service'] ?? null) {
            $container->register($storageId = 'limiter.storage.'.$name, CacheStorage::class)->addArgument(new Reference($limiterConfig['cache_pool']));
        }

        $limiter->replaceArgument(1, new Reference($storageId));
        unset($limiterConfig['storage_service'], $limiterConfig['cache_pool']);

        $limiterConfig['id'] = $name;
        $limiter->replaceArgument(0, $limiterConfig);

        $container->registerAliasForArgument($limiterId, RateLimiterFactory::class, $name.'.limiter');
    }
}


text:
var frameModule = require("ui/frame");
//var top = frameModule.topmost();

exports.load = function(args) {
  setTimeout(function () {
      frameModule.topmost().navigate({
            moduleName: "./components/home/home",
            animated: true
        });
    }, 1000);
};


text:
<?php

namespace SiteBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $uniqueTaxReference;

    public function setUniqueTaxReference($uniqueTaxReference)
    {
        $this->uniqueTaxReference = $uniqueTaxReference;

        return $this;
    }

    public function getUniqueTaxReference()
    {
        return $this->uniqueTaxReference;
    }
}


text:
using Xunit;

namespace System.Text.Tests
{
    // GetBytes(System.String,System.Int32,System.Int32,System.Byte[],System.Int32)
    public class EncodingGetBytes5
    {
        #region Private Fields
        private const string c_TEST_STR = "za\u0306\u01FD\u03B2\uD8FF\uDCFF";
        #endregion

        #region Positive Test Cases
        // PosTest1: Verify method GetBytes(System.String) with UTF8.
        [Fact]
        public void PosTest1()
        {
            Encoding u8 = Encoding.UTF8;
            byte[] bytes = new byte[u8.GetMaxByteCount(3)];
            Assert.Equal(6, u8.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)));
        }

        // PosTest2: Verify method GetBytes(System.String) with Unicode
        [Fact]
        public void PosTest2()
        {
            Encoding u16LE = Encoding.Unicode;
            byte[] bytes = new byte[u16LE.GetMaxByteCount(3)];
            Assert.Equal(6, u16LE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)));
        }

        // PosTest3: Verify method GetBytes(System.String) with BigEndianUnicode.
        [Fact]
        public void PosTest3()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Equal(6, u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.GetLowerBound(0)));
        }
        #endregion

        #region Negative Test Cases
        [Fact]
        public void NegTest1()
        {
            string testNullStr = null;
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Throws<ArgumentNullException>(() =>
            {
                int i = u16BE.GetBytes(testNullStr, 4, 3, bytes, bytes.GetLowerBound(0));
            });
        }

        [Fact]
        public void NegTest2()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = null;
            Assert.Throws<ArgumentNullException>(() =>
            {
                int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, 1);
            });
        }

        [Fact]
        public void NegTest3()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                int i = u16BE.GetBytes(c_TEST_STR, -1, 3, bytes, bytes.GetLowerBound(0));
            });
        }

        [Fact]
        public void NegTest4()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                int i = u16BE.GetBytes(c_TEST_STR, 4, -1, bytes, bytes.GetLowerBound(0));
            });
        }

        [Fact]
        public void NegTest5()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, -1);
            });
        }

        [Fact]
        public void NegTest6()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                int i = u16BE.GetBytes(c_TEST_STR, c_TEST_STR.Length - 1, 3, bytes, bytes.GetLowerBound(0));
            });
        }

        [Fact]
        public void NegTest7()
        {
            Encoding u16BE = Encoding.BigEndianUnicode;
            byte[] bytes = new byte[u16BE.GetMaxByteCount(3)];
            Assert.Throws<ArgumentException>(() =>
            {
                int i = u16BE.GetBytes(c_TEST_STR, 4, 3, bytes, bytes.Length - 1);
            });
        }
        #endregion
    }
}


text:
namespace remoting {

namespace {
// Both input and output data are assumed to be RGBA32.
const int kBytesPerPixel = 4;
}

DecoderRowBased* DecoderRowBased::CreateZlibDecoder() {
  return new DecoderRowBased(new DecompressorZlib(),
                             VideoPacketFormat::ENCODING_ZLIB);
}

DecoderRowBased* DecoderRowBased::CreateVerbatimDecoder() {
  return new DecoderRowBased(new DecompressorVerbatim(),
                             VideoPacketFormat::ENCODING_VERBATIM);
}

DecoderRowBased::DecoderRowBased(Decompressor* decompressor,
                                 VideoPacketFormat::Encoding encoding)
    : state_(kUninitialized),
      clip_(SkIRect::MakeEmpty()),
      decompressor_(decompressor),
      encoding_(encoding),
      row_pos_(0),
      row_y_(0),
      screen_size_(SkISize::Make(0, 0)) {
}

DecoderRowBased::~DecoderRowBased() {
}

bool DecoderRowBased::IsReadyForData() {
  switch (state_) {
    case kUninitialized:
    case kError:
      return false;
    case kReady:
    case kProcessing:
    case kPartitionDone:
    case kDone:
      return true;
  }
  NOTREACHED();
  return false;
}

void DecoderRowBased::Initialize(const SkISize& screen_size) {
  decompressor_->Reset();
  updated_region_.setEmpty();
  screen_buffer_.reset(NULL);

  screen_size_ = screen_size;
  // Allocate the screen buffer, if necessary.
  if (!screen_size_.isEmpty()) {
    screen_buffer_.reset(new uint8[
        screen_size_.width() * screen_size_.height() * kBytesPerPixel]);
  }

  state_ = kReady;
}

Decoder::DecodeResult DecoderRowBased::DecodePacket(const VideoPacket* packet) {
  UpdateStateForPacket(packet);

  if (state_ == kError) {
    return DECODE_ERROR;
  }

  const uint8* in = reinterpret_cast<const uint8*>(packet->data().data());
  const int in_size = packet->data().size();
  const int row_size = clip_.width() * kBytesPerPixel;

  int out_stride = screen_size_.width() * kBytesPerPixel;
  uint8* out = screen_buffer_.get() + out_stride * (clip_.top() + row_y_) +
      kBytesPerPixel * clip_.left();

  // Consume all the data in the message.
  bool decompress_again = true;
  int used = 0;
  while (decompress_again && used < in_size) {
    if (row_y_ >= clip_.height()) {
      state_ = kError;
      LOG(WARNING) << "Too much data is received for the given rectangle.";
      return DECODE_ERROR;
    }

    int written = 0;
    int consumed = 0;
    decompress_again = decompressor_->Process(
        in + used, in_size - used, out + row_pos_, row_size - row_pos_,
        &consumed, &written);
    used += consumed;
    row_pos_ += written;

    // If this row is completely filled then move onto the next row.
    if (row_pos_ == row_size) {
      ++row_y_;
      row_pos_ = 0;
      out += out_stride;
    }
  }

  if (state_ == kPartitionDone || state_ == kDone) {
    if (row_y_ < clip_.height()) {
      state_ = kError;
      LOG(WARNING) << "Received LAST_PACKET, but didn't get enough data.";
      return DECODE_ERROR;
    }

    updated_region_.op(clip_, SkRegion::kUnion_Op);
    decompressor_->Reset();
  }

  if (state_ == kDone) {
    return DECODE_DONE;
  } else {
    return DECODE_IN_PROGRESS;
  }
}

void DecoderRowBased::UpdateStateForPacket(const VideoPacket* packet) {
  if (state_ == kError) {
    return;
  }

  if (packet->flags() & VideoPacket::FIRST_PACKET) {
    if (state_ != kReady && state_ != kDone && state_ != kPartitionDone) {
      state_ = kError;
      LOG(WARNING) << "Received unexpected FIRST_PACKET.";
      return;
    }

    // Reset the buffer location status variables on the first packet.
    clip_.setXYWH(packet->format().x(), packet->format().y(),
                  packet->format().width(), packet->format().height());
    if (!SkIRect::MakeSize(screen_size_).contains(clip_)) {
      state_ = kError;
      LOG(WARNING) << "Invalid clipping area received.";
      return;
    }

    state_ = kProcessing;
    row_pos_ = 0;
    row_y_ = 0;
  }

  if (state_ != kProcessing) {
    state_ = kError;
    LOG(WARNING) << "Received unexpected packet.";
    return;
  }

  if (packet->flags() & VideoPacket::LAST_PACKET) {
    if (state_ != kProcessing) {
      state_ = kError;
      LOG(WARNING) << "Received unexpected LAST_PACKET.";
      return;
    }
    state_ = kPartitionDone;
  }

  if (packet->flags() & VideoPacket::LAST_PARTITION) {
    if (state_ != kPartitionDone) {
      state_ = kError;
      LOG(WARNING) << "Received unexpected LAST_PARTITION.";
      return;
    }
    state_ = kDone;
  }

  return;
}

VideoPacketFormat::Encoding DecoderRowBased::Encoding() {
  return encoding_;
}

void DecoderRowBased::Invalidate(const SkISize& view_size,
                                 const SkRegion& region) {
  updated_region_.op(region, SkRegion::kUnion_Op);
}

void DecoderRowBased::RenderFrame(const SkISize& view_size,
                                  const SkIRect& clip_area,
                                  uint8* image_buffer,
                                  int image_stride,
                                  SkRegion* output_region) {
  output_region->setEmpty();

  // TODO(alexeypa): scaling is not implemented.
  SkIRect clip_rect = SkIRect::MakeSize(screen_size_);
  if (!clip_rect.intersect(clip_area))
    return;

  int screen_stride = screen_size_.width() * kBytesPerPixel;

  for (SkRegion::Iterator i(updated_region_); !i.done(); i.next()) {
    SkIRect rect(i.rect());
    if (!rect.intersect(clip_rect))
      continue;

    CopyRGB32Rect(screen_buffer_.get(), screen_stride,
                  clip_rect,
                  image_buffer, image_stride,
                  clip_area,
                  rect);
    output_region->op(rect, SkRegion::kUnion_Op);
  }

  updated_region_.setEmpty();
}

}  // namespace remoting


text:
package com.sun.max.vm.hosted;

import java.io.*;

import com.oracle.max.elf.*;
import com.sun.max.program.Trace;

/**
 * A program to convert a Maxine VM image into a (sequence of) assembler file(s) or ELF file(s).
 *
 * @author Mick Jordan
 * @author Pradeep Natajaran
 *
 */
public class MemoryBootImage {

    private static final int MEGABYTE = 1024 * 1024;
    private static final int AS_CHUNK_SIZE = MEGABYTE * 100;
    private static final int MAXLL = 16;
    private static final String IMAGE_START = "maxvm_image_start";
    private static final String IMAGE_END = "maxvm_image_end";

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            int chunkSize = AS_CHUNK_SIZE;
            String imageFileName = null;
            boolean elf = true;
            // Checkstyle: stop modified control variable check
            for (int i = 0; i < args.length; i++) {
                final String arg = args[i];
                if (arg.equals("-chunksize")) {
                    final String css = args[++i];
                    final char m = css.charAt(css.length() - 1);
                    final int cs = Integer.parseInt(css.substring(0, css.length() - 1));
                    if (m == 'm') {
                        chunkSize = cs * MEGABYTE;
                    } else {
                        throw new Exception("invalid scale character: " + m);
                    }
                } else if (arg.equals("-image")) {
                    imageFileName = args[++i];
                } else if (arg.equals("-asm")) {
                    elf = false;
                }
            }
            // Checkstyle: resume modified control variable check
            File bootImage = null;
            if (imageFileName == null) {
                bootImage = BootImageGenerator.getBootImageFile(BootImageGenerator.getDefaultVMDirectory());
            } else {
                bootImage = new File(imageFileName);
            }
            if (elf) {
                writeELFFile(bootImage, chunkSize);
            } else {
                writeAsmFile(bootImage, chunkSize);
            }

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    private static File asFile(File bootImage, int index) {
        final String parent = bootImage.getParent();
        final String name = bootImage.getName();
        return new File(parent, name + "." + index + ".s");
    }

    private static void flushLine(PrintWriter wr, byte[] line, int ll) {
        wr.print(".byte ");
        for (int i = 0; i < ll; i++) {
            final int v = line[i];
            wr.print("0x" + Integer.toHexString(v & 0xFF));
            if (i != ll - 1) {
                wr.print(",");
            }
        }
        wr.println();
    }

    private static void writeELFFile(File bootImage, int chunkSize) {

        int index = 0;
        long offsetCount = 0;
        try {
            final long startTime = System.currentTimeMillis();
            Trace.line(1, "Writing Elf File....");
            final long size = bootImage.length(); // The size of the image file that is stored in a section.
            final ELFHeader imageElfHeader = new ELFHeader();
            imageElfHeader.writeHeader64(size);
            final ELFSectionHeaderTable imageElfSectionHdr = new ELFSectionHeaderTable(imageElfHeader);
            ELFSymbolTable imageSymTab;
            final BufferedInputStream is = new BufferedInputStream(
                    new FileInputStream(bootImage));

            // Set the string table .
            final ELFStringTable strtab = new ELFStringTable(imageElfHeader);
            strtab.addStringInTable("maxvm_image");
            strtab.addStringInTable(".shstrtab");
            strtab.addStringInTable(".symtab");
            strtab.addStringInTable(".strtab");
            imageElfSectionHdr.setStringTable(strtab);

            // to create a new file to write the ELF object file.
            final String parent = bootImage.getParent();
            final String name = bootImage.getName();
            final File f = new File(parent, name + ".0.o");
            // Open the file for writing.
            final RandomAccessFile fis = new RandomAccessFile(f, "rw");
            final ELFDataOutputStream os = new ELFDataOutputStream(imageElfHeader, fis);
            imageElfHeader.writeELFHeader64ToFile(os, fis);
            writeImageToFile(os, fis, size, is);
            imageElfSectionHdr.write(size);
            final ELFSectionHeaderTable.Entry e = imageElfSectionHdr.entries[imageElfHeader.e_shstrndx];
            imageElfSectionHdr.getStringTable().setSection(e);
            imageElfSectionHdr.getStringTable().write64ToFile(os, fis);

            // Creating Symbol Table and the string table.
            for (int cntr = 0; cntr < imageElfSectionHdr.entries.length; cntr++) {
                final ELFSectionHeaderTable.Entry e1 = imageElfSectionHdr.entries[cntr];
                if (e1.isSymbolTable()) {
                    imageSymTab = new ELFSymbolTable(imageElfHeader, e1);
                    final ELFSectionHeaderTable.Entry strent = imageElfSectionHdr.entries[e1.getLink()];
                    if (strent.isStringTable()) {
                        final ELFStringTable symStrTab = new ELFStringTable(imageElfHeader, strent);
                        // To add the values of the string names that will be used in the symbol table
                        symStrTab.addStringInTable("maxvm_image_start");
                        symStrTab.addStringInTable("maxvm_image_end");
                        imageSymTab.setStringTable(symStrTab);
                        index = imageElfSectionHdr.getStringTable().getIndex("maxvm_image");
                        imageSymTab.setSymbolTableEntries(index, size);
                        //set the size of the string table section.
                        strent.setEntrySize(symStrTab.getStringLength());
                        // Now we need to write the symbol table onto the file.
                        // It should be aligned to 8 bits, so we increment the offsetcount to be aligned to 8 bits and then
                        // seek to that position to write the symbol.
                        offsetCount = fis.getFilePointer();
                        if (offsetCount % 8 != 0) {
                            offsetCount += 8 - (offsetCount % 8);
                        }
                        fis.seek(offsetCount);
                        imageSymTab.write64ToFile(os, fis);
                        // Write the symbol table's string table on to the file
                        imageSymTab.getStringTable().write64ToFile(os, fis);
                    }
                    break;
                }
            }
            // We have written all the sections. We need to write the section headers now.
            //Lets update the size of the file till this point in the section header.
            offsetCount = fis.getFilePointer();
            imageElfSectionHdr.setOffsetCount(offsetCount);

            //Before that we need to retrieve the ELF header and update its e_shoff to give the correct value for the offset of the section Header
            fis.seek(0); // seek to the beginning of the file.

            final ELFHeader header = ELFLoader.readELFHeader(fis);

            // Set the offset Count for the section header in the ELF header.
            header.setShOff(offsetCount);

            fis.seek(0); // Seek to beginning of the file again to write this header.
            header.writeELFHeader64ToFile(os, fis);
            // Now seek to end of the sections to write the section header.

            fis.seek(offsetCount);

            imageElfSectionHdr.writeSectionHeadersToFile64(os, fis);
            fis.close();
            Trace.line(1, "Wrote ELF file in: " + ((System.currentTimeMillis() - startTime) / 1000.0f) + " seconds");

        } catch (Exception ex) {
            System.out.println(ex);
        }

    }

    private static void writeImageToFile(ELFDataOutputStream os, RandomAccessFile fis, long size, BufferedInputStream is) throws IOException {
        final byte[] buffer = new byte[8192];
        while (size > 0) {
            final int n = is.read(buffer, 0, buffer.length);
            fis.write(buffer, 0, n);
            // CheckStyle: stop parameter assignment check
            size -= n;
            // CheckStyle: resume parameter assignment check
        }
    }

    private static void writeAsmFile(File bootImage, int chunkSize) {
        try {
            long size = bootImage.length();
            int fx = 0;
            int chunkCount = 0;
            final BufferedInputStream is = new BufferedInputStream(
                    new FileInputStream(bootImage));

            final long startTime = System.currentTimeMillis();
            while (size > 0) {
                final boolean lastFile = size <= chunkSize;
                final File f = asFile(bootImage, fx);
                final PrintWriter wr = new PrintWriter(new BufferedWriter(new FileWriter(f)));
                System.out.println(" writing  " + f);
                wr.println(".section maxvm_image, \"a\"");
                if (fx == 0) {
                    wr.println(".global " + IMAGE_START);
                    wr.println(IMAGE_START + ":");
                }
                if (lastFile) {
                    wr.println(".global " + IMAGE_END);
                }
                int count = 0;
                final byte[] line = new byte[MAXLL];
                while (chunkCount < chunkSize) {
                    final int b = is.read();
                    if (b < 0) {
                        break;
                    }
                    line[count++] = (byte) b; chunkCount++;
                    if (count == MAXLL) {
                        flushLine(wr, line, MAXLL);
                        count = 0;
                    }
                }
                if (count > 0) {
                    flushLine(wr, line, count);
                }
                if (lastFile) {
                    wr.println(IMAGE_END + ":");
                }
                wr.close();
                size -= chunkSize;
                chunkCount = 0;
                fx++;
            }
            is.close();
            Trace.line(1, "Wrote ASM file in: " + ((System.currentTimeMillis() - startTime) / 1000.0f) + " seconds");
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
}


text:
#include <glib.h>
#include <string.h>
#include "libqtest.h"
#include "qemu/osdep.h"

/* Tests only initialization so far. TODO: Replace with functional tests */
static void pci_nop(void)
{
}

int main(int argc, char **argv)
{
    int ret;

    g_test_init(&argc, &argv, NULL);
    qtest_add_func("/virtio/scsi/pci/nop", pci_nop);

    qtest_start("-drive id=drv0,if=none,file=/dev/null "
                "-device virtio-scsi-pci,id=vscsi0 "
                "-device scsi-hd,bus=vscsi0.0,drive=drv0");
    ret = g_test_run();

    qtest_end();

    return ret;
}