text:
package models

import "strings"

type LocalIntelData struct {
	Number         int64   `db:"number" json:"number"`
	ID             int64   `db:"id" json:"id"`
	EntityName     string  `db:"entityName" json:"entityName"`
	FactionName    string  `db:"factionName" json:"factionName"`
	Type           string  `db:"type" json:"type"`
	MemberCount    int64   `db:"memberCount" json:"memberCount"`
	WarAggressor   int64   `db:"warAggressor" json:"warAggressor"`
	WarDefender    int64   `db:"warDefender" json:"warDefender"`
	Kills          int64   `db:"kills" json:"kills"`
	Losses         int64   `db:"losses" json:"losses"`
	CapKills       int64   `db:"capKills" json:"capKills"`
	Efficiency     float64 `db:"efficiency" json:"efficiency"`
	CapProbability float64 `db:"capProbability" json:"capProbability"`
}

// FALSE Positive AST, concatenation is for replace tokens, actual values are fed
// through vargs.
func GetLocalIntel(names []interface{}) ([]LocalIntelData, error) {
	wars := []LocalIntelData{}
	if err := database.Select(&wars, `
		SELECT 	number,
				entityName,
				SUB1.id,
				type,
				memberCount,
				IFNULL(factionName, "") AS factionName,
				COUNT(DISTINCT Agg.ID) AS warAggressor,
				COUNT(DISTINCT Def.ID) AS warDefender,
				COALESCE(kills,0) AS kills,
				COALESCE(losses,0) AS losses,
				COALESCE(capKills,0) AS capKills,
				IF(kills, capKills / kills, 0) AS capProbability,
				IF(losses+kills, (kills/(kills+losses)), 1.0000) AS efficiency
		FROM
			(SELECT
				COUNT(DISTINCT Ch.characterID) AS number,
				IF(A.allianceID, A.name, Co.name) AS entityName,
				CREST.id,
				itemName AS factionName,
				CREST.type,
				IF(A.allianceID, A.memberCount, Co.memberCount) AS memberCount,
				sum(kills) AS kills,
				sum(losses) AS losses,
				sum(capKills) AS capKills
				FROM evedata.characters Ch
				LEFT OUTER JOIN evedata.alliances A ON Ch.allianceID = A.allianceID
				LEFT OUTER JOIN evedata.corporations Co ON Ch.corporationID = Co.corporationID
				LEFT OUTER JOIN invNames Fa ON Fa.itemID = Co.factionID
				LEFT OUTER JOIN evedata.entityKillStats S ON S.id = Ch.characterID
				INNER JOIN evedata.entities CREST ON CREST.id = IF(A.allianceID, A.allianceID, Co.corporationID)
				WHERE Ch.name IN (?`+strings.Repeat(",?", len(names)-1)+`)
				GROUP BY CREST.id) SUB1
		LEFT OUTER JOIN evedata.wars Agg ON Agg.aggressorID = SUB1.id AND (Agg.timeFinished = "0001-01-01 00:00:00" OR Agg.timeFinished IS NULL OR Agg.timeFinished >= UTC_TIMESTAMP()) AND Agg.timeStarted <= UTC_TIMESTAMP()
		LEFT OUTER JOIN evedata.wars Def ON Def.defenderID = SUB1.id AND (Def.timeFinished = "0001-01-01 00:00:00" OR Def.timeFinished IS NULL OR Def.timeFinished >= UTC_TIMESTAMP()) AND Def.timeStarted <= UTC_TIMESTAMP()
		GROUP BY SUB1.id`, names...); err != nil {
		return nil, err
	}
	return wars, nil
}


text:
import window from 'ember-window-mock';

export function getItem(key) {
  try {
    return window.localStorage.getItem(key);
  } catch {
    return null;
  }
}

export function setItem(key, value) {
  try {
    window.localStorage.setItem(key, value);
  } catch {
    // ignored
  }
}

export function removeItem(key) {
  try {
    window.localStorage.removeItem(key);
  } catch {
    // ignored
  }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

angular.module('animation').controller('Ryuhm12Controller', ['$scope',
	function($scope) {
		// Ryuhm12 controller logic
		// ...
	}
]);


text:
import '@webex/internal-plugin-device';

import {assert} from '@webex/test-helper-chai';
import {flaky} from '@webex/test-helper-mocha';
import WebexCore, {
  ServiceCatalog,
  ServiceRegistry,
  ServiceState,
  ServiceUrl
} from '@webex/webex-core';
import testUsers from '@webex/test-helper-test-users';
import uuid from 'uuid';
import sinon from 'sinon';

/* eslint-disable no-underscore-dangle */
describe('webex-core', () => {
  describe('Services', () => {
    let webexUser;
    let webexUserEU;
    let webex;
    let webexEU;
    let services;
    let servicesEU;
    let catalog;

    before('create users', () => Promise.all([
      testUsers.create({count: 1}),
      testUsers.create({
        count: 1,
        config: {
          orgId: process.env.EU_PRIMARY_ORG_ID
        }
      })
    ])
      .then(([[user], [userEU]]) => {
        webexUser = user;
        webexUserEU = userEU;
      }));

    beforeEach('create webex instance', () => {
      webex = new WebexCore({credentials: {supertoken: webexUser.token}});
      webexEU = new WebexCore({credentials: {supertoken: webexUserEU.token}});
      services = webex.internal.services;
      servicesEU = webexEU.internal.services;
      catalog = services._getCatalog();

      return Promise.all([
        services.waitForCatalog('postauth', 10),
        servicesEU.waitForCatalog('postauth', 10)
      ])
        .then(() => services.updateServices({
          from: 'limited',
          query: {userId: webexUser.id}
        }));
    });

    describe('#_getCatalog()', () => {
      it('returns a catalog', () => {
        const localCatalog = services._getCatalog();

        assert.equal(localCatalog.namespace, 'ServiceCatalog');
      });
    });

    describe('#list()', () => {
      it('matches the values in serviceUrl', () => {
        let serviceList = services.list();

        Object.keys(serviceList).forEach((key) => {
          assert.equal(serviceList[key], catalog._getUrl(key).get());
        });

        serviceList = services.list(true);
        Object.keys(serviceList).forEach((key) => {
          assert.equal(serviceList[key], catalog._getUrl(key).get(true));
        });
      });
    });

    describe('#get()', () => {
      let testUrlTemplate;
      let testUrl;

      beforeEach('load test url', () => {
        testUrlTemplate = {
          defaultUrl: 'https://www.example.com/api/v1',
          hosts: [],
          name: 'exampleValid'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      afterEach('unload test url', () => {
        catalog._unloadServiceUrls('preauth', [testUrl]);
      });

      it('returns a valid string when name is specified', () => {
        const url = services.get(testUrlTemplate.name);

        assert.typeOf(url, 'string');
        assert.equal(url, testUrlTemplate.defaultUrl);
      });

      it('returns undefined if url doesn\'t exist', () => {
        const s = services.get('invalidUrl');

        assert.typeOf(s, 'undefined');
      });

      it('gets a service from a specific serviceGroup', () => {
        assert.isDefined(services.get(testUrlTemplate.name, false, 'preauth'));
      });

      it('fails to get a service if serviceGroup isn\'t accurate', () => {
        assert.isUndefined(services.get(testUrlTemplate.name,
          false, 'discovery'));
      });
    });

    describe('#getClusterId()', () => {
      let testUrlTemplate;
      let testUrl;

      beforeEach('load test url', () => {
        testUrlTemplate = {
          defaultUrl: 'https://www.example.com/api/v1',
          hosts: [
            {
              homeCluster: true,
              host: 'www.example-p5.com',
              ttl: -1,
              priority: 5,
              id: 'exampleClusterId'
            },
            {
              host: 'www.example-p3.com',
              ttl: -1,
              priority: 3,
              id: 'exampleClusterId'
            }
          ],
          name: 'exampleValid'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      it('returns a clusterId when found with default url', () => {
        assert.equal(services.getClusterId(testUrlTemplate.defaultUrl),
          testUrlTemplate.hosts[0].id);
      });

      it('returns a clusterId when found with priority host url', () => {
        assert.equal(services.getClusterId(testUrl.get(true)),
          testUrlTemplate.hosts[0].id);
      });

      it('returns a clusterId when found with resource-appended url', () => {
        assert.equal(
          services.getClusterId(`${testUrl.get()}example/resource/value`),
          testUrlTemplate.hosts[0].id
        );
      });

      it('returns undefined when the url doesn\'t exist in catalog', () => {
        assert.isUndefined(
          services.getClusterId('http://not-a-known-url.com/')
        );
      });

      it('returns undefined when the string isn\'t a url', () => {
        assert.isUndefined(services.getClusterId('not a url'));
      });
    });

    describe('#getServiceFromClusterId()', () => {
      let testUrlTemplate;
      let testUrl;

      beforeEach('load test url', () => {
        testUrlTemplate = {
          defaultUrl: 'https://www.example.com/api/v1',
          hosts: [
            {
              homeCluster: true,
              host: 'www.example-p5.com',
              ttl: -1,
              priority: 5,
              id: '0:0:cluster-a:exampleValid'
            },
            {
              host: 'www.example-p3.com',
              ttl: -1,
              priority: 3,
              id: '0:0:cluster-b:exampleValid'
            }
          ],
          name: 'exampleValid'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      it('finds a valid service url from only a clusterId', () => {
        const serviceFound = services.getServiceFromClusterId({
          clusterId: testUrlTemplate.hosts[0].id,
          priorityHost: false
        });

        assert.equal(serviceFound.name, testUrl.name);
        assert.equal(serviceFound.url, testUrl.defaultUrl);
      });

      it('finds a valid priority service url', () => {
        const serviceFound = services.getServiceFromClusterId({
          clusterId: testUrlTemplate.hosts[0].id,
          priorityHost: true
        });

        assert.equal(serviceFound.name, testUrl.name);
        assert.isTrue(
          serviceFound.url.includes(testUrlTemplate.hosts[0].host),
          `'${serviceFound.url}' is not host '${testUrlTemplate.hosts[0].host}'`
        );
        // assert.equal(serviceFound.url, catalog.get('exampleValid', true));
      });

      it('finds a valid service when a service group is defined', () => {
        const serviceFound = catalog.findServiceFromClusterId({
          clusterId: testUrlTemplate.hosts[0].id,
          priorityHost: false,
          serviceGroup: 'preauth'
        });

        assert.equal(serviceFound.name, testUrl.name);
        assert.equal(serviceFound.url, testUrl.defaultUrl);
      });

      it('fails to find a valid service when it\'s not in a group', () => {
        assert.isUndefined(
          services.getServiceFromClusterId({
            clusterId: testUrlTemplate.hosts[0].id,
            serviceGroup: 'signin'
          })
        );
      });

      it('returns undefined when service doesn\'t exist', () => {
        assert.isUndefined(
          services.getServiceFromClusterId({clusterId: 'not a clusterId'})
        );
      });
    });

    describe('#getServiceFromUrl()', () => {
      let testUrlTemplate;
      let testUrl;

      beforeEach('load test url', () => {
        testUrlTemplate = {
          defaultUrl: 'https://www.example.com/api/v1',
          hosts: [
            {
              host: 'www.example-p5.com',
              ttl: -1,
              priority: 5,
              id: 'exampleClusterId'
            },
            {
              host: 'www.example-p3.com',
              ttl: -1,
              priority: 3,
              id: 'exampleClusterId'
            }
          ],
          name: 'exampleValid'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      afterEach('unload test url', () => {
        catalog._unloadServiceUrls('preauth', [testUrl]);
      });

      it('gets a valid service object from an existing service', () => {
        const serviceObject = services
          .getServiceFromUrl(testUrlTemplate.defaultUrl);

        assert.isDefined(serviceObject);
        assert.hasAllKeys(serviceObject, ['name', 'defaultUrl', 'priorityUrl']);

        assert.equal(testUrlTemplate.name, serviceObject.name);
        assert.equal(testUrlTemplate.defaultUrl, serviceObject.defaultUrl);
        assert.equal(testUrl.get(true), serviceObject.priorityUrl);
      });

      it('returns undefined when the service url doesn\'t exist', () => {
        const serviceObject = services
          .getServiceFromUrl('http://www.not-real.com/');

        assert.isUndefined(serviceObject);
      });
    });

    describe('#hasService()', () => {
      it('returns a boolean', () => {
        assert.isBoolean(services.hasService('some-url'));
      });

      it('validates that a service exists', () => {
        const service = Object.keys(services.list())[0];

        assert.isTrue(services.hasService(service));
      });
    });

    describe('#initConfig()', () => {
      it('should set the discovery catalog based on the provided links', () => {
        const key = 'test';
        const url = 'http://www.test.com/';

        webex.config.services.discovery[key] = url;

        services.initConfig();

        assert.equal(services.get(key), url);
      });

      it('should set validate domains to true when provided true', () => {
        webex.config.services.validateDomains = true;

        services.initConfig();

        assert.isTrue(services.validateDomains);
      });

      it('should set validate domains to false when provided false', () => {
        webex.config.services.validateDomains = false;

        services.initConfig();

        assert.isFalse(services.validateDomains);
      });

      it('should set the allowed domains based on the provided domains', () => {
        const allowedDomains = ['domain'];

        webex.config.services.allowedDomains = allowedDomains;

        services.initConfig();

        assert.deepEqual(
          allowedDomains,
          services._getCatalog().allowedDomains
        );
      });
    });

    describe('#initialize()', () => {
      it('should create a catalog', () =>
        assert.instanceOf(services._getCatalog(), ServiceCatalog));

      it('should create a registry', () =>
        assert.instanceOf(services.getRegistry(), ServiceRegistry));

      it('should create a state', () =>
        assert.instanceOf(services.getState(), ServiceState));

      it('should call services#initConfig() when webex config changes', () => {
        services.initConfig = sinon.spy();
        services.initialize();
        webex.trigger('change:config');
        assert.called(services.initConfig);
        assert.isTrue(catalog.isReady);
      });

      it('should call services#initServiceCatalogs() on webex ready', () => {
        services.initServiceCatalogs = sinon.stub().resolves();
        services.initialize();
        webex.trigger('ready');
        assert.called(services.initServiceCatalogs);
        assert.isTrue(catalog.isReady);
      });

      it('should collect different catalogs based on OrgId region', () =>
        assert.notDeepEqual(
          services.list(true),
          servicesEU.list(true)
        ));

      it('should not attempt to collect catalogs without authorization', (done) => {
        const otherWebex = new WebexCore();
        let {initServiceCatalogs} = otherWebex.internal.services;

        initServiceCatalogs = sinon.stub();

        setTimeout(() => {
          assert.notCalled(initServiceCatalogs);
          assert.isFalse(otherWebex.internal.services._getCatalog().isReady);
          done();
        }, 2000);
      });
    });

    describe('#initServiceCatalogs()', () => {
      it('should reject if a OrgId cannot be retrieved', () => {
        webex.credentials.getOrgId = sinon.stub().throws();

        return assert.isRejected(services.initServiceCatalogs());
      });

      it('should call services#collectPreauthCatalog with the OrgId', () => {
        services.collectPreauthCatalog = sinon.stub().resolves();

        return services.initServiceCatalogs()
          .then(() =>
            assert.calledWith(services.collectPreauthCatalog, sinon.match({
              orgId: webex.credentials.getOrgId()
            })));
      });

      it('should not call services#updateServices() when not authed', () => {
        services.updateServices = sinon.stub().resolves();

        // Since credentials uses AmpState, we have to set the derived
        // properties of the dependent properties to undefined.
        webex.credentials.supertoken.access_token = undefined;
        webex.credentials.supertoken.refresh_token = undefined;

        webex.credentials.getOrgId = sinon.stub().returns(webexUser.orgId);

        return services.initServiceCatalogs()
          // services#updateServices() gets called once by the limited catalog
          // retrieval and should not be called again when not authorized.
          .then(() => assert.calledOnce(services.updateServices));
      });

      it('should call services#updateServices() when authed', () => {
        services.updateServices = sinon.stub().resolves();

        return services.initServiceCatalogs()
          // services#updateServices() gets called once by the limited catalog
          // retrieval and should get called again when authorized.
          .then(() => assert.calledTwice(services.updateServices));
      });
    });

    describe('#isServiceUrl()', () => {
      let testUrlTemplate;
      let testUrl;

      beforeEach('load test url', () => {
        testUrlTemplate = {
          defaultUrl: 'https://www.example.com/api/v1',
          hosts: [
            {
              homeCluster: true,
              host: 'www.example-p5.com',
              ttl: -1,
              priority: 5,
              id: 'exampleClusterId'
            },
            {
              host: 'www.example-p3.com',
              ttl: -1,
              priority: 3,
              id: 'exampleClusterId'
            }
          ],
          name: 'exampleValid'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      it('returns true if url is a service url', () => {
        assert.isTrue(services.isServiceUrl(testUrlTemplate.defaultUrl));
      });

      it('returns true for priority host urls', () => {
        assert.isTrue(services.isServiceUrl(testUrl.get(true)));
      });

      it('returns undefined if the url doesn\'t exist', () => {
        assert.isFalse(services.isServiceUrl('https://na.com/'));
      });

      it('returns undefined if the param is not a url', () => {
        assert.isFalse(services.isServiceUrl('not a url'));
      });
    });

    describe('#isAllowedDomainUrl()', () => {
      let list;

      beforeEach(() => {
        catalog.setAllowedDomains([
          'some-domain-a',
          'some-domain-b'
        ]);

        list = catalog.getAllowedDomains();
      });

      it('returns a boolean', () => {
        assert.isBoolean(services.isAllowedDomainUrl(''));
      });

      it('returns true if the url contains an allowed domain', () => {
        assert.isTrue(services.isAllowedDomainUrl(`https://${list[0]}/resource`));
      });

      it('returns false if the url does not contain an allowed domain', () => {
        assert.isFalse(services.isAllowedDomainUrl('https://bad-domain/resource'));
      });
    });

    describe('#convertUrlToPriorityUrl', () => {
      let testUrl;
      let testUrlTemplate;

      beforeEach('load test url', () => {
        testUrlTemplate = {
          defaultUrl: 'https://www.example.com/api/v1',
          hosts: [
            {
              homeCluster: true,
              host: 'www.example-p5.com',
              ttl: -1,
              priority: 5,
              id: '0:0:cluster-a:exampleValid'
            },
            {
              host: 'www.example-p3.com',
              ttl: -1,
              priority: 3,
              id: '0:0:cluster-b:exampleValid'
            }
          ],
          name: 'exampleValid'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      it('converts the url to a priority host url', () => {
        const resource = 'path/to/resource';
        const url = `${testUrlTemplate.defaultUrl}/${resource}`;

        const convertUrl = services.convertUrlToPriorityHostUrl(url);

        assert.isDefined(convertUrl);
        assert.isTrue(convertUrl.includes(testUrlTemplate.hosts[0].host));
      });

      it('throws an exception if not a valid service', () => {
        assert.throws(services.convertUrlToPriorityHostUrl, Error);

        assert.throws(
          services.convertUrlToPriorityHostUrl
            .bind(services, 'not-a-valid-service'),
          Error
        );
      });

      afterEach('unload test url', () => {
        catalog._unloadServiceUrls('preauth', [testUrl]);
      });
    });

    describe('#markFailedUrl()', () => {
      let testUrlTemplate;
      let testUrl;

      beforeEach('load test url', () => {
        catalog.clean();

        testUrlTemplate = {
          defaultUrl: 'https://www.example-phr.com/api/v1',
          hosts: [
            {
              host: 'www.example-phr-p5.com',
              ttl: -1,
              priority: 5,
              homeCluster: true
            },
            {
              host: 'www.example-phr-p3.com',
              ttl: -1,
              priority: 3,
              homeCluster: true
            }
          ],
          name: 'exampleValid-phr'
        };
        testUrl = new ServiceUrl({...testUrlTemplate});
        catalog._loadServiceUrls('preauth', [testUrl]);
      });

      afterEach('unload test url', () => {
        catalog._unloadServiceUrls('preauth', [testUrl]);
      });

      it('marks a host as failed', () => {
        const priorityServiceUrl = catalog._getUrl(testUrlTemplate.name);
        const priorityUrl = priorityServiceUrl._getPriorityHostUrl();

        services.markFailedUrl(priorityUrl);

        const failedHost = priorityServiceUrl.hosts.find(
          (host) => host.failed
        );

        assert.isTrue(priorityUrl.includes(failedHost.host));
      });

      it('returns the next priority url', () => {
        const priorityUrl = services.get(testUrlTemplate.name, true);

        const nextPriorityUrl = services.markFailedUrl(priorityUrl);

        assert.notEqual(priorityUrl, nextPriorityUrl);
      });

      it('should reset hosts once all hosts have been marked failed', () => {
        const priorityServiceUrl = catalog._getUrl(testUrlTemplate.name);
        const firstPriorityUrl = priorityServiceUrl._getPriorityHostUrl();

        priorityServiceUrl.hosts.forEach(
          () => {
            const priorityUrl = priorityServiceUrl._getPriorityHostUrl();

            services.markFailedUrl(priorityUrl);
          }
        );

        const lastPriorityUrl = priorityServiceUrl._getPriorityHostUrl();

        assert.equal(firstPriorityUrl, lastPriorityUrl);
      });
    });

    describe('#updateServices()', () => {
      it('returns a Promise that and resolves on success', (done) => {
        const servicesPromise = services.updateServices();

        assert.typeOf(servicesPromise, 'Promise');

        servicesPromise.then(() => {
          Object.keys(services.list()).forEach((key) => {
            assert.typeOf(key, 'string');
            assert.typeOf(services.list()[key], 'string');
          });

          done();
        });
      });

      it('updates the services list', (done) => {
        catalog.serviceGroups.postauth = [];

        services.updateServices()
          .then(() => {
            assert.isAbove(catalog.serviceGroups.postauth.length, 0);
            done();
          });

        services.updateServices();
      });

      it('updates query.email to be emailhash-ed using SHA256', (done) => {
        catalog.updateServiceUrls = sinon.stub().returns({}); // returns `this`
        services._fetchNewServiceHostmap = sinon.stub().resolves();

        services.updateServices({
          from: 'limited',
          query: {email: webexUser.email}
        })
          .then(() => {
            assert.calledWith(
              services._fetchNewServiceHostmap,
              sinon.match.has(
                'query', {emailhash: sinon.match(/\b[A-Fa-f0-9]{64}\b/)}
              )
            );
            done();
          });
      });

      it('updates the limited catalog when email is provided', (done) => {
        catalog.serviceGroups.preauth = [];

        services.updateServices({
          from: 'limited',
          query: {email: webexUser.email}
        })
          .then(() => {
            assert.isAbove(catalog.serviceGroups.preauth.length, 0);
            done();
          });
      });

      it('updates the limited catalog when userId is provided', (done) => {
        catalog.serviceGroups.preauth = [];

        services.updateServices({
          from: 'limited',
          query: {userId: webexUser.id}
        })
          .then(() => {
            assert.isAbove(catalog.serviceGroups.preauth.length, 0);
            done();
          });
      });

      it('updates the limited catalog when orgId is provided', (done) => {
        catalog.serviceGroups.preauth = [];

        services.updateServices({
          from: 'limited',
          query: {orgId: webexUser.orgId}
        })
          .then(() => {
            assert.isAbove(catalog.serviceGroups.preauth.length, 0);
            done();
          });
      });
      it('updates the limited catalog when query param mode is provided', (done) => {
        catalog.serviceGroups.preauth = [];

        services.updateServices({
          from: 'limited',
          query: {mode: 'DEFAULT_BY_PROXIMITY'}
        })
          .then(() => {
            assert.isAbove(catalog.serviceGroups.preauth.length, 0);
            done();
          });
      });
      it('does not update the limited catalog when nothing is provided', () => {
        catalog.serviceGroups.preauth = [];

        return services.updateServices({from: 'limited'})
          .then(() => {
            assert(false, 'resolved, should have thrown');
          })
          .catch(() => {
            assert(true);
          });
      });
    });

    describe('#validateUser()', () => {
      const unauthWebex = new WebexCore();
      const unauthServices = unauthWebex.internal.services;

      it('returns a rejected promise when no email is specified', () => unauthServices.validateUser({})
        .then(() => {
          assert(false, 'resolved, should have thrown');
        })
        .catch(() => {
          assert(true);
        }));

      it('validates an authorized user and webex instance', () => services.validateUser({email: webexUser.email})
        .then((r) => {
          assert.hasAllKeys(r, ['activated', 'exists', 'user', 'details']);
          assert.equal(r.activated, true);
          assert.equal(r.exists, true);
        }));

      it('validates an authorized EU user and webex instance', () => servicesEU.validateUser({email: webexUserEU.email})
        .then((r) => {
          assert.hasAllKeys(r, ['activated', 'exists', 'user', 'details']);
          assert.equal(r.activated, true);
          assert.equal(r.exists, true);
        }));

      it('returns a rejected promise if the provided email isn\'t valid', () => unauthServices.validateUser({email: 'not an email'})
        .then(() => {
          assert(false, 'resolved, should have thrown');
        })
        .catch(() => {
          assert(true);
        }));

      it('validates a non-existing user', () => unauthServices.validateUser({email: `Collabctg+webex-js-sdk-${uuid.v4()}@gmail.com`})
        .then((r) => {
          assert.hasAllKeys(r, ['activated', 'exists', 'user', 'details']);
          assert.equal(r.activated, false);
          assert.equal(r.exists, false);
          assert.isAbove(Object.keys(unauthServices.list(false, 'preauth')).length, 0);
          assert.equal(Object.keys(unauthServices.list(false, 'signin')).length, 0);
          assert.equal(Object.keys(unauthServices.list(false, 'postauth')).length, 0);
        }));

      it('validates an inactive user', () => {
        // This will be changed to utilize a new test user generation
        // method that can create a user without activating it. Currently,
        // this will throw an error if too many requests to Atlas are triggered
        // to send activation emails. A solution was to append a `skipEmail`
        // parameter key to allow bypassing the email request when necessary.
        const inactive = 'webex.web.client+nonactivated@gmail.com';

        return unauthServices.validateUser({email: inactive, skipEmail: true})
          .then((r) => {
            assert.hasAllKeys(r, ['activated', 'exists', 'user', 'details']);
            assert.equal(r.activated, false, 'activated');
            assert.equal(r.exists, true, 'exists');
            assert.isAbove(Object.keys(unauthServices.list(false, 'preauth')).length, 0);
            assert.equal(Object.keys(unauthServices.list(false, 'signin')).length, 0);
            assert.equal(Object.keys(unauthServices.list(false, 'postauth')).length, 0);
          }).catch(() => {
            assert(true);
          });
      });

      it('validates an existing user', () => unauthServices.validateUser({email: webexUser.email})
        .then((r) => {
          assert.hasAllKeys(r, ['activated', 'exists', 'user', 'details']);
          assert.equal(r.activated, true);
          assert.equal(r.exists, true);
          assert.isAbove(Object.keys(unauthServices.list(false, 'preauth')).length, 0);
          assert.isAbove(Object.keys(unauthServices.list(false, 'signin')).length, 0);
          assert.equal(Object.keys(unauthServices.list(false, 'postauth')).length, 0);
        }));

      it('validates an existing EU user', () => unauthServices.validateUser({email: webexUserEU.email})
        .then((r) => {
          assert.hasAllKeys(r, ['activated', 'exists', 'user', 'details']);
          assert.equal(r.activated, true);
          assert.equal(r.exists, true);
          assert.isAbove(Object.keys(unauthServices.list(false, 'preauth')).length, 0);
          assert.isAbove(Object.keys(unauthServices.list(false, 'signin')).length, 0);
          assert.equal(Object.keys(unauthServices.list(false, 'postauth')).length, 0);
        }));
    });

    describe('#waitForService()', () => {
      let name;
      let url;

      describe('when the service exists', () => {
        beforeEach('collect valid service info', () => {
          name = Object.keys(services.list())[0];
          url = services.list(true)[name];
        });

        describe('when using the name parameter property', () => {
          it('should resolve to the appropriate url', () =>
            services.waitForService({name})
              .then((foundUrl) => assert.equal(foundUrl, url)));
        });

        describe('when using the url parameter property', () => {
          it('should resolve to the appropriate url', () =>
            services.waitForService({url})
              .then((foundUrl) => assert.equal(foundUrl, url)));
        });

        describe('when using the url and name parameter properties', () => {
          it('should resolve to the appropriate url', () =>
            services.waitForService({name, url})
              .then((foundUrl) => assert.equal(foundUrl, url)));
        });
      });

      describe('when the service does not exist', () => {
        let timeout;

        beforeEach('set up the parameters', () => {
          name = 'not a service';
          url = 'http://not-a-service.com/resource';
          timeout = 1;
        });

        describe('when using the url parameter property', () => {
          it('should return a resolve promise', () =>
          // const waitForService = services.waitForService({url, timeout});

            services.waitForService({url, timeout}).then((foundUrl) => {
              assert.equal(foundUrl, url);
              assert.isTrue(catalog.isReady);
            }));
        });

        describe('when using the name parameter property', () => {
          it('should return a rejected promise', () => {
            const waitForService = services.waitForService({name, timeout});

            assert.isRejected(waitForService);
            assert.isTrue(catalog.isReady);
          });
        });

        describe('when using the name and url parameter properties', () => {
          it('should return a rejected promise', () => {
            const waitForService = services.waitForService({
              name, url, timeout
            });

            assert.isRejected(waitForService);
            assert.isTrue(catalog.isReady);
          });
        });

        describe('when the service will exist', () => {
          beforeEach('collect existing service and clear the catalog', () => {
            name = 'feature';
            url = services.get(name, true);
            catalog.clean();
            catalog.isReady = false;
          });

          describe('when using the name parameter property', () => {
            it('should resolve to the appropriate url', () =>
              Promise.all([
                services.waitForService({name}),
                services.initServiceCatalogs()
              ])
                .then(([foundUrl]) => assert.equal(foundUrl, url)));
          });

          describe('when using the url parameter property', () => {
            it('should resolve to the appropriate url', () =>
              Promise.all([
                services.waitForService({url}),
                services.initServiceCatalogs()
              ])
                .then(([foundUrl]) => assert.equal(foundUrl, url)));
          });

          describe('when using the name and url parameter property', () => {
            it('should resolve to the appropriate url', () =>
              Promise.all([
                services.waitForService({name, url}),
                services.initServiceCatalogs()
              ])
                .then(([foundUrl]) => assert.equal(foundUrl, url)));
          });
        });
      });
    });

    describe('#collectPreauthCatalog()', () => {
      const unauthWebex = new WebexCore({config: {credentials: {federation: true}}});
      const unauthServices = unauthWebex.internal.services;

      it('updates the preauth catalog without email', () => unauthServices.collectPreauthCatalog()
        .then(() => {
          assert.isAbove(Object.keys(unauthServices.list()).length, 0);
        }));

      it('updates the preauth catalog with email', () => unauthServices.collectPreauthCatalog({email: webexUser.email})
        .then(() => {
          assert.isAbove(Object.keys(unauthServices.list()).length, 0);
        }));
    });

    describe('#collectSigninCatalog()', () => {
      const unauthWebex = new WebexCore({config: {credentials: {federation: true}}});
      const unauthServices = unauthWebex.internal.services;

      it('requires an email as the parameter', () => unauthServices.collectPreauthCatalog()
        .catch((e) => {
          assert(true, e);
        }));

      it('requires a token as the parameter', () => unauthServices.collectPreauthCatalog({email: 'email@website.com'})
        .catch((e) => {
          assert(true, e);
        }));

      it('updates the preauth catalog', () => unauthServices.collectPreauthCatalog({email: webexUser.email})
        .then(() => {
          assert.isAbove(Object.keys(unauthServices.list()).length, 0);
        }));
    });

    flaky(describe, process.env.SKIP_FLAKY_TESTS)('#_fetchNewServiceHostmap()', () => {
      let fullRemoteHM;
      let limitedRemoteHM;

      before('collect remote catalogs', () => Promise.all([
        services._fetchNewServiceHostmap(),
        services._fetchNewServiceHostmap({
          from: 'limited',
          query: {userId: webexUser.id}
        })
      ])
        .then(([fRHM, lRHM]) => {
          fullRemoteHM = fRHM;
          limitedRemoteHM = lRHM;
        }));

      it('resolves to an authed u2c hostmap when no params specified', () => {
        assert.typeOf(fullRemoteHM, 'array');
        assert.isAbove(fullRemoteHM.length, 0);
      });

      it('resolves to a limited u2c hostmap when params specified', () => {
        assert.typeOf(limitedRemoteHM, 'array');
        assert.isAbove(limitedRemoteHM.length, 0);
      });

      it('rejects if the params provided are invalid', () => (
        services._fetchNewServiceHostmap({
          from: 'limited',
          query: {userId: 'notValid'}
        })
          .then(() => {
            assert.isTrue(false, 'should have rejected');
          })
          .catch((e) => {
            assert.typeOf(e, 'Error');
          })
      ));
    });
  });
});
/* eslint-enable no-underscore-dangle */


text:
"""Interface for controlling a browser that runs Neuroglancer."""

from typing import Sequence, Optional

import tempfile
import time
import threading

class Webdriver:
    def __init__(self,
                 viewer=None,
                 headless=True,
                 browser='chrome',
                 window_size=(1920, 1080),
                 debug=False,
                 docker=False,
                 print_logs=True,
                 extra_command_line_args: Optional[Sequence[str]] = None):
        if viewer is None:
            from .viewer import Viewer
            viewer = Viewer()
        self.viewer = viewer
        self.headless = headless
        self.browser = browser
        self.window_size = window_size
        self.headless = headless
        self.docker = docker
        self.extra_command_line_args = list(extra_command_line_args) if extra_command_line_args else []
        self.debug = debug
        self._logfile = None
        if browser == 'firefox':
            self._logfile = tempfile.NamedTemporaryFile(suffix='neuroglancer-geckodriver.log')
        self._init_driver()
        self._pending_logs = []
        self._pending_logs_to_print = []
        self._logs_lock = threading.Lock()
        self._closed = False

        def print_log_handler():
            while True:
                logs_to_print = self._get_logs_to_print()
                if logs_to_print:
                    print('\n'.join(x['message'] for x in logs_to_print))
                if self._closed:
                    break
                time.sleep(1)

        t = threading.Thread(target=print_log_handler)
        t.daemon = True
        t.start()

    def _init_chrome(self):
        import selenium.webdriver
        import selenium.webdriver.chrome.options
        import selenium.webdriver.common.service
        import selenium.webdriver.chrome.service

        def patched_init(self, executable_path, port=0, service_args=None, log_path=None, env=None):
            log_path = '/dev/stderr'
            self.service_args = service_args or []
            if log_path:
                self.service_args.append('--log-path=%s' % log_path)
            selenium.webdriver.common.service.Service.__init__(
                self,
                executable_path,
                port=port,
                env=env,
                log_file=None,
                start_error_message=
                "Please see https://sites.google.com/a/chromium.org/chromedriver/home")

        import selenium.webdriver.common.desired_capabilities
        executable_path = 'chromedriver'
        try:
            # Use webdriver_manager package if available
            import webdriver_manager.chrome
            import webdriver_manager.core.utils
            chrome_version = None
            chrome_types = (webdriver_manager.core.utils.ChromeType.GOOGLE,
                            webdriver_manager.core.utils.ChromeType.CHROMIUM)
            for chrome_type in chrome_types:
                try:
                    chrome_version = webdriver_manager.core.utils.get_browser_version_from_os(chrome_type)
                    if chrome_version is not None:
                        break
                except:
                    if chrome_type == chrome_types[-1]:
                        raise

            executable_path = webdriver_manager.chrome.ChromeDriverManager(
                chrome_type=chrome_type).install()
        except ImportError:
            # Fallback to system chromedriver
            pass
        chrome_options = selenium.webdriver.chrome.options.Options()
        if self.headless:
            chrome_options.add_argument('--headless')
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
        if self.docker:
            # https://www.intricatecloud.io/2019/05/running-webdriverio-tests-using-headless-chrome-inside-a-container/
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--disable-gpu')
            chrome_options.add_argument('--disable-setuid-sandbox')
            chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--window_size=%dx%d' %
                                    (self.window_size[0], self.window_size[1]))
        for arg in self.extra_command_line_args:
            chrome_options.add_argument(arg)
        caps = selenium.webdriver.common.desired_capabilities.DesiredCapabilities.CHROME.copy()
        caps['goog:loggingPrefs'] = {'browser': 'ALL'}
        try:
            orig_init = selenium.webdriver.chrome.service.Service.__init__
            if self.debug:
                selenium.webdriver.chrome.service.Service.__init__ = patched_init
            self.driver = selenium.webdriver.Chrome(executable_path=executable_path,
                                                    options=chrome_options,
                                                    desired_capabilities=caps)
        finally:
            if self.debug:
                selenium.webdriver.chrome.service.Service.__init__ = orig_init

    def _init_firefox(self):
        import selenium.webdriver
        import selenium.webdriver.firefox.firefox_binary
        executable_path = 'geckodriver'
        try:
            # Use webdriver_manager package if available
            import webdriver_manager.firefox
            executable_path = webdriver_manager.firefox.GeckoDriverManager().install()
        except (ImportError, SyntaxError):
            # Fallback to system geckodriver
            pass
        profile = selenium.webdriver.FirefoxProfile()
        profile.set_preference('devtools.console.stdout.content', True)
        binary = selenium.webdriver.firefox.firefox_binary.FirefoxBinary()
        for arg in self.extra_command_line_args:
            binary.add_command_line_options(arg)
        self.driver = selenium.webdriver.Firefox(firefox_profile=profile,
                                                 executable_path=executable_path,
                                                 firefox_binary=binary,
                                                 service_log_path=self._logfile.name)

    def _init_driver(self):
        if self.browser == 'chrome':
            self._init_chrome()
        elif self.browser == 'firefox':
            self._init_firefox()
        else:
            raise ValueError('unsupported browser: %s, must be "chrome" or "firefox"' %
                             (self.browser, ))
        self.driver.get(self.viewer.get_viewer_url())

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self._logfile is not None:
            self._logfile.file.close()
            self._logfile = None
        self.driver.quit()
        self._closed = True

    def _get_new_logs(self):
        if self.browser == 'chrome':
            new_logs = self.driver.get_log('browser')
        else:
            cur_offset = self._logfile.file.tell()
            new_data = self._logfile.file.read()
            # rfind may return -1, still works
            end_within_data = new_data.rfind(b'\n') + 1
            new_data = new_data[:end_within_data]
            self._logfile.file.seek(cur_offset + end_within_data)
            new_logs = []
            for msg in new_data.decode().split('\n'):
                msg = msg.strip()
                if not msg: continue
                if (not msg.startswith('console.log: ') and not msg.startswith('JavaScript ')):
                    continue
                new_logs.append({'message': msg})
        self._pending_logs.extend(new_logs)
        self._pending_logs_to_print.extend(new_logs)

    def _get_logs_to_print(self):
        with self._logs_lock:
            self._get_new_logs()
            new_logs = self._pending_logs_to_print
            self._pending_logs_to_print = []
            return new_logs

    def get_log(self):
        with self._logs_lock:
            self._get_new_logs()
            new_logs = self._pending_logs
            self._pending_logs = []
            return new_logs

    def get_log_messages(self):
        return '\n'.join(x['message'] for x in self.get_log())

    def sync(self):
        """Wait until client is ready."""
        while True:
            new_state = self.viewer.screenshot().viewer_state
            # Ensure self.viewer.state has also been updated to the new state.
            # The state sent in the screenshot reply can be newer.
            if new_state == self.viewer.state:
                return new_state
            time.sleep(0.1)

    def reload_browser(self):
        """Reloads the browser (useful if it crashes/becomes unresponsive)."""
        with self._logs_lock:
            try:
                self.driver.quit()
            except:
                pass
            self._init_driver()

    @property
    def root_element(self):
        return self.driver.find_element('xpath', '//body')

    def action_chain(self):
        import selenium.webdriver
        return selenium.webdriver.common.action_chains.ActionChains(self.driver)


text:
long hPrevWndProc;

int ShowMsgBox (OO_MSGBOXDATA *mbData)
{
	WNDCLASS wc;
	HWND hwnd;
	MSG msg;

	wc.style = 0;                                   // Class style
	wc.lpfnWndProc = (WNDPROC) WndProcMsg;		// window procedure address
	wc.cbClsExtra = 0;						// class extra bytes
	wc.cbWndExtra = 0;						// window extra bytes
	wc.hInstance  = (HINSTANCE) GetWindowLong(mbData->hwndParent, GWL_HINSTANCE);				// instance handler
	wc.hIcon = LoadIcon(NULL, IDI_ASTERISK); // icon handler
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);	// cursor handle
	wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);	// background color
	wc.lpszMenuName = NULL;		// menu name
	wc.lpszClassName = "SinOMsgBoxWndClass";		// WNDCLASS name

	RegisterClass (&wc);

	hwnd = CreateWindowEx(
		WS_EX_TOOLWINDOW,
		"SinOMsgBoxWndClass",			// WNDCLASS name
		"",		// Window title
		WS_OVERLAPPED | WS_SYSMENU,	// Window Style
		CW_USEDEFAULT,			// Horizontal position
		CW_USEDEFAULT,			// Vertical position
		CW_USEDEFAULT,			// Initial Width
		CW_USEDEFAULT,			// Initial Height
		mbData->hwndParent,			// Handle of parent window
		NULL,					// Menu Handle
		(HINSTANCE) GetWindowLong(mbData->hwndParent, GWL_HINSTANCE),				// Application Instance handle
		(void *)mbData					// Window creation data
		);

	PosToMiddle(hwnd);
	EnableWindow(mbData->hwndParent, false);
	ShowWindow (hwnd, SW_SHOW);
	UpdateWindow (hwnd);

	while  ( GetMessage (&msg, NULL, 0, 0) )
	{
		TranslateMessage (&msg);
		DispatchMessage(&msg);
	}

	EnableWindow(mbData->hwndParent, true);
	SetFocus(mbData->hwndParent);

	return (int) msg.wParam;
}

LRESULT CALLBACK WndProcMsg (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;
	static SIZE size;
	static int ixIcon, iyIcon;
	static int iWidth, iHeight;
	static HWND hwndButton1, hwndButton2;

	static OO_MSGBOXDATA *mbData;
	static int retVal = 0;

	switch (message)
	{
	case WM_CREATE:
		mbData = (OO_MSGBOXDATA *) ((CREATESTRUCT *) lParam)->lpCreateParams;
		hdc = GetDC(hwnd);
		SelectObject(hdc, hSinFontMe);
		GetTextExtentPoint32(hdc, mbData->MsgStr, strlen(mbData->MsgStr), &size);
		ReleaseDC(hwnd, hdc);

		ixIcon = GetSystemMetrics(SM_CXICON);
		iyIcon = GetSystemMetrics(SM_CYICON);

		iWidth  = MSG_SPCITEMSX + ixIcon + MSG_SPCITEMSX + size.cx + MSG_SPCITEMSX ;
		iHeight = MSG_SPCITEMSY + iyIcon + MSG_SPCITEMSY + MSG_OK_Y + MSG_SPCITEMSY;

		iWidth  = max(iWidth, (MSG_SPCITEMSX + ixIcon + MSG_OK_X + MSG_SPCITEMSX));
		iHeight = max(iHeight,(MSG_SPCITEMSY + iyIcon + MSG_SPCITEMSY +  MSG_SPCITEMSY));

		SetWindowPos(hwnd, HWND_TOPMOST, 250, 250, iWidth, iHeight, 0);

		if (mbData->msgBoxType & MB_ONEBUTTON)
		{
			hwndButton1 = CreateWindow("BUTTON",
				mbData->butText1,
				WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
				(iWidth - MSG_OK_X) / 2,
				MSG_SPCITEMSY + iyIcon + 5,
				MSG_OK_X,
				MSG_OK_Y,
				hwnd,
				(HMENU) BUT_ONE,
				(HINSTANCE) GetWindowLong(mbData->hwndParent, GWL_HINSTANCE),
				NULL);
		}
		else
		{
			if (mbData->msgBoxType & MB_TWOBUTTON)
			{
				hwndButton1 = CreateWindow("BUTTON",
					mbData->butText1,
					WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
					((iWidth - MSG_OK_X) / 2) - (MSG_OK_X/ 2) - 5,
					MSG_SPCITEMSY + iyIcon + 5,
					MSG_OK_X,
					MSG_OK_Y,
					hwnd,
					(HMENU) BUT_ONE,
					(HINSTANCE) GetWindowLong(mbData->hwndParent, GWL_HINSTANCE),
					NULL);

				hwndButton2 = CreateWindow("BUTTON",
					mbData->butText2,
					WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
					((iWidth - MSG_OK_X) / 2) + (MSG_OK_X/2) + 5,
					MSG_SPCITEMSY + iyIcon + 5,
					MSG_OK_X,
					MSG_OK_Y,
					hwnd,
					(HMENU) BUT_TWO,
					(HINSTANCE) GetWindowLong(mbData->hwndParent, GWL_HINSTANCE),
					NULL);

			}
			else
				MessageBox(0,"Error!","", 0);
		}

		//SetSinhalaFont to button
		SendMessage(hwndButton1, WM_SETFONT, (WPARAM)hSinFontSm, MAKELPARAM(true, 0));
		SendMessage(hwndButton2, WM_SETFONT, (WPARAM)hSinFontSm, MAKELPARAM(true, 0));

		MessageBeep(MB_ICONEXCLAMATION);
		SetFocus(hwnd);
		return 0;

	case WM_PAINT:

		hdc = BeginPaint(hwnd, &ps);
		SetBkMode(hdc, TRANSPARENT);
		SetTextColor(hdc, GetSysColor(COLOR_BTNTEXT));
		SelectObject(hdc, hSinFontSm);

		if (mbData->msgBoxType & MBIT_EXCLAMATION)
			DrawIcon(hdc, MSG_SPCITEMSX, MSG_SPCITEMSY, LoadIcon(NULL, IDI_EXCLAMATION));
		else
		{
			if (mbData->msgBoxType & MBIT_QUESTION)
				DrawIcon(hdc, MSG_SPCITEMSX, MSG_SPCITEMSY, LoadIcon(NULL, IDI_QUESTION));
			else
				if (mbData->msgBoxType & MBIT_INFORMATION)
					DrawIcon(hdc, MSG_SPCITEMSX, MSG_SPCITEMSY, LoadIcon(NULL, IDI_INFORMATION));
		}

		TextOut(hdc,
			MSG_SPCITEMSX + ixIcon + MSG_SPCITEMSX,
			MSG_SPCITEMSY,
			mbData->MsgStr,
			strlen(mbData->MsgStr));

		EndPaint (hwnd, &ps);
		return 0;

	case WM_NCPAINT:
	case WM_NCACTIVATE:
		DefWindowProc(hwnd, message, wParam, lParam);
		hdc = GetWindowDC(hwnd);
		SetTextColor(hdc, GetSysColor(COLOR_CAPTIONTEXT));
		SetBkMode(hdc, TRANSPARENT);
		SelectObject(hdc, hSinFontSm);
		TextOut(hdc, 5,1, mbData->Title, strlen(mbData->Title));
		ReleaseDC(hwnd, hdc);
		return 0;

	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case BUT_ONE:
			retVal = 0;
			break;

		case BUT_TWO:
			retVal = 1;
			break;
		}
		DestroyWindow(hwnd);
		return 0;

	case WM_KEYUP:
		switch(wParam)
		{
		case VK_ESCAPE:
			if (mbData->msgBoxType & MB_TWOBUTTON)
				SendMessage(hwnd, WM_COMMAND, MAKEWPARAM(BUT_TWO, 0), 0);
			break;

		case VK_RETURN:
			SendMessage(hwnd, WM_COMMAND, MAKEWPARAM(BUT_ONE, 0), 0);
			break;
		}
		return 0;

	case WM_DESTROY:
		PostQuitMessage(retVal);
		return 0;
	}

	return DefWindowProc (hwnd, message, wParam, lParam);
}


text:
Update a model in the services layer.

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

## Usage

Model.update(id, [success], [failure])

### Params

| Param           | Type          | Details                          |
| --------------- | ------------- | -------------------------------- |
| id              | `number`      | The ID.                          |
| success         | `Function`    | The success callback.            |
| failure         | `Function`    | The failure callback.            |

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

## Example

**index.html**

	<html>
		<body>
			<script src="scripts/leaf.min.js"></script>
			<script>
				var Person = new leaf.Model();

				Person.url = 'api/people';

				Person.fetch(1, function() {
					Person.set('lastName', 'Doe');

					Person.update(1, function() {
						console.log('The model was updated.');
					});
				});
			</script>
		</body>
	</html>


text:
var socket = io();

var n = nunchuck.init('player', socket);

n.onJoin(function(data, err){
  if (!err){
    bounceIn('controller');
    bounceOut('join');
  } else {
    alert(err.msg)
  }
});

function bounceOut(id){
  $('#' + id)
      .removeClass('animate bounceIn')
      .addClass('animate bounceOut')
      .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
        $(this)
            .css('display', 'none')
            .removeClass('animate bounceOut');
        });
}

function join(){
  n.join($('#username').val(), $('#roomId').val());
}

function bounceIn(id){
  $('#' + id)
      .addClass('animate bounceIn')
      .css('display', 'block');
}


text:
package email.extractor;

import org.apache.poi.hsmf.MAPIMessage;

public class ApacheMsgHeaders
{
	public static void main(String[] args) throws Exception
	{
		MAPIMessage msg = new MAPIMessage("data/message.msg");

		System.out.println("From: " + msg.getDisplayFrom());
		System.out.println("To: " + msg.getDisplayTo());
		System.out.println("CC: " + msg.getDisplayCC());
		System.out.println("BCC: " + msg.getDisplayBCC());
		System.out.println("Subject: " + msg.getSubject());
	}
}


text:
"use strict";
import Symbols from "./symbol";
import { FactSet, Facts, FactKind, Rules, Rule, Response, Line, Actors, Actor } from "./ruler";

var actors = new Actors();
var concept = new Actor("f()");
var jack = new Actor("jack");
var femme = new Actor("femme");
var au = new Actor("Au");
var world = new Actor("world");
actors.add(jack).add(femme).add(au).add(world);

var factset = new FactSet();
var facts = new Facts(concept, FactKind.EventParams)
facts.add("E", 55).add("F", 66).add("A", 11).add("D", 44);
factset.add(facts);
//
facts = new Facts(jack, FactKind.State).add("B", 22).add("G", 77);
factset.add(facts);
//
facts = new Facts(jack, FactKind.Memory).add("m.B", 22).add("m.G", 77);
factset.add(facts);
//
facts = new Facts(world).add("w.B", 22).add("w.G", 77);
factset.add(facts);

var rules = new Rules("Rules for some dialog");
rules.add(new Rule(femme)
    .eq("G", 77).eq("A", 11).eq("B", 22)
    .response(new Response().add(new Line("dummy line")))
);
rules.add(new Rule(jack)
    .eq("B", 22).eq("E", 55).eq("A", 11).eq("G", 77)
    .response(new Response()
        .add(new Line("Il était une fois dans l'ouest").then(jack, "concept"))
        .add(new Line("Il était une fois dans l'est")))
    .remember("B", 42)
    .trigger(femme, "concept")
);

var matchingRule = rules.findMatchingRule(factset);
matchingRule.execute(factset, actors);

console.log( matchingRule );


text:
export default (function() {
  var localStorageMock = (function() {
    var store = {};

    return {
      getItem: function(key) {
        return store[key] || null;
      },
      setItem: function(key, value) {
        store[key] = value.toString();
      },
      clear: function() {
        store = {};
      }
    };
  })();

  Object.defineProperty(window, "localStorage", {
    value: localStorageMock
  });
})();


text:
#ifndef __ARM_KVM_HOST_H__
#define __ARM_KVM_HOST_H__

#include <asm/kvm.h>
#include <asm/kvm_asm.h>
#include <asm/kvm_mmio.h>
#include <asm/fpstate.h>
#include <asm/kvm_arch_timer.h>

#define KVM_MAX_VCPUS CONFIG_KVM_ARM_MAX_VCPUS
#define KVM_USER_MEM_SLOTS 32
#define KVM_PRIVATE_MEM_SLOTS 4
#define KVM_COALESCED_MMIO_PAGE_OFFSET 1
#define KVM_HAVE_ONE_REG

#define KVM_VCPU_MAX_FEATURES 1

/* We don't currently support large pages. */
#define KVM_HPAGE_GFN_SHIFT(x)	0
#define KVM_NR_PAGE_SIZES	1
#define KVM_PAGES_PER_HPAGE(x)	(1UL<<31)

#include <asm/kvm_vgic.h>

struct kvm_vcpu;
u32 *kvm_vcpu_reg(struct kvm_vcpu *vcpu, u8 reg_num, u32 mode);
int kvm_target_cpu(void);
int kvm_reset_vcpu(struct kvm_vcpu *vcpu);
void kvm_reset_coprocs(struct kvm_vcpu *vcpu);

struct kvm_arch {
	/* VTTBR value associated with below pgd and vmid */
	u64    vttbr;

	/* Timer */
	struct arch_timer_kvm	timer;

	/*
	 * Anything that is not used directly from assembly code goes
	 * here.
	 */

	/* The VMID generation used for the virt. memory system */
	u64    vmid_gen;
	u32    vmid;

	/* Stage-2 page table */
	pgd_t *pgd;

	/* Interrupt controller */
	struct vgic_dist	vgic;
};

#define KVM_NR_MEM_OBJS     40

/*
 * We don't want allocation failures within the mmu code, so we preallocate
 * enough memory for a single page fault in a cache.
 */
struct kvm_mmu_memory_cache {
	int nobjs;
	void *objects[KVM_NR_MEM_OBJS];
};

struct kvm_vcpu_fault_info {
	u32 hsr;		/* Hyp Syndrome Register */
	u32 hxfar;		/* Hyp Data/Inst. Fault Address Register */
	u32 hpfar;		/* Hyp IPA Fault Address Register */
	u32 hyp_pc;		/* PC when exception was taken from Hyp mode */
};

typedef struct vfp_hard_struct kvm_cpu_context_t;

struct kvm_vcpu_arch {
	struct kvm_regs regs;

	int target; /* Processor target */
	DECLARE_BITMAP(features, KVM_VCPU_MAX_FEATURES);

	/* System control coprocessor (cp15) */
	u32 cp15[NR_CP15_REGS];

	/* The CPU type we expose to the VM */
	u32 midr;

	/* Exception Information */
	struct kvm_vcpu_fault_info fault;

	/* Floating point registers (VFP and Advanced SIMD/NEON) */
	struct vfp_hard_struct vfp_guest;

	/* Host FP context */
	kvm_cpu_context_t *host_cpu_context;

	/* VGIC state */
	struct vgic_cpu vgic_cpu;
	struct arch_timer_cpu timer_cpu;

	/*
	 * Anything that is not used directly from assembly code goes
	 * here.
	 */
	/* dcache set/way operation pending */
	int last_pcpu;
	cpumask_t require_dcache_flush;

	/* Don't run the guest on this vcpu */
	bool pause;

	/* IO related fields */
	struct kvm_decode mmio_decode;

	/* Interrupt related fields */
	u32 irq_lines;		/* IRQ and FIQ levels */

	/* Cache some mmu pages needed inside spinlock regions */
	struct kvm_mmu_memory_cache mmu_page_cache;

	/* Detect first run of a vcpu */
	bool has_run_once;
};

struct kvm_vm_stat {
	u32 remote_tlb_flush;
};

struct kvm_vcpu_stat {
	u32 halt_wakeup;
};

struct kvm_vcpu_init;
int kvm_vcpu_set_target(struct kvm_vcpu *vcpu,
			const struct kvm_vcpu_init *init);
unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu);
int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *indices);
struct kvm_one_reg;
int kvm_arm_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg);
int kvm_arm_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg);
u64 kvm_call_hyp(void *hypfn, ...);
void force_vm_exit(const cpumask_t *mask);

#define KVM_ARCH_WANT_MMU_NOTIFIER
struct kvm;
int kvm_unmap_hva(struct kvm *kvm, unsigned long hva);
int kvm_unmap_hva_range(struct kvm *kvm,
			unsigned long start, unsigned long end);
void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte);

unsigned long kvm_arm_num_regs(struct kvm_vcpu *vcpu);
int kvm_arm_copy_reg_indices(struct kvm_vcpu *vcpu, u64 __user *indices);

/* We do not have shadow page tables, hence the empty hooks */
static inline int kvm_age_hva(struct kvm *kvm, unsigned long hva)
{
	return 0;
}

static inline int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
{
	return 0;
}

struct kvm_vcpu *kvm_arm_get_running_vcpu(void);
struct kvm_vcpu __percpu **kvm_get_running_vcpus(void);

int kvm_arm_copy_coproc_indices(struct kvm_vcpu *vcpu, u64 __user *uindices);
unsigned long kvm_arm_num_coproc_regs(struct kvm_vcpu *vcpu);
struct kvm_one_reg;
int kvm_arm_coproc_get_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *);
int kvm_arm_coproc_set_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *);

int handle_exit(struct kvm_vcpu *vcpu, struct kvm_run *run,
		int exception_index);

static inline void __cpu_init_hyp_mode(unsigned long long boot_pgd_ptr,
				       unsigned long long pgd_ptr,
				       unsigned long hyp_stack_ptr,
				       unsigned long vector_ptr)
{
	/*
	 * Call initialization code, and switch to the full blown HYP
	 * code. The init code doesn't need to preserve these
	 * registers as r0-r3 are already callee saved according to
	 * the AAPCS.
	 * Note that we slightly misuse the prototype by casing the
	 * stack pointer to a void *.
	 *
	 * We don't have enough registers to perform the full init in
	 * one go.  Install the boot PGD first, and then install the
	 * runtime PGD, stack pointer and vectors. The PGDs are always
	 * passed as the third argument, in order to be passed into
	 * r2-r3 to the init code (yes, this is compliant with the
	 * PCS!).
	 */

	kvm_call_hyp(NULL, 0, boot_pgd_ptr);

	kvm_call_hyp((void*)hyp_stack_ptr, vector_ptr, pgd_ptr);
}

static inline int kvm_arch_dev_ioctl_check_extension(long ext)
{
	return 0;
}

int kvm_perf_init(void);
int kvm_perf_teardown(void);

#endif /* __ARM_KVM_HOST_H__ */


text:
<?php
global $yoast_ga_admin;

echo $yoast_ga_admin->content_head();
?>

<?php echo __( 'Yoast Google Analytics: Extensions', 'google-analytics-for-wordpress' ); ?>

Google Analytics
E-Commerce tracking

Track your E-Commerce data and transactions with this E-Commerce extension for Google Analytics.

					Get this extension

<?php
echo $yoast_ga_admin->content_footer();
?>


text:
package org.elasticsearch.xpack.core.ml.action;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xpack.core.ml.job.config.Job;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;

import java.io.IOException;
import java.util.Objects;

public class DeleteJobAction extends ActionType<AcknowledgedResponse> {

    public static final DeleteJobAction INSTANCE = new DeleteJobAction();
    public static final String NAME = "cluster:admin/xpack/ml/job/delete";
    public static final String DELETION_TASK_DESCRIPTION_PREFIX = "delete-job-";

    private DeleteJobAction() {
        super(NAME, AcknowledgedResponse::readFrom);
    }

    public static class Request extends AcknowledgedRequest<Request> {

        private String jobId;
        private boolean force;

        /**
         * Should this task store its result?
         */
        private boolean shouldStoreResult;

        public Request(String jobId) {
            this.jobId = ExceptionsHelper.requireNonNull(jobId, Job.ID.getPreferredName());
        }

        public Request(StreamInput in) throws IOException {
            super(in);
            jobId = in.readString();
            force = in.readBoolean();
        }

        public String getJobId() {
            return jobId;
        }

        public void setJobId(String jobId) {
            this.jobId = jobId;
        }

        public boolean isForce() {
            return force;
        }

        public void setForce(boolean force) {
            this.force = force;
        }

        /**
         * Should this task store its result after it has finished?
         */
        public void setShouldStoreResult(boolean shouldStoreResult) {
            this.shouldStoreResult = shouldStoreResult;
        }

        @Override
        public boolean getShouldStoreResult() {
            return shouldStoreResult;
        }

        @Override
        public ActionRequestValidationException validate() {
            return null;
        }

        @Override
        public String getDescription() {
            return DELETION_TASK_DESCRIPTION_PREFIX + jobId;
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            super.writeTo(out);
            out.writeString(jobId);
            out.writeBoolean(force);
        }

        @Override
        public int hashCode() {
            return Objects.hash(jobId, force);
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null || obj.getClass() != getClass()) {
                return false;
            }
            DeleteJobAction.Request other = (DeleteJobAction.Request) obj;
            return Objects.equals(jobId, other.jobId) && Objects.equals(force, other.force);
        }
    }
}


text:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import nl.cwi.reo.runtime.Port;

public class Engine {
	private final Port<String> inputPort;
	private final Port<String> outputPort;
	private final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
	private final BufferedReader reader;
	private final BufferedWriter writer;
	private final int moveTime = 500;

	public Engine(Port<String> inputPort, Port<String> outputPort) {
		this.inputPort = inputPort;
		this.outputPort = outputPort;

		String os = System.getProperty("os.name").toLowerCase();
		final String stockfish;
		if (os.contains("win"))
			stockfish = "stockfish-6-win-32.exe";
		else if (os.contains("mac"))
			stockfish = "stockfish-6-osx-64";
		else
			stockfish = "stockfish-6-linux-64";

		String path = "./" + stockfish;

		Process process = null;
		try {
			process = Runtime.getRuntime().exec(path);
			System.out.println("Running " + path + "...");
		} catch (IOException e) {
			System.out.println("Failed to run " + path);
			e.printStackTrace();
			throw new Error();
		}

		this.reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		this.writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

		new Thread() {
			@Override
			public void run() {
				String line;
				StringBuilder builder = new StringBuilder();
				if (reader == null || queue == null)
					throw new NullPointerException();

				try {
					while ((line = reader.readLine()) != null) {
						builder.append(line + "\n");
						if (line.startsWith("uciok") || line.startsWith("bestmove")) {

							queue.put(builder.toString());
							builder = new StringBuilder();
						}
					}
				} catch (IOException | InterruptedException e) {
					e.printStackTrace();
					throw new Error();
				}
			}
		}.start();

		try {
			writer.write("uci\n");
			writer.flush();
			queue.take();
		}

		catch (IOException | InterruptedException e) {
			e.printStackTrace();
			throw new Error();
		}
	}

	public void run() {
		while (true) {
			String moves = (String) inputPort.get();
			System.out.println(moves);
			String result = "";

			try {
				writer.write("ucinewgame\n");
				writer.write("position startpos moves " + moves + "\n");
				writer.write("go movetime " + moveTime + "\n");
				writer.flush();
				result = queue.take();
			}

			catch (IOException | InterruptedException e) {
				e.printStackTrace();
				throw new Error();
			}

			outputPort.put(result);
		}

	}
}


text:
@interface FOWay : NSObject <OSMWay>

@end


text:
drop function if exists forloop();
drop table if exists fordata;
-- end_ignore

create table fordata(a int) distributed by (a);

create function forloop() returns int as $$
declare
   rowcnt integer;
begin
   for i IN 1..200 LOOP
      insert into fordata(a) values(i);
      drop table fordata;
      create table fordata(a int) distributed by (a);
   end loop;
   select count(*) into rowcnt from fordata;
   return rowcnt;
end;
$$ language plpgsql;

set gp_plpgsql_clear_cache_always=on;
select forloop();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
OutlineEffect (Slick - The 2D Library)
</TITLE>

<META NAME="date" CONTENT="2012-08-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.newdawn.slick.font.effects

Class OutlineEffect

java.lang.Object
  org.newdawn.slick.font.effects.OutlineEffect

All Implemented Interfaces:
ConfigurableEffect, Effect

Direct Known Subclasses:
OutlineWobbleEffect, OutlineZigzagEffect

public class OutlineEffect
extends java.lang.Object
implements ConfigurableEffect

Strokes glyphs with an outline.

Author:

Nathan Sweet <misc@n4te.com>

Nested Class Summary

Nested classes/interfaces inherited from interface org.newdawn.slick.font.effects.ConfigurableEffect

ConfigurableEffect.Value

Constructor Summary

OutlineEffect()

          Default constructor for injection

OutlineEffect(int width,
              java.awt.Color color)

          Create a new effect to draw the outline of the text

Method Summary

 void
draw(java.awt.image.BufferedImage image,
     java.awt.Graphics2D g,
     UnicodeFont unicodeFont,
     Glyph glyph)

          Called to draw the effect.

 java.awt.Color
getColor()

          Get the colour of the outline being drawn

 int
getJoin()

          Get the join type as indicated by @see BasicStroke

 java.awt.Stroke
getStroke()

          Get the stroke being used to draw the outline

 java.util.List
getValues()

          Returns the list of ConfigurableEffect.Values for this effect.

 float
getWidth()

          Get the width of the outline being drawn

 void
setColor(java.awt.Color color)

          Set the colour of the outline being drawn

 void
setJoin(int join)

          Sets how the corners of the outline are drawn.

 void
setStroke(java.awt.Stroke stroke)

          Sets the stroke to use for the outline.

 void
setValues(java.util.List values)

          Sets the list of ConfigurableEffect.Values for this effect.

 void
setWidth(int width)

          Sets the width of the outline.

 java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

OutlineEffect

public OutlineEffect()

Default constructor for injection

OutlineEffect

public OutlineEffect(int width,
                     java.awt.Color color)

Create a new effect to draw the outline of the text

Parameters:
width - The width of the outline
color - The colour of the outline

Method Detail

draw

public void draw(java.awt.image.BufferedImage image,
                 java.awt.Graphics2D g,
                 UnicodeFont unicodeFont,
                 Glyph glyph)

Description copied from interface: Effect

Called to draw the effect.

Specified by:
draw in interface Effect

Parameters:
image - The image to draw into
g - The graphics context to use for applying the effect
unicodeFont - The font being rendered
glyph - The particular glyph being rendered
See Also:
Effect.draw(java.awt.image.BufferedImage, java.awt.Graphics2D, org.newdawn.slick.UnicodeFont, org.newdawn.slick.font.Glyph)

getWidth

public float getWidth()

Get the width of the outline being drawn

Returns:
The width of the outline being drawn

setWidth

public void setWidth(int width)

Sets the width of the outline. The glyphs will need padding so the
 outline doesn't get clipped.

Parameters:
width - The width of the outline being drawn

getColor

public java.awt.Color getColor()

Get the colour of the outline being drawn

Returns:
The colour of the outline being drawn

setColor

public void setColor(java.awt.Color color)

Set the colour of the outline being drawn

Parameters:
color - The colour of the outline to draw

getJoin

public int getJoin()

Get the join type as indicated by @see BasicStroke

Returns:
The join type between segments in the outline

getStroke

public java.awt.Stroke getStroke()

Get the stroke being used to draw the outline

Returns:
The stroke being used to draw the outline

setStroke

public void setStroke(java.awt.Stroke stroke)

Sets the stroke to use for the outline. If this is set,
 the other outline settings are ignored.

Parameters:
stroke - The stroke to be used to draw the outline

setJoin

public void setJoin(int join)

Sets how the corners of the outline are drawn. This is usually only noticeable
 at large outline widths.

Parameters:
join - One of: BasicStroke.JOIN_BEVEL, BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

See Also:
Object.toString()

getValues

public java.util.List getValues()

Description copied from interface: ConfigurableEffect

Returns the list of ConfigurableEffect.Values for this effect. This list is not typically backed by the effect, so changes to the
 values will not take affect until ConfigurableEffect.setValues(List) is called.

Specified by:
getValues in interface ConfigurableEffect

See Also:
ConfigurableEffect.getValues()

setValues

public void setValues(java.util.List values)

Description copied from interface: ConfigurableEffect

Sets the list of ConfigurableEffect.Values for this effect.

Specified by:
setValues in interface ConfigurableEffect

See Also:
ConfigurableEffect.setValues(java.util.List)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2006 New Dawn Software. All Rights Reserved.


text:
class CreateAddresses < ActiveRecord::Migration
  def change
    create_table :addresses do |t|
      t.string :line1
      t.string :line2
      t.string :city
      t.string :state
      t.string :zip

      t.timestamps
    end
  end
end


text:
require 'teststrap'

context "Nesting a context" do
  setup do
    a_context = Riot::Context.new("foobar") do
      asserts("passing") { true }
      context "bazboo" do
        asserts("passing") { true }
        asserts("failing") { false }
        asserts("erroring") { raise Exception }
      end
    end
    a_context.run(MockReporter.new)
  end

  asserts("one passed test") { topic.passes == 2 }
  asserts("one failed test") { topic.failures == 1 }
  asserts("one errored test") { topic.errors == 1 }

  context "with setups" do
    setup do
      a_context = Riot::Context.new("foobar") do
        setup { "foo" }
        context "bazboo" do
          setup { topic + "bar" }
          asserts("passing") { topic == "foobar" }
        end
      end
      a_context.run(MockReporter.new)
    end

    asserts("parent setups are called") { topic.passes == 1 }
  end # with setups
end # Nesting a context

context "A context with nested descriptions as classes" do
  setup { Riot::Context.new(String) {}.context(Hash) {} }
  asserts(:description).equals { Hash }
  asserts(:detailed_description).equals("String Hash")
end # A context with nested descriptions as classes


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Rambo (Ed. ), Iheringia, Sér. Bot. 4: 101 (1959)

#### Original name
Peniophora longispora var. macrospora Rick

### Remarks
null


text:
public class Solution {
    private char one = 'I';
    private char five = 'V';
    private char ten = 'X';
    private char fifty = 'L';
    private char hundred = 'C';
    private char fivehundred = 'D';
    private char thousand = 'M';
    public String intToRoman(int num) {
        StringBuffer sb = new StringBuffer();
        int th = num/1000;
        while(th>0){
            th--;
            sb.append(thousand);
        }
        num = num % 1000;
        sb = append(sb,num , hundred , fivehundred , thousand, 100);
        num = num % 100;
        sb = append(sb,num , ten , fifty ,hundred, 10);
        num = num % 10 ;
        sb = append(sb,num , one , five ,ten, 1);
        return sb.toString();
    }
    private StringBuffer append(StringBuffer sb  ,int num , char one , char five , char ten, int unit){
        int nineunit = unit * 9;
        int fiveunit = unit * 5;
        int fourunit = unit * 4;
        if(num / nineunit !=0){
            sb.append(one);
            sb.append(ten);
            return sb;
        }
        if(num / fiveunit !=0){
            sb.append(five);
            num -= fiveunit;
        }
        else{
            if(num / fourunit !=0){
                sb.append(one);
                sb.append(five);
                num -= fourunit;
            }
        }
        int k = num /unit;
        while(k>0){
            sb.append(one);
            k--;
        }
        return sb;
    }
}


text:
package ar.edu.utn.frre.ia.planning.model.scheduling;

import ar.edu.utn.frre.ia.planning.model.data.Action;
import ar.edu.utn.frre.ia.planning.model.data.strips.InstantAction;
import ar.edu.utn.frre.ia.planning.model.data.metric.BinaryComparator;
import ar.edu.utn.frre.ia.planning.model.data.metric.ResourceOperator;
import ar.edu.utn.frre.ia.planning.model.data.metric.MetricSymbolStore;
import ar.edu.utn.frre.ia.planning.model.data.temporal.DurationFunction;
import ar.edu.utn.frre.ia.planning.model.data.temporal.DurativeAction;

import java.util.Map;
import java.util.Hashtable;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.math.BigDecimal;

//OK for new precedence relations (i.e. meetCosntraints) should move consumers to AFTER the >= etc..) (actually maybe no)
// AND for the new bounds should do incremental sweeps as in precedence relations

public class PrecedenceResourceGraph {
	public Map operators = new Hashtable();
	public Map conditions = new Hashtable();
	public Map states = new Hashtable(); // Maps (Operators || Conditions =>
											// States)

	public MatrixSTN stn;

	public PrecedenceResourceGraph(MatrixSTN s) {
		stn = s;
	}

	public void addCondition(BinaryComparator bc, Action a) {
		conditions.put(bc, a);
	}

	public void addOperator(ResourceOperator ro, Action a) {
		operators.put(ro, a);
	}

	public boolean meetConditions() {
		boolean changed = false;
		Iterator bcit = conditions.keySet().iterator();
		while (bcit.hasNext()) {
			BinaryComparator bc = (BinaryComparator) bcit.next();
			BigDecimal comp = bc.second.getValue(null);
			Action a = (Action) conditions.get(bc);

			if (bc.type == MetricSymbolStore.LESS_THAN
					|| bc.type == MetricSymbolStore.LESS_THAN_EQUAL) {
				BigDecimal value = findBeforeMin(a);

				if (value.compareTo(comp) >= 0) {
					// move an unordered consumer back
					Set u = getUnorderedConsumers(a);
					Action a2 = stn.getEarliest(u);
					stn.addConstraint(TemporalConstraint.getConstraint(
							(InstantAction) a2, (InstantAction) a));
					changed = true;
				}
			} else if (bc.type == MetricSymbolStore.GREATER_THAN
					|| bc.type == MetricSymbolStore.GREATER_THAN_EQUAL) {
				BigDecimal value = findBeforeMax(a);
				if (value.compareTo(comp) <= 0) {
					// move an unordered producer back
					Set u = getUnorderedProducers(a);
					Action a2 = stn.getEarliest(u);
					stn.addConstraint(TemporalConstraint.getConstraint(
							(InstantAction) a2, (InstantAction) a));
					changed = true;
				}
			}
		}
		return changed;
	}

	private BigDecimal findBeforeMax(Action a) {
		BigDecimal value = new BigDecimal(0);
		Iterator opit = operators.keySet().iterator();
		while (opit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) opit.next();
			Action a2 = (Action) operators.get(ro);
			if (ro.type == MetricSymbolStore.INCREASE
					|| ro.type == MetricSymbolStore.SCALE_UP) {
				if (stn.B(a2, a) || stn.BS(a2, a))
					value = ro.applyMax(value, stn); // WARNING This is not
														// taking into the
														// account the order of
														// the actions

			} else if (ro.type == MetricSymbolStore.DECREASE
					|| ro.type == MetricSymbolStore.SCALE_DOWN) {
				if (stn.B(a2, a))
					value = ro.applyMin(value, stn);
			}
		}
		return value;
	}

	private BigDecimal findBeforeMin(Action a) {
		BigDecimal value = new BigDecimal(0);
		Iterator opit = operators.keySet().iterator();
		while (opit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) opit.next();
			Action a2 = (Action) operators.get(ro);
			if (ro.type == MetricSymbolStore.INCREASE
					|| ro.type == MetricSymbolStore.SCALE_UP) {
				if (stn.B(a2, a))
					value = ro.applyMin(value, stn); // WARNING This is not
														// taking into the
														// account the order of
														// the actions
			} else if (ro.type == MetricSymbolStore.DECREASE
					|| ro.type == MetricSymbolStore.SCALE_DOWN) {
				if (stn.B(a2, a) || stn.BS(a2, a))
					value = ro.applyMax(value, stn);
			}
		}
		return value;
	}

	private Set getUnorderedProducers(Action a) {
		Set rSet = new HashSet();
		Iterator opit = operators.keySet().iterator();
		while (opit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) opit.next();
			Action a2 = (Action) operators.get(ro);
			if (ro.type == MetricSymbolStore.INCREASE
					|| ro.type == MetricSymbolStore.SCALE_UP) {
				if (stn.U(a2, a))
					rSet.add(a2);
			}
		}
		return rSet;
	}

	private Set getUnorderedConsumers(Action a) {
		Set rSet = new HashSet();
		Iterator opit = operators.keySet().iterator();
		while (opit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) opit.next();
			Action a2 = (Action) operators.get(ro);
			if (ro.type == MetricSymbolStore.DECREASE
					|| ro.type == MetricSymbolStore.SCALE_DOWN) {
				if (stn.U(a2, a))
					rSet.add(a2);
			}
		}
		return rSet;
	}

	private Set getBeforeOperators(Action a) {
		Set rSet = new HashSet();
		Iterator opit = operators.keySet().iterator();
		while (opit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) opit.next();
			Action a2 = (Action) operators.get(ro);
			rSet.add(ro);
		}
		return rSet;
	}

	public boolean limitBounds() {
		boolean change = false;
		Iterator bcit = conditions.keySet().iterator();
		while (bcit.hasNext()) {
			BinaryComparator bc = (BinaryComparator) bcit.next();

			BigDecimal comp = bc.second.getValue(null);
			Action a = (Action) conditions.get(bc);

			if (bc.type == MetricSymbolStore.LESS_THAN
					|| bc.type == MetricSymbolStore.LESS_THAN_EQUAL) {
				BigDecimal value = findBeforeMax(a);
				if (value.compareTo(comp) > 0) {
					BigDecimal diff = value.subtract(comp);
					// change an before producers back
					Set u = getBeforeOperators(a);
					Iterator uit = u.iterator();
					while (uit.hasNext()) {
						ResourceOperator ro = (ResourceOperator) uit.next();
						if (ro.change instanceof DurationFunction) {
							DurationFunction df = (DurationFunction) ro.change;
							DurativeAction da = df.durativeAction;
							if (ro.type == MetricSymbolStore.INCREASE
									|| ro.type == MetricSymbolStore.SCALE_UP)
								stn.decreaseMax(da, diff);
							else if (ro.type == MetricSymbolStore.DECREASE
									|| ro.type == MetricSymbolStore.SCALE_DOWN)
								stn.increaseMin(da, diff);
							change = true;
							break;
						}
					}
				}
			}

			else if (bc.type == MetricSymbolStore.GREATER_THAN
					|| bc.type == MetricSymbolStore.GREATER_THAN_EQUAL) {
				BigDecimal value = findBeforeMin(a);
				if (value.compareTo(comp) < 0) {
					BigDecimal diff = comp.subtract(value);
					// change an before producers back
					Set u = getBeforeOperators(a);
					Iterator uit = u.iterator();
					while (uit.hasNext()) {
						ResourceOperator ro = (ResourceOperator) uit.next();
						if (ro.change instanceof DurationFunction) {
							DurationFunction df = (DurationFunction) ro.change;
							DurativeAction da = df.durativeAction;
							if (ro.type == MetricSymbolStore.INCREASE
									|| ro.type == MetricSymbolStore.SCALE_UP)
								stn.increaseMin(da, diff);
							else if (ro.type == MetricSymbolStore.DECREASE
									|| ro.type == MetricSymbolStore.SCALE_DOWN)
								stn.decreaseMax(da, diff);
							change = true;
							break;
						}
					}
				}
			}
		}
		return change;
	}

	public void minimize() {
		Iterator roit = operators.keySet().iterator();
		while (roit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) roit.next();
			if (ro.change instanceof DurationFunction) {
				DurativeAction da = ((DurationFunction) ro.change).durativeAction;
				if (ro.type == MetricSymbolStore.INCREASE
						|| ro.type == MetricSymbolStore.SCALE_UP) {
					stn.minimize(da);
				} else if (ro.type == MetricSymbolStore.DECREASE
						|| ro.type == MetricSymbolStore.SCALE_DOWN) {
					stn.maximize(da);
				}
			}
		}
	}

	public void maximize() {
		Iterator roit = operators.keySet().iterator();
		while (roit.hasNext()) {
			ResourceOperator ro = (ResourceOperator) roit.next();
			if (ro.change instanceof DurationFunction) {
				DurativeAction da = ((DurationFunction) ro.change).durativeAction;
				if (ro.type == MetricSymbolStore.INCREASE
						|| ro.type == MetricSymbolStore.SCALE_UP) {
					stn.maximize(da);
				} else if (ro.type == MetricSymbolStore.DECREASE
						|| ro.type == MetricSymbolStore.SCALE_DOWN) {
					stn.minimize(da);
				}
			}
		}
	}

}


text:
#region Copyright
// Copyright 2017 Gigya Inc.  All rights reserved.
//
// 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Threading.Tasks;
using Gigya.Common.Contracts.HttpService;
using Newtonsoft.Json;
using NUnit.Framework;
#pragma warning disable 169

namespace Gigya.Common.Contracts.UnitTests
{
    class DataParamBase
    {
        [Sensitive]
        public int BaseField;
    }
    class Data: DataParamBase
    {
        public string s;
        public Nested n;
    }

    class Nested
    {
        public DateTime time;
    }

    class ResponseData
    {
        public string a;
        public int b;
    }

    public class SensitiveAttribute : Attribute {}

    [HttpService(100)]
    internal interface ITestInterface
    {
        [PublicEndpoint("demo.doSomething")]
        Task<ResponseData> DoSomething(int i, double? nd, string s, [Sensitive] Data data);
    }

    [TestFixture,Parallelizable(ParallelScope.Fixtures)]
    public class ServiceSchemaTests
    {

        [Test]
        public void TestSerialization()
        {
            ServiceSchema schema = new ServiceSchema(new[] { typeof(ITestInterface) });
            string serialized = JsonConvert.SerializeObject(schema, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore });
            schema = JsonConvert.DeserializeObject<ServiceSchema>(serialized);

            Assert.IsTrue(schema.Interfaces.Length == 1);
            Assert.IsTrue(schema.Interfaces[0].Name == typeof(ITestInterface).FullName);
            Assert.IsTrue(schema.Interfaces[0].Attributes.Length == 1);
            Assert.IsTrue(schema.Interfaces[0].Attributes[0].Attribute is HttpServiceAttribute);
            Assert.IsTrue(schema.Interfaces[0].Attributes[0].TypeName == typeof(HttpServiceAttribute).AssemblyQualifiedName);
            Assert.IsTrue((schema.Interfaces[0].Attributes[0].Attribute as HttpServiceAttribute).BasePort == 100);
            Assert.IsTrue(schema.Interfaces[0].Methods.Length == 1);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Name == nameof(ITestInterface.DoSomething));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Attributes.Length == 1);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Attributes[0].Attribute is PublicEndpointAttribute);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Attributes[0].TypeName == typeof(PublicEndpointAttribute).AssemblyQualifiedName);
            Assert.IsTrue((schema.Interfaces[0].Methods[0].Attributes[0].Attribute as PublicEndpointAttribute).EndpointName == "demo.doSomething");
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters.Length == 4);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].Attributes.Length == 0);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].Name == "i");
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].Type == typeof(int));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].TypeName == typeof(int).AssemblyQualifiedName);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[1].Name == "nd");
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[1].Type == typeof(double?));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[2].Name == "s");
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Attributes.Length == 1);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Attributes[0].Attribute is SensitiveAttribute);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[2].Name == nameof(DataParamBase.BaseField));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[2].Attributes[0].Attribute is SensitiveAttribute);
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[2].Type == typeof(int));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[1].Name == nameof(Data.n));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[1].Type == typeof(Nested));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[0].Name == nameof(Data.s));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[0].Type == typeof(string));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Type == typeof(ResponseData));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[0].Name == nameof(ResponseData.a));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[0].Type == typeof(string));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[1].Name == nameof(ResponseData.b));
            Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[1].Type == typeof(int));
        }

        [Test]
        public void TestUnknownAttribute()
        {
            var typeFullName = typeof(SensitiveAttribute).AssemblyQualifiedName;
            string json = @"
                {
                  ""TypeName"": """ + typeFullName + @""",
                  ""Data"": {
                    ""TypeId"": """ + typeFullName + @"""
                  }
                }";
            AttributeSchema attr = JsonConvert.DeserializeObject<AttributeSchema>(json);
            Assert.IsNotNull(attr.Attribute);

            json = @"
                {
                  ""TypeName"": ""Gigya.Microdot.ServiceContract.UnitTests.HttpService.SensitiveAttribute2, Gigya.Microdot.ServiceContract.UnitTests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"",
                  ""Data"": {
                    ""TypeId"": """ + typeFullName + @"""
                  }
                }";
            attr = JsonConvert.DeserializeObject<AttributeSchema>(json);
            Assert.IsNull(attr.Attribute);
            Assert.IsTrue(attr.TypeName == "Gigya.Microdot.ServiceContract.UnitTests.HttpService.SensitiveAttribute2, Gigya.Microdot.ServiceContract.UnitTests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
        }

        [Test]
        public void TestUnknownParamType()
        {
            string json = @"
                {
                  ""Name"": ""i"",
                  ""TypeName"": ""System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
                  ""Attributes"": []
                }";
            ParameterSchema param = JsonConvert.DeserializeObject<ParameterSchema>(json);
            Assert.IsNotNull(param.Type);

            json = @"
                {
                  ""Name"": ""i"",
                  ""TypeName"": ""System.Int33, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
                  ""Attributes"": []
                }";
            param = JsonConvert.DeserializeObject<ParameterSchema>(json);
            Assert.IsNull(param.Type);
            Assert.IsTrue(param.TypeName == "System.Int33, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
        }
    }
}


text:
<!DOCTYPE HTML>
<html>
<head>
  <script src="../../closure-library/closure/goog/base.js"></script>
  <script src="./test_js_deps.js"></script>
  <script src="../wgxpath.install.js"></script>
  <script>
    goog.require('goog.testing.jsunit');
    goog.require('goog.userAgent');
    goog.require('wgxpath.test');
  </script>
</head>
<body>
<svg id="svg" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1000 50">
  <rect id="rect" fill="red" stroke="none" height="12" width="12" y="20" x="100"></rect>
  <text id="text" fill="black" font-size="12" font-family="Arial" y="30" x="115">Apple</text>
  <path id="path" d="M 200 26 L 600 26" stroke="red" stroke-width="1em"/>
</svg>
  <script>
    var SVG_NS_RESOLVER = function(prefix) {
      return prefix == 'svg' ? 'http://www.w3.org/2000/svg' : null;
    };

    function setUpPage() {
      wgxpath.test.setContext(document);
    }

    function assertEvaluatesToSvgNodeSet(expected, expr) {
      wgxpath.test.assertEvaluatesToNodeSet(expected, expr, SVG_NS_RESOLVER);
    }

    function testSvgElement() {
      assertEvaluatesToSvgNodeSet(['svg#svg'], '//svg:svg');
    }

    function testSvgRectElement() {
      assertEvaluatesToSvgNodeSet(['rect#rect'], '//svg:rect');
    }

    function testSvgTextElement() {
      assertEvaluatesToSvgNodeSet(['text#text'], '//svg:text');
    }

    function testSvgPathElement() {
      assertEvaluatesToSvgNodeSet(['path#path'], '//svg:path');
    }
  </script>
</body>
</html>


text:
/*
 * MonsterFactory.h
 *
 *  Created on: Nov 22, 2014
 *      Author: dean
 */

#ifndef MONSTERFACTORY_H_
#define MONSTERFACTORY_H_
#include <unordered_map>
#include <string>
#include <json/json.h>
#include "Monster.h"

namespace enDJIN {

class MonsterFactory {
	std::unordered_map<std::string, Monster> mapOfMonsterTemplates;
public:
	MonsterFactory(Json::Value *JV);
	virtual ~MonsterFactory();
};

}; /* namespace enDJIN */

#endif /* MONSTERFACTORY_H_ */


text:
    {{ .User.AccountName }}

      <time class="timeago" datetime="{{.CreatedAt.Format "2006-01-02T15:04:05-07:00"}}"></time>

    {{ .User.AccountName }}
    {{ .Body }}

      comments: {{ .CommentCount }}

    {{ range .Comments }}

      {{.User.AccountName}}
      {{.Comment}}

    {{ end }}

      <form method="post" action="/comment">
        <input type="text" name="comment">
        <input type="hidden" name="post_id" value="{{.ID}}">
        <input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
        <input type="submit" name="submit" value="submit">
      </form>


text:
<?php

namespace Acclimate\Container\Test;

use Acclimate\Container\ArrayContainer;
use Acclimate\Container\Test\Adapter\AbstractContainerAdapterTest;
use Interop\Container\ContainerInterface;

/**
 * @covers \Acclimate\Container\ArrayContainer
 */
class ArrayContainerTest extends \PHPUnit_Framework_TestCase
{
    public function testCanInstantiateWithArrayOrArrayLikeObject()
    {
        $a1 = ['foo' => 'bar'];
        $a2 = new \ArrayObject(['foo' => 'bar']);
        $a3 = new \LimitIterator(new \ArrayIterator($a1), 0, 1);
        $a4 = 'foo';

        $this->assertInstanceOf('Acclimate\Container\ArrayContainer', new ArrayContainer($a1));
        $this->assertInstanceOf('Acclimate\Container\ArrayContainer', new ArrayContainer($a2));
        $this->assertInstanceOf('Acclimate\Container\ArrayContainer', new ArrayContainer($a3));

        $this->setExpectedException('InvalidArgumentException');
        new ArrayContainer($a4);
    }

    public function testSupportsContainerInterface()
    {
        $container = new ArrayContainer(['array_iterator' => new \ArrayIterator(range(1, 5))]);

        $this->assertTrue($container->has('array_iterator'));
        $arrayIterator = $container->get('array_iterator');
        $this->assertEquals([1, 2, 3, 4, 5], iterator_to_array($arrayIterator));
    }

    public function testThrowsExceptionOnNonExistentItem()
    {
        $container = new ArrayContainer();

        $this->assertFalse($container->has('foo'));

        $this->setExpectedException('Interop\Container\Exception\NotFoundException');
        $container->get('foo');
    }

    public function testAdapterWrapsOtherExceptions()
    {
        $container = new ArrayContainer();
        $container['error'] = function ($c) {
            throw new \RuntimeException;
        };

        $this->setExpectedException('Interop\Container\Exception\ContainerException');
        $container->get('error');
    }

    public function testContainerSupportsArrayAccessInterface()
    {
        $container = new ArrayContainer();
        $this->assertFalse(isset($container['queue']));
        $container['queue'] = new \SplQueue();
        $this->assertTrue(isset($container['queue']));
        $queue = $container['queue'];
        $this->assertInstanceOf('SplQueue', $queue);
        unset($container['queue']);
        $this->assertFalse(isset($container['queue']));
    }

    public function testClosuresAreExecutedOnGet()
    {
        $container = new ArrayContainer();
        $container['foo'] = 'bar';
        $container['baz'] = function ($c) {
            $obj = new \stdClass;
            $obj->foo = $c['foo'];
            return $obj;
        };

        $baz = $container['baz'];
        $this->assertInstanceOf('stdClass', $baz);
        $this->assertEquals('bar', $baz->foo);
        $this->assertSame($baz, $container['baz']);
    }

    public function testDelegateLookupFeature() {
    	$container1 = new ArrayContainer([
    			'foo' => 'bar'
    	]);
    	$container2 = new ArrayContainer([
    			'baz' => function(ContainerInterface $container) {
    				return $container->get('foo');
    			}
    	], $container1);

    	$this->assertEquals('bar', $container2->get('baz'));
    }
}