text:
package loadbalancer

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"reflect"
	"sort"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/elbv2"
	"github.com/coreos/alb-ingress-controller/pkg/alb/listeners"
	"github.com/coreos/alb-ingress-controller/pkg/alb/targetgroup"
	"github.com/coreos/alb-ingress-controller/pkg/alb/targetgroups"
	"github.com/coreos/alb-ingress-controller/pkg/annotations"
	"github.com/coreos/alb-ingress-controller/pkg/aws/ec2"
	albelbv2 "github.com/coreos/alb-ingress-controller/pkg/aws/elbv2"
	"github.com/coreos/alb-ingress-controller/pkg/util/log"
	util "github.com/coreos/alb-ingress-controller/pkg/util/types"
	api "k8s.io/api/core/v1"
)

// LoadBalancer contains the overarching configuration for the ALB
type LoadBalancer struct {
	ID                       string
	Current                  *elbv2.LoadBalancer // current version of load balancer in AWS
	Desired                  *elbv2.LoadBalancer // desired version of load balancer in AWS
	TargetGroups             targetgroups.TargetGroups
	Listeners                listeners.Listeners
	DesiredIdleTimeout       int64
	CurrentIdleTimeout       *int64
	CurrentTags              util.Tags
	DesiredTags              util.Tags
	CurrentPorts             portList
	DesiredPorts             portList
	CurrentManagedSG         *string
	DesiredManagedSG         *string
	CurrentManagedInstanceSG *string
	DesiredManagedInstanceSG *string
	Deleted                  bool // flag representing the LoadBalancer instance was fully deleted.
	logger                   *log.Logger
}

type loadBalancerChange uint

const (
	securityGroupsModified loadBalancerChange = 1 << iota
	subnetsModified
	tagsModified
	schemeModified
	managedSecurityGroupsModified
	connectionIdleTimeoutModified
)

type NewDesiredLoadBalancerOptions struct {
	ALBNamePrefix        string
	Namespace            string
	IngressName          string
	ExistingLoadBalancer *LoadBalancer
	Logger               *log.Logger
	Annotations          *annotations.Annotations
	Tags                 util.Tags
}

type portList []int64

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

// NewDesiredLoadBalancer returns a new loadbalancer.LoadBalancer based on the parameters provided.
func NewDesiredLoadBalancer(o *NewDesiredLoadBalancerOptions) *LoadBalancer {
	// TODO: LB name  must contain only alphanumeric characters or hyphens, and must
	// not begin or end with a hyphen.
	name := createLBName(o.Namespace, o.IngressName, o.ALBNamePrefix)

	newLoadBalancer := &LoadBalancer{
		ID:                 name,
		DesiredTags:        o.Tags,
		DesiredIdleTimeout: o.Annotations.ConnectionIdleTimeout,
		Desired: &elbv2.LoadBalancer{
			AvailabilityZones: o.Annotations.Subnets.AsAvailabilityZones(),
			LoadBalancerName:  aws.String(name),
			Scheme:            o.Annotations.Scheme,
			SecurityGroups:    o.Annotations.SecurityGroups,
			VpcId:             o.Annotations.VPCID,
		},
		logger: o.Logger,
	}

	lsps := portList{}
	for _, port := range o.Annotations.Ports {
		lsps = append(lsps, port.Port)
	}
	if len(newLoadBalancer.Desired.SecurityGroups) == 0 {
		newLoadBalancer.DesiredPorts = lsps
	}

	// TODO: What is this for??
	if o.ExistingLoadBalancer != nil {
		// we had an existing LoadBalancer in ingress, so just copy the desired state over
		o.ExistingLoadBalancer.Desired = newLoadBalancer.Desired
		o.ExistingLoadBalancer.DesiredTags = newLoadBalancer.DesiredTags
		o.ExistingLoadBalancer.DesiredIdleTimeout = newLoadBalancer.DesiredIdleTimeout
		if len(o.ExistingLoadBalancer.Desired.SecurityGroups) == 0 {
			o.ExistingLoadBalancer.DesiredPorts = lsps
		}
		return o.ExistingLoadBalancer
	}

	// no existing LoadBalancer, so use the one we just created
	return newLoadBalancer
}

type NewCurrentLoadBalancerOptions struct {
	LoadBalancer          *elbv2.LoadBalancer
	Tags                  util.Tags
	ALBNamePrefix         string
	Logger                *log.Logger
	ManagedSG             *string
	ManagedInstanceSG     *string
	ManagedSGPorts        []int64
	ConnectionIdleTimeout *int64
}

// NewCurrentLoadBalancer returns a new loadbalancer.LoadBalancer based on an elbv2.LoadBalancer.
func NewCurrentLoadBalancer(o *NewCurrentLoadBalancerOptions) (*LoadBalancer, error) {
	ingressName, ok := o.Tags.Get("IngressName")
	if !ok {
		return nil, fmt.Errorf("The LoadBalancer %s does not have an IngressName tag, can't import", *o.LoadBalancer.LoadBalancerName)
	}

	namespace, ok := o.Tags.Get("Namespace")
	if !ok {
		return nil, fmt.Errorf("The LoadBalancer %s does not have a Namespace tag, can't import", *o.LoadBalancer.LoadBalancerName)
	}

	name := createLBName(namespace, ingressName, o.ALBNamePrefix)
	if name != *o.LoadBalancer.LoadBalancerName {
		return nil, fmt.Errorf("Loadbalancer does not have expected (calculated) name. "+
			"Expecting %s but was %s.", name, *o.LoadBalancer.LoadBalancerName)
	}

	return &LoadBalancer{
		ID:                       name,
		CurrentTags:              o.Tags,
		Current:                  o.LoadBalancer,
		logger:                   o.Logger,
		CurrentManagedSG:         o.ManagedSG,
		CurrentPorts:             o.ManagedSGPorts,
		CurrentManagedInstanceSG: o.ManagedInstanceSG,
		CurrentIdleTimeout:       o.ConnectionIdleTimeout,
	}, nil
}

// Reconcile compares the current and desired state of this LoadBalancer instance. Comparison
// results in no action, the creation, the deletion, or the modification of an AWS ELBV2 (ALB) to
// satisfy the ingress's current state.
func (lb *LoadBalancer) Reconcile(rOpts *ReconcileOptions) []error {
	var errors []error

	switch {
	case lb.Desired == nil: // lb should be deleted
		if lb.Current == nil {
			break
		}
		lb.logger.Infof("Start ELBV2 (ALB) deletion.")
		if err := lb.delete(rOpts); err != nil {
			errors = append(errors, err)
			break
		}
		rOpts.Eventf(api.EventTypeNormal, "DELETE", "%s deleted", *lb.Current.LoadBalancerName)
		lb.logger.Infof("Completed ELBV2 (ALB) deletion. Name: %s | ARN: %s",
			*lb.Current.LoadBalancerName,
			*lb.Current.LoadBalancerArn)

	case lb.Current == nil: // lb doesn't exist and should be created
		lb.logger.Infof("Start ELBV2 (ALB) creation.")
		if err := lb.create(rOpts); err != nil {
			errors = append(errors, err)
			return errors
		}
		rOpts.Eventf(api.EventTypeNormal, "CREATE", "%s created", *lb.Current.LoadBalancerName)
		lb.logger.Infof("Completed ELBV2 (ALB) creation. Name: %s | ARN: %s",
			*lb.Current.LoadBalancerName,
			*lb.Current.LoadBalancerArn)

	default: // check for diff between lb current and desired, modify if necessary
		needsModification, _ := lb.needsModification()
		if needsModification == 0 {
			lb.logger.Debugf("No modification of ELBV2 (ALB) required.")
			break
		}

		lb.logger.Infof("Start ELBV2 (ALB) modification.")
		if err := lb.modify(rOpts); err != nil {
			errors = append(errors, err)
			break
		}
		lb.logger.Infof("Completed ELBV2 (ALB) modification.")
	}

	tgsOpts := &targetgroups.ReconcileOptions{
		Eventf:            rOpts.Eventf,
		VpcID:             lb.Current.VpcId,
		ManagedSGInstance: lb.CurrentManagedInstanceSG,
	}

	tgs, cleanUp, err := lb.TargetGroups.Reconcile(tgsOpts)
	if err != nil {
		errors = append(errors, err)
		return errors
	} else {
		lb.TargetGroups = tgs
	}

	lsOpts := &listeners.ReconcileOptions{
		Eventf:          rOpts.Eventf,
		LoadBalancerArn: lb.Current.LoadBalancerArn,
		TargetGroups:    lb.TargetGroups,
	}
	if ltnrs, err := lb.Listeners.Reconcile(lsOpts); err != nil {
		errors = append(errors, err)
	} else {
		lb.Listeners = ltnrs
	}

	for _, l := range lb.Listeners {
		if l.Deleted {
			i := lb.Listeners.Find(l.Current)
			lb.Listeners = append(lb.Listeners[:i], lb.Listeners[i+1:]...)
		}
	}

	// Return now if listeners are already deleted, signifies has already been destructed and
	// TG clean-up, based on rules below does not need to occur.
	if len(lb.Listeners) < 1 {
		for _, tg := range cleanUp {
			if err := targetgroup.DeleteTG(tg); err != nil {
				errors = append(errors, err)
				return errors
			}
			index, _ := lb.TargetGroups.FindById(tg.ID)
			lb.TargetGroups = append(lb.TargetGroups[:index], lb.TargetGroups[index+1:]...)
		}
		return errors
	}

	unusedTGs := lb.Listeners[0].Rules.FindUnusedTGs(lb.TargetGroups)
	for _, tg := range unusedTGs {
		if err := targetgroup.DeleteTG(tg); err != nil {
			errors = append(errors, err)
			return errors
		}
		index, _ := lb.TargetGroups.FindById(tg.ID)
		lb.TargetGroups = append(lb.TargetGroups[:index], lb.TargetGroups[index+1:]...)
	}

	return errors
}

// reconcileExistingManagedSG checks AWS for an existing SG with that matches the description of what would
// otherwise be created. If an SG is found, it will run an update to ensure the rules are up to date.
func (lb *LoadBalancer) reconcileExistingManagedSG() error {
	if len(lb.DesiredPorts) < 1 {
		return fmt.Errorf("No ports specified on ingress. Ingress resource may be misconfigured")
	}
	vpcID, err := ec2.EC2svc.GetVPCID()
	if err != nil {
		return err
	}

	sgID, instanceSG, err := ec2.EC2svc.UpdateSGIfNeeded(vpcID, aws.String(lb.ID), lb.CurrentPorts, lb.DesiredPorts)
	if err != nil {
		return err
	}

	// sgID could be nil, if an existing SG didn't exist or it could have a pointer to an sgID in it.
	lb.DesiredManagedSG = sgID
	lb.DesiredManagedInstanceSG = instanceSG
	return nil
}

// create requests a new ELBV2 (ALB) is created in AWS.
func (lb *LoadBalancer) create(rOpts *ReconcileOptions) error {

	// TODO: This whole thing can become a resolveSGs func
	var sgs util.AWSStringSlice
	// check if desired securitygroups are already expressed through annotations
	if len(lb.Desired.SecurityGroups) > 0 {
		sgs = lb.Desired.SecurityGroups
	} else {
		lb.reconcileExistingManagedSG()
	}
	if lb.DesiredManagedSG != nil {
		sgs = append(sgs, lb.DesiredManagedSG)

		if lb.DesiredManagedInstanceSG == nil {
			vpcID, err := ec2.EC2svc.GetVPCID()
			if err != nil {
				return err
			}
			instSG, err := ec2.EC2svc.CreateNewInstanceSG(aws.String(lb.ID), lb.DesiredManagedSG, vpcID)
			if err != nil {
				return err
			}
			lb.DesiredManagedInstanceSG = instSG
		}
	}

	// when sgs are not known, attempt to create them
	if len(sgs) < 1 {
		vpcID, err := ec2.EC2svc.GetVPCID()
		if err != nil {
			return err
		}
		newSG, newInstSG, err := ec2.EC2svc.CreateSecurityGroupFromPorts(vpcID, aws.String(lb.ID), lb.DesiredPorts)
		if err != nil {
			return err
		}
		sgs = append(sgs, newSG)
		lb.DesiredManagedSG = newSG
		lb.DesiredManagedInstanceSG = newInstSG
	}

	in := &elbv2.CreateLoadBalancerInput{
		Name:           lb.Desired.LoadBalancerName,
		Subnets:        util.AvailabilityZones(lb.Desired.AvailabilityZones).AsSubnets(),
		Scheme:         lb.Desired.Scheme,
		Tags:           lb.DesiredTags,
		SecurityGroups: sgs,
	}

	o, err := albelbv2.ELBV2svc.CreateLoadBalancer(in)
	if err != nil {
		rOpts.Eventf(api.EventTypeWarning, "ERROR", "Error creating %s: %s", *in.Name, err.Error())
		lb.logger.Errorf("Failed to create ELBV2 (ALB): %s", err.Error())
		return err
	}

	// lb created. set to current
	lb.Current = o.LoadBalancers[0]

	// DesiredIdleTimeout is 0 when no annotation was set, thus no modification should be attempted
	// this will result in using the AWS default
	if lb.DesiredIdleTimeout != 0 {
		if err := albelbv2.ELBV2svc.SetIdleTimeout(lb.Current.LoadBalancerArn, lb.DesiredIdleTimeout); err != nil {
			rOpts.Eventf(api.EventTypeWarning, "ERROR", "%s tag modification failed: %s", *lb.Current.LoadBalancerName, err.Error())
			lb.logger.Errorf("Failed ELBV2 (ALB) tag modification: %s", err.Error())
			return err
		}
		lb.CurrentIdleTimeout = aws.Int64(lb.DesiredIdleTimeout)
		rOpts.Eventf(api.EventTypeNormal, "CREATE", "Set ALB's connection idle timeout to %d", *lb.CurrentIdleTimeout)
		lb.logger.Infof("Connection idle timeout set to %d", *lb.CurrentIdleTimeout)
	}

	// when a desired managed sg was present, it was used and should be set as the new CurrentManagedSG.
	if lb.DesiredManagedSG != nil {
		lb.CurrentManagedSG = lb.DesiredManagedSG
		lb.CurrentManagedInstanceSG = lb.DesiredManagedInstanceSG
		lb.CurrentPorts = lb.DesiredPorts
	}
	return nil
}

// modify modifies the attributes of an existing ALB in AWS.
func (lb *LoadBalancer) modify(rOpts *ReconcileOptions) error {
	needsMod, canMod := lb.needsModification()
	if canMod {

		// Modify Security Groups
		if needsMod&securityGroupsModified != 0 {
			lb.logger.Infof("Start ELBV2 security groups modification.")
			in := &elbv2.SetSecurityGroupsInput{
				LoadBalancerArn: lb.Current.LoadBalancerArn,
				SecurityGroups:  lb.Desired.SecurityGroups,
			}
			if _, err := albelbv2.ELBV2svc.SetSecurityGroups(in); err != nil {
				lb.logger.Errorf("Failed ELBV2 security groups modification: %s", err.Error())
				rOpts.Eventf(api.EventTypeWarning, "ERROR", "%s security group modification failed: %s", *lb.Current.LoadBalancerName, err.Error())
				return err
			}
			lb.Current.SecurityGroups = lb.Desired.SecurityGroups
			rOpts.Eventf(api.EventTypeNormal, "MODIFY", "%s security group modified", *lb.Current.LoadBalancerName)
			lb.logger.Infof("Completed ELBV2 security groups modification. SGs: %s",
				log.Prettify(lb.Current.SecurityGroups))
		}

		// Modify ALB-managed security groups
		if needsMod&managedSecurityGroupsModified != 0 {
			lb.logger.Infof("Start ELBV2-managed security groups modification.")
			if err := lb.reconcileExistingManagedSG(); err != nil {
				lb.logger.Errorf("Failed ELBV2-managed security groups modification: %s", err.Error())
				rOpts.Eventf(api.EventTypeWarning, "ERROR", "%s security group modification failed: %s", *lb.Current.LoadBalancerName, err.Error())
				return err
			}
			lb.CurrentPorts = lb.DesiredPorts
		}

		// Modify Subnets
		if needsMod&subnetsModified != 0 {
			lb.logger.Infof("Start subnets modification.")
			in := &elbv2.SetSubnetsInput{
				LoadBalancerArn: lb.Current.LoadBalancerArn,
				Subnets:         util.AvailabilityZones(lb.Desired.AvailabilityZones).AsSubnets(),
			}
			if _, err := albelbv2.ELBV2svc.SetSubnets(in); err != nil {
				rOpts.Eventf(api.EventTypeWarning, "ERROR", "%s subnet modification failed: %s", *lb.Current.LoadBalancerName, err.Error())
				return fmt.Errorf("Failure Setting ALB Subnets: %s", err)
			}
			lb.Current.AvailabilityZones = lb.Desired.AvailabilityZones
			rOpts.Eventf(api.EventTypeNormal, "MODIFY", "%s subnets modified", *lb.Current.LoadBalancerName)
			lb.logger.Infof("Completed subnets modification. Subnets are %s.",
				log.Prettify(lb.Current.AvailabilityZones))
		}

		// Modify Tags
		if needsMod&tagsModified != 0 {
			lb.logger.Infof("Start ELBV2 tag modification.")
			if err := albelbv2.ELBV2svc.UpdateTags(lb.Current.LoadBalancerArn, lb.CurrentTags, lb.DesiredTags); err != nil {
				rOpts.Eventf(api.EventTypeWarning, "ERROR", "%s tag modification failed: %s", *lb.Current.LoadBalancerName, err.Error())
				lb.logger.Errorf("Failed ELBV2 (ALB) tag modification: %s", err.Error())
			}
			lb.CurrentTags = lb.DesiredTags
			rOpts.Eventf(api.EventTypeNormal, "MODIFY", "%s tags modified", *lb.Current.LoadBalancerName)
			lb.logger.Infof("Completed ELBV2 tag modification. Tags are %s.",
				log.Prettify(lb.CurrentTags))
		}

		// Modify Connection Idle Timeout
		if needsMod&connectionIdleTimeoutModified != 0 {
			if lb.DesiredIdleTimeout != 0 {
				if err := albelbv2.ELBV2svc.SetIdleTimeout(lb.Current.LoadBalancerArn, lb.DesiredIdleTimeout); err != nil {
					rOpts.Eventf(api.EventTypeWarning, "ERROR", "%s tag modification failed: %s", *lb.Current.LoadBalancerName, err.Error())
					lb.logger.Errorf("Failed ELBV2 (ALB) tag modification: %s", err.Error())
					return err
				}
				lb.CurrentIdleTimeout = aws.Int64(lb.DesiredIdleTimeout)
				rOpts.Eventf(api.EventTypeNormal, "MODIFY", "Connection idle timeout updated to %d", *lb.CurrentIdleTimeout)
				lb.logger.Infof("Connection idle timeout updated to %d", *lb.CurrentIdleTimeout)
			}
		}

	} else {
		// Modification is needed, but required full replacement of ALB.
		lb.logger.Infof("Start ELBV2 full modification (delete and create).")
		rOpts.Eventf(api.EventTypeNormal, "REBUILD", "Impossible modification requested, rebuilding %s", *lb.Current.LoadBalancerName)
		lb.delete(rOpts)
		// Since listeners and rules are deleted during lb deletion, ensure their current state is removed
		// as they'll no longer exist.
		lb.Listeners.StripCurrentState()
		lb.create(rOpts)
		lb.logger.Infof("Completed ELBV2 full modification (delete and create). Name: %s | ARN: %s",
			*lb.Current.LoadBalancerName, *lb.Current.LoadBalancerArn)

	}

	return nil
}

// delete Deletes the load balancer from AWS.
func (lb *LoadBalancer) delete(rOpts *ReconcileOptions) error {
	in := &elbv2.DeleteLoadBalancerInput{
		LoadBalancerArn: lb.Current.LoadBalancerArn,
	}

	if _, err := albelbv2.ELBV2svc.DeleteLoadBalancer(in); err != nil {
		rOpts.Eventf(api.EventTypeWarning, "ERROR", "Error deleting %s: %s", *lb.Current.LoadBalancerName, err.Error())
		lb.logger.Errorf("Failed deletion of ELBV2 (ALB): %s.", err.Error())
		return err
	}

	// if the alb controller was managing a SG we must:
	// - Remove the InstanceSG from all instances known to targetgroups
	// - Delete the InstanceSG
	// - Delete the ALB's SG
	// Deletions are attempted as best effort, if it fails we log the error but don't
	// fail the overall reconcile
	if lb.CurrentManagedSG != nil {
		if err := ec2.EC2svc.DisassociateSGFromInstanceIfNeeded(lb.TargetGroups[0].Targets.Current, lb.CurrentManagedInstanceSG); err != nil {
			rOpts.Eventf(api.EventTypeWarning, "WARN", "Failed disassociating sgs from instances: %s", err.Error())
			lb.logger.Warnf("Failed in deletion of managed SG: %s.", err.Error())
		}
		if err := attemptSGDeletion(lb.CurrentManagedInstanceSG); err != nil {
			rOpts.Eventf(api.EventTypeWarning, "WARN", "Failed deleting %s: %s", *lb.CurrentManagedInstanceSG, err.Error())
			lb.logger.Warnf("Failed in deletion of managed SG: %s. Continuing remaining deletions, may leave orphaned SGs in AWS.", err.Error())
		} else { // only attempt this SG deletion if the above passed, otherwise it will fail due to depenencies.
			if err := attemptSGDeletion(lb.CurrentManagedSG); err != nil {
				rOpts.Eventf(api.EventTypeWarning, "WARN", "Failed deleting %s: %s", *lb.CurrentManagedSG, err.Error())
				lb.logger.Warnf("Failed in deletion of managed SG: %s. Continuing remaining deletions, may leave orphaned SG in AWS.", err.Error())
			}
		}

	}

	lb.Deleted = true
	return nil
}

// attemptSGDeletion makes a few attempts to remove an SG. If it cannot due to DependencyViolations
// it reattempts in 10 seconds. For up to 2 minutes.
func attemptSGDeletion(sg *string) error {
	// Possible a DependencyViolation will be seen, make a few attempts incase
	var rErr error
	for i := 0; i < 6; i++ {
		time.Sleep(20 * time.Second)
		if err := ec2.EC2svc.DeleteSecurityGroupByID(sg); err != nil {
			rErr = err
			if aerr, ok := err.(awserr.Error); ok {
				if aerr.Code() == "DependencyViolation" {
					continue
				}
			}
		} else { // success, no AWS err occured
			rErr = nil
		}
		break
	}
	return rErr
}

// needsModification returns if a LB needs to be modified and if it can be modified in place
// first parameter is true if the LB needs to be changed
// second parameter true if it can be changed in place
func (lb *LoadBalancer) needsModification() (loadBalancerChange, bool) {
	var changes loadBalancerChange

	// In the case that the LB does not exist yet
	if lb.Current == nil {
		return changes, true
	}

	if !util.DeepEqual(lb.Current.Scheme, lb.Desired.Scheme) {
		changes |= schemeModified
		return changes, false
	}

	currentSubnets := util.AvailabilityZones(lb.Current.AvailabilityZones).AsSubnets()
	desiredSubnets := util.AvailabilityZones(lb.Desired.AvailabilityZones).AsSubnets()
	sort.Sort(currentSubnets)
	sort.Sort(desiredSubnets)
	if log.Prettify(currentSubnets) != log.Prettify(desiredSubnets) {
		changes |= subnetsModified
	}

	if lb.CurrentPorts != nil && lb.CurrentManagedSG != nil {
		sort.Sort(lb.CurrentPorts)
		sort.Sort(lb.DesiredPorts)
		if !reflect.DeepEqual(lb.DesiredPorts, lb.CurrentPorts) {

			changes |= managedSecurityGroupsModified
		}
	} else {
		currentSecurityGroups := util.AWSStringSlice(lb.Current.SecurityGroups)
		desiredSecurityGroups := util.AWSStringSlice(lb.Desired.SecurityGroups)
		sort.Sort(currentSecurityGroups)
		sort.Sort(desiredSecurityGroups)
		if log.Prettify(currentSecurityGroups) != log.Prettify(desiredSecurityGroups) {
			changes |= securityGroupsModified
		}
	}

	sort.Sort(lb.CurrentTags)
	sort.Sort(lb.DesiredTags)
	if log.Prettify(lb.CurrentTags) != log.Prettify(lb.DesiredTags) {
		changes |= tagsModified
	}

	if lb.DesiredIdleTimeout > 0 && lb.CurrentIdleTimeout != nil && *lb.CurrentIdleTimeout != lb.DesiredIdleTimeout {
		changes |= connectionIdleTimeoutModified
	}

	return changes, true
}

// StripDesiredState removes the DesiredLoadBalancer from the LoadBalancer
func (l *LoadBalancer) StripDesiredState() {
	l.Desired = nil
	l.DesiredPorts = nil
	l.DesiredManagedSG = nil
	if l.Listeners != nil {
		l.Listeners.StripDesiredState()
	}
	if l.TargetGroups != nil {
		l.TargetGroups.StripDesiredState()
	}
}

type ReconcileOptions struct {
	Eventf func(string, string, string, ...interface{})
}

func createLBName(namespace string, ingressName string, clustername string) string {
	hasher := md5.New()
	hasher.Write([]byte(namespace + ingressName))
	hash := hex.EncodeToString(hasher.Sum(nil))[:4]
	name := fmt.Sprintf("%s-%s-%s",
		clustername,
		strings.Replace(namespace, "-", "", -1),
		strings.Replace(ingressName, "-", "", -1),
	)
	if len(name) > 26 {
		name = name[:26]
	}
	name = name + "-" + hash
	return name
}


text:
<?php

/**
 * @author Tamas Imrei <tamas.imrei@gmail.com>
 */

namespace Imrei\AddRest\Tests\Components;

use Imrei\AddRest\Components\Response;
use PHPUnit\Framework\TestCase;

/**
 * Testing the Response class
 */
class ResponseTest extends TestCase
{
    /**
     * @runInSeparateProcess
     */
    public function testSendHeaders()
    {
        $response = new Response();
        $response->addHeader('Content-type', 'application/json');
        $response->addHeader('X-FooBar', 'baz/qux');

        $this->assertTrue($response->sendHeaders());

        if (function_exists('xdebug_get_headers')) {
            $headers = xdebug_get_headers();
            $expected = [
                '/Content-type:\s*application\/json/',
                '/X-FooBar:\s*baz\/qux/'
            ];
            foreach ($expected as $expectedHeader) {
                $this->assertNotEmpty(preg_grep($expectedHeader, $headers));
            }
        }
    }

    public function testSendBody()
    {
        $bodyString = 'peanut butter icecream';
        $this->expectOutputString($bodyString);

        $response = new Response($bodyString);
        $response->sendBody();
    }

    public function testSend()
    {
        $response = $this->getMockBuilder(Response::class)
            ->setMethods(['sendHeaders', 'sendBody'])
            ->getMock()
        ;
        $response
            ->expects($this->once())
            ->method('sendHeaders')
        ;
        $response
            ->expects($this->once())
            ->method('sendBody')
        ;
        $response->send();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Server;
using Server.Regions;
using Server.Targeting;
using Server.Engines.CannedEvil;
using Server.Network;

namespace Server.Multis
{
	public abstract class BaseBoatDeed : Item
	{
		private int m_MultiID;
		private Point3D m_Offset;

		[CommandProperty( AccessLevel.GameMaster )]
		public int MultiID{ get{ return m_MultiID; } set{ m_MultiID = value; } }

		[CommandProperty( AccessLevel.GameMaster )]
		public Point3D Offset{ get{ return m_Offset; } set{ m_Offset = value; } }

		public BaseBoatDeed( int id, Point3D offset ) : base( 0x14F2 )
		{
			Weight = 1.0;

			if ( !Core.AOS )
				LootType = LootType.Newbied;

			m_MultiID = id;
			m_Offset = offset;
		}

		public BaseBoatDeed( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version

			writer.Write( m_MultiID );
			writer.Write( m_Offset );
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();

			switch ( version )
			{
				case 0:
				{
					m_MultiID = reader.ReadInt();
					m_Offset = reader.ReadPoint3D();

					break;
				}
			}

			if ( Weight == 0.0 )
				Weight = 1.0;
		}

		public override void OnDoubleClick( Mobile from )
		{
			if ( !IsChildOf( from.Backpack ) )
			{
				from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
			}
			else if ( from.AccessLevel < AccessLevel.GameMaster && (from.Map == Map.Ilshenar || from.Map == Map.Malas) )
			{
				from.SendLocalizedMessage( 1010567, null, 0x25 ); // You may not place a boat from this location.
			}
			else
			{
				if ( Core.SE )
					from.SendLocalizedMessage( 502482 ); // Where do you wish to place the ship?
				else
					from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 502482 ); // Where do you wish to place the ship?

				from.Target = new InternalTarget( this );
			}
		}

		public abstract BaseBoat Boat{ get; }

		public void OnPlacement( Mobile from, Point3D p )
		{
			if ( Deleted )
			{
				return;
			}
			else if ( !IsChildOf( from.Backpack ) )
			{
				from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
			}
			else
			{
				Map map = from.Map;

				if ( map == null )
					return;

				if ( from.AccessLevel < AccessLevel.GameMaster && (map == Map.Ilshenar || map == Map.Malas) )
				{
					from.SendLocalizedMessage( 1043284 ); // A ship can not be created here.
					return;
				}

				if ( from.Region.IsPartOf( typeof( HouseRegion ) ) || BaseBoat.FindBoatAt( from, from.Map ) != null )
				{
					from.SendLocalizedMessage( 1010568, null, 0x25 ); // You may not place a ship while on another ship or inside a house.
					return;
				}

				BaseBoat boat = Boat;

				if ( boat == null )
					return;

				p = new Point3D( p.X - m_Offset.X, p.Y - m_Offset.Y, p.Z - m_Offset.Z );

				if ( BaseBoat.IsValidLocation( p, map ) && boat.CanFit( p, map, boat.ItemID ) )
				{
					Delete();

					boat.Owner = from;
					boat.Anchored = true;

					uint keyValue = boat.CreateKeys( from );

					if ( boat.PPlank != null )
						boat.PPlank.KeyValue = keyValue;

					if ( boat.SPlank != null )
						boat.SPlank.KeyValue = keyValue;

					boat.MoveToWorld( p, map );
				}
				else
				{
					boat.Delete();
					from.SendLocalizedMessage( 1043284 ); // A ship can not be created here.
				}
			}
		}

		private class InternalTarget : MultiTarget
		{
			private BaseBoatDeed m_Deed;

			public InternalTarget( BaseBoatDeed deed ) : base( deed.MultiID, deed.Offset )
			{
				m_Deed = deed;
			}

			protected override void OnTarget( Mobile from, object o )
			{
				IPoint3D ip = o as IPoint3D;

				if ( ip != null )
				{
					if ( ip is Item )
						ip = ((Item)ip).GetWorldTop();

					Point3D p = new Point3D( ip );

					Region region = Region.Find( p, from.Map );

					if ( region.IsPartOf( typeof( DungeonRegion ) ) )
						from.SendLocalizedMessage( 502488 ); // You can not place a ship inside a dungeon.
					else if ( region.IsPartOf( typeof( HouseRegion ) ) || region.IsPartOf( typeof( ChampionSpawnRegion ) ) )
						from.SendLocalizedMessage( 1042549 ); // A boat may not be placed in this area.
					else
						m_Deed.OnPlacement( from, p );
				}
			}
		}
	}
}


text:
package mods.belgabor.bitdrawers.gui;

import mods.belgabor.bitdrawers.BitDrawers;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.translation.I18n;
import org.lwjgl.opengl.GL11;

import java.util.List;

/**
 * Created by Belgabor on 14.11.2016.
 * Adapted from flatcoloredblocks by AlgortihmX2
 */
public class GuiScreenStartup extends GuiScreen
{
    String[] lines;

    @Override
    public void initGui() {
        final String msga = I18n.translateToLocal( "flatcoloredblocks.startup_a" );
        final String msgb = I18n.translateToLocal( "flatcoloredblocks.startup_b" );
        final String msgc = I18n.translateToLocal( "flatcoloredblocks.startup_c" );
        final String msgd = I18n.translateToLocal( "flatcoloredblocks.startup_d" );
        final String msge = I18n.translateToLocal( "flatcoloredblocks.startup_e" );
        final String msgf = I18n.translateToLocal( "flatcoloredblocks.startup_f" );

        String msg = I18n.translateToLocal("bitDrawers.startup_a") + "\n\n";
        msg += I18n.translateToLocalFormatted("bitDrawers.startup_b", BitDrawers.SD_VERSION, BitDrawers.detectedSdVersion) + "\n";
        if (BitDrawers.sdVersionCheckFailed) {
            msg += I18n.translateToLocal("bitDrawers.startup_fubar") + "\n\n";
        } else if (BitDrawers.sdMajorMismatch) {
            msg += I18n.translateToLocal("bitDrawers.startup_maj") + "\n\n";
        } else if (BitDrawers.sdMinorMismatch) {
            msg += I18n.translateToLocal("bitDrawers.startup_min") + "\n\n";
        }
        msg += I18n.translateToLocal("bitDrawers.startup_c") + "\n\n";
        msg += I18n.translateToLocal("bitDrawers.startup_d") + "\n\n";
        msg += I18n.translateToLocal("bitDrawers.startup_e");

        lines = msg.split( "\n" );

        buttonList.add( new GuiButton( 0, width / 2 - 144 / 2, height / 2 + 96, 144, 20, "Ok" ) );
    }

    @Override
    public void drawScreen(final int mouseX, final int mouseY, final float partialTicks ) {
        GL11.glEnable( GL11.GL_TEXTURE_2D );
        drawDefaultBackground();

        int heightLoc = 90;
        drawCenteredString( fontRendererObj, TextFormatting.YELLOW + "Drawers & Bits", width / 2, height / 2 - 110, 0xFFFFFF );

        for ( final String s : lines )
        {
            final List<String> info = fontRendererObj.listFormattedStringToWidth( s, width - 40 );
            for ( final String infoCut : info )
            {
                drawCenteredString( fontRendererObj, infoCut, width / 2, height / 2 - heightLoc, 0xFFFFFF );
                heightLoc = heightLoc - 12;
            }
        }

        super.drawScreen( mouseX, mouseY, partialTicks );
    }

    @Override
    public void actionPerformed(final GuiButton button ) {
        switch (button.id) {
            case 0: {
                for (final GuiButton b : buttonList) {
                    b.enabled = false;
                }

                if (!BitDrawers.detectedSdVersion.equals(""))
                    BitDrawers.config.updateSDVersion();

                mc.displayGuiScreen( null );

                break;
            }
        }
    }

    @Override
    public boolean doesGuiPauseGame()
    {
        return false;
    }
}


text:
//! \file fbxprocessorxref.h
#ifndef _FBXSDK_UTILS_PROCESSOR_XREF_H_
#define _FBXSDK_UTILS_PROCESSOR_XREF_H_

#include <fbxsdk/fbxsdk_def.h>

#include <fbxsdk/core/base/fbxmap.h>
#include <fbxsdk/utils/fbxprocessor.h>

#include <fbxsdk/fbxsdk_nsbegin.h>

/** This class contains objects
  * This class also provides access to global settings and take information.
  */
class FBXSDK_DLL FbxProcessorXRefCopy : public FbxProcessor
{
    FBXSDK_OBJECT_DECLARE(FbxProcessorXRefCopy, FbxProcessor);

public:
    class FBXSDK_DLL MissingUrlHandler
    {
    public:
        virtual ~MissingUrlHandler();
        virtual void MissingUrl(const FbxString& pUrl, const FbxProperty&) = 0;
    };

    /**
    * \name Properties
    */
    //@{
        FbxPropertyT<FbxString>    OutputDirectory;

        /** As we resolve xref and copy assets, do we update properties to
          * now use this relative path?  Defaults to TRUE.
          */
        FbxPropertyT<FbxBool>     UpdateProperties;

        /** Default to FALSE -- when set, this informs the processor to track
          * every properties that were modified during the scene processing.
          */
        FbxPropertyT<FbxBool>     TrackUpdatedProperties;

        /** Default to TRUE -- when not set, files are only copied if one of
          * the following conditions is met:
          *
          * 1) Target does not exist
          * 2) Target has a different time
          * 3) Target has a different size
          */
        FbxPropertyT<FbxBool>     ForceCopy;

        /** Default to TRUE -- when copying a file, also copy its modification
          * time.  A bit of a requirement if you're not going to use ForceCopy.
          */
        FbxPropertyT<FbxBool>     CopyFileTimes;
    //@}

        /** Optional callback; when set, this will be called when an Url cannot be
          * be copied because the source is not found.
          * Memory is owned by the client code, and will not be freed by us.
          */
        MissingUrlHandler*          MissingUrlHandler;

    /** Since FbxProperty is an opaque type, we can't do an efficient operator <
      * on it, and must keep the data on the object, which can be compared through
      * pointers, and then we can further compare against the property name.
      */
    struct PropertyUpdate
    {
        FbxProperty mProperty;
        FbxString    mOriginalValue;

        inline PropertyUpdate() {}
        inline PropertyUpdate(const FbxProperty& pProp, const FbxString& pVal) :
            mProperty(pProp), mOriginalValue(pVal) {}

        inline bool operator <(const PropertyUpdate& pOther) const
        {
            return strcmp(mProperty.GetName(), pOther.mProperty.GetName()) < 0;
        }
    };
    typedef FbxSet2<PropertyUpdate>           UpdateSet;
    typedef FbxMap<FbxObject*, UpdateSet>    PropertyUpdateMap;

    /** All properties that were updated, with their original value.
      * Will always be empty if TrackUpdatedProperties
      * was not set before calling ProcessCollection/ProcessObject.
      * NOT cleared before each processing run.
      */
    PropertyUpdateMap& GetUpdatedProperties();

    /** If property tracking was enabled, goes through and reverts all changes
      * to the properties.  Does not un-copy the files, naturally.
      */
    void RevertPropertyChanges();

    /** This is just a safety net to make sure RevertPropertyChanges is called when
      * this goes out of scope.
      */
    struct FBXSDK_DLL AutoRevertPropertyChanges
    {
        AutoRevertPropertyChanges(FbxProcessorXRefCopy* pCopy) : mXRefCopy(pCopy) {}
        ~AutoRevertPropertyChanges()
        {
            if( mXRefCopy )
                mXRefCopy->RevertPropertyChanges();
        }

        FbxProcessorXRefCopy* mXRefCopy;
    };

/*****************************************************************************************************************************
** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! **
*****************************************************************************************************************************/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
protected:
	virtual void Construct(const FbxObject* pFrom);
	virtual void ConstructProperties(bool pForceSet);

	PropertyUpdateMap mUpdatedProperties;

	// Implements the rules specified for the ForceCopy property.
	// Also checks the ForceCopy property.
	bool ShouldCopyFile(const FbxString& pTarget, const FbxString& pSource) const;

	virtual bool	internal_ProcessCollectionBegin (FbxCollection*     pObject);
	virtual bool	internal_ProcessCollectionEnd   (FbxCollection*     pObject);
	virtual bool	internal_ProcessObject          (FbxObject*     pObject);
	bool			ProcessPathProperty(FbxProperty &pProperty);
	virtual bool	ValidPropertyForXRefCopy(FbxObject* pObject, FbxProperty& lProperty) const;
#endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/
};

#include <fbxsdk/fbxsdk_nsend.h>

#endif /* _FBXSDK_UTILS_PROCESSOR_XREF_H_ */


text:
package de.hshannover.f4.trust.iron.mapserver.datamodel.meta;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import de.hshannover.f4.trust.iron.mapserver.exceptions.InvalidMetadataException;
import de.hshannover.f4.trust.iron.mapserver.utils.Iso8601DateTime;
import de.hshannover.f4.trust.iron.mapserver.utils.NullCheck;
import de.hshannover.f4.trust.iron.mapserver.utils.TimestampFraction;

public class W3cXmlMetadata extends Metadata {

	private final Document mXmlDocument;
	private final Element mXmlElement;
	private String mPrefixElementName;
	private String mMetadataAsString;
	private Date mTimeStamp;
	private String mPublisherId;

	private static TransformerFactory transformerFactory;

	static {
		try {
			transformerFactory = TransformerFactory.newInstance();
		} catch (TransformerFactoryConfigurationError e) {
			sLogger.error("Could not get a TransformerFactory instance: "
					+ e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	}

	public W3cXmlMetadata(Document doc, MetadataType type, boolean validated)
			throws InvalidMetadataException {
		// As dangerous as before :-(
		super(type, validated);
		NullCheck.check(doc, "node is null");

		mXmlDocument = doc;

		if (mXmlDocument.getChildNodes().getLength() != 1) {
			throw new InvalidMetadataException("wrong number of elements");
		}

		if (mXmlDocument.getFirstChild().getNodeType() != Node.ELEMENT_NODE) {
			throw new InvalidMetadataException("node is not element node");
		}

		mXmlElement = (Element) mXmlDocument.getFirstChild();
		createStrings();
	}

	@Override
	public void setPublisherIdInternal(String pubId) {
		mPublisherId = pubId;
		mXmlElement.setAttribute(PUBLISHERID, mPublisherId);
		createStrings();
	}

	@Override
	public Document toW3cDocument() {
		return (Document) mXmlDocument.cloneNode(true);
	}

	@Override
	public void setTimeStampInternal(Date ts) {
		mTimeStamp = ts;
		mXmlElement.setAttribute(TIMESTAMP,
				Iso8601DateTime.formatDate(mTimeStamp));
		mXmlElement.setAttribute(TIMESTAMP_FRACTION,
				TimestampFraction.getSecondFraction(mTimeStamp) + "");
		createStrings();
	}

	/**
	 * No pretty print, no nothing, but remove the leading <xml .... > stuff
	 */
	private void createStrings() {

		Transformer trans = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Result result = new StreamResult(baos);
		Source source = new DOMSource(mXmlElement);
		try {
			trans = transformerFactory.newTransformer();
			trans.setOutputProperty(OutputKeys.INDENT, "no");
			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			trans.setOutputProperty(OutputKeys.METHOD, "xml");
		} catch (TransformerConfigurationException e) {
			sLogger.error("Could not create Transformer instance: "
					+ e.getMessage());
			throw new RuntimeException(e.getMessage());
		}

		try {
			trans.transform(source, result);
		} catch (TransformerException e) {
			sLogger.error("Could not do transformation: " + e.getMessage());
			throw new RuntimeException(e.getMessage());
		}

		try {
			baos.flush();
		} catch (IOException e) {
			sLogger.error("Could not create Transformer instance: "
					+ e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
		mMetadataAsString = new String(baos.toByteArray());
		mPrefixElementName = mXmlElement.getNodeName();

		// only set the byte count if we are fully initialzied
		if (mTimeStamp != null && mPublisherId != null) {
			setByteCount(mMetadataAsString.length());
		}
	}

	@Override
	public String getMetadataAsString() {
		return mMetadataAsString;
	}

	@Override
	public String toString() {
		return mMetadataAsString;
	}

	@Override
	public String getPrefixAndElement() {
		return mPrefixElementName;
	}
}


text:
super关键字的使用场景:
1. 子类隐藏了父类字段,可以使用super解决。
 ```
class SuperClass
{
  public string name = "SuperClass.name";
}

class SubClass extends SuperClass
{
  public int name = 18;//hiding superclass name
  public void doWork()
  {
    System.out.println(name);//18
    System.out.println(super.name);//SuperClass.name
  }
}
```
2.在子类方法中调用父类被覆盖的方法,要用super
```
class SuperClass
{
  public string name = "SuperClass.name";
  public void doWork()
  {
    System.out.println("SuperClass doWork");
  }
}

class SubClass extends SuperClass
{
  public int name = 18;//hiding superclass name
  public void doWork()
  {
    System.out.println(name);//18
    System.out.println(super.name);//SuperClass.name
  }
  publc void person()
  {
    super.doWork();//invoke SuperClass doWork
  }
}
```
3.在子类构造函数中调用父类构造函数,必须使用super(super(实参))。


text:
"""A command that generates all DevSite and manpage documents."""

import os

from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import walker_util
from googlecloudsdk.core.util import pkg_resources

_HELP_HTML_DATA_FILES = [
    'favicon.ico',
    'index.html',
    '_menu_.css',
    '_menu_.js',
    '_title_.html',
]

def WriteHtmlMenu(command, out):
  """Writes the command menu tree HTML on out.

  Args:
    command: dict, The tree (nested dict) of command/group names.
    out: stream, The output stream.
  """

  def ConvertPathToIdentifier(path):
    return '_'.join(path)

  def WalkCommandTree(command, prefix):
    """Visit each command and group in the CLI command tree.

    Args:
      command: dict, The tree (nested dict) of command/group names.
      prefix: [str], The subcommand arg prefix.
    """
    level = len(prefix)
    visibility = 'visible' if level <= 1 else 'hidden'
    indent = level * 2 + 2
    name = command.get('_name_')
    args = prefix + [name]
    out.write('{indent}
{name}'.format(
                  indent=' ' * indent, visibility=visibility, name=name,
                  item=ConvertPathToIdentifier(args)))
    commands = command.get('commands', []) + command.get('groups', [])
    if commands:
      out.write('
\n')
      for c in sorted(commands, key=lambda x: x['_name_']):
        WalkCommandTree(c, args)
      out.write('{indent}
\n'.format(indent=' ' * (indent + 1)))
      out.write('{indent}
\n'.format(indent=' ' * indent))
    else:
      out.write('
\n'.format(indent=' ' * (indent + 1)))

  out.write("""\

<meta name="description" content="man page tree navigation">
<meta name="generator" content="gcloud meta generate-help-docs --html-dir=.">
<title> man page tree navigation </title>
<base href="." target="_blank">
<link rel="stylesheet" type="text/css" href="_menu_.css">

""")
  WalkCommandTree(command, [])
  out.write("""\

""")

class GenerateHelpDocs(base.Command):
  """Generate all DevSite and man page help docs.

  The DevSite docs are generated in the --devsite-dir directory with pathnames
  in the reference directory hierarchy. The manpage docs are generated in the
  --manpage-dir directory with pathnames in the manN/ directory hierarchy.
  """

  @staticmethod
  def Args(parser):
    parser.add_argument(
        '--hidden',
        action='store_true',
        default=None,
        help=('Include documents for hidden commands and groups.'))
    parser.add_argument(
        '--devsite-dir',
        metavar='DIRECTORY',
        help=('The directory where the generated DevSite reference document '
              'subtree will be written. If not specified then DevSite '
              'documents will not be generated.'))
    parser.add_argument(
        '--html-dir',
        metavar='DIRECTORY',
        help=('The directory where the standalone manpage HTML files will be '
              'generated. index.html contains manpage tree navigation in the '
              'left pane. The active command branch and its immediate children '
              'are visible and clickable. Hover to navigate the tree. Run '
              '`python -m SimpleHTTPServer 8888 &` in DIRECTORY and point '
              'your browser at http://localhost:8888 to view the manpage tree. '
              'If not specified then the HTML manpage site will not be '
              'generated.'))
    parser.add_argument(
        '--manpage-dir',
        metavar='DIRECTORY',
        help=('The directory where the generated manpage document subtree will '
              'be written. If not specified then manpage documents will not be '
              'generated.'))
    parser.add_argument(
        'restrict',
        metavar='COMMAND/GROUP',
        nargs='*',
        default=None,
        help=('Restrict document generation to these dotted command paths. '
              'For example: gcloud.alpha gcloud.beta.test'))

  def Run(self, args):
    if args.devsite_dir:
      walker_util.DevSiteGenerator(self.cli, args.devsite_dir).Walk(
          args.hidden, args.restrict)
    if args.html_dir:
      walker_util.HtmlGenerator(
          self.cli, args.html_dir).Walk(args.hidden, args.restrict)
      tree = walker_util.CommandTreeGenerator(
          self.cli).Walk(args.hidden, args.restrict)
      with open(os.path.join(args.html_dir, '_menu_.html'), 'w') as out:
        WriteHtmlMenu(tree, out)
      for file_name in _HELP_HTML_DATA_FILES:
        with open(os.path.join(args.html_dir, file_name), 'wb') as out:
          file_contents = pkg_resources.GetResource(
              'googlecloudsdk.api_lib.meta.help_html_data.', file_name)
          out.write(file_contents)
    if args.manpage_dir:
      walker_util.ManPageGenerator(
          self.cli, args.manpage_dir).Walk(args.hidden, args.restrict)


text:
using System;
using Medusa.Siren;
using Medusa.Siren.Schema;

namespace Medusa.Network.Message
{
    public abstract class BaseRequestResponseMessage<TRequest, TResponse> : BaseMessage
            where TRequest : class, new()
            where TResponse : class, new()
    {

        protected BaseRequestResponseMessage(TRequest request)
            : base(typeof(TRequest))
        {
            Request = request;
            IncreaseSessionId();
        }

        protected BaseRequestResponseMessage()
            : base(typeof(TRequest))
        {
            Request = new TRequest();
            IncreaseSessionId();
        }
        public void IncreaseSessionId()
        {
            SessionId = ++MessageFactory.SessionId;
        }

        public TRequest Request { get; set; }
        public TResponse Response { get; set; }

        public override ArraySegment<byte>? SerializeRequest()
        {
            return Serializer.Serialize(Request);
        }

        public override ArraySegment<byte>? SerializeResponse()
        {
            return Serializer.Serialize(Response);
        }

        public override void DeserializeRequest(ArraySegment<byte> val)
        {
            Request = Deserializer.Deserialize<TRequest>(val);
        }

        public override void DeserializeResponse(ArraySegment<byte> val)
        {
            Response = Deserializer.Deserialize<TResponse>(val);
        }
    }
}


text:
package com.github.pagehelper.test.basic.sql;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.mapper.CountryMapper;
import com.github.pagehelper.model.Country;
import com.github.pagehelper.util.MybatisHelper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;

public class TestExists {

    /**
     * union的count查询sql特殊
     */
    @Test
    public void testExists() {
        SqlSession sqlSession = MybatisHelper.getSqlSession();
        CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
        try {
            //获取第1页,10条内容,默认查询总数count
            PageHelper.startPage(1, 10);
            List<Country> list = countryMapper.selectExists();
            assertEquals(101, list.get(0).getId());
            assertEquals(10, list.size());
            assertEquals(83, ((Page) list).getTotal());

            //获取第1页,10条内容,默认查询总数count
            PageHelper.startPage(2, 10);
            list = countryMapper.selectExists();
            assertEquals(111, list.get(0).getId());
            assertEquals(10, list.size());
            assertEquals(83, ((Page) list).getTotal());
        } finally {
            sqlSession.close();
        }
    }
}


text:
/*
 *  21.04.2004 Original verion. davagin@udm.ru.
 *-----------------------------------------------------------------------
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *----------------------------------------------------------------------
 */
package davaguine.jmac.encoder;

import davaguine.jmac.info.CompressionLevel;
import davaguine.jmac.info.InputSource;
import davaguine.jmac.info.WaveFormat;
import davaguine.jmac.tools.ByteBuffer;
import davaguine.jmac.tools.File;
import davaguine.jmac.tools.IntegerPointer;

import java.io.IOException;

/**
 * Author: Dmitry Vaguine
 * Date: 07.05.2004
 * Time: 13:10:46
 */
public abstract class IAPECompress {
    public final static int CREATE_WAV_HEADER_ON_DECOMPRESSION = -1;
    public final static int MAX_AUDIO_BYTES_UNKNOWN = -1;

    /**
     * ******************************************************************************************
     * Start
     * *******************************************************************************************
     */

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Start(...) / StartEx(...) - starts encoding
    //
    // Parameters:
    //	CIO * pioOutput / const wchar_t * pFilename
    //		the output... either a filename or an I/O source
    //	WAVEFORMATEX * pwfeInput
    //		format of the audio to encode (use FillWaveFormatEx() if necessary)
    //	int nMaxAudioBytes
    //		the absolute maximum audio bytes that will be encoded... encoding fails with a
    //		ERROR_APE_COMPRESS_TOO_MUCH_DATA if you attempt to encode more than specified here
    //		(if unknown, use MAX_AUDIO_BYTES_UNKNOWN to allocate as much storage in the seek table as
    //		possible... limit is then 2 GB of data (~4 hours of CD music)... this wastes around
    //		30kb, so only do it if completely necessary)
    //	int nCompressionLevel
    //		the compression level for the APE file (fast - extra high)
    //		(note: extra-high is much slower for little gain)
    //	const unsigned char * pHeaderData
    //		a pointer to a buffer containing the WAV header (data before the data block in the WAV)
    //		(note: use NULL for on-the-fly encoding... see next parameter)
    //	int nHeaderBytes
    //		number of bytes in the header data buffer (use CREATE_WAV_HEADER_ON_DECOMPRESSION and
    //		NULL for the pHeaderData and MAC will automatically create the appropriate WAV header
    //		on decompression)
    //////////////////////////////////////////////////////////////////////////////////////////////
    public void Start(String pOutputFilename, WaveFormat pwfeInput) throws IOException {
        Start(pOutputFilename, pwfeInput, MAX_AUDIO_BYTES_UNKNOWN, CompressionLevel.COMPRESSION_LEVEL_NORMAL, null, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public void Start(String pOutputFilename, WaveFormat pwfeInput, int nMaxAudioBytes) throws IOException {
        Start(pOutputFilename, pwfeInput, nMaxAudioBytes, CompressionLevel.COMPRESSION_LEVEL_NORMAL, null, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public void Start(String pOutputFilename, WaveFormat pwfeInput, int nMaxAudioBytes, int nCompressionLevel) throws IOException {
        Start(pOutputFilename, pwfeInput, nMaxAudioBytes, nCompressionLevel, null, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public void Start(String pOutputFilename, WaveFormat pwfeInput, int nMaxAudioBytes, int nCompressionLevel, byte[] pHeaderData) throws IOException {
        Start(pOutputFilename, pwfeInput, nMaxAudioBytes, nCompressionLevel, pHeaderData, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public abstract void Start(String pOutputFilename, WaveFormat pwfeInput, int nMaxAudioBytes, int nCompressionLevel, byte[] pHeaderData, int nHeaderBytes) throws IOException;

    public void StartEx(File pioOutput, WaveFormat pwfeInput) throws IOException {
        StartEx(pioOutput, pwfeInput, MAX_AUDIO_BYTES_UNKNOWN, CompressionLevel.COMPRESSION_LEVEL_NORMAL, null, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public void StartEx(File pioOutput, WaveFormat pwfeInput, int nMaxAudioBytes) throws IOException {
        StartEx(pioOutput, pwfeInput, nMaxAudioBytes, CompressionLevel.COMPRESSION_LEVEL_NORMAL, null, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public void StartEx(File pioOutput, WaveFormat pwfeInput, int nMaxAudioBytes, int nCompressionLevel) throws IOException {
        StartEx(pioOutput, pwfeInput, nMaxAudioBytes, nCompressionLevel, null, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public void StartEx(File pioOutput, WaveFormat pwfeInput, int nMaxAudioBytes, int nCompressionLevel, byte[] pHeaderData) throws IOException {
        StartEx(pioOutput, pwfeInput, nMaxAudioBytes, nCompressionLevel, pHeaderData, CREATE_WAV_HEADER_ON_DECOMPRESSION);
    }

    public abstract void StartEx(File pioOutput, WaveFormat pwfeInput, int nMaxAudioBytes, int nCompressionLevel, byte[] pHeaderData, int nHeaderBytes) throws IOException;

    /**
     * ******************************************************************************************
     * Add / Compress Data
     * - there are 3 ways to add data:
     * 1) simple call AddData(...)
     * 2) lock MAC's buffer, copy into it, and unlock (LockBuffer(...) / UnlockBuffer(...))
     * 3) from an I/O source (AddDataFromInputSource(...))
     * *******************************************************************************************
     */

    //////////////////////////////////////////////////////////////////////////////////////////////
    // AddData(...) - adds data to the encoder
    //
    // Parameters:
    //	unsigned char * pData
    //		a pointer to a buffer containing the raw audio data
    //	int nBytes
    //		the number of bytes in the buffer
    //////////////////////////////////////////////////////////////////////////////////////////////
    public abstract void AddData(byte[] pData, int nBytes) throws IOException;

    //////////////////////////////////////////////////////////////////////////////////////////////
    // GetBufferBytesAvailable(...) - returns the number of bytes available in the buffer
    //	(helpful when locking)
    //////////////////////////////////////////////////////////////////////////////////////////////
    public abstract int GetBufferBytesAvailable();

    //////////////////////////////////////////////////////////////////////////////////////////////
    // LockBuffer(...) - locks MAC's buffer so we can copy into it
    //
    // Parameters:
    //	int * pBytesAvailable
    //		returns the number of bytes available in the buffer (DO NOT COPY MORE THAN THIS IN)
    //
    // Return:
    //	pointer to the buffer (add at that location)
    //////////////////////////////////////////////////////////////////////////////////////////////
    public abstract ByteBuffer LockBuffer(IntegerPointer pBytesAvailable);

    //////////////////////////////////////////////////////////////////////////////////////////////
    // UnlockBuffer(...) - releases the buffer
    //
    // Parameters:
    //	int nBytesAdded
    //		the number of bytes copied into the buffer
    //	BOOL bProcess
    //		whether MAC should process as much as possible of the buffer
    //////////////////////////////////////////////////////////////////////////////////////////////
    public void UnlockBuffer(int nBytesAdded) throws IOException {
        UnlockBuffer(nBytesAdded, true);
    }

    public abstract void UnlockBuffer(int nBytesAdded, boolean bProcess) throws IOException;

    //////////////////////////////////////////////////////////////////////////////////////////////
    // AddDataFromInputSource(...) - use a CInputSource (input source) to add data
    //
    // Parameters:
    //	CInputSource * pInputSource
    //		a pointer to the input source
    //	int nMaxBytes
    //		the maximum number of bytes to let MAC add (-1 if MAC can add any amount)
    //	int * pBytesAdded
    //		returns the number of bytes added from the I/O source
    //////////////////////////////////////////////////////////////////////////////////////////////
    public int AddDataFromInputSource(InputSource pInputSource) throws IOException {
        return AddDataFromInputSource(pInputSource, -1);
    }

    public abstract int AddDataFromInputSource(InputSource pInputSource, int nMaxBytes) throws IOException;

    /**
     * ******************************************************************************************
     * Finish / Kill
     * *******************************************************************************************
     */

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Finish(...) - ends encoding and finalizes the file
    //
    // Parameters:
    //	unsigned char * pTerminatingData
    //		a pointer to a buffer containing the information to place at the end of the APE file
    //		(comprised of the WAV terminating data (data after the data block in the WAV) followed
    //		by any tag information)
    //	int nTerminatingBytes
    //		number of bytes in the terminating data buffer
    //	int nWAVTerminatingBytes
    //		the number of bytes of the terminating data buffer that should be appended to a decoded
    //		WAV file (it's basically nTerminatingBytes - the bytes that make up the tag)
    //////////////////////////////////////////////////////////////////////////////////////////////
    public abstract void Finish(byte[] pTerminatingData, int nTerminatingBytes, int nWAVTerminatingBytes) throws IOException;

    //////////////////////////////////////////////////////////////////////////////////////////////
    // Kill(...) - stops encoding and deletes the output file
    // --- NOT CURRENTLY IMPLEMENTED ---
    //////////////////////////////////////////////////////////////////////////////////////////////
    public abstract void Kill();

    public static IAPECompress CreateIAPECompress() {
        return new APECompress();
    }

}


text:
module Gitlab
  module CycleAnalytics
    module MetricsTables
      def mr_metrics_table
        MergeRequest::Metrics.arel_table
      end

      def mr_table
        MergeRequest.arel_table
      end

      def mr_diff_table
        MergeRequestDiff.arel_table
      end

      def mr_diff_commits_table
        MergeRequestDiffCommit.arel_table
      end

      def mr_closing_issues_table
        MergeRequestsClosingIssues.arel_table
      end

      def issue_table
        Issue.arel_table
      end

      def issue_metrics_table
        Issue::Metrics.arel_table
      end

      def user_table
        User.arel_table
      end

      def build_table
        ::CommitStatus.arel_table
      end
    end
  end
end


text:
/*jshint jquery:true*/
define([
    "jquery",
    "jquery/ui",
    "mage/translate",
    "Magento_DesignEditor/js/dialog"
], function($){
    'use strict';

    /**
     * Dialog button title
     *
     * @const
     * @type {string}
     */
    var BUTTON_ASSIGN = 'OK';

    //TODO since we can't convert data to JSON string we use magic numbers DEFAULT_STORE and EMPTY_STORES

    /**
     * Magic number to send via AJAX request to notify that theme should be assigned to default store
     *
     * @const
     * @type {number}
     */
    var DEFAULT_STORE = -1;

    /**
     * Magic number to send via AJAX request to notify that theme should be unassigned from every store
     *
     * @const
     * @type {number}
     */
    var EMPTY_STORES = -2;

    /**
     * Multiple Stores Dialog
     */
    $.widget('vde.multipleStoresDialog', $.vde.dialog, {
        options: {
            autoOpen:    false,
            modal:       true,
            width:       570,
            dialogClass: 'vde-dialog'
        },

        /**
         * List of stores for current selected theme
         *
         * @var {Array.<number>}
         */
        _defaultStores: undefined,

        /**
         * Set stores to dialog related to theme
         *
         * @param stores
         * @returns {*}
         */
        setStores: function(stores) {
            this._defaultStores = stores;
            this._setCheckboxes(stores);
            this._setDefaultContent();
            return this;
        },

        /**
         * Get selected stores
         *
         * @returns {Array.<number>}
         */
        getStores: function() {
            return this._getCheckboxes();
        },

        /**
         * Callback event when we click on 'assign'
         *
         * @returns {*}
         */
        assignBefore: function() {
            this._checkChangesInfo();
            return this;
        },

        /**
         * Callback for after assign action
         *
         * @param response
         * @returns {*}
         */
        assignAfter: function(response) {
            if (response.error) {
                this.messages.add(response.message, messageType);
            } else {
                this.close();
                document.location.reload();
            }
            return this;
        },

        /**
         * Check changes, were they be made (selected other stores)
         *
         * @private
         */
        _checkChangesInfo: function() {
            if (!this._isStoreChanged()) {
                this.messages.set($.mage.__('No stores were reassigned.'), 'info');
            }
        },

        /**
         * Set to dialog default content
         *
         * @private
         */
        _setDefaultContent: function() {
            this.title.set($.mage.__('Assign theme to your live store-view:'));
            this.messages.clear();
        },

        /**
         * Set checkboxes according to array passed
         *
         * @param {Array.<number>} stores
         * @private
         */
        _setCheckboxes: function(stores) {
            this.element.find('input[type=checkbox]').each(function(index, element) {
                element = $(element);

                var storeViewId = parseInt(element.attr('id').replace('storeview_', ''), 10);
                var isChecked = !(!stores || stores.indexOf(storeViewId) === -1);
                element.attr('checked', isChecked);
            });
        },

        /**
         * Get the IDs of those stores-views, whose checkboxes are set in the popup.
         *
         * @returns {Array.<number>}
         * @private
         */
        _getCheckboxes: function() {
            var stores = [];
            var checkedValue = 1;
            this.element.find('form').serializeArray().each(function(object, index) {
                if (parseInt(object.value, 10) === checkedValue) {
                    stores.push(parseInt(object.name.match('storeviews\\[(\\d+)\\]')[1], 10));
                }
            });
            return stores;
        },

        /**
         * Check if the stores changed
         *
         * @protected
         */
        _isStoreChanged: function() {
            var currentStores = this.getStores();
            var defaultStores = this._defaultStores;
            return !(currentStores.length === defaultStores.length &&
                $(currentStores).not(defaultStores).length === 0);
        }
    });

    /**
     * Single Store Dialog
     */
    $.widget('vde.singleStoreDialog', $.vde.dialog, {
        options: {
            autoOpen:    false,
            modal:       true,
            width:       570,
            dialogClass: 'vde-dialog'
        },

        /**
         * Set stores to dialog related to theme
         *
         * @returns {*}
         */
        setStores: function() {
            this.messages.clear();
            this._setDefaultContent();
            return this;
        },

        /**
         * Get selected stores
         *
         * @returns {Array.<number>|number}
         */
        getStores: function() {
            return DEFAULT_STORE;
        },

        /**
         * Callback event when we click on 'assign'
         *
         * @returns {*}
         */
        assignBefore: function() {
            return this;
        },

        /**
         * Callback event which called after assign
         *
         * @param {Object} response
         * @returns {*}
         */
        assignAfter: function(response) {
            this.close();
            document.location.reload();
            return this;
        },

        /**
         * Set default dialog content
         *
         * @private
         */
        _setDefaultContent: function() {
            this.title.set($.mage.__('Default title'));
        }
    });

    /**
     * VDE assign theme widget
     */
    $.widget('vde.themeAssign', {
        options: {
            beforeShowStoresEvent: 'show-stores-before',
            dialogSelectorMS:      '#dialog-message-assign',
            dialogSelector:        '#dialog-message-assign-single',
            closePopupBtn:         '[class^="action-close"]',
            assignUrl:             null,
            afterAssignUrl:        null,
            storesByThemes:        [],
            hasMultipleStores:     null,
            redirectOnAssign:      false,
            refreshOnAssign:       true,
            afterAssignMode:       'navigation'
        },

        /**
         * Dialog widget
         */
        _dialog: undefined,

        /**
         * List of themes and stores that assigned to them
         *
         * @type {Object.<number, Array>}
         * @private
         */
        _storesByThemes: [],

        /**
         * Form creation
         * @protected
         */
        _create: function() {

            if (this.options.hasMultipleStores) {
                this._dialog = $(this.options.dialogSelectorMS).multipleStoresDialog().data('multipleStoresDialog');
            } else {
                this._dialog = $(this.options.dialogSelector).singleStoreDialog().data('singleStoreDialog');
            }

            this._setAssignedStores(this.options.storesByThemes);
            this._bind();
        },

        /**
         * Bind handlers
         *
         * @protected
         */
        _bind: function() {
            $('body').on('assign-confirm', $.proxy(this._onAssignConfirm, this));
            this._on({
                'assign': '_onAssign',
                'loaded': function() {
                    this.element.trigger('contentUpdated');
                }
            });
        },

        /**
         * Handler for 'assign' event
         *
         * This event can be triggered from different locations:
         *  - Store Designer
         *  - VDE
         *  - VDE when trying to perform save-and-assign
         *
         * @param {Object.<string>} event
         * @param {Object.<string>} data
         * @private
         */
        _onAssign: function(event, data) {
            data.dialog = this._dialog;
            this._dialog.setStores(this._getAssignedStores(data.theme_id));

            if (data.confirm.message) {
                this._dialog.text.set(data.confirm.message);
            }
            this._dialog.title.set(data.confirm.title);

            var buttons = data.confirm.buttons || {
                text: BUTTON_ASSIGN,
                click: $.proxy(function(event) {
                    var button = $(event.currentTarget);
                    if (!button.hasClass('disabled')) {
                        button.addClass('disabled');
                        this._sendAssignRequest(data.theme_id, this._dialog.getStores(), 1);
                    }
                    return false;
                }, this),
                'class': 'primary'
            };
            this._dialog.setButtons(buttons);
            this._dialog.open();
        },

        /**
         * Event handler
         *
         * @param event
         * @param data
         * @private
         */
        _onAssignConfirm: function(event, data) {
            this._sendAssignRequest(data.theme_id, this._dialog.getStores(), data.reportToSession);
        },

        /**
         * Get stores that given theme is assigned to
         *
         * @param {number} theme
         * @returns {Array}
         * @private
         */
        _getAssignedStores: function(theme) {
            return this._storesByThemes[theme] || [];
        },

        /**
         * Setter for internal list of stores that themes assigned to
         *
         * @param {number|Object.<number, Array>} theme
         * @param {Array} stores
         * @private
         */
        _setAssignedStores: function(theme, stores) {
            if (arguments.length == 1) {
                this._storesByThemes = arguments[0];
            } else {
                this._storesByThemes[theme] = stores;
            }
        },

        /**
         * Send AJAX request to assign theme to store-views
         *
         * @param {number} themeId
         * @param {Array.<number>|null} stores
         * @param {boolean} reportToSession
         * @protected
         */
        _sendAssignRequest: function(themeId, stores, reportToSession) {
            if (!this.options.assignUrl) {
                throw Error($.mage.__('The URL to assign stores is not defined.'));
            }

            var data = {
                theme_id: themeId,
                reportToSession: reportToSession
            };
            if (stores === null) {
                data.stores = DEFAULT_STORE;
            } else if (stores.length === 0) {
                data.stores = EMPTY_STORES;
            } else {
                data.stores = stores;
            }

            // This is backend page standard messages container.
            $('#messages').html('');
            this._dialog.assignBefore();
            $.ajax({
                type: 'POST',
                url:  this.options.assignUrl,
                data: data,
                dataType: 'json',
                showLoader: true,
                success: $.proxy(function(response) {
                    this._dialog.assignAfter(response);
                    this.assignThemeSuccess(response, stores, themeId);
                }, this),
                error: $.proxy(function() {
                    var message = $.mage.__('Sorry, there was an unknown error.');
                    this._dialog.messages.set(message, 'error');
                }, this)
            });
        },

        /**
         * Assign Save Theme AJAX call Success handler
         *
         * @param {Object} response
         * @param {Array} stores
         * @param {number} themeId
         */
        assignThemeSuccess: function(response, stores, themeId) {
            if (!response.error) {
                this._setAssignedStores(themeId, stores);
                if (this.options.redirectOnAssign && this.options.afterAssignUrl != null) {
                    document.location = this.options.afterAssignUrl;
                }
            }
        },

        /**
         * Prepare items for post request
         *
         * @param {Object} items
         * @return {Object}
         * @private
         */
        _preparePostItems: function(items) {
            var postData = {};
            $.each(items, function(index, item){
                postData[index] = item.getPostData();
            });
            return postData;
        }
    });

});


text:
//
//  Copyright (c) 2020 Alexander Grund
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <boost/nowide/stat.hpp>

#include <boost/nowide/cstdio.hpp>
#include "test.hpp"
#ifdef BOOST_WINDOWS
#include <errno.h>
#endif

// coverity [root_function]
void test_main(int, char** argv, char**)
{
    const std::string prefix = argv[0];
    const std::string filename = prefix + "\xd7\xa9-\xd0\xbc-\xce\xbd.txt";

    // Make sure file does not exist
    boost::nowide::remove(filename.c_str());

    std::cout << " -- stat - non-existing file" << std::endl;
    {
#ifdef BOOST_WINDOWS
        struct _stat stdStat;
#else
        struct stat stdStat;
#endif
        TEST(boost::nowide::stat(filename.c_str(), &stdStat) != 0);
        boost::nowide::stat_t boostStat;
        TEST(boost::nowide::stat(filename.c_str(), &boostStat) != 0);
    }

    std::cout << " -- stat - existing file" << std::endl;
    FILE* f = boost::nowide::fopen(filename.c_str(), "wb");
    TEST(f);
    const char testData[] = "Hello World";
    constexpr size_t testDataSize = sizeof(testData);
    TEST(std::fwrite(testData, sizeof(char), testDataSize, f) == testDataSize);
    std::fclose(f);
    {
#ifdef BOOST_WINDOWS
        struct _stat stdStat;
#else
        struct stat stdStat;
#endif /*  */
        TEST(boost::nowide::stat(filename.c_str(), &stdStat) == 0);
        TEST(stdStat.st_size == testDataSize);
        boost::nowide::stat_t boostStat;
        TEST(boost::nowide::stat(filename.c_str(), &boostStat) == 0);
        TEST(boostStat.st_size == testDataSize);
    }

#ifdef BOOST_WINDOWS
    std::cout << " -- stat - invalid struct size" << std::endl;
    {
        struct _stat stdStat;
        // Simulate passing a struct that is 4 bytes smaller, e.g. if it uses 32 bit time field instead of 64 bit
        // Need to use the detail function directly
        TEST(boost::nowide::detail::stat(filename.c_str(), &stdStat, sizeof(stdStat) - 4u) == EINVAL);
        TEST(errno == EINVAL);
    }
#endif

    boost::nowide::remove(filename.c_str());
}


text:
using Skybrud.Social.Google.Analytics.Objects.Data;
using Skybrud.Social.Http;
using Skybrud.Social.Json;

namespace Skybrud.Social.Google.Analytics.Responses.Data {

    ///
    /// Class representing the response of a request to get Analytics realtime data.
    ///
    public class AnalyticsRealtimeDataResponse : AnalyticsResponse<AnalyticsDataResponseBody> {

        #region Constructors

        private AnalyticsRealtimeDataResponse(SocialHttpResponse response) : base(response) { }

        #endregion

        #region Static methods

        ///
        /// Parses the specified response into an instance of AnalyticsDataResponse.
        ///
        /// <param name="response">The response to be parsed.</param>
        /// <returns></returns>
        public static AnalyticsRealtimeDataResponse ParseResponse(SocialHttpResponse response) {

            if (response == null) return null;

            // Parse the raw JSON response
            JsonObject obj = response.GetBodyAsJsonObject();
            // TODO: Should we throw an exception here?
            if (obj == null) return null;

            // Validate the response
            ValidateResponse(response, obj);

            // Initialize the response object
            return new AnalyticsRealtimeDataResponse(response) {
                // TODO: Check whether the realtime data response body is the same as for historical data
                Body = AnalyticsDataResponseBody.Parse(obj)
            };

        }

        #endregion

    }

}


text:
package com.stoyanr.util;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * A generic Producer / Consumer executor. It starts a single producer task and multiple mediator
 * and consumer tasks with their number equal to the specified parallelism level. The producer puts
 * {@code T1} instances in a {@code BlockingQueue<T1>}. The mediators take these instances from
 * there, convert them to {@code T2}, and put them in another blocking queue of type
 * {@code BlockingQueue<T2>}. Finally, the consumers take the {@code T2} instances from the second
 * blocking queue and process them.
 *
 * @author Stoyan Rachev
 * @param <T1>
 * @param <T2>
 */
public class ProducerConsumerExecutor<T1, T2> {

    public static final int DEFAULT_PAR_LEVEL = Runtime.getRuntime().availableProcessors();

    public interface Producer<T> {
        void produce(java.util.function.Consumer<T> block);
    }

    public interface Consumer<T> {
        void consume(T t);
    }

    public interface Mediator<T1, T2> {
        void mediate(T1 t, java.util.function.Consumer<T2> block);
    }

    private final Producer<T1> producer;
    private final Mediator<T1, T2> mediator;
    private final Consumer<T2> consumer;
    private final int parLevel;
    private final BlockingQueue<T1> q1;
    private final BlockingQueue<T2> q2;
    private volatile ScheduledExecutorService producers = null;
    private volatile ScheduledExecutorService mediators = null;
    private volatile ScheduledExecutorService consumers = null;

    public ProducerConsumerExecutor(Producer<T1> producer, Mediator<T1, T2> mediator,
        Consumer<T2> consumer) {
        this(producer, mediator, consumer, DEFAULT_PAR_LEVEL);
    }

    public ProducerConsumerExecutor(Producer<T1> producer, Mediator<T1, T2> mediator,
        Consumer<T2> consumer, int parLevel) {
        if (producer == null || mediator == null || consumer == null) {
            throw new NullPointerException();
        }
        this.producer = producer;
        this.mediator = mediator;
        this.consumer = consumer;
        this.parLevel = parLevel;
        this.q1 = new LinkedBlockingQueue<>(parLevel);
        this.q2 = new LinkedBlockingQueue<>(parLevel);
    }

    public void execute() {
        if (producers != null || mediators != null || consumers != null) {
            throw new IllegalStateException();
        }
        q1.clear();
        q2.clear();
        producers = createProducers();
        mediators = createMediators();
        consumers = createConsumers();
        try {
            shutdown(producers);
            while (!q1.isEmpty()) {
                Thread.yield();
            }
            shutdown(mediators);
            while (!q2.isEmpty()) {
                Thread.yield();
            }
            shutdown(consumers);
        } catch (InterruptedException e) {
            throw new RuntimeException(String.format("Interrupted: %s", e.getMessage()), e);
        }
        producers = null;
        mediators = null;
        consumers = null;
    }

    private ScheduledExecutorService createProducers() {
        ScheduledExecutorService producers = new ScheduledThreadPoolExecutor(1);
        producers.submit(() -> producer.produce(this::put1x));
        return producers;
    }

    private ScheduledExecutorService createMediators() {
        ScheduledExecutorService mediators = new ScheduledThreadPoolExecutor(parLevel);
        for (int i = 0; i < parLevel; i++) {
            mediators.submit(() -> mediate(mediator, this::put2x));
        }
        return mediators;
    }

    private ScheduledExecutorService createConsumers() {
        ScheduledExecutorService consumers = new ScheduledThreadPoolExecutor(parLevel);
        for (int i = 0; i < parLevel; i++) {
            consumers.submit(() -> consume(consumer));
        }
        return consumers;
    }

    private boolean shutdown(ScheduledExecutorService ses) throws InterruptedException {
        ses.shutdown();
        return ses.awaitTermination(24, TimeUnit.HOURS);
    }

    private void mediate(Mediator<T1, T2> mediator, java.util.function.Consumer<T2> block) {
        boolean finished = false;
        while (!finished) {
            try {
                T1 t = take1();
                if (t != null) {
                    mediator.mediate(t, block);
                } else {
                    finished = true;
                }
            } catch (InterruptedException e) {
                finished = true;
            }
        }
    }

    private void consume(Consumer<T2> consumer) {
        boolean finished = false;
        while (!finished) {
            try {
                T2 t = take2();
                if (t != null) {
                    consumer.consume(t);
                } else {
                    finished = true;
                }
            } catch (InterruptedException e) {
                finished = true;
            }
        }
    }

    private void put1x(T1 t) {
        try {
            put1(t);
        } catch (InterruptedException e) {
        }
    }

    private void put2x(T2 t) {
        try {
            put2(t);
        } catch (InterruptedException e) {
        }
    }

    private void put1(T1 t) throws InterruptedException {
        logDone("Producer", t);
        long t0 = logQueueFull("Producer", q1);
        q1.put(t);
        logWaitTime("Producer", t0);
    }

    private T1 take1() throws InterruptedException {
        long t0 = logQueueEmpty("Mediator", q1);
        T1 t;
        do {
            t = q1.poll(1, TimeUnit.MILLISECONDS);
        } while (t == null && !mediators.isShutdown());
        logWaitTime("Mediator", t0);
        logDone("Mediator", t);
        return t;
    }

    private void put2(T2 t) throws InterruptedException {
        logDone("Mediator", t);
        long t0 = logQueueFull("Mediator", q2);
        q2.put(t);
        logWaitTime("Mediator", t0);
    }

    private T2 take2() throws InterruptedException {
        long t0 = logQueueEmpty("Consumer", q2);
        T2 t;
        do {
            t = q2.poll(1, TimeUnit.MILLISECONDS);
        } while (t == null && !consumers.isShutdown());
        logWaitTime("Consumer", t0);
        logDone("Consumer", t);
        return t;
    }

    private <T> long logQueueFull(String name, BlockingQueue<T> q) {
        long t0 = 0;
        if (Logger.isDebug() && q.remainingCapacity() == 0) {
            Logger.debug("[%s (%s)] Queue full, waiting ...", name, getThreadName());
            t0 = System.nanoTime();
        }
        return t0;
    }

    private void logWaitTime(String name, long t0) {
        if (Logger.isDebug() && t0 != 0) {
            long t1 = System.nanoTime();
            Logger.debug("[%s (%s)] Waited for %.2f us", name, getThreadName(), ((double) (t1 - t0)) / 1000);
        }
    }

    private <T> void logDone(String name, T t) {
        if (Logger.isDebug() && t!= null) {
            Logger.debug("[%s (%s)] Done '%s'", name, getThreadName(), trim(t.toString()));
        }
    }

    private <T> long logQueueEmpty(String name, BlockingQueue<T> q) {
        long t0 = 0;
        if (Logger.isDebug() && q.isEmpty()) {
            Logger.debug("[%s (%s)] Queue empty, waiting ...", name, getThreadName());
            t0 = System.nanoTime();
        }
        return t0;
    }

    private static String trim(String text) {
        return text.substring(0, Math.min(text.length(), 20));
    }

    private static String getThreadName() {
        return Thread.currentThread().getName();
    }

}


text:
/**
 * Adds parameters to the Instance's attributes.
 *
 * @param {Object} attributes The attributes to add.
 *
 * @returns {undefined}
 */
Instance.prototype.add = function( attributes ) {
    // Loop through each attribute specified (as `attr`).
    Object.keys(attributes).forEach(function (attr) {
        // Append the new attribute to the instance's attributes object variable (this.attributes).
        // eg:
        // this.attributes = {name: "Adam"}
        // this.attributes["handle"] = "@adammcarth"
        // => {name: "Adam", handle: "@adammcarth"}
        this.attributes[attr] = attributes[attr];
    }, this);
};

/**
 * Watches html input form elements and continuously updates instance attributes with their current value.
 *
 * @param {Array} names An array of form element to watch.
 *
 * @returns {undefined}
 */
Instance.prototype.addField = function( names ) {
    // Convert `names` to an array if it is a string
    names = this.ensureArray( names );

    // Add the field names to the instance's fields variable, and
    // we'll use it later to retrieve the latest values from the inputs.
    this.fields = this.fields.concat( names );
};

/**
 * Watches html elements (using their #) and continuously updates intance attributes with their current value.
 *
 * @param {Array} ids An array of form element id's to watch.
 *
 * @returns {undefined}
 */
Instance.prototype.addElement = function( ids ) {
    // Convert `ids` to an array if it is a string
    ids = this.ensureArray( ids );

    // Add the element id's to the instance's elements variable, and
    // we'll use it later to retrieve the latest html content from the elements.
    this.elements = this.elements.concat( ids );
};


text:
/* http://localhost:1841/ext/packages/font-ext/sass/etc/all.scss:5 */
@font-face {
    font-family: 'ExtJS';
    src: url('font-ext/fonts/ExtJS.eot?7f8uzy');
    src: url('font-ext/fonts/ExtJS.eot?#iefix7f8uzy') format('embedded-opentype'), url('font-ext/fonts/ExtJS.woff?7f8uzy') format('woff'), url('font-ext/fonts/ExtJS.ttf?7f8uzy') format('truetype'), url('font-ext/fonts/ExtJS.svg?7f8uzy#ExtJS') format('svg');
    font-weight: normal;
    font-style: normal;
}


text:
PropertyDef::PropertyDef(){
	memset(tp,'\0',NAMELENGTH);
   memset(nm,'\0',NAMELENGTH);
}

PropertyDef::PropertyDef(char *t, char *n, int typ){
	memset(tp,'\0',NAMELENGTH);
   memset(nm,'\0',NAMELENGTH);
   setName(t);
   setPropName(n);
   setDataType(typ);
}

PropertyDef::PropertyDef(char *t, char *n){
	memset(tp,'\0',NAMELENGTH);
   memset(nm,'\0',NAMELENGTH);
   setName(t);
   setPropName(n);
   setDataType(_VARIABLE_);
}

PropertyDef::~PropertyDef(){}

char *PropertyDef::getName(void){
	return tp;
}

void PropertyDef::setName(char *t){
	strcpy(tp,t);
}

char *PropertyDef::getPropName(void){
	return nm;
}

void PropertyDef::setPropName(char *p){
	strcpy(nm,p);
}

int PropertyDef::getDataType(void){
	return datatype;
}

void PropertyDef::setDataType(int i){
	datatype=i;
}

//-----------------------------------------------------------------------
// generic parse tree stuff
//-----------------------------------------------------------------------

template <class T> LinkedList<T>::LinkedList(){
	next=NULL;
   element=NULL;
}

template <class T> LinkedList<T>::LinkedList(T *elem){
	next=NULL;
   element=elem;
}

template <class T> LinkedList<T>::~LinkedList(){
	if (next!=NULL) delete next;
   delete element;
}

template <class T> LinkedList * LinkedList<T>::getNextListElem(){
	return next;
}

template <class T> void LinkedList<T>::setNextListElem(LinkedList *ne){
	next=ne;
}

template <class T> T *LinkedList<T>::getElem(){
	return element;
}

template <class T> int LinkedList<T>::insertElem(T *elem){
LinkedList *ptr, *ne;
	ptr=this;
   	while(ptr->getNextListElem()!=NULL){
      	ptr=ptr->getNextListElem();
      }

      ne=new LinkedList(elem);
      ptr->setNextListElem(ne);
      return 1;
}

template <class T> T *LinkedList<T>::getElemNamed(char *nm){
	if (element==NULL) return NULL;
	if (strcmp(element->getName(),nm)==0) return element;
   if (next!=NULL) return next->getElemNamed(nm);
   else return NULL;
}

//-----------------------------------------------------------------------------
// variable stuff
//-----------------------------------------------------------------------------
variable::variable(void){
	memset(name,'\0',NAMELENGTH);
   tp=-1;
   typeref=NULL;
   intval=0;
   realval=0;
   setval=NULL;
   charval=NULL;
   objval=NULL;
}

variable::variable(char *tpnm, int t, ODB_TYPE r){
	if (tpnm!=NULL) strcpy(name,tpnm);
   else generateName();
   tp=t;
   typeref=r;
   intval=0;
   realval=0;
   setval=NULL;
   charval=NULL;
   objval=NULL;
}

void variable::generateName(void){

	sprintf(name,"_ODBVariable_%i_",variable::autoEnum);
   variable::autoEnum++;
}

variable::~variable(void){
}

char *variable::getName(void){
	return name;
}

int variable::getType(void){
	return tp;
}

ODB_TYPE variable::getTypeRef(void){
	return typeref;
}

ODB_INT variable::getIntval(void){
return intval;
}

ODB_REAL variable::getRealval(void){
	return realval;
}

ODB_SET	variable::getSetval(void){
	return setval;
}

ODB_CHAR	variable::getCharval(void){
	return charval;
}

ODB_REF	variable::getObjval(void){
	return objval;
}

void variable::setName(char *n){
	strcpy(name,n);
}

void variable::setType(int t){
	tp=t;
}

void variable::setTypeRef(ODB_TYPE t){
	typeref=t;
}

void variable::setIntval(ODB_INT i){
	intval=i;
}

void variable::setRealval(ODB_REAL r){
	realval=r;
}

void variable::setSetval(ODB_SET s){
	setval=s;
}

void variable::setCharval(ODB_CHAR c){
	charval=c;
}

void variable::setObjval(ODB_REF r){
	objval=r;
}


text:
require 'rubygems'
require 'test/unit'
require 'shoulda'
require "mocha"
require "action_controller"
require 'active_resource'
require 'active_record'
require 'active_support'
require "active_record/base"
require "active_record/associations"

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'rails_relations_fix'

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Base.configurations = true

ActiveRecord::Schema.verbose = false
ActiveRecord::Schema.define(:version => 1) do
  create_table :users do |t|
    t.string :name
    t.integer :movies_count
  end

  create_table :movies do |t|
    t.string :name
    t.string :subject_type
    t.integer :subject_id
  end

end

class Test::Unit::TestCase

  class User < ActiveRecord::Base
    has_many :movies, :as => :subject
  end

  class Movie < ActiveRecord::Base
    belongs_to :subject, :polymorphic => true, :counter_cache => true
  end
end


text:
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Dummy implementation of the ajax page loader
 */
var AJAX = {
    registerOnload: function (idx, func) {
        $(document).ready(func);
    },
    registerTeardown: function (idx, func) {
    }
};


text:
package com.badlogic.gdx.utils;

import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.LifecycleListener;

/** Executes tasks in the future on the main loop thread.
 * @author Nathan Sweet */
public class Timer {
	static final Array<Timer> instances = new Array(1);
	static TimerThread thread;
	static private final int CANCELLED = -1;
	static private final int FOREVER = -2;

	/** Timer instance for general application wide usage. Static methods on {@link Timer} make convenient use of this instance. */
	static Timer instance = new Timer();

	static public Timer instance () {
		if (instance == null) {
			instance = new Timer();
		}
		return instance;
	}

	private final Array<Task> tasks = new Array(false, 8);

	public Timer () {
		start();
	}

	/** Schedules a task to occur once as soon as possible, but not sooner than the start of the next frame. */
	public Task postTask (Task task) {
		return scheduleTask(task, 0, 0, 0);
	}

	/** Schedules a task to occur once after the specified delay. */
	public Task scheduleTask (Task task, float delaySeconds) {
		return scheduleTask(task, delaySeconds, 0, 0);
	}

	/** Schedules a task to occur once after the specified delay and then repeatedly at the specified interval until cancelled. */
	public Task scheduleTask (Task task, float delaySeconds, float intervalSeconds) {
		return scheduleTask(task, delaySeconds, intervalSeconds, FOREVER);
	}

	/** Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval. */
	public Task scheduleTask (Task task, float delaySeconds, float intervalSeconds, int repeatCount) {
		if (task.repeatCount != CANCELLED) throw new IllegalArgumentException("The same task may not be scheduled twice.");
		task.executeTimeMillis = System.nanoTime() / 1000000 + (long)(delaySeconds * 1000);
		task.intervalMillis = (long)(intervalSeconds * 1000);
		task.repeatCount = repeatCount;
		synchronized (tasks) {
			tasks.add(task);
		}
		wake();

		return task;
	}

	/** Stops the timer, tasks will not be executed and time that passes will not be applied to the task delays. */
	public void stop () {
		synchronized (instances) {
			instances.removeValue(this, true);
		}
	}

	/** Starts the timer if it was stopped. */
	public void start () {
		synchronized (instances) {
			if (instances.contains(this, true)) return;
			instances.add(this);
			if (thread == null) thread = new TimerThread();
			wake();
		}
	}

	/** Cancels all tasks. */
	public void clear () {
		synchronized (tasks) {
			for (int i = 0, n = tasks.size; i < n; i++)
				tasks.get(i).cancel();
			tasks.clear();
		}
	}

	long update (long timeMillis, long waitMillis) {
		synchronized (tasks) {
			for (int i = 0, n = tasks.size; i < n; i++) {
				Task task = tasks.get(i);
				if (task.executeTimeMillis > timeMillis) {
					waitMillis = Math.min(waitMillis, task.executeTimeMillis - timeMillis);
					continue;
				}
				if (task.repeatCount != CANCELLED) {
					if (task.repeatCount == 0) {
						// Set cancelled before run so it may be rescheduled in run.
						task.repeatCount = CANCELLED;
					}
					Gdx.app.postRunnable(task);
				}
				if (task.repeatCount == CANCELLED) {
					tasks.removeIndex(i);
					i--;
					n--;
				} else {
					task.executeTimeMillis = timeMillis + task.intervalMillis;
					waitMillis = Math.min(waitMillis, task.intervalMillis);
					if (task.repeatCount > 0) task.repeatCount--;
				}
			}
		}
		return waitMillis;
	}

	/** Adds the specified delay to all tasks. */
	public void delay (long delayMillis) {
		synchronized (tasks) {
			for (int i = 0, n = tasks.size; i < n; i++) {
				Task task = tasks.get(i);
				task.executeTimeMillis += delayMillis;
			}
		}
	}

	static void wake () {
		synchronized (instances) {
			instances.notifyAll();
		}
	}

	/** Schedules a task on {@link #instance}.
	 * @see #postTask(Task) */
	static public Task post (Task task) {
		return instance().postTask(task);
	}

	/** Schedules a task on {@link #instance}.
	 * @see #scheduleTask(Task, float) */
	static public Task schedule (Task task, float delaySeconds) {
		return instance().scheduleTask(task, delaySeconds);
	}

	/** Schedules a task on {@link #instance}.
	 * @see #scheduleTask(Task, float, float) */
	static public Task schedule (Task task, float delaySeconds, float intervalSeconds) {
		return instance().scheduleTask(task, delaySeconds, intervalSeconds);
	}

	/** Schedules a task on {@link #instance}.
	 * @see #scheduleTask(Task, float, float, int) */
	static public Task schedule (Task task, float delaySeconds, float intervalSeconds, int repeatCount) {
		return instance().scheduleTask(task, delaySeconds, intervalSeconds, repeatCount);
	}

	/** Runnable with a cancel method.
	 * @see Timer
	 * @author Nathan Sweet */
	static abstract public class Task implements Runnable {
		long executeTimeMillis;
		long intervalMillis;
		int repeatCount = CANCELLED;

		/** If this is the last time the task will be ran or the task is first cancelled, it may be scheduled again in this method. */
		abstract public void run ();

		/** Cancels the task. It will not be executed until it is scheduled again. This method can be called at any time. */
		public void cancel () {
			executeTimeMillis = 0;
			repeatCount = CANCELLED;
		}

		/** Returns true if this task is scheduled to be executed in the future by a timer. */
		public boolean isScheduled () {
			return repeatCount != CANCELLED;
		}

		/** Returns the time when this task will be executed in milliseconds */
		public long getExecuteTimeMillis () {
			return executeTimeMillis;
		}
	}

	/** Manages the single timer thread. Stops thread on libgdx application pause and dispose, starts thread on resume.
	 * @author Nathan Sweet */
	static class TimerThread implements Runnable, LifecycleListener {
		Application app;
		private long pauseMillis;

		public TimerThread () {
			Gdx.app.addLifecycleListener(this);
			resume();
		}

		public void run () {
			while (true) {
				synchronized (instances) {
					if (app != Gdx.app) return;

					long timeMillis = System.nanoTime() / 1000000;
					long waitMillis = 5000;
					for (int i = 0, n = instances.size; i < n; i++) {
						try {
							waitMillis = instances.get(i).update(timeMillis, waitMillis);
						} catch (Throwable ex) {
							throw new GdxRuntimeException("Task failed: " + instances.get(i).getClass().getName(), ex);
						}
					}

					if (app != Gdx.app) return;

					try {
						if (waitMillis > 0) instances.wait(waitMillis);
					} catch (InterruptedException ignored) {
					}
				}
			}
		}

		public void resume () {
			long delayMillis = System.nanoTime() / 1000000 - pauseMillis;
			synchronized (instances) {
				for (int i = 0, n = instances.size; i < n; i++) {
					instances.get(i).delay(delayMillis);
				}
			}
			app = Gdx.app;
			Thread t = new Thread(this, "Timer");
			t.setDaemon(true);
			t.start();
			thread = this;
		}

		public void pause () {
			pauseMillis = System.nanoTime() / 1000000;
			synchronized (instances) {
				app = null;
				wake();
			}
			thread = null;
		}

		public void dispose () {
			pause();
			Gdx.app.removeLifecycleListener(this);
			instances.clear();
			instance = null;
		}
	}
}


text:
<?php

namespace Pfe\Bundle\WebBundle\Controller\Frontend;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class PageController extends Controller
{
    public function homeAction()
    {
        return $this->render('PfeWebBundle:Frontend/Page:home.html.twig');
    }
}