text:
<?php
namespace Payum\Core\Tests\Registry;

use Doctrine\Persistence\Proxy;
use PHPUnit\Framework\TestCase;

class AbstractRegistryTest extends TestCase
{
    /**
     * @test
     */
    public function shouldImplementGatewayRegistryInterface()
    {
        $rc = new \ReflectionClass('Payum\Core\Registry\AbstractRegistry');

        $this->assertTrue($rc->implementsInterface('Payum\Core\Registry\GatewayRegistryInterface'));
    }

    /**
     * @test
     */
    public function shouldImplementStorageRegistryInterface()
    {
        $rc = new \ReflectionClass('Payum\Core\Registry\AbstractRegistry');

        $this->assertTrue($rc->implementsInterface('Payum\Core\Registry\StorageRegistryInterface'));
    }

    /**
     * @test
     */
    public function shouldImplementGatewayFactoryInterface()
    {
        $rc = new \ReflectionClass('Payum\Core\Registry\AbstractRegistry');

        $this->assertTrue($rc->implementsInterface('Payum\Core\Registry\GatewayFactoryRegistryInterface'));
    }

    /**
     * @test
     */
    public function shouldBeAbstractClass()
    {
        $rc = new \ReflectionClass('Payum\Core\Registry\AbstractRegistry');

        $this->assertTrue($rc->isAbstract());
    }

    /**
     * @test
     */
    public function shouldAllowGetGatewayWithNamePassedExplicitly()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
        ));

        $this->assertEquals('barGateway', $registry->getGateway('barName'));
    }

    /**
     * @test
     */
    public function shouldAllowGetAllGateways()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
        ));

        $gateways = $registry->getGateways();

        $this->assertIsArray($gateways);
        $this->assertCount(2, $gateways);

        $this->assertArrayHasKey('fooName', $gateways);
        $this->assertEquals('fooGateway', $gateways['fooName']);

        $this->assertArrayHasKey('barName', $gateways);
        $this->assertEquals('barGateway', $gateways['barName']);
    }

    /**
     * @test
     */
    public function throwIfTryToGetGatewayWithNotExistName()
    {
        $this->expectException(\Payum\Core\Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('Gateway "notExistName" does not exist.');
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
        ));

        $registry->getGateway('notExistName');
    }

    /**
     * @test
     */
    public function shouldAllowGetGatewayFactoryByName()
    {
        $gatewayFactories = array('foo' => 'fooGatewayFactory', 'bar' => 'barGatewayFactory');

        $registry = $this->createAbstractRegistryMock(array(
            array(),
            array(),
            $gatewayFactories,
        ));

        $this->assertEquals('barGatewayFactory', $registry->getGatewayFactory('bar'));
    }

    /**
     * @test
     */
    public function shouldAllowGetAllGatewayFactories()
    {
        $gatewayFactories = array('foo' => 'fooGatewayFactory', 'bar' => 'barGatewayFactory');

        $registry = $this->createAbstractRegistryMock(array(
            array(),
            array(),
            $gatewayFactories,
        ));

        $gateways = $registry->getGatewayFactories();

        $this->assertIsArray($gateways);
        $this->assertCount(2, $gateways);

        $this->assertArrayHasKey('foo', $gateways);
        $this->assertEquals('fooGatewayFactory', $gateways['foo']);

        $this->assertArrayHasKey('bar', $gateways);
        $this->assertEquals('barGatewayFactory', $gateways['bar']);
    }

    /**
     * @test
     */
    public function throwIfTryToGetGatewayFactoryWithNotExistName()
    {
        $this->expectException(\Payum\Core\Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('Gateway factory "notExistName" does not exist.');
        $gatewayFactories = array('foo' => 'fooGatewayFactory', 'bar' => 'barGatewayFactory');

        $registry = $this->createAbstractRegistryMock(array(
            array(),
            array(),
            $gatewayFactories
        ));

        $registry->getGatewayFactory('notExistName');
    }

    /**
     * @test
     */
    public function shouldAllowGetStorageForGivenModelClass()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');
        $storages = array('stdClass' => 'barStorage');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
            $storages,
        ));

        $this->assertEquals('barStorage', $registry->getStorage('stdClass'));
    }

    /**
     * @test
     */
    public function shouldAllowGetStorageIfDoctrineProxyClassGiven()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');
        $storages = array('Payum\Core\Tests\Registry\DoctrineModel' => 'barStorage');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
            $storages,
        ));

        $this->assertEquals('barStorage', $registry->getStorage('Payum\Core\Tests\Registry\DoctrineProxy'));
    }

    /**
     * @test
     */
    public function shouldAllowGetStorageIfDoctrineProxyObjectGiven()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');
        $storages = array('Payum\Core\Tests\Registry\DoctrineModel' => 'barStorage');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
            $storages,
        ));

        $this->assertEquals('barStorage', $registry->getStorage(new DoctrineProxy()));
    }

    /**
     * @test
     */
    public function throwIfTryToGetStorageWithNotRegisteredModelClass()
    {
        $this->expectException(\Payum\Core\Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('A storage for model notRegisteredModelClass was not registered. There are storages for next models: stdClass.');
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');
        $storages = array('stdClass' => 'barStorage');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
            $storages,
        ));

        $this->assertEquals('barStorage', $registry->getStorage('notRegisteredModelClass'));
    }

    /**
     * @test
     */
    public function shouldAllowGetStorageWithObjectModel()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');
        $storages = array('stdClass' => 'barStorage');

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
            $storages,
        ));

        $this->assertEquals('barStorage', $registry->getStorage(new \stdClass()));
    }

    /**
     * @test
     */
    public function shouldAllowGetStorages()
    {
        $gateways = array('fooName' => 'fooGateway', 'barName' => 'barGateway');
        $storages = array(
            'stdClass' => 'barStorage', 'FooClass' => 'FooStorage',
        );

        $registry = $this->createAbstractRegistryMock(array(
            $gateways,
            $storages,
        ));

        $this->assertEquals($storages, $registry->getStorages());
    }

    /**
     * @param array $constructorArguments
     *
     * @return \PHPUnit_Framework_MockObject_MockObject|\Payum\Core\Registry\AbstractRegistry
     */
    protected function createAbstractRegistryMock(array $constructorArguments)
    {
        $registryMock = $this->getMockForAbstractClass('Payum\Core\Registry\AbstractRegistry', $constructorArguments);

        $registryMock
            ->method('getService')
            ->willReturnArgument(0)
        ;

        return $registryMock;
    }
}

class DoctrineModel
{
}

class DoctrineProxy extends DoctrineModel implements Proxy
{
    public function __load()
    {
    }

    public function __isInitialized()
    {
    }
}


text:
#ifndef TESTICKLE_H
#define	TESTICKLE_H

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

#define TEST_FIXTURE(number_of_tests) \
    do { \
        printf("TAP version 13\n"); \
        printf("1..%d\n", number_of_tests); \
    } while(0);

#define RUN_TEST(test_name, test_number) \
    do { \
        struct TESTickle_test_result TESTickle_result; \
        setup(); \
        TESTickle_result = test_name(); \
        if (TESTickle_result.test_passed) { \
            printf("ok %d - %s\n", test_number, #test_name); \
        } \
        else { \
            printf("not ok %d - %s\n", test_number, #test_name); \
            printf("  ---\n"); \
            printf("  message: %s\n", TESTickle_result.failure_message); \
            printf("  severity: fail\n"); \
            if (TESTickle_result.data_specified) { \
                printf("  data:\n"); \
                printf("    got: '%s'\n", TESTickle_result.got); \
                printf("    expect: '%s'\n", TESTickle_result.expect); \
            } \
            printf("  ...\n"); \
        } \
        teardown(); \
    } while(0);

#define TEST(test_name) \
    struct TESTickle_test_result test_name() \
    { \
        struct TESTickle_test_result TESTickle_result = {.test_passed = false, .data_specified = false};

#define END_TEST \
        TESTickle_result.test_passed = true; \
        return TESTickle_result; \
    }

#define ASSERT_TRUE(test, message) \
    if (!(test)) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        return TESTickle_result; \
    }

#define ASSERT_FALSE(test, message) \
    if (test) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        return TESTickle_result; \
    }

#define ASSERT_EQUAL(actual, expected, type, message) \
    if (actual != expected) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        TESTickle_result.data_specified = true; \
        snprintf(TESTickle_result.got, MESSAGE_LENGTH, type, actual); \
        snprintf(TESTickle_result.expect, MESSAGE_LENGTH, type, expected); \
        return TESTickle_result; \
    }

#define ASSERT_NOT_EQUAL(actual, expected, message) \
    if (actual == expected) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        return TESTickle_result; \
    }

#define ASSERT_STRING_EQUAL(actual, expected, message) \
    if (strncmp(actual, expected, MESSAGE_LENGTH) != 0) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        TESTickle_result.data_specified = true; \
        snprintf(TESTickle_result.got, MESSAGE_LENGTH, "%s", actual); \
        snprintf(TESTickle_result.expect, MESSAGE_LENGTH, "%s", expected); \
        return TESTickle_result; \
    }

#define ASSERT_STRING_EMPTY(actual, message) \
    if (strncmp(actual, "", MESSAGE_LENGTH) != 0) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        TESTickle_result.data_specified = true; \
        snprintf(TESTickle_result.got, MESSAGE_LENGTH, "%s", actual); \
        return TESTickle_result; \
    }

#define ASSERT_STRING_NOT_EMPTY(actual, message) \
    if (strncmp(actual, "", MESSAGE_LENGTH) == 0) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        return TESTickle_result; \
    }

#define ASSERT_NULL(expr, message) \
    if ((expr) != NULL) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        return TESTickle_result; \
    }

#define ASSERT_NOT_NULL(expr, message) \
    if ((expr) == NULL) { \
        snprintf(TESTickle_result.failure_message, MESSAGE_LENGTH, "%s", message); \
        return TESTickle_result; \
    }

#define MESSAGE_LENGTH 128

struct TESTickle_test_result {
    bool test_passed;
    char failure_message[MESSAGE_LENGTH];
    bool data_specified;
    char got[MESSAGE_LENGTH];
    char expect[MESSAGE_LENGTH];
};

void setup();
void teardown();

#endif	/* TESTICKLE_H */

redpajama_set_name: RedPajamaGithub


text:
package org.hisp.dhis.common;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.schema.PropertyType;
import org.hisp.dhis.schema.annotation.Property;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@JacksonXmlRootElement( localName = "linkableObject", namespace = DxfNamespaces.DXF_2_0 )
public class BaseLinkableObject
    implements LinkableObject
{
    /**
     * As part of the serializing process, this field can be set to indicate a link to this
     * identifiable object (will be used on the web layer for navigating the REST API)
     */
    private transient String href;

    @Override
    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    @Property( PropertyType.URL )
    public String getHref()
    {
        return href;
    }

    @Override
    public void setHref( String href )
    {
        this.href = href;
    }
}


text:
package cass.pure.ioc.handlers;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

import cass.pure.ioc.handlers.EmptyHandler;

public class TypeHandlerChain {
	private Set<TypeAnnotationHandler> set;
	private TypeAnnotationHandler current = null;

	public TypeHandlerChain(Set<TypeAnnotationHandler> handlers,
			Annotation[] anns) {
		set = new HashSet<TypeAnnotationHandler>();
		for (TypeAnnotationHandler ah : handlers) {
			if (ah.canHandle(anns)) {
				set.add(ah);
			}
		}
	}

	public TypeAnnotationHandler next() {
		if (current == null) {
			TypeAnnotationHandler ret = EmptyHandler.getInstance();
			for (TypeAnnotationHandler ah : set) {
				if (ah.priority() < ret.priority()) {
					ret = ah;
				}
			}
			current = ret;
			return ret;
		}
		TypeAnnotationHandler ret = EmptyHandler.getInstance();
		for (TypeAnnotationHandler ah : set) {
			if (ah.priority() < ret.priority()
					&& ah.priority() > current.priority()) {
				ret = ah;
			}
		}
		current = ret;
		return ret;
	}
}


text:
require 'ocular'

RSpec.describe Ocular::DSL::Etcd do

    it "#etcd returns object" do
        ::Ocular::Settings.load_from_file('spec/data/settings.yaml')

        ef = Ocular::Event::EventFactory.new
        a = "nan"
        proxy = ef.load_from_block "test_dsl" do
            fork false
            onEvent "name" do
                a = etcd()
            end
        end
        eventbase = proxy.events["onEvent"]["name"]

        context = Ocular::DSL::RunContext.new(Ocular::Logging::ConsoleLogger.new)
        eventbase.exec(context)
        expect(a).not_to eq(nil)
    end

    describe("locking") do
        it "can lock and unlock" do
            c = Class.new.extend(Ocular::DSL::Etcd)
            locked = c.ttl_lock("foo", ttl:5)

            expect(locked).not_to eq(nil)
            expect(c.locked?("foo")).to eq(locked)
            expect(c.unlock("foo")).to eq(true)
        end

        it "can refresh a lock" do
            c = Class.new.extend(Ocular::DSL::Etcd)
            locked = c.ttl_lock("foo", ttl:5)

            # refresh the lock
            expect(c.ttl_lock("foo")).to eq(locked)
            expect(c.ttl_lock("foo")).to eq(locked)

            expect(c.unlock("foo")).to eq(true)
        end

        it "can't lock if somebody else has a lock" do
            c = Class.new.extend(Ocular::DSL::Etcd)
            c.instance_variable_set(:@run_id, "run_id:c")
            locked = c.ttl_lock("foo", ttl:5)

            expect(locked).not_to eq(nil)
            expect(c.locked?("foo")).to eq(locked)

            # Simulate another process
            d = Class.new.extend(Ocular::DSL::Etcd)
            d.instance_variable_set(:@run_id, "run_id:d")

            # This process can't lock because process 'c' has already the lock
            expect(d.ttl_lock("foo")).to eq(nil)

            # c has still the lock
            expect(c.ttl_lock("foo")).not_to eq(nil)

            expect(c.unlock("foo")).to eq(true)
        end
    end

end


text:
//
//  test_esdhttp.hpp
//  EyeOfSauronDHTMonitor
//
//  Created by shuaizhai on 4/25/16.
//  Copyright © 2016 com.dhtMonitor.www. All rights reserved.
//

#ifndef test_esdhttp_hpp
#define test_esdhttp_hpp

#include <stdio.h>
#include "ESDHttpUtility.hpp"
#include "ESDHttpProtocol.hpp"

namespace test_esdhttp {

    void test_esdhttp();

}

#endif /* test_esdhttp_hpp */


text:
package com.mytian.lb.enums;

import com.mytian.lb.R;

/**
 * tab菜单枚举类.
 *
 * @author
 */
public enum BottomMenu {

    //    主界面
    //动态
    DYNAMIC(R.string.menu_dynamic,R.string.menu_dynamic, R.mipmap.main_tab_news_down, R.mipmap.main_tab_news_normal, 0xFFFFD704, 0xFF333333),
    //爱的约定
    AGREEMENT(R.string.menu_follow,R.string.menu_follow, R.mipmap.main_tab_love_down, R.mipmap.main_tab_love_normal, 0xFFFFD704, 0xFF333333),
    //其他
    KINDLE(R.string.menu_kindle,R.string.menu_kindle, R.mipmap.main_tab_kindle_down, R.mipmap.main_tab_kindle_normal, 0xFFFFD704, 0xFF333333),
    //帐号管理
    USER(R.string.menu_user, R.string.menu_user,R.mipmap.main_tab_me_down, R.mipmap.main_tab_me_normal, 0xFFFFD704, 0xFF333333);

    private int title;
    private int title_press;
    private int resid_press;
    private int resid_normal;
    private int title_colos_press;
    private int title_colos_normal;

    BottomMenu(int title,int title_press ,int resid_press, int resid_normal, int title_colos_press, int title_colos_normal) {
        this.title = title;
        this.title_press = title_press;
        this.resid_press = resid_press;
        this.resid_normal = resid_normal;
        this.title_colos_press = title_colos_press;
        this.title_colos_normal = title_colos_normal;
    }

    public int getTitle() {
        return title;
    }

    public void setTitle(int title) {
        this.title = title;
    }

    public int getTitle_press() {
        return title_press;
    }

    public void setTitle_press(int title_press) {
        this.title_press = title_press;
    }

    public int getResid_press() {
        return resid_press;
    }

    public void setResid_press(int resid_press) {
        this.resid_press = resid_press;
    }

    public int getResid_normal() {
        return resid_normal;
    }

    public void setResid_normal(int resid_normal) {
        this.resid_normal = resid_normal;
    }

    public int getTitle_colos_press() {
        return title_colos_press;
    }

    public void setTitle_colos_press(int title_colos_press) {
        this.title_colos_press = title_colos_press;
    }

    public int getTitle_colos_normal() {
        return title_colos_normal;
    }

    public void setTitle_colos_normal(int title_colos_normal) {
        this.title_colos_normal = title_colos_normal;
    }

    @Override
    public String toString() {
        return "BottomMenu{" +
                "title=" + title +
                ", title_press=" + title_press +
                ", resid_press=" + resid_press +
                ", resid_normal=" + resid_normal +
                ", title_colos_press=" + title_colos_press +
                ", title_colos_normal=" + title_colos_normal +
                '}';
    }
}


text:
package com.gentics.mesh.changelog;

import com.gentics.mesh.core.db.Database;
import com.gentics.mesh.graphdb.spi.GraphDatabase;
import com.tinkerpop.blueprints.TransactionalGraph;

/**
 * Interface for a mesh graph database change. A change may alter graph structure, content and indices.
 */
public interface Change {

	/**
	 * Return the uuid of the change.
	 *
	 * @return
	 */
	String getUuid();

	/**
	 * Return the name of the change.
	 *
	 * @return
	 */
	String getName();

	/**
	 * Apply the change to the graph.
	 */
	void apply();

	/**
	 * Check whether the change already has been applied.
	 *
	 * @return
	 */
	boolean isApplied();

	/**
	 * Return the description of the change.
	 *
	 * @return
	 */
	String getDescription();

	/**
	 * Set the graph instance to be used when handling the change.
	 *
	 * @param graph
	 */
	void setGraph(TransactionalGraph graph);

	/**
	 * Return the graph that is currently set for the change.
	 *
	 * @return
	 */
	TransactionalGraph getGraph();

	/**
	 * Persist the info that the change has been applied to the graph.
	 */
	void markAsComplete();

	/**
	 * Set the time that passed to execute the change.
	 *
	 * @param timeMs
	 */
	void setDuration(long timeMs);

	/**
	 * Return the time it took to execute the change.
	 *
	 * @return
	 */
	long getDuration();

	/**
	 * Validate the change. A unsuccessful validation will abort the changelog execution.
	 *
	 * @return true if validation was successful. Otherwise false.
	 */
	boolean validate();

	/**
	 * Return a flag which informs the changelog system whether the change requires a reindex of the search index.
	 *
	 * @return
	 */
	boolean requiresReindex();

	/**
	 * Set the database.
	 *
	 * @param db
	 */
	void setDb(GraphDatabase db);

	/**
	 * Return the database.
	 *
	 * @return
	 */
	Database getDb();

}


text:
<template name="settings">

Some setting

Some other setting

</template>


text:
<?php

abstract class NuanceItemType
  extends Phobject {

  private $viewer;
  private $controller;

  public function setViewer(PhabricatorUser $viewer) {
    $this->viewer = $viewer;
    return $this;
  }

  public function getViewer() {
    return $this->viewer;
  }

  public function setController(PhabricatorController $controller) {
    $this->controller = $controller;
    return $this;
  }

  public function getController() {
    return $this->controller;
  }

  public function canUpdateItems() {
    return false;
  }

  final public function buildItemView(NuanceItem $item) {
    return $this->newItemView($item);
  }

  protected function newItemView(NuanceItem $item) {
    return null;
  }

  public function getItemTypeDisplayIcon() {
    return null;
  }

  public function getItemActions(NuanceItem $item) {
    return array();
  }

  public function getItemCurtainPanels(NuanceItem $item) {
    return array();
  }

  abstract public function getItemTypeDisplayName();
  abstract public function getItemDisplayName(NuanceItem $item);

  final public function updateItem(NuanceItem $item) {
    if (!$this->canUpdateItems()) {
      throw new Exception(
        pht(
          'This item type ("%s", of class "%s") can not update items.',
          $this->getItemTypeConstant(),
          get_class($this)));
    }

    $this->updateItemFromSource($item);
  }

  protected function updateItemFromSource(NuanceItem $item) {
    throw new PhutilMethodNotImplementedException();
  }

  final public function getItemTypeConstant() {
    return $this->getPhobjectClassConstant('ITEMTYPE', 64);
  }

  final public static function getAllItemTypes() {
    return id(new PhutilClassMapQuery())
      ->setAncestorClass(__CLASS__)
      ->setUniqueMethod('getItemTypeConstant')
      ->execute();
  }

  final protected function newItemAction(NuanceItem $item, $key) {
    $id = $item->getID();
    $action_uri = "/nuance/item/action/{$id}/{$key}/";

    return id(new PhabricatorActionView())
      ->setHref($action_uri);
  }

  final protected function newCurtainPanel(NuanceItem $item) {
    return id(new PHUICurtainPanelView());
  }

  final public function buildActionResponse(NuanceItem $item, $action) {
    $response = $this->handleAction($item, $action);

    if ($response === null) {
      return new Aphront404Response();
    }

    return $response;
  }

  protected function handleAction(NuanceItem $item, $action) {
    return null;
  }

  final public function applyCommand(
    NuanceItem $item,
    NuanceItemCommand $command) {

    $result = $this->handleCommand($item, $command);

    if ($result === null) {
      return;
    }

    $xaction = id(new NuanceItemTransaction())
      ->setTransactionType(NuanceItemTransaction::TYPE_COMMAND)
      ->setNewValue(
        array(
          'command' => $command->getCommand(),
          'parameters' => $command->getParameters(),
          'result' => $result,
        ));

    $viewer = $this->getViewer();

    // TODO: Maybe preserve the actor's original content source?
    $source = PhabricatorContentSource::newForSource(
      PhabricatorDaemonContentSource::SOURCECONST);

    $editor = id(new NuanceItemEditor())
      ->setActor($viewer)
      ->setActingAsPHID($command->getAuthorPHID())
      ->setContentSource($source)
      ->setContinueOnMissingFields(true)
      ->setContinueOnNoEffect(true)
      ->applyTransactions($item, array($xaction));
  }

  protected function handleCommand(
    NuanceItem $item,
    NuanceItemCommand $command) {
    return null;
  }

  final protected function newContentSource(
    NuanceItem $item,
    $agent_phid) {
    return PhabricatorContentSource::newForSource(
      NuanceContentSource::SOURCECONST,
      array(
        'itemPHID' => $item->getPHID(),
        'agentPHID' => $agent_phid,
      ));
  }

  protected function getActingAsPHID(NuanceItem $item) {
    return id(new PhabricatorNuanceApplication())->getPHID();
  }

}


text:
Spree::Admin::StockLocationsController.class_eval do
    include DomainedController
end


text:
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.conf import settings
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User

from projects.models import Project
from projects.forms import *

if "notification" in settings.INSTALLED_APPS:
    from notification import models as notification
else:
    notification = None

try:
    from friends.models import Friendship
    friends = True
except ImportError:
    friends = False

try:
    from threadedcomments.models import ThreadedComment
    forums = True
except ImportError:
    forums = False

try:
    from wiki.models import Article
    from wiki.views import get_ct
    wiki = True
except ImportError:
    wiki = False

# from microblogging.models import TweetInstance

TOPIC_COUNT_SQL = """
SELECT COUNT(*)
FROM projects_topic
WHERE projects_topic.project_id = projects_project.id
"""
MEMBER_COUNT_SQL = """
SELECT COUNT(*)
FROM projects_projectmember
WHERE projects_projectmember.project_id = projects_project.id
"""

def create(request, form_class=ProjectForm,
        template_name="projects/create.html"):
    if request.user.is_authenticated() and request.method == "POST":
        if request.POST["action"] == "create":
            project_form = form_class(request.POST)
            if project_form.is_valid():
                project = project_form.save(commit=False)
                project.creator = request.user
                project.save()
                project_member = ProjectMember(project=project, user=request.user)
                project.members.add(project_member)
                project_member.save()
                project_form = form_class()
                return HttpResponseRedirect(project.get_absolute_url())
        else:
            project_form = form_class()
    else:
        project_form = form_class()

    return render_to_response(template_name, {
        "project_form": project_form,
    }, context_instance=RequestContext(request))

def delete(request, slug, redirect_url=None):
    project = get_object_or_404(Project, slug=slug)
    if not redirect_url:
        redirect_url = reverse('project_list')

    if request.user.is_authenticated() and request.method == "POST" and request.user == project.creator:
        project.deleted = True
        project.save()
        request.user.message_set.create(message="Project %s deleted." % project)
        if notification:
            notification.send(project.member_users.all(), "projects_deleted", {"project": project})

    return HttpResponseRedirect(redirect_url)

def projects(request, template_name="projects/projects.html", order=None):
    projects = Project.objects.filter(deleted=False)
    search_terms = request.GET.get('search', '')
    if search_terms:
        projects = (projects.filter(name__icontains=search_terms) |
            projects.filter(description__icontains=search_terms))
    if order == 'least_topics':
        projects = projects.extra(select={'topic_count': TOPIC_COUNT_SQL})
        projects = projects.order_by('topic_count')
    elif order == 'most_topics':
        projects = projects.extra(select={'topic_count': TOPIC_COUNT_SQL})
        projects = projects.order_by('-topic_count')
    elif order == 'least_members':
        projects = projects.extra(select={'member_count': MEMBER_COUNT_SQL})
        projects = projects.order_by('member_count')
    elif order == 'most_members':
        projects = projects.extra(select={'member_count': MEMBER_COUNT_SQL})
        projects = projects.order_by('-member_count')
    elif order == 'name_ascending':
        projects = projects.order_by('name')
    elif order == 'name_descending':
        projects = projects.order_by('-name')
    elif order == 'date_oldest':
        projects = projects.order_by('-created')
    elif order == 'date_newest':
        projects = projects.order_by('created')
    context = {
        'projects': projects,
        'search_terms': search_terms,
        'order': order,
    }
    return render_to_response(
        template_name,
        context,
        context_instance=RequestContext(request)
    )

def your_projects(request, template_name="projects/your_projects.html"):
    return render_to_response(template_name, {
        "projects": Project.objects.filter(deleted=False, members__user=request.user).order_by("name"),
    }, context_instance=RequestContext(request))
your_projects = login_required(your_projects)

def project(request, slug, template_name="projects/project.html"):
    project = get_object_or_404(Project, slug=slug)

    if project.deleted:
        raise Http404

    photos = project.photos.all()
    if request.user.is_authenticated() and request.method == "POST" and request.user == project.creator:
        if request.POST["action"] == "update":
            adduser_form = AddUserForm(project=project)
            project_form = ProjectUpdateForm(request.POST, instance=project)
            if project_form.is_valid():
                project = project_form.save()
        elif request.POST["action"] == "add":
            project_form = ProjectUpdateForm(instance=project)
            adduser_form = AddUserForm(project, request.POST)
            if adduser_form.is_valid():
                adduser_form.save(project, request.user)
                adduser_form = AddUserForm(project=project) # @@@ is this the right way to clear it?
        else:
            project_form = ProjectUpdateForm(instance=project)
            adduser_form = AddUserForm(project=project)
    else:
        adduser_form = AddUserForm(project=project)
        project_form = ProjectUpdateForm(instance=project)

    topics = project.topics.all()[:5]
    articles = Article.objects.filter(
        content_type=get_ct(project),
        object_id=project.id).order_by('-last_update')
    total_articles = articles.count()
    articles = articles[:5]

    total_tasks = project.tasks.count()
    tasks = project.tasks.order_by("-modified")[:10]

    # tweets = TweetInstance.objects.tweets_for(project).order_by("-sent")

    are_member = project.has_member(request.user)

    return render_to_response(template_name, {
        "project_form": project_form,
        "adduser_form": adduser_form,
        "project": project,
        "photos": photos,
        "topics": topics,
        "articles": articles,
        "total_tasks": total_tasks,
        "tasks": tasks,
        "total_articles": total_articles,
        "are_member": are_member,
    }, context_instance=RequestContext(request))

def topics(request, slug, form_class=TopicForm,
        template_name="projects/topics.html"):
    project = get_object_or_404(Project, slug=slug)

    if project.deleted:
        raise Http404

    is_member = project.has_member(request.user)

    if request.method == "POST":
        if is_member:
            topic_form = form_class(request.POST)
            if topic_form.is_valid():
                topic = topic_form.save(commit=False)
                topic.project = project
                topic.creator = request.user
                topic.save()
                request.user.message_set.create(message="You have started the topic %s" % topic.title)
                if notification:
                    notification.send(project.member_users.all(), "projects_new_topic", {"creator": request.user, "topic": topic, "project": project})
                topic_form = form_class() # @@@ is this the right way to reset it?
        else:
            request.user.message_set.create(message="You are not a member and so cannot start a new topic")
            topic_form = form_class()
    else:
        topic_form = form_class()

    return render_to_response(template_name, {
        "project": project,
        "is_member": is_member,
        "topic_form": topic_form,
    }, context_instance=RequestContext(request))

def topic(request, id, template_name="projects/topic.html"):
    topic = get_object_or_404(Topic, id=id)

    if topic.project.deleted:
        raise Http404

    return render_to_response(template_name, {
        'topic': topic,
    }, context_instance=RequestContext(request))

def tasks(request, slug, form_class=TaskForm,
        template_name="projects/tasks.html"):
    project = get_object_or_404(Project, slug=slug)

    if project.deleted:
        raise Http404

    is_member = project.has_member(request.user)

    if request.user.is_authenticated() and request.method == "POST":
        if request.POST["action"] == "add_task":
            task_form = form_class(project, request.POST)
            if task_form.is_valid():
                task = task_form.save(commit=False)
                task.creator = request.user
                task.project = project
                # @@@ we should check that assignee is really a member
                task.save()
                request.user.message_set.create(message="added task '%s'" % task.summary)
                if notification:
                    notification.send(project.member_users.all(), "projects_new_task", {"creator": request.user, "task": task, "project": project})
                task_form = form_class(project=project) # @@@ is this the right way to clear it?
        else:
            task_form = form_class(project=project)
    else:
        task_form = form_class(project=project)

    group_by = request.GET.get("group_by")
    tasks = project.tasks.all()

    return render_to_response(template_name, {
        "project": project,
        "tasks": tasks,
        "group_by": group_by,
        "is_member": is_member,
        "task_form": task_form,
    }, context_instance=RequestContext(request))

def task(request, id, template_name="projects/task.html"):
    task = get_object_or_404(Task, id=id)
    project = task.project

    if project.deleted:
        raise Http404

    is_member = project.has_member(request.user)

    if is_member and request.method == "POST":
        if request.POST["action"] == "assign":
            status_form = StatusForm(instance=task)
            assign_form = AssignForm(project, request.POST, instance=task)
            if assign_form.is_valid():
                task = assign_form.save()
                request.user.message_set.create(message="assigned task to '%s'" % task.assignee)
                if notification:
                    notification.send(project.member_users.all(), "projects_task_assignment", {"user": request.user, "task": task, "project": project, "assignee": task.assignee})
        elif request.POST["action"] == "update_status":
            assign_form = AssignForm(project, instance=task)
            status_form = StatusForm(request.POST, instance=task)
            if status_form.is_valid():
                task = status_form.save()
                request.user.message_set.create(message="updated your status on the task")
                if notification:
                    notification.send(project.member_users.all(), "projects_task_status", {"user": request.user, "task": task, "project": project})
        else:
            assign_form = AssignForm(project, instance=task)
            status_form = StatusForm(instance=task)
            if request.POST["action"] == "mark_resolved" and request.user == task.assignee:
                task.state = '2'
                task.save()
                request.user.message_set.create(message="task marked resolved")
                if notification:
                    notification.send(project.member_users.all(), "projects_task_change", {"user": request.user, "task": task, "project": project, "new_state": "resolved"})
            elif request.POST["action"] == "mark_closed" and request.user == task.creator:
                task.state = '3'
                task.save()
                request.user.message_set.create(message="task marked closed")
                if notification:
                    notification.send(project.member_users.all(), "projects_task_change", {"user": request.user, "task": task, "project": project, "new_state": "closed"})
            elif request.POST["action"] == "reopen" and is_member:
                task.state = '1'
                task.save()
                request.user.message_set.create(message="task reopened")
                if notification:
                    notification.send(project.member_users.all(), "projects_task_change", {"user": request.user, "task": task, "project": project, "new_state": "reopened"})
    else:
        assign_form = AssignForm(project, instance=task)
        status_form = StatusForm(instance=task)

    return render_to_response(template_name, {
        "task": task,
        "is_member": is_member,
        "assign_form": assign_form,
        "status_form": status_form,
    }, context_instance=RequestContext(request))

def user_tasks(request, username, template_name="projects/user_tasks.html"):
    other_user = get_object_or_404(User, username=username)
    tasks = other_user.assigned_project_tasks.filter(project__deleted=False).order_by("state")

    return render_to_response(template_name, {
        "tasks": tasks,
        "other_user": other_user,
    }, context_instance=RequestContext(request))
user_tasks = login_required(user_tasks)

def members_status(request, slug, form_class=AwayForm,
        template_name="projects/members_status.html"):
    project = get_object_or_404(Project, slug=slug)

    if project.deleted:
        raise Http404

    is_member = project.has_member(request.user)
    try:
        project_member = project.members.get(user=request.user)
    except ProjectMember.DoesNotExist:
        project_member = None

    away_form = None
    if is_member and request.method == "POST":
        if request.POST["action"] == "set_away":
            away_form = form_class(request.POST)
            if away_form.is_valid():
                away_form.save(project_member)
                away_form = form_class()
        elif request.POST["action"] == "set_back":
            project_member.away = False
            project_member.save()

    if away_form is None:
        away_form = form_class()

    active_members = project.members.filter(away=False)
    away_members = project.members.filter(away=True).order_by('away_since')

    return render_to_response(template_name, {
        "project": project,
        "is_member": is_member,
        "project_member": project_member,
        "away_form": away_form,
        "active_members": active_members,
        "away_members": away_members,
    }, context_instance=RequestContext(request))
members_status = login_required(members_status)


text:
module Api
  module V1
    class ClientsController < ApiBaseController
      def search
        fill_in = params[:fill_in]
        if /last_name/.match fill_in
          search_attr='last_name'
        else
          search_attr='first_name'
        end

        @clients = Client.where "#{search_attr} like ?", "%#{params[:q]}%"
        autolist = @clients.map do |ct|
          if can?(:read, ct)
            resp={id: ct.id, label: ct.send(search_attr.to_sym), last_name: ct.last_name,
              first_name: ct.first_name, mr_number: ct.mr_number}
          end
          resp
        end.compact

        puts ">> response #{autolist.to_json}"

        respond_to do |fmt|
          fmt.json { render json: autolist }
        end
      end

      def update
        # Check if the role is allowed to execute this action
        update_action = params[:api_action]
        if !(action_rec = ApiAction.find_by_name(update_action)) or cannot?(:run_api_command, action_rec)
          send_response_failure
          return
        end

        # if it's a client specific update, check if the user has access to that resource
        ct=nil
        if params[:id]
          ct = Client.find params[:id]
          if ct.nil? or cannot?(:update, ct)
            send_response_failure
          end
        end

        if eval("#{action_rec.name}(ct, params)")
          set_response_success
          send_response
        else
          send_response_failure
        end
      end

      private
      # TODO none of these methods check if the underlying DB action fails
      def toggle_client_flag(ct, params)
        return if ct.nil?

        if(flag = ct.client_flags.select { |x| x.yes_no_flag and x.yes_no_flag.key == params[:flag_name]}.first)
          flag.toggle_value
          flag.save
        else
          # client hasn't been flagged so far, so now we flag it.
          flag=ClientFlag.new flag_value: 'yes'
          flag.yes_no_flag = YesNoFlag.find_by_key params[:flag_name]
          flag.save
          ct.client_flags << flag
        end

        set_response_field('flag_value', flag.flag_value.capitalize)

        true
      end

      def add_note(ct, params)
        return if ct.nil?

        f=FieldNote.new(author: current_user, client: ct, entry: params[:entry])
        f.save
        ct.field_notes << f

        set_response_field('entry', f.entry)

        true
      end

      def update_case_contact(ct, params)
        ct.case_contact_id = params[:new_case_contact_id]
        if ct.save
          true
        else
          false
        end
      end

      def set_client_priorities(ct, params)
        send_list = params[:priorities].each_with_index.map { |p, idx| [p.to_i, idx] }
        Client.change_priorities send_list, -1

        true
      end
    end
  end
end


text:
<!DOCTYPE html>
<html>
<head>
	<title>test</title>
	<script src="https://cdn.anychart.com/js/7.14.0/anychart.min.js"></script>
	<style>
		html,body,#test {
			margin: 0;
			widht: 100%;
			height: 100%;
		}
	</style>
</head>
<body>
<div id="test">
</div>
</body>
<script type="text/javascript">

	window.addEventListener( 'message' , function( event ) {
		window[ event.data[0] ].apply( null , event.data.slice( 1 ) )
	} )

	var stage = anychart.graphics.create( 'test' )
	var chart = anychart.line().container( stage ).draw()
	chart.legend().enabled( true )

	function fill( data ) {
		stage.suspend()
		for( var i = 0 ; i < data.graphs.length ; ++i ) {
			chart.line( data.graphs[ i ] ).markers({ type : 'circle' , size : 4 }).name( `Graph #${ i }` )
		}
		stage.resume()
	}

	function update( data ) {
		stage.suspend()
		for( var i = 0 ; i < data.graphs.length ; ++i ) {
			chart.getSeries(i).data( data.graphs[i] )
		}
		stage.resume()
	}

</script>
</html>


text:
layout: post
date:	2007-06-05 17:31:00
title:  And today....
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
"It's World Environment Day!" one of my friends said to me when I met her at her door in the morning. "We must take this seriously, unless each of us is careful, we will spoil the world!"
"Yes," I said.
"Just one minute...let me give the driver the keys....Ramappa, can you take the car to the store at the corner and pick up three eggs? Take the large car, the smaller one has less petrol, I will drop Neeraj in that...these drivers just guzzle the petrol!" she said.
"Yes," I said.
"It says in the paper that we must be really sparing and think green," she said.  "I just drove down and bought some plants from that lovely new nursery in North Bangalore which everyone says has the most exotic plants...aren't they lovely?"
"Yes," I said.
"And we must be careful of water, too...I don't intend watering these plants too often, perhaps that's why the last lot died...and yesterday my maid just left the tap open in the kitchen and I only noticed when I came home in the evening, can you believe it?"
"Yes," I said.
"And I buy vegetables only in that new mall which has come up, they give such lovely plastic bags, too, look, Green'n'Fresh, it's as good as anything you get in the States, isn't it?" she said.
"Yes," I said.
"I asked for a few extra, so that I can use them for other things and have less of waste. It's essential not to waste, isn't it?"
"Yes," I said.
"Muniamma! Just throw those three towels into the washing machine and start it, you can't keep waiting for more clothes!...where was I? Oh, yes, I felt so bad yesterday, having to throw such a lot of leftovers from my dinner party into the dustbin...Muniamma didn't turn up for work and I didn't want to put it all in the fridge. These servants are so unreliable, aren't they?"
"Yes," I said.
"But I'll cut her salary for the days she takes off she's always complaining that her husband beats her...oh, you've got your cycle keys...! It's so dangerous, you know, but you are SO eco-friendly..."
"Yes," I said.
"I couldn't cycle for nuts, especially in this hot weather.I just have to have the air-conditioning on... I really admire you!"
"Yes," I said.
"You are always such an inspiration to me! Oh well, it was nice chatting to you, I have to go in and make sure Muniamma washes the balcony properly...Muniamma, throw a few more buckets of water, and scrub the floor well! And don't forget to spray the pesticide in all the corners...I'll see you later, I have so much to do. Thank goodness we are all so aware of our environment!"
"Yes," I said. "Bye!"

Yes, that lady IS a figment of my imagination, but she is made up of several ladies who do exist...


text:
/* *
 * dataPage.js
 * Written by: Stephen Lindberg
 * Created: 7/11/11
 * Last modified: 7/19/11 by Stephen Lindberg
 *
 * This js file only contains a function for displaying time data collected by the prototypes in a printable web browser window.
 * Its purpose is to make data collection easier, especially for recording data from several hundred graph renderings. That would
 * be a lot of information to write down by hand!
 * */

/* *
 * displayDataWindow
 * Creates a pop-up window that displays data received from the calling prototype. The window will
 * 		immediately request itself to be printed.
 * Preconditions: This function assumes that your pop-up blocker is turned off.
 * Inputs: nodes is the number of nodes in our graph.
 * 		connectivity is the graph's connectivity
 * 		data is the time data collected by the calling prototype. data[0] contains the sum of all the collected time.
 * 			data[1] contains the number of time data recorded. data[2 - n+2] contains the individual time data.
 * 		dataType is a String to show what type of data the prototype recorded ("Initial Rendering" or "Interactive Redrawing").
 * 		tool is a String to show which tool was used by the prototype ("Canvas" or "SVG").
 * Postconditions: The data received by the prototype is nicely formatted and displayed in the window. The window will request itself
 * 		to be printed by pulling up the browser's print wizard.
 * */

function displayDataWindow(nodes, connectivity, data, dataType, tool)
{
	var dataCollectWindow=window.open('','','width=640,height=480');
	var pageStr = "";
	pageStr += "";
	pageStr += "Web-based Large Graph Visualization project
";
	pageStr += "Data collection form

";
	pageStr += "Measuring: " + dataType + "

";
	pageStr += "Tool: " + tool + "

";
	pageStr += "# Nodes: " + nodes + "
";
	pageStr += "Connectivity: " + connectivity + "

";
	if(dataType == "Initial Rendering")
	{
		pageStr += "Server Time (ms)

";
		pageStr += "
";

		var i;
		for(i = 0; i < data[1]; i++)
		{
			if(i % 10 == 0)
			{
				pageStr += "
";
			}
			pageStr += " " + data[i+103] + " 	";
			if(i % 10 == 9)
			{
				pageStr += "
";
			}
		}
		pageStr += "

";
		pageStr += "Average time (ms): " + (data[102] / data[1]) + "

";
	}
	pageStr += "Draw Times (ms)

";
	pageStr += "
";

	var i;
	for(i = 0; i < data[1]; i++)
	{
		if(i % 10 == 0)
		{
			pageStr += "
";
		}
		pageStr += " " + data[i+2] + " 	";
		if(i % 10 == 9)
		{
			pageStr += "
";
		}
	}

	pageStr += "

";
	pageStr += "Average time (ms): " + (data[0] / data[1]) + "

";
	if(dataType == "Initial Rendering")
		pageStr += "Total Average time (ms): " + ((data[0] / data[1]) + (data[102] / data[1])) + "

";
	pageStr += "";
	dataCollectWindow.document.write(pageStr);
	dataCollectWindow.focus();

	dataCollectWindow.document.onload = new function(evt){dataCollectWindow.print();};
}


text:
package io.enmasse.systemtest.isolated.infra.brokered;

import io.enmasse.address.model.AddressBuilder;
import io.enmasse.address.model.AddressSpaceBuilder;
import io.enmasse.admin.model.v1.AddressSpacePlan;
import io.enmasse.admin.model.v1.AddressSpacePlanBuilder;
import io.enmasse.admin.model.v1.BrokeredInfraConfig;
import io.enmasse.admin.model.v1.BrokeredInfraConfigBuilder;
import io.enmasse.admin.model.v1.BrokeredInfraConfigSpecAdmin;
import io.enmasse.admin.model.v1.BrokeredInfraConfigSpecAdminBuilder;
import io.enmasse.admin.model.v1.BrokeredInfraConfigSpecBroker;
import io.enmasse.admin.model.v1.BrokeredInfraConfigSpecBrokerBuilder;
import io.enmasse.admin.model.v1.ResourceAllowance;
import io.enmasse.admin.model.v1.ResourceRequest;
import io.enmasse.systemtest.bases.infra.InfraTestBase;
import io.enmasse.systemtest.bases.isolated.ITestIsolatedBrokered;
import io.enmasse.systemtest.infra.InfraConfiguration;
import io.enmasse.systemtest.model.address.AddressType;
import io.enmasse.systemtest.model.addressspace.AddressSpaceType;
import io.enmasse.systemtest.time.TimeoutBudget;
import io.enmasse.systemtest.utils.AddressUtils;
import io.enmasse.systemtest.utils.PlanUtils;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.junit.jupiter.api.Assertions.assertEquals;

class InfraTestBrokered extends InfraTestBase implements ITestIsolatedBrokered {

    @Test
    void testCreateInfra() throws Exception {
        PodTemplateSpec brokerTemplateSpec = PlanUtils.createTemplateSpec(Collections.singletonMap("mycomponent", "broker"), "mybrokernode", "broker");
        PodTemplateSpec adminTemplateSpec = PlanUtils.createTemplateSpec(Collections.singletonMap("mycomponent", "admin"), "myadminnode", "admin");
        BrokeredInfraConfig testInfra = new BrokeredInfraConfigBuilder()
                .withNewMetadata()
                .withName("test-infra-3-brokered")
                .endMetadata()
                .withNewSpec()
                .withVersion(environment.enmasseVersion())
                .withBroker(new BrokeredInfraConfigSpecBrokerBuilder()
                        .withAddressFullPolicy("FAIL")
                        .withNewResources()
                        .withMemory("512Mi")
                        .withStorage("1Gi")
                        .endResources()
                        .withJavaOpts("-Dsystemtest=property")
                        .withPodTemplate(brokerTemplateSpec)
                        .build())
                .withAdmin(new BrokeredInfraConfigSpecAdminBuilder()
                        .withNewResources()
                        .withMemory("512Mi")
                        .endResources()
                        .withPodTemplate(adminTemplateSpec)
                        .build())
                .endSpec()
                .build();
        resourcesManager.createInfraConfig(testInfra);

        exampleAddressPlan = PlanUtils.createAddressPlanObject("example-queue-plan-brokered", AddressType.QUEUE,
                Collections.singletonList(new ResourceRequest("broker", 1.0)));

        resourcesManager.createAddressPlan(exampleAddressPlan);

        AddressSpacePlan exampleSpacePlan = new AddressSpacePlanBuilder()
                .withNewMetadata()
                .withName("example-space-plan-brokered")
                .withNamespace(kubernetes.getInfraNamespace())
                .endMetadata()
                .withNewSpec()
                .withAddressSpaceType(AddressSpaceType.BROKERED.toString())
                .withShortDescription("Custom systemtests defined address space plan")
                .withInfraConfigRef(testInfra.getMetadata().getName())
                .withResourceLimits(Collections.singletonList(new ResourceAllowance("broker", 3.0))
                        .stream().collect(Collectors.toMap(ResourceAllowance::getName, ResourceAllowance::getMax)))
                .withAddressPlans(Collections.singletonList(exampleAddressPlan)
                        .stream().map(addressPlan -> addressPlan.getMetadata().getName()).collect(Collectors.toList()))
                .endSpec()
                .build();
        resourcesManager.createAddressSpacePlan(exampleSpacePlan);

        exampleAddressSpace = new AddressSpaceBuilder()
                .withNewMetadata()
                .withName("example-address-space")
                .withNamespace(kubernetes.getInfraNamespace())
                .endMetadata()
                .withNewSpec()
                .withType(AddressSpaceType.BROKERED.toString())
                .withPlan(exampleSpacePlan.getMetadata().getName())
                .withNewAuthenticationService()
                .withName("standard-authservice")
                .endAuthenticationService()
                .endSpec()
                .build();

        resourcesManager.createAddressSpace(exampleAddressSpace);

        resourcesManager.setAddresses(new AddressBuilder()
                .withNewMetadata()
                .withNamespace(exampleSpacePlan.getMetadata().getNamespace())
                .withName(AddressUtils.generateAddressMetadataName(exampleAddressSpace, "example-queue"))
                .endMetadata()
                .withNewSpec()
                .withType(AddressType.QUEUE.toString())
                .withAddress("example-queue")
                .withPlan(exampleAddressPlan.getMetadata().getName())
                .endSpec()
                .build());

        assertInfra(InfraConfiguration.broker(null, "512Mi", brokerTemplateSpec, "1Gi", "-Dsystemtest=property"),
                InfraConfiguration.admin(null, "512Mi", adminTemplateSpec));
    }

    @Test
    void testIncrementInfra() throws Exception {
        testReplaceInfra(InfraConfiguration.broker("500m", "1Gi", null, "2Gi", null),
                InfraConfiguration.admin("500m", "768Mi", null));
    }

    @Test
    void testDecrementInfra() throws Exception {
        testReplaceInfra(InfraConfiguration.broker("250m", "256Mi", null, "512Mi", null),
                InfraConfiguration.admin("250m", "256Mi", null));
    }

    void testReplaceInfra(InfraConfiguration brokerConfig, InfraConfiguration adminConfig) throws Exception {
        testCreateInfra();

        Boolean updatePersistentVolumeClaim = volumeResizingSupported();

        BrokeredInfraConfig infra = new BrokeredInfraConfigBuilder()
                .withNewMetadata()
                .withName("test-infra-2-brokered")
                .endMetadata()
                .withNewSpec()
                .withVersion(environment.enmasseVersion())
                .withBroker(new BrokeredInfraConfigSpecBrokerBuilder()
                        .withAddressFullPolicy("FAIL")
                        .withUpdatePersistentVolumeClaim(updatePersistentVolumeClaim)
                        .withNewResources()
                        .withCpu(brokerConfig.getCpu())
                        .withMemory(brokerConfig.getMemory())
                        .withStorage(brokerConfig.getBrokerStorage())
                        .endResources()
                        .build())
                .withAdmin(new BrokeredInfraConfigSpecAdminBuilder()
                        .withNewResources()
                        .withCpu(adminConfig.getCpu())
                        .withMemory(adminConfig.getMemory())
                        .endResources()
                        .build())
                .endSpec()
                .build();
        resourcesManager.createInfraConfig(infra);

        AddressSpacePlan exampleSpacePlan = new AddressSpacePlanBuilder()
                .withNewMetadata()
                .withName("example-space-plan2-brokered")
                .endMetadata()
                .withNewSpec()
                .withAddressSpaceType(AddressSpaceType.BROKERED.toString())
                .withShortDescription("Custom systemtests defined address space plan")
                .withInfraConfigRef(infra.getMetadata().getName())
                .withResourceLimits(Collections.singletonList(new ResourceAllowance("broker", 3.0))
                        .stream().collect(Collectors.toMap(ResourceAllowance::getName, ResourceAllowance::getMax)))
                .withAddressPlans(Collections.singletonList(exampleAddressPlan)
                        .stream().map(addressPlan -> addressPlan.getMetadata().getName()).collect(Collectors.toList()))
                .endSpec()
                .build();
        resourcesManager.createAddressSpacePlan(exampleSpacePlan);

        exampleAddressSpace = new AddressSpaceBuilder(exampleAddressSpace).editSpec().withPlan(exampleSpacePlan.getMetadata().getName()).endSpec().build();
        isolatedResourcesManager.replaceAddressSpace(exampleAddressSpace);

        if (!updatePersistentVolumeClaim) {
            brokerConfig.setBrokerStorage(null);
        }

        waitUntilInfraReady(
            () -> assertInfra(brokerConfig, adminConfig),
                new TimeoutBudget(5, TimeUnit.MINUTES));
    }

    @Test
    void testReadInfra() throws Exception {
        BrokeredInfraConfig testInfra = new BrokeredInfraConfigBuilder()
                .withNewMetadata()
                .withName("test-infra-1-brokered")
                .endMetadata()
                .withNewSpec()
                .withVersion(environment.enmasseVersion())
                .withBroker(new BrokeredInfraConfigSpecBrokerBuilder()
                        .withAddressFullPolicy("FAIL")
                        .withNewResources()
                        .withMemory("512Mi")
                        .withStorage("1Gi")
                        .endResources()
                        .build())
                .withAdmin(new BrokeredInfraConfigSpecAdminBuilder()
                        .withNewResources()
                        .withMemory("512Mi")
                        .endResources()
                        .build())
                .endSpec()
                .build();
        resourcesManager.createInfraConfig(testInfra);

        BrokeredInfraConfig actualInfra = resourcesManager.getBrokeredInfraConfig(testInfra.getMetadata().getName());

        assertEquals(testInfra.getMetadata().getName(), actualInfra.getMetadata().getName());

        BrokeredInfraConfigSpecAdmin expectedAdmin = testInfra.getSpec().getAdmin();
        BrokeredInfraConfigSpecAdmin actualAdmin = actualInfra.getSpec().getAdmin();
        assertEquals(expectedAdmin.getResources().getMemory(), actualAdmin.getResources().getMemory());

        BrokeredInfraConfigSpecBroker expectedBroker = testInfra.getSpec().getBroker();
        BrokeredInfraConfigSpecBroker actualBroker = actualInfra.getSpec().getBroker();
        assertEquals(expectedBroker.getResources().getMemory(), actualBroker.getResources().getMemory());
        assertEquals(expectedBroker.getResources().getStorage(), actualBroker.getResources().getStorage());
        assertEquals(expectedBroker.getAddressFullPolicy(), actualBroker.getAddressFullPolicy());
        assertEquals(expectedBroker.getStorageClassName(), actualBroker.getStorageClassName());

    }

    private boolean assertInfra(InfraConfiguration brokerConfig, InfraConfiguration adminConfig) {
        assertAdminConsole(adminConfig);
        assertBroker(brokerConfig);
        return true;
    }

}


text:
namespace content {
class BrowserContext;
}

namespace prerender {
class NoStatePrefetchLinkManager;
}

namespace weblayer {

class NoStatePrefetchProcessorImplDelegateImpl
    : public prerender::NoStatePrefetchProcessorImplDelegate {
 public:
  NoStatePrefetchProcessorImplDelegateImpl() = default;
  ~NoStatePrefetchProcessorImplDelegateImpl() override = default;

  // prerender::NoStatePrefetchProcessorImplDelegate overrides,
  prerender::NoStatePrefetchLinkManager* GetNoStatePrefetchLinkManager(
      content::BrowserContext* browser_context) override;
};

}  // namespace weblayer

#endif  // WEBLAYER_BROWSER_NO_STATE_PREFETCH_NO_STATE_PREFETCH_PROCESSOR_IMPL_DELEGATE_IMPL_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <display-name>jottings</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- <param-value> /WEB-INF/spring-servlet.xml,/WEB-INF/mybatis-config.xml
            </param-value> -->
        <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>1440</session-timeout>
    </session-config>

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <!--<filter>
        <filter-name>xssFilter</filter-name>
        <filter-class>com.anteoy.filter.XssFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>xssFilter</filter-name>
        <url-pattern>*.html</url-pattern>
      </filter-mapping>-->
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Travessa</tipo><logradouro>Seabra</logradouro><bairro>Peró</bairro><cidade>Cabo Frio</cidade><uf>RJ</uf><cep>28924198</cep></feed>


text:
package org.arsenal.framework.web.server;

import org.arsenal.framework.core.concurrent.ILifecycleState;

public abstract  class HttpServerHandler implements IHttpServer {

	protected int state = ILifecycleState.READY;

}


text:
<?php

namespace Yoast\WP\SEO\Integrations\Admin;

use WP_Post;
use Yoast\WP\SEO\Conditionals\Admin_Conditional;
use Yoast\WP\SEO\Integrations\Integration_Interface;
use Yoast\WP\SEO\Models\Indexable;
use Yoast\WP\SEO\Repositories\Indexable_Repository;

/**
 * Admin_Columns_Cache_Integration class.
 */
class Admin_Columns_Cache_Integration implements Integration_Interface {

	/**
	 * Cache of indexables.
	 *
	 * @var Indexable[]
	 */
	protected $indexable_cache = [];

	/**
	 * The indexable repository.
	 *
	 * @var Indexable_Repository
	 */
	protected $indexable_repository;

	/**
	 * Returns the conditionals based on which this loadable should be active.
	 *
	 * In this case: only when on an admin page.
	 *
	 * @return array The conditionals.
	 */
	public static function get_conditionals() {
		return [ Admin_Conditional::class ];
	}

	/**
	 * Admin_Columns_Cache_Integration constructor.
	 *
	 * @param Indexable_Repository $indexable_repository The indexable repository.
	 */
	public function __construct( Indexable_Repository $indexable_repository ) {
		$this->indexable_repository = $indexable_repository;
	}

	/**
	 * Registers the appropriate actions and filters to fill the cache with
	 * indexables on admin pages.
	 *
	 * This cache is used in showing the Yoast SEO columns on the posts overview
	 * page (e.g. keyword score, incoming link count, etc.)
	 */
	public function register_hooks() {
		// Hook into tablenav to calculate links and linked.
		\add_action( 'manage_posts_extra_tablenav', [ $this, 'maybe_fill_cache' ] );
	}

	/**
	 * Makes sure we calculate all values in one query by filling our cache beforehand.
	 *
	 * @param string $target Extra table navigation location which is triggered.
	 */
	public function maybe_fill_cache( $target ) {
		if ( $target === 'top' ) {
			$this->fill_cache();
		}
	}

	/**
	 * Fills the cache of indexables for all known post IDs.
	 */
	public function fill_cache() {
		global $wp_query;

		// No need to continue building a cache if the main query did not return anything to cache.
		if ( empty( $wp_query->posts ) ) {
			return;
		}

		$posts    = $wp_query->posts;
		$post_ids = [];

		// Post lists return a list of objects.
		if ( isset( $posts[0] ) && \is_a( $posts[0], 'WP_Post' ) ) {
			$post_ids = \wp_list_pluck( $posts, 'ID' );
		}
		elseif ( isset( $posts[0] ) && \is_object( $posts[0] ) ) {
			$post_ids = $this->get_current_page_page_ids( $posts );
		}
		elseif ( ! empty( $posts ) ) {
			// Page list returns an array of post IDs.
			$post_ids = \array_keys( $posts );
		}

		if ( empty( $post_ids ) ) {
			return;
		}

		if ( isset( $posts[0] ) && ! \is_a( $posts[0], WP_Post::class ) ) {
			// Prime the post caches as core would to avoid duplicate queries.
			// This needs to be done as this executes before core does.
			\_prime_post_caches( $post_ids );
		}

		$indexables = $this->indexable_repository->find_by_multiple_ids_and_type( $post_ids, 'post', false );

		foreach ( $indexables as $indexable ) {
			$this->indexable_cache[ $indexable->object_id ] = $indexable;
		}
	}

	/**
	 * Returns the indexable for a given post ID.
	 *
	 * @param int $post_id The post ID.
	 *
	 * @return Indexable|false The indexable. False if none could be found.
	 */
	public function get_indexable( $post_id ) {
		if ( ! \array_key_exists( $post_id, $this->indexable_cache ) ) {
			$this->indexable_cache[ $post_id ] = $this->indexable_repository->find_by_id_and_type( $post_id, 'post' );
		}
		return $this->indexable_cache[ $post_id ];
	}

	/**
	 * Gets all the page IDs set to be shown on the current page.
	 * This is copied over with some changes from WP_Posts_List_Table::_display_rows_hierarchical.
	 *
	 * @param array $pages The pages, each containing an ID and post_parent.
	 *
	 * @return array The IDs of all pages shown on the current page.
	 */
	private function get_current_page_page_ids( $pages ) {
		global $per_page;
		$pagenum = isset( $_REQUEST['paged'] ) ? \absint( $_REQUEST['paged'] ) : 0;
		$pagenum = \max( 1, $pagenum );

		/*
		 * Arrange pages into two parts: top level pages and children_pages
		 * children_pages is two dimensional array, eg.
		 * children_pages[10][] contains all sub-pages whose parent is 10.
		 * It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations
		 * If searching, ignore hierarchy and treat everything as top level
		 */
		if ( empty( $_REQUEST['s'] ) ) {
			$top_level_pages = [];
			$children_pages  = [];
			$pages_map       = [];

			foreach ( $pages as $page ) {

				// Catch and repair bad pages.
				if ( $page->post_parent === $page->ID ) {
					$page->post_parent = 0;
				}

				if ( $page->post_parent === 0 ) {
					$top_level_pages[] = $page;
				}
				else {
					$children_pages[ $page->post_parent ][] = $page;
				}
				$pages_map[ $page->ID ] = $page;
			}

			$pages = &$top_level_pages;
		}

		$count      = 0;
		$start      = ( ( $pagenum - 1 ) * $per_page );
		$end        = ( $start + $per_page );
		$to_display = [];

		foreach ( $pages as $page ) {
			if ( $count >= $end ) {
				break;
			}

			if ( $count >= $start ) {
				$to_display[] = $page->ID;
			}

			++$count;

			$this->get_child_page_ids( $children_pages, $count, $page->ID, $start, $end, $to_display, $pages_map );
		}

		// If it is the last pagenum and there are orphaned pages, display them with paging as well.
		if ( isset( $children_pages ) && $count < $end ) {
			foreach ( $children_pages as $orphans ) {
				foreach ( $orphans as $op ) {
					if ( $count >= $end ) {
						break;
					}

					if ( $count >= $start ) {
						$to_display[] = $op->ID;
					}

					++$count;
				}
			}
		}

		return $to_display;
	}

	/**
	 * Adds all child pages due to be shown on the current page to the $to_display array.
	 * Copied over with some changes from WP_Posts_List_Table::_page_rows.
	 *
	 * @param array $children_pages The full map of child pages.
	 * @param int   $count          The number of pages already processed.
	 * @param int   $parent         The parent that's currently being processed.
	 * @param int   $start          The number at which the current overview starts.
	 * @param int   $end            The number at which the current overview ends.
	 * @param int   $to_display     The page IDs to be shown.
	 * @param int   $pages_map      A map of page ID to an object with ID and post_parent.
	 *
	 * @return void
	 */
	private function get_child_page_ids( &$children_pages, &$count, $parent, $start, $end, &$to_display, &$pages_map ) {
		if ( ! isset( $children_pages[ $parent ] ) ) {
			return;
		}

		foreach ( $children_pages[ $parent ] as $page ) {
			if ( $count >= $end ) {
				break;
			}

			// If the page starts in a subtree, print the parents.
			if ( $count === $start && $page->post_parent > 0 ) {
				$my_parents = [];
				$my_parent  = $page->post_parent;
				while ( $my_parent ) {
					// Get the ID from the list or the attribute if my_parent is an object.
					$parent_id = $my_parent;
					if ( \is_object( $my_parent ) ) {
						$parent_id = $my_parent->ID;
					}

					$my_parent    = $pages_map[ $parent_id ];
					$my_parents[] = $my_parent;
					if ( ! $my_parent->post_parent ) {
						break;
					}
					$my_parent = $my_parent->post_parent;
				}
				while ( $my_parent = \array_pop( $my_parents ) ) {
					$to_display[] = $my_parent->ID;
				}
			}

			if ( $count >= $start ) {
				$to_display[] = $page->ID;
			}

			++$count;

			$this->get_child_page_ids( $children_pages, $count, $page->ID, $start, $end, $to_display, $pages_map );
		}

		unset( $children_pages[ $parent ] ); // Required in order to keep track of orphans.
	}
}


text:
import {Route, Routes } from "react-router-dom";
import React, { Suspense } from "react";
import {SelfAdminPageContainer} from "./SelfAdminPageContainer";
import {ProgressBar} from "../common/ProgressBar";
import { Alert } from "@material-ui/lab";
import { Span } from "../common/theme/typography/Tags";
import { Trans } from "react-i18next";
import LinkExtern from "../common/theme/LinkExtern";
import { CONSTANTS } from "@runningdinner/shared";
import { Box } from "@material-ui/core";

const SelfAdminChangeTeamHostPage = React.lazy(() => import('./SelfAdminChangeTeamHostPage'));
const SelfAdminDinnerRoutePage = React.lazy(() => import('./SelfAdminDinnerRoutePage'));
const SelfAdminManageTeamPartnerWishPage = React.lazy(() => import('./SelfAdminManageTeamPartnerWishPage'));

export function SelfAdminRoute() {

  return (
    <Routes>
        <Route path={`:selfAdminId/teamhost/:participantId/:teamId`} element={
          <Suspense fallback={<ProgressBar showLoadingProgress={true} />}>
            <SelfAdminPageContainer htmlPageTitleI18n="host_manage_title">
              <SelfAdminChangeTeamHostPage />
            </SelfAdminPageContainer>
          </Suspense>
        } />

        <Route path={`:selfAdminId/dinnerroute/:participantId/:teamId`} element={
          <Suspense fallback={<ProgressBar showLoadingProgress={true} />}>
            <SelfAdminPageContainer htmlPageTitleI18n="dinnerroute_title">
              <SelfAdminDinnerRoutePage />
            </SelfAdminPageContainer>
          </Suspense>
        } />

        <Route path={`:selfAdminId/teampartnerwish/:participantId`} element={
          <Suspense fallback={<ProgressBar showLoadingProgress={true} />}>
            <SelfAdminPageContainer htmlPageTitleI18n="team_partner_wish_manage_title">
              <SelfAdminManageTeamPartnerWishPage />
            </SelfAdminPageContainer>
          </Suspense>
        } />

        <Route path="*" element={
          <Box my={3}>
            <Alert severity={"error"} variant={"outlined"}>
              <Span>
                <Trans i18nKey={"selfadmin:invalid_url"} values={{adminEmail: CONSTANTS.GLOBAL_ADMIN_EMAIL}}
                  // @ts-ignore
                       components={{ anchor: <LinkExtern /> }} />
              </Span>
            </Alert>
          </Box>
        } />

    </Routes>
  );
}


text:
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core;

namespace Azure.Analytics.Synapse.Artifacts.Models
{
    [JsonConverter(typeof(BigDataPoolResourceInfoListResultConverter))]
    public partial class BigDataPoolResourceInfoListResult
    {
        internal static BigDataPoolResourceInfoListResult DeserializeBigDataPoolResourceInfoListResult(JsonElement element)
        {
            Optional<string> nextLink = default;
            Optional<IReadOnlyList<BigDataPoolResourceInfo>> value = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<BigDataPoolResourceInfo> array = new List<BigDataPoolResourceInfo>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(BigDataPoolResourceInfo.DeserializeBigDataPoolResourceInfo(item));
                    }
                    value = array;
                    continue;
                }
            }
            return new BigDataPoolResourceInfoListResult(nextLink.Value, Optional.ToList(value));
        }

        internal partial class BigDataPoolResourceInfoListResultConverter : JsonConverter<BigDataPoolResourceInfoListResult>
        {
            public override void Write(Utf8JsonWriter writer, BigDataPoolResourceInfoListResult model, JsonSerializerOptions options)
            {
                throw new NotImplementedException();
            }
            public override BigDataPoolResourceInfoListResult Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                using var document = JsonDocument.ParseValue(ref reader);
                return DeserializeBigDataPoolResourceInfoListResult(document.RootElement);
            }
        }
    }
}


text:
"""Validate the locations in the downloaded checklists.

Validation Tests:

   Location:
       1. the location is a dict.

   LocationIdentifier (optional):
       1. identifier is a string.
       2. identifier is set.
       3. identifier does not have leading/trailing whitespace.

   LocationName:
       1. name is a string.
       2. name is set.
       3. name does not have leading/trailing whitespace.

   LocationCounty (optional):
       1. county is a string.

   LocationRegion (optional):
       1. region is a string.

   LocationCountry:
       1. country is a string.

   LocationCoordinates
       1. latitude and longitude are floats.

"""
from checklists_scrapers.tests.validation import checklists, ValidationTestCase

class Location(ValidationTestCase):
    """Validate the locations in the downloaded checklists."""

    def setUp(self):
        """Initialize the test."""
        self.locations = [(checklist['location'], checklist['source'])
                          for checklist in checklists]

    def test_location_type(self):
        """Verify the locations field contains a dict."""
        for location, source in self.locations:
            self.assertIsInstance(location, dict, msg=source)

class LocationIdentifier(ValidationTestCase):
    """Validate the location identifier in the downloaded checklists.

    This field is optional.
    """

    def setUp(self):
        """Initialize the test."""
        self.identifiers = [
            (checklist['location']['identifier'], checklist['source'])
            for checklist in checklists
            if 'identifier' in checklist['location']
        ]

    def test_identifier_type(self):
        """Verify the location identifier is a unicode string."""
        for identifier, source in self.identifiers:
            self.assertIsInstance(identifier, unicode, msg=source)

    def test_identifier_set(self):
        """Verify the location identifier is set."""
        for identifier, source in self.identifiers:
            self.assertTrue(identifier, msg=source)

    def test_identifier_stripped(self):
        """Verify the location identifier has no extra whitespace."""
        for identifier, source in self.identifiers:
            self.assertStripped(identifier, msg=source)

class LocationName(ValidationTestCase):
    """Validate the location name in the downloaded checklists."""

    def setUp(self):
        """Initialize the test."""
        self.locations = [(checklist['location'], checklist['source'])
                          for checklist in checklists]

    def test_name_type(self):
        """Verify the location name is a unicode string."""
        for location, source in self.locations:
            self.assertIsInstance(location['name'], unicode, msg=source)

    def test_name_set(self):
        """Verify the location name is set."""
        for location, source in self.locations:
            self.assertTrue(location['name'], msg=source)

    def test_name_stripped(self):
        """Verify the location name has no extra whitespace."""
        for location, source in self.locations:
            self.assertStripped(location['name'], msg=source)

class LocationCounty(ValidationTestCase):
    """Validate the location county name in the downloaded checklists.

    This field is optional.
    """

    def setUp(self):
        """Initialize the test."""
        self.counties = [(checklist['location']['county'], checklist['source'])
                         for checklist in checklists
                         if 'county' in checklist['location']]

    def test_county_type(self):
        """Verify the location county is a unicode string."""
        for county, source in self.counties:
            self.assertIsInstance(county, unicode, msg=source)

class LocationRegion(ValidationTestCase):
    """Validate the location region name in the downloaded checklists.

    This field is optional.
    """

    def setUp(self):
        """Initialize the test."""
        self.regions = [(checklist['location']['region'], checklist['source'])
                        for checklist in checklists
                        if 'region' in checklist['location']]

    def test_region_type(self):
        """Verify the location county is a unicode string."""
        for region, source in self.regions:
            self.assertIsInstance(region, unicode, msg=source)

class LocationCountry(ValidationTestCase):
    """Validate the location country name in the downloaded checklists."""

    def setUp(self):
        """Initialize the test."""
        self.locations = [(checklist['location'], checklist['source'])
                          for checklist in checklists]

    def test_country_type(self):
        """Verify the location country is a unicode string."""
        for location, source in self.locations:
            self.assertIsInstance(location['country'], unicode, msg=source)

class LocationCoordinates(ValidationTestCase):
    """Validate the latitude and longitude fields."""

    def setUp(self):
        """Initialize the test."""
        self.locations = [(checklist['location'], checklist['source'])
                          for checklist in checklists]

    def test_latitude(self):
        """Verify the location latitude is a unicode string."""
        for location, source in self.locations:
            self.assertIsInstance(location['lat'], float, msg=source)

    def test_longitude(self):
        """Verify the location longitude is a unicode string."""
        for location, source in self.locations:
            self.assertIsInstance(location['lon'], float, msg=source)


text:
var size = 1024 * 128; // * 256;

function randomizeChar() {
    return 97 + Math.round(Math.random() * 25);
}

function buildString() {
    var longString = "";
    for (var i = 0; i < size; i++) {
        longString += String.fromCharCode(randomizeChar());
    }
    return longString;
}

function buildBuffer() {
    var buffer = new Buffer(size);
    for (var i = 0; i < buffer.length; i++) {
        buffer[i] = randomizeChar();
    }

    return buffer.toString("utf-8");
}

console.time("buildString");
buildString();
console.timeEnd("buildString");
console.time("buildBuffer");
buildBuffer();
console.timeEnd("buildBuffer");


text:
package net.sf.mmm.util.contenttype.impl;

import java.util.List;

import net.sf.mmm.util.contenttype.base.ContentTypeBean;
import net.sf.mmm.util.contenttype.base.DecisionTreeNode;
import net.sf.mmm.util.io.api.spi.DetectorStreamProcessor;
import net.sf.mmm.util.io.base.AbstractDetectorStreamProcessorFactory;

/**
 * This is the implementation of {@link net.sf.mmm.util.io.api.spi.DetectorStreamProcessorFactory} for
 * {@link ContentTypeDetectorStreamProcessor}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
public class ContentTypeDetectorStreamProcessorFactory extends AbstractDetectorStreamProcessorFactory {

  /** The top-level {@link DecisionTreeNode}. */
  private final DecisionTreeNode rootNode;

  private final int lookaheadCount;

  /**
   * The constructor.
   *
   * @param rootNode is the top-level {@link DecisionTreeNode}.
   * @param lookaheadCount - see {@link #getLookaheadCount()}.
   */
  public ContentTypeDetectorStreamProcessorFactory(DecisionTreeNode rootNode, int lookaheadCount) {

    super();
    this.rootNode = rootNode;
    this.lookaheadCount = lookaheadCount;
  }

  @Override
  public int getLookaheadCount() {

    return this.lookaheadCount;
  }

  @Override
  public DetectorStreamProcessor createProcessor() {

    List<ContentTypeBean> contentTypes = null;
    return new ContentTypeDetectorStreamProcessor(contentTypes);
  }

}


text:
using Expressive.Expressions;
using System;

namespace Expressive.Functions.Conversion
{
    internal sealed class DecimalFunction : FunctionBase
    {
        #region FunctionBase Members

        public override string Name => "Decimal";

        public override object Evaluate(IExpression[] parameters, Context context)
        {
            this.ValidateParameterCount(parameters, 1, 1);

            var objectToConvert = parameters[0].Evaluate(this.Variables);

            // No point converting if there is nothing to convert.
            if (objectToConvert is null) { return null; }

            return Convert.ToDecimal(objectToConvert, context.CurrentCulture);
        }

        #endregion
    }
}


text:
import os
import sys
import unittest

import rospy
import rosunit

class CleanMasterTest(unittest.TestCase):

    def test_clean_master(self):
        self.failIf(rospy.has_param('dirty'))
        rospy.set_param('dirty', True)

if __name__ == '__main__':
    rosunit.unitrun('test_rostest', 'test_clean_master', CleanMasterTest, coverage_packages=[])


text:
@echo off

powershell .\install.dependencies.ps1
if %errorlevel% neq 0 exit /b %errorlevel%

..\..\tools\windows\gs1000w32.exe /S
if %errorlevel% neq 0 exit /b %errorlevel%


text:
var _ = require('lodash');

module.exports = function (db) {

  var MatchDb = require('./db')('match', db);

  var ret = {};

  ret.get = function (time, fn) {
    MatchDb.get(time, fn);
  };

  ret.save = function (match, fn) {
    MatchDb.save(match.date, match.json(), fn);
  };

  ret.updateScore = function (time, score, fn) {
    MatchDb.get(time, function (err, match) {
      if(err) return fn(err);

      match.score.a = score.a;
      match.score.b = score.b;

      MatchDb.save(time, match, function (err, match) {
        if (err) return fn(err);
        fn(null, score);
      });
    });
  };

  ret.all = function (fn) {
    MatchDb.all("", function (err, matches) {
      if (err) return fn(err);
      fn(null, matches);
    });
  };

  return ret;
};


text:
/**
 * This module adds Publisher Provided ids support to the User ID module
 * The {@link module:modules/userId} module is required.
 * @module modules/pubProvidedSystem
 * @requires module:modules/userId
 */

import {submodule} from '../src/hook.js';
import { logInfo, isArray } from '../src/utils.js';

const MODULE_NAME = 'pubProvidedId';

/** @type {Submodule} */
export const pubProvidedIdSubmodule = {

  /**
   * used to link submodule with config
   * @type {string}
   */
  name: MODULE_NAME,

  /**
   * decode the stored id value for passing to bid request
   * @function
   * @param {string} value
   * @returns {{pubProvidedId: array}} or undefined if value doesn't exists
   */
  decode(value) {
    const res = value ? {pubProvidedId: value} : undefined;
    logInfo('PubProvidedId: Decoded value ' + JSON.stringify(res));
    return res;
  },

  /**
   * performs action to obtain id and return a value.
   * @function
   * @param {SubmoduleConfig} [config]
   * @returns {{id: array}}
   */
  getId(config) {
    const configParams = (config && config.params) || {};
    let res = [];
    if (isArray(configParams.eids)) {
      res = res.concat(configParams.eids);
    }
    if (typeof configParams.eidsFunction === 'function') {
      res = res.concat(configParams.eidsFunction());
    }
    return {id: res};
  }
};

// Register submodule for userId
submodule('userId', pubProvidedIdSubmodule);


text:
package edu.uw.easysrl.lemmatizer;

/* author: Michael Schmitz <schmmd@cs.washington.edu>
 *
 * This is a light wrapper for the JFLEX-generated code from the original lex
 * morpha stemmer.  It provides a nicer interface and handles exceptions.
 */

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class MorphaStemmer {
	private static final Pattern whitespace = Pattern.compile("\\s+");

	private final static Map<String, String> cache = new HashMap<>();

	/***
	 * Stem the supplied token.
	 *
	 * @throws IllegalArgumentException
	 *             token contains whitespace
	 **/
	public static String stemToken(final String token) {
		String result = cache.get(token);

		if (result == null) {
			if (whitespace.matcher(token).find()) {
				throw new IllegalArgumentException(
						"Token may not contain a space: " + token);
			}
			result = morpha(cleanText(token), false);
			synchronized (cache) {
				cache.put(token, result);
			}
		}

		return result;
	}

	/***
	 * Stem the supplied token using supplemental postag information.
	 *
	 * @throws IllegalArgumentException
	 *             token contains whitespace
	 **/
	public static String stemToken(final String token, final String postag) {
		if (whitespace.matcher(token).find()) {
			throw new IllegalArgumentException(
					"Token may not contain a space: " + token);
		}
		return morpha(cleanText(token) + "_" + postag, true);
	}

	private static String cleanText(final String text) {
		return text.replaceAll("_", "-");
	}

	/***
	 * Run the morpha algorithm on the specified string.
	 **/
	public static String morpha(final String text, final boolean tags) {
		if (text.isEmpty()) {
			return "";
		}

		final String[] textParts = whitespace.split(text);

		final StringBuilder result = new StringBuilder();
		try {
			for (int i = 0; i < textParts.length; i++) {
				final Morpha morpha = new Morpha(
						new StringReader(textParts[i]), tags);

				if (result.length() != 0) {
					result.append(" ");
				}

				result.append(morpha.next());
			}
		}
		// yes, Morpha is cool enough to throw Errors
		// usually when the text contains underscores
		catch (final Error e) {
			return text;
		} catch (final java.io.IOException e) {
			return text;
		}

		return result.toString();
	}
}


text:
/*
 * cubegeometry.h
 *
 *  Created on: 9. des. 2015
 *      Author: larso
 */

#ifndef SRC_SCENE_CUBEGEOMETRY_H_
#define SRC_SCENE_CUBEGEOMETRY_H_

#include "arraygeometry.h"

namespace scene
{

class cube_geometry : public array_geometry
{
public:
    cube_geometry();
};

} /* namespace scene */

#endif /* SRC_SCENE_CUBEGEOMETRY_H_ */


text:
package net.bingosoft.oss.ssoclient;

import net.bingosoft.oss.ssoclient.exception.InvalidCodeException;
import net.bingosoft.oss.ssoclient.exception.InvalidTokenException;
import net.bingosoft.oss.ssoclient.exception.TokenExpiredException;
import net.bingosoft.oss.ssoclient.model.AccessToken;
import net.bingosoft.oss.ssoclient.model.Authentication;
import net.bingosoft.oss.ssoclient.spi.CacheProvider;
import net.bingosoft.oss.ssoclient.spi.CacheProviderImpl;
import net.bingosoft.oss.ssoclient.spi.TokenProvider;
import net.bingosoft.oss.ssoclient.spi.TokenProviderImpl;

import javax.servlet.http.HttpServletRequest;

/**
 * 客户端入口类,所有公开的操作都从这个入口类进行调用。
 */
public class SSOClient {

    protected SSOConfig     config;
    protected CacheProvider cacheProvider;
    protected TokenProvider tokenProvider;

    public SSOClient() {

    }

    public SSOClient(SSOConfig config) {
        this.config = config;
    }

    /**
     * 验证访问令牌并返回认证信息
     *
     *

     * 在Servlet容器中可以通过调用{@link SSOUtils#extractAccessToken(HttpServletRequest)}获取到访问令牌。
     *
     * @throws InvalidTokenException 如果accessToken是无效的
     * @throws TokenExpiredException 如果accessToken已经过期
     */
    public Authentication verifyAccessToken(String accessToken) throws InvalidTokenException, TokenExpiredException{
        CacheProvider cp = cp();

        Authentication authc = cp.get(accessToken);
        if(null != authc) {
            if(!authc.isExpired()) {
                return authc;
            }else{
                cp.remove(accessToken);
            }
        }

        boolean jwt = checkJwtToken(accessToken);
        if(jwt) {
            authc = tp().verifyJwtAccessToken(accessToken);
        }else{
            authc = tp().verifyBearerAccessToken(accessToken);
        }

        cp.put(accessToken, authc, authc.getExpires());

        return authc;
    }

    /**
     * 验证登录后获取到的Id Token并返回认证信息。
     *
     * @throws InvalidTokenException 如果idToken是无效的
     * @throws TokenExpiredException 如果idToken已经过期
     *
     * @since 3.0.1
     */
    public Authentication verifyIdToken(String idToken) throws InvalidTokenException, TokenExpiredException {
        CacheProvider cp = cp();
        Authentication authc = cp.get(idToken);
        if(null != authc) {
            if(!authc.isExpired()) {
                return authc;
            }else{
                cp.remove(idToken);
            }
        }

        //check is jwt token?
        boolean jwt = checkJwtToken(idToken);
        if(jwt) {
            authc = tp().verifyIdToken(idToken);
        }else{
            throw new InvalidTokenException("idToken is not and jwt token:"+idToken);
        }

        cp.put(idToken, authc, authc.getExpires());

        return authc;
    }

    /**
     * 验证登录后获取到的授权码并返回access token。
     *
     * 返回代表用户和应用的access token,这里的用户和应用由authorizationCode决定
     *
     * @throws InvalidTokenException
     * @throws TokenExpiredException
     */
    public AccessToken obtainAccessTokenByCode(String authorizationCode) throws InvalidCodeException, TokenExpiredException {
        AccessToken token = tp().obtainAccessTokenByAuthzCode(authorizationCode);
        return token;
    }

    /**
     * 使用client_id和client_secret通过grant_type=client_credentials的方式
     * 获取access token。
     *
     * 返回SSO颁发给当前应用的access token,代表当前应用的身份。
     *
     * @see ClientAuthentication
     *
     * @since 3.0.1
     */
    public AccessToken obtainAccessTokenByClientCredentials() throws TokenExpiredException{
        String key = "obtainAccessTokenByClientCredentials:"+config.getClientId();
        AccessToken accessToken = getAccessTokenFromCache(key);
        if (accessToken != null){
            return accessToken;
        }

        accessToken = tp().obtainAccessTokenByClientCredentials();
        cp().put(key,accessToken,accessToken.getExpires());
        return accessToken;
    }

    /**
     * 使用client_id和client_secret加上用户的access token获取一个新的access token,
     *
     * 新的access token是SSO颁发给用户和当前应用的,这里的用户由accessToken决定
     *
     * 返回代表用户和当前应用的身份的access token。
     *
     * @throws InvalidTokenException 如果传入的accessToken是无效的
     * @throws TokenExpiredException 如果传入的accessToken已经过期
     *
     * @since 3.0.1
     */
    public AccessToken obtainAccessTokenByToken(String accessToken) throws InvalidTokenException, TokenExpiredException{
        String key = "obtainAccessTokenByToken:"+accessToken;
        AccessToken token = getAccessTokenFromCache(key);
        if (token != null){
            return token;
        }

        boolean isJwt = checkJwtToken(accessToken);
        if(isJwt){
            token = tp().obtainAccessTokenByClientCredentialsWithJwtToken(accessToken);
        }else {
            token = tp().obtainAccessTokenByClientCredentialsWithBearerToken(accessToken);
        }
        cp().put(key,token,token.getExpires());
        return token;
    }

    /**
     * 使用accessToken中所带的refreshToken获取一个新的access token,
     *
     * 新的accessToken包含的信息和传入的accessToken一致
     *
     * @throws InvalidTokenException 如果传入的accessToken所带的refreshToken是无效的
     * @throws TokenExpiredException 如果传入的accessToken所带的refreshToken已经过期
     *
     * @since 3.0.3
     */
    public AccessToken refreshAccessToken(AccessToken accessToken) throws InvalidTokenException, TokenExpiredException{
        return tp().refreshAccessToken(accessToken);
    }

    protected AccessToken getAccessTokenFromCache(String key){
        CacheProvider cp = cp();
        AccessToken token = cp.get(key);
        if(token != null){
            if(!token.isExpired()){
                return token;
            }else {
                cp.remove(key);
            }
        }
        return null;
    }

    protected boolean checkJwtToken(String accessToken) {
        return accessToken.contains(".");
    }

    protected final CacheProvider cp() {
        if(null == cacheProvider) {
            synchronized (this) {
                if(null == cacheProvider) {
                    cacheProvider = new CacheProviderImpl();
                }
            }
        }
        return cacheProvider;
    }

    protected final TokenProvider tp() {
        if(null == tokenProvider) {
            synchronized (this) {
                if(null == tokenProvider) {
                    tokenProvider = new TokenProviderImpl(getConfig());
                }
            }
        }
        return tokenProvider;
    }

    //================================ getters & setters ======================================

    public SSOConfig getConfig() {
        return config;
    }

    public void setConfig(SSOConfig config) {
        this.config = config;
    }

    public CacheProvider getCacheProvider() {
        return cacheProvider;
    }

    public void setCacheProvider(CacheProvider cacheProvider) {
        this.cacheProvider = cacheProvider;
    }

    public TokenProvider getTokenProvider() {
        return tokenProvider;
    }

    public void setTokenProvider(TokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }

}


text:
<!DOCTYPE html>

    <meta encoding="utf-8" />
    <title>Emojie test page</title>

🎤test💁

🎤test💁

🎤test💁

Can render emoji