text:
package service

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

	"github.com/control-center/serviced/datastore"
	"github.com/control-center/serviced/domain"
	"github.com/control-center/serviced/domain/addressassignment"
	"github.com/control-center/serviced/domain/servicedefinition"
	"github.com/control-center/serviced/health"
	"github.com/control-center/serviced/utils"
	"github.com/zenoss/glog"
)

// Desired states of services.
type DesiredState int

var protocolPrefixRegex = regexp.MustCompile("^(.+://)")

func (state DesiredState) String() string {
	switch state {
	case SVCRestart:
		return "restart"
	case SVCStop:
		return "stop"
	case SVCRun:
		return "go"
	case SVCPause:
		return "pause"
	default:
		return "unknown"
	}
}

const (
	SVCRestart = DesiredState(-1)
	SVCStop    = DesiredState(0)
	SVCRun     = DesiredState(1)
	SVCPause   = DesiredState(2)
)

// Service A Service that can run in serviced.
type Service struct {
	ID                string
	Name              string
	Title             string // Title is a label used when describing this service in the context of a service tree
	Version           string
	Context           map[string]interface{}
	Startup           string
	Description       string
	Tags              []string
	OriginalConfigs   map[string]servicedefinition.ConfigFile
	ConfigFiles       map[string]servicedefinition.ConfigFile
	Instances         int
	InstanceLimits    domain.MinMax
	ChangeOptions     []string
	ImageID           string
	PoolID            string
	DesiredState      int
	HostPolicy        servicedefinition.HostPolicy
	Hostname          string
	Privileged        bool
	Launch            string
	Endpoints         []ServiceEndpoint
	Tasks             []servicedefinition.Task
	ParentServiceID   string
	Volumes           []servicedefinition.Volume
	CreatedAt         time.Time
	UpdatedAt         time.Time
	DeploymentID      string
	DisableImage      bool
	LogConfigs        []servicedefinition.LogConfig
	Snapshot          servicedefinition.SnapshotCommands
	DisableShell      bool
	Runs              map[string]string // FIXME: This field is deprecated. Remove when possible.
	Commands          map[string]domain.Command
	RAMCommitment     utils.EngNotation
	CPUCommitment     uint64
	Actions           map[string]string
	HealthChecks      map[string]health.HealthCheck // A health check for the service.
	Prereqs           []domain.Prereq               // Optional list of scripts that must be successfully run before kicking off the service command.
	MonitoringProfile domain.MonitorProfile
	MemoryLimit       float64
	CPUShares         int64
	PIDFile           string
	datastore.VersionedEntity
}

//ServiceEndpoint endpoint exported or imported by a service
type ServiceEndpoint struct {
	Name                string // Human readable name of the endpoint. Unique per service definition
	Purpose             string
	Protocol            string
	PortNumber          uint16
	PortTemplate        string // A template which, if specified, is used to calculate the port number
	VirtualAddress      string // An address by which an imported endpoint may be accessed within the container, e.g. "mysqlhost:1234"
	Application         string
	ApplicationTemplate string
	AddressConfig       servicedefinition.AddressResourceConfig
	VHosts              []string // VHost is used to request named vhost for this endpoint. Should be the name of a
	// subdomain, i.e "myapplication"  not "myapplication.host.com"
	VHostList         []servicedefinition.VHost // VHost is used to request named vhost(s) for this endpoint.
	AddressAssignment addressassignment.AddressAssignment
	PortList          []servicedefinition.Port // The list of enabled/disabled ports to assign to this endpoint.
}

// IsConfigurable returns true if the endpoint is configurable
func (endpoint ServiceEndpoint) IsConfigurable() bool {
	return endpoint.AddressConfig.Port > 0 && endpoint.AddressConfig.Protocol != ""
}

// NewService Create a new Service.
func NewService() (s *Service, err error) {
	s = &Service{}
	s.ID, err = utils.NewUUID36()
	return s, err
}

// HasEndpointsFor determines if the service has any imports
// for the specified purpose, eg import
func (s *Service) HasEndpointsFor(purpose string) bool {
	if s.Endpoints == nil {
		return false
	}

	for _, ep := range s.Endpoints {
		if ep.Purpose == purpose {
			return true
		}
	}
	return false
}

//BuildServiceEndpoint build a ServiceEndpoint from a EndpointDefinition
func BuildServiceEndpoint(epd servicedefinition.EndpointDefinition) ServiceEndpoint {
	sep := ServiceEndpoint{}
	sep.Name = epd.Name
	sep.Purpose = epd.Purpose
	sep.Protocol = epd.Protocol
	sep.PortNumber = epd.PortNumber
	sep.PortTemplate = epd.PortTemplate
	sep.VirtualAddress = epd.VirtualAddress
	sep.Application = epd.Application
	sep.ApplicationTemplate = epd.ApplicationTemplate
	sep.AddressConfig = epd.AddressConfig
	sep.VHosts = epd.VHosts
	sep.VHostList = epd.VHostList
	sep.PortList = epd.PortList

	// run public ports through scrubber to allow for "almost correct" port addresses
	for index, port := range sep.PortList {
		sep.PortList[index].PortAddr = ScrubPortString(port.PortAddr)
	}
	return sep
}

//BuildService build a service from a ServiceDefinition.
func BuildService(sd servicedefinition.ServiceDefinition, parentServiceID string, poolID string, desiredState int, deploymentID string) (*Service, error) {
	svcuuid, err := utils.NewUUID36()
	if err != nil {
		return nil, err
	}

	now := time.Now()

	svc := Service{}
	svc.ID = svcuuid
	svc.Name = sd.Name
	svc.Title = sd.Title
	svc.Version = sd.Version
	svc.Context = sd.Context
	svc.Startup = sd.Command
	svc.Description = sd.Description
	svc.Tags = sd.Tags
	if sd.Instances.Default != 0 {
		svc.Instances = sd.Instances.Default
	} else {
		svc.Instances = sd.Instances.Min
	}
	svc.InstanceLimits = sd.Instances
	svc.ChangeOptions = sd.ChangeOptions
	svc.ImageID = sd.ImageID
	svc.PoolID = poolID
	svc.DesiredState = desiredState
	svc.Launch = sd.Launch
	svc.HostPolicy = sd.HostPolicy
	svc.Hostname = sd.Hostname
	svc.Privileged = sd.Privileged
	svc.OriginalConfigs = sd.ConfigFiles
	svc.ConfigFiles = sd.ConfigFiles
	svc.Tasks = sd.Tasks
	svc.ParentServiceID = parentServiceID
	svc.CreatedAt = now
	svc.UpdatedAt = now
	svc.Volumes = sd.Volumes
	svc.DeploymentID = deploymentID
	svc.LogConfigs = sd.LogConfigs
	svc.Snapshot = sd.Snapshot
	svc.RAMCommitment = sd.RAMCommitment
	svc.CPUCommitment = sd.CPUCommitment
	svc.DisableShell = sd.DisableShell
	svc.Runs = sd.Runs
	svc.Commands = sd.Commands
	svc.Actions = sd.Actions
	svc.HealthChecks = sd.HealthChecks
	svc.Prereqs = sd.Prereqs
	svc.PIDFile = sd.PIDFile

	svc.Endpoints = make([]ServiceEndpoint, 0)
	for _, ep := range sd.Endpoints {
		svc.Endpoints = append(svc.Endpoints, BuildServiceEndpoint(ep))
	}

	tags := map[string][]string{
		"controlplane_service_id": []string{svc.ID},
	}
	profile, err := sd.MonitoringProfile.ReBuild("1h-ago", tags)
	if err != nil {
		return nil, err
	}
	svc.MonitoringProfile = *profile
	svc.MemoryLimit = sd.MemoryLimit
	svc.CPUShares = sd.CPUShares

	return &svc, nil
}

//CloneService copies a service and mutates id and names
func CloneService(fromSvc *Service, suffix string) (*Service, error) {
	svcuuid, err := utils.NewUUID36()
	if err != nil {
		return nil, err
	}

	svc := *fromSvc
	svc.ID = svcuuid
	svc.DesiredState = int(SVCStop)

	now := time.Now()
	svc.CreatedAt = now
	svc.UpdatedAt = now

	// add suffix to make certain things unique
	suffix = strings.TrimSpace(suffix)
	if len(suffix) == 0 {
		suffix = "-" + svc.ID[0:12]
	}
	svc.Name += suffix
	for idx, ep := range svc.Endpoints {
		if ep.Purpose == "export" {
			svc.Endpoints[idx].Name += suffix
			svc.Endpoints[idx].Application += suffix
			svc.Endpoints[idx].ApplicationTemplate += suffix
		}
	}
	for idx := range svc.Volumes {
		svc.Volumes[idx].ResourcePath += suffix
	}

	return &svc, nil
}

// GetServiceImports retrieves service endpoints whose purpose is "import"
func (s *Service) GetServiceImports() []ServiceEndpoint {
	result := []ServiceEndpoint{}

	if s.Endpoints != nil {
		for _, ep := range s.Endpoints {
			if ep.Purpose == "import" || ep.Purpose == "import_all" {
				result = append(result, ep)
			}
		}
	}

	return result
}

// GetServiceExports retrieves service endpoints whose purpose is "export"
func (s *Service) GetServiceExports() []ServiceEndpoint {
	result := []ServiceEndpoint{}

	if s.Endpoints != nil {
		for _, ep := range s.Endpoints {
			if ep.Purpose == "export" {
				result = append(result, ep)
			}
		}
	}

	return result
}

// GetServiceVHosts retrieves service endpoints that specify a virtual HostPort
func (s *Service) GetServiceVHosts() []ServiceEndpoint {
	result := []ServiceEndpoint{}

	if s.Endpoints != nil {
		for _, ep := range s.Endpoints {
			if len(ep.VHostList) > 0 {
				result = append(result, ep)
			}
		}
	}

	return result
}

// GetServicePorts retrieves service endpoints that specify additional port(s)
func (s *Service) GetServicePorts() []ServiceEndpoint {
	result := []ServiceEndpoint{}

	if s.Endpoints != nil {
		for _, ep := range s.Endpoints {
			if len(ep.PortList) > 0 {
				result = append(result, ep)
			}
		}
	}

	return result
}

// AddVirtualHost Add a virtual host for given service, this method avoids duplicates vhosts
func (s *Service) AddVirtualHost(application, vhostName string) error {
	if s.Endpoints != nil {

		//find the matching endpoint
		for i := range s.Endpoints {
			ep := &s.Endpoints[i]

			if ep.Application == application && ep.Purpose == "export" {
				_vhostName := strings.ToLower(vhostName)
				vhosts := make([]servicedefinition.VHost, 0)
				for _, vhost := range ep.VHostList {
					if strings.ToLower(vhost.Name) != _vhostName {
						vhosts = append(vhosts, vhost)
					}
				}
				ep.VHostList = append(vhosts, servicedefinition.VHost{Name: _vhostName, Enabled: true})
				return nil
			}
		}
	}

	return fmt.Errorf("unable to find application %s in service: %s", application, s.Name)
}

// AddPort Add a port for given service, this method avoids duplicate ports
func (s *Service) AddPort(application string, portAddr string) error {
	portAddr = ScrubPortString(portAddr)
	if s.Endpoints != nil {
		//find the matching endpoint
		for i := range s.Endpoints {
			ep := &s.Endpoints[i]

			if ep.Application == application && ep.Purpose == "export" {
				var ports = make([]servicedefinition.Port, 0)
				for _, port := range ep.PortList {
					if port.PortAddr != portAddr {
						ports = append(ports, port)
					}
				}
				ep.PortList = append(ports, servicedefinition.Port{PortAddr: portAddr, Enabled: true})
				return nil
			}
		}
	}

	return fmt.Errorf("unable to find application %s in service: %s", application, s.Name)
}

// RemovePort Remove a port for given service
func (s *Service) RemovePort(application string, portAddr string) error {
	if s.Endpoints == nil {
		return fmt.Errorf("Service %s has no Endpoints", s.Name)
	}

	//find the matching endpoint
	for i := range s.Endpoints {
		ep := &s.Endpoints[i]

		if ep.Application == application && ep.Purpose == "export" {
			if len(ep.PortList) == 0 {
				break
			}

			found := false
			var ports = make([]servicedefinition.Port, 0)
			for _, port := range ep.PortList {
				if port.PortAddr != portAddr {
					ports = append(ports, port)
				} else {
					found = true
				}
			}

			//error removing an unknown vhost
			if !found {
				break
			}

			ep.PortList = ports
			return nil
		}
	}

	return fmt.Errorf("unable to find application %s in service: %s", application, s.Name)
}

// EnablePort enables or disables a port for given service
func (s *Service) EnablePort(application string, portAddr string, enable bool) error {
	appFound := false
	portFound := false
	for _, ep := range s.GetServicePorts() {
		if ep.Application == application {
			appFound = true
			for i, port := range ep.PortList {
				if port.PortAddr == portAddr {
					portFound = true
					ep.PortList[i].Enabled = enable
					glog.V(1).Infof("Enable port %s for %s %s set to %v", portAddr, s.ID, application, enable)
				}
			}
		}
	}
	if !appFound {
		return fmt.Errorf("port %s not found; application %s not found in service %s:%s", portAddr, application, s.ID, s.Name)
	}
	if !portFound {
		return fmt.Errorf("port %s not found in service %s:%s", portAddr, s.ID, s.Name)
	}

	return nil
}

// Make best effort to make a port address valid
func ScrubPortString(port string) string {
	// remove possible protocol at string beginning
	scrubbed := protocolPrefixRegex.ReplaceAllString(port, "")

	matched, _ := regexp.MatchString("^[0-9]+$", scrubbed)
	if matched {
		scrubbed = fmt.Sprintf(":%s", scrubbed)
	}

	return scrubbed
}

// EnableVirtualHost enable or disable a virtual host for given service
func (s *Service) EnableVirtualHost(application, vhostName string, enable bool) error {
	appFound := false
	vhostFound := false
	for _, ep := range s.GetServiceVHosts() {
		if ep.Application == application {
			appFound = true
			for i, vhost := range ep.VHostList {
				if vhost.Name == vhostName {
					vhostFound = true
					ep.VHostList[i].Enabled = enable
					glog.V(1).Infof("enable vhost %s for %s %s set to %v", vhostName, s.ID, application, enable)
				}
			}
		}
	}
	if !appFound {
		return fmt.Errorf("vhost %s not found; application %s not found in service %s:%s", vhostName, application, s.ID, s.Name)
	}
	if !vhostFound {
		return fmt.Errorf("vhost %s not found in service %s:%s", vhostName, s.ID, s.Name)
	}

	return nil
}

// RemoveVirtualHost Remove a virtual host for given service
func (s *Service) RemoveVirtualHost(application, vhostName string) error {
	if s.Endpoints != nil {

		//find the matching endpoint
		for i := range s.Endpoints {
			ep := &s.Endpoints[i]

			if ep.Application == application && ep.Purpose == "export" {
				if len(ep.VHostList) == 0 {
					break
				}

				_vhostName := strings.ToLower(vhostName)
				found := false
				var vhosts = make([]servicedefinition.VHost, 0)
				for _, vhost := range ep.VHostList {
					if vhost.Name != _vhostName {
						vhosts = append(vhosts, vhost)
					} else {
						found = true
					}
				}
				//error removing an unknown vhost
				if !found {
					break
				}

				ep.VHostList = vhosts
				return nil
			}
		}
	}

	return fmt.Errorf("unable to find application %s in service: %s", application, s.Name)
}

// GetPath uses the GetService function to determine the / delimited name path i.e. /test/app/sevicename
func (s Service) GetPath(gs GetService) (string, error) {
	var err error
	svc := s
	path := fmt.Sprintf("/%s", s.Name)
	for svc.ParentServiceID != "" {
		svc, err = gs(svc.ParentServiceID)
		if err != nil {
			return "", err
		}
		path = fmt.Sprintf("/%s%s", svc.Name, path)
	}
	return path, nil
}

//SetAssignment sets the AddressAssignment for the endpoint
func (se *ServiceEndpoint) SetAssignment(aa addressassignment.AddressAssignment) error {
	if se.AddressConfig.Port == 0 {
		return errors.New("cannot assign address to endpoint without AddressResourceConfig")
	}
	se.AddressAssignment = aa
	return nil
}

//RemoveAssignment resets a service endpoints to nothing
func (se *ServiceEndpoint) RemoveAssignment() error {
	se.AddressAssignment = addressassignment.AddressAssignment{}
	return nil
}

//GetAssignment Returns nil if no assignment set
func (se *ServiceEndpoint) GetAssignment() *addressassignment.AddressAssignment {
	if se.AddressAssignment.ID == "" {
		return nil
	}
	//return reference to copy
	result := se.AddressAssignment
	return &result
}

//Equals are they the same
func (s *Service) Equals(b *Service) bool {
	if s.ID != b.ID {
		return false
	}
	if s.Name != b.Name {
		return false
	}
	if s.Version != b.Version {
		return false
	}
	if !reflect.DeepEqual(s.Context, b.Context) {
		return false
	}
	if s.Startup != b.Startup {
		return false
	}
	if s.Description != b.Description {
		return false
	}
	if s.Instances != b.Instances {
		return false
	}
	if s.ImageID != b.ImageID {
		return false
	}
	if s.PoolID != b.PoolID {
		return false
	}
	if s.DesiredState != b.DesiredState {
		return false
	}
	if s.Launch != b.Launch {
		return false
	}
	if s.Hostname != b.Hostname {
		return false
	}
	if s.Privileged != b.Privileged {
		return false
	}
	if s.HostPolicy != b.HostPolicy {
		return false
	}
	if s.ParentServiceID != b.ParentServiceID {
		return false
	}
	if s.CreatedAt.Unix() != b.CreatedAt.Unix() {
		return false
	}
	if s.UpdatedAt.Unix() != b.UpdatedAt.Unix() {
		return false
	}
	return true
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Ziziphora kurdica Rech.f.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
class Solution {
    struct Info {
        int cost=0;
        int time_left=0;
        int node=0;
    };
    vector<int> fees;

    // key_outer: from node
    // key_inner: to node
    // value: min cost of all such direct roads
    unordered_map<int, unordered_map<int, int>> adj_list;

    void addRoad(int from, int to, int cost) {
        if (adj_list[from].find(to) == adj_list[from].end()) {
            adj_list[from][to] = cost;
        } else {
            adj_list[from][to] = std::min(adj_list[from][to], cost);
        }
    }

    void populate(const vector<vector<int>>& edges) {
        for (const vector<int>& edge : edges) {
            addRoad(edge[0], edge[1], edge[2]);
            addRoad(edge[1], edge[0], edge[2]);
        }
    }

    function<bool(const Info&, const Info&)> comp = [](const Info& lhs, const Info& rhs) -> bool {
        if (lhs.time_left != rhs.time_left) {return lhs.time_left < rhs.time_left;}
        if (lhs.cost != rhs.cost) {return lhs.cost > rhs.cost;}
        return lhs.node > rhs.node;
    };

    using MinHeap = priority_queue<Info, vector<Info>, decltype(comp)>;
public:
    int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& passingFees) {
        fees = passingFees;
        int n = fees.size();
        populate(edges);

        int best = std::numeric_limits<int>::max();
        MinHeap min_heap(comp);

        // visited key:node with (time_left, cost so far)
        // the idea is that if you visit this node AGAIN with both
        //       time_left < recorded AND
        //       cost > recorded
        // then we can prune that path
        unordered_map<int, pair<int, int>> visited;

        visited[0] = {maxTime, fees[0]};
        min_heap.push({fees[0], maxTime, 0});

        while (!min_heap.empty()) {
            auto elem = min_heap.top(); min_heap.pop();
            if (elem.node == n-1) {  // destination
                best = std::min(best, elem.cost);
                continue;
            }

            for (const auto& kv : adj_list[elem.node]) {
                int neigh = kv.first;
                int time = kv.second;
                int my_cost = elem.cost + fees[neigh];
                int my_time = elem.time_left - time;

                // 3 types of pruning.

                // Don't have enough time to traverse road!
                if (time > elem.time_left) continue;

                // Already incurred too much of a cost, and something better cost made it through already.
                if (my_cost > best) continue;

                // See note above the map declaration.
                if (visited.find(neigh) != visited.end()) {
                    auto record = visited[neigh];
                    if (record.first >= my_time && record.second <= my_cost) {
                        continue;
                    }
                }
                visited[neigh] = {my_time, my_cost};

                Info info = {my_cost, my_time, neigh};
                min_heap.push(info);
            }
        }

        return best == std::numeric_limits<int>::max() ? -1 : best;
    }
};


text:
require 'rspec'

if ENV['CI']
  require 'codeclimate-test-reporter'
  CodeClimate::TestReporter.start
else
  require 'simplecov'
  SimpleCov.start
end

ENV['HIVE_ENVIRONMENT'] ||= 'test'
ENV['HIVE_CONFIG'] = File.expand_path('../configs', __FILE__)
$LOAD_PATH << File.expand_path('../../lib', __FILE__)
$LOAD_PATH << File.expand_path('../helper_lib', __FILE__)

require 'hive'

SPEC_ROOT = File.expand_path('..', __FILE__)


text:
<?php

declare (strict_types = 1);

namespace Dumplie\SharedKernel\Application\Extension;

use Dumplie\Metadata\Hydrator\DefaultHydrator;
use Dumplie\Metadata\MetadataAccessRegistry;
use Dumplie\Metadata\Schema\Builder;
use Dumplie\SharedKernel\Application\Extension\Command\TransactionExtension;
use Dumplie\SharedKernel\Application\Command\ExtensionRegistry;
use Dumplie\SharedKernel\Application\Exception\ServiceContainer\ServiceNotFoundException;
use Dumplie\SharedKernel\Application\Extension;
use Dumplie\SharedKernel\Application\ServiceContainer;
use Dumplie\SharedKernel\Application\ServiceLocator;
use Dumplie\SharedKernel\Application\Services;
use Dumplie\SharedKernel\Infrastructure\InMemory\InMemoryEventLog;
use Dumplie\SharedKernel\Infrastructure\InMemory\InMemoryHandlerMap;

final class CoreExtension implements Extension
{
    /**
     * @var string
     */
    private $storageServiceId;

    /**
     * @param string $storageServiceId
     */
    public function __construct(string $storageServiceId)
    {
        $this->storageServiceId = $storageServiceId;
    }

    /**
     * @return array
     */
    public function dependsOn() : array
    {
        return [];
    }

    /**
     * @param ServiceContainer $serviceContainer
     * @throws ServiceNotFoundException
     */
    public function build(ServiceContainer $serviceContainer)
    {
        if (!$serviceContainer->definitionExists(Services::KERNEL_SERVICE_LOCATOR)) {
            throw new ServiceNotFoundException(sprintf('Service with id "%s" is missing in service container.', Services::KERNEL_SERVICE_LOCATOR));
        }

        $serviceContainer->register(Services::KERNEL_EVENT_LOG, new ServiceContainer\Definition(
           InMemoryEventLog::class
        ));

        $this->registerCommandServices($serviceContainer);
        $this->registerMetadataServices($serviceContainer);
    }

    /**
     * @param ServiceLocator $serviceLocator
     * @throws ServiceNotFoundException
     */
    public function boot(ServiceLocator $serviceLocator)
    {
        if (!$serviceLocator->has(Services::KERNEL_TRANSACTION_FACTORY)) {
            throw new ServiceNotFoundException(sprintf('Service with id "%s" is missing in service locator.', Services::KERNEL_TRANSACTION_FACTORY));
        }

        $serviceLocator->get(Services::KERNEL_COMMAND_EXTENSION_REGISTRY)
            ->register(new TransactionExtension($serviceLocator->get(Services::KERNEL_TRANSACTION_FACTORY)), -1024);
    }

    /**
     * @param ServiceContainer $serviceContainer
     */
    protected function registerCommandServices(ServiceContainer $serviceContainer)
    {
        $serviceContainer->register(Services::KERNEL_COMMAND_EXTENSION_REGISTRY, new ServiceContainer\Definition(
            ExtensionRegistry::class,
            [new ServiceContainer\ArgumentService(Services::KERNEL_SERVICE_LOCATOR)]
        ));

        $serviceContainer->register(
            Services::KERNEL_COMMAND_HANDLER_MAP,
            new ServiceContainer\Definition(
                InMemoryHandlerMap::class
            )
        );
    }

    /**
     * @param ServiceContainer $serviceContainer
     */
    protected function registerMetadataServices(ServiceContainer $serviceContainer)
    {
        $serviceContainer->register(Services::KERNEL_METADATA_SCHEMA_BUILDER, new ServiceContainer\Definition(
            Builder::class,
            []
        ));

        $serviceContainer->register(Services::KERNEL_METADATA_HYDRATOR, new ServiceContainer\Definition(
            DefaultHydrator::class,
            [
                new ServiceContainer\ArgumentService($this->storageServiceId)
            ]
        ));

        $serviceContainer->register(Services::KERNEL_METADATA_ACCESS_REGISTRY, new ServiceContainer\Definition(
            MetadataAccessRegistry::class,
            [
                new ServiceContainer\ArgumentService($this->storageServiceId),
                new ServiceContainer\ArgumentService(Services::KERNEL_METADATA_SCHEMA_BUILDER),
                new ServiceContainer\ArgumentService(Services::KERNEL_METADATA_HYDRATOR)
            ]
        ));
    }
}


text:
@gov.au/header
============

> Headers provide a consistent start to pages.

## Contents

* [Install](#install)
* [Usage](#usage)
* [Dependency graph](#dependency-graph)
* [Tests](#tests)
* [Release History](#release-history)
* [License](#license)

----------------------------------------------------------------------------------------------------------------------------------------------------------------

## Install

```shell
yarn add @gov.au/header
```

```shell
npm install @gov.au/header
```

**[⬆ back to top](#contents)**

----------------------------------------------------------------------------------------------------------------------------------------------------------------

## Usage

* [React](#react)

**[⬆ back to top](#contents)**

----------------------------------------------------------------------------------------------------------------------------------------------------------------

### React

Usage:

```jsx
import AUheader, { AUheaderBrand } from './header.js';

<AUheader>
	<AUheaderBrand
		link="#"
		brandImage="http://placehold.it/256x80"
		brandImageAlt="Digital Transformation Agency"
	/>
</AUheader>
```

All props:

```jsx
<AUheader
  alt={ false }       {/* An alternate variation of the component, optional */}
  dark={ false }      {/* A dark variation of the component, optional */}
  hero={ false }      {/* The hero option, optional, optional */}
/>

<AUheaderBrand
  title="Page title"      {/* The headline content, optional */}
  level="1"               {/* The headline tag level, h1-h6, optional */}
  subline="Subline"       {/* The subline content, optional */}
  brandImage="Page title" {/* The headline content, optional */}
  brandImageAlt="1"       {/* Brand image alt tag */}
  link="/"                {/* An optional link for the header brand, optional */}
  linkComponent="a"       {/* The component used for the link, optional */}
  children                {/* Anything inside */}
  attributeOptions        {/* Any other attribute options */}
></AUheaderBrand>
```
_(💡 additional props are spread onto the component)_

For more details have a look at the [usage example](https://github.com/govau/design-system-components/tree/master/packages/header/tests/react/index.js).

**[⬆ back to top](#contents)**

----------------------------------------------------------------------------------------------------------------------------------------------------------------

## Dependency graph

```shell
header
└─ core
```

**[⬆ back to top](#contents)**

----------------------------------------------------------------------------------------------------------------------------------------------------------------

## Tests

The visual test: https://auds.service.gov.au/packages/header/tests/site/

**[⬆ back to top](#contents)**

----------------------------------------------------------------------------------------------------------------------------------------------------------------

## Release History

* v4.1.13 - Header image should be a block element on XS and SM breakpoints (Fix based on the new grid breakpoints)
* v4.1.12 - Remove --save-dev flag from readme instructions
* v4.1.11 - Removed unused `Fragment` React import
* v4.1.10 - Resolve autoprefixer warning
* v4.1.9 - Fix pancake build path
* v4.1.8 - Updated deprecated `text-decoration-skip` property to `text-decoration-skip-ink`
* v4.1.7 - Removed uikit references
* v4.1.6 - Update dependencies
* v4.1.5 - Removing web pack dev server, updating dependencies
* v4.1.4 - Removed border from header brand image on ie8, ie9 and ie10
* v4.1.3 - AUheaderBrand without a link now defaults to div
* v4.1.2 - Fixed build scripts for Windows
* v4.1.1 - Replace node-sass with sass
* v4.1.0 - React router support
* v4.0.2 - Update dependencies
* v4.0.1 - Added missing documentation
* v4.0.0 - Added placeholder for Australian Government logo and optional grid layout
* v3.0.2 - Change homepage link
* v3.0.1 - Fix dependencies
* v3.0.0 - Change to focus colour and border/muted color mix
* v2.0.0 - Moved to AU namespace, added new color themes and spacing
* v1.2.0 - Added pancake-react plugin, ES5 main file, added children
* v1.1.0 - Added react component
* v1.0.0 - Removed the side spacing #147
* v0.1.0 - 💥 Initial version

**[⬆ back to top](#contents)**

----------------------------------------------------------------------------------------------------------------------------------------------------------------

## License

Copyright (c) Commonwealth of Australia.
Licensed under [MIT](https://raw.githubusercontent.com/govau/design-system-components/packages/core/master/LICENSE).

**[⬆ back to top](#contents)**

# };


text:
using System.ComponentModel;

using AlteryxRecordInfoNet;

using OmniBus.Framework;
using OmniBus.Framework.Attributes;
using OmniBus.Framework.TypeConverters;

namespace OmniBus
{
    /// <summary>
    ///     Configuration Class For <see cref="DateTimeParserEngine" />
    /// </summary>
    public class DateTimeParserConfig : ConfigWithIncomingConnection
    {
        /// <summary>
        ///     Gets or sets the type of the output.
        /// </summary>
        [Category("Output")]
        [Description("Alteryx Type for the Output Field")]
        [FieldList(FieldType.E_FT_Date, FieldType.E_FT_DateTime, FieldType.E_FT_Time, FieldType.E_FT_String)]
        [TypeConverter(typeof(FixedListTypeConverter<FieldType>))]
        public FieldType OutputType { get; set; } = FieldType.E_FT_DateTime;

        /// <summary>
        ///     Gets or sets the name of the output field.
        /// </summary>
        [Category("Output")]
        [Description("Field Name To Use For Output Field")]
        public string OutputFieldName { get; set; } = "Date";

        /// <summary>
        ///     Gets or sets the culture.
        /// </summary>
        [TypeConverter(typeof(CultureTypeConverter))]
        [Category("Format")]
        [Description("The Culture Used To Parse The Text Value")]
        public string Culture { get; set; } = CultureTypeConverter.Current;

        /// <summary>
        ///     Gets or sets the name of the input field.
        /// </summary>
        [Category("Input")]
        [Description("The Field On Input Stream To Parse")]
        [TypeConverter(typeof(InputFieldTypeConverter))]
        [InputPropertyName(
            nameof(DateTimeParserEngine.Input),
            typeof(DateTimeParserEngine),
            FieldType.E_FT_String,
            FieldType.E_FT_V_String,
            FieldType.E_FT_V_WString,
            FieldType.E_FT_WString)]
        public string InputFieldName { get; set; } = "DateInput";

        /// <summary>
        ///     Gets or sets the input format.
        /// </summary>
        [Category("Format")]
        [Description("The Format Expected To Parse (blank to use general formats)")]
        public string FormatString { get; set; }

        /// <summary>
        ///     ToString used for annotation
        /// </summary>
        /// <returns>Default Annotation</returns>
        public override string ToString()
        {
            return $"{this.InputFieldName} ({this.FormatString}) ⇒ {this.OutputFieldName}";
        }
    }
}


text:
<!--
  Copyright 2013 Google Inc.

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

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

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

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:listPreferredItemHeight">

    <ProgressBar
        style="?android:progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:indeterminate="true" />
</FrameLayout>


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Seminary Info</title>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css" />
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="/assets/css/custom.css" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">

        </button>
        Blacksburg Seminary

seminary.lds.org

Scripture Mastery

Revelations in Context

WISE

 Loading schedule info...

    This site is not officially affiliated with The Church of Jesus Christ of Latter-Day Saints.  It is only a site by a member of the church as a resource to others.


text:
    <java-class-file name="D:\Experiments\Analisi di Sopravvivenza\Progetto16715\ProgettiDaAnalizzare\jhotdraw\JHotDraw 7.4.1\JHotDraw 7.4.1\Source\jhotdraw7\src\main\java\org\jhotdraw\util\prefs\PreferencesUtil.java">
        <package-decl name="org.jhotdraw.util.prefs"/>
        <class name="PreferencesUtil" visibility="public">
            <constructor visibility="public" name="PreferencesUtil">
            </constructor>
            <method name="put" visibility="public">
            </method>
            <method name="get" visibility="public">
            </method>
            <method name="remove" visibility="public">
            </method>
            <method name="clear" visibility="public">
            </method>
            <method name="putInt" visibility="public">
            </method>
            <method name="getInt" visibility="public">
            </method>
            <method name="putLong" visibility="public">
            </method>
            <method name="getLong" visibility="public">
            </method>
            <method name="putBoolean" visibility="public">
            </method>
            <method name="getBoolean" visibility="public">
            </method>
            <method name="putFloat" visibility="public">
            </method>
            <method name="getFloat" visibility="public">
            </method>
            <method name="putDouble" visibility="public">
            </method>
            <method name="getDouble" visibility="public">
            </method>
            <method name="putByteArray" visibility="public">
            </method>
            <method name="getByteArray" visibility="public">
            </method>
            <method name="keys" visibility="public">
            </method>
            <method name="childrenNames" visibility="public">
            </method>
            <method name="parent" visibility="public">
            </method>
            <method name="node" visibility="public">
            </method>
            <method name="nodeExists" visibility="public">
            </method>
            <method name="removeNode" visibility="public">
            </method>
            <method name="name" visibility="public">
            </method>
            <method name="absolutePath" visibility="public">
            </method>
            <method name="isUserNode" visibility="public">
            </method>
            <method name="toString" visibility="public">
            </method>
            <method name="flush" visibility="public">
            </method>
            <method name="sync" visibility="public">
            </method>
            <method name="addPreferenceChangeListener" visibility="public">
            </method>
            <method name="removePreferenceChangeListener" visibility="public">
            </method>
            <method name="addNodeChangeListener" visibility="public">
            </method>
            <method name="removeNodeChangeListener" visibility="public">
            </method>
            <method name="exportNode" visibility="public">
            </method>
            <method name="exportSubtree" visibility="public">
            </method>
            <method name="systemNodeForPackage" visibility="public" static="true">
            </method>
            <method name="userNodeForPackage" visibility="public" static="true">
            </method>
            <method name="installPrefsHandler" visibility="public" static="true">
            </method>
            <constructor visibility="private" name="PreferencesUtil">
            </constructor>
            <method name="installFramePrefsHandler" visibility="public" static="true">
            </method>
            <method name="installFramePrefsHandler" visibility="public" static="true">
                                    <method name="componentMoved" visibility="public">
                                    </method>
                                    <method name="componentResized" visibility="public">
                                    </method>
            </method>
            <method name="installPalettePrefsHandler" visibility="public" static="true">
            </method>
            <method name="installPalettePrefsHandler" visibility="public" static="true">
                                    <method name="componentMoved" visibility="public">
                                    </method>
                                    <method name="windowClosing" visibility="public">
                                    </method>
                                    <method name="windowOpened" visibility="public">
                                    </method>
            </method>
            <method name="installInternalFramePrefsHandler" visibility="public" static="true">
                                    <method name="componentMoved" visibility="public">
                                    </method>
                                    <method name="componentResized" visibility="public">
                                    </method>
            </method>
            <method name="installToolBarPrefsHandler" visibility="public" static="true">
            </method>
            <method name="installTabbedPanePrefsHandler" visibility="public" static="true">
                                    <method name="stateChanged" visibility="public">
                                    </method>
            </method>
        </class>
    </java-class-file>


text:
package com.potlatch.client;

import com.google.common.base.Objects;

public class User {

	private String id;

	private String name;
	private String password;
	private long touchCount;

	public User() {
	}

	public User(String id, String name, String password) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public long getTouchCount() {
		return touchCount;
	}

	public void setTouchCount(long touchCount) {
		this.touchCount = touchCount;
	}

	public void addTouch() {
		++touchCount;
	}

	public void removeTouch() {
		if (touchCount > 0) {
			--touchCount;
		}
	}

	@Override
	public int hashCode() {
		// Google Guava provides great utilities for hashing
		return Objects.hashCode(id, name);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof User) {
			User other = (User) obj;
			// Google Guava provides great utilities for equals too!
			return Objects.equal(id, other.id)
					&& Objects.equal(name, other.name);
		} else {
			return false;
		}
	}

}


text:
#ifndef HOUGH_H
#define HOUGH_H

#include <opencv2/opencv.hpp>
#include <vector>

#include "../common/timer.h"

class Hough : public Timable {
public:
	Hough(Timer& timer, std::vector<cv::Vec3f>& circles);

	void apply(cv::Mat& src, cv::Mat& dst);

	void operator()(cv::Mat& src, cv::Mat& dst);
private:
	std::vector<cv::Vec3f>& _circles;

	void draw(cv::Mat& dst);
};

#endif


text:
using FlipFall.Theme;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamColorSetter : MonoBehaviour
{
    public static CamColorSetter _instance;

    // Use this for initialization
    private void Start()
    {
        _instance = this;
        BgColorUpdate();
    }

    // Update is called once per frame
    public static void BgColorUpdate()
    {
        if (_instance != null)
            _instance.GetComponent<Camera>().backgroundColor = ThemeManager.theme.backgorundColor;
    }
}


text:
//
//  QBRequest+QBAuth.h
//
//  Created by QuickBlox team
//  Copyright (c) 2017 QuickBlox. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <Quickblox/QBRequest.h>

@class QBUUser;

NS_ASSUME_NONNULL_BEGIN

typedef void(^qb_response_user_block_t)(QBResponse *response, QBUUser *tUser);

@interface QBRequest (QBAuth)

//MARK: - App authorization

/**
 Session Destroy

 @param successBlock Block with response instance if the request is succeeded.
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest for cancel operation mainly.
 */
+ (QBRequest *)destroySessionWithSuccessBlock:(nullable qb_response_block_t)successBlock
                                   errorBlock:(nullable qb_response_block_t)errorBlock;

//MARK: - LogIn

/**
 User LogIn with login

 @param login Login of QBUUser which authenticates.
 @param password Password of QBUUser which authenticates.
 @param successBlock Block with response and user instances if the request is succeeded.
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest for cancel operation mainly.
 */
+ (QBRequest *)logInWithUserLogin:(NSString *)login
                         password:(NSString *)password
                     successBlock:(nullable qb_response_user_block_t)successBlock
                       errorBlock:(nullable qb_response_block_t)errorBlock;

/**
 User LogIn with email

 @param email Email of QBUUser which authenticates.
 @param password Password of QBUUser which authenticates.
 @param successBlock Block with response and user instances if the request is succeeded.
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest for cancel operation mainly.
 */
+ (QBRequest *)logInWithUserEmail:(NSString *)email
                         password:(NSString *)password
                     successBlock:(nullable qb_response_user_block_t)successBlock
                       errorBlock:(nullable qb_response_block_t)errorBlock;

/**
 User LogIn with social provider's token

 @param provider Social provider. Posible values: facebook, twitter.
 @param accessToken Social provider access token.
 @param accessTokenSecret Social provider access token secret.
 @param successBlock Block with response and user instances if the request is succeeded.
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest for cancel operation mainly.
 */
+ (QBRequest *)logInWithSocialProvider:(NSString *)provider
                           accessToken:(nullable NSString *)accessToken
                     accessTokenSecret:(nullable NSString *)accessTokenSecret
                          successBlock:(nullable qb_response_user_block_t)successBlock
                            errorBlock:(nullable qb_response_block_t)errorBlock;

/**
 User login using Firebase (only phone number. See https://firebase.google.com/docs/auth/ios/phone-auth).

 @param projectID Firebase project ID
 @param accessToken Access token
 @param successBlock Block with response and user instances if the request is succeeded.
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest for cancel operation mainly.
 */
+ (QBRequest *)logInWithFirebaseProjectID:(NSString *)projectID
                              accessToken:(NSString *)accessToken
                             successBlock:(nullable qb_response_user_block_t)successBlock
                               errorBlock:(nullable qb_response_block_t)errorBlock;

//MARK: - LogOut

/**
 LogOut current user

 @param successBlock Block with response instance if the request is succeeded
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest for cancel operation mainly.
 */
+ (QBRequest *)logOutWithSuccessBlock:(nullable qb_response_block_t)successBlock
                           errorBlock:(nullable qb_response_block_t)errorBlock;

//MARK: - Create User

/**
 User sign up

 @param user User to signup
 @param successBlock Block with response and user instances if the request is succeeded.
 @param errorBlock Block with response instance if the request is failed.

 @return An instance of QBRequest. Use this instance to cancel the operation.
 */
+ (QBRequest *)signUp:(QBUUser *)user
         successBlock:(nullable qb_response_user_block_t)successBlock
           errorBlock:(nullable qb_response_block_t)errorBlock;

@end

NS_ASSUME_NONNULL_END


text:
persistence-jpa
===============

Telosys - Custom Persistence layer - Templates for Java Persistence based on JPA.
Run only once per entity. Developers can create custom methods/queries. Be careful
when running this as it wil lwipe out all custom work.


text:
'use strict'

module.exports = comment

/* Stringify a comment `node`. */
function comment(ctx, node) {
  return '<!--' + node.value + '-->'
}


text:
package org.innovateuk.ifs.management.assessment.viewmodel;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * Holder of model attributes for the Assessor Progress view.
 */
public class AssessorAssessmentProgressRemoveViewModel {

    private long competitionId;
    private long assessorId;
    private long assessmentId;
    private Long assessmentPeriodId;

    public AssessorAssessmentProgressRemoveViewModel(
            long competitionId,
            long assessorId,
            long assessmentId) {
        this.competitionId = competitionId;
        this.assessorId = assessorId;
        this.assessmentId = assessmentId;
    }

    public AssessorAssessmentProgressRemoveViewModel(
            long competitionId,
            long assessorId,
            long assessmentId,
            long assessmentPeriodId) {
        this.competitionId = competitionId;
        this.assessorId = assessorId;
        this.assessmentId = assessmentId;
        this.assessmentPeriodId = assessmentPeriodId;
    }

    public long getCompetitionId() {
        return competitionId;
    }

    public long getAssessorId() {
        return assessorId;
    }

    public long getAssessmentId() {
        return assessmentId;
    }

    public Long getAssessmentPeriodId() {
        return assessmentPeriodId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        AssessorAssessmentProgressRemoveViewModel that = (AssessorAssessmentProgressRemoveViewModel) o;

        return new EqualsBuilder()
                .append(competitionId, that.competitionId)
                .append(assessorId, that.assessorId)
                .append(assessmentId, that.assessmentId)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(competitionId)
                .append(assessorId)
                .append(assessmentId)
                .toHashCode();
    }
}


text:
'use strict';
define(["d3"],
  function(d3) {

   // var utils = new Utils();

    var Graph = function(width, height, xdomain_limit, ydomain_limit, color,target_div,y_units) {
      var self = this;
      this.data = [
        []
      ];
      this.prevTime = 0;
      this.xDomainLimit = xdomain_limit;
      this.yDomainLimit = ydomain_limit;

      var margin = {
        top: 20,
        right: 20,
        bottom: 20,
        left: 50
      };

      // draw and append the container
      this.svg = d3.select("#"+target_div).append("svg")
        .attr("height", height+20)
        .attr("width", width+20)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.right + ")");

     this.svg.append("text")      // text label for the x axis
        .attr("x", width/3)
        .attr("y", height-15 )
        .style("text-anchor", "middle")
        .text("Seconds");

    this.svg.append("text")      // text label for the x axis
          .attr("transform", "rotate(-90)")
        .attr("y", 0-margin.left)
        .attr("x",0 - (height / 2))
        .attr("dy", "1em")
        .style("text-anchor", "middle")
        .text(y_units);

      this.svg
        .append("clipPath") // define a clip path
        .attr("id", "clip") // give the clipPath an ID
        .append("rect") // shape it as an ellipse
        .attr("x", 0)
        .attr("y", 0)
        .attr("height", height) // set the height
        .attr("width", width); // set the width*/

     this.xScale = d3.scale.linear()
        .range([0, width - margin.left - margin.right])
        .domain([0, this.xDomainLimit]);
     this.yScale = d3.scale.linear()
        .range([height - margin.top - margin.bottom, 0]);

        this.line = d3.svg.line()
          .x(function(d) {
            //console.log("x =",d.x,xScale(d.x));
            return self.xScale(d.x);
          })
          .y(function(d) {
            //console.log("y =",d.y,yScale(d.y));
            return self.yScale(d.y);
          });

      this.height = height;
      this.width = width;
      this.margin = margin;
      this.color = color;

      // initial page render
      this.render();
      this.data[0].push({
        y: 0,
        x: 1
      });
      this.render();
      // continuous page render
      self.set = setInterval(function() {
        self.render();
      }, 1);

    };

    Graph.prototype.calculateMin = function(data, prop) {
      var min = data.reduce(function(pv, cv) {
        var currentMin = cv.reduce(function(pv, cv) {
          return Math.min(pv, cv[prop]);
        }, 100);
        return Math.min(pv, currentMin);
      }, 100);
      return min;
    };

    Graph.prototype.calculateMax = function(data, prop) {
      var max = data.reduce(function(pv, cv) {
        var currentMax = cv.reduce(function(pv, cv) {
          return Math.max(pv, cv[prop]);
        }, 0);
        return Math.max(pv, currentMax);
      }, 0);
      return max;
    };

    Graph.prototype.render = function() {
      // generate new data
      var data = this.data;
      var color = this.color;
      // obtain absolute min and max

      var yMin = this.calculateMin(data, "y");
      var yMax = this.calculateMax(data, "y");

      var xMin = this.calculateMin(data, "x");
      var xMax = this.calculateMax(data, "x");

      // set domain for axis
      this.yScale.domain([yMin, yMax]);
      var start;
      if(xMax>this.xDomainLimit){
         start = xMax-this.xDomainLimit;
            this.xScale.domain([start,xMax]);

     }

     else{
          start = 0;
          this.xScale.domain([start,this.xDomainLimit]);

     }

      if(yMax>this.yDomainLimit){

          this.yScale.domain([0,yMax]);
        }
        else{
            this.yScale.domain([0,this.yDomainLimit]);
        }

        // create axis scale
      var yAxis = d3.svg.axis()
        .scale(this.yScale).orient("left");

      // create axis scale
      var xAxis = d3.svg.axis()
        .scale(this.xScale).orient("bottom");

      // if no axis exists, create one, otherwise update it
      if (this.svg.selectAll(".y.axis")[0].length < 1) {
        this.svg.append("g")
          .attr("class", "y axis")
          .call(yAxis);
      } else {
        this.svg.selectAll(".y.axis").call(yAxis);
      }

      // if no axis exists, create one, otherwise update it
      if (this.svg.selectAll(".x.axis")[0].length < 1) {
        this.svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + (this.height-40) + ")")
          .call(xAxis);
      } else {
        this.svg.selectAll(".x.axis").call(xAxis);
      }

      /*var line = d3.svg.line().interpolate("monotone")
        .x(function(d){ return xScale(d.x); })
        .y(function(d){ return yScale(d.y); });

*/
      // generate line paths
      var lines = this.svg.selectAll(".line").data(this.data).attr("class", "line");

      // transition from previous paths to new paths
      lines.transition().duration(1)
        .attr("d", this.line);

      // enter any new data
      lines.enter()
        .append("path")
        .attr("clip-path", "url(#clip)") // clip the rectangle
        .attr("class", "line")
        .attr("d", this.line)
        .style("stroke", function() {
          return color;
        });

      // exit
      lines.exit()
        .remove();

    };

    Graph.prototype.setData = function(data) {
      //console.log('tick', dataPoint);
      // push a new data point onto the back
      this.data[0] = data[data.length-1];

      //this.path.attr("d", this.line);

    };
    return Graph;

  });


text:
var create = require('../javascript/Create')
var sinon = require('sinon')
var assert = require('assert')
const {JSDOM} = require('jsdom')

const fakeCreateHTML = `
Project name
<input id="projectName" type="text" placeholder="" value="" class="swal2-input">
Suite name
<input id="suiteName" type="text" placeholder="" value="" class="swal2-input">
Case name
<input id="caseName" type="text"  placeholder="" value="" class="swal2-input">
The path on your device
<button type="button" id="SelectFolder">Select Path</button>

`

describe('Create', function() {
    before(function(){
        const jsdom = new JSDOM(fakeCreateHTML)
        global.window = jsdom.window
        global.document = jsdom.window.document
    })

    beforeEach(function(){
        var swal = sinon.spy()
        global.swal = swal
    })

    it('Create swal function args test', function(){
        create.Create()
        assert.equal(swal.callCount, 1, 'swal should be called once')
        assert.equal(swal.args[0][0].width, '200%', 'swal width should be 200%')
        assert.equal(swal.args[0][0].title, 'Create your first test!', `swal title should be 'Create your first test!'`)
        assert.equal(swal.args[0][0].html, fakeCreateHTML, 'swal html should be fakeCreateHTML')
        assert.equal(swal.args[0][0].focusConfirm, false, 'swal focusConfirm should be false')
        assert.equal(swal.args[0][0].showCancelButton, true, 'swal showCancelButton should be true')
        assert.equal(swal.args[0][0].allowEscapeKey, false, 'swal allowEscapeKey should be false')
        assert.equal(swal.args[0][0].allowOutsideClick, false, 'swal allowOutsideClick should be false')
        assert.equal(typeof(swal.args[0][0].preConfirm), 'function', 'swal preConfirm should be a function')
    })

})


text:
describe('WalkontableColumnFilter', function () {
  describe('offsettedTH', function () {
    it("should do nothing if row header is not visible", function () {
      var filter = new WalkontableColumnFilter();
      filter.countTH = 0;
      expect(filter.offsettedTH(1)).toEqual(1);
    });

    it("should decrease n by 1 if row header is visible", function () {
      var filter = new WalkontableColumnFilter();
      filter.countTH = 1;
      expect(filter.offsettedTH(1)).toEqual(0);
    })
  });

  describe('unOffsettedTH', function () {
    it("should do nothing if row header is not visible", function () {
      var filter = new WalkontableColumnFilter();
      filter.countTH = 0;
      expect(filter.unOffsettedTH(1)).toEqual(1);
    });

    it("should increase n by 1 if row header is visible", function () {
      var filter = new WalkontableColumnFilter();
      filter.countTH = 1;
      expect(filter.unOffsettedTH(0)).toEqual(1);
    })
  });
});


text:
import matplotlib
from matplotlib.testing.conftest import *  # noqa

def pytest_configure(config):
    for key, value in [
        ("markers", "flaky: (Provided by pytest-rerunfailures.)"),
        ("markers", "timeout: (Provided by pytest-timeout.)"),
        ("markers", "backend: Set alternate Matplotlib backend temporarily."),
        ("markers", "style: Set alternate Matplotlib style temporarily."),
        ("markers", "baseline_images: Compare output against references."),
        ("markers", "pytz: Tests that require pytz to be installed."),
    ]:
        config.addinivalue_line(key, value)

    matplotlib.use("agg", force=True)
    matplotlib._called_from_pytest = True
    matplotlib._init_tests()


text:
package logger

import (
	"sync"
)

type registry struct {
	mu sync.Mutex

	mux    Mux
	catmap map[string]*CategoryLogger
}

var registryInstance *registry
var muRegistryInstance sync.Mutex

func Registry() *registry {
	muRegistryInstance.Lock()
	defer muRegistryInstance.Unlock()

	if registryInstance == nil {
		registryInstance = &registry{
			catmap: make(map[string]*CategoryLogger),
		}
	}

	return registryInstance
}

func (r *registry) AddOutput(l Logger) {
	r.mu.Lock()
	defer r.mu.Unlock()

	r.mux.Ls = append(r.mux.Ls, l)
}

func (r *registry) Category(c string) *CategoryLogger {
	r.mu.Lock()
	defer r.mu.Unlock()

	l, ok := r.catmap[c]
	if !ok {
		l = &CategoryLogger{
			BE:       &r.mux,
			Category: c,
			Level:    Debug,
		}
		r.catmap[c] = l
	}
	return l
}

func (r *registry) CategoryIfExist(c string) *CategoryLogger {
	r.mu.Lock()
	defer r.mu.Unlock()

	return r.catmap[c]
}

type CategoryEntry struct {
	Category string `json:"category"`
	Level    `json:"level"`
}

func (cl *CategoryLogger) View() CategoryEntry {
	return CategoryEntry{Category: cl.Category, Level: cl.Level}
}

func (r *registry) Categories() []CategoryEntry {
	r.mu.Lock()
	defer r.mu.Unlock()

	ret := make([]CategoryEntry, 0, len(r.catmap))
	for _, cl := range r.catmap {
		ret = append(ret, cl.View())
	}
	return ret
}


text:
package com.capitalone.dashboard.rest;

import com.capitalone.dashboard.editors.CaseInsensitiveScoreValueTypeEditor;
import com.capitalone.dashboard.model.score.ScoreValueType;
import com.capitalone.dashboard.model.score.settings.ScoreCriteriaSettings;
import com.capitalone.dashboard.service.ScoreCriteriaSettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class ScoreCriteriaSettingsController {

  private final ScoreCriteriaSettingsService scoreCriteriaSettingsService;

  @InitBinder
  public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(ScoreValueType.class, new CaseInsensitiveScoreValueTypeEditor());
  }

  @Autowired
  public ScoreCriteriaSettingsController(
    ScoreCriteriaSettingsService scoreCriteriaSettingsService
  ) {
    this.scoreCriteriaSettingsService = scoreCriteriaSettingsService;
  }

  @RequestMapping(value = "/score/settings/type/{scoreValueType}",
    method = GET, produces = APPLICATION_JSON_VALUE)
  public ScoreCriteriaSettings getScoreCriteriaSettingsByType(@PathVariable ScoreValueType scoreValueType) {
     return this.scoreCriteriaSettingsService.getScoreCriteriaSettingsByType(scoreValueType);
  }
}


text:
#pragma once
#include <aws/devicefarm/DeviceFarm_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace DeviceFarm
{
namespace Model
{
  enum class NetworkProfileType
  {
    NOT_SET,
    CURATED,
    PRIVATE_
  };

namespace NetworkProfileTypeMapper
{
AWS_DEVICEFARM_API NetworkProfileType GetNetworkProfileTypeForName(const Aws::String& name);

AWS_DEVICEFARM_API Aws::String GetNameForNetworkProfileType(NetworkProfileType value);
} // namespace NetworkProfileTypeMapper
} // namespace Model
} // namespace DeviceFarm
} // namespace Aws


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Threading;
using Roslyn.VisualStudio.Test.Utilities;

namespace Roslyn.VisualStudio.IntegrationTests
{
    public abstract class AbstractIntegrationTest : IDisposable
    {
        protected readonly VisualStudioInstanceContext VisualStudio;

        protected AbstractIntegrationTest(VisualStudioInstanceFactory instanceFactory)
        {
            VisualStudio = instanceFactory.GetNewOrUsedInstance(SharedIntegrationHostFixture.RequiredPackageIds);
        }

        public void Dispose()
        {
            VisualStudio.Dispose();
        }

        protected void Wait(double seconds)
        {
            var timeout = TimeSpan.FromMilliseconds(seconds * 1000);
            Thread.Sleep(timeout);
        }
    }
}


text:
PlanckUnit
==========

A simple, small, and extensible unit testing framework for embedded systems
and standard OSs alike. The framework only depends on `stdio.h`, `stdlib.h`,
and `string.h`, and has helper libraries to aid use on
Arduino platforms. The library can be used to output unit test results
in almost any format, and specifically has support for JSON and a
human-friendly formats. For standard operating systems, `planckunit.c` and
`planckunit.h` are the only files necessary for using the library.

License
-------

This code is released under the terms of the Apache License (version 2.0).
Please refer to the [LICENSE](LICENSE) file for more information.

Contributors
------------

Graeme Douglas, Dana Klamut, Eliana Wardle

Basic Terminology
-----------------

* An _assertion_ is a check of some condition involving some pieces of data.
* A _test_, _unit test_ or _test case_ is code that executes some
instructions creating data mixed with assertions verifying the integrity
of said data.
* A _suite_ or _test suite_ is an ordered collection of tests.
* An _output style_ or _output format_ is one of the predefined syntax
options to print test results in.

***

# Usage

## Restrictions

* If tests are to be used with [PyPlanck](https://github.com/iondbproject/planck-parser) for verification:
 * Tests must use the XML output format.
 * Avoid use of the following tags in output messages to ensure proper parsing:
  * `<suite>`, `</suite>`
  * `<test>`, `</test>`
  * `<summary>`, `</summary>`
* Some output styles may be too verbose for devices with very small memory.
* File paths are left blank in Arduino builds (and otherwise use the absolute path).
* Only tests that fail include full details in output (line, file, function, message).

## Configuration

In order to use PlanckUnit, this header file must be included in any source
file that defines test cases or runs test suites:

```c
#include "planck_unit.h"
```

Within `planck_unit.h`, these preprocessor definitions enable particular
output styles in the build when included (only Concise is enabled by default).
For example, to enable the JSON, XML, and Concise output styles:

```c
#define PLANCK_UNIT_OUTPUT_STYLE_JSON
/*#define PLANCK_UNIT_OUTPUT_STYLE_HUMAN*/
#define PLANCK_UNIT_OUTPUT_STYLE_XML
#define PLANCK_UNIT_OUTPUT_STYLE_CONCISE
```

If multiple styles are enabled, the one to use for a suite can be defined
using `planck_unit_init_suite()` (see "Constructing a Test Suite" below).
Otherwise, it will default to the first enabled (from high to low precedence:
JSON, Human, XML, Concise).

## Assertions, Test Cases, Test Suites

#### Assertion Types
| Macro | Usage |
|-------|-------|
| `PLANCK_UNIT_ASSERT_TRUE(state, condition)` | Assert that a condition is true. |
| `PLANCK_UNIT_ASSERT_FALSE(state, condition)` | Assert that a condition is false. |
| `PLANCK_UNIT_SET_FAIL(state)` |  Unconditionally fail the test. |
| `PLANCK_UNIT_ASSERT_INT_ARE_EQUAL(state, expected, actual)`,
`PLANCK_UNIT_ASSERT_INT_ARE_NOT_EQUAL(state, expected, actual)` | Assert that two integers are (or are not) equal. |
| `PLANCK_UNIT_ASSERT_STR_ARE_EQUAL(state, expected, actual)`,
`PLANCK_UNIT_ASSERT_STR_ARE_NOT_EQUAL(state, expected, actual)` | Assert that two null-terminated strings are (or are not) equal. |

#### Constructing a Test Case:

```c
void
test_foo(
	planck_unit_test_t *tc
) {
	// Include any data and assertions here.
}
```

#### Constructing a Test Suite:

```c
planck_unit_suite_t *suite = planck_unit_new_suite();
```

Setting the output style to be used in a suite:

```c
planck_unit_init_suite(
	suite,
	planck_unit_print_funcs_xml
);
```

Adding tests to a suite:

```c
PLANCK_UNIT_ADD_TO_SUITE(suite, test_foo);
PLANCK_UNIT_ADD_TO_SUITE(suite, test_bar);
// ...
```

#### Running a Test Suite:

```c
planck_unit_run_suite(suite);
planck_unit_destroy_suite(suite);
```

Be sure to destroy the suite after it runs in order to conserve memory.

Output will be generated in `stdout` by default
(usually the console for a workstation, or serial monitor for an Arduino).

## Examples

#### Usage Example

A full code example of PlanckUnit usage is provided in `examples/test_example.c`.

#### Output Syntax Examples

JSON:

```c
{"results":[{"error_at_line":50,"file":"[file path]\test_example.c","function":"test_addstuff1_1","message":"condition was false, expected true"},{"error_at_line":-1,"file":"","function":"","message":""},{"error_at_line":-1,"file":"","function":"","message":""},{"error_at_line":70,"file":"[file path]\test_example.c","function":"test_stringequals_failure","message":"expected \"apple\", got \"orange\""},{"error_at_line":-1,"file":"","function":"","message":""},{"error_at_line":-1,"file":"","function":"","message":""},{"error_at_line":-1,"file":"","function":"","message":""}],"total_tests":7,"total_passed":5}
```

Human:

```c
in function 'test_addstuff1_1', at [file path]\test_example.c:50: condition was false, expected true
in function 'test_stringequals_failure', at [file path]\test_example.c:70: expected \"apple\", got \"orange\"

F**F***

Total Tests:    7
Total Passed:   5
```

XML:

```c
<suite>
<test>line:"50",file:"[file path]\test_example.c",function:"test_addstuff1_1",mes
sage:"condition was false, expected true"</test>
<test>line:"-1",file:"",function:"",message:""</test>
<test>line:"-1",file:"",function:"",message:""</test>
<test>line:"70",file:"[file path]\test_example.c",function:"test_stringequals_failure",message:"expected \"apple\", got \"orange\""</test>
<test>line:"-1",file:"",function:"",message:""</test>
<test>line:"-1",file:"",function:"",message:""</test>
<test>line:"-1",file:"",function:"",message:""</test>
<summary>total_tests:"7",total_passed:"5"</summary>
</suite>
```

Concise:

```c
[[Results]]
[test_addstuff1_1: 50: condition was false, expected true]
[: pass]
[: pass]
[test_stringequals_failure: 70: expected \"apple\", got \"orange\"]
[: pass]
[: pass]
[: pass]
[[Passed: 5/7]]
```