text:
namespace base {

File::Info::Info()
    : size(0),
      is_directory(false),
      is_symbolic_link(false) {
}

File::Info::~Info() {
}

File::File()
    : error_details_(FILE_ERROR_FAILED),
      created_(false),
      async_(false) {
}

#if !defined(OS_NACL)
File::File(const FilePath& path, uint32 flags)
    : error_details_(FILE_OK),
      created_(false),
      async_(false) {
  Initialize(path, flags);
}
#endif

File::File(PlatformFile platform_file)
    : file_(platform_file),
      error_details_(FILE_OK),
      created_(false),
      async_(false) {
#if defined(OS_POSIX)
  DCHECK_GE(platform_file, -1);
#endif
}

File::File(Error error_details)
    : error_details_(error_details),
      created_(false),
      async_(false) {
}

File::File(File&& other)
    : file_(other.TakePlatformFile()),
      tracing_path_(other.tracing_path_),
      error_details_(other.error_details()),
      created_(other.created()),
      async_(other.async_) {}

File::~File() {
  // Go through the AssertIOAllowed logic.
  Close();
}

// static
File File::CreateForAsyncHandle(PlatformFile platform_file) {
  File file(platform_file);
  // It would be nice if we could validate that |platform_file| was opened with
  // FILE_FLAG_OVERLAPPED on Windows but this doesn't appear to be possible.
  file.async_ = true;
  return file.Pass();
}

File& File::operator=(File&& other) {
  DCHECK_NE(this, &other);
  Close();
  SetPlatformFile(other.TakePlatformFile());
  tracing_path_ = other.tracing_path_;
  error_details_ = other.error_details();
  created_ = other.created();
  async_ = other.async_;
  return *this;
}

#if !defined(OS_NACL)
void File::Initialize(const FilePath& path, uint32 flags) {
  if (path.ReferencesParent()) {
    error_details_ = FILE_ERROR_ACCESS_DENIED;
    return;
  }
  if (FileTracing::IsCategoryEnabled())
    tracing_path_ = path;
  SCOPED_FILE_TRACE("Initialize");
  DoInitialize(path, flags);
}
#endif

std::string File::ErrorToString(Error error) {
  switch (error) {
    case FILE_OK:
      return "FILE_OK";
    case FILE_ERROR_FAILED:
      return "FILE_ERROR_FAILED";
    case FILE_ERROR_IN_USE:
      return "FILE_ERROR_IN_USE";
    case FILE_ERROR_EXISTS:
      return "FILE_ERROR_EXISTS";
    case FILE_ERROR_NOT_FOUND:
      return "FILE_ERROR_NOT_FOUND";
    case FILE_ERROR_ACCESS_DENIED:
      return "FILE_ERROR_ACCESS_DENIED";
    case FILE_ERROR_TOO_MANY_OPENED:
      return "FILE_ERROR_TOO_MANY_OPENED";
    case FILE_ERROR_NO_MEMORY:
      return "FILE_ERROR_NO_MEMORY";
    case FILE_ERROR_NO_SPACE:
      return "FILE_ERROR_NO_SPACE";
    case FILE_ERROR_NOT_A_DIRECTORY:
      return "FILE_ERROR_NOT_A_DIRECTORY";
    case FILE_ERROR_INVALID_OPERATION:
      return "FILE_ERROR_INVALID_OPERATION";
    case FILE_ERROR_SECURITY:
      return "FILE_ERROR_SECURITY";
    case FILE_ERROR_ABORT:
      return "FILE_ERROR_ABORT";
    case FILE_ERROR_NOT_A_FILE:
      return "FILE_ERROR_NOT_A_FILE";
    case FILE_ERROR_NOT_EMPTY:
      return "FILE_ERROR_NOT_EMPTY";
    case FILE_ERROR_INVALID_URL:
      return "FILE_ERROR_INVALID_URL";
    case FILE_ERROR_IO:
      return "FILE_ERROR_IO";
    case FILE_ERROR_MAX:
      break;
  }

  NOTREACHED();
  return "";
}

bool File::Flush() {
  ElapsedTimer timer;
  SCOPED_FILE_TRACE("Flush");
  bool return_value = DoFlush();
  UMA_HISTOGRAM_TIMES("PlatformFile.FlushTime", timer.Elapsed());
  return return_value;
}

}  // namespace base


text:
using System;
using System.IO;

using log4net;
using log4net.Appender;
using log4net.Repository.Hierarchy;

namespace Framework.Layer.Logging.Inspector
{
    public class LoggerInspector
    {
//        This method can be used to inspect the settings defined for the file appender and check
//        if there are any issues with creating the log file or writing to it at runtime.
        public void Log4NetSettingsInspector()
        {
            foreach (var fileAppender in ((Hierarchy) LogManager.GetRepository()).Root.Appenders)
            {
                var appender = fileAppender as FileAppender;
                if (appender != null)
                {
                    Console.WriteLine(appender.File);

                    if (!File.Exists(appender.File))
                    {
                        using (var fileStream = File.CreateText(appender.File))
                        {
                            fileStream.Write("TESTING THIS FILE");
                        }
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.beam.runners.direct;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Callable;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.runners.core.metrics.MetricUpdates;
import org.apache.beam.runners.core.metrics.MetricsContainerImpl;
import org.apache.beam.sdk.metrics.MetricsEnvironment;
import org.apache.beam.sdk.runners.AppliedPTransform;
import org.apache.beam.sdk.util.WindowedValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@link Callable} responsible for constructing a {@link TransformEvaluator} from a {@link
 * TransformEvaluatorFactory} and evaluating it on some bundle of input, and registering the result
 * using a registered {@link CompletionCallback}.
 */
class DirectTransformExecutor<T> implements TransformExecutor {
  private static final Logger LOG = LoggerFactory.getLogger(DirectTransformExecutor.class);

  static class Factory implements TransformExecutorFactory {
    private final EvaluationContext context;
    private final TransformEvaluatorRegistry registry;
    private final Map<String, Collection<ModelEnforcementFactory>> transformEnforcements;

    Factory(
        EvaluationContext context,
        TransformEvaluatorRegistry registry,
        Map<String, Collection<ModelEnforcementFactory>> transformEnforcements) {
      this.context = context;
      this.registry = registry;
      this.transformEnforcements = transformEnforcements;
    }

    @Override
    public TransformExecutor create(
        CommittedBundle<?> bundle,
        AppliedPTransform<?, ?, ?> transform,
        CompletionCallback onComplete,
        TransformExecutorService executorService) {
      Collection<ModelEnforcementFactory> enforcements =
          MoreObjects.firstNonNull(
              transformEnforcements.get(
                  PTransformTranslation.urnForTransform(transform.getTransform())),
              Collections.<ModelEnforcementFactory>emptyList());
      return new DirectTransformExecutor<>(
          context, registry, enforcements, bundle, transform, onComplete, executorService);
    }
  }

  private final TransformEvaluatorRegistry evaluatorRegistry;
  private final Iterable<? extends ModelEnforcementFactory> modelEnforcements;

  /** The transform that will be evaluated. */
  private final AppliedPTransform<?, ?, ?> transform;
  /** The inputs this {@link DirectTransformExecutor} will deliver to the transform. */
  private final CommittedBundle<T> inputBundle;

  private final CompletionCallback onComplete;
  private final TransformExecutorService transformEvaluationState;
  private final EvaluationContext context;

  @VisibleForTesting
  DirectTransformExecutor(
      EvaluationContext context,
      TransformEvaluatorRegistry factory,
      Iterable<? extends ModelEnforcementFactory> modelEnforcements,
      CommittedBundle<T> inputBundle,
      AppliedPTransform<?, ?, ?> transform,
      CompletionCallback completionCallback,
      TransformExecutorService transformEvaluationState) {
    this.evaluatorRegistry = factory;
    this.modelEnforcements = modelEnforcements;

    this.inputBundle = inputBundle;
    this.transform = transform;

    this.onComplete = completionCallback;

    this.transformEvaluationState = transformEvaluationState;
    this.context = context;
  }

  @Override
  public void run() {
    MetricsContainerImpl metricsContainer = new MetricsContainerImpl(transform.getFullName());
    try (Closeable metricsScope = MetricsEnvironment.scopedMetricsContainer(metricsContainer)) {
      Collection<ModelEnforcement<T>> enforcements = new ArrayList<>();
      for (ModelEnforcementFactory enforcementFactory : modelEnforcements) {
        ModelEnforcement<T> enforcement = enforcementFactory.forBundle(inputBundle, transform);
        enforcements.add(enforcement);
      }
      TransformEvaluator<T> evaluator =
          evaluatorRegistry.forApplication(transform, inputBundle);
      if (evaluator == null) {
        onComplete.handleEmpty(transform);
        // Nothing to do
        return;
      }

      processElements(evaluator, metricsContainer, enforcements);

      finishBundle(evaluator, metricsContainer, enforcements);
    } catch (Exception e) {
      onComplete.handleException(inputBundle, e);
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }
      throw new RuntimeException(e);
    } catch (Error err) {
      LOG.error("Error occurred within {}", this, err);
      onComplete.handleError(err);
      throw err;
    } finally {
      // Report the physical metrics from the end of this step.
      context.getMetrics().commitPhysical(inputBundle, metricsContainer.getCumulative());

      transformEvaluationState.complete(this);
    }
  }

  /**
   * Processes all the elements in the input bundle using the transform evaluator, applying any
   * necessary {@link ModelEnforcement ModelEnforcements}.
   */
  private void processElements(
      TransformEvaluator<T> evaluator,
      MetricsContainerImpl metricsContainer,
      Collection<ModelEnforcement<T>> enforcements)
      throws Exception {
    if (inputBundle != null) {
      for (WindowedValue<T> value : inputBundle.getElements()) {
        for (ModelEnforcement<T> enforcement : enforcements) {
          enforcement.beforeElement(value);
        }

        evaluator.processElement(value);

        // Report the physical metrics after each element
        MetricUpdates deltas = metricsContainer.getUpdates();
        if (deltas != null) {
          context.getMetrics().updatePhysical(inputBundle, deltas);
          metricsContainer.commitUpdates();
        }

        for (ModelEnforcement<T> enforcement : enforcements) {
          enforcement.afterElement(value);
        }
      }
    }
  }

  /**
   * Finishes processing the input bundle and commit the result using the
   * {@link CompletionCallback}, applying any {@link ModelEnforcement} if necessary.
   *
   * @return the {@link TransformResult} produced by
   *         {@link TransformEvaluator#finishBundle()}
   */
  private TransformResult<T> finishBundle(
      TransformEvaluator<T> evaluator, MetricsContainerImpl metricsContainer,
      Collection<ModelEnforcement<T>> enforcements)
      throws Exception {
    TransformResult<T> result =
        evaluator.finishBundle().withLogicalMetricUpdates(metricsContainer.getCumulative());
    CommittedResult outputs = onComplete.handleResult(inputBundle, result);
    for (ModelEnforcement<T> enforcement : enforcements) {
      enforcement.afterFinish(inputBundle, result, outputs.getOutputs());
    }
    return result;
  }
}


text:
import threading
import time

from hazelcast import HazelcastClient
from hazelcast.core import Address
from tests.base import HazelcastTestCase
from tests.util import open_connection_to_address, wait_for_partition_table

class HeartbeatTest(HazelcastTestCase):
    rc = None

    @classmethod
    def setUpClass(cls):
        cls.rc = cls.create_rc()

    @classmethod
    def tearDownClass(cls):
        cls.rc.exit()

    def setUp(self):
        self.cluster = self.create_cluster(self.rc)
        self.member = self.rc.startMember(self.cluster.id)
        self.client = HazelcastClient(
            cluster_name=self.cluster.id,
            heartbeat_interval=0.5,
            heartbeat_timeout=2,
        )

    def tearDown(self):
        self.client.shutdown()
        self.rc.shutdownCluster(self.cluster.id)

    def test_heartbeat_stopped_and_restored(self):
        member2 = self.rc.startMember(self.cluster.id)
        addr = Address(member2.host, member2.port)
        wait_for_partition_table(self.client)
        open_connection_to_address(self.client, member2.uuid)

        def connection_collector():
            connections = []

            def collector(c, *_):
                connections.append(c)

            collector.connections = connections
            return collector

        connection_added_collector = connection_collector()
        connection_removed_collector = connection_collector()

        self.client._connection_manager.add_listener(
            connection_added_collector, connection_removed_collector
        )

        assertion_succeeded = False

        def run():
            nonlocal assertion_succeeded
            # It is possible for client to override the set last_read_time
            # of the connection, in case of the periodically sent heartbeat
            # requests getting responses, right after we try to set a new
            # value to it, before the next iteration of the heartbeat manager.
            # In this case, the connection won't be closed, and the test would
            # fail. To avoid it, we will try multiple times.
            for i in range(10):
                if assertion_succeeded:
                    # We have successfully simulated heartbeat loss
                    return

                for connection in self.client._connection_manager.active_connections.values():
                    if connection.remote_address == addr:
                        connection.last_read_time -= 2
                        break

                time.sleep((i + 1) * 0.1)

        simulation_thread = threading.Thread(target=run)
        simulation_thread.start()

        def assert_heartbeat_stopped_and_restored():
            nonlocal assertion_succeeded
            self.assertGreaterEqual(len(connection_added_collector.connections), 1)
            self.assertGreaterEqual(len(connection_removed_collector.connections), 1)

            stopped_connection = connection_removed_collector.connections[0]
            restored_connection = connection_added_collector.connections[0]

            self.assertEqual(
                stopped_connection.connected_address,
                Address(member2.host, member2.port),
            )
            self.assertEqual(
                restored_connection.connected_address,
                Address(member2.host, member2.port),
            )
            assertion_succeeded = True

        self.assertTrueEventually(assert_heartbeat_stopped_and_restored)
        simulation_thread.join()


text:
module.exports = Client

var browserify = require('browserify/bin/args.js')
  , tracejs = require('tracejs').trace
  , path = require('path')
  , util = require('util')
  , fs = require('fs')

var DIR = path.resolve(path.join(__dirname, '..'))
  , test_tr = require('./test_transform')
  , hash = require('./hash')

function Client(dnode, conn, for_browserify, browserify_options, failfast) {
  this.browserify = !!for_browserify
  this.browserify_options = browserify_options
  this.failfast = failfast
  this.dnode = dnode
  conn.on('end', this.disconnect_all.bind(this))
}

var cons = Client
  , proto = cons.prototype

// server side
proto.send = function(message) {

}

proto.disconnect_all = function() {
  for(var key in this) if(typeof this[key] == 'function')
    this[key] = Function()

  this.okay = Function('return false')
}

proto.okay = function() {
  return true
}

proto.repl_get = function(ident, ready) {
  this.dnode.repl_get(ident, ready)
}

proto.repl_put = function(json_str) {
  this.dnode.repl_put(json_str)
}

proto.update = function(file, msg, suite, test_number) {
  this.dnode.update(file, msg, suite, test_number)
}

proto.report = function(env, name, result_data, is_done, total_tests) {
  this.dnode.report(env, name, result_data, is_done, total_tests)
}

proto.load = function(suite_name, ready) {
  this.dnode.load(suite_name, ready)
}

proto.load_media = function(endpoint, ready) {
  this.dnode.load_media(endpoint, ready)
}

proto.load_html = function(from_suite, endpoint, ready) {
  this.dnode.load_html(from_suite, endpoint, ready)
}

proto.console = function(env_type, json_str) {
  this.dnode.console(env_type, json_str)
}

function Local(cli, files) {
  this.cwd = process.cwd()
  this.num_errors = 0
  this.cli = cli
  this.browserify = !!cli.options.browserify
  this.browserify_options = cli.browserify_options || []
  this.current_suite = null
  this.failfast = cli.options.failfast
  this.files = files

}

proto = Local.prototype

proto.output = function(data) {
  this.cli.write(data)
}

proto.update = function(name, type, suite_info, test_number) {
  var msg

  if(this.cli.options.tap) {
    if(suite_info.suite.name !== this.current_suite) {
      var suite_test_count = Object.keys(suite_info.suite.members).length

      this.current_suite = suite_info.suite.name
      this.cli.write(
          '### ' + this.current_suite + ' (' +
          suite_test_count + ' tests)\n'
      )
    }

    msg = type === 'pass' ? 'ok ' : 'not ok '
    msg += test_number + ' - ' + suite_info.test + '\n'
  } else {
    msg = {
        pass: '.'
      , fail: 'F'
      , error: 'E'
    }[type] || '?'
  }

  this.cli.write(msg)

  type !== 'pass' && ++this.num_errors
}

proto.load = function(name, ready) {
  fs.readFile(path.join(this.cwd, name), 'utf8', ready)
}

proto.bundle_browserify = function(tests, ready) {
  var self = this
    , browserify_options = {}
    , bundler_options = {}
    , CWD = process.cwd()
    , test_bundles = {}
    , bundler
    , argv

  argv = self.browserify_options.slice()

  // inject a transform, insert globals by
  // default, debug by default
  argv = argv.concat([
      '-t'
    , path.join(__dirname, 'test_transform.js')
    , '-ig'
    , '-d'
  ])

  bundler = browserify(argv)
  tests.forEach(bundle_tests)
  bundler.bundle(bundler_options, onbundled)

  function bundle_tests(file) {
    var name = hash.hash(file)

    bundler.require(resolve_file(file), { expose: name })
    test_bundles[file] = name
  }

  function onbundled(err, data) {
    if(err) {
      return ready(err)
    }

    ready(null, data, test_bundles)
  }

  function resolve_file(file) {
    return path.resolve(CWD, file)
  }
}

proto.report = function(env, suite_name, result_data, is_done, total_tests) {
  var self = this
    , exceptions = []
    , coverage = {}
    , browsers = []
    , summary = {}

  process.removeAllListeners('uncaughtException')

  if(self.cli.options.tap) {
    self.cli.write('1..' + total_tests + '\n')

    self.cli.exit(self.num_errors)
  }

  Object.keys(result_data).forEach(function(browser) {
    browsers.push(browser)

    var passes = 0
      , errors = 0
      , fails = 0
      , ms = 0

    Object.keys(result_data[browser]).forEach(function(file) {

      var file_data = result_data[browser][file]

      if(file_data.coverage && Object.keys(file_data.coverage).length) {
        coverage[file] = coverage[file] || {}
        coverage[file].mask = file_data.coverage.mask
        coverage[file].browsers = coverage[file].browsers || {}
        coverage[file].browsers[browser] = file_data.coverage.cover
      }

      Object.keys(file_data.result).forEach(function(test_name) {
        var test_result = file_data.result[test_name]

        ms += test_result.elapsed

        if(test_result.pass) {
          ++passes
        } else {
          if(test_result.assertion)
            ++fails
          else
            ++errors

          var augmented = Object.create(test_result)

          augmented.test_file = file
          augmented.browser = browser
          augmented.fail = test_result.assertion
          augmented.stack = test_result.stacktrace

          exceptions.push(augmented)
        }
      })
    })

    summary[browser] = {passes:passes, fails:fails, errors:errors, total:passes+fails+errors, ms:ms}
  })

  self.cli.write('\n\n')

  exceptions.forEach(function(exception) {
    self.cli.write(
      '\n'+exception.test_file +
      ': ' +
      exception.browser +
      ': ' +
      (exception.fail ? 'FAIL' : 'ERROR') +
      '\n' +
      self.format_exc(exception.browser, exception, exception.fail)
    )
  })

  self.cli.write('\n\n')

  Object.keys(summary).forEach(function(browser) {
    var data = summary[browser]

    self.cli.write(browser+': '+(data.fails || data.errors ? 'FAIL' : 'PASS')+' in '+data.ms+'ms, (passed '+data.passes+'/'+data.total+' tests with '+data.errors+' errors, '+data.fails+' failures)\n')
  })

  if(!self.num_errors && Object.keys(coverage).length)
    self.report_coverage(coverage, browsers)

  if(is_done && self.cli.should_exit())
    self.cli.exit(self.num_errors)
}

function firefox_to_webkit(exc) {
  var bits = exc.stack.split('\n')

  return 'Error: '+exc.message+'\n'+bits.map(function(bit) {
    bit = bit.split(')@/')
    var fn = bit[0]
      , loc = bit[1]

    fn = fn.split('(')[0].replace(/\s+/g, '')
    loc = '/'+loc+':0'

    return '    '+'at '+(fn.length ? loc : fn +' ('+loc+')')
  }).join('\n')
}

proto.format_exc = function(browser, trace, is_fail) {
  var original_trace = trace

  function replace_http(cwd, str) {
    return str
      .replace(/http(s)?:\/\/([^\/]+)(:\d+)?\/media\//g, path.join(__dirname, '..', 'public')+'/')
      .replace(/http(s)?:\/\/([^\/]+)(:\d+)?\/([\w\d\-]+)\/([\w\d\-]+)\/_media\//g, cwd+'/')
  }

  trace = replace_http(
      this.cwd
    , trace.stack || ('Error: '+trace.message+'\n    at <unknown> ('+trace.sourceURL +':'+trace.lineNumber+':0)')
  )

  if(/firefox/i.test(browser) && original_trace.stack) {
    original_trace.stack = replace_http(this.cwd, original_trace.stack)

    trace = firefox_to_webkit(original_trace)
  }

  try {
    var traced = tracejs({stack:trace})

    traced.frames = traced.frames.filter(function(frame, idx) {
      return frame && frame.filename.indexOf(DIR) !== 0
    })

    return traced.toString()
  } catch(err) {

    return original_trace
  }

  return trace
}

proto.load_media = function(name, ready) {
  fs.readFile(path.join(this.cwd, name), 'utf8', ready)
}

proto.load_html = function(from_suite, template_path, ready) {
  template_path = path.join(path.dirname(path.join(this.cwd, from_suite)), template_path)

  fs.readFile(template_path, 'utf8', ready)
}

proto.exit = function() {
  process.exit(1)
}

proto.dnodify = function() {
  var out = {}

  out.browserify = this.browserify
  out.browserify_options = this.browserify_options || []
  out.failfast = this.failfast
  for(var key in this.constructor.prototype) if(this.constructor.prototype.hasOwnProperty(key))
    out[key] = this[key].bind(this)
  return out
}

proto.repl_put = function(json_str) {
  try {
    console.log(JSON.parse(json_str))
  } catch(err) {
    console.log(json_str)
  }
}

proto.okay = function() {
  return true
}

proto.repl_get = function(ident, ready) {
  this.cli.repl.take(ident, ready)
}

proto.console = function(env_type, json_str) {
  var json = JSON.parse(json_str)
  this.cli.write('\n===== '+env_type+' =====\n'+json.map(function(item) {
    return util.inspect(item, true, 5, true) + ' '
  })+'\n')
}

proto.environments = function(targets) {
  var self = this
  targets.forEach(function(target) {
    self.cli.write(target+'\n')
  })
}

proto.report_coverage = function(coverage, browsers) {
  // coverage: {<filename>:{browsers:BROWSERS, mask:MASK}, ...}
  // BROWSERS: {browser_name:{HASH:NUM}, ...}
  // MASK:     {HASH:{file:filename, start:"line:col", end:"line:col"}}
  var self = this
    , complete_mask = Object.create(null)
    , browser_results = {}
    , mask_by_file = []
    , common = {}
    , Empty = new Object
    , cached_files = {}

  // create an empty "results" object
  // for each available env.
  browsers.forEach(function(browser) {
    browser_results[browser] = {}
  })

  // iterate over the coverage object's different test suites,
  // accumulating a "complete mask" representing all hashes available
  // to all test suites.
  //
  // automatically assume every environment is missing every hash.
  iterobject(coverage, function(test, test_filename) {
    var mask = test.mask

    complete_mask = Object.create(complete_mask)
    iterobject(mask, function(item, hash) {
      complete_mask[hash] = item

      ;(mask_by_file[item.file] = mask_by_file[item.file] || []).push(hash)

      browsers.forEach(function(browser) {
        browser_results[browser][hash] = Empty
      })
    })
  })

  // iterate over the coverage object again, now that the mask is complete.
  // delete hashes from browsers who have results for that line.
  iterobject(coverage, function(test, test_file) {
    var browsers = test.browsers
    iterobject(browsers, function(hash_mask, browser_name) {
      iterobject(hash_mask, function(num, hash) {
        delete browser_results[browser_name][hash]
      })
    })
  })

  // roll-up the results into a "common" environment -- any hash
  // that is missing from **all** envs is placed here (in an effort
  // to make the output more readable).
  iterobject(browser_results, function(missing_hashes, browser_name) {
    iterobject(missing_hashes, function(xxx, hash) {
      if(hash in common) {
        // this hash is already common.
        return
      } else {
        var missing_in_all = browsers.every(function(other_browser_name) {
          if(other_browser_name === browser_name) return true
          return hash in browser_results[other_browser_name]
        })

        if(missing_in_all) {
          common[hash] = Empty
          // remove this missing hash from all other browsers.
          iterobject(browser_results, function(missing_hashes) {
            delete missing_hashes[hash]
          })
        }
      }
    })
  })

  // if there's any commonality, output it first.
  if(Object.keys(common).length) {
    output_results('ALL ENVS', common)
  }

  // and go through the browsers one last time,
  // displaying any "browser specific" missing lines.
  iterobject(browser_results, function(browser, title) {
    if(Object.keys(browser).length) {
      output_results(title, common)
    }
  })

  self.cli.write('\x1b[0m\n')

  function output_results(title, result_object) {
    var by_file = {}
    iterobject(result_object, function(loc, hash) {
      loc = complete_mask[hash]
      by_file[loc.file] = by_file[loc.file] || []
      by_file[loc.file].push(loc)
    })

    self.cli.write('\x1b[0m'+title+':\n')
    iterobject(by_file, function(locations, filename) {
      var lines = cached_files[filename] = cached_files[filename] || fs.readFileSync(filename, 'utf8').split('\n')
        , total = mask_by_file[filename].length
        , hit = total - by_file[filename].length
        , percent = ~~(hit / total * 100.0)
        , out = {}

      iterobject(locations, function(offsets) {
        var start = offsets.start.split(':')
          , start_line = start[0]
          , start_character = start[1]
          , end = offsets.end.split(':')
          , end_line = end[0]
          , end_character = 1 + ~~end[1]

        out[start_line] = out[start_line] || {offs:{}, no:start[0]}

        out[start_line].line = lines[start_line]
        out[start_line].offs[start_character] = 1
        out[start_line].offs[end_character] = -1
      })

      var color = percent > 80 ? 32 :
                  percent > 60 ? 33 :
                  percent > 40 ? 35 :
                  31

      self.cli.write('\x1b[0m'+filename+' ('+hit+'/'+total+', \x1b['+color+'m'+percent+'%\x1b[0m):\n')
      iterobject(out, function(output) {
        process.stderr.write('\x1b[33m'+pad(output.no)+':\x1b[0m')
        var color = 0
        for(var i = 0; i < output.line.length; ++i) {
          if(output.offs[i]) {
            color += output.offs[i]
            if(color > 0)
              process.stderr.write('\x1b[31m')
            else
              process.stderr.write('\x1b[0m')
          }
          process.stderr.write(output.line.charAt(i))
        }
        process.stderr.write('\n')
      })
    })
  }
}

    function pad(num) {
      num = ''+num
      while(num.length < 4)
        num = ' '+num
      return num
    }

function iterobject(obj, fn) {
  Object.keys(obj).forEach(function(key, idx) {
    return fn(obj[key], key, idx)
  })
}

Client.LocalClient = Local


text:
'use strict';

/*
 *  Module dependencies
*/

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var privs = {
  values = ['box1'],
  message : 'enum validator failed for `{PATH}` with value `{VALUE}`'
};

var AuthSchema = new Schema({
  name : {
    type : String,
    required: true
  },
  swipe : {
    type: String,
    enum : privs
    required: true
  },
  privs : [{
    type : String,
    enum: privs
  }]
  //TODO - Add experiation date
});

mongoose.model('Auth', AuthSchema);


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

namespace Ldp
{
    public class ScoreHolder
    {
        public float initialDistanceToPlanet;
        public float minimalDistanceSoFar;
        public float timeLeft;

        public ScoreHolder()
        {

        }

        public ScoreHolder(float initialDistance, float maxTime)
        {
            timeLeft = maxTime;
            initialDistanceToPlanet = initialDistance;
            minimalDistanceSoFar = initialDistanceToPlanet;
        }

        public float PartialScore
        {
            get { return initialDistanceToPlanet - minimalDistanceSoFar; }
        }

        public float FinalScore(bool alive)
        {
            if (alive)
            {
                return (initialDistanceToPlanet - minimalDistanceSoFar) * timeLeft;
            }
            return PartialScore;
        }

        public void SetMaxDistanceTowardsPlanet(Transform currentPosition, Transform targetPlanet)
        {
            float currentDistance = Vector2.Distance(currentPosition.position, targetPlanet.position) -
                (targetPlanet.localScale.x / 2);
            minimalDistanceSoFar = Mathf.Min(minimalDistanceSoFar, currentDistance);
        }
    }
}


text:
<?php

class DeleteController extends BtPageAdminController {

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionIndex($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
}


text:
class SmsCancellationSuccessJob < SmsJobBase
  TEMPLATE_ID = '1cbd533d-4cae-40a6-a2b5-339af96b3c58'.freeze

  def perform(appointment)
    return unless api_key

    appointment = LocationAwareEntity.new(
      entity: appointment,
      booking_location: BookingLocations.find(appointment.location_id)
    )

    send_sms(appointment)
  end

  private

  def send_sms(appointment)
    sms_client.send_sms(
      phone_number: appointment.phone,
      template_id: TEMPLATE_ID,
      reference: appointment.reference,
      personalisation: {
        date: appointment.proceeded_at.to_s(:govuk_date_short),
        location: appointment.location_name
      }
    )
  end
end


text:
@import UIKit;

@interface UIViewController (OBAContainment)

- (void)oba_removeChildViewController:(UIViewController*)viewController;
- (void)oba_addChildViewController:(UIViewController*)viewController;

@end


text:
@haspermission($permission, $tenant)
has permission
@else
does not have permission
@endhaspermission


text:
//
//  SerializeJSON.cc
//  snowcrash
//
//  Created by Zdenek Nemec on 4/27/13.
//  Copyright (c) 2013 Apiary Inc. All rights reserved.
//

#include "SerializeJSON.h"
#include "Serialize.h"

using namespace snowcrash;

static const std::string IndentBlock = "  ";
static const std::string NewLineItemBlock = ",\n";

/**
 * \brief Serialize a JSON string.
 * \param value    JSON string to serialize
 * \param os       An output stream to serialize into
 */
static void serialize(const std::string& value, std::ostream &os)
{
    os << "\"" << value << "\"";
}

/**
 * \brief Inserts indentation into an output stream.
 * \param level    Level of indentation
 * \param os       An output stream to serialize into
 */
static void indent(size_t level, std::ostream &os)
{
    for (size_t i = 0; i < level; ++i) {
        os << IndentBlock;
    }
}

/**
 * \brief Serialize key value pair into output stream.
 * \param key      Key to serialize
 * \param value    Value to serialize
 * \param level    Indentation level
 * \param object   Flag to indicate whether the pair should be serialized as an object
 * \param os       An output stream to serialize into
 */
static void serialize(const std::string& key, const std::string& value, size_t level, bool object, std::ostream &os)
{
    indent(level, os);

    if (object) {
        os << "{\n";
        indent(level + 1, os);
    }

    serialize(key, os);
    os << ": ";

    std::string normValue = EscapeDoubleQuotes(value);

    if (normValue.find("\n") != std::string::npos)
        serialize(EscapeNewlines(normValue), os);
    else
        serialize(normValue, os);

    if (object) {
        os << "\n";
        indent(level, os);
        os << "}";
    }
}

/**
 * \brief Serialize key boolean value pair into output stream
 * \param key      Key to serialize
 * \param value    Value to serialize
 * \param level    Indentation level
 * \param os       An output stream to serialize into
 */
static void serialize(const std::string& key, bool value, size_t level, std::ostream &os)
{
    indent(level, os);
    serialize(key, os);
    os << ": ";
    os << ((value) ? "true" : "false");
}

/**
 * \brief Serialize key value pair as an object into output stream
 * \param key      Key to serialize
 * \param value    Value to serialize
 * \param level    Indentation level
 * \param os       An output stream to serialize into
 */
static void serialize(const std::string& key, const std::string& value, size_t level, std::ostream &os)
{
    indent(level, os);

    os << "{\n";

    serialize(SerializeKey::Name, key, level + 1, false, os);
    os << NewLineItemBlock;

    serialize(SerializeKey::Value, value, level + 1, false, os);
    os << "\n";

    indent(level, os);
    os << "}";
}

/**
 * \brief Serialize source map without key into output stream
 * \param set      Source map
 * \param level    Indentation level
 * \param os       An output stream to serialize into
 */
static void serialize(const SourceMapBase& set, size_t level, std::ostream &os)
{
    os << "[";

    if (!set.sourceMap.empty()) {
        size_t i = 0;
        os << "\n";

        for (mdp::RangeSet<mdp::BytesRange>::const_iterator it = set.sourceMap.begin(); it != set.sourceMap.end(); ++i, ++it) {

            if (i > 0 && i < set.sourceMap.size())
                os << NewLineItemBlock;

            indent(level + 1, os);
            os << "[" << it->location << ", " << it->length << "]";
        }

        os << std::endl;
        indent(level, os);
    }

    os << "]";
}

/**
 * \brief Serialize a key and source map value into output stream.
 * \param key      Key to serialize
 * \param value    Source Map to serialize
 * \param level    Indentation level
 * \param object   Flag to indicate whether the pair should be serialized as an object
 * \param os       An output stream to serialize into
 */
static void serialize(const std::string& key, const SourceMapBase& value, size_t level, bool object, std::ostream &os)
{
    indent(level, os);

    if (object) {
        os << "{\n";
        indent(level + 1, os);
    }

    serialize(key, os);
    os << ": ";

    serialize(value, level, os);

    if (object) {
        os << "\n";
        indent(level, os);
        os << "}";
    }
}

/**
 * \brief Serialize an array of source maps.
 * \param collection    Collection to serialize
 * \param level         Level of indentation
 * \param os            An output stream to serialize into
 */
static void serializeSourceMapCollection(const Collection<SourceMap<KeyValuePair> >::type& collection, size_t level, std::ostream &os)
{
    os << "[";

    if (!collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<KeyValuePair> >::const_iterator it = collection.begin(); it != collection.end(); ++i, ++it) {

            if (i > 0 && i < collection.size())
                os << NewLineItemBlock;

            indent(level + 1, os);
            serialize(*it, level + 1, os);
        }

        os << "\n";
        indent(level, os);
    }

    os << "]";
}

/**
 * \brief Serialize an array of key value pairs.
 * \param collection    Collection to serialize
 * \param level         Level of indentation
 * \param os            An output stream to serialize into
 */
static void serializeKeyValueCollection(const Collection<KeyValuePair>::type& collection, size_t level, std::ostream &os)
{
    os << "[";

    if (!collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<KeyValuePair>::const_iterator it = collection.begin(); it != collection.end(); ++i, ++it) {

            if (i > 0 && i < collection.size())
                os << NewLineItemBlock;

            serialize(it->first, it->second, level + 1, os);
        }

        os << "\n";
        indent(level, os);
    }

    os << "]";
}

/**
 * \brief Serialize Metadata into output stream.
 * \param metadata  Metadata to serialize
 * \param os        An output stream to serialize into
 */
static void serialize(const MetadataCollection& metadata, std::ostream &os)
{
    indent(1, os);
    serialize(SerializeKey::Metadata, os);
    os << ": ";

    serializeKeyValueCollection(metadata, 1, os);

    os << NewLineItemBlock;
}

/**
 * \brief Serialize Metadata source map into output stream.
 * \param metadata  Metadata source map to serialize
 * \param os        An output stream to serialize into
 */
static void serialize(const Collection<SourceMap<Metadata> >::type& metadata, std::ostream &os)
{
    indent(1, os);
    serialize(SerializeKey::Metadata, os);
    os << ": ";

    serializeSourceMapCollection(metadata, 1, os);

    os << NewLineItemBlock;
}

/**
 * \brief Serialize Parameters into output stream.
 * \param prarameters   Parameters to serialize.
 * \param level         Level of indentation.
 * \param os            An output stream to serialize into.
 */
static void serialize(const Parameters& parameters, size_t level, std::ostream &os)
{
    indent(level, os);
    serialize(SerializeKey::Parameters, os);
    os << ": [";

    if (!parameters.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<Parameter>::const_iterator it = parameters.begin(); it != parameters.end(); ++i, ++it) {

            if (i > 0 && i < parameters.size())
                os << NewLineItemBlock;

            indent(level + 1, os);
            os << "{\n";

            // Name
            serialize(SerializeKey::Name, it->name, level + 2, false, os);
            os << NewLineItemBlock;

            // Description
            serialize(SerializeKey::Description, it->description, level + 2, false, os);
            os << NewLineItemBlock;

            // Type
            serialize(SerializeKey::Type, it->type, level + 2, false, os);
            os << NewLineItemBlock;

            // Requried
            serialize(SerializeKey::Required, (it->use != OptionalParameterUse), level + 2, os);
            os << NewLineItemBlock;

            // Default
            serialize(SerializeKey::Default, it->defaultValue, level + 2, false, os);
            os << NewLineItemBlock;

            // Example
            serialize(SerializeKey::Example, it->exampleValue, level + 2, false, os);
            os << NewLineItemBlock;

            // Values
            indent(level + 2, os);
            serialize(SerializeKey::Values, os);
            os << ": [";

            if (!it->values.empty()) {
                os << "\n";
                size_t j = 0;

                for (Collection<Value>::const_iterator val_it = it->values.begin();
                     val_it != it->values.end();
                     ++j, ++val_it) {

                    if (j > 0 && j < it->values.size())
                        os << NewLineItemBlock;

                    serialize(SerializeKey::Value, *val_it, level + 3, true, os);
                }

                os << "\n";
                indent(level + 2, os);
            }

            // Close Values
            os << "]";

            // Close Key / name object
            os << "\n";
            indent(level + 1, os);
            os << "}";
        }

        os << std::endl;
        indent(level, os);
    }

    os << "]";
}

/**
 * \brief Serialize Parameters source map into output stream.
 * \param prarameters   Parameters source map to serialize.
 * \param level         Level of indentation.
 * \param os            An output stream to serialize into.
 */
static void serialize(const Collection<SourceMap<Parameter> >::type& parameters, size_t level, std::ostream &os)
{
    indent(level, os);
    serialize(SerializeKey::Parameters, os);
    os << ": [";

    if (!parameters.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<Parameter> >::const_iterator it = parameters.begin(); it != parameters.end(); ++i, ++it) {

            if (i > 0 && i < parameters.size())
                os << NewLineItemBlock;

            indent(level + 1, os);
            os << "{\n";

            // Name
            serialize(SerializeKey::Name, it->name, level + 2, false, os);
            os << NewLineItemBlock;

            // Description
            serialize(SerializeKey::Description, it->description, level + 2, false, os);
            os << NewLineItemBlock;

            // Type
            serialize(SerializeKey::Type, it->type, level + 2, false, os);
            os << NewLineItemBlock;

            // Requried
            serialize(SerializeKey::Required, it->use, level + 2, false, os);
            os << NewLineItemBlock;

            // Default
            serialize(SerializeKey::Default, it->defaultValue, level + 2, false, os);
            os << NewLineItemBlock;

            // Example
            serialize(SerializeKey::Example, it->exampleValue, level + 2, false, os);
            os << NewLineItemBlock;

            // Values
            indent(level + 2, os);
            serialize(SerializeKey::Values, os);
            os << ": [";

            if (!it->values.collection.empty()) {
                os << "\n";
                size_t j = 0;

                indent(level + 3, os);

                for (Collection<SourceMap<Value> >::const_iterator val_it = it->values.collection.begin();
                     val_it != it->values.collection.end();
                     ++j, ++val_it) {

                    if (j > 0 && j < it->values.collection.size())
                        os << NewLineItemBlock;

                    serialize(*val_it, level + 3, os);
                }

                os << "\n";
                indent(level + 2, os);
            }

            // Close Values
            os << "]";

            // Close Key / name object
            os << "\n";
            indent(level + 1, os);
            os << "}";
        }

        os << std::endl;
        indent(level, os);
    }

    os << "]";
}

/**
 * \brief Serialize HTTP headers into output stream.
 * \param headers   Headers to serialize.
 * \param level Level of indentation.
 * \param os    An output stream to serialize into.
 */
static void serialize(const Headers& headers, size_t level, std::ostream &os)
{
    indent(level, os);
    serialize(SerializeKey::Headers, os);
    os << ": ";

    serializeKeyValueCollection(headers, level, os);
}

/**
 * \brief Serialize HTTP headers source map into output stream.
 * \param headers   Headers source map to serialize.
 * \param level Level of indentation.
 * \param os    An output stream to serialize into.
 */
static void serialize(const Collection<SourceMap<Header> >::type& headers, size_t level, std::ostream &os)
{
    indent(level, os);
    serialize(SerializeKey::Headers, os);
    os << ": ";

    serializeSourceMapCollection(headers, level, os);
}

/**
 * \brief Serialize a reference into output stream.
 * \param reference A reference to serialize.
 * \param os An output stream to serialize into.
 */
static void serialize(const Reference& reference, size_t level, std::ostream &os)
{

    if (reference.id.empty()) {
        return;
    }

    indent(level, os);
    os << "\"" << SerializeKey::Reference << "\": {\n";

    serialize(SerializeKey::Id, reference.id, level + 1, false, os);
    os << "\n";

    indent(level, os);
    os << "}";

    os << NewLineItemBlock;
}

/**
 * \brief Serialize a reference source map into output stream.
 * \param reference A reference source map to serialize.
 * \param os An output stream to serialize into.
 */
static void serialize(const SourceMap<Reference>& reference, size_t level, std::ostream &os)
{

    if (reference.sourceMap.empty()) {
        return;
    }

    serialize(SerializeKey::Reference, reference, level, false, os);
    os << NewLineItemBlock;
}

/**
 * \brief Serialize a payload into output stream.
 * \param payload   A payload to serialize.
 * \param os    An output stream to serialize into.
 */
static void serialize(const Payload& payload, size_t level, std::ostream &os)
{
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, payload.name, level + 1, false, os);
    os << NewLineItemBlock;

    // Reference
    serialize(payload.reference, level + 1, os);

    // Description
    serialize(SerializeKey::Description, payload.description, level + 1, false, os);
    os << NewLineItemBlock;

    // Headers
    serialize(payload.headers, level + 1, os);
    os << NewLineItemBlock;

    // Body
    serialize(SerializeKey::Body, payload.body, level + 1, false, os);
    os << NewLineItemBlock;

    // Schema
    serialize(SerializeKey::Schema, payload.schema, level + 1, false, os);

    os << "\n";
    indent(level, os);
    os << "}";
}

/**
 * \brief Serialize a payload source map into output stream.
 * \param payload   A payload source map to serialize.
 * \param os    An output stream to serialize into.
 */
static void serialize(const SourceMap<Payload>& payload, size_t level, std::ostream &os)
{
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, payload.name, level + 1, false, os);
    os << NewLineItemBlock;

    // Symbol Reference
    serialize(payload.reference, level + 1, os);

    // Description
    serialize(SerializeKey::Description, payload.description, level + 1, false, os);
    os << NewLineItemBlock;

    // Headers
    serialize(payload.headers.collection, level + 1, os);
    os << NewLineItemBlock;

    // Body
    serialize(SerializeKey::Body, payload.body, level + 1, false, os);
    os << NewLineItemBlock;

    // Schema
    serialize(SerializeKey::Schema, payload.schema, level + 1, false, os);

    os << "\n";
    indent(level, os);
    os << "}";
}

/**
 * \brief Serialize a transaction example into output stream.
 * \param transaction   A transaction example to serialize.
 * \param os            An output stream to serialize into.
 */
static void serialize(const TransactionExample& example, std::ostream &os)
{
    indent(8, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, example.name, 9, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, example.description, 9, false, os);
    os << NewLineItemBlock;

    // Requests
    indent(9, os);
    serialize(SerializeKey::Requests, os);
    os << ": ";
    os << "[";

    if (!example.requests.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<Request>::const_iterator it = example.requests.begin();
             it != example.requests.end();
             ++i, ++it) {

            if (i > 0 && i < example.requests.size())
                os << NewLineItemBlock;

            indent(10, os);
            serialize(*it, 10, os);
        }

        os << "\n";
        indent(9, os);
    }
    os << "]";
    os << NewLineItemBlock;

    // Responses
    indent(9, os);
    serialize(SerializeKey::Responses, os);
    os << ": ";
    os << "[";

    if (!example.responses.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<Response>::const_iterator it = example.responses.begin();
             it != example.responses.end();
             ++i, ++it) {

            if (i > 0 && i < example.responses.size())
                os << NewLineItemBlock;

            indent(10, os);
            serialize(*it, 10, os);
        }

        os << "\n";
        indent(9, os);
    }
    os << "]";

    // Close the transaction
    os << "\n";
    indent(8, os);
    os << "}";
}

/**
 * \brief Serialize a transaction example source map into output stream.
 * \param transaction   A transaction example source map to serialize.
 * \param os            An output stream to serialize into.
 */
static void serialize(const SourceMap<TransactionExample>& example, std::ostream &os)
{
    indent(8, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, example.name, 9, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, example.description, 9, false, os);
    os << NewLineItemBlock;

    // Requests
    indent(9, os);
    serialize(SerializeKey::Requests, os);
    os << ": ";
    os << "[";

    if (!example.requests.collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<Request> >::const_iterator it = example.requests.collection.begin();
             it != example.requests.collection.end();
             ++i, ++it) {

            if (i > 0 && i < example.requests.collection.size())
                os << NewLineItemBlock;

            indent(10, os);
            serialize(*it, 10, os);
        }

        os << "\n";
        indent(9, os);
    }
    os << "]";
    os << NewLineItemBlock;

    // Responses
    indent(9, os);
    serialize(SerializeKey::Responses, os);
    os << ": ";
    os << "[";

    if (!example.responses.collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<Response> >::const_iterator it = example.responses.collection.begin();
             it != example.responses.collection.end();
             ++i, ++it) {

            if (i > 0 && i < example.responses.collection.size())
                os << NewLineItemBlock;

            indent(10, os);
            serialize(*it, 10, os);
        }

        os << "\n";
        indent(9, os);
    }
    os << "]";

    // Close the transaction
    os << "\n";
    indent(8, os);
    os << "}";
}

/**
 * \brief Serialize an action into output stream.
 * \param action    The action to serialize.
 * \param os        An output stream to serialize into.
 */
static void serialize(const Action& action, std::ostream &os)
{
    indent(6, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, action.name, 7, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, action.description, 7, false, os);
    os << NewLineItemBlock;

    // HTTP Method
    serialize(SerializeKey::Method, action.method, 7, false, os);
    os << NewLineItemBlock;

    // Parameters
    serialize(action.parameters, 7, os);
    os << NewLineItemBlock;

    // Transactions
    indent(7, os);
    serialize(SerializeKey::Examples, os);
    os << ": ";
    os << "[";

    if (!action.examples.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<TransactionExample>::const_iterator it = action.examples.begin();
             it != action.examples.end();
             ++i, ++it) {

            if (i > 0 && i < action.examples.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        os << "\n";
        indent(7, os);
    }

    os << "]";

    // Close the action
    os << "\n";
    indent(6, os);
    os << "}";
}

/**
 * \brief Serialize an action source map into output stream.
 * \param action    The action source map to serialize.
 * \param os        An output stream to serialize into.
 */
static void serialize(const SourceMap<Action>& action, std::ostream &os)
{
    indent(6, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, action.name, 7, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, action.description, 7, false, os);
    os << NewLineItemBlock;

    // HTTP Method
    serialize(SerializeKey::Method, action.method, 7, false, os);
    os << NewLineItemBlock;

    // Parameters
    serialize(action.parameters.collection, 7, os);
    os << NewLineItemBlock;

    // Transactions
    indent(7, os);
    serialize(SerializeKey::Examples, os);
    os << ": ";
    os << "[";

    if (!action.examples.collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<TransactionExample> >::const_iterator it = action.examples.collection.begin();
             it != action.examples.collection.end();
             ++i, ++it) {

            if (i > 0 && i < action.examples.collection.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        os << "\n";
        indent(7, os);
    }

    os << "]";

    // Close the action
    os << "\n";
    indent(6, os);
    os << "}";
}

/**
 * \brief Serialize a resource into output stream.
 * \param resource     A resource to serialize
 * \param os           An output stream to serialize into
 */
static void serialize(const Resource& resource, std::ostream &os)
{
    indent(4, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, resource.name, 5, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, resource.description, 5, false, os);
    os << NewLineItemBlock;

    // URI template
    serialize(SerializeKey::URITemplate, resource.uriTemplate, 5, false, os);
    os << NewLineItemBlock;

    // Model
    indent(5, os);
    serialize(SerializeKey::Model, os);
    if (resource.model.name.empty()) {
        os << ": {}";
    }
    else {
        os << ": ";

        serialize(resource.model, 5, os);
    }
    os << NewLineItemBlock;

    // Parameters
    serialize(resource.parameters, 5, os);
    os << NewLineItemBlock;

    // Actions
    indent(5, os);
    serialize(SerializeKey::Actions, os);
    os << ": ";
    os << "[";

    if (!resource.actions.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<Action>::const_iterator it = resource.actions.begin();
             it != resource.actions.end();
             ++i, ++it) {

            if (i > 0 && i < resource.actions.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        os << "\n";
        indent(5, os);
    }

    os << "]";

    // Close the resource
    os << "\n";
    indent(4, os);
    os << "}";
}

/**
 * \brief Serialize a resource source map into output stream.
 * \param resource     A resource source map to serialize
 * \param os           An output stream to serialize into
 */
static void serialize(const SourceMap<Resource>& resource, std::ostream &os)
{
    indent(4, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, resource.name, 5, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, resource.description, 5, false, os);
    os << NewLineItemBlock;

    // URI template
    serialize(SerializeKey::URITemplate, resource.uriTemplate, 5, false, os);
    os << NewLineItemBlock;

    // Model
    indent(5, os);
    serialize(SerializeKey::Model, os);
    if (resource.model.name.sourceMap.empty()) {
        os << ": {}";
    }
    else {
        os << ": ";

        serialize(resource.model, 5, os);
    }
    os << NewLineItemBlock;

    // Parameters
    serialize(resource.parameters.collection, 5, os);
    os << NewLineItemBlock;

    // Actions
    indent(5, os);
    serialize(SerializeKey::Actions, os);
    os << ": ";
    os << "[";

    if (!resource.actions.collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<Action> >::const_iterator it = resource.actions.collection.begin();
             it != resource.actions.collection.end();
             ++i, ++it) {

            if (i > 0 && i < resource.actions.collection.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        os << "\n";
        indent(5, os);
    }

    os << "]";

    // Close the resource
    os << "\n";
    indent(4, os);
    os << "}";
}

/**
 * \brief Serialize a group of resources into output stream.
 * \param resourceGroup A group to serialize.
 * \brief os    An output stream to serialize into.
 */
static void serialize(const ResourceGroup& resourceGroup, std::ostream &os)
{
    indent(2, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, resourceGroup.name, 3, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, resourceGroup.description, 3, false, os);
    os << NewLineItemBlock;

    // Resources
    indent(3, os);
    serialize(SerializeKey::Resources, os);
    os << ": ";
    os << "[";

    if (!resourceGroup.resources.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<Resource>::const_iterator it = resourceGroup.resources.begin();
             it != resourceGroup.resources.end();
             ++i, ++it) {

            if (i > 0 && i < resourceGroup.resources.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        if (!resourceGroup.resources.empty()) {
            os << "\n";
            indent(3, os);
        }
    }

    os << "]";

    // Close the group
    os << "\n";
    indent(2, os);
    os << "}";
}

/**
 * \brief Serialize a source map of group of resources into output stream.
 * \param resourceGroup Source map of a group to serialize.
 * \brief os    An output stream to serialize into.
 */
static void serialize(const SourceMap<ResourceGroup>& resourceGroup, std::ostream &os)
{
    indent(2, os);
    os << "{\n";

    // Name
    serialize(SerializeKey::Name, resourceGroup.name, 3, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, resourceGroup.description, 3, false, os);
    os << NewLineItemBlock;

    // Resources
    indent(3, os);
    serialize(SerializeKey::Resources, os);
    os << ": ";
    os << "[";

    if (!resourceGroup.resources.collection.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<Resource> >::const_iterator it = resourceGroup.resources.collection.begin();
             it != resourceGroup.resources.collection.end();
             ++i, ++it) {

            if (i > 0 && i < resourceGroup.resources.collection.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        if (!resourceGroup.resources.collection.empty()) {
            os << "\n";
            indent(3, os);
        }
    }

    os << "]";

    // Close the group
    os << "\n";
    indent(2, os);
    os << "}";
}

/**
 * \brief Serialize Resource Groups into output stream.
 * \param resourceGroups Resource Groups to serialize.
 * \param os             An output stream to serialize into.
 */
static void serialize(const ResourceGroups& resourceGroups, std::ostream &os)
{
    indent(1, os);
    serialize(SerializeKey::ResourceGroups, os);
    os << ": ";
    os << "[";

    if (!resourceGroups.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<ResourceGroup>::const_iterator it = resourceGroups.begin(); it != resourceGroups.end(); ++i, ++it) {

            if (i > 0 && i < resourceGroups.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        os << "\n";
        indent(1, os);
    }

    os << "]";
}

/**
 * \brief Serialize Resource Groups source map into output stream.
 * \param resourceGroups Resource Groups source map to serialize.
 * \param os             An output stream to serialize into.
 */
static void serialize(const Collection<SourceMap<ResourceGroup> >::type& resourceGroups, std::ostream &os)
{
    indent(1, os);
    serialize(SerializeKey::ResourceGroups, os);
    os << ": ";
    os << "[";

    if (!resourceGroups.empty()) {
        os << "\n";
        size_t i = 0;

        for (Collection<SourceMap<ResourceGroup> >::const_iterator it = resourceGroups.begin(); it != resourceGroups.end(); ++i, ++it) {

            if (i > 0 && i < resourceGroups.size())
                os << NewLineItemBlock;

            serialize(*it, os);
        }

        os << "\n";
        indent(1, os);
    }

    os << "]";
}

/**
 * \brief Serialize a blueprint into output stream.
 * \param blueprint     The blueprint to serialize.
 * \param os            An output stream to serialize into.
 */
static void serialize(const Blueprint& blueprint, std::ostream &os)
{
    os << "{\n";

    // AST Version
    serialize(SerializeKey::ASTVersion, AST_SERIALIZATION_VERSION, 1, false, os);
    os << NewLineItemBlock;

    // Metadata
    serialize(blueprint.metadata, os);

    // Name
    serialize(SerializeKey::Name, blueprint.name, 1, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, blueprint.description, 1, false, os);
    os << NewLineItemBlock;

    // Resource Groups
    serialize(blueprint.resourceGroups, os);

    os << "\n}\n";
}

/**
 * \brief Serialize a blueprint source map into output stream.
 * \param blueprint     The blueprint source map to serialize.
 * \param os            An output stream to serialize into.
 */
static void serialize(const SourceMap<Blueprint>& blueprint, std::ostream &os)
{
    os << "{\n";

    // Metadata
    serialize(blueprint.metadata.collection, os);

    // Name
    serialize(SerializeKey::Name, blueprint.name, 1, false, os);
    os << NewLineItemBlock;

    // Description
    serialize(SerializeKey::Description, blueprint.description, 1, false, os);
    os << NewLineItemBlock;

    // Resource Groups
    serialize(blueprint.resourceGroups.collection, os);

    os << "\n}\n";
}

void snowcrash::SerializeJSON(const snowcrash::Blueprint& blueprint, std::ostream &os)
{
    serialize(blueprint, os);
}

void snowcrash::SerializeSourceMapJSON(const snowcrash::SourceMap<snowcrash::Blueprint>& blueprint, std::ostream &os)
{
    serialize(blueprint, os);
}


text:
package org.usfirst.frc.team334.robot.auton.sources;

import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDSourceType;
import org.usfirst.frc.team334.robot.vision.VisionData;

public class VisionAreaSource implements PIDSource {

    @Override
    public PIDSourceType getPIDSourceType() {
        return PIDSourceType.kDisplacement;
    }

    @Override
    public double pidGet() {
        return Math.sqrt(VisionData.getArea());
    }

    @Override
    public void setPIDSourceType(PIDSourceType pidSource) {}

}


text:
var piller = require('./');

describe('piller', function() {
  var backspaceChar = '\u0008';
  var deleteChar = '\u007F';
  var isMacOS = !!(~window.navigator.userAgent.indexOf('Mac OS'));

  beforeEach(function() {
    this.backspaceChar = backspaceChar;
    this.deleteChar = deleteChar;
    this.defaultOptions = {
      storageKey: 'testStorageKey',
      excludeStoredPillsNotFoundInCorpus: false,
      showSearchMatches: function() {}
    };
    this.container = document.createElement('div');
    document.body.appendChild(this.container);

    this.pill = createPill.call(this);

    this.pillTextValue = this.pill.text + ' ';
    this.pillHtmlValue = this.pill.html + ' ';

    jasmine.clock().install();
  });

  afterEach(function() {
    jasmine.clock().uninstall();
    localStorage.clear();

    document.body.removeChild(this.container);

    if (this.pillerInstance) {
      this.pillerInstance.destroy();
    }
  });

  function setSelectionRange(selStart, selEnd) {
    this.pillerInstance.ui.textarea.selectionStart = selStart;
    this.pillerInstance.ui.textarea.selectionEnd = typeof selEnd === 'number' ? selEnd : selStart;
  }

  function triggerInput(newValue) {
    this.pillerInstance.ui.textarea.value = newValue;
    this.pillerInstance.ui.textarea.dispatchEvent(new Event('input'));
    flushTimers();
  }

  function triggerKey(el, eventName, eventProps) {
    var keyboardEvent = new Event(eventName);
    el.dispatchEvent(Object.assign(keyboardEvent, eventProps));
  }

  function triggerKeyEvents(el, charCode, keyCode, eventExtras, input) {
    var eventProps = Object.assign({
      charCode: charCode,
      keyCode: keyCode,
      which: charCode || keyCode
    }, eventExtras);

    triggerKey(el, 'keydown', eventProps);

    if (charCode) {
      triggerKey(el, 'keypress', eventProps);
    }

    triggerKey(el, 'keyup', eventProps);

    if (typeof input === 'string') {
      triggerInput.call(this, input);
    } else {
      flushTimers();
    }
  }

  function simulateKeyEvents(charCode, keyCode, selStart, selEnd, charToAdd, eventExtras) {
    var oldValue = this.pillerInstance.ui.textarea.value;
    var newValue = '';

    selStart = typeof selStart === 'number' ? selStart : 0;
    selEnd = typeof selEnd === 'number' ? selEnd : 0;

    setSelectionRange.call(this, selStart, selEnd);

    if (selStart > selEnd) {
      throw 'selection start should never be greater than selection end';
    } else if (selStart !== selEnd) {
      newValue = oldValue.substring(0, selStart) + oldValue.substring(selEnd);
    } else if (!charToAdd) {
      newValue = oldValue.substring(0, selStart - 1) + oldValue.substring(selEnd);
    } else {
      newValue = oldValue;
    }

    if (charToAdd) {
      newValue = newValue.slice(0, selStart) + charToAdd + newValue.slice(selStart);
    }

    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, charCode, keyCode, eventExtras, newValue);
  }

  function simulateTypingOfString(str, selStart, selEnd, eventExtras) {
    for (var i = 0; i < str.length; i++) {
      var start = (selStart || 0) + i;
      var end = i > 0 ? start : (selEnd || start);
      var charCode = str.charCodeAt(i);
      var charToAdd = str[i];
      var keyCode = null;

      switch (str[i]) {
        case '\n':
          charCode = 0;
          keyCode = 13; // ENTER
          break;
        case this.backspaceChar:
          charCode = 0;
          charToAdd = null;
          keyCode = 8; // BACKSPACE
          break;
        case this.deleteChar:
          charCode = 0;
          charToAdd = null;
          keyCode = 46; // DELETE
          break;
      }

      simulateKeyEvents.call(this, charCode, keyCode, start, end, charToAdd, eventExtras);
    }
  }

  function flushTimers() {
    jasmine.clock().tick(600);
  }

  function storageExpects(text, pills) {
    var storedValue = JSON.parse(localStorage.getItem(this.defaultOptions.storageKey));

    if (text) {
      expect(storedValue.text).toBe(text);
      expect(storedValue._pills).toEqual(pills && JSON.parse(JSON.stringify(pills)) || []);
    } else {
      expect(storedValue).toBeFalsy();
    }
  }

  function modelExpects(text, html, pills) {
    expect(this.pillerInstance.modelValue.text).toBe(text);
    expect(this.pillerInstance.ui.textarea.value).toBe(text);
    expect(this.pillerInstance.ui.decorator.innerHTML).toBe(html);
    expect(JSON.parse(JSON.stringify(this.pillerInstance.modelValue.getPills()))).toEqual(pills && JSON.parse(JSON.stringify(pills)) || []);
    storageExpects.call(this, text, pills);
  }

  function createPill(positionStart, value, text) {
    if (typeof positionStart !== 'number' && this.pillerInstance) {
      positionStart = this.pillerInstance.ui.textarea.selectionStart;
    }

    return piller.createPill(value && value.id || 'id', value || {}, text || 'test at reference', positionStart, {
      searchPrefix: '@',
      prefix: '@'
    });
  }

  function basicTextTest(plainText, html) {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    simulateTypingOfString.call(this, plainText);
    modelExpects.call(this, plainText, html);
  }

  function insertTextTest(startValue, typedValue, resultValue, resultHtml, selStart, selEnd) {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    simulateTypingOfString.call(this, startValue);
    simulateTypingOfString.call(this, typedValue, selStart, selEnd);

    modelExpects.call(this, resultValue, resultHtml);
  }

  function insertPill(pillOverride, optionalEndIndex) {
    var pill = pillOverride || createPill.call(this);
    var newCaretPos = this.pillerInstance.modelValue.addPill(pill, optionalEndIndex);
    setSelectionRange.call(this, newCaretPos);
    flushTimers();
    return pill;
  }

  function basicPillTest(startValue, caretPos, numAdjacentPills) {
    var finalPillValue = '';
    var finalPillHtmlValue = '';
    var startText = '';
    var endText = '';
    var pills = [];
    numAdjacentPills = numAdjacentPills || 1;

    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);

    if (typeof caretPos === 'number') {
      startText = startValue.substring(0, caretPos);
      endText = startValue.substring(caretPos);
    } else {
      startText = startValue;
    }

    simulateTypingOfString.call(this, startText + endText);

    if (typeof caretPos === 'number') {
      this.pillerInstance.ui.textarea.selectionStart = caretPos;
      this.pillerInstance.ui.textarea.selectionEnd = caretPos;
    }

    var insertIndex = this.pillerInstance.ui.textarea.selectionStart;

    for (var i = 0; i < numAdjacentPills; i++) {
      var p = createPill.call(this, insertIndex);
      pills.push(p);
      insertPill.call(this, p);
      finalPillValue += p.text + p.suffix;
      finalPillHtmlValue += p.html + p.suffix;

      insertIndex += (p.text + p.suffix).length;
    }

    modelExpects.call(this, startText + finalPillValue + endText, startText.replace('\n', '
') + finalPillHtmlValue + endText, pills);
  }

  it('should render plain text', function() {
    basicTextTest.call(this, 'hello world', 'hello world');
  });

  it('should render a break in html for a new line', function() {
    basicTextTest.call(this, 'hello\nworld', 'hello
world');
  });

  it('should render multiple breaks in html for multiple new lines', function() {
    basicTextTest.call(this, 'hello\n\n\nworld', 'hello

world');
  });

  it('should replace selection range at index 0 with new characters', function() {
    insertTextTest.call(this, 'cheerio', 'spaghett', 'spaghettio', 'spaghettio', 0, 5);
  });

  it('should replace middle selection range with new characters', function() {
    insertTextTest.call(this, 'stanford', 'o tire', 'so tired', 'so tired', 1, 7);
  });

  it('should replace selection range at the end of input with new characters', function() {
    insertTextTest.call(this, 'relateIQ', 'ionship', 'relationship', 'relationship', 5, 8);
  });

  it('should replace html breaks in selection range', function() {
    var result = 'I am the slightest bit tired';
    insertTextTest.call(this, 'I am\nvery\ntired', ' the slightest bit ', result, result, 4, 10);
  });

  it('should replace selection range with breaks in html', function() {
    insertTextTest.call(this, 'I am the slightest bit tired', '\nvery\n', 'I am\nvery\ntired', 'I am
very
tired', 4, 23);
  });

  function doAdjacentPillTests(numAdjacentPills) {
    var pillDescription = numAdjacentPills + ' @ reference' + (numAdjacentPills > 1 ? 's' : '');

    it('should insert ' + pillDescription + ' as only content', function() {
      basicPillTest.call(this, '', null, numAdjacentPills);
    });

    it('should insert ' + pillDescription + ' after text content', function() {
      basicPillTest.call(this, 'hello ', null, numAdjacentPills);
    });

    it('should insert ' + pillDescription + ' before text content', function() {
      basicPillTest.call(this, 'hello', 0, numAdjacentPills);
    });

    it('should insert ' + pillDescription + ' in between text content', function() {
      basicPillTest.call(this, 'hello world', 6, numAdjacentPills);
    });

    it('should insert ' + pillDescription + ' after new line', function() {
      basicPillTest.call(this, 'hello\n', null, numAdjacentPills);
    });

    it('should set caret after inserted ' + pillDescription, function() {
      var startValue = 'hello world';
      var caretPos = 6;

      basicPillTest.call(this, startValue, caretPos, numAdjacentPills);
      expect(this.pillerInstance.ui.textarea.selectionStart).toBe(caretPos + this.pillTextValue.length * numAdjacentPills);
    });

    it('should insert ' + pillDescription + ' and then remove all content', function() {
      basicPillTest.call(this, '', 0, numAdjacentPills);
      simulateTypingOfString.call(this, this.backspaceChar, 0, this.pillTextValue.length * numAdjacentPills);
      modelExpects.call(this, '', '');
    });

    it('should insert ' + pillDescription + ' with text and then remove all content', function() {
      var startValue = 'hello world';
      var caretPos = 6;

      basicPillTest.call(this, startValue, caretPos, numAdjacentPills);
      simulateTypingOfString.call(this, this.backspaceChar, 0, startValue.length + this.pillTextValue.length * numAdjacentPills);
      modelExpects.call(this, '', '');
    });

    it('should remove all inserted ' + pillDescription, function() {
      var startValue = 'hello world';
      var caretPos = 6;

      basicPillTest.call(this, startValue, caretPos, numAdjacentPills);
      simulateTypingOfString.call(this, 'test ', caretPos, caretPos + this.pillTextValue.length * numAdjacentPills);
      modelExpects.call(this, 'hello test world', 'hello test world');
    });

    if (numAdjacentPills > 1) {
      it('should insert ' + pillDescription + ' and remove the last one', function() {
        var startValue = 'hello world';
        var caretPos = 6;
        var resultPillText = '';
        var resultPillHtml = '';
        var pills = [];

        basicPillTest.call(this, startValue, caretPos, numAdjacentPills);

        for (var i = 0; i < numAdjacentPills - 1; i++) {
          pills.push(createPill.call(this, caretPos + this.pillTextValue.length * i));
          resultPillText += this.pillTextValue;
          resultPillHtml += this.pillHtmlValue;
        }

        var startSel = caretPos + resultPillText.length;
        simulateTypingOfString.call(this, 'test ', startSel, startSel + this.pillTextValue.length);
        modelExpects.call(this, 'hello ' + resultPillText + 'test world', 'hello ' + resultPillHtml + 'test world', pills);
      });

      it('should insert ' + pillDescription + ' and remove the first one', function() {
        var startValue = 'hello world';
        var caretPos = 6;
        var resultPillText = '';
        var resultPillHtml = '';
        var replacementText = 'test';
        var pills = [];

        basicPillTest.call(this, startValue, caretPos, numAdjacentPills);

        for (var i = 0; i < numAdjacentPills - 1; i++) {
          //replacementText.length + 1 (+ 1 is for a space)
          pills.push(createPill.call(this, caretPos + (replacementText.length + 1) + this.pillTextValue.length * i));
          resultPillText += this.pillTextValue;
          resultPillHtml += this.pillHtmlValue;
        }

        simulateTypingOfString.call(this, replacementText, caretPos, caretPos + this.pillTextValue.length - 1);
        modelExpects.call(this, 'hello test ' + resultPillText + 'world', 'hello test ' + resultPillHtml + 'world', pills);
      });
    }

    if (numAdjacentPills === 3) {
      it('should insert 3 @refs and remove the middle one', function() {
        var startValue = 'hello world';
        var caretPos = 6;
        var replacementText = 'test ';
        var pills = [];

        basicPillTest.call(this, startValue, caretPos, numAdjacentPills);

        pills.push(createPill.call(this, caretPos));
        pills.push(createPill.call(this, caretPos + this.pillTextValue.length + replacementText.length));

        var startSel = caretPos + this.pillTextValue.length;

        simulateTypingOfString.call(this, 'test', startSel, startSel + this.pillTextValue.length - 1);
        modelExpects.call(this, 'hello ' + this.pillTextValue + replacementText + this.pillTextValue + 'world', 'hello ' + this.pillHtmlValue + replacementText + this.pillHtmlValue + 'world', pills);
      });
    }
  }

  for (var numAdjacentPills = 1; numAdjacentPills < 4; numAdjacentPills++) {
    doAdjacentPillTests(numAdjacentPills);
  }

  function doRemoveAtRefTests(deletionChar) {

    it('should dereference @ reference on input when the selectionStart is within it and the selectionEnd is at the end of the input value', function() {
      var startText = 'hello world';
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);

      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || ' universe', 11, (startText + this.pillTextValue).length);

      var expected = 'hello @test' + (deletionChar ? '' : ' universe');
      modelExpects.call(this, expected, expected);
    });

    it('should dereference 1 @ reference on input when the selectionStart is within it and the selectionEnd is at the end of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello world';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || ' universe', 11, startText.length + this.pillTextValue.length * 2);

      var expected = 'hello @test' + (deletionChar ? '' : ' universe');
      modelExpects.call(this, expected, expected);
    });

    it('should dereference 1 @ reference on input when the selectionEnd is within it and the selectionStart is at the beginning of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello test';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'passing', 0, 6 + this.pillTextValue.length + 5);

      var expected = (deletionChar ? '' : 'passing') + ' at reference test';
      modelExpects.call(this, expected, expected);
    });

    it('should dereference @ reference on input when the selectionStart is within it and the selectionEnd is NOT at the end of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello testing';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || ' winn', 11, (startText + this.pillTextValue).length - 3);

      var expected = 'hello @test' + (deletionChar ? '' : ' winn') + 'ing';
      modelExpects.call(this, expected, expected);
    });

    it('should remove @ref on input when the selectionStart is on the left edge of the @ref and the selectionEnd is at the end of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello world';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'universe', 6, (startText + this.pillTextValue).length);

      var expected = 'hello ' + (deletionChar ? '' : 'universe');
      modelExpects.call(this, expected, expected);
    });

    it('should remove @ref on input when the selectionStart is on the left edge of the @ref and the selectionEnd is NOT at the end of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello testing';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'winn', 6, (startText + this.pillTextValue).length - 3);

      var expected = 'hello ' + (deletionChar ? '' : 'winn') + 'ing';
      modelExpects.call(this, expected, expected);
    });

    it('should dereference @ref on input when the selectionEnd is within it and the selectionStart is at the beginning of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello test';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'passing', 0, 11);

      var expected = (deletionChar ? '' : 'passing') + ' at reference test';
      modelExpects.call(this, expected, expected);
    });

    it('should dereference @ reference on input when the selectionEnd is within it and the selectionStart is NOT at the beginning of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello test';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'p me', 3, 11);

      var expected = 'hel' + (deletionChar ? '' : 'p me') + ' at reference test';
      modelExpects.call(this, expected, expected);
    });

    it('should remove @ref on input when the selectionEnd is on the right edge of the @ref and the selectionStart is at the beginning of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello world';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'what\'s up', 0, 6 + this.pillTextValue.length - 1);

      var expected = (deletionChar ? '' : 'what\'s up') + ' world';
      modelExpects.call(this, expected, expected);
    });

    it('should remove @ref on input when the selectionEnd is on the left edge of the @ref and the selectionStart is NOT at the beginning of the input value', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello world';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'p me', 3, 6 + this.pillTextValue.length - 1);

      var expected = 'hel' + (deletionChar ? '' : 'p me') + ' world';
      modelExpects.call(this, expected, expected);
    });

    it('should remove @ref on input when the selection range is equal to the @ref edges', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      var startText = 'hello world';
      simulateTypingOfString.call(this, startText);
      setSelectionRange.call(this, 6, 6); //set caret to place @ ref after 'hello '
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'test', 6, 6 + this.pillTextValue.length - 1);

      var expected = 'hello ' + (deletionChar ? '' : 'test') + ' world';
      modelExpects.call(this, expected, expected);
    });

    it('should remove @ref on input when the selection range is equal to the @ref edges and was only content', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      insertPill.call(this);
      simulateTypingOfString.call(this, deletionChar || 'test', 0, this.pillTextValue.length - 1);

      var expected = (deletionChar ? '' : 'test') + ' ';
      modelExpects.call(this, expected, expected);
    });
  }

  doRemoveAtRefTests(null);
  doRemoveAtRefTests(backspaceChar);
  doRemoveAtRefTests(deleteChar);

  it('should insert @ reference by replacing selection range', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    var pills = [createPill.call(this, 6)];
    simulateTypingOfString.call(this, 'hello test world');
    setSelectionRange.call(this, 6, 11);
    insertPill.call(this, pills[0], 11);

    modelExpects.call(this, 'hello ' + this.pillTextValue + 'world', 'hello ' + this.pillHtmlValue + 'world', pills);
  });

  it('should dereference @ref on single word deletion to the left', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    insertPill.call(this);

    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 8, {
      ctrlKey: !isMacOS,
      altKey: isMacOS
    }, '@test at ');

    modelExpects.call(this, '@test at ', '@test at ');
  });

  it('should dereference @ref on single word deletion to the right', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    simulateTypingOfString.call(this, ' ');
    insertPill.call(this);
    setSelectionRange.call(this, 0);

    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 46, {
      ctrlKey: !isMacOS,
      altKey: isMacOS
    }, ' at reference');

    modelExpects.call(this, ' at reference', ' at reference');
  });

  it('should remove text before an @ref using forward DELETE', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    simulateTypingOfString.call(this, ' ');
    var ref = insertPill.call(this);
    setSelectionRange.call(this, 0);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 46, null, this.pillTextValue);
    ref.positionStart = 0;
    modelExpects.call(this, this.pillTextValue, this.pillHtmlValue, [ref]);
  });

  it('should add . char before an @ref', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    var ref = insertPill.call(this);
    setSelectionRange.call(this, 0);
    simulateTypingOfString.call(this, '.');
    modelExpects.call(this, '.' + this.pillTextValue, '.' + this.pillHtmlValue, [ref]);
  });

  if (isMacOS) {
    it('should focus @ref on bordering backspace', function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      insertPill.call(this);
      setSelectionRange.call(this, this.pillTextValue.length - 1);
      triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 8, {
        ctrlKey: !isMacOS,
        altKey: isMacOS
      });
      expect(document.activeElement.matches('.js-piller-pill')).toBeTruthy();
    });
  }

  it('should focus @ref on bordering left arrow', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    insertPill.call(this);
    setSelectionRange.call(this, this.pillTextValue.length - 1);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 37);
    expect(document.activeElement.matches('.js-piller-pill')).toBeTruthy();
  });

  it('should focus @ref on bordering right arrow', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    insertPill.call(this);
    setSelectionRange.call(this, 0);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 39);
    expect(document.activeElement.matches('.js-piller-pill')).toBeTruthy();
  });

  it('should focus @ref on bordering delete', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    insertPill.call(this);
    setSelectionRange.call(this, 0);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 46);
    expect(document.activeElement.matches('.js-piller-pill')).toBeTruthy();
  });

  it('should focus the correct (first) @ref when there are more than one of the same', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    insertPill.call(this);
    simulateTypingOfString.call(this, 'hello ', this.pillTextValue.length);
    insertPill.call(this);
    setSelectionRange.call(this, 0);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 39);

    expect(document.activeElement.matches('.js-piller-pill:first-child')).toBeTruthy();
  });

  it('should focus the correct (last) @ref when there are more than one of the same', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    var middleText = 'hello ';
    insertPill.call(this);
    simulateTypingOfString.call(this, middleText, this.pillTextValue.length);
    insertPill.call(this);
    setSelectionRange.call(this, middleText.length + this.pillTextValue.length);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 39);

    expect(document.activeElement.matches('.js-piller-pill:last-child')).toBeTruthy();
  });

  function doKeyNavOffAtReferenceTests(keyCode, isAfter, eventExtras) {
    it('should move caret ' + (isAfter ? 'after' : 'before') + ' focused @ref on ' + keyCode, function() {
      this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
      insertPill.call(this);
      setSelectionRange.call(this, 0);

      triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 39); //focus the inserted at ref
      triggerKeyEvents.call(this, document.activeElement, 0, keyCode, eventExtras);

      expect(document.activeElement === this.pillerInstance.ui.textarea).toBeTruthy();
      expect(this.pillerInstance.ui.textarea.selectionStart).toBe(isAfter ? this.pillTextValue.length - 1 : 0);
    });
  }

  // triggering keyevents on the pills is not working for some reason

  // doKeyNavOffAtReferenceTests(39, true);
  // doKeyNavOffAtReferenceTests(40, true);
  // doKeyNavOffAtReferenceTests(9, true);
  // doKeyNavOffAtReferenceTests(37, false);
  // doKeyNavOffAtReferenceTests(38, false);
  // doKeyNavOffAtReferenceTests(9, false, {
  //   shiftKey: true
  // });

  function doRemoveFocusedRefPillTest(keyCode, addAdjacentRef) {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    insertPill.call(this);

    if (addAdjacentRef) {
      insertPill.call(this);
    }

    setSelectionRange.call(this, 0);
    triggerKeyEvents.call(this, this.pillerInstance.ui.textarea, 0, 39); //focus the inserted at ref
    triggerKeyEvents.call(this, document.activeElement, 0, keyCode);
  }

  // triggering keyevents on the pills is not working for some reason

  // [8, 46].forEach(function(keyCode) {
  //   it('should remove focused @ref pill on ' + keyCode, function() {
  //     doRemoveFocusedRefPillTest.call(this, keyCode);
  //     expect(document.activeElement === this.pillerInstance.ui.textarea).toBeTruthy();
  //     modelExpects.call(this, ' ', ' ');
  //   });

  //   it('should remove first focused @ref with backspace when there is an adjacent @ref', function() {
  //     doRemoveFocusedRefPillTest.call(this, keyCode, true);
  //     modelExpects.call(this, ' ' + this.pillTextValue, ' ' + this.pillHtmlValue, [createPill.call(this, 1)]);
  //   });

  //   it('should set caret at position start of removed focused @ref pill on ' + keyCode, function() {
  //     doRemoveFocusedRefPillTest.call(this, keyCode);
  //     expect(this.pillerInstance.ui.textarea.selectionStart).toBe(0);
  //   });
  // });

  it('should set initial model value from client', function() {
    var startText = 'hello model world ';
    var text = startText + this.pillTextValue + this.pillTextValue;
    var pill1 = createPill.call(this, startText.length);
    var pill2 = createPill.call(this, pill1.positionEnd + 1);
    var pills = [pill1, pill2];
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    this.pillerInstance.modelValue = this.pillerInstance.createModelValue(text, pills);

    modelExpects.call(this, text, startText + this.pillHtmlValue + this.pillHtmlValue, pills);
  });

  // DEPRECATED
  // it('should reset model when the storageId changes', function() {
  //   var text = 'hello model world ';
  //   this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
  //   this.pillerInstance.modelValue = this.pillerInstance.createModelValue(text, []);
  //   flushTimers();
  //   this.defaultOptions.storageId = 'newStorageId';
  //   flushTimers();
  //   modelExpects.call(this, '', '');
  // });

  // it('should set model to storage value of new model when the storageId changes', function() {
  //   var text = 'hello model world ';
  //   this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
  //   this.pillerInstance.modelValue = this.pillerInstance.createModelValue(text, []);
  //   var originalStorageId = this.defaultOptions.storageId;
  //   this.defaultOptions.storageId = 'newStorageId';
  //   flushTimers();
  //   this.defaultOptions.storageId = originalStorageId;
  //   flushTimers();
  //   modelExpects.call(this, text, text);
  // });

  it('should reset model when set to a falsey value', function() {
    var text = 'hello model world ';
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    this.pillerInstance.modelValue = this.pillerInstance.createModelValue(text, []);
    this.pillerInstance.modelValue = null;
    flushTimers();
    modelExpects.call(this, '', '');
  });

  it('should always have the at reference ranges sorted by positionStart when adding @refs', function() {
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);
    var ref2 = createPill.call(this, 0, {
      id: 'ref2',
      name: 'ref2'
    }, 'ref2');
    var ref3 = createPill.call(this, ref2.text.length + 1, {
      id: 'ref3',
      name: 'ref3'
    }, 'ref3');
    var ref1 = createPill.call(this, ref2.text.length + ref3.text.length + 2, {
      id: 'ref1',
      name: 'ref1'
    }, 'ref1');

    var ref1Html = ref1.html + ' ';
    var ref2Html = ref2.html + ' ';
    var ref3Html = ref3.html + ' ';

    insertPill.call(this, ref1);
    setSelectionRange.call(this, 0);
    insertPill.call(this, ref2);
    setSelectionRange.call(this, ref2.text.length + 1);
    insertPill.call(this, ref3);

    modelExpects.call(this, ref2.text + ' ' + ref3.text + ' ' + ref1.text + ' ', ref2Html + ref3Html + ref1Html, [ref2, ref3, ref1]);
  });

  it('should add an @ref that matches a query without @', function() {
    var ref1 = createPill.call(this, 0, {
      id: 'ref1',
      name: 'ref1'
    }, 'ref1');
    var ref1Html = ref1.html + ' ';
    this.pillerInstance = piller.create(this.container, [], this.defaultOptions);

    insertPill.call(this, ref1);

    modelExpects.call(this, ref1.text + ' ', ref1Html, [ref1]);
  });

  it('should add adjacent @refs that are the same instance and matches a query without @', function() {
    var ref1 = createPill.call(this, 0, {
      id: 'ref1',
      name: 'ref1'
    }, 'ref1');
    var ref1Html = ref1.html + ' ';
    this.pillerInstance = piller.create(this.container, [ref1], this.defaultOptions);

    insertPill.call(this, ref1);
    insertPill.call(this, ref1);

    var clone = ref1.clone();
    var clone2 = ref1.clone();
    clone.positionStart = 0;
    clone2.positionStart = ref1.text.length + 1;

    modelExpects.call(this, ref1.text + ' ' + ref1.text + ' ', ref1Html + ref1Html, [clone, clone2]);
  });

});


text: Saved Queries


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

plugins.sass = require('gulp-sass');
plugins.useref = require('gulp-useref');
plugins.uglify = require('gulp-uglify');
plugins.gulpIf = require('gulp-if');
plugins.cssnano = require('gulp-cssnano');
plugins.runSequence = require('run-sequence');
plugins.browserSync = require('browser-sync').create();
plugins.del = require('del');
plugins.sass = require('gulp-sass');
plugins.nunjucksRender = require('gulp-nunjucks-render');
plugins.gutil = require('gulp-util');
plugins.removeCode = require('gulp-remove-code');

function getTask(task) {
    return require('./gulp-tasks/' + task)(gulp, plugins);
}

gulp.task('sass', getTask('sass'));
gulp.task('browserSync', getTask('browserSync'));
gulp.task('clean:dist', getTask('clean'));
gulp.task('nunjucks', getTask('nunjucks'));
gulp.task('useref', getTask('useref'));
gulp.task('indexcleanup', getTask('indexcleanup'));
gulp.task('sass-build', getTask('sass-build'));

gulp.task('jsload', function() {
  return gulp.src('app/js/**/*.js')
    .pipe(gulp.dest('.tmp/js'))
    .pipe(plugins.browserSync.reload({
      stream: true
    }))
});

gulp.task('watch', ['browserSync', 'sass', 'nunjucks'], function (){
  gulp.watch('app/scss/**/*.scss', ['sass']);
  gulp.watch('app/**/*.html', ['nunjucks']);
  gulp.watch('app/js/**/*.js',['jsload']);
});

gulp.task('default', function (callback) {
  plugins.runSequence(['sass','jsload','nunjucks', 'browserSync', 'watch'],
    callback
  )
})

gulp.task('build', function (callback) {
  plugins.runSequence('clean:dist',
    ['sass-build','nunjucks'],'useref','indexcleanup',
    callback
  )
})