text:
sync_attr [![Build Status](https://secure.travis-ci.org/reidmorrison/sync_attr.png?branch=master)](http://travis-ci.org/reidmorrison/sync_attr)
=========

Thread-safe Ruby class and instance attributes

* http://github.com/reidmorrison/sync_attr

## Status

Enterprise Production Ready - In daily use in large multi-threaded application

## Introduction

When working in a multi-threaded environment it is important to ensure that
any attributes that are shared across threads are properly protected to ensure
that inconsistent data is not created. Lazy initializing these safe attributes
improves startup times and only creates resources when they are needed.

For example, without sync_attr if two threads attempt to write to the
same attribute at the same time it is not deterministic what the results will be.
This condition is made worse when two threads attempt to initialize class instance
attributes at the same time that could take a second or longer to complete.

A `sync_cattr_reader` is ideal for holding data loaded from configuration files.
Also, shared objects, such as connection pools can be safely initialized and
shared in this way across hundreds of threads.
Once initialized all reads are shared without locks since no writer is defined.

Aside from safely sharing reads `sync_cattr_accessor` also ensures that data
is not read while it is being modified. The writes are completely thread-safe
ensuring that only one thread is modifying the value at a time and that reads
are suspended until the write is complete.

## Features

* Adds thread-safe accessors for class instance attributes.
* Only one thread can read or write the value at any one time.
* Prevents attributes from being read while it is being updated or initialized for
  the first time.
* Thread-safe attribute lazy initialization.
  Lazy initialization allows class attributes to be loaded only when first read.
  As a result it's value can be read for the first time from a database or
  configuration file once and only when needed.
* Avoids having to create yet another Rails initializer, when the data can be
  fetched or held by a class instance attribute.
* Avoids costly startup initialization when the initialized data may never be accessed.
  For example, when Rake tasks are run, they may not need access to everything in
  the Rails environment.
* Works with Rails and regular Ruby.

## Thread-safe Class Attribute example

Create a reader for a class attribute and lazy initialize its value on the first
attempt to read it. I.e. Lazy initialize the value.

Very useful for initializing shared services that take time to initialize.
In particular services that may not even be called in a specific process,
for example when running rake, or when opening a console.

An optional block can be supplied to initialize the synchronized class attribute
when it is first read. The initializer is thread safe and will block all other
reads to this attribute while it is being initialized. This ensures that the
initializer is only run once and that all threads to call the reader receive the
same value, regardless of how many threads call the reader at the same time.

Example:

```ruby
require 'sync_attr'

# Sample class with lazy initialized Thread-safe Class Attributes
class Person
  # Create a reader for the class attribute :name
  # and lazy initialize the value to 'Joe Bloggs' only on the first
  # call to the reader.
  # Ideal for when :name is loaded from a database or configuration file.
  sync_cattr_reader :name do
    'Joe Bloggs'
  end

  # Create a reader and a writer for the class attribute :age
  # and lazy initialize the value to 21 only on the first
  # call to the reader.
  sync_cattr_accessor :age do
    21
  end
end

puts "The person is #{Person.name} with age #{Person.age}"

Person.age = 22
puts "The person is #{Person.name} now has age #{Person.age}"

# => The person is Joe Bloggs now has age 22

Person.age = Proc.new {|age| age += 1 }
puts "The person is #{Person.name} now has age #{Person.age}"

# => The person is Joe Bloggs now has age 23
```

## Thread-safe Instance Attribute example

Create a reader for an attribute and lazy initialize its value on the first
attempt to read it. I.e. Lazy initialize the value.

An optional block can be supplied to initialize the synchronized attribute
when it is first read. The initializer is thread safe and will block all other
reads to this attribute while it is being initialized. This ensures that the
initializer is only run once per object and that all threads to call the reader
receive the same value, regardless of how many threads call the reader at the same time.

Example:

```ruby
require 'sync_attr'

# Sample class with lazy initialized Thread-safe attributes
class Person
  include SyncAttr::Attributes

  # Create a reader for the thread-safe attribute :name
  # and lazy initialize the value to 'Joe Bloggs' only on the first
  # call to the reader.
  sync_attr_reader :name do
    'Joe Bloggs'
  end

  # Create a thread-safe reader and a writer for the attribute :age
  # and lazy initialize the value to 21 only on the first
  # call to the reader.
  sync_attr_accessor :age do
    21
  end
end

person = Person.new
puts "The person is #{person.name} with age #{person.age}"

# => The person is Joe Bloggs with age 21

person.age = 22
puts "The person is #{person.name} now has age #{person.age}"

# => The person is Joe Bloggs now has age 22

person.age = Proc.new {|age| age += 1 }
puts "The person is #{person.name} now has age #{person.age}"

# => The person is Joe Bloggs now has age 23
```

## Install

  gem install sync_attr

Meta
----

* Code: `git clone git://github.com/reidmorrison/sync_attr.git`
* Home: <https://github.com/reidmorrison/sync_attr>
* Bugs: <http://github.com/reidmorrison/sync_attr/issues>
* Gems: <http://rubygems.org/gems/sync_attr>

This project uses [Semantic Versioning](http://semver.org/).

Authors
-------

Reid Morrison :: reidmo@gmail.com :: @reidmorrison

License
-------

Copyright 2012, 2013, 2014, 2015 Reid Morrison

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.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

    Successful response returned for a Cosmos request
    http://api.technorati.com/cosmos?key=VALID_API_KEY&url=www.simonecarletti.com/blog&type=weblog&claim=1

    The request has the following properties:
     * url is blog
     * type is weblog
     * claim = 1

    When claim is enabled Technorati *returns* details
    about the author who claimed the blog, if any.

    TECHNORATI BUG: for somewhat reason Technorati decided
    this option doens't work when type is weblog.
    Don't ask me why, that's the way it goes!

    See
     * http://sitaram.splinder.com
     * http://www.dreamsworld.it/emanuele
     * http://robyww.blogspot.com
    and more below compared with TestCosmosBlogWeblogClaim.xml

-->
<!-- generator="Technorati API version 1.0" -->
<!DOCTYPE tapi PUBLIC "-//Technorati, Inc.//DTD TAPI 0.02//EN" "http://api.technorati.com/dtd/tapi-002.xml">
<tapi version="1.0">
    <document>
        <result>
            <url>www.simonecarletti.com/blog</url>
            <weblog>
                <name>Simone Carletti's Blog</name>
                <url>http://www.simonecarletti.com/blog</url>
                <atomurl>http://www.simonecarletti.com/blog/index.xml</atomurl>
                <inboundblogs>85</inboundblogs>
                <inboundlinks>112</inboundlinks>
                <lastupdate>2007-11-12 20:51:52 GMT</lastupdate>
                <rank>81766</rank>
            </weblog>
            <inboundblogs>85</inboundblogs>
            <inboundlinks/>
            <rankingstart>1</rankingstart>
        </result>
        <item>
            <weblog>
                <name> Gioxx's Wall</name>
                <url>http://gioxx.org</url>
                <inboundblogs>271</inboundblogs>
                <inboundlinks>774</inboundlinks>
                <lastupdate>2007-11-12 17:01:29 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Controrete - Search Marketing e dintorni</name>
                <url>http://controrete.blog.excite.it</url>
                <rssurl>http://feeds.feedburner.com/controrete/cFuo</rssurl>
                <inboundblogs>1</inboundblogs>
                <inboundlinks>1</inboundlinks>
                <lastupdate>1970-01-01 00:00:00 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name> Gioxx's Wall</name>
                <url>http://gioxx.wordpress.com</url>
                <inboundblogs>7</inboundblogs>
                <inboundlinks>8</inboundlinks>
                <lastupdate>2007-11-12 21:35:14 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Progetto-Seo </name>
                <url>http://www.progetto-seo.com</url>
                <rssurl>http://www.progetto-seo.com/feed/</rssurl>
                <inboundblogs>43</inboundblogs>
                <inboundlinks>84</inboundlinks>
                <lastupdate>2007-11-10 08:57:22 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Progetto-Seo </name>
                <url>http://www.progetto-seo.com</url>
                <rssurl>http://www.progetto-seo.com/feed/</rssurl>
                <inboundblogs>43</inboundblogs>
                <inboundlinks>84</inboundlinks>
                <lastupdate>2007-11-10 08:57:22 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>FeedBurner Stats 2 Feed 1.1 - Build your own FeedBurner feeds stats feed</name>
                <url>http://lab.rss-world.info/feedburner-feedstats</url>
                <rssurl>http://lab.rss-world.info/feedburner-feedstats/stats2feed.php</rssurl>
                <inboundblogs>1</inboundblogs>
                <inboundlinks>4</inboundlinks>
                <lastupdate>2007-11-07 17:54:16 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Se siamo fatti di pura energia,</name>
                <url>http://sitaram.splinder.com</url>
                <rssurl>http://syndication.splinder.com/sitaram/rss2.xml</rssurl>
                <atomurl>http://syndication.splinder.com/sitaram/atom.xml</atomurl>
                <inboundblogs>27</inboundblogs>
                <inboundlinks>49</inboundlinks>
                <lastupdate>2007-11-10 19:27:05 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>BLOG intarget.net</name>
                <url>http://blog.intarget.net</url>
                <rssurl>http://blog.intarget.net/feed</rssurl>
                <atomurl>http://blog.intarget.net/feed/atom</atomurl>
                <inboundblogs>0</inboundblogs>
                <inboundlinks>0</inboundlinks>
                <lastupdate>2007-11-06 16:58:08 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Soft Review </name>
                <url>http://softrevi.com</url>
                <rssurl>http://softrevi.com/feed/</rssurl>
                <inboundblogs>1</inboundblogs>
                <inboundlinks>1</inboundlinks>
                <lastupdate>2007-11-12 17:38:55 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Progetto-Seo </name>
                <url>http://www.progetto-seo.com</url>
                <rssurl>http://www.progetto-seo.com/feed/</rssurl>
                <inboundblogs>43</inboundblogs>
                <inboundlinks>84</inboundlinks>
                <lastupdate>2007-11-10 08:57:22 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name> Gioxx's Wall</name>
                <url>http://gioxx.wordpress.com</url>
                <inboundblogs>7</inboundblogs>
                <inboundlinks>8</inboundlinks>
                <lastupdate>2007-11-12 21:35:14 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>DreamsWorld - www.dreamsworld.it - Errore Interno del Server</name>
                <url>http://www.dreamsworld.it/emanuele</url>
                <inboundblogs>112</inboundblogs>
                <inboundlinks>354</inboundlinks>
                <lastupdate>2007-11-12 18:42:17 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name> …time is what you make of it…</name>
                <url>http://emanuele.dreamsworld.it</url>
                <rssurl>http://www.dreamsworld.it/emanuele/feed/</rssurl>
                <inboundblogs>2</inboundblogs>
                <inboundlinks>2</inboundlinks>
                <lastupdate>2007-11-12 15:24:46 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Stefano Gorgoni » Dovevo chiedervi scusa?</name>
                <url>http://www.stefanogorgoni.com/384/dovevo-chiedervi-scusa</url>
                <rssurl>http://www.stefanogorgoni.com/feed/</rssurl>
                <inboundblogs>0</inboundblogs>
                <inboundlinks>0</inboundlinks>
                <lastupdate>2007-11-02 14:11:04 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>[•] - RSS/ATOM Feeds Aggregator </name>
                <url>http://www.codicesorgente.it</url>
                <rssurl>http://www.codicesorgente.it/feedsaggregator/rss.php</rssurl>
                <inboundblogs>67</inboundblogs>
                <inboundlinks>321</inboundlinks>
                <lastupdate>2007-11-05 02:40:19 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>Roby Web World Italia</name>
                <url>http://robyww.blogspot.com</url>
                <atomurl>http://robyww.blogspot.com/feeds/posts/default</atomurl>
                <inboundblogs>71</inboundblogs>
                <inboundlinks>103</inboundlinks>
                <lastupdate>2007-11-11 08:47:26 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>ItalyFilm Blog</name>
                <url>http://italyfilm.net</url>
                <rssurl>http://italyfilm.net/feed/</rssurl>
                <atomurl>http://italyfilm.net/feed/atom/</atomurl>
                <inboundblogs>5</inboundblogs>
                <inboundlinks>39</inboundlinks>
                <lastupdate>2007-11-12 18:48:28 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>ItalyFilm Blog</name>
                <url>http://italyfilm.net</url>
                <rssurl>http://italyfilm.net/feed/</rssurl>
                <atomurl>http://italyfilm.net/feed/atom/</atomurl>
                <inboundblogs>5</inboundblogs>
                <inboundlinks>39</inboundlinks>
                <lastupdate>2007-11-12 18:48:28 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name>980km | Smart Web Marketing</name>
                <url>http://www.980km.com</url>
                <rssurl>http://feeds.980km.com/980kmSmartWebMarketing</rssurl>
                <inboundblogs>137</inboundblogs>
                <inboundlinks>327</inboundlinks>
                <lastupdate>2007-11-11 21:08:33 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
        <item>
            <weblog>
                <name> Allora vendi PageRank! E Matt Cutts lo conferma su Search Engine Journal | 980km</name>
                <url>http://www.980km.com/google/allora-vendi-pagerank-e-matt-cutts-lo-conferma-su-search-engine-journal.html</url>
                <rssurl>http://feeds.980km.com/980kmSmartWebMarketing</rssurl>
                <inboundblogs>0</inboundblogs>
                <inboundlinks>0</inboundlinks>
                <lastupdate>2007-10-31 13:06:51 GMT</lastupdate>
            </weblog>
            <linkurl>www.simonecarletti.com/blog</linkurl>
        </item>
    </document>
</tapi>

redpajama_set_name: RedPajamaGithub


text:
'use strict'

let fs = require('fs')
let path = require('path')
let _ = require('isa.js')

let Structurer = require('./generator/Structurer')
let Injector = require('./generator/Injector')

global.done = function ( message ) {
	console.log( message || 'Done.' )
	process.exit( -1 )
}

global.forceExit = function ( err ) {
	console.error( _.isString(err) ? new Error(err) : err )
	process.exit( -1 )
}

global.printUsage = function printUsage () {
	let content = fs.readFileSync( path.join(__dirname, 'usage.list' ), {encoding: 'utf8'})
	global.forceExit( content )
}

function createStructure ( structure, name, options, commands ) {
	if ( structure === 'project' ) {
		return Structurer.createProject( name, options )
	}
	else if ( structure === 'entity' ) {
		return Structurer.createEntity( name, options )
	}
	else if ( structure === 'service' ) {
		if ( commands.length < 4 ) {
			return global.printUsage()
		}
		return Structurer.createService( name, commands[3], options )
	}
	global.printUsage()
}

function createCode ( codeType, options, commands ) {
	if ( codeType === 'test' ) {
		if ( options.mocha )
			return Injector.createMochaCode( options )
	}
	global.printUsage()
}

let optionsAccepted = [ 'force', 'gulp', 'mocha', 'folder', 'amqp', 'mqtt', 'sqs', 'rest', 'websocket', 'projectFolder', 'entityName', 'appName', 'servicePort', 'web' ]
function readCommand ( commands, command ) {
	for ( let i = 0; i < commands.length; ++i ) {
		if ( commands[i] === command )
			return true
		if ( commands[i].startsWith( command + '=' ) )
			return commands[i].substring( commands[i].indexOf('=') + 1 )
	}
	return false
}
function collectOptions ( commands ) {
	let res = {}
	optionsAccepted.forEach(function ( option ) {
		res[ option ] = readCommand(commands, '--' + option)
	})
	return res
}

module.exports = {
	execute: function ( ) {
		let commands = arguments
		if ( commands.length < 3 ) {
			return global.printUsage()
		}
		let options = collectOptions( commands )
		switch ( commands[0] ) {
		case 'create':
			return createStructure( commands[1], commands[2], options, commands )
		case 'generate':
			return createCode( commands[1], options, commands )
		default:
			return global.printUsage()
		}
	}
}


text:
using namespace Furiosity;

////////////////////////////////////////////////////////////////////////////////
//
//                       - GUI Size  Animation -
//
////////////////////////////////////////////////////////////////////////////////

GUISizeAnimation::GUISizeAnimation(GUIElement* el,
                                   Vector2 from,
                                   Vector2 to,
                                   float duration,
                                   InterpolationType interpolation) :
    ParameterAnimation(el,
                       &GUIElement::SetSize,
                       from,
                       to,
                       duration,
                       interpolation) {}

GUISizeAnimation::GUISizeAnimation(GUIElement* el,
                                   Vector2 to,
                                   float duration,
                                   InterpolationType interpolation) :
    ParameterAnimation(el,
                       &GUIElement::Size,
                       &GUIElement::SetSize,
                       to,
                       duration,
                       interpolation) {}

// end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.security.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** configuration for Vulnerability Assessment autoprovisioning. */
@Fluent
public final class DefenderForServersAwsOfferingVaAutoProvisioningConfiguration {
    /*
     * The Vulnerability Assessment solution to be provisioned. Can be either 'TVM' or 'Qualys'
     */
    @JsonProperty(value = "type")
    private Type type;

    /** Creates an instance of DefenderForServersAwsOfferingVaAutoProvisioningConfiguration class. */
    public DefenderForServersAwsOfferingVaAutoProvisioningConfiguration() {
    }

    /**
     * Get the type property: The Vulnerability Assessment solution to be provisioned. Can be either 'TVM' or 'Qualys'.
     *
     * @return the type value.
     */
    public Type type() {
        return this.type;
    }

    /**
     * Set the type property: The Vulnerability Assessment solution to be provisioned. Can be either 'TVM' or 'Qualys'.
     *
     * @param type the type value to set.
     * @return the DefenderForServersAwsOfferingVaAutoProvisioningConfiguration object itself.
     */
    public DefenderForServersAwsOfferingVaAutoProvisioningConfiguration withType(Type type) {
        this.type = type;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
.class Lcom/htc/gson/DefaultTypeAdapters$MapTypeAdapter;
.super Ljava/lang/Object;
.source "DefaultTypeAdapters.java"

# interfaces
.implements Lcom/htc/gson/JsonSerializer;
.implements Lcom/htc/gson/JsonDeserializer;
.implements Lcom/htc/gson/InstanceCreator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/htc/gson/DefaultTypeAdapters;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "MapTypeAdapter"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Lcom/htc/gson/JsonSerializer",
        "<",
        "Ljava/util/Map;",
        ">;",
        "Lcom/htc/gson/JsonDeserializer",
        "<",
        "Ljava/util/Map;",
        ">;",
        "Lcom/htc/gson/InstanceCreator",
        "<",
        "Ljava/util/Map;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 604
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method private constructMapType(Ljava/lang/reflect/Type;Lcom/htc/gson/JsonDeserializationContext;)Ljava/util/Map;
    .locals 3
    .parameter "mapType"
    .parameter "context"

    .prologue
    .line 653
    move-object v0, p2

    check-cast v0, Lcom/htc/gson/JsonDeserializationContextDefault;

    .line 654
    .local v0, contextImpl:Lcom/htc/gson/JsonDeserializationContextDefault;
    invoke-virtual {v0}, Lcom/htc/gson/JsonDeserializationContextDefault;->getObjectConstructor()Lcom/htc/gson/ObjectConstructor;

    move-result-object v1

    .line 655
    .local v1, objectConstructor:Lcom/htc/gson/ObjectConstructor;
    invoke-interface {v1, p1}, Lcom/htc/gson/ObjectConstructor;->construct(Ljava/lang/reflect/Type;)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Ljava/util/Map;

    return-object v2
.end method

# virtual methods
.method public bridge synthetic createInstance(Ljava/lang/reflect/Type;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 603
    invoke-virtual {p0, p1}, Lcom/htc/gson/DefaultTypeAdapters$MapTypeAdapter;->createInstance(Ljava/lang/reflect/Type;)Ljava/util/Map;

    move-result-object v0

    return-object v0
.end method

.method public createInstance(Ljava/lang/reflect/Type;)Ljava/util/Map;
    .locals 1
    .parameter "type"

    .prologue
    .line 663
    new-instance v0, Ljava/util/LinkedHashMap;

    invoke-direct {v0}, Ljava/util/LinkedHashMap;-><init>()V

    return-object v0
.end method

.method public bridge synthetic deserialize(Lcom/htc/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/htc/gson/JsonDeserializationContext;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/htc/gson/JsonParseException;
        }
    .end annotation

    .prologue
    .line 603
    invoke-virtual {p0, p1, p2, p3}, Lcom/htc/gson/DefaultTypeAdapters$MapTypeAdapter;->deserialize(Lcom/htc/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/htc/gson/JsonDeserializationContext;)Ljava/util/Map;

    move-result-object v0

    return-object v0
.end method

.method public deserialize(Lcom/htc/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/htc/gson/JsonDeserializationContext;)Ljava/util/Map;
    .locals 8
    .parameter "json"
    .parameter "typeOfT"
    .parameter "context"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Lcom/htc/gson/JsonParseException;
        }
    .end annotation

    .prologue
    .line 642
    invoke-direct {p0, p2, p3}, Lcom/htc/gson/DefaultTypeAdapters$MapTypeAdapter;->constructMapType(Ljava/lang/reflect/Type;Lcom/htc/gson/JsonDeserializationContext;)Ljava/util/Map;

    move-result-object v3

    .line 643
    .local v3, map:Ljava/util/Map;,"Ljava/util/Map<Ljava/lang/Object;Ljava/lang/Object;>;"
    new-instance v4, Lcom/htc/gson/TypeInfoMap;

    invoke-direct {v4, p2}, Lcom/htc/gson/TypeInfoMap;-><init>(Ljava/lang/reflect/Type;)V

    .line 644
    .local v4, mapTypeInfo:Lcom/htc/gson/TypeInfoMap;
    invoke-virtual {p1}, Lcom/htc/gson/JsonElement;->getAsJsonObject()Lcom/htc/gson/JsonObject;

    move-result-object v6

    invoke-virtual {v6}, Lcom/htc/gson/JsonObject;->entrySet()Ljava/util/Set;

    move-result-object v6

    invoke-interface {v6}, Ljava/util/Set;->iterator()Ljava/util/Iterator;

    move-result-object v1

    .local v1, i$:Ljava/util/Iterator;
    :goto_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v6

    if-eqz v6, :cond_0

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/util/Map$Entry;

    .line 645
    .local v0, entry:Ljava/util/Map$Entry;,"Ljava/util/Map$Entry<Ljava/lang/String;Lcom/htc/gson/JsonElement;>;"
    new-instance v7, Lcom/htc/gson/JsonPrimitive;

    invoke-interface {v0}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Ljava/lang/String;

    invoke-direct {v7, v6}, Lcom/htc/gson/JsonPrimitive;-><init>(Ljava/lang/String;)V

    invoke-virtual {v4}, Lcom/htc/gson/TypeInfoMap;->getKeyType()Ljava/lang/reflect/Type;

    move-result-object v6

    invoke-interface {p3, v7, v6}, Lcom/htc/gson/JsonDeserializationContext;->deserialize(Lcom/htc/gson/JsonElement;Ljava/lang/reflect/Type;)Ljava/lang/Object;

    move-result-object v2

    .line 646
    .local v2, key:Ljava/lang/Object;
    invoke-interface {v0}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Lcom/htc/gson/JsonElement;

    invoke-virtual {v4}, Lcom/htc/gson/TypeInfoMap;->getValueType()Ljava/lang/reflect/Type;

    move-result-object v7

    invoke-interface {p3, v6, v7}, Lcom/htc/gson/JsonDeserializationContext;->deserialize(Lcom/htc/gson/JsonElement;Ljava/lang/reflect/Type;)Ljava/lang/Object;

    move-result-object v5

    .line 647
    .local v5, value:Ljava/lang/Object;
    invoke-interface {v3, v2, v5}, Ljava/util/Map;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    goto :goto_0

    .line 649
    .end local v0           #entry:Ljava/util/Map$Entry;,"Ljava/util/Map$Entry<Ljava/lang/String;Lcom/htc/gson/JsonElement;>;"
    .end local v2           #key:Ljava/lang/Object;
    .end local v5           #value:Ljava/lang/Object;
    :cond_0
    return-object v3
.end method

.method public bridge synthetic serialize(Ljava/lang/Object;Ljava/lang/reflect/Type;Lcom/htc/gson/JsonSerializationContext;)Lcom/htc/gson/JsonElement;
    .locals 1
    .parameter "x0"
    .parameter "x1"
    .parameter "x2"

    .prologue
    .line 603
    check-cast p1, Ljava/util/Map;

    .end local p1
    invoke-virtual {p0, p1, p2, p3}, Lcom/htc/gson/DefaultTypeAdapters$MapTypeAdapter;->serialize(Ljava/util/Map;Ljava/lang/reflect/Type;Lcom/htc/gson/JsonSerializationContext;)Lcom/htc/gson/JsonElement;

    move-result-object v0

    return-object v0
.end method

.method public serialize(Ljava/util/Map;Ljava/lang/reflect/Type;Lcom/htc/gson/JsonSerializationContext;)Lcom/htc/gson/JsonElement;
    .locals 8
    .parameter "src"
    .parameter "typeOfSrc"
    .parameter "context"

    .prologue
    .line 612
    new-instance v4, Lcom/htc/gson/JsonObject;

    invoke-direct {v4}, Lcom/htc/gson/JsonObject;-><init>()V

    .line 613
    .local v4, map:Lcom/htc/gson/JsonObject;
    const/4 v0, 0x0

    .line 614
    .local v0, childGenericType:Ljava/lang/reflect/Type;
    instance-of v7, p2, Ljava/lang/reflect/ParameterizedType;

    if-eqz v7, :cond_0

    .line 615
    new-instance v7, Lcom/htc/gson/TypeInfoMap;

    invoke-direct {v7, p2}, Lcom/htc/gson/TypeInfoMap;-><init>(Ljava/lang/reflect/Type;)V

    invoke-virtual {v7}, Lcom/htc/gson/TypeInfoMap;->getValueType()Ljava/lang/reflect/Type;

    move-result-object v0

    .line 618
    :cond_0
    invoke-interface {p1}, Ljava/util/Map;->entrySet()Ljava/util/Set;

    move-result-object v7

    invoke-interface {v7}, Ljava/util/Set;->iterator()Ljava/util/Iterator;

    move-result-object v3

    .local v3, i$:Ljava/util/Iterator;
    :goto_0
    invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z

    move-result v7

    if-eqz v7, :cond_3

    invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Ljava/util/Map$Entry;

    .line 619
    .local v2, entry:Ljava/util/Map$Entry;
    invoke-interface {v2}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v5

    .line 622
    .local v5, value:Ljava/lang/Object;
    if-nez v5, :cond_1

    .line 623
    invoke-static {}, Lcom/htc/gson/JsonNull;->createJsonNull()Lcom/htc/gson/JsonNull;

    move-result-object v6

    .line 629
    .local v6, valueElement:Lcom/htc/gson/JsonElement;
    :goto_1
    invoke-interface {v2}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v7

    invoke-static {v7}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v7

    invoke-virtual {v4, v7, v6}, Lcom/htc/gson/JsonObject;->add(Ljava/lang/String;Lcom/htc/gson/JsonElement;)V

    goto :goto_0

    .line 625
    .end local v6           #valueElement:Lcom/htc/gson/JsonElement;
    :cond_1
    if-nez v0, :cond_2

    invoke-virtual {v5}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    .line 627
    .local v1, childType:Ljava/lang/reflect/Type;
    :goto_2
    invoke-interface {p3, v5, v1}, Lcom/htc/gson/JsonSerializationContext;->serialize(Ljava/lang/Object;Ljava/lang/reflect/Type;)Lcom/htc/gson/JsonElement;

    move-result-object v6

    .restart local v6       #valueElement:Lcom/htc/gson/JsonElement;
    goto :goto_1

    .end local v1           #childType:Ljava/lang/reflect/Type;
    .end local v6           #valueElement:Lcom/htc/gson/JsonElement;
    :cond_2
    move-object v1, v0

    .line 625
    goto :goto_2

    .line 631
    .end local v2           #entry:Ljava/util/Map$Entry;
    .end local v5           #value:Ljava/lang/Object;
    :cond_3
    return-object v4
.end method

.method public toString()Ljava/lang/String;
    .locals 1

    .prologue
    .line 672
    const-class v0, Lcom/htc/gson/DefaultTypeAdapters$MapTypeAdapter;

    invoke-virtual {v0}, Ljava/lang/Class;->getSimpleName()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
<?php

namespace utest\router\unit;

use umi\route\result\IRouteResultBuilder;
use umi\route\result\RouteResultBuilder;
use utest\route\RouteTestCase;

/**
 * Тесты билдера результата роутинга.
 */
class ResultBuilderTest extends RouteTestCase
{
    /**
     * @var IRouteResultBuilder $resultBuilder билдер результата роутинга.
     */
    protected $resultBuilder;

    public function setUpFixtures()
    {
        $this->resultBuilder = new RouteResultBuilder();
        $this->resolveOptionalDependencies($this->resultBuilder);
    }

    public function testCleanBuild()
    {
        $result = $this->resultBuilder->getResult();
        $this->assertEmpty($result->getUnmatchedUrl(), 'Ожидается, что все поля собраного результата будут пусты.');
        $this->assertEmpty($result->getMatchedUrl(), 'Ожидается, что все поля собраного результата будут пусты.');
        $this->assertEmpty($result->getMatches(), 'Ожидается, что все поля собраного результата будут пусты.');
        $this->assertEmpty($result->getName(), 'Ожидается, что все поля собраного результата будут пусты.');
    }

    public function testSomeBuild()
    {
        $this->resultBuilder->addMatch('match1', ['param1' => 'value1'], '/match1');
        $this->resultBuilder->addMatch('match2', ['param2' => 'value2'], '/match2');
        $this->resultBuilder->setUnmatchedUrl('/match3');

        $result = $this->resultBuilder->getResult();
        $this->assertEquals('/match3', $result->getUnmatchedUrl(), 'Ожидается, поле результата будет установлено.');
        $this->assertEquals(
            '/match1/match2',
            $result->getMatchedUrl(),
            'Ожидается, что совпавшая часть результата будет собрана.'
        );
        $this->assertEquals(
            ['param1' => 'value1', 'param2' => 'value2'],
            $result->getMatches(),
            'Ожидается, что параметры результата будут собраны.'
        );
        $this->assertEquals(
            'match1/match2',
            $result->getName(),
            'Ожидается, что имя собраного результата будет собрано.'
        );
    }
}


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

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Interval Selection Calendar</title>

<link rel="stylesheet" type="text/css" href="../../build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="../../build/calendar/assets/skins/sam/calendar.css" />

    The IntervalCalendar class and example is based on the iCalendarGroup class, graciously contributed to YUI by John Peloquin, of W. Hardy Interactive, Inc..

Interval Selection Calendar

The Calendar widget is commonly used to select pairs of dates, representing the start and end dates of an interval, for example flight departure and return dates, or hotel check-in and check-out dates.

This example defines a custom IntervalCalendar class, based on CalendarGroup, which is designed specifically for this use case.

Check In:<input type="text" name="in" id="in">

Check Out:<input type="text" name="out" id="out">


text:
<ion-view title="MTG Grimoire">

MTG Grimoire

    <ion-content padding="true" class="has-header">

				    MTG Grimoire is everything you need to play Magic: The Gathering unite in on single app!

				    with MTG-G you can: Search for cards, build your deck, compare your card list with pre-build decks

Search

				    Search Cards

Match Manager

				    go to Match Manager

	</ion-content>

</ion-view>


text:
import os
import re
import sys
import string
import collections
import codecs
import shelve
import textwrap

shelf_file       = "shelf.shelf"
exam_folder      = "./returned_exams"
uuidpat          = "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"

from exam_settings import endseparator

from bio_info_questions import reverse_complement
from bio_info_questions import change_origin
from bio_info_questions import find_feature_rc
from bio_info_questions import find_region_of_similarity
from bio_info_questions import find_repeated_sequences
from bio_info_questions import blunt_cloning
from bio_info_questions import pcr_primer_design

files  = sorted([f for f in sorted(os.listdir(exam_folder)) if re.search("_([a-fA-F\d]{32})\.(txt|TXT)",f)]) # all files ending with md5.txt

files = [f for f in files if not f.endswith("~")]

print "{} files out of {} in {} identified as exams".format(len(files), len(os.listdir(exam_folder)), exam_folder)

shelf  = shelve.open(shelf_file)
matrix = collections.defaultdict(list)
point_matrix = collections.defaultdict(list)

#files = [f for f in sorted(os.listdir(exam_folder)) if "60730" in f]

names=[]

for f in files:
    print f
    test = codecs.open(os.path.join(exam_folder,f),"r","latin_1").read()
    header, rest = re.split(uuidpat,test, maxsplit=1)
    rest = rest.split(endseparator)[0]
    name_from_header = re.search(u"(Name|Nome)(.*?)$",header,re.M).group(2).strip()
    mec_from_header  = re.search(u"^(Número mecanográfico \(mec\))(.*?)$",header,re.M).group(2).strip()
    exame = list((f.group(1),f.group(2)) for f in re.finditer("({uuidpat})(.*?)(?=({uuidpat}|$))".format(uuidpat=uuidpat),test,re.DOTALL))

    names.append((name_from_header, mec_from_header,))

    for question_no, (id, answer) in enumerate(exame):

        if sys.argv[1:] and not str(question_no+1) in sys.argv[1:]:
            print "\tquestion {} skipped".format(question_no+1)
            continue

        questionobj = shelf[str(id)]
        print "\t{} points {}".format(questionobj.__class__.__module__, questionobj.points)
        grade, comment = questionobj.correct(answer)
        point_matrix[question_no].append(questionobj.points)
        matrix[mec_from_header].append(textwrap.dedent(u'''
                {sep1}
                {correct_answer}
                {sep2}
                {students_answer}
                {sep3}

                automatic comments:
                {comment}
                manual comment:

                question..........: {question_no:03d}
                points............: {points}
                name..............: {name}
                mec...............: {mec}
                automatic grade(%): {grade}
                manual grade(%)...:
                {sep4}
                ''').format( question_no     = question_no+1,
                             points          = questionobj.points,
                             mec             = mec_from_header,
                             name            = name_from_header,
                             correct_answer  = questionobj.correct_answer,
                             students_answer = answer,
                             grade           = grade,
                             comment         = comment,
                             sep1            = "^"*(79-15)+" CORRECT ANSWER",
                             sep2            = "="*(79-16)+" students answer",
                             sep3            = "_"*(79-11)+" correction",
                             sep4            = "~"*79,
                             ))

lengths=[]

for key in sorted(matrix.keys()):
    lengths.append(len(matrix[key]))
lengths = list(set(lengths))

if len(lengths) != 1: # The same number of questions found in all exams!
    print lengths
    raw_input()

length = lengths.pop()

points=[]
for key in point_matrix:
    point = list(set(point_matrix[key]))
    assert len(point) == 1

for q in range(length):

    text = "".join([matrix[key][q] for key in [m for n,m in sorted(names)]])
    text = string.replace(text, '\r\n', '\n')
    text = string.replace(text, '\n',   '\r\n')

    codecs.open("question{0:03d}.txt".format(q+1),"w","utf-8").write(text)

shelf.close()


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>在 jsx 中使用 js</title>


text:
'use strict';

module.exports = function(grunt) {

    var fs              = require('fs'),
        path            = require('path'),
        exec            = require('child_process').exec,
        defaultOptions  = {
            cwd: '.',
            releaseBranch: 'gh-pages',
            remoteRepository: 'origin',
            distDir: 'dist',
            commitMessage: 'RELEASE',
            commit: true,
            push: false,
            orphan: false,
            blacklist: [
                '.git'
            ]
        };

    grunt.registerMultiTask('releaseBranchPre','release dist as branch', function(){

        var options = this.options(defaultOptions);

        var done = this.async();

        var releaseBranch = options.releaseBranch;

        var checkoutOptions = options.orphan ? '--orphan ' : '-b '

        exec('git branch -D ' +  releaseBranch + '; git checkout ' + checkoutOptions  + releaseBranch, options.execOptions, function(){
            done();
        });

        grunt.log.writeln('running release branch pre task...');
    });

    grunt.registerMultiTask('releaseBranch','release dist as branch', function(){

        var options = this.options(defaultOptions);
        var blacklist = options.blacklist;
        var cwd = options.cwd;
        var distContainer;

        process.chdir(cwd);

        if (options.distDir.indexOf(path.sep)){
            //if the dist is in a subdir like 'app/dist' we need to
            //blacklist the containing folder (e.g. app)
            distContainer = options.distDir.split(path.sep)[0];
            blacklist.push(distContainer);
        }
        else{
            blacklist.push(options.distDir);
        }

        var rmdirRec = function(path) {
            var files = [];
            if( fs.existsSync(path) ) {
                files = fs.readdirSync(path);
                files.forEach(function(file,index){
                    var curPath = path + '/' + file;
                    if(fs.statSync(curPath).isDirectory()) { // recurse
                        rmdirRec(curPath);
                    } else { // delete file
                        fs.unlinkSync(curPath);
                    }
                });
                fs.rmdirSync(path);
            }
        };

        var done = this.async();

        fs.readdir('.', function(err, contents){

            contents.forEach(function(name, index){
                if (blacklist.indexOf(name) === -1){
                    var stats = fs.lstatSync(name);

                    if (!err && stats.isDirectory()) {
                        grunt.log.writeln('delete directory: ' + name);
                        rmdirRec(name);
                    }
                    else{
                        grunt.log.writeln('delete file: ' + name);
                        fs.unlinkSync(name);
                    }
                }
            });
            grunt.log.writeln('now moving files from ' + options.distDir + ' to root level');
            //move all files from the dist dir to the root level
            exec('mv ' + options.distDir + '/* .', function(){

                //now that everything has been moved. Delete the dist dir
                rmdirRec(distContainer || options.distDir);

                if (options.commit){

                    grunt.log.writeln('commiting files as: ' + options.commitMessage);

                    exec('git add -A && git commit -m "' + options.commitMessage + '"', function(){

                        if (options.push){

                            grunt.log.writeln('pushing commit to: ' + options.releaseBranch);
                            exec('git push -f ' + options.remoteRepository + ' ' + options.releaseBranch, function(){
                                done();
                            });
                        }
                        else{
                            done();
                        }
                    });
                }
                else{
                    done();
                }
            });
        });

        grunt.log.writeln('running release branch task...');
    });
};


text:
package com.github.paolorotolo.appintro;

import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;
import java.util.Vector;

public abstract class AppIntro extends AppCompatActivity {
    private PagerAdapter mPagerAdapter;
    private ViewPager pager;
    private List<Fragment> fragments = new Vector<>();
    private List<ImageView> dots;
    private int slidesNumber;
    private Vibrator mVibrator;
    private IndicatorController mController;
    private boolean isVibrateOn = false;
    private int vibrateIntensity = 20;
    private boolean showSkip = true;
    private boolean showDone = true;

    static enum TransformType {
        FLOW,
        DEPTH,
        ZOOM,
        SLIDE_OVER,
        FADE
    }

    @Override
    final protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.intro_layout);

        final TextView skipButton = (TextView) findViewById(R.id.skip);
        final ImageView nextButton = (ImageView) findViewById(R.id.next);
        final TextView doneButton = (TextView) findViewById(R.id.done);
        mVibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);

        skipButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(@NonNull View v) {
                if (isVibrateOn) {
                    mVibrator.vibrate(vibrateIntensity);
                }
                onSkipPressed();
            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(@NonNull View v) {
                if (isVibrateOn) {
                    mVibrator.vibrate(vibrateIntensity);
                }
                pager.setCurrentItem(pager.getCurrentItem() + 1);
            }
        });

        doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(@NonNull View v) {
                if (isVibrateOn) {
                    mVibrator.vibrate(vibrateIntensity);
                }
                onDonePressed();
            }
        });

        mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
        pager = (ViewPager) findViewById(R.id.view_pager);

        pager.setAdapter(this.mPagerAdapter);
        /**
         *  ViewPager.setOnPageChangeListener is now deprecated. Use addOnPageChangeListener() instead of it.
         */
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (slidesNumber > 1)
                    mController.selectPosition(position);
                if (position == slidesNumber - 1) {
                    skipButton.setVisibility(View.INVISIBLE);
                    nextButton.setVisibility(View.GONE);
                    if (showDone) {
                        doneButton.setVisibility(View.VISIBLE);
                    } else {
                        doneButton.setVisibility(View.INVISIBLE);
                    }
                } else {
                    skipButton.setVisibility(View.VISIBLE);
                    doneButton.setVisibility(View.GONE);
                    nextButton.setVisibility(View.VISIBLE);
                }

                if (!showSkip) {
                    skipButton.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        init(savedInstanceState);
        slidesNumber = fragments.size();

        if (slidesNumber == 1) {
            nextButton.setVisibility(View.GONE);
            doneButton.setVisibility(View.VISIBLE);
        } else {
            initController();
        }
    }

    public ViewPager getPager() {
        return pager;
    }

    private void initController() {
        if (mController == null)
            mController = new DefaultIndicatorController();

        FrameLayout indicatorContainer = (FrameLayout) findViewById(R.id.indicator_container);
        indicatorContainer.addView(mController.newInstance(this));

        mController.initialize(slidesNumber);
    }
    public void selectDot(int index) {
        Resources res = getResources();
        for (int i = 0; i < fragments.size(); i++) {
            int drawableId = (i == index) ? (R.drawable.indicator_dot_white) : (R.drawable.indicator_dot_grey);
            Drawable drawable = res.getDrawable(drawableId);
            dots.get(i).setImageDrawable(drawable);
        }
        onDotSelected(index);
    }

    public void addSlide(@NonNull Fragment fragment) {
        fragments.add(fragment);
        mPagerAdapter.notifyDataSetChanged();
    }

    @NonNull
    public List<Fragment> getSlides() {
        return mPagerAdapter.getFragments();
    }

    public void setBarColor(@ColorInt final int color) {
        LinearLayout bottomBar = (LinearLayout) findViewById(R.id.bottom);
        bottomBar.setBackgroundColor(color);
    }

    public void setSeparatorColor(@ColorInt final int color) {
        TextView separator = (TextView) findViewById(R.id.bottom_separator);
        separator.setBackgroundColor(color);
    }

    public void setSkipText(@Nullable final String text) {
        TextView skipText = (TextView) findViewById(R.id.skip);
        skipText.setText(text);
    }

    public void setDoneText(@Nullable final String text) {
        TextView doneText = (TextView) findViewById(R.id.done);
        doneText.setText(text);
    }

    public void showSkipButton(boolean showButton) {
        this.showSkip = showButton;
        if (!showButton) {
            TextView skip = (TextView) findViewById(R.id.skip);
            skip.setVisibility(View.INVISIBLE);
        }
    }

    public void showDoneButton(boolean showDone) {
        this.showDone = showDone;
        if (!showDone) {
            TextView done = (TextView) findViewById(R.id.done);
            done.setVisibility(View.GONE);
        }
    }

    public void setVibrate(boolean vibrate) {
        this.isVibrateOn = vibrate;
    }

    public void setVibrateIntensity(int intensity) {
        this.vibrateIntensity = intensity;
    }

    public void setFadeAnimation() {
        pager.setPageTransformer(true, new ViewPageTransformer(ViewPageTransformer.TransformType.FADE));
    }
    public void setZoomAnimation() {
        pager.setPageTransformer(true, new ViewPageTransformer(ViewPageTransformer.TransformType.ZOOM));
    }
    public void setFlowAnimation() {
        pager.setPageTransformer(true, new ViewPageTransformer(ViewPageTransformer.TransformType.FLOW));
    }
    public void setSlideOverAnimation() {
        pager.setPageTransformer(true, new ViewPageTransformer(ViewPageTransformer.TransformType.SLIDE_OVER));
    }
    public void setDepthAnimation() {
        pager.setPageTransformer(true, new ViewPageTransformer(ViewPageTransformer.TransformType.DEPTH));
    }

    public void setCustomTransformer(@Nullable ViewPager.PageTransformer transformer) {
        pager.setPageTransformer(true, transformer);
    }

    public void setOffScreenPageLimit(int limit) {
        pager.setOffscreenPageLimit(limit);
    }

    /**
     * Set a progress indicator instead of dots. This is recommended for a large amount of slides. In this case there
     * could not be enough space to display all dots on smaller device screens.
     */
    public void setProgressIndicator() {
        mController = new ProgressIndicatorController();
    }

    /**
     * Set a custom {@link IndicatorController} to use a custom indicator view for the {@link AppIntro} instead of the
     * default one.
     *
     * @param controller The controller to use
     */
    public void setCustomIndicator(@NonNull IndicatorController controller) {
        mController = controller;
    }

    public abstract void init(@Nullable Bundle savedInstanceState);

    public abstract void onSkipPressed();

    public abstract void onDonePressed();

    public void onDotSelected(int index) {}

    @Override
    public boolean onKeyDown(int code, KeyEvent kvent) {
        if (code == KeyEvent.KEYCODE_ENTER || code == KeyEvent.KEYCODE_BUTTON_A) {
            ViewPager vp = (ViewPager) this.findViewById(R.id.view_pager);
            if (vp.getCurrentItem() == vp.getAdapter().getCount() - 1) {
                onDonePressed();
            } else {
                vp.setCurrentItem(vp.getCurrentItem() + 1);
            }
            return false;
        }
        return super.onKeyDown(code, kvent);
    }
}


text:
function DemoCtrl($scope) {

  'use strict';

  $scope.workbook = {};

  $scope.Object = window.Object;

  $scope.hasSavedFullWorkbook = function() {
    return localStorage.getItem('workbook');
  };

  $scope.saveFullWorkbook = function() {

    var excellentLoader = new Excellent.Loader(),
      json = excellentLoader.unload($scope.fullWorkbook);

    localStorage.setItem('workbook', JSON.stringify(json));
  };

  $scope.loadFullWorkbook = function() {

    var excellentLoader = new Excellent.Loader(),
      workbook = excellentLoader.load(JSON.parse(localStorage.getItem('workbook')));

    console.log(workbook);

    $scope.fullWorkbook = workbook;
    $scope.workbook = workbook.workbook;

  };

  $scope.isNumber = function(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  };

  $scope.updateCell = function(workbook, sheet, cell) {
    if ($scope.isNumber(cell.value)) {
      workbook[sheet][cell.index] = parseFloat(cell.value, 10);
    } else {
      workbook[sheet][cell.index] = cell.value;
    }
  };

  function numToChar(number) {
    var numeric = (number - 1) % 26;
    var letter = chr(65 + numeric);
    var number2 = parseInt((number - 1) / 26);
    if (number2 > 0) {
      return numToChar(number2) + letter;
    } else {
      return letter;
    }
  }

  function chr(codePt) {
    if (codePt > 0xFFFF) {
      codePt -= 0x10000;
      return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
    }
    return String.fromCharCode(codePt);
  }

  $scope.sheetColumns = function(worksheet) {
    var highest = worksheet.rows[0],
      columns = [],
      i;

    worksheet.rows.forEach(function(row) {
      if (!row || !highest) {
        return;
      }
      if (highest.length < row.length) {
        highest = row;
      }
    });

    if (!highest) {
      return;
    }

    for (i = 0; i < highest.length; i += 1) {
      columns.push(numToChar(i + 1));
    }

    return columns;

  };

  $scope.upload = function(uploadFiles) {
    var uploadFile = uploadFiles.files[0],
      reader = new FileReader();

    reader.onload = (function(file) {
      return function(e) {
        try {
          var excellent = new Excellent.Xlsx(),
            parsed = excellent.load(e.target.result);
          $scope.$apply(function() {
            $scope.fullWorkbook = parsed;
            $scope.workbook = parsed.workbook;
            console.log(parsed);
          });
        } catch (e) {
          alert('There was a problem parsing this file.  Excellent is still under development. \n\nMessage:\n\n' + e.message);
        }
      };
    })(uploadFile);

    reader.readAsArrayBuffer(uploadFile);
  };
}


text:
package com.dataartisans.flink.cascading.runtime.hashJoin;

import cascading.CascadingException;
import cascading.flow.FlowElement;
import cascading.flow.FlowException;
import cascading.flow.FlowNode;
import cascading.flow.SliceCounters;
import cascading.flow.stream.duct.Duct;
import cascading.flow.stream.element.ElementDuct;
import cascading.pipe.Boundary;
import cascading.tuple.Tuple;
import com.dataartisans.flink.cascading.runtime.util.FlinkFlowProcess;
import com.dataartisans.flink.cascading.util.FlinkConfigConverter;
import org.apache.flink.api.common.functions.RichMapPartitionFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Set;

@SuppressWarnings("unused")
public class HashJoinMapper extends RichMapPartitionFunction<Tuple2<Tuple, Tuple[]>, Tuple> {

	private static final Logger LOG = LoggerFactory.getLogger(HashJoinMapper.class);

	private FlowNode flowNode;
	private HashJoinMapperStreamGraph streamGraph;
	private JoinBoundaryMapperInStage sourceStage;
	private FlinkFlowProcess currentProcess;

	public HashJoinMapper() {}

	public HashJoinMapper(FlowNode flowNode) {
		this.flowNode = flowNode;
	}

	@Override
	public void open(Configuration config) {

		try {

			currentProcess = new FlinkFlowProcess(FlinkConfigConverter.toHadoopConfig(config), getRuntimeContext(), flowNode.getID());

			Set<FlowElement> sources = flowNode.getSourceElements();
			// pick one (arbitrary) source
			FlowElement sourceElement = sources.iterator().next();
			if(!(sourceElement instanceof Boundary)) {
				throw new RuntimeException("Source of HashJoinMapper must be a boundary");
			}

			Boundary source = (Boundary)sourceElement;

			streamGraph = new HashJoinMapperStreamGraph( currentProcess, flowNode, source );
			sourceStage = this.streamGraph.getSourceStage();

			for( Duct head : streamGraph.getHeads() ) {
				LOG.info("sourcing from: " + ((ElementDuct) head).getFlowElement());
			}

			for( Duct tail : streamGraph.getTails() ) {
				LOG.info("sinking to: " + ((ElementDuct) tail).getFlowElement());
			}
		}
		catch( Throwable throwable ) {

			if( throwable instanceof CascadingException) {
				throw (CascadingException) throwable;
			}

			throw new FlowException( "internal error during HashJoinMapper configuration", throwable );
		}

	}

	@Override
	public void mapPartition(Iterable<Tuple2<Tuple, Tuple[]>> input, Collector<Tuple> output) throws Exception {

		this.streamGraph.setTupleCollector(output);
		streamGraph.prepare();

		long processBeginTime = System.currentTimeMillis();
		currentProcess.increment( SliceCounters.Process_Begin_Time, processBeginTime );

		try {
			try {

				sourceStage.run( input.iterator() );
			}
			catch( OutOfMemoryError error ) {
				throw error;
			}
			catch( IOException exception ) {
				throw exception;
			}
			catch( Throwable throwable ) {

				if( throwable instanceof CascadingException ) {
					throw (CascadingException) throwable;
				}

				throw new FlowException( "internal error during HashJoinMapper execution", throwable );
			}
		}
		finally {
			try {
				streamGraph.cleanup();
			}
			finally {
				long processEndTime = System.currentTimeMillis();
				currentProcess.increment( SliceCounters.Process_End_Time, processEndTime );
				currentProcess.increment( SliceCounters.Process_Duration, processEndTime - processBeginTime );
			}
		}
	}

}


text:
namespace SpecDrill.Infrastructure.Configuration
{
    public class BrowserWindowConfiguration
    {
        public bool IsMaximized { get; set; }
        public int? InitialWidth { get; set; }
        public int? InitialHeight { get; set; }
    }
}


text:
package org.apache.wicket.markup.html.internal;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;

/**
 * Mock page for testing.
 *
 * @author Juergen Donnerstag
 */
public class EnclosurePage_1 extends WebPage
{
	private static final long serialVersionUID = 1L;

	/**
	 * Construct.
	 */
	public EnclosurePage_1()
	{
		add(new Label("label1", "Test Label 1"));
		add(new Label("label2", "Test Label 2"));
		add(new Label("label3", "Test Label 3").setVisible(false));
		add(new Label("label4", "Test Label 2"));
		add(new Label("label5", "Test Label 2"));
		add(new Label("label6", "Test Label 2"));
		add(new Label("label7", "Test Label 2"));
		WebMarkupContainer container = new WebMarkupContainer("container");
		add(container);
		container.add(new Label("label8", "Test Label 2"));
		add(new Label("label9", "Test Label 2"));
		add(new Label("label10", "Test Label 3"));
	}
}


text:
Plotarrd -- web-based RRD browser
=================================

Plotarrd is a small webapplication for browsing RRD files and plotting them in
some simple way.

The central function of Plotarrd is to expose predefined, named graph through
a friendly URL, like

    http://example.net/plotarrd/temperature.png

assuming, of course, that Plotarrd is deployed under
<http://example.net/plotarrd/> and the predefined graph is called
*temperature*.

To make things easier for operator, Plotarrd allows also to define new graphs
and save them for later.

All the fuss is to combine [collectd](http://collectd.org) as a data collector
and [DashWiki](http://dashwiki.jarowit.net/) as a dashboard. Of course,
there's no problem to use Plotarrd with any other metrics collector (as long
as it writes RRD files) or dashboard application.

URL interface
-------------

All PNG URLs allow specifying image size and graph period.

    http://example.net/plotarrd/temperature.png?size=800x500
    http://example.net/plotarrd/temperature.png?timespan=2weeks

Currently, only the recent period is displayed (i.e. there's no way to make
a graph for 3 days that were two months ago).

The timespan is anything that RRDtool accepts, especially in the form of
`{number}{unit}`, where `{unit}` can be `minute`, `hour`, `day`, `week`,
`month` or `year` (of course, it's not limited to those).

All editing resides under `.../edit/*` path
(`http://example.net/plotarrd/edit/` with our current convention for
examples), so even though Plotarrd doesn't provide any access control, it
should be fairly easy to add one with HTTP server.

Parametrized graphs
-------------------

Several graphs can use parameters in the form of `${name}` in various places:

  * variable label
  * RRD database path
  * datasource
  * title
  * Y-axis label

These parameters typically will be passed as *GET* parameters. They can also
have default values (this is recommended practice, so one can quickly see what
this graph is about).

For instance, one could define a graph *free_disk* as follows:

    | label | file                                         | DS    |
    | used  | ${host}/df-${filesystem}/df_complex-used.rrd | value |

This graph could be then displayed as

    http://example.net/plotarrd/free_disk.png?host=web01.example.net&filesystem=root

Installation
------------

Simple WSGI application, requiring Python bindings for RRDtool and
[Flask](http://flask.pocoo.org/) (0.6+; older versions were not checked).
Python 2.6 or newer (it possibly works under 2.5, but this was not checked).

**TODO**: be more verbose.

Contact
-------

Plotarrd is written by Stanislaw Klekot `(dozzie at jarowit.net)`.
The primary distribution point is
[dozzie.jarowit.net](http://dozzie.jarowit.net/), with
a secondary address on [GitHub](https://github.com/dozzie/plotarrd).

Plotarrd is distributed under 3-clause BSD license. See `COPYING` file for
details.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package soccer.mind.broker;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pguan
 */
public class MailServer implements Runnable {

    private final ConcurrentLinkedQueue<String> queue;

    private final SimpleMailSender sender;

    public MailServer(ConcurrentLinkedQueue<String> queue) throws IOException {
        this.queue = queue;
        this.sender = new SimpleMailSender();
    }

    @Override
    public void run() {
        while (true) {
            try {
                if (queue.isEmpty()) {
                    TimeUnit.MINUTES.sleep(1);
                } else {
                    String toBeSend = queue.poll();
                    if (null == toBeSend || toBeSend.isEmpty()) {
                        continue;
                    } else {
                        sender.sendToMyself("From Soccer App", toBeSend);
                    }
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(MailServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}


text:
package info.xonix.passmanager;

import com.google.appengine.api.datastore.*;
import info.xonix.passmanager.model.Attachment;
import info.xonix.passmanager.model.PassData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
@RequiredArgsConstructor
public class AppLogic {
  public static final int BACKUPS_COUNT = 10;
  public static final String KEY_MASTER_DATA = "0";

  public static final String ENTITY_DATA = "Data";
  public static final String ENTITY_FILE = "File";
  public static final String ENTITY_DATA_BACKUP = "DataBackup";

  public static final String PROP_VALUE = "value";
  public static final String PROP_TIMESTAMP = "timestamp";
  public static final String PROP_LAST_BACKUP_KEY = "lastBackupKey";

  private final DatastoreService datastoreService;

  public PassData getEncryptedPassData() {
    Entity data = null;
    try {
      data = datastoreService.get(KeyFactory.createKey(ENTITY_DATA, KEY_MASTER_DATA));
    } catch (EntityNotFoundException e) {
      log.info("Data not found");
    }

    if (data != null) {
      String value = ((Text) data.getProperty(PROP_VALUE)).getValue();
      Date timestamp = (Date) data.getProperty(PROP_TIMESTAMP);

      log.info("Found data of size: {}, lastUpdated: {}", value.length(), timestamp);

      return new PassData(value, timestamp);
    } else {
      log.info("No data saved yet...");
    }
    return null;
  }

  /**
   * @param encData data to store
   * @return last updated date
   */
  public Date storeEncryptedPassData(String encData) {
    Entity currentData = null;
    try {
      currentData = datastoreService.get(KeyFactory.createKey(ENTITY_DATA, KEY_MASTER_DATA));
    } catch (EntityNotFoundException ignore) {
    }

    long newBackupKey = -1;
    if (currentData != null) {
      long lastBackupKey = -1; // no backup
      Long currentBackupKey = (Long) currentData.getProperty(PROP_LAST_BACKUP_KEY);
      if (currentBackupKey != null) {
        lastBackupKey = currentBackupKey;
      }
      newBackupKey = (lastBackupKey + 1) % BACKUPS_COUNT;

      log.info("Storing backup: #{}", newBackupKey);

      Entity backupData = new Entity(ENTITY_DATA_BACKUP, "" + newBackupKey);
      backupData.setProperty(PROP_VALUE, currentData.getProperty(PROP_VALUE));
      backupData.setProperty(PROP_TIMESTAMP, new Date());
      datastoreService.put(backupData);
    }

    Entity data = new Entity(ENTITY_DATA, KEY_MASTER_DATA);
    data.setProperty(PROP_VALUE, new Text(encData));
    Date lastUpdated = new Date();
    data.setProperty(PROP_TIMESTAMP, lastUpdated);
    data.setProperty(PROP_LAST_BACKUP_KEY, newBackupKey);

    log.info("Storing data of size: {}", encData.length());

    datastoreService.put(data);
    return lastUpdated;
  }

  /** @param key file id */
  public void deleteFile(String key) {
    datastoreService.delete(KeyFactory.createKey(ENTITY_FILE, key));
  }

  /**
   * @param key file id
   * @param data encrypted file content
   * @return file upload date
   */
  public Date saveFile(String key, String data) {
    Entity fileEntity = new Entity(ENTITY_FILE, key);

    Date uploadDate = new Date();

    fileEntity.setProperty(PROP_TIMESTAMP, uploadDate);
    fileEntity.setProperty(PROP_VALUE, new Text(data));

    datastoreService.put(fileEntity);

    log.info("Uploaded file key={}, size={}", key, data.length());
    return uploadDate;
  }

  /**
   * @param key file id
   * @return file || null if absent
   */
  public Attachment loadFile(String key) {
    try {
      Entity file = datastoreService.get(KeyFactory.createKey(ENTITY_FILE, key));
      return new Attachment(
          ((Text) file.getProperty(PROP_VALUE)).getValue(),
          (Date) file.getProperty(PROP_TIMESTAMP));
    } catch (EntityNotFoundException e) {
      log.info("File not found for key:{}", key);
      return null;
    }
  }
}


text:
package com.simpligility.maven.plugins.android.standalonemojos;

import java.io.IOException;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;
import com.android.ddmlib.testrunner.MonkeyTestRunner;
import com.simpligility.maven.plugins.android.AbstractAndroidMojo;
import com.simpligility.maven.plugins.android.AndroidTestRunListener;
import com.simpligility.maven.plugins.android.DeviceCallback;
import com.simpligility.maven.plugins.android.common.DeviceHelper;
import com.simpligility.maven.plugins.android.config.ConfigHandler;
import com.simpligility.maven.plugins.android.config.ConfigPojo;
import com.simpligility.maven.plugins.android.config.PullParameter;
import com.simpligility.maven.plugins.android.configuration.Monkey;

/**
 * Can execute tests using UI/Application Exerciser Monkey.

 * Implements parsing parameters from pom or command line arguments and sets useful defaults as well. This goal will
 * invoke Android Monkey exerciser. If the application crashes during the exercise, this goal can fail the build.

 * A typical usage of this goal can be found at Quality tools for Android project.
 *
 * @see Monkey docs by Google
 * @see Stack Over Flow thread for parsing monkey output.
 * @author Stéphane Nicolas <snicolas@octo.com>
 */
@SuppressWarnings( "unused" )
@Mojo( name = "monkey" )
public class MonkeyMojo extends AbstractAndroidMojo
{
    /**
     * -Dmaven.test.skip is commonly used with Maven to skip tests. We honor it.
     */
    @Parameter( property = "maven.test.skip", defaultValue = "false", readonly = true )
    private boolean mavenTestSkip;

    /**
     * -DskipTests is commonly used with Maven to skip tests. We honor it too.
     */
    @Parameter( property = "skipTests", defaultValue = "false", readonly = true )
    private boolean mavenSkipTests;

    /**
     * -Dmaven.test.failure.ignore is commonly used with Maven to prevent failure of build when (some) tests fail. We
     * honor it too.
     */
    @Parameter( property = "maven.test.failure.ignore", defaultValue = "false", readonly = true )
    private boolean mavenTestFailureIgnore;

    /**
     * -Dmaven.test.failure.ignore is commonly used with Maven to prevent failure of build when (some) tests fail. We
     * honor it too.
     */
    @Parameter( property = "testFailureIgnore", defaultValue = "false", readonly = true )
    private boolean mavenIgnoreTestFailure;

    /**
     * The configuration for the ui automator goal. As soon as a lint goal is invoked the command will be executed
     * unless the skip parameter is set. A minimal configuration that will run lint and produce a XML report in
     * ${project.build.directory}/lint/lint-results.xml is
     *
     *

     * <monkey>
     *   <skip>false</skip>
     * </monkey>
     *

     *
     * Full configuration can use these parameters.
     *
     *

     *  <monkey>
     *    <skip>false</skip>
     *    <eventCount>5000</eventCount>
     *    <seed>123456</seed>
     *    <throttle>10</throttle>
     *    <percentTouch>10</percentTouch>
     *    <percentMotion>10</percentMotion>
     *    <percentTrackball>10</percentTrackball>
     *    <percentNav>10</percentNav>
     *    <percentMajorNav>10</percentMajorNav>
     *    <percentSyskeys>10</percentSyskeys>
     *    <percentAppswitch>10</percentAppswitch>
     *    <percentAnyevent>10</percentAnyevent>
     *    <packages>
     *        <package>com.foo</package>
     *        <package>com.bar</package>
     *    </packages>
     *    <categories>
     *        <category>foo</category>
     *        <category>bar</category>
     *    </categories>
     *    <debugNoEvents>true</debugNoEvents>
     *    <hprof>true</hprof>
     *    <ignoreCrashes>true</ignoreCrashes>
     *    <ignoreTimeouts>true</ignoreTimeouts>
     *    <ignoreSecurityExceptions>true</ignoreSecurityExceptions>
     *    <killProcessAfterError>true</killProcessAfterError>
     *    <monitorNativeCrashes>true</monitorNativeCrashes>
     *    <createReport>true</createReport>
     *  </monkey>
     *

     *
     * Alternatively to the plugin configuration values can also be configured as properties on the command line as
     * android.lint.* or in pom or settings file as properties like lint*.
     */
    @Parameter
    @ConfigPojo
    private Monkey monkey;

    /**
     * Enables or disables monkey test goal. If true it will be skipped; if false, it will be
     * run. Defaults to true.
     */
    @Parameter( property = "android.monkey.skip" )
    private Boolean monkeySkip;

    @PullParameter( defaultValue = "true" )
    private Boolean parsedSkip;

    /**
     * Number of generated events. Defaults to 1000.
     */
    @Parameter( property = "android.monkey.eventCount" )
    private Integer monkeyEventCount;

    @PullParameter( required = true, defaultValue = "1000" )
    private Integer parsedEventCount;

    /**
     * Seed value for pseudo-random number generator. If you re-run the Monkey with the same seed value, it will
     * generate the same sequence of events.
     */
    @Parameter( property = "android.monkey.seed" )
    private Long monkeySeed;

    @PullParameter( required = false, defaultValueGetterMethod = "getSeed" )
    private Long parsedSeed;

    /**
     * Inserts a fixed delay between events. You can use this option to slow down the Monkey. If not specified, there is
     * no delay and the events are generated as rapidly as possible.
     */
    @Parameter( property = "android.monkey.throttle" )
    private Long monkeyThrottle;

    @PullParameter( required = false, defaultValueGetterMethod = "getThrottle" )
    private Long parsedThrottle;

    /**
     * Adjust percentage of touch events. (Touch events are a down-up event in a single place on the screen.)
     */
    @Parameter( property = "android.monkey.percentTouch" )
    private Integer monkeyPercentTouch;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentTouch" )
    private Integer parsedPercentTouch;

    /**
     * Adjust percentage of motion events. (Motion events consist of a down event somewhere on the screen, a series of
     * pseudo-random movements, and an up event.)
     */
    @Parameter( property = "android.monkey.percentMotion" )
    private Integer monkeyPercentMotion;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentMotion" )
    private Integer parsedPercentMotion;

    /**
     * Adjust percentage of trackball events. (Trackball events consist of one or more random movements, sometimes
     * followed by a click.)
     */
    @Parameter( property = "android.monkey.percentTrackball" )
    private Integer monkeyPercentTrackball;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentTrackball" )
    private Integer parsedPercentTrackball;

    /**
     * Adjust percentage of "basic" navigation events. (Navigation events consist of up/down/left/right, as input from a
     * directional input device.)
     */
    @Parameter( property = "android.monkey.percentNav" )
    private Integer monkeyPercentNav;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentNav" )
    private Integer parsedPercentNav;

    /**
     * Adjust percentage of "major" navigation events. (These are navigation events that will typically cause actions
     * within your UI, such as the center button in a 5-way pad, the back key, or the menu key.)
     */
    @Parameter( property = "android.monkey.percentMajorNav" )
    private Integer monkeyPercentMajorNav;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentMajorNav" )
    private Integer parsedPercentMajorNav;

    /**
     * Adjust percentage of "system" key events. (These are keys that are generally reserved for use by the system, such
     * as Home, Back, Start Call, End Call, or Volume controls.) Defaults to null.
     */
    @Parameter( property = "android.monkey.percentSyskeys" )
    private Integer monkeyPercentSyskeys;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentSyskeys" )
    private Integer parsedPercentSyskeys;

    /**
     * Adjust percentage of activity launches. At random intervals, the Monkey will issue a startActivity() call, as a
     * way of maximizing coverage of all activities within your package.
     */
    @Parameter( property = "android.monkey.percentAppswitch" )
    private Integer monkeyPercentAppswitch;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentAppswitch" )
    private Integer parsedPercentAppswitch;

    /**
     * Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses,
     * other less-used buttons on the device, and so forth.
     */
    @Parameter( property = "android.monkey.percentAnyevent" )
    private Integer monkeyPercentAnyEvent;

    @PullParameter( required = false, defaultValueGetterMethod = "getPercentAnyevent" )
    private Integer parsedPercentAnyevent;

    /**
     * If you specify one or more packages this way, the Monkey will only allow the system to visit activities within
     * those packages. If your application requires access to activities in other packages (e.g. to select a contact)
     * you'll need to specify those packages as well. If you don't specify any packages, the Monkey will allow the
     * system to launch activities in all packages.
     */
    @Parameter( property = "android.monkey.packages" )
    private String[] monkeyPackages;

    @PullParameter( required = false, defaultValueGetterMethod = "getPackages" )
    private String[] parsedPackages;

    /**
     * If you specify one or more categories this way, the Monkey will only allow the system to visit activities that
     * are listed with one of the specified categories. If you don't specify any categories, the Monkey will select
     * activities listed with the category Intent.CATEGORY_LAUNCHER or Intent.CATEGORY_MONKEY.
     */
    @Parameter( property = "android.monkey.categories" )
    private String[] monkeyCategories;

    @PullParameter( required = false, defaultValueGetterMethod = "getCategories" )
    private String[] parsedCategories;

    /**
     * When specified, the Monkey will perform the initial launch into a test activity, but will not generate any
     * further events. For best results, combine with -v, one or more package constraints, and a non-zero throttle to
     * keep the Monkey running for 30 seconds or more. This provides an environment in which you can monitor package
     * transitions invoked by your application.
     */
    @Parameter( property = "android.monkey.debugNoEvents" )
    private Boolean monkeyDebugNoEvents;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedDebugNoEvents;

    /**
     * If set, this option will generate profiling reports immediately before and after the Monkey event sequence. This
     * will generate large (~5Mb) files in data/misc, so use with care. See Traceview for more information on trace
     * files.
     */
    @Parameter( property = "android.monkey.Hprof" )
    private Boolean monkeyHprof;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedHprof;

    /**
     * Normally, the Monkey will stop when the application crashes or experiences any type of unhandled exception. If
     * you specify this option, the Monkey will continue to send events to the system, until the count is completed.
     * Settings this option is different to setting testFailureIgnore or maven.test.failure.ignore to true, it will
     * impact monkey run but not the result of the maven build.
     */
    @Parameter( property = "android.monkey.ignoreCrashes" )
    private Boolean monkeyIgnoreCrashes;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedIgnoreCrashes;

    /**
     * Normally, the Monkey will stop when the application experiences any type of timeout error such as a
     * "Application Not Responding" dialog. If you specify this option, the Monkey will continue to send events to the
     * system, until the count is completed.
     *
     * Defaults to false.
     */
    @Parameter( property = "android.monkey.IgnoreTimeouts" )
    private Boolean monkeyIgnoreTimeouts;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedIgnoreTimeouts;

    /**
     * Normally, the Monkey will stop when the application experiences any type of permissions error, for example if it
     * attempts to launch an activity that requires certain permissions. If you specify this option, the Monkey will
     * continue to send events to the system, until the count is completed. *
     *
     * Defaults to false.
     */
    @Parameter( property = "android.monkey.IgnoreSecurityExceptions" )
    private Boolean monkeyIgnoreSecurityExceptions;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedIgnoreSecurityExceptions;

    /**
     * Normally, when the Monkey stops due to an error, the application that failed will be left running. When this
     * option is set, it will signal the system to stop the process in which the error occurred. Note, under a normal
     * (successful) completion, the launched process(es) are not stopped, and the device is simply left in the last
     * state after the final event.
     *
     * Defaults to false.
     */
    @Parameter( property = "android.monkey.KillProcessAfterError" )
    private Boolean monkeyKillProcessAfterError;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedKillProcessAfterError;

    /**
     * Watches for and reports crashes occurring in the Android system native code. If --kill-process-after-error is
     * set, the system will stop.
     *
     * Defaults to false.
     */
    @Parameter( property = "android.monkey.MonitorNativeCrashes" )
    private Boolean monkeyMonitorNativeCrashes;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedMonitorNativeCrashes;

    /**
     * Create a junit xml format compatible output file containing the test results for each device the instrumentation
     * tests run on.

     *

     * The files are stored in target/surefire-reports and named TEST-deviceid.xml. The deviceid for an emulator is
     * deviceSerialNumber_avdName_manufacturer_model. The serial number is commonly emulator-5554 for the first emulator
     * started with numbers increasing. avdName is as defined in the SDK tool. The manufacturer is typically "unknown"
     * and the model is typically "sdk".

     * The deviceid for an actual devices is deviceSerialNumber_manufacturer_model.

     *

     * The file contains system properties from the system running the Android Maven Plugin (JVM) and device properties
     * from the device/emulator the tests are running on.

     *

     * The file contains a single TestSuite for all tests and a TestCase for each test method. Errors and failures are
     * logged in the file and the system log with full stack traces and other details available.
     *
     * Defaults to false.
     */
    @Parameter( property = "android.monkey.createReport" )
    private Boolean monkeyCreateReport;

    @PullParameter( defaultValue = "false" )
    private Boolean parsedCreateReport;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException
    {
        ConfigHandler configHandler = new ConfigHandler( this, this.session, this.execution );
        configHandler.parseConfiguration();

        if ( isEnableIntegrationTest() )
        {
            exerciseApp();
        }
    }

    /**
     * Whether or not tests are enabled.
     *
     * @return a boolean indicating whether or not tests are enabled.
     */
    protected boolean isEnableIntegrationTest()
    {
        return !parsedSkip && !mavenTestSkip && !mavenSkipTests;
    }

    /**
     * Whether or not test failures should be ignored.
     *
     * @return a boolean indicating whether or not test failures should be ignored.
     */
    protected boolean isIgnoreTestFailures()
    {
        return mavenIgnoreTestFailure || mavenTestFailureIgnore;
    }

    /**
     * Actually plays tests.
     *
     * @throws MojoExecutionException
     *             if exercising app threw an exception and isIgnoreTestFailures is false..
     * @throws MojoFailureException
     *             if exercising app failed and isIgnoreTestFailures is false.
     */
    protected void exerciseApp() throws MojoExecutionException, MojoFailureException
    {

        getLog().debug( "Parsed values for Android Monkey invocation: " );
        getLog().debug( "seed:" + parsedSeed );

        DeviceCallback instrumentationTestExecutor = new DeviceCallback()
        {
            @Override
            public void doWithDevice( final IDevice device ) throws MojoExecutionException, MojoFailureException
            {
                String deviceLogLinePrefix = DeviceHelper.getDeviceLogLinePrefix( device );

                MonkeyTestRunner monkeyTestRunner = new MonkeyTestRunner( parsedEventCount, device );

                monkeyTestRunner.setRunName( "ui monkey tests" );
                if ( parsedSeed != null )
                {
                    monkeyTestRunner.setSeed( parsedSeed );
                }
                if ( parsedPercentTouch != null )
                {
                    monkeyTestRunner.setPercentTouch( parsedPercentTouch );
                }
                if ( parsedPercentMotion != null )
                {
                    monkeyTestRunner.setPercentTouch( parsedPercentMotion );
                }
                if ( parsedPercentTrackball != null )
                {
                    monkeyTestRunner.setPercentTrackball( parsedPercentTrackball );
                }
                if ( parsedPercentNav != null )
                {
                    monkeyTestRunner.setPercentNav( parsedPercentNav );
                }
                if ( parsedPercentMajorNav != null )
                {
                    monkeyTestRunner.setPercentMajorNav( parsedPercentMajorNav );
                }
                if ( parsedPercentSyskeys != null )
                {
                    monkeyTestRunner.setPercentSyskeys( parsedPercentSyskeys );
                }
                if ( parsedPercentAppswitch != null )
                {
                    monkeyTestRunner.setPercentAppswitch( parsedPercentAppswitch );
                }
                if ( parsedPercentAnyevent != null )
                {
                    monkeyTestRunner.setPercentAnyEvent( parsedPercentAnyevent );
                }
                if ( parsedPackages != null )
                {
                    monkeyTestRunner.setPackages( parsedPackages );
                }
                if ( parsedCategories != null )
                {
                    monkeyTestRunner.setCategories( parsedCategories );
                }
                monkeyTestRunner.setDebugNoEvents( parsedDebugNoEvents );
                monkeyTestRunner.setHprof( parsedHprof );
                monkeyTestRunner.setIgnoreCrashes( parsedIgnoreCrashes );
                monkeyTestRunner.setIgnoreTimeouts( parsedIgnoreTimeouts );
                monkeyTestRunner.setIgnoreSecurityExceptions( parsedIgnoreSecurityExceptions );
                monkeyTestRunner.setKillProcessAfterError( parsedKillProcessAfterError );
                monkeyTestRunner.setMonitorNativeCrash( parsedMonitorNativeCrashes );

                getLog().info( deviceLogLinePrefix + "Running ui monkey tests" );
                try
                {
                    AndroidTestRunListener testRunListener = new AndroidTestRunListener( project, device, getLog(),
                            parsedCreateReport, false, "", "", targetDirectory );
                    monkeyTestRunner.run( testRunListener );
                    if ( testRunListener.hasFailuresOrErrors() && !isIgnoreTestFailures() )
                    {
                        throw new MojoFailureException( deviceLogLinePrefix + "Tests failed on device." );
                    }
                    if ( testRunListener.testRunFailed() )
                    {
                        throw new MojoFailureException( deviceLogLinePrefix + "Test run failed to complete: "
                                + testRunListener.getTestRunFailureCause() );
                    }
                    if ( testRunListener.threwException() && !isIgnoreTestFailures() )
                    {
                        throw new MojoFailureException( deviceLogLinePrefix + testRunListener.getExceptionMessages() );
                    }
                }
                catch ( TimeoutException e )
                {
                    throw new MojoExecutionException( deviceLogLinePrefix + "timeout", e );
                }
                catch ( AdbCommandRejectedException e )
                {
                    throw new MojoExecutionException( deviceLogLinePrefix + "adb command rejected", e );
                }
                catch ( ShellCommandUnresponsiveException e )
                {
                    throw new MojoExecutionException( deviceLogLinePrefix + "shell command " + "unresponsive", e );
                }
                catch ( IOException e )
                {
                    throw new MojoExecutionException( deviceLogLinePrefix + "IO problem", e );
                }
            }
        };

        doWithDevices( instrumentationTestExecutor );
    }

    /**
     * @return default seed.
     */
    // used via PullParameter annotation - do not remove
    private Long getSeed()
    {
        return parsedSeed;
    }

    /**
     * @return default throttle.
     */
    // used via PullParameter annotation - do not remove
    private Long getThrottle()
    {
        return parsedThrottle;
    }

    /**
     * @return default percentTouch.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentTouch()
    {
        return parsedPercentTouch;
    }

    /**
     * @return default percentMotion.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentMotion()
    {
        return parsedPercentMotion;
    }

    /**
     * @return default percentTrackball.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentTrackball()
    {
        return parsedPercentTrackball;
    }

    /**
     * @return default percentNav.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentNav()
    {
        return parsedPercentNav;
    }

    /**
     * @return default percentMajorNav.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentMajorNav()
    {
        return parsedPercentMajorNav;
    }

    /**
     * @return default percentSyskeys.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentSyskeys()
    {
        return parsedPercentSyskeys;
    }

    /**
     * @return default percentAppSwitch.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentAppswitch()
    {
        return parsedPercentAppswitch;
    }

    /**
     * @return default percentAnyEvent.
     */
    // used via PullParameter annotation - do not remove
    private Integer getPercentAnyevent()
    {
        return parsedPercentAnyevent;
    }

    /**
     * @return default packages.
     */
    public String[] getPackages()
    {
        return parsedPackages;
    }

    /**
     * @return default categories.
     */
    public String[] getCategories()
    {
        return parsedCategories;
    }
}