text:
package org.apache.druid.msq.exec;

import com.google.common.util.concurrent.ListenableFuture;
import org.apache.druid.frame.key.ClusterBy;
import org.apache.druid.frame.key.ClusterByPartition;
import org.apache.druid.frame.key.ClusterByPartitions;
import org.apache.druid.java.util.common.Either;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.msq.kernel.StageDefinition;
import org.apache.druid.msq.statistics.ClusterByStatisticsCollector;
import org.apache.druid.msq.statistics.ClusterByStatisticsSnapshot;
import org.apache.druid.msq.statistics.CompleteKeyStatisticsInformation;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * Queues up fetching sketches from workers and progressively generates partitions boundaries.
 */
public class WorkerSketchFetcher
{
  private static final Logger log = new Logger(WorkerSketchFetcher.class);
  private static final int DEFAULT_THREAD_COUNT = 4;
  // If the combined size of worker sketches is more than this threshold, SEQUENTIAL merging mode is used.
  static final long BYTES_THRESHOLD = 1_000_000_000L;
  // If there are more workers than this threshold, SEQUENTIAL merging mode is used.
  static final long WORKER_THRESHOLD = 100;

  private final ClusterStatisticsMergeMode clusterStatisticsMergeMode;
  private final int statisticsMaxRetainedBytes;
  private final WorkerClient workerClient;
  private final ExecutorService executorService;

  public WorkerSketchFetcher(WorkerClient workerClient, ClusterStatisticsMergeMode clusterStatisticsMergeMode, int statisticsMaxRetainedBytes)
  {
    this.workerClient = workerClient;
    this.clusterStatisticsMergeMode = clusterStatisticsMergeMode;
    this.executorService = Executors.newFixedThreadPool(DEFAULT_THREAD_COUNT);
    this.statisticsMaxRetainedBytes = statisticsMaxRetainedBytes;
  }

  /**
   * Submits a request to fetch and generate partitions for the given worker statistics and returns a future for it. It
   * decides based on the statistics if it should fetch sketches one by one or together.
   */
  public CompletableFuture<Either<Long, ClusterByPartitions>> submitFetcherTask(
      CompleteKeyStatisticsInformation completeKeyStatisticsInformation,
      List<String> workerTaskIds,
      StageDefinition stageDefinition
  )
  {
    ClusterBy clusterBy = stageDefinition.getClusterBy();

    switch (clusterStatisticsMergeMode) {
      case SEQUENTIAL:
        return sequentialTimeChunkMerging(completeKeyStatisticsInformation, stageDefinition, workerTaskIds);
      case PARALLEL:
        return inMemoryFullSketchMerging(stageDefinition, workerTaskIds);
      case AUTO:
        if (clusterBy.getBucketByCount() == 0) {
          log.debug("Query [%s] AUTO mode: chose PARALLEL mode to merge key statistics", stageDefinition.getId().getQueryId());
          // If there is no time clustering, there is no scope for sequential merge
          return inMemoryFullSketchMerging(stageDefinition, workerTaskIds);
        } else if (stageDefinition.getMaxWorkerCount() > WORKER_THRESHOLD || completeKeyStatisticsInformation.getBytesRetained() > BYTES_THRESHOLD) {
          log.debug("Query [%s] AUTO mode: chose SEQUENTIAL mode to merge key statistics", stageDefinition.getId().getQueryId());
          return sequentialTimeChunkMerging(completeKeyStatisticsInformation, stageDefinition, workerTaskIds);
        }
        log.debug("Query [%s] AUTO mode: chose PARALLEL mode to merge key statistics", stageDefinition.getId().getQueryId());
        return inMemoryFullSketchMerging(stageDefinition, workerTaskIds);
      default:
        throw new IllegalStateException("No fetching strategy found for mode: " + clusterStatisticsMergeMode);
    }
  }

  /**
   * Fetches the full {@link ClusterByStatisticsCollector} from all workers and generates partition boundaries from them.
   * This is faster than fetching them timechunk by timechunk but the collector will be downsampled till it can fit
   * on the controller, resulting in less accurate partition boundries.
   */
  CompletableFuture<Either<Long, ClusterByPartitions>> inMemoryFullSketchMerging(
      StageDefinition stageDefinition,
      List<String> workerTaskIds
  )
  {
    CompletableFuture<Either<Long, ClusterByPartitions>> partitionFuture = new CompletableFuture<>();

    // Create a new key statistics collector to merge worker sketches into
    final ClusterByStatisticsCollector mergedStatisticsCollector =
        stageDefinition.createResultKeyStatisticsCollector(statisticsMaxRetainedBytes);
    final int workerCount = workerTaskIds.size();
    // Guarded by synchronized mergedStatisticsCollector
    final Set<Integer> finishedWorkers = new HashSet<>();

    // Submit a task for each worker to fetch statistics
    IntStream.range(0, workerCount).forEach(workerNo -> {
      executorService.submit(() -> {
        ListenableFuture<ClusterByStatisticsSnapshot> snapshotFuture =
            workerClient.fetchClusterByStatisticsSnapshot(
                workerTaskIds.get(workerNo),
                stageDefinition.getId().getQueryId(),
                stageDefinition.getStageNumber()
            );
        partitionFuture.whenComplete((result, exception) -> {
          if (exception != null || (result != null && result.isError())) {
            snapshotFuture.cancel(true);
          }
        });

        try {
          ClusterByStatisticsSnapshot clusterByStatisticsSnapshot = snapshotFuture.get();
          if (clusterByStatisticsSnapshot == null) {
            throw new ISE("Worker %s returned null sketch, this should never happen", workerNo);
          }
          synchronized (mergedStatisticsCollector) {
            mergedStatisticsCollector.addAll(clusterByStatisticsSnapshot);
            finishedWorkers.add(workerNo);

            if (finishedWorkers.size() == workerCount) {
              log.debug("Query [%s] Received all statistics, generating partitions", stageDefinition.getId().getQueryId());
              partitionFuture.complete(stageDefinition.generatePartitionsForShuffle(mergedStatisticsCollector));
            }
          }
        }
        catch (Exception e) {
          synchronized (mergedStatisticsCollector) {
            partitionFuture.completeExceptionally(e);
            mergedStatisticsCollector.clear();
          }
        }
      });
    });
    return partitionFuture;
  }

  /**
   * Fetches cluster statistics from all workers and generates partition boundaries from them one time chunk at a time.
   * This takes longer due to the overhead of fetching sketches, however, this prevents any loss in accuracy from
   * downsampling on the controller.
   */
  CompletableFuture<Either<Long, ClusterByPartitions>> sequentialTimeChunkMerging(
      CompleteKeyStatisticsInformation completeKeyStatisticsInformation,
      StageDefinition stageDefinition,
      List<String> workerTaskIds
  )
  {
    SequentialFetchStage sequentialFetchStage = new SequentialFetchStage(
        stageDefinition,
        workerTaskIds,
        completeKeyStatisticsInformation.getTimeSegmentVsWorkerMap().entrySet().iterator()
    );
    sequentialFetchStage.submitFetchingTasksForNextTimeChunk();
    return sequentialFetchStage.getPartitionFuture();
  }

  private class SequentialFetchStage
  {
    private final StageDefinition stageDefinition;
    private final List<String> workerTaskIds;
    private final Iterator<Map.Entry<Long, Set<Integer>>> timeSegmentVsWorkerIdIterator;
    private final CompletableFuture<Either<Long, ClusterByPartitions>> partitionFuture;
    // Final sorted list of partition boundaries. This is appended to after statistics for each time chunk are gathered.
    private final List<ClusterByPartition> finalPartitionBoundries;

    public SequentialFetchStage(
        StageDefinition stageDefinition,
        List<String> workerTaskIds,
        Iterator<Map.Entry<Long, Set<Integer>>> timeSegmentVsWorkerIdIterator
    )
    {
      this.finalPartitionBoundries = new ArrayList<>();
      this.stageDefinition = stageDefinition;
      this.workerTaskIds = workerTaskIds;
      this.timeSegmentVsWorkerIdIterator = timeSegmentVsWorkerIdIterator;
      this.partitionFuture = new CompletableFuture<>();
    }

    /**
     * Submits the tasks to fetch key statistics for the time chunk pointed to by {@link #timeSegmentVsWorkerIdIterator}.
     * Once the statistics have been gathered from all workers which have them, generates partitions and adds it to
     * {@link #finalPartitionBoundries}, stiching the partitions between time chunks using
     * {@link #abutAndAppendPartitionBoundries(List, List)} to make them continuous.
     *
     * The time chunks returned by {@link #timeSegmentVsWorkerIdIterator} should be in ascending order for the partitions
     * to be generated correctly.
     *
     * If {@link #timeSegmentVsWorkerIdIterator} doesn't have any more values, assumes that partition boundaries have
     * been successfully generated and completes {@link #partitionFuture} with the result.
     *
     * Completes the future with an error as soon as the number of partitions exceed max partition count for the stage
     * definition.
     */
    public void submitFetchingTasksForNextTimeChunk()
    {
      if (!timeSegmentVsWorkerIdIterator.hasNext()) {
        partitionFuture.complete(Either.value(new ClusterByPartitions(finalPartitionBoundries)));
      } else {
        Map.Entry<Long, Set<Integer>> entry = timeSegmentVsWorkerIdIterator.next();
        // Time chunk for which partition boundries are going to be generated for
        Long timeChunk = entry.getKey();
        Set<Integer> workerIdsWithTimeChunk = entry.getValue();
        // Create a new key statistics collector to merge worker sketches into
        ClusterByStatisticsCollector mergedStatisticsCollector =
            stageDefinition.createResultKeyStatisticsCollector(statisticsMaxRetainedBytes);
        // Guarded by synchronized mergedStatisticsCollector
        Set<Integer> finishedWorkers = new HashSet<>();

        log.debug("Query [%s]. Submitting request for statistics for time chunk %s to %s workers",
                  stageDefinition.getId().getQueryId(),
                  timeChunk,
                  workerIdsWithTimeChunk.size());

        // Submits a task for every worker which has a certain time chunk
        for (int workerNo : workerIdsWithTimeChunk) {
          executorService.submit(() -> {
            ListenableFuture<ClusterByStatisticsSnapshot> snapshotFuture =
                workerClient.fetchClusterByStatisticsSnapshotForTimeChunk(
                    workerTaskIds.get(workerNo),
                    stageDefinition.getId().getQueryId(),
                    stageDefinition.getStageNumber(),
                    timeChunk
                );
            partitionFuture.whenComplete((result, exception) -> {
              if (exception != null || (result != null && result.isError())) {
                snapshotFuture.cancel(true);
              }
            });

            try {
              ClusterByStatisticsSnapshot snapshotForTimeChunk = snapshotFuture.get();
              if (snapshotForTimeChunk == null) {
                throw new ISE("Worker %s returned null sketch for %s, this should never happen", workerNo, timeChunk);
              }
              synchronized (mergedStatisticsCollector) {
                mergedStatisticsCollector.addAll(snapshotForTimeChunk);
                finishedWorkers.add(workerNo);

                if (finishedWorkers.size() == workerIdsWithTimeChunk.size()) {
                  Either<Long, ClusterByPartitions> longClusterByPartitionsEither =
                      stageDefinition.generatePartitionsForShuffle(mergedStatisticsCollector);

                  log.debug("Query [%s]. Received all statistics for time chunk %s, generating partitions",
                            stageDefinition.getId().getQueryId(),
                            timeChunk);

                  long totalPartitionCount = finalPartitionBoundries.size() + getPartitionCountFromEither(longClusterByPartitionsEither);
                  if (totalPartitionCount > stageDefinition.getMaxPartitionCount()) {
                    // Fail fast if more partitions than the maximum have been reached.
                    partitionFuture.complete(Either.error(totalPartitionCount));
                    mergedStatisticsCollector.clear();
                  } else {
                    List<ClusterByPartition> timeSketchPartitions = longClusterByPartitionsEither.valueOrThrow().ranges();
                    abutAndAppendPartitionBoundries(finalPartitionBoundries, timeSketchPartitions);
                    log.debug("Query [%s]. Finished generating partitions for time chunk %s, total count so far %s",
                              stageDefinition.getId().getQueryId(),
                              timeChunk,
                              finalPartitionBoundries.size());
                    submitFetchingTasksForNextTimeChunk();
                  }
                }
              }
            }
            catch (Exception e) {
              synchronized (mergedStatisticsCollector) {
                partitionFuture.completeExceptionally(e);
                mergedStatisticsCollector.clear();
              }
            }
          });
        }
      }
    }

    /**
     * Takes a list of sorted {@link ClusterByPartitions} {@param timeSketchPartitions} and adds it to a sorted list
     * {@param finalPartitionBoundries}. If {@param finalPartitionBoundries} is not empty, the end time of the last
     * partition of {@param finalPartitionBoundries} is changed to abut with the starting time of the first partition
     * of {@param timeSketchPartitions}.
     *
     * This is used to make the partitions generated continuous.
     */
    private void abutAndAppendPartitionBoundries(
        List<ClusterByPartition> finalPartitionBoundries,
        List<ClusterByPartition> timeSketchPartitions
    )
    {
      if (!finalPartitionBoundries.isEmpty()) {
        // Stitch up the end time of the last partition with the start time of the first partition.
        ClusterByPartition clusterByPartition = finalPartitionBoundries.remove(finalPartitionBoundries.size() - 1);
        finalPartitionBoundries.add(new ClusterByPartition(clusterByPartition.getStart(), timeSketchPartitions.get(0).getStart()));
      }
      finalPartitionBoundries.addAll(timeSketchPartitions);
    }

    public CompletableFuture<Either<Long, ClusterByPartitions>> getPartitionFuture()
    {
      return partitionFuture;
    }
  }

  /**
   * Gets the partition size from an {@link Either}. If it is an error, the long denotes the number of partitions
   * (in the case of creating too many partitions), otherwise checks the size of the list.
   */
  private static long getPartitionCountFromEither(Either<Long, ClusterByPartitions> either)
  {
    if (either.isError()) {
      return either.error();
    } else {
      return either.valueOrThrow().size();
    }
  }
}


text:
FROM dockerfile/java

# that's me!
MAINTAINER Adam Warski, adam@warski.org

# we need this because the workdir is modified in dockerfile/java
WORKDIR /

# run the (java) server as the daemon user
USER daemon

# copy the locally built fat-jar to the image
ADD target/scala-2.11/docker-spray-example-assembly-1.0.jar /app/server.jar

# run the server when a container based on this image is being run
ENTRYPOINT [ "java", "-jar", "/app/server.jar" ]

# the server binds to 8080 - expose that port
EXPOSE 8080

redpajama_set_name: RedPajamaGithub


text:
title: PhoneGap Day US Videos
date: 2012-08-28 00:00:00 Z
tags:
- PhoneGap Day
- Video
author: Steve Gill
format: html
---

[PhoneGap Day US](http://pgday.phonegap.com/us2012/) was a huge success thanks to all of the speakers and attendees. To not lose the memory of this great event, we decided to film all of the sessions and have decided to release those videos for free to our wonderful community!

We will be releasing some videos every few days leading up to [PhoneGap Day EU](http://pgday.phonegap.com/eu2012/) happening on September 14th in Amsterdam. Our first release includes the opening remarks at PhoneGap Day US by [Andre Charland](https://twitter.com/AndreCharland) and an overview of the mobile web landscape by [Matt Kelly](https://twitter.com/mattwkelly). You can view the videos below or by going to our [Youtube Page](http://youtube.com/phonegap).

{% include video.html id="BxVNm50dpfQ" %}

{% include video.html id="MDkb_D-37LU" %}

You can view all the slides from PhoneGap Day US over on [Github](https://gist.github.com/3165756).

Thank you again to everyone who attended PhoneGap Day US and a big thank you to our PhoneGap Day sponsors: [Intel](http://intel.com), [Breaking Development](http://bdconf.com), [OneTok](http://onetok.com) and [AT&T Developer Program](https://developer.att.com/htmlPackages/ATT_Speech_API/index.html?sid=36485). We appreciate your commitment to supporting PhoneGap and the developer community.


text:
[![Build Status](https://secure.travis-ci.org/papabricole/EggDuino.png)](http://travis-ci.org/papabricole/EggDuino)

Eggduino
========

Arduino Firmware for Eggbot / Spherebot with Inkscape-Integration

Forked and heavily modified from https://github.com/cocktailyogi/EggDuino.

The aim of this fork is to allow hackers to easily add their own hardware/tweaks.

# Build the firmware

## Using Arduino IDE

    - Click the github 'Clone or Download' button, then 'Download ZIP'
    - Extract the ZIP
    - Rename the extracted folder into 'EggDuino'
    - Open 'EggDuino.ino' using the Arduino IDE
    - Install the 'VarSpeedServo' library
    - Build & upload firmware

## Using Platformio

    - Click the github 'Clone or Download' button, then 'Download ZIP'
    - Extract the ZIP
    - Build: 'platformio run'
    - Upload firmware: 'platformio run --target upload'

# Default Implementation

The default implementation 'EBBHardware' is designed for:

    - arduino nano + cnc shield or similar
    - optional: autoreset disabled (See Troubleshooting section)
    - 2x A4988, 1/16 microstepping stepper motor driver
    - 2x nema 17 stepper motors for the rotation and pen axes
    - 1x standard rc micro servo for the pen up/down
    - 3x optional buttons (abort, toggle pen up/down, enable motors)

If your hardware is based on similar specs, you just need to edit 'config.h' and check
the Arduino pin assignments.

# Setup the Inkscape plugin

    - Install Inkscape 0.91 (0.92 has no cancel buttons)
    - Install the Eggbot extension:

      http://wiki.evilmadscientist.com/Installing_software

    - The Eggduino cannot be detected by default, but we can fix it on our own:
        - Go to your Inkscape-Installationfolder and navigate to subfolder .\App\Inkscape\share\extensions
        - Open File "ebb_serial.py" in a texteditor
        - In the 'findPort()' function, search the line:

            "if port[2].startswith("USB VID:PID=04D8:FD92"):"

        - Replace "04D8:FD92" by your arduino VID:PID usb identifier (e.g arduino nano clone "USB VID:PID=1A86:7523")
        - In the 'testPort()' function, search the line:

            serialPort = serial.Serial( comPort, timeout=1.0 ) # 1 second timeout!

        - Replace "timeout=1.0" by "timeout=2.0"
        - Save the file.

# Software Overview

The main file is EBBParser: it's a c++ interface responsible for parsing the 'EBB EggBot' protocol and
dispatch the work to different functions. Alone, it does nothing and should not need any modification.

The real work is done in the derived class EBBHardware: it implement the necessary functions declared
in EBBParser. The list of functions you need to implement are declared in 'EBBParser.h'.
The one ending with '= 0' (virtual pure) are mandatory and generates compilation errors if not implemented, the
one without are optional, depends only on what features you are interested in.

MyEggDuino.h: This minimal implementation does nothing.

    #include "EBBParser.h"

    class MyEggDuino : public EBBParser {
    public:
        MyEggDuino(Stream& stream);

        virtual void enableMotor(int axis, bool state)
        {
        }

        virtual void stepperMove(int duration, int numPenSteps, int numRotSteps)
        {
        }

        virtual void setPenState(bool up, short delayMs)
        {
        }

        virtual bool getPenState()
        {
            return true;
        }

        virtual void setPenUpPos(int percent)
        {
        }

        virtual void setPenDownPos(int percent)
        {
        }

        virtual void setServoRateUp(int percentPerSecond)
        {
        }

        virtual void setServoRateDown(int percentPerSecond)
        {
        }

        virtual bool getPrgButtonState()
        {
            return false;
        }

        virtual void setPinOutput(char port, int pin, int value)
        {
        }

        virtual void setEngraverState(bool state, int power)
        {
        }
    };

EggDuino.ino

    #include "MyEggDuino.h"

    MyEggDuino ebb(Serial);

    void setup()
    {
        Serial.begin(9600);
        ebb.init();
    }

    void loop()
    {
        ebb.processEvents();
    }

# Troubleshooting

The arduino is auto reset when a serial communication is initialized. This is an
Arduino feature for automatic firmware upload.
This is a problem since the EggBot inkscape plugin sometime re-initialize the serial communication,
breaking the current paint job.
To prevent this autoreset, you need to solder a 10uF capacitor between RST and GND pin of the arduino,
or google 'Disabling Auto Reset On Serial Connection' for alternatives.


text:
require 'rubygems'
require 'bundler/setup'

# Setup logging
require 'rjack-logback'
RJack::Logback.config_console( :stderr => true, :thread => true )
RJack::Logback.root.level = RJack::Logback::DEBUG if ENV['DEBUG_LOG']

# All dependencies for testing.
require 'yaml'
require 'net/http'
require 'openssl'
require 'rack/urlmap'
require 'rack/lint'
require 'fishwife'

Thread.abort_on_exception = true

# Adjust Rack::Lint to not interfere with File body.to_path
class Rack::Lint

  def respond_to?( mth )
    if mth == :to_path
      @body.respond_to?( :to_path )
    else
      super
    end
  end

  def to_path
    @body.to_path
  end

end

RSpec.configure do |cfg|
  cfg.expect_with(:rspec) { |c| c.syntax = :should }
  cfg.mock_with(:rspec) { |m| m.syntax = :should }
end


text:
[![NPM](https://nodei.co/npm/vuedeux.png?compact=true)](https://npmjs.org/package/vuedeux)

# vuedeux

![Alt Text](https://github.com/dmrx/vuedoo/raw/master/examples/TodoMVC/assets/vuedeuxsmall.png)

## Full Documentation
https://vueduex.gitbooks.io/vuedeux-documentation/content/

## Synopsis

Vuedeux is a lightweight open-source utility layer for binding Vuex to Redux in a way that allows developers to re-use their pre-existing Redux stores.

## Motivation
Vuedeux answers our team's desire to create a simple way to re-use and share state-management code with Vue/Vuex. The decision to create the Vuedeux compatibility layer between Vuex and Redux was inspired by the idea of uniting the quickly growing Vue community and Redux's broad user-base and ecosystem.

We love Vue & Vuex. We love the elegance and the tight integration. We love Redux. We love that it is framework agnostic and has a robust ecosystem of tools, middlewares, and bindings.

We wanted to make them work together in a developer-friendly and highly customizable way to encourage interoperability and streamline reusability of code bases.

Vuedeux allows Redux developers to feel at home in Vue while providing all the conveniences and efficiencies of Vuex.

## How It Works
The Vuedeux Plugin Creator takes your Redux action types and Redux store, and then maps your Redux state and all associated actions to a Vuex module with equivalent actions and mutations, allowing you to easily reuse your existing Redux state store and dispatch to Vuex just like you would with Redux.

## Prerequisites
Redux, Vue, Vuex

## FIRING UP A SIMPLE VUEDEUX EXAMPLE - TODO MVC
Fork and clone down a copy of this repository, and navigate to the directory within your terminal.

To download and install all dependencies

run:
```
 npm install
 ```

Start up the dev server
```
npm start
```

You should now be able to navigate to http://localhost:8080/ to demo the app.

The architecture of this classic TODO MVC app can be found in the examples folder and offers a simple example of the Vuedeux data flow from VueX to Redux and back.

## Installation
```
npm install vuedeux
```
## Getting Started
In this section we will be breaking down how to get started with the Vuedeux Plugin Creator.

The Vuedeux plugin initiates a Vuex module and maps all actions between the newly created Vuex module and Redux. It also keeps our Redux store and our Vuex 'Redux' module in sync.

### Importing the dependencies
```
import vdxPluginCreator from 'vuedeux';
import reduxStore from './reduxstore';
import * as reduxActionTypes from './actions/reduxactiontypes';
```
The dependencies for the Vuedeux plugin are:
* Vuedeux package
* Your Redux store
* Your Action Type CONSTANTS

It is common convention in Flux and Redux to identify your Action Types using Constants and group them together in their own file (as seen below) . Vuedeux relies on this convention in order to accurately map your Redux Action types to Vuex actions and mutations.

The PluginCreators expects your Action Type Constants in an object.
```
import * as reduxActionTypes from './actions/reduxactiontypes';
```
The following Node import statement is an easy way for you to create an action type object from your action types.
```
// ReduxActionTypes.js

export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO'
export const EDIT_TODO = 'EDIT_TODO'
export const COMPLETE_TODO = 'COMPLETE_TODO'
export const COMPLETE_ALL = 'COMPLETE_ALL'
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED'
```
### Generating the plugin
```
const vdx = vdxPluginCreator(reduxStore, reduxActionTypes);
```
Again, you may call the plugin anything you wish. Above we are calling our plugin 'vdx' for simplicty.

### Inserting the plugin into a Vuex Store
```
const store = new Vuex.Store({
state,
mutations,
plugins: [vdx],
});
```
To add the plugin simply place the plugin into the plugin option of your Vuex store.

All the existing mutations, actions , getters, even existing plugin you utilize in an existing Vuex state will be unaffected.

### Putting it all together
```
//vuex.js

import Vue from 'vue';
import Vuex from 'vuex';
import { state, mutations } from './mutations';

import vdxPluginCreator from 'vuedeux';
import reduxStore from './reduxstore';
import * as reduxActionTypes from './actions/reduxactiontypes';

// Make sure to call Vue.use(Vuex) first if you're using a Vue module build system
Vue.use(Vuex);

const vdx = vdxPluginCreator(reduxStore, reduxActionTypes);

const store = new Vuex.Store({
state,
mutations,
plugins: [vdx, localStoragePlugin],
});

export default store;
```

### Your new Vuex Structure
* VUEX STORE ($store in child components)
  * STATE ($store.state)
    * REDUX --- ($store.state.redux)
      * (Your existing Redux Store)

## Contributers
Nikol Marentes, David Marx, & Brian Rudloff


text:
layout: post
date: '2015-12-14'
title: "Graduation Dresses Sheath V-Neck Split Front Elastic Satin Long Red Party Dress"
category: Graduation Dresses
tags: [Graduation Dresses]
---
### Graduation Dresses Sheath V-Neck Split Front Elastic Satin Long Red Party Dress
Just **$198.99**
###

Buy it: [https://www.readybrides.com/en/graduation-dresses/17507-sheath-v-neck-split-front-elastic-satin-long-red-party-dress.html](https://www.readybrides.com/en/graduation-dresses/17507-sheath-v-neck-split-front-elastic-satin-long-red-party-dress.html)


text:
function render() {
  elementOpen("root");
  elementOpen("ul");
  elementOpen("li");
  text("test");
  elementClose("li");
  elementClose("ul");
  return elementClose("root");
}


text:
import pytest

import apistar
from apistar import validators
from apistar.exceptions import (
    ErrorMessage, ParseError, Position, ValidationError
)

def test_valid_json():
    apistar.parse('{"abc": "def"}', encoding='json')

def test_invalid_base_format():
    with pytest.raises(ValueError):
        apistar.parse('{"abc": "def"}', encoding='xyz')

def test_empty_string():
    with pytest.raises(ParseError) as exc:
        apistar.parse(b'', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text='No content.',
            code='parse_error',
            position=Position(line_no=1, column_no=1, index=0)
        )
    ]

def test_object_missing_property_name():
    with pytest.raises(ParseError) as exc:
        apistar.parse('{', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text='Expecting property name enclosed in double quotes.',
            code='parse_error',
            position=Position(line_no=1, column_no=2, index=1)
        )
    ]

def test_object_missing_colon_delimiter():
    with pytest.raises(ParseError) as exc:
        apistar.parse('{"abc"', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Expecting ':' delimiter.",
            code='parse_error',
            position=Position(line_no=1, column_no=7, index=6)
        )
    ]

def test_object_missing_comma_delimiter():
    with pytest.raises(ParseError) as exc:
        apistar.parse('{"abc": "def" 1', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Expecting ',' delimiter.",
            code='parse_error',
            position=Position(line_no=1, column_no=15, index=14)
        )
    ]

def test_object_invalid_property_name():
    with pytest.raises(ParseError) as exc:
        apistar.parse('{"abc": "def", 1', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Expecting property name enclosed in double quotes.",
            code='parse_error',
            position=Position(line_no=1, column_no=16, index=15)
        )
    ]

def test_object_unterminated_after_key():
    with pytest.raises(ParseError) as exc:
        apistar.parse('{"abc": ', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Expecting value.",
            code='parse_error',
            position=Position(line_no=1, column_no=9, index=8)
        )
    ]

def test_object_unterminated_after_value():
    with pytest.raises(ParseError) as exc:
        apistar.parse('{"abc": "def"', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Expecting ',' delimiter.",
            code='parse_error',
            position=Position(line_no=1, column_no=14, index=13)
        )
    ]

def test_invalid_token():
    with pytest.raises(ParseError) as exc:
        apistar.parse('-', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Expecting value.",
            code='parse_error',
            position=Position(line_no=1, column_no=1, index=0)
        )
    ]

def test_unterminated_string():
    with pytest.raises(ParseError) as exc:
        apistar.parse('"ab', encoding='json')

    assert exc.value.messages == [
        ErrorMessage(
            text="Unterminated string.",
            code='parse_error',
            position=Position(line_no=1, column_no=1, index=0)
        )
    ]

VALIDATOR = validators.Object(
    properties={
        'a': validators.Integer()
    },
    required=['a'],
    additional_properties=False
)

def test_invalid_top_level_item():
    with pytest.raises(ValidationError) as exc:
        apistar.parse('123', encoding="json", validator=VALIDATOR)

    assert exc.value.messages == [
        ErrorMessage(
            text='Must be an object.',
            code='type',
            index=None,
            position=Position(line_no=1, column_no=1, index=0)
        )
    ]

def test_missing_required_property():
    with pytest.raises(ValidationError) as exc:
        apistar.parse('{}', encoding="json", validator=VALIDATOR)

    assert exc.value.messages == [
        ErrorMessage(
            text='The "a" field is required.',
            code='required',
            index=['a'],
            position=Position(line_no=1, column_no=1, index=0))
    ]

def test_invalid_property():
    with pytest.raises(ValidationError) as exc:
        apistar.parse('{"a": "abc"}', encoding="json", validator=VALIDATOR)

    assert exc.value.messages == [
        ErrorMessage(
            text='Must be a number.',
            code='type',
            index=['a'],
            position=Position(line_no=1, column_no=7, index=6))
    ]

def test_invalid_properties():
    with pytest.raises(ValidationError) as exc:
        apistar.parse('{"a": "abc", "b": 123}', encoding="json", validator=VALIDATOR)

    assert exc.value.messages == [
        ErrorMessage(
            text='Must be a number.',
            code='type',
            index=['a'],
            position=Position(line_no=1, column_no=7, index=6)
        ),
        ErrorMessage(
            text='Invalid property name.',
            code='invalid_property',
            index=['b'],
            position=Position(line_no=1, column_no=14, index=13)
        )
    ]


text:
package org.apache.camel.component.smpp;

import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.support.DefaultEndpoint;
import org.jsmpp.bean.AlertNotification;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DeliverSm;

/**
 * To send and receive SMS using a SMSC (Short Message Service Center).
 */
@UriEndpoint(firstVersion = "2.2.0", scheme = "smpp,smpps", title = "SMPP", syntax = "smpp:host:port",
        label = "mobile", lenientProperties = true)
public class SmppEndpoint extends DefaultEndpoint {

    private SmppBinding binding;
    @UriParam
    private SmppConfiguration configuration;

    public SmppEndpoint(String endpointUri, Component component, SmppConfiguration configuration) {
        super(endpointUri, component);
        this.configuration = configuration;
    }

    public boolean isSingleton() {
        return true;
    }

    @Override
    protected String createEndpointUri() {
        return getConnectionString();
    }

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

    public Consumer createConsumer(Processor processor) throws Exception {
        SmppConsumer answer = new SmppConsumer(this, configuration, processor);
        configureConsumer(answer);
        return answer;
    }

    public Producer createProducer() throws Exception {
        return new SmppProducer(this, configuration);
    }

    /**
     * Create a new exchange for communicating with this endpoint from a SMSC
     *
     * @param alertNotification the received message from the SMSC
     * @return a new exchange
     */
    public Exchange createOnAcceptAlertNotificationExchange(AlertNotification alertNotification) {
        return createOnAcceptAlertNotificationExchange(getExchangePattern(), alertNotification);
    }

    /**
     * Create a new exchange for communicating with this endpoint from a SMSC
     * with the specified {@link ExchangePattern} such as whether its going
     * to be an {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} exchange
     *
     * @param exchangePattern the message exchange pattern for the exchange
     * @param alertNotification the received message from the SMSC
     * @return a new exchange
     */
    public Exchange createOnAcceptAlertNotificationExchange(ExchangePattern exchangePattern,
                                                            AlertNotification alertNotification) {
        Exchange exchange = createExchange(exchangePattern);
        exchange.setProperty(Exchange.BINDING, getBinding());
        exchange.setIn(getBinding().createSmppMessage(getCamelContext(), alertNotification));
        return exchange;
    }

    /**
     * Create a new exchange for communicating with this endpoint from a SMSC
     *
     * @param deliverSm the received message from the SMSC
     * @return a new exchange
     */
    public Exchange createOnAcceptDeliverSmExchange(DeliverSm deliverSm) throws Exception {
        return createOnAcceptDeliverSmExchange(getExchangePattern(), deliverSm);
    }

    /**
     * Create a new exchange for communicating with this endpoint from a SMSC
     * with the specified {@link ExchangePattern} such as whether its going
     * to be an {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} exchange
     *
     * @param exchangePattern the message exchange pattern for the exchange
     * @param deliverSm the received message from the SMSC
     * @return a new exchange
     */
    public Exchange createOnAcceptDeliverSmExchange(ExchangePattern exchangePattern,
                                                    DeliverSm deliverSm) throws Exception {
        Exchange exchange = createExchange(exchangePattern);
        exchange.setProperty(Exchange.BINDING, getBinding());
        exchange.setIn(getBinding().createSmppMessage(getCamelContext(), deliverSm));
        return exchange;
    }

    /**
     * Create a new exchange for communicating with this endpoint from a SMSC
     *
     * @param dataSm the received message from the SMSC
     * @param smppMessageId the smpp message id which will be used in the response
     * @return a new exchange
     */
    public Exchange createOnAcceptDataSm(DataSm dataSm, String smppMessageId) {
        return createOnAcceptDataSm(getExchangePattern(), dataSm, smppMessageId);
    }

    /**
     * Create a new exchange for communicating with this endpoint from a SMSC
     * with the specified {@link ExchangePattern} such as whether its going
     * to be an {@link ExchangePattern#InOnly} or {@link ExchangePattern#InOut} exchange
     *
     * @param exchangePattern the message exchange pattern for the exchange
     * @param dataSm the received message from the SMSC
     * @param smppMessageId the smpp message id which will be used in the response
     * @return a new exchange
     */
    public Exchange createOnAcceptDataSm(ExchangePattern exchangePattern, DataSm dataSm, String smppMessageId) {
        Exchange exchange = createExchange(exchangePattern);
        exchange.setProperty(Exchange.BINDING, getBinding());
        exchange.setIn(getBinding().createSmppMessage(getCamelContext(), dataSm, smppMessageId));
        return exchange;
    }

    /**
     * Returns the connection string for the current connection which has the form:
     * smpp://<user>@<host>:<port>
     *
     * @return the connection string
     */
    public String getConnectionString() {
        return (configuration.getUsingSSL() ? "smpps://" : "smpp://")
                + (getConfiguration().getSystemId() != null ? getConfiguration().getSystemId() + "@" : "")
                + getConfiguration().getHost() + ":"
                + getConfiguration().getPort();
    }

    /**
     * Returns the smpp configuration
     *
     * @return the configuration
     */
    public SmppConfiguration getConfiguration() {
        return configuration;
    }

    public SmppBinding getBinding() {
        if (binding == null) {
            binding = new SmppBinding(getConfiguration());
        }
        return binding;
    }

    public void setBinding(SmppBinding binding) {
        this.binding = binding;
    }
}


text:
package com.systematic.trading.signals.data.api.alpha.vantage.resource;

import java.util.Optional;

import com.fasterxml.jackson.annotation.JsonSetter;

/**
 * ErrorPossibleResponseResource is for resources that have the possibility of containing errors.
 *
 * @author CJ Hare
 */
public abstract class AlphaVantqgeErrorPossibleResponseResource {

	/** Optional error message, only present on failure */
	private String error;

	public Optional<String> error() {

		return error == null ? Optional.empty() : Optional.of(error);
	}

	@JsonSetter("Error Message")
	public void error( final String error ) {

		this.error = error;
	}
}


text:
import os
from datetime import datetime, timedelta

from numpy import array, nan, loadtxt, append, zeros
from pandas import DataFrame, notnull, to_numeric, concat

from app.paths import paths

def load_df(path):
    """
    :param path: path to csv file

    :returns dataframe of etrm time series input
    """
    print 'reading in csv: {}'.format(path)
    csv = loadtxt(path, dtype=str, delimiter=',')

    # extracts should have headers
    csv = csv[1:]

    try:
        new_ind = [datetime.strptime(row[0], '%Y-%m-%d') for row in csv]
    except ValueError:
        new_ind = [datetime.strptime(row[0], '%Y/%m/%d') for row in csv[1:]]

    arr = array(csv[:, 1:], dtype=float)

    cols = ['kcb', 'rg', 'etrs', 'min_temp', 'max_temp', 'temp', 'precip']

    df = DataFrame(arr, index=new_ind, columns=cols)

    return df

def get_etrm_time_series(input_root, dict_):
    """
    Read pre-extracted data out of a formatted csv.  Use recharge.point_extract_utility.py to do extract.

    :param input_root: path to a folder of csv files.
    :param dict_: dict of point locations

    csv will be in the following format
    ['kcb', 'rg', 'etrs', 'min_temp', 'max_temp', 'temp', 'precip']
    """

    csv_list = [filename for filename in os.listdir(input_root) if filename.endswith('.csv')]

    print 'etrm extract csv list: {}'.format(csv_list)
    for path in csv_list:
        name = os.path.splitext(path)[0]
        df = load_df(os.path.join(input_root, path))

        if dict_:
            for key, val in dict_.iteritems():
                if val['Name'] == name:
                    print 'updating {} number {} with etrm inputs df'.format(name, key)
                    # print 'your df: \n{}'.format(df)
                    dict_[key]['etrm'] = df

def amf_obs_time_series(dict_, save_cleaned_data_path=False, complete_days_only=False,
                        close_threshold=0.20, return_low_err=False):
    """ Analyze, clean and return dict of AmeriFlux sites and relevant data.

    :param dict_: dict object of Ameriflux IDs as keys, nested dict with 'Name', 'Coords' etc
    :param path: string path to AmeriFlux folder containing AmeriFlux csv files
    :param return_low_err: retun dataframe of only low energy balance closure error
    :param close_threshold: threshold of error tolerated
    :param complete_days_only: return only full days of valid data
    :param save_cleaned_data_path: path to save location of output

    #  (year, dtime, H, LE, FG, RN, RG, RGin, RGout)
    # H  = sensible heat flux
    # LE = latent heat flux
    # FG = soil heat flux
    # RN = net radiation
    # RG = incoming shortwave
    # RGout = outgoing shortwave
    # RGL  = incoming longwave
    # RGLout = outgoing longwave
    """
    path = paths.amf_sites # this doesn't work

    def day_fraction_to_hr_min(fractional_day, year):
        """

        :param fractional_day:  100.134
        :param year:
        :return:
        """

        def ext(d, scalar):
            d = str(d)
            a, b = d.split('.')
            aa, bb = int(a), float('.{}'.format(b))
            return aa, bb * scalar

        dec = str(fractional_day)
        day, timepart = ext(dec, 24)
        hour, minpart = ext(timepart, 60)
        minutes = int(minpart)

        # day_part_str = '.{}'.format(dec_split[1])
        # day, day_part_flt = int(dec_split[0]), float(day_part_str)
        # hour_dec = day_part_flt * 24
        # hour_split = str(hour_dec).split('.')
        # hour, hour_part = int(hour_split[0]), float('.{}'.format(hour_split[1]))
        # min_part = str(hour_part * 60).split('.')
        #

        if minutes == 29:
            minutes = 30
        elif minutes == 59:
            minutes = 0

        tup = datetime(year, 1, 1) + timedelta(days=day, hours=hour, minutes=minutes)
        return tup

    arr_cols = [0, 2, 12, 14, 28, 30, 33, 34, 35]
    subset = ['year', 'day', 'H', 'LE', 'RN', 'RG', 'RGout', 'RGL', 'RGLout']
    # ncols = len(arr_cols)

    columns = ['H', 'LE', 'RN', 'RG', 'RGout', 'RGL', 'RGLout']
    for key, val in dict_.iteritems():  # Changes here
        amf_name = val['Name']
        path = os.path.join('C:\Users\Mike\PyRANA',
                            'ETRM_inputs_Ameriflux','ameriflux_sites')
        folder = os.path.join(path,'AMF_Data',amf_name)

        folder_contents = os.listdir(folder)
        print "this is the folder contents: {}".format(folder_contents)

        csv_list = [os.path.join(folder, item) for item in folder_contents]
        print "this is the new list: {}".format(csv_list)

        # amf_data = array([]).reshape(0, ncols)

        print 'attempting to fetch headers: {}'.format(subset)
        amf_data = None
        for item in csv_list:
            p = os.path.join(folder, item)
            # if i == 0:
            #     col_check = loadtxt(p, dtype=str, skiprows=0, delimiter=',', usecols=arr_cols)
            #     print 'headers being read: \n {}'.format(col_check[:1, :])

            csv = loadtxt(p, dtype=str, skiprows=3, delimiter=',', usecols=arr_cols)
            if amf_data is None:
                amf_data = csv
            else:
                amf_data = append(amf_data, csv, axis=0)

        new_ind = [day_fraction_to_hr_min(float(row[1]), int(row[0])) for row in amf_data]
        amf_data = amf_data[:, 2:]

        df = DataFrame(amf_data, index=new_ind, columns=columns)
        print 'You have {} rows of --RAW-- data from {}'.format(df.shape[0], amf_name)

        # drop rows with NA values in 'subset'
        df[df == '-9999'] = nan
        df = df[notnull(df)]
        df = df.apply(to_numeric)
        df.dropna(axis=0, how='any', inplace=True)
        print 'You have {} rows of FlUX  data from {}'.format(df.shape[0], amf_name)

        # Find all complete days (48) records with no NULL values,
        if complete_days_only:
            df = df.groupby(lambda xx: xx.date())
            print 'df grouped: {}'.format(df)
            df = df.aggregate(lambda xx: sum(xx) if len(xx) > 23 else nan)

        df.dropna(axis=0, how='any', inplace=True)

        # and convert energy to MJ
        for name, series in df.iteritems():
            if name in columns:
                series *= 0.0864 / 48

        # calculate energy balance error
        calculated_cols = ['rad_err', 'en_bal_err', 'rad_minus_sens_heat', 'amf_ET']
        empty = zeros((df.shape[0], len(calculated_cols)), dtype=float)
        new_df = DataFrame(empty, index=df.index, columns=calculated_cols)
        df = concat([df, new_df], axis=1, join='outer')

        for ind, row in df.iterrows():

            rn = row['RN']
            leg = row['LE'] + row['H']
            rn_leg = rn - leg

            row['rad_err'] = (abs(rn - (row['RG'] - row['RGout'] + row['RGL'] - row['RGLout'])) / rn)
            row['en_bal_err'] = rn_leg / rn
            row['rad_minus_sens_heat'] = rn_leg * 0.0864 / 48
            row['amf_ET'] = (row['LE'] / 2.45)  # convert from MJ/(step * m**2) to mm water

        df_low_err = df[df['en_bal_err'] <= close_threshold]

        print 'You have {} DAYS of CLEAN RN/LE/H/RAD data from {}'.format(df.shape[0], amf_name)
        print 'The mean energy balance closure error is: {}'.format(df['en_bal_err'].mean())
        print 'You have {} DAYS  of [0.0 < CLOSURE ERROR < {}] data from {}'.format(len(df_low_err), close_threshold,
                                                                                amf_name)

        if save_cleaned_data_path:
            p = os.path.join(save_cleaned_data_path, 'ameriflux_sites', 'AMF_ETRM_output', '{}_cleaned_all.csv'.format(amf_name))
            df.to_csv(p)

            p = os.path.join(save_cleaned_data_path, '{}_cleaned_lowErr.csv'.format(amf_name))
            df_low_err.to_csv(p)

        if return_low_err:
            val['AMF_Data'] = df_low_err
        else:
            val['AMF_Data'] = df_low_err

    return dict_

if __name__ == '__main__':
    pass

# ============= EOF =============================================


text:
"""
This is a subfile for IsyClass.py

ZigBee Support

Only applicable to ISY994 Z Series.

for now these are just empty hooks will I get my ZigBee Net working
to test against

"""

# author : Peter Shipley <peter.shipley@gmail.com>
# copyrigh :  Copyright (C) 2015 Peter Shipley
# license : BSD

def load_zb():
    # /rest/zb/nodes
    pass

def zb_scannetwork():
    # /rest/zb/scanNetwork
    pass

def zb_ntable():
    # /rest/zb/ntable
    pass

def zb_ping_node():
    # /rest/zb/nodes/[euid]/ping
    pass

def get_zbnode():
    pass

def zbnode_addrs():
    pass

def zbnode_names():
    pass

def _zbnode_get_id():
    pass

def zbnode_comm():
    pass

def zbnode_iter():
    pass

# Do nothing
# (syntax check)
#
if __name__ == "__main__":
    import __main__
    print(__main__.__file__)

    print("syntax ok")
    exit(0)


text:
package backingform;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import model.collectedsample.CollectedSample;
import model.product.Product;
import model.product.ProductStatus;
import model.producttype.ProductType;
import model.user.User;

import org.apache.commons.lang3.StringUtils;

import utils.CustomDateFormatter;

public class ProductBackingForm {

  public static final int ID_LENGTH = 12;

  @NotNull
  @Valid
  private Product product;

  private String createdOn;

  private String expiresOn;

  private List<String> productTypes;

  public ProductBackingForm() {
    setProduct(new Product());
  }

  public ProductBackingForm(boolean autoGenerate) {
    setProduct(new Product());
  }

  public ProductBackingForm(Product product) {
    this.setProduct(product);
  }

  public Long getId() {
    return product.getId();
  }

  public CollectedSample getCollectedSample() {
    return product.getCollectedSample();
  }

  public String getProductType() {
    ProductType productType = product.getProductType();
    if (productType == null)
      return "";
    else
      return productType.getId().toString();
  }

  public Date getLastUpdated() {
    return product.getLastUpdated();
  }

  public Date getCreatedDate() {
    return product.getCreatedDate();
  }

  public User getCreatedBy() {
    return product.getCreatedBy();
  }

  public User getLastUpdatedBy() {
    return product.getLastUpdatedBy();
  }

  public String getNotes() {
    return product.getNotes();
  }

  public Boolean getIsDeleted() {
    return product.getIsDeleted();
  }

  public int hashCode() {
    return product.hashCode();
  }

  public void setId(Long id) {
    product.setId(id);
  }

  public void setCollectedSample(CollectedSample collectedSample) {
    product.setCollectedSample(collectedSample);
  }

  public void setProductType(String productTypeId) {
    if (StringUtils.isBlank(productTypeId)) {
      product.setProductType(null);
    }
    else {
      ProductType pt = new ProductType();
      try {
        pt.setId(Integer.parseInt(productTypeId));
        product.setProductType(pt);
      } catch (Exception ex) {
        ex.printStackTrace();
        product.setProductType(null);
      }
    }
  }

  public String getCreatedOn() {
    if (createdOn != null)
      return createdOn;
    if (getProduct() == null)
      return "";
    return CustomDateFormatter.getDateTimeString(product.getCreatedOn());
  }

  public String getExpiresOn() {
    if (expiresOn != null)
      return expiresOn;
    if (getProduct() == null)
      return "";
    return CustomDateFormatter.getDateString(product.getExpiresOn());
  }

  public void setLastUpdated(Date lastUpdated) {
    product.setLastUpdated(lastUpdated);
  }

  public void setCreatedDate(Date createdDate) {
    product.setCreatedDate(createdDate);
  }

  public void setCreatedBy(User createdBy) {
    product.setCreatedBy(createdBy);
  }

  public void setLastUpdatedBy(User lastUpdatedBy) {
    product.setLastUpdatedBy(lastUpdatedBy);
  }

  public void setNotes(String notes) {
    product.setNotes(notes);
  }

  public void setIsDeleted(Boolean isDeleted) {
    product.setIsDeleted(isDeleted);
  }

  public void setCreatedOn(String createdOn) {
    this.createdOn = createdOn;
    try {
      product.setCreatedOn(CustomDateFormatter.getDateTimeFromString(createdOn));
    } catch (ParseException ex) {
      ex.printStackTrace();
      product.setCreatedOn(null);
    }
  }

  public void setExpiresOn(String expiresOn) {
    this.expiresOn = expiresOn;
    try {
      product.setExpiresOn(CustomDateFormatter.getDateTimeFromString(expiresOn));
    } catch (ParseException ex) {
      ex.printStackTrace();
      product.setExpiresOn(null);
    }
  }

  public String toString() {
    return product.toString();
  }

  public List<String> getProductTypes() {
    return productTypes;
  }

  public void setProductTypes(List<String> productTypes) {
    this.productTypes = productTypes;
  }

  public String getCollectionNumber() {
    if (product == null || product.getCollectedSample() == null ||
        product.getCollectedSample().getCollectionNumber() == null
       )
      return "";
    return product.getCollectedSample().getCollectionNumber();
  }

  public void setCollectionNumber(String collectionNumber) {
    CollectedSample collectedSample = new CollectedSample();
    collectedSample.setCollectionNumber(collectionNumber);
    product.setCollectedSample(collectedSample);
  }

  public Product getProduct() {
    return product;
  }

  public void setProduct(Product product) {
    this.product = product;
  }

  public String getStatus() {
    ProductStatus status = product.getStatus();
    if (status == null)
      return "";
    else
      return product.getStatus().toString();
  }

  public void setStatus(String status) {
    product.setStatus(ProductStatus.valueOf(status));
  }
}


text:
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Web.Services.Description;
using System.Web.Services.Discovery;
using System.Management;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.CSharp;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using Dbg = System.Management.Automation;
using System.Runtime.InteropServices;
using System.Resources;
using Microsoft.Win32;
using System.Text.RegularExpressions;

namespace Microsoft.PowerShell.Commands
{
    #region New-WebServiceProxy

    /// <summary>
    /// Cmdlet for new-WebService Proxy.
    /// </summary>
    [Cmdlet(VerbsCommon.New, "WebServiceProxy", DefaultParameterSetName = "NoCredentials", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135238")]
    public sealed class NewWebServiceProxy : PSCmdlet
    {
        #region Parameters

        /// <summary>
        /// URI of the web service.
        /// </summary>
        [Parameter(Mandatory = true, Position = 0)]
        [ValidateNotNullOrEmpty]
        [Alias("WL", "WSDL", "Path")]
        public System.Uri Uri
        {
            get { return _uri; }

            set
            {
                _uri = value;
            }
        }

        private System.Uri _uri;

        /// <summary>
        /// Parameter Class name.
        /// </summary>
        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty]
        [Alias("FileName", "FN")]
        public string Class
        {
            get { return _class; }

            set
            {
                _class = value;
            }
        }

        private string _class;

        /// <summary>
        /// Namespace.
        /// </summary>
        [Parameter(Position = 2)]
        [ValidateNotNullOrEmpty]
        [Alias("NS")]
        public string Namespace
        {
            get { return _namespace; }

            set
            {
                _namespace = value;
            }
        }

        private string _namespace;

        /// <summary>
        /// Credential.
        /// </summary>
        [Parameter(ParameterSetName = "Credential")]
        [ValidateNotNullOrEmpty]
        [Credential]
        [Alias("Cred")]
        public PSCredential Credential
        {
            get { return _credential; }

            set
            {
                _credential = value;
            }
        }

        private PSCredential _credential;

        /// <summary>
        /// Use default credential..
        /// </summary>
        [Parameter(ParameterSetName = "UseDefaultCredential")]
        [ValidateNotNull]
        [Alias("UDC")]
        public SwitchParameter UseDefaultCredential
        {
            get { return _usedefaultcredential; }

            set
            {
                _usedefaultcredential = value;
            }
        }

        private SwitchParameter _usedefaultcredential;

        #endregion

        #region overrides
        /// <summary>
        /// Cache for storing URIs.
        /// </summary>
        private static Dictionary<Uri, string> s_uriCache = new Dictionary<Uri, string>();

        /// <summary>
        /// Cache for storing sourcecodehashes.
        /// </summary>
        private static Dictionary<int, object> s_srccodeCache = new Dictionary<int, object>();

        /// <summary>
        /// Holds the hash code of the source generated.
        /// </summary>
        private int _sourceHash;
        /// <summary>
        /// Random class.
        /// </summary>

        private object _cachelock = new object();
        private static Random s_rnd = new Random();
        /// <summary>
        /// BeginProcessing code.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (string.IsNullOrWhiteSpace(_uri.ToString()))
            {
                Exception ex = new ArgumentException(WebServiceResources.InvalidUri);
                ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null);
                ThrowTerminatingError(er);
            }
            // check if system.web is available.This assembly is not available in win server core.
            string AssemblyString = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
            try
            {
                Assembly webAssembly = Assembly.Load(AssemblyString);
            }
            catch (FileNotFoundException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "SystemWebAssemblyNotFound", ErrorCategory.ObjectNotFound, null);
                er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported);
                ThrowTerminatingError(er);
            }

            int sourceCache = 0;

            lock (s_uriCache)
            {
                if (s_uriCache.ContainsKey(_uri))
                {
                    // if uri is present in the cache
                    string ns;
                    s_uriCache.TryGetValue(_uri, out ns);
                    string[] data = ns.Split('|');
                    if (string.IsNullOrEmpty(_namespace))
                    {
                        if (data[0].StartsWith("Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.", StringComparison.OrdinalIgnoreCase))
                        {
                            _namespace = data[0];
                            _class = data[1];
                        }
                    }

                    sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(_namespace))
            {
                _namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName();
            }
            // if class is null,generate a name for it
            if (string.IsNullOrEmpty(_class))
            {
                _class = "MyClass" + GenerateRandomName();
            }

            Assembly webserviceproxy = GenerateWebServiceProxyAssembly(_namespace, _class);
            if (webserviceproxy == null)
                return;
            object instance = InstantiateWebServiceProxy(webserviceproxy);

            // to set the credentials into the generated webproxy Object
            PropertyInfo[] pinfo = instance.GetType().GetProperties();
            foreach (PropertyInfo pr in pinfo)
            {
                if (pr.Name.Equals("UseDefaultCredentials", StringComparison.OrdinalIgnoreCase))
                {
                    if (UseDefaultCredential.IsPresent)
                    {
                        bool flag = true;
                        pr.SetValue(instance, flag as object, null);
                    }
                }

                if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase))
                {
                    if (Credential != null)
                    {
                        NetworkCredential cred = Credential.GetNetworkCredential();
                        pr.SetValue(instance, cred as object, null);
                    }
                }
            }

            // disposing the entries in a cache
            // Adding to Cache
            lock (s_uriCache)
            {
                s_uriCache.Remove(_uri);
            }

            if (sourceCache > 0)
            {
                lock (_cachelock)
                {
                    s_srccodeCache.Remove(sourceCache);
                }
            }

            string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) });
            lock (s_uriCache)
            {
                s_uriCache.Add(_uri, key);
            }

            lock (_cachelock)
            {
                s_srccodeCache.Add(_sourceHash, instance);
            }

            WriteObject(instance, true);
        }

        #endregion

        #region private

        private static ulong s_sequenceNumber = 1;
        private static object s_sequenceNumberLock = new object();

        /// <summary>
        /// Generates a random name.
        /// </summary>
        /// <returns>String.</returns>
        private string GenerateRandomName()
        {
            string rndname = null;
            string givenuri = _uri.ToString();
            for (int i = 0; i < givenuri.Length; i++)
            {
                Int32 val = System.Convert.ToInt32(givenuri[i], CultureInfo.InvariantCulture);
                if ((val >= 65 && val <= 90) || (val >= 48 && val <= 57) || (val >= 97 && val <= 122))
                {
                    rndname += givenuri[i];
                }
                else
                {
                    rndname += "_";
                }
            }

            string sequenceString;
            lock (s_sequenceNumberLock)
            {
                sequenceString = (s_sequenceNumber++).ToString(CultureInfo.InvariantCulture);
            }

            if (rndname.Length > 30)
            {
                return (sequenceString + rndname.Substring(rndname.Length - 30));
            }

            return (sequenceString + rndname);
        }

        /// <summary>
        /// Generates the Assembly.
        /// </summary>
        /// <param name="NameSpace"></param>
        /// <param name="ClassName"></param>
        /// <returns></returns>
        [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
        private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
        {
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();

            // if paramset is defaultcredential, set the flag in wcclient
            if (_usedefaultcredential.IsPresent)
                dcp.UseDefaultCredentials = true;

            // if paramset is credential, assign the credentials
            if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
                dcp.Credentials = _credential.GetNetworkCredential();

            try
            {
                dcp.AllowAutoRedirect = true;
                dcp.DiscoverAny(_uri.ToString());
                dcp.ResolveAll();
            }
            catch (WebException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri);
                if (ex.InnerException != null)
                    er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
                WriteError(er);
                return null;
            }
            catch (InvalidOperationException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri);
                WriteError(er);
                return null;
            }

            // create the namespace
            CodeNamespace codeNS = new CodeNamespace();
            if (!string.IsNullOrEmpty(NameSpace))
                codeNS.Name = NameSpace;

            // create the class and add it to the namespace
            if (!string.IsNullOrEmpty(ClassName))
            {
                CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);
                codeClass.IsClass = true;
                codeClass.Attributes = MemberAttributes.Public;
                codeNS.Types.Add(codeClass);
            }

            // create a web reference to the uri docs
            WebReference wref = new WebReference(dcp.Documents, codeNS);
            WebReferenceCollection wrefs = new WebReferenceCollection();
            wrefs.Add(wref);

            // create a codecompileunit and add the namespace to it
            CodeCompileUnit codecompileunit = new CodeCompileUnit();
            codecompileunit.Namespaces.Add(codeNS);

            WebReferenceOptions wrefOptions = new WebReferenceOptions();
            wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            wrefOptions.Verbose = true;

            // create a csharpprovider and compile it
            CSharpCodeProvider csharpprovider = new CSharpCodeProvider();
            StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions);

            StringBuilder codegenerator = new StringBuilder();
            StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture);
            try
            {
                csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null);
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }
            // generate the hashcode of the CodeCompileUnit
            _sourceHash = codegenerator.ToString().GetHashCode();

            // if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so
            // return the instance of th eproxy in the cache
            if (s_srccodeCache.ContainsKey(_sourceHash))
            {
                object obj;
                s_srccodeCache.TryGetValue(_sourceHash, out obj);
                WriteObject(obj, true);
                return null;
            }

            CompilerParameters options = new CompilerParameters();
            CompilerResults results = null;

            foreach (string warning in Warnings)
            {
                this.WriteWarning(warning);
            }

            // add the references to the required assemblies
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Data.dll");
            options.ReferencedAssemblies.Add("System.Xml.dll");
            options.ReferencedAssemblies.Add("System.Web.Services.dll");
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            GetReferencedAssemblies(typeof(Cmdlet).Assembly, options);
            options.GenerateInMemory = true;
            options.TreatWarningsAsErrors = false;
            options.WarningLevel = 4;
            options.GenerateExecutable = false;
            try
            {
                results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString());
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }

            return results.CompiledAssembly;
        }

        /// <summary>
        /// Function to add all the assemblies required to generate the web proxy.
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="parameters"></param>
        private void GetReferencedAssemblies(Assembly assembly, CompilerParameters parameters)
        {
            if (!parameters.ReferencedAssemblies.Contains(assembly.Location))
            {
                string location = Path.GetFileName(assembly.Location);
                if (!parameters.ReferencedAssemblies.Contains(location))
                {
                    parameters.ReferencedAssemblies.Add(assembly.Location);
                    foreach (AssemblyName referencedAssembly in assembly.GetReferencedAssemblies())
                        GetReferencedAssemblies(Assembly.Load(referencedAssembly.FullName), parameters);
                }
            }
        }
        /// <summary>
        /// Instantiates the object
        ///  if a type of WebServiceBindingAttribute is not found, throw an exception.
        /// </summary>
        /// <param name="assembly"></param>
        /// <returns></returns>
        private object InstantiateWebServiceProxy(Assembly assembly)
        {
            Type proxyType = null;
            // loop through the types of the assembly and identify the type having
            // a web service binding attribute
            foreach (Type type in assembly.GetTypes())
            {
                object[] obj = type.GetCustomAttributes(typeof(WebServiceBindingAttribute), false);
                if (obj.Length > 0)
                {
                    proxyType = type;
                    break;
                }

                if (proxyType != null) break;
            }

            System.Management.Automation.Diagnostics.Assert(
                proxyType != null,
                "Proxy class should always get generated unless there were some errors earlier (in that case we shouldn't get here)");

            return assembly.CreateInstance(proxyType.ToString());
        }

        #endregion
    }
    #endregion
}


text:
{% extends "base.html" %}

{% block navbar %}
{% endblock %}

{% block content %}

(Answer question at bottom)

    <form method="post" action="{% url 'vote_likert' project.id %}">
        {% csrf_token %}
        <input type="hidden" name="item_id" value="{{ item.id }}">

{{ project.individual_likert_prompt }}

                <fieldset>
                    <input id="l7" name="rating" type="radio" value="7"
                    required /> {{ project.likert_label_7 }}

                    <input id="l6" name="rating" type="radio" value="6"
                    /> {{ project.likert_label_6 }}

                    <input id="l5" name="rating" type="radio" value="5"
                    /> {{ project.likert_label_5 }}

                    <input id="l4" name="rating" type="radio" value="4"
                    /> {{ project.likert_label_4 }}

                    <input id="l3" name="rating" type="radio" value="3"
                    /> {{ project.likert_label_3 }}

                    <input id="l2" name="rating" type="radio" value="2"
                    /> {{ project.likert_label_2 }}

                    <input id="l1" name="rating" type="radio" value="1"
                    /> {{ project.likert_label_1 }}

                </fieldset>

            <button id="submit">Submit</button>

    </form>

Rater Key: {{ key }}

# of Individual Ratings: {{ count }}

{% endblock %}


text:
/* jshint node: true */
"use strict";
var util = require('util');

/*
    Example:

    UserAddError = makeError('userAddError', {
      prop1: true,
      prop2: false
    }, {addContext: false});

    ...

    var errContext = {
      reason: 'there was an error connecting to the database',
      userId: '12344'
    };
    return cb(UserAddError('Unable to add user', errContext));
 */

/**
 * make a new Error (inherits from Error)
 * @param  {String}  name                 Becomes err.name
 * @param  {Object}  errorProps           Properties to populate on every generated error
 * @param  {Object}  opts                 Options
 * @param  {Boolean} opts.addContext      Add context to the .message string (default: true)
 * @return {Error}                        The generated error object
 */
function makeError(name, errorProps, opts) {
  errorProps = errorProps || {};
  opts = opts || {};
  if (opts.addContext === undefined) opts.addContext = true;

  var ex = function (message, context) {
    if (typeof message === 'object' && context === undefined) {
      context = message;
      message = util.inspect(context);
    }
    else if (opts.addContext && context !== undefined) {
      message += ' ' + util.inspect(context);
    }

    // Build the error, set the context
    Error.call(this);
    Error.captureStackTrace(this, this.constructor);
    this.name = name;
    this.message = message;
    this.context = context;

    // Add default error properties
    for (var k in errorProps) this[k] = errorProps[k];
  };
  util.inherits(ex, Error);

  return ex;
}

// Exports
//
module.exports = makeError;


text:
struct Empty;

namespace msm = boost::msm;
namespace mpl = boost::mpl;
using namespace msm::front;

struct Open : public msm::front::state<>
{
    template <class Event,class FSM>
    void on_entry(Event const& ,FSM&) {std::cout << "entering: Open" << std::endl;}
    template <class Event,class FSM>
    void on_exit(Event const&,FSM& ) {std::cout << "leaving: Open" << std::endl;}
    void close_drawer(open_close const&);

    struct internal_transition_table : mpl::vector<
        //               Start     Event         Next      Action                      Guard
        //+-------------+---------+-------------+---------+---------------------------+----------------------+
    msm::front::a_row2  < Open    , open_close  , Empty   , Open,&Open::close_drawer                         >
        //+-------------+---------+-------------+---------+---------------------------+----------------------+
    > {};
};

#endif


text:
package com.google.ads.googleads.v12.enums;

public interface GeoTargetingTypeEnumOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.enums.GeoTargetingTypeEnum)
    com.google.protobuf.MessageOrBuilder {
}


text:
`acgn-stock` can use [prerender](https://github.com/prerender/prerender-node) to help its SEO process.

Since the setup process is a little bit complicated, we wrote down this how-to document to help those in need.

**This is not necessary**, you can just skip this if you won't develop anything about SEO.

## Setting Up a Prerender Server

To enable this functionality, you will need a **prerender server** to handle the request.

### Hosted Service

If you don't want to run your own prerender server, check out [PrerenderIO](https://prerender.io/) for their hosted service.

### Run Your Own Prerender Server

If you choose to run your own prerender server, you can use our [prerender-server](https://github.com/ACGN-stock/acgn-stock-prerender-server) project, or follow these steps to develop your server:

1. install [Chrome](https://www.google.com/chrome/)

   [(Guide for installing Chrome on a Ubuntu server)](https://askubuntu.com/a/79284)

2. create a new node project and install [prerender](https://github.com/prerender/prerender)

   ```sh
   npm install prerender --save
   ```

   **IMPORTANT NOTE: Don't try to install prerender server in your `acgn-stock` project!**

   We tried to integrate prerender into this project (see [#589](https://github.com/ACGN-stock/acgn-stock/pull/589), [#591](https://github.com/ACGN-stock/acgn-stock/pull/591)). Since then we encountered some serious issues which prevent `acgn-stock` from working, so we decided to remove it (see [#597](https://github.com/ACGN-stock/acgn-stock/pull/597)).

3. write `index.js`
   ```js
   const prerender = require('prerender');
   const prerenderServer = prerender({
     port: 3900,
     waitAfterLastRequest: 3000
   });
   prerenderServer.start();
   ```

   For the port, we use `3900` here. Feel free to switch to the other port if you want. Just make sure it's not being used.

   For the `waitAfterLastRequest`, we recommend `3000`ms here. [(Check the document about `waitAfterLastRequest`)](https://github.com/prerender/prerender#waitafterlastrequest)

4. start the server

   ```sh
   node index.js
   ```

After the server is started, you can connect to, for example, `http://localhost:3900/https://github.com/`, to see if it works.

## Setting Your `acgn-stock`

Update your prerender setting in [config.json](../config.json)

```json
"prerender": {
  "use": true,
  "url": "http://127.0.0.1:3900/"
}
```

`"use"` must be `true` if you want to use prerender.

`"url"` is the URL of the prerender server.

Now you can run your `acgn-stock`, and visit the following URL to see if it's working or not.

```
http://localhost:3000/company/1?_escaped_fragment_=
```


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

namespace Pathfinding {
	[System.Serializable]
	/** Adjusts start and end points of a path.
	 * \ingroup modifiers
	 */
	public class StartEndModifier : PathModifier {
		public override int Order { get { return 0; } }

		/** Add points to the path instead of replacing them */
		public bool addPoints;
		public Exactness exactStartPoint = Exactness.ClosestOnNode;
		public Exactness exactEndPoint = Exactness.ClosestOnNode;

		/** Will be called when a path is processed.
		 * The value which is returned will be used as the start point of the path
		 * and potentially clamped depending on the value of the #exactStartPoint field.
		 * Only used for the Original, Interpolate and NodeConnection modes.
		 */
		public System.Func<Vector3> adjustStartPoint;

		/** Sets where the start and end points of a path should be placed */
		public enum Exactness {
			/** The point is snapped to the first/last node in the path*/
			SnapToNode,
			/** The point is set to the exact point which was passed when calling the pathfinding */
			Original,
			/** The point is set to the closest point on the line between either the two first points or the two last points.
			 * Usually you will want to use the NodeConnection mode instead since that is usually the behaviour that you really want.
			 */
			Interpolate,
			/** The point is set to the closest point on the node. Note that for some node types (point nodes) the "closest point" is the node's position which makes this identical to Exactness.SnapToNode */
			ClosestOnNode,
			/** The point is set to the closest point on one of the connections from the start/end node */
			NodeConnection,
		}

		public bool useRaycasting;
		public LayerMask mask = -1;

		public bool useGraphRaycasting;

		List<GraphNode> connectionBuffer;
		GraphNodeDelegate connectionBufferAddDelegate;

		public override void Apply (Path _p) {
			var p = _p as ABPath;

			// This modifier only supports ABPaths (doesn't make much sense for other paths anyway)
			if (p == null || p.vectorPath.Count == 0) return;

			if (p.vectorPath.Count == 1 && !addPoints) {
				// Duplicate first point
				p.vectorPath.Add(p.vectorPath[0]);
			}

			// Add instead of replacing points
			bool forceAddStartPoint, forceAddEndPoint;

			Vector3 pStart = Snap(p, exactStartPoint, true, out forceAddStartPoint);
			Vector3 pEnd = Snap(p, exactEndPoint, false, out forceAddEndPoint);

			// Add or replace the start point
			// Disable adding of points if the mode is SnapToNode since then
			// the first item in vectorPath will very likely be the same as the
			// position of the first node
			if ((forceAddStartPoint || addPoints) && exactStartPoint != Exactness.SnapToNode) {
				p.vectorPath.Insert(0, pStart);
			} else {
				p.vectorPath[0] = pStart;
			}

			if ((forceAddEndPoint || addPoints) && exactEndPoint != Exactness.SnapToNode) {
				p.vectorPath.Add(pEnd);
			} else {
				p.vectorPath[p.vectorPath.Count-1] = pEnd;
			}
		}

		Vector3 Snap (ABPath path, Exactness mode, bool start, out bool forceAddPoint) {
			var index = start ? 0 : path.path.Count - 1;
			var node = path.path[index];
			var nodePos = (Vector3)node.position;

			forceAddPoint = false;

			switch (mode) {
			case Exactness.ClosestOnNode:
				return GetClampedPoint(nodePos, start ? path.startPoint : path.endPoint, node);
			case Exactness.SnapToNode:
				return nodePos;
			case Exactness.Original:
			case Exactness.Interpolate:
			case Exactness.NodeConnection:
				Vector3 relevantPoint;
				if (start) {
					relevantPoint = adjustStartPoint != null ? adjustStartPoint() : path.originalStartPoint;
				} else {
					relevantPoint = path.originalEndPoint;
				}

				switch (mode) {
				case Exactness.Original:
					return GetClampedPoint(nodePos, relevantPoint, node);
				case Exactness.Interpolate:
					var clamped = GetClampedPoint(nodePos, relevantPoint, node);
					// Adjacent node to either the start node or the end node in the path
					var adjacentNode = path.path[Mathf.Clamp(index + (start ? 1 : -1), 0, path.path.Count-1)];
					return VectorMath.ClosestPointOnSegment(nodePos, (Vector3)adjacentNode.position, clamped);
				case Exactness.NodeConnection:
					// This code uses some tricks to avoid allocations
					// even though it uses delegates heavily
					// The connectionBufferAddDelegate delegate simply adds whatever node
					// it is called with to the connectionBuffer
					connectionBuffer = connectionBuffer ?? new List<GraphNode>();
					connectionBufferAddDelegate = connectionBufferAddDelegate ?? (GraphNodeDelegate)connectionBuffer.Add;

					// Adjacent node to either the start node or the end node in the path
					adjacentNode = path.path[Mathf.Clamp(index + (start ? 1 : -1), 0, path.path.Count-1)];

					// Add all neighbours of #node to the connectionBuffer
					node.GetConnections(connectionBufferAddDelegate);
					var bestPos = nodePos;
					var bestDist = float.PositiveInfinity;

					// Loop through all neighbours
					// Do it in reverse order because the length of the connectionBuffer
					// will change during iteration
					for (int i = connectionBuffer.Count - 1; i >= 0; i--) {
						var neighbour = connectionBuffer[i];

						// Find the closest point on the connection between the nodes
						// and check if the distance to that point is lower than the previous best
						var closest = VectorMath.ClosestPointOnSegment(nodePos, (Vector3)neighbour.position, relevantPoint);

						var dist = (closest - relevantPoint).sqrMagnitude;
						if (dist < bestDist) {
							bestPos = closest;
							bestDist = dist;

							// If this node is not the adjacent node
							// then the path should go through the start node as well
							forceAddPoint = neighbour != adjacentNode;
						}
					}

					connectionBuffer.Clear();
					return bestPos;
				default:
					throw new System.ArgumentException("Cannot reach this point, but the compiler is not smart enough to realize that.");
				}
			default:
				throw new System.ArgumentException("Invalid mode");
			}
		}

		public Vector3 GetClampedPoint (Vector3 from, Vector3 to, GraphNode hint) {
			Vector3 point = to;
			RaycastHit hit;

			if (useRaycasting && Physics.Linecast(from, to, out hit, mask)) {
				point = hit.point;
			}

			if (useGraphRaycasting && hint != null) {
				var rayGraph = AstarData.GetGraph(hint) as IRaycastableGraph;

				if (rayGraph != null) {
					GraphHitInfo graphHit;
					if (rayGraph.Linecast(from, point, hint, out graphHit)) {
						point = graphHit.point;
					}
				}
			}

			return point;
		}
	}
}


text:
angular.module('app').config(['$provide', '$stateProvider', '$urlRouterProvider', function ($provide, $stateProvider, $urlRouterProvider) {
    //默认进入页面的路由地址
    $urlRouterProvider.otherwise('/home');

    $stateProvider.state('app', {
        abstract: true,
        templateUrl: 'app/index.html',
        resolve: {
            //加载指令
            load: ['$ocLazyLoad', 'AppConfig', function ($ocLazyLoad, AppConfig) {
                return $ocLazyLoad.load([
                    'app/user/user.service.js',
                    'app/shared/dialog/dialog.js'
                ]);
            }]
        },
        controller: ['$rootScope', '$scope', '$state', '$modal', 'userService', 'dialog', '$location', '$cookies', function ($rootScope, $scope, $state, $modal, userService, dialog, $location, $cookies) {

            //用户注销
            $rootScope.logout = function () {
                userService.logout().success(function (response) {
                    if (response.meta.success) {
                        $cookies.remove("currentUser");
                        $state.go('app.login');
                        $scope.hasLogin = false;
                    } else {
                        dialog.alert(response.meta.message);
                    }
                }).error(function (response) {

                });
            };

            $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                var currentUser = $cookies.getObject("currentUser");
                if (currentUser !== undefined && currentUser !== '') {
                    $scope.hasLogin = true;
                } else {
                    $scope.hasLogin = false;
                }
            });

            $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
                event.preventDefault();
                if(error=="user isn't admin"){
                    $state.go("app.dashboard.overview");
                }else{
                    $state.go("app.login");
                }

            });

        }]
    });
}]);


text:
#ifndef __SIMPLE_TCP_SERVER
#define __SIMPLE_TCP_SERVER

#ifdef _XBOX360
#include "Console1Includes.h"
#elif defined(_WIN32)
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h> // fd_set
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <pthread.h>
/// Unix/Linux uses ints for sockets
typedef unsigned int SOCKET;
#endif

#include "RakMemoryOverride.h"
#include "DS_List.h"
#include "RakNetTypes.h"
#include "SingleProducerConsumer.h"
#include "Export.h"
#include "RakThread.h"
#include "DS_Queue.h"
#include "SimpleMutex.h"
#include "RakNetDefines.h"

struct RemoteClient;

#if defined(OPEN_SSL_CLIENT_SUPPORT)
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#endif

/// \internal
/// \brief As the name says, a simple multithreaded TCP server.  Used by TelnetTransport
class RAK_DLL_EXPORT TCPInterface : public RakNet::RakMemoryOverride
{
public:
	TCPInterface();
	~TCPInterface();

	/// Starts the TCP server on the indicated port
	bool Start(unsigned short port, unsigned short maxIncomingConnections);

	/// Stops the TCP server
	void Stop(void);

	/// Connect to the specified host on the specified port
	SystemAddress Connect(const char* host, unsigned short remotePort, bool block=true);

#if defined(OPEN_SSL_CLIENT_SUPPORT)
	/// Start SSL on an existing connection, notified with HasCompletedConnectionAttempt
	void StartSSLClient(SystemAddress systemAddress);

	/// Was SSL started on this socket?
	bool IsSSLActive(SystemAddress systemAddress);
#endif

	/// Sends a byte stream
	void Send( const char *data, unsigned length, SystemAddress systemAddress );

	/// Returns data received
	Packet* Receive( void );

	/// Disconnects a player/address
	void CloseConnection( SystemAddress systemAddress );

	/// Deallocates a packet returned by Receive
	void DeallocatePacket( Packet *packet );

	/// Has a previous call to connect succeeded? Only used if block==false in the call to Connect
	/// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes.
	SystemAddress HasCompletedConnectionAttempt(void);

	/// Has a previous call to connect failed? Only used if block==false in the call to Connect
	/// \return UNASSIGNED_SYSTEM_ADDRESS = no. Anything else means yes.
	SystemAddress HasFailedConnectionAttempt(void);

	/// Queued events of new connections
	SystemAddress HasNewConnection(void);

	/// Queued events of lost connections
	SystemAddress HasLostConnection(void);
protected:

	bool isStarted, threadRunning;
	SOCKET listenSocket;

	// Assuming remoteClients is only used by one thread!
	DataStructures::List<RemoteClient*> remoteClients;
	// Use this thread-safe queue to add to remoteClients
	DataStructures::Queue<RemoteClient*> remoteClientsInsertionQueue;
	SimpleMutex remoteClientsInsertionQueueMutex;
	DataStructures::SingleProducerConsumer<Packet> outgoingMessages, incomingMessages;
	DataStructures::SingleProducerConsumer<SystemAddress> newConnections, lostConnections, requestedCloseConnections;
	DataStructures::SingleProducerConsumer<RemoteClient*> newRemoteClients;
	SimpleMutex completedConnectionAttemptMutex, failedConnectionAttemptMutex;
	DataStructures::Queue<SystemAddress> completedConnectionAttempts, failedConnectionAttempts;

	DataStructures::List<SOCKET> blockingSocketList;
	SimpleMutex blockingSocketListMutex;

	friend RAK_THREAD_DECLARATION(UpdateTCPInterfaceLoop);
	friend RAK_THREAD_DECLARATION(ConnectionAttemptLoop);

	void DeleteRemoteClient(RemoteClient *remoteClient, fd_set *exceptionFD);
	void InsertRemoteClient(RemoteClient* remoteClient);
	SOCKET SocketConnect(const char* host, unsigned short remotePort);

	struct ThisPtrPlusSysAddr
	{
		TCPInterface *tcpInterface;
		SystemAddress systemAddress;
		bool useSSL;
	};

#if defined(OPEN_SSL_CLIENT_SUPPORT)
	SSL_CTX* ctx;
	SSL_METHOD *meth;
	DataStructures::SingleProducerConsumer<SystemAddress> startSSL;
	DataStructures::List<SystemAddress> activeSSLConnections;
#endif
};

/// Stores information about a remote client.
struct RemoteClient
{
	RemoteClient() {
#if defined(OPEN_SSL_CLIENT_SUPPORT)
		ssl=0;
#endif
	}
	SOCKET socket;
	SystemAddress systemAddress;

#if defined(OPEN_SSL_CLIENT_SUPPORT)
	SSL*     ssl;
	void InitSSL(SSL_CTX* ctx, SSL_METHOD *meth);
	void DisconnectSSL(void);
	void FreeSSL(void);
	void Send(const char *data, unsigned int length);
	int Recv(char *data, const int dataSize);
#else
	void Send(const char *data, unsigned int length);
	int Recv(char *data, const int dataSize);
#endif
};

#endif


text:
/**
 * Module dependencies
 */

var express = require('express'),
  bodyParser = require('body-parser'),
  methodOverride = require('method-override'),
  errorhandler = require('errorhandler'),
  morgan = require('morgan'),
  routes = require('./routes'),
  api = require('./routes/api'),
  http = require('http'),
  stylus = require('stylus'),
  path = require('path');

var app = module.exports = express();

/**
 * Configuration
 */

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use('/css', stylus.middleware({
  src: __dirname + '/stylus',
  dest: __dirname + '/public/css',
  compile: function (str, path) {
    return stylus(str)
      .set('filename', path)
      .set('compress', true);
  }
}));
app.use(morgan('dev'));
app.use(bodyParser());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

var env = process.env.NODE_ENV || 'development';

// development only
if (env === 'development') {
  app.use(errorhandler());
}

// production only
if (env === 'production') {
  // TODO
}

/**
 * Routes
 */

// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// JSON API
app.get('/api/name', api.name);

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

/**
 * Start Server
 */

http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});


text:
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency';

export default Component.extend({
  router: service(),
  store: service(),
  flashMessages: service(),
  deleteOutcomeModal: false,
  deleteOutcomeModalError: false,
  deleteOutcome: task(function *() {
    try {
      yield this.model.destroyRecord({
        'by': this.get('currentUser.user.id'),
      });
      this.set('deleteOutcomeModal', false);
      this.set('deleteOutcomeModalError', false);
      this.flashMessages.success("Deleted!");
      this.router.transitionTo('dashboard.conventions.convention.sessions.session.rounds.round.outcomes');
    } catch(e) {
      this.set('deleteOutcomeModalError', true);
    }
  }).drop(),
});


text:
require File.expand_path("../../spec_helper", __FILE__)

module Playgroundbook
  describe GlossaryGenerator do
    include FakeFS::SpecHelpers
    let(:glossary_generator) { GlossaryGenerator.new }
    let(:glossary) do
      {
      "example term" => "example definition"
    }
    end
    let(:glossary_file_name) { "Contents/Resources/Glossary.plist" }

    before do
      FileUtils.mkdir_p("Contents/Resources")
    end

    it "generates a glossary plist" do
      glossary_generator.generate({}, [], glossary)

      expect(File.exist?(glossary_file_name)).to be_truthy
    end

    context "glossary plist" do
      let(:glossary_plist) { Plist.parse_xml(glossary_file_name) }

      it "has a glossary with correct terms" do
        glossary_generator.generate({}, [], glossary)

        expect(glossary_plist["Terms"]["example term"]["Definition"]).to eq("example definition")
      end

      it "generates correct first use page references" do
        glossary_generator.generate([
                                      {
                                        page_names: ["Page 1"],
                                        page_contents: ["/*: Here's how to use [a thing](glossary://example%20term) */"]
                                      },
                                      {
                                        page_names: ["Should not see this"],
                                        page_contents: ["/*: Here's how to use [a thing](glossary://example%20term) even though this shouldn't match' */"]
                                      }
                                    ],
                                    ["Chapter 1", "Chapter 2"],
                                    glossary)

        expect(glossary_plist["Terms"]["example term"]["FirstUse"]).to eq({
          "PageReference" => "Chapter%201/Page%201",
          "Title" => "Page 1"
        })
      end
    end
  end
end


text:
module Azure::Security::Mgmt::V2015_06_01_preview
  module Models
    #
    # Factors that increase our confidence that the alert is a true positive
    #
    class AlertConfidenceReason

      include MsRestAzure

      # @return [String] Type of confidence factor
      attr_accessor :type

      # @return [String] description of the confidence reason
      attr_accessor :reason

      #
      # Mapper for AlertConfidenceReason class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'AlertConfidenceReason',
          type: {
            name: 'Composite',
            class_name: 'AlertConfidenceReason',
            model_properties: {
              type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              reason: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'reason',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
This tests loading of a JPEG image and no HTML when the HTTP content-type is set to "image/png" .
 Expected : This page should have an IMAGE .

<script>
  window.location="resources/getpage.pl?type=image/png&switch=nohtml&content=type_jpg.jpg";
</script>


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

    <com.heaven7.android.StickyLayout.NestedScrollFrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_green_light"
        app:nsfl_max_y_percent="0.5"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="16sp"
            android:textColor="@android:color/holo_red_light"
            android:text="TestNestedScrollView"
            android:padding="10dp"
            />

    </com.heaven7.android.StickyLayout.NestedScrollFrameLayout>

</LinearLayout>