text:
package com.github.mjeanroy.springmvc.view.mustache.logging;

/**
 * Implementation of {@link Logger} that does nothing.
 */
class NoopLogger implements Logger {

	private static final NoopLogger INSTANCE = new NoopLogger();

	static NoopLogger getInstance() {
		return INSTANCE;
	}

	private NoopLogger() {
	}

	@Override
	public void trace(String message) {
	}

	@Override
	public void trace(String message, Object arg) {
	}

	@Override
	public void trace(String message, Object arg1, Object arg2) {
	}

	@Override
	public void trace(String message, Throwable ex) {
	}

	@Override
	public void debug(String message) {
	}

	@Override
	public void debug(String message, Object arg) {
	}

	@Override
	public void debug(String message, Object arg1, Object arg2) {
	}

	@Override
	public void debug(String message, Throwable ex) {
	}

	@Override
	public void info(String message) {
	}

	@Override
	public void info(String message, Object arg) {
	}

	@Override
	public void info(String message, Object arg1, Object arg2) {
	}

	@Override
	public void info(String message, Throwable ex) {
	}

	@Override
	public void warn(String message) {
	}

	@Override
	public void warn(String message, Object arg) {
	}

	@Override
	public void warn(String message, Object arg1, Object arg2) {
	}

	@Override
	public void warn(String message, Throwable ex) {
	}

	@Override
	public void error(String message) {
	}

	@Override
	public void error(String message, Object arg) {
	}

	@Override
	public void error(String message, Object arg1, Object arg2) {
	}

	@Override
	public void error(String message, Throwable ex) {
	}

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

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

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

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

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


text:
<?php

namespace GitSSH2\NotificationBundle\Notification\Handler;

use GitSSH2\NotificationBundle\Notification\NotificationEntityInterface;
use \GitSSH2\NotificationBundle\Notification\Handler\NotificationHandlerInterface;
use Doctrine\ORM\EntityManager;

class NotificationSystemHandler implements NotificationHandlerInterface
{

    /**
     * EntityManager
     *
     * @var Doctrine\ORM\EntityManager
     */
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * Handles the notification
     *
     * @return string
     */
    public function handle(NotificationEntityInterface $notification)
    {
        $this->em->persist($notification);
        $this->em->flush();
    }

    /**
     * Checks if this handler can handle this notification
     *
     * @param NotificationEntityInterface $notification
     */
    public function canHandle(NotificationEntityInterface $notification)
    {
        if ($notification instanceof \GitSSH2\NotificationBundle\Entity\Notification) {
            return true;
        }else{
            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
const test = require('ava')
const path = require('path')
const inquirer = require('inquirer')
const fs = require('fs')
const SpeikeInit = require('../lib/init.js')
const utils = require('../lib/utils.js')
const cacheTemplatePath = path.join(__dirname, '.speike-templates')
const targetDir = 'tmp'
const targetName = 'speike-cli-unit-test'
const localTargetName = 'speike-cli-unit-test-local'

const answers = {
  name: 'speike-cli-test',
  author: 'Berwin <liubowen.niubi@gmail.com>',
  description: 'speike-cli unit test'
}

test.before(() => {
  inquirer.prompt = (questions) => {
    const _answers = {}
    for (var i = 0; i < questions.length; i++) {
      const key = questions[i].name
      _answers[key] = answers[key]
    }
    return Promise.resolve(_answers)
  }
})

test.cb('should generation speike-cli-unit-test project', t => {
  const targetPath = path.join(__dirname, targetDir, targetName)
  const init = new SpeikeInit({
    template: 'speike-template-haotech',
    name: targetName,
    cacheTemplatePath,
    targetPath,
    clone: false
  })

  init.run()

  const timer = setInterval(() => {
    if (utils.isExist(targetPath)) {
      clearInterval(timer)
      t.pass()
      t.end()
    }
  }, 1000)
})

test.cb('project content be equal to answers', t => {
  const targetPath = path.join(__dirname, targetDir, targetName)
  fs.readFile(path.join(targetPath, 'Server', 'package.json'), 'utf8', (err, data) => {
    if (err) throw err
    const json = JSON.parse(data)
    t.is(json.name, answers.name)
    t.is(json.description, answers.description)
    t.is(json.author, answers.author)
    t.end()
  })
})

test.cb('should generate from a local template', t => {
  const targetPath = path.join(__dirname, targetDir, localTargetName)
  const init = new SpeikeInit({
    template: path.join(__dirname, './test-template'),
    targetPath,
    name: localTargetName
  })

  init.run()

  const timer = setInterval(() => {
    if (utils.isExist(targetPath)) {
      clearInterval(timer)
      t.pass()
      t.end()
    }
  }, 1000)
})

test.cb('local template generate project content be equal to answers', t => {
  const targetPath = path.join(__dirname, targetDir, localTargetName)
  fs.readFile(path.join(targetPath, 'index.js'), 'utf8', (err, data) => {
    if (err) throw err
    const json = JSON.parse(data)
    t.is(json.name, answers.name)
    t.is(json.description, answers.description)
    t.is(json.author, answers.author)
    t.end()
  })
})

test.after(t => {
  return utils.rmdir(cacheTemplatePath)
    .then(() => utils.rmdir(path.join(__dirname, targetDir)))
})


text:
namespace Microsoft.Tools.ServiceModel.WsatConfig
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Reflection;
    using System.Diagnostics;
    using System.Security.Principal;
    using System.Security.Cryptography.X509Certificates;

    class ArgumentsParser
    {
        Dictionary<string, ParserBase> parsersTable = new Dictionary<string, ParserBase>();
        Dictionary<string, string> optionsLookupTable = new Dictionary<string, string>();

        Dictionary<string, int> optionsHitCount = new Dictionary<string, int>();
        WsatConfiguration config;

        public ArgumentsParser(WsatConfiguration config)
        {
            this.config = config;
            InitializeParsers();
        }

        public bool ParseOptionAndArgument(string optionAndArgument)
        {
            string value;
            string lowerCaseOption = ExtractOption(optionAndArgument, out value);
            if (!string.IsNullOrEmpty(lowerCaseOption) && optionsLookupTable.ContainsKey(lowerCaseOption))
            {
                string normalizedOption = optionsLookupTable[lowerCaseOption];
                ParserBase parser = parsersTable[normalizedOption];
                parser.Parse(value, config);
                UpdateOptionHitCount(normalizedOption);
                return true;
            }
            return false;
        }

        public void ValidateArgumentsThrow()
        {
            if (optionsHitCount.Count >= 1)
            {
                foreach (string option in optionsHitCount.Keys)
                {
                    if (optionsHitCount[option] > 1)
                    {
                        throw new WsatAdminException(WsatAdminErrorCode.DUPLICATE_OPTION, SR.GetString(SR.ErrorDuplicateOption, option));
                    }
                }

                if (!config.TransactionBridgeEnabled)
                {
                    int optionsAllowed = 0;
                    if (optionsHitCount.ContainsKey(CommandLineOption.Network))
                    {
                        ++optionsAllowed;
                    }

                    if (optionsHitCount.ContainsKey(CommandLineOption.ClusterRemoteNode))
                    {
                        ++optionsAllowed;
                    }

                    if (optionsHitCount.ContainsKey(CommandLineOption.Restart))
                    {
                        ++optionsAllowed;
                    }

                    if (optionsHitCount.Count > optionsAllowed)
                    {
                        throw new WsatAdminException(WsatAdminErrorCode.CANNOT_UPDATE_SETTINGS_WHEN_NETWORK_IS_DISABLED, SR.GetString(SR.ErrorUpdateSettingsWhenNetworkIsDisabled));
                    }
                }
            }
        }

        void UpdateOptionHitCount(string option)
        {
            int hitCount = 0;
            if (optionsHitCount.TryGetValue(option, out hitCount))
            {
                optionsHitCount[option] = hitCount + 1;
            }
            else
            {
                optionsHitCount.Add(option, 1);
            }
        }

        static public string ExtractOption(string arg, out string value)
        {
            value = null;
            if (!string.IsNullOrEmpty(arg))
            {
                int separator = arg.IndexOf(':');
                if (separator != -1)
                {
                    value = arg.Substring(separator + 1);
                    return arg.Substring(0, separator).Trim().ToLowerInvariant();
                }
            }
            return string.Empty;
        }

        void InitializeParsers()
        {
            AddOptionParserPair(CommandLineOption.Network, new NetworkParser());
            AddOptionParserPair(CommandLineOption.Port, new PortParser());
            AddOptionParserPair(CommandLineOption.MaxTimeout, new MaxTimeoutParser());
            AddOptionParserPair(CommandLineOption.DefaultTimeout, new DefaultTimeoutParser());
            AddOptionParserPair(CommandLineOption.TraceLevel, new TraceLevelParser());
            AddOptionParserPair(CommandLineOption.TraceActivity, new TraceActivityParser());
            AddOptionParserPair(CommandLineOption.TraceProp, new TracePropagationParser());
            AddOptionParserPair(CommandLineOption.TracePii, new TracePiiParser());
            AddOptionParserPair(CommandLineOption.EndpointCert, new EndpointCertificateParser());
            AddOptionParserPair(CommandLineOption.Accounts, new AccountsParser());
            AddOptionParserPair(CommandLineOption.ClusterRemoteNode, new ClusterRemoteNodeParser());
            AddOptionParserPair(CommandLineOption.AccountsCerts, new AccountsCertificatesParser());
        }

        void AddOptionParserPair(string standardOption, ParserBase parser)
        {
            optionsLookupTable.Add(standardOption.ToLowerInvariant(), standardOption);
            parsersTable.Add(standardOption, parser);
        }

        abstract class ParserBase
        {
            abstract protected void DoParse(string value, WsatConfiguration config);

            public void Parse(string value, WsatConfiguration config)
            {
                Debug.Assert(config != null, "config is null");

                DoParse(value, config);
            }
        }

        class NetworkParser : ParserBase
        {
            // -network:{enable|disable}
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (Utilities.SafeCompare(value, CommandLineOption.Enable))
                    {
                        QfeChecker.CheckQfe();
                        config.TransactionBridgeEnabled = true;
                        return;
                    }
                    else if (Utilities.SafeCompare(value, CommandLineOption.Disable))
                    {
                        config.TransactionBridgeEnabled = false;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_NETWORK_ARGUMENT, SR.GetString(SR.ErrorNetworkArgument));
            }
        }

        class PortParser : ParserBase
        {
            // -port:<portNum>
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    UInt16 parsedValue;
                    if (UInt16.TryParse(value, out parsedValue))
                    {
                        config.HttpsPort = parsedValue;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_HTTPS_PORT, SR.GetString(SR.ErrorHttpsPortRange));
            }
        }

        class MaxTimeoutParser : ParserBase
        {
            // -maxTimeout:<sec>
            override protected void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    UInt16 parsedValue;
                    if (UInt16.TryParse(value, out parsedValue))
                    {
                        config.MaxTimeout = parsedValue;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_MAXTIMEOUT_ARGUMENT, SR.GetString(SR.ErrorMaximumTimeoutRange));
            }
        }

        class DefaultTimeoutParser : ParserBase
        {
            // -timeout:<sec>
            override protected void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    UInt16 parsedValue;
                    if (UInt16.TryParse(value, out parsedValue))
                    {
                        config.DefaultTimeout = parsedValue;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_DEFTIMEOUT_ARGUMENT, SR.GetString(SR.ErrorDefaultTimeoutRange));
            }
        }

        // -traceLevel:{Off|Error|Critical|Warning|Information|Verbose|All}
        class TraceLevelParser : ParserBase
        {
            override protected void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    SourceLevels level;
                    bool parsedCorrectly = Utilities.ParseSourceLevel(value, out level);
                    if (parsedCorrectly)
                    {
                        config.TraceLevel = level;
                        return;
                    }
                    else
                    {
                        // check to see if it's a number
                        uint temp;
                        if (UInt32.TryParse(value, out temp))
                        {
                            config.TraceLevel = (SourceLevels)temp;
                            return;
                        }
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACELEVEL_ARGUMENT,
                                    SR.GetString(SR.ErrorTraceLevelArgument));
            }
        }

        class TraceActivityParser : ParserBase
        {
            // -traceActivity:{enable|disable}
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (Utilities.SafeCompare(value, CommandLineOption.Enable))
                    {
                        config.ActivityTracing = true;
                        return;
                    }
                    else if (Utilities.SafeCompare(value, CommandLineOption.Disable))
                    {
                        config.ActivityTracing = false;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACE_ACTIVITY_ARGUMENT,
                                                    SR.GetString(SR.ErrorTraceActivityArgument));
            }
        }

        class TracePropagationParser : ParserBase
        {
            // -traceProp:{enable|disable}
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (Utilities.SafeCompare(value, CommandLineOption.Enable))
                    {
                        config.ActivityPropagation = true;
                        return;
                    }
                    else if (Utilities.SafeCompare(value, CommandLineOption.Disable))
                    {
                        config.ActivityPropagation = false;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACE_PROPAGATION_ARGUMENT,
                                        SR.GetString(SR.ErrorTracePropArgument));
            }
        }

        class TracePiiParser : ParserBase
        {
            // -tracePII:{enable|disable}
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (Utilities.SafeCompare(value, CommandLineOption.Enable))
                    {
                        config.TracePii = true;
                        return;
                    }
                    else if (Utilities.SafeCompare(value, CommandLineOption.Disable))
                    {
                        config.TracePii = false;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_TRACE_PII_ARGUMENT,
                                    SR.GetString(SR.ErrorTracePiiArgument));
            }
        }

        // -endpointCert:{machine|<thumb>|"Issuer\SubjectName"}
        class EndpointCertificateParser : ParserBase
        {
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (Utilities.SafeCompare(value, CommandLineOption.CertMachine))
                    {
                        config.X509Certificate = CertificateManager.GetMachineIdentityCertificate();
                        if (config.X509Certificate == null)
                        {
                            throw new WsatAdminException(WsatAdminErrorCode.CANNOT_FIND_MACHINE_CERTIFICATE,
                                                            SR.GetString(SR.ErrorCannotFindMachineCertificate));
                        }
                    }
                    else if (value.IndexOf('\\') >= 0) // "Issuer\SubjectName" e.g. "*\This is a distinguished subject"
                    {
                        config.X509Certificate = CertificateManager.GetCertificateFromIssuerAndSubjectName(value);
                    }
                    else // thumbprint
                    {
                        config.X509Certificate = CertificateManager.GetCertificateFromThumbprint(value, string.Empty);
                    }

                    if (config.X509Certificate != null)
                    {
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_SSL_CERTIFICATE,
                                    SR.GetString(SR.ErrorMissingSSLCert));
            }
        }

        // -accounts:<account,>
        class AccountsParser : ParserBase
        {
            protected override void DoParse(string value, WsatConfiguration config)
            {
                // Empty value is allowed and means then users want to remove all accounts
                config.KerberosGlobalAcl = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                List<string> acceptedAccounts = new List<string>(config.KerberosGlobalAcl);

                List<string> validAccounts = new List<string>();
                foreach (string account in acceptedAccounts)
                {
                    string normalizedAccount = account.Trim();
                    if (!string.IsNullOrEmpty(normalizedAccount))
                    {
                        if (IsValidAccount(normalizedAccount))
                        {
                            validAccounts.Add(normalizedAccount);
                        }
                        else
                        {
                            throw new WsatAdminException(WsatAdminErrorCode.INVALID_ACCOUNT, SR.GetString(SR.ErrorAccountArgument, normalizedAccount));
                        }
                    }
                }
                config.KerberosGlobalAcl = validAccounts.ToArray();
            }

            bool IsValidAccount(string account)
            {
                bool isValid = false;
                try
                {
                    NTAccount ntAccount = new NTAccount(account);
                    IdentityReference identityRef = ntAccount.Translate(typeof(SecurityIdentifier));
                    isValid = identityRef != null;
                }
                catch (IdentityNotMappedException)
                {
                }
                catch (Exception e)
                {
                    if (Utilities.IsCriticalException(e))
                    {
                        throw;
                    }
                }

                return isValid;
            }
        }

        class ClusterRemoteNodeParser : ParserBase
        {
            // private switch: -clusterRemoteNode
            protected override void DoParse(string value, WsatConfiguration config)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (Utilities.SafeCompare(value, CommandLineOption.Enable))
                    {
                        config.IsClusterRemoteNode = true;
                        return;
                    }
                    else if (Utilities.SafeCompare(value, CommandLineOption.Disable))
                    {
                        config.IsClusterRemoteNode = false;
                        return;
                    }
                }
                throw new WsatAdminException(WsatAdminErrorCode.INVALID_CLUSTER_REMOTE_NODE_ARGUMENT, SR.GetString(SR.ErrorClusterRemoteNodeArgument));
            }
        }

        class AccountsCertificatesParser : ParserBase
        {
            // -accountsCerts:<base64hash|"Issuer\SubjectName",>
            protected override void DoParse(string value, WsatConfiguration config)
            {
                // Empty value is allowed and means then users want to remove all accounts certs
                config.X509GlobalAcl = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                // newConfig.X509GlobalAcl can be empty, but never null

                int i = 0;
                foreach (string certString in config.X509GlobalAcl)
                {
                    if (!string.IsNullOrEmpty(certString))
                    {
                        X509Certificate2 cert = null;
                        if (certString.IndexOf('\\') >= 0)
                        {
                            // issuer\subject
                            cert = CertificateManager.GetCertificateFromIssuerAndSubjectName(certString);
                        }
                        else
                        {
                            // thumbprint
                            cert = CertificateManager.GetCertificateFromThumbprint(certString, string.Empty);
                        }

                        if (cert != null)
                        {
                            config.X509GlobalAcl[i] = cert.Thumbprint;
                        }
                        else
                        {
                            throw new WsatAdminException(WsatAdminErrorCode.INVALID_OR_MISSING_CLIENT_CERTIFICATE,
                                                            SR.GetString(SR.ErrorInvalidOrMissingClientCert));
                        }
                    }
                    i++;
                }
            }
        }
    }
}


text:
package org.cache2k.test.util;

/**
 * A condition we may wait for.
 *
 * @author Jens Wilke
 */
public interface Condition {

  boolean check();

}


text:
<?xml version="1.0" encoding="utf-8"?>

<net.bensdeals.views.DealItemView
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/block"
    >
    <LinearLayout
        style="@style/block"
        android:orientation="vertical"
        android:padding="5dip">
        <ImageView
            style="@style/block"
            android:id="@+id/gallery_image"
            android:scaleType="fitCenter"
            android:layout_margin="15dip"
            android:padding="15dip"
            android:background="@color/solid_white"
            />
        <LinearLayout
            android:id="@+id/gallery_text_container"
            style="@style/fill"
            android:layout_marginLeft="15dip"
            android:layout_marginRight="15dip"
            android:orientation="vertical">
            <TextView
                android:id="@+id/title_text"
                style="@style/block"
                android:textSize="16sp"
                android:textStyle="bold"
                android:lineSpacingMultiplier="1.1"
                android:textColor="@color/solid_white"
                android:layout_marginBottom="10dip"
                android:lines="2"
                android:ellipsize="end"
                />
            <TextView
                style="@style/fill_no_height"
                android:id="@+id/desc_text"
                android:lineSpacingMultiplier="1.1"
                android:textColor="@color/solid_white"
                android:lines="6"
                android:ellipsize="end"/>
            <LinearLayout
                style="@style/block"
                android:gravity="right">
                <ImageView
                    android:layout_width="30dip"
                    android:layout_height="30dip"
                    android:src="@android:drawable/ic_menu_share"
                    />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</net.bensdeals.views.DealItemView>


text:
    </div><!-- /.container -->

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  </body>
</html>


text:
NSString *BraintreeDemoAppDelegatePaymentsURLScheme = @"com.braintreepayments.Demo.payments";

@implementation BraintreeDemoAppDelegate

- (BOOL)application:(__unused UIApplication *)application didFinishLaunchingWithOptions:(__unused NSDictionary *)launchOptions {
    [[BITHockeyManager sharedHockeyManager] configureWithIdentifier:@"7134982f3df6419a0eb52b16e7d6d175"];
    [[BITHockeyManager sharedHockeyManager] startManager];
    [[BITHockeyManager sharedHockeyManager].authenticator authenticateInstallation];
    if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-enableUpdateCheck"]) {
        [[BITHockeyManager sharedHockeyManager] updateManager].checkForUpdateOnLaunch = YES;
    } else {
        [[BITHockeyManager sharedHockeyManager] updateManager].checkForUpdateOnLaunch = NO;
    }
    [[BITHockeyManager sharedHockeyManager] updateManager].updateSetting = BITUpdateCheckDaily;

    [self setupAppearance];
    [self registerDefaultsFromSettings];

    [BTAppSwitch setReturnURLScheme:BraintreeDemoAppDelegatePaymentsURLScheme];

    return YES;
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
- (BOOL)application:(__unused UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    if ([[url.scheme lowercaseString] isEqualToString:[BraintreeDemoAppDelegatePaymentsURLScheme lowercaseString]]) {
        return [BTAppSwitch handleOpenURL:url options:options];
    }
    return YES;
}
#endif

// Deprecated in iOS 9, but necessary to support < versions
- (BOOL)application:(__unused UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(__unused id)annotation {
    if ([[url.scheme lowercaseString] isEqualToString:[BraintreeDemoAppDelegatePaymentsURLScheme lowercaseString]]) {
        return [BTAppSwitch handleOpenURL:url sourceApplication:sourceApplication];
    }
    return YES;
}

- (void)setupAppearance {
    UIColor *pleasantGray = [UIColor colorWithWhite:42/255.0f alpha:1.0f];

    [[UIToolbar appearance] setBarTintColor:pleasantGray];
    [[UIToolbar appearance] setBarStyle:UIBarStyleBlackTranslucent];
}

- (void)registerDefaultsFromSettings {
    // Check for testing arguments
    if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-EnvironmentSandbox"]) {
        [[NSUserDefaults standardUserDefaults] setInteger:BraintreeDemoTransactionServiceEnvironmentSandboxBraintreeSampleMerchant forKey:BraintreeDemoSettingsEnvironmentDefaultsKey];
    }else if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-EnvironmentProduction"]) {
        [[NSUserDefaults standardUserDefaults] setInteger:BraintreeDemoTransactionServiceEnvironmentProductionExecutiveSampleMerchant forKey:BraintreeDemoSettingsEnvironmentDefaultsKey];
    }

    if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-TokenizationKey"]) {
        [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"BraintreeDemoUseTokenizationKey"];
    }else if ([[[NSProcessInfo processInfo] arguments] containsObject:@"-ClientToken"]) {
        [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"BraintreeDemoUseTokenizationKey"];
        // Use random users for testing with Client Tokens
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"BraintreeDemoCustomerIdentifier"];
    }

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"BraintreeDemoSettingsAuthorizationOverride"];
    for (NSString* arg in [[NSProcessInfo processInfo] arguments]) {
        if ([arg rangeOfString:@"-Integration:"].location != NSNotFound) {
            NSString* testIntegration = [arg stringByReplacingOccurrencesOfString:@"-Integration:" withString:@""];
            [[NSUserDefaults standardUserDefaults] setObject:testIntegration forKey:@"BraintreeDemoSettingsIntegration"];
        } else if ([arg rangeOfString:@"-Authorization:"].location != NSNotFound) {
            NSString* testIntegration = [arg stringByReplacingOccurrencesOfString:@"-Authorization:" withString:@""];
            [[NSUserDefaults standardUserDefaults] setObject:testIntegration forKey:@"BraintreeDemoSettingsAuthorizationOverride"];
        }
    }
    // End checking for testing arguments

    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }

    NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];

    NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
    for (NSDictionary *prefSpecification in preferences) {
        NSString *key = [prefSpecification objectForKey:@"Key"];
        if(key && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) {
            [defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
        }
    }

    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
}

#if DEBUG
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    CGPoint location = [[[event allTouches] anyObject] locationInView:[self window]];
    if(location.y > 0 && location.y < [[UIApplication sharedApplication] statusBarFrame].size.height) {
        [[FLEXManager sharedManager] showExplorer];
    }
}
#endif

@end


text:
[![Build Status](https://travis-ci.org/MichaelRocks/CallMeMaybe.svg?branch=master)](https://travis-ci.org/MichaelRocks/callmemaybe)
[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-CallMeMaybe-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/3542)

CallMeMaybe
===========
An Android `EditText` for phone numbers.

This library uses [libphonenumber-android][1] for phone number formatting.

![CallMeMaybe](https://raw.githubusercontent.com/MichaelRocks/CallMeMaybe/master/callmemaybe.gif)

Download
--------
Gradle:
```groovy
repositories {
  jcenter()
}

dependencies {
  compile 'io.michaelrocks:callmemaybe:1.2.9'
}
```

Usage
-----
Just replace your `EditText` with the `PhoneEditText` and that's it!

If using the `PhoneEditText` view doesn't work well for you it's possible
to make `TextView` act as the `PhoneEditText`.
```java
final TextView phoneEditText = (TextView) findViewById(R.id.phoneEditText);
CallMeMaybe.attachTo(phoneEditText);
```

If you already use `libphonenumber-android` somewhere in you project
pass an instance of `PhoneNumberUtil` to `CallMeMaybe` using the
`CallMeMaybe.setPhoneNumberUtil(PhoneNumberUtil)` method to avoid
creation of another instance of `PhoneNumberUtil`.

License
=======
    Copyright 2017 Michael Rozumyanskiy

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

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

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

 [1]: https://github.com/MichaelRocks/libphonenumber-android


text:
using System;
using Umbraco.Cms.Core.Models.PublishedContent;

namespace Umbraco.Cms.Core.PropertyEditors.ValueConverters
{
    /// <summary>
    /// The upload property value converter.
    /// </summary>
    [DefaultPropertyValueConverter]
    public class UploadPropertyConverter : PropertyValueConverterBase
    {
        public override bool IsConverter(IPublishedPropertyType propertyType)
            => propertyType.EditorAlias.Equals(Constants.PropertyEditors.Aliases.UploadField);

        public override Type GetPropertyValueType(IPublishedPropertyType propertyType)
            => typeof (string);

        public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
            => PropertyCacheLevel.Element;

        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel cacheLevel, object source, bool preview)
        {
            return source?.ToString() ?? "";
        }
    }
}


text:
#ifndef _ACTIVEMQ_UTIL_IDGENERATORTEST_H_
#define _ACTIVEMQ_UTIL_IDGENERATORTEST_H_

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>

namespace activemq {
namespace util {

    class IdGeneratorTest : public CppUnit::TestFixture {

        CPPUNIT_TEST_SUITE( IdGeneratorTest );
        CPPUNIT_TEST( testConstructor1 );
        CPPUNIT_TEST( testConstructor2 );
        CPPUNIT_TEST( testCompare );
        CPPUNIT_TEST( testThreadSafety );
        CPPUNIT_TEST_SUITE_END();

    public:

        IdGeneratorTest();
        virtual ~IdGeneratorTest();

        void testConstructor1();
        void testConstructor2();
        void testCompare();
        void testThreadSafety();

    };

}}

#endif /* _ACTIVEMQ_UTIL_IDGENERATORTEST_H_ */


text:
/**
 * navbar-ontop.js 1.0.0
 * Add .navbar-ontop class to navbar when the page is scrolled to top
 * Make sure to add this script to the <head> of page to avoid flickering on load
 */

(function() {

	var className = "navbar-ontop"

	// we start hidden, to avoid flickering
	document.write("<style id='temp-navbar-ontop'>.navbar {opacity:0; transition: none !important}</style>")

	function update() {
		// toggle className based on the scrollTop property of document
		var nav = document.querySelector(".navbar")

		if (window.scrollY > 15)
			nav.classList.remove(className)
		else
			nav.classList.add(className)
	}

	document.addEventListener("DOMContentLoaded", function(event) {
		$(window).on('show.bs.collapse', function (e) {
			$(e.target).closest("." + className).removeClass(className);
		})

		$(window).on('hidden.bs.collapse', function (e) {
			update()
		})
		update()
		// still hacking to avoid flickering
		setTimeout(function() {
			document.querySelector("#temp-navbar-ontop").remove()
		})
  	});

	window.addEventListener("scroll", function() {
		update()
	})

})();


text:
'use strict';

const RuleTester = require('eslint').RuleTester;
const tester = new RuleTester();

const ruleName = 'detect-child-process';
const rule = require(`../rules/${ruleName}`);

tester.run(ruleName, rule, {
  valid: ["child_process.exec('ls')"],
  invalid: [
    {
      code: "require('child_process')",
      errors: [{ message: 'Found require("child_process")' }],
    },
    {
      code: "var child = require('child_process'); child.exec(com)",
      errors: [{ message: 'Found require("child_process")' }, { message: 'Found child_process.exec() with non Literal first argument' }],
    },
    {
      code: "var child = require('child_process'); child.exec()",
      errors: [{ message: 'Found require("child_process")' }],
    },
  ],
});


text:
{% extends "base.html" %}

{% block content %}
    {{ page.text|safe }}
{% endblock %}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var g_webview = null;
var embedder = {};
var seenFocusCount = 0;
embedder.tests = {};
embedder.guestURL =
    'data:text/html,<html><body>Guest<body></html>';
var g_inputMethodTestHelper = null;
var g_focusRestoredTestHelper = null;

window.runTest = function(testName) {
  if (!embedder.test.testList[testName]) {
    console.log('Incorrect testName: ' + testName);
    embedder.test.fail();
    return;
  }

  // Run the test.
  embedder.test.testList[testName]();
};

window.runCommand = function(command, opt_step) {
  window.console.log('window.runCommand: ' + command);
  switch (command) {
    case 'testFocusTracksEmbedderRunNextStep':
      testFocusTracksEmbedderRunNextStep();
      break;
    case 'testInputMethodRunNextStep':
      testInputMethodRunNextStep(opt_step);
      break;
    case 'testFocusRestoredRunNextStep':
      testFocusRestoredRunNextStep(opt_step);
    default:
      embedder.test.fail();
  }
};
// window.* exported functions end.

var LOG = function(msg) {
  window.console.log(msg);
};

embedder.test = {};
embedder.test.succeed = function() {
  chrome.test.sendMessage('TEST_PASSED');
};

embedder.test.fail = function() {
  chrome.test.sendMessage('TEST_FAILED');
};

embedder.test.assertEq = function(a, b) {
  if (a != b) {
    console.log('assertion failed: ' + a + ' != ' + b);
    embedder.test.fail();
  }
};

embedder.test.assertTrue = function(condition) {
  if (!condition) {
    console.log('assertion failed: true != ' + condition);
    embedder.test.fail();
  }
};

embedder.test.assertFalse = function(condition) {
  if (condition) {
    console.log('assertion failed: false != ' + condition);
    embedder.test.fail();
  }
};

/** @private */
embedder.setUpGuest_ = function() {
  document.querySelector('#webview-tag-container').innerHTML =
      '<webview style="width: 100px; height: 100px;"></webview>';
  var webview = document.querySelector('webview');
  if (!webview) {
    embedder.test.fail('No <webview> element created');
  }
  return webview;
};

/**
 * @private
 *
 * A test helper for focus related tests.
 * It does the following steps:
 * 1. It navigates |webview|.
 * 2. On 'loadstop', it injects the script |inject_js_guest_url|.
 * 3. When the injection has completed, it sends a ['connect'] message to the
 * guest to initiate a two-way communication channel.
 * 4. When the two way channel has been established |channelCreationCallback| is
 * called.
 * 5. It ignores all messages from the guest until it gets an
 * |expectedResponse|.
 * If there is no |expectedResponse|, the method is done.
 * 6. Once the expected result is received, call |responseCallback|.
 */
embedder.waitForResponseFromGuest_ =
    function(webview,
             inject_js_guest_url,
             channelCreationCallback,
             expectedResponse,
             responseCallback) {
  var onPostMessageReceived = function(e) {
    var data = JSON.parse(e.data);
    var response = data[0];
    if (response == 'connected') {
      channelCreationCallback(webview);

      if (!expectedResponse) {
        // We are done.
        window.removeEventListener('message', onPostMessageReceived);
      }
      return;
    }
    if (response != expectedResponse) {
      return;
    }
    responseCallback(data);
    window.removeEventListener('message', onPostMessageReceived);
  };
  window.addEventListener('message', onPostMessageReceived);

  webview.addEventListener('consolemessage', function(e) {
    LOG('g: ' + e.message);
  });

  var onWebViewLoadStop = function(e) {
    console.log('loadstop');
    webview.executeScript(
      {file: inject_js_guest_url},
      function(results) {
        console.log('Injected script into webview.');
        // Establish a communication channel with the webview1's guest.
        var msg = ['connect'];
        webview.contentWindow.postMessage(JSON.stringify(msg), '*');
      });
    webview.removeEventListener('loadstop', onWebViewLoadStop);
  };
  webview.addEventListener('loadstop', onWebViewLoadStop);
  webview.src = embedder.guestURL;
};

// Helper class for testFocusRestored.
//
// This test has multiple steps, WebViewTest instructs this test to advance to
// each step and then performs some action and verification and runs the next
// step.
// See WebViewInteractiveTest.Focus_FocusRestored for details.
function FocusRestoredTestHelper() {
  // Total number of steps for this test that we run thru
  // testFocusRestoredRunNextStep.
  this.TOTAL_STEPS = 3;
  // Currently running step index.
  this.step_ = 0;
  this.messageHandlerRegistered_ = false;
  this.doneCallback_ = null;
}

FocusRestoredTestHelper.prototype.runStep = function(step, doneCallback) {
  LOG('runStep: ' + step);
  this.doneCallback_ = doneCallback;

  if (step != this.step_ + 1 || step < 0 || step > this.TOTAL_STEPS) {
    LOG('Incorrect step, expected:', this.step_ + 1, 'got', step);
    this.passStep_(false);
    return;
  }
  this.step_ = step;

  if (!this.messageHandlerRegistered_) {
    this.messageHandlerRegistered_ = true;
    window.addEventListener('message', this.messageHandler_.bind(this));
  }

  var msgToSend = '';
  if (step == 1) {
    msgToSend = 'request-waitForFocus';
  } else if (step == 2) {
    msgToSend = 'request-waitForBlur';
  } else if (step == 3) {
    msgToSend = 'request-waitForFocusAgain';
  }

  if (!msgToSend) {
    this.passStep_(false);
    return;
  }

  g_webview.contentWindow.postMessage(JSON.stringify([msgToSend]), '*');
};

FocusRestoredTestHelper.prototype.messageHandler_ = function(e) {
  var data = JSON.parse(e.data);
  LOG('FocusRestoredTestHelper.message, data: ' + data);
  switch (this.step_) {
    case 1:
      this.passStep_(data[0] == 'response-focus');
      break;
    case 2:
      this.passStep_(data[0] == 'response-blur');
      g_webview.focus();
      break;
    case 3:
      this.passStep_(data[0] == 'response-focusAgain');
      break;
    default:
      LOG('Unexpected message: ' + data);
      this.passStep_(false);
  }
};

FocusRestoredTestHelper.prototype.passStep_ = function(passed) {
  if (!this.doneCallback_) {
    LOG('Expected doneCallback_ in FocusRestoredTestHelper');
    embedder.test.fail();
    return;
  }
  this.doneCallback_(passed);
};

// Helper class for testInputMethod.
// This test has multiple steps, WebViewTest instructs this test to advance to
// each step and then performs some action and verification and runs the next
// step.
//
// See WebViewInteractiveTest.Focus_InputMethod for details about these steps.
function InputMethodTestHelper() {
  // Total number of steps for this test that we run thru
  // testInputMethodRunNextStep.
  this.TOTAL_STEPS = 4;
  // Currently running step index.
  this.step_ = 0;
  // True iff post message handler has been regsitered.
  this.messageHandlerRegistered_ = false;
  this.doneCallback_ = null;
};

InputMethodTestHelper.prototype.passStep_ = function(passed) {
  if (!this.doneCallback_) {
    LOG('Expected doneCallback_ in InputMethodTestHelper');
    embedder.test.fail();
    return;
  }
  this.doneCallback_(passed);
};

InputMethodTestHelper.prototype.runStep = function(step, doneCallback) {
  LOG('runStep: ' + step);
  this.doneCallback_ = doneCallback;

  if (step != this.step_ + 1 || step < 0 || step > this.TOTAL_STEPS) {
    LOG('Incorrect step, expected:', this.step_ + 1, 'got', step);
    this.passStep_(false);
    return;
  }
  this.step_ = step;

  if (!this.messageHandlerRegistered_) {
    this.messageHandlerRegistered_ = true;
    window.addEventListener('message', this.messageHandler_.bind(this));
  }

  var msgToSend = '';
  if (step == 1) {
    msgToSend = 'request-waitForOnInput';
  } else if (step == 2) {
    msgToSend = 'request-waitForOnInput';
  } else if (step == 3) {
    msgToSend = 'request-moveFocus';
  } else if (step == 4) {
    msgToSend = 'request-valueAfterExtendSelection';
  }
  if (!msgToSend) {
    this.passStep_(false);
    return;
  }

  g_webview.contentWindow.postMessage(JSON.stringify([msgToSend]), '*');
};

InputMethodTestHelper.prototype.messageHandler_ = function(e) {
  var data = JSON.parse(e.data);
  LOG('InputMethodTestHelper.message, data: ' + data);
  switch (this.step_) {
    case 1:
      this.passStep_(data[0] == 'response-waitForOnInput' &&
                     data[1] == 'InputTest123');
      break;
    case 2:
      this.passStep_(data[0] == 'response-waitForOnInput' &&
                     data[1] == 'InputTest456');
      break;
    case 3:
      this.passStep_(data[0] == 'response-movedFocus' &&
                     data[1] == 'InputTest789');
      break;
    case 4:
      this.passStep_(data[0] == 'response-valueAfterExtendSelection' &&
                     data[1] == 'InputABC');
      break;
    default:
      LOG('Unexpected message: ' + data);
      this.passStep_(false);
  }
};

// Tests begin.

// The embedder has to initiate a post message so that the guest can get a
// reference to embedder to send the reply back.

embedder.testFocus_ = function(channelCreationCallback,
                               expectedResponse,
                               responseCallback) {
  var webview = embedder.setUpGuest_();

  embedder.waitForResponseFromGuest_(webview,
                                     'inject_focus.js',
                                     channelCreationCallback,
                                     expectedResponse,
                                     responseCallback);
};

// Verifies that if a <webview> is focused before navigation then the guest
// starts off focused.
//
// We create a <webview> element and make it focused before navigating it.
// Then we load a URL in it and make sure document.hasFocus() returns true
// for the <webview>.
function testFocusBeforeNavigation() {
  var webview = document.createElement('webview');
  document.body.appendChild(webview);

  var onChannelEstablished = function(webview) {
    // Query the guest if it has focus.
    var msg = ['request-hasFocus'];
    webview.contentWindow.postMessage(JSON.stringify(msg), '*');
  };

  // Focus the <webview> before navigating it.
  webview.focus();

  embedder.waitForResponseFromGuest_(
    webview,
    'inject_focus.js',
    onChannelEstablished,
    'response-hasFocus',
    function(data) {
      LOG('data, hasFocus: ' + data[1]);
      embedder.test.assertEq(true, data[1]);
      embedder.test.succeed();
    });
}

function testFocusEvent() {
  var seenResponse = false;
  embedder.testFocus_(function(webview) {
    webview.focus();
  }, 'focused', function() {
    // The focus event fires three times on first focus. We only care about
    // the first focus.
    if (seenResponse) {
      return;
    }
    seenResponse = true;
    embedder.test.succeed();
  });
}

function testBlurEvent() {
  var seenResponse = false;
  embedder.testFocus_(function(webview) {
    webview.focus();
    webview.blur();
  }, 'blurred', function() {
    if (seenResponse) {
      return;
    }
    seenResponse = true;
    embedder.test.succeed();
  });
}

// This test verifies IME related stuff for guest.
//
// Briefly:
// 1) We load a guest, the guest gets initial focus and sends message
// back to the embedder.
// 2) In InputMethodTestHelper's step 1, we receive some text via cpp, the
// text is InputTest123, we verify we've seen the change in the guest.
// 3) In InputMethodTestHelper's step 2, we expect the text to be changed
// to InputTest456, this is done from cpp via committing an IME composition.
// 4) In InputMethodTestHelper's step 3, we have a composition (InputTest789)
// on an input element but we move the focus to another input element, we
// make sure the first element gets the composition commit.
// 5) In InputMethodTestHelper's step 4, we verify extending and deleting
// selection through caret works properly.
function testInputMethod() {
  var webview = document.createElement('webview');
  g_webview = webview;
  document.body.appendChild(webview);

  webview.focus();

  var onChannelEstablished = function(webview) {
    var msg = ['request-waitForFocus'];
    webview.contentWindow.postMessage(JSON.stringify(msg), '*');
  };
  embedder.waitForResponseFromGuest_(
      webview,
      'inject_input_method.js',
      onChannelEstablished,
      'response-seenFocus',
      function(data) { embedder.test.succeed(); });
}

// Runs additional test steps for testInputMethod.
function testInputMethodRunNextStep(step) {
  LOG('testInputMethodRunNextStep, step: ' + step);
  if (!g_inputMethodTestHelper) {
    g_inputMethodTestHelper = new InputMethodTestHelper();
  }

  g_inputMethodTestHelper.runStep(step, function(stepPassed) {
    LOG('runStep callback, stepPassed: ' + stepPassed);
    chrome.test.sendMessage(stepPassed ? 'TEST_STEP_PASSED'
                                       : 'TEST_STEP_FAILED');
  });
}

// This test ensures we get TextInputTypeChanged event if we bring
// back focus to a guest's <input> after it was initially focused.
//
// Briefly:
// 1) We load a guest.
// 2) In FocusRestoredTestHelper's step 1, we click on the guest to
// focus its <input> element.
// 3) In FocusRestoredTestHelper's step 2, we click outside the guest
// so that the <input> gets a blur event.
// 4. In FocusRestoredTestHelper's step 3, we click on the guest again
// to bring the focus back.
// In the end we check the guest rvh's TextInputType in cpp to make
// sure it initialises properly.
function testFocusRestored() {
  var webview = document.createElement('webview');
  webview.style.width = '100px';
  webview.style.height = '100px';
  g_webview = webview;
  document.body.appendChild(webview);

  webview.focus();

  var onChannelEstablished = function(webview) {
    chrome.test.sendMessage('TEST_PASSED');
  };

  embedder.waitForResponseFromGuest_(webview,
                                     'inject_focus_restored.js',
                                     onChannelEstablished,
                                     undefined,
                                     undefined);
}

// Runs additional test steps for testFocusRestored.
function testFocusRestoredRunNextStep(step) {
  LOG('testFocusRestoredRunNextStep, step: ' + step);
  if (!g_focusRestoredTestHelper) {
    g_focusRestoredTestHelper = new FocusRestoredTestHelper();
  }
  g_focusRestoredTestHelper.runStep(step, function(stepPassed) {
    LOG('runStep callback, stepPassed: ' + stepPassed);
    chrome.test.sendMessage(stepPassed ? 'TEST_STEP_PASSED'
                                       : 'TEST_STEP_FAILED');
  });
}

// Tests that if we focus/blur the embedder, it also gets reflected in the
// guest.
//
// This test has two steps:
// 1) testFocusTracksEmbedder(), in this step we create a <webview> and
// focus it before navigating. After navigating it to a URL, we focus an input
// element inside the <webview>, and wait for its 'focus' event to fire.
// 2) testFocusTracksEmbedderRunNextStep(), in this step, we have already called
// Blur() on the embedder's RVH (see WebViewTest.Focus_FocusTracksEmbedder),
// we make sure we see a 'blur' event on the <webview>'s input element.
function testFocusTracksEmbedder() {
  var webview = document.createElement('webview');
  g_webview = webview;
  document.body.appendChild(webview);

  var onChannelEstablished = function(webview) {
    var msg = ['request-waitForFocus'];
    webview.contentWindow.postMessage(JSON.stringify(msg), '*');
  };

  // Focus the <webview> before navigating it.
  // This is necessary so that 'blur' event on guest's <input> element fires.
  webview.focus();

  embedder.waitForResponseFromGuest_(
      webview,
      'inject_focus.js',
      onChannelEstablished,
      'response-seenFocus',
      function(data) { embedder.test.succeed(); });
}

// Runs the second step for testFocusTracksEmbedder().
// See WebViewTest.Focus_FocusTracksEmbedder() to see how this is invoked.
function testFocusTracksEmbedderRunNextStep() {
  g_webview.contentWindow.postMessage(
      JSON.stringify(['request-waitForBlurAfterFocus']), '*');

  window.addEventListener('message', function(e) {
    var data = JSON.parse(e.data);
    LOG('send window.message, data: ' + data);
    if (data[0] == 'response-seenBlurAfterFocus') {
      chrome.test.sendMessage('TEST_STEP_PASSED');
    } else {
      chrome.test.sendMessage('TEST_STEP_FAILED');
    }
  });
}

// Tests that <webview> sees advanceFocus() call when we cycle through the
// elements inside it using tab key.
//
// This test has two steps:
// 1) testAdvanceFocus(), in this step, we focus the embedder and press a
// tab key, we expect the input element inside the <webview> to be focused.
// 2) POST_testAdvanceFocus(), in this step we send additional tab keypress
// to the embedder/app (from WebViewInteractiveTest.Focus_AdvanceFocus), this
// would cycle the focus within the elements and will bring focus back to
// the input element present in the <webview> mentioned in step 1.
function testAdvanceFocus() {
  var webview = document.createElement('webview');
  g_webview = webview;
  document.body.appendChild(webview);

  webview.addEventListener('consolemessage', function(e) {
    LOG('g: ' + e.message);
  });
  webview.addEventListener('loadstop', function(e) {
    LOG('loadstop');

    window.addEventListener('message', function(e) {
      var data = JSON.parse(e.data);
      LOG('message, data: ' + data);

      if (data[0] == 'connected') {
        embedder.test.succeed();
      } else if (data[0] == 'button1-focused') {
        var focusCount = data[1];
        LOG('focusCount: ' + focusCount);
        seenFocusCount++;
        if (focusCount == 1) {
          chrome.test.sendMessage('button1-focused');
        } else {
          chrome.test.sendMessage('button1-advance-focus');
        }
      }
    });

    webview.executeScript(
      {file: 'inject_advance_focus_test.js'},
      function(results) {
        window.console.log('webview.executeScript response');
        if (!results || !results.length) {
          LOG('Inject script failure.');
          embedder.test.fail();
          return;
        }
        webview.contentWindow.postMessage(JSON.stringify(['connect']), '*');
      });
  });

  webview.src = embedder.guestURL;
}

embedder.test.testList = {
  'testAdvanceFocus': testAdvanceFocus,
  'testBlurEvent': testBlurEvent,
  'testFocusBeforeNavigation': testFocusBeforeNavigation,
  'testFocusEvent': testFocusEvent,
  'testFocusTracksEmbedder': testFocusTracksEmbedder,
  'testInputMethod': testInputMethod,
  'testFocusRestored': testFocusRestored
};

onload = function() {
  chrome.test.getConfig(function(config) {
    chrome.test.sendMessage('Launched');
  });
};


text:
package ua.com.fielden.platform.persistence.types;

import ua.com.fielden.platform.dao.EntityBasedOnAbstractPersistentEntityDao;
import ua.com.fielden.platform.entity.AbstractPersistentEntity;
import ua.com.fielden.platform.entity.annotation.CompanionObject;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.MapEntityTo;
import ua.com.fielden.platform.entity.annotation.Observable;

/**
 * This is an entity for testing of {@link AbstractPersistentEntity} property related auto-assignments.
 *
 * @author TG Team
 *
 */
@KeyType(String.class)
@MapEntityTo
@CompanionObject(EntityBasedOnAbstractPersistentEntityDao.class)
public class EntityBasedOnAbstractPersistentEntity extends AbstractPersistentEntity<String> {
    private static final long serialVersionUID = 1L;

    @Override
    @Observable
    public EntityBasedOnAbstractPersistentEntity setKey(String key) {
        super.setKey(key);
        return this;
    }

}


text:
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "h2o.h"
#include "h2o/configurator.h"
#include "h2o/http1.h"
#include "h2o/http2.h"

static h2o_hostconf_t *create_hostconf(h2o_globalconf_t *globalconf)
{
    h2o_hostconf_t *hostconf = h2o_mem_alloc(sizeof(*hostconf));
    *hostconf = (h2o_hostconf_t){globalconf};
    h2o_config_init_pathconf(&hostconf->fallback_path, globalconf, NULL, globalconf->mimemap);
    hostconf->mimemap = globalconf->mimemap;
    h2o_mem_addref_shared(hostconf->mimemap);
    return hostconf;
}

static void destroy_hostconf(h2o_hostconf_t *hostconf)
{
    size_t i;

    if (hostconf->authority.hostport.base != hostconf->authority.host.base)
        free(hostconf->authority.hostport.base);
    free(hostconf->authority.host.base);
    for (i = 0; i != hostconf->paths.size; ++i) {
        h2o_pathconf_t *pathconf = hostconf->paths.entries + i;
        h2o_config_dispose_pathconf(pathconf);
    }
    h2o_config_dispose_pathconf(&hostconf->fallback_path);
    h2o_mem_release_shared(hostconf->mimemap);

    free(hostconf);
}

void h2o_config_init_pathconf(h2o_pathconf_t *pathconf, h2o_globalconf_t *globalconf, const char *path, h2o_mimemap_t *mimemap)
{
    memset(pathconf, 0, sizeof(*pathconf));
    pathconf->global = globalconf;
    h2o_chunked_register(pathconf);
    if (path != NULL)
        pathconf->path = h2o_strdup_slashed(NULL, path, SIZE_MAX);
    h2o_mem_addref_shared(mimemap);
    pathconf->mimemap = mimemap;
}

void h2o_config_dispose_pathconf(h2o_pathconf_t *pathconf)
{
#define DESTROY_LIST(type, list)                                                                                \
    do {                                                                                \
        size_t i;                                                                                \
        for (i = 0; i != list.size; ++i) {                                                                                \
            type *e = list.entries[i];                                                                                \
            if (e->dispose != NULL)                                                                                \
                e->dispose(e);                                                                                \
            free(e);                                                                                \
        }                                                                                \
        free(list.entries);                                                                                \
    } while (0)
    DESTROY_LIST(h2o_handler_t, pathconf->handlers);
    DESTROY_LIST(h2o_filter_t, pathconf->filters);
    DESTROY_LIST(h2o_logger_t, pathconf->loggers);
#undef DESTROY_LIST

    if (pathconf->mimemap != NULL)
        h2o_mem_release_shared(pathconf->mimemap);
}

void h2o_config_init(h2o_globalconf_t *config)
{
    memset(config, 0, sizeof(*config));
    config->hosts = h2o_mem_alloc(sizeof(config->hosts[0]));
    config->hosts[0] = NULL;
    h2o_linklist_init_anchor(&config->configurators);
    config->server_name = h2o_iovec_init(H2O_STRLIT("h2o/" H2O_VERSION));
    config->max_request_entity_size = H2O_DEFAULT_MAX_REQUEST_ENTITY_SIZE;
    config->max_delegations = H2O_DEFAULT_MAX_DELEGATIONS;
    config->handshake_timeout = H2O_DEFAULT_HANDSHAKE_TIMEOUT;
    config->http1.req_timeout = H2O_DEFAULT_HTTP1_REQ_TIMEOUT;
    config->http1.upgrade_to_http2 = H2O_DEFAULT_HTTP1_UPGRADE_TO_HTTP2;
    config->http1.callbacks = H2O_HTTP1_CALLBACKS;
    config->http2.idle_timeout = H2O_DEFAULT_HTTP2_IDLE_TIMEOUT;
    config->proxy.io_timeout = H2O_DEFAULT_PROXY_IO_TIMEOUT;
    config->http2.max_concurrent_requests_per_connection = H2O_HTTP2_SETTINGS_HOST.max_concurrent_streams;
    config->http2.max_streams_for_priority = 16;
    config->http2.callbacks = H2O_HTTP2_CALLBACKS;
    config->mimemap = h2o_mimemap_create();

    h2o_configurator__init_core(config);
}

h2o_pathconf_t *h2o_config_register_path(h2o_hostconf_t *hostconf, const char *pathname)
{
    h2o_pathconf_t *pathconf;

    h2o_vector_reserve(NULL, (void *)&hostconf->paths, sizeof(hostconf->paths.entries[0]), hostconf->paths.size + 1);
    pathconf = hostconf->paths.entries + hostconf->paths.size++;

    h2o_config_init_pathconf(pathconf, hostconf->global, pathname, hostconf->mimemap);

    return pathconf;
}

h2o_hostconf_t *h2o_config_register_host(h2o_globalconf_t *config, h2o_iovec_t host, uint16_t port)
{
    h2o_hostconf_t *hostconf;

    assert(host.len != 0);

    /* create hostconf */
    hostconf = create_hostconf(config);
    hostconf->authority.host = h2o_strdup(NULL, host.base, host.len);
    h2o_strtolower(hostconf->authority.host.base, hostconf->authority.host.len);
    hostconf->authority.port = port;
    if (hostconf->authority.port == 65535) {
        hostconf->authority.hostport = hostconf->authority.host;
    } else {
        hostconf->authority.hostport.base = h2o_mem_alloc(hostconf->authority.host.len + sizeof("[]:65535"));
        if (strchr(hostconf->authority.host.base, ':') != NULL) {
            hostconf->authority.hostport.len =
                sprintf(hostconf->authority.hostport.base, "[%s]:%" PRIu16, hostconf->authority.host.base, port);
        } else {
            hostconf->authority.hostport.len =
                sprintf(hostconf->authority.hostport.base, "%s:%" PRIu16, hostconf->authority.host.base, port);
        }
    }

    /* append to the list */
    h2o_append_to_null_terminated_list((void *)&config->hosts, hostconf);

    return hostconf;
}

void h2o_config_dispose(h2o_globalconf_t *config)
{
    size_t i;

    for (i = 0; config->hosts[i] != NULL; ++i) {
        h2o_hostconf_t *hostconf = config->hosts[i];
        destroy_hostconf(hostconf);
    }
    free(config->hosts);

    h2o_configurator__dispose_configurators(config);
}

h2o_handler_t *h2o_create_handler(h2o_pathconf_t *conf, size_t sz)
{
    h2o_handler_t *handler = h2o_mem_alloc(sz);

    memset(handler, 0, sz);
    handler->_config_slot = conf->global->_num_config_slots++;

    h2o_vector_reserve(NULL, (void *)&conf->handlers, sizeof(conf->handlers.entries[0]), conf->handlers.size + 1);
    conf->handlers.entries[conf->handlers.size++] = handler;

    return handler;
}

h2o_filter_t *h2o_create_filter(h2o_pathconf_t *conf, size_t sz)
{
    h2o_filter_t *filter = h2o_mem_alloc(sz);

    memset(filter, 0, sz);
    filter->_config_slot = conf->global->_num_config_slots++;

    h2o_vector_reserve(NULL, (void *)&conf->filters, sizeof(conf->filters.entries[0]), conf->filters.size + 1);
    memmove(conf->filters.entries + 1, conf->filters.entries, conf->filters.size * sizeof(conf->filters.entries[0]));
    conf->filters.entries[0] = filter;
    ++conf->filters.size;

    return filter;
}

h2o_logger_t *h2o_create_logger(h2o_pathconf_t *conf, size_t sz)
{
    h2o_logger_t *logger = h2o_mem_alloc(sz);

    memset(logger, 0, sz);
    logger->_config_slot = conf->global->_num_config_slots++;

    h2o_vector_reserve(NULL, (void *)&conf->loggers, sizeof(conf->loggers.entries[0]), conf->loggers.size + 1);
    conf->loggers.entries[conf->loggers.size++] = logger;

    return logger;
}


text:
<?
/* @package Lattice */

    class MyDOMDocument {
      public $_delegate;
      private $_validationErrors;

      public function __construct (DOMDocument $pDocument) {
        $this->_delegate = $pDocument;
        $this->_validationErrors = array();
      }

      public function __call ($pMethodName, $pArgs) {
        if ($pMethodName == "validate") {
          $eh = set_error_handler(array($this, "onValidateError"));
          $rv = $this->_delegate->validate();
          if ($eh) {
            set_error_handler($eh);
          }
          return $rv;
        }
        else {
          return call_user_func_array(array($this->_delegate, $pMethodName), $pArgs);
        }
      }
      public function __get ($pMemberName) {
        if ($pMemberName == "errors") {
          return $this->_validationErrors;
        }
        else {
          return $this->_delegate->$pMemberName;
        }
      }
      public function __set ($pMemberName, $pValue) {
        $this->_delegate->$pMemberName = $pValue;
      }
      public function onValidateError ($pNo, $pString, $pFile = null, $pLine = null, $pContext = null) {
        $this->_validationErrors[] = preg_replace("/^.+: */", "", $pString).$pLine;
      }
    }

Class lattice {

	private static $config;

	public static function config($arena, $xpath, $contextNode=null){
		if(!is_array(self::$config)){
			self::$config = array();
		}

		if($activeConfig = Kohana::config('lattice.activeConfiguration')){
			if($configurations = Kohana::config('lattice.configurations')){
				if($active = $configurations[$activeConfig]){
					if(isset($active[$arena]) && $newName = $active[$arena]){
						$arena = $newName;
					}
				}
			}
		}

		if(!isset(self::$config[$arena])){

			$dom = new DOMDocument();
			$dom->preserveWhiteSpace = false;
			$dom = new MyDOMDocument($dom);

			//check for arena mappings
			if($customPath = Kohana::config('lattice.paths.'.$arena)){
				$arenaPath = $customPath;
			} else {
            $arenaPath = $arena;
         }

         $request = NULL;
         $response = NULL;
         try{
           $request = Request::Factory($arenaPath);
           $response = $request->execute();

         } catch(Exception $e){
            //checking for existence of xml controller
            if(get_class($e) != 'HTTP_Exception_404'){
               throw $e;
            }
            //else continue on
         }

         if($response){
            $dom->loadXML($response->body());

         } else {

            if (file_exists($arenaPath)) {
               //if the argument is actually a path to a file
               $arenaPath = getcwd() . '/' . $arenaPath;
            } else {
               $arenaFilePath = Kohana::find_file('lattice', $arenaPath, 'xml', true);
               if (!count($arenaFilePath)) {
                  throw new Kohana_Exception('Could not locate xml :file', array(':file' => $arenaPath));
               }
               $arenaPath = $arenaFilePath[count($arenaFilePath) - 1];
            }
            $dom->load($arenaPath);
         }
         if (!$dom->validate()) {
            echo('Validation failed on '.$arenaPath);
				print_r($dom->errors);
				die();
			}

			if($arena == 'objects'){
				$clusters = new DOMDocument();
				$clusters = new MYDOMDocument($clusters);
				$path = Kohana::find_file('lattice', 'clusters', 'xml', true);
				if(!count($path)){
					throw new Kohana_Exception('Could not locate xml clusters');
				}
				$clusters->load( $path[0] );
				//echo $clusters->_delegate->saveXML();
				$clusters = new DOMXPath($clusters->_delegate);
				$clusterNodes = $clusters->evaluate('//objectType');
				foreach($clusterNodes as $node){
					$node = $dom->_delegate->importNode($node, true);
					$objectTypesNode = $dom->_delegate->getElementsByTagName('objectTypes')->item(0);
					$objectTypesNode->appendChild($node);
					//$dom->_delegate->insertBefore($node, $refNode);
				}
				//recreate Xpath object
				//$dom->formatOutput;
				//echo $dom->_delegate->saveXML();
			}

			$xpathObject = new DOMXPath($dom->_delegate);

			self::$config[$arena] = $xpathObject;
		}
		if($contextNode){
			$xmlNodes = self::$config[$arena]->evaluate($xpath, $contextNode);
		} else {
			$xmlNodes = self::$config[$arena]->evaluate($xpath);
		}
		return $xmlNodes;
	}

	/*
	 * Function: buildModule
	 This is the same function as in Display_Controller..
	 Obviously these classes should share a parent class or this is a static helper
	 Parameters:
	 $module - module configuration parameters
	 $constructorArguments - module arguments to constructor
	 */
	public static function buildModule($module, $constructorArguments=array() ){
		//need to look into this, these should be converged or interoperable
		if(isset($module['elementname'])){
			$module['modulename'] = $module['elementname'];
		}

		if(!Kohana::find_file('controllers', $module['modulename'] ) ){
			if(!isset($module['controllertype'])){
				$view = new View($module['modulename']);
				$object = Graph::object($module['modulename']);
        if($object->loaded()){ // in this case it's a slug for a specific object
					foreach(latticeviews::getViewContent($object->id, $object->objecttype->objecttypename) as $key=>$content){
						$view->$key = $content;
					}
				}
				return $view->render();
			}
      try {
        if(!class_exists($module['modulename'].'_Controller')){
          $includeclass = 'class '.$module['modulename'].'_Controller extends '.$module['controllertype'].'_Controller { } ';
          eval($includeclass);
        }
      } catch (Exception $e){
        throw new Kohana_User_Exception('Redeclared Virtual Class', 'Redeclared Virtual Class '.  'class '.$module['modulename'].'_Controller ');
      }
		}

		$fullname = $module['modulename'].'_Controller';
		$module = new $fullname; //this needs to be called with fargs
		call_user_func_array(array($module, '__construct'), $constructorArguments);

		$module->createIndexView();
		$module->view->loadResources();

		//and load resources for it's possible parents
		$parentclass = get_parent_class($module);
		$parentname = str_replace('_Controller', '', $parentclass);
		$module->view->loadResources(strtolower($parentname));

		//build submodules of this module (if any)
		$module->buildModules();

		return $module->view->render();

		//render some html
		//
		//BELOW HERE NEEDS TO BE FIXED IN ALL CHILDREN OF Lattice_CONTROLLER
		//CONTROLERS SHOULD JUST ASSIGN TEMPLATE VARS THEN AND THERE
		if($objectTypevar==NULL){
			$this->view->$module['modulename'] = $module->view->render();
		} else {
			$this->view->$objectTypevar = $module->view->render();
		}
	}

	public static function setCurrentLanguage($languageCode){
		Session::instance()->set('languageCode', $languageCode);
	}

	public static function getCurrentLanguage(){
		$languageCode = Session::instance()->get('languageCode');
		if(!$languageCode){
			$languageCode = Kohana::config('lattice.defaultLanguage');
		}
		return $languageCode;
	}

	//takes Exception as argument
	public static function getOneLineErrorReport(Exception $e){
		switch(get_class($e)){
			case 'Lattice_ApiException':
           // echo get_class($e);
           // die();
				return $e->getOneLineErrorReport();
				break;
			default:
				$message = $e->getMessage();
				foreach( $e->getTrace() as $trace){
					if(isset($trace['file'])){
						$message .= " ::::: ".$trace['file'].':'.$trace['line']."\n;";
					}
				}
				return $message;
				break;
		}
	}

	public static $webRoot = null;

	public static function convertFullPathToWebPath($fullPath){

		if(self::$webRoot == null){
			self::$webRoot  = getcwd().'/';
		}
		$webpath = str_replace(self::$webRoot, '', $fullPath);

		return $webpath;
	}

}