text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\JsonLd;

use ApiPlatform\Core\Api\UrlGeneratorInterface;
use ApiPlatform\Core\JsonLd\ContextBuilder;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use ApiPlatform\Core\Metadata\Property\PropertyNameCollection;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\ResourceMetadata;
use ApiPlatform\Core\Metadata\Resource\ResourceNameCollection;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Dto\OutputDto;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy;
use PHPUnit\Framework\TestCase;
use Symfony\Component\PropertyInfo\Type;

/**
 * @author Markus Mächler <markus.maechler@bithost.ch>
 */
class ContextBuilderTest extends TestCase
{
    private $entityClass;
    private $resourceNameCollectionFactoryProphecy;
    private $resourceMetadataFactoryProphecy;
    private $propertyNameCollectionFactoryProphecy;
    private $propertyMetadataFactoryProphecy;
    private $urlGeneratorProphecy;

    protected function setUp(): void
    {
        $this->entityClass = '\Dummy\DummyEntity';
        $this->resourceNameCollectionFactoryProphecy = $this->prophesize(ResourceNameCollectionFactoryInterface::class);
        $this->resourceMetadataFactoryProphecy = $this->prophesize(ResourceMetadataFactoryInterface::class);
        $this->propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
        $this->propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
        $this->urlGeneratorProphecy = $this->prophesize(UrlGeneratorInterface::class);
    }

    public function testResourceContext()
    {
        $this->resourceMetadataFactoryProphecy->create($this->entityClass)->willReturn(new ResourceMetadata('DummyEntity'));
        $this->propertyNameCollectionFactoryProphecy->create($this->entityClass)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create($this->entityClass, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, []));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $expected = [
            '@vocab' => '#',
            'hydra' => 'http://www.w3.org/ns/hydra/core#',
            'dummyPropertyA' => 'DummyEntity/dummyPropertyA',
        ];

        $this->assertEquals($expected, $contextBuilder->getResourceContext($this->entityClass));
    }

    public function testResourceContextWithJsonldContext()
    {
        $this->resourceMetadataFactoryProphecy->create($this->entityClass)->willReturn(new ResourceMetadata('DummyEntity'));
        $this->propertyNameCollectionFactoryProphecy->create($this->entityClass)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create($this->entityClass, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, ['jsonld_context' => ['@type' => '@id', '@id' => 'customId', 'foo' => 'bar']]));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $expected = [
            '@vocab' => '#',
            'hydra' => 'http://www.w3.org/ns/hydra/core#',
            'dummyPropertyA' => [
                '@type' => '@id',
                '@id' => 'customId',
                'foo' => 'bar',
            ],
        ];

        $this->assertEquals($expected, $contextBuilder->getResourceContext($this->entityClass));
    }

    public function testGetEntryPointContext()
    {
        $this->resourceMetadataFactoryProphecy->create('dummyPropertyA')->willReturn(new ResourceMetadata('DummyEntity'));
        $this->propertyNameCollectionFactoryProphecy->create($this->entityClass)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->resourceNameCollectionFactoryProphecy->create()->willReturn(new ResourceNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create($this->entityClass, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, ['jsonld_context' => ['@type' => '@id', '@id' => 'customId', 'foo' => 'bar']]));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $expected = [
            '@vocab' => '#',
            'hydra' => 'http://www.w3.org/ns/hydra/core#',
            'dummyEntity' => [
                '@type' => '@id',
                '@id' => 'Entrypoint/dummyEntity',
            ],
        ];

        $this->assertEquals($expected, $contextBuilder->getEntrypointContext());
    }

    public function testResourceContextWithReverse()
    {
        $this->resourceMetadataFactoryProphecy->create($this->entityClass)->willReturn(new ResourceMetadata('DummyEntity'));
        $this->propertyNameCollectionFactoryProphecy->create($this->entityClass)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create($this->entityClass, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, ['jsonld_context' => ['@reverse' => 'parent']]));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $expected = [
            '@vocab' => '#',
            'hydra' => 'http://www.w3.org/ns/hydra/core#',
            'dummyPropertyA' => [
                '@id' => 'DummyEntity/dummyPropertyA',
                '@reverse' => 'parent',
            ],
        ];

        $this->assertEquals($expected, $contextBuilder->getResourceContext($this->entityClass));
    }

    public function testAnonymousResourceContext()
    {
        $dummy = new Dummy();
        $this->propertyNameCollectionFactoryProphecy->create(Dummy::class)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create(Dummy::class, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, []));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $iri = '_:'.(\function_exists('spl_object_id') ? spl_object_id($dummy) : spl_object_hash($dummy));
        $expected = [
            '@context' => [
                '@vocab' => '#',
                'hydra' => 'http://www.w3.org/ns/hydra/core#',
                'dummyPropertyA' => 'Dummy/dummyPropertyA',
            ],
            '@id' => $iri,
            '@type' => 'Dummy',
        ];

        $this->assertEquals($expected, $contextBuilder->getAnonymousResourceContext($dummy));
    }

    public function testAnonymousResourceContextWithIri()
    {
        $output = new OutputDto();
        $this->propertyNameCollectionFactoryProphecy->create(OutputDto::class)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create(OutputDto::class, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, []));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $expected = [
            '@context' => [
                '@vocab' => '#',
                'hydra' => 'http://www.w3.org/ns/hydra/core#',
                'dummyPropertyA' => 'OutputDto/dummyPropertyA',
            ],
            '@id' => '/dummies',
            '@type' => 'OutputDto',
        ];

        $this->assertEquals($expected, $contextBuilder->getAnonymousResourceContext($output, ['iri' => '/dummies', 'name' => 'Dummy']));
    }

    public function testAnonymousResourceContextWithApiResource()
    {
        $output = new OutputDto();
        $this->propertyNameCollectionFactoryProphecy->create(OutputDto::class)->willReturn(new PropertyNameCollection(['dummyPropertyA']));
        $this->propertyMetadataFactoryProphecy->create(OutputDto::class, 'dummyPropertyA')->willReturn(new PropertyMetadata(new Type(Type::BUILTIN_TYPE_STRING), 'Dummy property A', true, true, true, true, false, false, null, null, []));

        $this->resourceMetadataFactoryProphecy->create(Dummy::class)->willReturn(new ResourceMetadata('Dummy'));

        $contextBuilder = new ContextBuilder($this->resourceNameCollectionFactoryProphecy->reveal(), $this->resourceMetadataFactoryProphecy->reveal(), $this->propertyNameCollectionFactoryProphecy->reveal(), $this->propertyMetadataFactoryProphecy->reveal(), $this->urlGeneratorProphecy->reveal());

        $expected = [
            '@context' => [
                '@vocab' => '#',
                'hydra' => 'http://www.w3.org/ns/hydra/core#',
                'dummyPropertyA' => 'OutputDto/dummyPropertyA',
            ],
            '@id' => '/dummies',
            '@type' => 'Dummy',
        ];

        $this->assertEquals($expected, $contextBuilder->getAnonymousResourceContext($output, ['iri' => '/dummies', 'name' => 'Dummy', 'api_resource' => new Dummy()]));
    }
}


text:
<ion-view>
     <ion-nav-title><mm-format-text watch="true">{{fullname}}</mm-format-text></ion-nav-title>
    <ion-content>

          <ng-include src="'addons/morph/templates/topnotifications.html'"></ng-include>

              <mm-format-text>This is the standard version of the course content.</mm-format-text>

     <mm-loading hide-until="sectionsLoaded">
      <ion-list>

                        {{section.name}}

                </ion-list>
                  </mm-loading>
    </ion-content>
</ion-view>

redpajama_set_name: RedPajamaGithub


text:
@interface specialModel : NSObject
@property(nonatomic, copy) NSString *nameLable;
@property(nonatomic, copy) NSString *makeLable;
@property(nonatomic, copy) NSString *ShowImageView;
@property(nonatomic, copy) NSString *SecondID;
@property(nonatomic, copy) NSString *xid;

-(instancetype)initWithModel:(NSDictionary *)dict;

@end


text:
from rest_framework import filters
import inspect

class IsOwnerFilter(filters.BaseFilterBackend):
    """
    Filter that only allows users to see their own objects.
    """
    def filter_queryset(self, request, queryset, view):
        try:
            return queryset.filter(user = request.user) # check for note object
        except:
            try:
                return queryset.filter(username = request.user) # check for user object
            except:
                try:
                    return queryset # try to return the original queryset
                except:
                    pass


text:
using MbUnit.Framework;

namespace Rhino.Mocks.Tests.FieldsProblem
{
	[TestFixture]
	public class FieldProblem_Kevin
	{
		//This is related to an initialization mechanism in use for the CodeGenerationServices on Castle.Contrib
		//I am not sure if this is related to invalid construction of the object. Resharper complains that invoking virtual methods from ctors is a bad idea.
		//It surely seems that it is preventing me from partial mocking a class that has some complex construction.

		[Test]
		public void Virtual_protected_method_called_from_ctor_is_not_called_during_partial_mock_construction()
		{
			string mockedResult = "mocked result";

			MockRepository mockRepository = new MockRepository();
			ConcreteProtectedMethodCalledFromCtor concreteProtectedMethodCalledFromCtor = mockRepository.PartialMock<ConcreteProtectedMethodCalledFromCtor>();

			Expect.Call(concreteProtectedMethodCalledFromCtor.SimplyHereSoThereIsSomethingToMock()).Return(mockedResult);

			mockRepository.ReplayAll();

			string result = concreteProtectedMethodCalledFromCtor.SimplyHereSoThereIsSomethingToMock();

			mockRepository.VerifyAll();

			Assert.AreEqual(mockedResult, result);
			Assert.AreEqual(true, concreteProtectedMethodCalledFromCtor.WasAbstractMethodCalledFromCtor);
		}

		[Test]
		public void Virtual_public_method_called_from_ctor_is_not_called_during_partial_mock_construction()
		{
			string mockedResult = "mocked result";

			MockRepository mockRepository = new MockRepository();
			ConcretePublicMethodCalledFromCtor concretePublicMethodCalledFromCtor = mockRepository.PartialMock<ConcretePublicMethodCalledFromCtor>();

			Expect.Call(concretePublicMethodCalledFromCtor.SimplyHereSoThereIsSomethingToMock()).Return(mockedResult);

			mockRepository.ReplayAll();

			string result = concretePublicMethodCalledFromCtor.SimplyHereSoThereIsSomethingToMock();

			mockRepository.VerifyAll();

			Assert.AreEqual(mockedResult, result);
			Assert.AreEqual(true, concretePublicMethodCalledFromCtor.WasAbstractMethodCalledFromCtor);
		}
	}

	//Abstract Protected

	public class ConcreteProtectedMethodCalledFromCtor : ProtectedExampleCalledFromCtor
	{
		protected override void AbstractCalledFromCtor()
		{
			_wasAbstractMethodCalledFromCtor = true;
		}
	}

	public abstract class ProtectedExampleCalledFromCtor
	{
		protected bool _wasAbstractMethodCalledFromCtor = false;

		public bool WasAbstractMethodCalledFromCtor
		{
			get { return _wasAbstractMethodCalledFromCtor; }
		}

		public ProtectedExampleCalledFromCtor()
		{
			AbstractCalledFromCtor();
		}

		protected abstract void AbstractCalledFromCtor();

		public virtual string SimplyHereSoThereIsSomethingToMock()
		{
			return "If this value is returned the method was not mocked";
		}
	}

	//Abstract Public
	public class ConcretePublicMethodCalledFromCtor : PublicExampleCalledFromCtor
	{
	    public override void AbstractCalledFromCtor()
	    {
	        _wasAbstractMethodCalledFromCtor = true;
	    }
	}

	public abstract class PublicExampleCalledFromCtor
	{
	    protected bool _wasAbstractMethodCalledFromCtor = false;

	    public bool WasAbstractMethodCalledFromCtor
	    {
	        get { return _wasAbstractMethodCalledFromCtor; }
	    }

	    public PublicExampleCalledFromCtor()
	    {
	        AbstractCalledFromCtor();
	    }

	    public abstract void AbstractCalledFromCtor();

	    public virtual string SimplyHereSoThereIsSomethingToMock()
	    {
	        return "If this value is returned the method was not mocked";
	    }
	}

}


text:
title: "home"
bg: white
color: black
style: center
---

# Home for everything related to qPCR, dPCR, qIA and MCA in R

    qPCR
    real-time quantitive PCR

    dPCR
    digital PCR

    qIA
    real-time quantitive isothermal amplification

    MCA
    Melting Curve Analysis

[R is a powerful statistical programming language.](https://cran.r-project.org/)

It has advanced [graphics methods](https://cran.r-project.org/web/views/Graphics.html) and supports [reproducible research](https://cran.r-project.org/web/views/ReproducibleResearch.html) and [web technologies](https://cran.r-project.org/web/views/WebTechnologies.html).

R's applications are far beyond classicial statistics - it is widely used among others in [finance](https://cran.r-project.org/web/views/Finance.html), [genetics](https://cran.r-project.org/web/views/Genetics.html), [social sciences](https://cran.r-project.org/web/views/SocialSciences.html) and...

## PCR analysis

Every package in the pcRuniveRsum helps in investigating data from qPCR, dPCR, qIA and MCA experiments, starting from importing data into R environment to creating interactive study reports.


text:
package com.docker.errors;

/**
 */
public interface CoreErrorCodes {

	public static final int CODE_CORE = 0;//0~999

	public static final int ERROR_RPC_ILLEGAL = CODE_CORE + 192;

	public static final int ERROR_SCRIPT_UNZIP_FAILED = CODE_CORE + 342;
	public static final int ERROR_LANID_ILLEGAL = CODE_CORE + 343;
	public static final int ERROR_REDIS = CODE_CORE + 344;
	public static final int ERROR_KAFKA_CONFCENT_ILLEGAL = CODE_CORE + 345;

	public static final int ERROR_LOCK = 8000;
	public static final int ERROR_LOCK_CAN_NOT_FOUND = ERROR_LOCK + 5;
	public static final int ERROR_LOCK_VERIFY_FIELD = ERROR_LOCK + 2;
}


text:
/* $Id: dnssec-settime.c,v 1.32 2011/06/02 20:24:45 each Exp $ */

/*! \file */

#include <config.h>

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>

#include <isc/buffer.h>
#include <isc/commandline.h>
#include <isc/entropy.h>
#include <isc/file.h>
#include <isc/hash.h>
#include <isc/mem.h>
#include <isc/print.h>
#include <isc/string.h>
#include <isc/util.h>

#include <dns/keyvalues.h>
#include <dns/result.h>
#include <dns/log.h>

#include <dst/dst.h>

#include "dnssectool.h"

const char *program = "dnssec-settime";
int verbose;

static isc_mem_t	*mctx = NULL;

ISC_PLATFORM_NORETURN_PRE static void
usage(void) ISC_PLATFORM_NORETURN_POST;

static void
usage(void) {
	fprintf(stderr, "Usage:\n");
	fprintf(stderr,	"    %s [options] keyfile\n\n", program);
	fprintf(stderr, "Version: %s\n", VERSION);
	fprintf(stderr, "General options:\n");
#ifdef USE_PKCS11
	fprintf(stderr, "    -E engine:          specify OpenSSL engine "
						 "(default \"pkcs11\")\n");
#else
	fprintf(stderr, "    -E engine:          specify OpenSSL engine\n");
#endif
	fprintf(stderr, "    -f:                 force update of old-style "
						 "keys\n");
	fprintf(stderr, "    -K directory:       set key file location\n");
	fprintf(stderr, "    -L ttl:             set default key TTL\n");
	fprintf(stderr, "    -v level:           set level of verbosity\n");
	fprintf(stderr, "    -h:                 help\n");
	fprintf(stderr, "Timing options:\n");
	fprintf(stderr, "    -P date/[+-]offset/none: set/unset key "
						     "publication date\n");
	fprintf(stderr, "    -A date/[+-]offset/none: set/unset key "
						     "activation date\n");
	fprintf(stderr, "    -R date/[+-]offset/none: set/unset key "
						     "revocation date\n");
	fprintf(stderr, "    -I date/[+-]offset/none: set/unset key "
						     "inactivation date\n");
	fprintf(stderr, "    -D date/[+-]offset/none: set/unset key "
						     "deletion date\n");
	fprintf(stderr, "Printing options:\n");
	fprintf(stderr, "    -p C/P/A/R/I/D/all: print a particular time "
						"value or values\n");
	fprintf(stderr, "    -u:                 print times in unix epoch "
						"format\n");
	fprintf(stderr, "Output:\n");
	fprintf(stderr, "     K<name>+<alg>+<new id>.key, "
			     "K<name>+<alg>+<new id>.private\n");

	exit (-1);
}

static void
printtime(dst_key_t *key, int type, const char *tag, isc_boolean_t epoch,
	  FILE *stream)
{
	isc_result_t result;
	const char *output = NULL;
	isc_stdtime_t when;

	if (tag != NULL)
		fprintf(stream, "%s: ", tag);

	result = dst_key_gettime(key, type, &when);
	if (result == ISC_R_NOTFOUND) {
		fprintf(stream, "UNSET\n");
	} else if (epoch) {
		fprintf(stream, "%d\n", (int) when);
	} else {
		time_t time = when;
		output = ctime(&time);
		fprintf(stream, "%s", output);
	}
}

int
main(int argc, char **argv) {
	isc_result_t	result;
#ifdef USE_PKCS11
	const char	*engine = "pkcs11";
#else
	const char	*engine = NULL;
#endif
	char		*filename = NULL, *directory = NULL;
	char		newname[1024];
	char		keystr[DST_KEY_FORMATSIZE];
	char		*endp, *p;
	int		ch;
	isc_entropy_t	*ectx = NULL;
	const char	*predecessor = NULL;
	dst_key_t	*prevkey = NULL;
	dst_key_t	*key = NULL;
	isc_buffer_t	buf;
	dns_name_t	*name = NULL;
	dns_secalg_t 	alg = 0;
	unsigned int 	size = 0;
	isc_uint16_t	flags = 0;
	int		prepub = -1;
	dns_ttl_t	ttl = 0;
	isc_stdtime_t	now;
	isc_stdtime_t	pub = 0, act = 0, rev = 0, inact = 0, del = 0;
	isc_stdtime_t	prevact = 0, previnact = 0, prevdel = 0;
	isc_boolean_t	setpub = ISC_FALSE, setact = ISC_FALSE;
	isc_boolean_t	setrev = ISC_FALSE, setinact = ISC_FALSE;
	isc_boolean_t	setdel = ISC_FALSE, setttl = ISC_FALSE;
	isc_boolean_t	unsetpub = ISC_FALSE, unsetact = ISC_FALSE;
	isc_boolean_t	unsetrev = ISC_FALSE, unsetinact = ISC_FALSE;
	isc_boolean_t	unsetdel = ISC_FALSE;
	isc_boolean_t	printcreate = ISC_FALSE, printpub = ISC_FALSE;
	isc_boolean_t	printact = ISC_FALSE,  printrev = ISC_FALSE;
	isc_boolean_t	printinact = ISC_FALSE, printdel = ISC_FALSE;
	isc_boolean_t	force = ISC_FALSE;
	isc_boolean_t   epoch = ISC_FALSE;
	isc_boolean_t   changed = ISC_FALSE;
	isc_log_t       *log = NULL;

	if (argc == 1)
		usage();

	result = isc_mem_create(0, 0, &mctx);
	if (result != ISC_R_SUCCESS)
		fatal("Out of memory");

	setup_logging(verbose, mctx, &log);

	dns_result_register();

	isc_commandline_errprint = ISC_FALSE;

	isc_stdtime_get(&now);

#define CMDLINE_FLAGS "A:D:E:fhI:i:K:L:P:p:R:S:uv:"
	while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
		switch (ch) {
		case 'E':
			engine = isc_commandline_argument;
			break;
		case 'f':
			force = ISC_TRUE;
			break;
		case 'p':
			p = isc_commandline_argument;
			if (!strcasecmp(p, "all")) {
				printcreate = ISC_TRUE;
				printpub = ISC_TRUE;
				printact = ISC_TRUE;
				printrev = ISC_TRUE;
				printinact = ISC_TRUE;
				printdel = ISC_TRUE;
				break;
			}

			do {
				switch (*p++) {
				case 'C':
					printcreate = ISC_TRUE;
					break;
				case 'P':
					printpub = ISC_TRUE;
					break;
				case 'A':
					printact = ISC_TRUE;
					break;
				case 'R':
					printrev = ISC_TRUE;
					break;
				case 'I':
					printinact = ISC_TRUE;
					break;
				case 'D':
					printdel = ISC_TRUE;
					break;
				case ' ':
					break;
				default:
					usage();
					break;
				}
			} while (*p != '\0');
			break;
		case 'u':
			epoch = ISC_TRUE;
			break;
		case 'K':
			/*
			 * We don't have to copy it here, but do it to
			 * simplify cleanup later
			 */
			directory = isc_mem_strdup(mctx,
						   isc_commandline_argument);
			if (directory == NULL) {
				fatal("Failed to allocate memory for "
				      "directory");
			}
			break;
		case 'L':
			if (strcmp(isc_commandline_argument, "none") == 0)
				ttl = 0;
			else
				ttl = strtottl(isc_commandline_argument);
			setttl = ISC_TRUE;
			break;
		case 'v':
			verbose = strtol(isc_commandline_argument, &endp, 0);
			if (*endp != '\0')
				fatal("-v must be followed by a number");
			break;
		case 'P':
			if (setpub || unsetpub)
				fatal("-P specified more than once");

			changed = ISC_TRUE;
			if (!strcasecmp(isc_commandline_argument, "none")) {
				unsetpub = ISC_TRUE;
			} else {
				setpub = ISC_TRUE;
				pub = strtotime(isc_commandline_argument,
						now, now);
			}
			break;
		case 'A':
			if (setact || unsetact)
				fatal("-A specified more than once");

			changed = ISC_TRUE;
			if (!strcasecmp(isc_commandline_argument, "none")) {
				unsetact = ISC_TRUE;
			} else {
				setact = ISC_TRUE;
				act = strtotime(isc_commandline_argument,
						now, now);
			}
			break;
		case 'R':
			if (setrev || unsetrev)
				fatal("-R specified more than once");

			changed = ISC_TRUE;
			if (!strcasecmp(isc_commandline_argument, "none")) {
				unsetrev = ISC_TRUE;
			} else {
				setrev = ISC_TRUE;
				rev = strtotime(isc_commandline_argument,
						now, now);
			}
			break;
		case 'I':
			if (setinact || unsetinact)
				fatal("-I specified more than once");

			changed = ISC_TRUE;
			if (!strcasecmp(isc_commandline_argument, "none")) {
				unsetinact = ISC_TRUE;
			} else {
				setinact = ISC_TRUE;
				inact = strtotime(isc_commandline_argument,
						now, now);
			}
			break;
		case 'D':
			if (setdel || unsetdel)
				fatal("-D specified more than once");

			changed = ISC_TRUE;
			if (!strcasecmp(isc_commandline_argument, "none")) {
				unsetdel = ISC_TRUE;
			} else {
				setdel = ISC_TRUE;
				del = strtotime(isc_commandline_argument,
						now, now);
			}
			break;
		case 'S':
			predecessor = isc_commandline_argument;
			break;
		case 'i':
			prepub = strtottl(isc_commandline_argument);
			break;
		case '?':
			if (isc_commandline_option != '?')
				fprintf(stderr, "%s: invalid argument -%c\n",
					program, isc_commandline_option);
			/* Falls into */
		case 'h':
			usage();

		default:
			fprintf(stderr, "%s: unhandled option -%c\n",
				program, isc_commandline_option);
			exit(1);
		}
	}

	if (argc < isc_commandline_index + 1 ||
	    argv[isc_commandline_index] == NULL)
		fatal("The key file name was not specified");
	if (argc > isc_commandline_index + 1)
		fatal("Extraneous arguments");

	if (ectx == NULL)
		setup_entropy(mctx, NULL, &ectx);
	result = isc_hash_create(mctx, ectx, DNS_NAME_MAXWIRE);
	if (result != ISC_R_SUCCESS)
		fatal("Could not initialize hash");
	result = dst_lib_init2(mctx, ectx, engine,
			       ISC_ENTROPY_BLOCKING | ISC_ENTROPY_GOODONLY);
	if (result != ISC_R_SUCCESS)
		fatal("Could not initialize dst: %s",
		      isc_result_totext(result));
	isc_entropy_stopcallbacksources(ectx);

	if (predecessor != NULL) {
		char keystr[DST_KEY_FORMATSIZE];
		int major, minor;

		if (prepub == -1)
			prepub = (30 * 86400);

		if (setpub || unsetpub)
			fatal("-S and -P cannot be used together");
		if (setact || unsetact)
			fatal("-S and -A cannot be used together");

		result = dst_key_fromnamedfile(predecessor, directory,
					       DST_TYPE_PUBLIC |
					       DST_TYPE_PRIVATE,
					       mctx, &prevkey);
		if (result != ISC_R_SUCCESS)
			fatal("Invalid keyfile %s: %s",
			      filename, isc_result_totext(result));
		if (!dst_key_isprivate(prevkey))
			fatal("%s is not a private key", filename);

		name = dst_key_name(prevkey);
		alg = dst_key_alg(prevkey);
		size = dst_key_size(prevkey);
		flags = dst_key_flags(prevkey);

		dst_key_format(prevkey, keystr, sizeof(keystr));
		dst_key_getprivateformat(prevkey, &major, &minor);
		if (major != DST_MAJOR_VERSION || minor < DST_MINOR_VERSION)
			fatal("Predecessor has incompatible format "
			      "version %d.%d\n\t", major, minor);

		result = dst_key_gettime(prevkey, DST_TIME_ACTIVATE, &prevact);
		if (result != ISC_R_SUCCESS)
			fatal("Predecessor has no activation date. "
			      "You must set one before\n\t"
			      "generating a successor.");

		result = dst_key_gettime(prevkey, DST_TIME_INACTIVE,
					 &previnact);
		if (result != ISC_R_SUCCESS)
			fatal("Predecessor has no inactivation date. "
			      "You must set one before\n\t"
			      "generating a successor.");

		pub = prevact - prepub;
		if (pub < now && prepub != 0)
			fatal("Predecessor will become inactive before the\n\t"
			      "prepublication period ends.  Either change "
			      "its inactivation date,\n\t"
			      "or use the -i option to set a shorter "
			      "prepublication interval.");

		result = dst_key_gettime(prevkey, DST_TIME_DELETE, &prevdel);
		if (result != ISC_R_SUCCESS)
			fprintf(stderr, "%s: warning: Predecessor has no "
					"removal date;\n\t"
					"it will remain in the zone "
					"indefinitely after rollover.\n",
					program);
		else if (prevdel < previnact)
			fprintf(stderr, "%s: warning: Predecessor is "
					"scheduled to be deleted\n\t"
					"before it is scheduled to be "
					"inactive.\n", program);

		changed = setpub = setact = ISC_TRUE;
		dst_key_free(&prevkey);
	} else {
		if (prepub < 0)
			prepub = 0;

		if (prepub > 0) {
			if (setpub && setact && (act - prepub) < pub)
				fatal("Activation and publication dates "
				      "are closer together than the\n\t"
				      "prepublication interval.");

			if (setpub && !setact) {
				setact = ISC_TRUE;
				act = pub + prepub;
			} else if (setact && !setpub) {
				setpub = ISC_TRUE;
				pub = act - prepub;
			}

			if ((act - prepub) < now)
				fatal("Time until activation is shorter "
				      "than the\n\tprepublication interval.");
		}
	}

	if (directory != NULL) {
		filename = argv[isc_commandline_index];
	} else {
		result = isc_file_splitpath(mctx, argv[isc_commandline_index],
					    &directory, &filename);
		if (result != ISC_R_SUCCESS)
			fatal("cannot process filename %s: %s",
			      argv[isc_commandline_index],
			      isc_result_totext(result));
	}

	result = dst_key_fromnamedfile(filename, directory,
				       DST_TYPE_PUBLIC | DST_TYPE_PRIVATE,
				       mctx, &key);
	if (result != ISC_R_SUCCESS)
		fatal("Invalid keyfile %s: %s",
		      filename, isc_result_totext(result));

	if (!dst_key_isprivate(key))
		fatal("%s is not a private key", filename);

	dst_key_format(key, keystr, sizeof(keystr));

	if (predecessor != NULL) {
		if (!dns_name_equal(name, dst_key_name(key)))
			fatal("Key name mismatch");
		if (alg != dst_key_alg(key))
			fatal("Key algorithm mismatch");
		if (size != dst_key_size(key))
			fatal("Key size mismatch");
		if (flags != dst_key_flags(key))
			fatal("Key flags mismatch");
	}

	prevdel = previnact = 0;
	if ((setdel && setinact && del < inact) ||
	    (dst_key_gettime(key, DST_TIME_INACTIVE,
			     &previnact) == ISC_R_SUCCESS &&
	     setdel && !setinact && del < previnact) ||
	    (dst_key_gettime(key, DST_TIME_DELETE,
			     &prevdel) == ISC_R_SUCCESS &&
	     setinact && !setdel && prevdel < inact) ||
	    (!setdel && !setinact && prevdel < previnact))
		fprintf(stderr, "%s: warning: Key is scheduled to "
				"be deleted before it is\n\t"
				"scheduled to be inactive.\n",
			program);

	if (force)
		set_keyversion(key);
	else
		check_keyversion(key, keystr);

	if (verbose > 2)
		fprintf(stderr, "%s: %s\n", program, keystr);

	/*
	 * Set time values.
	 */
	if (setpub)
		dst_key_settime(key, DST_TIME_PUBLISH, pub);
	else if (unsetpub)
		dst_key_unsettime(key, DST_TIME_PUBLISH);

	if (setact)
		dst_key_settime(key, DST_TIME_ACTIVATE, act);
	else if (unsetact)
		dst_key_unsettime(key, DST_TIME_ACTIVATE);

	if (setrev) {
		if ((dst_key_flags(key) & DNS_KEYFLAG_REVOKE) != 0)
			fprintf(stderr, "%s: warning: Key %s is already "
					"revoked; changing the revocation date "
					"will not affect this.\n",
					program, keystr);
		if ((dst_key_flags(key) & DNS_KEYFLAG_KSK) == 0)
			fprintf(stderr, "%s: warning: Key %s is not flagged as "
					"a KSK, but -R was used.  Revoking a "
					"ZSK is legal, but undefined.\n",
					program, keystr);
		dst_key_settime(key, DST_TIME_REVOKE, rev);
	} else if (unsetrev) {
		if ((dst_key_flags(key) & DNS_KEYFLAG_REVOKE) != 0)
			fprintf(stderr, "%s: warning: Key %s is already "
					"revoked; removing the revocation date "
					"will not affect this.\n",
					program, keystr);
		dst_key_unsettime(key, DST_TIME_REVOKE);
	}

	if (setinact)
		dst_key_settime(key, DST_TIME_INACTIVE, inact);
	else if (unsetinact)
		dst_key_unsettime(key, DST_TIME_INACTIVE);

	if (setdel)
		dst_key_settime(key, DST_TIME_DELETE, del);
	else if (unsetdel)
		dst_key_unsettime(key, DST_TIME_DELETE);

	if (setttl)
		dst_key_setttl(key, ttl);

	/*
	 * No metadata changes were made but we're forcing an upgrade
	 * to the new format anyway: use "-P now -A now" as the default
	 */
	if (force && !changed) {
		dst_key_settime(key, DST_TIME_PUBLISH, now);
		dst_key_settime(key, DST_TIME_ACTIVATE, now);
		changed = ISC_TRUE;
	}

	if (!changed && setttl)
		changed = ISC_TRUE;

	/*
	 * Print out time values, if -p was used.
	 */
	if (printcreate)
		printtime(key, DST_TIME_CREATED, "Created", epoch, stdout);

	if (printpub)
		printtime(key, DST_TIME_PUBLISH, "Publish", epoch, stdout);

	if (printact)
		printtime(key, DST_TIME_ACTIVATE, "Activate", epoch, stdout);

	if (printrev)
		printtime(key, DST_TIME_REVOKE, "Revoke", epoch, stdout);

	if (printinact)
		printtime(key, DST_TIME_INACTIVE, "Inactive", epoch, stdout);

	if (printdel)
		printtime(key, DST_TIME_DELETE, "Delete", epoch, stdout);

	if (changed) {
		isc_buffer_init(&buf, newname, sizeof(newname));
		result = dst_key_buildfilename(key, DST_TYPE_PUBLIC, directory,
					       &buf);
		if (result != ISC_R_SUCCESS) {
			fatal("Failed to build public key filename: %s",
			      isc_result_totext(result));
		}

		result = dst_key_tofile(key, DST_TYPE_PUBLIC|DST_TYPE_PRIVATE,
					directory);
		if (result != ISC_R_SUCCESS) {
			dst_key_format(key, keystr, sizeof(keystr));
			fatal("Failed to write key %s: %s", keystr,
			      isc_result_totext(result));
		}

		printf("%s\n", newname);

		isc_buffer_clear(&buf);
		result = dst_key_buildfilename(key, DST_TYPE_PRIVATE, directory,
					       &buf);
		if (result != ISC_R_SUCCESS) {
			fatal("Failed to build private key filename: %s",
			      isc_result_totext(result));
		}
		printf("%s\n", newname);
	}

	dst_key_free(&key);
	dst_lib_destroy();
	isc_hash_destroy();
	cleanup_entropy(&ectx);
	if (verbose > 10)
		isc_mem_stats(mctx, stdout);
	cleanup_logging(&log);
	isc_mem_free(mctx, directory);
	isc_mem_destroy(&mctx);

	return (0);
}


text:
title: "(WIP draft) Haskell numeric classes"
author: Jens Petersen
date: Feb 4, 2022
tags: [haskell]
description: Summary about the Haskell Numeric type classes
---

I have often found Haskell's various Num type-classes a little confusing.
So I thought I would write a short summary to help myself and hopefully others
to make it clearer.

## Table of Numeric classes from the Prelude

| Super =>         | Class         | property                      |
|:----------------:|:--------------|:------------------------------|
|                  | `Num a`       |`fromInteger :: Integer -> a`  |
|`Num, Ord =>`     | `Real a`      |`toRational :: a -> Rational`  |
|`Real, Enum =>`   | `Integral a`  |`toInteger :: a -> Integer`    |
|`Num =>`          | `Fractional a`|`fromRational :: Rational -> a`|
|`Fractional =>`   | `Floating a`  |`exp`, `log`, `sin`, `cosh`, ...|
|`Fractional =>`   |`RealFrac a`|`properFraction :: Integral b => a -> (b, a)`|
|`Floating,RealFrac =>`|`RealFloat a`|`decodeFloat :: a -> (Integer, Int)`|

(`type Rational = Ratio Integer`)

## Other Numeric types

`Complex`

`Ratio a`

`Fixed a`


text:
namespace graphic
{
	struct sRawMesh;

	namespace importer
	{

		bool ReadRawMeshFile( const string &fileName, OUT sRawMeshGroup &raw );

		bool ReadRawAnimationFile( const string &fileName, OUT sRawAniGroup &rawAni );

		RESOURCE_TYPE::TYPE GetFileKind( const string &fileName );

	}
}


text:
package org.wildfly.build.provisioning.forge.command.featurepack.config;

import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.input.UIInput;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Metadata;
import org.wildfly.build.provisioning.forge.resource.ConfigFileOverrideResource;
import org.wildfly.build.provisioning.forge.resource.ConfigFileOverrideSubsystemsResource;
import org.wildfly.build.provisioning.forge.resource.DomainConfigFileOverrideResource;
import org.wildfly.build.provisioning.forge.resource.StandaloneConfigFileOverrideResource;

import javax.inject.Inject;

/**
 * A command to add subsystems to a config file override, overriding the original config file related subsystems.
 *
 * {@link org.wildfly.build.provisioning.forge.resource.ConfigFileOverrideResource} of domain type support multiple subsystems profiles, if such resource is selected then the profile --name param is activated.
 * @author Eduardo Martins
 */
public class ConfigFileOverrideSubsystemsAddCommand extends AbstractConfigFileOverrideResourceSelectedCommand {

    @Inject
    @WithAttributes(label="Subsystems Profile's name", required=true)
    private UIInput<String> name;

    @Inject
    @WithAttributes(label="Edit after adding")
    private UIInput<Boolean> edit;

    @Override
    public Metadata getMetadata(UIContext context) {
        return super.getMetadata(context)
                .name("config-file-override-subsystems-add")
                .description("Add subsystems filter to a config file override");
    }

    @Override
    public void initializeUI(UIBuilder builder) throws Exception {
        ConfigFileOverrideResource resourceSelected = getResourceSelected(builder.getUIContext());
        if (resourceSelected.getType() == ConfigFileOverrideResource.Type.domain) {
            builder.add(name);
        }
        builder.add(edit);
    }

    @Override
    public Result execute(UIExecutionContext context) throws Exception {
        final ConfigFileOverrideResource resourceSelected = getResourceSelected(context.getUIContext());
        final ConfigFileOverrideSubsystemsResource resourceAdded;
        switch (resourceSelected.getType()) {
            case standalone:
                resourceAdded = ((StandaloneConfigFileOverrideResource)resourceSelected).addSubsystems();
                break;
            case domain:
                resourceAdded = ((DomainConfigFileOverrideResource)resourceSelected).addSubsystemsProfile(name.getValue());
                break;
            default:
                throw new IllegalStateException("unexpected config file override resource type selected");
        }
        if (resourceAdded != null) {
            if (edit.getValue()) {
                context.getUIContext().setSelection(resourceAdded);
            }
            return Results.success();
        } else {
            return Results.fail();
        }
    }

    @Override
    public boolean isEnabled(UIContext context) {
        if (super.isEnabled(context)) {
            final ConfigFileOverrideResource resourceSelected = getResourceSelected(context);
            if (resourceSelected.getType() == ConfigFileOverrideResource.Type.standalone) {
                return ((StandaloneConfigFileOverrideResource) resourceSelected).getSubsystems() == null;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}


text:
const Discord = require('discord.js')
const channelTracker = require('../util/channelTracker.js')
const getSubList = require('./util/getSubList.js')

module.exports = function (bot, message, command) {
  var rssList = []
  try {rssList = require(`../sources/${message.guild.id}.json`).sources} catch (e) {}
  if (rssList.length === 0) return message.channel.sendMessage('There are no active feeds to subscribe to.').catch(err => console.log(`Promise Warning: subAdd 1: ${err}`));

  var options = getSubList(bot, message.guild, rssList)
  if (!options) return message.channel.sendMessage('There are either no feeds with subscriptions, or no eligible subscribed roles that can be self-added.').catch(err => console.log(`Promise Warning: subAdd 2: ${err}`));

  var list = new Discord.RichEmbed()
  .setTitle('Self-Subscription Addition')
  .setDescription('Below is the list of feeds, their channels, and its eligible roles that you may add to yourself. Type the role name you want to be added to, or type *exit* to cancel.\n_____')

  for (var option in options) {
    var roleList = '';
    for (var roleID in options[option].roleList) {
      let roleName = message.guild.roles.get(options[option].roleList[roleID]).name;
      roleList += `${roleName}\n`;
    }
    let channelID = options[option].source.channel;
    let channelName = message.guild.channels.get(channelID).name;
    list.addField(options[option].source.title, `**Channel:** #${channelName}\n${roleList}`, true);
  }

  message.channel.sendEmbed(list).catch(err => console.log(`Promise Warning: subAdd Embed: ${err}`))
  .then(m => {
    const collectorFilter = m => m.author.id == message.author.id;
    const collector = message.channel.createCollector(collectorFilter,{time:240000})
    channelTracker.addCollector(message.channel.id)
    collector.on('message', function (response) {
      let chosenRoleName = response.content
      if (chosenRoleName.toLowerCase() === 'exit') return collector.stop('Self-subscription addition canceled.');
      if (!bot.guilds.get(message.guild.id).roles.find('name', chosenRoleName)) message.channel.sendMessage('That is not a valid role subscription to add. Try again.').catch(err => console.log(`Promise Warning: subAdd 3: ${err}`));
      else {
        var found = false;
        let chosenRole = message.guild.roles.find('name', chosenRoleName);
        let chosenRoleID = chosenRole.id;
        for (var option in options) {
          if (options[option].roleList.includes(chosenRoleID)) {
            var source = options[option].source.title;
            found = true;
          }
        }
        if (found === false) message.channel.sendMessage('That is not a valid role subscription to add. Try again.').catch(err => console.log(`Promise Warning: subAdd 4: ${err}`));
        else {
          collector.stop();
          if (message.member.roles.get(chosenRole.id)) return message.channel.sendMessage(`You already have that role.`).catch(err => console.log(`Promise Warning: subAdd 5: ${err}`));
          message.member.addRole(chosenRole)
          .then(m => {
            console.log(`Self Subscription: (${message.guild.id}, ${message.guild.name}) => Role *${chosenRole.name}* successfully added to member. `)
            message.channel.sendMessage(`You now have the role **${chosenRole.name}**, subscribed to the feed titled **${source}**.`).catch(err => console.log(`Promise Warning: subAdd 6: ${err}`))
          })
          .catch(err => {
            message.channel.sendMessage(`Error: Unable to add role.`).catch(err => console.log(`Promise Warning: subAdd 7: ${err}`))
            console.log(`(${message.guild.id}, ${message.guild.name}) => Could not add role *${chosenRole.name}* to member due to ` + err)
          });
        }
      }
    })
    collector.on('end', (collected, reason) => {
      channelTracker.removeCollector(message.channel.id)
      if (reason === 'time') return message.channel.sendMessage(`I have closed the menu due to inactivity.`).catch(err => {});
      else if (reason !== 'user') return message.channel.sendMessage(reason);
    })
  })
  .catch(err => console.log(`Self Subscription Error: (${message.guild.id}, ${message.guild.name}) => Could not send self-subscription prompt due to ` + err))
}


text:
import AccountHooks from './hooks/account';
import CartHooks from './hooks/cart';
import CurrencySelectorHooks from './hooks/currency-selector';
import ProductHooks from './hooks/product';
import SearchHooks from './hooks/search';
import CountryHooks from './hooks/country';
import CookieHooks from './hooks/cookie';
import FacetedSearchHooks from './hooks/faceted-search';
import SortByHooks from './hooks/sort-by';

const internals = {};

internals.classes = {
    account: new AccountHooks(),
    cart: new CartHooks(),
    currencySelector: new CurrencySelectorHooks(),
    product: new ProductHooks(),
    search: new SearchHooks(),
    country: new CountryHooks(),
    cookie: new CookieHooks(),
    facetedSearch: new FacetedSearchHooks(),
    sortBy: new SortByHooks(),
};

internals.parseHooks = function(hookName) {
    const hookType = hookName.split('-')[0];

    if (internals.classes[hookType] === undefined) {
        throw new Error(hookType + ' is not a valid hookType');
    }

    return internals.classes[hookType];
};

class Hooks {
    on(hookName, callback) {
        const hook = internals.parseHooks(hookName);

        return hook.on(hookName, callback);
    }

    off(hookName, callback) {
        const hook = internals.parseHooks(hookName);

        return hook.off(hookName, callback);
    }

    emit(hookName) {
        const hook = internals.parseHooks(hookName);

        return hook.emit.apply(hook, arguments);
    }
}

export default new Hooks();


text:
import React from "react";
import {Action, Store, Context} from "material-flux";
//Application Const
const MENU = {
    Pasta: 0,
    Salada: 1
}

class MenuStore extends Store{
    constructor(context){
      super(context);
      this.register("handleMenu", this.onMenuHandler);
      this.state = {
          menuStatus : MENU.Pasta
      }
    }
    onMenuHandler(menuStatus){
      this.setState({
        menuStatus : menuStatus
      });
    }
    getMenuStatus(){
      return this.state.menuStatus;
    }
}

class MenuAction extends Action{
    handleMenu(state){
        this.dispatch("handleMenu", state);
    }
}

class MenuContext extends Context{
    constructor(){
      super();
      this.menuAction = new MenuAction(this);
      this.menuStore = new MenuStore(this);
    }
}
//Header
var Header = React.createClass({
    handleClick: function(event) {
        var selected = event.target.getAttribute("data-value");
        var { context } = this.props;
        context.menuAction.handleMenu(selected);
    },
    render: function() {
        var self = this;
        var selected = this.props.menu;
        var menus = Object.keys(MENU).map(function(m){
            return {name:m, value:MENU[m], className: (MENU[m] == selected ? "menu active" : "menu")}
        });
        var nodes = menus.map(function(m){
            return
{m.name}
;
        });
        return
{nodes}
;
    }
});

//Content
var Content = React.createClass({
    render: function() {
        var list = [];
        if(this.props.menu == MENU.Pasta){
            list = ["Carbonara", "Peperoncino", "Mentaiko"]
        }else{
            list = ["Green Salada", "Caesar salad"]
        }
        return
{list.map(function(e, i){ return
{e}
; })}
;
    }
});

//Pager
var Pager = React.createClass({
    handleClick: function(event) {
        var next = (this.props.menu == MENU.Pasta ? MENU.Salada : MENU.Pasta);
        var { context } = this.props;
        context.menuAction.handleMenu(next);
    },
    render: function() {
        var arrow = (this.props.menu == MENU.Pasta ? ">>" : "<<");
        return <button onClick={this.handleClick}>{arrow}</button>;
    }
})

var menuContext = new MenuContext()
var header = React.render(, document.getElementById("header"));
var content = React.render(<Content context={menuContext}/>, document.getElementById("content"));
var pager = React.render(<Pager context={menuContext}/>, document.getElementById("pager"));
function updateMenu(menu){
    [header, content, pager].forEach(function(component){
      component.setProps({menu : menu});
    });
}
menuContext.menuStore.onChange(function(){
    updateMenu(menuContext.menuStore.getMenuStatus());
});
// initialize
updateMenu(menuContext.menuStore.getMenuStatus());


text:
chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   	if(request.mood){
   		// Display message in active textarea.
   		if(document.activeElement.tagName == "TEXTAREA"){
	   		document.activeElement.textContent += request.message;
   		}
   	}
  }
);


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>GridEZ-ReadMe</title>

ReadMe

PolyShell tutorial


text:
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NorthHorizon.Common.Xmp.Tests
{
	[TestClass]
	public class ObjectExtensionsTestFixture
	{
		[TestMethod]
		public void TestAsForProperType()
		{
			var test = new TestClass();
			object obj = test;
			var success = obj.As<TestClass>(t => t.Call());
			Assert.IsTrue(success);
			Assert.AreEqual(1, test.Calls);
		}

		[TestMethod]
		public void TestAsForDifferentType()
		{
			var test = new TestClass();
			object obj = test;
			var success = obj.As<HashSet<string>>(s => s.Clear());
			Assert.IsFalse(success);
			Assert.AreEqual(0, test.Calls);
		}

		[TestMethod]
		public void TestAsValueTypeForProperType()
		{
			int test = 1;
			object obj = test;
			var success = obj.AsValueType<int>(t => test = ++t);
			Assert.IsTrue(success);
			Assert.AreEqual(2, test);
		}

		[TestMethod]
		public void TestAsValueTypeForDifferentType()
		{
			double test = 1;
			object obj = test;
			var success = obj.AsValueType<int>(t => test = ++t);
			Assert.IsFalse(success);
			Assert.AreEqual(1, test);
		}

		[TestMethod]
		public void TestChainGetSuccess()
		{
			var chain = new TestNode(0, new TestNode(1, new TestNode(2, new TestNode(3, null))));

			bool success;
			var id = chain.ChainGet(c => c.Node.Node.Node.Id, out success);
			Assert.IsTrue(success);
			Assert.AreEqual(3, id);
		}

		[TestMethod]
		public void TestChainGetFail()
		{
			var chain = new TestNode(0, new TestNode(1, new TestNode(2, new TestNode(3, null))));

			bool success;
			var id = chain.ChainGet(c => c.Node.Node.Node.Node.Id, out success);
			Assert.IsFalse(success);
		}

		[TestMethod]
		public void TestChainGetAccessTime()
		{
			const int repeat = 10000;

			var chain = new TestNode(0, new TestNode(1, new TestNode(2, new TestNode(3, null))));

			int id = 0;

			var normalStopwatch = Stopwatch.StartNew();
			for (int i = 0; i < repeat; i++)
				if (chain != null)
					if (chain.Node != null)
						if (chain.Node.Node != null)
							if (chain.Node.Node.Node != null)
								id = chain.Node.Node.Node.Id;
			normalStopwatch.Stop();

			var chainStopwatch = Stopwatch.StartNew();
			for (int i = 0; i < repeat; i++)
				id = chain.ChainGet(c => c.Node.Node.Node.Id);
			chainStopwatch.Stop();

			Assert.Inconclusive("Normal conditional null checking took {0} ticks, ChainGet took {1} ticks.", normalStopwatch.ElapsedTicks, chainStopwatch.ElapsedTicks);
		}

		[TestMethod, Ignore]
		public void TestChainGetWithIndexes()
		{
			var chain = new TestTree(0) { Nodes = new[] { new TestNode(1, new TestNode(2, null)) } };

			var id = chain.ChainGet(c => c.Nodes[0].Node.Node.Id);

			Assert.AreEqual(2, id);
		}

		private class TestClass
		{
			public int Calls { get; private set; }

			public void Call()
			{
				Calls++;
			}
		}

		private class TestNode
		{
			public TestNode(int id, TestNode node)
			{
				Id = id;
				Node = node;
			}

			public int Id { get; private set; }
			public TestNode Node { get; private set; }
		}

		private class TestTree : TestNode
		{
			public TestTree(int id)
				: base(id, null)
			{
			}

			public TestNode this[int index]
			{
				get { return Nodes[index]; }
			}

			public TestNode[] Nodes { get; set; }
		}
	}
}


text:
from twisted.internet import defer
from twisted.trial import unittest
from twisted.words.protocols.jabber import xmlstream

from mimir.aggregator import aggregator

class DummyManager(object):
    def __init__(self):
        self.outlist = []

    def send(self, obj):
        self.outlist.append(obj)

class DummyAggregator(object):
    def __init__(self):
        self.feeds = {}

    def setFeed(self, handle, url):
        self.feeds[handle] = url
        return defer.succeed({'handle': handle, 'url': url})

class XMPPControlTest(unittest.TestCase):
    def test_onFeed(self):
        """
        Test adding a feed through XMPP.
        """
        xc = aggregator.XMPPControl(DummyAggregator())
        xc.parent = DummyManager()

        iq = xmlstream.IQ(None)
        iq['to'] = 'user1@example.org'
        iq['from'] = 'user2@example.org'
        iq.addElement(('http://mimir.ik.nu/protocol/aggregator', 'aggregator'))
        feed = iq.aggregator.addElement('feed')
        feed.addElement('handle', content='test')
        feed.addElement('url', content='http://www.example.org/')
        xc.onFeed(iq)
        self.assertEquals(xc.parent.outlist[0]['type'], 'result')
        self.assertEquals(xc.service.feeds['test'], 'http://www.example.org/')

class MemoryFeedStorage(object):
    def __init__(self):
        self.feeds = {}
        self.feedList = {}

    def getFeedList(self):
        return defer.succeed(self.feedList)

    def setFeedURL(self, handle, url):
        feed = {'handle': handle, 'href': url}
        self.feedList[handle] = feed
        return defer.succeed(feed)

    def getFeed(self, handle):
        return defer.succeed(self.feeds[handle])

    def storeFeed(self, feed):
        self.feeds[feed['handle']] = feed
        return defer.succeed(None)

class AggregatorTest(unittest.TestCase):

    def test_setFeed(self):
        """
        Test setting a feed to be aggregated.

        The feed should have been added to storage, and aggregation
        scheduled.
        """

        feed = {'handle': 'test', 'href': 'http://example.org/feed/atom'}

        rescheduled = []

        def reschedule(delay, handle, useCache):
            rescheduled.append((delay, handle, useCache))

        def cb2(feedList):
            self.assertIn('test', feedList)
            self.assertEquals(feed, feedList['test'])

        def cb(result):
            self.assertEquals([(0, 'test', 0)], rescheduled)
            self.assertEquals(feed, result)
            d = storage.getFeedList()
            d.addCallback(cb2)
            return d

        storage = MemoryFeedStorage()
        agg = aggregator.AggregatorService(storage)
        agg.reschedule = reschedule
        agg.startService()

        d = agg.setFeed('test', 'http://example.org/feed/atom')
        d.addCallback(cb)
        return d

    def test_setFeedInvalidHandle(self):
        """
        Test setting a feed to be aggregated, with an invalid handle.

        The feed should not have been added to storage, and aggregation
        not scheduled.
        """

        rescheduled = []

        def reschedule(delay, handle, useCache):
            rescheduled.append((delay, handle, useCache))

        def cb(result):
            self.assertEquals([], rescheduled)

        storage = MemoryFeedStorage()
        agg = aggregator.AggregatorService(storage)
        agg.reschedule = reschedule
        agg.startService()

        d = agg.setFeed('!test', 'http://example.org/feed/atom')
        self.assertFailure(d, aggregator.InvalidHandleError)
        d.addCallback(cb)
        return d


text:
package gwt.material.design.client.ui.pager.actions;

import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.IsWidget;
import gwt.material.design.client.ui.pager.MaterialDataPager;

/**
 * Provides a selection control to {@link MaterialDataPager} pages.
 * Call {@link MaterialDataPager#setPageSelection(PageSelection)} for applying the component.
 * Two available components are available already, see {@link PageNumberBox} and {@link PageListBox}
 *
 * @author kevzlou7979
 */
public interface PageSelection extends HasValue<Integer>, IsWidget {

    /**
     * Will load and initialize all handlers.
     */
    void load();

    /**
     * Will automatically updated the page number based on the current page
     */
    void updatePageNumber(int currentPage);

    /**
     * Clear or reset the page number
     */
    void clearPageNumber();

    /**
     * Will set the current {@link MaterialDataPager} for it's controller.
     */
    void setPager(MaterialDataPager<?> pager);

    /**
     * Will set the component label
     */
    void setLabel(String label);

    /**
     * Will set the total number of pages
     */
    void updateTotalPages(int totalPages);
}


text:
Abc::Backend::Engine.routes.draw do
  root to: 'base#index'

  resources :pages
end


text:
/**
 * siblingsOf
 * Get the siblings of a provided block
 */

export default function siblingsOf(list, block) {
  if (block.parent) {
    return list.filter(i => i.parent === block.parent)
  } else {
    return list.filter(i => !i.parent)
  }
}


text:
var express = require('express'),
    path = require('path'),
    mongoose = require('mongoose'),
    exphbs = require('express3-handlebars'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    http = require('http'),
    logger = require('morgan'),
    multer = require('multer'),
    cookieParser = require('cookie-parser'),
    bodyParser = require('body-parser'),
    cookieSession = require('cookie-session');

var app = express();

var errorHandler = require('express-error-handler'),
    handler = errorHandler({
        static: {
            '404': 'public/404.html',
        }
    });
app.engine('html', exphbs({
    defaultLayout: 'main.html'
}));
app.set('view engine', 'html');
app.configure(function() {
    //app.use(logger('dev'));
    app.set('views', __dirname + '/views');
    app.use(multer({}));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(cookieParser());
    app.use(cookieSession({
        secret: 'robinisthebest'
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(errorHandler.httpError(404));
    app.use(handler);
});
app.configure('development', function() {
    app.use(express.errorHandler());
});
app.configure('production', function() {
    app.use(express.errorHandler());
});
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.auth()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

mongoose.connect('mongodb://localhost/mixdatup');
require('./routes.js')(app);

// Configure passport
http.createServer(app).listen(8080, '0.0.0.0', function() {
    console.log("Express server listening on %s:%d in %s mode", '192.168.0.14', 8080, app.settings.env);
});


text:
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
	[ActionCategory(ActionCategory.Input)]
	[Tooltip("Sends an Event when the specified Mouse Button is pressed. Optionally store the button state in a bool variable.")]
	public class GetMouseButtonDown : FsmStateAction
	{
		[RequiredField]
        [Tooltip("The mouse button to test.")]
		public MouseButton button;

        [Tooltip("Event to send if the mouse button is down.")]
		public FsmEvent sendEvent;

		[UIHint(UIHint.Variable)]
		[Tooltip("Store the button state in a Bool Variable.")]
        public FsmBool storeResult;

        [Tooltip("Uncheck to run when entering the state.")]
	    public bool inUpdateOnly;

		public override void Reset()
		{
			button = MouseButton.Left;
			sendEvent = null;
			storeResult = null;
		    inUpdateOnly = true;
		}

        public override void OnEnter()
        {
            if (!inUpdateOnly)
            {
                DoGetMouseButtonDown();
            }
        }

        public override void OnUpdate()
        {
            DoGetMouseButtonDown();
        }

		void DoGetMouseButtonDown()
		{
			bool buttonDown = Input.GetMouseButtonDown((int)button);
		    if (buttonDown)
			{
			    Fsm.Event(sendEvent);
			}

			storeResult.Value = buttonDown;
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="phpunit.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="true"
         syntaxCheck="false"
        >

    <testsuites>
        <testsuite name="AdForm">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./src/</directory>
            <exclude>
                <directory suffix="Interface.php">./src/</directory>
            </exclude>
        </whitelist>

    </filter>

</phpunit>


text:
angular
  .module('secondLead')
  .controller('WarningModalCtrl', function ($scope, $uibModalInstance){

    $scope.ok = function () {
      $uibModalInstance.close({confirmation: true});
    };

    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };
  });


text: select c_integer as a, cume_dist() over(order by c_integer) as b from j1 order by  a, b desc;


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>SharpTnefMessage Properties</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            SharpMimeTools Documented Class Library

SharpTnefMessage Properties

The properties of the SharpTnefMessage class are listed below. For a complete list of SharpTnefMessage class members, see the SharpTnefMessage Members topic.

Public Instance Properties

Attachments	 Gets a ArrayList instance that contains the attachments found in the tnef stream.

TextBody	 Gets a the text body from the ms-tnef stream (BODY tnef attribute).

See Also

        SharpTnefMessage Class | anmar.SharpMimeTools Namespace

          Send comments on this topic.

          Copyright (C) 2003-2006 Angel Marin. All Rights Reserved.


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, minimal-ui" />

        <title>HTML Encoding Test</title>

        <link href="/css/greyspots.css" type="text/css" rel="stylesheet" />

        <gs-page>
            <gs-header>
HTML Encoding Test
</gs-header>
            <gs-body padded>

<gs-test>

&lt;gs-test&gt;

                <template id="test-container-3"><gs-test></template>
                <template id="test-container-4">&lt;gs-test&gt;</template>

                <gs-form src="test.tpeople">
                    <template>
                        {{! row.first_name }} {{! row.last_name }}

                        <gs-text column="first_name"></gs-text>

                        {{? 5 > 1 }}
                            Math Still Works
                        {{??}}
                            Math Is Broken
                        {{?}}

                        <template>
                            <gs-test>
                            <gs-text column="first_name"></gs-text>
                            <template>
                                &lt;gs-test&gt;
                                <gs-text column="first_name"></gs-text>
                                <template>
                                    <gs-text column="first_name"></gs-text>
                                </template>
                            </template>
                        </template>

<gs-test>

&lt;gs-test&gt;

                        <gs-form src="test.tpeople">
                            <template>
                                {{! row.first_name }} {{! row.last_name }}

<gs-test>

&lt;gs-test&gt;

                            </template>
                        </gs-form>
                    </template>
                </gs-form>

                <gs-envelope src="test.tpeople" limit="1" no-huddelete no-hudlimit no-hudorderby expand-to-content>
                    <template for="table">

                                        <gs-text column="first_name"></gs-text>

<gs-test>

&lt;gs-test&gt;

                    </template>
                </gs-envelope>

                <gs-listbox src="test.tpeople" limit="1" style="height: auto;">
                    <template>

                                        <gs-text column="first_name"></gs-text>

<gs-test>

&lt;gs-test&gt;

                    </template>
                </gs-listbox>

                <gs-combo src="test.tpeople" limit="1">
                    <template>

                                        <gs-text column="first_name"></gs-text>

<gs-test>

&lt;gs-test&gt;

                    </template>
                </gs-combo>

            </gs-body>
        </gs-page>


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta charset="utf-8">

  <title>sEditor</title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="css/style.css"></link>

sEditor Simple, tiny, no javascript dependencies editors

About

          sEditor is a tiny (500 lines), no javascript dependencies library makes it easy to create simple wysiwyg editors .

          View project on Github

Usage

sEditor('.editor')

Examples


text:
using System.Data.Entity;
using Northwind.Data.Common;
using Northwind.Models;

namespace Northwind.Data {
    public class NorthwindDbContext : DataContext, IContext {
        public NorthwindDbContext()
            : base("NorthwindEntities") {
        }

        public virtual DbSet<Category> Category { get; set; }
        public virtual DbSet<Customer> Customer { get; set; }
        public virtual DbSet<Employee> Employee { get; set; }
        public virtual DbSet<Order> Order { get; set; }
        public virtual DbSet<OrderDetail> OrderDetail { get; set; }
        public virtual DbSet<Product> Product { get; set; }
        public virtual DbSet<Shipper> Shipper { get; set; }
        public virtual DbSet<Supplier> Supplier { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Entity<Category>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Customer>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Employee>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Order>()
                .Property(e => e.Freight)
                .HasPrecision(19, 4);

            modelBuilder.Entity<Order>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Order>()
                .HasMany(e => e.OrderDetail)
                .WithOptional(e => e.Order)
                .WillCascadeOnDelete();

            modelBuilder.Entity<OrderDetail>()
                .Property(e => e.UnitPrice)
                .HasPrecision(19, 4);

            modelBuilder.Entity<OrderDetail>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Product>()
                .Property(e => e.UnitPrice)
                .HasPrecision(19, 4);

            modelBuilder.Entity<Product>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Shipper>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();

            modelBuilder.Entity<Supplier>()
                .Property(e => e.RowTimeStamp)
                .IsFixedLength();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.design.widget.TabLayout
        android:id="@+id/tabnews"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable" />

    <android.support.v4.view.ViewPager
        android:layout_below="@id/tabnews"
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</RelativeLayout>


text: Backend API for calorie checking system


text:
package bind

import "io"

// EnvVar represents a environment variable for an app.
type EnvVar struct {
	Name   string `json:"name"`
	Value  string `json:"value"`
	Public bool   `json:"public"`
}

type ServiceEnvVar struct {
	EnvVar       `bson:",inline"`
	ServiceName  string `json:"-"`
	InstanceName string `json:"-"`
}

// Unit represents an application unit to be used in binds.
type Unit interface {
	GetID() string
	GetIp() string
}

type App interface {
	// GetAddresses returns the app addresses.
	GetAddresses() ([]string, error)

	// GetName returns the app name.
	GetName() string

	// GetUnits returns the app units.
	GetUnits() ([]Unit, error)

	// AddInstance adds an instance to the application.
	AddInstance(args AddInstanceArgs) error

	// RemoveInstance removes an instance from the application.
	RemoveInstance(args RemoveInstanceArgs) error
}

type SetEnvArgs struct {
	Envs          []EnvVar
	Writer        io.Writer
	ShouldRestart bool
}

type UnsetEnvArgs struct {
	VariableNames []string
	Writer        io.Writer
	ShouldRestart bool
}

type AddInstanceArgs struct {
	Envs          []ServiceEnvVar
	Writer        io.Writer
	ShouldRestart bool
}

type RemoveInstanceArgs struct {
	ServiceName   string
	InstanceName  string
	Writer        io.Writer
	ShouldRestart bool
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IRuntimeTypeInfoFactory.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Declares the IRuntimeTypeInfoFactory interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Runtime
{
    using System;

    /// <summary>
    /// Contract for factories creating <see cref="IRuntimeTypeInfo"/> instances.
    /// </summary>
    public interface IRuntimeTypeInfoFactory
    {
        /// <summary>
        /// Tries to create the runtime type information type for the provided raw type.
        /// </summary>
        /// <param name="type">The raw type.</param>
        /// <returns>
        /// The matching runtime type information type, or <c>null</c> if a runtime type info could not be created.
        /// </returns>
        IRuntimeTypeInfo? TryCreateRuntimeTypeInfo(Type type);
    }
}


text:
require "test_helper"

class ErrorsTest < MiniTest::Spec
  class AlbumForm < TestForm
    property :title
    validation do
      required(:title).filled
    end

    property :artists, default: []
    property :producer do
      property :name
    end

    property :hit do
      property :title
      validation do
        required(:title).filled
      end
    end

    collection :songs do
      property :title
      validation do
        required(:title).filled
      end
    end

    property :band do # yepp, people do crazy stuff like that.
      property :name
      property :label do
        property :name
        validation do
          required(:name).filled
        end
      end
      # TODO: make band a required object.

      validation do
        configure do
          config.messages_file = "test/fixtures/dry_error_messages.yml"

          def good_musical_taste?(value)
            value != "Nickelback"
          end
        end

        required(:name).filled(:good_musical_taste?)
      end
    end

    validation do
      required(:title).filled
      required(:artists).each(:str?)
      required(:producer).schema do
        required(:name).filled
      end
    end
  end

  let(:album_title) { "Blackhawks Over Los Angeles" }
  let(:album) do
    OpenStruct.new(
      title: album_title,
      hit: song,
      songs: songs, # TODO: document this requirement,
      band: Struct.new(:name, :label).new("Epitaph", OpenStruct.new),
      producer: Struct.new(:name).new("Sun Records")
    )
  end
  let(:song)  { OpenStruct.new(title: "Downtown") }
  let(:songs) { [song = OpenStruct.new(title: "Calling"), song] }
  let(:form)  { AlbumForm.new(album) }

  describe "#validate with invalid array property" do
    it do
      form.validate(
        title: "Swimming Pool - EP",
        band: {
          name: "Marie Madeleine",
          label: {name: "Ekler'o'shocK"}
        },
        artists: [42, "Good Charlotte", 43]
      ).must_equal false
      form.errors.messages.must_equal(artists: {0 => ["must be a string"], 2 => ["must be a string"]})
      form.errors.size.must_equal(1)
    end
  end

  describe "#errors without #validate" do
    it do
      form.errors.size.must_equal 0
    end
  end

  describe "blank everywhere" do
    before do
      form.validate(
        "hit" => {"title" => ""},
        "title" => "",
        "songs" => [{"title" => ""}, {"title" => ""}],
        "producer" => {"name" => ""}
      )
    end

    it do
      form.errors.messages.must_equal(
        title: ["must be filled"],
        "hit.title": ["must be filled"],
        "songs.title": ["must be filled"],
        "band.label.name": ["must be filled"],
        "producer.name": ["must be filled"]
      )
    end

    # it do
    #   form.errors.must_equal({:title  => ["must be filled"]})
    #   TODO: this should only contain local errors?
    # end

    # nested forms keep their own Errors:
    it { form.producer.errors.messages.must_equal(name: ["must be filled"]) }
    it { form.hit.errors.messages.must_equal(title: ["must be filled"]) }
    it { form.songs[0].errors.messages.must_equal(title: ["must be filled"]) }

    it do
      form.errors.messages.must_equal(
        title: ["must be filled"],
        "hit.title": ["must be filled"],
        "songs.title": ["must be filled"],
        "band.label.name": ["must be filled"],
        "producer.name": ["must be filled"]
      )
      form.errors.size.must_equal(5)
    end
  end

  describe "#validate with main form invalid" do
    it do
      form.validate("title" => "", "band" => {"label" => {name: "Fat Wreck"}}, "producer" => nil).must_equal false
      form.errors.messages.must_equal(title: ["must be filled"], producer: ["must be a hash"])
      form.errors.size.must_equal(2)
    end
  end

  describe "#validate with middle nested form invalid" do
    before { @result = form.validate("hit" => {"title" => ""}, "band" => {"label" => {name: "Fat Wreck"}}) }

    it { @result.must_equal false }
    it { form.errors.messages.must_equal("hit.title": ["must be filled"]) }
    it { form.errors.size.must_equal(1) }
  end

  describe "#validate with collection form invalid" do
    before { @result = form.validate("songs" => [{"title" => ""}], "band" => {"label" => {name: "Fat Wreck"}}) }

    it { @result.must_equal false }
    it { form.errors.messages.must_equal("songs.title": ["must be filled"]) }
    it { form.errors.size.must_equal(1) }
  end

  describe "#validate with collection and 2-level-nested invalid" do
    before { @result = form.validate("songs" => [{"title" => ""}], "band" => {"label" => {}}) }

    it { @result.must_equal false }
    it { form.errors.messages.must_equal("songs.title": ["must be filled"], "band.label.name": ["must be filled"]) }
    it { form.errors.size.must_equal(2) }
  end

  describe "#validate with nested form using :base invalid" do
    it do
      result = form.validate("songs" => [{"title" => "Someday"}], "band" => {"name" => "Nickelback", "label" => {"name" => "Roadrunner Records"}})
      result.must_equal false
      form.errors.messages.must_equal("band.name": ["you're a bad person"])
      form.errors.size.must_equal(1)
    end
  end

  describe "#add" do
    let(:album_title) { nil }
    it do
      form.errors.add(:before, "validate")
      form.errors.add(:before, "validate 2")
      form.errors.add(:title, "before validate")
      result = form.validate("songs" => [{"title" => "Someday"}], "band" => {"name" => "Nickelback", "label" => {"name" => "Roadrunner Records"}})
      result.must_equal false
      form.errors.messages.must_equal(before: ["validate", "validate 2"], title: ["before validate", "must be filled"], "band.name": ["you're a bad person"])
      # add a new custom error
      form.errors.add(:policy, "error_text")
      form.errors.messages.must_equal(before: ["validate", "validate 2"], title: ["before validate", "must be filled"], "band.name": ["you're a bad person"], policy: ["error_text"])
      # does not duplicate errors
      form.errors.add(:title, "must be filled")
      form.errors.messages.must_equal(before: ["validate", "validate 2"], title: ["before validate", "must be filled"], "band.name": ["you're a bad person"], policy: ["error_text"])
      # merge existing errors
      form.errors.add(:policy, "another error")
      form.errors.messages.must_equal(before: ["validate", "validate 2"], title: ["before validate", "must be filled"], "band.name": ["you're a bad person"], policy: ["error_text", "another error"])
    end
  end

  describe "correct #validate" do
    before do
      @result = form.validate(
        "hit"   => {"title" => "Sacrifice"},
        "title" => "Second Heat",
        "songs" => [{"title" => "Heart Of A Lion"}],
        "band"  => {"label" => {name: "Fat Wreck"}}
      )
    end

    it { @result.must_equal true }
    it { form.hit.title.must_equal "Sacrifice" }
    it { form.title.must_equal "Second Heat" }
    it { form.songs.first.title.must_equal "Heart Of A Lion" }
    it do
      skip "WE DON'T NEED COUNT AND EMPTY? ON THE CORE ERRORS OBJECT"
      form.errors.size.must_equal(0)
      form.errors.empty?.must_equal(true)
    end
  end

  describe "Errors#to_s" do
    before { form.validate("songs" => [{"title" => ""}], "band" => {"label" => {}}) }

    # to_s is aliased to messages
    it {
      skip "why do we need Errors#to_s ?"
      form.errors.to_s.must_equal "{:\"songs.title\"=>[\"must be filled\"], :\"band.label.name\"=>[\"must be filled\"]}"
    }
  end
end


text:
namespace StaticMap.Google.Tests
{
    #region Usings

    using System;
    using System.Globalization;
    using System.Security.Permissions;
    using System.Text.RegularExpressions;
    using Core.Model;
    using NUnit.Framework;
    using Shouldly;

    #endregion

    [TestFixture]
    public class GoogleStaticMapUrlBuilderTests
    {
        private const int Height = 100;
        private const int Width = 100;
        private const string BaseUrl = "baseurl";
        private const double Latitude = 52.0716543;
        private const double Longitude = 4.3098683;
        private GoogleStaticMapUrlBuilder googleStaticMapUrlBuilder;

        [SetUp]
        public void Setup()
        {
            googleStaticMapUrlBuilder = new GoogleStaticMapUrlBuilder(BaseUrl);
        }

        [Test]
        public void BuildShouldContainBaseUrl()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldContain(BaseUrl);
        }

        [Test]
        public void BuildWithoutHeightThrowsArgumentNullException()
        {
            Should.Throw<ArgumentNullException>(() => { googleStaticMapUrlBuilder.Build(Width, 0); });
        }

        [Test]
        public void BuildWithoutWidthThrowsArgumentNullException()
        {
            Should.Throw<ArgumentNullException>(() => { googleStaticMapUrlBuilder.Build(0, Height); });
        }

        #region Language

        [Test]
        public void BuildWithLanguageShouldSetLanguage()
        {
            var url = googleStaticMapUrlBuilder.SetLanguage("nl")
                                               .Build(Width, Height);
            url.ShouldContain("language");
        }

        [Test]
        public void BuildWithoutLanguageShouldSetNotLanguage()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldNotContain("language");
        }

        #endregion

        #region Region

        [Test]
        public void BuildWithRegionShouldSetRegion()
        {
            var url = googleStaticMapUrlBuilder.SetRegion("nl")
                                               .Build(Width, Height);
            url.ShouldContain("region");
        }

        [Test]
        public void BuildWithoutRegionShouldNotSetRegion()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldNotContain("region");
        }

        #endregion

        #region MapType

        [Test]
        public void BuildWithMapTypeShouldSetMapType()
        {
            var url = googleStaticMapUrlBuilder.SetMapType("road")
                                               .Build(Width, Height);
            url.ShouldContain("maptype");
        }

        [Test]
        public void BuildWithoutMapTypeShouldNotSetMapType()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldNotContain("maptype");
        }

        #endregion

        #region Scale

        [Test]
        public void BuildWithScaleShouldSetScale()
        {
            var url = googleStaticMapUrlBuilder.SetScale(1)
                                               .Build(Width, Height);
            url.ShouldContain("scale");
        }

        [Test]
        public void BuildWithoutScaleShouldNotSetScale()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldNotContain("scale");
        }

        #endregion

        #region Zoom

        [Test]
        public void BuildWithZoomShouldSetZoom()
        {
            var url = googleStaticMapUrlBuilder.SetZoom(1)
                                               .Build(Width, Height);
            url.ShouldContain("zoom");
        }

        [Test]
        public void BuildWithoutZoomShouldNotSetZoom()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldNotContain("zoom");
        }

        #endregion

        #region Center

        [Test]
        public void BuildWithCenterShouldSetCenter()
        {
            var url = googleStaticMapUrlBuilder.SetCenter(new Point(Latitude, Longitude))
                                               .Build(Width, Height);
            url.ShouldContain("center");
            url.ShouldContain(Latitude.ToString(CultureInfo.InvariantCulture));
            url.ShouldContain(Longitude.ToString(CultureInfo.InvariantCulture));
        }

        [Test]
        public void BuildWithoutCenterShouldNotSetCenter()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);
            url.ShouldNotContain("center");
        }

        #endregion

        #region Markers

        [Test]
        public void BuildShouldNotContainMarkersGivenNoMarkers()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);

            url.ShouldNotContain("markers");
        }

        [Test]
        public void BuildShouldContainOneMarkerGivenOneMarker()
        {
            var url = googleStaticMapUrlBuilder.AddMarker(new Marker(new Point(Latitude, Longitude)))
                                               .Build(Width, Height);

            //TODO This is not 'correct' testing i think.
            Regex.Matches(url, "markers")
                 .Count.ShouldBe(1);
        }

        [Test]
        public void BuildShouldContainTwoMarkerGivenTwoMarkers()
        {
            var url = googleStaticMapUrlBuilder.AddMarker(new Marker(new Point(Latitude, Longitude)))
                                               .AddMarker(new Marker(new Point(Latitude, Longitude)))
                                               .Build(Width, Height);

            //TODO This is not 'correct' testing i think.
            Regex.Matches(url, "markers")
                 .Count.ShouldBe(2);
        }

        #endregion

        #region Paths

        [Test]
        public void BuildShouldNotContainPathsGivenNoPaths()
        {
            var url = googleStaticMapUrlBuilder.Build(Width, Height);

            url.ShouldNotContain("path");
        }

        [Test]
        public void BuildShouldContainOnePathGivenOnePath()
        {
            var url = googleStaticMapUrlBuilder.AddPath(new PolylinePath("polyline"))
                                               .Build(Width, Height);

            //TODO This is not 'correct' testing i think.
            Regex.Matches(url, "path")
                 .Count.ShouldBe(1);
        }

        [Test]
        public void BuildShouldContainTwoPathsGivenTwoPaths()
        {
            var url = googleStaticMapUrlBuilder.AddPath(new PolylinePath("polyline"))
                                               .AddPath(new PolylinePath("polyline"))
                                               .Build(Width, Height);

            //TODO This is not 'correct' testing i think.
            Regex.Matches(url, "path")
                 .Count.ShouldBe(2);
        }
        #endregion
    }
}


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\Youtube\Form;

use Chamilo\Core\Repository\Form\ComplexContentObjectItemForm;

/**
 *
 * @package core\repository\content_object\youtube
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class ComplexYoutubeForm extends ComplexContentObjectItemForm
{
}


text: module.exports = require("npm:envify@3.4.0/index.js");


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Bacidia umbrina var. marina Degel.

### Remarks
null


text:
'use strict';

import React, { Component } from 'react';

export default class Team extends Component {

  onClick(event) {
    event.preventDefault();
    this.props.onClick();
  }

  render() {
    let team = this.props.team;

    return (

        {team.name}
         {team.score}

    );
  }
}


text:
package com.github.liosha2007.vkontakte_api;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: liosha
 * Date: 09.11.13
 * Time: 23:27
 * https://gist.github.com/smat/1058578
 */
public class MapUtils {
    public static <K, V> MapBuilder<K, V> asMap(K key, V value) {
        return new MapBuilder<K, V>().entry(key, value);
    }

    public static class MapBuilder<K, V> extends HashMap<K, V> {
        public MapBuilder<K, V> entry(K key, V value) {
            this.put(key, value);
            return this;
        }

        public MapBuilder<K, V> pt(K key, V value) {
            super.put(key,  value);
            return this;
        }
    }
}


text:
{{me.first_name}}

                 Dashboard

                Users

                Campuses

                Devices


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/menu_fragment"
        android:name="it.infn.ct.dchrpSGmobile.MenuFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <fragment
        android:id="@+id/details_fragment"
        android:name="it.infn.ct.dchrpSGmobile.DetailsFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2" />

</LinearLayout>


text:
{% extends "header_footer.html" %}
{% load render_bundle from webpack_loader %}

{% block content %}

        <button class="modal-close is-large" aria-label="close"></button>

            {% if references %}

                    Reference(s):

                        {% for ref in references %}

{{ref.label}}

                        {% endfor %}
                        {% if more_references %}

                        [+]
                        {% for ref in more_references %}

{{ref.label}}

                        {% endfor %}
                        {% endif %}

            {% endif %}

            {% if title %}

                {{ title }}
                {% if license %}
                {{ license }}
                {% endif %}

            {% endif %}
            {% if authors %}

                {{ authors.main }}
                {% if authors.etal %}
                et al.
                , {{ authors.etal }}
                {% endif %}

            {% endif %}

        {% if columns and columns.strip != 'null' %}

                    <button class="button is-primary" aria-haspopup="true" aria-controls="dropdown-menu2" disabled>
                        Download

                    </button>

                        {% for component in components %}

                            <input type="checkbox" name=include id="with_{{component}}" value="{{component}}">
                            with {{component}}

                        {% endfor %}

                                JSON

                                CSV

                            <progress class="progress is-small is-hidden" max="100" id=download_progress></progress>
                            Check status
                            Click to download

        {% endif %}

    {% if descriptions or other %}

            {% if descriptions %}

                {{ descriptions.0|safe }}.
                {% if descriptions.1 %}
                More »
                {{ descriptions.1|safe }}
                {% endif %}

            {% endif %}
            {% if other and other.strip != 'null' %}

                Other Info

                    {{ other|safe }}

            {% endif %}

    {% endif %}

    {% if columns and columns.strip != 'null' %}

Count

Filter Contributions

                            <select id=table_select>
                                {% for col in search_columns %}
                                <option>{{ col }}</option>
                                {% endfor %}
                            </select>

                        <input id=table_keyword class="input" type="text" placeholder="Keyword">

                        Filter

                        Reset

Select Columns

                    <input type="checkbox" id=toggle_collapse>
                    collapse all

                                <input class="is-checkradio" id="column_manager_select_all" type="checkbox" checked="checked">
                                {{ columns|length }} Columns

                            {% for col in columns %}

                                {% if col in "id,identifier,formula" %}
                                <input class="is-checkradio" name="column_manager_item"
                                     id="column_manager_checkbox_{{col}}_{{forloop.counter0}}" type="checkbox" checked="checked" disabled="disabled">
                                {% else %}
                                <input class="is-checkradio" name="column_manager_item"
                                     id="column_manager_checkbox_{{col}}_{{forloop.counter0}}" type="checkbox" checked="checked">
                                {% endif %}
                                {{col}}

                            {% endfor %}

Download

                    JSON
                    CSV

                    Click to download

    {% elif name %}

Data not available yet

                        If you are the owner or a member of this project, use the
                        MPContribs python client
                        and the code snippet below to add data to this project. Full examples for other
                        projects can be found
                        on GitHub.

                        If you don't have permissions to manage or view the data in this project, feel free
                        to reach out to the
                        owner
                        to become a member of the {{name}} group.

from mpcontribs.client import Client
client = Client(
    host="{{API_CNAME}}",
    apikey="{{ request.META.HTTP_X_CONSUMER_CUSTOM_ID }}",
    project="{{name}}"
)
client.init_columns({"a": "eV", "b.c": None, "b.d": ""})
contributions = [{
    "identifier": "mp-4",
    "data": {
        "a": "3 eV",
        "b": {"c": "hello", "d": 3}
    },
    "structures": [`pymatgen.core.Structure`, ...],
    "tables": [`pandas.DataFrame`, ...],
    "attachments": [`pathlib.Path`, `mpcontribs.client.Attachment`, ...]
}]
client.submit_contributions(contributions)

    {% endif %}

{% endblock %}

{% block footer %}
{% render_bundle 'landingpage' %}
{% endblock %}


text:
using namespace std;

class Fish;
class Bear;
class Dinosaur;

class Animal
{
public:
	virtual bool eats(const Animal& inPrey) const = 0;

	virtual bool eatenBy(const Bear& inBear) const = 0;
	virtual bool eatenBy(const Fish& inFish) const = 0;
	virtual bool eatenBy(const Dinosaur& inDinosaur) const = 0;
};

class Bear : public Animal
{
public:
	virtual bool eats(const Animal& inPrey) const
	{
		return inPrey.eatenBy(*this);
	}

	virtual bool eatenBy(const Bear& inBear) const
	{
		return false;
	}

	virtual bool eatenBy(const Fish& inFish) const
	{
		return false;
	}

	virtual bool eatenBy(const Dinosaur& inDinosaur) const
	{
		return true;
	}
};

class Fish : public Animal
{
public:
	virtual bool eats(const Animal& inPrey) const
	{
		return inPrey.eatenBy(*this);
	}

	virtual bool eatenBy(const Bear& inBear) const
	{
		return true;
	}

	virtual bool eatenBy(const Fish& inFish) const
	{
		return true;
	}

	virtual bool eatenBy(const Dinosaur& inDinosaur) const
	{
		return true;
	}
};

class Dinosaur : public Animal
{
public:
	virtual bool eats(const Animal& inPrey) const
	{
		return inPrey.eatenBy(*this);
	}

	virtual bool eatenBy(const Bear& inBear) const
	{
		return false;
	}

	virtual bool eatenBy(const Fish& inFish) const
	{
		return false;
	}

	virtual bool eatenBy(const Dinosaur& inDinosaur) const
	{
		return true;
	}
};

int main()
{
	Fish myFish;
	Bear myBear;
	Dinosaur myDino;

	cout << "Fish eats bear? " << myFish.eats(myBear) << endl;
	cout << "Fish eats dino? " << myFish.eats(myDino) << endl;
	cout << "Dino eats bear? " << myDino.eats(myBear) << endl;
	cout << "Bear eats fish? " << myBear.eats(myFish) << endl;

	return 0;
}