text:
(function(env){
	var crawler = require('../lib/crawler')
			, spsu

	console.log('Creating Crawler');
	console.assert(typeof(crawler) === 'object')

	console.log('Testing existance of spsu submodule')
	console.assert(typeof(crawler.spsu) === 'object')

	console.log('Crawling')
	crawl = crawler.spsu.crawl('201208')
	crawl.on('done', function(d){
		console.log('GOT DONE EVENT:', d.length, 'departments')
	})

})(this)


text:
<!-- Import Polymer -->
<link rel="import" href="../bower_components/polymer/polymer.html">

<!-- Define your custom element -->
<polymer-element name="gplus-follow"
         attributes="annotation height href lang rel size width">

    <script>
        Polymer("gplus-follow", {
            annotation : "bubble",
            height     : 20,
            href       : "https://plus.google.com/+WebcomponentsOrg",
            lang       : "en-US",
            rel        : "",
            size       : "standard",
            width      : 300,

            ready: function () {
                var script = document.createElement("script"),
                    div = document.createElement("div"),
                    body = document.body;

                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", "https://apis.google.com/js/plusone.js");
                script.setAttribute("async", true);
                script.innerHTML = "{lang: '" + this.lang + "'}";

                div.setAttribute("class", "g-follow");

                div.setAttribute("data-href", this.href);
                div.setAttribute("data-annotation", this.annotation);
                div.setAttribute("data-rel", this.rel);
                div.setAttribute("data-height", this.height);

                this.appendChild(div);
                body.appendChild(script);
            }
        });
    </script>

</polymer-element>

redpajama_set_name: RedPajamaGithub


text:
using biz.dfch.CS.Appclusive.UI.App_LocalResources;
using biz.dfch.CS.Appclusive.UI.Models.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace biz.dfch.CS.Appclusive.UI.Models
{
    public interface IAppcusiveEntityBase
    {
        [Display(Name = "Id", ResourceType = typeof(GeneralResources))]
        long Id { get; set; }

        [Display(Name = "Created", ResourceType = typeof(GeneralResources))]
        DateTimeOffset Created { get; set; }

        [Display(Name = "Modified", ResourceType = typeof(GeneralResources))]
        DateTimeOffset Modified { get; set; }

        [Display(Name = "RowVersion", ResourceType = typeof(GeneralResources))]
        byte[] RowVersion { get; set; }

        [Required(ErrorMessageResourceName = "requiredField", ErrorMessageResourceType = typeof(ErrorResources))]
        [Display(Name = "Tid", ResourceType = typeof(GeneralResources))]
        Guid Tid { get; set; }

        [Display(Name = "Tenant", ResourceType = typeof(GeneralResources))]
        Tenant Tenant { get; set; }

        [Required(ErrorMessageResourceName = "requiredField", ErrorMessageResourceType = typeof(ErrorResources))]
        [Display(Name = "CreatedById", ResourceType = typeof(GeneralResources))]
        long CreatedById { get; set; }

        [Display(Name = "CreatedBy", ResourceType = typeof(GeneralResources))]
        User CreatedBy { get; set; }

        [Required(ErrorMessageResourceName = "requiredField", ErrorMessageResourceType = typeof(ErrorResources))]
        [Display(Name = "ModifiedById", ResourceType = typeof(GeneralResources))]
        long ModifiedById { get; set; }

        [Display(Name = "ModifiedBy", ResourceType = typeof(GeneralResources))]
        User ModifiedBy { get; set; }

        [StringLength(1024)]
        [Required(ErrorMessageResourceName = "requiredName", ErrorMessageResourceType = typeof(ErrorResources))]
        [Display(Name = "Name", ResourceType = typeof(GeneralResources))]
        string Name { get; set; }

        [Display(Name = "Description", ResourceType = typeof(GeneralResources))]
        string Description { get; set; }
    }
}


text:
//----------------------------------*-C++-*----------------------------------//
/**
 *  @file   GenException.hh
 *  @author Jeremy Roberts
 *  @date   04/09/2011
 *  @brief  GenException class definition.
 *  @note   Modified version of K. Huff's class from cyclus
 */
//---------------------------------------------------------------------------//

#ifndef detran_utilities_GENEXCEPTION_HH
#define detran_utilities_GENEXCEPTION_HH

#include "utilities/utilities_export.hh"
#include "utilities/Definitions.hh"
#include <iostream>
#include <exception>
#include <string>

namespace detran_utilities
{

/**
 *  A generic mechanism to manually manage exceptions
 */
class UTILITIES_EXPORT GenException: public std::exception
{

public:

  /// Constructs a new GenException with the default message.
  GenException();

  /**
   * @brief Constructs a new GenException with a provided message
   *
   * @param line line of code erring
   * @param file file in which error occurs
   * @param msg the message
   */
  GenException(int line, std::string file, std::string msg);

  /**
   * Returns the error message associated with this GenException.
   *
   * @return the message
   */
  virtual const char* what() const throw ();

  /**
   * Destroys this GenException.
   */
  virtual ~GenException() throw ();

protected:

  /// The message associated with this exception.
  std::string myMessage;
  /// A string to prepend to all message of this class.
  static std::string prepend;

};

/// Easy macro for throwing exceptions.
#define THROW(m) throw detran_utilities::GenException(__LINE__,__FILE__,m);

} // end namespace detran_utilities

#endif // detran_utilities_GENEXCEPTION_HH


text:
package	org.apache.derby.impl.sql.compile;

import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.services.compiler.LocalField;
import org.apache.derby.iapi.types.DataTypeDescriptor;

import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.reference.ClassName;

import org.apache.derby.iapi.services.classfile.VMOpcode;

import java.lang.reflect.Modifier;

import java.sql.Types;

import java.util.List;

/**
 * This node represents a unary DB2 compatible length operator
 *
 */

public final class DB2LengthOperatorNode extends UnaryOperatorNode
{

	/**
	 * Initializer for a DB2LengthOperatorNode
	 *
	 * @param operand	The operand of the node
	 */
	public void init(Object	operand)
	{
		super.init( operand, "length", "getDB2Length");
    }

	/**
	 * Bind this operator
	 *
	 * @param fromList			The query's FROM list
	 * @param subqueryList		The subquery list being built as we find SubqueryNodes
	 * @param aggregateVector	The aggregate vector being built as we find AggregateNodes
	 *
	 * @return	The new top of the expression tree.
	 *
	 * @exception StandardException		Thrown on error
	 */

	public ValueNode bindExpression(
		FromList	fromList, SubqueryList subqueryList,
		List aggregateVector)
			throws StandardException
	{
        bindOperand( fromList, subqueryList, aggregateVector);

        // This operator is not allowed on XML types.
        TypeId operandType = operand.getTypeId();
        if (operandType.isXMLTypeId()) {
            throw StandardException.newException(SQLState.LANG_UNARY_FUNCTION_BAD_TYPE,
                                    getOperatorString(),
                                    operandType.getSQLTypeName());
        }

        setType( new DataTypeDescriptor( TypeId.getBuiltInTypeId( Types.INTEGER),
                                         operand.getTypeServices().isNullable()));
        return this;
    }

	/**
	 * This is a length operator node.  Overrides this method
	 * in UnaryOperatorNode for code generation purposes.
	 */
	public String getReceiverInterfaceName() {
	    return ClassName.ConcatableDataValue;
	}

    /**
	 * Do code generation for this unary operator.
	 *
	 * @param acb	The ExpressionClassBuilder for the class we're generating
	 * @param mb	The method the expression will go into
	 *
	 *
	 * @exception StandardException		Thrown on error
	 */

	public void generateExpression(ExpressionClassBuilder acb,
											MethodBuilder mb)
									throws StandardException
	{
		if (operand == null)
			return;

        int constantLength = getConstantLength();
        // -1 if the length of a non-null operand depends on the data

		String resultTypeName = getTypeCompiler().interfaceName();

        mb.pushThis();
		operand.generateExpression(acb, mb);
        mb.upCast( ClassName.DataValueDescriptor);
        mb.push( constantLength);

        /* Allocate an object for re-use to hold the result of the operator */
        LocalField field = acb.newFieldDeclaration(Modifier.PRIVATE, resultTypeName);
        mb.getField(field);
        mb.callMethod(VMOpcode.INVOKEVIRTUAL, ClassName.BaseActivation, methodName, resultTypeName, 3);

        /*
        ** Store the result of the method call in the field, so we can re-use
        ** the object.
        */
        mb.putField(field);
    } // end of generateExpression

    private int getConstantLength( ) throws StandardException
    {
        DataTypeDescriptor typeDescriptor = operand.getTypeServices();

        switch( typeDescriptor.getJDBCTypeId())
        {
        case Types.BIGINT:
            return 8;
		case Types.BOOLEAN:
        case Types.BIT:
            return 1;
        case Types.BINARY:
        case Types.CHAR:
            return typeDescriptor.getMaximumWidth();
        case Types.DATE:
            return 4;
        case Types.DECIMAL:
        case Types.NUMERIC:
            return typeDescriptor.getPrecision()/2 + 1;
        case Types.DOUBLE:
            return 8;
        case Types.FLOAT:
        case Types.REAL:
        case Types.INTEGER:
            return 4;
        case Types.SMALLINT:
            return 2;
        case Types.TIME:
            return 3;
        case Types.TIMESTAMP:
            return 10;
        case Types.TINYINT:
            return 1;
        case Types.LONGVARCHAR:
        case Types.VARCHAR:
        case Types.LONGVARBINARY:
        case Types.VARBINARY:
        case Types.BLOB:
            return getConstantNodeLength();
        default:
			return -1;
        }
    } // end of getConstantLength

    private int getConstantNodeLength() throws StandardException
    {
        if( operand instanceof ConstantNode)
            return ((ConstantNode) operand).getValue().getLength();
        return -1;
    }
}


text:
require 'spec_helper'

describe Excon::Connection do
  include_context('test server', :webrick, 'basic.ru', before: :start, after: :stop)
  context 'when an explicit uri is passed' do
    let(:conn) do
      Excon::Connection.new(host: '127.0.0.1',
                                           hostname: '127.0.0.1',
                                           nonblock: false,
                                           port: 9292,
                                           scheme: 'http',
                                           ssl_verify_peer: false)
    end

    describe '.new' do
      it 'returns an instance' do
        expect(conn).to be_instance_of Excon::Connection
      end
    end

    context "when :method is :get and :path is /content-length/100" do
      describe "#request" do
        let(:response) do
          response = conn.request(method: :get, path: '/content-length/100')
        end
        it 'returns an Excon::Response' do
          expect(response).to be_instance_of Excon::Response
        end
        describe Excon::Response do
          describe '#status' do
            it 'returns 200' do
              expect(response.status).to eq 200
            end
          end
        end
      end
    end
    include_examples 'a basic client'
  end
end


text:
package com.lightbend.lagom.internal

import io.netty.channel.{ Channel, ChannelFuture, ChannelFutureListener }
import io.netty.util.concurrent.{ GenericFutureListener, Future => NettyFuture }

import scala.concurrent.{ Future, Promise }

object NettyFutureConverters {

  implicit class ToFuture[T](future: NettyFuture[T]) {
    def toScala: Future[T] = {
      val promise = Promise[T]()
      future.addListener(new GenericFutureListener[NettyFuture[T]] {
        def operationComplete(future: NettyFuture[T]) = {
          if (future.isSuccess) {
            promise.success(future.getNow)
          } else if (future.isCancelled) {
            promise.failure(new RuntimeException("Future cancelled"))
          } else {
            promise.failure(future.cause())
          }
        }
      })
      promise.future
    }
  }

  implicit class ChannelFutureToFuture(future: ChannelFuture) {
    def channelFutureToScala: Future[Channel] = {
      val promise = Promise[Channel]()
      future.addListener(new ChannelFutureListener {
        def operationComplete(future: ChannelFuture) = {
          if (future.isSuccess) {
            promise.success(future.channel())
          } else if (future.isCancelled) {
            promise.failure(new RuntimeException("Future cancelled"))
          } else {
            promise.failure(future.cause())
          }
        }
      })
      promise.future
    }
  }

}


text:
<?php
namespace vendor\project;

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Warning;

class StatusTest extends TestCase
{
    public function testSuccess()
    {
        $this->assertTrue(true);
    }

    public function testFailure()
    {
        $this->assertTrue(false);
    }

    public function testError()
    {
        throw new \RuntimeException;
    }

    public function testIncomplete()
    {
        $this->markTestIncomplete();
    }

    public function testSkipped()
    {
        $this->markTestSkipped();
    }

    public function testRisky()
    {
    }

    public function testWarning()
    {
        throw new Warning;
    }
}


text:
package com.armandgray.shared.navigation;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;

import static junit.framework.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class NavigationActivityTest {

    private ActivityController<NavigationActivity> activityController;
    private NavigationActivity activity;

    @Before
    public void setUp() {

    }

    @Test
    public void stub_test_testing() {
        // TODO Complete Testing
        assertTrue(true);
    }

    @Test
    public void testNavigationModule_ProvideNavigationViewModel() {
        NavigationActivity.NavigationModule module = new NavigationActivity.NavigationModule() {
        };

        // TODO Implement test

        Assert.assertThat(module, is(notNullValue()));
    }

    @After
    public void tearDown() {

    }
}


text:
<package>
	<description brief="print FPS">
		Print frames per second on a sensor_msgs::Image topic
	</description>
	<author>max.schwarz@uni-bonn.de</author>
	<license>BSD</license>

	<depend package="nodelet"/>
	<depend package="sensor_msgs" />
	<export>
		<nodelet plugin="${prefix}/nodelet_plugins.xml" />
	</export>
</package>


text:
export interface UnsyncedAction {
    type: string,
    payload: any,
    meta: {
        effect: any,
        commit: any,
        rollback: any,
    }
}


text:
use core::convert::From;
use core::{cmp, fmt, slice};

// XXX todo(tmfink): create rusty versions
pub use capstone_sys::xcore_insn_group as XcoreInsnGroup;
pub use capstone_sys::xcore_insn as XcoreInsn;
pub use capstone_sys::xcore_reg as XcoreReg;
use capstone_sys::{cs_xcore, cs_xcore_op, xcore_op_mem, xcore_op_type};

pub use crate::arch::arch_builder::xcore::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{RegId, RegIdInt};

/// Contains XCORE-specific details for an instruction
pub struct XcoreInsnDetail<'a>(pub(crate) &'a cs_xcore);

impl_PartialEq_repr_fields!(XcoreInsnDetail<'a> [ 'a ];
    operands
);

/// XCORE operand
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum XcoreOperand {
    /// Register
    Reg(RegId),

    /// Immediate
    Imm(i32),

    /// Memory
    Mem(XcoreOpMem),

    /// Invalid
    Invalid,
}

impl Default for XcoreOperand {
    fn default() -> Self {
        XcoreOperand::Invalid
    }
}

/// XCORE memory operand
#[derive(Debug, Copy, Clone)]
pub struct XcoreOpMem(pub(crate) xcore_op_mem);

impl XcoreOpMem {
    /// Base register
    pub fn base(&self) -> RegId {
        RegId(RegIdInt::from(self.0.base))
    }

    /// Index register
    pub fn index(&self) -> RegId {
        RegId(RegIdInt::from(self.0.index))
    }

    /// Disp value
    pub fn disp(&self) -> i32 {
        self.0.disp
    }

    /// Direct value
    pub fn direct(&self) -> i32 {
        self.0.direct
    }
}

impl_PartialEq_repr_fields!(XcoreOpMem;
    base, index, disp, direct
);

impl cmp::Eq for XcoreOpMem {}

impl<'a> From<&'a cs_xcore_op> for XcoreOperand {
    fn from(insn: &cs_xcore_op) -> XcoreOperand {
        match insn.type_ {
            xcore_op_type::XCORE_OP_REG => {
                XcoreOperand::Reg(RegId(unsafe { insn.__bindgen_anon_1.reg } as RegIdInt))
            }
            xcore_op_type::XCORE_OP_IMM => XcoreOperand::Imm(unsafe { insn.__bindgen_anon_1.imm }),
            xcore_op_type::XCORE_OP_MEM => {
                XcoreOperand::Mem(XcoreOpMem(unsafe { insn.__bindgen_anon_1.mem }))
            }
            xcore_op_type::XCORE_OP_INVALID => XcoreOperand::Invalid,
        }
    }
}

def_arch_details_struct!(
    InsnDetail = XcoreInsnDetail;
    Operand = XcoreOperand;
    OperandIterator = XcoreOperandIterator;
    OperandIteratorLife = XcoreOperandIterator<'a>;
    [ pub struct XcoreOperandIterator<'a>(slice::Iter<'a, cs_xcore_op>); ]
    cs_arch_op = cs_xcore_op;
    cs_arch = cs_xcore;
);


text:
_[www.codever.land/bookmarks/t/ruby-clients](https://www.codever.land/bookmarks/t/ruby-clients)_
---
#### [Net::HTTP](http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/Net/HTTP.html)
_http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/Net/HTTP.html_

Net::HTTP provides a rich library which can be used to build HTTP user-agents.
* **tags**: [rest](../tagged/rest.md), [ruby-clients](../tagged/ruby-clients.md)
---
#### [raml-ruby-client-generator](https://github.com/zlx/raml-ruby-client-generator)
_https://github.com/zlx/raml-ruby-client-generator_

Auto generate API client from a RAML file.
* **tags**: [rest](../tagged/rest.md), [ruby-clients](../tagged/ruby-clients.md)
* :octocat: **[source code](https://github.com/zlx/raml-ruby-client-generator)**
---


text:
package org.apache.hadoop.fs;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.PeerCache;
import org.apache.hadoop.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;

public class TestUnbuffer {
  private static final Log LOG =
      LogFactory.getLog(TestUnbuffer.class.getName());

  /**
   * Test that calling Unbuffer closes sockets.
   */
  @Test
  public void testUnbufferClosesSockets() throws Exception {
    Configuration conf = new Configuration();
    // Set a new ClientContext.  This way, we will have our own PeerCache,
    // rather than sharing one with other unit tests.
    conf.set(DFSConfigKeys.DFS_CLIENT_CONTEXT,
        "testUnbufferClosesSocketsContext");

    // Disable short-circuit reads.  With short-circuit, we wouldn't hold open a
    // TCP socket.
    conf.setBoolean(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY, false);

    // Set a really long socket timeout to avoid test timing issues.
    conf.setLong(DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY,
        100000000L);
    conf.setLong(DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY,
        100000000L);

    MiniDFSCluster cluster = null;
    FSDataInputStream stream = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).build();
      DistributedFileSystem dfs = (DistributedFileSystem)
          FileSystem.newInstance(conf);
      final Path TEST_PATH = new Path("/test1");
      DFSTestUtil.createFile(dfs, TEST_PATH, 128, (short)1, 1);
      stream = dfs.open(TEST_PATH);
      // Read a byte.  This will trigger the creation of a block reader.
      stream.seek(2);
      int b = stream.read();
      Assert.assertTrue(-1 != b);

      // The Peer cache should start off empty.
      PeerCache cache = dfs.getClient().getClientContext().getPeerCache();
      Assert.assertEquals(0, cache.size());

      // Unbuffer should clear the block reader and return the socket to the
      // cache.
      stream.unbuffer();
      stream.seek(2);
      Assert.assertEquals(1, cache.size());
      int b2 = stream.read();
      Assert.assertEquals(b, b2);
    } finally {
      if (stream != null) {
        IOUtils.cleanup(null, stream);
      }
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }

  /**
   * Test opening many files via TCP (not short-circuit).
   *
   * This is practical when using unbuffer, because it reduces the number of
   * sockets and amount of memory that we use.
   */
  @Test
  public void testOpenManyFilesViaTcp() throws Exception {
    final int NUM_OPENS = 500;
    Configuration conf = new Configuration();
    conf.setBoolean(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY, false);
    MiniDFSCluster cluster = null;
    FSDataInputStream[] streams = new FSDataInputStream[NUM_OPENS];
    try {
      cluster = new MiniDFSCluster.Builder(conf).build();
      DistributedFileSystem dfs = cluster.getFileSystem();
      final Path TEST_PATH = new Path("/testFile");
      DFSTestUtil.createFile(dfs, TEST_PATH, 131072, (short)1, 1);

      for (int i = 0; i < NUM_OPENS; i++) {
        streams[i] = dfs.open(TEST_PATH);
        LOG.info("opening file " + i + "...");
        Assert.assertTrue(-1 != streams[i].read());
        streams[i].unbuffer();
      }
    } finally {
      for (FSDataInputStream stream : streams) {
        IOUtils.cleanup(null, stream);
      }
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }
}


text:
module ToSource
  class Emitter
    # Emitter for toplevel constants, classes and modules
    class Toplevel < self

      handle(Rubinius::AST::ToplevelClassName)
      handle(Rubinius::AST::ToplevelModuleName)
      handle(Rubinius::AST::ToplevelConstant)

    private

      # Perform dispatch
      #
      # @return [undefined]
      #
      # @api private
      #
      def dispatch
        emit('::')
        emit(node.name)
      end

    end
  end
end


text:
package io.jasonyang.taskqueue;

/**
 * Created by JasonYang on 2015/7/27.
 */
public interface ResultDelivery {

    public void postResult(Task<?, ?> task, Result<?> result);

    public void postResult(Task<?, ?> task, Result<?> result, Runnable runnable);

    public void postError(Task<?, ?> task, Throwable error);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;

namespace Microsoft.WindowsAzure.Management.Sql
{
    /// <summary>
    /// Contains the operation to create recovery requests for Azure SQL
    /// Databases.
    /// </summary>
    internal partial class RecoverDatabaseOperations : IServiceOperations<SqlManagementClient>, IRecoverDatabaseOperations
    {
        /// <summary>
        /// Initializes a new instance of the RecoverDatabaseOperations class.
        /// </summary>
        /// <param name='client'>
        /// Reference to the service client.
        /// </param>
        internal RecoverDatabaseOperations(SqlManagementClient client)
        {
            this._client = client;
        }

        private SqlManagementClient _client;

        /// <summary>
        /// Gets a reference to the
        /// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient.
        /// </summary>
        public SqlManagementClient Client
        {
            get { return this._client; }
        }

        /// <summary>
        /// Issues a recovery request for an Azure SQL Database.
        /// </summary>
        /// <param name='sourceServerName'>
        /// Required. The name of the Azure SQL Database Server on which the
        /// database was hosted.
        /// </param>
        /// <param name='parameters'>
        /// Required. Additional parameters for the Create Recover Database
        /// Operation request.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// Contains the response to the Create Recover Database Operation
        /// request.
        /// </returns>
        public async Task<RecoverDatabaseOperationCreateResponse> CreateAsync(string sourceServerName, RecoverDatabaseOperationCreateParameters parameters, CancellationToken cancellationToken)
        {
            // Validate
            if (sourceServerName == null)
            {
                throw new ArgumentNullException("sourceServerName");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (parameters.SourceDatabaseName == null)
            {
                throw new ArgumentNullException("parameters.SourceDatabaseName");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("sourceServerName", sourceServerName);
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + "/";
            if (this.Client.Credentials.SubscriptionId != null)
            {
                url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
            }
            url = url + "/services/sqlservers/servers/";
            url = url + Uri.EscapeDataString(sourceServerName);
            url = url + "/recoverdatabaseoperations";
            string baseUrl = this.Client.BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Post;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("x-ms-version", "2012-03-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Serialize Request
                string requestContent = null;
                XDocument requestDoc = new XDocument();

                XElement serviceResourceElement = new XElement(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
                requestDoc.Add(serviceResourceElement);

                XElement sourceDatabaseNameElement = new XElement(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure"));
                sourceDatabaseNameElement.Value = parameters.SourceDatabaseName;
                serviceResourceElement.Add(sourceDatabaseNameElement);

                if (parameters.TargetServerName != null)
                {
                    XElement targetServerNameElement = new XElement(XName.Get("TargetServerName", "http://schemas.microsoft.com/windowsazure"));
                    targetServerNameElement.Value = parameters.TargetServerName;
                    serviceResourceElement.Add(targetServerNameElement);
                }

                if (parameters.TargetDatabaseName != null)
                {
                    XElement targetDatabaseNameElement = new XElement(XName.Get("TargetDatabaseName", "http://schemas.microsoft.com/windowsazure"));
                    targetDatabaseNameElement.Value = parameters.TargetDatabaseName;
                    serviceResourceElement.Add(targetDatabaseNameElement);
                }

                requestContent = requestDoc.ToString();
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    RecoverDatabaseOperationCreateResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.Created)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new RecoverDatabaseOperationCreateResponse();
                        XDocument responseDoc = XDocument.Parse(responseContent);

                        XElement serviceResourceElement2 = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"));
                        if (serviceResourceElement2 != null)
                        {
                            RecoverDatabaseOperation serviceResourceInstance = new RecoverDatabaseOperation();
                            result.Operation = serviceResourceInstance;

                            XElement requestIDElement = serviceResourceElement2.Element(XName.Get("RequestID", "http://schemas.microsoft.com/windowsazure"));
                            if (requestIDElement != null)
                            {
                                string requestIDInstance = requestIDElement.Value;
                                serviceResourceInstance.Id = requestIDInstance;
                            }

                            XElement sourceDatabaseNameElement2 = serviceResourceElement2.Element(XName.Get("SourceDatabaseName", "http://schemas.microsoft.com/windowsazure"));
                            if (sourceDatabaseNameElement2 != null)
                            {
                                string sourceDatabaseNameInstance = sourceDatabaseNameElement2.Value;
                                serviceResourceInstance.SourceDatabaseName = sourceDatabaseNameInstance;
                            }

                            XElement targetServerNameElement2 = serviceResourceElement2.Element(XName.Get("TargetServerName", "http://schemas.microsoft.com/windowsazure"));
                            if (targetServerNameElement2 != null)
                            {
                                string targetServerNameInstance = targetServerNameElement2.Value;
                                serviceResourceInstance.TargetServerName = targetServerNameInstance;
                            }

                            XElement targetDatabaseNameElement2 = serviceResourceElement2.Element(XName.Get("TargetDatabaseName", "http://schemas.microsoft.com/windowsazure"));
                            if (targetDatabaseNameElement2 != null)
                            {
                                string targetDatabaseNameInstance = targetDatabaseNameElement2.Value;
                                serviceResourceInstance.TargetDatabaseName = targetDatabaseNameInstance;
                            }

                            XElement nameElement = serviceResourceElement2.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
                            if (nameElement != null)
                            {
                                string nameInstance = nameElement.Value;
                                serviceResourceInstance.Name = nameInstance;
                            }

                            XElement typeElement = serviceResourceElement2.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure"));
                            if (typeElement != null)
                            {
                                string typeInstance = typeElement.Value;
                                serviceResourceInstance.Type = typeInstance;
                            }

                            XElement stateElement = serviceResourceElement2.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
                            if (stateElement != null)
                            {
                                string stateInstance = stateElement.Value;
                                serviceResourceInstance.State = stateInstance;
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}


text:
<?= Unitkit::t('backend', 'password_reset_title'); ?>

        <?php if( ! isset($models['NewPasswordForm'])): ?>

        		<?= $message; ?>

        <?php else: ?>
            <?php if($models['NewPasswordForm']->hasErrors()): ?>

        		<?= UHtml::errorSummary($models['NewPasswordForm']); ?>

        	<?php endif; ?>
            <form method="POST" class="csrf" action="<?= $this->createUrl($this->id.'/validate', array('code' => $_GET['code'], 'uuid' => $_GET['uuid'])); ?>">
                <div class="form-group <?= $models['NewPasswordForm']->hasErrors('password') ? 'error' : ''; ?>">
                    <?= $models['NewPasswordForm']->getAttributeLabel('password'); ?>
                    <?= UHtml::activePasswordField($models['NewPasswordForm'], 'password', array('class' => 'form-control input-sm')); ?>

                <div class="form-group <?= $models['NewPasswordForm']->hasErrors('repeat_password') ? 'has-error' : ''; ?>">
                    <?= $models['NewPasswordForm']->getAttributeLabel('repeat_password'); ?>
                    <?=UHtml::activePasswordField($models['NewPasswordForm'], 'repeat_password', array('class' => 'form-control input-sm'));?>

                <?=UHtml::button(Unitkit::t('unitkit', 'btn_save'), array('type' => 'submit','class' => 'btn btn-primary'));?>
            </form>
        <?php endif; ?>


text:
var EventEmitter = require('events');

function EventBus(state) {
    this.state = state;
}

EventBus.prototype = Object.create(EventEmitter.prototype);
EventBus.prototype.constructor = EventBus;

EventBus.prototype.trigger = function() {

    if (this.state.fog !== undefined)
        this.emit('fog-up', this.state.fog.id, this.state.fog.cinfo);

    if (this.state.cloud !== undefined)
        this.emit('cloud-up', this.state.cloud.id, this.state.cloud.cinfo);
}

EventBus.prototype.emitFogUp = function(id, cinfo) {

    this.state.fog = {id: id, cinfo: cinfo};
    this.emit('fog-up', id, cinfo);
}

EventBus.prototype.emitFogDown = function(id, info) {

    if (this.state.fog === undefined || this.state.fog.id !== id)
        return;

    this.emit('fog-down', id, this.state.fog.cinfo);
    this.state.fog = undefined;
}

EventBus.prototype.emitCloudUp = function(id, cinfo) {

    this.state.cloud = {id: id, cinfo: cinfo};
    this.emit('cloud-up', id, cinfo);
}

EventBus.prototype.dataUp = function(host, port) {

    this.state.data = {host: host, port: port};
    this.emit('data-up', {host: host, port: port});
}

EventBus.prototype.dataDown = function() {

    if (this.state.data === undefined)
        return;
    this.emit('data-down');
}

EventBus.prototype.emitCloudDown = function(id, info) {

    if (this.state.cloud === undefined || this.state.cloud.id !== id)
        return;

    this.emit('cloud-down', id, this.state.cloud.cinfo);
    this.state.cloud = undefined;
}

// These are specialized ebus events to handle the worker side
EventBus.prototype.fogDataUp = function(info) {

    this.state.fogdata = info;
    this.emit('fog-data-up', info);
}

EventBus.prototype.cloudDataUp = function(info) {

    this.state.clouddata = info;
    this.emit('cloud-data-up', info);
}

EventBus.prototype.fogDataDown = function() {

    this.state.fogdata = undefined;
    this.emit('fog-data-down');
}

EventBus.prototype.cloudDataDown = function() {

    this.state.clouddata = undefined;
    this.emit('cloud-data-down');
}

module.exports = new EventBus({cloud: undefined, fog: undefined, data: undefined});


text:
/* */
"use strict";
var Observable_1 = require('../../Observable');
var observeOn_1 = require('../../operator/observeOn');
Observable_1.Observable.prototype.observeOn = observeOn_1.observeOn;


text:
package org.apache.axis2.wsdl.codegen.extension;

import org.apache.axis2.wsdl.codegen.CodeGenConfiguration;
import org.apache.axis2.wsdl.codegen.CodeGenerationException;
import org.apache.axis2.wsdl.databinding.CDefaultTypeMapper;
import org.apache.axis2.wsdl.databinding.DefaultTypeMapper;
import org.apache.axis2.wsdl.databinding.TypeMapper;
import org.apache.axis2.wsdl.databinding.CPPDefaultTypeMapper;
import org.apache.axis2.wsdl.i18n.CodegenMessages;

public class DefaultDatabindingExtension extends AbstractDBProcessingExtension {

    public void engage(CodeGenConfiguration configuration) throws CodeGenerationException {
        TypeMapper mapper = configuration.getTypeMapper();
        if (testFallThrough(configuration.getDatabindingType())) {
            //if it's fall through for the default databinding extension and a mapper has
            //not yet being set, then there's a problem.
            //Hence check the mapper status here

            if (mapper == null) {
                //this shouldn't happen
                throw new CodeGenerationException(
                        CodegenMessages.getMessage("extension.noProperDatabinding"));
            }
            return;
        }
        //the mapper has not been populated yet. since this extension is
        //registered for -d none, we have to generate a new type mapper
        //that serves only the default types
        if (mapper == null) {
            if (configuration.getOutputLanguage() != null &&
                    !configuration.getOutputLanguage().trim().equals("") &&
                    configuration.getOutputLanguage().toLowerCase().equals("c")) {
                configuration.setTypeMapper(new CDefaultTypeMapper());

            }else if (configuration.getOutputLanguage() != null &&
                    !configuration.getOutputLanguage().trim().equals("") &&
                    configuration.getOutputLanguage().toLowerCase().equals("cpp")) {
                configuration.setTypeMapper(new CPPDefaultTypeMapper());

            } else {
                configuration.setTypeMapper(new DefaultTypeMapper());
            }

        }
    }
}


text:
FactoryGirl.define do
  sequence :user_authentication_token do |n|
    "xxxx#{Time.now.to_i}#{rand(1000)}#{n}xxxxxxxxxxxxx"
  end

  factory :user, class: Spree.user_class do
    email { generate(:random_email) }
    login { email }
    password 'secret'
    password_confirmation { password }
    authentication_token { generate(:user_authentication_token) } if Spree.user_class.attribute_method? :authentication_token

    factory :admin_user do
      spree_roles { [Spree::Role.find_by(name: 'admin') || create(:role, name: 'admin')] }
    end

    factory :user_with_addresses, aliases: [:user_with_addreses] do
      ship_address
      bill_address
    end
  end
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\SalesSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'sale_record') ?>

    <?= $form->field($model, 'buyer_id') ?>

    <?= $form->field($model, 'buyer_name') ?>

    <?= $form->field($model, 'buyer_phone') ?>

    <?php // echo $form->field($model, 'buyer_email') ?>

    <?php // echo $form->field($model, 'buyer_addr_one') ?>

    <?php // echo $form->field($model, 'buyer_addr_two') ?>

    <?php // echo $form->field($model, 'buyer_addr_city') ?>

    <?php // echo $form->field($model, 'buyer_addr_state') ?>

    <?php // echo $form->field($model, 'buyer_addr_post') ?>

    <?php // echo $form->field($model, 'buyer_addr_country') ?>

    <?php // echo $form->field($model, 'item_number') ?>

    <?php // echo $form->field($model, 'item_title') ?>

    <?php // echo $form->field($model, 'sku') ?>

    <?php // echo $form->field($model, 'qty') ?>

    <?php // echo $form->field($model, 'paypal_trans_id') ?>

    <?php // echo $form->field($model, 'ebay_trans_id') ?>

    <?php // echo $form->field($model, 'post_addr_one') ?>

    <?php // echo $form->field($model, 'post_addr_two') ?>

    <?php // echo $form->field($model, 'post_addr_city') ?>

    <?php // echo $form->field($model, 'post_addr_state') ?>

    <?php // echo $form->field($model, 'post_addr_post') ?>

    <?php // echo $form->field($model, 'post_addr_country') ?>

    <?php // echo $form->field($model, 'ebay_id') ?>

    <?php // echo $form->field($model, 'sale_id') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
module Puppet::Parser::Functions
  newfunction(:deep_merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args|
    Recursively merges two or more hashes together and returns the resulting hash.

    For example:

        $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
        $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
        $merged_hash = deep_merge($hash1, $hash2)
        # The resulting hash is equivalent to:
        # $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }

    When there is a duplicate key that is a hash, they are recursively merged.
    When there is a duplicate key that is not a hash, the key in the rightmost hash will "win."

    ENDHEREDOC

    if args.length < 2
      raise Puppet::ParseError, ("deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)")
    end

    deep_merge = Proc.new do |hash1,hash2|
      hash1.merge!(hash2) do |key,old_value,new_value|
        if old_value.is_a?(Hash) && new_value.is_a?(Hash)
          deep_merge.call(old_value, new_value)
        else
          new_value
        end
      end
    end

    result = Hash.new
    args.each do |arg|
      next if arg.is_a? String and arg.empty? # empty string is synonym for puppet's undef
      # If the argument was not a hash, skip it.
      unless arg.is_a?(Hash)
        raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments"
      end

      deep_merge.call(result, arg)
    end
    return( result )
  end
end


text:
package com.swfarm.biz.ebay.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.ebay.dto.SearchCategoryCommissionRatesCriteria;
import com.swfarm.pub.framework.OrderItem;

public class SearchCategoryCommissionRatesController extends AbstractController {

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		SearchCategoryCommissionRatesCriteria criteria = new SearchCategoryCommissionRatesCriteria();

		String ebaySite = req.getParameter("ebaySite");
		if (StringUtils.isNotEmpty(ebaySite)) {
			criteria.setEbaySite(ebaySite);
		}
		String categoryName = req.getParameter("categoryName");
		if (StringUtils.isNotEmpty(categoryName)) {
			criteria.setCategoryName(categoryName);
		}
		String categoryDisplayName = req.getParameter("categoryDisplayName");
		if (StringUtils.isNotEmpty(categoryDisplayName)) {
			criteria.setCategoryDisplayName(categoryDisplayName);
		}

		String[] orderItemInfos = req.getParameterValues("orderItem");
		if (orderItemInfos != null && orderItemInfos.length > 0) {
			for (int i = 0; i < orderItemInfos.length; i++) {
				String[] orderItemInfo = StringUtils.split(orderItemInfos[i],
						"|");
				OrderItem orderItem = new OrderItem();
				orderItem.setField(orderItemInfo[0]);
				orderItem.setStatus(orderItemInfo[1]);
				orderItem.setIndex(new Integer(orderItemInfo[2]));
				criteria.addOrderItem(orderItem);
			}
		}

		Map dataMap = new HashMap();
		if (!(criteria.getEbaySite() == null
				&& criteria.getCategoryName() == null
				&& criteria.getCategoryDisplayName() == null && CollectionUtils
					.isEmpty(criteria.getOrderItemList()))) {
			dataMap.put("criteria", criteria);
		}
		return new ModelAndView("forward:/ebay/categorycommissionrates.shtml",
				dataMap);
	}
}


text:
package com.flightstats.flex.domain.fids;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.flightstats.flex.domain.Appendix;
import com.flightstats.flex.domain.flighttrack.FlightTrack;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.Value;

import java.util.List;

@Value
@Builder
@AllArgsConstructor
@NoArgsConstructor(force = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class FidsResponse {
    public List<FidsEntry> fidsData;
}


text:
  //==================================================
  //
  //
  //
  //  THOSE TEST ARE **REALLY** IMPORTANT SO IF SOME
  //  OF THEM IS BROKEN, PLEASE, TAKE CARE OF IT
  //
  //  Visualization model specs
  //
  //==================================================

  describe("Visualization model", function() {
    var vis, table, table_server, map_id;

    beforeEach(function() {

      cdb.admin.CartoDBLayer.updateCartoCss = function() {};

      map_id = 96;

      // Visualization model
      vis = new cdb.admin.Visualization({
        map_id:           map_id,
        active_layer_id:  null,
        name:             "test_table",
        description:      "Visualization description",
        tags:             ["jamon","probando","test"],
        privacy:          "PUBLIC",
        updated_at:       "2013-03-04T18:09:34+01:00",
        type:             "table",
        permission: {
          owner: {
            username: 'rambo',
          },
          acl: [
          {
            type: 'user',
            access: 'r',
            entity:{ usernamae: 'charly'}
          }
          ]
        }
      });
    });

    describe('permission', function() {
      it("should load permissions", function() {
        expect(vis.permission.owner.get('username')).toEqual('rambo');
        expect(vis.permission.acl.length).toEqual(1);
      });
    });

    /* defaults & config */
    describe('> defaults & config', function() {

      it("should define a number of ITEMS_PER_PAGE", function() {
        expect(cdb.admin.Visualizations.prototype._ITEMS_PER_PAGE).toBeDefined();
      });

      it("should define a number of PREVIEW_ITEMS_PER_PAGE", function() {
        expect(cdb.admin.Visualizations.prototype._PREVIEW_ITEMS_PER_PAGE).toBeDefined();
      });

      it("should setup map bindings by default", function() {
        expect(vis.get("bindMap")).toBeTruthy();
        expect(vis.map.get("id")).toEqual(map_id);
      });

      it("shouldn't setup map bindings when bindMap is false", function() {

        vis = new cdb.admin.Visualization({
          map_id:  map_id,
          bindMap: false
        });

        expect(vis.get("bindMap")).toBeFalsy();
        expect(vis.map.get("id")).toEqual(undefined);

      });

    });

    describe('> related tables', function() {

      it("should generate related_tables collection if related_tables attribute exists", function() {
        var new_vis = new cdb.admin.Visualization({
          map_id:           map_id,
          active_layer_id:  null,
          name:             "test_table",
          description:      "Visualization description",
          tags:             ["jamon","probando","test"],
          privacy:          "PUBLIC",
          updated_at:       "2013-03-04T18:09:34+01:00",
          type:             "derived",
          related_tables:   [{ id: "hello", "table_name": "hello", "privacy": "PRIVATE" }]
        });

        expect(new_vis.related_tables).toBeDefined();
        expect(new_vis.related_tables.size()).toBe(1);
      });

      it("shouldn't generate related_tables collection if visualization is a table type", function() {
        var new_vis = new cdb.admin.Visualization({
          map_id:           map_id,
          active_layer_id:  null,
          name:             "test_table",
          description:      "Visualization description",
          tags:             ["jamon","probando","test"],
          privacy:          "PUBLIC",
          updated_at:       "2013-03-04T18:09:34+01:00",
          type:             "table",
          related_tables:   [{ id: "hello", "table_name": "hello", "privacy": "PRIVATE" }]
        });

        expect(new_vis.related_tables).not.toBeDefined();
      });

      it("should generate related_tables collection if it is required by the user", function() {
        // Visualization model
        var new_vis = new cdb.admin.Visualization({
          map_id:           map_id,
          active_layer_id:  null,
          name:             "test_table",
          description:      "Visualization description",
          tags:             ["jamon","probando","test"],
          privacy:          "PUBLIC",
          updated_at:       "2013-03-04T18:09:34+01:00",
          type:             "derived",
          id:               5
        });

        var server = sinon.fakeServer.create();
        new_vis.getRelatedTables();

        server.respondWith('/api/v1/viz/5', [200, { "Content-Type": "application/json" }, '{ "related_tables": [{ "table_name": "jamon", "privacy": "PRIVATE" }] }']);
        server.respond();

        expect(new_vis.related_tables).toBeDefined();
        expect(new_vis.related_tables.size()).toBe(1);
      });

      it("related_tables should be regenrated when a new layer is added and saved", function() {
        spyOn(vis, 'getRelatedTables');
        var layer = new cdb.geo.MapLayer()
        vis.map.layers.add(layer);
        expect(vis.getRelatedTables).not.toHaveBeenCalled();
        layer.set('id', 1);
        expect(vis.getRelatedTables).toHaveBeenCalledWith(null, { force: true });
      });

      it("related_tables should be regenrated when a layer is removed", function() {
        var layer = new cdb.geo.MapLayer()
        vis.map.layers.add(layer);
        spyOn(vis, 'getRelatedTables');
        vis.map.layers.remove(layer);
        expect(vis.getRelatedTables).toHaveBeenCalledWith(null, { force: true });
      });
    });

    /* map_id specs */
    describe('> map_id', function() {

      it("should set bindMap to false for all visualizations on parse/fetch", function() {
        var visualizations = new cdb.admin.Visualizations({ type: "derived" });
        var v = visualizations.parse({total_entries: 1, visualizations: [{ id: 1 }]});
        expect(v[0].bindMap).toBeFalsy();

      });

    });

    /* isVisualization spec */
    describe('> isVisualization', function() {
      var cartodb_layer;

      beforeEach(function() {
        cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'});

        vis.map.layers.reset([
          new cdb.geo.MapLayer(),
          cartodb_layer
        ]);
      });

      it("should return if the model is a visualization or a table", function() {
        expect(vis.isVisualization()).toBeFalsy();
        vis.set({
          "type": "derived"
        });

        vis.map.layers.reset([
          new cdb.geo.MapLayer()
        ]);

        expect(vis.isVisualization()).toBeTruthy();
      });
    });

    /* transform to visualization specs */
    describe('> transform to visualization', function() {
      var cartodb_layer, map_payload;

      beforeEach(function() {
        cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'});
        map_payload = {
            id: 69,
            bounding_box_ne: "[]",
            bounding_box_sw: "[]",
            view_bounds_ne: "[]",
            view_bounds_sw: "[]",
            center: "[]"
        };

        vis.map.layers.reset([
          new cdb.geo.MapLayer(),
          cartodb_layer
        ]);
      });

      it("should copy correctly", function() {
        var c = vis.copy();
        expect(c.get('source_visualization_id')).toEqual(vis.id);
      });

      it("should change to", function() {
        vis.changeTo(new cdb.admin.Visualization({
          map_id: 'raboquetecomes',
          id: 'unzupo'
        }));
        expect(vis.map.id).toEqual("raboquetecomes");
        expect(vis.id).toEqual("unzupo");
      })
    });

    /* name specs */
    describe('> name', function() {
      var cartodb_layer;

      beforeEach(function() {
        cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'});

        vis.map.layers.reset([
          new cdb.geo.MapLayer(),
          cartodb_layer
        ]);
      });

      // ALREADY DONE IN THE SERVER SIDE
      //
      // it("should set table layer name if there is only one data layer <==> table", function() {
      //   vis.set({
      //     'derived': false
      //   },{
      //     silent: true
      //   });

      //   cartodb_layer.table.sync = function(a, b, opts) {
      //     opts.success({
      //       name: 'this_is_a_name'
      //     }, 200);
      //   }

      //   vis.map.layers.each(function(l){
      //     l.updateCartoCss = function() {};
      //   });

      //   vis.set('name', 'this is a name');
      //   expect(cartodb_layer.get('table_name')).toBe('this_is_a_name');
      //   expect(vis.get('name')).toBe('this_is_a_name');
      // });

      // it("should set name of the table when the visualization name changes", function() {
      //   vis.set({ 'type': 'table' },{ silent: true });
      //   vis.set('name', 'ola_ke_ase');
      //   cartodb_layer.table.sync = function(a, b, opts) {
      //     opts.success({'name': 'ola_ke_ase'}, 200);
      //   }
      //   expect(cartodb_layer.table.get('name')).toEqual('ola_ke_ase');
      // });

      it("should fetch cartodb layer if the table name has changed", function() {
        vis.set({
          'type': 'table'
        },{
          silent: true
        });

        var called = false;

        cartodb_layer.fetch = function(a, b, opts) {
          called = true;
        }

        vis.map.layers.each(function(l){
          l.updateCartoCss = function() {};
        });

        vis.set('name', 'a visualization name');
        expect(called).toBeTruthy();
      });

      // THIS IS NOT HAPPENING ANYMORE, IF FAILS
      // SET ATTRIBUTE FUNCTION IS NOT BEING CALLED
      // AND, OF COURSE, DONE IN THE SERVER SIDE :)

      // it("shouldn't set table layer name if sync fails", function() {
      //   vis.set({
      //     'type': 'table'
      //   },{
      //     silent: true
      //   });

      //   cartodb_layer.table.sync = function(a, b, opts) {
      //     opts.error({}, 404);
      //   }

      //   vis.map.layers.each(function(l){
      //     l.updateCartoCss = function() {};
      //   });

      //   vis.set('name', 'a visualization name');
      //   expect(cartodb_layer.get('table_name')).toBe('test_table');
      //   expect(vis.get('name')).toBe('test_table');
      // });

      it("shouldn't set name if it is a visualization", function() {
        vis.map.layers.add(new cdb.admin.CartoDBLayer({ table_name: 'jam'}));

        vis.set({
          'type': 'derived'
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.error({}, 404);
        }

        spyOn(cartodb_layer.table, 'sync');

        vis.set('name', 'another name');

        expect(vis.map.getLayerAt(1).table.get('name')).not.toBe('another name');
        expect(vis.map.getLayerAt(2).table.get('name')).not.toBe('another name');
        expect(cartodb_layer.table.sync).not.toHaveBeenCalled();
      });
    });

    /* description specs */
    describe('> description', function() {
      var cartodb_layer;

      beforeEach(function() {
        cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'});

        vis.map.layers.reset([
          new cdb.geo.MapLayer(),
          cartodb_layer
        ]);
      });

      it("shouldn't set description layer name in any case", function() {
        cartodb_layer.table.set('description', 'hey description');
        vis.set({
          'type': 'table'
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.success({
            description: 'this is a description'
          }, 200);
        }

        vis.set('description', 'this is a description');
        expect(vis.map.getLayerAt(1).table.get('description')).not.toBe('this is a description');
      });

      it("shouldn't set table layer description if sync fails", function() {
        cartodb_layer.table.set('description', 'Visualization description');
        vis.set('type', 'table');

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.error({}, 404);
        }

        vis.set('description', 'this is a description');
        expect(vis.map.getLayerAt(1).table.get('description')).toBe('Visualization description');
        expect(vis.get('description')).toBe('this is a description');
      });

      it("shouldn't set itself if there are at least 2 data layers", function() {
        vis.map.layers.add(new cdb.admin.CartoDBLayer({ table_name: 'test_table'}));

        vis.map.layers.each(function(l){
          if (l.table)
            l.table.set('description', 'desc example');
        });

        vis.set({
          'type': 'derived'
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.error({}, 404);
        }

        spyOn(cartodb_layer.table, 'sync');

        vis.set('description', 'another world');

        expect(vis.map.getLayerAt(1).table.get('description')).not.toBe('another world');
        expect(vis.map.getLayerAt(2).table.get('description')).not.toBe('another world');
        expect(cartodb_layer.table.sync).not.toHaveBeenCalled();
      });
    });

    /* tags specs */
    describe('> tags', function() {
      var cartodb_layer;

      beforeEach(function() {
        cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'});

        vis.map.layers.reset([
          new cdb.geo.MapLayer(),
          cartodb_layer
        ]);
      });

      it("shouldn't set table layer tags if there is only one data layer <==> table", function() {
        cartodb_layer.table.set('tags', ['zurullo']);
        vis.set({
          'type': 'table'
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.success({
            tags: ['zurullo']
          }, 200);
        }

        vis.set('tags', ['zurullo']);
        expect(vis.map.getLayerAt(1).table.get('tags').length).toBe(1);
        expect(vis.map.getLayerAt(1).table.get('tags')[0]).toBe('zurullo');
      });

      it("shouldn't set table layer tags if sync fails", function() {
        cartodb_layer.table.set('tags', ['eing']);
        vis.set({
          'type': 'table'
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.error({}, 404);
        }

        vis.set('tags', ['esto', 'va', 'a', 'fallar']);

        expect(vis.map.getLayerAt(1).table.get('tags').length).toBe(1);
        expect(vis.map.getLayerAt(1).table.get('tags').toString()).toBe('eing');
        expect(vis.get('tags').length).toBe(4);
        expect(vis.get('tags').toString()).toBe("esto,va,a,fallar");
      });

      it("shouldn't set table layers tags if there are at least 2 data layers", function() {
        vis.map.layers.add(new cdb.admin.CartoDBLayer({ table_name: 'test_table'}));

        vis.map.layers.each(function(l){
          if (l.table)
            l.table.set('tags', ['i', 'love', 'this', 'game']);
        });

        vis.set({
          "type": "derived"
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.error({}, 404);
        }

        spyOn(cartodb_layer.table, 'sync');

        vis.set('tags', ['ciruelo']);

        expect(vis.map.getLayerAt(1).table.get('tags').length).not.toBe(1);
        expect(vis.map.getLayerAt(2).table.get('tags').length).not.toBe(1);
        expect(cartodb_layer.table.sync).not.toHaveBeenCalled();
      });
    });

    /* privacy specs */
    describe('> privacy', function() {
      var cartodb_layer;

      beforeEach(function() {
        cartodb_layer = new cdb.admin.CartoDBLayer({ table_name: 'test_table'});

        vis.map.layers.reset([
          new cdb.geo.MapLayer(),
          cartodb_layer
        ]);
      });

      // ALREADY DONE IN THE SERVER SIDE

      // it("should set table layer privacy if there is only one data layer <==> table", function() {
      //   cartodb_layer.table.set('privacy', 'PUBLIC');
      //   vis.set({
      //     'derived': false
      //   },{
      //     silent: true
      //   });

      //   cartodb_layer.table.sync = function(a, b, opts) {
      //     opts.success({
      //       privacy: 'PRIVATE'
      //     }, 200);
      //   }

      //   vis.set('privacy', 'PRIVATE');
      //   expect(cartodb_layer.table.get('privacy').toLowerCase()).toBe('private');
      // });

      it("should fetch cartodb layer if the table PRIVACY has changed", function() {
        vis.set({
          'type': 'table'
        },{
          silent: true
        });

        var called = false;

        cartodb_layer.fetch = function(a, b, opts) {
          called = true;
        }

        vis.map.layers.each(function(l){
          l.updateCartoCss = function() {};
        });

        vis.set('privacy', 'PRIVATE');
        expect(called).toBeTruthy();
      });

      // THIS IS NOT HAPPENING ANYMORE, IF FAILS
      // SET ATTRIBUTE FUNCTION IS NOT BEING CALLED
      // AND, OF COURSE, DONE IN THE SERVER SIDE :)

      // it("shouldn't set table layer privacy if sync fails", function() {
      //   cartodb_layer.table.set('privacy', 'PUBLIC');
      //   vis.set({
      //     'derived': false
      //   },{
      //     silent: true
      //   });

      //   cartodb_layer.table.sync = function(a, b, opts) {
      //     opts.error({}, 404);
      //   }

      //   vis.set('privacy', 'PRIVATE');

      //   expect(cartodb_layer.table.get('privacy').toLowerCase()).toBe('public');
      //   expect(vis.get('privacy').toLowerCase()).toBe('public');
      // });

      it("shouldn't set table layers privacy if there are at least 2 data layers", function() {
        vis.map.layers.add(new cdb.admin.CartoDBLayer({ table_name: 'test_table'}));

        vis.map.layers.each(function(l){
          if (l.table)
            l.table.set('privacy', 'PUBLIC');
        });

        vis.set({
          'type': 'derived'
        },{
          silent: true
        });

        cartodb_layer.table.sync = function(a, b, opts) {
          opts.error({}, 404);
        }

        spyOn(cartodb_layer.table, 'sync');

        vis.set('privacy', 'PRIVATE');

        expect(vis.map.getLayerAt(1).table.get('privacy').toLowerCase()).toBe('public');
        expect(vis.get('privacy').toLowerCase()).toBe('private');
        expect(cartodb_layer.table.sync).not.toHaveBeenCalled();
      });

    });

  });


text:
code: true
type: page
title: count
description: Count subscribers for a subscription room
---

# count

Returns the number of other connections sharing the same subscription.

## Arguments

```js
count(roomId, [options]);
```

| Arguments | Type              | Description          |
| --------- | ----------------- | -------------------- |
| `roomId`  |
string
 | Subscription room ID |
| `options` |
object
 | Query options        |

### options

Additional query options

| Option     | Type
(default)              | Description                                                                                |
| ---------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `queuable` |
boolean

(`true`) | Make this request queuable or not                                                                                |
| [`timeout`](/sdk/7/core-classes/kuzzle/query#timeout)  |
number

          | Time (in ms) during which a request will still be waited to be resolved. Set it `-1` if you want to wait indefinitely |

## Resolves

Resolves to a number representing active connections using the same provided subscription room.

## Usage

<<< ./snippets/count.js


text:
#include <uc/ucdb.h>

/*
  Method methods which are inherited by the concrete implementations of
  the DatabaseInterface, like SQLiteDatabase and MySQLDatabase.
 */

namespace JAD {

  bool DatabaseInterface::start_transaction(void)
  {
    return sql_exec("START TRANSACTION");
  }

  bool DatabaseInterface::commit(void)
  {
    return sql_exec("COMMIT");
  }

  bool DatabaseInterface::rollback(void)
  {
    return sql_exec("ROLLBACK");
  }
  UniversalContainer DatabaseInterface::get_db_info(void)
  {
    return db_info;
  }
}// end namespace


text:
package com.ajlopez.ajtalk.compiler.ast;

public class IdNode extends Node {
	private String name;

	public IdNode(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}
}


text:
<?php

namespace Sparky7\Worker;

use Closure;

/**
 * Consumer.
 */
class Consumer
{
    private $Protocol;

    /**
     * Construct.
     *
     * @param Protocol $Protocol Protocol Object
     */
    final public function __construct(Protocol $Protocol)
    {
        $this->Protocol = $Protocol;
    }

    /**
     * Consume queue.
     *
     * @param Closure $Closure Callback
     */
    final public function consume(Closure $Closure)
    {
        return $this->Protocol->consume($Closure);
    }

    /**
     * Stop accepting new messages.
     *
     * @return bool
     */
    final public function wait()
    {
        $this->Protocol->wait();
    }

    /**
     * Acknowledge message.
     *
     * @param string $tag Message Id
     *
     * @return bool
     */
    final public function acknowledge($tag)
    {
        return $this->Protocol->acknowledge($tag);
    }

    /**
     * Reject message.
     *
     * @param string $tag     Message Id
     * @param bool   $requeue Requeue message
     *
     * @return bool
     */
    final public function reject($tag, $requeue = false)
    {
        return $this->Protocol->reject($tag, $requeue);
    }
}


text:
package es.tid.fiware.iot.ac.util;

import es.tid.fiware.iot.ac.rs.Tenant;
import es.tid.fiware.iot.ac.rs.Correlator;
import io.dropwizard.hibernate.UnitOfWork;
import java.io.IOException;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import java.util.Arrays;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.Level;

@Path("/admin/log")
@Produces(MediaType.APPLICATION_XML)
public class LogsEndpoint {

    private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(LogsEndpoint.class);

    private static String[] ValidLogLevels = {
        "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL"
    };

    public LogsEndpoint() {

    }

    /**
     * Get LogLevel
     *
     * @return logLevel
     */

    @GET
    @UnitOfWork
    public Response getLogLevel(@Tenant String tenant,
                                @Correlator String correlator
                                ) {
        // Get current logLevel
        Logger root_LOGGER = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        Level level = root_LOGGER.getLevel();
        LOGGER.debug("get current log level: " + level.toString());
        return Response.status(200).entity(level.toString()).build();
    }

    /**
     * Change LogLevel
     *
     * @param logLevel
     * @return
     */

    @PUT
    @UnitOfWork
    public Response updateLogLevel(@Tenant String tenant,
                                   @Correlator String correlator,
                                   @QueryParam("logLevel") String logLevel,
                                   @QueryParam("level") String level
                                   ) {
        // Allow level as well as logLevel
        if (level != null) {
            logLevel = level;
        }

        // Check logLevel proposed
        if (logLevel != null) {
            if (Arrays.asList(ValidLogLevels).contains(logLevel.toUpperCase())) {
                String newLogLevel = logLevel.toUpperCase();
                LOGGER.debug("trying to change log level changed to " + newLogLevel);

                Logger root_LOGGER = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
                root_LOGGER.setLevel(Level.toLevel(newLogLevel));
                LOGGER.info("Keypass log level changed to " + newLogLevel);
                return Response.status(200).build();
            } else {
                LOGGER.info("invalid log level " + logLevel);
                return Response.status(400).entity("invalid log level").build();
            }
        } else {
            LOGGER.info("log level missing " + logLevel);
            return Response.status(400).entity("log level missing").build();
        }

    }

}


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe "cve_2013_1857" do

  before :each do
    @sanitizer = HTML::WhiteListSanitizer.new
  end
  it "test_x03a" do
    assert_sanitized %(), ""
    assert_sanitized %(), ""
    assert_sanitized %(), %()
    assert_sanitized %(), ""
    assert_sanitized %(), ""
    assert_sanitized %(), %()
  end

  def assert_sanitized(input, expected)
    if input
      assert_dom_equal expected, @sanitizer.sanitize(input)
    else
      assert_nil @sanitizer.sanitize(input)
    end
  end
end


text:
require 'spec_helper'

describe Stats::ArenaController do

end


text:
"""
Contains the protocols, commands, and client factory needed for the Server
and Portal to communicate with each other, letting Portal work as a proxy.
Both sides use this same protocol.

The separation works like this:

Portal - (AMP client) handles protocols. It contains a list of connected
         sessions in a dictionary for identifying the respective player
         connected. If it looses the AMP connection it will automatically
         try to reconnect.

Server - (AMP server) Handles all mud operations. The server holds its own list
         of sessions tied to player objects. This is synced against the portal
         at startup and when a session connects/disconnects

"""

# imports needed on both server and portal side
import os
from time import time
from collections import defaultdict
try:
    import cPickle as pickle
except ImportError:
    import pickle
from twisted.protocols import amp
from twisted.internet import protocol, task
from twisted.internet.defer import Deferred
from evennia.utils.utils import to_str, variable_from_module

# communication bits

PCONN = chr(1)        # portal session connect
PDISCONN = chr(2)     # portal session disconnect
PSYNC = chr(3)        # portal session sync
SLOGIN = chr(4)       # server session login
SDISCONN = chr(5)     # server session disconnect
SDISCONNALL = chr(6)  # server session disconnect all
SSHUTD = chr(7)       # server shutdown
SSYNC = chr(8)        # server session sync
SCONN = chr(9)        # server creating new connection (for irc/imc2 bots etc)
PCONNSYNC = chr(10)   # portal post-syncing a session
AMP_MAXLEN = 65535    # max allowed data length in AMP protocol (cannot be changed)

BATCH_RATE = 500    # max commands/sec before switching to batch-sending
BATCH_TIMEOUT = 1.0 # how often to poll to empty batch queue, in seconds

# buffers
_SENDBATCH = defaultdict(list)
_MSGBUFFER = defaultdict(list)

def get_restart_mode(restart_file):
    """
    Parse the server/portal restart status
    """
    if os.path.exists(restart_file):
        flag = open(restart_file, 'r').read()
        return flag == "True"
    return False

class AmpServerFactory(protocol.ServerFactory):
    """
    This factory creates the Server as a new AMPProtocol instance for accepting
    connections from the Portal.
    """
    def __init__(self, server):
        """
        server: The Evennia server service instance
        protocol: The protocol the factory creates instances of.
        """
        self.server = server
        self.protocol = AMPProtocol

    def buildProtocol(self, addr):
        """
        Start a new connection, and store it on the service object
        """
        #print "Evennia Server connected to Portal at %s." % addr
        self.server.amp_protocol = AMPProtocol()
        self.server.amp_protocol.factory = self
        return self.server.amp_protocol

class AmpClientFactory(protocol.ReconnectingClientFactory):
    """
    This factory creates an instance of the Portal, an AMPProtocol
    instances to use to connect
    """
    # Initial reconnect delay in seconds.
    initialDelay = 1
    factor = 1.5
    maxDelay = 1

    def __init__(self, portal):
        self.portal = portal
        self.protocol = AMPProtocol

    def startedConnecting(self, connector):
        """
        Called when starting to try to connect to the MUD server.
        """
        pass
        #print 'AMP started to connect:', connector

    def buildProtocol(self, addr):
        """
        Creates an AMPProtocol instance when connecting to the server.
        """
        #print "Portal connected to Evennia server at %s." % addr
        self.resetDelay()
        self.portal.amp_protocol = AMPProtocol()
        self.portal.amp_protocol.factory = self
        return self.portal.amp_protocol

    def clientConnectionLost(self, connector, reason):
        """
        Called when the AMP connection to the MUD server is lost.
        """
        if hasattr(self, "server_restart_mode"):
            self.maxDelay = 1
        else:
            # Don't translate this; avoid loading django on portal side.
            self.maxDelay = 10
            self.portal.sessions.announce_all(" ... Portal lost connection to Server.")
        protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason)

    def clientConnectionFailed(self, connector, reason):
        """
        Called when an AMP connection attempt to the MUD server fails.
        """
        if hasattr(self, "server_restart_mode"):
            self.maxDelay = 1
        else:
            self.maxDelay = 10
        self.portal.sessions.announce_all(" ...")
        protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

# AMP Communication Command types

class MsgPortal2Server(amp.Command):
    """
    Message portal -> server
    """
    key = "MsgPortal2Server"
    arguments = [('hashid', amp.String()),
                 ('data', amp.String()),
                 ('ipart', amp.Integer()),
                 ('nparts', amp.Integer())]
    errors = [(Exception, 'EXCEPTION')]
    response = []

class MsgServer2Portal(amp.Command):
    """
    Message server -> portal
    """
    key = "MsgServer2Portal"
    arguments = [('hashid', amp.String()),
                 ('data', amp.String()),
                 ('ipart', amp.Integer()),
                 ('nparts', amp.Integer())]
    errors = [(Exception, 'EXCEPTION')]
    response = []

class ServerAdmin(amp.Command):
    """
    Portal -> Server

    Sent when the portal needs to perform admin
     operations on the server, such as when a new
     session connects or resyncs
    """
    key = "ServerAdmin"
    arguments = [('hashid', amp.String()),
                 ('data', amp.String()),
                 ('ipart', amp.Integer()),
                 ('nparts', amp.Integer())]
    errors = [(Exception, 'EXCEPTION')]
    response = []

class PortalAdmin(amp.Command):
    """
    Server -> Portal

    Sent when the server needs to perform admin
     operations on the portal.
    """
    key = "PortalAdmin"
    arguments = [('hashid', amp.String()),
                 ('data', amp.String()),
                 ('ipart', amp.Integer()),
                 ('nparts', amp.Integer())]
    errors = [(Exception, 'EXCEPTION')]
    response = []

class FunctionCall(amp.Command):
    """
    Bidirectional

    Sent when either process needs to call an
    arbitrary function in the other. This does
    not use the batch-send functionality.
    """
    key = "FunctionCall"
    arguments = [('module', amp.String()),
                 ('function', amp.String()),
                 ('args', amp.String()),
                 ('kwargs', amp.String())]
    errors = [(Exception, 'EXCEPTION')]
    response = [('result', amp.String())]

# Helper functions

dumps = lambda data: to_str(pickle.dumps(to_str(data), pickle.HIGHEST_PROTOCOL))
loads = lambda data: pickle.loads(to_str(data))

#------------------------------------------------------------
# Core AMP protocol for communication Server <-> Portal
#------------------------------------------------------------

class AMPProtocol(amp.AMP):
    """
    This is the protocol that the MUD server and the proxy server
    communicate to each other with. AMP is a bi-directional protocol, so
    both the proxy and the MUD use the same commands and protocol.

    AMP specifies responder methods here and connect them to amp.Command
    subclasses that specify the datatypes of the input/output of these methods.
    """

    # helper methods

    def __init__(self, *args, **kwargs):
        """
        Initialize protocol with some things that need to be
        in place already before connecting both on portal and server.
        """
        self.min_batch_step = 1.0 / BATCH_RATE
        self.lastsend = time()
        self.task = task.LoopingCall(self.batch_send, None, None)
        self.task.start(BATCH_TIMEOUT)

    def connectionMade(self):
        """
        This is called when a connection is established
        between server and portal. AMP calls it on both sides,
        so we need to make sure to only trigger resync from the
        portal side.
        """
        self.transport.setTcpNoDelay(True) # this makes for a factor x10 faster sends!

        if hasattr(self.factory, "portal"):
            # only the portal has the 'portal' property, so we know we are
            # on the portal side and can initialize the connection.
            sessdata = self.factory.portal.sessions.get_all_sync_data()
            self.call_remote_ServerAdmin(0,
                                         PSYNC,
                                         data=sessdata)
            self.factory.portal.sessions.at_server_connection()
            if hasattr(self.factory, "server_restart_mode"):
                del self.factory.server_restart_mode

    # Error handling

    def errback(self, e, info):
        "error handler, to avoid dropping connections on server tracebacks."
        e.trap(Exception)
        print "AMP Error for %(info)s: %(e)s" % {'info': info,
                                                 'e': e.getErrorMessage()}

    def batch_send(self, command, sessid, **kwargs):
        """
        This will batch data together to send fewer, large batches.

        Kwargs:
            force_direct: send direct
        """
        #print "batch_send 1:", command, sessid
        global _SENDBATCH
        if command is None:
            # called by the automatic cleanup mechanism
            commands = [cmd for cmd in (MsgPortal2Server, MsgServer2Portal, ServerAdmin, PortalAdmin)
                        if _SENDBATCH.get(cmd, False)]
            if not commands:
                return
        else:
            # called to send right away
            commands = [command]
            _SENDBATCH[command].append((sessid, kwargs))

        force_direct = kwargs.pop("force_direct", False)
        now = time()
        #print "batch_send 2:", now, self.lastsend, self.min_batch_step, now-self.lastsend > self.min_batch_step

        if force_direct or now - self.lastsend > self.min_batch_step:
            for command in commands:
                batch = dumps(_SENDBATCH[command])
                _SENDBATCH[command] = []
                # split in parts small enough to fit in AMP MAXLEN
                to_send = [batch[i:i+AMP_MAXLEN] for i in range(0, len(batch), AMP_MAXLEN)]
                nparts = len(to_send)
                # tag this batch
                hashid = "%s-%s" % (id(batch), now)
                if nparts == 1:
                    deferreds = [self.callRemote(command,
                                           hashid=hashid,
                                           data=batch,
                                           ipart=0,
                                           nparts=1).addErrback(self.errback, command.key)]
                else:
                    deferreds = []
                    for ipart, part in enumerate(to_send):
                        deferred = self.callRemote(command,
                                                   hashid=hashid,
                                                   data=part,
                                                   ipart=ipart,
                                                   nparts=nparts)
                        deferred.addErrback(self.errback, "%s part %i/%i" % (command.key, ipart, part))
                        deferreds.append(deferred)
                self.lastsend = time() # don't use now here, keep it as up-to-date as possible
                return deferreds

    def batch_recv(self, hashid, data, ipart, nparts):
        """
        This will receive and unpack data sent as a batch. This both
        handles too-long data as well as batch-sending very fast-
        arriving commands.
        """
        global _MSGBUFFER
        if nparts == 1:
            # most common case
            return loads(data)
        else:
            if ipart < nparts-1:
                # not yet complete
                _MSGBUFFER[hashid].append(data)
                return []
            else:
                # all parts in place - deserialize it
                return loads(_MSGBUFFER.pop(hashid) + data)

    # Message definition + helper methods to call/create each message type

    # Portal -> Server Msg

    def amp_msg_portal2server(self, hashid, data, ipart, nparts):
        """
        Relays message to server. This method is executed on the Server.

        Since AMP has a limit of 65355 bytes per message, it's possible the
        data comes in multiple chunks; if so (nparts>1) we buffer the data
        and wait for the remaining parts to arrive before continuing.
        """
        batch = self.batch_recv(hashid, data, ipart, nparts)
        for (sessid, kwargs) in batch:
            #print "msg portal -> server (server side):", sessid, msg, loads(ret["data"])
            self.factory.server.sessions.data_in(sessid,
                                             text=kwargs["msg"],
                                             data=kwargs["data"])
        return {}
    MsgPortal2Server.responder(amp_msg_portal2server)

    def call_remote_MsgPortal2Server(self, sessid, msg, data=""):
        """
        Access method called by the Portal and executed on the Portal.
        """
        #print "msg portal->server (portal side):", sessid, msg, data
        return self.batch_send(MsgPortal2Server, sessid,
                               msg=msg if msg is not None else "",
                               data=data)

    # Server -> Portal message

    def amp_msg_server2portal(self, hashid, data, ipart, nparts):
        """
        Relays message to Portal. This method is executed on the Portal.
        """
        batch = self.batch_recv(hashid, data, ipart, nparts)
        for (sessid, kwargs) in batch:
            #print "msg server->portal (portal side):", sessid, ret["text"], loads(ret["data"])
            self.factory.portal.sessions.data_out(sessid,
                                                  text=kwargs["msg"],
                                                  data=kwargs["data"])
        return {}
    MsgServer2Portal.responder(amp_msg_server2portal)

    def amp_batch_server2portal(self, hashid, data, ipart, nparts):
        """
        Relays batch data to Portal. This method is executed on the Portal.
        """
        batch = self.batch_recv(hashid, data, ipart, nparts)
        if batch is not None:
            for (sessid, kwargs) in batch:
                self.factory.portal.sessions.data_out(sessid,
                                                      text=kwargs["msg"],
                                                      **kwargs["data"])
        return {}
    MsgServer2Portal.responder(amp_batch_server2portal)

    def call_remote_MsgServer2Portal(self, sessid, msg, data=""):
        """
        Access method called by the Server and executed on the Server.
        """
        #print "msg server->portal (server side):", sessid, msg, data
        return self.batch_send(MsgServer2Portal, sessid, msg=msg, data=data)

    # Server administration from the Portal side
    def amp_server_admin(self, hashid, data, ipart, nparts):
        """
        This allows the portal to perform admin
        operations on the server.  This is executed on the Server.

        """
        #print "serveradmin (server side):", hashid, ipart, nparts
        batch = self.batch_recv(hashid, data, ipart, nparts)

        for (sessid, kwargs) in batch:
            operation = kwargs["operation"]
            data = kwargs["data"]
            server_sessionhandler = self.factory.server.sessions

            #print "serveradmin (server side):", sessid, ord(operation), data

            if operation == PCONN:  # portal_session_connect
                # create a new session and sync it
                server_sessionhandler.portal_connect(data)

            elif operation == PCONNSYNC: #portal_session_sync
                server_sessionhandler.portal_session_sync(data)

            elif operation == PDISCONN:  # portal_session_disconnect
                # session closed from portal side
                self.factory.server.sessions.portal_disconnect(sessid)

            elif operation == PSYNC:  # portal_session_sync
                # force a resync of sessions when portal reconnects to
                # server (e.g. after a server reboot) the data kwarg
                # contains a dict {sessid: {arg1:val1,...}}
                # representing the attributes to sync for each
                # session.
                server_sessionhandler.portal_sessions_sync(data)
            else:
                raise Exception("operation %(op)s not recognized." % {'op': operation})
        return {}
    ServerAdmin.responder(amp_server_admin)

    def call_remote_ServerAdmin(self, sessid, operation="", data=""):
        """
        Access method called by the Portal and Executed on the Portal.
        """
        #print "serveradmin (portal side):", sessid, ord(operation), data
        if hasattr(self.factory, "server_restart_mode"):
            return self.batch_send(ServerAdmin, sessid, force_direct=True, operation=operation, data=data)
        return self.batch_send(ServerAdmin, sessid, operation=operation, data=data)

    # Portal administraton from the Server side

    def amp_portal_admin(self, hashid, data, ipart, nparts):
        """
        This allows the server to perform admin
        operations on the portal. This is executed on the Portal.
        """
        #print "portaladmin (portal side):", sessid, ord(operation), data
        batch = self.batch_recv(hashid, data, ipart, nparts)
        for (sessid, kwargs) in batch:
            operation = kwargs["operation"]
            data = kwargs["data"]
            portal_sessionhandler = self.factory.portal.sessions

            if operation == SLOGIN:  # server_session_login
                # a session has authenticated; sync it.
                portal_sessionhandler.server_logged_in(sessid, data)

            elif operation == SDISCONN:  # server_session_disconnect
                # the server is ordering to disconnect the session
                portal_sessionhandler.server_disconnect(sessid, reason=data)

            elif operation == SDISCONNALL:  # server_session_disconnect_all
                # server orders all sessions to disconnect
                portal_sessionhandler.server_disconnect_all(reason=data)

            elif operation == SSHUTD:  # server_shutdown
                # the server orders the portal to shut down
                self.factory.portal.shutdown(restart=False)

            elif operation == SSYNC:  # server_session_sync
                # server wants to save session data to the portal,
                # maybe because it's about to shut down.
                portal_sessionhandler.server_session_sync(data)
                # set a flag in case we are about to shut down soon
                self.factory.server_restart_mode = True

            elif operation == SCONN: # server_force_connection (for irc/imc2 etc)
                portal_sessionhandler.server_connect(**data)

            else:
                raise Exception("operation %(op)s not recognized." % {'op': operation})
        return {}
    PortalAdmin.responder(amp_portal_admin)

    def call_remote_PortalAdmin(self, sessid, operation="", data=""):
        """
        Access method called by the server side.
        """
        if operation == SSYNC:
            return self.batch_send(PortalAdmin, sessid, force_direct=True, operation=operation, data=data)
        return self.batch_send(PortalAdmin, sessid, operation=operation, data=data)

    # Extra functions

    def amp_function_call(self, module, function, args, **kwargs):
        """
        This allows Portal- and Server-process to call an arbitrary function
        in the other process. It is intended for use by plugin modules.
        """
        args = loads(args)
        kwargs = loads(kwargs)

        # call the function (don't catch tracebacks here)
        result = variable_from_module(module, function)(*args, **kwargs)

        if isinstance(result, Deferred):
            # if result is a deferred, attach handler to properly
            # wrap the return value
            result.addCallback(lambda r: {"result": dumps(r)})
            return result
        else:
            return {'result': dumps(result)}
    FunctionCall.responder(amp_function_call)

    def call_remote_FunctionCall(self, modulepath, functionname, *args, **kwargs):
        """
        Access method called by either process. This will call an arbitrary
        function on the other process (On Portal if calling from Server and
        vice versa).

        Inputs:
            modulepath (str) - python path to module holding function to call
            functionname (str) - name of function in given module
            *args, **kwargs will be used as arguments/keyword args for the
                            remote function call
        Returns:
            A deferred that fires with the return value of the remote
            function call
        """
        return self.callRemote(FunctionCall,
                               module=modulepath,
                               function=functionname,
                               args=dumps(args),
                               kwargs=dumps(kwargs)).addCallback(lambda r: loads(r["result"])).addErrback(self.errback, "FunctionCall")


text:
package cz.vsb.resbill.dao;

import java.util.Date;
import java.util.List;

import cz.vsb.resbill.model.DailyUsage;

/**
 * @author Ing. Radek Liebzeit <radek.liebzeit@vsb.cz>
 *
 */
public interface DailyUsageDAO {

  DailyUsage saveDailyUsage(DailyUsage dailyUsage);

  /**
   * Pro zadany kontrakt najde pres vsechny servery kontraktu vsechny DailyUsage, ktere doposud nebyly fakturovany a jsou nejpozdeji v pozadovanem dni.
   * Navic pripoji cenik prislusejici DailyUsage (dle data importu).
   *
   * Server musi byt kontraktu prirazen take nejpozdeji v pozadovanem dni.
   *
   * @param lastDay
   * @param contractId
   * @return
   */
  List<Object[]> findUninvoicedDailyUsages(Date lastDay, Integer contractId);

  DailyUsage findServerLastDailyUsage(Integer serverId);
}