text:
$(document).ready(function(){

	$("a.switcher").bind("click", function(e){
		e.preventDefault();

		var theid = $(this).attr("id");
		var theproducts = $("ul#products");
		var classNames = $(this).attr('class').split(' ');

		var gridthumb = "images/products/grid-default-thumb.png";
		var listthumb = "images/products/list-default-thumb.png";

		if($(this).hasClass("active")) {
			// if currently clicked button has the active class
			// then we do nothing!
			return false;
		} else {
			// otherwise we are clicking on the inactive button
			// and in the process of switching views!

  			if(theid == "gridview") {
				$(this).addClass("active");
				$("#listview").removeClass("active");

				$("#listview").children("img").attr("src","images/list-view.png");

				var theimg = $(this).children("img");
				theimg.attr("src","images/grid-view-active.png");

				// remove the list class and change to grid
				theproducts.removeClass("list");
				theproducts.addClass("grid");

				// update all thumbnails to larger size
				$("img.thumb").attr("src",gridthumb);
			}

			else if(theid == "listview") {
				$(this).addClass("active");
				$("#gridview").removeClass("active");

				$("#gridview").children("img").attr("src","images/grid-view.png");

				var theimg = $(this).children("img");
				theimg.attr("src","images/list-view-active.png");

				// remove the grid view and change to list
				theproducts.removeClass("grid")
				theproducts.addClass("list");
				// update all thumbnails to smaller size
				$("img.thumb").attr("src",listthumb);
			}
		}

	});
});


text: output.setValue(in.value.adDouble() - 273.15);

redpajama_set_name: RedPajamaGithub


text:
req.flash('success', { msg: 'Your account has been unlinked.' });
res.redirect('/account');


text:
Pamięć podręczna
================

Mechanizmy wykorzystujące pamięć podręczną pozwalają na poprawienie wydajności aplikacji sieciowej w tani i efektywny sposób.
Zapisanie mniej lub bardziej statycznych danych w pamięci podręcznej i serwowanie ich stamtąd, zamiast generować je od podstaw przy każdym
wywołaniu, pozwala na znaczne zaoszczędzenie czasu odpowiedzi aplikacji.

Zapis pamięci podręcznej może odbywać się na wielu poziomach i w wielu miejscach aplikacji. Po stronie serwera, na niskim poziomie,
można wykorzystać pamięć podręczną do zapisania podstawowych danych, takich jak zbiór informacji o najnowszych artykułach pobieranych z bazy danych.
Na wyższym poziomie, pamięci podręcznej można użyć do przechowania części bądź całości strony www, na przykład w postaci rezultatu wyrenderowania
listy ww. najświeższych artykułów. Po stronie klienta, pamięć podręczna HTTP przeglądarki może zapisać zawartość ostatnio odwiedzonej strony.

Yii wpiera wszystkie te mechanizmy zapisu w pamięci podręcznej:

* [Pamięć podręczna danych](caching-data.md)
* [Pamięć podręczna fragmentów](caching-fragment.md)
* [Pamięć podręczna stron](caching-page.md)
* [Pamięć podręczna HTTP](caching-http.md)


text:
"""Module to find and include all spynl plugins"""
from pkg_resources import iter_entry_points  # pylint: disable=E0611

def main(config):
    """initialize this module, find all plugins and include them"""
    installed_plugins = {
        plugin.name: plugin for plugin in iter_entry_points('spynl.plugins')
    }

    # Either load what is requested or all the installed plugins.
    load = config.get_settings().get('enable_plugins')
    if load is None:
        load = list(installed_plugins.keys())

    # Recursively load plugins and their dependencies.
    def load_plugins(load):
        for plugin_ in load:
            try:
                plugin = installed_plugins.pop(plugin_)
            except KeyError:
                continue

            if plugin.extras:
                load_plugins(plugin.extras)

            # We call resolve instead of load because extras are not actually
            # available distributions but other plugins that need to be loaded
            # first. Load would call require which would raise.
            # http://setuptools.readthedocs.io/en/latest/pkg_resources.html#entrypoint-objects
            entrypoint = plugin.resolve()
            # If the entrypoint is a callable let pyramid include it.
            if callable(entrypoint):
                config.include(entrypoint)

    load_plugins(load)


text:
using UnityEngine;
using System.Collections;

public class ExampleTwoScript : MonoBehaviour {

	[HideInInspector] public float hiddenVariable = 1.0f;
	[SerializeField] private float serializedPrivateVariable = 2.0f;
	[Space(30.0f)] public float spacedFloat = 10.0f;
	[Range(3.0f, 4.0f)] public float rangeFloat = 3.5f;
	[Header("Text Attributes")]
	public string headeredString = "headeredString";
	[TextArea(3, 6)] public string textArea =
		"Here is some text\nin a\ntext area";
	[Multiline(4)] public string multilineText = "Mult\ni\nline\ntext\nscroll\nto\nthis\ntext";
	[Tooltip("This variable is an integer!")] public int tooltippedInteger = 9;

    [ContextMenuItem("Output Value", "FieldContextFunction")]
    public float ContextFloat = 0.0f;

    void FieldContextFunction()
    {
        Debug.Log(ContextFloat);
    }

    [ContextMenu("Context Function")]
    public void ContextFunction()
    {
        Debug.Log("Context Function Activated!");
    }
}


text:
'use strict';

module.exports = require('array-uniq');


text:
const express = require('express')
const _ = require('lodash')
const pluralize = require('pluralize')
const write = require('./write')
const getFullURL = require('./get-full-url')
const utils = require('../utils')
const delay = require('./delay')

module.exports = (db, name, opts) => {
  // Create router
  const router = express.Router()
  router.use(delay)

  // Embed function used in GET /name and GET /name/id
  function embed(resource, e) {
    e &&
      [].concat(e).forEach((externalResource) => {
        if (db.get(externalResource).value) {
          const query = {}
          const singularResource = pluralize.singular(name)
          query[`${singularResource}${opts.foreignKeySuffix}`] = resource.id
          resource[externalResource] = db
            .get(externalResource)
            .filter(query)
            .value()
        }
      })
  }

  // Expand function used in GET /name and GET /name/id
  function expand(resource, e) {
    e &&
      [].concat(e).forEach((innerResource) => {
        const plural = pluralize(innerResource)
        if (db.get(plural).value()) {
          const prop = `${innerResource}${opts.foreignKeySuffix}`
          resource[innerResource] = db
            .get(plural)
            .getById(resource[prop])
            .value()
        }
      })
  }

  // GET /name
  // GET /name?q=
  // GET /name?attr=&attr=
  // GET /name?_end=&
  // GET /name?_start=&_end=&
  // GET /name?_embed=&_expand=
  function list(req, res, next) {
    // Resource chain
    let chain = db.get(name)

    // Remove q, _start, _end, ... from req.query to avoid filtering using those
    // parameters
    let q = req.query.q
    let _start = req.query._start
    let _end = req.query._end
    let _page = req.query._page
    const _sort = req.query._sort
    const _order = req.query._order
    let _limit = req.query._limit
    const _embed = req.query._embed
    const _expand = req.query._expand
    delete req.query.q
    delete req.query._start
    delete req.query._end
    delete req.query._sort
    delete req.query._order
    delete req.query._limit
    delete req.query._embed
    delete req.query._expand

    // Automatically delete query parameters that can't be found
    // in the database
    Object.keys(req.query).forEach((query) => {
      const arr = db.get(name).value()
      for (const i in arr) {
        if (
          _.has(arr[i], query) ||
          query === 'callback' ||
          query === '_' ||
          /_lte$/.test(query) ||
          /_gte$/.test(query) ||
          /_ne$/.test(query) ||
          /_like$/.test(query)
        )
          return
      }
      delete req.query[query]
    })

    if (q) {
      // Full-text search
      if (Array.isArray(q)) {
        q = q[0]
      }

      q = q.toLowerCase()

      chain = chain.filter((obj) => {
        for (const key in obj) {
          const value = obj[key]
          if (db._.deepQuery(value, q)) {
            return true
          }
        }
        return false
      })
    }

    Object.keys(req.query).forEach((key) => {
      // Don't take into account JSONP query parameters
      // jQuery adds a '_' query parameter too
      if (key !== 'callback' && key !== '_') {
        // Always use an array, in case req.query is an array
        const arr = [].concat(req.query[key])

        const isDifferent = /_ne$/.test(key)
        const isRange = /_lte$/.test(key) || /_gte$/.test(key)
        const isLike = /_like$/.test(key)
        const path = key.replace(/(_lte|_gte|_ne|_like)$/, '')

        chain = chain.filter((element) => {
          return arr
            .map(function (value) {
              // get item value based on path
              // i.e post.title -> 'foo'
              const elementValue = _.get(element, path)

              // Prevent toString() failing on undefined or null values
              if (elementValue === undefined || elementValue === null) {
                return undefined
              }

              if (isRange) {
                const isLowerThan = /_gte$/.test(key)

                return isLowerThan
                  ? value <= elementValue
                  : value >= elementValue
              } else if (isDifferent) {
                return value !== elementValue.toString()
              } else if (isLike) {
                return new RegExp(value, 'i').test(elementValue.toString())
              } else {
                return value === elementValue.toString()
              }
            })
            .reduce((a, b) => (isDifferent ? a && b : a || b))
        })
      }
    })

    // Sort
    if (_sort) {
      const _sortSet = _sort.split(',')
      const _orderSet = (_order || '').split(',').map((s) => s.toLowerCase())
      chain = chain.orderBy(_sortSet, _orderSet)
    }

    // Slice result
    if (_end || _limit || _page) {
      res.setHeader('X-Total-Count', chain.size())
      res.setHeader(
        'Access-Control-Expose-Headers',
        `X-Total-Count${_page ? ', Link' : ''}`
      )
    }

    if (_page) {
      _page = parseInt(_page, 10)
      _page = _page >= 1 ? _page : 1
      _limit = parseInt(_limit, 10) || 10
      const page = utils.getPage(chain.value(), _page, _limit)
      const links = {}
      const fullURL = getFullURL(req)

      if (page.first) {
        links.first = fullURL.replace(
          `page=${page.current}`,
          `page=${page.first}`
        )
      }

      if (page.prev) {
        links.prev = fullURL.replace(
          `page=${page.current}`,
          `page=${page.prev}`
        )
      }

      if (page.next) {
        links.next = fullURL.replace(
          `page=${page.current}`,
          `page=${page.next}`
        )
      }

      if (page.last) {
        links.last = fullURL.replace(
          `page=${page.current}`,
          `page=${page.last}`
        )
      }

      res.links(links)
      chain = _.chain(page.items)
    } else if (_end) {
      _start = parseInt(_start, 10) || 0
      _end = parseInt(_end, 10)
      chain = chain.slice(_start, _end)
    } else if (_limit) {
      _start = parseInt(_start, 10) || 0
      _limit = parseInt(_limit, 10)
      chain = chain.slice(_start, _start + _limit)
    }

    // embed and expand
    chain = chain.cloneDeep().forEach(function (element) {
      embed(element, _embed)
      expand(element, _expand)
    })

    res.locals.data = chain.value()
    next()
  }

  // GET /name/:id
  // GET /name/:id?_embed=&_expand
  function show(req, res, next) {
    const _embed = req.query._embed
    const _expand = req.query._expand
    const resource = db.get(name).getById(req.params.id).value()

    if (resource) {
      // Clone resource to avoid making changes to the underlying object
      const clone = _.cloneDeep(resource)

      // Embed other resources based on resource id
      // /posts/1?_embed=comments
      embed(clone, _embed)

      // Expand inner resources based on id
      // /posts/1?_expand=user
      expand(clone, _expand)

      res.locals.data = clone
    }

    next()
  }

  // POST /name
  function create(req, res, next) {
    let resource
    if (opts._isFake) {
      const id = db.get(name).createId().value()
      resource = { ...req.body, id }
    } else {
      resource = db.get(name).insert(req.body).value()
    }

    res.setHeader('Access-Control-Expose-Headers', 'Location')
    res.location(`${getFullURL(req)}/${resource.id}`)

    res.status(201)
    res.locals.data = resource

    next()
  }

  // PUT /name/:id
  // PATCH /name/:id
  function update(req, res, next) {
    const id = req.params.id
    let resource

    if (opts._isFake) {
      resource = db.get(name).getById(id).value()

      if (req.method === 'PATCH') {
        resource = { ...resource, ...req.body }
      } else {
        resource = { ...req.body, id: resource.id }
      }
    } else {
      let chain = db.get(name)

      chain =
        req.method === 'PATCH'
          ? chain.updateById(id, req.body)
          : chain.replaceById(id, req.body)

      resource = chain.value()
    }

    if (resource) {
      res.locals.data = resource
    }

    next()
  }

  // DELETE /name/:id
  function destroy(req, res, next) {
    let resource

    if (opts._isFake) {
      resource = db.get(name).value()
    } else {
      resource = db.get(name).removeById(req.params.id).value()

      // Remove dependents documents
      const removable = db._.getRemovable(db.getState(), opts)
      removable.forEach((item) => {
        db.get(item.name).removeById(item.id).value()
      })
    }

    if (resource) {
      res.locals.data = {}
    }

    next()
  }

  const w = write(db)

  router.route('/').get(list).post(create, w)

  router
    .route('/:id')
    .get(show)
    .put(update, w)
    .patch(update, w)
    .delete(destroy, w)

  return router
}


text:
using MDS.Serialization;

namespace MDS.Communication.Messages.ControllerMessages
{
    /// <summary>
    /// Stores all MDS server's and server graph's informations.
    /// </summary>
    public class ServerGraphInfo : IMDSSerializable
    {
        /// <summary>
        /// Reference to this server on graph (This server is also in Servers list).
        /// </summary>
        public string ThisServerName { get; set; }

        /// <summary>
        /// All servers on graph.
        /// </summary>
        public ServerOnGraph[] Servers { get; set; }

        /// <summary>
        /// Serializes this object.
        /// </summary>
        /// <param name="serializer">Serializer used to serialize objects</param>
        public void Serialize(IMDSSerializer serializer)
        {
            serializer.WriteStringUTF8(ThisServerName);
            serializer.WriteObjectArray(Servers);
        }

        /// <summary>
        /// Deserializes this object.
        /// </summary>
        /// <param name="deserializer">Deserializer used to deserialize objects</param>
        public void Deserialize(IMDSDeserializer deserializer)
        {
            ThisServerName = deserializer.ReadStringUTF8();
            Servers = deserializer.ReadObjectArray(() => new ServerOnGraph());
        }

        #region Sub classes

        public class ServerOnGraph : IMDSSerializable
        {
            /// <summary>
            /// Name of this server.
            /// </summary>
            public string Name { get; set; }

            /// <summary>
            /// IP address of this server.
            /// </summary>
            public string IpAddress { get; set; }

            /// <summary>
            /// TCP Port number that is listened by this server.
            /// </summary>
            public int Port { get; set; }

            /// <summary>
            /// List of adjacent servers of this server that are splitted by , or ;
            /// </summary>
            public string Adjacents { get; set; }

            /// <summary>
            /// Location of server (Left (X) and Top (Y) properties in design area, seperated by comma (,)).
            /// </summary>
            public string Location { get; set; }

            /// <summary>
            /// Serializes this object.
            /// </summary>
            /// <param name="serializer">Serializer used to serialize objects</param>
            public void Serialize(IMDSSerializer serializer)
            {
                serializer.WriteStringUTF8(Name);
                serializer.WriteStringUTF8(IpAddress);
                serializer.WriteInt32(Port);
                serializer.WriteStringUTF8(Adjacents);
                serializer.WriteStringUTF8(Location);
            }

            /// <summary>
            /// Deserializes this object.
            /// </summary>
            /// <param name="deserializer">Deserializer used to deserialize objects</param>
            public void Deserialize(IMDSDeserializer deserializer)
            {
                Name = deserializer.ReadStringUTF8();
                IpAddress = deserializer.ReadStringUTF8();
                Port = deserializer.ReadInt32();
                Adjacents = deserializer.ReadStringUTF8();
                Location = deserializer.ReadStringUTF8();
            }
        }

        #endregion
    }
}


text:
#ifndef __INFO_H
#define __INFO_H

#define PROGRAM_NAME			"rmln"
#define PROGRAM_VERSION_MAJOR		0
#define PROGRAM_VERSION_MINOR		1
#define PROGRAM_VERSION_PATCH		2
#define PROGRAM_AUTHORS			"Ammon Smith"
#define PROGRAM_YEARS           	"2016-2017"

#ifndef GIT_HASH
# define GIT_HASH			"nogithash"
#endif /* GIT_HASH */

#if defined(__clang__)
# define COMPILER_NAME				"Clang/LLVM"
# define COMPILER_VERSION			__clang_version__
#elif defined(__ICC) || defined(__INTEL_COMPILER)
# define COMPILER_NAME				"Intel ICC"
# define COMPILER_VERSION			__INTEL_COMPILER
#elif defined(__MINGW32__)
# define COMPILER_NAME				"Mingw"
# define COMPILER_VERSION			__VERSION__
#elif defined(__GNUC__) || defined(__GNUG__)
# define COMPILER_NAME				"GCC"
# define COMPILER_VERSION			__VERSION__
#elif defined(__HP_cc) || defined(__HP_aCC)
# define COMPILER_NAME				"Hewlett-Packard C"
# define COMPILER_VERSION			__HP_cc
#elif defined(__IBMC__) || defined(__IBMCPP__)
# define COMPILER_NAME				"IBM XL C"
# define COMPILER_VERSION			__xlc__
#elif defined(_MSC_VER)
# define COMPILER_NAME				"Microsoft Visual Studio"
# define COMPILER_VERSION			_MSC_VER
#elif defined(__PGI)
# define COMPILER_NAME				"Portland Group PGCC"
# define COMPILER_VERSION			__PGIC__
#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
# define COMPILER_NAME				"Oracle Solaris Studio"
# define COMPILER_VERSION			__SUNPRO_C
#else
# define COMPILER_NAME				"Unknown"
# define COMPILER_VERSION			"compiler"
#endif

#if defined(_WIN64)
# define PLATFORM_NAME				"Windows 64-bit"
#elif defined(_WIN32)
# define PLATFORM_NAME				"Windows 32-bit"
#elif defined(__linux__)
# define PLATFORM_NAME				"Linux"
#elif defined(__APPLE__) || defined(__MACH__)
# define PLATFORM_NAME				"Apple"
#elif defined(__FreeBSD__)
# define PLATFORM_NAME				"FreeBSD"
#elif defined(__unix) || defined(__unix__)
# define PLATFORM_NAME				"Unknown UNIX"
#else
# define PLATFORM_NAME				"Unknown"
#endif

#endif /* __INFO_H */


text:
module Commands
  class IncidentsMine
    include Base

    def call
      incidents = pagerduty.get_incidents(query_params)
      response format_incidents(incidents)
    rescue Exceptions::IncidentsEmptyList
      response message: 'incident.none'
    rescue Exceptions::UserNotIdentified
      response message: 'incident.none_mine'
    end

    private

    def query_params
      {
        statuses: %w[triggered acknowledged],
        'user_ids[]' => current_user[:id]
      }
    end
  end
end


text:
<?php

/**
 * @uses       Zend_Service_DeveloperGarden_Response_Exception
 * @category   Zend
 * @package    Zend_Service
 * @subpackage DeveloperGarden
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @author     Marco Kaiser
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
abstract class Zend_Service_DeveloperGarden_Response_AbstractResponse
{
    /**
     * errorCode
     *
     * @var string
     */
    public $errorCode = null;

    /**
     * errorMessage
     *
     * @var string
     */
    public $errorMessage = null;

    /**
     * parse the token data and throws exceptions
     *
     * @throws Zend_Service_DeveloperGarden_Response_Exception
     * @return Zend_Service_DeveloperGarden_Response_AbstractResponse
     */
    public function parse()
    {
        if ($this->hasError()) {
            throw new Zend_Service_DeveloperGarden_Response_Exception(
                $this->getErrorMessage(),
                $this->getErrorCode()
            );
        }

        return $this;
    }

    /**
     * returns the error code
     *
     * @return string|null
     */
    public function getErrorCode()
    {
        return $this->errorCode;
    }

    /**
     * returns the error message
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }

    /**
     * returns true if the errorCode is not null and not 0000
     *
     * @return boolean
     */
    public function isValid()
    {
        return ($this->errorCode === null
             || $this->errorCode == '0000');
    }

    /**
     * returns true if we have a error situation
     *
     * @return boolean
     */
    public function hasError()
    {
        return ($this->errorCode !== null
                && $this->errorCode != '0000');
    }
}


text:
@interface UIBarButtonItem (Extension)
+ (UIBarButtonItem *)itemWithTarget:(id)target selector:(SEL)selector image:(NSString *)image selectedImage:(NSString *)selectedImage;
@end


text:
#ifndef OPENTISSUE_CORE_CONTAINERS_MESH_COMMON_UTIL_MESH_COMPUTE_AABB_H
#define OPENTISSUE_CORE_CONTAINERS_MESH_COMMON_UTIL_MESH_COMPUTE_AABB_H
//
// OpenTissue Template Library
// - A generic toolbox for physics-based modeling and simulation.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/core/containers/mesh/common/util/mesh_compute_mesh_minimum_coord.h>
#include <OpenTissue/core/containers/mesh/common/util/mesh_compute_mesh_maximum_coord.h>

namespace OpenTissue
{
  namespace mesh
  {

    /**
     * Compute min max AABB Corners of Mesh.
     *
     * Example usage:
     *
     *  typedef ...   vector3_type;
     *  typedef ...   mesh_type;
     *
     *  mesh_type mesh;
     *  ...
     *
     *  vector3_type min_coord;
     *  vector3_type max_coord;
     *  OpenTissue::mesh::compute_aabb( mesh, min_coord , max_coord );
     *
     * @param mesh           A refence to a mesh.
     * @param min_coord      Upon return this argument holds the minimum coordinates of the mesh.
     * @param max_coord      Upon return this argument holds the maximum coordinates of the mesh.
     */
    template<typename mesh_type>
    inline void compute_aabb(
        mesh_type const & mesh
        , typename mesh_type::math_types::vector3_type & min_coord
        , typename mesh_type::math_types::vector3_type & max_coord
      )
    {
      OpenTissue::mesh::compute_mesh_minimum_coord( mesh, min_coord );
      OpenTissue::mesh::compute_mesh_maximum_coord( mesh, max_coord );
    }

  } // namespace mesh
} // namespace OpenTissue

// OPENTISSUE_CORE_CONTAINERS_MESH_COMMON_UTIL_MESH_COMPUTE_AABB_H
#endif


text:
package com.lastabyss.psciv.cinematics;

/**
 * @author Navid
 */
public class CinematicPlayer {
}


text:
package collins.util.parsers

import collins.models.lshw.LshwAsset
import collins.models.lshw.Cpu
import collins.models.lshw.Memory
import collins.models.lshw.Disk
import collins.models.lshw.Nic
import collins.models.lshw.ServerBase

import collins.util.config.LshwConfig
import collins.util.LshwRepresentation
import collins.util.ByteStorageUnit
import collins.util.BitStorageUnit

import scala.xml.{ Elem, MalformedAttributeException, Node, NodeSeq, XML }

object SpeedConversions {
  private val ghz = (1000 * 1000 * 1000).toDouble
  private val mhz = (1000 * 1000 * 1000 * 1000).toDouble
  def hzToGhz(l: Long): Double = l / ghz
  def hzToMhz(l: Long): Double = l / mhz
}

class LshwParser(txt: String) extends CommonParser[LshwRepresentation](txt) {

  val wildcard: PartialFunction[NodeSeq, LshwAsset] = { case _ => null }
  lazy val matcher = cpuMatcher.orElse(
    memMatcher.orElse(
      diskMatcher.orElse(
        nicMatcher.orElse(
          wildcard))))

  override def parse(): Either[Throwable, LshwRepresentation] = {
    val xml = try {
      XML.loadString(txt)
    } catch {
      case e: Throwable =>
        logger.info("Invalid XML specified: " + e.getMessage)
        return Left(e)
    }
    val rep = try {
      val base = getBaseInfo(xml)
      getCoreNodes(xml).foldLeft(LshwRepresentation(Nil, Nil, Nil, Nil, base)) {
        case (holder, node) =>
          matcher(node) match {
            case c: Cpu    => holder.copy(cpus = c +: holder.cpus)
            case m: Memory => holder.copy(memory = m.copy(bank = holder.memory.size) +: holder.memory)
            case d: Disk   => holder.copy(disks = d +: holder.disks)
            case n: Nic    => holder.copy(nics = n +: holder.nics)
            case _         => holder
          }
      }
    } catch {
      case e: Throwable =>
        logger.warn("Caught exception processing LSHW XML: %s".format(e.getMessage), e)
        return Left(e)
    }
    Right(rep)
  }

  val cpuMatcher: PartialFunction[NodeSeq, Cpu] = {
    case n if isCpuNode(n) =>
      val asset = getAsset(n)
      val speedString = Option(n \ "size" text).filter(_.nonEmpty).getOrElse("0")
      val speed = SpeedConversions.hzToGhz(speedString.toLong)
      val map = {
        val settings = (n \ "configuration" \ "setting")
        settings.size match {
          case 0 => Map("cores" -> "1", "threads" -> "1")
          case _ => settingsMap(settings)
        }
      }
      val cores = map.getOrElse("cores", {
        throw AttributeNotFoundException("Could not find cpu configuration.setting.cores")
      }).toInt
      val threads = map.getOrElse("threads", {
        throw AttributeNotFoundException("Could not find cpu configuration.setting.threads")
      }).toInt
      Cpu(cores, threads, speed, asset.description, asset.product, asset.vendor)
  }

  val memMatcher: PartialFunction[NodeSeq, Memory] = {
    case n if (n \ "@class" text) == "memory" && (n \ "@id" text).contains("bank:") =>
      val asset = getAsset(n)
      val size = (n \ "size" text) match {
        case n if n.isEmpty => ByteStorageUnit(0)
        case n              => ByteStorageUnit(n.toLong)
      }
      val bank: Int = try { (n \ "@id" text).split(":").last.toInt } catch { case _: Throwable => -1 }
      Memory(size, bank, asset.description, asset.product, asset.vendor)
  }

  val diskMatcher: PartialFunction[NodeSeq, Disk] = {
    case n if ((n \ "@class" text) == "disk") ||
      ((n \ "@class" text) == "volume" &&
        (n \ "@id" text).contains("disk")) =>
      val _type = (n \ "physid" text).contains("\\.") match {
        case true => Disk.Type.Ide
        case false =>
          (n \ "description" text).toLowerCase.contains("cd-rom") match {
            case true  => Disk.Type.CdRom
            case false => Disk.Type.Scsi
          }
      }
      val asset = getAsset(n)
      val size = (n \ "size" text) match {
        case noSize if noSize.isEmpty => ByteStorageUnit(0)
        case size                     => ByteStorageUnit(size.toLong)
      }
      Disk(size, _type, asset.description, asset.product, asset.vendor)
    case n if (n \ "@class" text) == "memory" && LshwConfig.flashProducts.exists(s => (n \ "product" text).toLowerCase.contains(s)) =>
      val asset = getAsset(n)
      val size = ByteStorageUnit(LshwConfig.flashSize)
      Disk(size, Disk.Type.Flash, asset.description, asset.product, asset.vendor)
  }

  private val defaultNicCapacity = LshwConfig.defaultNicCapacity

  val nicMatcher: PartialFunction[NodeSeq, Nic] = {
    case n if ((n \ "@class" text) == "network") => {
      val asset = getAsset(n)
      val mac = (n \ "serial" text)
      val speed = (n \ "capacity" text) match {
        case cap if cap.nonEmpty => BitStorageUnit(cap.toLong)
        case empty => (n \ "size" text) match {
          case size if size.nonEmpty => BitStorageUnit(size.toLong)
          case empty                 => getDefaultNicStorage(asset)
        }
      }
      Nic(speed, mac, asset.description, asset.product, asset.vendor)
    }
  }

  /**
   * Parse the NIC capacity from product name or use the configured default
   * @return The NIC capacity of the asset or the default if the asset did not provide a NIC capacity
   * @throws AttributeNotFoundException if cannot deduce speed from product name and not default configured
   */
  private def getDefaultNicStorage(asset: LshwAsset): BitStorageUnit = {
    asset.product.toLowerCase.contains("10-gig") match {
      case true => BitStorageUnit(10000000000L)
      case false => defaultNicCapacity
        .map((s: String) => BitStorageUnit(s.toLong))
        .getOrElse(
          throw AttributeNotFoundException(
            "Could not find capacity for network interface for %s".format(asset.product)))
    }
  }

  protected def isCpuNode(n: NodeSeq): Boolean = {
    val isProc = (n \ "@class" text) == "processor"
    // For unclear reasons, lshw B.02.12.01 on el5 can claim that
    // bogus CPUs exist. This leads to nonsensical results where lshw
    // claims there are more CPUs than physical sockets. In text mode
    // they are listed as UNCLAIMED, but are only identified in the
    // xml by empty attributes
    val hasHandle = !(n \ "@handle" text).isEmpty
    // lshw B.02.12.01 on el5 will also populate an empty socket with
    // generic ghost data (like "I'm socket 2 and I *could* in theory
    // have a proc with this clock speed, but I'm not going to give
    // you a useful field like <empty>true</true> to figure out what's
    // going on.")  It appears that the "product" field is the best
    // bet for identifying occupied sockets.
    val isOccupiedSocket = n \ "product" nonEmpty
    val isDisabled = (n \ "@disabled" text).toString == "true"
    val probablyRealCpu = isProc && hasHandle && (LshwConfig.includeEmptySocket || isOccupiedSocket)
    if (LshwConfig.includeDisabledCpu) {
      probablyRealCpu
    } else {
      probablyRealCpu && !isDisabled
    }
  }

  protected def getCoreNodes(elem: Elem): NodeSeq = {
    val core = (elem \\ "node").find { node =>
      (node \ "@id" text) == "core"
    }.getOrElse(throw MalformedAttributeException("Expected id=core node attribute"))
    core \\ "node"
  }

  protected def getBaseInfo(elem: Elem): ServerBase = {
    // Note that this does not uniquely identify the root of the lshw
    // xml, but is only a sanity check that this is being called on
    // the correct element
    if ((elem \ "@class" text).toString == "system") {
      val asset = getAsset(elem)
      val serial = (elem \ "serial" text)
      ServerBase(asset.description, asset.product, asset.vendor, serial)
    } // To spice things up, sometimes we get <list>$everything</list>
    // instead of just $everything
    else if (((elem \ "node") \ "@class" text) == "system") {
      val asset = getAsset(elem \ "node")
      val serial = (elem \ "serial" text)
      ServerBase(asset.description, asset.product, asset.vendor, serial)
    } else {
      throw MalformedAttributeException("Expected root class=system node attribute")
    }
  }

  protected def settingsMap(n: NodeSeq): Map[String, String] = {
    n.foldLeft(Map[String, String]()) {
      case (r, setting) =>
        r ++ Map((setting \ "@id" text) -> (setting \ "@value" text))
    }
  }

  protected def getAsset(node: NodeSeq): LshwAsset = {
    val description = (node \ "description" text)
    val product = (node \ "product" text)
    val vendor = (node \ "vendor" text)
    LshwAsset(description, product, vendor)
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<color name="colorPrimary">#3F51B5</color>
	<color name="colorPrimaryDark">#303F9F</color>
	<color name="colorAccent">#FF4081</color>

	<color name="blackPrimary">@color/black87</color>
	<color name="blackSecondary">@color/black54</color>

	<!--Black-->
	<color name="black87">#df000000</color>
	<color name="black70">#B3000000</color>
	<color name="black54">#8a000000</color>
	<color name="black50">#88000000</color>
	<color name="black25">#44000000</color>
	<color name="black12">#1f000000</color>
	<color name="black10">#1b000000</color>

	<color name="white">#F7F7F7</color>
	<color name="window_background">#FFF5F5F5</color>
</resources>


text:
package com.alibaba.dubbo.remoting.codec;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.remoting.Channel;
import com.alibaba.dubbo.remoting.Codec2;
import com.alibaba.dubbo.remoting.buffer.ChannelBuffer;
import com.alibaba.dubbo.remoting.buffer.ChannelBuffers;
import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

public class TelnetCodecTest {
    protected Codec2 codec;
    byte[] UP = new byte[]{27, 91, 65};
    byte[] DOWN = new byte[]{27, 91, 66};
    //======================================================
    URL url = URL.valueOf("dubbo://10.20.30.40:20880");

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        codec = new TelnetCodec();
    }

    protected AbstractMockChannel getServerSideChannel(URL url) {
        url = url.addParameter(AbstractMockChannel.LOCAL_ADDRESS, url.getAddress())
                .addParameter(AbstractMockChannel.REMOTE_ADDRESS, "127.0.0.1:12345");
        AbstractMockChannel channel = new AbstractMockChannel(url);
        return channel;
    }

    protected AbstractMockChannel getCliendSideChannel(URL url) {
        url = url.addParameter(AbstractMockChannel.LOCAL_ADDRESS, "127.0.0.1:12345")
                .addParameter(AbstractMockChannel.REMOTE_ADDRESS, url.getAddress());
        AbstractMockChannel channel = new AbstractMockChannel(url);
        return channel;
    }

    protected byte[] join(byte[] in1, byte[] in2) {
        byte[] ret = new byte[in1.length + in2.length];
        System.arraycopy(in1, 0, ret, 0, in1.length);
        System.arraycopy(in2, 0, ret, in1.length, in2.length);
        return ret;
    }

    protected byte[] objectToByte(Object obj) {
        byte[] bytes;
        if (obj instanceof String) {
            bytes = ((String) obj).getBytes();
        } else if (obj instanceof byte[]) {
            bytes = (byte[]) obj;
        } else {
            try {
                //object to bytearray
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                ObjectOutputStream oo = new ObjectOutputStream(bo);
                oo.writeObject(obj);
                bytes = bo.toByteArray();
                bo.close();
                oo.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return (bytes);
    }

    protected Object byteToObject(byte[] objBytes) throws Exception {
        if (objBytes == null || objBytes.length == 0) {
            return null;
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(objBytes);
        ObjectInputStream oi = new ObjectInputStream(bi);
        return oi.readObject();
    }

    protected void testDecode_assertEquals(byte[] request, Object ret) throws IOException {
        testDecode_assertEquals(request, ret, true);
    }

    protected void testDecode_assertEquals(byte[] request, Object ret, boolean isServerside) throws IOException {
        //init channel
        Channel channel = isServerside ? getServerSideChannel(url) : getCliendSideChannel(url);
        //init request string
        ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);

        //decode
        Object obj = codec.decode(channel, buffer);
        Assert.assertEquals(ret, obj);
    }

    protected void testEecode_assertEquals(Object request, byte[] ret, boolean isServerside) throws IOException {
        //init channel
        Channel channel = isServerside ? getServerSideChannel(url) : getCliendSideChannel(url);

        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);

        codec.encode(channel, buffer, request);
        byte[] data = new byte[buffer.readableBytes()];
        buffer.readBytes(data);

        Assert.assertEquals(ret.length, data.length);
        for (int i = 0; i < ret.length; i++) {
            if (ret[i] != data[i]) {
                Assert.fail();
            }
        }
    }

    protected void testDecode_assertEquals(Object request, Object ret) throws IOException {
        testDecode_assertEquals(request, ret, null);
    }

    private void testDecode_assertEquals(Object request, Object ret, Object channelReceive) throws IOException {
        testDecode_assertEquals(null, request, ret, channelReceive);
    }

    private void testDecode_assertEquals(AbstractMockChannel channel, Object request, Object expectret, Object channelReceive) throws IOException {
        //init channel
        if (channel == null) {
            channel = getServerSideChannel(url);
        }

        byte[] buf = objectToByte(request);
        ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(buf);

        //decode
        Object obj = codec.decode(channel, buffer);
        Assert.assertEquals(expectret, obj);
        Assert.assertEquals(channelReceive, channel.getReceivedMessage());
    }

    private void testDecode_PersonWithEnterByte(byte[] enterbytes, boolean isNeedmore) throws IOException {
        //init channel
        Channel channel = getServerSideChannel(url);
        //init request string
        Person request = new Person();
        byte[] newbuf = join(objectToByte(request), enterbytes);
        ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(newbuf);

        //decode
        Object obj = codec.decode(channel, buffer);
        if (isNeedmore) {
            Assert.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT, obj);
        } else {
            Assert.assertTrue("return must string ", obj instanceof String);
        }
    }

    private void testDecode_WithExitByte(byte[] exitbytes, boolean isChannelClose) throws IOException {
        //init channel
        Channel channel = getServerSideChannel(url);
        ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(exitbytes);

        //decode
        codec.decode(channel, buffer);
        Assert.assertEquals(isChannelClose, channel.isClosed());
    }

    @Test
    public void testDecode_String_ClientSide() throws IOException {
        testDecode_assertEquals("aaa".getBytes(), "aaa", false);
    }

    @Test
    public void testDecode_BlankMessage() throws IOException {
        testDecode_assertEquals(new byte[]{}, Codec2.DecodeResult.NEED_MORE_INPUT);
    }

    @Test
    public void testDecode_String_NoEnter() throws IOException {
        testDecode_assertEquals("aaa", Codec2.DecodeResult.NEED_MORE_INPUT);
    }

    @Test
    public void testDecode_String_WithEnter() throws IOException {
        testDecode_assertEquals("aaa\n", "aaa");
    }

    @Test
    public void testDecode_String_MiddleWithEnter() throws IOException {
        testDecode_assertEquals("aaa\r\naaa", Codec2.DecodeResult.NEED_MORE_INPUT);
    }

    @Test
    public void testDecode_Person_ObjectOnly() throws IOException {
        testDecode_assertEquals(new Person(), Codec2.DecodeResult.NEED_MORE_INPUT);
    }

    @Test
    public void testDecode_Person_WithEnter() throws IOException {
        testDecode_PersonWithEnterByte(new byte[]{'\r', '\n'}, false);//windows end
        testDecode_PersonWithEnterByte(new byte[]{'\n', '\r'}, true);
        testDecode_PersonWithEnterByte(new byte[]{'\n'}, false); //linux end
        testDecode_PersonWithEnterByte(new byte[]{'\r'}, true);
        testDecode_PersonWithEnterByte(new byte[]{'\r', 100}, true);
    }

    @Test
    public void testDecode_WithExitByte() throws IOException {
        HashMap<byte[], Boolean> exitbytes = new HashMap<byte[], Boolean>();
        exitbytes.put(new byte[]{3}, true); /* Windows Ctrl+C */
        exitbytes.put(new byte[]{1, 3}, false); //must equal the bytes
        exitbytes.put(new byte[]{-1, -12, -1, -3, 6}, true); /* Linux Ctrl+C */
        exitbytes.put(new byte[]{1, -1, -12, -1, -3, 6}, false); //must equal the bytes
        exitbytes.put(new byte[]{-1, -19, -1, -3, 6}, true);  /* Linux Pause */

        for (byte[] exit : exitbytes.keySet()) {
            testDecode_WithExitByte(exit, exitbytes.get(exit));
        }
    }

    @Test
    public void testDecode_Backspace() throws IOException {
        //32 8 first add space and then add backspace.
        testDecode_assertEquals(new byte[]{'\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[]{32, 8}));

        // test chinese
        byte[] chineseBytes = "中".getBytes();
        byte[] request = join(chineseBytes, new byte[]{'\b'});
        testDecode_assertEquals(request, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[]{32, 32, 8, 8}));
        //There may be some problem handling chinese (negative number recognition). Ignoring this problem, the backspace key is only meaningfully input in a real telnet program.
        testDecode_assertEquals(new byte[]{'a', 'x', -1, 'x', '\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[]{32, 32, 8, 8}));
    }

    @Test(expected = IOException.class)
    public void testDecode_Backspace_WithError() throws IOException {
        url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString());
        testDecode_Backspace();
        url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND);
    }

    @Test()
    public void testDecode_History_UP() throws IOException {
        //init channel
        AbstractMockChannel channel = getServerSideChannel(url);

        testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null);

        String request1 = "aaa\n";
        Object expected1 = "aaa";
        //init history
        testDecode_assertEquals(channel, request1, expected1, null);

        testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1);
    }

    @Test(expected = IOException.class)
    public void testDecode_UPorDOWN_WithError() throws IOException {
        url = url.addParameter(AbstractMockChannel.ERROR_WHEN_SEND, Boolean.TRUE.toString());

        //init channel
        AbstractMockChannel channel = getServerSideChannel(url);

        testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null);

        String request1 = "aaa\n";
        Object expected1 = "aaa";
        //init history
        testDecode_assertEquals(channel, request1, expected1, null);

        testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1);

        url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND);
    }

    //=============================================================================================================================
    @Test
    public void testEncode_String_ClientSide() throws IOException {
        testEecode_assertEquals("aaa", "aaa\r\n".getBytes(), false);
    }

    /*@Test()
    public void testDecode_History_UP_DOWN_MULTI() throws IOException{
        AbstractMockChannel channel = getServerSideChannel(url);

        String request1 = "aaa\n";
        Object expected1 = request1.replace("\n", "");
        //init history
        testDecode_assertEquals(channel, request1, expected1, null);

        String request2 = "bbb\n";
        Object expected2 = request2.replace("\n", "");
        //init history
        testDecode_assertEquals(channel, request2, expected2, null);

        String request3 = "ccc\n";
        Object expected3= request3.replace("\n", "");
        //init history
        testDecode_assertEquals(channel, request3, expected3, null);

        byte[] UP = new byte[] {27, 91, 65};
        byte[] DOWN = new byte[] {27, 91, 66};
        //history[aaa,bbb,ccc]
        testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected3);
        testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
        testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2);
        testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1);
        testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1);
        testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected1);
        testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected2);
        testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
        testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
        testDecode_assertEquals(channel, DOWN, Codec.NEED_MORE_INPUT, expected3);
        testDecode_assertEquals(channel, UP, Codec.NEED_MORE_INPUT, expected2);
    }*/

    //======================================================
    public static class Person implements Serializable {
        private static final long serialVersionUID = 3362088148941547337L;
        public String name;
        public String sex;

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            result = prime * result + ((sex == null) ? 0 : sex.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Person other = (Person) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            if (sex == null) {
                if (other.sex != null)
                    return false;
            } else if (!sex.equals(other.sex))
                return false;
            return true;
        }

    }

}


text:
/* eslint-env node, mocha */
/* global $database, $pg_database */
import knexCleaner from 'knex-cleaner';
import origExpect from 'unexpected';

import { getSingleton } from '../../app/app';
import { dbAdapter, PubSub } from '../../app/models';
import { PubSubAdapter } from '../../app/support/PubSubAdapter'

import * as funcTestHelper from './functional_test_helper';
import * as realtimeAssertions from './realtime_assertions';

const expect = origExpect.clone().use(realtimeAssertions);

describe('Realtime (Socket.io)', () => {
  before(async () => {
    await getSingleton();
    const pubsubAdapter = new PubSubAdapter($database)
    PubSub.setPublisher(pubsubAdapter)
  });

  let lunaContext = {};
  let marsContext = {};
  let marsTimeline = null;
  let lunaTimeline = null;
  const anonContext = { authToken: '' }

  beforeEach(async () => {
    await knexCleaner.clean($pg_database);

    [lunaContext, marsContext] = await Promise.all([
      funcTestHelper.createUserAsync('luna', 'pw'),
      funcTestHelper.createUserAsync('mars', 'pw'),
    ]);

    [{ Posts: lunaTimeline }, { Posts: marsTimeline }] = await Promise.all([
      dbAdapter.getUserTimelinesIds(lunaContext.user.id),
      dbAdapter.getUserTimelinesIds(marsContext.user.id),
    ]);
  })

  describe('User timeline', () => {
    it(
      'Luna gets notifications about public posts',
      () => expect(lunaContext, 'when subscribed to timeline', marsTimeline, 'to get post:* events from', marsContext)
    );

    it(
      'Anonymous user gets notifications about public posts',
      () => expect(anonContext, 'when subscribed to timeline', marsTimeline, 'to get post:* events from', marsContext)
    );

    describe('Mars is a private user', () => {
      beforeEach(async () => {
        await funcTestHelper.goPrivate(marsContext)
      });

      it(
        'Luna does not get notifications about his posts',
        () => expect(lunaContext, 'when subscribed to timeline', marsTimeline, 'not to get post:* events from', marsContext)
      );

      describe('Mars accepted luna\'s subscription request', () => {
        beforeEach(async () => {
          await funcTestHelper.sendRequestToSubscribe(lunaContext, marsContext)
          await funcTestHelper.acceptRequestAsync(marsContext, lunaContext)
        });

        it(
          'Luna gets notifications about his posts',
          () => expect(lunaContext, 'when subscribed to timeline', marsTimeline, 'to get post:* events from', marsContext)
        );
      });
    });

    describe('Mars blocked luna', () => {
      beforeEach(async () => {
        await funcTestHelper.banUser(marsContext, lunaContext)
      });

      it(
        'Luna does not get notifications about his posts',
        () => expect(lunaContext, 'when subscribed to timeline', marsTimeline, 'not to get post:* events from', marsContext)
      );

      it(
        'Mars does not get notifications about her posts',
        () => expect(marsContext, 'when subscribed to timeline', lunaTimeline, 'not to get post:* events from', lunaContext)
      );

      describe('Reactions', () => {
        let venusContext = {};
        let venusTimeline = null;
        let postId;

        beforeEach(async () => {
          venusContext = await funcTestHelper.createUserAsync('venus', 'pw');
          [
            { id: postId },
            { Posts: venusTimeline },
          ] = await Promise.all([
            funcTestHelper.createAndReturnPost(venusContext, 'test post'),
            dbAdapter.getUserTimelinesIds(venusContext.user.id),
          ]);
        });

        it('Mars does not get notifications about her likes',
          () => expect(marsContext,
            'when subscribed to timeline', venusTimeline,
            'with post having id', postId,
            'not to get like:* events from', lunaContext
          )
        );

        it('Mars does not get notifications about her comments',
          () => expect(marsContext,
            'when subscribed to timeline', venusTimeline,
            'with post having id', postId,
            'not to get comment:* events from', lunaContext
          )
        );
      });
    });
  });
});


text:
package seedu.gtd.storage;

import javax.xml.bind.annotation.XmlElement;

import seedu.gtd.commons.exceptions.IllegalValueException;
import seedu.gtd.model.task.*;
import seedu.gtd.model.tag.Tag;
import seedu.gtd.model.tag.UniqueTagList;

import java.util.ArrayList;
import java.util.List;

/**
 * JAXB-friendly version of the Task.
 */
public class XmlAdaptedTask {

	//@@author A0130677A
    @XmlElement(required = true)
    private String name;
    @XmlElement(required = true)
    private String startDate;
    @XmlElement(required = true)
    private String dueDate;
    @XmlElement(required = true)
    private String address;
    @XmlElement(required = true)
    private String priority;
    @XmlElement(required = true)
    private boolean isDone;

    @XmlElement
    private List<XmlAdaptedTag> tagged = new ArrayList<>();

    /**
     * No-arg constructor for JAXB use.
     */
    public XmlAdaptedTask() {}

    /**
     * Converts a given Task into this class for JAXB use.
     *
     * @param source future changes to this will not affect the created XmlAdaptedTask
     */
    public XmlAdaptedTask(ReadOnlyTask source) {
        name = source.getName().fullName;
        startDate = source.getStartDate().value;
        dueDate = source.getDueDate().value;
        address = source.getAddress().value;
        priority = source.getPriority().value;
        isDone = source.getisDone();
        tagged = new ArrayList<>();
        for (Tag tag : source.getTags()) {
            tagged.add(new XmlAdaptedTag(tag));
        }
    }

    /**
     * Converts this jaxb-friendly adapted task object into the model's Task object.
     *
     * @throws IllegalValueException if there were any data constraints violated in the adapted task
     */
    public Task toModelType() throws IllegalValueException {
        final List<Tag> taskTags = new ArrayList<>();
        for (XmlAdaptedTag tag : tagged) {
            taskTags.add(tag.toModelType());
        }
        final Name name = new Name(this.name);
        final DueDate startDate = new DueDate(this.startDate);
        final DueDate dueDate = new DueDate(this.dueDate);
        final Address address = new Address(this.address);
        final Priority priority = new Priority(this.priority);
        final boolean isDone = this.isDone;
        System.out.println("printed isdone as: " + isDone);
        final UniqueTagList tags = new UniqueTagList(taskTags);
        return new Task(name, startDate, dueDate, address, priority, tags, isDone);
    }
}


text:
<!DOCTYPE html>

    <title th:text="#{cas.dashboard.pagetitle}"></title>

[[#{cas.dashboard.section.dashboard.title}]]

No dashboard functionality/endpoint is configured and accessible.
                    Unless you teach CAS otherwise, all endpoints are disabled by default.
                    Revisit the CAS configuration/documentation and explicitly enable access for desired endpoints and knobs.

                    Status

                        Auto Configuration

                    Beans

                    Endpoint Mappings

                    Configuration Properties

                    Thread Dump

                    Environment

                    Health

                    Info

                    Metrics

                    Trace Requests

                    Statistics Panel

                    Configuration Panel

                    SSO Sessions

                    SSO Status

                    Registered Services

                    Webflow Report

                    Logging

                    Attribute Resolution

                    Trusted Devices

                    AuthN Events

[[#{cas.dashboard.section.server.functions.title}]]

                    <form method="post" th:action="@{/status/restart}">
                        <button class="btn btn-restart"
                                type="button"
                                data-toggle="modal"
                                data-target="#myModal"
                                th:inline="text"
                                th:attr="data-title=#{cas.dashboard.action.button.reboot.modal.title},data-message=#{cas.dashboard.action.button.reboot.modal.message}"
                        >
                            [[#{cas.dashboard.action.button.reboot}]]
                        </button>
                    </form>

                    <form method="post" th:action="@{/status/shutdown}">
                        <button type="button" class="btn btn-shutdown"
                                data-toggle="modal"
                                data-target="#myModal"
                                th:inline="text"
                                th:attr="data-title=#{cas.dashboard.action.button.shutdown.modal.title},data-message=#{cas.dashboard.action.button.shutdown.modal.message}"
                        >

                            [[#{cas.dashboard.action.button.shutdown}]]
                        </button>
                    </form>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Whom I Know</title>
    <meta name="description" content="Поиск общих друзей вконтакте">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <link rel="stylesheet" href="css/libs1.min.css"/>
    <link rel="stylesheet" href="css/main.min.css"/>

        Fork me!

                                vk.com/
                                <input type="text" class="form-control" id="first" aria-describedby="firstStatus">

                            (success)

                                vk.com/
                                <input type="text" class="form-control" id="second" aria-describedby="secondStatus">

                            (success)

                            <button type="button" class="btn btn-primary" id="startButton" data-toggle="modal" data-target="#startModal">Поиск</button>
                            <button type="button" class="btn btn-primary" id="settingButton" data-toggle="modal" data-target="#settingModal" aria-expanded="false">

                            </button>

                                    <input type="radio" data-panel="count">Посчитать

                                    <input type="radio" data-panel="write">Написать

                                    <input type="radio" data-panel="draw">Нарисовать

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Настройки

                        Длина цепочки

                    <button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Начать поиск?

                    При поиске всё будет люто тормозить.

                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="search">Готов</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Не готов</button>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Поиск завершен

                    Общие пользователи не найдены. Попробуй увеличить максимальную длину цепочки.

                    <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>


text:
package suadb.index.btree;

import suadb.buffer.PageFormatter;
import suadb.file.Page;
import suadb.record.TableInfo;

import static java.sql.Types.INTEGER;
import static suadb.file.Page.BLOCK_SIZE;
import static suadb.file.Page.INT_SIZE;

/**
 * An object that can format a page to look like an
 * empty B-tree chunk.
 * @author Edward Sciore
 */
public class BTPageFormatter implements PageFormatter {
	private TableInfo ti;
	private int flag;

	/**
	 * Creates a formatter for a new page of the
	 * specified B-tree suadb.index.
	 * @param ti the suadb.index's suadb.metadata
	 * @param flag the page's initial flag value
	 */
	public BTPageFormatter(TableInfo ti, int flag) {
		this.ti = ti;
		this.flag = flag;
	}

	/**
	 * Formats the page by initializing as many suadb.index-suadb.record slots
	 * as possible to have default values.
	 * Each integer field is given a value of 0, and
	 * each string field is given a value of "".
	 * The location that indicates the number of records
	 * in the page is also set to 0.
	 * @see suadb.buffer.PageFormatter#format(suadb.file.Page)
	 */
	public void format(Page page) {
		page.setInt(0, flag);
		page.setInt(INT_SIZE, 0);  // #records = 0
		int recsize = ti.recordLength();
		for (int pos=2*INT_SIZE; pos+recsize<=BLOCK_SIZE; pos += recsize)
			makeDefaultRecord(page, pos);
	}

	private void makeDefaultRecord(Page page, int pos) {
		for (String fldname : ti.schema().fields()) {
			int offset = ti.offset(fldname);
			if (ti.schema().type(fldname) == INTEGER)
				page.setInt(pos + offset, 0);
			else
				page.setString(pos + offset, "");
		}
	}
}


text:
<?php

namespace App\Validation\Rules\SubdivisionCode;

use App\Validation\Rules\AbstractSearcher;

/**
 * Validator for Nicaragua subdivision code.
 *
 * ISO 3166-1 alpha-2: NI
 *
 * @link http://www.geonames.org/NI/administrative-division-nicaragua.html
 */
class NiSubdivisionCode extends AbstractSearcher
{
    public $haystack = [
        'AN', // Region Autonoma del Atlantico Norte
        'AS', // Region Autonoma del Atlantico Sur
        'BO', // Boaco
        'CA', // Carazo
        'CI', // Chinandega
        'CO', // Chontales
        'ES', // Esteli
        'GR', // Granada
        'JI', // Jinotega
        'LE', // Leon
        'MD', // Madriz
        'MN', // Managua
        'MS', // Masaya
        'MT', // Matagalpa
        'NS', // Nueva Segovia
        'RI', // Rivas
        'SJ', // Rio San Juan
    ];

    public $compareIdentical = true;
}


text:
package com.opengamma.livedata.server.distribution;

import static org.testng.AssertJUnit.assertEquals;

import org.fudgemsg.FudgeContext;
import org.fudgemsg.MutableFudgeMsg;
import org.testng.annotations.Test;

import com.opengamma.id.ExternalId;
import com.opengamma.livedata.LiveDataValueUpdate;
import com.opengamma.livedata.normalization.StandardRules;
import com.opengamma.livedata.server.DistributionSpecification;
import com.opengamma.livedata.server.MapLastKnownValueStoreProvider;
import com.opengamma.livedata.server.Subscription;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class MarketDataDistributorTest {
  public static MarketDataDistributor getTestDistributor(MarketDataSenderFactory factory) {
    MapLastKnownValueStoreProvider lkvStoreProvider = new MapLastKnownValueStoreProvider();
    return new MarketDataDistributor(new DistributionSpecification(
        ExternalId.of("RIC", "AAPL.O"),
        StandardRules.getNoNormalization(),
        "LiveData.Bloomberg.Equity.AAPL"),
        new Subscription("", factory, lkvStoreProvider),
        factory,
        false,
        lkvStoreProvider);
  }

  static MarketDataDistributor getTestDistributor() {
    return getTestDistributor(new EmptyMarketDataSenderFactory());
  }

  //-------------------------------------------------------------------------
  public void testSequenceNumber() {
    MarketDataDistributor mdd = getTestDistributor();
    assertEquals(LiveDataValueUpdate.SEQUENCE_START, mdd.getNumMessagesSent());
    mdd.updateFieldHistory(FudgeContext.EMPTY_MESSAGE);
    assertEquals(0, mdd.getNumMessagesSent());
    MutableFudgeMsg msg = OpenGammaFudgeContext.getInstance().newMessage();
    msg.add("foo", "bar");
    mdd.distributeLiveData(msg);
    assertEquals(1, mdd.getNumMessagesSent());

    mdd.distributeLiveData(FudgeContext.EMPTY_MESSAGE); // empty msg not sent
    assertEquals(1, mdd.getNumMessagesSent());
  }

}


text:
'use strict';

(function() {
	// Calendaritems Controller Spec
	describe('Calendaritems Controller Tests', function() {
		// Initialize global variables
		var CalendaritemsController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Calendaritems controller.
			CalendaritemsController = $controller('CalendaritemsController', {
				$scope: scope
			});
		}));

		it('$scope.find() should create an array with at least one Calendaritem object fetched from XHR', inject(function(Calendaritems) {
			// Create sample Calendaritem using the Calendaritems service
			var sampleCalendaritem = new Calendaritems({
				name: 'New Calendaritem'
			});

			// Create a sample Calendaritems array that includes the new Calendaritem
			var sampleCalendaritems = [sampleCalendaritem];

			// Set GET response
			$httpBackend.expectGET('calendaritems').respond(sampleCalendaritems);

			// Run controller functionality
			scope.find();
			$httpBackend.flush();

			// Test scope value
			expect(scope.calendaritems).toEqualData(sampleCalendaritems);
		}));

		it('$scope.findOne() should create an array with one Calendaritem object fetched from XHR using a calendaritemId URL parameter', inject(function(Calendaritems) {
			// Define a sample Calendaritem object
			var sampleCalendaritem = new Calendaritems({
				name: 'New Calendaritem'
			});

			// Set the URL parameter
			$stateParams.calendaritemId = '525a8422f6d0f87f0e407a33';

			// Set GET response
			$httpBackend.expectGET(/calendaritems\/([0-9a-fA-F]{24})$/).respond(sampleCalendaritem);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.calendaritem).toEqualData(sampleCalendaritem);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Calendaritems) {
			// Create a sample Calendaritem object
			var sampleCalendaritemPostData = new Calendaritems({
				name: 'New Calendaritem'
			});

			// Create a sample Calendaritem response
			var sampleCalendaritemResponse = new Calendaritems({
				_id: '525cf20451979dea2c000001',
				name: 'New Calendaritem'
			});

			// Fixture mock form input values
			scope.name = 'New Calendaritem';

			// Set POST response
			$httpBackend.expectPOST('calendaritems', sampleCalendaritemPostData).respond(sampleCalendaritemResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.name).toEqual('');

			// Test URL redirection after the Calendaritem was created
			expect($location.path()).toBe('/calendaritems/' + sampleCalendaritemResponse._id);
		}));

		it('$scope.update() should update a valid Calendaritem', inject(function(Calendaritems) {
			// Define a sample Calendaritem put data
			var sampleCalendaritemPutData = new Calendaritems({
				_id: '525cf20451979dea2c000001',
				name: 'New Calendaritem'
			});

			// Mock Calendaritem in scope
			scope.calendaritem = sampleCalendaritemPutData;

			// Set PUT response
			$httpBackend.expectPUT(/calendaritems\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/calendaritems/' + sampleCalendaritemPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid calendaritemId and remove the Calendaritem from the scope', inject(function(Calendaritems) {
			// Create new Calendaritem object
			var sampleCalendaritem = new Calendaritems({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new Calendaritems array and include the Calendaritem
			scope.calendaritems = [sampleCalendaritem];

			// Set expected DELETE response
			$httpBackend.expectDELETE(/calendaritems\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleCalendaritem);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.calendaritems.length).toBe(0);
		}));
	});
}());


text:
import { register, waitFor } from '../dispatcher/AppDispatcher';
import { ActionTypes } from '../utils/Constants';
import BaseStore from  './BaseStore'
import messageStore from './MessageStore';
import threadStore from '../stores/ThreadStore';

class UnreadThreadStore extends BaseStore {

    constructor() {
        super();
    }

    getCount() {
        let threads = threadStore.getAll();
        let unreadCount = 0;
        //for (let id in threads) {
        //    if (!threads[ id ].lastMessage.isRead) {
        //        unreadCount++;
        //    }
        //}

        return unreadCount;
    }

}

let unreadThreadStore = new UnreadThreadStore();
unreadThreadStore.dispatchToken = register(action => {

    waitFor([
        threadStore.dispatchToken,
        messageStore.dispatchToken
    ]);

    switch (action.type) {

        case ActionTypes.CLICK_THREAD:

            unreadThreadStore.emitChange();
            break;

        case ActionTypes.RECEIVE_MESSAGES:

            unreadThreadStore.emitChange();
            break;

        default:
        // do nothing
    }
});

export default unreadThreadStore;


text:
package arbitrary

func (arb T) phonenumber_benisuef() string {
	return arb.phonenumber_egypt_3_4("82")
}


text:
<?php

namespace Integrated\Bundle\WebsiteBundle\DataFixtures\MongoDB;

use Doctrine\Bundle\MongoDBBundle\Fixture\ODMFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Nelmio\Alice\Loader\SimpleFilesLoader;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\Finder\Finder;

/**
 * @author Ger Jan van den Bosch <gerjan@e-active.nl>
 */
class LoadFixtureData implements ContainerAwareInterface, ODMFixtureInterface
{
    use ContainerAwareTrait;

    /**
     * @var SimpleFilesLoader|null
     */
    private $loader;

    public function __construct(?SimpleFilesLoader $loader)
    {
        $this->loader = $loader;
    }

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        if (!$this->loader) {
            throw new \Exception('Nelmio\Alice is required to load fixtures');
        }

        $files = [];

        /** @var \Symfony\Component\Finder\SplFileInfo $file */
        foreach (Finder::create()->in(__DIR__.\DIRECTORY_SEPARATOR.'alice')->name('*.yml')->sortByName() as $file) {
            $files[] = $file->getRealpath();
        }

        foreach ($this->loader->loadFiles($files)->getObjects() as $object) {
            $manager->persist($object);
        }

        $manager->flush();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Security.Principal;
using Xunit;

namespace System.Security.AccessControl.Tests
{
    public partial class SystemAcl_Purge
    {
        [Fact]
        public static void BasicValidationTestCases()
        {
            bool isContainer = false;
            bool isDS = false;

            RawAcl rawAcl = null;
            SystemAcl systemAcl = null;
            int aceCount = 0;
            SecurityIdentifier sid = null;

            GenericAce gAce = null;
            byte revision = 0;
            int capacity = 0;
            //CustomAce constructor parameters
            AceType aceType = AceType.AccessAllowed;
            AceFlags aceFlag = AceFlags.None;
            byte[] opaque = null;
            //CompoundAce constructor additional parameters
            int accessMask = 0;
            CompoundAceType compoundAceType = CompoundAceType.Impersonation;
            string sidStr = "BG";
            //CommonAce constructor additional parameters
            AceQualifier aceQualifier = 0;
            //ObjectAce constructor additional parameters
            ObjectAceFlags objectAceFlag = 0;
            Guid objectAceType;
            Guid inheritedObjectAceType;
            //case 1, no Ace
            revision = 127;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            isContainer = true;
            isDS = false;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 0;
            sidStr = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            Assert.True(TestPurge(systemAcl, sid, aceCount));

            //case 2, only have 1 explicit Ace of the sid
            revision = 0;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            sidStr = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            //199 has all aceflags but inheritedonly and inherited
            gAce = new CommonAce((AceFlags)199, AceQualifier.SystemAudit, 1, sid, false, null);
            rawAcl.InsertAce(0, gAce);
            isContainer = false;
            isDS = false;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 0;
            Assert.True(TestPurge(systemAcl, sid, aceCount));

            //case 3, only have 1 explicit Ace of different sid
            revision = 0;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            //199 has all aceflags but inheritedonly and inherited
            sidStr = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            gAce = new CommonAce((AceFlags)199, AceQualifier.SystemAudit, 1, sid, false, null);
            rawAcl.InsertAce(0, gAce);
            isContainer = false;
            isDS = false;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 1;
            sidStr = "BA";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            Assert.True(TestPurge(systemAcl, sid, aceCount));

            //case 4, only have 1 inherited Ace of the sid
            revision = 0;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            sidStr = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            //215 has all aceflags but inheritedonly
            gAce = new CommonAce((AceFlags)215, AceQualifier.SystemAudit, 1, sid, false, null);
            rawAcl.InsertAce(0, gAce);
            isContainer = false;
            isDS = false;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 1;
            Assert.True(TestPurge(systemAcl, sid, aceCount));

            //case 5, have one explicit Ace and one inherited Ace of the sid
            revision = 255;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            sidStr = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            //199 has all aceflags but inheritedonly and inherited
            gAce = new CommonAce((AceFlags)199, AceQualifier.SystemAudit, 1, sid, false, null);
            rawAcl.InsertAce(0, gAce);
            //215 has all aceflags but inheritedonly
            gAce = new CommonAce((AceFlags)215, AceQualifier.SystemAudit, 2, sid, false, null);
            rawAcl.InsertAce(1, gAce);
            isContainer = true;
            isDS = false;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 1;
            Assert.True(TestPurge(systemAcl, sid, aceCount));

            //case 6, have two explicit Aces of the sid
            revision = 255;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            sidStr = "BG";
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sidStr));
            gAce = new CommonAce(AceFlags.FailedAccess, AceQualifier.SystemAudit, 1, sid, false, null);
            rawAcl.InsertAce(0, gAce);
            gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 2, sid, false, null);
            rawAcl.InsertAce(0, gAce);
            isContainer = true;
            isDS = false;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 0;
            Assert.True(TestPurge(systemAcl, sid, 0));

            //case 7, 1 explicit CustomAce

            Assert.Throws<InvalidOperationException>(() =>
            {
                revision = 127;
                capacity = 1;
                rawAcl = new RawAcl(revision, capacity);
                aceType = AceType.MaxDefinedAceType + 1;
                //199 has all aceflags but inheritedonly and inherited
                aceFlag = (AceFlags)199;
                opaque = null;
                gAce = new CustomAce(aceType, aceFlag, opaque);
                rawAcl.InsertAce(0, gAce);
                isContainer = false;
                isDS = false;
                systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
                sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG"));
                aceCount = 1;
                //After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and
                //forbid the modification on uncanonical ACL, this case will throw InvalidOperationException
                TestPurge(systemAcl, sid, aceCount);
            });
            //case 8,  1 explicit CompoundAce

            Assert.Throws<InvalidOperationException>(() =>
            {
                revision = 127;
                capacity = 1;
                rawAcl = new RawAcl(revision, capacity);
                //207 has all AceFlags but inherited
                aceFlag = (AceFlags)207;
                accessMask = 1;
                compoundAceType = CompoundAceType.Impersonation;
                sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG"));
                gAce = new CompoundAce(aceFlag, accessMask, compoundAceType, sid);
                rawAcl.InsertAce(0, gAce);
                isContainer = true;
                isDS = false;
                systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
                aceCount = 0;
                //After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and
                //forbid the modification on uncanonical ACL, this case will throw InvalidOperationException
                TestPurge(systemAcl, sid, aceCount);
            });
            //case 9, 1 explicit ObjectAce

            revision = 127;
            capacity = 1;
            rawAcl = new RawAcl(revision, capacity);
            sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG"));
            //207 has all AceFlags but inherited
            aceFlag = (AceFlags)207;
            aceQualifier = AceQualifier.SystemAudit;
            accessMask = 1;
            objectAceFlag = ObjectAceFlags.ObjectAceTypePresent | ObjectAceFlags.InheritedObjectAceTypePresent;
            objectAceType = new Guid("11111111-1111-1111-1111-111111111111");
            inheritedObjectAceType = new Guid("22222222-2222-2222-2222-222222222222");
            gAce = new ObjectAce(aceFlag, aceQualifier, accessMask, sid, objectAceFlag, objectAceType, inheritedObjectAceType, false, null);
            rawAcl.InsertAce(0, gAce);
            isContainer = true;
            isDS = true;
            systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
            aceCount = 0;
            Assert.True(TestPurge(systemAcl, sid, aceCount));

        }

        [Fact]
        public static void AdditionalTestCases()
        {
            bool isContainer = false;
            bool isDS = false;

            RawAcl rawAcl = null;
            SystemAcl systemAcl = null;

            byte revision = 0;
            int capacity = 0;
            //case 1, null Sid

            Assert.Throws<ArgumentNullException>(() =>
            {
                revision = 127;
                capacity = 1;
                rawAcl = new RawAcl(revision, capacity);
                isContainer = true;
                isDS = false;
                systemAcl = new SystemAcl(isContainer, isDS, rawAcl);
                systemAcl.Purge(null);
            });
        }

        private static bool TestPurge(SystemAcl systemAcl, SecurityIdentifier sid, int aceCount)
        {
            KnownAce ace = null;
            systemAcl.Purge(sid);
            if (aceCount != systemAcl.Count)
                return false;
            for (int i = 0; i < systemAcl.Count; i++)
            {
                ace = systemAcl[i] as KnownAce;
                if (ace != null && ((ace.AceFlags & AceFlags.Inherited) == 0))
                {
                    if (ace.SecurityIdentifier == sid)
                        return false;
                }
            }
            return true;
        }

    }
}


text:
(function () {

module("base");

test("bind", 3, function() {
    function func(a, b) {
        equals(this.prop, 5);
        equals(a, "banana");
        deepEqual(b, [2, 3, 4]);
    }

    var thisObject = {
        "prop": 5
    };

    var bound = func.bind(thisObject, "banana");
    bound([2, 3, 4]);
});

test("joinPath", 1, function() {
    var value = base.joinPath("path/to", "test.html");
    equals(value, "path/to/test.html");
});

test("endsWith", 9, function() {
    ok(base.endsWith("xyz", ""));
    ok(base.endsWith("xyz", "z"));
    ok(base.endsWith("xyz", "yz"));
    ok(base.endsWith("xyz", "xyz"));
    ok(!base.endsWith("xyz", "wxyz"));
    ok(!base.endsWith("xyz", "gwxyz"));
    ok(base.endsWith("", ""));
    ok(!base.endsWith("", "z"));
    ok(!base.endsWith("xyxy", "yx"));
});

test("trimExtension", 6, function() {
    equals(base.trimExtension("xyz"), "xyz");
    equals(base.trimExtension("xy.z"), "xy");
    equals(base.trimExtension("x.yz"), "x");
    equals(base.trimExtension("x.y.z"), "x.y");
    equals(base.trimExtension(".xyz"), "");
    equals(base.trimExtension(""), "");
});

test("joinPath with empty parent", 1, function() {
    var value = base.joinPath("", "test.html");
    equals(value, "test.html");
});

test("dirName", 3, function() {
    equals(base.dirName("foo.html"), "foo.html");
    equals(base.dirName("foo/bar.html"), "foo");
    equals(base.dirName("foo/bar/baz.html"), "foo/bar");
});

test("uniquifyArray", 5, function() {
    deepEqual(base.uniquifyArray([]), []);
    deepEqual(base.uniquifyArray(["a"]), ["a"]);
    deepEqual(base.uniquifyArray(["a", "b"]), ["a", "b"]);
    deepEqual(base.uniquifyArray(["a", "b", "b"]), ["a", "b"]);
    deepEqual(base.uniquifyArray(["a", "b", "b", "a"]), ["a", "b"]);
});

test("flattenArray", 5, function() {
    deepEqual(base.flattenArray([]), []);
    deepEqual(base.flattenArray([["a"]]), ["a"]);
    deepEqual(base.flattenArray([["a"], ["b"]]), ["a", "b"]);
    deepEqual(base.flattenArray([["a"], ["b", "c"]]), ["a", "b", "c"]);
    deepEqual(base.flattenArray([["a"], [], ["b"]]), ["a", "b"]);
});

test("callInParallel", 4, function() {
    var expectedCall = [true, true, true];
    var expectCompletionCallback = true;

    base.callInParallel([
        function(callback) {
            ok(expectedCall[0]);
            expectedCall[0] = false;
            callback();
        },
        function(callback) {
            ok(expectedCall[1]);
            expectedCall[1] = false;
            callback();
        },
        function(callback) {
            ok(expectedCall[2]);
            expectedCall[2] = false;
            callback();
        },
    ], function() {
        ok(expectCompletionCallback);
        expectCompletionCallback = false;
    })
});

test("callInSequence", 7, function() {
    var expectedArg = 42;
    var expectCompletionCallback = true;

    base.callInSequence(function(arg, callback) {
        ok(arg < 45);
        equals(arg, expectedArg++);
        callback();
    }, [42, 43, 44], function() {
        ok(expectCompletionCallback);
        expectCompletionCallback = false;
    })
});

test("RequestTracker", 5, function() {
    var ready = false;
    var tracker = new base.RequestTracker(1, function() {
        ok(ready);
    });
    ready = true;
    tracker.requestComplete();
    ready = false;

    tracker = new base.RequestTracker(2, function(parameter) {
        ok(ready);
        equals(parameter, 'argument');
    }, ['argument']);
    tracker.requestComplete();
    ready = true;
    tracker.requestComplete();
    ready = false;

    tracker = new base.RequestTracker(0, function() {
        ok(true);
    });
    tracker.requestComplete();

    tracker = new base.RequestTracker(0);
    tracker.requestComplete();
    // Should not barf.
    ok(true);
});

test("CallbackIterator", 22, function() {
    var expected = 0;
    var iterator = new base.CallbackIterator(function(a, b) {
        equals(a, 'ArgA' + expected);
        equals(b, 'ArgB' + expected);
        ++expected;
    }, [
        ['ArgA0', 'ArgB0'],
        ['ArgA1', 'ArgB1'],
        ['ArgA2', 'ArgB2'],
    ]);
    ok(iterator.hasNext())
    ok(!iterator.hasPrevious())
    iterator.callNext();
    ok(iterator.hasNext())
    ok(!iterator.hasPrevious())
    iterator.callNext();
    ok(iterator.hasNext())
    ok(iterator.hasPrevious())
    iterator.callNext();
    ok(!iterator.hasNext())
    ok(iterator.hasPrevious())
    expected = 1;
    iterator.callPrevious();
    ok(iterator.hasNext())
    ok(iterator.hasPrevious())
    expected = 0;
    iterator.callPrevious();
    ok(iterator.hasNext())
    ok(!iterator.hasPrevious())
});

test("filterDictionary", 3, function() {
    var dictionary = {
        'foo': 43,
        'bar': 11
    };
    deepEqual(base.filterDictionary(dictionary, function() { return true; }), {
        "foo": 43,
        "bar": 11
    });
    deepEqual(base.filterDictionary(dictionary, function() { return false; }), { });
    deepEqual(base.filterDictionary(dictionary, function(key) { return key == 'foo'; }), {
        "foo": 43
    });
});

test("mapDictionary", 3, function() {
    deepEqual(base.mapDictionary({}, function(value) { return value - 10; }), {});
    var dictionary = {
        'foo': 43,
        'bar': 11
    };
    deepEqual(base.mapDictionary(dictionary, function(value) { return value - 10; }), {
        "foo": 33,
        "bar": 1
    });
    deepEqual(base.mapDictionary(dictionary, function(value) {
        if (value > 20)
            return value - 20;
    }), {
        "foo": 23,
    });
});

test("filterTree", 2, function() {
    var tree = {
        'path': {
            'to': {
                'test.html': {
                    'actual': 'PASS',
                    'expected': 'FAIL'
                }
            },
            'another.html': {
                'actual': 'TEXT',
                'expected': 'PASS'
            }
        }
    }

    function isLeaf(node)
    {
        return !!node.actual;
    }

    function actualIsText(node)
    {
        return node.actual == 'TEXT';
    }

    var all = base.filterTree(tree, isLeaf, function() { return true });
    deepEqual(all, {
        'path/to/test.html': {
            'actual': 'PASS',
            'expected': 'FAIL'
        },
        'path/another.html': {
            'actual': 'TEXT',
            'expected': 'PASS'
        }
    });

    var text = base.filterTree(tree, isLeaf, actualIsText);
    deepEqual(text, {
        'path/another.html': {
            'actual': 'TEXT',
            'expected': 'PASS'
        }
    });
});

test("UpdateTracker", 20, function() {
    var dict;

    function dumpKeys()
    {
        var updates = []
        dict.forEach(function(item, key, updated) {
            updates.push(key);
        });
        return updates;
    }

    function dumpUpdatedKeys()
    {
        var updates = []
        dict.forEach(function(item, key, updated) {
            updated && updates.push(key);
        });
        return updates;
    }

    dict = new base.UpdateTracker();
    dict.update("5", {});
    deepEqual(dumpUpdatedKeys(), ["5"]);
    dict.update("6", {});
    dict.update("7", {});
    deepEqual(dumpUpdatedKeys(), ["5", "6", "7"]);
    deepEqual(dict.get("6"), {});
    ok(dict.exists("7"));
    dict.purge();
    deepEqual(dumpUpdatedKeys(), []);
    deepEqual(dumpKeys(), ["5", "6", "7"]);
    dict.update("5", {});
    deepEqual(dumpUpdatedKeys(), ["5"]);
    dict.update("4", {});
    deepEqual(dumpUpdatedKeys(), ["4", "5"]);
    deepEqual(dumpKeys(), ["4", "5", "6", "7"]);
    dict.purge();
    deepEqual(dumpKeys(), ["4", "5"]);
    deepEqual(dumpUpdatedKeys(), []);
    dict.purge();
    deepEqual(dumpKeys(), []);

    var removeCount = 0;
    dict.update("one");
    deepEqual(dumpUpdatedKeys(), ["one"]);
    dict.update("two");
    deepEqual(dumpUpdatedKeys(), ["one", "two"]);
    dict.update("three");
    dict.purge();
    deepEqual(dumpKeys(), ["one", "three", "two"]);
    dict.update("two");
    dict.purge(function() {
        removeCount++;
    });
    deepEqual(dumpKeys(), ["two"]);
    equal(removeCount, 2);
    dict.update("four");
    var removeCounter = { count: 0 };
    dict.purge(function() {
        this.count++;
    }, removeCounter);
    equal(removeCounter.count, 1);
    dict.purge(function() {
        equal(String(this), "four");
    });

    dict = new base.UpdateTracker();
    dict.update("one");
    var thisObject = {}
    dict.forEach(function(item) {
        equal(this, thisObject);
    }, thisObject);

});

test("extends", 14, function() {

    var LikeDiv = base.extends("div", {
        init: function() {
            this.textContent = "awesome";
        },
        method: function(msg) {
            return 42;
        }
    });

    var LikeLikeDiv = base.extends(LikeDiv, {
        init: function() {
            this.className = "like";
        }
    });

    var LikeP = base.extends("p", {
        init: function(content) {
            this.textContent = content
        }
    });

    var LikeProgress = base.extends("progress", {
        init: function() {
            this.max = 100;
            this.value = 10;
        }
    });

    var LikeLikeProgress = base.extends(LikeProgress, {
        completed: function() {
            this.value = 100;
        }
    });

    document.body.appendChild(new LikeDiv());
    equals(document.body.lastChild.tagName, "DIV");
    equals(document.body.lastChild.innerHTML, "awesome");
    equals(document.body.lastChild.method(), 42);
    document.body.removeChild(document.body.lastChild);

    document.body.appendChild(new LikeLikeDiv());
    equals(document.body.lastChild.tagName, "DIV");
    equals(document.body.lastChild.innerHTML, "awesome");
    equals(document.body.lastChild.method(), 42);
    equals(document.body.lastChild.className, "like");
    document.body.removeChild(document.body.lastChild);

    document.body.appendChild(new LikeP("super"));
    equals(document.body.lastChild.tagName, "P");
    equals(document.body.lastChild.innerHTML, "super");
    raises(function() {
        document.body.lastChild.method();
    });
    document.body.removeChild(document.body.lastChild);

    document.body.appendChild(new LikeProgress());
    equals(document.body.lastChild.tagName, "PROGRESS");
    // Safari 5.1 lacks the <progress> element.
    // equals(document.body.lastChild.position, 0.1);
    equals(document.body.lastChild.innerHTML, "");
    raises(function() {
        document.body.lastChild.method();
    });
    document.body.removeChild(document.body.lastChild);

    document.body.appendChild(new LikeLikeProgress());
    equals(document.body.lastChild.tagName, "PROGRESS");
    // Safari 5.1 lacks the <progress> element.
    // equals(document.body.lastChild.position, 0.1);
    document.body.lastChild.completed();
    // Safari 5.1 lacks the <progress> element.
    // equals(document.body.lastChild.position, 1);
    document.body.removeChild(document.body.lastChild);
});

test("relativizeTime", 14, function() {
    var time = new Date();
    equals(base.relativizeTime(time), "Just now");
    time.setMinutes(time.getMinutes() - 1);
    equals(base.relativizeTime(time), "1 minute ago");
    time.setMinutes(time.getMinutes() - 1);
    equals(base.relativizeTime(time), "2 minutes ago");
    time.setMinutes(time.getMinutes() - 1);
    equals(base.relativizeTime(time), "3 minutes ago");
    time.setMinutes(time.getMinutes() - 56);
    equals(base.relativizeTime(time), "59 minutes ago");
    time.setMinutes(time.getMinutes() - 1);
    equals(base.relativizeTime(time), "1 hour ago");
    time.setMinutes(time.getMinutes() - 29);
    equals(base.relativizeTime(time), "1 hour ago");
    time.setMinutes(time.getMinutes() - 2);
    equals(base.relativizeTime(time), "2 hours ago");
    time.setMinutes(time.getMinutes() - 29);
    equals(base.relativizeTime(time), "2 hours ago");
    time.setHours(time.getHours() - 1);
    equals(base.relativizeTime(time), "3 hours ago");
    time.setHours(time.getHours() - 20);
    equals(base.relativizeTime(time), "23 hours ago");
    time.setHours(time.getHours() - 1);
    equals(base.relativizeTime(time), "1 day ago");
    time.setDate(time.getDate() - 1);
    equals(base.relativizeTime(time), "2 days ago");
    time.setDate(time.getDate() - 998);
    equals(base.relativizeTime(time), "1000 days ago");
});

test("getURLParameter", 1, function() {
    ok(!base.getURLParameter('non-existant'));
});

test("parseJSONP", 6, function() {
    deepEqual(base.parseJSONP(""), {});
    deepEqual(base.parseJSONP('p({"key": "value"})'), {"key": "value"});
    deepEqual(base.parseJSONP('ADD_RESULTS({"dummy":"data"});'), {"dummy":"data"});
    deepEqual(base.parseJSONP('{"dummy":"data"}'), {"dummy":"data"});
    deepEqual(base.parseJSONP('ADD_RESULTS({"builder(1)":"data"});'), {"builder(1)":"data"});
    deepEqual(base.parseJSONP('{"builder(1)":"data"}'), {"builder(1)":"data"});
});

})();


text:
                BuckleGarde
                Bridging the gap between verbal and aggressive restraints

Safety

                        BuckleGarde is an easy-to-use tool for healthcare personnel to
                        help deter patients from removing their safety straps, creating a
                        safer transport environment.

                    Learn More

Deterrance

                        The BuckleGarde helps deter patients from harming
                        themselves by unbuckling the safety straps used during medical
                        transport, handling, observation, and positioning.

                    Learn More

Options

                        BuckleGarde works with the safety buckles currently used
                        in the industry to bridge the gap between verbal restraint and more
                        aggressive restraint methods.

                    Learn More


text:
require 'test/unit'
require 'appiaries'
require 'yaml'

APP_ID       = 'smilein5sec'
DATASTORE_ID = '_sandbox'

class JsonDataClientTest < Test::Unit::TestCase
  def setup
    @config = YAML.load(File.open(File.join(File.dirname(__FILE__), 'config.yml')).read)
    apptoken = @config['appiaries_app_token']
    collection_id = "sample_json_data"
    @client = Appiaries::JsonDataClient.new(:application_token => apptoken, :application_id => APP_ID, :datastore_id => DATASTORE_ID, :collection_id => collection_id)
    # puts "#{apptoken} is ready"
    @to_be_deleted_on_teardown = []
  end
  def teardown
    @to_be_deleted_on_teardown.each do |object_id|
      @client.delete(object_id)
    end
  end

  def test_json_data_client_get
    res = @client.get("sample")
    assert_equal "sample", res["_id"]
    assert_equal "sample", res["name"]
  end
  def test_json_data_client_create
    body = {"my_name_is" =>"appiaries"}
    res = @client.create(body)
    assert_equal "appiaries", res["my_name_is"]
    @to_be_deleted_on_teardown.push(res["_id"])
  end
  def test_json_data_client_update
    body = {"my_name_is" =>"to be updated"}
    res = @client.create(body)
    assert_equal "to be updated", res["my_name_is"]
    object_id = res["_id"]
    #puts "\n\n" + object_id + "\n\n"
    newbody = {"my_name_is" => "SAYAKA", "greeting" => "hello"}
    res = @client.put(object_id, newbody)
    assert_equal "SAYAKA", res["my_name_is"]
    assert_equal "hello", res["greeting"]
    @to_be_deleted_on_teardown.push(object_id)
  end
  def test_json_data_client_update_field
    body = {"my_name_is" =>"to be field updated", "stay" => "no change", "replace_me" => "please"}
    res = @client.create(body)
    assert_equal "please", res["replace_me"]
    object_id = res["_id"]

    new_field = {"replace_me" => "completed"}
    res = @client.update(object_id, new_field)
    assert_equal "completed", res["replace_me"]
    @to_be_deleted_on_teardown.push(object_id)
  end
  def test_json_data_client_update_delete
    body = {"my_name_is" =>"to be deleted"}
    res = @client.create(body)
    assert_equal "to be deleted", res["my_name_is"]
    object_id = res["_id"]

    res = @client.delete(object_id)
    # TODO assert
  end
  def test_json_data_client_update_query
    # TODO implement
  end
end