text:
package com.hubspot.singularity.mesos;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;

import javax.inject.Singleton;

import org.apache.mesos.Protos;
import org.apache.mesos.Protos.CommandInfo;
import org.apache.mesos.Protos.CommandInfo.URI;
import org.apache.mesos.Protos.ContainerInfo;
import org.apache.mesos.Protos.ContainerInfo.DockerInfo;
import org.apache.mesos.Protos.Environment;
import org.apache.mesos.Protos.Environment.Variable;
import org.apache.mesos.Protos.ExecutorID;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.Label;
import org.apache.mesos.Protos.Labels;
import org.apache.mesos.Protos.Labels.Builder;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.Parameter;
import org.apache.mesos.Protos.Resource;
import org.apache.mesos.Protos.TaskID;
import org.apache.mesos.Protos.TaskInfo;
import org.apache.mesos.Protos.Volume;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.google.protobuf.ByteString;
import com.hubspot.deploy.ExecutorDataBuilder;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.mesos.MesosUtils;
import com.hubspot.mesos.Resources;
import com.hubspot.mesos.SingularityContainerInfo;
import com.hubspot.mesos.SingularityDockerInfo;
import com.hubspot.mesos.SingularityDockerNetworkType;
import com.hubspot.mesos.SingularityDockerParameter;
import com.hubspot.mesos.SingularityDockerPortMapping;
import com.hubspot.mesos.SingularityMesosArtifact;
import com.hubspot.mesos.SingularityMesosTaskLabel;
import com.hubspot.mesos.SingularityVolume;
import com.hubspot.singularity.SingularityS3UploaderFile;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskExecutorData;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskRequest;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.ExecutorIdGenerator;

@Singleton
class SingularityMesosTaskBuilder {

  private static final Logger LOG = LoggerFactory.getLogger(SingularityMesosTaskBuilder.class);

  private final ObjectMapper objectMapper;
  private final SingularitySlaveAndRackHelper slaveAndRackHelper;
  private final ExecutorIdGenerator idGenerator;
  private final SingularityConfiguration configuration;

  @Inject
  SingularityMesosTaskBuilder(ObjectMapper objectMapper, SingularitySlaveAndRackHelper slaveAndRackHelper, ExecutorIdGenerator idGenerator, SingularityConfiguration configuration) {
    this.objectMapper = objectMapper;
    this.slaveAndRackHelper = slaveAndRackHelper;
    this.idGenerator = idGenerator;
    this.configuration = configuration;
  }

  public SingularityTask buildTask(Protos.Offer offer, List<Resource> availableResources, SingularityTaskRequest taskRequest, Resources desiredTaskResources, Resources desiredExecutorResources) {
    final String sanitizedRackId = JavaUtils.getReplaceHyphensWithUnderscores(slaveAndRackHelper.getRackIdOrDefault(offer));
    final String sanitizedHost = JavaUtils.getReplaceHyphensWithUnderscores(slaveAndRackHelper.getMaybeTruncatedHost(offer));

    final SingularityTaskId taskId = new SingularityTaskId(taskRequest.getPendingTask().getPendingTaskId().getRequestId(), taskRequest.getDeploy().getId(), System.currentTimeMillis(),
        taskRequest.getPendingTask().getPendingTaskId().getInstanceNo(), sanitizedHost, sanitizedRackId);

    final TaskInfo.Builder bldr = TaskInfo.newBuilder()
        .setTaskId(TaskID.newBuilder().setValue(taskId.toString()));

    Optional<long[]> ports = Optional.absent();
    Optional<Resource> portsResource = Optional.absent();

    final Optional<SingularityContainerInfo> containerInfo = taskRequest.getDeploy().getContainerInfo();
    if (desiredTaskResources.getNumPorts() > 0 || hasLiteralPortMapping(containerInfo)) {
      List<Long> requestedPorts = new ArrayList<>();
      if (hasLiteralPortMapping(containerInfo)) {
        requestedPorts.addAll(containerInfo.get().getDocker().get().getLiteralHostPorts());
      }
      portsResource = Optional.of(MesosUtils.getPortsResource(desiredTaskResources.getNumPorts(), availableResources, requestedPorts));
      ports = Optional.of(MesosUtils.getPorts(portsResource.get(), desiredTaskResources.getNumPorts()));
    }

    if (containerInfo.isPresent()) {
      prepareContainerInfo(offer, taskId, bldr, containerInfo.get(), ports);
    }

    if (taskRequest.getDeploy().getCustomExecutorCmd().isPresent()) {
      prepareCustomExecutor(bldr, taskId, taskRequest, offer, ports, desiredExecutorResources);
    } else {
      prepareCommand(bldr, taskId, taskRequest, offer, ports);
    }

    if (portsResource.isPresent()) {
      bldr.addResources(portsResource.get());
    }

    Optional<String> requiredRole = taskRequest.getRequest().getRequiredRole();
    bldr.addResources(MesosUtils.getCpuResource(desiredTaskResources.getCpus(), requiredRole));
    bldr.addResources(MesosUtils.getMemoryResource(desiredTaskResources.getMemoryMb(), requiredRole));

    if (desiredTaskResources.getDiskMb() > 0) {
      bldr.addResources(MesosUtils.getDiskResource(desiredTaskResources.getDiskMb(), requiredRole));
    }

    bldr.setSlaveId(offer.getSlaveId());

    bldr.setName(taskRequest.getRequest().getId());

    final Builder labelsBuilder = Labels.newBuilder();
    // apply request-specific labels, if any
    if (taskRequest.getDeploy().getMesosLabels().isPresent() && !taskRequest.getDeploy().getMesosLabels().get().isEmpty()) {
      for (SingularityMesosTaskLabel label : taskRequest.getDeploy().getMesosLabels().get()) {
        org.apache.mesos.Protos.Label.Builder labelBuilder = Label.newBuilder();
        labelBuilder.setKey(label.getKey());
        if ((label.getValue().isPresent())) {
          labelBuilder.setValue(label.getValue().get());
        }
        labelsBuilder.addLabels(labelBuilder.build());
      }
    }

    // apply task-specific labels, if any
    final int taskInstanceNo = taskRequest.getPendingTask().getPendingTaskId().getInstanceNo();
    if (taskRequest.getDeploy().getMesosTaskLabels().isPresent() && taskRequest.getDeploy().getMesosTaskLabels().get().containsKey(taskInstanceNo) && !taskRequest.getDeploy().getMesosTaskLabels().get().get(taskInstanceNo).isEmpty()) {
      for (SingularityMesosTaskLabel label : taskRequest.getDeploy().getMesosTaskLabels().get().get(taskInstanceNo)) {
        org.apache.mesos.Protos.Label.Builder labelBuilder = Label.newBuilder();
        labelBuilder.setKey(label.getKey());
        if ((label.getValue().isPresent())) {
          labelBuilder.setValue(label.getValue().get());
        }
        labelsBuilder.addLabels(labelBuilder.build());
      }
    }
    bldr.setLabels(labelsBuilder);

    TaskInfo task = bldr.build();

    return new SingularityTask(taskRequest, taskId, offer, task, slaveAndRackHelper.getRackId(offer));
  }

  private boolean hasLiteralPortMapping(Optional<SingularityContainerInfo> maybeContainerInfo) {
    return maybeContainerInfo.isPresent() && maybeContainerInfo.get().getDocker().isPresent() && !maybeContainerInfo.get().getDocker().get().getLiteralHostPorts().isEmpty();
  }

  private void setEnv(Environment.Builder envBldr, String key, Object value) {
    if (value == null) {
      return;
    }
    envBldr.addVariables(Variable.newBuilder().setName(key).setValue(value.toString()));
  }

  private void prepareEnvironment(final SingularityTaskRequest task, SingularityTaskId taskId, CommandInfo.Builder commandBuilder, final Protos.Offer offer, final Optional<long[]> ports) {
    Environment.Builder envBldr = Environment.newBuilder();

    setEnv(envBldr, "INSTANCE_NO", task.getPendingTask().getPendingTaskId().getInstanceNo());
    setEnv(envBldr, "TASK_HOST", offer.getHostname());

    Optional<String> rack = slaveAndRackHelper.getRackId(offer);

    if (rack.isPresent()) {
      setEnv(envBldr, "TASK_RACK_ID", rack.get());
    }

    setEnv(envBldr, "TASK_REQUEST_ID", task.getPendingTask().getPendingTaskId().getRequestId());
    setEnv(envBldr, "TASK_DEPLOY_ID", taskId.getDeployId());
    setEnv(envBldr, "TASK_ID", taskId.getId());
    setEnv(envBldr, "ESTIMATED_INSTANCE_COUNT", task.getRequest().getInstancesSafe());

    if (task.getPendingTask().getUser().isPresent()) {
      setEnv(envBldr, "STARTED_BY_USER", task.getPendingTask().getUser().get());
    }

    for (Entry<String, String> envEntry : task.getDeploy().getEnv().or(Collections.<String, String>emptyMap()).entrySet()) {
      setEnv(envBldr, envEntry.getKey(), fillInTaskIdValues(envEntry.getValue(), offer, taskId));
    }

    if (task.getDeploy().getTaskEnv().isPresent() && task.getDeploy().getTaskEnv().get().containsKey(taskId.getInstanceNo()) && !task.getDeploy().getTaskEnv().get().get(taskId.getInstanceNo()).isEmpty()) {
      for (Entry<String, String> envEntry : task.getDeploy().getTaskEnv().get().get(taskId.getInstanceNo()).entrySet()) {
        setEnv(envBldr, envEntry.getKey(), fillInTaskIdValues(envEntry.getValue(), offer, taskId));
      }
    }

    if (ports.isPresent()) {
      for (int portNum = 0; portNum < ports.get().length; portNum++) {
        if (portNum == 0) {
          setEnv(envBldr, "PORT", ports.get()[portNum]);
        }

        setEnv(envBldr, String.format("PORT%s", portNum), ports.get()[portNum]);
      }
    }

    commandBuilder.setEnvironment(envBldr.build());
  }

  private Optional<DockerInfo.PortMapping> buildPortMapping(final SingularityDockerPortMapping singularityDockerPortMapping, final Optional<long[]> ports) {
    final int containerPort;
    switch (singularityDockerPortMapping.getContainerPortType()) {
      case LITERAL:
        containerPort = singularityDockerPortMapping.getContainerPort();
        break;
      case FROM_OFFER:
        containerPort = Ints.checkedCast(ports.get()[singularityDockerPortMapping.getContainerPort()]);
        break;
      default:
        return Optional.absent();
    }

    final int hostPort;
    switch (singularityDockerPortMapping.getHostPortType()) {
      case LITERAL:
        hostPort = singularityDockerPortMapping.getHostPort();
        break;
      case FROM_OFFER:
        hostPort = Ints.checkedCast(ports.get()[singularityDockerPortMapping.getHostPort()]);
        break;
      default:
        return Optional.absent();
    }

    return Optional.of(DockerInfo.PortMapping.newBuilder()
        .setContainerPort(containerPort)
        .setHostPort(hostPort)
        .setProtocol(singularityDockerPortMapping.getProtocol())
        .build());
  }

  private String fillInTaskIdValues(String string, Offer offer, SingularityTaskId taskId) {
    if (!Strings.isNullOrEmpty(string)) {
      string = string.replace("${TASK_REQUEST_ID}", taskId.getRequestId())
          .replace("${TASK_DEPLOY_ID}", taskId.getDeployId())
          .replace("${TASK_STARTED_AT}", Long.toString(taskId.getStartedAt()))
          .replace("${TASK_INSTANCE_NO}", Integer.toString(taskId.getInstanceNo()))
          .replace("${TASK_HOST}", offer.getHostname())
          .replace("${TASK_RACK_ID}", slaveAndRackHelper.getRackIdOrDefault(offer))
          .replace("${TASK_ID}", taskId.getId());
    }

    return string;
  }

  private void prepareContainerInfo(final Offer offer, final SingularityTaskId taskId, final TaskInfo.Builder bldr, final SingularityContainerInfo containerInfo, final Optional<long[]> ports) {
    ContainerInfo.Builder containerBuilder = ContainerInfo.newBuilder();
    containerBuilder.setType(ContainerInfo.Type.valueOf(containerInfo.getType().toString()));

    final Optional<SingularityDockerInfo> dockerInfo = containerInfo.getDocker();

    if (dockerInfo.isPresent()) {
      final DockerInfo.Builder dockerInfoBuilder = DockerInfo.newBuilder();
      dockerInfoBuilder.setImage(dockerInfo.get().getImage());

      if (dockerInfo.get().getNetwork().isPresent()) {
        dockerInfoBuilder.setNetwork(DockerInfo.Network.valueOf(dockerInfo.get().getNetwork().get().toString()));
      }

      final List<SingularityDockerPortMapping> portMappings = dockerInfo.get().getPortMappings();
      final boolean isBridged = SingularityDockerNetworkType.BRIDGE.equals(dockerInfo.get().getNetwork().orNull());

      if ((dockerInfo.get().hasAllLiteralHostPortMappings() || ports.isPresent()) && !portMappings.isEmpty()) {
        for (SingularityDockerPortMapping singularityDockerPortMapping : portMappings) {
          final Optional<DockerInfo.PortMapping> maybePortMapping = buildPortMapping(singularityDockerPortMapping, ports);

          if (maybePortMapping.isPresent()) {
            dockerInfoBuilder.addPortMappings(maybePortMapping.get());
          }
        }
      } else if (configuration.getNetworkConfiguration().isDefaultPortMapping() && isBridged && portMappings.isEmpty() && ports.isPresent()) {
        for (long longPort : ports.get()) {
          int port = Ints.checkedCast(longPort);
          dockerInfoBuilder.addPortMappings(DockerInfo.PortMapping.newBuilder()
              .setHostPort(port)
              .setContainerPort(port)
              .build());
        }
      }

      if (!dockerInfo.get().getDockerParameters().isEmpty()) {
        List<Parameter> parameters = new ArrayList<>();
        for (SingularityDockerParameter parameter : dockerInfo.get().getDockerParameters()) {
          parameters.add(Parameter.newBuilder().setKey(parameter.getKey()).setValue(parameter.getValue()).build());
        }
        dockerInfoBuilder.addAllParameters(parameters);
      }

      dockerInfoBuilder.setPrivileged(dockerInfo.get().isPrivileged());

      dockerInfoBuilder.setForcePullImage(dockerInfo.get().isForcePullImage());

      containerBuilder.setDocker(dockerInfoBuilder);
    }

    for (SingularityVolume volumeInfo : containerInfo.getVolumes().or(Collections.<SingularityVolume>emptyList())) {
      final Volume.Builder volumeBuilder = Volume.newBuilder();
      volumeBuilder.setContainerPath(fillInTaskIdValues(volumeInfo.getContainerPath(), offer, taskId));
      if (volumeInfo.getHostPath().isPresent()) {
        volumeBuilder.setHostPath(fillInTaskIdValues(volumeInfo.getHostPath().get(), offer, taskId));
      }
      if (volumeInfo.getMode().isPresent()) {
        volumeBuilder.setMode(Volume.Mode.valueOf(volumeInfo.getMode().get().toString()));
      } else {
        volumeBuilder.setMode(Volume.Mode.RO);
      }
      containerBuilder.addVolumes(volumeBuilder);
    }

    bldr.setContainer(containerBuilder);
  }

  private List<Resource> buildMesosResources(final Resources resources, Optional<String> role) {
    ImmutableList.Builder<Resource> builder = ImmutableList.builder();

    if (resources.getCpus() > 0) {
      builder.add(MesosUtils.getCpuResource(resources.getCpus(), role));
    }

    if (resources.getMemoryMb() > 0) {
      builder.add(MesosUtils.getMemoryResource(resources.getMemoryMb(), role));
    }

    if (resources.getDiskMb() > 0) {
      builder.add(MesosUtils.getDiskResource(resources.getDiskMb(), role));
    }

    return builder.build();
  }

  private void prepareCustomExecutor(final TaskInfo.Builder bldr, final SingularityTaskId taskId, final SingularityTaskRequest task, final Protos.Offer offer,
      final Optional<long[]> ports, final Resources desiredExecutorResources) {
    CommandInfo.Builder commandBuilder = CommandInfo.newBuilder().setValue(task.getDeploy().getCustomExecutorCmd().get());

    prepareEnvironment(task, taskId, commandBuilder, offer, ports);

    if (task.getDeploy().getUser().isPresent()) {
      commandBuilder.setUser(task.getDeploy().getUser().get());
    }

    bldr.setExecutor(ExecutorInfo.newBuilder()
        .setCommand(commandBuilder.build())
        .setExecutorId(ExecutorID.newBuilder().setValue(task.getDeploy().getCustomExecutorId().or(idGenerator.getNextExecutorId())))
        .setSource(task.getDeploy().getCustomExecutorSource().or(taskId.getId())) // set source to taskId for use in statistics endpoint
        .addAllResources(buildMesosResources(desiredExecutorResources, task.getRequest().getRequiredRole()))
        .build()
        );

    if (task.getDeploy().getExecutorData().isPresent()) {
      final ExecutorDataBuilder executorDataBldr = task.getDeploy().getExecutorData().get().toBuilder();

      String defaultS3Bucket = "";
      String s3UploaderKeyPattern = "";
      if (configuration.getS3ConfigurationOptional().isPresent()) {
        if (task.getRequest().getGroup().isPresent() && configuration.getS3ConfigurationOptional().get().getGroupOverrides().containsKey(task.getRequest().getGroup().get())) {
          defaultS3Bucket = configuration.getS3ConfigurationOptional().get().getGroupOverrides().get(task.getRequest().getGroup().get()).getS3Bucket();
          LOG.trace("Setting defaultS3Bucket to {} for task {} executorData", defaultS3Bucket, taskId.getId());
        } else {
          defaultS3Bucket = configuration.getS3ConfigurationOptional().get().getS3Bucket();
        }
        s3UploaderKeyPattern = configuration.getS3ConfigurationOptional().get().getS3KeyFormat();
      }

      if (task.getPendingTask().getCmdLineArgsList().isPresent() && !task.getPendingTask().getCmdLineArgsList().get().isEmpty()) {
        LOG.trace("Adding cmd line args {} to task {} executorData", task.getPendingTask().getCmdLineArgsList(), taskId.getId());

        final ImmutableList.Builder<String> extraCmdLineArgsBuilder = ImmutableList.builder();
        if (executorDataBldr.getExtraCmdLineArgs() != null && !executorDataBldr.getExtraCmdLineArgs().isEmpty()) {
          extraCmdLineArgsBuilder.addAll(executorDataBldr.getExtraCmdLineArgs());
        }
        extraCmdLineArgsBuilder.addAll(task.getPendingTask().getCmdLineArgsList().get());
        executorDataBldr.setExtraCmdLineArgs(extraCmdLineArgsBuilder.build());
      }

      List<SingularityS3UploaderFile> uploaderAdditionalFiles = configuration.getS3ConfigurationOptional().isPresent() ? configuration.getS3ConfigurationOptional().get().getS3UploaderAdditionalFiles() : Collections.<SingularityS3UploaderFile>emptyList();
      Optional<String> maybeS3StorageClass = configuration.getS3ConfigurationOptional().isPresent() ? configuration.getS3ConfigurationOptional().get().getS3StorageClass() : Optional.<String>absent();
      Optional<Long> maybeApplyAfterBytes = configuration.getS3ConfigurationOptional().isPresent() ? configuration.getS3ConfigurationOptional().get().getApplyS3StorageClassAfterBytes() : Optional.<Long>absent();

      final SingularityTaskExecutorData executorData = new SingularityTaskExecutorData(executorDataBldr.build(), uploaderAdditionalFiles, defaultS3Bucket, s3UploaderKeyPattern,
          configuration.getCustomExecutorConfiguration().getServiceLog(), configuration.getCustomExecutorConfiguration().getServiceFinishedTailLog(), task.getRequest().getGroup(),
          maybeS3StorageClass, maybeApplyAfterBytes);

      try {
        bldr.setData(ByteString.copyFromUtf8(objectMapper.writeValueAsString(executorData)));
      } catch (JsonProcessingException e) {
        LOG.warn("Unable to process executor data {} for task {} as json (trying as string)", executorData, taskId.getId(), e);

        bldr.setData(ByteString.copyFromUtf8(executorData.toString()));
      }
    } else if (task.getDeploy().getCommand().isPresent()) {
      bldr.setData(ByteString.copyFromUtf8(task.getDeploy().getCommand().get()));
    }
  }

  private void prepareCommand(final TaskInfo.Builder bldr, final SingularityTaskId taskId, final SingularityTaskRequest task, final Protos.Offer offer, final Optional<long[]> ports) {
    CommandInfo.Builder commandBldr = CommandInfo.newBuilder();

    if (task.getDeploy().getUser().isPresent()) {
      commandBldr.setUser(task.getDeploy().getUser().get());
    }

    if (task.getDeploy().getCommand().isPresent()) {
      commandBldr.setValue(task.getDeploy().getCommand().get());
    }

    if (task.getDeploy().getArguments().isPresent()) {
      commandBldr.addAllArguments(task.getDeploy().getArguments().get());
    }

    if (task.getPendingTask().getCmdLineArgsList().isPresent()) {
      commandBldr.addAllArguments(task.getPendingTask().getCmdLineArgsList().get());
    }

    if (task.getDeploy().getShell().isPresent()){
      commandBldr.setShell(task.getDeploy().getShell().get());
    } else if ((task.getDeploy().getArguments().isPresent() && !task.getDeploy().getArguments().get().isEmpty()) ||
        // Hopefully temporary workaround for
        // http://www.mail-archive.com/user@mesos.apache.org/msg01449.html
        task.getDeploy().getContainerInfo().isPresent() ||
        (task.getPendingTask().getCmdLineArgsList().isPresent() && !task.getPendingTask().getCmdLineArgsList().get().isEmpty())) {
      commandBldr.setShell(false);
    }

    for (SingularityMesosArtifact artifact : task.getDeploy().getUris().or(Collections.<SingularityMesosArtifact> emptyList())) {
      commandBldr.addUris(URI.newBuilder()
          .setValue(artifact.getUri())
          .setCache(artifact.isCache())
          .setExecutable(artifact.isExecutable())
          .setExtract(artifact.isExtract())
          .build());
    }

    prepareEnvironment(task, taskId, commandBldr, offer, ports);

    bldr.setCommand(commandBldr);
  }

}


text:
#include <linux/bootmem.h>
#include <linux/pfn.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/hugetlb.h>
#include <linux/slab.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/setup.h>
#include <asm/tlbflush.h>
#include <asm/sections.h>

static DEFINE_MUTEX(vmem_mutex);

struct memory_segment {
	struct list_head list;
	unsigned long start;
	unsigned long size;
};

static LIST_HEAD(mem_segs);

static void __ref *vmem_alloc_pages(unsigned int order)
{
	if (slab_is_available())
		return (void *)__get_free_pages(GFP_KERNEL, order);
	return alloc_bootmem_pages((1 << order) * PAGE_SIZE);
}

static inline pud_t *vmem_pud_alloc(void)
{
	pud_t *pud = NULL;

#ifdef CONFIG_64BIT
	pud = vmem_alloc_pages(2);
	if (!pud)
		return NULL;
	clear_table((unsigned long *) pud, _REGION3_ENTRY_EMPTY, PAGE_SIZE * 4);
#endif
	return pud;
}

static inline pmd_t *vmem_pmd_alloc(void)
{
	pmd_t *pmd = NULL;

#ifdef CONFIG_64BIT
	pmd = vmem_alloc_pages(2);
	if (!pmd)
		return NULL;
	clear_table((unsigned long *) pmd, _SEGMENT_ENTRY_EMPTY, PAGE_SIZE * 4);
#endif
	return pmd;
}

static pte_t __ref *vmem_pte_alloc(unsigned long address)
{
	pte_t *pte;

	if (slab_is_available())
		pte = (pte_t *) page_table_alloc(&init_mm, address);
	else
		pte = alloc_bootmem(PTRS_PER_PTE * sizeof(pte_t));
	if (!pte)
		return NULL;
	clear_table((unsigned long *) pte, _PAGE_TYPE_EMPTY,
		    PTRS_PER_PTE * sizeof(pte_t));
	return pte;
}

/*
 * Add a physical memory range to the 1:1 mapping.
 */
static int vmem_add_mem(unsigned long start, unsigned long size, int ro)
{
	unsigned long end = start + size;
	unsigned long address = start;
	pgd_t *pg_dir;
	pud_t *pu_dir;
	pmd_t *pm_dir;
	pte_t *pt_dir;
	int ret = -ENOMEM;

	while (address < end) {
		pg_dir = pgd_offset_k(address);
		if (pgd_none(*pg_dir)) {
			pu_dir = vmem_pud_alloc();
			if (!pu_dir)
				goto out;
			pgd_populate(&init_mm, pg_dir, pu_dir);
		}
		pu_dir = pud_offset(pg_dir, address);
#if defined(CONFIG_64BIT) && !defined(CONFIG_DEBUG_PAGEALLOC)
		if (MACHINE_HAS_EDAT2 && pud_none(*pu_dir) && address &&
		    !(address & ~PUD_MASK) && (address + PUD_SIZE <= end)) {
			pud_val(*pu_dir) = __pa(address) |
				_REGION_ENTRY_TYPE_R3 | _REGION3_ENTRY_LARGE |
				(ro ? _REGION_ENTRY_RO : 0);
			address += PUD_SIZE;
			continue;
		}
#endif
		if (pud_none(*pu_dir)) {
			pm_dir = vmem_pmd_alloc();
			if (!pm_dir)
				goto out;
			pud_populate(&init_mm, pu_dir, pm_dir);
		}
		pm_dir = pmd_offset(pu_dir, address);
#if defined(CONFIG_64BIT) && !defined(CONFIG_DEBUG_PAGEALLOC)
		if (MACHINE_HAS_EDAT1 && pmd_none(*pm_dir) && address &&
		    !(address & ~PMD_MASK) && (address + PMD_SIZE <= end)) {
			pmd_val(*pm_dir) = __pa(address) |
				_SEGMENT_ENTRY | _SEGMENT_ENTRY_LARGE |
				(ro ? _SEGMENT_ENTRY_RO : 0);
			address += PMD_SIZE;
			continue;
		}
#endif
		if (pmd_none(*pm_dir)) {
			pt_dir = vmem_pte_alloc(address);
			if (!pt_dir)
				goto out;
			pmd_populate(&init_mm, pm_dir, pt_dir);
		}

		pt_dir = pte_offset_kernel(pm_dir, address);
		pte_val(*pt_dir) = __pa(address) | (ro ? _PAGE_RO : 0);
		address += PAGE_SIZE;
	}
	ret = 0;
out:
	flush_tlb_kernel_range(start, end);
	return ret;
}

/*
 * Remove a physical memory range from the 1:1 mapping.
 * Currently only invalidates page table entries.
 */
static void vmem_remove_range(unsigned long start, unsigned long size)
{
	unsigned long end = start + size;
	unsigned long address = start;
	pgd_t *pg_dir;
	pud_t *pu_dir;
	pmd_t *pm_dir;
	pte_t *pt_dir;
	pte_t  pte;

	pte_val(pte) = _PAGE_TYPE_EMPTY;
	while (address < end) {
		pg_dir = pgd_offset_k(address);
		if (pgd_none(*pg_dir)) {
			address += PGDIR_SIZE;
			continue;
		}
		pu_dir = pud_offset(pg_dir, address);
		if (pud_none(*pu_dir)) {
			address += PUD_SIZE;
			continue;
		}
		if (pud_large(*pu_dir)) {
			pud_clear(pu_dir);
			address += PUD_SIZE;
			continue;
		}
		pm_dir = pmd_offset(pu_dir, address);
		if (pmd_none(*pm_dir)) {
			address += PMD_SIZE;
			continue;
		}
		if (pmd_large(*pm_dir)) {
			pmd_clear(pm_dir);
			address += PMD_SIZE;
			continue;
		}
		pt_dir = pte_offset_kernel(pm_dir, address);
		*pt_dir = pte;
		address += PAGE_SIZE;
	}
	flush_tlb_kernel_range(start, end);
}

/*
 * Add a backed mem_map array to the virtual mem_map array.
 */
int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node)
{
	unsigned long address = start;
	pgd_t *pg_dir;
	pud_t *pu_dir;
	pmd_t *pm_dir;
	pte_t *pt_dir;
	int ret = -ENOMEM;

	for (address = start; address < end;) {
		pg_dir = pgd_offset_k(address);
		if (pgd_none(*pg_dir)) {
			pu_dir = vmem_pud_alloc();
			if (!pu_dir)
				goto out;
			pgd_populate(&init_mm, pg_dir, pu_dir);
		}

		pu_dir = pud_offset(pg_dir, address);
		if (pud_none(*pu_dir)) {
			pm_dir = vmem_pmd_alloc();
			if (!pm_dir)
				goto out;
			pud_populate(&init_mm, pu_dir, pm_dir);
		}

		pm_dir = pmd_offset(pu_dir, address);
		if (pmd_none(*pm_dir)) {
#ifdef CONFIG_64BIT
			/* Use 1MB frames for vmemmap if available. We always
			 * use large frames even if they are only partially
			 * used.
			 * Otherwise we would have also page tables since
			 * vmemmap_populate gets called for each section
			 * separately. */
			if (MACHINE_HAS_EDAT1) {
				void *new_page;

				new_page = vmemmap_alloc_block(PMD_SIZE, node);
				if (!new_page)
					goto out;
				pmd_val(*pm_dir) = __pa(new_page) |
					_SEGMENT_ENTRY | _SEGMENT_ENTRY_LARGE |
					_SEGMENT_ENTRY_CO;
				address = (address + PMD_SIZE) & PMD_MASK;
				continue;
			}
#endif
			pt_dir = vmem_pte_alloc(address);
			if (!pt_dir)
				goto out;
			pmd_populate(&init_mm, pm_dir, pt_dir);
		} else if (pmd_large(*pm_dir)) {
			address = (address + PMD_SIZE) & PMD_MASK;
			continue;
		}

		pt_dir = pte_offset_kernel(pm_dir, address);
		if (pte_none(*pt_dir)) {
			unsigned long new_page;

			new_page =__pa(vmem_alloc_pages(0));
			if (!new_page)
				goto out;
			pte_val(*pt_dir) = __pa(new_page);
		}
		address += PAGE_SIZE;
	}
	memset((void *)start, 0, end - start);
	ret = 0;
out:
	flush_tlb_kernel_range(start, end);
	return ret;
}

void vmemmap_free(unsigned long start, unsigned long end)
{
}

/*
 * Add memory segment to the segment list if it doesn't overlap with
 * an already present segment.
 */
static int insert_memory_segment(struct memory_segment *seg)
{
	struct memory_segment *tmp;

	if (seg->start + seg->size > VMEM_MAX_PHYS ||
	    seg->start + seg->size < seg->start)
		return -ERANGE;

	list_for_each_entry(tmp, &mem_segs, list) {
		if (seg->start >= tmp->start + tmp->size)
			continue;
		if (seg->start + seg->size <= tmp->start)
			continue;
		return -ENOSPC;
	}
	list_add(&seg->list, &mem_segs);
	return 0;
}

/*
 * Remove memory segment from the segment list.
 */
static void remove_memory_segment(struct memory_segment *seg)
{
	list_del(&seg->list);
}

static void __remove_shared_memory(struct memory_segment *seg)
{
	remove_memory_segment(seg);
	vmem_remove_range(seg->start, seg->size);
}

int vmem_remove_mapping(unsigned long start, unsigned long size)
{
	struct memory_segment *seg;
	int ret;

	mutex_lock(&vmem_mutex);

	ret = -ENOENT;
	list_for_each_entry(seg, &mem_segs, list) {
		if (seg->start == start && seg->size == size)
			break;
	}

	if (seg->start != start || seg->size != size)
		goto out;

	ret = 0;
	__remove_shared_memory(seg);
	kfree(seg);
out:
	mutex_unlock(&vmem_mutex);
	return ret;
}

int vmem_add_mapping(unsigned long start, unsigned long size)
{
	struct memory_segment *seg;
	int ret;

	mutex_lock(&vmem_mutex);
	ret = -ENOMEM;
	seg = kzalloc(sizeof(*seg), GFP_KERNEL);
	if (!seg)
		goto out;
	seg->start = start;
	seg->size = size;

	ret = insert_memory_segment(seg);
	if (ret)
		goto out_free;

	ret = vmem_add_mem(start, size, 0);
	if (ret)
		goto out_remove;
	goto out;

out_remove:
	__remove_shared_memory(seg);
out_free:
	kfree(seg);
out:
	mutex_unlock(&vmem_mutex);
	return ret;
}

/*
 * map whole physical memory to virtual memory (identity mapping)
 * we reserve enough space in the vmalloc area for vmemmap to hotplug
 * additional memory segments.
 */
void __init vmem_map_init(void)
{
	unsigned long ro_start, ro_end;
	unsigned long start, end;
	int i;

	ro_start = PFN_ALIGN((unsigned long)&_stext);
	ro_end = (unsigned long)&_eshared & PAGE_MASK;
	for (i = 0; i < MEMORY_CHUNKS; i++) {
		if (!memory_chunk[i].size)
			continue;
		start = memory_chunk[i].addr;
		end = memory_chunk[i].addr + memory_chunk[i].size;
		if (start >= ro_end || end <= ro_start)
			vmem_add_mem(start, end - start, 0);
		else if (start >= ro_start && end <= ro_end)
			vmem_add_mem(start, end - start, 1);
		else if (start >= ro_start) {
			vmem_add_mem(start, ro_end - start, 1);
			vmem_add_mem(ro_end, end - ro_end, 0);
		} else if (end < ro_end) {
			vmem_add_mem(start, ro_start - start, 0);
			vmem_add_mem(ro_start, end - ro_start, 1);
		} else {
			vmem_add_mem(start, ro_start - start, 0);
			vmem_add_mem(ro_start, ro_end - ro_start, 1);
			vmem_add_mem(ro_end, end - ro_end, 0);
		}
	}
}

/*
 * Convert memory chunk array to a memory segment list so there is a single
 * list that contains both r/w memory and shared memory segments.
 */
static int __init vmem_convert_memory_chunk(void)
{
	struct memory_segment *seg;
	int i;

	mutex_lock(&vmem_mutex);
	for (i = 0; i < MEMORY_CHUNKS; i++) {
		if (!memory_chunk[i].size)
			continue;
		seg = kzalloc(sizeof(*seg), GFP_KERNEL);
		if (!seg)
			panic("Out of memory...\n");
		seg->start = memory_chunk[i].addr;
		seg->size = memory_chunk[i].size;
		insert_memory_segment(seg);
	}
	mutex_unlock(&vmem_mutex);
	return 0;
}

core_initcall(vmem_convert_memory_chunk);

redpajama_set_name: RedPajamaGithub


text:
package xyz.openmodloader.util;

import java.util.Objects;

/**
 * @param <T> the type of the first argument to the operation
 * @param <U> the type of the second argument to the operation
 * @param <V> the type of the third argument to the operation
 *
 * @see java.util.function.Consumer
 * @see java.util.function.BiConsumer
 */
@FunctionalInterface
public interface TriConsumer<T, U, V> {

    /**
     * Performs this operation on the given arguments.
     *
     * @param t the first input argument
     * @param u the second input argument
     * @param v the third input argument
     */
    void accept(T t, U u, V v);

    /**
     * @param after the operation to perform after this operation
     * @return a composed {@code TriConsumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default TriConsumer<T, U, V> andThen(TriConsumer<? super T, ? super U, ? super V> after) {
        Objects.requireNonNull(after);
        return (t, u, v) -> {
            accept(t, u, v);
            after.accept(t, u, v);
        };
    }
}


text:
package com.radiusnetworks.ibeacon.simulator;

import com.radiusnetworks.ibeacon.IBeacon;

import java.util.List;

/**
 * Created by dyoung on 4/18/14.
 */
public interface BeaconSimulator {
    public List<IBeacon> getBeacons();
}


text:
.. _development_process:

Development Process Documentation
=================================

.. toctree::
   :hidden:

   MakefileGuide
   Projects

* :ref:`projects`

  How-to guide and templates for new projects that *use* the LLVM
  infrastructure.  The templates (directory organization, Makefiles, and test
  tree) allow the project code to be located outside (or inside) the ``llvm/``
  tree, while using LLVM header files and libraries.

* `LLVMBuild Documentation <LLVMBuild.html>`_

  Describes the LLVMBuild organization and files used by LLVM to specify
  component descriptions.

* :ref:`makefile_guide`

  Describes how the LLVM makefiles work and how to use them.

* `How To Release LLVM To The Public <HowToReleaseLLVM.html>`_

  This is a guide to preparing LLVM releases. Most developers can ignore it.


text:
package build

import (
	"github.com/hashicorp/terraform/helper/schema"
	"k8s.io/kubernetes/pkg/api"
)

func Namespace(d *schema.ResourceData, version string) *api.Namespace {
	namespace := &api.Namespace{
		Spec: NamespaceSpec(d.Get("spec").([]interface{})),
	}

	namespace.Kind = "Namespace"
	namespace.APIVersion = version

	populateMetadata(&namespace.ObjectMeta, d.Get("metadata").([]interface{}))

	return namespace
}

func NamespaceSpec(namespaceSpecs []interface{}) api.NamespaceSpec {
	if len(namespaceSpecs) == 0 {
		return api.NamespaceSpec{}
	}
	userNamespaceSpec := namespaceSpecs[0].(map[string]interface{})

	namespaceSpec := api.NamespaceSpec{}

	if _, ok := userNamespaceSpec["finalizers"]; ok {
		strFinalizers := convertListToStringArray(userNamespaceSpec["finalizers"].([]interface{}))
		var finalizers []api.FinalizerName
		for _, f := range strFinalizers {
			finalizers = append(finalizers, api.FinalizerName(f))
		}
		namespaceSpec.Finalizers = finalizers
	}

	return namespaceSpec
}


text:
var plugins     = require('gulp-load-plugins')();

module.exports = function(gulp, packageJSON) {
    return function() {
        gulp.watch(packageJSON.paths.css, ['css']);
    }
};


text:
If You have trouble making a-frame stuff in angular.io, check out my example,
or follow my advice @https://stackoverflow.com/questions/44468787/angular-io-aframe-typings-error-with-three-js-cannot-find-namespace-three/44502162#44502162

Check it the project @https://cdn.rawgit.com/gftruj/aframe-experients/1dfaf58a/angular/index.html


text:
import DS from 'ember-data';

export default DS.Model.extend({
	title: DS.attr('string'),
	body: DS.attr('string'),
	timestamp: DS.attr('number')
});


text:
require 'test_helper'

class AgendasHelperTest < ActionView::TestCase
end


text:
package org.motechproject.ihe.interop.handler.helper;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.motechproject.ihe.interop.domain.CdaTemplate;
import org.motechproject.ihe.interop.domain.HL7Recipient;
import org.motechproject.ihe.interop.exception.RecipientNotFoundException;
import org.motechproject.ihe.interop.exception.TemplateNotFoundException;
import org.motechproject.ihe.interop.service.HL7RecipientsService;
import org.motechproject.ihe.interop.service.IHETemplateDataService;
import org.motechproject.ihe.interop.service.IHETemplateService;
import org.motechproject.ihe.interop.util.Constants;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class IHEActionHelperTest {

    @Mock
    private HL7RecipientsService hl7RecipientsService;

    @Mock
    private IHETemplateDataService iheTemplateDataService;

    @Mock
    private IHETemplateService iheTemplateService;

    @Mock
    private CdaTemplate cdaTemplate;

    @Mock
    private HL7Recipient hl7Recipient;

    @InjectMocks
    private IHEActionHelper iheActionHelper = new IHEActionHelper();

    @Before
    public void setUp() {
        initMocks(this);
    }

    @Test(expected = TemplateNotFoundException.class)
    public void shouldThrowExceptionWhenTemplateNotFound() throws ClassNotFoundException, ParserConfigurationException, SAXException, IOException {
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.TEMPLATE_NAME_PARAM, "sampleTemplate2");
        params.put(Constants.RECIPIENT_NAME_PARAM, "sampleRecipient2");

        iheActionHelper.handleAction(params);
    }

    @Test(expected = RecipientNotFoundException.class)
    public void shouldThrowExceptionWhenRecipientNotFound() throws ClassNotFoundException, ParserConfigurationException, SAXException, IOException {
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.TEMPLATE_NAME_PARAM, "sampleTemplate3");
        params.put(Constants.RECIPIENT_NAME_PARAM, "sampleRecipient3");

        when(iheTemplateDataService.findByName("sampleTemplate3")).thenReturn(cdaTemplate);
        iheActionHelper.handleAction(params);
    }

    @Test
    public void shouldCallSendTemplateMethod() throws IOException, SAXException, ParserConfigurationException, ClassNotFoundException {
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.TEMPLATE_NAME_PARAM, "sampleTemplate3");
        params.put(Constants.RECIPIENT_NAME_PARAM, "sampleRecipient3");

        byte[] bytes;
        try (InputStream inputStream = getClass().getResourceAsStream("/empty_template.xml")) {
            bytes = IOUtils.toByteArray(inputStream);
        }
        Byte[] byteObjects = ArrayUtils.toObject(bytes);

        when(iheTemplateDataService.findByName("sampleTemplate3")).thenReturn(cdaTemplate);
        when(hl7RecipientsService.getRecipientbyName("sampleRecipient3")).thenReturn(hl7Recipient);
        when((Byte[]) iheTemplateDataService.getDetachedField(cdaTemplate, "templateData")).thenReturn(byteObjects);

        iheActionHelper.handleAction(params);

        verify(iheTemplateService).sendTemplateToRecipientUrl(hl7Recipient.getRecipientUrl(), new String(bytes, StandardCharsets.UTF_8));
    }

    @Test
    public void shouldCallSendTemplateWithBasicAuthenticationMethod() throws IOException, SAXException, ParserConfigurationException, ClassNotFoundException {
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.TEMPLATE_NAME_PARAM, "sampleTemplate3");
        params.put(Constants.RECIPIENT_NAME_PARAM, "sampleRecipient3");

        HL7Recipient sampleRecipient = new HL7Recipient("sampleName", "sampleUrl", "sampleUsername", "samplePassword");

        byte[] bytes;
        try (InputStream inputStream = getClass().getResourceAsStream("/empty_template.xml")) {
            bytes = IOUtils.toByteArray(inputStream);
        }
        Byte[] byteObjects = ArrayUtils.toObject(bytes);

        when(iheTemplateDataService.findByName("sampleTemplate3")).thenReturn(cdaTemplate);
        when((Byte[]) iheTemplateDataService.getDetachedField(cdaTemplate, "templateData")).thenReturn(byteObjects);
        when(hl7RecipientsService.getRecipientbyName("sampleRecipient3")).thenReturn(sampleRecipient);

        iheActionHelper.handleAction(params);

        verify(iheTemplateService).sendTemplateToRecipientUrlWithBasicAuthentication(sampleRecipient, new String(bytes, StandardCharsets.UTF_8));
    }
}


text:
import isEqual from 'lodash.isequal';

/* It iterates through each deep nested object and if finds object that has prop and value specified in objToFindBy
 argument, it pushes this object to the result array. When it finishes the walk, it returns the array.
 If none is found, it returns false. */

const findAll = function (tree, childrenKey, objToFindBy) {
  let objToReturn = [];
  function innerFunc(tree, childrenKey, objToFindBy) {
    const findKeys = Object.keys(objToFindBy);
    let findSuccess = false;
    findKeys.forEach((key) => {
      isEqual(tree[key], objToFindBy[key]) ? findSuccess = true : findSuccess = false;
    });
    if (findSuccess) {
      objToReturn.push(tree);
    }
    if (tree.hasOwnProperty(childrenKey)) {
      for (let n of tree[childrenKey]) {
        innerFunc(n, childrenKey, objToFindBy);
      }
    }
  }
  innerFunc(tree, childrenKey, objToFindBy);
  return objToReturn;
};

export default findAll;


text:
DROP TABLE IF EXISTS `schedule`;
CREATE TABLE `schedule` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ident` varchar(999) NOT NULL,
  `departure_airport_icao` varchar(999) NOT NULL,
  `departure_airport_time` varchar(999) NOT NULL,
  `arrival_airport_icao` varchar(999) NOT NULL,
  `arrival_airport_time` varchar(999) NOT NULL,
  `date_added` datetime,
  `date_modified` datetime,
  `date_lastseen` datetime,
  PRIMARY KEY (`id`),
  KEY `id` (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;

ALTER TABLE schedule ADD INDEX identidx (ident);


text:
package com.wxap;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wxap.client.TenpayHttpClient;
import com.wxap.util.MD5Util;
import com.wxap.util.TenpayUtil;

/*
 '΢ÐÅÖ§¸¶·þÎñÆ÷Ç©ÃûÖ§¸¶ÇëÇóÇëÇóÀà
 '============================================================================
 'api˵Ã÷£º
 'init(app_id, app_secret, partner_key, app_key);
 '³õ'»¯º¯Êý£¬Ä¬ÈϸøһЩ²ÎÊý¸³Öµ£¬Èçcmdno,dateµÈ¡£
 'setKey(key_)'ÉèÖÃÉÌ»§ÃÜÔ¿
 'getLasterrCode(),»ñÈ¡×îºó´íÎóºÅ
 'GetToken();»ñÈ¡Token
 'getTokenReal();Token¹ýÆÚºóʵʱ»ñÈ¡Token
 'createMd5Sign(signParams);Éú³ÉMd5Ç©Ãû
 'genPackage(packageParams);»ñÈ¡package°ü
 'createSHA1Sign(signParams);´´½¨Ç©ÃûSHA1
 'sendPrepay(packageParams);Ìá½»Ô¤Ö§¸¶
 'getDebugInfo(),»ñÈ¡debugÐÅÏ¢
 '============================================================================
 '*/
public class RequestHandler {
	/** Token»ñÈ¡Íø¹ØµØÖ·µØÖ· */
	private String tokenUrl;
	/** Ô¤Ö§¸¶Íø¹ØurlµØÖ· */
	private String gateUrl;
	/** ²éѯ֧¸¶Í¨ÖªÍø¹ØURL */
	private String notifyUrl;
	/** ÉÌ»§²ÎÊý */
	private String appid;
	private String appkey;
	private String partnerkey;
	private String appsecret;
	private String key;
	/** ÇëÇóµÄ²ÎÊý */
	private SortedMap parameters;
	/** Token */
	private String Token;
	private String charset;
	/** debugÐÅÏ¢ */
	private String debugInfo;
	private String last_errcode;

	private HttpServletRequest request;

	private HttpServletResponse response;

	/**
	 * ³õ'¹¹Ô캯Êý¡£
	 *
	 * @return
	 */
	public RequestHandler(HttpServletRequest request,
			HttpServletResponse response) {
		this.last_errcode = "0";
		this.request = request;
		this.response = response;
		this.charset = "GBK";
		this.parameters = new TreeMap();
		// ÑéÖ¤notifyÖ§¸¶¶©µ¥Íø¹Ø
		notifyUrl = "https://gw.tenpay.com/gateway/simpleverifynotifyid.xml";

	}

	/**
	 * ³õ'»¯º¯Êý¡£
	 */
	public void init(String app_id, String app_secret, String app_key,
			String partner_key) {
		this.last_errcode = "0";
		this.Token = "token_";
		this.debugInfo = "";
		this.appkey = app_key;
		this.appid = app_id;
		this.partnerkey = partner_key;
		this.appsecret = app_secret;
	}

	public void init() {
	}

	/**
	 * »ñÈ¡×îºó´íÎóºÅ
	 */
	public String getLasterrCode() {
		return last_errcode;
	}

	/**
	 *»ñÈ¡Èë¿ÚµØÖ·,²»°üº¬²ÎÊýÖµ
	 */
	public String getGateUrl() {
		return gateUrl;
	}

	/**
	 * »ñÈ¡²ÎÊýÖµ
	 *
	 * @param parameter
	 *            ²ÎÊýÃû³Æ
	 * @return String
	 */
	public String getParameter(String parameter) {
		String s = (String) this.parameters.get(parameter);
		return (null == s) ? "" : s;
	}

	 //ÉèÖÃÃÜÔ¿

	public void setKey(String key) {
		this.partnerkey = key;
	}
	//ÉèÖÃ΢ÐÅÃÜÔ¿
	public void  setAppKey(String key){
		this.appkey = key;
	}

	// ÌØÊâ×Ö·û´¦Àí
	public String UrlEncode(String src) throws UnsupportedEncodingException {
		return URLEncoder.encode(src, this.charset).replace("+", "%20");
	}

	// »ñÈ¡packageµÄÇ©Ãû°ü
	public String genPackage(SortedMap<String, String> packageParams)
			throws UnsupportedEncodingException {
		String sign = createSign(packageParams);

		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + UrlEncode(v) + "&");
		}

		// È¥µô×îºóÒ»¸ö&
		String packageValue = sb.append("sign=" + sign).toString();
		System.out.println("packageValue=" + packageValue);
		return packageValue;
	}

	/**
	 * ´´½¨md5ÕªÒª,¹æÔòÊÇ:°´²ÎÊýÃû³Æa-zÅÅÐò,Óöµ½¿ÕÖµµÄ²ÎÊý²»²Î¼ÓÇ©Ãû¡£
	 */
	public String createSign(SortedMap<String, String> packageParams) {
		StringBuffer sb = new StringBuffer();
		Set es = packageParams.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k)
					&& !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + this.getKey());
		System.out.println("md5 sb:" + sb);
		String sign = MD5Util.MD5Encode(sb.toString(), this.charset)
				.toUpperCase();

		return sign;

	}
	/**
	 * ´´½¨packageÇ©Ãû
	 */
	public boolean createMd5Sign(String signParams) {
		StringBuffer sb = new StringBuffer();
		Set es = this.parameters.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (!"sign".equals(k) && null != v && !"".equals(v)) {
				sb.append(k + "=" + v + "&");
			}
		}

		// Ëã³öÕªÒª
		String enc = TenpayUtil.getCharacterEncoding(this.request,
				this.response);
		String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

		String tenpaySign = this.getParameter("sign").toLowerCase();

		// debugÐÅÏ¢
		this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:"
				+ tenpaySign);

		return tenpaySign.equals(sign);
	}

    //Êä³öXML
	   public String parseXML() {
		   StringBuffer sb = new StringBuffer();
	       sb.append("<xml>");
	       Set es = this.parameters.entrySet();
	       Iterator it = es.iterator();
	       while(it.hasNext()) {
				Map.Entry entry = (Map.Entry)it.next();
				String k = (String)entry.getKey();
				String v = (String)entry.getValue();
				if(null != v && !"".equals(v) && !"appkey".equals(k)) {

					sb.append("<" + k +">" + getParameter(k) + "</" + k + ">\n");
				}
			}
	       sb.append("</xml>");
			return sb.toString();
		}

	/**
	 * ÉèÖÃdebugÐÅÏ¢
	 */
	protected void setDebugInfo(String debugInfo) {
		this.debugInfo = debugInfo;
	}
	public void setPartnerkey(String partnerkey) {
		this.partnerkey = partnerkey;
	}
	public String getDebugInfo() {
		return debugInfo;
	}
	public String getKey() {
		return key;
	}

}


text:
(function() {
    var customers = getCustomerList();

    var waCustomers = customers.filter(function(c) {
        return c.Region == "WA";
    });

    console.log("Customers from Washington and their orders:");

    waCustomers.forEach(function(customer) {
        console.log("Customer " + customer.CustomerId + ": " + customer.CompanyName);
        customer.Orders.forEach(function(order) {
            console.log("  Order " + order.OrderId + ": " + order.OrderDate);
        });
    });
})();


text:
using System;
using System.Collections.Generic;
using Autofac;
using Tweetinvi.Events;

namespace Tweetinvi.Core.Injectinvi
{
    public interface ITweetinviContainer
    {
        bool IsInitialized { get; }
        List<Action<ContainerBuilder>> RegistrationActions { get; }
        ITwitterClient AssociatedClient { get; set; }
        event EventHandler<TweetinviContainerEventArgs> BeforeRegistrationCompletes;

        void Initialize();

        void RegisterType<TRegistered, TTo>(RegistrationLifetime registrationLifetime = RegistrationLifetime.InstancePerResolve) where TTo : TRegistered;
        void RegisterGeneric(Type sourceType, Type targetType, RegistrationLifetime registrationLifetime = RegistrationLifetime.InstancePerResolve);
        void RegisterInstance(Type targetType, object value);
        void RegisterDecorator<TDecorator, TDecorated>() where TDecorator : TDecorated;
        T Resolve<T>(params IConstructorNamedParameter[] parameters);
    }
}


text:
class D(object):
    def __init__(self, items):
        if isinstance(items, dict):
            self._items = [(k, v) for k, v in items.items()]
        else:
            self._items = items

    def __str__(self):
        return 'D{' + ', '.join('%s:%s' % i for i in self._items) + '}'

    def __repr__(self):
        return 'D([' + ', '.join('(%s, %s)' % i for i in self._items) + '])'

    def __getitem__(self, k):
        val = self.get(k)
        if val is None:
            raise KeyError(str(k))
        return val

    def __len__(self):
        return len(self._items)

    def __iter__(self):
        return iter(self._items)

    def __eq__(self, other):
        if len(self) != len(other):
            return False
        return all([(s == o) for s, o in zip(self._items, other.items())])

    def keys(self):
        return [k for k, v in self._items]

    def values(self):
        return [v for k, v in self._items]

    def items(self):
        return [(k, v) for k, v in self._items]

    def has_key(self, k):
        return k in self.keys()

    def has_value(self, v):
        return v in self.values()

    def has_item(self, item):
        return item in self._items

    def get(self, k, default=None):
        for _k, v in self._items:
            if _k == k:
                return v
        else:
            return default

    def append(self, k, v):
        items = self._items + [(k, v)]
        return D(items)

    def prepend(self, k, v):
        items = [(k, v)] + self._items
        return D(items)

    def insert(self, index, k, v):
        items = self._items[:index] + [(k, v)] + self._items[index:]
        return D(items)

    def transpose(self):
        return D([(v, k) for k, v in self._items])

    def sort(self, cmp=None, key=None, reverse=False):
        return D(sorted(self._items, cmp, key, reverse))

    def reverse(self):
        return self.sort(key=lambda item: item[0], reverse=True)

    def key_sort(self, reverse=False):
        return self.sort(key=lambda item: item[0], reverse=reverse)

    def value_sort(self, reverse=False):
        return self.sort(key=lambda item: item[1], reverse=reverse)

    def map(self, fxn):
        """
        Returns a new underdict, which is the map of the given function over the
        items in the underdict. The function will be passed each key and value,
        and must return the new key and value in a a 2-tuple.
        """
        return D([fxn(k, v) for k, v in self._items])

    def map_values(self, fxn):
        """
        Returns a new underdict, which is the map of the given function over the
        values of the underdict. The function will be passed each key and value,
        and must return a single value.

        This is just a special case of D.map().
        """
        return self.map(lambda k, v: (k, fxn(k, v)))

    def map_keys(self, fxn):
        """
        Returns a new underdict, which is the map of the given function over the
        keys of the underdict. The function will be passed each key and value,
        and must return a single value.

        This is just a special case of D.map().
        """
        return self.map(lambda k, v: (fxn(k, v), v))

    def filter(self, fxn):
        """
        Returns an underdict containing the items for which the passed function
        returns True. The function is passed each key and value.
        """
        return D([(k, v) for k, v in self._items if fxn(k, v)])

    def reduce(self, fxn, initial):
        """
        Applies a 3-argument function successively to the keys and values of the
        underdict ie it computes fxn(...fxn(fxn(initial, k1, v1), k2, v2)...kn, vn)
        """
        val = initial
        for k, v in self._items:
            val = fxn(val, k, v)
        return val

    def reduce_keys(self, fxn, initial):
        return reduce(fxn, self.keys(), initial)

    def reduce_values(self, fxn, initial):
        return reduce(fxn, self.values(), initial)


text:
package com.zundrel.simplyconveyors.client;

import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.PlayerTickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;

import com.zundrel.simplyconveyors.SimplyConveyors;
import com.zundrel.simplyconveyors.api.interfaces.IModifier;
import com.zundrel.simplyconveyors.api.interfaces.IWrenchable;
import com.zundrel.simplyconveyors.client.render.RenderHelper;
import com.zundrel.simplyconveyors.common.blocks.advanced.BlockFlatAdvancedConveyor;
import com.zundrel.simplyconveyors.common.blocks.advanced.BlockInverseAdvancedConveyor;
import com.zundrel.simplyconveyors.common.blocks.modular.BlockFlatModularConveyor;
import com.zundrel.simplyconveyors.common.blocks.modular.BlockInverseModularConveyor;
import com.zundrel.simplyconveyors.common.blocks.tiles.TileModularConveyor;
import com.zundrel.simplyconveyors.common.handlers.ConfigHandler;
import com.zundrel.simplyconveyors.common.helpers.BusStopManager;
import com.zundrel.simplyconveyors.common.info.ModInfo;
import com.zundrel.simplyconveyors.common.items.ItemEntityFilter;
import com.zundrel.simplyconveyors.common.items.ItemWorkerGloves;
import com.zundrel.simplyconveyors.common.items.SimplyConveyorsItems;
import com.zundrel.simplyconveyors.common.items.tracks.ItemSpongeTrack;

@EventBusSubscriber(value = Side.CLIENT, modid = ModInfo.MOD_ID)
public class ClientEventHandler
{
	@SubscribeEvent
	public static void onTooltipEvent(ItemTooltipEvent event) {
		if (event.getItemStack() != ItemStack.EMPTY && event.getItemStack().getItem() instanceof ItemBlock) {
			Block block = Block.getBlockFromItem(event.getItemStack().getItem());

			if (block instanceof BlockFlatAdvancedConveyor || block instanceof BlockInverseAdvancedConveyor) {
				if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
					event.getToolTip().add(TextFormatting.BLUE + "Items can be inserted onto the top of the conveyor as if it was an inventory.");
				} else {
					event.getToolTip().add(TextFormatting.DARK_GRAY + "Press shift for more information...");
				}
			}

			if (block instanceof BlockFlatModularConveyor || block instanceof BlockInverseModularConveyor) {
				if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
					event.getToolTip().add(TextFormatting.BLUE + "Items can be inserted onto the top of the conveyor as if it was an inventory.");
					event.getToolTip().add(TextFormatting.BLUE + "You can place Modules and Special Tracks in the modular conveyor to change it's function.");
				} else {
					event.getToolTip().add(TextFormatting.DARK_GRAY + "Press shift for more information...");
				}
			}

			if (event.getItemStack() != ItemStack.EMPTY && event.getItemStack().getItem() instanceof IModifier) {
				IModifier modifier = (IModifier) event.getItemStack().getItem();

				event.getToolTip().add(modifier.getDescription());
				if (modifier.isConductive()) {
					event.getToolTip().add("This modifier reacts to redstone. Try powering it.");
				}
			}
		}
	}

	@SubscribeEvent
	@SideOnly(Side.CLIENT)
	public static void onRenderGameOverlay(RenderGameOverlayEvent.Post event)
	{
		Minecraft mc = Minecraft.getMinecraft();

		if(mc.player.isSneaking() && ConfigHandler.compass)
		{
			if(event.getType() != ElementType.ALL)
			{
				return;
			}

			GL11.glPushMatrix();

			RenderHelper tessellator = RenderHelper.getInstance();

			int s = 32;
			int s2 = 52;

			GL11.glTranslated(0, 10, 0);

			tessellator.startDrawing(GL11.GL_QUADS);
			{
				GL11.glTranslated((mc.displayWidth - 102.5) / 4, 0, 0);

				mc.renderEngine.bindTexture(new ResourceLocation(ModInfo.MOD_ID + ":" + "textures/gui/compass_directions.png"));

				tessellator.addVertexWithUV(2 + 0, 2 + 0, 0, 0, 0);
				tessellator.addVertexWithUV(2 + 0, 2 + s2, 0, 0, 1);
				tessellator.addVertexWithUV(2 + s2, 2 + s2, 0, 1, 1);
				tessellator.addVertexWithUV(2 + s2, 2 + 0, 0, 1, 0);
			}
			tessellator.draw();

			GL11.glTranslated(-((mc.displayWidth - 102.5) / 4), 0, 0);

			tessellator.startDrawing(GL11.GL_QUADS);
			{
				GL11.glColor4f(1, 1, 1, 1F);
				GL11.glMatrixMode(GL11.GL_MODELVIEW);
				GL11.glTranslated((mc.displayWidth - 62.5) / 4, 8.75, 0);
				GL11.glTranslated(18, 18, 18);
				GL11.glRotated(180, 0, 0, 1);
				GL11.glRotated(mc.player.rotationYaw, 0, 0, 1);
				GL11.glTranslated(-18, -18, -18);

				mc.renderEngine.bindTexture(new ResourceLocation(ModInfo.MOD_ID + ":" + "textures/gui/arrow.png"));

				tessellator.addVertexWithUV(2 + 0, 2 + 0, 0, 0, 0);
				tessellator.addVertexWithUV(2 + 0, 2 + s, 0, 0, 1);
				tessellator.addVertexWithUV(2 + s, 2 + s, 0, 1, 1);
				tessellator.addVertexWithUV(2 + s, 2 + 0, 0, 1, 0);
			}
			tessellator.draw();

			GL11.glPopMatrix();
		}

		if(mc.player.getHeldItemMainhand() != ItemStack.EMPTY && mc.player.getHeldItemMainhand().getItem() instanceof ItemEntityFilter)
		{
			if(event.getType() != ElementType.ALL)
			{
				return;
			}

			int x = 2;
			int y = 2;

			ScaledResolution resolution = new ScaledResolution(mc);

			int offsetY = 0;

			if(!mc.player.capabilities.isCreativeMode)
			{
				offsetY = 14;
			}

			FontRenderer fr = mc.fontRenderer;
			try
			{
				if (mc.player.getHeldItemMainhand().hasTagCompound()) {
					if (!mc.player.getHeldItemMainhand().getTagCompound().getString("filter").equals("net.minecraft.entity.Entity")) {
						fr.drawStringWithShadow(Class.forName(mc.player.getHeldItemMainhand().getTagCompound().getString("filter")).getSimpleName(),
								(resolution.getScaledWidth() / 2) - (fr.getStringWidth(Class.forName(mc.player.getHeldItemMainhand().getTagCompound().getString("filter")).getSimpleName()) / 2),
								resolution.getScaledHeight() - 55 - offsetY, 0xFFFFFF);
					} else {
						fr.drawStringWithShadow("Empty",
								(resolution.getScaledWidth() / 2) - (fr.getStringWidth("Empty") / 2),
								resolution.getScaledHeight() - 55 - offsetY, 0xFFFFFF);
					}
				}
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}

		if(mc.player.getHeldItemOffhand() != ItemStack.EMPTY && mc.player.getHeldItemOffhand().getItem() instanceof ItemEntityFilter)
		{
			if(event.getType() != ElementType.ALL)
			{
				return;
			}

			int x = 2;
			int y = 2;

			ScaledResolution resolution = new ScaledResolution(mc);

			int offsetY = 0;

			if(!mc.player.capabilities.isCreativeMode)
			{
				offsetY = 15;
			}

			FontRenderer fr = mc.fontRenderer;
			try
			{
				if (!mc.player.getHeldItemOffhand().getTagCompound().getString("filter").equals("net.minecraft.entity.Entity")) {
					fr.drawStringWithShadow(Class.forName(mc.player.getHeldItemOffhand().getTagCompound().getString("filter")).getSimpleName(),
							(resolution.getScaledWidth() / 2) - (fr.getStringWidth(Class.forName(mc.player.getHeldItemOffhand().getTagCompound().getString("filter")).getSimpleName()) / 2),
							resolution.getScaledHeight() - 34 - offsetY, 0xFFFFFF);
				} else {
					fr.drawStringWithShadow("Empty",
							(resolution.getScaledWidth() / 2) - (fr.getStringWidth("Empty") / 2),
							resolution.getScaledHeight() - 34 - offsetY, 0xFFFFFF);
				}
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}
	}
}


text:
class CreateSections < ActiveRecord::Migration[5.1]
  def change
    create_table :sections do |t|
      t.string :name
      t.text :discription

      t.timestamps
    end
  end
end


text:
\subsection{Participants}

Everyone

\subsection{Agenda}

Still missing hardware.

\subsection{Additional Information}

Due to a mixup, the hardware haven't been sent from the place it was ordered. It should now be on its way, available to us during this week.

\subsection{To do}

Fix the report, so it's ready for the hand in next week. See the todo for monday 16th document.


text:
package cn.ytxu.http_wrapper.config.property.api_data;

import java.util.Objects;

/**
 * api_data数据文件的多操作系统配置
 */
public class ApiDataFilePathInfoBean {
    private String os_name;
    private String path;
    private String path_type;// private path type, API数据文件的地址类型(ApiDataFilePathType):现在有file与url两种

    public String getOSName() {
        return os_name;
    }

    public String getPath() {
        return path;
    }

    public String getPathType() {
        return path_type;
    }

    public boolean hasPrivatePathType() {
        return Objects.nonNull(path_type);
    }
}


text:
<?php

/**
 * This file is part of the Nextras community extensions of Nette Framework
 *
 * @license    New BSD License
 * @link       https://github.com/nextras/migrations
 */

namespace Nextras\Migrations\Entities;

use DateTime;

/**
 * @author Petr Procházka
 * @author Jan Tvrdík
 */
class Migration
{
	/** @var int */
	public $id;

	/** @var string */
	public $group;

	/** @var string */
	public $filename;

	/** @var string */
	public $checksum;

	/** @var DateTime */
	public $executedAt;

	/** @var bool */
	public $completed;

}


text:
/*
 @param {Object} object: Any object you want to tween. For example: PIXI.Sprite
 @param {String} property: the property which needs to be changed. Use "property.property.property..." if the property is little deeper. Pass "" to create a Wait-Tween
 @param {float} value: targetValue of tweening
 @param {int} frames: duration of the tween in frames.
 @param {boolean} autostart: starting when created? Set to false if you use it with ChainedTween

 use examples:
 new Tween(sprite, "position.x", 100, 60, true);
 new Tween(sprite.position, "x", 100, 60, true);

 */
function Tween(object, property, value, frames, autostart){
    this.object = object;

    var properties = property.split(".");
    this.property = properties[properties.length-1];
    for(var i=0;i<properties.length -1; i++){
        this.object = this.object[properties[i]]
    }

    this.targetValue = value;
    this.startValue;
    this.active = autostart;
    this.currentFrame = 0;
    this.endFrame = frames;
    this.onComplete;
    this.onCompleteParams;
    this.easing = Tween.noEase;

    Tween.tweens.push(this);
}

Tween.prototype.setOnComplete = function(callback, parameters){
    this.onComplete = callback;
    this.onCompleteParams = parameters;
}

Tween.prototype.start = function(){
    this.active = true;
}

Tween.prototype.initIterations = function(){
    if(this.property != ""){
        this.startValue = this.object[this.property];
        this.targetValue = this.targetValue - this.object[this.property];
    }
}

Tween.prototype.update = function(){
    if(!this.active){
        return false;
    }
    if(this.currentFrame == 0){
        this.initIterations();
    }
    this.currentFrame ++;
    if(this.currentFrame <= this.endFrame){
        if(this.property != ""){
            var oldValue = this.object[this.property];
            var newValue = this.easing(this.currentFrame, this.startValue, this.targetValue, this.endFrame);
            this.object[this.property] = newValue;
        }
        return false;
    }else{
        this.active = false;
        if(this.onComplete != null){
            this.onComplete(this.onCompleteParams);

        }
        return true;
    }
}

Tween.tweens = [];
// Call this every Frame of your Game/Application to keep the tweens running.
Tween.runTweens = function(){
    for(var i=0;i < Tween.tweens.length;i++){
        var tween = Tween.tweens[i];
        if(tween.update()){
            var index = Tween.tweens.indexOf(tween);
            if(index != -1){
                Tween.tweens.splice(index, 1);
            }
            i--;
        }
    }
};

// EASING
// use example:
// var tween = new Tween(sprite, "alpha", 0, 60, true);
// tween.easing = Tween.outElastic;

Tween.noEase = function(t, b, c, d) {
    t/=d;
    return b+c*(t);
}

Tween.outElastic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(33*tc*ts + -106*ts*ts + 126*tc + -67*ts + 15*t);
}

Tween.inElastic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(56*tc*ts + -105*ts*ts + 60*tc + -10*ts);
}

Tween.inOutQuintic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(6*tc*ts + -15*ts*ts + 10*tc);
}

Tween.inQuintic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(tc*ts);
}

Tween.outQuintic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(tc*ts + -5*ts*ts + 10*tc + -10*ts + 5*t);
}

Tween.inCubic = function(t, b, c, d) {
    var tc=(t/=d)*t*t;
    return b+c*(tc);
}

Tween.inOutCubic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(-2*tc + 3*ts);
}

Tween.outCubic = function(t, b, c, d) {
    var ts=(t/=d)*t;
    var tc=ts*t;
    return b+c*(tc + -3*ts + 3*t);
}

// CHAINED TWEEN

/*
 @param {Array} tweens: Array of Tweens.

 example:
 var tween1 = new Tween(sprite, "position.x", 100, 60, false);
 var tween2 = new Tween(sprite, "position.x", 0, 60, false);
 new ChainedTween([tween1, tween2]);
 */
function ChainedTween(tweens){
    this.tweens = tweens;
    Tween.tweens.push(this);
}

ChainedTween.prototype.update = function(){
    if(this.tweens.length == 0){
        return true;
    }
    var currentTween = this.tweens[0];
    if(!currentTween.active){
        currentTween.start();
    }
    var finished = currentTween.update();
    if(finished){
        this.tweens.splice(0,1);
    }
    return false;
}

// TODO: COMBINED TWEEN
function CombinedTween(tweens){
}

CombinedTween.prototype.start = function(){
}

CombinedTween.prototype.update = function(){
}


text:
using UnityEngine;
using System.Collections;

public class PlaqueCursor : MonoBehaviour {
	public GameObject cursor;
	public string myGroup;
	// Use this for initialization
	void Start () {
		myGroup = PlayerPrefs.GetString("Group");
	}

	// Update is called once per frame
	void Update () {
		RaycastHit hit;
		if(Camera.main!=null)
		{
			if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
			{
				if(hit.transform.tag=="plaque") //the plaques will only be tagged if I am in the correct group already
				{
					if(!Test.isHitting)
					{
						cursor.SendMessage("ShowPlaqueCursor", true);
					}
				}
				else
				{
					cursor.SendMessage("ShowPlaqueCursor", false);
				}
			}
			else
			{
				cursor.SendMessage("ShowPlaqueCursor", false);
			}
		}
	}
}