text:
package net.liftweb
package record
package field
package joda

import scala.xml._

import common._
import http.S
import http.js._
import json._
import util._

import Helpers._
import S._
import JE._

import org.joda.time._

trait JodaTimeTypedField extends TypedField[DateTime] with JodaHelpers {

  def setFromAny(in: Any): Box[DateTime] = toDateTime(in).flatMap(d => setBox(Full(d))) or genericSetFromAny(in)

  def setFromString(s: String): Box[DateTime] = s match {
    case null|"" if optional_? => setBox(Empty)
    case null|"" => setBox(Failure(notOptionalErrorMessage))
    case other => setBox(toDateTime(other))
  }

  private def elem =
    S.fmapFunc(SFuncHolder(this.setFromAny(_))){funcName =>
      <input type={formInputType}
        name={funcName}
        value={valueBox.map(v => dateTimeFormatter.print(v)) openOr ""}
        tabindex={tabIndex.toString}/>
    }

  def toForm: Box[NodeSeq] =
    uniqueFieldId match {
      case Full(id) => Full(elem % ("id" -> id))
      case _        => Full(elem)
    }

  def asJs = valueBox.map(v => Num(v.getMillis)) openOr JsNull

  protected def asJInt(encode: MyType => BigInt): JValue =
    valueBox.map(v => JInt(encode(v))) openOr (JNothing: JValue)

  def asJValue: JValue = asJInt(v => v.getMillis)
  def setFromJValue(jvalue: JValue) = setFromJInt(jvalue) {
    v => toDateTime(v)
  }

  protected def setFromJInt(jvalue: JValue)(decode: BigInt => Box[MyType]): Box[MyType] = jvalue match {
    case JNothing|JNull if optional_? => setBox(Empty)
    case JInt(n)                      => setBox(decode(n))
    case other                        => setBox(FieldHelpers.expectedA("JInt", other))
  }
}

class JodaTimeField[OwnerType <: Record[OwnerType]](@deprecatedName('rec) val owner: OwnerType)
  extends Field[DateTime, OwnerType] with MandatoryTypedField[DateTime] with JodaTimeTypedField {

  def this(@deprecatedName('rec) owner: OwnerType, value: DateTime) = {
    this(owner)
    setBox(Full(value))
  }

  def defaultValue = DateTime.now
}

class OptionalJodaTimeField[OwnerType <: Record[OwnerType]](@deprecatedName('rec) val owner: OwnerType)
  extends Field[DateTime, OwnerType] with OptionalTypedField[DateTime] with JodaTimeTypedField {

  def this(@deprecatedName('rec) owner: OwnerType, value: Box[DateTime]) = {
    this(owner)
    setBox(value)
  }
}


text:
Treeboard
=====

Treeboard is a plugin-based web forum with tree-style threaded discussions. The project was started in December, 2005 and has been actively developed since.

Originally created as a learning exercise and used by a small community, its design was heavily influenced by [Slashdot](http://slashdot.org) and later [reddit](http://reddit.com).

Some basic features include:
* A Javascript [BBCode implementation](http://philip.jurik.org/9)
* File uploads
* Post search
* Post privacy by rank, user list, and password
* Post moving, editing, locking
* Read history
* Post voting (up/down/sidevotes)
* Anti-spam features including user and IP bans
* Polls attached to any post in a thread
* Wiki-style posts with edit history
* Customizable themes and thread layouts

A demo can be seen at [http://philip.jurik.org](http://philip.jurik.org).

**Dependencies**
* PHP5
* MySQL
* mod_rewrite

redpajama_set_name: RedPajamaGithub


text:
layout: post
date: 2016-01-16
title: "Enzoani Hainsworth Sleeveless Sweep/Brush Train Sheath/Column"
category: Enzoani
tags: [Enzoani,Sheath/Column,Sweetheart,Sweep/Brush Train,Sleeveless]
---
### Enzoani Hainsworth
Just **$269.99**
###   Sleeveless Sweep/Brush Train Sheath/Column

BRANDS	Enzoani

Silhouette	Sheath/Column

Neckline	Sweetheart

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/enzoani/5104-enzoani-hainsworth.html](https://www.readybrides.com/en/enzoani/5104-enzoani-hainsworth.html)


text:
package com.spotify.helios.testing;

import java.io.IOException;
import java.net.Socket;

class DefaultProber implements Prober {

  @Override
  public boolean probe(final String host, final int port) {
    try (final Socket ignored = new Socket(host, port)) {
      return true;
    } catch (IOException e) {
      return false;
    }
  }
}


text:
<?php

namespace Impact\SurveyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Survey
 *
 * @ORM\Table(name="surveys")
 * @ORM\Entity
 */
class Survey
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="email_content", type="text")
     */
    private $email_content;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * @ORM\OneToMany(targetEntity="Impact\SurveyBundle\Entity\Question", mappedBy="survey", cascade={"persist"})
     */
    protected $questions;

    public function __construct(){
        $this->questions = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Survey
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set email_content
     *
     * @param string $emailContent
     * @return Survey
     */
    public function setEmailContent($emailContent)
    {
        $this->email_content = $emailContent;

        return $this;
    }

    /**
     * Get email_content
     *
     * @return string
     */
    public function getEmailContent()
    {
        return $this->email_content;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Survey
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}


text:
// Copyright 2016 Twitter. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// 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.

package com.twitter.heron.packing.binpacking;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import com.google.common.base.Optional;

import com.twitter.heron.api.generated.TopologyAPI;
import com.twitter.heron.common.basics.Pair;
import com.twitter.heron.packing.Container;
import com.twitter.heron.packing.PackingUtils;
import com.twitter.heron.packing.RamRequirement;
import com.twitter.heron.spi.common.Config;
import com.twitter.heron.spi.common.Constants;
import com.twitter.heron.spi.common.Context;
import com.twitter.heron.spi.packing.IPacking;
import com.twitter.heron.spi.packing.IRepacking;
import com.twitter.heron.spi.packing.InstanceId;
import com.twitter.heron.spi.packing.PackingPlan;
import com.twitter.heron.spi.packing.Resource;
import com.twitter.heron.spi.utils.TopologyUtils;

import static com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_MAX_CPU_HINT;
import static com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_MAX_DISK_HINT;
import static com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_MAX_RAM_HINT;
import static com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_PADDING_PERCENTAGE;

/**
 * FirstFitDecreasing packing algorithm
 *

 * This IPacking implementation generates a PackingPlan based on the
 * First Fit Decreasing heuristic for the binpacking problem. The algorithm attempts to minimize
 * the amount of resources used.
 *

 * Following semantics are guaranteed:
 * 1. Supports heterogeneous containers. The number of containers used is determined
 * by the algorithm and not by the config file.
 * The user provides a hint for the maximum container size and a padding percentage.
 * The padding percentage whose values range from [0, 100], determines the per container
 * resources allocated for system-related processes (e.g., the stream manager).
 *

 * 2. The user provides a hint for the maximum CPU, RAM and Disk that can be used by each container through
 * the com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_MAX_CPU_HINT,
 * com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_MAX_RAM_HINT,
 * com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_MAX_DISK_HINT parameters.
 * If the parameters are not specified then a default value is used for the maximum container
 * size.
 *

 * 3. The user provides a percentage of each container size that will be used for padding
 * through the com.twitter.heron.api.Config.TOPOLOGY_CONTAINER_PADDING_PERCENTAGE
 * If the parameter is not specified then a default value of 10 is used (10% of the container size)
 *

 * 4. The ram required for one instance is calculated as:
 * value in com.twitter.heron.api.Config.TOPOLOGY_COMPONENT_RAMMAP if exists, otherwise,
 * the default ram value for one instance.
 *

 * 5. The cpu required for one instance is calculated as the default cpu value for one instance.
 *

 * 6. The disk required for one instance is calculated as the default disk value for one instance.
 *

 * 7. The ram required for a container is calculated as:
 * (ram for instances in container) + (paddingPercentage * ram for instances in container)
 *

 * 8. The cpu required for a container is calculated as:
 * (cpu for instances in container) + (paddingPercentage * cpu for instances in container)
 *

 * 9. The disk required for a container is calculated as:
 * (disk for instances in container) + ((paddingPercentage * disk for instances in container)
 *

 * 10. The pack() return null if PackingPlan fails to pass the safe check, for instance,
 * the size of ram for an instance is less than the minimal required value.
 */
public class FirstFitDecreasingPacking implements IPacking, IRepacking {

  private static final long MIN_RAM_PER_INSTANCE = 192L * Constants.MB;
  private static final int DEFAULT_CONTAINER_PADDING_PERCENTAGE = 10;
  private static final int DEFAULT_NUMBER_INSTANCES_PER_CONTAINER = 4;

  private static final Logger LOG = Logger.getLogger(FirstFitDecreasingPacking.class.getName());
  private TopologyAPI.Topology topology;

  private Resource defaultInstanceResources;
  private Resource maxContainerResources;

  private int paddingPercentage;

  @Override
  public void initialize(Config config, TopologyAPI.Topology inputTopology) {
    this.topology = inputTopology;
    setPackingConfigs(config);
  }

  /**
   * Instatiate the packing algorithm parameters related to this topology.
   */
  private void setPackingConfigs(Config config) {
    List<TopologyAPI.Config.KeyValue> topologyConfig = topology.getTopologyConfig().getKvsList();

    this.defaultInstanceResources = new Resource(
        Context.instanceCpu(config),
        Context.instanceRam(config),
        Context.instanceDisk(config));

    this.paddingPercentage = TopologyUtils.getConfigWithDefault(topologyConfig,
        TOPOLOGY_CONTAINER_PADDING_PERCENTAGE, DEFAULT_CONTAINER_PADDING_PERCENTAGE);

    double defaultCpu = this.defaultInstanceResources.getCpu()
        * DEFAULT_NUMBER_INSTANCES_PER_CONTAINER;
    long defaultRam = this.defaultInstanceResources.getRam()
        * DEFAULT_NUMBER_INSTANCES_PER_CONTAINER;
    long defaultDisk = this.defaultInstanceResources.getDisk()
        * DEFAULT_NUMBER_INSTANCES_PER_CONTAINER;

    this.maxContainerResources = new Resource(
        TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_MAX_CPU_HINT,
            (double) Math.round(PackingUtils.increaseBy(defaultCpu, paddingPercentage))),
        TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_MAX_RAM_HINT,
            PackingUtils.increaseBy(defaultRam, paddingPercentage)),
        TopologyUtils.getConfigWithDefault(topologyConfig, TOPOLOGY_CONTAINER_MAX_DISK_HINT,
            PackingUtils.increaseBy(defaultDisk, paddingPercentage)));
  }

  /**
   * Get a packing plan using First Fit Decreasing
   *
   * @return packing plan
   */
  @Override
  public PackingPlan pack() {
    // Get the instances using FFD allocation
    Map<Integer, List<InstanceId>> ffdAllocation = getFFDAllocation();
    // Construct the PackingPlan
    Map<String, Long> ramMap = TopologyUtils.getComponentRamMapConfig(topology);

    Set<PackingPlan.ContainerPlan> containerPlans = PackingUtils.buildContainerPlans(
        ffdAllocation, ramMap, this.defaultInstanceResources, this.paddingPercentage);

    return new PackingPlan(topology.getId(), containerPlans);
  }

  /**
   * Get a new packing plan given an existing packing plan and component-level changes.
   * @return new packing plan
   */
  public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) {
    // Get the instances using FFD allocation
    Map<Integer, List<InstanceId>> ffdAllocation =
        getFFDAllocation(currentPackingPlan, componentChanges);

    // Construct the PackingPlan
    Map<String, Long> ramMap = TopologyUtils.getComponentRamMapConfig(topology);

    Set<PackingPlan.ContainerPlan> containerPlans = PackingUtils.buildContainerPlans(
        ffdAllocation, ramMap, defaultInstanceResources, paddingPercentage);
    return new PackingPlan(topology.getId(), containerPlans);
  }

  @Override
  public void close() {

  }

  /**
   * Sort the components in decreasing order based on their RAM requirements
   *
   * @return The sorted list of components and their RAM requirements
   */
  private ArrayList<RamRequirement> getSortedRAMInstances(Map<String, Integer> parallelismMap) {
    ArrayList<RamRequirement> ramRequirements = new ArrayList<>();
    Map<String, Long> ramMap = TopologyUtils.getComponentRamMapConfig(topology);

    for (String component : parallelismMap.keySet()) {
      if (ramMap.containsKey(component)) {
        if (!PackingUtils.isValidInstance(
            this.defaultInstanceResources.cloneWithRam(ramMap.get(component)),
            MIN_RAM_PER_INSTANCE, maxContainerResources, this.paddingPercentage)) {
          throw new RuntimeException("The topology configuration does not have "
              + "valid resource requirements. Please make sure that the instance resource "
              + "requirements do not exceed the maximum per-container resources.");
        } else {
          ramRequirements.add(new RamRequirement(component, ramMap.get(component)));
        }
      } else {
        if (!PackingUtils.isValidInstance(this.defaultInstanceResources,
            MIN_RAM_PER_INSTANCE, maxContainerResources, this.paddingPercentage)) {
          throw new RuntimeException("The topology configuration does not have "
              + "valid resource requirements. Please make sure that the instance resource "
              + "requirements do not exceed the maximum per-container resources.");
        } else {
          ramRequirements.add(
              new RamRequirement(component, this.defaultInstanceResources.getRam()));
        }
      }
    }
    Collections.sort(ramRequirements, Collections.reverseOrder());

    return ramRequirements;
  }

  /**
   * Get the instances' allocation based on the First Fit Decreasing algorithm
   *
   * @return Map < containerId, list of InstanceId belonging to this container >
   */
  private Map<Integer, List<InstanceId>> getFFDAllocation() {
    Map<String, Integer> parallelismMap = TopologyUtils.getComponentParallelism(topology);
    HashMap<Integer, List<InstanceId>> allocation = new HashMap<>();
    assignInstancesToContainers(new ArrayList<Container>(), allocation, parallelismMap, 1,
        maxContainerResources);
    return allocation;
  }

  /**
   * Get the instances' allocation based on the First Fit Decreasing algorithm
   *
   * @return Map < containerId, list of InstanceId belonging to this container >
   */

  private Map<Integer, List<InstanceId>> getFFDAllocation(PackingPlan currentPackingPlan,
                                                          Map<String, Integer> componentChanges) {
    Map<String, Integer> componentsToScaleDown =
        PackingUtils.getComponentsToScale(componentChanges, PackingUtils.ScalingDirection.DOWN);
    Map<String, Integer> componentsToScaleUp =
        PackingUtils.getComponentsToScale(componentChanges, PackingUtils.ScalingDirection.UP);

    ArrayList<Container> containers = PackingUtils.getContainers(currentPackingPlan,
        this.paddingPercentage);
    Map<Integer, List<InstanceId>> allocation = PackingUtils.getAllocation(currentPackingPlan);

    int maxInstanceIndex = 0;
    for (PackingPlan.ContainerPlan containerPlan : currentPackingPlan.getContainers()) {
      for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
        maxInstanceIndex = Math.max(maxInstanceIndex, instancePlan.getTaskId());
      }
    }
    if (!componentsToScaleDown.isEmpty()) {
      removeInstancesFromContainers(containers, allocation, componentsToScaleDown);
    }
    if (!componentsToScaleUp.isEmpty()) {
      assignInstancesToContainers(containers, allocation, componentsToScaleUp,
          maxInstanceIndex + 1, containers.get(0).getCapacity());
    }
    removeEmptyContainers(allocation);
    return allocation;
  }

  /**
   * Removes containers from tha allocation that do not contain any instances
   */
  private void removeEmptyContainers(Map<Integer, List<InstanceId>> allocation) {
    Iterator<Integer> containerIds = allocation.keySet().iterator();
    while (containerIds.hasNext()) {
      Integer containerId = containerIds.next();
      if (allocation.get(containerId).isEmpty()) {
        containerIds.remove();
      }
    }
  }

  /**
   * Generates the containers that correspond to the current packing plan
   * along with their associated instances.
   *
   * @return List of containers for the current packing plan
   */
  private ArrayList<Container> getContainers(PackingPlan currentPackingPlan) {
    ArrayList<Container> containers = new ArrayList<>();

    //sort containers based on containerIds;
    PackingPlan.ContainerPlan[] currentContainers =
        PackingUtils.sortOnContainerId(currentPackingPlan.getContainers());

    Resource capacity = currentPackingPlan.getMaxContainerResources();
    for (int i = 0; i < currentContainers.length; i++) {
      int containerId = PackingUtils.allocateNewContainer(
          containers, capacity, this.paddingPercentage);
      for (PackingPlan.InstancePlan instancePlan
          : currentContainers[i].getInstances()) {
        containers.get(containerId - 1).add(instancePlan);
      }
    }
    return containers;
  }

  /**
   * Generates an instance allocation for the current packing plan
   *
   * @return Map < containerId, list of InstanceId belonging to this container >
   */
  private Map<Integer, List<InstanceId>> getAllocation(PackingPlan currentPackingPlan) {
    Map<Integer, List<InstanceId>> allocation = new HashMap<Integer, List<InstanceId>>();
    for (PackingPlan.ContainerPlan containerPlan : currentPackingPlan.getContainers()) {
      ArrayList<InstanceId> instances = new ArrayList<InstanceId>();
      for (PackingPlan.InstancePlan instance : containerPlan.getInstances()) {
        instances.add(new InstanceId(instance.getComponentName(), instance.getTaskId(),
            instance.getComponentIndex()));
      }
      allocation.put(containerPlan.getId(), instances);
    }
    PackingUtils.removeEmptyContainers(allocation);
    return allocation;
  }

  /**
   * Assigns instances to containers
   *
   * @param containers helper data structure that describes the containers' status
   * @param allocation existing packing plan
   * @param parallelismMap component parallelism
   * @param firstTaskIndex first taskId to use for the new instances
   */
  private void assignInstancesToContainers(
      ArrayList<Container> containers, Map<Integer, List<InstanceId>> allocation,
      Map<String, Integer> parallelismMap, int firstTaskIndex, Resource containerCapacity) {
    ArrayList<RamRequirement> ramRequirements = getSortedRAMInstances(parallelismMap);
    int globalTaskIndex = firstTaskIndex;
    for (RamRequirement ramRequirement : ramRequirements) {
      String component = ramRequirement.getComponentName();
      int numInstance = parallelismMap.get(component);
      for (int j = 0; j < numInstance; j++) {
        Resource instanceResource =
            this.defaultInstanceResources.cloneWithRam(ramRequirement.getRamRequirement());
        int containerId = placeFFDInstance(containers, new PackingPlan.InstancePlan(new InstanceId(
            component, globalTaskIndex, j), instanceResource), containerCapacity);
        List<InstanceId> instances = allocation.get(containerId);
        if (instances == null) {
          instances = new ArrayList<>();
        }
        instances.add(new InstanceId(component, globalTaskIndex++, j));
        allocation.put(containerId, instances);
      }
    }
  }

  /**
   * Removes instances from containers during scaling down
   *
   * @param containers helper data structure that describes the containers' status
   * @param allocation existing packing plan
   * @param componentsToScaleDown scale down factor for the components.
   */
  private void removeInstancesFromContainers(
      ArrayList<Container> containers, Map<Integer, List<InstanceId>> allocation,
      Map<String, Integer> componentsToScaleDown) {

    ArrayList<RamRequirement> ramRequirements = getSortedRAMInstances(componentsToScaleDown);
    for (RamRequirement ramRequirement : ramRequirements) {
      String component = ramRequirement.getComponentName();
      int numInstancesToRemove = -componentsToScaleDown.get(component);
      for (int j = 0; j < numInstancesToRemove; j++) {
        Pair<Integer, InstanceId> idPair = removeFFDInstance(containers, component);
        List<InstanceId> instances = allocation.get(idPair.first);
        instances.remove(idPair.second);
        allocation.put(idPair.first, instances);
      }
    }
  }

  /**
   * Assign a particular instance to an existing container or to a new container
   *
   * @return the container Id that incorporated the instance
   */
  private int placeFFDInstance(ArrayList<Container> containers,
                               PackingPlan.InstancePlan instancePlan,
                               Resource containerCapacity) {
    boolean placed = false;
    int containerId = 0;
    for (int i = 0; i < containers.size() && !placed; i++) {
      if (containers.get(i).add(instancePlan)) {
        placed = true;
        containerId = i + 1;
      }
    }
    if (!placed) {
      containerId = PackingUtils.allocateNewContainer(containers, containerCapacity,
          this.paddingPercentage);
      containers.get(containerId - 1).add(instancePlan);
    }
    return containerId;
  }

  /**
   * Remove an instance of a particular component from the containers
   *
   * @return the pairId that captures the corresponding container and instance id.
   */
  private Pair<Integer, InstanceId> removeFFDInstance(ArrayList<Container> containers,
                                                      String component)
      throws RuntimeException {
    boolean removed = false;
    int containerId = 0;
    for (int i = 0; i < containers.size() && !removed; i++) {
      Optional<PackingPlan.InstancePlan> instancePlan =
          containers.get(i).removeAnyInstanceOfComponent(component);
      if (instancePlan.isPresent()) {
        removed = true;
        containerId = i + 1;
        PackingPlan.InstancePlan plan = instancePlan.get();
        return new Pair<Integer, InstanceId>(containerId, new InstanceId(plan.getComponentName(),
            plan.getTaskId(), plan.getComponentIndex()));
      }
    }
    throw new RuntimeException("Cannot remove instance."
        + " No more instances of component " + component + " exist"
        + " in the containers.");
  }
}


text:
declare namespace Meteor {
	var isDevelopment : boolean;
}


text:
const startTime = new Date();

// clear terminal
process.stdout.write('\x1Bc');

const chalk = require('chalk');
const config = require('./config/config');
const util = require('./util');

const Koa = require('koa');
const Router = require('koa-router');
const json = require('koa-json');
const logger = require('koa-logger');
const bodyParser = require('koa-bodyparser');
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const send = require('koa-send');
const serve = require('koa-static');
const session = require('koa-session');
const multer = require('koa-multer');
const mount = require('koa-mount');
const upload = multer({
    dest: './public/files/'
});
const history = require('koa-connect-history-api-fallback');

const app = new Koa();

// Error handler
app.use(async (ctx, next) => {
    try {
        await next();
        if (!ctx.status || ctx.status === 404) {
            ctx.throw(404);
        }
    } catch (err) {
        console.log('Server error:', chalk.red(err));
        ctx.status = parseInt(err.status) || 500;
        if (ctx.request.header.accept.indexOf('application/json') === -1) { // browser request
            await send(ctx, './public/404.html');
        } else {
            switch (ctx.status) {
            case 404:
                ctx.body = util.notFound;
                break;
            default:
                ctx.body = util.error;
                break;
            }
        }
    }
});

app.use(history());

// E-Tag
app.use(conditional());
app.use(etag({
    weak: true
}));

// →_→
app.use(async (ctx, next) => {
    ctx.set('X-Powered-By', 'Koa');
    await next();
});

app.use(upload.single('file'));
app.use(bodyParser());
app.use(json());
app.use(logger());
app.keys = [config.server.sessionKey];
app.use(session({
    key: config.server.sessionKey,
    httpOnly: true,
    signed: true,
    maxAge: 86400000,
    overwrite: true
}, app));

// Router
const router = new Router({
    prefix: '/api'
});

const introduction = require('./routes/introduction');
const person = require('./routes/person');
const material = require('./routes/material');
const admin = require('./routes/admin');
const application = require('./routes/application');
const counselingRoom = require('./routes/counselingRoom');
const course = require('./routes/course');
const activity = require('./routes/activity');
const teacher = require('./routes/teacher');
const research = require('./routes/research');
const report = require('./routes/report');
router.use('/introduction', introduction.routes());
router.use('/person', person.routes());
router.use('/material', material.routes());
router.use('/admin', admin.routes());
router.use('/application', application.routes());
router.use('/counselingRoom', counselingRoom.routes());
router.use('/course', course.routes());
router.use('/activity', activity.routes());
router.use('/teacher', teacher.routes());
router.use('/research', research.routes());
router.use('/report', report.routes());
app.use(router.routes());

// Static file
app.use(mount('/api/material/download', serve(__dirname + '/public/files')));
app.use(mount('/', serve(__dirname + '/public')));

// Startup
app.listen('3000', async () => {
    console.log(chalk.green('Koa is listening on 3000...'));
    console.log(chalk.blue('Start time:', startTime.toLocaleString()));
});

module.exports = app;


text:
using System;

namespace CalculationTree
{
    /// <summary>
    /// Класс дерево разбора
    /// </summary>
    public class CalcTree
    {
        /// <summary>
        /// Корень дерева
        /// </summary>
        private AbstractNode root;

        /// <summary>
        /// Считает значение дерева
        /// </summary>
        /// <returns></returns>
        public int Calculate() => root.Calculate();

        /// <summary>
        /// Печатает дерево
        /// </summary>
        public string Print()
        {
            string outString = root.TreeIntoString();
            Console.WriteLine(outString);
            return outString;
        }

        /// <summary>
        /// Генерирует дерево по заданному выражению
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        private AbstractNode GenerateTree(string expression)
        {
            if (expression[0] != '(')
            {
                return new NumberNode(expression);
            }
            char op = expression[1];
            string leftOperand = "";
            string rightOperand = "";
            if (expression[2] != ' ')
            {
                throw new FormatException("Неверный формат");
            }
            if (expression[3] != '(')
            {
                int i = 3;
                while (expression[i] != ' ')
                {
                    leftOperand += expression[i];
                    ++i;
                }
                for (int j = i + 1; j < expression.Length - 1; ++j)
                {
                    rightOperand += expression[j];
                }
            }
            if (expression[3] == '(')
            {
                leftOperand = "(";
                int i = 4;
                int openingBracketsCount = 1;
                int closingBracketsCount = 0;
                while (openingBracketsCount > closingBracketsCount)
                {
                    if (expression[i] == '(')
                    {
                        ++openingBracketsCount;
                    }
                    else if (expression[i] == ')')
                    {
                        ++closingBracketsCount;
                    }
                    leftOperand += expression[i];
                    ++i;
                }
                for (int j = i + 1; j < expression.Length - 1; ++j)
                {
                    rightOperand += expression[j];
                }
            }
            var left = GenerateTree(leftOperand);
            var right = GenerateTree(rightOperand);
            return new OperatorNode(op, left, right);
        }

        /// <summary>
        /// Инициализирует новый экземпляр класса <see cref="CalcTree"/>
        /// </summary>
        /// <param name="expression">Выражение, которое должно удовлетворять следующему формату, соблюдая пробелы: инфиксная форма, например (* (+ 1 1) 2)</param>
        public CalcTree(string expression)
        {
            root = GenerateTree(expression);
        }
    }
}


text:
export type LogLevel = 'debug' | 'error' | 'info' | 'log' | 'trace' | 'warn';

export type LogLevelLabels = { [L in LogLevel]?: string };

export type LogMetadata = Record<string, unknown>;

export interface LogItem {
	/** The name of the host machine. */
	host: string;
	/** The log level as a localized or customized label. */
	label: string;
	/** The log level as a string. */
	level: LogLevel;
	/** The log message with interpolated arguments applied. */
	message: string;
	/** Additional data to include with a log item. */
	metadata: LogMetadata;
	/** Name of the logger. */
	name: string;
	/** Current process ID. */
	pid: number;
	/** Timestamp of the log, native to the host machine. */
	time: Date;
}

export interface LogOptions {
	/** Values to interpolate into the message string. */
	args?: unknown[];
	/** Level to log as. */
	level?: LogLevel;
	/** Message to log to the transports. */
	message: string;
	/** Metadata to include in the message item/string. */
	metadata?: LogMetadata;
}

export interface LoggableWriter {
	/**
	 * Log a message to the console and interpolate with the parameters,
	 * while also providing a metadata object to include with the log item.
	 */
	(metadata: LogMetadata, message: string, ...params: unknown[]): void;
	/** Log a message to the console and interpolate with the parameters. */
	(message: string, ...params: unknown[]): void;
}

export interface Loggable {
	/** Log a message with the `debug` log level. */
	debug: LoggableWriter;
	/** Disable all logger messages from logging to the console. */
	disable: () => void;
	/** Enable all logger messages to log the console. */
	enable: () => void;
	/** Log a message with the `error` log level. */
	error: LoggableWriter;
	/** Log a message with the `log` log level. */
	log: LoggableWriter;
	/** Log a message with the `info` log level. */
	info: LoggableWriter;
	/** Log a message with the `trace` log level. */
	trace: LoggableWriter;
	/** Log a message with the `warn` log level. */
	warn: LoggableWriter;
}

export interface LoggerFunction extends Loggable, LoggableWriter {}

export interface LoggerOptions {
	/** Custom labels to use for each log type. */
	labels?: LogLevelLabels;
	/** Metadata to include within each log item. */
	metadata?: LogMetadata;
	/** Unique name for this logger. */
	name: string;
	/** List of transports to write messages to. */
	transports?: Transportable[];
}

export interface Writable {
	/** Write a message to the configured stream. */
	write: (message: string) => void;
}

export type Formatter = (item: LogItem) => string;

export interface Transportable {
	levels: LogLevel[];
	format: Formatter;
	/** Write a message and log item to the transport. */
	write: (message: string, item: LogItem) => Promise<void> | void;
}

export interface TransportOptions {
	/** End of line character to append to a message. Defaults to `os.EOL`. */
	eol?: string;
	/** Function to format a log item into a message string. Default is transport dependent. */
	format?: Formatter;
	/** List of log levels to only write messages for. */
	levels: LogLevel[];
}

export type Rotation = 'daily' | 'hourly' | 'monthly' | 'weekly';


text:
require 'rails_helper'

module ApplicationForms
  RSpec.describe Form, type: :model do
    pending "add some examples to (or delete) #{__FILE__}"
  end
end


text:
'use strict'
//__________Import Modules
const express       =  require( 'express' )
const router        =  express.Router(  )
const bodyParser    =  require( 'body-parser' )
const Sequelize     =  require( 'Sequelize' )
const ReadandParser =  require (__dirname+'/../../Modules/JsonReadandParser')
const multer        =  require('multer')
const path          =  require('path')
const storage       =  multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, './public/images/')
	},
	filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)) //Appending extension
}
})
const db         =  new Sequelize('drunkkitty', process.env.POSTGRES_USER, process.env.POSTGRES_PASSWORD,{
	host: 'localhost',
	dialect: 'postgres'
});

//Middleware
router.use(bodyParser.json())
router.use(bodyParser.urlencoded({     // to support URL-encoded bodies
	extended: true
}));
//Define models
let Card = db.define('card', {
	name: {type: Sequelize.STRING},
	rule: {type: Sequelize.STRING},
	type: {type: Sequelize.STRING},
	origin: {type: Sequelize.STRING},
}, {
	timestamps: false
})

let User = db.define('user', {
	name: {type: Sequelize.STRING, unique: true},
});

let Email = db.define('email', {
	email: {type: Sequelize.STRING, unique: true},
});

// Sync and put info in card DB
db.sync( {'force': false} ).then(()=>{
	ReadandParser (__dirname+'/../Cards.json', function(jsonContent) {
		console.log(jsonContent)
		Card.bulkCreate(jsonContent)
		.catch(function(err) {
			console.log('Error ' + err);
		})
		.finally(function(err) {
			console.log('FINISHED')
		});
	})
})

//Set Routes
router.get('/', (req, res) => {
	res.render('customgame')
})

router.get('/SwitchCard', (req, res) => {
	Card.find({
		order: [
		Sequelize.fn( 'RANDOM' ),
		]
	}).then( (data)=>{
		console.log(data)
		res.send(data)
	})
})

//Save emails
router.post('/email', (req, res) => {
	Email.create({
		email: req.body.email
	}).then( (data)=>{
		console.log(data)
		res.status(204).end()
	})
})

//Upload Card
router.post('/upload', multer({ storage: storage}).single('upl'), function(req,res)
	{ console.log(req.body)
		console.log(req.file.filename)
		Card.create({
			name: req.file.filename,
			rule: req.body.Rule,
			type: req.body.Type,
			origin: "notoriginal",
		})
		res.status(204).end(); })

  ////////////////////
 ////// EXPORT //////
////////////////////

module.exports = router


text:
package printer

import (
	"bytes"
)

// 树节点打印接口
type TreeNodePrinter interface {
	// 显示文本
	String() string
	// 子节点
	Children() []interface{}
}

func PrintTree(n TreeNodePrinter) []string {
	return printTree(n, -1)
}

func TreeString(n TreeNodePrinter, lineBreak string) string {
	return TreeStringDepth(n, lineBreak, -1)
}

func PrintTreeDepth(n TreeNodePrinter, depth int) []string {
	return printTree(n, depth)
}

func TreeStringDepth(n TreeNodePrinter, lineBreak string, depth int) string {
	treeSlice := printTree(n, depth)
	var s bytes.Buffer
	for _, v := range treeSlice {
		s.WriteString(v)
		s.WriteString(lineBreak)
	}
	return s.String()
}

func printTree(n TreeNodePrinter, depth int) []string {
	dataThisNode := n.String()
	var treeSlice []string
	treeSlice = append(treeSlice, dataThisNode)
	if depth != -1 {
		depth--
		if depth <= 0 {
			return treeSlice
		}
	}

	children := n.Children()
	for i, c := range children {
		var child TreeNodePrinter
		var ok bool
		if child, ok = c.(TreeNodePrinter); !ok {
			continue
		}
		childSlice := printTree(child, depth)

		// 是否还有兄弟结点
		hasNextChild := false
		if i < len(children)-1 {
			hasNextChild = true
		}

		prefix := "|-- "
		// 先输出孩子结点的数据
		if hasNextChild {
			treeSlice = append(treeSlice, prefix+childSlice[0])
		} else {
			treeSlice = append(treeSlice, "`-- "+childSlice[0])
		}

		// 如果孩子结点还有孩子结点
		if len(childSlice) > 1 {
			// 修正前缀
			if hasNextChild {
				prefix = "|   "
			} else {
				prefix = "    "
			}
			// 输出孩子的孩子结点
			for i := 1; i < len(childSlice); i++ {
				treeSlice = append(treeSlice, prefix+childSlice[i])
			}
		}
	}

	return treeSlice
}


text:
import {deleteFile} from '../../utils/fs';
import {ng} from '../../utils/process';

export default function() {
  return ng('version')
    .then(() => deleteFile('.angular-cli.json'))
    // doesn't fail on a project with missing .angular-cli.json
    .then(() => ng('version'))
    // Doesn't fail outside a project.
    .then(() => process.chdir('/'))
    .then(() => ng('version'));
}


text:
using content::BrowserThread;
using std::vector;
using content::PasswordForm;

namespace {

// PasswordStoreConsumer callback requires vector const reference.
void RunConsumerCallbackIfNotCanceled(
    const CancelableTaskTracker::IsCanceledCallback& is_canceled_cb,
    PasswordStoreConsumer* consumer,
    const vector<PasswordForm*>* matched_forms) {
  if (is_canceled_cb.Run()) {
    STLDeleteContainerPointers(matched_forms->begin(), matched_forms->end());
    return;
  }

  // OnGetPasswordStoreResults owns PasswordForms in the vector.
  consumer->OnGetPasswordStoreResults(*matched_forms);
}

void PostConsumerCallback(
    base::TaskRunner* task_runner,
    const CancelableTaskTracker::IsCanceledCallback& is_canceled_cb,
    PasswordStoreConsumer* consumer,
    const base::Time& ignore_logins_cutoff,
    const vector<PasswordForm*>& matched_forms) {
  vector<PasswordForm*>* matched_forms_copy = new vector<PasswordForm*>();
  if (ignore_logins_cutoff.is_null()) {
    *matched_forms_copy = matched_forms;
  } else {
    // Apply |ignore_logins_cutoff| and delete old ones.
    for (size_t i = 0; i < matched_forms.size(); i++) {
      if (matched_forms[i]->date_created < ignore_logins_cutoff)
        delete matched_forms[i];
      else
        matched_forms_copy->push_back(matched_forms[i]);
    }
  }

  task_runner->PostTask(
      FROM_HERE,
      base::Bind(&RunConsumerCallbackIfNotCanceled,
                 is_canceled_cb, consumer, base::Owned(matched_forms_copy)));
}

}  // namespace

PasswordStore::GetLoginsRequest::GetLoginsRequest(
    const GetLoginsCallback& callback)
    : CancelableRequest1<GetLoginsCallback, vector<PasswordForm*> >(callback) {
}

void PasswordStore::GetLoginsRequest::ApplyIgnoreLoginsCutoff() {
  if (!ignore_logins_cutoff_.is_null()) {
    // Count down rather than up since we may be deleting elements.
    // Note that in principle it could be more efficient to copy the whole array
    // since that's worst-case linear time, but we expect that elements will be
    // deleted rarely and lists will be small, so this avoids the copies.
    for (size_t i = value.size(); i > 0; --i) {
      if (value[i - 1]->date_created < ignore_logins_cutoff_) {
        delete value[i - 1];
        value.erase(value.begin() + (i - 1));
      }
    }
  }
}

PasswordStore::GetLoginsRequest::~GetLoginsRequest() {
  if (canceled()) {
    STLDeleteElements(&value);
  }
}

PasswordStore::PasswordStore() {
}

bool PasswordStore::Init() {
  ReportMetrics();
  return true;
}

void PasswordStore::AddLogin(const PasswordForm& form) {
  ScheduleTask(base::Bind(&PasswordStore::WrapModificationTask, this,
      base::Closure(base::Bind(&PasswordStore::AddLoginImpl, this, form))));
}

void PasswordStore::UpdateLogin(const PasswordForm& form) {
  ScheduleTask(base::Bind(&PasswordStore::WrapModificationTask, this,
      base::Closure(base::Bind(&PasswordStore::UpdateLoginImpl, this, form))));
}

void PasswordStore::RemoveLogin(const PasswordForm& form) {
  ScheduleTask(base::Bind(&PasswordStore::WrapModificationTask, this,
      base::Closure(base::Bind(&PasswordStore::RemoveLoginImpl, this, form))));
}

void PasswordStore::RemoveLoginsCreatedBetween(const base::Time& delete_begin,
                                               const base::Time& delete_end) {
  ScheduleTask(base::Bind(&PasswordStore::WrapModificationTask, this,
      base::Closure(
          base::Bind(&PasswordStore::RemoveLoginsCreatedBetweenImpl, this,
                     delete_begin, delete_end))));
}

CancelableTaskTracker::TaskId PasswordStore::GetLogins(
    const PasswordForm& form,
    PasswordStoreConsumer* consumer) {
  // Per http://crbug.com/121738, we deliberately ignore saved logins for
  // http*://www.google.com/ that were stored prior to 2012. (Google now uses
  // https://accounts.google.com/ for all login forms, so these should be
  // unused.) We don't delete them just yet, and they'll still be visible in the
  // password manager, but we won't use them to autofill any forms. This is a
  // security feature to help minimize damage that can be done by XSS attacks.
  // TODO(mdm): actually delete them at some point, say M24 or so.
  base::Time ignore_logins_cutoff;  // the null time
  if (form.scheme == PasswordForm::SCHEME_HTML &&
      (form.signon_realm == "http://www.google.com" ||
       form.signon_realm == "http://www.google.com/" ||
       form.signon_realm == "https://www.google.com" ||
       form.signon_realm == "https://www.google.com/")) {
    static const base::Time::Exploded exploded_cutoff =
        { 2012, 1, 0, 1, 0, 0, 0, 0 };  // 00:00 Jan 1 2012
    ignore_logins_cutoff = base::Time::FromUTCExploded(exploded_cutoff);
  }

  CancelableTaskTracker::IsCanceledCallback is_canceled_cb;
  CancelableTaskTracker::TaskId id =
      consumer->cancelable_task_tracker()->NewTrackedTaskId(&is_canceled_cb);

  ConsumerCallbackRunner callback_runner =
      base::Bind(&PostConsumerCallback,
                 base::MessageLoopProxy::current(),
                 is_canceled_cb,
                 consumer,
                 ignore_logins_cutoff);
  ScheduleTask(
      base::Bind(&PasswordStore::GetLoginsImpl, this, form, callback_runner));
  return id;
}

CancelableRequestProvider::Handle PasswordStore::GetAutofillableLogins(
    PasswordStoreConsumer* consumer) {
  return Schedule(&PasswordStore::GetAutofillableLoginsImpl, consumer);
}

CancelableRequestProvider::Handle PasswordStore::GetBlacklistLogins(
    PasswordStoreConsumer* consumer) {
  return Schedule(&PasswordStore::GetBlacklistLoginsImpl, consumer);
}

void PasswordStore::ReportMetrics() {
  ScheduleTask(base::Bind(&PasswordStore::ReportMetricsImpl, this));
}

void PasswordStore::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void PasswordStore::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

PasswordStore::~PasswordStore() {}

PasswordStore::GetLoginsRequest* PasswordStore::NewGetLoginsRequest(
    const GetLoginsCallback& callback) {
  return new GetLoginsRequest(callback);
}

bool PasswordStore::ScheduleTask(const base::Closure& task) {
  return BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, task);
}

void PasswordStore::ForwardLoginsResult(GetLoginsRequest* request) {
  request->ApplyIgnoreLoginsCutoff();
  request->ForwardResult(request->handle(), request->value);
}

template<typename BackendFunc>
CancelableRequestProvider::Handle PasswordStore::Schedule(
    BackendFunc func,
    PasswordStoreConsumer* consumer) {
  scoped_refptr<GetLoginsRequest> request(
      NewGetLoginsRequest(
          base::Bind(&PasswordStoreConsumer::OnPasswordStoreRequestDone,
                     base::Unretained(consumer))));
  AddRequest(request, consumer->cancelable_consumer());
  ScheduleTask(base::Bind(func, this, request));
  return request->handle();
}

template<typename BackendFunc>
CancelableRequestProvider::Handle PasswordStore::Schedule(
    BackendFunc func,
    PasswordStoreConsumer* consumer,
    const PasswordForm& form,
    const base::Time& ignore_logins_cutoff) {
  scoped_refptr<GetLoginsRequest> request(
      NewGetLoginsRequest(
          base::Bind(&PasswordStoreConsumer::OnPasswordStoreRequestDone,
                     base::Unretained(consumer))));
  request->set_ignore_logins_cutoff(ignore_logins_cutoff);
  AddRequest(request, consumer->cancelable_consumer());
  ScheduleTask(base::Bind(func, this, request, form));
  return request->handle();
}

void PasswordStore::WrapModificationTask(base::Closure task) {
#if !defined(OS_MACOSX)
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
#endif  // !defined(OS_MACOSX)
  task.Run();
  PostNotifyLoginsChanged();
}

void PasswordStore::PostNotifyLoginsChanged() {
#if !defined(OS_MACOSX)
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
#endif  // !defined(OS_MACOSX)
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&PasswordStore::NotifyLoginsChanged, this));
}

void PasswordStore::NotifyLoginsChanged() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  FOR_EACH_OBSERVER(Observer, observers_, OnLoginsChanged());
}


text:
namespace content {

ResourceMessageFilter::ResourceMessageFilter(
    int child_id,
    ProcessType process_type,
    ResourceContext* resource_context,
    URLRequestContextSelector* url_request_context_selector)
    : child_id_(child_id),
      process_type_(process_type),
      resource_context_(resource_context),
      url_request_context_selector_(url_request_context_selector) {
  DCHECK(resource_context);
  DCHECK(url_request_context_selector);
}

ResourceMessageFilter::~ResourceMessageFilter() {
}

void ResourceMessageFilter::OnChannelClosing() {
  BrowserMessageFilter::OnChannelClosing();

  // Unhook us from all pending network requests so they don't get sent to a
  // deleted object.
  ResourceDispatcherHostImpl::Get()->CancelRequestsForProcess(child_id_);
}

bool ResourceMessageFilter::OnMessageReceived(const IPC::Message& message,
                                              bool* message_was_ok) {
  return ResourceDispatcherHostImpl::Get()->OnMessageReceived(
      message, this, message_was_ok);
}

net::URLRequestContext* ResourceMessageFilter::GetURLRequestContext(
    ResourceType::Type type) {
  return url_request_context_selector_->GetRequestContext(type);
}

}  // namespace content


text:
static CGFloat const kScrollLineW = 20.0;
static CGFloat const kScrollLineH = 2.0;
static int const kLabelTag = 2000;
static NSTimeInterval const kDurationTime = 0.15;

#define kNormalColor @{@"red":@255, @"green":@255, @"blue":@255}
#define kSelectedColor @{@"red":@42, @"green":@190, @"blue":@43}

@interface YDQMainPageTitleView ()

/// titles数组
@property(nonatomic, strong) NSArray *titles;

/// scrollView
@property(nonatomic, strong) UIScrollView *scrollView;

/// titleLable数组
@property(nonatomic, strong) NSMutableArray *titleLabels;

/// scrollLine
@property(nonatomic, strong) UIView *scrollLine;

/// 保存当前点击label的索引
@property(nonatomic, assign) int currentIndex;

@end

@implementation YDQMainPageTitleView

- (instancetype)initWithFrame:(CGRect)frame titles:(NSArray <NSString *> *)titles
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _titles = titles;

        [self setupUI];
    }

    return self;
}

#pragma mark - UI

- (void)setupUI
{
    [self addSubview:self.scrollView];
    self.scrollView.frame = self.bounds;

    [self setupTitleLabels];

    [self setupScrollLine];
}

// 设置lables
- (void)setupTitleLabels
{
    CGFloat labelW = self.clj_width / self.titles.count;
    CGFloat labelH = self.clj_height;

    for (int i = 0; i < self.titles.count; i++)
    {
        UILabel *label = [[UILabel alloc] init];
        NSString *text = self.titles[i];
        label.text = text;
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = UIColorRGB([kNormalColor[@"red"] intValue], [kNormalColor[@"green"] intValue], [kNormalColor[@"blue"] intValue]);
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = kLabelTag + i;

        CGFloat labelX = i * labelW;
        label.frame = CGRectMake(labelX, 0, labelW, labelH);

        self.userInteractionEnabled = YES;
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lableTapClick:)];
        [label addGestureRecognizer:tapGes];

        [self.scrollView addSubview:label];
        [self.titleLabels addObject:label];
    }
}

// 设置滑块
- (void)setupScrollLine
{
    UILabel *fristLable = [self.titleLabels firstObject];
    fristLable.textColor = UIColorRGB([kSelectedColor[@"red"] intValue], [kSelectedColor[@"green"] intValue], [kSelectedColor[@"blue"] intValue]);
    CGFloat scrollLineX = fristLable.clj_x + (fristLable.clj_width - kScrollLineW) / 2;
    self.scrollLine = [[UIView alloc] initWithFrame:CGRectMake(scrollLineX, fristLable.clj_height - kScrollLineH, kScrollLineW, kScrollLineH)];
    self.scrollLine.backgroundColor = [UIColor orangeColor];

    [self.scrollView addSubview:self.scrollLine];
}

#pragma mark - publicMethod

- (void)resetTitleViewWithSourceIndex:(int)sourceIndex targetIndex:(int)targetIndex progress:(CGFloat)progress
{
    // 1. 取出label
    UILabel *sourceLabel = self.titleLabels[sourceIndex];
    UILabel *targetLabel = self.titleLabels[targetIndex];

    // 2. 滑块滑动逻辑
    CGFloat moveTotalX = targetLabel.center.x - sourceLabel.center.x;
    CGFloat moveX = moveTotalX * progress;

    CGPoint tempPoint = self.scrollLine.center;
    tempPoint.x = sourceLabel.center.x + moveX;
    self.scrollLine.center = tempPoint;

    // 3. 颜色渐变
    // 颜色变化范围
    CGFloat redDelta = ([kNormalColor[@"red"] intValue] - [kSelectedColor[@"red"] intValue]) * progress;
    CGFloat greenDelta = ([kNormalColor[@"green"] intValue] - [kSelectedColor[@"green"] intValue]) * progress;
    CGFloat blueDelta = ([kNormalColor[@"blue"] intValue] - [kSelectedColor[@"blue"] intValue]) * progress;

    // 注意:sourceLabel 和 targetLabel的颜色设置不能调换顺序
    sourceLabel.textColor = UIColorRGB([kSelectedColor[@"red"] intValue] + redDelta, [kSelectedColor[@"green"] intValue] + greenDelta, [kSelectedColor[@"blue"] intValue] + blueDelta);
    targetLabel.textColor = UIColorRGB([kNormalColor[@"red"] intValue] - redDelta, [kNormalColor[@"green"] intValue] - greenDelta, [kNormalColor[@"blue"] intValue] - blueDelta);

    // 4.更新当前索引
    self.currentIndex = targetIndex;
}

#pragma mark - eventResponse

- (void)lableTapClick:(UITapGestureRecognizer *)gesture
{
    UILabel *currentlabel = (UILabel *)gesture.view;
    currentlabel.textColor = UIColorRGB([kSelectedColor[@"red"] intValue], [kSelectedColor[@"green"] intValue], [kSelectedColor[@"blue"] intValue]);
    [UIView animateWithDuration:kDurationTime animations:^{
        self.scrollLine.clj_x = currentlabel.center.x - kScrollLineW / 2;
    }];

    // 获取之前的label
    UILabel *oldLabel = self.titleLabels[self.currentIndex];
    oldLabel.textColor = UIColorRGB([kNormalColor[@"red"] intValue], [kNormalColor[@"green"] intValue], [kNormalColor[@"blue"] intValue]);

    // 保存最新的索引值
    self.currentIndex = (int)(currentlabel.tag - kLabelTag);

    // 将选中的索引传递出去
    if ([self.delegate respondsToSelector:@selector(pageTitleView:selectedIndex:)])
    {
        [self.delegate pageTitleView:self selectedIndex:self.currentIndex];
    }
}

#pragma mark - setter

- (UIScrollView *)scrollView
{
    if (!_scrollView)
    {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        _scrollView.scrollsToTop = NO;
    }

    return _scrollView;
}

- (NSMutableArray *)titleLabels
{
    if (!_titleLabels)
    {
        _titleLabels = [NSMutableArray arrayWithCapacity:4];
    }

    return _titleLabels;
}

@end


text:
<?php

namespace common\modules\message\models;

use common\modules\user\behaviors\UserBehavior;
use Yii;

/**
 * This is the model class for table "{{%message}}".
 *
 * @property integer $id
 * @property integer $from_uid
 * @property integer $to_uid
 * @property integer $message_id
 * @property integer $read
 */
class Message extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%message}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['from_uid', 'to_uid', 'message_id'], 'required'],
            [['from_uid', 'to_uid', 'message_id', 'read'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'from_uid' => Yii::t('app', 'From Uid'),
            'to_uid' => Yii::t('app', 'To Uid'),
            'message_id' => Yii::t('app', 'Message ID'),
            'read' => Yii::t('app', 'Read'),
        ];
    }

    public function behaviors()
    {
        return [
            UserBehavior::className()
        ];
    }

    public function getData()
    {
        return $this->hasOne(MessageData::className(), ['id' => 'message_id']);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            Yii::$app->notify->category('message')
                ->from($this->from_uid)
                ->to($this->to_uid)
                ->extra(['message' => $this->data->content])
                ->link(['/message/default/index'])
                ->send();
        }
    }
}


text:
package edu.byu.suite.features.galleries.model;

import android.os.Parcel;

import edu.byu.support.ByuParcelable;

/**
 * Created by poolguy on 11/30/16
 */
public class GalleryImage extends ByuParcelable {
	private String src;
	private String alt;

	private GalleryImage(Parcel in) {
		src = in.readString();
		alt = in.readString();
	}

	public static final Creator<GalleryImage> CREATOR = new Creator<GalleryImage>() {
		@Override
		public GalleryImage createFromParcel(Parcel in) {
			return new GalleryImage(in);
		}

		@Override
		public GalleryImage[] newArray(int size) {
			return new GalleryImage[size];
		}
	};

	public String getSrc() {
		return src;
	}

	public String getAlt() {
		return alt;
	}

	@Override
	public void writeToParcel(Parcel parcel, int i) {
		parcel.writeString(this.src);
		parcel.writeString(this.alt);
	}
}


text:
import Ember from "ember";
import { test } from 'qunit';
import moduleForAcceptance from 'ember-twiddle/tests/helpers/module-for-acceptance';

const { Test } = Ember;

moduleForAcceptance('Acceptance | routing', {
  beforeEach: function() {
    this.registerWaiter = () => {
      window.messagesWaiting = 1;
      this._waiter = () => {
        return window.messagesWaiting === 0;
      };
      Test.registerWaiter(this._waiter);
    };
  },

  afterEach: function() {
    window.messagesWaiting = 0;
    if (this._waiter) {
      Test.unregisterWaiter(this._waiter);
      this._waiter = null;
    }
  }
});

const aboutLink = '.test-about-link';
const indexLink = '.test-index-link';
const addressBar = '.url-bar input';
const outletText = 'p';

const TWIDDLE_WITH_ROUTES = [
  {
    filename: "about.template.hbs",
    content: "
About Page
"
  },
  {
    filename: "index.template.hbs",
    content: "
Main Page
"
  },
  {
    filename: "application.template.hbs",
    content: `{{#link-to "index" class="test-index-link"}}Index{{/link-to}}
              {{#link-to "about" class="test-about-link"}}About{{/link-to}}

              {{outlet}}`
  },
  {
    filename: "router.js",
    content: `import Ember from 'ember';
              import config from './config/environment';

              var Router = Ember.Router.extend({
                location: config.locationType
              });

              Router.map(function() {
                this.route("about");
              });

              export default Router;`
  },
  {
    filename: "twiddle.json",
    content: `{
                "version": "0.4.0",
                "dependencies": {
                  "jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
                  "ember": "https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.13.10/ember.debug.js",
                  "ember-data": "https://cdnjs.cloudflare.com/ajax/libs/ember-data.js/1.13.13/ember-data.js",
                  "ember-template-compiler": "https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.13.10/ember-template-compiler.js"
                }
              }`
  }
];

test('Able to do routing in a gist', function(assert) {
  let iframe_window;

  runGist(TWIDDLE_WITH_ROUTES);

  andThen(() => {
    if (!find(addressBar).val()) {
      this.registerWaiter();
    }
  });

  andThen(() => {
    assert.equal(find(addressBar).val(), '/', "Correct URL is shown in address bar 0");
    assert.ok(decodeURIComponent(window.location.search).indexOf("route=") === -1, "URL is not added to route query string parameter 0");

    this.registerWaiter();
    iframe_window = outputPane();
    iframe_window.click(iframe_window.find(aboutLink));
  });

  andThen(() => {
    assert.equal(outputContents(outletText), 'About Page', 'About Link leads to About Page being displayed');
    assert.equal(find(addressBar).val(), '/about', "Correct URL is shown in address bar 1");
    assert.ok(decodeURIComponent(window.location.search).indexOf("route=/about") > 0, "URL is added to route query string parameter 1");

    this.registerWaiter();
    iframe_window.click(iframe_window.find(indexLink));
  });

  andThen(() => {
    assert.equal(outputContents(outletText), 'Main Page', 'Index Link leads to Main Page being displayed');
    assert.equal(find(addressBar).val(), '/', "Correct URL is shown in address bar 2");
    assert.ok(decodeURIComponent(window.location.search).indexOf("route=") === -1, "URL is not added to route query string parameter 2");
  });
});

test('URL can be changed via the address bar', function(assert) {
  runGist(TWIDDLE_WITH_ROUTES);

  andThen(() => {
    if (!find(addressBar).val()) {
      this.registerWaiter();
    }
  });

  andThen(function() {
    assert.equal(find(addressBar).val(), '/', "Correct URL is shown in address bar 0");

    click(addressBar);
    fillIn(addressBar, '/about');
    keyEvent(addressBar, 'keyup', 13);
  });

  andThen(function() {
    assert.equal(outputContents(outletText), 'About Page', 'Changing the URL to /about and pressing enter leads to the About Page being displayed');
    assert.equal(find(addressBar).val(), '/about', "Correct URL is shown in address bar 1");

    click(addressBar);
    fillIn(addressBar, '/');
    keyEvent(addressBar, 'keyup', 13);
  });

  andThen(function() {
    assert.equal(outputContents(outletText), 'Main Page', 'Changing the URL to / and pressing enter leads to the Main Page being displayed');
    assert.equal(find(addressBar).val(), '/', "Correct URL is shown in address bar 2");
  });
});

test('URL can be set via route query parameter', function(assert) {
  runGist({
    files: TWIDDLE_WITH_ROUTES,
    initialRoute: "/about"
  });

  andThen(() => {
    if (!find(addressBar).val()) {
      this.registerWaiter();
    }
  });

  andThen(function() {
    assert.equal(find(addressBar).val(), "/about", "Correct URL appears when set via query parameter");
    assert.equal(outputContents(outletText), 'About Page', 'Initializing the URL to /about leads to the About Page being displayed');
  });
});


text:
SERV_IP=$(ip -4 -o addr show scope global  | awk '{print $4}' | sed -e 's:/.*::' | head -n1)
SERVER_CONF="/etc/openvpn/openvpn.conf"
TEST1_OVPN="/etc/openvpn/test1.ovpn"

# Function to fail
abort() { cat <<< "$@" 1>&2; exit 1; }

# Check a config (haystack) for a given line (needle) exit with error if not
# found.
test_config() {

    local needle="${2}"
    local file="${1}"

    busybox grep -q "${needle}" "${file}"
    if [ $? -ne 0 ]; then
        abort "==> Config match not found: ${needle}"
    fi
}

# Check a config (haystack) for absence of given line (needle) exit with error
# if found.
test_not_config() {

    local needle="${2}"
    local file="${1}"

    busybox grep -vq "${needle}" "${file}"
    if [ $? -ne 0 ]; then
        abort "==> Config match found: ${needle}"
    fi
}

#
# Generate openvpn.config file
#

ovpn_genconfig \
    -u udp://$SERV_IP \
    -m 1337 \

EASYRSA_BATCH=1 EASYRSA_REQ_CN="Travis-CI Test CA" ovpn_initpki nopass

easyrsa build-client-full test1 nopass 2>/dev/null

ovpn_getclient test1 > "${TEST1_OVPN}"

#
# Simple test cases
#

# 1. client MTU
test_config "${TEST1_OVPN}" "^tun-mtu\s\+1337"

#
# Test udp client with tcp fallback
#
ovpn_genconfig -u udp://$SERV_IP -E "remote $SERV_IP 443 tcp" -E "remote vpn.example.com 443 tcp"
# nopass is insecure
EASYRSA_BATCH=1 EASYRSA_REQ_CN="Travis-CI Test CA" ovpn_initpki nopass
easyrsa build-client-full client-fallback nopass
ovpn_getclient client-fallback > "${TEST1_OVPN}"

test_config "${TEST1_OVPN}" "^remote\s\+$SERV_IP\s\+443\s\+tcp"
test_config "${TEST1_OVPN}" "^remote\s\+vpn.example.com\s\+443\s\+tcp"

#
# Test non-defroute config
#
ovpn_genconfig -d -u udp://$SERV_IP -r "172.33.33.0/24" -r "172.34.34.0/24"
# nopass is insecure
EASYRSA_BATCH=1 EASYRSA_REQ_CN="Travis-CI Test CA" ovpn_initpki nopass
easyrsa build-client-full non-defroute nopass
ovpn_getclient non-defroute > "${TEST1_OVPN}"

# The '!' inverts the match to test that the string isn't present
test_not_config "${TEST1_OVPN}" "^redirect-gateway\s\+def1"


text:
package com.github.mati1979.play.soyplugin.ajax.process;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
 * Created with IntelliJ IDEA.
 * User: mati
 * Date: 06/10/2013
 * Time: 15:55
 *
 * An interface that defines a generic processing of compiled JavaScript output, e.g.
 * to perform JavaScript obfuscation.
 */
public interface OutputProcessor {

    void process(Reader reader, Writer writer) throws IOException;

}


text:
using System;
using System.Collections.Generic;

namespace Dire
{
    public class SearchPage
    {
        public string Query { get; set; }
        public ResultInfo ResultInfo { get; set; }
        public IEnumerable<SearchHit> SearchHits { get; set; }
    }
}


text:
package pl.kjaklik.maven.jstprecompile.compiler;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

/**
 * @author Krzysiek Jaklik
 *         created: 18.10.12 10:31
 */
public class HoganTemplateCompilerImpl extends AbstractTemplateCompiler implements TemplateCompiler {

    @Override
    public boolean isSupportDevMode() {
        return true;
    }

    @Override
    public void prepare() {
        super.prepare();

        loadClasspathScript("pl/kjaklik/maven/jstprecompile/scripts/engine/hogan.js");
        loadClasspathScript("pl/kjaklik/maven/jstprecompile/scripts/toolkit/hogan-toolkit.js");
    }

    @Override
    public void devCompileGroup(Iterable<File> templates, File output) {
        Writer writer = null;

        try {
            writer = prepareOutputWriter(output);
            IOUtils.write(generateNamespaceInitialisation(), writer);

            devCompileGroup(templates, writer);
        } catch(IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(writer != null) {
                IOUtils.closeQuietly(writer);
            }
        }
    }

    @Override
    public void devCompileGroup(Iterable<File> templates, Writer writer) throws IOException {
        for(File templateFile : templates) {
            devPrecompileFile(templateFile, writer);
            IOUtils.write("\n", writer);
        }
    }

    @Override
    protected void precompileFile(File file, Writer writer) throws IOException {
        loadTemplateFile(file);

        Object result = evaluate(String.format("jstprecompileHoganToolkit.generate('%s', '%s', %s)",
                                               getNamespace(), getClassName(), getOptions()));

        IOUtils.write(result.toString(), writer);
    }

    private void devPrecompileFile(File templateFile, Writer writer) throws IOException {
        String filepath = FilenameUtils.separatorsToUnix(StringUtils.removeStart(templateFile.getAbsolutePath(), getDevModeBaseDir().getAbsolutePath()));

        String script = readClasspathFile("pl/kjaklik/maven/jstprecompile/scripts/template/hogan-dev-template.js");
        script = StringUtils.replace(script, "{{namespace}}", getNamespace());
        script = StringUtils.replace(script, "{{classname}}", getClassName());
        script = StringUtils.replace(script, "{{filepath}}", filepath);

        IOUtils.write(script, writer);
    }
}


text:
'use strict'

app.factory('BrosetData', ($q, $http) => {
	const service = {}

	function getBrosetSum(score) {
		let sum = 0
		sum += score.confused === true ? 1 : 0
		sum += score.irritable === true ? 1 : 0
		sum += score.boisterous === true ? 1 : 0
		sum += score.verbal_threats === true ? 1 : 0
		sum += score.physical_threats === true ? 1 : 0
		sum += score.attacking_furniture === true ? 1 : 0
		score.sum = sum
		return score
	}

	function getUrl(score) {
		score.url = `/#/admission/${score.admission_id}/broset/${score.broset_id}/edit`
		return score
	}

	function getReadableTimeStamp(score) {
		score.score_time = new Date(score.score_time).toString().split(' ').slice(1,5).join(' ')
		return score
	}

	function getNurse(score) {
		score.nurse = `${score.last_name}, ${score.first_name} RN`
		return score
	}

	service.getScoresByAdmission = admission => {
		return $q((resolve, reject) => {
			$http
				.get(`/api/brosetByAdmission/${admission}`)
				.success(scores => {
					scores = scores
						.map(getBrosetSum)
						.map(getUrl)
						.map(getReadableTimeStamp)
						.map(getNurse)
					resolve(scores)
				})
				.error(error => reject(error))
		})
	}

	service.createScore = newScore => {
		return $q((resolve, reject) => {
			$http
				.post('/api/broset', newScore)
				.success(response => resolve(response))
				.error(error => reject(error))
		})
	}

	service.getSingleScore = id => {
		return $q((resolve, reject) => {
			$http
				.get(`/api/broset/${id}`)
				.success(score => resolve(score))
				.error(error => reject(error))
		})
	}

	// service.editScore
	service.editScore = (id, newScore) => {
		console.log('newScore', newScore)
		return $q((resolve, reject) => {
			$http
				.put(`/api/broset/${id}`, newScore)
				.success(score => {
					console.log('score', score)
					resolve(score)
				})
				.error(error => reject(error))
		})
	}

	service.deleteById = id => {
		return $q((resolve, reject) => {
			$http
				.delete(`/api/broset/${id}`)
				.success(response => resolve(response))
				.error(error => reject(error))
		})
	}

	return service
})


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

    <data>

        <import type="cz.zcu.fav.remotestimulatorcontrol.ui.configurations.detail.cvep.ConfigurationFragmentCVEP" />

        <import type="cz.zcu.fav.remotestimulatorcontrol.model.configuration.AConfiguration" />

        <import type="cz.zcu.fav.remotestimulatorcontrol.model.configuration.cvep.ConfigurationCVEP" />

        <import type="cz.zcu.fav.remotestimulatorcontrol.model.configuration.cvep.ConfigurationCVEP.Pattern" />

        <variable
            name="controller"
            type="ConfigurationFragmentCVEP" />

        <variable
            name="configuration"
            type="ConfigurationCVEP" />

        <variable
            name="pattern"
            type="Pattern" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="8dp">

                <cz.zcu.fav.remotestimulatorcontrol.widget.editableseekbar.EditableSeekBar
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:esbMax="@{ConfigurationCVEP.MAX_BIT_SHIFT}"
                    app:esbMin="@{ConfigurationCVEP.MIN_BIT_SHIFT}"
                    app:esbTitle="@string/parameter_bit_shift"
                    app:esbValue="@{configuration.bitShift}"
                    app:onProgressChanged="@{controller.bitShiftChanged}"/>

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@{@string/parameter_puls_length}"
                    app:errorText="@{@string/error_invalid_input}"
                    app:validity="@{configuration.validityFlag}"
                    app:validityFlag="@{ConfigurationCVEP.FLAG_PULS_LENGTH}">

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:inputType="numberSigned"
                        android:text='@={"" + configuration.pulsLength}' />
                </android.support.design.widget.TextInputLayout>

                <cz.zcu.fav.remotestimulatorcontrol.widget.editableseekbar.EditableSeekBar
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:esbMax="@{AConfiguration.MAX_BRIGHTNESS}"
                    app:esbMin="@{AConfiguration.MIN_BRIGHTNESS}"
                    app:esbTitle="@string/parameter_brightness"
                    app:esbValue="@{configuration.brightness}"
                    app:onProgressChanged="@{controller.brightnessChanged}"/>

            </LinearLayout>
        </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="8dp"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="8dp"
                    android:text="@string/parameter_pattern_32_bit" />

                <cz.zcu.fav.remotestimulatorcontrol.widget.patternlayout.PatternWidget
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:alignContent="flex_start"
                    app:alignItems="center"
                    app:bit_count="@{ConfigurationCVEP.PATTERN_LENGTH}"
                    app:flexDirection="row"
                    app:flexWrap="wrap"
                    app:justifyContent="flex_start"
                    app:onBitChange="@{controller.patternValueChange}"
                    app:value="@{pattern.value}" />

                <android.support.v7.widget.ButtonBarLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="@string/clear"
                        android:onClick="@{() -> controller.clearBitPattern()}"/>

                    <Button
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="@string/toggle"
                        android:onClick="@{() -> controller.toggleBitPattern()}"/>

                </android.support.v7.widget.ButtonBarLayout>
            </LinearLayout>
        </android.support.v7.widget.CardView>
    </LinearLayout>
</layout>


text:
package com.kargames.flumpgdx.flump;

import com.badlogic.gdx.utils.Array;

public class TextureGroup {
	public float scaleFactor;
	public Array<Atlas> atlases;
}


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

    <title>AreaManager</title>
    <meta name="date" content="2017-01-19">
    <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

manager.areamanagers

Class AreaManager

java.lang.Object

manager.areamanagers.AreaManager

Direct Known Subclasses:

GoalAreaManager,
                        ObstacleManager,
                        SpawnAreaManager

public abstract class AreaManager
extends java.lang.Object

Created by tgdflto1 on 09/11/16.
                    Abstract class that handles the simulation room and its areas

Constructor Summary

Constructors

                                Constructor and Description

                                AreaManager()

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

                                Modifier and Type
                                Method and Description

                                void
                                add(Area a)

                                void
                                addAnchors(java.util.List<Anchor> anchors)

                                abstract void
                                clear()

                                Room
                                getRoom()

                                void
                                remove(Area a)

                                void
                                removeAnchors(java.util.List<Anchor> anchors)

                                void
                                setRoom(Room room)

Methods inherited from class java.lang.Object

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

Constructor Detail

AreaManager

public AreaManager()

Method Detail

add

public void add(Area a)

addAnchors

public void addAnchors(java.util.List<Anchor> anchors)

removeAnchors

public void removeAnchors(java.util.List<Anchor> anchors)

setRoom

public void setRoom(Room room)

getRoom

public Room getRoom()

clear

public abstract void clear()

remove

public void remove(Area a)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method