text:
/* $This file is distributed under the terms of the license in LICENSE$ */

package edu.cornell.mannlib.vitro.webapp.web.images;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.IndividualDao;
import edu.cornell.mannlib.vitro.webapp.startup.StartupStatus;

/**
 * A utility for finding the URL of the correct Placeholder image.
 *
 * The mapping of image URLs to classes is created at startup, and stored in the
 * ServletContext.
 */
public class PlaceholderUtil {
	private static final Log log = LogFactory.getLog(PlaceholderUtil.class);

	private static final String ATTRIBUTE_NAME = PlaceholderUtil.class
			.getName();
	private static final String PROPERTIES_FILE_PATH = "/images/placeholders/placeholders.properties";
	private static final String DEFAULT_IMAGE_PATH = "/images/placeholders/thumbnail.jpg";

	// ----------------------------------------------------------------------
	// Static methods
	// ----------------------------------------------------------------------

	/**
	 * If we have a placeholder image for this exact type, return it. Otherwise,
	 * return the default.
	 */
	public static String getPlaceholderImagePathForType(VitroRequest vreq,
			String typeUri) {
		PlaceholderUtil pu = getPlaceholderUtil(vreq);
		if (pu == null) {
			return DEFAULT_IMAGE_PATH;
		} else {
			return pu.getPlaceholderImagePathForType(typeUri);
		}
	}

	/**
	 * If there is a placeholder image for any type that this Individual
	 * instantiates, return that image. Otherwise, return the default.
	 */
	public static String getPlaceholderImagePathForIndividual(
			VitroRequest vreq, String individualUri) {
		PlaceholderUtil pu = getPlaceholderUtil(vreq);
		if (pu == null) {
			return DEFAULT_IMAGE_PATH;
		} else {
			IndividualDao iDao = vreq.getWebappDaoFactory().getIndividualDao();
			return pu.getPlaceholderImagePathForIndividual(iDao, individualUri);
		}
	}

	/** Get the PlaceholderUtil instance from the context, or null if none. */
	private static PlaceholderUtil getPlaceholderUtil(VitroRequest vreq) {
		if (vreq == null) {
			return null;
		}
		ServletContext ctx = vreq.getSession().getServletContext();
		Object attrib = ctx.getAttribute(ATTRIBUTE_NAME);
		if (attrib instanceof PlaceholderUtil) {
			return (PlaceholderUtil) attrib;
		} else {
			log.warn("Looked for a PlaceholerUtil, but found " + attrib);
			return null;
		}
	}

	// ----------------------------------------------------------------------
	// The object
	// ----------------------------------------------------------------------

	private final Map<String, String> mapUrlsByClass;

	private PlaceholderUtil(Map<String, String> map) {
		this.mapUrlsByClass = Collections
				.unmodifiableMap(new HashMap<String, String>(map));
	}

	/**
	 * If we have a placeholder image for this exact type, return it. Otherwise,
	 * return the default.
	 */
	private String getPlaceholderImagePathForType(String typeUri) {
		if (typeUri == null) {
			log.debug("getPlaceholderImagePathForType: typeUri is null");
			return DEFAULT_IMAGE_PATH;
		}
		String url = mapUrlsByClass.get(typeUri);
		if (url == null) {
			log.debug("getPlaceholderImagePathForType: no value for '"
					+ typeUri + "'");
			return DEFAULT_IMAGE_PATH;
		}
		log.debug("getPlaceholderImagePathForType: value for '" + typeUri
				+ "' is '" + url + "'");
		return url;
	}

	/**
	 * If there is a placeholder image for any type that this Individual
	 * instantiates, return that image. Otherwise, return the default.
	 */
	private String getPlaceholderImagePathForIndividual(IndividualDao iDao,
			String individualUri) {
		if (individualUri == null) {
			log.debug("getPlaceholderImagePathForIndividual: "
					+ "individualUri is null");
			return DEFAULT_IMAGE_PATH;
		}
		for (String classUri : mapUrlsByClass.keySet()) {
			String imageUrl = mapUrlsByClass.get(classUri);
			if (iDao.isIndividualOfClass(classUri, individualUri)) {
				log.debug("getPlaceholderImagePathForIndividual: individual '"
						+ individualUri + "' is of class '" + classUri
						+ "', value is '" + imageUrl + "'");
				return imageUrl;
			}
		}
		log.debug("getPlaceholderImagePathForIndividual: individual '"
				+ individualUri + "' is not of any recognized class");
		return DEFAULT_IMAGE_PATH;
	}

	// ----------------------------------------------------------------------
	// Classes used for setup
	// ----------------------------------------------------------------------

	public static class Setup implements ServletContextListener {
		@Override
		public void contextInitialized(ServletContextEvent sce) {
			ServletContext ctx = sce.getServletContext();
			StartupStatus ss = StartupStatus.getBean(ctx);

			try {
				File propertiesFile = confirmRealPath(ctx, PROPERTIES_FILE_PATH);
				Map<String, String> map = loadPropertiesToMap(propertiesFile);
				confirmImagesArePresent(ctx, map);
				ctx.setAttribute(ATTRIBUTE_NAME, new PlaceholderUtil(map));
			} catch (SetupException e) {
				if (e.getCause() == null) {
					ss.warning(this, e.getMessage());
				} else {
					ss.warning(this, e.getMessage(), e.getCause());
				}
			}
		}

		private Map<String, String> loadPropertiesToMap(File propertiesFile)
				throws SetupException {
			Properties props = new Properties();
			try {
				props.load(new FileReader(propertiesFile));
			} catch (IOException e) {
				throw new SetupException(
						"Can't load properties from the file at '"
								+ PROPERTIES_FILE_PATH
								+ "'. Is it in a valid format?", e);
			}

			Map<String, String> map = new HashMap<String, String>();
			for (Enumeration<Object> keys = props.keys(); keys
					.hasMoreElements();) {
				String key = (String) keys.nextElement();
				String value = props.getProperty(key);
				map.put(key, value);
			}

			return map;
		}

		private void confirmImagesArePresent(ServletContext ctx,
				Map<String, String> map) throws SetupException {
			Set<String> imageUrls = new HashSet<String>();
			imageUrls.add(DEFAULT_IMAGE_PATH);
			imageUrls.addAll(map.values());
			for (String imageUrl : imageUrls) {
				confirmRealPath(ctx, imageUrl);
			}

		}

		private File confirmRealPath(ServletContext ctx, String url)
				throws SetupException {
			String path = ctx.getRealPath(url);
			if (path == null) {
				throw new SetupException("Can't translate to real path: '"
						+ url + "'");
			}
			File file = new File(path);
			if (!file.exists()) {
				throw new SetupException("No file found at '" + url + "'.");
			}
			if (!file.canRead()) {
				throw new SetupException("Can't read the file at '" + url
						+ "'.");
			}
			return file;
		}

		@Override
		public void contextDestroyed(ServletContextEvent sce) {
			sce.getServletContext().removeAttribute(ATTRIBUTE_NAME);
		}

	}

	private static class SetupException extends Exception {
		public SetupException(String message) {
			super(message);
		}

		public SetupException(String message, Throwable cause) {
			super(message, cause);
		}
	}
}


text:
namespace osu.Framework.Bindables
{
    /// <summary>
    /// An event fired when a value changes, providing the old and new value for reference.
    /// </summary>
    /// <typeparam name="T">The type of bindable.</typeparam>
    public class ValueChangedEvent<T>
    {
        /// <summary>
        /// The old value.
        /// </summary>
        public readonly T OldValue;

        /// <summary>
        /// The new (and current) value.
        /// </summary>
        public readonly T NewValue;

        public ValueChangedEvent(T oldValue, T newValue)
        {
            OldValue = oldValue;
            NewValue = newValue;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
    <wicket:head>

    </wicket:head>
    <wicket:panel>

                            <wicket:message key="resourceheader"/>

                            <wicket:message key="accountlinkheader"/>

                            <wicket:message key="statusheader"/>

                            [resource name]

                            [accountLink]

                    <wicket:fragment wicket:id="rowCheckFrag">

                            <input type="checkbox" wicket:id="check"/>

                    </wicket:fragment>

            <wicket:fragment wicket:id="headerCheckFrag">

                    <input type="checkbox" wicket:id="groupselector" />

            </wicket:fragment>

            <wicket:fragment wicket:id="emptyCheckFrag" />

    </wicket:panel>


text:
package org.drools.util.asm;

import java.io.InputStream;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

import org.drools.core.util.asm.MethodComparator;
import org.mvel2.asm.ClassReader;

public class MethodComparerTest {

    @Test
    public void testMethodCompare() throws Exception {
        final MethodComparator comp = new MethodComparator();
        boolean result = comp.equivalent( "evaluate",
                                          new ClassReader( getClassData( MethodCompareA.class ) ),
                                          "evaluate",
                                          new ClassReader( getClassData( MethodCompareB.class ) ) );
        assertEquals( true,
                      result );

        result = comp.equivalent( "evaluate",
                                  new ClassReader( getClassData( MethodCompareA.class ) ),
                                  "evaluate2",
                                  new ClassReader( getClassData( MethodCompareA.class ) ) );
        assertEquals( false,
                      result );

        result = comp.equivalent( "evaluate",
                                  new ClassReader( getClassData( MethodCompareB.class ) ),
                                  "evaluate2",
                                  new ClassReader( getClassData( MethodCompareA.class ) ) );
        assertEquals( false,
                      result );

        result = comp.equivalent( "evaluate",
                                  new ClassReader( getClassData( MethodCompareB.class ) ),
                                  "evaluate",
                                  new ClassReader( getClassData( MethodCompareA.class ) ) );
        assertEquals( true,
                      result );

        result = comp.equivalent( "evaluate",
                                  new ClassReader( getClassData( MethodCompareA.class ) ),
                                  "evaluate",
                                  new ClassReader( getClassData( MethodCompareA.class ) ) );
        assertEquals( true,
                      result );

        result = comp.equivalent( "evaluate",
                                  new ClassReader( getClassData( MethodCompareA.class ) ),
                                  "askew",
                                  new ClassReader( getClassData( MethodCompareA.class ) ) );
        assertEquals( false,
                      result );

    }

    private InputStream getClassData(final Class clazz) {
        final String name = getResourcePath( clazz );
        return clazz.getResourceAsStream( name );
    }

    private String getResourcePath(final Class clazz) {
        return "/" + clazz.getName().replaceAll( "\\.",
                                                 "/" ) + ".class";
    }

}


text:
#import <Foundation/NSArray.h>

@interface NSArray_concrete : NSArray {
    NSUInteger _count;
    id _objects[0];
}
@end

NSArray *NSArray_concreteNew(NSZone *zone, id *objects, NSUInteger count);
NSArray *NSArray_concreteNewWithCount(NSZone *zone, id **objects, NSUInteger count);
NSArray *NSArray_concreteWithArrayAndObject(NSArray *array, id object);
NSArray *NSArray_concreteWithArrayAndArray(NSArray *array1, NSArray *array2);
NSArray *NSArray_concreteWithArrayRange(NSArray *array1, NSRange range);


text:
namespace DfBAdminToolkit.View
{
    using DfBAdminToolkit.Model;
    using System;
    using System.Collections.Generic;

    public interface IGroupsView
        : IView
    {
        event EventHandler CommandGetGroups;
        event EventHandler CommandCreateGroup;
        event EventHandler CommandExportGroups;
        event EventHandler CommandExportGroupPerms;
        event EventHandler CommandAddMember;
        event EventHandler CommandDeleteMember;
        event EventHandler CommandLoadGroupsInputFile;
        event EventHandler CommandLoadGroupsMembersInputFile;

        string AccessToken { get; set; }

        void RefreshAccessToken();

        string GroupName { get; set; }

        string GroupType { get; set; }

        string UserEmail { get; set; }

        string AddStatus { get; set; }

        string GroupInputFilePath { get; set; }

        string GroupMemberInputFilePath { get; set; }

        void RenderGroupList(List<GroupListViewItemModel> groups);

        void RenderGroupsStatus(List<GroupListViewItemModel> groups);

        bool MultiGroupCreateCheck();

        bool MultiGroupMemberCreateCheck();
    }
}


text:
package core.aws.task.ec2;

import com.amazonaws.services.ec2.model.KeyPairInfo;
import core.aws.client.AWS;
import core.aws.env.Environment;
import core.aws.resource.ec2.KeyPair;
import core.aws.util.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Locale;

/**
 * @author neo
 */
public class KeyPairHelper {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final Environment env;

    public KeyPairHelper(Environment env) {
        this.env = env;
    }

    public void createKeyPair(KeyPair keyPair) throws IOException {
        com.amazonaws.services.ec2.model.KeyPair remoteKeyPair = AWS.getEc2().createKeyPair(keyPair.name);
        writeKeyFile(keyPair.name, remoteKeyPair.getKeyMaterial());
        keyPair.remoteKeyPair = new KeyPairInfo()
            .withKeyName(remoteKeyPair.getKeyName())
            .withKeyFingerprint(remoteKeyPair.getKeyFingerprint());
    }

    private void writeKeyFile(String keyName, String content) throws IOException {
        Path keyFile = KeyPair.keyFile(keyName, env);
        Files.createDirectories(keyFile.getParent());

        logger.info("write key, keyName={}, path={}", keyName, keyFile);
        Files.write(keyFile, content.getBytes(Charsets.UTF_8));

        String osName = System.getProperty("os.name").toLowerCase(Locale.getDefault());
        if (osName.contains("linux") || osName.contains("mac")) {
            HashSet<PosixFilePermission> permissions = new HashSet<>();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            Files.setPosixFilePermissions(keyFile, permissions);
        }
    }

    public void deleteKeyPair(String keyName) throws IOException {
        AWS.getEc2().deleteKeyPair(keyName);

        Path keyFile = KeyPair.keyFile(keyName, env);
        if (Files.exists(keyFile)) {
            logger.info("delete key, path={}", keyFile);
            Files.delete(keyFile);
        }
    }
}


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR"

if [ ! -f ./config/run.config ]
then
	echo Missing run configuration.
	echo Copy "config/run.config.example" to "config/run.config" and edit it to apply your settings.
	exit
fi

source ./config/run.config

# Start Paint.js
echo "Starting..."
"$RUN_NW_BINARY" ../src


text:
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render });

function preload() {

    game.load.image('atari1', 'assets/sprites/atari130xe.png');
    game.load.image('atari2', 'assets/sprites/atari800xl.png');

}

var atari1;
var atari2;

function create() {

    //  Items are rendered in the depth order in which they are added to the Group
    atari1 = game.add.sprite(100, 100, 'atari1');
    atari2 = game.add.sprite(250, 90, 'atari2');

    game.input.onTap.add(swapSprites, this);

}

function swapSprites() {

    //The 2 Sprites are in the global world Group (World class extends the Group class), but this will work for any Group:
    game.world.swap(atari1, atari2);

}

function render () {

    game.debug.renderText('Tap screen to swap the children and therefore swap their indexes.', 10, 280);

}


text:
<!DOCTYPE html>

  <title>WebRTC Demo</title>

WebRTC DataChannel Demo using WebSockets

  <input type="checkbox" id="enable_trace">TRACE


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>Nivo Slider Demo</title>
    <link rel="stylesheet" href="../themes/default/default.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../themes/pascal/pascal.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../themes/orman/orman.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../nivo-slider.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="style.css" type="text/css" media="screen" />

        dev7studios

                This is an example of a HTML caption with a link.


text:
using Microsoft.Extensions.Configuration;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;

namespace Umbraco.Extensions;

///
/// Extensions for <see cref="IConfiguration" />.
///
public static class ConfigurationExtensions
{
    ///
    /// The DataDirectory name.
    ///
    internal const string DataDirectoryName = "DataDirectory";

    ///
    /// The DataDirectory placeholder.
    ///
    internal const string DataDirectoryPlaceholder = "|DataDirectory|";

    ///
    /// The postfix used to identify a connection string provider setting.
    ///
    internal const string ProviderNamePostfix = "_ProviderName";

    ///
    /// Gets the provider name for the connection string name (shorthand for <c>GetSection("ConnectionStrings")[name + "_ProviderName"]</c>).
    ///
    /// <param name="configuration">The configuration.</param>
    /// <param name="name">The connection string key.</param>
    /// <returns>
    /// The provider name.
    /// </returns>
    /// <remarks>
    /// This uses the same convention as the Configuration API for connection string environment variables.
    /// </remarks>
    public static string? GetConnectionStringProviderName(this IConfiguration configuration, string name)
        => configuration.GetConnectionString(name + ProviderNamePostfix);

    ///
    /// Gets the Umbraco connection string (shorthand for <c>GetSection("ConnectionStrings")[name]</c> and replacing the <c>|DataDirectory|</c> placeholder).
    ///
    /// <param name="configuration">The configuration.</param>
    /// <param name="name">The connection string key.</param>
    /// <returns>
    /// The Umbraco connection string.
    /// </returns>
    public static string? GetUmbracoConnectionString(this IConfiguration configuration, string name = Constants.System.UmbracoConnectionName)
        => configuration.GetUmbracoConnectionString(name, out _);

    ///
    /// Gets the Umbraco connection string and provider name (shorthand for <c>GetSection("ConnectionStrings")[Constants.System.UmbracoConnectionName]</c> and replacing the <c>|DataDirectory|</c> placeholder).
    ///
    /// <param name="configuration">The configuration.</param>
    /// <param name="providerName">The provider name.</param>
    /// <returns>
    /// The Umbraco connection string.
    /// </returns>
    public static string? GetUmbracoConnectionString(this IConfiguration configuration, out string? providerName)
        => configuration.GetUmbracoConnectionString(Constants.System.UmbracoConnectionName, out providerName);

    ///
    /// Gets the Umbraco connection string and provider name (shorthand for <c>GetSection("ConnectionStrings")[name]</c> and replacing the <c>|DataDirectory|</c> placeholder).
    ///
    /// <param name="configuration">The configuration.</param>
    /// <param name="name">The name.</param>
    /// <param name="providerName">The provider name.</param>
    /// <returns>
    /// The Umbraco connection string.
    /// </returns>
    public static string? GetUmbracoConnectionString(this IConfiguration configuration, string name, out string? providerName)
    {
        string? connectionString = configuration.GetConnectionString(name);
        if (!string.IsNullOrEmpty(connectionString))
        {
            // Replace data directory
            string? dataDirectory = AppDomain.CurrentDomain.GetData(DataDirectoryName)?.ToString();
            if (!string.IsNullOrEmpty(dataDirectory))
            {
                connectionString = connectionString.Replace(DataDirectoryPlaceholder, dataDirectory);
            }

            // Get provider name
            providerName = configuration.GetConnectionStringProviderName(name);
        }
        else
        {
            providerName = null;
        }

        return connectionString;
    }

    ///
    /// Gets the Umbraco runtime mode.
    ///
    /// <param name="configuration">The configuration.</param>
    /// <returns>
    /// The Umbraco runtime mode.
    /// </returns>
    public static RuntimeMode GetRuntimeMode(this IConfiguration configuration)
        => configuration.GetValue<RuntimeMode>(Constants.Configuration.ConfigRuntimeMode);

    public static ModelsMode GetModelsMode(this IConfiguration configuration) => (configuration.GetSection(Constants.Configuration.ConfigModelsBuilder).Get<ModelsBuilderSettings>() ?? new ModelsBuilderSettings()).ModelsMode;
}


text:
describe('PluginHooks', function () {
  var id = 'testContainer';

  beforeEach(function () {
    this.$container = $('

').appendTo('body');
  });

  afterEach(function () {
    if (this.$container) {
      destroy();
      this.$container.remove();
    }
  });

  it('should add a global hook', function () {
    var errors = 0;

    try {
      Handsontable.PluginHooks.add('afterInit', function () {
      });
    } catch (e) {
      errors++;
    }

    expect(errors).toEqual(0);
  });

  it('should add a local hook', function () {
    var errors = 0;
    handsontable();

    try {
      getInstance().PluginHooks.add('afterInit', function () {
      });
    } catch (e) {
      errors++;
    }

    expect(errors).toEqual(0);
  });

  it('should add a local hook at init', function () {
    var afterInitHandler = jasmine.createSpy('afterInitHandler');

    handsontable({
      afterInit: afterInitHandler
    });

    expect(afterInitHandler).toHaveBeenCalled();
    expect(afterInitHandler.calls.length).toEqual(1);
  });

  it('should add a many local hooks at init (as array)', function () {
    var handler1 = jasmine.createSpy('handler1');
    var handler2 = jasmine.createSpy('handler2');
    var handler3 = jasmine.createSpy('handler3');

    handsontable({
      afterInit: [handler1, handler2, handler3]
    });

    expect(handler1).toHaveBeenCalled();
    expect(handler2).toHaveBeenCalled();
    expect(handler3).toHaveBeenCalled();
  });

  it('should remove a global hook', function () {
    var test = 0
      , hook = function () {
        test = 5;
      };

    Handsontable.PluginHooks.add('afterInit', hook);
    Handsontable.PluginHooks.remove('afterInit', hook);

    handsontable();

    expect(test).toEqual(0);
  });

  it('should remove a local hook', function () {
    var test = 0
      , hook = function () {
        test = 5;
      };

    handsontable();

    getInstance().PluginHooks.add('afterInit', hook);
    getInstance().PluginHooks.remove('afterInit', hook);

    expect(test).toEqual(0);
  });

  it('should run global hook', function () {
    var test = 0;
    Handsontable.PluginHooks.add('afterInit', function () {
      test = 5;
    });
    handsontable();
    expect(test).toEqual(5);
  });

  it('should run local hook', function () {
    var test = 0;

    handsontable();

    getInstance().PluginHooks.add('myHook', function () {
      test += 5;
    });
    getInstance().PluginHooks.run('myHook');
    getInstance().PluginHooks.run('myHook');

    expect(test).toEqual(10);
  });

  it('should run local hook once', function () {
    var test = 0;

    handsontable();

    getInstance().PluginHooks.once('myHook', function () {
      test += 5;
    });
    getInstance().PluginHooks.run('myHook');
    getInstance().PluginHooks.run('myHook');

    expect(test).toEqual(5);
  });

  it('should run all hooks', function () {
    var test = 0;

    Handsontable.PluginHooks.add('afterInit', function () {
      test += 5;
    });

    handsontable({
      afterInit: function () {
        test += 5;
      }
    });

    expect(test).toEqual(10);

  });

  it('should run all hooks', function () {
    var test = 0;

    Handsontable.PluginHooks.add('afterInit', function () {
      test += 5;
    });

    handsontable({
      afterInit: function () {
        test += 5;
      }
    });

    expect(test).toEqual(10);

  });

  it('list of all avaliable plugin hooks should be exposed as a public object', function () {
    var pluginHooks = Handsontable.PluginHooks.hooks; //this is used in demo/callbacks.html

    expect(pluginHooks.beforeInit).toBeDefined(); //duck check is fine

  });

  it('should add a local hook with addHooks method', function(){
    var hot1 = handsontable();

    var test = 0;

    hot1.addHook('myHook', function(){
      test += 5;
    });

    hot1.runHooks('myHook');

    expect(test).toEqual(5);
  });

  it('should remove a local hook with removeHook method', function(){
    var hot1 = handsontable();

    var test = 0;
    var handler = function(){
      test += 5;
    };

    hot1.addHook('myHook', handler);

    hot1.runHooks('myHook');
    hot1.runHooks('myHook');
    expect(test).toEqual(10);

    hot1.removeHook('myHook', handler);
    hot1.runHooks('myHook');

    expect(test).toEqual(10);
  });

  it('should add a local hook with addHookOnce method and run it just once', function(){
    var hot1 = handsontable();

    var test = 0;
    var handler = function(){
      test += 5;
    };

    hot1.addHookOnce('myHook', handler);

    hot1.runHooks('myHook');
    hot1.runHooks('myHook');
    expect(test).toEqual(5);

  });

  it('should run hook with runHooksAndReturn and return value', function(){
    var hot = handsontable();

    var handler = function(){
      return 5;
    };

    hot.addHook('myHook', handler);

    expect(hot.runHooksAndReturn('myHook')).toEqual(5);

  });

  it('should run two "once" hooks in desired order', function(){
    var hot = handsontable();
    var arr = [];

    hot.addHookOnce('myHook', function(){
      arr.push(1);
    });

    hot.addHookOnce('myHook', function(){
      arr.push(2);
    });

    hot.runHooks('myHook');

    expect(arr).toEqual([1,2]);
  });

  it('should execute two "once" hooks in desired order', function(){
    var hot = handsontable();
    var str = 'a';

    hot.addHookOnce('myHook', function(str){
      return str + 'b';
    });

    hot.addHookOnce('myHook', function(str){
      return str + 'c';
    });

    expect(hot.runHooksAndReturn('myHook', str)).toEqual('abc');
  });

  it('adding same hook twice should register it only once (without an error)', function () {
    var i = 0;
    var fn = function(){
      i++;
    };

    var hot = handsontable({
      afterOnCellMouseOver: fn
    });

    hot.getInstance().updateSettings({afterOnCellMouseOver: fn});

    hot.runHooks('afterOnCellMouseOver');

    expect(i).toEqual(1);
  });

  describe("controlling handler queue execution", function () {
    it("should execute all handlers if none of them returned false", function () {

      var handler1 = jasmine.createSpy('handler1');
      var handler2 = jasmine.createSpy('handler2');
      var handler3 = jasmine.createSpy('handler3');

      var hot = handsontable();

      hot.addHook('fakeEvent', handler1);
      hot.addHook('fakeEvent', handler2);
      hot.addHook('fakeEvent', handler3);

      expect(handler1).not.toHaveBeenCalled();
      expect(handler2).not.toHaveBeenCalled();
      expect(handler3).not.toHaveBeenCalled();

      var eventCancelled = hot.runHooksAndReturn('fakeEvent');

      expect(handler1).toHaveBeenCalled();
      expect(handler2).toHaveBeenCalled();
      expect(handler3).toHaveBeenCalled();

      expect(eventCancelled).not.toBe(true);

    });

    it("should stop executing handlers if one of them returned false", function () {

      var handler1 = jasmine.createSpy('handler1');
      var handler2 = jasmine.createSpy('handler2');

      handler2.plan = function () {
        return false;
      };

      var handler3 = jasmine.createSpy('handler3');

      var hot = handsontable();

      hot.addHook('fakeEvent', handler1);
      hot.addHook('fakeEvent', handler2);
      hot.addHook('fakeEvent', handler3);

      expect(handler1).not.toHaveBeenCalled();
      expect(handler2).not.toHaveBeenCalled();
      expect(handler3).not.toHaveBeenCalled();

      var result = hot.runHooksAndReturn('fakeEvent');

      expect(handler1).toHaveBeenCalled();
      expect(handler2).toHaveBeenCalled();
      expect(handler3).not.toHaveBeenCalled();

      expect(result).toBe(false);

    });

    it("should invoke 'once' handler in the next event run, if the previous run has been interrupted", function () {

      var handler1 = jasmine.createSpy('handler1');
      handler1.plan = function () {
        return false;
      };

      var handler2 = jasmine.createSpy('handler2');
      var handler3 = jasmine.createSpy('handler3');

      var hot = handsontable();

      hot.addHookOnce('fakeEvent', handler1);
      hot.addHookOnce('fakeEvent', handler2);
      hot.addHook('fakeEvent', handler3);

      expect(handler1).not.toHaveBeenCalled();
      expect(handler2).not.toHaveBeenCalled();
      expect(handler3).not.toHaveBeenCalled();

      var result = hot.runHooksAndReturn('fakeEvent');

      expect(handler1).toHaveBeenCalled();
      expect(handler2).not.toHaveBeenCalled();
      expect(handler3).not.toHaveBeenCalled();

      expect(result).toBe(false);

      handler1.reset();
      handler2.reset();
      handler3.reset();

      result = hot.runHooksAndReturn('fakeEvent');

      expect(handler1).not.toHaveBeenCalled();
      expect(handler2).toHaveBeenCalled();
      expect(handler3).toHaveBeenCalled();

      expect(result).not.toBe(false);

      handler1.reset();
      handler2.reset();
      handler3.reset();

      result = hot.runHooksAndReturn('fakeEvent');

      expect(handler1).not.toHaveBeenCalled();
      expect(handler2).not.toHaveBeenCalled();
      expect(handler3).toHaveBeenCalled();

      expect(result).not.toBe(false);

    });
  });
});


text:
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;

import javax.swing.*;

/**
 * Created by alvaro on 21/07/2016.
 */
public class ExampleCopyResourcesFolderForm extends JFrame {

    private JPanel rootPanel;
    private Project project;

    public ExampleCopyResourcesFolderForm(Project project) {
        super("ExampleCopyResourcesFolderForm");

        this.project = project;

        String configPath = PathManager.getConfigPath();

        VirtualFile file = LocalFileSystem.getInstance().findFileByPath(configPath);

        VirtualFile templatesFolder = null; // folder with templates in android (dest)

        for (VirtualFile children : file.getChildren()) {
            if (children.getName().equals("fileTemplates")) {
                templatesFolder = children;
                break;
            }
        }

        if (templatesFolder != null) { // Copy templates files in template folder

        }

    }
}


text:
package com.meiste.greg.ptw;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public final class RaceItemAdapter extends ArrayAdapter<Race> {
    private Race[] mRaces;
    private final Context mContext;

    private class ViewHolder {
        public LinearLayout row;
        public TextView raceNum;
        public TextView startDate;
        public TextView startTime;
        public TextView name;
        public TextView trackLong;
        public TextView trackShort;
        public TextView tv;
    }

    public RaceItemAdapter(final Context context, final int textViewResourceId) {
        super(context, textViewResourceId);
        mContext = context;
        mRaces = Races.get(context);
    }

    @Override
    public int getCount() {
        return mRaces.length;
    }

    @Override
    public void notifyDataSetChanged() {
        mRaces = Races.get(mContext);
        super.notifyDataSetChanged();
    }

    @Override
    public View getView(final int pos, final View convertView, final ViewGroup parent) {
        final ViewHolder holder;
        View v = convertView;

        if (v == null) {
            final LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.schedule_row, parent, false);

            holder = new ViewHolder();
            holder.row = (LinearLayout) v.findViewById(R.id.row);
            holder.raceNum = (TextView) v.findViewById(R.id.race_num);
            holder.startDate = (TextView) v.findViewById(R.id.race_date);
            holder.startTime = (TextView) v.findViewById(R.id.race_time);
            holder.name = (TextView) v.findViewById(R.id.race_name);
            holder.trackLong = (TextView) v.findViewById(R.id.race_track);
            holder.trackShort = (TextView) v.findViewById(R.id.race_track_short);
            holder.tv = (TextView) v.findViewById(R.id.race_tv);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        if (!mRaces[pos].isFuture() && !mRaces[pos].isRecent())
            holder.row.setBackgroundResource(R.drawable.schedule_past);
        else if (mRaces[pos].isInChase())
            holder.row.setBackgroundResource(R.drawable.schedule_chase);
        else
            holder.row.setBackgroundResource(R.drawable.schedule_future);

        if (holder.raceNum != null)
            holder.raceNum.setText(mRaces[pos].getRaceNum());

        if (holder.startDate != null)
            holder.startDate.setText(mRaces[pos].getStartDate(mContext));

        if (holder.startTime != null)
            holder.startTime.setText(mRaces[pos].getStartTime(mContext));

        if (holder.name != null)
            holder.name.setText(mRaces[pos].getName());

        if (holder.trackLong != null)
            holder.trackLong.setText(mRaces[pos].getTrack(Race.NAME_LONG));

        if (holder.trackShort != null)
            holder.trackShort.setText(mRaces[pos].getTrack(Race.NAME_SHORT));

        if (holder.tv != null)
            holder.tv.setText(mRaces[pos].getTv());

        return v;
    }
}


text:
angular.module('app.users').controller('users.controller', ['$scope', 'requestedUser', '$state', function ($scope, requestedUser, $state) {
    $scope.$emit('set-page-title', { title: requestedUser.firstName + requestedUser.lastName });
    $scope.user = requestedUser;
    $scope.editUser = function (id) {
        var targetState = $state.current.name + '.edit';
        if ($state.current.name.indexOf('.') !== -1) {
            targetState = $state.current.name.split('.')[0] + '.edit';
        }
        $state.go(targetState, { id: id });
    };
}]);


text:
<!DOCTYPE html>

    <title>Table View with Navbar - PatternFly</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="../../dist/img/favicon.ico">

    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../../dist/img/apple-touch-icon-precomposed-152.png">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../dist/img/apple-touch-icon-precomposed-144.png">

    <link rel="apple-touch-icon-precomposed" sizes="76x76" href="../../dist/img/apple-touch-icon-precomposed-76.png">

    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../dist/img/apple-touch-icon-precomposed-72.png">

    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="../../dist/img/apple-touch-icon-precomposed-180.png">

    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../dist/img/apple-touch-icon-precomposed-114.png">

    <link rel="apple-touch-icon-precomposed" sizes="57x57" href="../../dist/img/apple-touch-icon-precomposed-57.png">
    <link rel="stylesheet" href="../../dist/css/patternfly.min.css" >
    <link rel="stylesheet" href="../../dist/css/patternfly-additions.min.css" >
      <link href="tests.css" rel="stylesheet" media="screen, print">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse-1">
          Toggle navigation

        </button>

            Status

              Brian Johnson

                Link

                Another link

                Something else here

                More options

                    Link

                    Another link

                    Something else here

Nav header

                    Separated link

                    One more separated link

                One more separated link

            Basic

            Tree View

            Dashboard

            Form

            Tab

            Typography

            Card View - Multi Select

            Card View - Single Select

            Cards

      <form class="toolbar-pf-actions">

          Rendering Engine

              <button type="button" class="btn btn-default dropdown-toggle" id="filter" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Rendering Engine </button>

Rendering Engine

Browser

Platform(s)

Engine Version

CSS Grade

            <input type="text" class="form-control" placeholder="Filter By Rendering Engine..." autocomplete="off">

            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Rendering Engine </button>

Rendering Engine

Browser

Platform(s)

Engine Version

CSS Grade

          <button class="btn btn-link" type="button">

          </button>

          <button class="btn btn-default" type="button" id="deleteRows1">Delete Rows</button>
          <button class="btn btn-default" type="button" id="restoreRows1" disabled>Restore Rows</button>

  <button class="btn btn-link dropdown-toggle" type="button" id="dropdownKebab" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

  </button>

Action

Another action

Something else here

Separated link

            <button class="btn btn-link btn-find" type="button">

            </button>

              <input type="text" class="form-control" id="find" placeholder="Find By Keyword...">

                1 of 3
                <button class="btn btn-link" type="button">

                </button>
                <button class="btn btn-link" type="button">

                </button>
                <button class="btn btn-link btn-find-close" type="button">

                </button>

            <button class="btn btn-link active"></button>
            <button class="btn btn-link"></button>
            <button class="btn btn-link"></button>

      </form>

0 Results

Active filters:

Clear All Filters

          0 of 0 selected

      Select all rows<input type="checkbox" id="selectAll" name="selectAll">
      Rendering Engine
      Browser
      Platform(s)
      Engine Version
      CSS Grade
      Actions

<form class="content-view-pf-pagination table-view-pf-pagination clearfix" id="pagination1">

    <select class="selectpicker pagination-pf-pagesize">
      <option value="6">6</option>
      <option value="10">10</option>
      <option value="15" selected="selected">15</option>
      <option value="25">25</option>
      <option value="50">50</option>
    </select>
    per page

    1-15 of 75

    Current Page
    <input class="pagination-pf-page" type="text" value="1" id="pagination1-page"/>
    of 5

</form>

    Empty State Title

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Learn more about this on the documentation.

    <button class="btn btn-primary btn-lg"> Main Action </button>

    <button class="btn btn-default"> Secondary Action </button> <button class="btn btn-default"> Secondary Action </button> <button class="btn btn-default"> Secondary Action </button>


text:
module Corpus
  def self.table_name_prefix
    'corpus_'
  end
end


text:
"use strict";

import React from "react";
import ReactDOM from "react-dom";
import Docs from "./docs";

React.initializeTouchEvents && React.initializeTouchEvents(true);
ReactDOM.render(
  <React.StrictMode>
    <Docs />
  </React.StrictMode>,
  document.getElementById("rapp")
);


text:
package com.evolveum.midpoint.provisioning.ucf.api;

/**
 *
 */
public interface UcfExpressionEvaluatorAware {

    @SuppressWarnings("unused")
    UcfExpressionEvaluator getUcfExpressionEvaluator();

    void setUcfExpressionEvaluator(UcfExpressionEvaluator evaluator);
}


text:
module Rds
  module Authorization

    def self.included(base)

      if defined?(ActionController::Base)
        base < ActionController::Base
      end

      if defined?(ActionController::API)
        base < ActionController::API
      end

      base.helper_method :current_user, :can?
    end

    protected

    # if can't find current user for the current request, try to find authenticate by token
    def current_user
      if @current_user.present?
        @current_user
      else
        authentication_token = params[:authentication_token].presence
        @current_user = authentication_token && User.find_by_authentication_token(authentication_token)
      end
    end

    def can?(permission)
      current_user.present? && current_user.role_can?(permission)
    end
  end
end


text:
package com.dreamcc.gs.bean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeNode {

	private String id;

	private Integer dataId;

	private String text;

	private String url;

	private String state;//value closed,open

	private boolean checked; //

	private Integer parentId;

	private Map<String,Object> attributes = new HashMap<String, Object>();

	private List<TreeNode>  children;

	public String getId() {
		return id;
	}

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

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public  Integer getParentId() {
		return parentId;
	}

	public void setParentId( Integer parentId) {
		this.parentId = parentId;
	}

	public Integer getDataId() {
		return dataId;
	}

	public void setDataId(Integer dataId) {
		this.dataId = dataId;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public List<TreeNode> getChildren() {
		return children;
	}

	public void setChildren(List<TreeNode> children) {
		this.children = children;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

}


text:
namespace sfge
{

    class Way
    {
        typedef std::deque<Vector2f> WayPoints;
        typedef WayPoints::iterator WayIterator;

    public:
        Way (const WayPoints& points);

        Way (WayPoints&& points);

        void clear ();

        void pushPointFront (Vector2f);
        void pushPointBack (Vector2f);

        Vector2f getMovingVector (Vector2f position, float step);

        float getLength () const;

        size_t getPoints () const;

    protected:
        WayPoints m_points;
        WayIterator m_current_point;
    };

}


text:
require 'spec_helper'

require 'puppet/server/execution'

describe Puppet::Server::Execution do
  context "execution stub" do
    it "should return an instance of ProcessOutput" do
      result = Puppet::Server::Execution.execute("echo hi")
      expect(result).to be_a Puppet::Util::Execution::ProcessOutput
    end

    it "should return the STDOUT of the process" do
      result = Puppet::Server::Execution.execute("echo hi")
      expect(result).to eq "hi\n"
    end

    it "should return the exit code of the process" do
      result = Puppet::Server::Execution.execute("echo hi")
      expect(result.exitstatus).to eq 0

      result = Puppet::Server::Execution.execute("false")
      expect(result.exitstatus).not_to eq 0
    end
  end
end


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.test.internal.metadata.raw;

import java.util.Date;

import org.testng.annotations.Test;

import org.hibernate.validator.internal.metadata.raw.ExecutableElement;

import static org.testng.Assert.assertEquals;

/**
 * Unit test for {@link ExecutableElement}.
 *
 * @author Gunnar Morling
 */
public class ExecutableElementTest {

	@Test
	public void executableAsStringShouldReturnMethodNameWithBracesForParameterlessMethod() throws Exception {
		assertEquals( ExecutableElement.getExecutableAsString( "foo" ), "foo()" );
		assertEquals( ExecutableElement.forMethod( Bar.class.getMethod( "zap" ) ).getAsString(), "zap()" );
		assertEquals( ExecutableElement.forConstructor( Bar.class.getConstructor() ).getAsString(), "Bar()" );
	}

	@Test
	public void executableAsStringShouldReturnMethodNameWithSimpleParamerTypeNames() throws Exception {
		assertEquals( ExecutableElement.getExecutableAsString( "foo", int.class, Bar.class ), "foo(int, Bar)" );
		assertEquals(
				ExecutableElement.forMethod( Bar.class.getMethod( "zap", int.class, Date.class ) ).getAsString(),
				"zap(int, Date)"
		);
		assertEquals(
				ExecutableElement.forConstructor( Bar.class.getConstructor( int.class, Date.class ) )
						.getAsString(), "Bar(int, Date)"
		);
	}

	public static class Bar {

		public Bar() {
		}

		public Bar(int i, Date date) {
		}

		public void Foo() {
		}

		public void zip() {
		}

		public void zap(int i) {
		}

		public void zap() {
		}

		public void zap(int i, Date date) {
		}
	}
}


text:
package com.tvd12.ezyfox.binding.testing.scan.pack1;

import com.tvd12.ezyfox.binding.EzyReader;
import com.tvd12.ezyfox.binding.EzyUnmarshaller;
import com.tvd12.ezyfox.binding.annotation.EzyObjectBinding;
import com.tvd12.ezyfox.binding.annotation.EzyReaderImpl;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@EzyObjectBinding
public class ClassB {

    @com.tvd12.ezyfox.binding.annotation.EzyReader(TypeReader.class)
    private Type type = Type.HELLO;

    public enum Type {
        HELLO
    }

    @EzyReaderImpl
    public static class TypeReader implements EzyReader<Object, Type> {
        @Override
        public Type read(EzyUnmarshaller unmarshaller, Object value) {
            return Type.valueOf(value.toString());
        }
    }
}


text:
<?php

namespace MvConsultancy\Entity\Repository;

/**
 * ProjectRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProjectRepository
  extends \MvBase\Doctrine\ORM\AbstractEntityRepository
{
}


text:
package org.zalando.riptide.chaos;

import lombok.AllArgsConstructor;
import org.apiguardian.api.API;
import org.zalando.riptide.Plugin;
import org.zalando.riptide.RequestExecution;

import static org.apiguardian.api.API.Status.EXPERIMENTAL;

@API(status = EXPERIMENTAL)
@AllArgsConstructor
public final class ChaosPlugin implements Plugin {

    private final FailureInjection injection;

    @Override
    public RequestExecution aroundNetwork(final RequestExecution execution) {
        return injection.inject(execution);
    }

}


text:
using namespace DirectX;

#ifndef _CPPRTTI
#error Model requires RTTI
#endif

//--------------------------------------------------------------------------------------
// ModelMeshPart
//--------------------------------------------------------------------------------------

ModelMeshPart::ModelMeshPart(uint32_t ipartIndex) noexcept :
    partIndex(ipartIndex),
    materialIndex(0),
    indexCount(0),
    startIndex(0),
    vertexOffset(0),
    vertexStride(0),
    vertexCount(0),
    indexBufferSize(0),
    vertexBufferSize(0),
    primitiveType(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST),
    indexFormat(DXGI_FORMAT_R16_UINT)
{
}

ModelMeshPart::~ModelMeshPart()
{
}

_Use_decl_annotations_
void ModelMeshPart::Draw(_In_ ID3D12GraphicsCommandList* commandList) const
{
    if (!indexBufferSize || !vertexBufferSize)
    {
        DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", indexBufferSize, vertexBufferSize);
        throw std::exception("ModelMeshPart");
    }

    if (!staticIndexBuffer && !indexBuffer)
    {
        DebugTrace("ERROR: Model part missing index buffer!\n");
        throw std::exception("ModelMeshPart");
    }

    if (!staticVertexBuffer && !vertexBuffer)
    {
        DebugTrace("ERROR: Model part missing vertex buffer!\n");
        throw std::exception("ModelMeshPart");
    }

    D3D12_VERTEX_BUFFER_VIEW vbv;
    vbv.BufferLocation = staticVertexBuffer ? staticVertexBuffer->GetGPUVirtualAddress() : vertexBuffer.GpuAddress();
    vbv.StrideInBytes = vertexStride;
    vbv.SizeInBytes = vertexBufferSize;
    commandList->IASetVertexBuffers(0, 1, &vbv);

    D3D12_INDEX_BUFFER_VIEW ibv;
    ibv.BufferLocation = staticIndexBuffer ? staticIndexBuffer->GetGPUVirtualAddress() : indexBuffer.GpuAddress();
    ibv.SizeInBytes = indexBufferSize;
    ibv.Format = indexFormat;
    commandList->IASetIndexBuffer(&ibv);

    commandList->IASetPrimitiveTopology(primitiveType);

    commandList->DrawIndexedInstanced(indexCount, 1, startIndex, vertexOffset, 0);
}

_Use_decl_annotations_
void ModelMeshPart::DrawInstanced(_In_ ID3D12GraphicsCommandList* commandList, uint32_t instanceCount, uint32_t startInstanceLocation) const
{
    if (!indexBufferSize || !vertexBufferSize)
    {
        DebugTrace("ERROR: Model part missing values for vertex and/or index buffer size (indexBufferSize %u, vertexBufferSize %u)!\n", indexBufferSize, vertexBufferSize);
        throw std::exception("ModelMeshPart");
    }

    if (!staticIndexBuffer && !indexBuffer)
    {
        DebugTrace("ERROR: Model part missing index buffer!\n");
        throw std::exception("ModelMeshPart");
    }

    if (!staticVertexBuffer && !vertexBuffer)
    {
        DebugTrace("ERROR: Model part missing vertex buffer!\n");
        throw std::exception("ModelMeshPart");
    }

    D3D12_VERTEX_BUFFER_VIEW vbv;
    vbv.BufferLocation = staticVertexBuffer ? staticVertexBuffer->GetGPUVirtualAddress() : vertexBuffer.GpuAddress();
    vbv.StrideInBytes = vertexStride;
    vbv.SizeInBytes = vertexBufferSize;
    commandList->IASetVertexBuffers(0, 1, &vbv);

    D3D12_INDEX_BUFFER_VIEW ibv;
    ibv.BufferLocation = staticIndexBuffer ? staticIndexBuffer->GetGPUVirtualAddress() : indexBuffer.GpuAddress();
    ibv.SizeInBytes = indexBufferSize;
    ibv.Format = indexFormat;
    commandList->IASetIndexBuffer(&ibv);

    commandList->IASetPrimitiveTopology(primitiveType);

    commandList->DrawIndexedInstanced(indexCount, instanceCount, startIndex, vertexOffset, startInstanceLocation);
}

_Use_decl_annotations_
void ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList, const ModelMeshPart::Collection& meshParts)
{
    for (auto it = meshParts.cbegin(); it != meshParts.cend(); ++it)
    {
        auto part = (*it).get();
        assert(part != nullptr);

        part->Draw(commandList);
    }
}

_Use_decl_annotations_
void ModelMeshPart::DrawMeshParts(
    ID3D12GraphicsCommandList* commandList,
    const ModelMeshPart::Collection& meshParts,
    ModelMeshPart::DrawCallback callback)
{
    for (auto it = meshParts.cbegin(); it != meshParts.cend(); ++it)
    {
        auto part = (*it).get();
        assert(part != nullptr);

        callback(commandList, *part);
        part->Draw(commandList);
    }
}

_Use_decl_annotations_
void ModelMeshPart::DrawMeshParts(ID3D12GraphicsCommandList* commandList,
    const ModelMeshPart::Collection& meshParts,
    IEffect* effect)
{
    effect->Apply(commandList);
    DrawMeshParts(commandList, meshParts);
}

//--------------------------------------------------------------------------------------
// ModelMesh
//--------------------------------------------------------------------------------------

ModelMesh::ModelMesh() noexcept
{
}

ModelMesh::~ModelMesh()
{
}

// Draw the mesh
void __cdecl ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList) const
{
    ModelMeshPart::DrawMeshParts(commandList, opaqueMeshParts);
}

void __cdecl ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList) const
{
    ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts);
}

// Draw the mesh with an effect
void __cdecl ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const
{
    ModelMeshPart::DrawMeshParts(commandList, opaqueMeshParts, effect);
}

void __cdecl ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, _In_ IEffect* effect) const
{
    ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts, effect);
}

// Draw the mesh with a callback for each mesh part
void __cdecl ModelMesh::DrawOpaque(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const
{
    ModelMeshPart::DrawMeshParts(commandList, opaqueMeshParts, callback);
}

void __cdecl ModelMesh::DrawAlpha(_In_ ID3D12GraphicsCommandList* commandList, ModelMeshPart::DrawCallback callback) const
{
    ModelMeshPart::DrawMeshParts(commandList, alphaMeshParts, callback);
}

//--------------------------------------------------------------------------------------
// Model
//--------------------------------------------------------------------------------------
Model::Model() noexcept
{
}

Model::~Model()
{
}

// Load texture resources
int Model::LoadTextures(IEffectTextureFactory& texFactory, int destinationDescriptorOffset) const
{
    for (size_t i = 0; i < textureNames.size(); ++i)
    {
        texFactory.CreateTexture(textureNames[i].c_str(), destinationDescriptorOffset + static_cast<int>(i));
    }

    return static_cast<int>(textureNames.size());
}

// Load texture resources (helper function)
_Use_decl_annotations_
std::unique_ptr<EffectTextureFactory> Model::LoadTextures(
    ID3D12Device* device,
    ResourceUploadBatch& resourceUploadBatch,
    const wchar_t* texturesPath,
    D3D12_DESCRIPTOR_HEAP_FLAGS flags) const
{
    if (textureNames.empty())
        return nullptr;

    std::unique_ptr<EffectTextureFactory> texFactory = std::make_unique<EffectTextureFactory>(
        device,
        resourceUploadBatch,
        textureNames.size(),
        flags);
    if (texturesPath != nullptr && *texturesPath != 0)
    {
        texFactory->SetDirectory(texturesPath);
    }

    LoadTextures(*texFactory);

    return texFactory;
}

// Load VB/IB resources for static geometry
_Use_decl_annotations_
void Model::LoadStaticBuffers(
    ID3D12Device* device,
    ResourceUploadBatch& resourceUploadBatch,
    bool keepMemory)
{
    // Gather all unique parts
    std::set<ModelMeshPart*> uniqueParts;
    for (const auto& mesh : meshes)
    {
        for (const auto& part : mesh->opaqueMeshParts)
        {
            uniqueParts.insert(part.get());
        }
        for (const auto& part : mesh->alphaMeshParts)
        {
            uniqueParts.insert(part.get());
        }
    }

    CD3DX12_HEAP_PROPERTIES heapProperties(D3D12_HEAP_TYPE_DEFAULT);

    for(auto it = uniqueParts.cbegin(); it != uniqueParts.cend(); ++it)
    {
        auto part = *it;

        // Convert dynamic VB to static VB
        if (!part->staticVertexBuffer)
        {
            if (!part->vertexBuffer)
            {
                DebugTrace("ERROR: Model part missing vertex buffer!\n");
                throw std::exception("ModelMeshPart");
            }

            part->vertexBufferSize = static_cast<uint32_t>(part->vertexBuffer.Size());

            auto desc = CD3DX12_RESOURCE_DESC::Buffer(part->vertexBuffer.Size());

            ThrowIfFailed(device->CreateCommittedResource(
                &heapProperties,
                D3D12_HEAP_FLAG_NONE,
                &desc,
                D3D12_RESOURCE_STATE_COPY_DEST,
                nullptr,
                IID_GRAPHICS_PPV_ARGS(part->staticVertexBuffer.GetAddressOf())
            ));

            SetDebugObjectName(part->staticVertexBuffer.Get(), L"ModelMeshPart");

            resourceUploadBatch.Upload(part->staticVertexBuffer.Get(), part->vertexBuffer);

            resourceUploadBatch.Transition(part->staticVertexBuffer.Get(),
                D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);

            // Scan for any other part with the same vertex buffer for sharing
            for (auto sit = std::next(it); sit != uniqueParts.cend(); ++sit)
            {
                auto sharePart = *sit;
                assert(sharePart != part);

                if (sharePart->staticVertexBuffer)
                    continue;

                if (sharePart->vertexBuffer == part->vertexBuffer)
                {
                    sharePart->vertexBufferSize = part->vertexBufferSize;
                    sharePart->staticVertexBuffer = part->staticVertexBuffer;

                    if (!keepMemory)
                    {
                        sharePart->vertexBuffer.Reset();
                    }
                }
            }

            if (!keepMemory)
            {
                part->vertexBuffer.Reset();
            }
        }

        // Convert dynamic IB to static IB
        if (!part->staticIndexBuffer)
        {
            if (!part->indexBuffer)
            {
                DebugTrace("ERROR: Model part missing index buffer!\n");
                throw std::exception("ModelMeshPart");
            }

            part->indexBufferSize = static_cast<uint32_t>(part->indexBuffer.Size());

            auto desc = CD3DX12_RESOURCE_DESC::Buffer(part->indexBuffer.Size());

            ThrowIfFailed(device->CreateCommittedResource(
                &heapProperties,
                D3D12_HEAP_FLAG_NONE,
                &desc,
                D3D12_RESOURCE_STATE_COPY_DEST,
                nullptr,
                IID_GRAPHICS_PPV_ARGS(part->staticIndexBuffer.GetAddressOf())
            ));

            SetDebugObjectName(part->staticIndexBuffer.Get(), L"ModelMeshPart");

            resourceUploadBatch.Upload(part->staticIndexBuffer.Get(), part->indexBuffer);

            resourceUploadBatch.Transition(part->staticIndexBuffer.Get(),
                D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER);

            // Scan for any other part with the same index buffer for sharing
            for (auto sit = std::next(it); sit != uniqueParts.cend(); ++sit)
            {
                auto sharePart = *sit;
                assert(sharePart != part);

                if (sharePart->staticIndexBuffer)
                    continue;

                if (sharePart->indexBuffer == part->indexBuffer)
                {
                    sharePart->indexBufferSize = part->indexBufferSize;
                    sharePart->staticIndexBuffer = part->staticIndexBuffer;

                    if (!keepMemory)
                    {
                        sharePart->indexBuffer.Reset();
                    }
                }
            }

            if (!keepMemory)
            {
                part->indexBuffer.Reset();
            }
        }
    }
}

// Create effects for each mesh piece
std::vector<std::shared_ptr<IEffect>> Model::CreateEffects(
    IEffectFactory& fxFactory,
    const EffectPipelineStateDescription& opaquePipelineState,
    const EffectPipelineStateDescription& alphaPipelineState,
    int textureDescriptorOffset,
    int samplerDescriptorOffset) const
{
    if (materials.empty())
    {
        DebugTrace("ERROR: Model has no material information to create effects!\n");
        throw std::exception("CreateEffects");
    }

    std::vector<std::shared_ptr<IEffect>> effects;

    // Count the number of parts
    uint32_t partCount = 0;
    for (const auto& mesh : meshes)
    {
        for (const auto& part : mesh->opaqueMeshParts)
            partCount = std::max(part->partIndex + 1, partCount);
        for (const auto& part : mesh->alphaMeshParts)
            partCount = std::max(part->partIndex + 1, partCount);
    }

    if (partCount == 0)
        return effects;

    // Create an array of effects for each part. We need to have an effect per part because the part's vertex layout
    // combines with the material spec to create a unique effect. We rely on the EffectFactory to de-duplicate if it
    // wants to.
    effects.resize(partCount);

    for (const auto& mesh : meshes)
    {
        assert(mesh != nullptr);

        for (const auto& part : mesh->opaqueMeshParts)
        {
            assert(part != nullptr);

            if (part->materialIndex == uint32_t(-1))
                continue;

            // If this fires, you have multiple parts with the same unique ID
            assert(effects[part->partIndex] == nullptr);

            effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset, part.get());
        }

        for (const auto& part : mesh->alphaMeshParts)
        {
            assert(part != nullptr);

            if (part->materialIndex == uint32_t(-1))
                continue;

            // If this fires, you have multiple parts with the same unique ID
            assert(effects[part->partIndex] == nullptr);

            effects[part->partIndex] = CreateEffectForMeshPart(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset, part.get());
        }
    }

    return effects;
}

// Creates an effect for a mesh part
_Use_decl_annotations_
std::shared_ptr<IEffect> Model::CreateEffectForMeshPart(
    IEffectFactory& fxFactory,
    const EffectPipelineStateDescription& opaquePipelineState,
    const EffectPipelineStateDescription& alphaPipelineState,
    int textureDescriptorOffset,
    int samplerDescriptorOffset,
    const ModelMeshPart* part) const
{
    assert(part->materialIndex < materials.size());
    const auto& m = materials[part->materialIndex];

    if (!part->vbDecl || part->vbDecl->empty())
        throw std::exception("Model mesh part missing vertex buffer input elements data");

    if (part->vbDecl->size() > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT)
        throw std::exception("Model mesh part input layout size is too large for DirectX 12");

    D3D12_INPUT_LAYOUT_DESC il = {};
    il.NumElements = static_cast<UINT>(part->vbDecl->size());
    il.pInputElementDescs = part->vbDecl->data();

    return fxFactory.CreateEffect(m, opaquePipelineState, alphaPipelineState, il, textureDescriptorOffset, samplerDescriptorOffset);
}

// Create effects for each mesh piece with the default factory
_Use_decl_annotations_
std::vector<std::shared_ptr<IEffect>> Model::CreateEffects(
    const EffectPipelineStateDescription& opaquePipelineState,
    const EffectPipelineStateDescription& alphaPipelineState,
    ID3D12DescriptorHeap* textureDescriptorHeap,
    ID3D12DescriptorHeap* samplerDescriptorHeap,
    int textureDescriptorOffset,
    int samplerDescriptorOffset) const
{
    EffectFactory fxFactory(textureDescriptorHeap, samplerDescriptorHeap);
    return CreateEffects(fxFactory, opaquePipelineState, alphaPipelineState, textureDescriptorOffset, samplerDescriptorOffset);
}

// Updates effect matrices (if applicable)
void XM_CALLCONV Model::UpdateEffectMatrices(
    _In_ std::vector<std::shared_ptr<IEffect>>& effectList,
    DirectX::FXMMATRIX world,
    DirectX::CXMMATRIX view,
    DirectX::CXMMATRIX proj)
{
    for (auto& fx : effectList)
    {
        auto matFx = dynamic_cast<IEffectMatrices*>(fx.get());
        if (matFx)
        {
            matFx->SetMatrices(world, view, proj);
        }
    }
}

// Transition static VB/IB resources (if applicable)
void Model::Transition(
    _In_ ID3D12GraphicsCommandList* commandList,
    D3D12_RESOURCE_STATES stateBeforeVB,
    D3D12_RESOURCE_STATES stateAfterVB,
    D3D12_RESOURCE_STATES stateBeforeIB,
    D3D12_RESOURCE_STATES stateAfterIB)
{
    UINT count = 0;
    D3D12_RESOURCE_BARRIER barrier[64] = {};

    for (auto& mit : meshes)
    {
        for (auto& pit : mit->opaqueMeshParts)
        {
            assert(count < _countof(barrier));
            _Analysis_assume_(count < _countof(barrier));

            if (stateBeforeIB != stateAfterIB && pit->staticIndexBuffer)
            {
                barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
                barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
                barrier[count].Transition.pResource = pit->staticIndexBuffer.Get();
                barrier[count].Transition.StateBefore = stateBeforeIB;
                barrier[count].Transition.StateAfter = stateAfterIB;
                ++count;

                if (count >= _countof(barrier))
                {
                    commandList->ResourceBarrier(count, barrier);
                    count = 0;
                }
            }

            if (stateBeforeVB != stateAfterVB && pit->staticVertexBuffer)
            {
                barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
                barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
                barrier[count].Transition.pResource = pit->staticVertexBuffer.Get();
                barrier[count].Transition.StateBefore = stateBeforeVB;
                barrier[count].Transition.StateAfter = stateAfterVB;
                ++count;

                if (count >= _countof(barrier))
                {
                    commandList->ResourceBarrier(count, barrier);
                    count = 0;
                }
            }
        }

        for (auto& pit : mit->alphaMeshParts)
        {
            assert(count < _countof(barrier));
            _Analysis_assume_(count < _countof(barrier));

            if (stateBeforeIB != stateAfterIB && pit->staticIndexBuffer)
            {
                barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
                barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
                barrier[count].Transition.pResource = pit->staticIndexBuffer.Get();
                barrier[count].Transition.StateBefore = stateBeforeIB;
                barrier[count].Transition.StateAfter = stateAfterIB;
                ++count;

                if (count >= _countof(barrier))
                {
                    commandList->ResourceBarrier(count, barrier);
                    count = 0;
                }
            }

            if (stateBeforeVB != stateAfterVB && pit->staticVertexBuffer)
            {
                barrier[count].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
                barrier[count].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
                barrier[count].Transition.pResource = pit->staticVertexBuffer.Get();
                barrier[count].Transition.StateBefore = stateBeforeVB;
                barrier[count].Transition.StateAfter = stateAfterVB;
                ++count;

                if (count >= _countof(barrier))
                {
                    commandList->ResourceBarrier(count, barrier);
                    count = 0;
                }
            }
        }
    }

    if (count > 0)
    {
        commandList->ResourceBarrier(count, barrier);
    }
}


text:
using RegistryDict = policy::RegistryDict;

namespace {

// Maximum PReg file size we're willing to accept.
const int64_t kMaxPRegFileSize = 1024 * 1024 * 16;
static_assert(kMaxPRegFileSize <= std::numeric_limits<ptrdiff_t>::max(),
              "Max PReg file size too large.");

// Maximum number of components in registry key names. This corresponds to the
// maximum nesting level of RegistryDict trees.
const size_t kMaxKeyNameComponents = 1024;

// Constants for PReg file delimiters.
const char16_t kDelimBracketOpen = u'[';
const char16_t kDelimBracketClose = u']';
const char16_t kDelimSemicolon = u';';

// Registry path separator.
const char16_t kRegistryPathSeparator[] = u"\\";

// Magic strings for the PReg value field to trigger special actions.
const char kActionTriggerPrefix[] = "**";
const char kActionTriggerDeleteValues[] = "deletevalues";
const char kActionTriggerDel[] = "del.";
const char kActionTriggerDelVals[] = "delvals";
const char kActionTriggerDeleteKeys[] = "deletekeys";
const char kActionTriggerSecureKey[] = "securekey";
const char kActionTriggerSoft[] = "soft";

// Returns the character at |cursor| and increments it, unless the end is here
// in which case -1 is returned. The calling code must guarantee that
// end - *cursor does not overflow ptrdiff_t.
int NextChar(const uint8_t** cursor, const uint8_t* end) {
  // Only read the character if a full char16_t is available.
  // This comparison makes sure no overflow can happen.
  if (*cursor >= end ||
      end - *cursor < static_cast<ptrdiff_t>(sizeof(char16_t)))
    return -1;

  int result = **cursor | (*(*cursor + 1) << 8);
  *cursor += sizeof(char16_t);
  return result;
}

// Reads a fixed-size field from a PReg file. The calling code must guarantee
// that both end - *cursor and size do not overflow ptrdiff_t.
bool ReadFieldBinary(const uint8_t** cursor,
                     const uint8_t* end,
                     uint32_t size,
                     uint8_t* data) {
  if (size == 0)
    return true;

  // Be careful to prevent possible overflows here (don't do *cursor + size).
  if (*cursor >= end || end - *cursor < static_cast<ptrdiff_t>(size))
    return false;
  const uint8_t* field_end = *cursor + size;
  std::copy(*cursor, field_end, data);
  *cursor = field_end;
  return true;
}

bool ReadField32(const uint8_t** cursor, const uint8_t* end, uint32_t* data) {
  uint32_t value = 0;
  if (!ReadFieldBinary(cursor, end, sizeof(uint32_t),
                       reinterpret_cast<uint8_t*>(&value))) {
    return false;
  }
  *data = base::ByteSwapToLE32(value);
  return true;
}

// Reads a string field from a file.
bool ReadFieldString(const uint8_t** cursor,
                     const uint8_t* end,
                     std::u16string* str) {
  int current = -1;
  while ((current = NextChar(cursor, end)) > 0x0000)
    *str += current;

  return current == L'\0';
}

// Converts the UTF16 |data| to an UTF8 string |value|. Returns false if the
// resulting UTF8 string contains invalid characters.
bool DecodePRegStringValue(const std::vector<uint8_t>& data,
                           std::string* value) {
  size_t len = data.size() / sizeof(char16_t);
  if (len <= 0) {
    value->clear();
    return true;
  }

  const char16_t* chars = reinterpret_cast<const char16_t*>(data.data());
  std::u16string utf16_str;
  std::transform(chars, chars + len - 1, std::back_inserter(utf16_str),
                 base::ByteSwapToLE16);
  // Note: UTF16ToUTF8() only checks whether all chars are valid code points,
  // but not whether they're valid characters. IsStringUTF8(), however, does.
  *value = base::UTF16ToUTF8(utf16_str);
  if (!base::IsStringUTF8(*value)) {
    LOG(ERROR) << "String '" << *value << "' is not a valid UTF8 string";
    value->clear();
    return false;
  }
  return true;
}

// Decodes a value from a PReg file given as a uint8_t vector.
bool DecodePRegValue(uint32_t type,
                     const std::vector<uint8_t>& data,
                     std::unique_ptr<base::Value>* value) {
  std::string data_utf8;
  switch (type) {
    case REG_SZ:
    case REG_EXPAND_SZ:
      if (!DecodePRegStringValue(data, &data_utf8))
        return false;
      *value = std::make_unique<base::Value>(data_utf8);
      return true;
    case REG_DWORD_LITTLE_ENDIAN:
    case REG_DWORD_BIG_ENDIAN:
      if (data.size() == sizeof(uint32_t)) {
        uint32_t val = *reinterpret_cast<const uint32_t*>(data.data());
        if (type == REG_DWORD_BIG_ENDIAN)
          val = base::NetToHost32(val);
        else
          val = base::ByteSwapToLE32(val);
        *value = std::make_unique<base::Value>(static_cast<int>(val));
        return true;
      } else {
        LOG(ERROR) << "Bad data size " << data.size();
      }
      break;
    case REG_NONE:
    case REG_LINK:
    case REG_MULTI_SZ:
    case REG_RESOURCE_LIST:
    case REG_FULL_RESOURCE_DESCRIPTOR:
    case REG_RESOURCE_REQUIREMENTS_LIST:
    case REG_QWORD_LITTLE_ENDIAN:
    default:
      LOG(ERROR) << "Unsupported registry data type " << type;
  }

  return false;
}

// Returns true if the registry key |key_name| belongs to the sub-tree specified
// by the key |root|.
bool KeyRootEquals(const std::u16string& key_name, const std::u16string& root) {
  if (root.empty())
    return true;

  if (!base::StartsWith(key_name, root, base::CompareCase::INSENSITIVE_ASCII))
    return false;

  // Handle the case where |root| == "ABC" and |key_name| == "ABCDE\FG". This
  // should not be interpreted as a match.
  return key_name.length() == root.length() ||
         key_name.at(root.length()) == kRegistryPathSeparator[0];
}

// Adds |value| and |data| to |dict| or an appropriate sub-dictionary indicated
// by |key_name|. Creates sub-dictionaries if necessary. Also handles special
// action triggers, see |kActionTrigger*|, that can, for instance, remove an
// existing value.
void HandleRecord(const std::u16string& key_name,
                  const std::u16string& value,
                  uint32_t type,
                  const std::vector<uint8_t>& data,
                  RegistryDict* dict) {
  // Locate/create the dictionary to place the value in.
  std::vector<std::u16string> path;

  std::vector<base::StringPiece16> key_name_components =
      base::SplitStringPiece(key_name, kRegistryPathSeparator,
                             base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  if (key_name_components.size() > kMaxKeyNameComponents) {
    LOG(ERROR) << "Encountered a key which has more than "
               << kMaxKeyNameComponents << " components.";
    return;
  }
  for (const base::StringPiece16& key_name_component : key_name_components) {
    if (key_name_component.empty())
      continue;

    const std::string name = base::UTF16ToUTF8(key_name_component);
    RegistryDict* subdict = dict->GetKey(name);
    if (!subdict) {
      subdict = new RegistryDict();
      dict->SetKey(name, base::WrapUnique(subdict));
    }
    dict = subdict;
  }

  if (value.empty())
    return;

  std::string value_name(base::UTF16ToUTF8(value));
  if (!base::StartsWith(value_name, kActionTriggerPrefix,
                        base::CompareCase::SENSITIVE)) {
    std::unique_ptr<base::Value> value_ptr;
    if (DecodePRegValue(type, data, &value_ptr))
      dict->SetValue(value_name, std::move(value_ptr));
    return;
  }

  std::string data_utf8;
  std::string action_trigger(base::ToLowerASCII(
      value_name.substr(base::size(kActionTriggerPrefix) - 1)));
  if (action_trigger == kActionTriggerDeleteValues) {
    if (DecodePRegStringValue(data, &data_utf8)) {
      for (const std::string& value_str :
           base::SplitString(data_utf8, ";", base::KEEP_WHITESPACE,
                             base::SPLIT_WANT_NONEMPTY))
        dict->RemoveValue(value_str);
    }
  } else if (base::StartsWith(action_trigger, kActionTriggerDeleteKeys,
                              base::CompareCase::SENSITIVE)) {
    if (DecodePRegStringValue(data, &data_utf8)) {
      for (const std::string& key :
           base::SplitString(data_utf8, ";", base::KEEP_WHITESPACE,
                             base::SPLIT_WANT_NONEMPTY))
        dict->RemoveKey(key);
    }
  } else if (base::StartsWith(action_trigger, kActionTriggerDel,
                              base::CompareCase::SENSITIVE)) {
    dict->RemoveValue(value_name.substr(base::size(kActionTriggerPrefix) - 1 +
                                        base::size(kActionTriggerDel) - 1));
  } else if (base::StartsWith(action_trigger, kActionTriggerDelVals,
                              base::CompareCase::SENSITIVE)) {
    // Delete all values.
    dict->ClearValues();
  } else if (base::StartsWith(action_trigger, kActionTriggerSecureKey,
                              base::CompareCase::SENSITIVE) ||
             base::StartsWith(action_trigger, kActionTriggerSoft,
                              base::CompareCase::SENSITIVE)) {
    // Doesn't affect values.
  } else {
    LOG(ERROR) << "Bad action trigger " << value_name;
  }
}

}  // namespace

namespace policy {
namespace preg_parser {

const char kPRegFileHeader[8] = {'P',    'R',    'e',    'g',
                                 '\x01', '\x00', '\x00', '\x00'};

bool ReadFile(const base::FilePath& file_path,
              const std::u16string& root,
              RegistryDict* dict,
              PolicyLoadStatusSampler* status) {
  base::MemoryMappedFile mapped_file;
  if (!mapped_file.Initialize(file_path) || !mapped_file.IsValid()) {
    PLOG(ERROR) << "Failed to map " << file_path.value();
    status->Add(POLICY_LOAD_STATUS_READ_ERROR);
    return false;
  }

  return ReadDataInternal(
      mapped_file.data(), mapped_file.length(), root, dict, status,
      base::StringPrintf("file '%" PRFilePath "'", file_path.value().c_str()));
}

POLICY_EXPORT bool ReadDataInternal(const uint8_t* preg_data,
                                    size_t preg_data_size,
                                    const std::u16string& root,
                                    RegistryDict* dict,
                                    PolicyLoadStatusSampler* status,
                                    const std::string& debug_name) {
  DCHECK(status);
  DCHECK(root.empty() || root.back() != kRegistryPathSeparator[0]);

  // Check data size.
  if (preg_data_size > kMaxPRegFileSize) {
    LOG(ERROR) << "PReg " << debug_name << " too large: " << preg_data_size;
    status->Add(POLICY_LOAD_STATUS_TOO_BIG);
    return false;
  }

  // Check the header.
  const int kHeaderSize = base::size(kPRegFileHeader);
  if (!preg_data || preg_data_size < kHeaderSize ||
      memcmp(kPRegFileHeader, preg_data, kHeaderSize) != 0) {
    LOG(ERROR) << "Bad PReg " << debug_name;
    status->Add(POLICY_LOAD_STATUS_PARSE_ERROR);
    return false;
  }

  // Parse data, which is expected to be UCS-2 and little-endian. The latter I
  // couldn't find documentation on, but the example I saw were all
  // little-endian. It'd be interesting to check on big-endian hardware.
  const uint8_t* cursor = preg_data + kHeaderSize;
  const uint8_t* end = preg_data + preg_data_size;
  while (true) {
    if (cursor == end)
      return true;

    if (NextChar(&cursor, end) != kDelimBracketOpen)
      break;

    // Read the record fields.
    std::u16string key_name;
    std::u16string value;
    uint32_t type = 0;
    uint32_t size = 0;
    std::vector<uint8_t> data;

    if (!ReadFieldString(&cursor, end, &key_name))
      break;

    int current = NextChar(&cursor, end);
    if (current == kDelimSemicolon) {
      if (!ReadFieldString(&cursor, end, &value))
        break;
      current = NextChar(&cursor, end);
    }

    if (current == kDelimSemicolon) {
      if (!ReadField32(&cursor, end, &type))
        break;
      current = NextChar(&cursor, end);
    }

    if (current == kDelimSemicolon) {
      if (!ReadField32(&cursor, end, &size))
        break;
      current = NextChar(&cursor, end);
    }

    if (current == kDelimSemicolon) {
      if (size > kMaxPRegFileSize)
        break;
      data.resize(size);
      if (!ReadFieldBinary(&cursor, end, size, data.data()))
        break;
      current = NextChar(&cursor, end);
    }

    if (current != kDelimBracketClose)
      break;

    // Process the record if it is within the |root| subtree.
    if (KeyRootEquals(key_name, root))
      HandleRecord(key_name.substr(root.size()), value, type, data, dict);
  }

  LOG(ERROR) << "Error parsing PReg " << debug_name << " at offset "
             << (reinterpret_cast<const uint8_t*>(cursor - 1) - preg_data);
  status->Add(POLICY_LOAD_STATUS_PARSE_ERROR);
  return false;
}

}  // namespace preg_parser
}  // namespace policy


text:
package com.microsoft.azure.management.containerinstance.v2018_02_01_preview;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The instance view of the container group. Only valid in response.
 */
public class ContainerGroupPropertiesInstanceView {
    /**
     * The events of this container group.
     */
    @JsonProperty(value = "events", access = JsonProperty.Access.WRITE_ONLY)
    private List<Event> events;

    /**
     * The state of the container group. Only valid in response.
     */
    @JsonProperty(value = "state", access = JsonProperty.Access.WRITE_ONLY)
    private String state;

    /**
     * Get the events of this container group.
     *
     * @return the events value
     */
    public List<Event> events() {
        return this.events;
    }

    /**
     * Get the state of the container group. Only valid in response.
     *
     * @return the state value
     */
    public String state() {
        return this.state;
    }

}


text:
climlab.solar
=============

.. automodule:: climlab.solar
    :members:
    :undoc-members:
    :show-inheritance:

.. toctree::

   climlab.solar.insolation
   climlab.solar.orbital
   climlab.solar.orbital_cycles


text:
package org.kie.workbench.common.dmn.project.client.resources.i18n;

import org.jboss.errai.ui.shared.api.annotations.TranslationKey;

public interface DMNProjectClientConstants {

    @TranslationKey(defaultValue = "")
    String DMNDiagramResourceType = "DMNDiagramResourceType.shortName";

    @TranslationKey(defaultValue = "")
    String DMNDiagramResourceTypeDescription = "DMNDiagramResourceType.description";

    @TranslationKey(defaultValue = "")
    String DMNDiagramResourceTypeDownload = "DMNDiagramResourceType.download";
}