text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AutoMapper.Impl;
using AutoMapper.Mappers;

namespace AutoMapper
{
    using Configuration;
    using Internal;

    public class ConfigurationStore : IConfigurationProvider, IConfiguration
	{
	    private static readonly IDictionaryFactory DictionaryFactory = PlatformAdapter.Resolve<IDictionaryFactory>();
	    private readonly ITypeMapFactory _typeMapFactory;
	    private readonly IEnumerable<IObjectMapper> _mappers;
		internal const string DefaultProfileName = "";

		private readonly ThreadSafeList<TypeMap> _typeMaps = new ThreadSafeList<TypeMap>();

        private readonly IDictionary<TypePair, TypeMap> _typeMapCache = DictionaryFactory.CreateDictionary<TypePair, TypeMap>();
        private readonly IDictionary<TypePair, CreateTypeMapExpression> _typeMapExpressionCache = DictionaryFactory.CreateDictionary<TypePair, CreateTypeMapExpression>();
        private readonly IDictionary<string, ProfileConfiguration> _formatterProfiles = DictionaryFactory.CreateDictionary<string, ProfileConfiguration>();
		private Func<Type, object> _serviceCtor = ObjectCreator.CreateObject;

	    private readonly List<string> _globalIgnore;

	    public ConfigurationStore(ITypeMapFactory typeMapFactory, IEnumerable<IObjectMapper> mappers)
		{
		    _typeMapFactory = typeMapFactory;
		    _mappers = mappers;
            _globalIgnore = new List<string>();
		}

	    public event EventHandler<TypeMapCreatedEventArgs> TypeMapCreated;

	    public Func<Type, object> ServiceCtor
	    {
	        get { return _serviceCtor; }
	    }

	    public bool AllowNullDestinationValues
		{
			get { return GetProfile(DefaultProfileName).AllowNullDestinationValues; }
			set { GetProfile(DefaultProfileName).AllowNullDestinationValues = value; }
		}

	    public bool AllowNullCollections
		{
			get { return GetProfile(DefaultProfileName).AllowNullCollections; }
			set { GetProfile(DefaultProfileName).AllowNullCollections = value; }
		}

	    public void IncludeSourceExtensionMethods(Assembly assembly)
	    {
	        GetProfile(DefaultProfileName).IncludeSourceExtensionMethods(assembly);
	    }

	    public INamingConvention SourceMemberNamingConvention
		{
			get { return GetProfile(DefaultProfileName).SourceMemberNamingConvention; }
			set { GetProfile(DefaultProfileName).SourceMemberNamingConvention = value; }
		}

		public INamingConvention DestinationMemberNamingConvention
		{
			get { return GetProfile(DefaultProfileName).DestinationMemberNamingConvention; }
			set { GetProfile(DefaultProfileName).DestinationMemberNamingConvention = value; }
		}

	    public IEnumerable<string> Prefixes
	    {
            get { return GetProfile(DefaultProfileName).Prefixes; }
	    }

	    public IEnumerable<string> Postfixes
	    {
            get { return GetProfile(DefaultProfileName).Postfixes; }
	    }

	    public IEnumerable<string> DestinationPrefixes
	    {
            get { return GetProfile(DefaultProfileName).DestinationPrefixes; }
	    }

	    public IEnumerable<string> DestinationPostfixes
	    {
            get { return GetProfile(DefaultProfileName).DestinationPostfixes; }
	    }

	    public IEnumerable<MemberNameReplacer> MemberNameReplacers
        {
            get { return GetProfile(DefaultProfileName).MemberNameReplacers; }
        }

	    public IEnumerable<AliasedMember> Aliases
	    {
	        get { return GetProfile(DefaultProfileName).Aliases; }
	    }

	    public bool ConstructorMappingEnabled
	    {
	        get { return GetProfile(DefaultProfileName).ConstructorMappingEnabled; }
	    }

	    public bool DataReaderMapperYieldReturnEnabled
	    {
            get { return GetProfile(DefaultProfileName).DataReaderMapperYieldReturnEnabled; }
	    }

	    public IEnumerable<MethodInfo> SourceExtensionMethods
	    {
	        get
	        {
	            return GetProfile(DefaultProfileName).SourceExtensionMethods;
	        }
	    }

		bool IProfileConfiguration.MapNullSourceValuesAsNull
		{
			get { return AllowNullDestinationValues; }
		}

		bool IProfileConfiguration.MapNullSourceCollectionsAsNull
		{
			get { return AllowNullCollections; }
		}

		public IProfileExpression CreateProfile(string profileName)
		{
			var profileExpression = new Profile(profileName);

			profileExpression.Initialize(this);

			return profileExpression;
		}

		public void CreateProfile(string profileName, Action<IProfileExpression> profileConfiguration)
		{
			var profileExpression = new Profile(profileName);

			profileExpression.Initialize(this);

			profileConfiguration(profileExpression);
		}

		public void AddProfile(Profile profile)
		{
			profile.Initialize(this);

			profile.Configure();
		}

		public void AddProfile<TProfile>() where TProfile : Profile, new()
		{
			AddProfile(new TProfile());
		}

		public void ConstructServicesUsing(Func<Type, object> constructor)
		{
			_serviceCtor = constructor;
		}

	    public void DisableConstructorMapping()
	    {
	        GetProfile(DefaultProfileName).ConstructorMappingEnabled = false;
	    }

	    public void EnableYieldReturnForDataReaderMapper()
	    {
	        GetProfile(DefaultProfileName).DataReaderMapperYieldReturnEnabled = true;
	    }

	    public void Seal()
		{
			_typeMaps.Each(typeMap => typeMap.Seal());
		}

		public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>()
		{
		    return CreateMap<TSource, TDestination>(DefaultProfileName);
		}

		public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(MemberList memberList)
		{
		    return CreateMap<TSource, TDestination>(DefaultProfileName, memberList);
		}

        public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(string profileName)
        {
            return CreateMap<TSource, TDestination>(profileName, MemberList.Destination);
        }

        public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(string profileName, MemberList memberList)
        {
            TypeMap typeMap = CreateTypeMap(typeof(TSource), typeof(TDestination), profileName, memberList);

            return CreateMappingExpression<TSource, TDestination>(typeMap);
        }

		public IMappingExpression CreateMap(Type sourceType, Type destinationType)
		{
		    return CreateMap(sourceType, destinationType, MemberList.Destination);
		}

	    public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList)
	    {
	        return CreateMap(sourceType, destinationType, memberList, DefaultProfileName);
	    }

	    public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList, string profileName)
		{
	        if (sourceType.IsGenericTypeDefinition() && destinationType.IsGenericTypeDefinition())
	        {
	            var typePair = new TypePair(sourceType, destinationType);

                var expression = _typeMapExpressionCache.GetOrAdd(typePair, tp => new CreateTypeMapExpression(tp, memberList, profileName));

	            return expression;
	        }

	        var typeMap = CreateTypeMap(sourceType, destinationType, profileName, memberList);

			return CreateMappingExpression(typeMap, destinationType);
		}

		public void RecognizePrefixes(params string[] prefixes)
		{
			GetProfile(DefaultProfileName).RecognizePrefixes(prefixes);
		}

		public void RecognizePostfixes(params string[] postfixes)
		{
			GetProfile(DefaultProfileName).RecognizePostfixes(postfixes);
		}

		public void RecognizeAlias(string original, string alias)
		{
			GetProfile(DefaultProfileName).RecognizeAlias(original, alias);
		}

        public void ReplaceMemberName(string original, string newValue)
        {
            GetProfile(DefaultProfileName).ReplaceMemberName(original, newValue);
        }

        public void RecognizeDestinationPrefixes(params string[] prefixes)
        {
            GetProfile(DefaultProfileName).RecognizeDestinationPrefixes(prefixes);
        }

        public void RecognizeDestinationPostfixes(params string[] postfixes)
        {
            GetProfile(DefaultProfileName).RecognizeDestinationPostfixes(postfixes);
        }

		public TypeMap CreateTypeMap(Type source, Type destination)
		{
		    return CreateTypeMap(source, destination, DefaultProfileName, MemberList.Destination);
		}

		public TypeMap CreateTypeMap(Type source, Type destination, string profileName, MemberList memberList)
		{
			TypeMap typeMap = FindExplicitlyDefinedTypeMap(source, destination);

			if (typeMap == null)
			{
			    var profileConfiguration = GetProfile(profileName);

				typeMap = _typeMapFactory.CreateTypeMap(source, destination, profileConfiguration, memberList);

                typeMap.Profile = profileName;
			    typeMap.IgnorePropertiesStartingWith = _globalIgnore;

			    IncludeBaseMappings(source, destination, typeMap);

				_typeMaps.Add(typeMap);

			    var typePair = new TypePair(source, destination);
			    _typeMapCache.AddOrUpdate(typePair, typeMap, (tp, tm) => typeMap);

				OnTypeMapCreated(typeMap);
			}

			return typeMap;
		}

        private void IncludeBaseMappings(Type source, Type destination, TypeMap typeMap)
        {
            foreach (var inheritedTypeMap in _typeMaps.Where(t => t.TypeHasBeenIncluded(source, destination)))
            {
                typeMap.ApplyInheritedMap(inheritedTypeMap);
            }
        }

		public TypeMap[] GetAllTypeMaps()
		{
			return _typeMaps.ToArray();
		}

		public TypeMap FindTypeMapFor(Type sourceType, Type destinationType)
		{
			return FindTypeMapFor( null, null, sourceType, destinationType ) ;
		}

		public TypeMap FindTypeMapFor(object source, object destination, Type sourceType, Type destinationType)
		{
			var typeMapPair = new TypePair(sourceType, destinationType);

			TypeMap typeMap;

            if (!_typeMapCache.TryGetValue(typeMapPair, out typeMap))
            {
                // Cache miss
                typeMap = FindTypeMap(source, destination, sourceType, destinationType, DefaultProfileName);

                // peterc note: this used not to cache if polymorphic mapping occurring, but performance was
                //              a disaster. Our mappings seem to work fine when one always caches.
                _typeMapCache[typeMapPair] = typeMap;
            }
            // Due to the inheritance we can have derrived mapping cached which is not valid for this source object
            else if (source != null && typeMap != null && !typeMap.SourceType.IsAssignableFrom(source.GetType()))
            {
                typeMap = FindTypeMapFor(source, destination, source.GetType(), destinationType);
            }

            if (typeMap == null && destination != null && destination.GetType() != destinationType)
            {
                typeMap = FindTypeMapFor(source, destination, sourceType, destination.GetType());
            }
            if (typeMap != null && typeMap.DestinationTypeOverride != null)
            {
                return FindTypeMapFor(source, destination, sourceType, typeMap.DestinationTypeOverride);
            }
            // Check for runtime derived types
		    var shouldCheckDerivedType = (typeMap != null) && (typeMap.HasDerivedTypesToInclude()) && (source != null) && (source.GetType() != sourceType);

            if (shouldCheckDerivedType)
            {
                var potentialSourceType = source.GetType();
                //Try and get the most specific type map possible
                var potentialTypes = _typeMaps
                    .Where(t => ((destination == null && destinationType.IsAssignableFrom(t.DestinationType))
                                 || (destination != null && t.DestinationType.IsInstanceOfType(destination))) &&
                                t.SourceType.IsInstanceOfType(source));

                var potentialDestTypeMap =
                    potentialTypes
                        .OrderByDescending(t => GetInheritanceDepth(t.DestinationType))
                        .FirstOrDefault();
                var ambiguousPotentialTypes = potentialTypes
                    .Where(t => t.DestinationType == potentialDestTypeMap.DestinationType)
                    .ToList();

                if (ambiguousPotentialTypes.Count > 1)
                {
                    potentialDestTypeMap = ambiguousPotentialTypes
                        .OrderByDescending(t => GetInheritanceDepth(t.SourceType))
                        .FirstOrDefault();
                }

                if (potentialDestTypeMap == typeMap)
                    return typeMap;

                var targetDestinationType = potentialDestTypeMap.DestinationType;
                var potentialTypeMap = FindExplicitlyDefinedTypeMap(potentialSourceType, targetDestinationType);
                if (potentialTypeMap == null)
                {
                    var targetSourceType = targetDestinationType != destinationType ? potentialSourceType : typeMap.SourceType;
                    typeMap = FindTypeMap(source, destination, targetSourceType, targetDestinationType, DefaultProfileName);
                }
                else
                    typeMap = potentialTypeMap;
            }

		    return typeMap;
		}

        private static int GetInheritanceDepth(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            return InheritanceTree(type).Count();
        }

        private static IEnumerable<Type> InheritanceTree(Type type)
        {
            while (type != null)
            {
                yield return type;
                type = type.BaseType();
            }
        }

		public TypeMap FindTypeMapFor(ResolutionResult resolutionResult, Type destinationType)
		{
			return FindTypeMapFor(resolutionResult.Value, null, resolutionResult.Type, destinationType) ??
			       FindTypeMapFor(resolutionResult.Value, null, resolutionResult.MemberType, destinationType);
		}

		public IProfileConfiguration GetProfileConfiguration(string profileName)
		{
			return GetProfile(profileName);
		}

		public void AssertConfigurationIsValid(TypeMap typeMap)
		{
			AssertConfigurationIsValid(Enumerable.Repeat(typeMap, 1));
		}

		public void AssertConfigurationIsValid(string profileName)
		{
			AssertConfigurationIsValid(_typeMaps.Where(typeMap => typeMap.Profile == profileName));
		}

		public void AssertConfigurationIsValid<TProfile>()
            where TProfile : Profile, new()
		{
			AssertConfigurationIsValid(new TProfile().ProfileName);
		}

		public void AssertConfigurationIsValid()
		{
			AssertConfigurationIsValid(_typeMaps);
		}

	    public IObjectMapper[] GetMappers()
	    {
	        return _mappers.ToArray();
	    }

		private IMappingExpression<TSource, TDestination> CreateMappingExpression<TSource, TDestination>(TypeMap typeMap)
		{
			IMappingExpression<TSource, TDestination> mappingExp =
				new MappingExpression<TSource, TDestination>(typeMap, _serviceCtor, this);

		    TypeInfo destInfo = typeMap.ConfiguredMemberList == MemberList.Destination
		        ? new TypeInfo(typeof(TDestination))
		        : new TypeInfo(typeof(TSource));

			foreach (var destProperty in destInfo.GetPublicWriteAccessors())
			{
				var attrs = destProperty.GetCustomAttributes(true);
				if (attrs.Any(x => x is IgnoreMapAttribute))
				{
					mappingExp = mappingExp.ForMember(destProperty.Name, y => y.Ignore());
				}
			    if (_globalIgnore.Contains(destProperty.Name))
			    {
			        mappingExp = mappingExp.ForMember(destProperty.Name, y => y.Ignore());
			    }
			}

			return mappingExp;
		}

		private IMappingExpression CreateMappingExpression(TypeMap typeMap, Type destinationType)
		{
			IMappingExpression mappingExp = new MappingExpression(typeMap, _serviceCtor);

			TypeInfo destInfo = new TypeInfo(destinationType);
			foreach (var destProperty in destInfo.GetPublicWriteAccessors())
			{
				var attrs = destProperty.GetCustomAttributes(true);
				if (attrs.Any(x => x is IgnoreMapAttribute))
				{
					mappingExp = mappingExp.ForMember(destProperty.Name, y => y.Ignore());
				}
                if (_globalIgnore.Contains(destProperty.Name))
                {
                    mappingExp = mappingExp.ForMember(destProperty.Name, y => y.Ignore());
                }
            }

			return mappingExp;
		}

		private void AssertConfigurationIsValid(IEnumerable<TypeMap> typeMaps)
		{
		    var maps = typeMaps as TypeMap[] ?? typeMaps.ToArray();
		    var badTypeMaps =
				(from typeMap in maps
				where ShouldCheckMap(typeMap)
				let unmappedPropertyNames = typeMap.GetUnmappedPropertyNames()
				where unmappedPropertyNames.Length > 0
                select new AutoMapperConfigurationException.TypeMapConfigErrors(typeMap, unmappedPropertyNames)
                ).ToArray();

			if (badTypeMaps.Any())
			{
				throw new AutoMapperConfigurationException(badTypeMaps);
			}

			var typeMapsChecked = new List<TypeMap>();

			foreach (var typeMap in maps)
			{
				DryRunTypeMap(typeMapsChecked, new ResolutionContext(typeMap, null, typeMap.SourceType, typeMap.DestinationType, new MappingOperationOptions(), Mapper.Engine));
			}
		}

	    private static bool ShouldCheckMap(TypeMap typeMap)
	    {
	        return (typeMap.CustomMapper == null && typeMap.CustomProjection == null && typeMap.DestinationTypeOverride == null) && !FeatureDetector.IsIDataRecordType(typeMap.SourceType);
	    }

	    private TypeMap FindTypeMap(object source, object destination, Type sourceType, Type destinationType, string profileName)
        {
            TypeMap typeMap = FindExplicitlyDefinedTypeMap(sourceType, destinationType);

            if (typeMap == null && destinationType.IsNullableType())
            {
                typeMap = FindExplicitlyDefinedTypeMap(sourceType, destinationType.GetTypeOfNullable());
            }

            if (typeMap == null)
            {
                typeMap = _typeMaps.FirstOrDefault(x => x.SourceType == sourceType && x.GetDerivedTypeFor(sourceType) == destinationType);

                if (typeMap == null)
                {
                    foreach (var sourceInterface in sourceType.GetInterfaces())
                    {
                        typeMap = ((IConfigurationProvider)this).FindTypeMapFor(source, destination, sourceInterface, destinationType);

                        if (typeMap == null) continue;

                        var derivedTypeFor = typeMap.GetDerivedTypeFor(sourceType);
                        if (derivedTypeFor != destinationType)
                        {
                            typeMap = CreateTypeMap(sourceType, derivedTypeFor, profileName, typeMap.ConfiguredMemberList);
                        }

                        break;
                    }

                    if ((sourceType.BaseType() != null) && (typeMap == null))
                        typeMap = ((IConfigurationProvider)this).FindTypeMapFor(source, destination, sourceType.BaseType(), destinationType);
                }
            }
	        if (typeMap == null && sourceType.IsGenericType() && destinationType.IsGenericType())
	        {
	            var sourceGenericDefinition = sourceType.GetGenericTypeDefinition();
	            var destGenericDefinition = destinationType.GetGenericTypeDefinition();
	            if (sourceGenericDefinition == null || destGenericDefinition == null)
	            {
	                return null;
	            }
                var genericTypePair = new TypePair(sourceGenericDefinition, destGenericDefinition);
	            CreateTypeMapExpression genericTypeMapExpression;

	            if (_typeMapExpressionCache.TryGetValue(genericTypePair, out genericTypeMapExpression))
	            {
	                typeMap = CreateTypeMap(sourceType, destinationType, genericTypeMapExpression.ProfileName,
	                    genericTypeMapExpression.MemberList);

	                var mappingExpression = CreateMappingExpression(typeMap, destinationType);

	                genericTypeMapExpression.Accept(mappingExpression);
	            }
	        }
            return typeMap;
        }

		private TypeMap FindExplicitlyDefinedTypeMap(Type sourceType, Type destinationType)
		{
			return _typeMaps.FirstOrDefault(x => x.DestinationType == destinationType && x.SourceType == sourceType);
		}

		private void DryRunTypeMap(ICollection<TypeMap> typeMapsChecked, ResolutionContext context)
		{
            if (context.TypeMap != null)
            {
                typeMapsChecked.Add(context.TypeMap);
            }

			var mapperToUse = GetMappers().FirstOrDefault(mapper => mapper.IsMatch(context));

            if (mapperToUse == null && context.SourceType.IsNullableType())
            {
                var nullableContext = context.CreateValueContext(null, Nullable.GetUnderlyingType(context.SourceType));

                mapperToUse = GetMappers().FirstOrDefault(mapper => mapper.IsMatch(nullableContext));
            }

			if (mapperToUse == null)
			{
				throw new AutoMapperConfigurationException(context);
			}

			if (mapperToUse is TypeMapMapper)
			{
				foreach (var propertyMap in context.TypeMap.GetPropertyMaps())
				{
					if (!propertyMap.IsIgnored())
					{
						var lastResolver = propertyMap.GetSourceValueResolvers().OfType<IMemberResolver>().LastOrDefault();

						if (lastResolver != null)
						{
							var sourceType = lastResolver.MemberType;
							var destinationType = propertyMap.DestinationProperty.MemberType;
							var memberTypeMap = ((IConfigurationProvider)this).FindTypeMapFor(sourceType, destinationType);

                            if (typeMapsChecked.Any(typeMap => Equals(typeMap, memberTypeMap)))
                                continue;

                            var memberContext = context.CreateMemberContext(memberTypeMap, null, null, sourceType, propertyMap);

                            DryRunTypeMap(typeMapsChecked, memberContext);
						}
					}
				}
			}
			else if (mapperToUse is ArrayMapper || mapperToUse is EnumerableMapper || mapperToUse is CollectionMapper)
			{
				Type sourceElementType = TypeHelper.GetElementType(context.SourceType);
				Type destElementType = TypeHelper.GetElementType(context.DestinationType);
				TypeMap itemTypeMap = ((IConfigurationProvider) this).FindTypeMapFor(sourceElementType, destElementType);

                if (typeMapsChecked.Any(typeMap => Equals(typeMap, itemTypeMap)))
                    return;

                var memberContext = context.CreateElementContext(itemTypeMap, null, sourceElementType, destElementType, 0);

                DryRunTypeMap(typeMapsChecked, memberContext);
			}

		}

		protected void OnTypeMapCreated(TypeMap typeMap)
		{
			var typeMapCreated = TypeMapCreated;
			if (typeMapCreated != null)
				typeMapCreated(this, new TypeMapCreatedEventArgs(typeMap));
		}

		internal ProfileConfiguration GetProfile(string profileName)
		{
		    ProfileConfiguration expr = _formatterProfiles.GetOrAdd(profileName,
		                                                           name => new ProfileConfiguration());

		    return expr;
		}

	    public void AddGlobalIgnore(string startingwith)
	    {
	        _globalIgnore.Add(startingwith);
	    }
	}
}


text:
"""Set up script"""
from setuptools import setup
import os

def _create_long_desc():
    """Create long description and README formatted with rst."""
    _long_desc = ''
    if os.path.isfile('README.md'):
        with open('README.md', 'r') as rf:
            return rf.read()
    if os.path.isfile('README.rst'):
        with open('README.rst', 'r') as rf:
            return rf.read()
long_desc = _create_long_desc()

# Setup
setup(name='cronquot',
      version='0.1.4',
      description='Cron scheduler.',
      long_description=long_desc,
      long_description_content_type='text/markdown',
      classifiers=[
          'Programming Language :: Python',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3.6',
          'License :: OSI Approved :: MIT License',
          'Topic :: Software Development :: Libraries :: Python Modules'
          ],
      keywords='cron crontab schedule',
      author='Shohei Mukai',
      author_email='mukaishohei76@gmail.com',
      url='https://github.com/pyohei/cronquot',
      license='MIT',
      packages=['cronquot'],
      entry_points={
          'console_scripts': [
              'cronquot = cronquot.cronquot:execute_from_console'],
          },
      install_requires=['crontab'],
      test_suite='test'
      )

redpajama_set_name: RedPajamaGithub


text:
namespace Animal
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public class Cat : Animal, ISound
    {
        public Cat(uint age, string name, char sex)
            : base(age, name, sex)
        {
        }

        public void ProduceSound()
        {
            Console.WriteLine(Name + " Meau");
        }
    }
}


text:
/**
 */
package archoptions.impl;

import archoptions.ArchoptionsPackage;
import archoptions.DeploymentOption;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'Deployment Option'.
 *
 *
 * @generated
 */
public abstract class DeploymentOptionImpl extends ArchOptionImpl implements DeploymentOption {
	/**
	 *
	 *
	 * @generated
	 */
	protected DeploymentOptionImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return ArchoptionsPackage.Literals.DEPLOYMENT_OPTION;
	}

} //DeploymentOptionImpl


text:
#ifndef __MICROBLAZE_IO_H__
#define __MICROBLAZE_IO_H__

#include <asm/types.h>

#define IO_SPACE_LIMIT 0xFFFFFFFF

#define readb(addr) \
  ({ unsigned char __v = (*(volatile unsigned char *) (addr)); __v; })
#define readw(addr) \
  ({ unsigned short __v = (*(volatile unsigned short *) (addr)); __v; })
#define readl(addr) \
  ({ unsigned long __v = (*(volatile unsigned long *) (addr)); __v; })

#define writeb(b, addr) \
  (void)((*(volatile unsigned char *) (addr)) = (b))
#define writew(b, addr) \
  (void)((*(volatile unsigned short *) (addr)) = (b))
#define writel(b, addr) \
  (void)((*(volatile unsigned int *) (addr)) = (b))

#define memset_io(a,b,c)        memset((void *)(a),(b),(c))
#define memcpy_fromio(a,b,c)    memcpy((a),(void *)(b),(c))
#define memcpy_toio(a,b,c)      memcpy((void *)(a),(b),(c))

#define inb(addr)	readb (addr)
#define inw(addr)	readw (addr)
#define inl(addr)	readl (addr)
#define outb(x, addr)	((void) writeb (x, addr))
#define outw(x, addr)	((void) writew (x, addr))
#define outl(x, addr)	((void) writel (x, addr))

/* Some #definitions to keep strange Xilinx code happy */
#define in_8(addr)	readb (addr)
#define in_be16(addr)	readw (addr)
#define in_be32(addr)	readl (addr)

#define out_8(addr,x )	outb (x,addr)
#define out_be16(addr,x )	outw (x,addr)
#define out_be32(addr,x )	outl (x,addr)

#define inb_p(port)		inb((port))
#define outb_p(val, port)	outb((val), (port))
#define inw_p(port)		inw((port))
#define outw_p(val, port)	outw((val), (port))
#define inl_p(port)		inl((port))
#define outl_p(val, port)	outl((val), (port))

/* Some defines to keep the MTD flash drivers happy */

#define __raw_readb readb
#define __raw_readw readw
#define __raw_readl readl
#define __raw_writeb writeb
#define __raw_writew writew
#define __raw_writel writel

static inline void io_insb (unsigned long port, void *dst, unsigned long count)
{
	unsigned char *p = dst;
	while (count--)
		*p++ = inb (port);
}
static inline void io_insw (unsigned long port, void *dst, unsigned long count)
{
	unsigned short *p = dst;
	while (count--)
		*p++ = inw (port);
}
static inline void io_insl (unsigned long port, void *dst, unsigned long count)
{
	unsigned long *p = dst;
	while (count--)
		*p++ = inl (port);
}

static inline void
io_outsb (unsigned long port, const void *src, unsigned long count)
{
	const unsigned char *p = src;
	while (count--)
		outb (*p++, port);
}
static inline void
io_outsw (unsigned long port, const void *src, unsigned long count)
{
	const unsigned short *p = src;
	while (count--)
		outw (*p++, port);
}
static inline void
io_outsl (unsigned long port, const void *src, unsigned long count)
{
	const unsigned long *p = src;
	while (count--)
		outl (*p++, port);
}

#define outsb(a,b,l) io_outsb(a,b,l)
#define outsw(a,b,l) io_outsw(a,b,l)
#define outsl(a,b,l) io_outsl(a,b,l)

#define insb(a,b,l) io_insb(a,b,l)
#define insw(a,b,l) io_insw(a,b,l)
#define insl(a,b,l) io_insl(a,b,l)

#define iounmap(addr)				((void)0)
#define ioremap(physaddr, size)			(physaddr)
#define ioremap_nocache(physaddr, size)		(physaddr)
#define ioremap_writethrough(physaddr, size)	(physaddr)
#define ioremap_fullcache(physaddr, size)	(physaddr)

static inline void sync(void)
{
}

/*
 * Given a physical address and a length, return a virtual address
 * that can be used to access the memory range with the caching
 * properties specified by "flags".
 */
#define MAP_NOCACHE	(0)
#define MAP_WRCOMBINE	(0)
#define MAP_WRBACK	(0)
#define MAP_WRTHROUGH	(0)

static inline void *
map_physmem(phys_addr_t paddr, unsigned long len, unsigned long flags)
{
	return (void *)paddr;
}

/*
 * Take down a mapping set up by map_physmem().
 */
static inline void unmap_physmem(void *vaddr, unsigned long flags)
{

}

static inline phys_addr_t virt_to_phys(void * vaddr)
{
	return (phys_addr_t)(vaddr);
}

#endif /* __MICROBLAZE_IO_H__ */


text:
namespace spdy {

SpdyPinnableBufferPiece::SpdyPinnableBufferPiece()
    : buffer_(nullptr), length_(0) {}

SpdyPinnableBufferPiece::~SpdyPinnableBufferPiece() = default;

void SpdyPinnableBufferPiece::Pin() {
  if (!storage_ && buffer_ != nullptr && length_ != 0) {
    storage_.reset(new char[length_]);
    std::copy(buffer_, buffer_ + length_, storage_.get());
    buffer_ = storage_.get();
  }
}

void SpdyPinnableBufferPiece::Swap(SpdyPinnableBufferPiece* other) {
  size_t length = length_;
  length_ = other->length_;
  other->length_ = length;

  const char* buffer = buffer_;
  buffer_ = other->buffer_;
  other->buffer_ = buffer;

  storage_.swap(other->storage_);
}

}  // namespace spdy


text:
package linkedlist.singly;

import java.util.Objects;

/**
 * https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/
 * <p>
 * Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop.
 * For example, loop is present in below linked list and length of loop is 4. If loop is not present, then function should return 0.
 */
public class FindLengthOfLoop {

    static class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }

        public Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

    int countNodesinLoop(Node head) {
        Node slow = head, fast = head;
        while (Objects.nonNull(slow) && Objects.nonNull(fast) && Objects.nonNull(fast.getNext())) {
            slow = slow.getNext();
            fast = fast.getNext().getNext();
            if (slow == fast) {
                return countNodes(slow);
            }
        }
        return 0;
    }

    private int countNodes(Node node) {
        int result = 1;
        Node temp = node;
        while (temp.getNext() != node) {
            result++;
            temp = temp.getNext();
        }
        return result;
    }

    public static void main(String[] args) {
        Node fifth = new Node(5);
        Node fourth = new Node(4, fifth);
        Node third = new Node(3, fourth);
        Node second = new Node(2, third);
        Node head = new Node(1, second);
        fifth.setNext(second);

        FindLengthOfLoop findLengthOfLoop = new FindLengthOfLoop();
        System.out.println(findLengthOfLoop.countNodesinLoop(head));
    }
}


text:
#import "NSDarwinString.h"

#if __APPLE__
#import <Foundation/NSException.h>
#import <Foundation/NSStringHashing.h>
#import <Foundation/NSRaiseException.h>

// only needed for Darwin ppc
struct objc_class _NSConstantStringClassReference;

// only needed for Darwin i386/x86
#if __LP64__
int __CFConstantStringClassReference[24] = {0};
#else
int __CFConstantStringClassReference[12] = {0};
#endif

@implementation NSDarwinString

-copy {
   return self;
}

-copyWithZone:(NSZone *)zone {
   return self;
}

-retain {
   return self;
}

- (oneway void)release
{
}

-autorelease {
   return self;
}

-(void)dealloc {
   return;
   [super dealloc];
}

-(NSUInteger)length {
   return _length;
}

-(unichar)characterAtIndex:(NSUInteger)location {
   if(location>=_length){
      NSRaiseException(NSRangeException,self,_cmd,@"index %d beyond length %d",
                       location,[self length]);
   }

   return _bytes[location];
}

-(void)getCharacters:(unichar *)buffer {
   int i;

   for(i=0;i<_length;i++)
      buffer[i]=_bytes[i];
}

-(void)getCharacters:(unichar *)buffer range:(NSRange)range {
   NSInteger i,loc=range.location,len=range.length;

   if(NSMaxRange(range)>_length){
      NSRaiseException(NSRangeException,self,_cmd,@"range %@ beyond length %d",
                       NSStringFromRange(range),[self length]);
   }

   for(i=0;i<len;i++)
      buffer[i]=_bytes[loc+i];
}

-(NSUInteger)hash {
   return NSStringHashASCII(_bytes,MIN(_length,NSHashStringLength));
}

@end

#endif


text:
Due to GitHub's use of hosted repositories to train their Copilot AI system,
which provides code output with no source attribution, in violation of licenses,
this repository has been permanently removed from GitHub.

The primary source for my projects is
[https://tcp80.org/hub.html](https://tcp80.org/hub.html) (primary source), and
some may be found on [Shithub](https://shithub.us/) and
[Sourcehut](https://git.sr.ht/~grobe0ba).


text:
from pyFG import FortiOS, FortiConfig

if __name__ == '__main__':
    f = open('running.conf', 'r')
    running = f.read()
    f.close()

    d = FortiOS('')
    d.load_config(config_text=running)

    d.candidate_config['router bgp'].set_param('as', 123)
    d.candidate_config['router bgp']['neighbor']['10.240.4.3'].set_param('bfd', 'disable')
    d.candidate_config['router bgp']['neighbor'].del_block('10.240.4.24')

    new_neigh = FortiConfig('10.6.6.6', 'edit')
    new_neigh.set_param('as', '666')
    new_neigh.set_param('route-map-out', 'my_route_map')
    new_neigh.set_param('update-source', 'port6')
    new_neigh.set_param('bfd', 'enable')
    d.candidate_config['router bgp']['neighbor'].set_block(new_neigh)

    print "This is the diff of the conigs:"
    for line in d.compare_config(text=True):
        print line

    print "\n\n"
    print "This is how to reach the desired state:"
    print d.compare_config()


text:
/**
 * Autogenerated by Thrift for thrift/compiler/test/fixtures/mcpp2-compare/src/includes.thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated @nocommit
 */
#pragma once

#include "thrift/compiler/test/fixtures/mcpp2-compare/gen-cpp2/includes_metadata.h"
#include <thrift/lib/cpp2/visitation/for_each.h>

namespace apache {
namespace thrift {
namespace detail {

template <>
struct ForEachField<::a::different::ns::AStruct> {
  template <typename F, typename... T>
  void operator()(FOLLY_MAYBE_UNUSED F&& f, FOLLY_MAYBE_UNUSED T&&... t) const {
    f(0, static_cast<T&&>(t).FieldA_ref()...);
  }
};

template <>
struct ForEachField<::a::different::ns::AStructB> {
  template <typename F, typename... T>
  void operator()(FOLLY_MAYBE_UNUSED F&& f, FOLLY_MAYBE_UNUSED T&&... t) const {
    f(0, static_cast<T&&>(t).FieldA_ref()...);
  }
};
} // namespace detail
} // namespace thrift
} // namespace apache


text:
/**
 * an enumeration for all available collision types
 */
export enum CollisionType {

    None, Circle, Rectangle, RotatedRectangle
}


text:
meetup-to-json
=============

~~Inspired by~~ *stolen from* [@benfoxall](https://github.com/benfoxall)'s [lastfm-to-csv](https://github.com/benfoxall/lastfm-to-csv) and modified to get Meetup.com members.

### What does it do?
Goes off to meetup.com, fetches all the info for members of the specified froup and saves to the browsers local storage. You can then download to your machine as a .json file.

### Why JSON?
It's better then csv, no matter what Ben says


text:
<?php declare(strict_types=1);

namespace Nirvarnia\Exception;

use Exception;

/**
 * Exception type to represent problems deleting things from the filesystem. You
 * can throw exceptions of this type when the PHP function unlink() evaluates to
 * false.
 */
class FileNotDeleted extends Exception
{
    // No body.
}


text:
#ifndef DART_GUI_OSG_RENDER_SPHERESHAPENODE_HPP_
#define DART_GUI_OSG_RENDER_SPHERESHAPENODE_HPP_

#include <osg/ShapeDrawable>
#include <osg/MatrixTransform>

#include "dart/gui/osg/render/ShapeNode.hpp"

namespace dart {

namespace dynamics {
class SphereShape;
} // namespace dynamics

namespace gui {
namespace osg {
namespace render {

class SphereShapeGeode;
class SphereShapeDrawable;

class SphereShapeNode : public ShapeNode, public ::osg::MatrixTransform
{
public:

  SphereShapeNode(
      std::shared_ptr<dart::dynamics::SphereShape> shape,
      ShapeFrameNode* parent);

  void refresh();
  void extractData(bool firstTime);

protected:

  virtual ~SphereShapeNode();

  std::shared_ptr<dart::dynamics::SphereShape> mSphereShape;
  SphereShapeGeode* mGeode;

};

} // namespace render
} // namespace osg
} // namespace gui
} // namespace dart

#endif // DART_GUI_OSG_RENDER_SPHERESHAPENODE_HPP_


text:
#ifndef QT3DCORE_QEVENTFILTERSERVICE_H
#define QT3DCORE_QEVENTFILTERSERVICE_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of other Qt classes.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <Qt3DCore/qt3dcore_global.h>
#include <Qt3DCore/private/qservicelocator_p.h>

QT_BEGIN_NAMESPACE

namespace Qt3DCore {

class QEventFilterServicePrivate;

class QT3DCORESHARED_EXPORT QEventFilterService : public QAbstractServiceProvider
{
public:
    QEventFilterService();
    ~QEventFilterService();

    void initialize(QObject *eventSource);
    void shutdown(QObject *eventSource);
    void registerEventFilter(QObject *eventFilter, int priority);
    void unregisterEventFilter(QObject *eventFilter);

private:
    Q_DECLARE_PRIVATE(QEventFilterService)
};

} // Qt3DCore

QT_END_NAMESPACE

#endif // QT3DCORE_QEVENTFILTERSERVICE_H


text:
import {
  Bytes,
  DocumentReference,
  GeoPoint,
  Timestamp,
} from 'firebase/firestore';
import produce from 'immer';
import get from 'lodash.get';

import {
  FieldType,
  FirestoreAny,
  FirestoreArray,
  FirestoreMap,
  FirestorePrimitive,
} from './models';

/** Firestore supported numbers */
export const NUMBER_REGEX = /^-?([\d]*\.?\d+|Infinity|NaN)$/;

export function getParentPath(path: string[]) {
  return path.slice(0, path.length - 1);
}

export function lastFieldName(path: string[]): string {
  if (!path.length)
    throw new Error(`${path} is empty and has no _last_ field name`);
  return path[path.length - 1];
}

export function getFieldType(value: FirestoreAny): FieldType {
  if (value === null) {
    return FieldType.NULL;
  }

  if (value instanceof Timestamp) {
    return FieldType.TIMESTAMP;
  }

  if (value instanceof Array) {
    return FieldType.ARRAY;
  }

  if (value instanceof DocumentReference) {
    return FieldType.REFERENCE;
  }

  if (value instanceof GeoPoint) {
    return FieldType.GEOPOINT;
  }

  if (value instanceof Bytes) {
    return FieldType.BLOB;
  }

  if (typeof value === 'object') {
    return FieldType.MAP;
  }

  return typeof value as FieldType;
}

export function isBoolean(value: FirestoreAny): value is boolean {
  return typeof value === 'boolean';
}

export function isReference(value: FirestoreAny): value is DocumentReference {
  return value instanceof DocumentReference;
}

export function isTimestamp(value: FirestoreAny): value is Timestamp {
  return value instanceof Timestamp;
}

export function isString(value: FirestoreAny): value is string {
  return typeof value === 'string';
}

export function isNumber(value: FirestoreAny): value is number {
  return typeof value === 'number';
}

export function isGeoPoint(value: FirestoreAny): value is GeoPoint {
  return value instanceof GeoPoint;
}

export function isMap(value: any): value is FirestoreMap {
  return getFieldType(value) === FieldType.MAP;
}

export function isArray(value: any): value is FirestoreArray {
  return getFieldType(value) === FieldType.ARRAY;
}

export function isPrimitive(value: any): value is FirestorePrimitive {
  return !isMap(value) && !isArray(value);
}

/*
  Return a copy of base with the field (specified by path) updated to value.
  This function also works with array elements. base is never modified.
*/
export const withFieldSet = produce((draft, path: string[], value: any) => {
  const parent = get(draft, getParentPath(path)) || draft;
  if (isMap(parent)) {
    parent[lastFieldName(path)] = value;
  } else if (isArray(parent)) {
    parent[Number(lastFieldName(path))] = value;
  } else {
    return value;
  }
});

/*
  Return a copy of base with the field (specified by path) deleted.
  This function also works with removing array elements. base is never modified.
*/
export const withFieldRemoved = produce((draft, path: string[]) => {
  const parent = get(draft, getParentPath(path)) || draft;
  if (isMap(parent)) {
    delete parent[lastFieldName(path)];
  } else if (isArray(parent)) {
    parent.splice(Number(lastFieldName(path)), 1);
  }
});

// Give a brief text summary of the data.
// Note: maxLen is soft (at least for now). End result may still be longer.
export function summarize(data: FirestoreAny, maxLen: number): string {
  switch (getFieldType(data)) {
    case FieldType.ARRAY:
      return summarizeArray(data as FirestoreAny[], maxLen, summarize);
    case FieldType.MAP:
      return summarizeMap(
        data as Record<string, FirestoreAny>,
        maxLen,
        summarize
      );
    case FieldType.BLOB:
      const base64 = (data as Bytes).toBase64();
      if (base64.length < maxLen) return base64;
      else return base64.slice(0, maxLen) + '...';
    case FieldType.BOOLEAN:
      return (data as boolean).toString();
    case FieldType.GEOPOINT:
      const value = data as GeoPoint;
      return summarizeLatLng(value.latitude, value.longitude);
    case FieldType.NULL:
      return 'null';
    case FieldType.NUMBER:
      return (data as number).toString();
    case FieldType.REFERENCE:
      return (data as DocumentReference).path;
    case FieldType.STRING:
      return `"${data as string}"`;
    case FieldType.TIMESTAMP:
      return summarizeDate((data as Timestamp).toDate(), maxLen);
    case FieldType.JSON:
      throw new Error('JSON field type is input only');
  }
}

export function summarizeDate(date: Date, maxLen: number): string {
  // TODO: Better date time formatting.
  // Note: Not using toLocaleString() since it does not stringify timezone.
  return date.toString();
}

export function summarizeArray<E = FirestoreAny>(
  array: E[],
  maxLen: number,
  summarizeElement: (element: E, maxLen: number) => string
): string {
  let output = '[';
  for (const element of array) {
    if (output.length > 1) output += ', ';
    if (output.length > maxLen) {
      output += '...';
      break;
    }
    output += summarizeElement(element, maxLen - output.length);
  }
  output += ']';
  return output;
}

export function summarizeMap<V = FirestoreAny>(
  map: Record<string, V>,
  maxLen: number,
  summarizeValue: (value: V, maxLen: number) => string
): string {
  let output = '{';
  for (const [key, value] of Object.entries(map).sort((a, b) =>
    compareFirestoreKeys(a[0], b[0])
  )) {
    if (output.length > 1) output += ', ';
    if (output.length > maxLen) {
      output += '...';
      break;
    }
    output += `${key}: ${summarizeValue(value, maxLen - output.length)}`;
  }
  output += '}';
  return output;
}

export function summarizeLatLng(latitude: number, longitude: number) {
  return `[${latStr(latitude)}, ${longStr(longitude)}]`;
}

function latStr(lat: number): string {
  return `${Math.abs(lat)}° ${lat >= 0 ? 'N' : 'S'}`;
}

function longStr(long: number): string {
  return `${Math.abs(long)}° ${long >= 0 ? 'E' : 'W'}`;
}

export function compareFirestoreKeys(fieldA: string, fieldB: string): number {
  // TODO: Use UTF-8 encoded byte order instead of localCompare to match Firestore production behavior https://firebase.google.com/docs/firestore/manage-data/data-types
  return fieldA.localeCompare(fieldB);
}


text:
package mesosphere.marathon
package core.launchqueue.impl

import java.time.Clock

import akka.Done
import akka.actor._
import akka.event.LoggingReceive
import akka.pattern._
import akka.stream.scaladsl.SourceQueue
import com.typesafe.scalalogging.StrictLogging
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.instance.update.{InstanceDeleted, InstanceUpdateOperation, InstanceUpdated}
import mesosphere.marathon.core.launcher.{InstanceOp, InstanceOpFactory, OfferMatchResult}
import mesosphere.marathon.core.launchqueue.LaunchQueueConfig
import mesosphere.marathon.core.launchqueue.impl.TaskLauncherActor.RecheckIfBackOffUntilReached
import mesosphere.marathon.core.matcher.base.OfferMatcher
import mesosphere.marathon.core.matcher.base.OfferMatcher.{InstanceOpWithSource, MatchedInstanceOps}
import mesosphere.marathon.core.matcher.base.util.{ActorOfferMatcher, InstanceOpSourceDelegate}
import mesosphere.marathon.core.matcher.manager.OfferMatcherManager
import mesosphere.marathon.core.task.tracker.InstanceTracker
import mesosphere.marathon.state._
import mesosphere.marathon.util.CancellableOnce
import org.apache.mesos.{Protos => Mesos}
import scala.concurrent.ExecutionContext.Implicits.global

import scala.collection.mutable
import scala.concurrent.Promise
import scala.concurrent.duration._

private[launchqueue] object TaskLauncherActor {
  def props(
      config: LaunchQueueConfig,
      offerMatcherManager: OfferMatcherManager,
      clock: Clock,
      taskOpFactory: InstanceOpFactory,
      instanceTracker: InstanceTracker,
      rateLimiterActor: ActorRef,
      offerMatchStatistics: SourceQueue[OfferMatchStatistics.OfferMatchUpdate],
      localRegion: () => Option[Region]
  )(runSpecId: AbsolutePathId): Props = {
    Props(
      new TaskLauncherActor(
        config,
        offerMatcherManager,
        clock,
        taskOpFactory,
        instanceTracker,
        rateLimiterActor,
        offerMatchStatistics,
        runSpecId,
        localRegion
      )
    )
  }

  sealed trait Message

  sealed trait Requests extends Message

  /**
    * Results in rechecking whether we may launch tasks.
    */
  private case object RecheckIfBackOffUntilReached extends Requests

  private case class LoadedInstances(value: Map[Instance.Id, Instance]) extends Message
  private case class SynchronizedInstance(value: Option[Instance]) extends Message

  val OfferOperationRejectedTimeoutReason: String =
    "InstanceLauncherActor: no accept received within timeout. " +
      "You can reconfigure the timeout with --task_operation_notification_timeout."
}

/**
  * Allows processing offers for starting tasks for the given app.
  */
private class TaskLauncherActor(
    config: LaunchQueueConfig,
    offerMatcherManager: OfferMatcherManager,
    clock: Clock,
    instanceOpFactory: InstanceOpFactory,
    instanceTracker: InstanceTracker,
    rateLimiterActor: ActorRef,
    offerMatchStatistics: SourceQueue[OfferMatchStatistics.OfferMatchUpdate],
    runSpecId: AbsolutePathId,
    localRegion: () => Option[Region]
) extends Actor
    with Stash
    with StrictLogging {
  // scalastyle:on parameter.number

  import TaskLauncherActor._

  /** instances that are in the tracker */
  private[impl] var instanceMap: Map[Instance.Id, Instance] = Map.empty

  private[impl] def inFlightInstanceOperations = instanceMap.values.filter(_.isProvisioned)

  private[impl] val offerOperationAcceptTimeout = mutable.Map.empty[Instance.Id, Cancellable]

  private[impl] def scheduledInstances: Iterable[Instance] = instanceMap.values.filter(_.isScheduled)
  def scheduledVersions = scheduledInstances.map(_.runSpec.configRef).toSet

  def instancesToLaunch = scheduledInstances.size

  private[this] var recheckBackOff: Cancellable = CancellableOnce.noop

  /* A map of times a RunSpec version is allowed to launch. Sourced from RateLimiter DelayUpdate.
   * When we receive signal that there is no delay, the current time is used.
   */
  val launchAllowedAt: mutable.Map[RunSpecConfigRef, Timestamp] = mutable.Map.empty

  /** Decorator to use this actor as a [[OfferMatcher#TaskOpSource]] */
  private[this] val myselfAsLaunchSource = InstanceOpSourceDelegate(self)

  override def preStart(): Unit = {
    super.preStart()

    instanceTracker
      .instancesBySpec()
      .map(bySpec => LoadedInstances(bySpec.instancesMap(runSpecId).instanceMap))
      .pipeTo(self)
  }

  override def postStop(): Unit = {
    unregister()
    recheckBackOff.cancel()

    if (inFlightInstanceOperations.nonEmpty) {
      logger.warn(s"Actor shutdown while instances are in flight: ${inFlightInstanceOperations.map(_.instanceId).mkString(", ")}")
    }
    offerOperationAcceptTimeout.valuesIterator.foreach(_.cancel())

    offerMatchStatistics.offer(OfferMatchStatistics.LaunchFinished(runSpecId))

    super.postStop()

    logger.info(s"Stopped InstanceLauncherActor for ${runSpecId}.")
  }

  override def receive: Receive = loading

  /**
    * Initial loading of instances. The preStart calls the instance tracker and pipes the result here.
    */
  private[this] def loading: Receive = {
    case LoadedInstances(loadedInstances) =>
      instanceMap = loadedInstances
      val readable = instanceMap.values
        .map(i =>
          s"${i.instanceId}:{condition: ${i.state.condition}, goal: ${i.state.goal}, version: ${i.runSpecVersion}, reservation: ${i.reservation}}"
        )
        .mkString(", ")
      logger.info(s"Loaded instance map: instances=[$readable]")
      logger.info(s"Started instanceLaunchActor for $runSpecId with initial count $instancesToLaunch")
      scheduledVersions.foreach { configRef =>
        rateLimiterActor ! RateLimiterActor.GetDelay(configRef)
      }

      unstashAll()
      context.become(active)
      logger.debug("Became active.")

    case Status.Failure(cause) =>
      // escalate this failure
      throw new IllegalStateException("while loading tasks", cause)

    case other: AnyRef =>
      logger.debug(s"Stashing $other")
      stash()

  }

  /**
    * Processes the result from [[TaskLauncherActor.syncInstance()]].
    *
    * @param instanceId The id of the instance which is synchronized.
    */
  private[this] def syncing(instanceId: Instance.Id): Receive = {
    case SynchronizedInstance(maybeInstance) =>
      maybeInstance match {
        case Some(instance) =>
          instanceMap += instanceId -> instance

          // This timeout is only between us creating provisioned instance operation based on received offer
          // and that instance in provisioned state being persisted so this makes no sense for instances in all other states
          if (!instance.isProvisioned) {
            offerOperationAcceptTimeout.get(instanceId).foreach(_.cancel())
            offerOperationAcceptTimeout -= instanceId
          }
          logger.info(s"Synced single $instanceId from InstanceTracker: $instance")

          // Request delay for new run spec config.
          if (!launchAllowedAt.contains(instance.runSpec.configRef)) {
            // signal no interest in new offers until we get the back off delay.
            // this makes sure that we see unused offers again that we rejected for the old configuration.
            unregister()
            rateLimiterActor ! RateLimiterActor.GetDelay(instance.runSpec.configRef)
          }
        case None =>
          logger.info(s"Instance $instanceId does not exist in InstanceTracker - removing it from internal state.")
          removeInstanceFromInternalState(instanceId)
      }

      manageOfferMatcherStatus(clock.now())
      context.become(active)
      unstashAll()

    case other: AnyRef =>
      stash()
  }

  private[this] def active: Receive =
    LoggingReceive.withLabel("active") {
      Seq(
        receiveDelayUpdate,
        receiveTaskLaunchNotification,
        receiveInstanceUpdate,
        receiveProcessOffers,
        receiveUnknown
      ).reduce(_.orElse[Any, Unit](_))
    }

  private[this] def receiveUnknown: Receive = {
    case Status.Failure(ex) =>
      logger.error(s"TaskLauncherActor received a failure from $sender", ex)

    case msg: Any =>
      logger.debug(s"Received unknown message. msg=$msg")
      // fail fast and do not let the sender time out
      sender() ! Status.Failure(new IllegalStateException(s"Unhandled message: $msg"))
  }

  /**
    * Receive rate limiter updates.
    */
  private[this] def receiveDelayUpdate: Receive = {
    case RateLimiter.DelayUpdate(ref, maybeDelayUntil) if scheduledVersions.contains(ref) =>
      val now = clock.now()
      // If there's no delay, then launch immediately
      launchAllowedAt += ref -> maybeDelayUntil.fold(now)(_.deadline)

      manageOfferMatcherStatus(now)

      scheduleNextManageOfferStatus(now)

      logger.debug(s"After delay update $status")

    case RateLimiter.DelayUpdate(ref, delayUntil) if ref.id != runSpecId =>
      logger.warn(s"BUG! Received delay update for other run spec $ref and delay $delayUntil. Current run spec is $runSpecId")

    case RecheckIfBackOffUntilReached => manageOfferMatcherStatus(clock.now())
  }

  private[this] def scheduleNextManageOfferStatus(now: Timestamp): Unit = {
    recheckBackOff.cancel()
    val pendingBackOffs = launchAllowedAt.values.filter { _ > now }
    if (pendingBackOffs.nonEmpty) {
      val nextCheck = pendingBackOffs.min
      recheckBackOff = context.system.scheduler.scheduleOnce(now.until(nextCheck), self, RecheckIfBackOffUntilReached)(context.dispatcher)
    }
  }

  private[this] def receiveTaskLaunchNotification: Receive = {
    case InstanceOpSourceDelegate.InstanceOpRejected(op, TaskLauncherActor.OfferOperationRejectedTimeoutReason) =>
      if (inFlightInstanceOperations.exists(_.instanceId == op.instanceId) && offerOperationAcceptTimeout.contains(op.instanceId)) {
        // TaskLauncherActor is not always in sync with the state in InstanceTracker.
        // Especially when accepting offer, its state is ahead of InstanceTracker because it marks the instance as provisioned even before we persist it.
        // We do this because we need to know that we already attempted to launch that instance to not use the same one for another offer.
        // If everything goes well, some time after we manually adjust the internal state we should receive instance update to Provisioned.
        // It might happen that the we were not able to persist that Provisioned operation for some reason.
        // This timeout is here just to prevent us from staying in a state where we have different state locally than in InstanceTracker
        // This timeout should be set that far in the future that the offer operation should have already timed out anyway so it should be safe to do.
        // By explicitly syncing here we would either get the instance in Provisioned (we persisted the update) or scheduled (something failed).
        syncInstance(op.instanceId)
      }

    case InstanceOpSourceDelegate.InstanceOpRejected(op, reason) =>
      logger.debug(s"Task op '${op.getClass.getSimpleName}' for ${op.instanceId} was REJECTED, reason '$reason', rescheduling. $status")
      syncInstance(op.instanceId)

    case InstanceOpSourceDelegate.InstanceOpAccepted(op) =>
      logger.debug(s"Instance operation ${op.getClass.getSimpleName} for instance ${op.instanceId} got accepted")
      offerOperationAcceptTimeout.get(op.instanceId).foreach(_.cancel())
      offerOperationAcceptTimeout -= op.instanceId
  }

  private[this] def receiveInstanceUpdate: Receive = {
    case update: InstanceUpdated =>
      syncInstance(update.instance.instanceId)
      sender() ! Done

    case update: InstanceDeleted =>
      // if an instance was deleted, it's not needed anymore and we only have to remove it from the internal state
      logger.info(s"${update.instance.instanceId} was deleted. Will remove from internal state.")
      removeInstanceFromInternalState(update.instance.instanceId)
      sender() ! Done
  }

  private[this] def receiveProcessOffers: Receive = {
    case ActorOfferMatcher.MatchOffer(offer, promise) if !shouldLaunchInstances(clock.now()) =>
      logger.debug(s"Ignoring offer ${offer.getId.getValue}: $status")
      promise.trySuccess(MatchedInstanceOps.noMatch(offer.getId))

    case ActorOfferMatcher.MatchOffer(offer, promise) =>
      logger.info(s"Matching offer ${offer.getId.getValue} and need to launch $instancesToLaunch tasks.")
      val reachableInstances = instanceMap.filterNot {
        case (_, instance) =>
          instance.state.condition.isLost || instance.isScheduled
      }
      val candidateInstances = scheduledInstances.iterator.filter { instance => offer.getAllocationInfo.getRole == instance.role }.filter {
        instance => launchAllowed(clock.now(), instance.runSpec.configRef)
      }.toSeq

      candidateInstances match {
        case NonEmptyIterable(scheduledInstancesWithoutBackoff) =>
          val matchRequest = InstanceOpFactory.Request(offer, reachableInstances, scheduledInstancesWithoutBackoff, localRegion())
          instanceOpFactory.matchOfferRequest(matchRequest) match {
            case matched: OfferMatchResult.Match =>
              logger.info(s"Matched offer ${offer.getId.getValue} for run spec ${runSpecId}.")
              offerMatchStatistics.offer(OfferMatchStatistics.MatchResult(matched))
              handleInstanceOp(matched.instanceOp, offer, promise)
            case notMatched: OfferMatchResult.NoMatch =>
              logger.info(s"Did not match offer ${offer.getId.getValue} for run spec ${runSpecId}. Reasons: ${notMatched.reasons}")
              offerMatchStatistics.offer(OfferMatchStatistics.MatchResult(notMatched))
              promise.trySuccess(MatchedInstanceOps.noMatch(offer.getId))
          }
        case _ =>
          logger.debug(s"Ignoring offer ${offer.getId.getValue}: $status")
          promise.trySuccess(MatchedInstanceOps.noMatch(offer.getId))
      }
  }

  def syncInstance(instanceId: Instance.Id): Unit = {
    logger.debug(s"Synchronizing $instanceId")
    context.become(syncing(instanceId))
    instanceTracker.instancesBySpec.map(bySpec => SynchronizedInstance(bySpec.instance(instanceId))).pipeTo(self)
  }

  def removeInstanceFromInternalState(instanceId: Instance.Id): Unit = {
    instanceMap -= instanceId
    offerOperationAcceptTimeout.get(instanceId).foreach(_.cancel())
    offerOperationAcceptTimeout -= instanceId

    // Remove backoffs for deleted config refs
    launchAllowedAt.keySet.diff(scheduledVersions).foreach(launchAllowedAt.remove)
    manageOfferMatcherStatus(clock.now())

  }

  /**
    * Mutate internal state in response to having matched an instanceOp.
    *
    * @param instanceOp The instanceOp that is to be applied to on a previously
    *     received offer
    * @param offer The offer that could be matched successfully.
    * @param promise Promise that tells offer matcher that the offer has been accepted.
    */
  private[this] def handleInstanceOp(instanceOp: InstanceOp, offer: Mesos.Offer, promise: Promise[MatchedInstanceOps]): Unit = {

    // Mark instance in internal map as provisioned
    instanceOp.stateOp match {
      case InstanceUpdateOperation.Provision(instanceId, agentInfo, runSpecVersion, tasks, now) =>
        assert(instanceMap.contains(instanceId), s"Internal task launcher state did not include newly provisioned instance $instanceId")
        val existingInstance = instanceMap(instanceId)
        instanceMap += instanceId -> existingInstance.provisioned(agentInfo, runSpecVersion, tasks, now)
        scheduleTaskOpTimeout(context, instanceOp)
        logger.info(s"Updated instance map to ${instanceMap.values.map(i => i.instanceId -> i.state.condition)}")
      case InstanceUpdateOperation.Reserve(instanceId, reservation, agentInfo) =>
        assert(instanceMap.contains(instanceId), s"Internal task launcher state did not include reserved instance $instanceId")
        val existingInstance = instanceMap(instanceId)
        instanceMap += instanceId -> existingInstance.reserved(reservation, agentInfo)
        scheduleTaskOpTimeout(context, instanceOp)
        logger.info(s"Updated instance map to reserve ${instanceMap.values.map(i => i.instanceId -> i.state.condition)}")
      case other =>
        logger.info(s"Unexpected updated operation $other")
    }

    manageOfferMatcherStatus(clock.now())

    logger.info(s"Request ${instanceOp.getClass.getSimpleName} for instance '${instanceOp.instanceId.idString}'. $status")
    promise.trySuccess(MatchedInstanceOps(offer.getId, Seq(InstanceOpWithSource(myselfAsLaunchSource, instanceOp))))
  }

  private[this] def scheduleTaskOpTimeout(context: ActorContext, instanceOp: InstanceOp): Unit = {
    import context.dispatcher
    val message: InstanceOpSourceDelegate.InstanceOpRejected = InstanceOpSourceDelegate.InstanceOpRejected(
      instanceOp,
      TaskLauncherActor.OfferOperationRejectedTimeoutReason
    )
    val scheduledProvisionTimeout = context.system.scheduler.scheduleOnce(config.taskOpNotificationTimeout().milliseconds, self, message)
    offerOperationAcceptTimeout += instanceOp.instanceId -> scheduledProvisionTimeout
  }

  /**
    * Returns the time at which we know we can launch this instance
    *
    * Since this actor subscribes to task delays asynchronously, we pessimistically assume that an instance cannot be
    * launched until we've received a DelayUpdate for the respective config version
    */
  private[this] def launchAllowed(now: Timestamp, configRef: RunSpecConfigRef): Boolean = launchAllowedAt.get(configRef).exists(_ <= now)
  private[this] def shouldLaunchInstances(now: Timestamp): Boolean = {
    if (scheduledInstances.nonEmpty || launchAllowedAt.nonEmpty)
      logger.info(
        s"Found scheduled instances: ${scheduledInstances.map(_.instanceId).mkString(",")} and current back-off map: $launchAllowedAt"
      )
    scheduledInstances.nonEmpty && scheduledVersions.exists { configRef => launchAllowed(now, configRef) }
  }

  private[this] def status: String = {
    val activeBackOffs = launchAllowedAt.values.filter(_ > clock.now())
    val backoffStr = if (activeBackOffs.nonEmpty) {
      s"currently waiting for backoffs $activeBackOffs"
    } else {
      "not backing off"
    }

    val inFlight = inFlightInstanceOperations.size
    val launchedInstances = instanceMap.values.filterNot(_.isProvisioned).count(_.isActive)
    s"$instancesToLaunch instancesToLaunch, $inFlight in flight, $launchedInstances confirmed. $backoffStr"
  }

  /** Manage registering this actor as offer matcher. Only register it if there are empty reservations or scheduled instances. */
  private[this] lazy val myselfAsOfferMatcher: OfferMatcher = {
    //set the precedence only, if this app is resident
    val isResident = scheduledInstances.exists(_.runSpec.isResident)
    new ActorOfferMatcher(self, if (isResident) Some(runSpecId) else None)
  }
  private[this] var registeredAsMatcher = false

  /** Register/unregister as necessary */
  private[this] def manageOfferMatcherStatus(now: Timestamp): Unit = {
    val shouldBeRegistered = shouldLaunchInstances(now)

    if (shouldBeRegistered && !registeredAsMatcher) {
      logger.debug(s"Registering for ${runSpecId}.")
      offerMatcherManager.addSubscription(myselfAsOfferMatcher)(context.dispatcher)
      registeredAsMatcher = true
    } else if (!shouldBeRegistered && registeredAsMatcher) {
      if (instancesToLaunch > 0) {
        logger.info(s"Backing off due to task failures. Stop receiving offers for ${runSpecId}")
      } else {
        logger.info(s"No tasks left to launch. Stop receiving offers for ${runSpecId}")
      }
      unregister()
    }
  }

  private[this] def unregister(): Unit = {
    if (registeredAsMatcher) {
      logger.info("Deregister as matcher.")
      offerMatcherManager.removeSubscription(myselfAsOfferMatcher)(context.dispatcher)
      registeredAsMatcher = false
    }
  }
}


text:
The Direct Persistence Layer (DPL) adds a persistent object model to the
Berkeley DB transactional engine.

Package Specification

Introduction

The Entity Model

A brief example

Which API to use?

Java 1.5 dependencies

Generic Types

Annotations

Bytecode Enhancement

Introduction

The Direct Persistence Layer (DPL) was designed to meet the following
requirements.

A type safe and convenient API is provided for accessing persistent
objects.  The use of Java generic types, although optional, is fully exploited
to provide type safety.  For example:

{@literal PrimaryIndex<Long,Employer> employerById = ...;}
long employerId = ...;
Employer employer = employerById.get(employerId);

All Java types are allowed to be persistent without requiring that they
implement special interfaces.  Persistent fields may be {@code private},
package-private (default access), {@code protected}, or {@code public}.  No
hand-coding of bindings is required.  However, each persistent class must have
a default constructor.  For example:

{@literal @Persistent}
class Address {
    String street;
    String city;
    String state;
    int zipCode;
    private Address() {}
}

Bytecode enhancement provides fully optimized bindings that do not use Java
reflection.

It is easy to define primary and secondary keys.  No external schema is
required and Java annotations may be used for defining all metadata.
Extensions may derive metadata from other sources.  For example, the following
Employer class is defined as a persistent entity with a primary key field
{@code id} and the secondary key field {@code name}:

{@literal @Entity}
class Employer {

    {@literal @PrimaryKey(sequence="ID")}
    long id;

    {@literal @SecondaryKey(relate=ONE_TO_ONE)}
    String name;

    Address address;

    private Employer() {}
}

Interoperability with external components is supported via the Java
collections framework.  Any primary or secondary index can be accessed using a
standard java.util collection.  For example:

{@literal java.util.SortedMap<String,Employer> map = employerByName.sortedMap();}

Class evolution is explicitly supported.  Compatible changes (adding fields
and type widening) are performed automatically and transparently.  For example,
without any special configuration a {@code street2} field may be added to the
{@code Address} class and the type of the {@code zipCode} field may be changed
from {@code int} to {@code long}:

{@literal @Persistent}
class Address {
    String street;
    String street2;
    String city;
    String state;
    long zipCode;
    private Address() {}
}

Many incompatible class changes, such as renaming fields or refactoring a
single class, can be performed using {@link
com.sleepycat.persist.evolve.Mutations Mutations}.  Mutations are automatically
applied lazily as data is accessed, avoiding downtime to convert large
databases during a software upgrade.

Complex refactoring involving multiple classes may be performed using the a
store conversion.  The DPL
always provides access to your data via a {@code RawStore}, no matter what
changes have been made to persistent classes.

The performance of the Berkeley DB transactional engine is not compromised.
Operations are internally mapped directly to the engine API, object bindings
are lightweight, and all engine tuning parameters are available.  For example,
a "dirty read" may be performed using an optional {@link
com.sleepycat.db.LockMode LockMode} parameter:

Employer employer = employerByName.get(null, "Gizmo Inc", LockMode.READ_UNCOMMITTED);

For high performance applications, {@link com.sleepycat.db.DatabaseConfig
DatabaseConfig} parameters may be used to tune the performance of the Berkeley
DB engine.  For example, the size of an internal Btree node can be specified
as follows:

DatabaseConfig config = store.getPrimaryConfig(Employer.class);
config.setNodeMaxEntries(64);
store.setPrimaryConfig(config);

The Entity Model

The DPL is intended for applications that represent persistent domain
objects using Java classes.  An entity class is an ordinary Java class
that has a primary key and is stored and accessed using a primary index.  It
may also have any number of secondary keys, and entities may be accessed by
secondary key using a secondary index.

An entity class may be defined with the {@link
com.sleepycat.persist.model.Entity Entity} annotation.  For each entity class,
its primary key may be defined using the {@link
com.sleepycat.persist.model.PrimaryKey PrimaryKey} annotation and any number of
secondary keys may be defined using the {@link
com.sleepycat.persist.model.SecondaryKey SecondaryKey} annotation.

In the following example, the {@code Person.ssn} (social security number)
field is the primary key and the {@code Person.employerIds} field is a
many-to-many secondary key.

{@literal @Entity}
class Person {

    {@literal @PrimaryKey}
    String ssn;

    String name;
    Address address;

    {@literal @SecondaryKey(relate=MANY_TO_MANY, relatedEntity=Employer.class)}
    {@literal Set<Long> employerIds = new HashSet<Long>();}

    private Person() {} // For bindings
}

A set of entity classes constitutes an entity model.  In addition
to isolated entity classes, an entity model may contain relationships between
entities.  Relationships may be defined using the {@link
com.sleepycat.persist.model.SecondaryKey SecondaryKey} annotation.
Many-to-one, one-to-many, many-to-many and one-to-one relationships are
supported, as well as foreign key constraints.

In the example above, a relationship between the {@code Person} and {@code
Employer} entities is defined via the {@code Person.employerIds} field.  The
{@code relatedEntity=Employer.class} annotation property establishes foreign
key constraints to guarantee that every element of the {@code employerIds} set
is a valid {@code Employer} primary key.

For more information on the entity model, see the {@link
com.sleepycat.persist.model.AnnotationModel AnnotationModel} and the {@link
com.sleepycat.persist.model.Entity Entity} annotation.

The root object in the DPL is the {@link com.sleepycat.persist.EntityStore
EntityStore}.  An entity store manages any number of objects for each entity
class defined in the model.  The store provides access to the primary and
secondary indices for each entity class, for example:

EntityStore store = new EntityStore(...);

{@literal PrimaryIndex<String,Person> personBySsn} =
    store.getPrimaryIndex(String.class, Person.class);

A brief example

The following example shows how to define an entity model and how to store
and access persistent objects.  Exception handling is omitted for brevity.

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityIndex;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.PrimaryIndex;
import com.sleepycat.persist.SecondaryIndex;
import com.sleepycat.persist.StoreConfig;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.Persistent;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.SecondaryKey;
import static com.sleepycat.persist.model.DeleteAction.NULLIFY;
import static com.sleepycat.persist.model.Relationship.ONE_TO_ONE;
import static com.sleepycat.persist.model.Relationship.ONE_TO_MANY;
import static com.sleepycat.persist.model.Relationship.MANY_TO_ONE;
import static com.sleepycat.persist.model.Relationship.MANY_TO_MANY;

// An entity class.
//
{@literal @Entity}
class Person {

    {@literal @PrimaryKey}
    String ssn;

    String name;
    Address address;

    {@literal @SecondaryKey(relate=MANY_TO_ONE, relatedEntity=Person.class)}
    String parentSsn;

    {@literal @SecondaryKey(relate=ONE_TO_MANY)}
    {@literal Set<String> emailAddresses = new HashSet<String>();}

    {@code @SecondaryKey(relate=MANY_TO_MANY, relatedEntity=Employer.class,
                                       onRelatedEntityDelete=NULLIFY)}
    {@code Set<Long> employerIds = new HashSet<Long>();}

    Person(String name, String ssn, String parentSsn) {
        this.name = name;
        this.ssn = ssn;
        this.parentSsn = parentSsn;
    }

    private Person() {} // For bindings
}

// Another entity class.
//
{@literal @Entity}
class Employer {

    {@literal @PrimaryKey(sequence="ID")}
    long id;

    {@literal @SecondaryKey(relate=ONE_TO_ONE)}
    String name;

    Address address;

    Employer(String name) {
        this.name = name;
    }

    private Employer() {} // For bindings
}

// A persistent class used in other classes.
//
{@literal @Persistent}
class Address {
    String street;
    String city;
    String state;
    int zipCode;
    private Address() {} // For bindings
}

// The data accessor class for the entity model.
//
class PersonAccessor {

    // Person accessors
    //
    {@literal PrimaryIndex<String,Person> personBySsn;}
    {@literal SecondaryIndex<String,String,Person> personByParentSsn;}
    {@literal SecondaryIndex<String,String,Person> personByEmailAddresses;}
    {@literal SecondaryIndex<Long,String,Person> personByEmployerIds;}

    // Employer accessors
    //
    {@literal PrimaryIndex<Long,Employer> employerById;}
    {@literal SecondaryIndex<String,Long,Employer> employerByName;}

    // Opens all primary and secondary indices.
    //
    public PersonAccessor(EntityStore store)
        throws DatabaseException {

        personBySsn = store.getPrimaryIndex(
            String.class, Person.class);

        personByParentSsn = store.getSecondaryIndex(
            personBySsn, String.class, "parentSsn");

        personByEmailAddresses = store.getSecondaryIndex(
            personBySsn, String.class, "emailAddresses");

        personByEmployerIds = store.getSecondaryIndex(
            personBySsn, Long.class, "employerIds");

        employerById = store.getPrimaryIndex(
            Long.class, Employer.class);

        employerByName = store.getSecondaryIndex(
            employerById, String.class, "name");
    }
}

// Open a transactional Berkeley DB engine environment.
//
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setTransactional(true);
Environment env = new Environment(new File("/my/data"), envConfig);

// Open a transactional entity store.
//
StoreConfig storeConfig = new StoreConfig();
storeConfig.setAllowCreate(true);
storeConfig.setTransactional(true);
EntityStore store = new EntityStore(env, "PersonStore", storeConfig);

// Initialize the data access object.
//
PersonAccessor dao = new PersonAccessor(store);

// Add a parent and two children using the Person primary index.  Specifying a
// non-null parentSsn adds the child Person to the sub-index of children for
// that parent key.
//
dao.personBySsn.put(new Person("Bob Smith", "111-11-1111", null));
dao.personBySsn.put(new Person("Mary Smith", "333-33-3333", "111-11-1111"));
dao.personBySsn.put(new Person("Jack Smith", "222-22-2222", "111-11-1111"));

// Print the children of a parent using a sub-index and a cursor.
//
{@literal EntityCursor<Person> children =}
    dao.personByParentSsn.subIndex("111-11-1111").entities();
try {
    for (Person child : children) {
        System.out.println(child.ssn + ' ' + child.name);
    }
} finally {
    children.close();
}

// Get Bob by primary key using the primary index.
//
Person bob = dao.personBySsn.get("111-11-1111");
assert bob != null;

// Create two employers.  Their primary keys are assigned from a sequence.
//
Employer gizmoInc = new Employer("Gizmo Inc");
Employer gadgetInc = new Employer("Gadget Inc");
dao.employerById.put(gizmoInc);
dao.employerById.put(gadgetInc);

// Bob has two jobs and two email addresses.
//
bob.employerIds.add(gizmoInc.id);
bob.employerIds.add(gadgetInc.id);
bob.emailAddresses.add("bob@bob.com");
bob.emailAddresses.add("bob@gmail.com");

// Update Bob's record.
//
dao.personBySsn.put(bob);

// Bob can now be found by both email addresses.
//
bob = dao.personByEmailAddresses.get("bob@bob.com");
assert bob != null;
bob = dao.personByEmailAddresses.get("bob@gmail.com");
assert bob != null;

// Bob can also be found as an employee of both employers.
//
{@literal EntityIndex<String,Person> employees;}
employees = dao.personByEmployerIds.subIndex(gizmoInc.id);
assert employees.contains("111-11-1111");
employees = dao.personByEmployerIds.subIndex(gadgetInc.id);
assert employees.contains("111-11-1111");

// When an employer is deleted, the onRelatedEntityDelete=NULLIFY for the
// employerIds key causes the deleted ID to be removed from Bob's employerIds.
//
dao.employerById.delete(gizmoInc.id);
bob = dao.personBySsn.get("111-11-1111");
assert !bob.employerIds.contains(gizmoInc.id);

store.close();
env.close();

The example illustrates several characteristics of the DPL:

Persistent data and keys are defined in terms of instance fields.  For
brevity the example does not show getter and setter methods, although these
would normally exist to provide encapsulation.  The DPL accesses fields during
object serialization and deserialization, rather than calling getter/setter
methods, leaving business methods free to enforce arbitrary validation rules.
For example:

{@literal @Persistent}
public class ConstrainedValue {

    private int min;
    private int max;
    private int value;

    private ConstrainedValue() {} // For bindings

    public ConstrainedValue(int min, int max) {
        this.min = min;
        this.max = max;
        value = min;
    }

    public setValue(int value) {
        if (value < min || value > max) {
            throw new IllegalArgumentException("out of range");
        }
        this.value = value;
    }
}

The above {@code setValue} method would not work if it were called during
object deserialization, since the order of setting fields is arbitrary.  The
{@code min} and {@code max} fields may not be set before the {@code value} is
set.

The example creates a transactional store and therefore all operations are
transaction protected.  Because no explicit transactions are used, auto-commit
is used implicitly.

Explicit transactions may also be used to group multiple operations in a
single transaction, and all access methods have optional transaction
parameters.  For example, the following two operations are performed atomically
in a transaction:

Transaction txn = env.beginTransaction(null, null);
dao.employerById.put(txn, gizmoInc);
dao.employerById.put(txn, gadgetInc);
txn.commit();

To provide maximum performance, the DPL operations map directly to the
Btree operations of the Berkeley DB engine.  Unlike other persistence
approaches, keys and indices are exposed for direct access and performance
tuning.

Queries are implemented by calling methods of the primary and secondary
indices.  An {@link com.sleepycat.persist.EntityJoin EntityJoin} class is also
available for performing equality joins.  For example, the following code
queries all of Bob's children that work for Gizmo Inc:

{@literal EntityJoin<String,Person> join = new EntityJoin(dao.personBySsn);}

join.addCondition(dao.personByParentSsn, "111-11-1111");
join.addCondition(dao.personByEmployerIds, gizmoInc.id);

{@literal ForwardCursor<Person> results = join.entities();}
try {
    for (Person person : results) {
        System.out.println(person.ssn + ' ' + person.name);
    }
} finally {
    results.close();
}

Object relationships are based on keys.  When a {@code Person} with a given
employer ID in its {@code employerIds} set is stored, the {@code Person} object
becomes part of the collection of employees for that employer.  This collection
of employees is accessed using a {@link
com.sleepycat.persist.SecondaryIndex#subIndex SecondaryIndex.subIndex} for the
employer ID, as shown below:

{@literal EntityCursor<Person> employees =}
    dao.personByEmployerIds.subIndex(gizmoInc.id).entities();
try {
    for (Person employee : employees) {
        System.out.println(employee.ssn + ' ' + employee.name);
    }
} finally {
    employees.close();
}

Note that when Bob's employer is deleted in the example, the {@code Person}
object for Bob is refetched to see the change to its {@code employerIds}.  This
is because objects are accessed by value, not by reference.  In other words, no
object cache or "persistence context" is maintained by the DPL.  The low level
caching of the embedded Berkeley DB engine, combined with lightweight object
bindings, provides maximum performance.

Which API to use?

The Berkeley DB engine has a {@link com.sleepycat.db Base API}, a {@link
com.sleepycat.collections Collections API} and a {@link com.sleepycat.persist
Direct Persistence Layer (DPL)}.  Follow these guidelines if you are not sure
which API to use:

When Java classes are used to represent domain objects in an application,
the DPL is recommended.  The more domain classes, the more value there is in
using annotations to define your schema.

When porting an application between Berkeley DB and Berkeley DB Java
Edition, or when you've chosen not to use Java classes to represent domain
objects, then the Base API is recommended.  You may also prefer to use this API
if you have very few domain classes.

The Collections API is useful for interoperating with external components
because it conforms to the standard Java Collections Framework.  It is
therefore useful in combination with both the Base API and the DPL.  You may
prefer this API because it provides the familiar Java Collections
interface.

Java 1.5 dependencies

NOTE: The current release of the DPL requires compiling and
deploying with Java 1.5 or greater.  Support for Java 1.4 may be added in a
future release, based on user demand.

The DPL uses two features of Java 1.5: generic types and annotations.  If
you wish to avoid using these two Java 1.5 features, the DPL provides options
for doing so.

Generic Types

Generic types are used to provide type safety, especially for the {@link
com.sleepycat.persist.PrimaryIndex PrimaryIndex}, {@link
com.sleepycat.persist.SecondaryIndex SecondaryIndex}, and {@link
com.sleepycat.persist.EntityCursor EntityCursor} classes.  If you don't wish to
use generic types, you can simply not declare your index and cursor objects
using generic type parameters.  This is the same as using the Java 1.5
Collections Framework without using generic types.

Annotations

If you don't wish to use annotations, you can provide another source of
metadata by implementing an {@link com.sleepycat.persist.model.EntityModel
EntityModel} class.  For example, naming conventions, static members, or an XML
configuration file might be used as a source of metadata.  However, if you
don't use annotations then you won't be able to use bytecode enhancement, which
is described next.

Bytecode Enhancement

The persistent fields of a class may be private, package-private, protected
or public.  The DPL can access persistent fields either by bytecode enhancement
or by reflection.

Bytecode enhancement may be used to fully optimize binding performance and
to avoid the use of Java reflection.  In applications that are CPU bound,
avoiding Java reflection can have a significant performance impact.

Bytecode enhancement may be performed either at runtime or at build time
(offline).  When enhancement is performed at runtime, persistent classes are
enhanced as they are loaded.  When enhancement is performed offline, class
files are enhanced during a post-compilation step.
Enhanced classes are used to efficiently access all fields and default
constructors, including non-public members.

See {@link com.sleepycat.persist.model.ClassEnhancer ClassEnhancer} for
bytecode enhancement configuration details.

If bytecode enhancement is not used as described above, the DPL will use
reflection for accessing persistent fields and the default constructor.  The
{@link java.lang.reflect.AccessibleObject#setAccessible
AccessibleObject.setAccessible} method is called by the DPL to enable access to
non-public fields and constructors.  If you are running under a Java security
manager you must configure your security policy to allow the following
permission:

{@code permission java.lang.reflect.ReflectPermission "suppressAccessChecks";}

There are three cases where setting the above permission is not
required:

If you are not running under a Java Security Manager, then access to
non-public members via reflection is not restricted.  This is the default for
J2SE.

If all persistent fields and default constructors are {@code public} then
they can be accessed via reflection without special permissions, even when
running under a Java Security Manager.  However, declaring {@code public}
instance fields is not recommended because it discourages encapsulation.

If bytecode enhancement is used as described above, then reflection will
not be used.

It is well known that executing generated code is faster than reflection.
However, this performance difference may or may not impact a given application
since it may be overshadowed by other factors.  Performance testing in a
realistic usage scenario is the best way to determine the impact.  If you are
determined to avoid the use of reflection then option 3 above is
recommended.


text:
package lemming.ui.panel;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.util.visit.IVisitor;

import java.util.List;

/**
 * A panel containing a modal window with a form.
 */
public abstract class ModalFormPanel extends Panel {
    /**
     * Form of a modal form panel.
     */
    private final Form<?> form;

    /**
     * The modal window container.
     */
    private final MarkupContainer container;

    /**
     * Clears data when clicked.
     */
    private final Button clearButton;

    /**
     * Confirms the dialog when clicked.
     */
    private final Button confirmButton;

    /**
     * ID of the modal window.
     */
    private final String modalWindowId;

    /**
     * Creates a modal form panel.
     *
     * @param id ID of the panel
     */
    public ModalFormPanel(String id) {
        super(id);
        modalWindowId = id + "-window";
        form = new Form("form");

        container = new WebMarkupContainer("modalWindow");
        clearButton = new ClearButton(form);
        confirmButton = new ConfirmButton(form);
        CancelButton cancelButton = new CancelButton();

        // bring autocomplete ui to front
        container.add(AttributeModifier.append("class", "ui-front"));
        container.setMarkupId(modalWindowId);
        container.add(form);
        container.add(cancelButton);
        container.add(clearButton.setVisible(false));
        container.add(confirmButton.setOutputMarkupId(true));
        form.setDefaultButton(confirmButton);
        add(container);
    }

    /**
     * Called when a modal window panel is initialized.
     */
    @Override
    protected void onInitialize() {
        super.onInitialize();
        container.add(new Label("modalTitle", getTitleString()));
        confirmButton.add(new Label("modalConfirm", getConfirmationString()));
        setRenderBodyOnly(true);
    }

    /**
     * Renders to the web response what the panel wants to contribute.
     *
     * @param response response object
     */
    @Override
    public void renderHead(IHeaderResponse response) {
        // stop bootstrap from blocking focus on text fields and focus first text field
        String javaScript = "jQuery('#" + modalWindowId + "')"
                + ".on('shown.bs.modal', function () { "
                + "jQuery(this).find('.form-control:text:visible, textarea.form-control:visible').first().focus(); })"
                + ".on('hidden.bs.modal', function () { "
                + "var input = jQuery('input[autofocus]').first(); "
                + "if (jQuery(input).length && jQuery(input).isInViewport()) { input.focus(); "
                + "} else { jQuery(':focus').blur(); } }); "
                + "jQuery('#" + modalWindowId + "').on('keydown', function (event) { "
                + "event.stopPropagation(); });";
        response.render(OnDomReadyHeaderItem.forScript(javaScript));
    }

    /**
     * Returns the markup id of the modal window.
     *
     * @return A string.
     */
    protected String getModalWindowId() {
        return modalWindowId;
    }

    /**
     * Shows a modal window panel.
     *
     * @param target target that produces an Ajax response
     */
    public void show(AjaxRequestTarget target) {
        target.appendJavaScript("jQuery('#" + modalWindowId + "').modal('show');");
    }

    /**
     * Hides a modal window panel.
     *
     * @param target target that produces an Ajax response
     */
    private void hide(AjaxRequestTarget target) {
        form.visitFormComponents((IVisitor<FormComponent<?>, List<FormComponent>>) (formComponent, visit) -> target
                .appendJavaScript("jQuery('#" + formComponent.getMarkupId() + "').val('');"));
        target.appendJavaScript("jQuery('#" + modalWindowId + "').modal('hide');");
    }

    /**
     * Adds a form component to the form and prevents form submission when enter is pressed.
     *
     * @param component component which is added
     */
    public void addFormComponent(Component component) {
        form.add(component);
    }

    /**
     * Returns the button text of the confirmation button.
     *
     * @return A confirmation string.
     */
    public String getConfirmationString() {
        return getString("Action.save");
    }

    /**
     * Returns the title of the modal window.
     *
     * @return A title string.
     */
    public abstract String getTitleString();

    /**
     * Makes the clearButton visible.
     */
    public void enableClearButton() {
        clearButton.setVisible(true);
    }

    /**
     * Called when the modal dialog is used to clear data.
     *
     * @param form   form that is submitted
     * @param target target that produces an Ajax response
     */
    protected void onClear(AjaxRequestTarget target, Form<?> form) {
    }

    /**
     * Called when the modal dialog is confirmed.
     *
     * @param form   form that is submitted
     * @param target target that produces an Ajax response
     */
    public abstract void onConfirm(AjaxRequestTarget target, Form<?> form);

    /**
     * Called when the modal dialog is canceled.
     */
    @SuppressWarnings("EmptyMethod")
    private void onCancel() {
    }

    /**
     * Cancels the dialog when clicked.
     */
    private class CancelButton extends AjaxLink<Void> {
        /**
         * Creates a button.
         */
        public CancelButton() {
            super("cancelButton");
        }

        /**
         * Called when the button is clicked.
         *
         * @param target target that produces an Ajax response
         */
        @Override
        public void onClick(AjaxRequestTarget target) {
            onCancel();
            hide(target);
        }
    }

    /**
     * Clears data when clicked.
     */
    private class ClearButton extends AjaxButton {
        /**
         * Creates a button.
         *
         * @param form form of a modal form panel
         */
        public ClearButton(Form<?> form) {
            super("clearButton", form);
        }

        /**
         * Called when the button is clicked.
         *
         * @param target target that produces an Ajax response
         * @param form form of a modal form panel
         */
        @Override
        public void onSubmit(AjaxRequestTarget target, Form<?> form) {
            onClear(target, form);
            hide(target);
        }
    }

    /**
     * Confirms the dialog when clicked.
     */
    private class ConfirmButton extends AjaxButton {
        /**
         * Creates a button.
         *
         * @param form form of a modal form panel
         */
        public ConfirmButton(Form<?> form) {
            super("confirmButton", form);
        }

        /**
         * Called when the button is clicked.
         *
         * @param target target that produces an Ajax response
         * @param form form of a modal form panel
         */
        @Override
        public void onSubmit(AjaxRequestTarget target, Form<?> form) {
            onConfirm(target, form);
            hide(target);
        }
    }
}