text:
// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.

#ifndef MUDUO_NET_BUFFER_H
#define MUDUO_NET_BUFFER_H

#include <muduo/base/copyable.h>
#include <muduo/base/StringPiece.h>
#include <muduo/base/Types.h>

#include <muduo/net/Endian.h>

#include <algorithm>
#include <vector>

#include <assert.h>
#include <string.h>
//#include <unistd.h>  // ssize_t

namespace muduo
{
namespace net
{

/// A buffer class modeled after org.jboss.netty.buffer.ChannelBuffer
///
/// @code
/// +-------------------+------------------+------------------+
/// | prependable bytes |  readable bytes  |  writable bytes  |
/// |                   |     (CONTENT)    |                  |
/// +-------------------+------------------+------------------+
/// |                   |                  |                  |
/// 0      <=      readerIndex   <=   writerIndex    <=     size
/// @endcode
class Buffer : public muduo::copyable
{
 public:
  static const size_t kCheapPrepend = 8;
  static const size_t kInitialSize = 1024;

  explicit Buffer(size_t initialSize = kInitialSize)
    : buffer_(kCheapPrepend + initialSize),
      readerIndex_(kCheapPrepend),
      writerIndex_(kCheapPrepend)
  {
    assert(readableBytes() == 0);
    assert(writableBytes() == initialSize);
    assert(prependableBytes() == kCheapPrepend);
  }

  // implicit copy-ctor, move-ctor, dtor and assignment are fine
  // NOTE: implicit move-ctor is added in g++ 4.6

  void swap(Buffer& rhs)
  {
    buffer_.swap(rhs.buffer_);
    std::swap(readerIndex_, rhs.readerIndex_);
    std::swap(writerIndex_, rhs.writerIndex_);
  }

  size_t readableBytes() const
  { return writerIndex_ - readerIndex_; }

  size_t writableBytes() const
  { return buffer_.size() - writerIndex_; }

  size_t prependableBytes() const
  { return readerIndex_; }

  const char* peek() const
  { return begin() + readerIndex_; }

  const char* findCRLF() const
  {
    // FIXME: replace with memmem()?
    const char* crlf = std::search(peek(), beginWrite(), kCRLF, kCRLF+2);
    return crlf == beginWrite() ? NULL : crlf;
  }

  const char* findCRLF(const char* start) const
  {
    assert(peek() <= start);
    assert(start <= beginWrite());
    // FIXME: replace with memmem()?
    const char* crlf = std::search(start, beginWrite(), kCRLF, kCRLF+2);
    return crlf == beginWrite() ? NULL : crlf;
  }

  const char* findEOL() const
  {
    const void* eol = memchr(peek(), '\n', readableBytes());
    return static_cast<const char*>(eol);
  }

  const char* findEOL(const char* start) const
  {
    assert(peek() <= start);
    assert(start <= beginWrite());
    const void* eol = memchr(start, '\n', beginWrite() - start);
    return static_cast<const char*>(eol);
  }

  // retrieve returns void, to prevent
  // string str(retrieve(readableBytes()), readableBytes());
  // the evaluation of two functions are unspecified
  void retrieve(size_t len)
  {
    assert(len <= readableBytes());
    if (len < readableBytes())
    {
      readerIndex_ += len;
    }
    else
    {
      retrieveAll();
    }
  }

  void retrieveUntil(const char* end)
  {
    assert(peek() <= end);
    assert(end <= beginWrite());
    retrieve(end - peek());
  }

  void retrieveInt64()
  {
    retrieve(sizeof(int64_t));
  }

  void retrieveInt32()
  {
    retrieve(sizeof(int32_t));
  }

  void retrieveInt16()
  {
    retrieve(sizeof(int16_t));
  }

  void retrieveInt8()
  {
    retrieve(sizeof(int8_t));
  }

  void retrieveAll()
  {
    readerIndex_ = kCheapPrepend;
    writerIndex_ = kCheapPrepend;
  }

  string retrieveAllAsString()
  {
    return retrieveAsString(readableBytes());;
  }

  string retrieveAsString(size_t len)
  {
    assert(len <= readableBytes());
    string result(peek(), len);
    retrieve(len);
    return result;
  }

  StringPiece toStringPiece() const
  {
    return StringPiece(peek(), static_cast<int>(readableBytes()));
  }

  void append(const StringPiece& str)
  {
    append(str.data(), str.size());
  }

  void append(const char* /*restrict*/ data, size_t len)
  {
    ensureWritableBytes(len);
    std::copy(data, data+len, beginWrite());
    hasWritten(len);
  }

  void append(const void* /*restrict*/ data, size_t len)
  {
    append(static_cast<const char*>(data), len);
  }

  void ensureWritableBytes(size_t len)
  {
    if (writableBytes() < len)
    {
      makeSpace(len);
    }
    assert(writableBytes() >= len);
  }

  char* beginWrite()
  { return begin() + writerIndex_; }

  const char* beginWrite() const
  { return begin() + writerIndex_; }

  void hasWritten(size_t len)
  {
    assert(len <= writableBytes());
    writerIndex_ += len;
  }

  void unwrite(size_t len)
  {
    assert(len <= readableBytes());
    writerIndex_ -= len;
  }

  ///
  /// Append int64_t using network endian
  ///
  void appendInt64(int64_t x)
  {
    int64_t be64 = sockets::hostToNetwork64(x);
    append(&be64, sizeof be64);
  }

  ///
  /// Append int32_t using network endian
  ///
  void appendInt32(int32_t x)
  {
    int32_t be32 = sockets::hostToNetwork32(x);
    append(&be32, sizeof be32);
  }

  void appendInt16(int16_t x)
  {
    int16_t be16 = sockets::hostToNetwork16(x);
    append(&be16, sizeof be16);
  }

  void appendInt8(int8_t x)
  {
    append(&x, sizeof x);
  }

  ///
  /// Read int64_t from network endian
  ///
  /// Require: buf->readableBytes() >= sizeof(int32_t)
  int64_t readInt64()
  {
    int64_t result = peekInt64();
    retrieveInt64();
    return result;
  }

  ///
  /// Read int32_t from network endian
  ///
  /// Require: buf->readableBytes() >= sizeof(int32_t)
  int32_t readInt32()
  {
    int32_t result = peekInt32();
    retrieveInt32();
    return result;
  }

  int16_t readInt16()
  {
    int16_t result = peekInt16();
    retrieveInt16();
    return result;
  }

  int8_t readInt8()
  {
    int8_t result = peekInt8();
    retrieveInt8();
    return result;
  }

  ///
  /// Peek int64_t from network endian
  ///
  /// Require: buf->readableBytes() >= sizeof(int64_t)
  int64_t peekInt64() const
  {
    assert(readableBytes() >= sizeof(int64_t));
    int64_t be64 = 0;
    ::memcpy(&be64, peek(), sizeof be64);
    return sockets::networkToHost64(be64);
  }

  ///
  /// Peek int32_t from network endian
  ///
  /// Require: buf->readableBytes() >= sizeof(int32_t)
  int32_t peekInt32() const
  {
    assert(readableBytes() >= sizeof(int32_t));
    int32_t be32 = 0;
    ::memcpy(&be32, peek(), sizeof be32);
    return sockets::networkToHost32(be32);
  }

  int16_t peekInt16() const
  {
    assert(readableBytes() >= sizeof(int16_t));
    int16_t be16 = 0;
    ::memcpy(&be16, peek(), sizeof be16);
    return sockets::networkToHost16(be16);
  }

  int8_t peekInt8() const
  {
    assert(readableBytes() >= sizeof(int8_t));
    int8_t x = *peek();
    return x;
  }

  ///
  /// Prepend int64_t using network endian
  ///
  void prependInt64(int64_t x)
  {
    int64_t be64 = sockets::hostToNetwork64(x);
    prepend(&be64, sizeof be64);
  }

  ///
  /// Prepend int32_t using network endian
  ///
  void prependInt32(int32_t x)
  {
    int32_t be32 = sockets::hostToNetwork32(x);
    prepend(&be32, sizeof be32);
  }

  void prependInt16(int16_t x)
  {
    int16_t be16 = sockets::hostToNetwork16(x);
    prepend(&be16, sizeof be16);
  }

  void prependInt8(int8_t x)
  {
    prepend(&x, sizeof x);
  }

  void prepend(const void* /*restrict*/ data, size_t len)
  {
    assert(len <= prependableBytes());
    readerIndex_ -= len;
    const char* d = static_cast<const char*>(data);
    std::copy(d, d+len, begin()+readerIndex_);
  }

  void shrink(size_t reserve)
  {
    // FIXME: use vector::shrink_to_fit() in C++ 11 if possible.
    Buffer other;
    other.ensureWritableBytes(readableBytes()+reserve);
    other.append(toStringPiece());
    swap(other);
  }

  size_t internalCapacity() const
  {
    return buffer_.capacity();
  }

  /// Read data directly into buffer.
  ///
  /// It may implement with readv(2)
  /// @return result of read(2), @c errno is saved
  ssize_t readFd(int fd, int* savedErrno);

 private:

  char* begin()
  { return &*buffer_.begin(); }

  const char* begin() const
  { return &*buffer_.begin(); }

  void makeSpace(size_t len)
  {
    if (writableBytes() + prependableBytes() < len + kCheapPrepend)
    {
      // FIXME: move readable data
      buffer_.resize(writerIndex_+len);
    }
    else
    {
      // move readable data to the front, make space inside buffer
      assert(kCheapPrepend < readerIndex_);
      size_t readable = readableBytes();
      std::copy(begin()+readerIndex_,
                begin()+writerIndex_,
                begin()+kCheapPrepend);
      readerIndex_ = kCheapPrepend;
      writerIndex_ = readerIndex_ + readable;
      assert(readable == readableBytes());
    }
  }

 private:
  std::vector<char> buffer_;
  size_t readerIndex_;
  size_t writerIndex_;

  static const char kCRLF[];
};

}
}

#endif  // MUDUO_NET_BUFFER_H


text:
#ifndef SRS_APP_HTTP_CONN_HPP
#define SRS_APP_HTTP_CONN_HPP

/*
#include <srs_app_http_conn.hpp>
*/

#include <srs_core.hpp>

#ifdef SRS_AUTO_HTTP_SERVER

#include <srs_app_st.hpp>
#include <srs_app_conn.hpp>
#include <srs_app_http.hpp>

class SrsSocket;
class SrsHttpParser;
class SrsHttpMessage;
class SrsHttpHandler;

// for http root.
class SrsHttpRoot : public SrsHttpHandler
{
public:
    SrsHttpRoot();
    virtual ~SrsHttpRoot();
public:
    virtual int initialize();
    virtual int best_match(const char* path, int length, SrsHttpHandlerMatch** ppmatch);
protected:
    virtual bool is_handler_valid(SrsHttpMessage* req, int& status_code, std::string& reason_phrase);
    virtual int do_process_request(SrsSocket* skt, SrsHttpMessage* req);
};

class SrsHttpVhost : public SrsHttpHandler
{
private:
    std::string _vhost;
    std::string _mount;
    std::string _dir;
public:
    SrsHttpVhost(std::string vhost, std::string mount, std::string dir);
    virtual ~SrsHttpVhost();
public:
    virtual bool can_handle(const char* path, int length, const char** pchild);
protected:
    virtual bool is_handler_valid(SrsHttpMessage* req, int& status_code, std::string& reason_phrase);
    virtual int do_process_request(SrsSocket* skt, SrsHttpMessage* req);
private:
    virtual int response_regular_file(SrsSocket* skt, SrsHttpMessage* req, std::string fullpath);
    virtual int response_flv_file(SrsSocket* skt, SrsHttpMessage* req, std::string fullpath);
    virtual int response_flv_file2(SrsSocket* skt, SrsHttpMessage* req, std::string fullpath, int offset);
    virtual int response_ts_file(SrsSocket* skt, SrsHttpMessage* req, std::string fullpath);
    virtual std::string get_request_file(SrsHttpMessage* req);
public:
    virtual std::string vhost();
    virtual std::string mount();
    virtual std::string dir();
};

class SrsHttpConn : public SrsConnection
{
private:
    SrsHttpParser* parser;
    SrsHttpHandler* handler;
    bool requires_crossdomain;
public:
    SrsHttpConn(SrsServer* srs_server, st_netfd_t client_stfd, SrsHttpHandler* _handler);
    virtual ~SrsHttpConn();
protected:
    virtual int do_cycle();
private:
    virtual int process_request(SrsSocket* skt, SrsHttpMessage* req);
};

#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
#include <aws/appflow/model/DescribeConnectorProfilesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Appflow::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DescribeConnectorProfilesRequest::DescribeConnectorProfilesRequest() :
    m_connectorProfileNamesHasBeenSet(false),
    m_connectorType(ConnectorType::NOT_SET),
    m_connectorTypeHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_nextTokenHasBeenSet(false)
{
}

Aws::String DescribeConnectorProfilesRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_connectorProfileNamesHasBeenSet)
  {
   Array<JsonValue> connectorProfileNamesJsonList(m_connectorProfileNames.size());
   for(unsigned connectorProfileNamesIndex = 0; connectorProfileNamesIndex < connectorProfileNamesJsonList.GetLength(); ++connectorProfileNamesIndex)
   {
     connectorProfileNamesJsonList[connectorProfileNamesIndex].AsString(m_connectorProfileNames[connectorProfileNamesIndex]);
   }
   payload.WithArray("connectorProfileNames", std::move(connectorProfileNamesJsonList));

  }

  if(m_connectorTypeHasBeenSet)
  {
   payload.WithString("connectorType", ConnectorTypeMapper::GetNameForConnectorType(m_connectorType));
  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("maxResults", m_maxResults);

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("nextToken", m_nextToken);

  }

  return payload.View().WriteReadable();
}


text:
<?php

/* MisdPhoneNumberBundle:Form:tel.html.twig */
class __TwigTemplate_615b8bb4bd44b5ef43baecdde54966e8e2a38e8fcb7068b7009b60fcc72e83d0 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
            'tel_widget' => array($this, 'block_tel_widget'),
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $this->displayBlock('tel_widget', $context, $blocks);
    }

    public function block_tel_widget($context, array $blocks = array())
    {
        // line 2
        if (((isset($context["widget"]) ? $context["widget"] : null) === constant("Misd\\PhoneNumberBundle\\Form\\Type\\PhoneNumberType::WIDGET_COUNTRY_CHOICE"))) {
            // line 3
            echo "        <div ";
            $this->displayBlock("widget_container_attributes", $context, $blocks);
            echo ">";
            // line 4
            echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "country", array()), 'widget');
            // line 5
            echo $this->env->getRuntime('Symfony\Bridge\Twig\Form\TwigRenderer')->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : null), "number", array()), 'widget');
            // line 6
            echo "</div>
    ";
        } else {
            // line 8
            $this->displayBlock("form_widget_simple", $context, $blocks);
        }
    }

    public function getTemplateName()
    {
        return "MisdPhoneNumberBundle:Form:tel.html.twig";
    }

    public function getDebugInfo()
    {
        return array (  40 => 8,  36 => 6,  34 => 5,  32 => 4,  28 => 3,  26 => 2,  20 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("", "MisdPhoneNumberBundle:Form:tel.html.twig", "C:\\wamp64\\www\\Symfony\\vendor\\misd\\phone-number-bundle/Resources/views/Form/tel.html.twig");
    }
}


text:
package com.stratio.sparta.serving.core.models

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{Matchers, WordSpec}

@RunWith(classOf[JUnitRunner])
class ErrorsModelTest extends WordSpec with Matchers {

  val error = new ErrorModel("100", "Error 100", None, None)

  "ErrorModel" should {

    "toString method should return the number of the error and the error" in {
      val res = ErrorModel.toString(error)
      res should be ("""{"i18nCode":"100","message":"Error 100"}""")
    }

    "toError method should return the number of the error and the error" in {
      val res = ErrorModel.toErrorModel(
        """
          |{
          | "i18nCode": "100",
          | "message": "Error 100"
          |}
        """.stripMargin)
      res should be (error)
    }
  }
}


text:
require 'rubyXL/objects/ooxml_object'
require 'rubyXL/objects/simple_types'
require 'rubyXL/objects/text'
require 'rubyXL/objects/formula'
require 'rubyXL/cell'
require 'rubyXL/convenience_methods'

module RubyXL

  # http://www.datypic.com/sc/ooxml/e-ssml_v-1.html
  class CellValue < OOXMLObject
    define_attribute(:_, :string, :accessor => :value)
    define_attribute(:'xml:space', %w{ preserve })
    define_element_name 'v'

    def before_write_xml
      preserve_whitespace
      true
    end
  end

  # http://www.datypic.com/sc/ooxml/e-ssml_c-2.html
  class Cell < OOXMLObject
    NUMBER_REGEXP = /\A-?\d+((?:\.\d+)?(?:e[+-]?\d+)?)?\Z/i

    define_attribute(:r,   :ref)
    define_attribute(:s,   :int,  :default => 0, :accessor => :style_index)
    define_attribute(:t,   RubyXL::ST_CellType,  :accessor => :datatype, :default => 'n' )
    define_attribute(:cm,  :int,  :default => 0)
    define_attribute(:vm,  :int,  :default => 0)
    define_attribute(:ph,  :bool, :default => false)
    define_child_node(RubyXL::Formula,   :accessor => :formula)
    define_child_node(RubyXL::CellValue, :accessor => :value_container)
    define_child_node(RubyXL::RichText)    # is
    define_element_name 'c'

    def index_in_collection
      r.col_range.begin
    end

    def row
      r && r.first_row
    end

    def row=(v)
      self.r = RubyXL::Reference.new(v, column || 0)
    end

    def column
      r && r.first_col
    end

    def column=(v)
      self.r = RubyXL::Reference.new(row || 0, v)
    end

    def raw_value
      value_container && value_container.value
    end

    def raw_value=(v)
      self.value_container ||= RubyXL::CellValue.new
      value_container.value = v
    end

    def number_format
      workbook.stylesheet.get_number_format_by_id(get_cell_xf.num_fmt_id)
    end

    def is_date?
      return false unless raw_value =~ NUMBER_REGEXP # Only fully numeric values can be dates
      num_fmt = self.number_format
      num_fmt && num_fmt.is_date_format?
    end

    # Gets massaged value of the cell, converting datatypes to those known to Ruby (that includes
    # stripping any special formatting from RichText).
    def value(args = {})
      r = self.raw_value

      case datatype
      when RubyXL::DataType::SHARED_STRING then workbook.shared_strings_container[r.to_i].to_s
      when RubyXL::DataType::INLINE_STRING then is.to_s
      when RubyXL::DataType::RAW_STRING    then raw_value
      else
        if is_date? then workbook.num_to_date(r.to_f)
        elsif r.is_a?(String) && (r =~ NUMBER_REGEXP) then # Numeric
          if $1 != '' then r.to_f
          else r.to_i
          end
        else r
        end
      end
    end

    def inspect
      str = "#<#{self.class}(#{row},#{column}): #{raw_value.inspect}"
      str += " =#{self.formula.expression}" if self.formula
      str += ", datatype=#{self.datatype.inspect}, style_index=#{self.style_index.inspect}>"
      return str
    end

    include LegacyCell
    include CellConvenienceMethods
  end

#TODO#<row r="1" spans="1:1" x14ac:dyDescent="0.25">

  # http://www.datypic.com/sc/ooxml/e-ssml_row-1.html
  class Row < OOXMLObject
    define_attribute(:r,            :int)
    define_attribute(:spans,        :string)
    define_attribute(:s,            :int,   :default => 0, :accessor => :style_index)
    define_attribute(:customFormat, :bool,  :default => false)
    define_attribute(:ht,           :double)
    define_attribute(:hidden,       :bool,  :default => false)
    define_attribute(:customHeight, :bool,  :default => false)
    define_attribute(:outlineLevel, :int,   :default => 0)
    define_attribute(:collapsed,    :bool,  :default => false)
    define_attribute(:thickTop,     :bool,  :default => false)
    define_attribute(:thickBot,     :bool,  :default => false)
    define_attribute(:ph,           :bool,  :default => false)
    define_child_node(RubyXL::Cell, :collection => true, :accessor => :cells)
    define_element_name 'row'

    attr_accessor :worksheet

    def before_write_xml
      !(cells.nil? || cells.empty?)
    end

    def index_in_collection
      r - 1
    end

    def [](ind)
      cells[ind]
    end

    def size
      cells.size
    end

    def insert_cell_shift_right(c, col_index)
      cells.insert(col_index, c)
      update_cell_coords(col_index)
    end

    def delete_cell_shift_left(col_index)
      cells.delete_at(col_index)
      update_cell_coords(col_index)
    end

    def update_cell_coords(start_from_index)
      cells.drop(start_from_index).each_with_index { |cell, i|
        next if cell.nil?
        cell.column = start_from_index + i
      }
    end
    private :update_cell_coords

    def xf
      @worksheet.workbook.cell_xfs[self.style_index || 0]
    end

    def get_fill_color
      @worksheet.workbook.get_fill_color(xf)
    end

    def get_font
      @worksheet.workbook.fonts[xf.font_id]
    end

    DEFAULT_HEIGHT = 13
  end

  # http://www.datypic.com/sc/ooxml/e-ssml_sheetData-1.html
  class SheetData < OOXMLObject
    define_child_node(RubyXL::Row, :collection => true, :accessor => :rows)
    define_element_name 'sheetData'

    def [](ind)
      rows[ind]
    end

    def size
      rows.size
    end

  end

end


text:
package org.conqat.lib.commons.xml;

/**
 * Interface for resolution of element and attribute names.
 *
 * @author deissenb
 * @author $Author: kinnen $
 * @version $Rev: 41751 $
 * @ConQAT.Rating GREEN Hash: 8498CAA4E6F015E5BC7BCBCD53D92347
 */
public interface IXMLResolver<E extends Enum<E>, A extends Enum<A>> {
	/** Returns for an attribute the name which should be used in the XML file. */
	public String resolveAttributeName(A attribute);

	/** Returns for an element the name which should be used in the XML file. */
	public abstract String resolveElementName(E element);

	/** Returns the class of the attribute enumeration. */
	public abstract Class<A> getAttributeClass();
}


text:
require 'spec_helper'

module SpreeSignifyd
  describe UserSerializer do
    let(:user) { create(:user) }
    let!(:incomplete_order) { create(:order, user: user) }
    let!(:old_complete_order) { create(:shipped_order, user: user, created_at: 30.days.ago) }
    let!(:new_complete_order) { create(:shipped_order, user: user) }

    let(:serialized_user) { JSON.parse(UserSerializer.new(user).to_json) }

    context "node values" do
      it "emailAddress" do
        expect(serialized_user['emailAddress']).to eq user.email
      end

      it "username" do
       expect(serialized_user['username']).to eq user.email
      end

      it "createdDate" do
       expect(serialized_user['createdDate']).to eq user.created_at.utc.iso8601
      end

      it "lastUpdateDate" do
       expect(serialized_user['lastUpdateDate']).to eq user.updated_at.utc.iso8601
      end

      context "with at least 2 orders" do
        it "lastOrderId" do
          expect(serialized_user['lastOrderId']).to eq old_complete_order.number
        end
      end

      context "without prior orders" do
        let(:user_without_orders) { create(:user) }
        let(:serialized_user) { JSON.parse(UserSerializer.new(user_without_orders).to_json) }

        it "lastOrderId" do
          expect(serialized_user['lastOrderId']).to eq nil
        end
      end

      it "aggregateOrderCount" do
        expect(serialized_user['aggregateOrderCount']).to eq 2
      end

      it "aggregateOrderDollars" do
        expect(serialized_user['aggregateOrderDollars']).to eq (old_complete_order.total + new_complete_order.total).to_s
      end
    end
  end
end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using CupCake.Command;
using CupCake.Command.Source;

namespace CupCake
{
    /// <summary>
    ///     Class CommandManager.
    /// </summary>
    public sealed class CommandManager : CupCakeMuffinPart<string>, IEnumerable<ICommand>, IDisposable
    {
        private readonly List<ICommand> _commands = new List<ICommand>();
        private readonly object _lockObj = new object();
        private string _chatName;

        /// <summary>
        ///     Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        ///     A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<ICommand> GetEnumerator()
        {
            lock (this._lockObj)
            {
                return this._commands.ToArray().AsEnumerable().GetEnumerator();
            }
        }

        /// <summary>
        ///     Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        ///     An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        /// <summary>
        ///     Registers the specified command.
        /// </summary>
        /// <param name="callback">The command.</param>
        /// <exception cref="System.ArgumentException">Callback has already been added.</exception>
        public void Add(Action<IInvokeSource, ParsedCommand> callback)
        {
            lock (this._lockObj)
            {
                if (this.ContainsInternal(callback))
                {
                    throw new ArgumentException("Callback has already been added.");
                }

                var command = this.EnablePart<CommandHandle>(null);
                command.Activate(callback, this._chatName);
                this._commands.Add(command);
            }
        }

        /// <summary>
        ///     Determines whether the specified callback is registered in this <see cref="CommandManager" /> or not.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <returns></returns>
        public bool Contains(Action<IInvokeSource, ParsedCommand> callback)
        {
            lock (this._lockObj)
            {
                return this.ContainsInternal(callback);
            }
        }

        private bool ContainsInternal(Action<IInvokeSource, ParsedCommand> callback)
        {
            return this._commands.Any(c => c.Callback == callback);
        }

        /// <summary>
        ///     Removes the specified callback.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <returns></returns>
        public bool Remove(Action<IInvokeSource, ParsedCommand> callback)
        {
            ICommand command;
            if (this.TryGetCommand(callback, out command))
            {
                return this.Remove(command);
            }

            return false;
        }

        /// <summary>
        ///     Removes the specified callback.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <returns></returns>
        public bool Remove(ICommand callback)
        {
            if (this._commands.Remove(callback))
            {
                callback.Dispose();
                return true;
            }

            return false;
        }

        /// <summary>
        ///     Tries to get the command object linked with the specified handler.
        /// </summary>
        /// <param name="callback">The callback.</param>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public bool TryGetCommand(Action<IInvokeSource, ParsedCommand> callback, out ICommand command)
        {
            lock (this._lockObj)
            {
                foreach (ICommand c in
                    this._commands.Where(c =>
                        c.Callback == callback))
                {
                    command = c;
                    return true;
                }

                command = null;
                return false;
            }
        }

        /// <summary>
        ///     Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing">
        ///     <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
        ///     unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                lock (this._lockObj)
                {
                    foreach (ICommand command in this._commands.ToArray())
                    {
                        this.Remove(command);
                    }
                }
            }
        }

        /// <summary>
        ///     Enables this instance.
        /// </summary>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override void Enable()
        {
            this._chatName = this.Host;
        }
    }
}


text:
<?php

use Symfony\Component\Translation\MessageCatalogue;

$catalogue = new MessageCatalogue('af', array (
  'validators' =>
  array (
    'This value should be false.' => 'Hierdie waarde moet vals wees.',
    'This value should be true.' => 'Hierdie waarde moet waar wees.',
    'This value should be of type {{ type }}.' => 'Hierdie waarde moet van die soort {{type}} wees.',
    'This value should be blank.' => 'Hierdie waarde moet leeg wees.',
    'The value you selected is not a valid choice.' => 'Die waarde wat jy gekies het is nie \'n geldige keuse nie.',
    'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.' => 'Jy moet ten minste {{ limit }} kies.|Jy moet ten minste {{ limit }} keuses kies.',
    'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.' => 'Jy moet by die meeste {{ limit }} keuse kies.|Jy moet by die meeste {{ limit }} keuses kies.',
    'One or more of the given values is invalid.' => 'Een of meer van die gegewe waardes is ongeldig.',
    'This field was not expected.' => 'Die veld is nie verwag nie.',
    'This field is missing.' => 'Hierdie veld ontbreek.',
    'This value is not a valid date.' => 'Hierdie waarde is nie \'n geldige datum nie.',
    'This value is not a valid datetime.' => 'Hierdie waarde is nie \'n geldige datum en tyd nie.',
    'This value is not a valid email address.' => 'Hierdie waarde is nie \'n geldige e-pos adres nie.',
    'The file could not be found.' => 'Die lêer kon nie gevind word nie.',
    'The file is not readable.' => 'Die lêer kan nie gelees word nie.',
    'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.' => 'Die lêer is te groot ({{ size }} {{ suffix }}). Toegelaat maksimum grootte is {{ limit }} {{ suffix }}.',
    'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.' => 'Die MIME-tipe van die lêer is ongeldig ({{ type }}). Toegelaat MIME-tipes is {{ types }}.',
    'This value should be {{ limit }} or less.' => 'Hierdie waarde moet {{ limit }} of minder wees.',
    'This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.' => 'Hierdie waarde is te lank. Dit moet {{ limit }} karakter of minder wees.|Hierdie waarde is te lank. Dit moet {{ limit }} karakters of minder wees.',
    'This value should be {{ limit }} or more.' => 'Hierdie waarde moet {{ limit }} of meer wees.',
    'This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.' => 'Hierdie waarde is te kort. Dit moet {{ limit }} karakter of meer wees.|Hierdie waarde is te kort. Dit moet {{ limit }} karakters of meer wees.',
    'This value should not be blank.' => 'Hierdie waarde moet nie leeg wees nie.',
    'This value should not be null.' => 'Hierdie waarde moet nie nul wees nie.',
    'This value should be null.' => 'Hierdie waarde moet nul wees.',
    'This value is not valid.' => 'Hierdie waarde is nie geldig nie.',
    'This value is not a valid time.' => 'Hierdie waarde is nie \'n geldige tyd nie.',
    'This value is not a valid URL.' => 'Hierdie waarde is nie \'n geldige URL nie.',
    'The two values should be equal.' => 'Die twee waardes moet gelyk wees.',
    'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.' => 'Die lêer is te groot. Toegelaat maksimum grootte is {{ limit }} {{ suffix }}.',
    'The file is too large.' => 'Die lêer is te groot.',
    'The file could not be uploaded.' => 'Die lêer kan nie opgelaai word nie.',
    'This value should be a valid number.' => 'Hierdie waarde moet \'n geldige nommer wees.',
    'This file is not a valid image.' => 'Hierdie lêer is nie \'n geldige beeld nie.',
    'This is not a valid IP address.' => 'Hierdie is nie \'n geldige IP-adres nie.',
    'This value is not a valid language.' => 'Hierdie waarde is nie \'n geldige taal nie.',
    'This value is not a valid locale.' => 'Hierdie waarde is nie \'n geldige land instelling nie.',
    'This value is not a valid country.' => 'Hierdie waarde is nie \'n geldige land nie.',
    'This value is already used.' => 'Hierdie waarde word reeds gebruik.',
    'The size of the image could not be detected.' => 'Die grootte van die beeld kon nie opgespoor word nie.',
    'The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.' => 'Die beeld breedte is te groot ({{ width }}px). Toegelaat maksimum breedte is {{ max_width }}px.',
    'The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.' => 'Die beeld breedte is te klein ({{ width }}px). Minimum breedte verwag is {{ min_width }}px.',
    'The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.' => 'Die beeld hoogte is te groot ({{ height }}px). Toegelaat maksimum hoogte is {{ max_height }}px.',
    'The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.' => 'Die beeld hoogte is te klein ({{ height }}px). Minimum hoogte verwag is {{ min_height }}px.',
    'This value should be the user\'s current password.' => 'Hierdie waarde moet die huidige wagwoord van die gebruiker wees.',
    'This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.' => 'Hierdie waarde moet presies {{ limit }} karakter wees.|Hierdie waarde moet presies {{ limit }} karakters wees.',
    'The file was only partially uploaded.' => 'Die lêer is slegs gedeeltelik opgelaai.',
    'No file was uploaded.' => 'Geen lêer is opgelaai nie.',
    'No temporary folder was configured in php.ini.' => 'Geen tydelike lêer is ingestel in php.ini nie.',
    'Cannot write temporary file to disk.' => 'Kan nie tydelike lêer skryf op skyf nie.',
    'A PHP extension caused the upload to fail.' => '\'n PHP-uitbreiding veroorsaak die oplaai van die lêer om te misluk.',
    'This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.' => 'Hierdie versameling moet {{ limit }} element of meer bevat.|Hierdie versameling moet {{ limit }} elemente of meer bevat.',
    'This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.' => 'Hierdie versameling moet {{ limit }} element of minder bevat.|Hierdie versameling moet {{ limit }} elemente of meer bevat.',
    'This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.' => 'Hierdie versameling moet presies {{ limit }} element bevat.|Hierdie versameling moet presies {{ limit }} elemente bevat.',
    'Invalid card number.' => 'Ongeldige kredietkaart nommer.',
    'Unsupported card type or invalid card number.' => 'Nie-ondersteunde tipe kaart of ongeldige kredietkaart nommer.',
  ),
));

$catalogueEn = new MessageCatalogue('en', array (
  'validators' =>
  array (
    'This value should be false.' => 'This value should be false.',
    'This value should be true.' => 'This value should be true.',
    'This value should be of type {{ type }}.' => 'This value should be of type {{ type }}.',
    'This value should be blank.' => 'This value should be blank.',
    'The value you selected is not a valid choice.' => 'The value you selected is not a valid choice.',
    'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.' => 'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.',
    'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.' => 'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.',
    'One or more of the given values is invalid.' => 'One or more of the given values is invalid.',
    'This field was not expected.' => 'This field was not expected.',
    'This field is missing.' => 'This field is missing.',
    'This value is not a valid date.' => 'This value is not a valid date.',
    'This value is not a valid datetime.' => 'This value is not a valid datetime.',
    'This value is not a valid email address.' => 'This value is not a valid email address.',
    'The file could not be found.' => 'The file could not be found.',
    'The file is not readable.' => 'The file is not readable.',
    'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.' => 'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.',
    'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.' => 'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.',
    'This value should be {{ limit }} or less.' => 'This value should be {{ limit }} or less.',
    'This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.' => 'This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.',
    'This value should be {{ limit }} or more.' => 'This value should be {{ limit }} or more.',
    'This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.' => 'This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.',
    'This value should not be blank.' => 'This value should not be blank.',
    'This value should not be null.' => 'This value should not be null.',
    'This value should be null.' => 'This value should be null.',
    'This value is not valid.' => 'This value is not valid.',
    'This value is not a valid time.' => 'This value is not a valid time.',
    'This value is not a valid URL.' => 'This value is not a valid URL.',
    'The two values should be equal.' => 'The two values should be equal.',
    'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.' => 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.',
    'The file is too large.' => 'The file is too large.',
    'The file could not be uploaded.' => 'The file could not be uploaded.',
    'This value should be a valid number.' => 'This value should be a valid number.',
    'This file is not a valid image.' => 'This file is not a valid image.',
    'This is not a valid IP address.' => 'This is not a valid IP address.',
    'This value is not a valid language.' => 'This value is not a valid language.',
    'This value is not a valid locale.' => 'This value is not a valid locale.',
    'This value is not a valid country.' => 'This value is not a valid country.',
    'This value is already used.' => 'This value is already used.',
    'The size of the image could not be detected.' => 'The size of the image could not be detected.',
    'The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.' => 'The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.',
    'The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.' => 'The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.',
    'The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.' => 'The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.',
    'The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.' => 'The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.',
    'This value should be the user\'s current password.' => 'This value should be the user\'s current password.',
    'This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.' => 'This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.',
    'The file was only partially uploaded.' => 'The file was only partially uploaded.',
    'No file was uploaded.' => 'No file was uploaded.',
    'No temporary folder was configured in php.ini.' => 'No temporary folder was configured in php.ini.',
    'Cannot write temporary file to disk.' => 'Cannot write temporary file to disk.',
    'A PHP extension caused the upload to fail.' => 'A PHP extension caused the upload to fail.',
    'This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.' => 'This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.',
    'This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.' => 'This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.',
    'This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.' => 'This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.',
    'Invalid card number.' => 'Invalid card number.',
    'Unsupported card type or invalid card number.' => 'Unsupported card type or invalid card number.',
    'This is not a valid International Bank Account Number (IBAN).' => 'This is not a valid International Bank Account Number (IBAN).',
    'This value is not a valid ISBN-10.' => 'This value is not a valid ISBN-10.',
    'This value is not a valid ISBN-13.' => 'This value is not a valid ISBN-13.',
    'This value is neither a valid ISBN-10 nor a valid ISBN-13.' => 'This value is neither a valid ISBN-10 nor a valid ISBN-13.',
    'This value is not a valid ISSN.' => 'This value is not a valid ISSN.',
    'This value is not a valid currency.' => 'This value is not a valid currency.',
    'This value should be equal to {{ compared_value }}.' => 'This value should be equal to {{ compared_value }}.',
    'This value should be greater than {{ compared_value }}.' => 'This value should be greater than {{ compared_value }}.',
    'This value should be greater than or equal to {{ compared_value }}.' => 'This value should be greater than or equal to {{ compared_value }}.',
    'This value should be identical to {{ compared_value_type }} {{ compared_value }}.' => 'This value should be identical to {{ compared_value_type }} {{ compared_value }}.',
    'This value should be less than {{ compared_value }}.' => 'This value should be less than {{ compared_value }}.',
    'This value should be less than or equal to {{ compared_value }}.' => 'This value should be less than or equal to {{ compared_value }}.',
    'This value should not be equal to {{ compared_value }}.' => 'This value should not be equal to {{ compared_value }}.',
    'This value should not be identical to {{ compared_value_type }} {{ compared_value }}.' => 'This value should not be identical to {{ compared_value_type }} {{ compared_value }}.',
    'The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.' => 'The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.',
    'The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.' => 'The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.',
    'The image is square ({{ width }}x{{ height }}px). Square images are not allowed.' => 'The image is square ({{ width }}x{{ height }}px). Square images are not allowed.',
    'The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.' => 'The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.',
    'The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.' => 'The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.',
    'An empty file is not allowed.' => 'An empty file is not allowed.',
    'The host could not be resolved.' => 'The host could not be resolved.',
    'This value does not match the expected {{ charset }} charset.' => 'This value does not match the expected {{ charset }} charset.',
    'This form should not contain extra fields.' => 'This form should not contain extra fields.',
    'The uploaded file was too large. Please try to upload a smaller file.' => 'The uploaded file was too large. Please try to upload a smaller file.',
    'The CSRF token is invalid. Please try to resubmit the form.' => 'The CSRF token is invalid. Please try to resubmit the form.',
    'fos_user.username.already_used' => 'The username is already used',
    'fos_user.username.blank' => 'Please enter a username',
    'fos_user.username.short' => '[-Inf,Inf]The username is too short',
    'fos_user.username.long' => '[-Inf,Inf]The username is too long',
    'fos_user.email.already_used' => 'The email is already used',
    'fos_user.email.blank' => 'Please enter an email',
    'fos_user.email.short' => '[-Inf,Inf]The email is too short',
    'fos_user.email.long' => '[-Inf,Inf]The email is too long',
    'fos_user.email.invalid' => 'The email is not valid',
    'fos_user.password.blank' => 'Please enter a password',
    'fos_user.password.short' => '[-Inf,Inf]The password is too short',
    'fos_user.password.mismatch' => 'The entered passwords don\'t match',
    'fos_user.new_password.blank' => 'Please enter a new password',
    'fos_user.new_password.short' => '[-Inf,Inf]The new password is too short',
    'fos_user.current_password.invalid' => 'The entered password is invalid',
    'fos_user.group.blank' => 'Please enter a name',
    'fos_user.group.short' => '[-Inf,Inf]The name is too short',
    'fos_user.group.long' => '[-Inf,Inf]The name is too long',
  ),
  'security' =>
  array (
    'An authentication exception occurred.' => 'An authentication exception occurred.',
    'Authentication credentials could not be found.' => 'Authentication credentials could not be found.',
    'Authentication request could not be processed due to a system problem.' => 'Authentication request could not be processed due to a system problem.',
    'Invalid credentials.' => 'Invalid credentials.',
    'Cookie has already been used by someone else.' => 'Cookie has already been used by someone else.',
    'Not privileged to request the resource.' => 'Not privileged to request the resource.',
    'Invalid CSRF token.' => 'Invalid CSRF token.',
    'Digest nonce has expired.' => 'Digest nonce has expired.',
    'No authentication provider found to support the authentication token.' => 'No authentication provider found to support the authentication token.',
    'No session available, it either timed out or cookies are not enabled.' => 'No session available, it either timed out or cookies are not enabled.',
    'No token could be found.' => 'No token could be found.',
    'Username could not be found.' => 'Username could not be found.',
    'Account has expired.' => 'Account has expired.',
    'Credentials have expired.' => 'Credentials have expired.',
    'Account is disabled.' => 'Account is disabled.',
    'Account is locked.' => 'Account is locked.',
  ),
  'CmfRoutingBundle' =>
  array (
    'dashboard.cmf' => 'Symfony CMF',
    'dashboard.label_routing' => 'Route',
    'dashboard.label_redirect_routing' => 'Redirect Route',
    'breadcrumb.link_route_list' => 'Routes',
    'breadcrumb.link_route_create' => 'Create',
    'breadcrumb.link_route_edit' => 'Edit',
    'breadcrumb.link_route_delete' => 'Delete',
    'breadcrumb.link_redirect_route_list' => 'Redirect Routes',
    'breadcrumb.link_redirect_route_create' => 'Create',
    'breadcrumb.link_redirect_route_edit' => 'Edit',
    'breadcrumb.link_redirect_route_delete' => 'Delete',
    'filter.label_name' => 'Name',
    'list.label_path' => 'URL',
    'form.group_general' => 'General',
    'form.group_advanced' => 'Advanced',
    'form.label_parent' => 'Parent',
    'form.label_name' => 'Last URL part',
    'form.label_variable_pattern' => 'Variable pattern',
    'form.help_variable_pattern' => 'A pattern in the format {variable}/{more}... The fields are passed to the controller if it declares them as arguments.',
    'form.label_content' => 'Content',
    'form.label_defaults' => 'Defaults',
    'form.label_options' => 'Options',
    'form.label_route_name' => 'Name',
    'form.label_uri' => 'URI',
    'form.label_route_target' => 'Route target',
    'form.group_routes' => 'Routes',
    'form.label_routes' => 'Routes',
    'form.label_add_locale_pattern' => 'Add locale pattern',
    'form.label_add_format_pattern' => 'Add format pattern',
    'form.label_add_trailing_slash' => 'Add trailing slash',
    'form.help_options' => '

            Locale: Prepend locale to route like /{locale}/your/route<br/>
            Format: Append format to route like /your/route.{format}. Default format is \'html\'<br/>
            Slash: Append a trailing slash to route like /your/route/

        ',
    'admin.menu_frontend_link_caption' => 'Frontend',
    'admin.menu_frontend_link_title' => 'Open frontend view in new tab',
  ),
  'SonataCoreBundle' =>
  array (
    'link_add' => 'Add new',
    'label_type_yes' => 'yes',
    'label_type_no' => 'no',
    'sonata_core_template_box_file_found_in' => 'This file can be found in',
    'label_type_equals' => 'is equal to',
    'label_type_not_equals' => 'is not equal to',
    'date_range_start' => 'From',
    'date_range_end' => 'To',
  ),
  'SonataAdminBundle' =>
  array (
    'sonata_administration' => 'Administration',
    'action_delete' => 'Delete',
    'btn_batch' => 'OK',
    'btn_create' => 'Create',
    'btn_create_and_edit_again' => 'Create',
    'btn_create_and_create_a_new_one' => 'Create and add another',
    'btn_create_and_return_to_list' => 'Create and return to list',
    'btn_filter' => 'Filter',
    'btn_update' => 'Update',
    'btn_update_and_edit_again' => 'Update',
    'btn_update_and_return_to_list' => 'Update and close',
    'link_delete' => 'Delete',
    'link_action_create' => 'Add new',
    'link_action_list' => 'Return to list',
    'link_action_show' => 'Show',
    'link_action_edit' => 'Edit',
    'link_add' => 'Add new',
    'link_list' => 'List',
    'link_reset_filter' => 'Reset',
    'title_create' => 'Create',
    'title_dashboard' => 'Dashboard',
    'title_edit' => 'Edit "%name%"',
    'title_list' => 'List',
    'link_next_pager' => 'Next',
    'link_previous_pager' => 'Previous',
    'link_first_pager' => 'First',
    'link_last_pager' => 'Last',
    'Admin' => 'Admin',
    'link_expand' => 'expand/collapse',
    'no_result' => 'No result',
    'confirm_msg' => 'Are you sure ?',
    'action_edit' => 'Edit',
    'action_show' => 'Show',
    'all_elements' => 'All elements',
    'flash_batch_empty' => 'Action aborted. No items were selected.',
    'flash_create_success' => 'Item "%name%" has been successfully created.',
    'flash_create_error' => 'An error has occurred during the creation of item "%name%".',
    'flash_edit_success' => 'Item "%name%" has been successfully updated.',
    'flash_edit_error' => 'An error has occurred during update of item "%name%".',
    'flash_batch_delete_success' => 'Selected items have been successfully deleted.',
    'flash_batch_delete_error' => 'An Error has occurred during selected items deletion.',
    'flash_delete_error' => 'An Error has occurred during deletion of item "%name%".',
    'flash_delete_success' => 'Item "%name%" has been deleted successfully.',
    'breadcrumb.link_dashboard' => '<i class="fa fa-home"></i>',
    'title_delete' => 'Confirm deletion',
    'message_delete_confirmation' => 'Are you sure you want to delete the selected "%object%" element?',
    'btn_delete' => 'Yes, delete',
    'title_batch_confirmation' => 'Confirm batch action \'%action%\'',
    'message_batch_confirmation' => 'Are you sure you want to confirm this action and execute it for the selected element?|Are you sure you want to confirm this action and execute it for the %count% selected elements?',
    'message_batch_all_confirmation' => 'Are you sure you want to confirm this action and execute it for all the elements?',
    'btn_execute_batch_action' => 'Yes, execute',
    'label_type_yes' => 'yes',
    'label_type_no' => 'no',
    'label_type_contains' => 'contains',
    'label_type_not_contains' => 'does not contain',
    'label_type_equals' => 'is equal to',
    'label_type_not_equals' => 'is not equal to',
    'label_type_equal' => '=',
    'label_type_greater_equal' => '>=',
    'label_type_greater_than' => '>',
    'label_type_less_equal' => '<=',
    'label_type_less_than' => '<',
    'label_date_type_equal' => '=',
    'label_date_type_greater_equal' => '>=',
    'label_date_type_greater_than' => '>',
    'label_date_type_less_equal' => '<=',
    'label_date_type_less_than' => '<',
    'label_date_type_null' => 'is empty',
    'label_date_type_not_null' => 'is not empty',
    'label_date_type_between' => 'between',
    'label_date_type_not_between' => 'not between',
    'label_filters' => 'Filters',
    'delete_or' => 'or',
    'link_action_history' => 'Revisions',
    'td_action' => 'Action',
    'td_compare' => 'Compare',
    'td_revision' => 'Revisions',
    'td_timestamp' => 'Date',
    'td_username' => 'Author',
    'label_view_revision' => 'View Revision',
    'label_compare_revision' => 'Compare revision',
    'list_results_count' => '1 result|%count% results',
    'label_export_download' => 'Download',
    'loading_information' => 'Loading information…',
    'btn_preview' => 'Preview',
    'btn_preview_approve' => 'Approve',
    'btn_preview_decline' => 'Decline',
    'label_per_page' => 'Per page',
    'list_select' => 'Select',
    'confirm_exit' => 'You have unsaved changes.',
    'link_edit_acl' => 'Edit ACL',
    'btn_update_acl' => 'Update ACL',
    'flash_acl_edit_success' => 'ACL has been successfuly updated.',
    'link_action_acl' => 'ACL',
    'short_object_description_placeholder' => 'No selection',
    'title_search_results' => 'Search results: %query%',
    'search_placeholder' => 'Search',
    'no_results_found' => 'no result found',
    'add_new_entry' => 'add new entry',
    'link_actions' => 'Actions',
    'noscript_warning' => 'Javascript is disabled in your web browser. Some features will not work properly.',
    'message_form_group_empty' => 'No fields available.',
  ),
  'SonataDoctrinePHPCRAdmin' =>
  array (
    'content_tree' => 'Content',
    'reset_tree' => 'Reset',
    'create_item' => 'Create',
    'delete_item' => 'Delete',
    'confirm_move_node' => 'Really move that node?',
    'list_results_count_prefix' => 'at least',
    'not_editable' => '(not editable)',
    'label_type_contains_words' => 'contains words',
  ),
  'FOSUserBundle' =>
  array (
    'Bad credentials' => 'Invalid username or password',
    'group.edit.submit' => 'Update group',
    'group.show.name' => 'Group name',
    'group.new.submit' => 'Create group',
    'group.flash.updated' => 'The group has been updated',
    'group.flash.created' => 'The group has been created',
    'group.flash.deleted' => 'The group has been deleted',
    'security.login.username' => 'Username:',
    'security.login.password' => 'Password:',
    'security.login.remember_me' => 'Remember me',
    'security.login.submit' => 'Login',
    'profile.show.username' => 'Username',
    'profile.show.email' => 'Email',
    'profile.edit.submit' => 'Update',
    'profile.flash.updated' => 'The profile has been updated',
    'change_password.submit' => 'Change password',
    'change_password.flash.success' => 'The password has been changed',
    'registration.check_email' => 'An email has been sent to %email%. It contains an activation link you must click to activate your account.',
    'registration.confirmed' => 'Congrats %username%, your account is now activated.',
    'registration.back' => 'Back to the originating page.',
    'registration.submit' => 'Register',
    'registration.flash.user_created' => 'The user has been created successfully',
    'registration.email.subject' => 'Welcome %username%!',
    'registration.email.message' => 'Hello %username%!

To finish activating your account - please visit %confirmationUrl%

Regards,
the Team.
',
    'resetting.password_already_requested' => 'The password for this user has already been requested within the last 24 hours.',
    'resetting.check_email' => 'An email has been sent to %email%. It contains a link you must click to reset your password.',
    'resetting.request.invalid_username' => 'The username or email address "%username%" does not exist.',
    'resetting.request.username' => 'Username or email address:',
    'resetting.request.submit' => 'Reset password',
    'resetting.reset.submit' => 'Change password',
    'resetting.flash.success' => 'The password has been reset successfully',
    'resetting.email.subject' => 'Reset Password',
    'resetting.email.message' => 'Hello %username%!

To reset your password - please visit %confirmationUrl%

Regards,
the Team.
',
    'layout.logout' => 'Logout',
    'layout.login' => 'Login',
    'layout.register' => 'Register',
    'layout.logged_in_as' => 'Logged in as %username%',
    'form.group_name' => 'Group name:',
    'form.username' => 'Username:',
    'form.email' => 'Email:',
    'form.current_password' => 'Current password:',
    'form.password' => 'Password:',
    'form.password_confirmation' => 'Repeat password:',
    'form.new_password' => 'New password:',
    'form.new_password_confirmation' => 'Repeat new password:',
  ),
  'SonataUserBundle' =>
  array (
    'title_user_registration' => 'Register',
    'title_user_account' => 'User Profile',
    'title_user_edit_profile' => 'Edit',
    'title_user_authentication' => 'Authentication',
    'sonata_user_submit' => 'Submit',
    'breadcrumb.link_user_list' => 'Users',
    'breadcrumb.link_user_create' => 'Create',
    'breadcrumb.link_user_edit' => 'Edit',
    'breadcrumb.link_user_delete' => 'Delete',
    'breadcrumb.link_group_list' => 'Groups',
    'breadcrumb.link_group_create' => 'Create',
    'breadcrumb.link_group_edit' => 'Edit',
    'users' => 'Users',
    'groups' => 'Groups',
    'switch_user_exit' => 'Exit impersonating mode',
    'switch_user' => 'Impersonate User',
    'user_block_logout' => 'Logout',
    'form.label_username' => 'Username',
    'form.label_email' => 'E-Mail-Address',
    'form.label_plain_password' => 'Plain password',
    'form.label_groups' => 'Groups',
    'form.label_roles' => 'Roles',
    'form.label_locked' => 'Locked',
    'form.label_expired' => 'Expired',
    'form.label_enabled' => 'Enabled',
    'form.label_credentials_expired' => 'Credentials expired',
    'form.label_created_at' => 'Created at',
    'form.label_last_login' => 'Last login',
    'form.label_name' => 'Name',
    'filter.label_username' => 'Username',
    'filter.label_name' => 'Name',
    'filter.label_email' => 'E-Mail-Address',
    'filter.label_locked' => 'Locked',
    'filter.label_id' => 'ID',
    'filter.label_groups' => 'Groups',
    'filter.label_created_at' => 'Created at',
    'filter.label_last_login' => 'Last login',
    'filter.label_firstname' => 'Firstname',
    'filter.label_lastname' => 'Lastname',
    'list.label_username' => 'Username',
    'list.label_name' => 'Name',
    'list.label_email' => 'E-Mail-Address',
    'list.label_groups' => 'Groups',
    'list.label_locked' => 'Locked',
    'list.label_enabled' => 'Enabled',
    'list.label_created_at' => 'Created at',
    'list.label_last_login' => 'Last login',
    'list.label_impersonating' => 'Impersonate User',
    'list.label_roles' => 'Roles',
    'list.label_firstname' => 'Firstname',
    'list.label_lastname' => 'Lastname',
    'label_two_step_code' => 'Two-step verification',
    'message_two_step_code_help' => 'Enter the verification code generated by your mobile application.',
    'label_two_step_code_error' => 'The verification code is not valid',
    'sonata_user' => 'Users',
    'General' => 'General',
    'Groups' => 'Groups',
    'Management' => 'Management',
    'field.label_roles_editable' => 'Roles',
    'form.label_date_of_birth' => 'Date of birth',
    'form.label_firstname' => 'Firstname',
    'form.label_lastname' => 'Lastname',
    'form.label_website' => 'Website',
    'form.label_biography' => 'Biography',
    'form.label_gender' => 'Gender',
    'form.label_locale' => 'Locale',
    'form.label_timezone' => 'Timezone',
    'form.label_phone' => 'Phone',
    'form.label_facebook_uid' => 'Facebook Uid',
    'form.label_facebook_name' => 'Facebook Name',
    'form.label_twitter_uid' => 'Twitter Uid',
    'form.label_twitter_name' => 'Twitter Name',
    'form.label_gplus_uid' => 'Google+ Uid',
    'form.label_gplus_name' => 'Google+ Name',
    'form.label_token' => 'Token',
    'form.label_two_step_verification_code' => 'Two Step Verification Code',
    'show.label_username' => 'Username',
    'show.label_email' => 'Email',
    'show.label_groups' => 'Groups',
    'show.label_date_of_birth' => 'Date of birth',
    'show.label_firstname' => 'Firstname',
    'show.label_lastname' => 'Lastname',
    'show.label_website' => 'Website',
    'show.label_biography' => 'Biography',
    'show.label_gender' => 'Gender',
    'show.label_locale' => 'Locale',
    'show.label_timezone' => 'Timezone',
    'show.label_phone' => 'Phone',
    'show.label_facebook_uid' => 'Facebook Uid',
    'show.label_facebook_name' => 'Facebook Name',
    'show.label_twitter_uid' => 'Twitter Uid',
    'show.label_twitter_name' => 'Twitter Name',
    'show.label_gplus_uid' => 'Google+ Uid',
    'show.label_gplus_name' => 'Google+ Name',
    'show.label_token' => 'Token',
    'show.label_two_step_verification_code' => 'Two Step Verification Code',
    'show.label_created_at' => 'Created at',
    'show.label_last_login' => 'Last login',
    'breadcrumb.link_user_show' => 'Show',
    'gender_unknown' => 'unknown',
    'gender_female' => 'female',
    'gender_male' => 'male',
    'sonata_profile_title' => 'Dashboard',
    'link_show_profile' => 'Dashboard',
    'link_edit_profile' => 'Profile',
    'title_user_edit_authentication' => 'Authentication',
    'link_edit_authentication' => 'Authentication',
    'label_profile_gender' => 'Gender',
    'label_profile_firstname' => 'Firstname',
    'label_profile_lastname' => 'Lastname',
    'label_profile_website' => 'Website',
    'label_profile_dob' => 'Date of birth',
    'label_profile_biography' => 'Biography',
    'label_profile_locale' => 'Locale',
    'label_profile_timezone' => 'Timezone',
    'label_profile_phone' => 'Phone',
    'profile.flash.updated' => 'Your profile has been updated.',
    'sonata_change_password_link' => 'Change your password',
    'link_register' => 'Register',
    'link_login' => 'Log In',
    'link_logout' => 'Log out',
    'registration.flash.user_created' => 'Your account has been created successfully!',
    'forgotten_password' => 'Forgotten password?',
    'sonata_user_profile_breadcrumb_index' => 'Dashboard',
    'sonata_user_profile_breadcrumb_edit' => 'Edit profile',
    'sonata_user_already_authenticated' => 'You are already logged in',
  ),
  'CmfCoreBundle' =>
  array (
    'form.group_publish_workflow' => 'Publish Workflow',
    'form.label_publishable' => 'Publishable',
    'form.label_publish_start_date' => 'Publish from',
    'form.label_publish_end_date' => 'Publish until',
    'form.label_locale' => 'Locale',
    'form.help_publish_start_date' => 'Only publish on or after this date, leave empty to immediately publish',
    'form.help_publish_end_date' => 'Only publish before this date, leave empty to not end publishing',
    'list.label_locales' => 'Locales',
  ),
  'CmfMenuBundle' =>
  array (
    'dashboard.cmf' => 'Symfony CMF',
    'dashboard.label_menu' => 'Menus',
    'dashboard.label_menu_node' => 'Menu node',
    'breadcrumb.link_menu_list' => 'Menus',
    'breadcrumb.link_menu_create' => 'Create',
    'breadcrumb.link_menu_edit' => 'Edit',
    'breadcrumb.link_menu_delete' => 'Delete',
    'breadcrumb.link_menu_node_list' => 'Menu nodes',
    'breadcrumb.link_menu_node_create' => 'Create',
    'breadcrumb.link_menu_node_edit' => 'Edit',
    'breadcrumb.link_menu_node_delete' => 'Delete',
    'list.label_id' => 'Id',
    'list.label_name' => 'Name',
    'list.label_label' => 'Label',
    'list.label_uri' => 'URI',
    'list.label_route' => 'Route',
    'form.group_general' => 'General',
    'form.group_items' => 'Items',
    'form.label_children' => 'Items',
    'form.label_parent' => 'Parent',
    'form.label_name' => 'Name',
    'form.label_label' => 'Label',
    'form.label_uri' => 'URI',
    'form.label_route' => 'Route',
    'form.label_parameters' => 'Route parameters',
    'form.label_content' => 'Content',
    'form.label_link_type' => 'Link type',
    'form.label_weak' => 'Weak association',
    'help.items_help' => 'Click on item to edit, right click to create new items.',
    'form.group_menus' => 'Menu',
    'form.label_menu_nodes' => 'Menu',
    'form.group_menu_options' => 'Menu Options',
    'form.label_display' => 'Display',
    'form.help_display' => 'A menu entry is only displayed if the label is not empty.',
    'form.label_display_children' => 'Display Children',
    'form.help_display_children' => 'Children are only displayed if the menu entry itself is displayed.',
    'form.label_attributes' => 'Menu attributes',
    'form.label_label_attributes' => 'Label attributes',
    'form.label_children_attributes' => 'Children attributes',
    'form.label_link_attributes' => 'Link attributes',
  ),
));
$catalogue->addFallbackCatalogue($catalogueEn);

return $catalogue;


text:
package org.apache.harmony.xnet.provider.jsse;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;

import junit.framework.TestCase;

/**
 * Tests for ServerKeyExchange constructor and methods
 *
 */
public class ServerKeyExchangeTest extends TestCase {

    public void testServerKeyExchange_RSA_EXPORT() throws Exception {
        BigInteger rsa_mod = new BigInteger(
                "0620872145533812525365347773040950432706816921321053881493952289532007782427182339053847578435298266865073748931755945944874247298083566202475988854994079");
        BigInteger rsa_exp = new BigInteger("65537");

        byte[] hash = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5,
                6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
        ServerKeyExchange message = new ServerKeyExchange(rsa_mod, rsa_exp,
                null, hash);
        assertEquals("incorrect type", Handshake.SERVER_KEY_EXCHANGE, message
                .getType());

        assertTrue("incorrect ServerKeyExchange", Arrays.equals(message.hash,
                hash));
        assertEquals("incorrect ServerKeyExchange", rsa_mod, message.par1);
        assertEquals("incorrect ServerKeyExchange", rsa_exp, message.par2);
        assertNull("incorrect ServerKeyExchange", message.par3);

        HandshakeIODataStream out = new HandshakeIODataStream();
        message.send(out);
        byte[] encoded = out.getData(1000);
        assertEquals("incorrect out data length", message.length(),
                encoded.length);

        HandshakeIODataStream in = new HandshakeIODataStream();
        in.append(encoded);
        ServerKeyExchange message_2 = new ServerKeyExchange(in, message
                .length(), CipherSuite.KeyExchange_RSA_EXPORT);

        assertTrue("incorrect message decoding", Arrays.equals(message.hash,
                message_2.hash));
        assertEquals("incorrect message decoding", message.par1, message_2.par1);
        assertEquals("incorrect message decoding", message.par2, message_2.par2);
        assertNull("incorrect message decoding", message_2.par3);
        assertEquals("incorrect message decoding", message.getRSAPublicKey(),
                message_2.getRSAPublicKey());

        in.append(encoded);
        try {
            new ServerKeyExchange(in, message.length() - 1,
                    CipherSuite.KeyExchange_RSA_EXPORT);
            fail("Small length: No expected AlertException");
        } catch (AlertException e) {
        }

        in.append(encoded);
        in.append(new byte[] { 1, 2, 3 });
        try {
            new ServerKeyExchange(in, message.length() + 3,
                    CipherSuite.KeyExchange_RSA_EXPORT);
            fail("Extra bytes: No expected AlertException ");
        } catch (AlertException e) {
        }
    }

    public void testServerKeyExchange_DHE_DSS() throws Exception {
        BigInteger dh_p = new BigInteger("1234567890");
        BigInteger dh_g = new BigInteger("987654321");
        BigInteger dh_Ys = new BigInteger("123123123");
        byte[] hash = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5,
                6, 7, 8, 9, 0 };
        ServerKeyExchange message = new ServerKeyExchange(dh_p, dh_g, dh_Ys,
                hash);
        assertEquals("incorrect type", Handshake.SERVER_KEY_EXCHANGE, message
                .getType());

        assertTrue("incorrect ServerKeyExchange", Arrays.equals(message.hash,
                hash));
        assertEquals("incorrect ServerKeyExchange", dh_p, message.par1);
        assertEquals("incorrect ServerKeyExchange", dh_g, message.par2);
        assertEquals("incorrect ServerKeyExchange", dh_Ys, message.par3);

        HandshakeIODataStream out = new HandshakeIODataStream();
        message.send(out);
        byte[] encoded = out.getData(1000);
        assertEquals("incorrect out data length", message.length(),
                encoded.length);

        HandshakeIODataStream in = new HandshakeIODataStream();
        in.append(encoded);
        ServerKeyExchange message_2 = new ServerKeyExchange(in, message
                .length(), CipherSuite.KeyExchange_DHE_DSS);

        assertTrue("incorrect message decoding", Arrays.equals(message.hash,
                message_2.hash));
        assertEquals("incorrect message decoding", message.par1, message_2.par1);
        assertEquals("incorrect message decoding", message.par2, message_2.par2);
        assertEquals("incorrect message decoding", message.par3, message_2.par3);

        in.append(encoded);
        try {
            new ServerKeyExchange(in, message.length() - 1,
                    CipherSuite.KeyExchange_DHE_DSS);
            fail("Small length: No expected AlertException");
        } catch (AlertException e) {
        }

        in.append(encoded);
        in.append(new byte[] { 1, 2, 3 });
        try {
            new ServerKeyExchange(in, message.length() + 3,
                    CipherSuite.KeyExchange_DHE_DSS);
            fail("Extra bytes: No expected AlertException ");
        } catch (AlertException e) {
        }
    }

    public void testServerKeyExchange_DH_anon() throws Exception {
        BigInteger dh_p = new BigInteger("1234567890");
        BigInteger dh_g = new BigInteger("987654321");
        BigInteger dh_Ys = new BigInteger("123123123");
        ServerKeyExchange message = new ServerKeyExchange(dh_p, dh_g, dh_Ys,
                null);
        assertEquals("incorrect type", Handshake.SERVER_KEY_EXCHANGE, message
                .getType());

        assertNull("incorrect ServerKeyExchange", message.hash);
        assertEquals("incorrect ServerKeyExchange", dh_p, message.par1);
        assertEquals("incorrect ServerKeyExchange", dh_g, message.par2);
        assertEquals("incorrect ServerKeyExchange", dh_Ys, message.par3);

        HandshakeIODataStream out = new HandshakeIODataStream();
        message.send(out);
        byte[] encoded = out.getData(1000);
        assertEquals("incorrect out data length", message.length(),
                encoded.length);

        HandshakeIODataStream in = new HandshakeIODataStream();
        in.append(encoded);
        ServerKeyExchange message_2 = new ServerKeyExchange(in, message
                .length(), CipherSuite.KeyExchange_DH_anon);

        assertNull("incorrect message decoding", message_2.hash);
        assertEquals("incorrect message decoding", message.par1, message_2.par1);
        assertEquals("incorrect message decoding", message.par2, message_2.par2);
        assertEquals("incorrect message decoding", message.par3, message_2.par3);

        in.append(encoded);
        try {
            new ServerKeyExchange(in, message.length() - 1,
                    CipherSuite.KeyExchange_DH_anon);
            fail("Small length: No expected AlertException");
        } catch (AlertException e) {
        }

        in.append(encoded);
        in.append(new byte[] { 1, 2, 3 });
        try {
            new ServerKeyExchange(in, message.length() + 3,
                    CipherSuite.KeyExchange_DH_anon);
            fail("Extra bytes: No expected AlertException ");
        } catch (AlertException e) {
        }
    }

}


text:
exports.pitch = function(remainingRequest) {
	this.addDependency("remainingRequest:" + remainingRequest);
};


text: this is a test article


text:
package com.wb.nextgenlibrary.util.utils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import com.wb.nextgenlibrary.util.HttpImageHelper;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

/**
 * Current ImageOrder implementation is more convoluted than ImageRequest.
 */
public class ImageGetter {
    private static final ImageGetter INSTANCE = new ImageGetter();

    private final Queue<ImageRequest> imageQueue;

    private ImageGetter() {
        imageQueue = new LinkedBlockingQueue<ImageRequest>(); // Alternative: use LinkedBlockingQueue for auto blocking
        new Thread(new ImageRequestConsumer(imageQueue)).start();
    }

    public static ImageGetter instance() {
        return INSTANCE;
    }

    public void get(String url, Handler handler) {
    //    Logger.d("ImageGetter", "ImageGetter requesting: " + url);
        synchronized (imageQueue) {
            imageQueue.add(new ImageRequest(url, handler));
            if (imageQueue.size() == 1) {
                imageQueue.notifyAll();
            }
        }
    }

    private static class ImageRequest {
        public final String url;
        public final Handler handler;

        private ImageRequest(String url, Handler handler) {
            this.url = url;
            this.handler = handler;
        }
    }

    private static abstract class RequestConsumer<T> implements Runnable {
        private final Queue<T> queue;

        protected RequestConsumer(Queue<T> q) {
            queue = q;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    T object = null;
                    synchronized (queue) {
                        if (queue.size() == 0) {
                       //     Logger.d("ImageGetter", "RequestConsumer waiting");
                            queue.wait();
                        }
                        object = queue.remove();
                    }
                    consume(object);
                 //   Logger.d("ImageGetter", "RequestConsumer consuming");

                } catch (InterruptedException e) {
                    NextGenLogger.e(F.TAG, "ImageGetter.RequestConsumer.run", e);
                }
            }
        }

        protected abstract void consume(T object);
    }

    private static class ImageRequestConsumer extends RequestConsumer<ImageRequest> {
        protected ImageRequestConsumer(Queue<ImageRequest> q) {
            super(q);
        }

        @Override
        protected void consume(ImageRequest request) {
            URL url = null;
            try {
                url = new URL(request.url);
            } catch (MalformedURLException e) {
                NextGenLogger.e(F.TAG, "ImageRequestConsumer.consume url=" + url, e);
                return;
            }
            try {
                if (request.handler == null) {
                  //  HttpImageHelper.fetchImageDoNotCache(url);
                    Bitmap image = HttpImageHelper.fetchImage(url); // Caching enabled
                } else {
                    Bitmap image = HttpImageHelper.fetchImage(url); // Caching enabled
                    request.handler.sendMessage(Message.obtain(null, 0, image));
                }
            } catch (IOException e) {
                NextGenLogger.e(F.TAG, "ImageRequestConsumer.consume", e);
            }
        }
    }
}


text:
package net.sf.jailer.ui.graphical_view;

import java.awt.Cursor;
import java.awt.event.MouseEvent;

import prefuse.Display;
import prefuse.controls.ControlAdapter;
import prefuse.util.ui.UILib;
import prefuse.visual.VisualItem;

/**
 * Pans the display, changing the viewable region of the visualization.
 * By default, panning is accomplished by clicking on the background of a
 * visualization with the left mouse button and then dragging.
 *
 * @author jeffrey heer
 */
public class PanControl extends ControlAdapter {

	private boolean m_panOverItem;
	private boolean m_DownValid;
	private int m_xDown, m_yDown;
	private int m_button;

	/**
	 * Create a new PanControl.
	 */
	public PanControl() {
		this(LEFT_MOUSE_BUTTON, false);
	}

	/**
	 * Create a new PanControl.
	 * @param panOverItem if true, the panning control will work even while
	 * the mouse is over a visual item.
	 */
	public PanControl(boolean panOverItem) {
		this(LEFT_MOUSE_BUTTON, panOverItem);
	}

	/**
	 * Create a new PanControl.
	 * @param mouseButton the mouse button that should initiate a pan. One of
	 * {@link Control#LEFT_MOUSE_BUTTON}, {@link Control#MIDDLE_MOUSE_BUTTON},
	 * or {@link Control#RIGHT_MOUSE_BUTTON}.
	 */
	public PanControl(int mouseButton) {
		this(mouseButton, false);
	}

	/**
	 * Create a new PanControl
	 * @param mouseButton the mouse button that should initiate a pan. One of
	 * {@link Control#LEFT_MOUSE_BUTTON}, {@link Control#MIDDLE_MOUSE_BUTTON},
	 * or {@link Control#RIGHT_MOUSE_BUTTON}.
	 * @param panOverItem if true, the panning control will work even while
	 * the mouse is over a visual item.
	 */
	public PanControl(int mouseButton, boolean panOverItem) {
		m_button = mouseButton;
		m_panOverItem = panOverItem;
	}

	// ------------------------------------------------------------------------

	/**
	 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
	 */
	@Override
	public void mousePressed(MouseEvent e) {
		if ( UILib.isButtonPressed(e, m_button) ) {
			e.getComponent().setCursor(
				Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
			m_xDown = e.getX();
			m_yDown = e.getY();
			m_DownValid = true;
		}
	}

	/**
	 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
	 */
	@Override
	public void mouseDragged(MouseEvent e) {
		if ( UILib.isButtonPressed(e, m_button) ) {
			Display display = (Display)e.getComponent();
			int x = e.getX(),   y = e.getY();
			int dx = x-m_xDown, dy = y-m_yDown;
			if (m_DownValid) {
				display.pan(dx,dy);
			}
			m_xDown = x;
			m_yDown = y;
			m_DownValid = true;
			display.repaint();
		}
	}

	/**
	 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
	 */
	@Override
	public void mouseReleased(MouseEvent e) {
		if ( UILib.isButtonPressed(e, m_button) ) {
			e.getComponent().setCursor(null); // e.getComponent().setCursor(Cursor.getDefaultCursor());
			m_xDown = -1;
			m_yDown = -1;
			m_DownValid = false;
		}
	}

	/**
	 * @see prefuse.controls.Control#itemPressed(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
	 */
	@Override
	public void itemPressed(VisualItem item, MouseEvent e) {
		if ( m_panOverItem )
			mousePressed(e);
	}

	/**
	 * @see prefuse.controls.Control#itemDragged(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
	 */
	@Override
	public void itemDragged(VisualItem item, MouseEvent e) {
		if ( m_panOverItem )
			mouseDragged(e);
	}

	/**
	 * @see prefuse.controls.Control#itemReleased(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
	 */
	@Override
	public void itemReleased(VisualItem item, MouseEvent e) {
		if ( m_panOverItem )
			mouseReleased(e);
	}

} // end of class PanControl


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.proxy;

import com.facebook.airlift.configuration.Config;
import com.facebook.airlift.configuration.ConfigDescription;
import io.airlift.units.Duration;

import javax.validation.constraints.NotNull;

import java.io.File;
import java.net.URI;

import static java.util.concurrent.TimeUnit.MINUTES;

public class ProxyConfig
{
    private URI uri;
    private File sharedSecretFile;
    private Duration asyncTimeout = new Duration(2, MINUTES);

    @NotNull
    public URI getUri()
    {
        return uri;
    }

    @Config("proxy.uri")
    @ConfigDescription("URI of the remote Presto server")
    public ProxyConfig setUri(URI uri)
    {
        this.uri = uri;
        return this;
    }

    @NotNull
    public File getSharedSecretFile()
    {
        return sharedSecretFile;
    }

    @Config("proxy.shared-secret-file")
    @ConfigDescription("Shared secret file used for authenticating URIs")
    public ProxyConfig setSharedSecretFile(File sharedSecretFile)
    {
        this.sharedSecretFile = sharedSecretFile;
        return this;
    }

    @NotNull
    public Duration getAsyncTimeout()
    {
        return asyncTimeout;
    }

    @Config("proxy.async-timeout")
    @ConfigDescription("Timeout for reading responses from Coordinator to Proxy")
    public ProxyConfig setAsyncTimeout(Duration asyncTimeout)
    {
        this.asyncTimeout = asyncTimeout;
        return this;
    }
}


text:
import { Component, NgZone } from '@angular/core';
import { App, NavController } from 'ionic-angular';
import { FirebaseListObservable } from 'angularfire2';
import { User, Meal, MealFactory } from '../../models';
import { Auth } from '../../providers';
import { MealService } from '../../services';
import { MealNewTabsPage, MealTabsPage } from '../';

@Component({
  selector: 'page-meal-search',
  templateUrl: 'search.html'
})
export class MealSearchPage {

  user: User;
  meals: Array<any> = [];

  constructor(
    public app: App, public nav: NavController,
    public auth: Auth, private mealService: MealService, private mealFactory: MealFactory,
  ) {}

  ngOnInit() {
    this.auth.loggedUser().subscribe((user: User) => {
      this.user = user;
    });

    this.mealService.getAll().subscribe(meals => {
      this.meals = [];
      meals.forEach((meal) => {
        this.meals.push(this.mealFactory.create(meal));
      });

      console.log(this.meals)
    });
  }

  mealTabs(meal: any) {
    this.nav.push(MealTabsPage, { meal: meal, user: this.user });
  }

  edit(meal: any) {
    this.nav.push(MealNewTabsPage, { meal: meal, user: this.user });
  }

  new() {
    this.nav.push(MealNewTabsPage, { user: this.user });
  }

}


text:
#ifndef DEBUG_CLOCK_H
#define DEBUG_CLOCK_H

#include "config.h"

#include "TimeUtility.h"
#include <iosfwd>

/// uses milli seconds
class DebugClock {
public:
   inline DebugClock() : m_startTime( TimeUtility::getCurrentTime() ) {}
   /// @return time in msec
   inline uint32 getTime() const {
      return TimeUtility::getCurrentTime() - m_startTime;
   }
private:
   uint32 m_startTime;
};

/// uses micro seconds
class DebugClockMicro {
public:
   DebugClockMicro(): m_startTime( TimeUtility::getCurrentMicroTime() ) { }
   /// @return time in usec
   uint32 getTime() const {
      return TimeUtility::getCurrentMicroTime() - m_startTime;
   }
private:
   uint32 m_startTime;
};

/// Uses seconds.
class DebugClockSeconds {
public:
   DebugClockSeconds(): m_startTime( TimeUtility::getRealTime() ) { }
   /// @return elapsed time in seconds.
   uint32 getTime() const {
      return TimeUtility::getRealTime() - m_startTime;
   }
private:
   /// Start time in seconds since 00:00:00 1970-01-01 UTC.
   uint32 m_startTime;
};

/// write debug clock to ostream
inline ostream& operator<<( ostream& ost, const DebugClock& clock) {
   ost << clock.getTime() << " ms";
   return ost;
}

/// write debug clock micro to ostream
inline ostream& operator << ( ostream& ost, const DebugClockMicro& clock ) {
   ost << clock.getTime() << " us";
   return ost;
}

inline ostream& operator << ( ostream& ost, const DebugClockSeconds& clock ) {
   ost << clock.getTime() << " s";
   return ost;
}

#endif


text:
> NOTA: Progetto universitario di Tecnologie Software.

 * URL: http://labappweb.labinfo.educ.di.unito.it/studenti/st116798/SocialProject
 * ADMIN: Admin:Qwe123
 * USER:
  *  Topolino:Qwe123
  *  Pippo:Qwe123
  *  Pluto:Qwe123
  *  Paperino:Qwe123

## HOWTO
Il progetto dovrebbe partire senza problemi, tuttavia se si dovessero presentare problemi riguardanti il percorso è possibile modificare quest'ultimo
globalmente dentro i file di configurazioni, posizionati nella cartella config.
Un'altra possibile aggiunta (non necessaria al funzionamento, ma che implementa un ulteriore livello di sicurezza) è l'abilitazione dell' .htaccess (Qualora  apache non sia già configurato per attivarlo)

```
E' Opportuno attivare gli .htaccess aggiungendo al file /etc/apache2/sites-available/000-default.conf

<Directory "/var/www">
   AllowOverride All
</Directory>
```
> Nota: In questo modo  .htaccess presente nella dir principale del progetto impedirà l'accesso a qualsiasi file php diverso dall' index.php (i singoli file hanno in ogni caso i controlli che impediscono l'accesso non autorizzato, ma nessuno dovrebbe essere in grado di accedere direttamente a un file php che non sia tramite index.php, anche avendo gli accessi per vedere quella sezione )

## Realizzazione

Il progetto implementa il pattern mvc, prendendo anche un' ispirazione da Wordpress come struttura di realizzazione:
Il progetto sarà composto infatti oltre al Model, al Controller e alle View anche da una cartella **Template**.

### Database
* **User**: Contiene le informazioni principali dell' utente
* **Profile**: Con una relazione 1:1 con User, Contiene le altre informazioni personali dell' utente. E' stato pensato separatamente dall' Utente Semplicemente per predisporlo alla possibilità futura di avere multi-profili o magari cambiare profilo mantenendo i dati di login, lasciando comunque uno storico nel database.
* **Relationship**:Relazioni fra utenti diversi (Sia amicizie ma anche utenti bloccati)
* **Post**: I Post scritti dagli utenti. E' possibile citare altri utenti usano il @NOME_UTENTE oppure aggiungere hashtag #HashTag, oltre che condividere immagini
* **Comment**: I commenti ai post
* **Showcase**: La bacheca: serve per indicare quali post devono essere mostrati nella home. Tale Tabella si rende necessaria
* **Notify**: Tabella usata per inviare le notifiche ai vari utenti

### Controller
Il Controller viene richiamato subito da index.php.
E' lui che esegue tutte le azioni in base alla variabile richiesta.
In particolare è il **MasterController.php** che oltre a generare il menu, richiama i vari sotto-controller in base alle richieste ricevute tramite POST o GET.
Alla fine di tutto si occupa anche di generare la pagina richiamando il Template.
In genere il controller si può comportare in due modi in base alle richieste:
nel caso di una richiesta ajax restituisce una porzione di html o in alcuni casi anche dei file JSON, nel caso di richieste non asincrone invece genera nuovamente tutta la pagina.

### Model
I model si interfacciano con il Database.
A ogni tabella del database corrisponde una corrispettiva classe php che si occupa di recuperare i dati dal database oppure effettuare le query per salvarli.
particolare importanza si può dare al **Model.php**, che è una classe astratta che estende poi tutte le altre classi Model.
Questa classe richiama la classe **Database.php** per effettuare le query. Per interfacciarsi al database sono stati usati i **PDO**.
In questa classe è possibile cambiare le configurazioni del database cambiando semplicemente delle variabili.

### VIEW

In questo progetto le view sono trattati di fatto come se fossero dei plugin da aggiungere al template. Sono dei "blocchi" che implementano una funzionalità.
Spesso questi rappresentano il contenuto di un intera pagina, ma potrebbero anche essere solo una parte di essa. Il Controller posiziona la view corretta all' interno del template.
Se ad esempio siamo interessati a vedere il profilo di un utente il controller caricherà la view Profile.php e Showcase.php per vedere rispettivamente le informazioni dell' utente e i suou ultimi post in bacheca.

### Template
Il template contiene la struttura della pagina, in cui saranno inseriti i contenuti come una sorta di "hook semplificati". L'idea di base è quella di avere la possibilità di cambiare il Template della pagina agevolmente, senza intaccare il contenuto del SocialWeb.
i componenti fondamentali sono:
* **ManageTemplate.php**: Mette a disposizione delle funzioni che permettono di aggiungere agevolmente css, js, voci del menu e contenuto da visualizzare in una pagina. Il tutto viene fatto caricando degli array che saranno poi usati per inserire il contenuto una volta che si genera la pagina.
* **page.php**: è il Template della pagina. Cambiando questo file è possibile cambiare l'aspetto del Social Network, lasciando inalterato (o quasi) il contenuto dello stesso.

## Funzionalita
Attualmente il Social Network implementa tutte le richieste della consegna, con alcune piccole aggiunte.
Ad esempio, è possibile inserire hashtag nel commento oppure citare un amico nel commento usando @Nome_Utente.
Nelle varie barre di ricerca e nel caso si cerchi un amico si è supportati nella ricerca tramite funzioni js, che man mano si va avanti ti offrono suggerimenti su quello che stai scrivendo.

## Contenuto
```
/
├───Config
├───Controller
├───Model
├───Public
├───Template
│   ├───css
│   │   └───images
│   ├───fonts
│   ├───images
│   └───js
└───View
    ├───Account
    ├───Friends
    ├───Hashtag
    ├───Join
    ├───Login
    ├───News
    ├───Notify
    ├───PrivateArea
    ├───SearchBar
    ├───Showcase
    └───Statistiche
        └───Grafici
```


text:
package net.japan.kana.hakana.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.TextView;

/**
 * Author Vitalii Lebedynskyi
 * Date 11/3/14
 */
public class CheckableTextView extends TextView implements Checkable {
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
    private boolean isChecked;

    public CheckableTextView(Context context) {
        super(context);
    }

    public CheckableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CheckableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked())
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        return drawableState;
    }

    @Override
    public void setChecked(boolean checked) {
        isChecked = checked;
        refreshDrawableState();
    }

    @Override
    public boolean isChecked() {
        return isChecked;
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }
}


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Data;

namespace Windows.UI.Interactivity
{
    /// <summary>
    /// Encapsulates state information and zero or more ICommands into an attachable object.
    ///
    /// </summary>
    ///
    /// <remarks>
    /// This is an infrastructure class. Behavior authors should derive from Behavior<T> instead of from this class.
    /// </remarks>
    public abstract class Behavior : InteractivityBase
    {
        internal Behavior(Type associatedObjectTypeConstraint)
        {
            this.AssociatedObjectTypeConstraint = associatedObjectTypeConstraint;
        }

        /// <summary>
        /// Attaches to the specified object.
        ///
        /// </summary>
        /// <param name="frameworkElement">The object to attach to.</param><exception cref="T:System.InvalidOperationException">The Behavior is already hosted on a different element.</exception><exception cref="T:System.InvalidOperationException">dependencyObject does not satisfy the Behavior type constraint.</exception>
        public override void Attach(FrameworkElement frameworkElement)
        {
            if (frameworkElement == this.AssociatedObject)
            {
                return;
            }
            if (this.AssociatedObject != null)
            {
                throw new InvalidOperationException("Cannot host behavior multiple times.");
            }
            if (frameworkElement != null && !this.AssociatedObjectTypeConstraint.GetTypeInfo().IsAssignableFrom(frameworkElement.GetType().GetTypeInfo()))
            {
                throw new InvalidOperationException("Type constraint violated.");
            }
            else
            {
                this.AssociatedObject = frameworkElement;
                this.OnAssociatedObjectChanged();
                //Attach handles the DataContext
                base.Attach(frameworkElement);
                this.OnAttached();
            }
        }

        /// <summary>
        /// Detaches this instance from its associated object.
        ///
        /// </summary>
        public override void Detach()
        {
            base.Detach();
            this.OnDetaching();
            this.AssociatedObject = null;
            this.OnAssociatedObjectChanged();
        }
    }
}