text:
Please, describe why the refactoring is necessary. What are its pros and cons
in respect to the previous code, and other possible design choices.

## PR review check list

Quality check list that cannot be automatically verified.

- [ ] Safety
    - [ ] The changes respect the necessary conditions for safety (https://raiden-network-specification.readthedocs.io/en/latest/smart_contracts.html#protocol-values-constraints)
- [ ] Code quality
    - [ ] Error conditions are handled
    - [ ] Exceptions are propagated to the correct parent greenlet
    - [ ] Exceptions are correctly classified as recoverable or unrecoverable
- [ ] Compatibility
    - [ ] State changes are forward compatible
    - [ ] Transport messages are backwards and forward compatible
- [ ] Tests for the new code
    - [ ] Properly covers the new code
    - [ ] If an integration test is used, it could not be written as a unit test
- [ ] Commits
    - [ ] Have good messages
    - [ ] Squashed unecessary commits
- [ ] Docummented the design choices


text:
namespace MarkupDiff
{
    /// <summary>
    /// Types of lines
    /// </summary>
    public enum LineTypes
    {
        Other = 0,
        Whitespace = 1,
        LinkingTag  = 2,
        Markup = 3,

        // padding is not whitespace ; it is inserted so matching lines can appear next to eachother
        Padding = 4
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>BasicBlock Structure Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

LLVM Docs (100% documented)

        LLVM Reference

        BasicBlock Structure Reference

            Classes

                AttachedMetadata

                – PinnedKind

                – Entry

                Comdat

                – SelectionKind

                Context

                DIBuilder

                Function

                FunctionPassManager

                Global

                IRBuilder

                Intrinsic

                – Selector

                – DynamicIntrinsicResolver

                JIT

                – TargetAddress

                – ModuleHandle

                MemoryBuffer

                Module

                – Flags

                NamedMetadata

                ObjectFile

                RelocationSequence

                SectionSequence

                SymbolSequence

                Target

                TargetData

                TargetMachine

            Enumerations

                AtomicOrdering

                AtomicReadModifyWriteOperation

                AttributeIndex

                AttributeKind

                ByteOrder

                CallingConvention

                CodeGenOptLevel

                CodeModel

                CodegenFileType

                DIAttributeTypeEncoding

                DWARFEmissionKind

                DWARFExpression

                DWARFSourceLanguage

                DWARFTag

                Floating

                FunctionPass

                IRMetadataKind

                IRValueKind

                InlineAssemblyDialect

                IntPredicate

                JITError

                LandingPadClause

                Linkage

                MemoryBufferError

                ModuleError

                OpCode

                – Binary

                – Cast

                OverflowBehavior

                RealPredicate

                RelocationModel

                Signed

                StorageClass

                Struct

                TargetMachineError

                ThreadLocalModel

                UnnamedAddressKind

                Unsigned

                Vector

                Visibility

            Extensions

                Bool

                Int

                Int16

                Int32

                Int64

                Int8

                LLVMValueRef

                String

                UInt

                UInt16

                UInt32

                UInt64

                UInt8

            Functions

                initializeLLVM()

            Protocols

                Attribute

                ConstantRepresentation

                DIScope

                DIType

                IRConstant

                IRGlobal

                IRMetadata

                IRType

                IRValue

                IntegralConstantRepresentation

                NumericalConstantRepresentation

                _IRMetadataInitializerHack

            Structures

                APInt

                Alias

                Alignment

                ArrayType

                BasicBlock

                – Address

                Call

                CompileUnitMetadata

                Constant

                DIBasicType

                DIFlags

                DISubroutineType

                DebugLocation

                EnumAttribute

                ExpressionMetadata

                FileMetadata

                FloatType

                – Kind

                FunctionMetadata

                FunctionType

                ImportedEntityMetadata

                Instruction

                IntType

                Invoke

                LabelType

                LexicalBlockFileMetadata

                LexicalBlockMetadata

                LocalVariableMetadata

                MetadataType

                ModuleMetadata

                NameSpaceMetadata

                ObjectiveCPropertyAttribute

                ObjectiveCPropertyMetadata

                Parameter

                PhiNode

                PointerType

                Relocation

                Section

                Size

                StringAttribute

                StructLayout

                StructType

                Switch

                Symbol

                TerminatorInstruction

                TokenType

                Use

                VectorType

                VoidType

                X86MMXType

BasicBlock

public struct BasicBlock : IRValue

A BasicBlock represents a basic block in an LLVM IR program.  A basic
block contains a sequence of instructions, a pointer to its parent block and
its follower block, and an optional label that gives the basic block an
entry in the symbol table.

A basic block can be thought of as a sequence of instructions, and indeed
its member instructions may be iterated over with a for-in loop.

The first basic block in a function is special in two ways: it is
immediately executed on entrance to the function, and it is not allowed to
have predecessor basic blocks (i.e. there can not be any branches to the
entry block of a function). Because the block can have no predecessors, it
also cannot have any PHI nodes.

                    init(llvm:)

Creates a BasicBlock from an LLVMBasicBlockRef object.

Declaration

Swift

public init(llvm: LLVMBasicBlockRef)

                    init(context:name:)

Creates a new basic block without a parent function.

The basic block should be inserted into a function or destroyed before
the IR builder is finalized.

Declaration

Swift

public init(context: Context = .global, name: String = "")

                    move(before:)

Given that this block and a given block share a parent function, move this
block before the given block in that function’s basic block list.

Declaration

Swift

public func move(before position: BasicBlock)

Parameters

                                position

The basic block that acts as a position before
which this block will be moved.

                    move(after:)

Given that this block and a given block share a parent function, move this
block after the given block in that function’s basic block list.

Declaration

Swift

public func move(after position: BasicBlock)

Parameters

                                position

The basic block that acts as a position after
which this block will be moved.

                    asLLVM()

Retrieves the underlying LLVM value object.

Declaration

Swift

public func asLLVM() -> LLVMValueRef

                    name

Retrieves the name of this basic block.

Declaration

Swift

public var name: String { get }

                    firstInstruction

Returns the first instruction in the basic block, if it exists.

Declaration

Swift

public var firstInstruction: Instruction? { get }

                    lastInstruction

Returns the first instruction in the basic block, if it exists.

Declaration

Swift

public var lastInstruction: Instruction? { get }

                    terminator

Returns the terminator instruction if this basic block is well formed or
nil if it is not well formed.

Declaration

Swift

public var terminator: TerminatorInstruction? { get }

                    parent

Returns the parent function of this basic block, if it exists.

Declaration

Swift

public var parent: Function? { get }

                    next()

Returns the basic block following this basic block, if it exists.

Declaration

Swift

public func next() -> BasicBlock?

                    previous()

Returns the basic block before this basic block, if it exists.

Declaration

Swift

public func previous() -> BasicBlock?

                    instructions

Returns a sequence of the Instructions that make up this basic block.

Declaration

Swift

public var instructions: AnySequence<Instruction> { get }

                    removeFromParent()

Removes this basic block from a function but keeps it alive.

Note

    To ensure correct removal of the block, you must invalidate any
    references to it and its child instructions.  The block must also
    have no successor blocks that make reference to it.

Declaration

Swift

public func removeFromParent()

                    moveBefore(_:)

Moves this basic block before the given basic block.

Declaration

Swift

public func moveBefore(_ block: BasicBlock)

                    moveAfter(_:)

Moves this basic block after the given basic block.

Declaration

Swift

public func moveAfter(_ block: BasicBlock)

                    Address

An Address represents a function-relative address of a basic block for
use with the indirectbr instruction.

                        See more

Declaration

Swift

public struct Address : IRValue

                    ==(_:_:)

Declaration

Swift

public static func == (lhs: BasicBlock, rhs: BasicBlock) -> Bool

© 2019 . All rights reserved. (Last updated: 2019-03-22)

Generated by jazzy ♪♫ v0.9.5, a Realm project.


text:
@interface SCPrimerCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic) NSString *lesson;
@end


text:
import { Component } from '@angular/core';
import { layoutStyleTableHtmlSnippet } from '../../../example/layout-style/snippets/layout-style-table-html.snippet';
import { layoutStyleTableScssSnippet } from '../../../example/layout-style/snippets/layout-style-table-scss.snippet';
import { layoutStyleTableTsSnippet } from '../../../example/layout-style/snippets/layout-style-table-ts.snippet';

@Component({
  selector: 'app-layout-style-article',
  templateUrl: './layout-style-article.component.html',
  styleUrls: ['./layout-style-article.component.scss']
})
export class LayoutStyleArticleComponent {

  public layoutStyleTableHtmlSnippet = layoutStyleTableHtmlSnippet;
  public layoutStyleTableTsSnippet =  layoutStyleTableTsSnippet;
  public layoutStyleTableScssSnippet =  layoutStyleTableScssSnippet;
}


text:
DROP EXTENSION numhstore CASCADE;
CREATE EXTENSION numhstore VERSION '0.1.6';
ALTER EXTENSION numhstore UPDATE TO '0.1.7';


text:
/*body {
  padding: 50px;
  font-family: 'Creepster', cursive;
  color:green;
  background-color: peachpuff;
}

a {
  color: #00B7FF;
}*/
body {
  font-family: 'Creepster', cursive;
  color:green;
  background-image: url("/images/yfluff.png");
}


text:
from __future__ import print_function, division, absolute_import, unicode_literals

import hashlib
import os
import re
import random
import string

uri_reserved_chars_re = re.compile(r'[:\/?#\[\]@!$&\'()*+,;=]')

def create_unique_id(package_info, os_string, architecture, id_prefix):
    """
    Create a Unique-ID.

    Args:
        package_info (PackageInfo):
            A ``PackageInfo`` instance.
        os_string (str):
            An string representing the current distribution,
            e.g. ``Debian_7.4`` or ``Fedora_19``.
        architecture (str):
            The system architecture, e.g. ``x86_64`` or ``i386``.

    Returns:
        The Unique-ID string.

    """
    if id_prefix is None:
        unique_id_format = '{os_string}-{architecture}-{pi.package}-{pi.version}'
    else:
        unique_id_format = '{id_prefix}{pi.package}-{pi.version}'
    unique_id = unique_id_format.format(os_string=os_string,
                                        architecture=architecture,
                                        pi=package_info,
                                        id_prefix=id_prefix)
    return uri_reserved_chars_re.sub('~', unique_id)

def create_system_id(os_string, architecture):
    """
    Create a system-ID by joining the OS-String and the architecture with a hyphen.

    Args:
        os_string (str):
            The Operating system string.
        architecture (str):
            The Architecture string.

    Returns:
        The System-ID string.

    """
    system_id_format = '{os_string} {architecture}'
    return system_id_format.format(os_string=os_string.replace('_', ' '),
                                   architecture=architecture)

def create_software_id(regid, unique_id):
    """
    Create a Software-ID by joining the Regid and the Unique-ID with a double underscore.

    Args:
        regid (str):
            The Regid string.
        unique_id (str):
            The Unique-ID string.

    Returns:
        The Software-ID string.

    """
    return '{regid}__{unique_id}'.format(regid=regid, unique_id=unique_id)

def create_sha256_hash(filepath):
    return _create_hash(filepath, hashlib.sha256())

def create_sha384_hash(filepath):
    return _create_hash(filepath, hashlib.sha384())

def create_sha512_hash(filepath):
    return _create_hash(filepath, hashlib.sha512())

def _create_hash(file_path, hash_algorithm):
    blocksize = 65536
    with open(file_path, 'rb') as afile:
        buf = afile.read(blocksize)
        while len(buf) > 0:
            hash_algorithm.update(buf)
            buf = afile.read(blocksize)

    return hash_algorithm.hexdigest()

def create_temp_folder(file_path):
    """
    It creates a folder in the directory /tmp of the client/server.
    This folder has the prefix "swid_". To this prefix a random generated String is appended to
    prevent collisions of foldernames.

    :param file_path: Path to the file (package or certificate)
    :return: A dictionary with the save options of the temporary folder.
    """
    temp_folder_name = '/tmp'
    folder_prefix = 'swid_'

    random_string = ''.join(random.choice(string.ascii_letters) for _ in range(5))

    if file_path[0] == "/":
        absolute_package_path = file_path
    else:
        absolute_package_path = '/'.join((os.getcwd(), file_path))

    save_location_pathname = '/'.join((temp_folder_name, folder_prefix + random_string))

    if not os.path.exists(save_location_pathname):
        os.makedirs(save_location_pathname)

    folder_information = {
        'absolute_package_path': absolute_package_path,
        'save_location': save_location_pathname
    }

    return folder_information


text: <!DOCTYPE html>


text:
<!DOCTYPE foo SYSTEM "src/test/resources/org/apache/tapestry5/internal/services/simple.dtd" >
<foo>bar</foo>


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.crowleysimon.basil.view.recipelist.RecipeListActivity">
    <item
        android:id="@+id/action_search"
        android:orderInCategory="100"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="@string/search"
        app:showAsAction="always" />
</menu>


text:
package de.terrestris.shoguncore.importer.communication;

import com.fasterxml.jackson.annotation.JsonRootName;

import java.util.ArrayList;

/**
 * terrestris GmbH & Co. KG
 *
 * @author ahenn
 * @date 15.04.2016
 */
@JsonRootName("tasks")
public class RESTImportTaskList extends ArrayList<RESTImportTask> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public RESTImportTaskList() {

    }

}


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # This module authenticates to oVirt/RHV engine and creates SSO token, which should be later used in all other oVirt/RHV modules, so all modules don't need to perform login and logout. This module returns an Ansible fact called I(ovirt_auth). Every module can use this fact as C(auth) parameter, to perform authentication.
      class Ovirt_auth < Base
        # @return [:present, :absent, nil] Specifies if a token should be created or revoked.
        attribute :state
        validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}, allow_nil: true

        # @return [Object, nil] The name of the user. For example: I(admin@internal) Default value is set by I(OVIRT_USERNAME) environment variable.
        attribute :username

        # @return [Object, nil] The password of the user. Default value is set by I(OVIRT_PASSWORD) environment variable.
        attribute :password

        # @return [Object, nil] SSO token to be used instead of login with username/password. Default value is set by I(OVIRT_TOKEN) environment variable.
        attribute :token

        # @return [Object, nil] A string containing the API URL of the server. For example: I(https://server.example.com/ovirt-engine/api). Default value is set by I(OVIRT_URL) environment variable.,Either C(url) or C(hostname) is required.
        attribute :url

        # @return [Object, nil] A string containing the hostname of the server. For example: I(server.example.com). Default value is set by I(OVIRT_HOSTNAME) environment variable.,Either C(url) or C(hostname) is required.
        attribute :hostname

        # @return [Object, nil] A boolean flag that indicates if the server TLS certificate and host name should be checked.
        attribute :insecure

        # @return [Object, nil] A PEM file containing the trusted CA certificates. The certificate presented by the server will be verified using these CA certificates. If C(ca_file) parameter is not set, system wide CA certificate store is used. Default value is set by I(OVIRT_CAFILE) environment variable.
        attribute :ca_file

        # @return [Object, nil] The maximum total time to wait for the response, in seconds. A value of zero (the default) means wait forever. If the timeout expires before the response is received an exception will be raised.
        attribute :timeout

        # @return [Object, nil] A boolean flag indicating if the SDK should ask the server to send compressed responses. The default is I(True). Note that this is a hint for the server, and that it may return uncompressed data even when this parameter is set to I(True).
        attribute :compress

        # @return [Object, nil] A boolean flag indicating if Kerberos authentication should be used instead of the default basic authentication.
        attribute :kerberos

        # @return [Object, nil] A dictionary of HTTP headers to be added to each API call.
        attribute :headers
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.springframework.jdbc.core.namedparam (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Package

Next Package

Frames

No Frames

All Classes

@NonNullApi
 @NonNullFields

Package org.springframework.jdbc.core.namedparam

JdbcTemplate variant with named parameter support.

See: Description

Interface Summary

Interface
Description

NamedParameterJdbcOperations

Interface specifying a basic set of JDBC operations allowing the use
 of named parameters rather than the traditional '?' placeholders.

SqlParameterSource

Interface that defines common functionality for objects that can
 offer parameter values for named SQL parameters, serving as argument
 for NamedParameterJdbcTemplate operations.

Class Summary

Class
Description

AbstractSqlParameterSource

Abstract base class for SqlParameterSource implementations.

BeanPropertySqlParameterSource

SqlParameterSource implementation that obtains parameter values
 from bean properties of a given JavaBean object.

EmptySqlParameterSource

A simple empty implementation of the SqlParameterSource interface.

MapSqlParameterSource

SqlParameterSource implementation that holds a given Map of parameters.

NamedParameterBatchUpdateUtils
Deprecated

as of 5.1.3, not used by NamedParameterJdbcTemplate anymore

NamedParameterJdbcDaoSupport

Extension of JdbcDaoSupport that exposes a NamedParameterJdbcTemplate as well.

NamedParameterJdbcTemplate

Template class with a basic set of JDBC operations, allowing the use
 of named parameters rather than traditional '?' placeholders.

NamedParameterUtils

Helper methods for named parameter parsing.

ParsedSql

Holds information about a parsed SQL statement.

SqlParameterSourceUtils

Class that provides helper methods for the use of SqlParameterSource,
 in particular with NamedParameterJdbcTemplate.

Package org.springframework.jdbc.core.namedparam Description

JdbcTemplate variant with named parameter support.

NamedParameterJdbcTemplate is a wrapper around JdbcTemplate that adds
 support for named parameter parsing. It does not implement the JdbcOperations
 interface or extend JdbcTemplate, but implements the dedicated
 NamedParameterJdbcOperations interface.

If you need the full power of Spring JDBC for less common operations, use
 the getJdbcOperations() method of NamedParameterJdbcTemplate and
 work with the returned classic template, or use a JdbcTemplate instance directly.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev Package

Next Package

Frames

No Frames

All Classes


text:
import packingAlgorithms from './packing/packing-algorithms';

/**
 * Converts a set combinator representations into a blueprint by selecting
 * a packing algorithm to construct and arrange the combinators
 */
export default (combinators, {pack = true} = {}) => {
    if(pack) {
        return packingAlgorithms.compactPackingAlgorithm(combinators);
    } else {
        return packingAlgorithms.debugPackingAlgorithm(combinators);
    }
};


text:
package org.drools.chance.common;

import org.drools.chance.distribution.Distribution;
import org.drools.chance.distribution.DistributionStrategies;

/**
 * Abstract class for the structures holding the imperfect information regarding a single bean's field.
 *
 * This structure mimics the field's value, actually storing a Distribution over that field's domain.
 * i.e. if Person.age is the target field, this structure will e.g. hold one (or more) Distribution<Integer>.
 * A Distribution maps one or more elements of that domain to an Degree. The semantics is determined on
 * a case-by-case basis. For example, it may be a discrete probability distribution, or a fuzzy set (possibility
 * distribution), or a basic mass assignment, etc...
 *
 * See ImperfectFieldImpl for the rationale and ImperfectHistoryField
 *
 *
 */
public abstract class AbstractImperfectField<T> implements ImperfectField<T> {

    /**
     * Reference to a Strategy class holding all the algorithms for the manipulation of this field's distribution
     */
    protected DistributionStrategies<T> strategies;

    /**
     * Basic constructor
     * @param strategies a reference to the Strategy class with the logic for handling this field's distribution
     */
    public AbstractImperfectField(DistributionStrategies<T> strategies){
        this.strategies = strategies;
    }

    /**
     * "By value" setter. Creates a (degenerate) distribution with full degree assigned to the value
     * @param value the value used to create a degenerate distribution
     */
    public void setValue(T value) {
        setValue(strategies.toDistribution(value));
    }

    public void setValue(T value, boolean update) {
        setValue(strategies.toDistribution(value),update);
    }

    /**
     * Setter. Overrides the previous distribution, if any)
     * @param dist A distribution over a bean's field domain
     */
    public void setValue(Distribution<T> dist) {
        setValue(dist, isSet());
    }

    /**
     * Setter
     * @param dist A distribution over a bean's field domain
     * @param update if true, the new distribution dist will be merged with the current distribution, according to
     * this instance's strategies. If false, the new distribution will override the previous one.
     */
    public abstract void setValue(Distribution<T> dist, boolean update);

    /**
     * Predicate.
     * @return true if the current field has already been set, or is still to be initialized
     */
    public abstract boolean isSet();

    /**
     * Getter
     * @return converts the current distribution to a crisp value (according to the current strategies "toCrispValue").
     * The value returned belongs to the same domain the distribution is defined on (e.g. an Distribution<String> will
     * return a String when crispified)
     */
    public T getCrisp(){
        return strategies.toCrispValue(getCurrent());
    }

    /**
     * Tries to access a "previous" value of this field. Every "set" operation on the field counts
     * as a step.
     *
     * @param time a non-positive integer value.
     * @return The value the field had before the last #time set operations, if possible.
     * 0 corresponds to the current value.
     * @throws IndexOutOfBoundsException
     */
    public abstract Distribution<T> getPast(int time) throws IndexOutOfBoundsException;

    /**
     * @return the current distribution for this field
     */
    public abstract Distribution<T> getCurrent();

    /**
     * Getter
     * @return the current Strategies used to manipulate this field's distribution
     */
    public DistributionStrategies<T> getStrategies() {
        return strategies;
    }

    /**
     * Setter.
     * Do not change the strategy at runtime, unless you REALLY
     * know what you're doing. So, no public API for this
     * @param factory the new Strategies used to manipulate this field's distribution
     */
    protected void setStrategies(DistributionStrategies<T> factory) {
        this.strategies = factory;
    }

    /**
     * updates the current distribution, merging it with the provided one, using the current strategies.
     * Convenience method that calls "setValue" with update set to true
     * @param fieldBit the new distribution to merge with the current one
     */
    public void update(Distribution<T> fieldBit) {
        this.setValue( fieldBit, true );
    }

    /**
     * updates the current distribution, by converting the provided value into a (degenerate) distribution
     * and merging it with the current one.
     * (In many cases, this operation could still return a degenerate distribution centered on value)
     * @param value the value to merge with the current distribution
     */
    public void update(T value) {
        this.update(strategies.toDistribution(value));
    }
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var di_1 = require("angular2/src/core/di");
var api_1 = require("angular2/src/core/render/api");
var api_2 = require("angular2/src/web_workers/shared/api");
var collection_1 = require("angular2/src/core/facade/collection");
var RenderViewWithFragmentsStore = (function () {
    function RenderViewWithFragmentsStore(onWebWorker) {
        this._nextIndex = 0;
        this._onWebWorker = onWebWorker;
        this._lookupByIndex = new Map();
        this._lookupByView = new Map();
        this._viewFragments = new Map();
    }
    RenderViewWithFragmentsStore.prototype.allocate = function (fragmentCount) {
        var initialIndex = this._nextIndex;
        var viewRef = new WebWorkerRenderViewRef(this._nextIndex++);
        var fragmentRefs = collection_1.ListWrapper.createGrowableSize(fragmentCount);
        for (var i = 0; i < fragmentCount; i++) {
            fragmentRefs[i] = new WebWorkerRenderFragmentRef(this._nextIndex++);
        }
        var renderViewWithFragments = new api_1.RenderViewWithFragments(viewRef, fragmentRefs);
        this.store(renderViewWithFragments, initialIndex);
        return renderViewWithFragments;
    };
    RenderViewWithFragmentsStore.prototype.store = function (view, startIndex) {
        var _this = this;
        this._lookupByIndex.set(startIndex, view.viewRef);
        this._lookupByView.set(view.viewRef, startIndex);
        startIndex++;
        view.fragmentRefs.forEach(function (ref) {
            _this._lookupByIndex.set(startIndex, ref);
            _this._lookupByView.set(ref, startIndex);
            startIndex++;
        });
        this._viewFragments.set(view.viewRef, view.fragmentRefs);
    };
    RenderViewWithFragmentsStore.prototype.remove = function (view) {
        var _this = this;
        this._removeRef(view);
        var fragments = this._viewFragments.get(view);
        fragments.forEach(function (fragment) { _this._removeRef(fragment); });
        this._viewFragments.delete(view);
    };
    RenderViewWithFragmentsStore.prototype._removeRef = function (ref) {
        var index = this._lookupByView.get(ref);
        this._lookupByView.delete(ref);
        this._lookupByIndex.delete(index);
    };
    RenderViewWithFragmentsStore.prototype.serializeRenderViewRef = function (viewRef) {
        return this._serializeRenderFragmentOrViewRef(viewRef);
    };
    RenderViewWithFragmentsStore.prototype.serializeRenderFragmentRef = function (fragmentRef) {
        return this._serializeRenderFragmentOrViewRef(fragmentRef);
    };
    RenderViewWithFragmentsStore.prototype.deserializeRenderViewRef = function (ref) {
        if (ref == null) {
            return null;
        }
        return this._retrieve(ref);
    };
    RenderViewWithFragmentsStore.prototype.deserializeRenderFragmentRef = function (ref) {
        if (ref == null) {
            return null;
        }
        return this._retrieve(ref);
    };
    RenderViewWithFragmentsStore.prototype._retrieve = function (ref) {
        if (ref == null) {
            return null;
        }
        if (!this._lookupByIndex.has(ref)) {
            return null;
        }
        return this._lookupByIndex.get(ref);
    };
    RenderViewWithFragmentsStore.prototype._serializeRenderFragmentOrViewRef = function (ref) {
        if (ref == null) {
            return null;
        }
        if (this._onWebWorker) {
            return ref.serialize();
        }
        else {
            return this._lookupByView.get(ref);
        }
    };
    RenderViewWithFragmentsStore.prototype.serializeViewWithFragments = function (view) {
        var _this = this;
        if (view == null) {
            return null;
        }
        if (this._onWebWorker) {
            return {
                'viewRef': view.viewRef.serialize(),
                'fragmentRefs': view.fragmentRefs.map(function (val) { return val.serialize(); })
            };
        }
        else {
            return {
                'viewRef': this._lookupByView.get(view.viewRef),
                'fragmentRefs': view.fragmentRefs.map(function (val) { return _this._lookupByView.get(val); })
            };
        }
    };
    RenderViewWithFragmentsStore.prototype.deserializeViewWithFragments = function (obj) {
        var _this = this;
        if (obj == null) {
            return null;
        }
        var viewRef = this.deserializeRenderViewRef(obj['viewRef']);
        var fragments = obj['fragmentRefs'].map(function (val) { return _this.deserializeRenderFragmentRef(val); });
        return new api_1.RenderViewWithFragments(viewRef, fragments);
    };
    RenderViewWithFragmentsStore = __decorate([
        di_1.Injectable(),
        __param(0, di_1.Inject(api_2.ON_WEB_WORKER)),
        __metadata('design:paramtypes', [Object])
    ], RenderViewWithFragmentsStore);
    return RenderViewWithFragmentsStore;
})();
exports.RenderViewWithFragmentsStore = RenderViewWithFragmentsStore;
var WebWorkerRenderViewRef = (function (_super) {
    __extends(WebWorkerRenderViewRef, _super);
    function WebWorkerRenderViewRef(refNumber) {
        _super.call(this);
        this.refNumber = refNumber;
    }
    WebWorkerRenderViewRef.prototype.serialize = function () { return this.refNumber; };
    WebWorkerRenderViewRef.deserialize = function (ref) {
        return new WebWorkerRenderViewRef(ref);
    };
    return WebWorkerRenderViewRef;
})(api_1.RenderViewRef);
exports.WebWorkerRenderViewRef = WebWorkerRenderViewRef;
var WebWorkerRenderFragmentRef = (function (_super) {
    __extends(WebWorkerRenderFragmentRef, _super);
    function WebWorkerRenderFragmentRef(refNumber) {
        _super.call(this);
        this.refNumber = refNumber;
    }
    WebWorkerRenderFragmentRef.prototype.serialize = function () { return this.refNumber; };
    WebWorkerRenderFragmentRef.deserialize = function (ref) {
        return new WebWorkerRenderFragmentRef(ref);
    };
    return WebWorkerRenderFragmentRef;
})(api_1.RenderFragmentRef);
exports.WebWorkerRenderFragmentRef = WebWorkerRenderFragmentRef;
//# sourceMappingURL=render_view_with_fragments_store.js.map


text:
namespace Seeker.Actors
{
    /// <summary>
    /// Repesents actor paths.
    /// </summary>
    public static class ActorPaths
    {
        public static readonly ActorMetaData UserManager = new ActorMetaData("user-manager");

        public static readonly ActorMetaData MessageIngestor = new ActorMetaData("message-ingestor");

        public static readonly ActorMetaData Indexer = new ActorMetaData("log-indexer");

        public static readonly ActorMetaData QueryStatistics = new ActorMetaData("query-statistics");
    }
}


text:
@implementation OCDiscount

+ (NSString *)convertMarkdownFileAtPath:(NSString *)path error:(NSError **)error
{
    NSString *string = [NSString stringWithContentsOfFile:path
                                                 encoding:NSUTF8StringEncoding
                                                    error:error];

    return [OCDiscount convertMarkdownString:string];
}

+ (NSString *)convertMarkdownFileAtURL:(NSURL *)url error:(NSError **)error
{
    NSString *string = [NSString stringWithContentsOfURL:url
                                                encoding:NSUTF8StringEncoding
                                                   error:error];

    return [OCDiscount convertMarkdownString:string];
}

+ (NSString *)convertMarkdownString:(NSString *)string
{
    NSString *html = nil;

    if (string != nil) {
        char *markdownUTF8 = (char*)[string UTF8String];
        Document *document = mkd_string(markdownUTF8, (int)strlen(markdownUTF8), 0);

        if (document) {
            if (mkd_compile(document, 0)) {
                char *htmlUTF8;
                int htmlUTF8Len = mkd_document(document, &htmlUTF8);
                if (htmlUTF8Len != EOF) {
                    html = [[NSString alloc] initWithBytes:htmlUTF8
                                                    length:htmlUTF8Len
                                                  encoding:NSUTF8StringEncoding];
                }
                mkd_cleanup(document);
            }
        }
    }

    return html;
}

@end


text:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\ParserAlias;

/**
 * AliasSearch represents the model behind the search form about `backend\models\ParserAlias`.
 */
class AliasSearch extends ParserAlias
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'category'], 'safe'],
            [['id'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ParserAlias::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'category', $this->category]);

        return $dataProvider;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv='Content-type' content='text/html; charset=utf-8'>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Log in | Lost & Found Management System</title>

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

    <link href="css/flat-ui.css" rel="stylesheet">

    <link rel="stylesheet" href="css/login.css">

Please finish your personal infomation

      <form class="login-form" name="signupForm" action="" method="POST">

          <input type="text" class="form-control login-field" placeholder="Enter your Name" id="login-name" name="name" required autofocus>

          <input type="tel" class="form-control login-field" placeholder="Enter your phone" id="login-phone" name="phone">

          <input type="number" class="form-control login-field" placeholder="Enter your student ID" id="login-stuID" required>

          <input type="text" class="form-control login-field" placeholder="Enter your username" id="login-username" required>

          <input type="password" class="form-control login-field" placeholder="Password" id="login-pass" required>

        <button type="submit" class="btn btn-primary btn-lg btn-block">Sign up</button>

      </form>


text:
package org.apache.beam.sdk.coders;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import org.apache.beam.sdk.testing.CoderProperties;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.util.CoderUtils;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Test case for {@link CollectionCoder}.
 */
@RunWith(JUnit4.class)
public class CollectionCoderTest {

  private static final Coder<Collection<Integer>> TEST_CODER = CollectionCoder.of(VarIntCoder.of());

  private static final List<Collection<Integer>> TEST_VALUES = Arrays.<Collection<Integer>>asList(
      Collections.<Integer>emptyList(),
      Collections.<Integer>emptySet(),
      Collections.singletonList(13),
      Arrays.asList(1, 2, 3, 4),
      new LinkedList<>(Arrays.asList(7, 6, 5)),
      new TreeSet<>(Arrays.asList(31, -5, 83)));

  @Test
  public void testDecodeEncodeContentsEqual() throws Exception {
    for (Collection<Integer> value : TEST_VALUES) {
      CoderProperties.coderDecodeEncodeContentsEqual(TEST_CODER, value);
    }
  }

  /**
   * Generated data to check that the wire format has not changed. To regenerate, see
   * {@link org.apache.beam.sdk.coders.PrintBase64Encodings}.
   */
  private static final List<String> TEST_ENCODINGS = Arrays.asList(
      "AAAAAA",
      "AAAAAA",
      "AAAAAQ0",
      "AAAABAECAwQ",
      "AAAAAwcGBQ",
      "AAAAA_v___8PH1M");

  @Test
  public void testWireFormat() throws Exception {
    CoderProperties.coderDecodesBase64ContentsEqual(TEST_CODER, TEST_ENCODINGS, TEST_VALUES);
  }

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Test
  public void encodeNullThrowsCoderException() throws Exception {
    thrown.expect(CoderException.class);
    thrown.expectMessage("cannot encode a null Collection");

    CoderUtils.encodeToBase64(TEST_CODER, null);
  }

  @Test
  public void testCoderIsSerializableWithWellKnownCoderType() throws Exception {
    CoderProperties.coderSerializable(CollectionCoder.of(GlobalWindow.Coder.INSTANCE));
  }

  public void testEncodedTypeDescriptor() throws Exception {
    TypeDescriptor<Collection<Integer>> expectedTypeDescriptor =
        new TypeDescriptor<Collection<Integer>>() {};
    assertThat(TEST_CODER.getEncodedTypeDescriptor(), equalTo(expectedTypeDescriptor));
  }
}


text:
shared_context "a Celluloid Mailbox" do
  after do
    Celluloid.logger.stub(:debug)
    subject.shutdown if subject.alive?
  end

  it "receives messages" do
    message = :ohai

    subject << message
    subject.receive.should == message
  end

  it "prioritizes system events over other messages" do
    subject << :dummy1
    subject << :dummy2

    subject << Celluloid::SystemEvent.new
    subject.receive.should be_a(Celluloid::SystemEvent)
  end

  it "selectively receives messages with a block" do
    class Foo; end
    class Bar; end
    class Baz; end

    foo, bar, baz = Foo.new, Bar.new, Baz.new

    subject << baz
    subject << foo
    subject << bar

    subject.receive { |msg| msg.is_a? Foo }.should eq(foo)
    subject.receive { |msg| msg.is_a? Bar }.should eq(bar)
    subject.receive.should eq(baz)
  end

  it "waits for a given timeout interval" do
    interval = 0.1
    started_at = Time.now

    expect do
      subject.receive(interval) { false }
    end.to raise_exception(Celluloid::TimeoutError)

    (Time.now - started_at).should be_within(Celluloid::TIMER_QUANTUM).of interval
  end

  it "has a size" do
    subject.should respond_to(:size)
    subject.size.should be_zero
    subject << :foo
    subject << :foo
    subject.should have(2).entries
  end

  it "discards messages received when when full" do
    subject.max_size = 2
    subject << :first
    subject << :second
    subject << :third
    subject.to_a.should =~ [:first, :second]
  end

  it "logs discarded messages" do
    Celluloid.logger.should_receive(:debug).with("Discarded message (mailbox is dead): third")

    subject.max_size = 2
    subject << :first
    subject << :second
    subject << :third
  end

  it "discard messages when dead" do
    Celluloid.logger.should_receive(:debug).with("Discarded message (mailbox is dead): first")
    Celluloid.logger.should_receive(:debug).with("Discarded message (mailbox is dead): second")
    Celluloid.logger.should_receive(:debug).with("Discarded message (mailbox is dead): third")

    subject << :first
    subject << :second
    subject.shutdown
    subject << :third
  end
end


text:
"use strict";

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };

var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };

var FamousRenderNode = _interopRequire(require("famous/core/RenderNode"));

var FamousSequentialLayout = _interopRequire(require("famous/views/SequentialLayout"));

var defaults = _interopRequire(require("lodash/object/defaults"));

var React = _interopRequire(require("react"));

var FamousComponent = _interopRequire(require("../lib/FamousComponent"));

var SequentialLayout = (function (_FamousComponent) {
  function SequentialLayout() {
    _classCallCheck(this, SequentialLayout);

    if (_FamousComponent != null) {
      _FamousComponent.apply(this, arguments);
    }
  }

  _inherits(SequentialLayout, _FamousComponent);

  _createClass(SequentialLayout, {
    famousCreate: {
      value: function famousCreate() {
        return new FamousSequentialLayout(this.props.options);
      }
    },
    famousCreateNode: {
      value: function famousCreateNode(parentNode) {
        var sequentialLayout = this.getFamous();
        var node = parentNode.add(sequentialLayout);
        var next = [];
        var sequence = this.getFamousChildrenRef().map(function (child, idx) {
          var renderNode = new FamousRenderNode();
          next.push([child, renderNode]);
          return renderNode;
        });
        sequentialLayout.sequenceFrom(sequence);
        return [node, next];
      }
    },
    famousUpdate: {
      value: function famousUpdate(nextProps) {
        var sequentialLayout = this.getFamous();

        sequentialLayout.setOptions(nextProps.options);
      }
    },
    render: {
      value: function render() {
        return React.createElement(
          "div",
          { "data-famous": "SequentialLayout" },
          this.getFamousChildren()
        );
      }
    }
  });

  return SequentialLayout;
})(FamousComponent);

defaults(SequentialLayout, FamousSequentialLayout);

module.exports = SequentialLayout;


text:
// Module:  Log4CPLUS
// File:    thread-config.h
// Created: 4/2003
// Author:  Tad E. Smith
//
//
// Copyright 2003-2009 Tad E. Smith
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** @file */

#ifndef LOG4CPLUS_HELPERS_THREAD_CONFIG_HEADER_
#define LOG4CPLUS_HELPERS_THREAD_CONFIG_HEADER_

#define INCLUDE_CSTDDEF               /* For NULL */
#include "dcmtk/ofstd/ofstdinc.h"

#ifdef LOG4CPLUS_USE_PTHREADS
#   include <pthread.h>
#   include <semaphore.h>
#   define LOG4CPLUS_MUTEX_PTR_DECLARE pthread_mutex_t*
#   define LOG4CPLUS_MUTEX_CREATE ::log4cplus::thread::createNewMutex()
#   define LOG4CPLUS_MUTEX_LOCK(mutex) pthread_mutex_lock(mutex)
#   define LOG4CPLUS_MUTEX_UNLOCK(mutex) pthread_mutex_unlock(mutex)
#   define LOG4CPLUS_MUTEX_FREE(mutex) ::log4cplus::thread::deleteMutex(mutex)
#   define LOG4CPLUS_THREAD_HANDLE_TYPE  pthread_t
#   define LOG4CPLUS_THREAD_KEY_TYPE pthread_t
#   define LOG4CPLUS_GET_CURRENT_THREAD_NAME \
    ::log4cplus::thread::getCurrentThreadName()
#   define LOG4CPLUS_GET_CURRENT_THREAD pthread_self()
#   define LOG4CPLUS_THREAD_LOCAL_TYPE pthread_key_t*
#   define LOG4CPLUS_THREAD_LOCAL_INIT(cleanup) \
    ::log4cplus::thread::createPthreadKey(cleanup)
#   define LOG4CPLUS_GET_THREAD_LOCAL_VALUE(key) pthread_getspecific(*(key))
#   define LOG4CPLUS_SET_THREAD_LOCAL_VALUE(key, value) \
    pthread_setspecific(*(key), value)
#   define LOG4CPLUS_THREAD_LOCAL_CLEANUP(key) \
    do { pthread_key_t * pthkey (key); pthread_key_delete(*pthkey); \
    delete pthkey; } while(0)
namespace log4cplus {
    namespace thread {
        LOG4CPLUS_EXPORT LOG4CPLUS_MUTEX_PTR_DECLARE createNewMutex();
        LOG4CPLUS_EXPORT void deleteMutex(LOG4CPLUS_MUTEX_PTR_DECLARE);
        LOG4CPLUS_EXPORT LOG4CPLUS_THREAD_LOCAL_TYPE createPthreadKey(void (*) (void *));
    }
}

#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
#   undef WIN32_LEAN_AND_MEAN
#   define WIN32_LEAN_AND_MEAN
#   include <windows.h>

#   define LOG4CPLUS_MUTEX_PTR_DECLARE CRITICAL_SECTION*
#   define LOG4CPLUS_MUTEX_CREATE ::log4cplus::thread::createNewMutex()
#   define LOG4CPLUS_MUTEX_LOCK(mutex)  EnterCriticalSection(mutex)
#   define LOG4CPLUS_MUTEX_UNLOCK(mutex)  LeaveCriticalSection(mutex)
#   define LOG4CPLUS_MUTEX_FREE(mutex) ::log4cplus::thread::deleteMutex(mutex)

#   define LOG4CPLUS_THREAD_HANDLE_TYPE  HANDLE
#   define LOG4CPLUS_THREAD_KEY_TYPE  DWORD
#   define LOG4CPLUS_GET_CURRENT_THREAD  GetCurrentThreadId()
#   define LOG4CPLUS_GET_CURRENT_THREAD_NAME \
    ::log4cplus::thread::getCurrentThreadName()
#   define LOG4CPLUS_THREAD_LOCAL_TYPE DWORD
#   define LOG4CPLUS_THREAD_LOCAL_INIT(cleanup) TlsAlloc()
#   define LOG4CPLUS_GET_THREAD_LOCAL_VALUE(key) TlsGetValue(key)
#   define LOG4CPLUS_SET_THREAD_LOCAL_VALUE(key, value) \
    TlsSetValue(key, OFstatic_cast(LPVOID, value))
#   define LOG4CPLUS_THREAD_LOCAL_CLEANUP(key) TlsFree(key)
#   if defined (_MSC_VER)
#     undef LOG4CPLUS_HAVE_TLS_SUPPORT
#     undef LOG4CPLUS_THREAD_LOCAL_VAR
// Comment out the following two lines if you do intend to use log4cplus.dll
// for loading using LoadLibrary(). The __declspec(thread) functionality is not
// compatible with such DLL use. For more information why is this necessary see
// <http://msdn.microsoft.com/en-us/library/2s9wt68x(vs.80).aspx>.
#     define LOG4CPLUS_HAVE_TLS_SUPPORT 1
#     define LOG4CPLUS_THREAD_LOCAL_VAR __declspec(thread)
#   endif

namespace log4cplus { namespace thread {

LOG4CPLUS_EXPORT LOG4CPLUS_MUTEX_PTR_DECLARE createNewMutex();
LOG4CPLUS_EXPORT void deleteMutex(LOG4CPLUS_MUTEX_PTR_DECLARE);

} } // namespace log4cplus { namespace thread {

#elif defined(LOG4CPLUS_SINGLE_THREADED)
#   define LOG4CPLUS_MUTEX_PTR_DECLARE int*
#   define LOG4CPLUS_MUTEX_CREATE NULL
#   define LOG4CPLUS_MUTEX_LOCK(mutex)
#   define LOG4CPLUS_MUTEX_UNLOCK(mutex)
#   define LOG4CPLUS_MUTEX_FREE(mutex)
#   define LOG4CPLUS_THREAD_HANDLE_TYPE  void *
#   define LOG4CPLUS_THREAD_KEY_TYPE int
#   define LOG4CPLUS_GET_CURRENT_THREAD 1
#   define LOG4CPLUS_GET_CURRENT_THREAD_NAME \
    LOG4CPLUS_C_STR_TO_TSTRING("single")
#   define LOG4CPLUS_THREAD_LOCAL_TYPE void*
#   define LOG4CPLUS_THREAD_LOCAL_INIT(cleanup) NULL
#   define LOG4CPLUS_GET_THREAD_LOCAL_VALUE(key) (key)
#   define LOG4CPLUS_SET_THREAD_LOCAL_VALUE(key, value) \
    do { (key) = (value); } while (0)
#   define LOG4CPLUS_THREAD_LOCAL_CLEANUP(key) do { (key) = NULL; } while (0)
#   undef LOG4CPLUS_HAVE_TLS_SUPPORT
#   undef LOG4CPLUS_THREAD_LOCAL_VAR

#else
#   error "You Must define a Threading model"
#endif

/**
 * @def LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX(mutex)
 * Begin a block synchronized on a mutex.
 *
 * @see LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
 *
 * @def LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
 * End a block synchronized on a mutex.
 *
 * @see LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX
 */
#ifndef LOG4CPLUS_SINGLE_THREADED
#  define LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX(mutex) \
             do { ::log4cplus::thread::Guard _sync_guard_object(mutex);
#else
#  define LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX(mutex) do { (void)(mutex);
#endif

#define LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX } while (0)

#endif // LOG4CPLUS_HELPERS_THREAD_CONFIG_HEADER_


text:
package com.vrachieru.cnp4j.exception;

public class InvalidDateOfBirthException extends Cnp4jException {
    public InvalidDateOfBirthException() {
        super();
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:orientation="vertical">

    <com.acg12.lib.widget.recycle.CommonRecycleview
        android:id="@+id/common_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <FrameLayout
        android:id="@+id/video_full_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


text:
package controllers

import akka.actor.ActorSystem
import akka.util.Timeout
import play.modules.reactivemongo.MongoController
import reactivemongo.api.DB
import utils.QueryStringParser

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

import akka.pattern.ask

import play.api.libs.ws.WS
import play.api.mvc._
import play.api.libs.json.{Json, JsValue, JsSuccess, JsError}
import play.api.Play.current

import models.{User, FacebookProfile}

import services.{UserService, JWTService}
import services.JWTService.Generate
import services.UserService.CreateOrMergeUser

object Authentication extends Controller with MongoController {
  val system: ActorSystem = ActorSystem("authentication")
  implicit val timeout = Timeout.intToTimeout(60 * 1000) // Long timeout because we do two operation over internet
  val userService = system.actorOf(UserService.props(db))
  val jwtService = system.actorOf(JWTService.props)

  case class AuthData(redirectUri: String, code: String)
  object AuthData {
    implicit val fmt = Json.format[AuthData]

    def fromRequest(implicit request: Request[JsValue]) =
      request.body.validate[AuthData]
  }

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

  def facebook() = Action.async(parse.json) { implicit request =>
    val clientId = "your-facebook-app-id"
    val clientSecret = "your-facebook-app-secret"
    val accessTokenUrl = "https://graph.facebook.com/v2.3/oauth/access_token"
    val graphApiUrl = "https://graph.facebook.com/v2.3/me"
    AuthData.fromRequest match {
      case JsSuccess(data, _) =>
        // Step 1. Exchange authorization code for access token.
        val accessTokenData =
          WS.url(accessTokenUrl)
            .withQueryString(
              "redirect_uri" -> data.redirectUri,
              "code" -> data.code,
              "client_id" -> clientId,
              "client_secret" -> clientSecret)
            .get
            .map(_.body)
            .map(QueryStringParser.parse)
            .map(_.get)

        val accessToken = accessTokenData.map(_("access_token"))

        // Step 2. Retrieve information about the current user.
        val profile = accessToken.flatMap{ t =>
          WS.url(graphApiUrl)
            .withQueryString("access_token" -> t)
            .get
        }.map(_.json.validate[FacebookProfile]).map(_.get)

        // Step 3. update/merge/create our data and fetch user
        val user = profile.flatMap(userService ? CreateOrMergeUser(_)).mapTo[User]

        // Step 4. Generate JWT and send it back to client
        val token = user.flatMap(jwtService ? Generate(_)).mapTo[String]

        token map { t =>
          Created(Json.obj("token" -> t))
        } recover {
          case e: Exception =>
            println(e)
            InternalServerError
        }
      case e: JsError =>
        Future successful BadRequest(JsError.toFlatJson(e))
    }
  }

  def foursquare() = Action.async(parse.json) { implicit request =>
    ???
  }

  def google() = Action.async(parse.json) { implicit request =>
    ???
  }

  def github() = Action.async(parse.json) { implicit request =>
    ???
  }

  def linkedin() = Action.async(parse.json) { implicit request =>
    ???
  }

  def twitter() = Action.async(parse.json) { implicit request =>
    ???
  }

}


text:
package org.apache.druid.indexing.common.task;

import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.LocalInputSource;
import org.apache.druid.data.input.impl.NoopInputFormat;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.guice.FirehoseModule;
import org.apache.druid.indexer.HadoopIOConfig;
import org.apache.druid.indexer.HadoopIngestionSpec;
import org.apache.druid.indexer.partitions.DynamicPartitionsSpec;
import org.apache.druid.indexer.partitions.PartitionsSpec;
import org.apache.druid.indexing.common.TestUtils;
import org.apache.druid.indexing.common.task.IndexTask.IndexIOConfig;
import org.apache.druid.indexing.common.task.IndexTask.IndexIngestionSpec;
import org.apache.druid.indexing.common.task.IndexTask.IndexTuningConfig;
import org.apache.druid.indexing.common.task.batch.parallel.ParallelIndexTuningConfig;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.DoubleSumAggregatorFactory;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.incremental.RowIngestionMetersFactory;
import org.apache.druid.segment.indexing.DataSchema;
import org.apache.druid.segment.indexing.RealtimeIOConfig;
import org.apache.druid.segment.indexing.RealtimeTuningConfig;
import org.apache.druid.segment.indexing.granularity.UniformGranularitySpec;
import org.apache.druid.segment.realtime.FireDepartment;
import org.apache.druid.segment.realtime.firehose.LocalFirehoseFactory;
import org.apache.druid.server.security.AuthTestUtils;
import org.apache.druid.timeline.partition.NoneShardSpec;
import org.hamcrest.CoreMatchers;
import org.joda.time.Period;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.File;

public class TaskSerdeTest
{
  private final ObjectMapper jsonMapper;
  private final RowIngestionMetersFactory rowIngestionMetersFactory;
  private final IndexSpec indexSpec = new IndexSpec();

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  public TaskSerdeTest()
  {
    TestUtils testUtils = new TestUtils();
    jsonMapper = testUtils.getTestObjectMapper();
    rowIngestionMetersFactory = testUtils.getRowIngestionMetersFactory();

    for (final Module jacksonModule : new FirehoseModule().getJacksonModules()) {
      jsonMapper.registerModule(jacksonModule);
    }
    jsonMapper.registerSubtypes(
        new NamedType(ParallelIndexTuningConfig.class, "index_parallel"),
        new NamedType(IndexTuningConfig.class, "index")
    );
  }

  @Test
  public void testIndexTaskIOConfigDefaults() throws Exception
  {
    final IndexTask.IndexIOConfig ioConfig = jsonMapper.readValue(
        "{\"type\":\"index\",\"inputSource\":{\"type\":\"noop\"},\"inputFormat\":{\"type\":\"noop\"}}",
        IndexTask.IndexIOConfig.class
    );

    Assert.assertEquals(false, ioConfig.isAppendToExisting());
  }

  @Test
  public void testIndexTaskTuningConfigDefaults() throws Exception
  {
    final IndexTask.IndexTuningConfig tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\"}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertFalse(tuningConfig.isReportParseExceptions());
    Assert.assertEquals(new IndexSpec(), tuningConfig.getIndexSpec());
    Assert.assertEquals(new Period(Integer.MAX_VALUE), tuningConfig.getIntermediatePersistPeriod());
    Assert.assertEquals(0, tuningConfig.getMaxPendingPersists());
    Assert.assertEquals(1000000, tuningConfig.getMaxRowsInMemory());
    Assert.assertNull(tuningConfig.getNumShards());
    Assert.assertNull(tuningConfig.getMaxRowsPerSegment());
  }

  @Test
  public void testIndexTaskTuningConfigTargetPartitionSizeOrNumShards() throws Exception
  {
    IndexTask.IndexTuningConfig tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\", \"targetPartitionSize\":10}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertEquals(10, (int) tuningConfig.getMaxRowsPerSegment());
    Assert.assertNull(tuningConfig.getNumShards());

    tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\"}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertNull(tuningConfig.getMaxRowsPerSegment());

    tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\", \"maxRowsPerSegment\":10}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertEquals(10, (int) tuningConfig.getMaxRowsPerSegment());
    Assert.assertNull(tuningConfig.getNumShards());

    tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\", \"numShards\":10, \"forceGuaranteedRollup\": true}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertNull(tuningConfig.getMaxRowsPerSegment());
    Assert.assertEquals(10, (int) tuningConfig.getNumShards());

    tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\", \"targetPartitionSize\":-1, \"numShards\":10, \"forceGuaranteedRollup\": true}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertNull(tuningConfig.getMaxRowsPerSegment());
    Assert.assertEquals(10, (int) tuningConfig.getNumShards());

    tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\", \"targetPartitionSize\":10, \"numShards\":-1}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertNull(tuningConfig.getNumShards());
    Assert.assertEquals(10, (int) tuningConfig.getMaxRowsPerSegment());

    tuningConfig = jsonMapper.readValue(
        "{\"type\":\"index\", \"targetPartitionSize\":-1, \"numShards\":-1, \"forceGuaranteedRollup\": true}",
        IndexTask.IndexTuningConfig.class
    );

    Assert.assertNull(tuningConfig.getNumShards());
    Assert.assertNotNull(tuningConfig.getMaxRowsPerSegment());
    Assert.assertEquals(PartitionsSpec.DEFAULT_MAX_ROWS_PER_SEGMENT, tuningConfig.getMaxRowsPerSegment().intValue());
  }

  @Test
  public void testIndexTaskTuningConfigTargetPartitionSizeAndNumShards() throws Exception
  {
    thrown.expectCause(CoreMatchers.isA(IllegalArgumentException.class));

    jsonMapper.readValue(
        "{\"type\":\"index\", \"targetPartitionSize\":10, \"numShards\":10, \"forceGuaranteedRollup\": true}",
        IndexTask.IndexTuningConfig.class
    );
  }

  @Test
  public void testTaskResourceValid() throws Exception
  {
    TaskResource actual = jsonMapper.readValue(
        "{\"availabilityGroup\":\"index_xxx_mmm\", \"requiredCapacity\":1}",
        TaskResource.class
    );
    Assert.assertNotNull(actual);
    Assert.assertNotNull(actual.getAvailabilityGroup());
    Assert.assertTrue(actual.getRequiredCapacity() > 0);
  }

  @Test
  public void testTaskResourceWithNullAvailabilityGroupShouldFail() throws Exception
  {
    thrown.expectCause(CoreMatchers.isA(NullPointerException.class));
    jsonMapper.readValue(
        "{\"availabilityGroup\":null, \"requiredCapacity\":10}",
        TaskResource.class
    );
  }

  @Test
  public void testTaskResourceWithZeroRequiredCapacityShouldFail() throws Exception
  {
    thrown.expectCause(CoreMatchers.isA(NullPointerException.class));
    jsonMapper.readValue(
        "{\"availabilityGroup\":null, \"requiredCapacity\":0}",
        TaskResource.class
    );
  }

  @Test
  public void testTaskResourceWithNegativeRequiredCapacityShouldFail() throws Exception
  {
    thrown.expectCause(CoreMatchers.isA(NullPointerException.class));
    jsonMapper.readValue(
        "{\"availabilityGroup\":null, \"requiredCapacity\":-1}",
        TaskResource.class
    );
  }

  @Test
  public void testIndexTaskSerde() throws Exception
  {
    final IndexTask task = new IndexTask(
        null,
        null,
        new IndexIngestionSpec(
            new DataSchema(
                "foo",
                new TimestampSpec(null, null, null),
                DimensionsSpec.EMPTY,
                new AggregatorFactory[]{new DoubleSumAggregatorFactory("met", "met")},
                new UniformGranularitySpec(
                    Granularities.DAY,
                    null,
                    ImmutableList.of(Intervals.of("2010-01-01/P2D"))
                ),
                null
            ),
            new IndexIOConfig(null, new LocalInputSource(new File("lol"), "rofl"), new NoopInputFormat(), true),
            new IndexTuningConfig(
                null,
                null,
                null,
                10,
                null,
                null,
                9999,
                null,
                null,
                new DynamicPartitionsSpec(10000, null),
                indexSpec,
                null,
                3,
                false,
                null,
                null,
                null,
                null,
                null,
                null,
                null
            )
        ),
        null
    );

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final IndexTask task2 = (IndexTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());

    IndexTask.IndexIOConfig taskIoConfig = task.getIngestionSchema().getIOConfig();
    IndexTask.IndexIOConfig task2IoConfig = task2.getIngestionSchema().getIOConfig();

    Assert.assertTrue(taskIoConfig.getInputSource() instanceof LocalInputSource);
    Assert.assertTrue(task2IoConfig.getInputSource() instanceof LocalInputSource);
    Assert.assertEquals(taskIoConfig.isAppendToExisting(), task2IoConfig.isAppendToExisting());

    IndexTask.IndexTuningConfig taskTuningConfig = task.getIngestionSchema().getTuningConfig();
    IndexTask.IndexTuningConfig task2TuningConfig = task2.getIngestionSchema().getTuningConfig();

    Assert.assertEquals(taskTuningConfig.getBasePersistDirectory(), task2TuningConfig.getBasePersistDirectory());
    Assert.assertEquals(taskTuningConfig.getIndexSpec(), task2TuningConfig.getIndexSpec());
    Assert.assertEquals(
        taskTuningConfig.getIntermediatePersistPeriod(),
        task2TuningConfig.getIntermediatePersistPeriod()
    );
    Assert.assertEquals(taskTuningConfig.getMaxPendingPersists(), task2TuningConfig.getMaxPendingPersists());
    Assert.assertEquals(taskTuningConfig.getMaxRowsInMemory(), task2TuningConfig.getMaxRowsInMemory());
    Assert.assertEquals(taskTuningConfig.getNumShards(), task2TuningConfig.getNumShards());
    Assert.assertEquals(taskTuningConfig.getMaxRowsPerSegment(), task2TuningConfig.getMaxRowsPerSegment());
    Assert.assertEquals(taskTuningConfig.isReportParseExceptions(), task2TuningConfig.isReportParseExceptions());
  }

  @Test
  public void testIndexTaskwithResourceSerde() throws Exception
  {
    final IndexTask task = new IndexTask(
        null,
        new TaskResource("rofl", 2),
        new IndexIngestionSpec(
            new DataSchema(
                "foo",
                new TimestampSpec(null, null, null),
                DimensionsSpec.EMPTY,
                new AggregatorFactory[]{new DoubleSumAggregatorFactory("met", "met")},
                new UniformGranularitySpec(
                    Granularities.DAY,
                    null,
                    ImmutableList.of(Intervals.of("2010-01-01/P2D"))
                ),
                null
            ),
            new IndexIOConfig(null, new LocalInputSource(new File("lol"), "rofl"), new NoopInputFormat(), true),
            new IndexTuningConfig(
                null,
                null,
                null,
                10,
                null,
                null,
                null,
                null,
                null,
                new DynamicPartitionsSpec(10000, null),
                indexSpec,
                null,
                3,
                false,
                null,
                null,
                null,
                null,
                null,
                null,
                null
            )
        ),
        null
    );

    for (final Module jacksonModule : new FirehoseModule().getJacksonModules()) {
      jsonMapper.registerModule(jacksonModule);
    }

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final IndexTask task2 = (IndexTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(2, task.getTaskResource().getRequiredCapacity());
    Assert.assertEquals("rofl", task.getTaskResource().getAvailabilityGroup());
    Assert.assertEquals(task.getTaskResource().getRequiredCapacity(), task2.getTaskResource().getRequiredCapacity());
    Assert.assertEquals(task.getTaskResource().getAvailabilityGroup(), task2.getTaskResource().getAvailabilityGroup());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertTrue(task.getIngestionSchema().getIOConfig().getInputSource() instanceof LocalInputSource);
    Assert.assertTrue(task2.getIngestionSchema().getIOConfig().getInputSource() instanceof LocalInputSource);
  }

  @Test
  public void testRealtimeIndexTaskSerde() throws Exception
  {

    final RealtimeIndexTask task = new RealtimeIndexTask(
        null,
        new TaskResource("rofl", 2),
        new FireDepartment(
            new DataSchema(
                "foo",
                null,
                new AggregatorFactory[0],
                new UniformGranularitySpec(Granularities.HOUR, Granularities.NONE, null),
                null,
                jsonMapper
            ),
            new RealtimeIOConfig(
                new LocalFirehoseFactory(new File("lol"), "rofl", null),
                (schema, config, metrics) -> null
            ),

            new RealtimeTuningConfig(
                null,
                1,
                10L,
                new Period("PT10M"),
                null,
                null,
                null,
                null,
                1,
                NoneShardSpec.instance(),
                indexSpec,
                null,
                null,
                0,
                0,
                true,
                null,
                null,
                null,
                null
            )
        ),
        null
    );

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final RealtimeIndexTask task2 = (RealtimeIndexTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());
    Assert.assertEquals(2, task.getTaskResource().getRequiredCapacity());
    Assert.assertEquals("rofl", task.getTaskResource().getAvailabilityGroup());
    Assert.assertEquals(
        new Period("PT10M"),
        task.getRealtimeIngestionSchema()
            .getTuningConfig().getWindowPeriod()
    );
    Assert.assertEquals(
        Granularities.HOUR,
        task.getRealtimeIngestionSchema().getDataSchema().getGranularitySpec().getSegmentGranularity()
    );
    Assert.assertTrue(task.getRealtimeIngestionSchema().getTuningConfig().isReportParseExceptions());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(task.getTaskResource().getRequiredCapacity(), task2.getTaskResource().getRequiredCapacity());
    Assert.assertEquals(task.getTaskResource().getAvailabilityGroup(), task2.getTaskResource().getAvailabilityGroup());
    Assert.assertEquals(
        task.getRealtimeIngestionSchema().getTuningConfig().getWindowPeriod(),
        task2.getRealtimeIngestionSchema().getTuningConfig().getWindowPeriod()
    );
    Assert.assertEquals(
        task.getRealtimeIngestionSchema().getTuningConfig().getMaxBytesInMemory(),
        task2.getRealtimeIngestionSchema().getTuningConfig().getMaxBytesInMemory()
    );
    Assert.assertEquals(
        task.getRealtimeIngestionSchema().getDataSchema().getGranularitySpec().getSegmentGranularity(),
        task2.getRealtimeIngestionSchema().getDataSchema().getGranularitySpec().getSegmentGranularity()
    );
  }

  @Test
  public void testArchiveTaskSerde() throws Exception
  {
    final ArchiveTask task = new ArchiveTask(
        null,
        "foo",
        Intervals.of("2010-01-01/P1D"),
        null
    );

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final ArchiveTask task2 = (ArchiveTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());
    Assert.assertEquals(Intervals.of("2010-01-01/P1D"), task.getInterval());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(task.getInterval(), task2.getInterval());
  }

  @Test
  public void testRestoreTaskSerde() throws Exception
  {
    final RestoreTask task = new RestoreTask(
        null,
        "foo",
        Intervals.of("2010-01-01/P1D"),
        null
    );

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final RestoreTask task2 = (RestoreTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());
    Assert.assertEquals(Intervals.of("2010-01-01/P1D"), task.getInterval());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(task.getInterval(), task2.getInterval());
  }

  @Test
  public void testMoveTaskSerde() throws Exception
  {
    final MoveTask task = new MoveTask(
        null,
        "foo",
        Intervals.of("2010-01-01/P1D"),
        ImmutableMap.of("bucket", "hey", "baseKey", "what"),
        null,
        null
    );

    final String json = jsonMapper.writeValueAsString(task);

    Thread.sleep(100); // Just want to run the clock a bit to make sure the task id doesn't change
    final MoveTask task2 = (MoveTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());
    Assert.assertEquals(Intervals.of("2010-01-01/P1D"), task.getInterval());
    Assert.assertEquals(ImmutableMap.<String, Object>of("bucket", "hey", "baseKey", "what"), task.getTargetLoadSpec());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(task.getInterval(), task2.getInterval());
    Assert.assertEquals(task.getTargetLoadSpec(), task2.getTargetLoadSpec());
  }

  @Test
  public void testHadoopIndexTaskSerde() throws Exception
  {
    final HadoopIndexTask task = new HadoopIndexTask(
        null,
        new HadoopIngestionSpec(
            new DataSchema(
                "foo", null, new AggregatorFactory[0], new UniformGranularitySpec(
                Granularities.DAY,
                null,
                ImmutableList.of(Intervals.of("2010-01-01/P1D"))
            ),
                null,
                jsonMapper
            ), new HadoopIOConfig(ImmutableMap.of("paths", "bar"), null, null), null
        ),
        null,
        null,
        "blah",
        jsonMapper,
        null,
        AuthTestUtils.TEST_AUTHORIZER_MAPPER,
        null
    );

    final String json = jsonMapper.writeValueAsString(task);

    final HadoopIndexTask task2 = (HadoopIndexTask) jsonMapper.readValue(json, Task.class);

    Assert.assertEquals("foo", task.getDataSource());

    Assert.assertEquals(task.getId(), task2.getId());
    Assert.assertEquals(task.getGroupId(), task2.getGroupId());
    Assert.assertEquals(task.getDataSource(), task2.getDataSource());
    Assert.assertEquals(
        task.getSpec().getTuningConfig().getJobProperties(),
        task2.getSpec().getTuningConfig().getJobProperties()
    );
    Assert.assertEquals("blah", task.getClasspathPrefix());
    Assert.assertEquals("blah", task2.getClasspathPrefix());
  }
}


text:
/**
 * Routes
 *
 * Your routes map URLs to views and controllers.
 *
 * If Sails receives a URL that doesn't match any of the routes below,
 * it will check for matching files (images, scripts, stylesheets, etc.)
 * in your assets directory.  e.g. `http://localhost:1337/images/foo.jpg`
 * might match an image file: `/assets/images/foo.jpg`
 *
 * Finally, if those don't match either, the default 404 handler is triggered.
 * See `config/404.js` to adjust your app's 404 logic.
 *
 * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
 * flat files from `assets` to `.tmp/public`.  This allows you to do things like compile LESS or
 * CoffeeScript for the front-end.
 *
 * For more information on routes, check out:
 * http://sailsjs.org/#documentation
 */

module.exports.routes = {

  // Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, etc. depending on your
  // default view engine) your home page.
  //
  // (Alternatively, remove this and add an `index.html` file in your `assets` directory)
  'get /': {
    controller: 'ItemController',
    action: 'search'
  },

  'get /login': 'AuthController.login',
  'get /logout': 'AuthController.logout',
  'get /register': 'AuthController.register',

  'post /auth/local': 'AuthController.callback',
  'post /auth/local/:action': 'AuthController.callback',

  // Custom routes here...

    /**
     * User routes
     */
    'get /api/user': 'UserController.getAll',
    'get /api/user/:id': 'UserController.getOne',
    'post /api/user': 'UserController.create',
     /**
     * Item routes
     */
    'get /api/item/getAll': 'ItemController.getAll',
    'get /api/item/getMylist/:id':  'ItemController.getMylist',
    'post /api/item/sendMessage': 'ItemController.sendMessage',
    'post /api/item/join/users': 'ItemController.join',

    'get /item/create':  'ItemController.create',
    'get /item/getAll':  'ItemController.getAll',
    'get /item/search':  'ItemController.search',
    'get /item/mylist':  'ItemController.mylist',
    'post /item/upload': 'ItemController.upload',
    'get /item/:id':     'ItemController.detail',

  /**
     * Message routes
     *
     */
    'get /api/message': 'MessageController.getAll',
    'get /api/message/:id': 'MessageController.getOne',
    'post /api/message': 'MessageController.create',
    'put /api/message': 'MessageController.update',
//    'put /api/message/:id': 'MessageController.update',

    /**
     * Zipcode routes
     */
    'get /api/zipcode': 'ZipcodeController.getByCity',

    'delete /api/message/:id': 'MessageController.destroy',

    //todo
    'get /api/todo': 'TodoController.getAll',
    'get /todo/search': 'TodoController.search',
    'get /api/todo/:id': 'TodoController.getOne',
    'post /api/todo': 'TodoController.create',
    'delete /api/todo/:id': 'TodoController.destroy',

  // If a request to a URL doesn't match any of the custom routes above, it is matched
  // against Sails route blueprints.  See `config/blueprints.js` for configuration options
  // and examples.

  'get /home': 'HomeController.index',
  'get /about': 'HomeController.about',
  'get /messages': 'HomeController.index',
  'get /todos': 'HomeController.index',
  'get /zipcodes': 'HomeController.index',
  'get /itemLists': 'HomeController.index',

};


text:
package com.szparag.ijtest1;

import java.io.*;
import java.net.Socket;

public class CivServerThread extends Thread
{

    private CivServer server = null;
    private Socket socket = null;
    private  int ID = -1;
    private  ObjectInputStream streamIn = null;
    private  ObjectOutputStream streamOut = null;
    private int playerCount;
    private boolean onetime = true;

    public CivServerThread(CivServer server,Socket socket, int playerCount) {
        System.out.println(Long.toString(System.nanoTime()) + " CivServerThread: constructor();");
        this.server = server;
        this.socket = socket;
        ID = socket.getPort();
        this.playerCount = playerCount;
    }

    public void open() throws  IOException {
        System.out.println(Long.toString(System.nanoTime()) + " CivServerThread: open();");
        streamIn = CivServerThread.createObjectStreamIn(socket);
        streamOut = CivServerThread.createObjectStreamOut(socket);
    }

    public static ObjectOutputStream createObjectStreamOut(Socket socket) throws IOException {
        OutputStream stream = socket.getOutputStream();
        return  new ObjectOutputStream(stream);

    }

    public  static  ObjectInputStream createObjectStreamIn(Socket socket) throws  IOException {
        InputStream stream = socket.getInputStream();
        return  new ObjectInputStream(stream);
    }

    public void run() {
        System.out.println(Long.toString(System.nanoTime()) + " CivServerThread: run();");
        //!
     //   send(server.getActualPackage());
        while (true) {
            try {
                System.err.println(Long.toString(System.nanoTime()) + " CivSrvThread: Object received from pipe;");
                server.handle(streamIn.readObject());
            } catch (IOException e) {
                server.setConninfochar(e.getMessage());
                server.setOnline(false);
                e.printStackTrace();
                stop();
            } catch (ClassNotFoundException e) {
                server.setConninfochar(e.getMessage());
                server.setOnline(false);
                e.printStackTrace();
                stop();
            }
        }
    }

   public void send(Object object){
       System.out.println(Long.toString(System.nanoTime()) + " CivServerThread: send();");
       try {
           streamOut.writeObject(object);
       } catch (IOException e) {
           server.setConninfochar(e.getMessage());
           server.setOnline(false);
           e.printStackTrace();
       }
   }

    public void close()throws  IOException {
        System.out.println(Long.toString(System.nanoTime()) + " CivServerThread: close();");
        if(socket != null)
            socket.close();
        if(streamOut != null)
            streamOut.close();
        if(streamIn != null)
            streamIn.close();
    }

}