text:
from django.shortcuts import render
from django.http import HttpResponse
from uberjobs.models import EconCategory, EconSeries

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from datetime import datetime

from scipy import stats
import json

# Create your views here.
def index(request):
    return render(request, 'uberjobs/index.html')

def serieslist(request):
    series_list = EconSeries.objects.all()
    category_list = EconCategory.objects.all()

    context = {
            'series_list' : series_list,
            'category_list' : category_list
        }

    return render(request, 'uberjobs/serieslist.html', context)

def seriesdetail(request, series_id):

    series_data = []
    series_json = ''
    error_msg = ''

    try:
        if len(EconSeries.objects.filter(series_id=series_id)) > 0:
            series = EconSeries.objects.filter(series_id=series_id)[0]
            series_data = series.get_data()
        else:
            error_msg = "Sorry, we couldn't find your series!"
    except:
        raise Http404("Series does not exist.")

    context = {
        'series_id' : series_id,
        'series_data' : series_data,
        'series_json' : json.dumps(series_data),
        'error_msg' : error_msg
    }

    return render(request, 'uberjobs/seriesdetail.html', context)

def seriesmodel(request, series_id):

    series_data = []
    series_json = ''
    error_msg = ''
    slope = 0
    intercept = 0
    r_value = 0
    p_value = 0
    std_err = 0

    try:
        if len(EconSeries.objects.filter(series_id=series_id)) > 0:
            series = EconSeries.objects.filter(series_id=series_id)[0]
            job_series = EconSeries.objects.get(pk=1)

            series_data = series.get_data()
            job_series_data = job_series.get_data()
        else:
            error_msg = "An error happened!"

        X = job_series_data.values()
        Y = series_data.values()

        # Create linear regression object
        slope, intercept, r_value, p_value, std_err = stats.linregress(X,Y)

    except:
        error_msg = 'An error happened!'

    context = {
        'series_id' : series_id,
        'series_data' : series_data,
        'job_series_data' : job_series_data,
        'slope' : round(slope,3),
        'intercept' : round(intercept,6),
        'r_value' : round(r_value,3),
        'p_value' : round(p_value,6),
        'std_err' : round(std_err,3),
        'r_squared' : round(r_value**2,3),
        'error_msg' : error_msg
    }

    return render(request, 'uberjobs/seriesmodel.html', context)

def serieschart(request, series_id):

    try:
        series = EconSeries.objects.filter(series_id=series_id)[0]
        series_data = series.get_raw_data()
        series_name = series.series_name
    except EconSeries.DoesNotExist:
        raise Http404("Series does not exist.")

    x_labels = [datetime.strptime(n, '%Y-%m') for n in series_data.keys()]

    fig = Figure(facecolor="white")
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.plot(x_labels, series_data.values())
    ax.set_title(series_name)
    ax.grid(True)
    ax.set_xlabel('Time')
    response = HttpResponse(content_type = 'image/png')
    canvas.print_png(response)
    return response

def serieschartcompare(request, series_id, lag=0):

    try:
        user_series = EconSeries.objects.filter(series_id=series_id)[0]
        job_series = EconSeries.objects.get(pk=1)

        user_series_data = user_series.get_data()
        user_series_name = user_series.series_name

        job_series_data = job_series.get_data()
        job_series_name = job_series.series_name

    except EconSeries.DoesNotExist:
        raise Http404("Series does not exist.")

    x_labels = [datetime.strptime(n, '%Y-%m') for n in user_series_data.keys()]

    fig = Figure(facecolor="white")
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.plot(x_labels, user_series_data.values(), label=user_series.series_id)
    ax.plot(x_labels, job_series_data.values(), label=job_series.series_id, color='r')
    ax.set_title(user_series_name + " vs. " + job_series_name)
    ax.grid(True)
    ax.set_xlabel('Time')
    ax.legend([user_series.series_id, job_series.series_id], loc='upper right')
    response = HttpResponse(content_type = 'image/png')
    canvas.print_png(response)
    return response

def serieschartscatter(request, series_id, lag=0):

    try:
        user_series = EconSeries.objects.filter(series_id=series_id)[0]
        job_series = EconSeries.objects.get(pk=1)

        user_series_data = user_series.get_data()
        user_series_name = user_series.series_name

        job_series_data = job_series.get_data()
        job_series_name = job_series.series_name

    except EconSeries.DoesNotExist:
        raise Http404("Series does not exist.")

    fig = Figure(facecolor="white")
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.scatter(job_series_data.values(), user_series_data.values())
    ax.set_title("Scatter Plotting")
    ax.grid(True)
    ax.set_xlabel(job_series_name)
    ax.set_ylabel(user_series_name)
    response = HttpResponse(content_type = 'image/png')
    canvas.print_png(response)
    return response


text:
<?php
/**
 * simple-vccw-env Theme Customizer.
 *
 * @package simple-vccw-env
 */

/**
 * Add postMessage support for site title and description for the Theme Customizer.
 *
 * @param WP_Customize_Manager $wp_customize Theme Customizer object.
 */
function simple_vccw_env_customize_register( $wp_customize ) {
	$wp_customize->get_setting( 'blogname' )->transport         = 'postMessage';
	$wp_customize->get_setting( 'blogdescription' )->transport  = 'postMessage';
	$wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage';
}
add_action( 'customize_register', 'simple_vccw_env_customize_register' );

/**
 * Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
 */
function simple_vccw_env_customize_preview_js() {
	wp_enqueue_script( 'simple_vccw_env_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20130508', true );
}
add_action( 'customize_preview_init', 'simple_vccw_env_customize_preview_js' );

redpajama_set_name: RedPajamaGithub


text:
package client.facades

import scala.scalajs.js
import scala.scalajs.js.annotation.JSName

/**
  * Created by bhagyashree.b on 2016-08-18.
  */

@js.native
@JSName("SRPClient")
class SRPClient(username: String, password: String) extends js.Object {
  def getAHex(): String = js.native
  def getMHex(BHex: String, saltHex: String): String = js.native
  def getVerifierHex(saltHex: String): String = js.native
  def matches(M2Hex: String): Boolean = js.native
}


text:
/* -*- Mode: C; tab-width:4 -*- */
/* ex: set ts=4: */
/*
 * Copyright (c) 2005 Yale University.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgement:
 *       This product includes software developed by the Embedded Networks
 *       and Applications Lab (ENALAB) at Yale University.
 * 4. Neither the name of the University nor that of the Laboratory
 *    may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY YALE UNIVERSITY AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <hardware.h>
#include <sos_timer.h>
#include "timer.h"
#include <hardware_proc.h>
//#include "ML674000.h"
//#include "irq.h"

/* constants */
//#define MHz     (1000000L)
//#define TMRCYC  (30)      /* interval of TIMER interrupt (ms) */
//#define CCLK    (56*MHz)    /* frequency of CCLK */
//#define VALUE_OF_TMRLR      /* reload value of timer */
 //               ((0x10000L*(16*1000)-((TMRCYC)*(CCLK)))/(16*1000))
static void set_timer(unsigned long timer_value);
static void timer0_interrupt_handler();

void enable_timer(void)
{
	set_wbit(ILC, ILC_ILC16);
}

void disable_timer(void)
{
	clr_wbit(ILC, ILC_ILC16);
}

/**
 * @brief timer hardware routine
 */
void timer_hardware_init(uint8_t interval, uint8_t scale){

    HAS_CRITICAL_SECTION;
	unsigned long timer_value;
	timer_value = ((0x10000L*(16*1000)-((interval)*(CCLK)))/(16*1000));
    ENTER_CRITICAL_SECTION();
	IRQ_HANDLER_TABLE[INT_TIMER0] = timer0_interrupt_handler;
	set_wbit(ILC, ILC_ILC16 & ILC_INT_LV1); /* interrupt level of
                       ||            ||          IRQ number 16 (timer0)  is set as 1
                   IRQ number  interrupt level  */

    //! Initialize and start hardware timer
	set_timer(timer_value);

    LEAVE_CRITICAL_SECTION();
	// enable timer by writing '1' in TMEN[0] register
    put_wvalue(TMEN, 0x01);

    //! Call the SOS timer init function
    timer_init();
}

/**
 * @brief real Timer handler
 */
static void timer0_interrupt_handler()
{
	_timer_interrupt();
	put_wvalue(TIMESTAT0, 0x01);   // implicitly clear the STATUS of the timer0
								   // so that timer interrupts can be re-enabled
}

/******************************************************************************
 * Timer0_setInterval													 	  *
 * Description: alters the interval for an instance of the time				  *
 * Parameters: 1) interval - specifies running time of timer 				  *
 * Returns a character symbolizing PALOS_TASK_DONE							  *
 ******************************************************************************/

void timer_setInterval(int32_t interval)
{
	// convert interval so it accurately reflects time in seconds
	unsigned long timer_value;

	if(interval > 250) interval = 250;
	timer_value = ((0x10000L*(16*1000)-((interval)*(CCLK)))/(16*1000));

	// set the timer with the appropriate value

	set_timer(timer_value);
}

/*------------------------ functions about TIMER -------------------------------*/

/****************************************************************************/
/*  Setup of timer                                                          */
/*  Function : set_timer                                                    */
/*      Parameters                                                          */
/*          Input   :   Nothing                                             */
/*          Output  :   Nothing                                             */
/****************************************************************************/
static void set_timer(unsigned long timer_value)
{
	put_wvalue(TIMECNTL0, (get_wvalue(TIMECNTL0) & 0xFFE7));   // disable interrupt and stop timer0
	put_wvalue(TIMECMP1, timer_value);						  // load the new interval in the compare register
	put_wvalue(TIMEBASE0, 0x0000);							  // initialize the time base of the counter
	put_wvalue(TIMECNTL0, (get_wvalue(TIMECNTL0) & 0xFFF7));  // make timer periodic
	put_wvalue(TIMECNTL0, (get_wvalue(TIMECNTL0) | 0x0018));  // enable interrupt and start timer0 as one-shot timer

    return;
}

/****************************************************************************/
/*  Registration of IRQ Handler                                             */
/*  Function : reg_irq_handler                                              */
/*      Parameters                                                          */
/*          Input   :   Nothing                                             */
/*          Output  :   Nothing                                             */
/*  Note : Initialization of IRQ needs to be performed before this process. */
/****************************************************************************/
//void reg_irq_handler(void)
//{
    /***********************************************************
      IRQ handler (timer_handler) is registered into IRQ handler table.
    ***********************************************************/
    //IRQ_HANDLER_TABLE[INT_SYSTEM_TIMER] = (*Timer0_handler);

    /***********************************************************
      setup of ILC0.
      ILC0 sets interrupt level of IRQ number 0-7.
      ILC0_ILR0 corresponds to IRQ number 0.
      ILC0_ILR1 corresponds to IRQ number 1-3.
      ILC0_ILR4 corresponds to IRQ number 4 and 5.
      ILC0_ILR6 corresponds to IRQ number 6 and 7.
    ***********************************************************/
    /* set_wbit(ILC0, ILC0_ILR0 & ILC0_INT_LV1);  interrupt level of
                       ||            ||          IRQ number 0 is set as 1
                   IRQ number  interrupt level  */

    /***********************************************************
      setup of ILC1.
      ILC1 sets interrupt level of IRQ number 8-15.
      ILC1_ILR8 corresponds to IRQ number 8.
      ILC1_ILR9 corresponds to IRQ number 9.
      ILC1_ILR10 corresponds to IRQ number 10.
      ILC1_ILR11 corresponds to IRQ number 11.
      ILC1_ILR12 corresponds to IRQ number 12.
      ILC1_ILR13 corresponds to IRQ number 13.
      ILC1_ILR14 corresponds to IRQ number 14.
      ILC1_ILR15 corresponds to IRQ number 15.
    ***********************************************************/
    /* in this sample ILC1 isn't used */

    /***********************************************************
      setup of ILC.
      ILC sets interrupt level of IRQ number 16-31.
      ILC_ILR16 corresponds to IRQ number 16 and 17.
      ILC_ILR18 corresponds to IRQ number 18 and 19.
      ILC_ILR20 corresponds to IRQ number 20 and 21.
      ILC_ILR22 corresponds to IRQ number 22 and 23.
      ILC_ILR24 corresponds to IRQ number 24 and 25.
      ILC_ILR26 corresponds to IRQ number 26 and 27.
      ILC_ILR28 corresponds to IRQ number 28 and 29.
      ILC_ILR30 corresponds to IRQ number 30 and 31.
    ***********************************************************/
    /* in this sample ILC isn't used */

    /***********************************************************
      setup of IDM.
      IDM sets IRQ detection mode and interrupt level of IRQ number 16-31.
      IDM_IDM16 and IDM_IDMP16 correspond to IRQ number 16 and 17.
      IDM_IDM18 and IDM_IDMP18 correspond to IRQ number 18 and 19.
      IDM_IDM20 and IDM_IDMP20 correspond to IRQ number 20 and 21.
      IDM_IDM22 and IDM_IDMP22 correspond to IRQ number 22 and 23.
      IDM_IDM24 and IDM_IDMP24 correspond to IRQ number 24 and 25.
      IDM_IDM26 and IDM_IDMP26 correspond to IRQ number 26 and 27.
      IDM_IDM28 and IDM_IDMP28 correspond to IRQ number 28 and 29.
      IDM_IDM30 and IDM_IDMP30 correspond to IRQ number 30 and 31.
    ***********************************************************/
    /* in this sample IDM isn't used */

    //return;
//}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.10.22 at 03:53:01 PM IST
//

package com.pacificmetrics.saaif.passage1;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;

/**
 *
 *     Define the itemattributelist type.
 *     Attributes of an item.
 *
 *
 *
Java class for itemattriblistType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="itemattriblistType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="attrib" type="{http://www.smarterapp.org/xsd/saaif/v1p0/passageitem_v1p0.xsd}itemattribType" maxOccurs="unbounded"/>
 *         <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "itemattriblistType", propOrder = {
    "attrib",
    "any"
})
public class ItemattriblistType {

    @XmlElement(required = true)
    protected List<ItemattribType> attrib;
    @XmlAnyElement(lax = true)
    protected List<Object> any;

    /**
     * Gets the value of the attrib property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the attrib property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAttrib().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ItemattribType }
     *
     *
     */
    public List<ItemattribType> getAttrib() {
        if (attrib == null) {
            attrib = new ArrayList<ItemattribType>();
        }
        return this.attrib;
    }

    /**
     * Gets the value of the any property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the any property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAny().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Object }
     * {@link Element }
     *
     *
     */
    public List<Object> getAny() {
        if (any == null) {
            any = new ArrayList<Object>();
        }
        return this.any;
    }

}


text:
import { Inject, Injectable } from '@angular/core';
import { Restangular } from 'ngx-restangular';
import { ConfigMap, ConfigMaps } from '../model/configmap.model';
import { KUBERNETES_RESTANGULAR } from './kubernetes.restangular';
import { NamespaceScope } from './namespace.scope';
import { NamespacedResourceService } from './namespaced.resource.service';
import { WatcherFactory } from './watcher-factory.service';

@Injectable()
export class ConfigMapService extends NamespacedResourceService<ConfigMap, ConfigMaps> {
  constructor(
    @Inject(KUBERNETES_RESTANGULAR) kubernetesRestangular: Restangular,
    namespaceScope: NamespaceScope,
    watcherFactory: WatcherFactory,
  ) {
    super(kubernetesRestangular, namespaceScope, '/configmaps', watcherFactory);
  }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.contrib.gis.db.models.fields
from django.conf import settings
import django.core.validators
import jsonfield.fields

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='GravelSite',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
                ('name', models.CharField(max_length=80)),
                ('notes', models.TextField(default='', blank=True)),
                ('date_created', models.DateTimeField(auto_now_add=True)),
                ('date_modified', models.DateTimeField(auto_now=True)),
                ('geometry', django.contrib.gis.db.models.fields.MultiPolygonField(srid=3857)),
                ('shared_with_public', models.BooleanField(default=False)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='InputNode',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
                ('name', models.CharField(max_length=80)),
                ('notes', models.TextField(default='', blank=True)),
                ('date_created', models.DateTimeField(auto_now_add=True)),
                ('date_modified', models.DateTimeField(auto_now=True)),
                ('value', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='MapLayer',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
                ('name', models.CharField(max_length=200)),
                ('url_template', models.TextField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Pit',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
                ('name', models.CharField(max_length=80)),
                ('notes', models.TextField(default='', blank=True)),
                ('date_created', models.DateTimeField(auto_now_add=True)),
                ('date_modified', models.DateTimeField(auto_now=True)),
                ('geometry', django.contrib.gis.db.models.fields.PolygonField(srid=3857)),
                ('contamination', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('substrate', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('adjacent_river_depth', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('slope_dist', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('pit_levies', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('bedrock', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('bank_slope', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('pit_depth', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('surface_area', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('complexity', models.FloatField(validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(1.0)])),
                ('site', models.ForeignKey(to='survey.GravelSite')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Question',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),
                ('name', models.CharField(max_length=80)),
                ('title', models.CharField(max_length=80)),
                ('question', models.CharField(max_length=250)),
                ('detail', models.TextField()),
                ('order', models.FloatField()),
                ('image', models.ImageField(upload_to='', blank=True)),
                ('supplement', models.FileField(upload_to='', blank=True)),
                ('choices', jsonfield.fields.JSONField(default='[\n        {\n          "choice": "high",\n          "value": 1.0\n        },\n        {\n          "choice": "low",\n          "value": 0.0\n        }\n]')),
                ('layers', models.ManyToManyField(to='survey.MapLayer', blank=True, related_name='layers')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='inputnode',
            name='question',
            field=models.ForeignKey(to='survey.Question'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='inputnode',
            name='site',
            field=models.ForeignKey(to='survey.GravelSite'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='inputnode',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='inputnode',
            unique_together=set([('site', 'question', 'user')]),
        ),
    ]


text:
<?php

namespace Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Service;

use Assert\Assertion;
use Surfnet\StepupMiddleware\CommandHandlingBundle\Configuration\Service\EmailTemplateService;
use Surfnet\StepupMiddleware\CommandHandlingBundle\Value\Sender;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface as Mailer;
use Symfony\Component\Mime\Address;
use Symfony\Component\Translation\TranslatorInterface;

final class EmailVerificationMailService
{
    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var EmailTemplateService
     */
    private $emailTemplateService;

    /**
     * @var string
     */
    private $emailVerificationUrlTemplate;

    /**
     * @var string
     */
    private $fallbackLocale;

    /**
     * @var Mailer
     */
    private $mailer;

    /**
     * @var Sender
     */
    private $sender;

    /**
     * @var string
     */
    private $selfServiceUrl;

    /**
     * @throws \Assert\AssertionFailedException
     */
    public function __construct(
        Mailer $mailer,
        Sender $sender,
        TranslatorInterface $translator,
        string $emailVerificationUrlTemplate,
        EmailTemplateService $emailTemplateService,
        string $fallbackLocale,
        string $selfServiceUrl
    ) {
        Assertion::string(
            $emailVerificationUrlTemplate,
            'Email verification URL template "%s" expected to be string, type %s given'
        );

        $this->mailer = $mailer;
        $this->sender = $sender;
        $this->translator = $translator;
        $this->emailVerificationUrlTemplate = $emailVerificationUrlTemplate;
        $this->emailTemplateService = $emailTemplateService;
        $this->fallbackLocale = $fallbackLocale;
        $this->selfServiceUrl = $selfServiceUrl;
    }

    /**
     * @throws TransportExceptionInterface
     */
    public function sendEmailVerificationEmail(
        string $locale,
        string $commonName,
        string $email,
        string $verificationNonce
    ): void {
        $subject = $this->translator->trans(
            'ss.mail.email_verification_email.subject',
            ['%commonName%' => $commonName],
            'messages',
            $locale
        );

        $verificationUrl = str_replace(
            '{nonce}',
            urlencode($verificationNonce),
            $this->emailVerificationUrlTemplate
        );

        // In TemplatedEmail email is a reserved keyword, we also use it as a parameter that can be used in the mail
        // message, to prevent having to update all templates, and prevent a 500 error from the mailer, we perform a
        // search and replace of the {email} parameter in the template.
        $emailTemplate = $this->emailTemplateService->findByName('confirm_email', $locale, $this->fallbackLocale);
        $emailTemplate->htmlContent = str_replace(
            '{email}',
            '{emailAddress}',
            $emailTemplate->htmlContent
        );

        $parameters = [
            'templateString' => $emailTemplate->htmlContent,
            'locale' => $locale,
            'commonName' => $commonName,
            'emailAddress' => $email,
            'verificationUrl' => $verificationUrl,
            'selfServiceUrl' => $this->selfServiceUrl,
        ];

        $fromAddress = new Address($this->sender->getEmail(), $this->sender->getName());
        $toAddress = new Address($email, $commonName);
        $message = new TemplatedEmail();
        $message
            ->from($fromAddress)
            ->to($toAddress)
            ->subject($subject)
            ->htmlTemplate('@SurfnetStepupMiddlewareCommandHandling/SecondFactorMailService/email.html.twig')
            ->context($parameters);
        $this->mailer->send($message);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00000000"
    android:gravity="center"
    android:orientation="horizontal">

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

    <TextView
        android:id="@+id/textView1_play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#fe0000"/>

</FrameLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite.Net.Attributes;

namespace StartFinance.Models
{
    class ShoppingList
    {

        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }

        [Unique]
        public string ShoppingItemID { get; set; }

        [NotNull]
        public string ShoppingDate { get; set; }

        [NotNull]
        public string NameOfItem { get; set; }

        [NotNull]
        public double PriceQuoted { get; set; }
    }
}


text:
//
//  camera-capturer.h
//  ndnrtc
//
//  Copyright 2013 Regents of the University of California
//  For licensing details see the LICENSE file.
//
//  Author:  Peter Gusev
//  Created: 8/16/13
//

#ifndef __ndnrtc__camera_capturer__
#define __ndnrtc__camera_capturer__

#include "webrtc.h"
#include "ndnrtc-common.h"
#include "ndnrtc-object.h"
#include "ndnrtc-utils.h"

namespace ndnrtc {
    class IRawFrameConsumer;

    class CameraCapturer : public NdnRtcObject, public webrtc::VideoCaptureDataCallback
    {
    public:
        // construction/desctruction
        CameraCapturer(const ParamsStruct &params);
        ~CameraCapturer();

        // public methods go here
        void setFrameConsumer(IRawFrameConsumer *frameConsumer){ frameConsumer_ = frameConsumer; }
        bool isCapturing() { return (vcm_)?vcm_->CaptureStarted():false; }

        int init();
        int startCapture();
        int stopCapture();
        int numberOfCaptureDevices();
        vector<std::string>* availableCaptureDevices();
        void printCapturingInfo();

        // interface conformance - webrtc::VideoCaptureDataCallback
        void OnIncomingCapturedFrame(const int32_t id,
                                     webrtc::I420VideoFrame& videoFrame);
        void OnCaptureDelayChanged(const int32_t id,
                                   const int32_t delay);

        // statistics
        double getCapturingFrequency() { return NdnRtcUtils::currentFrequencyMeterValue(meterId_); }

    private:
        webrtc::scoped_ptr<webrtc::CriticalSectionWrapper> capture_cs_;
        webrtc::scoped_ptr<webrtc::CriticalSectionWrapper> deliver_cs_;
        webrtc::ThreadWrapper &captureThread_;
        webrtc::EventWrapper &captureEvent_;
        webrtc::I420VideoFrame capturedFrame_, deliverFrame_;
        // private attributes go here
        webrtc::VideoCaptureCapability capability_;
        webrtc::VideoCaptureModule* vcm_ = nullptr;
        IRawFrameConsumer *frameConsumer_ = nullptr;

        // statistics
        unsigned int meterId_;

        static bool deliverCapturedFrame(void *obj) { return ((CameraCapturer*)obj)->process(); }

        bool process();
    };

    class IRawFrameConsumer
    {
    public:
        virtual void onDeliverFrame(webrtc::I420VideoFrame &frame) = 0;
    };
}

#endif /* defined(__ndnrtc__camera_capturer__) */


text:
import { set, get } from '@ember/object';
import { run } from '@ember/runloop';
import RSVP, { resolve } from 'rsvp';
import setupStore from 'dummy/tests/helpers/store';

import { module, test } from 'qunit';
import DS from 'ember-data';

const { all, hash } = RSVP;
const { attr } = DS;

let Person, env, store;

module("integration/adapter/record_persistence - Persisting Records", {
  beforeEach() {
    Person = DS.Model.extend({
      updatedAt: attr('string'),
      name: attr('string'),
      firstName: attr('string'),
      lastName: attr('string')
    });

    env = setupStore({
      adapter: DS.Adapter.extend({
        shouldBackgroundReloadRecord: () => false
      }),
      person: Person
    });
    store = env.store;
  },

  afterEach() {
    run(env.container, 'destroy');
  }
});

test("When a store is committed, the adapter's `commit` method should be called with records that have been changed.", function(assert) {
  assert.expect(2);

  env.adapter.updateRecord = function(store, type, snapshot) {
    assert.equal(type, Person, "the type is correct");
    assert.equal(snapshot.record, tom, "the record is correct");

    return run(RSVP, 'resolve');
  };

  run(() => {
    env.store.push({
      data: {
        type: 'person',
        id: '1',
        attributes: {
          name: 'Braaaahm Dale'
        }
      }
    });
  });

  let tom;

  return run(() => {
    return env.store.findRecord('person', 1).then(person => {
      tom = person;
      set(tom, "name", "Tom Dale");
      return tom.save();
    });
  });
});

test("When a store is committed, the adapter's `commit` method should be called with records that have been created.", function(assert) {
  assert.expect(2);
  let tom;

  env.adapter.createRecord = function(store, type, snapshot) {
    assert.equal(type, Person, "the type is correct");
    assert.equal(snapshot.record, tom, "the record is correct");

    return resolve({ data: { id: 1, type: "person", attributes: { name: "Tom Dale" } } });
  };

  return run(() => {
    tom = env.store.createRecord('person', { name: "Tom Dale" });
    return tom.save();
  });
});

test("After a created record has been assigned an ID, finding a record by that ID returns the original record.", function(assert) {
  assert.expect(1);
  let tom;

  env.adapter.createRecord = function(store, type, snapshot) {
    return resolve({ data: { id: 1, type: "person", attributes: { name: "Tom Dale" } } });
  };

  return run(() => {
    tom = env.store.createRecord('person', { name: "Tom Dale" });
    return tom.save();
  }).then(tom => {
    return env.store.find('person', 1).then(nextTom => {
      assert.equal(tom, nextTom, "the retrieved record is the same as the created record");
    });
  });
});

test("when a store is committed, the adapter's `commit` method should be called with records that have been deleted.", function(assert) {
  env.adapter.deleteRecord = function(store, type, snapshot) {
    assert.equal(type, Person, "the type is correct");
    assert.equal(snapshot.record, tom, "the record is correct");

    return run(RSVP, 'resolve');
  };

  let tom;

  run(() => {
    env.store.push({
      data: {
        type: 'person',
        id: '1',
        attributes: {
          name: "Tom Dale"
        }
      }
    });
  });

  return env.store.findRecord('person', 1).then(person => {
    tom = person;
    tom.deleteRecord();
    return tom.save();
  }).then(tom => {
    assert.equal(get(tom, 'isDeleted'), true, "record is marked as deleted");
  });
});

test("An adapter can notify the store that records were updated by calling `didSaveRecords`.", function(assert) {
  assert.expect(6);

  let tom, yehuda;

  env.adapter.updateRecord = function(store, type, snapshot) {
    return resolve();
  };

  run(() => {
    env.store.push({
      data: [{
        type: 'person',
        id: '1'
      }, {
        type: 'person',
        id: '2'
      }]
    });
  });

  return all([
    env.store.findRecord('person', 1),
    env.store.findRecord('person', 2)
  ])
    .then(array => {
      tom = array[0];
      yehuda = array[1];

      tom.set('name', "Michael Phelps");
      yehuda.set('name', "Usain Bolt");

      assert.ok(tom.get('hasDirtyAttributes'), "tom is dirty");
      assert.ok(yehuda.get('hasDirtyAttributes'), "yehuda is dirty");

      let savedTom = assert.assertClean(tom.save()).then(record => {
        assert.equal(record, tom, "The record is correct");
      });

      let savedYehuda = assert.assertClean(yehuda.save()).then(record => {
        assert.equal(record, yehuda, "The record is correct");
      });

      return all([
        savedTom,
        savedYehuda
      ]);
    });
});

test("An adapter can notify the store that records were updated and provide new data by calling `didSaveRecords`.", function(assert) {
  env.adapter.updateRecord = function(store, type, snapshot) {
    if (snapshot.id === "1") {
      return resolve({ data: { id: 1, type: "person", attributes: { name: "Tom Dale", "updated-at": "now" } } });
    } else if (snapshot.id === "2") {
      return resolve({ data: { id: 2, type: "person", attributes: { name: "Yehuda Katz", "updated-at": "now!" } } });
    }
  };

  run(() => {
    env.store.push({
      data: [{
        type: 'person',
        id: '1',
        attributes: {
          name: 'Braaaahm Dale'
        }
      }, {
        type: 'person',
        id: '2',
        attributes: {
          name: 'Gentile Katz'
        }
      }]
    });
  });

  return hash({
    tom: env.store.findRecord('person', 1),
    yehuda: env.store.findRecord('person', 2)
  }).then(people => {
    people.tom.set('name', "Draaaaaahm Dale");
    people.yehuda.set('name', "Goy Katz");

    return hash({
      tom: people.tom.save(),
      yehuda: people.yehuda.save()
    });
  }).then(people => {
    assert.equal(people.tom.get('name'), "Tom Dale", "name attribute should reflect value of hash passed to didSaveRecords");
    assert.equal(people.tom.get('updatedAt'), "now", "updatedAt attribute should reflect value of hash passed to didSaveRecords");
    assert.equal(people.yehuda.get('name'), "Yehuda Katz", "name attribute should reflect value of hash passed to didSaveRecords");
    assert.equal(people.yehuda.get('updatedAt'), "now!", "updatedAt attribute should reflect value of hash passed to didSaveRecords");
  });
});

test("An adapter can notify the store that a record was updated by calling `didSaveRecord`.", function(assert) {
  env.adapter.updateRecord = function(store, type, snapshot) {
    return resolve();
  };

  run(() => {
    store.push({
      data: [{
        type: 'person',
        id: '1'
      }, {
        type: 'person',
        id: '2'
      }]
    });
  });

  return hash({
    tom: store.findRecord('person', 1),
    yehuda: store.findRecord('person', 2)
  }).then(people => {
    people.tom.set('name', "Tom Dale");
    people.yehuda.set('name', "Yehuda Katz");

    assert.ok(people.tom.get('hasDirtyAttributes'), "tom is dirty");
    assert.ok(people.yehuda.get('hasDirtyAttributes'), "yehuda is dirty");

    assert.assertClean(people.tom.save());
    assert.assertClean(people.yehuda.save());
  });
});

test("An adapter can notify the store that a record was updated and provide new data by calling `didSaveRecord`.", function(assert) {
  env.adapter.updateRecord = function(store, type, snapshot) {
    switch (snapshot.id) {
      case "1":
        return resolve({ data: { id: 1, type: "person", attributes: { name: "Tom Dale", "updated-at": "now" } } });
      case "2":
        return resolve({ data: { id: 2, type: "person", attributes: { name: "Yehuda Katz", "updated-at": "now!" } } });
    }
  };

  run(() => {
    env.store.push({
      data: [{
        type: 'person',
        id: '1',
        attributes: {
          name: 'Braaaahm Dale'
        }
      }, {
        type: 'person',
        id: '2',
        attributes: {
          name: 'Gentile Katz'
        }
      }]
    });
  });

  return hash({
    tom: store.findRecord('person', 1),
    yehuda: store.findRecord('person', 2)
  }).then(people => {
    people.tom.set('name', "Draaaaaahm Dale");
    people.yehuda.set('name', "Goy Katz");

    return hash({
      tom: people.tom.save(),
      yehuda: people.yehuda.save()
    });
  }).then(people => {
    assert.equal(people.tom.get('name'), "Tom Dale", "name attribute should reflect value of hash passed to didSaveRecords");
    assert.equal(people.tom.get('updatedAt'), "now", "updatedAt attribute should reflect value of hash passed to didSaveRecords");
    assert.equal(people.yehuda.get('name'), "Yehuda Katz", "name attribute should reflect value of hash passed to didSaveRecords");
    assert.equal(people.yehuda.get('updatedAt'), "now!", "updatedAt attribute should reflect value of hash passed to didSaveRecords");
  });
});

test("An adapter can notify the store that records were deleted by calling `didSaveRecords`.", function(assert) {
  env.adapter.deleteRecord = function(store, type, snapshot) {
    return resolve();
  };

  run(() => {
    env.store.push({
      data: [{
        type: 'person',
        id: '1',
        attributes: {
          name: 'Braaaahm Dale'
        }
      }, {
        type: 'person',
        id: '2',
        attributes: {
          name: 'Gentile Katz'
        }
      }]
    });
  });

  return hash({
    tom: store.findRecord('person', 1),
    yehuda: store.findRecord('person', 2)
  }).then(people => {
    people.tom.deleteRecord();
    people.yehuda.deleteRecord();

    assert.assertClean(people.tom.save());
    assert.assertClean(people.yehuda.save());
  });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. natn. Sci. Mus. , Tokyo, B 8(2): 50 (1982)

#### Original name
Torrubiella ellipsoidea Kobayasi & Shimizu

### Remarks
null


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Razorfish | Experiment Title</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
    <meta property="og:site_name" content="Razorfish Expariment Title prototype" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Razorfish Expariment Title prototype" />
    <meta property="og:url" content="http://andrevenancio.github.io/playground/template/template.html" />
    <meta property="og:image" content="http://andrevenancio.github.io/playground/template/preview.png" />
    <meta property="og:description" content="prototype" />
    <link rel="stylesheet" type="text/css" href="css/rf.css">
    <script src="lib/stats.min.js"></script>
    <script src="lib/dat.gui.min.js"></script>
    <script src="lib/razor.min.js"></script>
    <script src="lib/raf.js"></script>
  </head>
  <body>
    <header>Experiment Title</header>

    <canvas id="canvas"></canvas>
    <script src="js/example.js"></script>
    <script>
      var example = new Example();
    </script>
  </body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Ash.Core
{
    public class MockEntity : IEntity
    {
        protected List<object> _components;
        public List<object> Components
        {
            get { return _components; }
            set { _components = value; }
        }

        public MockEntity()
        {
            ComponentAdded = new ComponentAdded();
            ComponentRemoved = new ComponentRemoved();
            _components = new List<object>();
        }

        public bool Has(Type type)
        {
            return _components.Any(c => type.IsAssignableFrom(c.GetType()));
        }

        public bool IsDestroyed { get; private set; }

        public object Get(Type type)
        {
            if (!Has(type))
                throw new Exception("Invalid type");

            return _components.FirstOrDefault(c => type.IsAssignableFrom(c.GetType()));
        }

        public T Add<T>() where T : Component
        {
            var inst = Activator.CreateInstance<T>();
            _components.Add(inst);
            return inst;
        }

        public void Remove(Component component)
        {
            _components.Remove(component);
        }

        public ComponentAdded ComponentAdded { get; private set; }
        public ComponentRemoved ComponentRemoved { get; private set; }
    }

    public class MockEntity<T1> : MockEntity
    {
        public MockEntity()
        {
            _components.Add(Activator.CreateInstance<T1>());
        }
    }

    public class MockEntity<T1,T2> : MockEntity
    {
        public MockEntity()
        {
            _components.Add(Activator.CreateInstance<T1>());
            _components.Add(Activator.CreateInstance<T2>());
        }
    }

    public class MockEntity<T1, T2, T3> : MockEntity
    {
        public MockEntity()
        {
            _components.Add(Activator.CreateInstance<T1>());
            _components.Add(Activator.CreateInstance<T2>());
            _components.Add(Activator.CreateInstance<T3>());
        }
    }
}


text:
openstack_logging_filemonitor "cinder-api" do
  monitor_name "cinder-api"
  action :create
  only_if { node.recipe?("cinder::cinder-api") }
end
openstack_logging_filemonitor "cinder-scheduler" do
  monitor_name "cinder-scheduler"
  action :create
  only_if { node.recipe?("cinder::cinder-api") }
end
openstack_logging_filemonitor "cinder-volume" do
  monitor_name "cinder-volume"
  action :create
  only_if { node.recipe?("cinder::cinder-volume") }
end


text:
module.exports = {
  strategy: 'git-commit-subj'
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const util_1 = require("../util");
const quote_1 = require("../../runtime/quote");
const genSerialize = {
    elements: serializeElements,
    values: serializeValues,
    discriminator: serializeDiscriminator,
    properties: serializeProperties,
    optionalProperties: serializeProperties,
    enum: serializeString,
    type: serializeType,
    ref: serializeRef,
};
function compileSerializer(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const serializeName = gen.scopeName("serialize");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.serializeName = serializeName;
        gen.func(serializeName, names_1.default.data, false, () => {
            gen.let(names_1.default.json, (0, codegen_1.str) ``);
            serializeCode(cxt);
            gen.return(names_1.default.json);
        });
        gen.optimize(this.opts.code.optimize);
        const serializeFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
        const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
        const serialize = makeSerialize(this.scope.get());
        this.scope.value(serializeName, { ref: serialize });
        sch.serialize = serialize;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling serializer, function code:", sourceCode);
        delete sch.serialize;
        delete sch.serializeName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileSerializer;
function serializeCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
}
function serializeNullable(cxt, serializeForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return serializeForm(cxt);
    gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt));
}
function serializeElements(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `[`);
    const first = gen.let("first", true);
    gen.forOf("el", data, (el) => {
        addComma(cxt, first);
        serializeCode({ ...cxt, schema: schema.elements, data: el });
    });
    gen.add(names_1.default.json, (0, codegen_1.str) `]`);
}
function serializeValues(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    const first = gen.let("first", true);
    gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeKeyValue(cxt, key, schema, first) {
    const { gen, data } = cxt;
    addComma(cxt, first);
    serializeString({ ...cxt, data: key });
    gen.add(names_1.default.json, (0, codegen_1.str) `:`);
    const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    serializeCode({ ...cxt, schema, data: value });
}
function serializeDiscriminator(cxt) {
    const { gen, schema, data } = cxt;
    const { discriminator } = schema;
    gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`);
    const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`);
    serializeString({ ...cxt, data: tag });
    gen.if(false);
    for (const tagValue in schema.mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        const sch = schema.mapping[tagValue];
        serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
    }
    gen.endIf();
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeProperties(cxt) {
    const { gen } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    serializeSchemaProperties(cxt);
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties } = schema;
    const props = keys(properties);
    const optProps = keys(optionalProperties);
    const allProps = allProperties(props.concat(optProps));
    let first = !discriminator;
    for (const key of props) {
        serializeProperty(key, properties[key], keyValue(key));
    }
    for (const key of optProps) {
        const value = keyValue(key);
        gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => serializeProperty(key, optionalProperties[key], value));
    }
    if (schema.additionalProperties) {
        gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, gen.let("first", first))));
    }
    function keys(ps) {
        return ps ? Object.keys(ps) : [];
    }
    function allProperties(ps) {
        if (discriminator)
            ps.push(discriminator);
        if (new Set(ps).size !== ps.length) {
            throw new Error("JTD: properties/optionalProperties/disciminator overlap");
        }
        return ps;
    }
    function keyValue(key) {
        return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    }
    function serializeProperty(key, propSchema, value) {
        if (first)
            first = false;
        else
            gen.add(names_1.default.json, (0, codegen_1.str) `,`);
        gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`);
        serializeCode({ ...cxt, schema: propSchema, data: value });
    }
    function isAdditional(key, ps) {
        return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true;
    }
}
function serializeType(cxt) {
    const { gen, schema, data } = cxt;
    switch (schema.type) {
        case "boolean":
            gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`);
            break;
        case "string":
            serializeString(cxt);
            break;
        case "timestamp":
            gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt));
            break;
        default:
            serializeNumber(cxt);
    }
}
function serializeString({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`);
}
function serializeNumber({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`);
}
function serializeRef(cxt) {
    const { gen, self, data, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default("", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return serializeCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`);
}
function getSerialize(gen, sch) {
    return sch.serialize
        ? gen.scopeValue("serialize", { ref: sch.serialize })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
}
function serializeEmpty({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`);
}
function addComma({ gen }, first) {
    gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`));
}
//# sourceMappingURL=serialize.js.map


text:
package org.telegram.api.input.user;

import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * The type TL input user user.
 */
public class TLInputUser extends TLAbsInputUser {
    /**
     * The constant CLASS_ID.
     */
    public static final int CLASS_ID = 0xd8292816;

    private int userId;
    private long accessHash;

    /**
     * Instantiates a new TL input user.
     */
    public TLInputUser() {
        super();
    }

    public int getClassId() {
        return CLASS_ID;
    }

    /**
     * Gets user id.
     *
     * @return the user id
     */
    public int getUserId() {
        return this.userId;
    }

    /**
     * Sets user id.
     *
     * @param userId the user id
     */
    public void setUserId(int userId) {
        this.userId = userId;
    }

    /**
     * Gets access hash.
     *
     * @return the access hash
     */
    public long getAccessHash() {
        return this.accessHash;
    }

    /**
     * Sets access hash.
     *
     * @param accessHash the access hash
     */
    public void setAccessHash(long accessHash) {
        this.accessHash = accessHash;
    }

    public void serializeBody(OutputStream stream)
            throws IOException {
        StreamingUtils.writeInt(this.userId, stream);
        StreamingUtils.writeLong(this.accessHash, stream);
    }

    public void deserializeBody(InputStream stream, TLContext context)
            throws IOException {
        this.userId = StreamingUtils.readInt(stream);
        this.accessHash = StreamingUtils.readLong(stream);
    }

    public String toString() {
        return "inputUser#d8292816";
    }
}


text:
<component name="libraryTable">
  <library name="android-permission-manager-1.0.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.buchandersenn/android-permission-manager/1.0.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.buchandersenn/android-permission-manager/1.0.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.github.buchandersenn/android-permission-manager/1.0.0/84551ca11ba77ce6ec3c7b512635d96a817be7b2/android-permission-manager-1.0.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package org.jivesoftware.spark.ui;

import java.awt.event.MouseEvent;
import java.util.Collection;

import org.jivesoftware.spark.plugin.ContextMenuListener;

/**
 * The ContactGroupListener interface is one of the interfaces extension writers use to add functionality to Spark.
 *

 * In general, you implement this interface in order to listen for mouse and key events on ContactGroups within
 * the Spark client ContactList.
 */
public interface ContactGroupListener {

    /**
     * Notifies a user that a new ContactItem has been added to the ContactGroup.
     *
     * @param item the ContactItem.
     */
    public void contactItemAdded(ContactItem item);

    /**
     * Notifies the user that a ContactItem has been removed from a ContactGroup.
     *
     * @param item the ContactItem removed.
     */
    public void contactItemRemoved(ContactItem item);

    /**
     * Notifies the user that a ContactItem within the ContactGroup has been double-clicked.
     *
     * @param item the ContactItem double clicked.
     */
    public void contactItemDoubleClicked(ContactItem item);

    /**
     * Notifies the user that a ContactItem within the ContactGroup has been clicked.
     *
     * @param item the ContactItem clicked.
     */
    public void contactItemClicked(ContactItem item);

    /**
     * Notifies the user that a popup call has occured on the ContactGroup.
     *
     * @param e    the MouseEvent that triggered the event.
     * @param item the ContactItem clicked within the ContactGroup.
     * @deprecated see {@link ContextMenuListener}
     */
    public void showPopup(MouseEvent e, ContactItem item);

    /**
     * Notifies the user that a popup call has occured on the ContactGroup.
     *
     * @param e     the MouseEvent that triggered the event.
     * @param items the ContactItems within the ContactGroup.
     * @deprecated see ContextMenuListener
     */
    public void showPopup(MouseEvent e, Collection<ContactItem> items);

    /**
     * Notifies the user that a Popup event has occured on the ContactGroup title
     * bar.
     *
     * @param e     the MouseEvent that triggered the event.
     * @param group the ContactGroup.
     */
    public void contactGroupPopup(MouseEvent e, ContactGroup group);
}


text:
<?php

namespace Google\Service\Contentwarehouse;

class TeragoogleDocumentInfoSection extends \Google\Collection
{
  protected $collection_key = 'fieldName';
  /**
   * @var string[]
   */
  public $fieldName;
  /**
   * @var string
   */
  public $name;
  /**
   * @var string
   */
  public $tokens;

  /**
   * @param string[]
   */
  public function setFieldName($fieldName)
  {
    $this->fieldName = $fieldName;
  }
  /**
   * @return string[]
   */
  public function getFieldName()
  {
    return $this->fieldName;
  }
  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param string
   */
  public function setTokens($tokens)
  {
    $this->tokens = $tokens;
  }
  /**
   * @return string
   */
  public function getTokens()
  {
    return $this->tokens;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(TeragoogleDocumentInfoSection::class, 'Google_Service_Contentwarehouse_TeragoogleDocumentInfoSection');


text:
using UnityEngine;
using System.Collections;

public class Global : MonoBehaviour {

	public bool showMenu = false;
	public bool showInterfaceMenu = false;
	public GameObject actualPlayer;
	public GameObject[] players;
	public GameObject selectedBlock;

	// Use this for initialization
	void Start () {

		players = GameObject.FindGameObjectsWithTag ("Character");
		Debug.Log (players.Length.ToString());

	}

	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown ("1")) {
			Debug.Log ("Entro en el input");
			foreach (GameObject playerFound in players) {
				if (playerFound.name.Equals ("Recolector")) {
					playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().active = true;
					actualPlayer = playerFound.transform.parent.gameObject;
					Debug.Log (playerFound.name + "if");
					if (!playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled)
						playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled = true;
				} else {
					playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().active = false;
					if (playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled)
						playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled = false;
					Debug.Log (playerFound.name + "else");
				}
			}
		} else if (Input.GetButtonDown ("2")) {
			Debug.Log ("Entro en el input");
			foreach (GameObject playerFound in players) {
				if (playerFound.name.Equals ("Digger")) {
					playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().active = true;
					actualPlayer = playerFound.transform.parent.gameObject;
					if (!playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled) {
						playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled = true;
					}
				} else {
					playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().active = false;
					if (playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled) {
						playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().move = 0;
						playerFound.transform.parent.gameObject.GetComponent<CharacterMovement> ().enabled = false;
					}
				}
			}
		}
	}
}


text:
define(["jquery"], function($) {

	"use strict";
	// copy of http://blog.csdn.net/sunxinty/article/details/52586556
	function Router() {
		this.routes = {};
		this.currentUrl = '';
	}

	Router.prototype.route = function(path, callback) {
		this.routes[path] = callback;
	};

	Router.prototype.refresh = function() {
		this.currentUrl = location.hash.slice(1) || '/';
		(this.routes[this.currentUrl] || (function(path) {
			return function() {
				console.log("no register router of path "+path);

				require(["rt/pageContext"],function(pageContext){
					// 触发卸载事件
					pageContext.shutdown();
					// 加载新页面
					$("#__pageContext").load(path,null,function(response,status,xhr){
						if(status == "error"){
							if(xhr.status == "404"){
								$("#__pageContext").html("

Page NotFound 404

")
							}
						}else{
							// 绑定页面模块

						}
					});
				})

				//$("#__pageContext").render();
			};
		}(this.currentUrl)))();
	};

	Router.prototype.init = function() {
		window.addEventListener('load', this.refresh.bind(this), false);
		window.addEventListener('hashchange', this.refresh.bind(this), false);
	}

	return new Router();
});


text:
package org.psjava.ds.tree.binary;

import java.util.Iterator;

import org.psjava.ds.tree.binary.bst.MinimumFinder;
import org.psjava.ds.tree.binary.bst.SuccessorFinder;
import org.psjava.util.Assertion;
import org.psjava.util.ReadOnlyIterator;

public class InOrderIterator {

    public static <D2, D1 extends D2> Iterator<D2> create(final BinaryTreeNodeWithParent<D1> rootOrNull) {
        return new ReadOnlyIterator<D2>() {

            BinaryTreeNodeWithParent<D1> nextOrNull = (rootOrNull == null) ? null : MinimumFinder.find(rootOrNull);

            @Override
            public boolean hasNext() {
                return nextOrNull != null;
            }

            @Override
            public D2 next() {
                Assertion.ensure(nextOrNull != null);
                BinaryTreeNodeWithParent<D1> r = nextOrNull;
                nextOrNull = SuccessorFinder.findOrNull(r);
                return r.getData();
            }
        };
    }

    private InOrderIterator() {
    }

}


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class GetMostEmailed(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the GetMostEmailed Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(GetMostEmailed, self).__init__(temboo_session, '/Library/NYTimes/MostPopular/GetMostEmailed')

    def new_input_set(self):
        return GetMostEmailedInputSet()

    def _make_result_set(self, result, path):
        return GetMostEmailedResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return GetMostEmailedChoreographyExecution(session, exec_id, path)

class GetMostEmailedInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the GetMostEmailed
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_APIKey(self, value):
        """
        Set the value of the APIKey input for this Choreo. ((required, string) The API Key provided by NY Times.)
        """
        super(GetMostEmailedInputSet, self)._set_input('APIKey', value)
    def set_Offset(self, value):
        """
        Set the value of the Offset input for this Choreo. ((optional, string) The first 20 results are shown by default. To page through the results, set Offset to the appropriate value.)
        """
        super(GetMostEmailedInputSet, self)._set_input('Offset', value)
    def set_ResponseFormat(self, value):
        """
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.)
        """
        super(GetMostEmailedInputSet, self)._set_input('ResponseFormat', value)
    def set_Section(self, value):
        """
        Set the value of the Section input for this Choreo. ((required, string) Limits the results by one or more sections (i.e. arts).  To get all sections, specify all-sections.)
        """
        super(GetMostEmailedInputSet, self)._set_input('Section', value)
    def set_TimePeriod(self, value):
        """
        Set the value of the TimePeriod input for this Choreo. ((required, integer) Allowed integer values: 1, 7, or 30, which corresponds to a day (1) , a week (7), or a month (30) of content.)
        """
        super(GetMostEmailedInputSet, self)._set_input('TimePeriod', value)

class GetMostEmailedResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the GetMostEmailed Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. (The response from the NY Times API.)
        """
        return self._output.get('Response', None)

class GetMostEmailedChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return GetMostEmailedResultSet(response, path)


text:
namespace paint_preview {

WarmCompositor::WarmCompositor()
    : compositor_service_(nullptr, base::OnTaskRunnerDeleter(nullptr)) {}
WarmCompositor::~WarmCompositor() = default;

// static
WarmCompositor* WarmCompositor::GetInstance() {
  return base::Singleton<WarmCompositor,
                         base::LeakySingletonTraits<WarmCompositor>>::get();
}

void WarmCompositor::WarmupCompositor() {
  if (compositor_service_)
    return;

  compositor_service_ = StartCompositorService(base::BindOnce(
      &WarmCompositor::OnDisconnect, weak_ptr_factory_.GetWeakPtr()));
}

bool WarmCompositor::StopCompositor() {
  if (!compositor_service_)
    return false;

  compositor_service_.reset();
  return true;
}

std::unique_ptr<PaintPreviewCompositorService, base::OnTaskRunnerDeleter>
WarmCompositor::GetOrStartCompositorService(
    base::OnceClosure disconnect_handler) {
  if (!compositor_service_)
    return StartCompositorService(std::move(disconnect_handler));

  compositor_service_->SetDisconnectHandler(std::move(disconnect_handler));
  return std::move(compositor_service_);
}

void WarmCompositor::OnDisconnect() {
  compositor_service_.reset();
}

}  // namespace paint_preview


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

interface Migration_Sprig_Field {

	/**
	 * Returns a list of columns represented by this field.
	 *
	 * @return	array
	 */
	public function columns();

} // End Migration_Sprig_Field


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.course')

/**
 * Courses nav handler.
 *
 * @module mm.core.course
 * @ngdoc service
 * @name $mmCourseCoursesNavHandler
 */
.factory('$mmCourseCoursesNavHandler', function() {
    return {

        /**
         * Check if handler is enabled.
         *
         * @return {Boolean} True if handler is enabled, false otherwise.
         */
        isEnabled: function() {
            return true;
        },

        /**
         * Check if handler is enabled for this course.
         *
         * @param {Number} courseId   Course ID.
         * @param {Object} accessData Type of access to the course: default, guest, ...
         * @return {Boolean}          True if handler is enabled, false otherwise.
         */
        isEnabledForCourse: function() {
            return true;
        },

        /**
         * Get the controller.
         *
         * @param {Number} courseId Course ID.
         * @return {Object}         Controller.
         */
        getController: function(courseId) {
            return function($scope, $state) {
                $scope.icon = 'ion-briefcase';
                $scope.title = 'mm.course.contents';
                $scope.class = 'mm-course-handler';

                $scope.action = function(e, course) {
                    $state.go('site.mm_course', {courseid: course.id, coursefullname: course.fullname});
                    e.preventDefault();
                    e.stopPropagation();
                };
            };
        }
    };
});


text:
'use strict';

var weapon = {};

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function pickOne(list) {
        return list[getRandomInt(0,list.length)]
}

function makeATreasure() {
    var magicList = ['Quest Orb', 'Orb', 'Wand', 'Tome', 'Rod', 'Puppy Foot', 'Boots', 'Staff', 'Ring', 'Belt'];
    var magicOf = ['Wonder', 'Stroking', 'Smiting', 'Flying', 'Water Breathing', 'Smiling', 'Jumping', 'Running', 'Swimming', 'Pooping', 'Leaving', 'Flames', 'Ice', 'the Wind'];
    var magicAdj = ['Wonderful', 'Lucky', 'Glittey', 'Glowing', 'Exquisite', 'Glimmering', 'Shimmering', 'Humming', 'Other-worldly', 'Rainbow-infused'];
    var itemList = ['knapsack', 'stick', 'rock', 'walking stick', 'lump of coal', 'peppermill', 'pouch', 'marble'];
    var itemAdj = ['snotty', 'clean', 'dirty', 'muddy', 'new', 'used', 'unused', 'worn', 'old', 'ancient', 'vintage', 'antique'];
    var weaponAdj = itemAdj.concat(['blood encrusted', 'brain encrusted', 'bloody', 'bile coated']);
    var metalWeaponAdj = weaponAdj.concat(['rusty', 'corroded', 'polished', 'dull', 'dented', 'bent']);
    var bladeAdj = metalWeaponAdj.concat(['sharp', 'dull', 'serrated']);
    var bladeItemList = ['butter knife', 'knife', 'stilleto', 'dagger', 'dirk', 'shortsword', 'longsword', 'epee', 'saber', 'katana', 'broadsword', 'bastard sword', 'butterfly knife', 'rapier'];
    var weaponMaterial = ['bronze', 'iron', 'steel'];

    var pick = getRandomInt(0,3);
    if (pick == 0) return pickOne(bladeAdj) + ' ' + pickOne(bladeItemList)
        else if (pick == 1) return pickOne(magicAdj) + ' ' + pickOne(magicList) + ' of ' + pickOne(magicOf)
            else if (pick == 2) {
                var weapon = new Weapon(pickOne(bladeAdj), getRandomInt(0,9), pickOne(weaponMaterial), pickOne(bladeItemList), pickOne(magicOf));
                return weapon.describe();
            }
            else return pickOne(itemAdj) + ' ' + pickOne(itemList);
}

function Button(parent, id, text, active, action, activeCondition) {
    this.myButton = document.createElement('button');
    this.myButton.innerHTML = text;
    this.myButton.id = id;
    this.myButton.type = 'button';
    this.parent = parent;
    this.activeCondition = activeCondition;

    document.getElementById(parent).appendChild(this.myButton);
    //document.getElementById(parent).appendChild(document.createElement('br'));

    if (active) {
        this.myButton.addEventListener('click', action);
    }
}

Button.prototype.deactivate = function() {
    document.getElementById(this.myButton.id).disabled = true;
}

Button.prototype.activate = function() {
    document.getElementById(this.myButton.id).disabled = false;
}

function Weapon(condition, quality, material, kind, modifier) {
    var magicList = ['Quest Orb', 'Orb', 'Wand', 'Tome', 'Rod', 'Puppy Foot', 'Boots', 'Staff', 'Ring', 'Belt'];
    var magicOf = ['Wonder', 'Stroking', 'Smiting', 'Flying', 'Water Breathing', 'Smiling', 'Jumping', 'Running', 'Swimming', 'Pooping', 'Leaving', 'Flames', 'Ice', 'the Wind'];
    var magicAdj = ['Wonderful', 'Lucky', 'Glittey', 'Glowing', 'Exquisite', 'Glimmering', 'Shimmering', 'Humming', 'Other-worldly', 'Rainbow-infused'];
    var itemList = ['knapsack', 'stick', 'rock', 'walking stick', 'lump of coal', 'peppermill', 'pouch', 'marble'];
    var itemAdj = ['snotty', 'clean', 'dirty', 'muddy', 'new', 'used', 'unused', 'worn', 'old', 'ancient', 'vintage', 'antique'];
    var weaponAdj = itemAdj.concat(['blood encrusted', 'brain encrusted', 'bloody', 'bile coated']);
    var metalWeaponAdj = weaponAdj.concat(['rusty', 'corroded', 'polished', 'dull', 'dented', 'bent']);
    var bladeAdj = metalWeaponAdj.concat(['sharp', 'dull', 'serrated']);
    var bladeItemList = ['butter knife', 'knife', 'stilleto', 'dagger', 'dirk', 'shortsword', 'longsword', 'epee', 'saber', 'katana', 'broadsword', 'bastard sword', 'butterfly knife', 'rapier'];
    var weaponMaterial = ['bronze', 'iron', 'steel'];

    if (condition===undefined) {
        this.condition = pickOne(bladeAdj);
        this.quality = pickOne(getRandomInt(0,9));
        this.material = pickOne(weaponMaterial);
        this.kind = pickOne(bladeItemList);
        this.modifier = pickOne(magicOf);
    }
    else {
        this.condition = condition;
        this.quality = quality;
        this.material = material;
        this.kind = kind;
        this.modifier = modifier;
    }
        switch (this.quality) {
            case 0:
                this.qualityAdj = 'junk';
                break;
            case 1:
                this.qualityAdj = 'crappy';
                break;
            case 2:
                this.qualityAdj = 'boring';
                break;
            default:
                this.qualityAdj = '';
                break;
            case 7:
                this.qualityAdj = 'quality';
                break;
            case 8:
                this.qualityAdj = 'excellent';
                break;
            case 9:
                this.qualityAdj = 'masterwork';
        }
}

Weapon.prototype.describe = function() {
    return this.condition + ', ' + this.qualityAdj + (this.qualityAdj == '' ? '' : ', ') + this.material + ' ' + this.kind + ' of ' + this.modifier;
}

function Item() {
    this.description = "Treasure"
}

Item.prototype.describe = function() {
    return this.description;
}

function Player(vitals, gold, skills) {
    this.gold = gold;
    this.vitals = vitals;
    this.skills = skills;
}

Player.prototype.haveABirthday = function() {
    yourDiary.addEntry('Happy Birthday!');
    this.addXp(10);
    this.vitals.age += 1;
    timer.addEvent('Birthday', SECONDS_IN_YEAR, function() {you.haveABirthday();});
}

Player.prototype.isAlive = function() {
    return (you.vitals.health >= 0);
}

Player.prototype.isAwake = function() {
    return (you.vitals.cognizance === 'awake');
}

Player.prototype.adjHealth = function(amount){
    this.vitals.health += amount;
    if (this.vitals.health > this.vitals.healthMax) { this.vitals.health = this.vitals.healthMax; }
    if (!this.isAlive()) { this.death(); }
}

Player.prototype.addXp = function(amount) {
    this.skills.xp += amount;
}

Player.prototype.death = function() {
    you.vitals.cognizance = 'dead';
    you.checkBladder();
    yourDiary.addEntry('You have died. Refresh page to start over, or press load to load from last save.')
    questButton.deactivate();
}

Player.prototype.nextLevel = function() {
    if (this.isAlive()) {
        var raise = Math.round(Math.log(this.skills.xp));
        this.vitals.healthMax += raise;
        this.adjHealth(this.vitals.healthMax);
        yourDiary.addEntry('Level UP! Max Health increases by ' + raise + ' and full heal!');
    }
}

Player.prototype.piss = function() {
    if (you.vitals.bladder > 0) {
        you.vitals.bladder = 0;
        if (you.isAlive()) {
            if (you.isAwake()) yourDiary.addEntry('You take a piss.')
            else yourDiary.addEntry('You wet the bed.');
        }
    }
    else yourDiary.addEntry('You don\'t need to go right now.')
}

Player.prototype.sleep = function () {
    if (you.isAlive()) {
        if (you.vitals.cognizance === 'asleep') {
            you.wakeUp();
        }
        else {
            you.vitals.cognizance = 'asleep';
            document.getElementById('sleep').innerHTML = 'Wake up';
            questButton.deactivate();
            yourDiary.addEntry('You go to sleep!');
            timer.addEvent('Wake', SECONDS_IN_HOUR * 8, function () { you.wakeUp() });
        }
    }
}

Player.prototype.wakeUp = function () {
    if (you.isAlive()) {
        if (you.vitals.cognizance === 'asleep') {
            you.vitals.cognizance = 'awake';
            document.getElementById('sleep').innerHTML = 'Sleep';
            questButton.activate();
            yourDiary.addEntry('You wake up refreshed');
        }
    }
}

Player.prototype.checkBladder = function() {
    var awake = you.vitals.cognizance === 'awake';
    var asleep = you.vitals.cognizance === 'asleep';
    var dead = you.vitals.cognizance === 'dead';
    var drunk = you.vitals.drunk > 4500;
    if (awake && !drunk && you.vitals.bladder > 100) {
        yourDiary.addEntry('You wet your pants.');
        you.vitals.bladder = 0;
    }
    else if (awake && drunk && you.vitals.bladder > 90) {
        yourDiary.addEntry('You drunkenly piss yourself.');
        you.vitals.bladder = 0;
    }
    else if (asleep && !drunk && you.vitals.bladder > 95) {
        yourDiary.addEntry('You wake up wetting the bed.');
        you.vitals.bladder = 0;
        you.wakeUp();
    }
    else if (asleep && drunk && you.vitals.bladder > 85) {
        yourDiary.addEntry('You piss the bed while passed out drunk.');
        you.vitals.bladder = 0;
    }
    else if (dead) {
        yourDiary.addEntry('You void your loins, as the dead are wont to do.');
        you.vitals.bladder = 0;
    }
}

Player.prototype.checkSelf = function(number) {
    if (you.isAlive()) {
        if (you.vitals.cognizance === 'asleep') {
            you.adjHealth(8*number/(SECONDS_IN_DAY));
        }
        else {
            you.adjHealth(4*number/(SECONDS_IN_DAY));
        }
        if (you.vitals.caffeine >= 0.1) {
            you.vitals.caffeine = you.vitals.caffeine * Math.pow(0.5, (number/(5*SECONDS_IN_HOUR)));
        }
        else {
            you.vitals.caffeine = 0;
        }
        if (you.skills.xp > xpIncrement) {
            you.nextLevel();
            xpIncrement *= 2;
        }
        if (you.vitals.drunk <= 1) {
            document.getElementById('job').innerHTML = 'Day Labor';
        }
        if (you.vitals.drunk > 0) {
            you.vitals.drunk -= number;
            if (you.vitals.drunk < 0) you.vitals.drunk = 0;
        }
        you.checkBladder();
    }
}

function Container(contents) {
    this.contents = contents;
}

Container.prototype.deposit = function(item) {
    var key = item.describe();
    var hist = this.contents;
    if (key in hist) hist[key] ++;
    else hist[key] = 1;
    this.contents = hist;
}

Container.prototype.show = function() {
    var hist = this.contents;
    var result = '';
    var key = '';
    document.getElementById('inventory').innerHTML = '';
    for(key in hist) {
        var item_id = key;
        var button_id = item_id;
        var div = document.createElement('div');
        div.id = item_id;
        div.innerHTML = (hist[key]==1?'a':hist[key]) + ' ' + key;
        document.getElementById('inventory').appendChild(div);
        var button_fun = function(key) {yourBag.drop(key);}
        var button = new Button(item_id, button_id, 'drop', true, button_fun, true);
    }
}

Container.prototype.list = function() {
    var result = [];
    this.contents.forEach(function (a) {result.unshift(a.describe())} )
    return result;
}

Container.prototype.drop = function(item_id) {
    var key = item_id.target.id;
    console.log(item_id);
    var hist = this.contents;
    if (key in hist) {
        hist[key]--;
        if (hist[key]===0) delete hist[key];
        yourDiary.addEntry('you drop the ' + key);
    }
    this.contents = hist;
}

function Diary(contents) {
    this.contents = contents;
}

Diary.prototype.addEntry = function(text) {
    this.contents.unshift(text);
}

Diary.prototype.show = function() {
    var result = '';
    this.contents.forEach(function (a) { result += (a + '
'); } )
    return result;
}

function Stat(id, prefix, suffix, valueFunction) {
    this.valueFunction = valueFunction;
    this.id = id;
    this.prefix = prefix;
    this.suffix = suffix;

    var mySpan = document.createElement("span");
    mySpan.id=id;
    mySpan.innerHTML = this.text;

    document.getElementById("top_left2").appendChild(mySpan);
}

Stat.prototype.toString = function() {
    return this.prefix + this.valueFunction() + this.suffix;
}

Stat.prototype.update = function() {
    document.getElementById(this.id).innerHTML = this.toString();
}

function clickQuest() {
    if (you.vitals.cognizance === 'awake') {
        var pay = Math.round(Math.log(you.skills.xp + 1) + 1);
        you.gold += pay;
        you.adjHealth(-10);
        you.addXp(1);
        you.job = false;
        if (you.isAlive()) {
            var treasure = new Weapon();
            yourBag.deposit(treasure);
            yourDiary.addEntry('You complete your quest, finding ' + pay + ' gold nugs and the ' + treasure.describe() + '.');
        }
        tickTock(SECONDS_IN_DAY);
    }
    else if (you.vitals.cognizance === 'asleep') {
        yourDiary.addEntry('You are sleeping.')
    }
    else if (you.vitals.cognizance === 'dead') {
        yourDiary.addEntry('You are too dead to go on a quest.');
    }
}

function clickJob() {
    if (you.vitals.cognizance === 'awake' && you.vitals.drunk < 1) {
            var pay = Math.round(Math.log(you.skills.working + 1) + 1);
            yourDiary.addEntry('You find some work and earn ' + pay + ' gold coins.');
            you.gold += pay;
            you.skills.working += 8;
            tickTock(8 * SECONDS_IN_HOUR);
    }
    else if (you.vitals.cognizance === 'dead') {
      yourDiary.addEntry('You are too dead to go to work.');
    }
    else if (you.vitals.drunk >= 1) {
      yourDiary.addEntry('You are too drunk to work.');
    }
}

function clickDrink() {
    if (you.isAlive()) {
        if (you.gold >= 2) {
            you.gold -= 2;
            you.adjHealth(2);
            you.job = false;
            you.vitals.drunk += 4500;
            you.vitals.bladder += 12;
            yourDiary.addEntry('You buy and drink a beer!');
            document.getElementById('job').innerHTML = 'Drunk';
        }
    }
}

function clickCoffee() {
    if (you.isAlive()) {
        if (you.gold >= 1) {
            you.gold -= 1;
            yourDiary.addEntry('You drink some coffee. You feel pumped up!');
            you.vitals.caffeine += 100;
            you.vitals.bladder += 5;
            you.adjHealth(1);
        }
    }
}

function clickSave() {
    var save = {
        you : you,
        yourDiary : yourDiary,
        timer : timer,
        xpIncrement : xpIncrement,
        yourBag : yourBag
    }
    localStorage.setItem('save',JSON.stringify(save));
    console.log('game saved');
}

function clickLoad() {
    var savegame = JSON.parse(localStorage.getItem('save'));
    if (typeof savegame.you !== 'undefined') you = new Player(savegame.you.vitals, savegame.you.gold, savegame.you.skills);
    if (typeof savegame.yourBag !== 'undefined') {
        yourBag = new Container({});
        //TODO: rewrite using forEach?
        for (var each in savegame.yourBag.contents) {
            var item = savegame.yourBag.contents[each];
            yourBag.deposit(new Weapon(item.condition, item.quality, item.material, item.kind, item.modifier));
        }
    }
    if (typeof savegame.xpIncrement !== 'undefined') xpIncrement = savegame.xpIncrement;
    if (typeof savegame.yourDiary !== 'undefined') yourDiary.contents =  savegame.yourDiary.contents; //new Diary(savegame.yourDiary.contents);
    if (typeof savegame.timer !== 'undefined') timer.ticks = savegame.timer.ticks;
    if (you.vitals.drunk <= 1)
        { document.getElementById('job').innerHTML = 'Day Labor'; }
    else
        { document.getElementById('job').innerHTML = 'Drunk'; }
    if (you.isAlive())
        { document.getElementById('quest').innerHTML = 'Quest'; }
    else
        { document.getElementById('quest').innerHTML = 'Dead'; }
}

function autoSave() {
    //auto-save once a week game-time, until dead
    if (you.isAlive()) {
        clickSave();
        timer.addEvent('Save', SECONDS_IN_DAY * 7, function () { autoSave(); });
    }
}

var you = new Player({healthMax: 60, health: 60, bladder: 0, age: 18, caffeine: 0, drunk: 0, cognizance: 'awake'}, 0, {working: 0, xp: 0});
var xpIncrement = 10;
var yourDiary = new Diary(['You are alive. ']);
var timer = new Timer(0, 666, []);

timer.addEvent('Save', SECONDS_IN_DAY * 7, function () { autoSave(); });
timer.addEvent('Birthday', getRandomInt(0, DAYS_IN_YEAR) * SECONDS_IN_DAY, function() { you.haveABirthday(); });

var buttons = [];
buttons.unshift(new Button('top_middle', 'quest', 'Go on a Quest', true, clickQuest, you.isAwake));
buttons.unshift(new Button('top_middle', 'job', 'Get a Job', true, clickJob, you.isAwake));
buttons.unshift(new Button('top_middle', 'sleep', 'Sleep', true, you.sleep, you.isAlive));
buttons.unshift(new Button('top_middle', 'drink', 'Buy beer', true, clickDrink, you.isAwake));
buttons.unshift(new Button('top_middle', 'coffee', 'Buy coffee', true, clickCoffee, you.isAwake));
buttons.unshift(new Button('top_middle', 'urinate', 'Urinate', true, you.piss, you.isAlive));
var questButton = buttons[0];
var pissButton = buttons[5];

buttons.unshift(new Button('top_left1', 'save', 'Save', true, clickSave, you.isAlive));
buttons.unshift(new Button('top_left1', 'load', 'Load', true, clickLoad, function() {return true; } ));
buttons.unshift(new Button('top_left2', 'speed_slow', 'Slow', true, function () { timer.speed = 1; }, function() {return true; } ));
buttons.unshift(new Button('top_left2', 'speed_medium', 'Medium', true, function () { timer.speed = SECONDS_IN_MINUTE; }, function () {return true;} ));
buttons.unshift(new Button('top_left2', 'speed_fast', 'Fast', true, function () { timer.speed = SECONDS_IN_HOUR; }, function () {return true;} ));

var stats = [];
stats.unshift(new Stat('time', '
Time: ', ' on ', function() {return timer.showTime(); } ));
stats.unshift(new Stat('date', 'Date: ', '
', function() { return timer.showDate(); } ));
stats.unshift(new Stat('bladder', '
Bladder: ', '% full
', function() { return you.vitals.bladder; } ));
stats.unshift(new Stat('health', 'Health: ', '/', function() { return you.vitals.health.toFixed(1); } ));
stats.unshift(new Stat('healthMax', '', '
', function() { return you.vitals.healthMax; } ));
stats.unshift(new Stat('caffeine', 'Caffeine: ', ' mg
', function() { return you.vitals.caffeine.toFixed(1) ; } ));
stats.unshift(new Stat('skillWork', 'Work Skill: ', '
', function () { return you.skills.working.toFixed(1); } ));
stats.unshift(new Stat('gold', 'Gold: ', '
', function () { return you.gold.toFixed(0); } ));
stats.unshift(new Stat('xp', 'XP: ', '
', function() { return you.skills.xp; } ));
stats.unshift(new Stat('age', 'Age: ', '
', function() { return you.vitals.age; }));
stats.unshift(new Stat('weapon', 'Weapon: ', '
', function() { } ));

var yourBag = new Container({});

function tickTock(number) {
    timer.passes(number);
    you.checkSelf(number);

    yourBag.show();
    document.getElementById('diary').innerHTML = yourDiary.show();
    stats.forEach(function (a) {a.update();});
    buttons.forEach(function (a) {if (a.activeCondition()) a.activate(); else a.deactivate();})
}

window.setInterval(function () {
    tickTock(timer.speed);
}, 500);