text:
package org.trade.core.query;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.trade.core.query.antlr.QueryLexer;
import org.trade.core.query.antlr.QueryParser;
import org.trade.core.query.listener.QueryErrorListener;
import org.trade.core.query.listener.QueryParseError;
import org.trade.core.query.listener.QueryTranslator;

import java.util.List;

/**
 * This class provides the model of a TraDE query.
 * <p>
 * Created by hahnml on 05.02.2018.
 */
public class Query {

    public static final String QUERY_PREFIX = "$";

    private String queryString;

    private String dataObjectName;

    private String dataElementName;

    private String indexOfDataValue;

    private PROPERTY property;

    private boolean specifiesPropertySelection;

    private boolean specifiesDataValue;

    private boolean specifiesDataValueIndex;

    private boolean isValid;

    private List<QueryParseError> parserErrors;

    private Query(String queryString) {
        this.queryString = queryString;
    }

    /**
     * Parses a query string into a respective Query model object.
     *
     * @param queryString the query string
     * @return the query object
     */
    public static Query parseQuery(String queryString) {
        // Create a new Query object that can be used by the QueryTranslator and QueryErrorListener
        Query query = new Query(queryString);

        // Read the query string as a char stream
        CharStream input = CharStreams.fromString(queryString);

        // Forward the char stream to the lexer
        QueryLexer lexer = new QueryLexer(input);

        // Create a stream for the tokens
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);

        // Forward the token stream to the parser
        QueryParser parser = new QueryParser(tokenStream);

        // Add a special error listener that collects all occurring errors in this class
        QueryErrorListener errorListener = new QueryErrorListener();
        parser.addErrorListener(errorListener);

        // Start parsing the query string
        ParseTree tree = parser.query();

        // Translate the query string into a Query object for further processing by walking through the parse tree
        // using our QueryTranslator
        ParseTreeWalker walker = new ParseTreeWalker();
        QueryTranslator translator = new QueryTranslator(query);
        walker.walk(translator, tree);

        query.setParserErrors(errorListener.getErrors());

        if (query.parserErrors.isEmpty()) {
            // Set to "false" as default
            query.setValid(false);

            // Apply some "semantic" checks, i.e., if the query will point to a usable value or not
            if (query.getDataObjectName() != null) {
                if (query.getDataElementName() != null) {
                    if (query.specifiesDataValue()) {
                        // Queries specifying a data object, data element and a data value might be valid.
                        // Further checks require run time information, e.g., a data value query
                        // ($dataObject/dataElement/value) without an index specification is valid if the data
                        // element is not a collection, else the query is invalid in that context since it requires
                        // an index to point to a single value.
                        query.setValid(true);
                    } else {
                        // Queries specifying a data object and data element without a data value are
                        // only valid, if they have a property selection
                        if (query.specifiesPropertySelection()) {
                            query.setValid(true);
                        }
                    }
                } else {
                    // Queries specifying only a data object without a data element are only valid, if they have a
                    // property selection
                    if (query.specifiesPropertySelection()) {
                        query.setValid(true);
                    }
                }
            }
        } else {
            query.setValid(false);
        }

        return query;
    }

    /**
     * Gets the data object name referenced in the query.
     *
     * @return the data object name
     */
    public String getDataObjectName() {
        return dataObjectName;
    }

    /**
     * Sets the data object name referenced in the query.
     *
     * @param dataObjectName the data object name
     */
    public void setDataObjectName(String dataObjectName) {
        this.dataObjectName = dataObjectName;
    }

    /**
     * Gets the data element name referenced in the query.
     *
     * @return the data element name
     */
    public String getDataElementName() {
        return dataElementName;
    }

    /**
     * Sets the data element name referenced in the query.
     *
     * @param dataElementName the data element name
     */
    public void setDataElementName(String dataElementName) {
        this.dataElementName = dataElementName;
    }

    /**
     * Gets the index of data value referenced in the query.
     *
     * @return the index of data value
     */
    public String getIndexOfDataValue() {
        return indexOfDataValue;
    }

    /**
     * Sets the index of data value referenced in the query.
     *
     * @param indexOfDataValue the index of data value
     */
    public void setIndexOfDataValue(String indexOfDataValue) {
        this.indexOfDataValue = indexOfDataValue;
    }

    /**
     * Gets the property referenced in the property selection of the query.
     *
     * @return the property
     */
    public PROPERTY getProperty() {
        return property;
    }

    /**
     * Sets the property referenced in the property selection of the query.
     *
     * @param property the property
     */
    public void setProperty(PROPERTY property) {
        this.property = property;
    }

    /**
     * Whether the query specifies a property selection (e.g., "..?size") or not.
     *
     * @return True, if the query has a property selection. False, otherwise.
     */
    public boolean specifiesPropertySelection() {
        return specifiesPropertySelection;
    }

    /**
     * Sets whether the query specifies a property selection or not.
     *
     * @param specifiesPropertySelection True, if the query has a property selection. False, otherwise.
     */
    public void setSpecifiesPropertySelection(boolean specifiesPropertySelection) {
        this.specifiesPropertySelection = specifiesPropertySelection;
    }

    /**
     * Whether the query refers to a data value ("../value") or not.
     *
     * @return True, if the query refers to a data value. False, otherwise.
     */
    public boolean specifiesDataValue() {
        return specifiesDataValue;
    }

    /**
     * Sets whether the query refers to a data value or not.
     *
     * @param specifiesDataValue True, if the query refers to a data value. False, otherwise.
     */
    public void setSpecifiesDataValue(boolean specifiesDataValue) {
        this.specifiesDataValue = specifiesDataValue;
    }

    /**
     * Whether the query refers to a collection of data values and specifies an index selection ("../value[3]") or not.
     *
     * @return True, if the query specifies an index selection. False, otherwise.
     */
    public boolean specifiesDataValueIndex() {
        return specifiesDataValueIndex;
    }

    /**
     * Sets whether the query refers to a collection of data values and specifies an index selection or not.
     *
     * @param specifiesDataValueIndex True, if the query specifies an index selection. False, otherwise.
     */
    public void setSpecifiesDataValueIndex(boolean specifiesDataValueIndex) {
        this.specifiesDataValueIndex = specifiesDataValueIndex;
    }

    /**
     * Whether the query is valid, i.e., it's syntax is correct. If the query is invalid, all detected errors can be
     * retrieved by calling {@link Query#getParserErrors()}.
     *
     * @return True, if the provided query string represents a valid query. False, otherwise.
     */
    public boolean isValid() {
        return isValid;
    }

    /**
     * Sets whether the query is valid or not.
     *
     * @param valid True, if the provided query string represents a valid query. False, otherwise.
     */
    public void setValid(boolean valid) {
        isValid = valid;
    }

    /**
     * Provides a list of detected parser errors.
     *
     * @return the parser errors
     */
    public List<QueryParseError> getParserErrors() {
        return parserErrors;
    }

    /**
     * Sets the list of detected parser errors.
     *
     * @param parserErrors the parser errors
     */
    public void setParserErrors(List<QueryParseError> parserErrors) {
        this.parserErrors = parserErrors;
    }

    /**
     * Gets the raw query string.
     *
     * @return the query string
     */
    public String getQueryString() {
        return queryString;
    }

    @Override
    public String toString() {
        return this.queryString;
    }

    /**
     * This enum represents possible property selection values.
     */
    public enum PROPERTY {
        SIZE, URL
    }

    /**
     * This enum represents possible static index values.
     */
    public enum INDEX {
        FIRST, LAST
    }
}


text:
package asp4j.mapping.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Explicit mapping name for enum constants, if their name is not used.
 *
 * @author hbeck June 8, 2013
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MapAs {

    /**
     * @return mapping name for enum constant (instead of default name)
     */
    String value();

}

redpajama_set_name: RedPajamaGithub


text:
package graph;

import java.awt.Point;

import interfaces.Graph;

public class ConresActivity {
    public int id;
    public Point position;
    public String name;
    public String role;
    public boolean isExecuted;
    public boolean isPending;
    public Graph nestedGraph = null;

    public ConresActivity(int id, Point position, String name, String role, boolean isPending, Graph nestedGraph) {
        this.id = id;
        this.position = position;
        this.name = name;
        this.role = role;
        this.isPending = isPending;
        this.nestedGraph = nestedGraph;
        this.isExecuted = false;
    }

    public ConresActivity(int id, Point position, String name, String role, boolean isPending) {
        this.id = id;
        this.position = position;
        this.name = name;
        this.role = role;
        this.isPending = isPending;
        this.isExecuted = false;
    }

    @Override
    public String toString() {
        return " ";
    }
}


text:
module Api
  module V1
    module Frontend
      class SkipsController < ApiApplicationController
        respond_to :json

        def index
          option = current_project.options.find(params[:option_id])
          skips = option.skips
          respond_with skips
        end

        def show
          option = current_project.options.find(params[:option_id])
          skip = option.skips.find(params[:id])
        end

        def create
          option = current_project.options.find(params[:option_id])
          @skip = option.skips.new(params)
          if @skip.save
            render nothing: true, status: :created
          else
            render nothing: true, status: :unprocessable_entity
          end
        end

        def update
          option = current_project.options.find(params[:option_id])
          skip = option.skips.find(params[:id])
          respond_with skip.update_attributes(params[:skip])
        end

        def destroy
          option = current_project.options.find(params[:option_id])
          skip = option.skips.find(params[:id])
          respond_with skip.destroy
        end

      end
    end
  end
end


text: Модуль для получения дампа объекта.


text:
# This file is part of RandomSources.
#
#    Copyright (C) 2012, Eric Astor
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

from math import log as _log, ceil as _ceil, floor as _floor
from random import Random
from urllib import urlencode, quote as urlquote
from urllib2 import Request, urlopen

import sys
bitsPerFloat = sys.float_info.mant_dig

try:
	import json
except ImportError:
	import simplejson as json

class QuantumRandom(Random):
	"""Alternate random number generator using the ANU Quantum
	Random Numbers Server as the source.

	Requires Internet access."""

	_URL = 'https://qrng.anu.edu.au/API/jsonI.php'
	_DATATYPES = ['uint8', 'uint16', 'hex16']
	_MAXLEN = 1024
	_MAXINT = 65536

	_generator = None

	def _fetch(self, dataType, arrayLength=1, blockSize=1):
		"Fetch data from the ANU Quantum Random Numbers JSON API"
		if dataType not in self._DATATYPES:
			raise ValueException('dataType must be one of %s' % self._DATATYPES)
		if arrayLength > self._MAXLEN:
			raise ValueException('arrayLength cannot be larger than %d' % self._MAXLEN)
		if blockSize > self._MAXLEN:
			raise ValueException('blockSize cannot be larger than %d' % self._MAXLEN)

		options = dict(type=dataType, length=arrayLength, size=blockSize)
		url = 'https://qrng.anu.edu.au/API/jsonI.php?' + urlencode(options)

		def object_hook(obj):
			if obj.get('type') == 'string':
				obj['data'] = [s.encode('ascii') for s in obj['data']]
			return obj
		data = json.loads(urlopen(url).read(), object_hook=object_hook)
		assert data['success'] is True, data
		assert data['length'] == arrayLength, data
		return data['data']

	def cached_generator(self, dataType='uint16', cacheSize=None):
		"""Returns numbers from the ANU Quantum Random Numbers Server.

		Caches numbers to avoid latency."""
		if cacheSize is None:
			cacheSize = self._MAXLEN
		while 1:
			for n in self._fetch(dataType, cacheSize, cacheSize):
				yield n

	def random(self, generator=None):
		return self.getrandbits(bitsPerFloat, generator) * 2**-bitsPerFloat
	random.__doc__ = Random.random.__doc__

	def getrandbits(self, k, generator=None):
		"getrandbits(k) -> x. Generates a long int with k random bits."
		if k == 0:
			return 0

		if generator is None:
			if self._generator is None:
				self._generator = self.cached_generator()
			generator = self._generator
		maxlen = self._MAXLEN

		if k <= 16*maxlen: # A uint16 fetch supplies enough bits
			r = 0
			for i in xrange((k + 15) // 16):
				r <<= 16
				r |= generator.next()
			if k%16:
				r >>= 16 - (k%16)
			return r
		else:
			fullFetch = 8*maxlen*maxlen
			fullBlock = 8*maxlen
			remainingBits = k%fullBlock

			hexString = ''
			if remainingBits:
				s = hex(self.getrandbits(remainingBits, generator))
				hexString = (s[:-1] if s.endswith('L') else s)
			if k >= fullFetch:
				hexString += ''.join(''.join(self._fetch('hex16', maxlen, maxlen)) for i in xrange(k // fullFetch))
				k %= fullFetch
			if k >= fullBlock:
				hexString += ''.join(self._fetch('hex16', k // fullBlock, maxlen))

			return long(hexString, 16)

	def _stub(self, *args, **kwargs):
		"Stub method. Not used for a remote random number generator."
		return None
	seed = _stub
	jumpahead = _stub

	def _notimplemented(self, *args, **kwargs):
		"Method should not be called for a remote random number generator."
		raise NotImplementedError('Remote entropy sources do not have state.')
	getstate = _notimplemented
	setstate = _notimplemented

## -------------------- integer methods  -------------------

	def randrange(self, start, stop=None, step=1, generator=None):
		# This function exactly parallels the code in Random.py,
		# so most comments are copied here.

		# This code is a bit messy to make it fast for the
		# common case while still doing adequate error checking.
		istart = int(start)
		if istart != start:
			raise ValueError('non-integer arg 1 for randrange()')
		if stop is None:
			if istart > 0:
				return self._randbelow(istart, generator)
			raise ValueError('empty range for randrange()')

		# stop argument supplied.
		istop = int(stop)
		if istop != stop:
			raise ValueError('non-integer stop for randrange()')
		width = istop - istart
		if step == 1:
			if width > 0:
				return int(istart + self._randbelow(width, generator))
			raise ValueError('empty range for randrange() (%d,%d, %d)' % (istart, istop, width))

		# Non-unit step argument supplied.
		istep = int(step)
		if istep != step:
			raise ValueError('non-integer step for randrange()')
		if istep > 0:
			n = (width + istep - 1) // istep
		elif istep < 0:
			n = (width + istep + 1) // istep
		else:
			raise ValueError('zero step for randrange()')

		if n <= 0:
			raise ValueError('empty range for randrange()')

		return int(istart + istep*self._randbelow(n, generator))
	randrange.__doc__ = Random.randrange.__doc__

	def _randbelow(self, n, generator=None, _log=_log, int=int):
		k = int(1.00001 + _log(n-1, 2.0))   # 2**k > n-1 > 2**(k-2)
		r = self.getrandbits(k, generator)
		while r >= n:
			r = self.getrandbits(k, generator)
		return r
	_randbelow.__doc__ = Random._randbelow.__doc__

## -------------------- sequence methods  -------------------

	def choice(self, seq, generator=None):
		length = len(seq)
		if length == 0:
			raise IndexError('list index out of range')
		return seq[self.randrange(length, generator=generator)]
	choice.__doc__ = Random.choice.__doc__

	def shuffle(self, x, random=None, generator=None):
		if random is not None:
			return Random.shuffle(self, x, random)

		randrange = self.randrange
		for i in reversed(xrange(1, len(x))):
			# pick an element in x[:i+1] with which to exchange x[i]
			j = randrange(i + 1, generator=generator)
			x[i], x[j] = x[j], x[i]
	shuffle.__doc__ = Random.shuffle.__doc__

	def sample(self, population, k, generator=None):
		# This function exactly parallels the code in Random.py.
		# Comments are therefore omitted, to save space.

		n = len(population)
		if not 0 <= k <= n:
			raise ValueError('sample larger than population')
		randrange = self.randrange
		result = [None] * k
		setsize = 21
		if k > 5:
			setsize += 4 ** _ceil(_log(k * 3, 4))
		if n <= setsize or hasattr(population, 'keys'):
			pool = list(population)
			for i in xrange(k):
				j = randrange(n-i, generator=generator)
				result[i] = pool[j]
				pool[j] = pool[n-i-1]
		else:
			try:
				selected = set()
				selected_add = selected.add
				for i in xrange(k):
					j = randrange(n, generator=generator)
					while j in selected:
						j = randrange(n, generator=generator)
					selected_add(j)
					result[i] = population[j]
			except (TypeError, KeyError):
				if isinstance(population, list):
					raise
				return self.sample(tuple(population), k, generator)
		return result
	sample.__doc__ = Random.sample.__doc__

if __name__ == '__main__':
   print __doc__.strip()


text:
var gulp = require('gulp');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var connect = require('gulp-connect');
var less = require('gulp-less');
var path = require('path');

var bundlePaths = {
    mainJs: ['public/src/main.js'],
    srcJs: ['public/src/main.js', 'public/src/components/**/*.js', 'src/common/**/*.js'],
    srcLess: ['public/src/main.less'],
    componentsLess: 'public/src/components/**/*.less',
    commonLess: 'public/src/common/**/*.less',
    html: ['public/*.html'],
    dest: 'public/src/build/js'
}

function compile() {
    var bundler = watchify(browserify(bundlePaths.mainJs, {debug: true}).transform(babelify, {presets: ['es2015']}));

    function rebundle() {
        bundler.bundle()
            .on('error', function(err) { console.error(err); this.emit('end'); })
            .pipe(source('build.js'))
            .pipe(buffer())
            .pipe(sourcemaps.init({loadMaps: true}))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest('./public/build'));
    }

    rebundle();
}

function watch() {
    gulp.watch(bundlePaths.html, ['html']);
    gulp.watch(bundlePaths.componentsLess, ['style']);
    gulp.watch(bundlePaths.commonLess, ['style']);
    gulp.watch(bundlePaths.srcLess, ['style']);
    gulp.watch(bundlePaths.srcJs, ['build', 'html']);
}

gulp.task('connect', function() {
    connect.server({
        root: './public/src',
        livereload: true
    });
});

gulp.task('html', function() {
    gulp.src('./public/*.html')
        .pipe(connect.reload());
});

gulp.task('style', function() {
    return gulp.src(bundlePaths.srcLess)
    .pipe(sourcemaps.init())
    .pipe(less({
        paths: [path.join(__dirname, 'components', 'includes'), path.join(__dirname, 'common', 'includes')]
    }))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('./public/build/css'));
})

gulp.task('build', function() { return compile(); });
gulp.task('watch', function() { return watch(); });

gulp.task('default', ['style', 'watch']);


text:
<!DOCTYPE html>

<link rel="stylesheet" th:href="@{/css/courses.css}">

Floated Courses

                        more_vert
                        These are the courses managed by you this session

remove

fullscreen

                                <input class="fuzzy-search form-control round mb-1" placeholder="Search" />

                                        <button class="sort btn btn-block btn-outline-info btn-round mb-2" data-sort="code">Sort by code</button>

                                        <button class="sort btn btn-block btn-outline-primary btn-round mb-2" data-sort="title">Sort by title</button>

                                        <button class="sort btn btn-block btn-outline-success btn-round mb-2" data-sort="semester">Sort by semester</button>

                                                         :

                                                    more_vert

                                                                event


text:
class HomeController < ApplicationController

  def index
    # if user is signed in, show documents page
    redirect_to records_path and return if current_user.present?
  end

end


text:
@interface GRMustacheTemplateRepositoryTest : GRMustachePublicAPITest
@end

@implementation GRMustacheTemplateRepositoryTest

- (void)testTemplateInstancesAreNotReused
{
    NSDictionary *templates = @{ @"name": @"value: {{ value }}" };
    GRMustacheTemplateRepository *repository = [GRMustacheTemplateRepository templateRepositoryWithDictionary:templates];

    GRMustacheTemplate *template1 = [repository templateNamed:@"name" error:NULL];
    template1.baseContext = [template1.baseContext contextByAddingObject:@{ @"value": @"foo" }];

    GRMustacheTemplate *template2 = [repository templateNamed:@"name" error:NULL];

    STAssertTrue(template1 != template2, @"");
    STAssertEqualObjects([template1 renderObject:nil error:NULL], @"value: foo", nil);
    STAssertEqualObjects([template2 renderObject:nil error:NULL], @"value: ", nil);
}

@end


text:
// Package metrics contains metrics interfaces and implementations for PodSecurity admission
package metrics // import "k8s.io/pod-security-admission/metrics"


text:
package serialize

import (
	"bytes"
	"fmt"
	"strconv"
)

// WithValues implements LogSink.WithValues. The old key/value pairs are
// assumed to be well-formed, the new ones are checked and padded if
// necessary. It returns a new slice.
func WithValues(oldKV, newKV []interface{}) []interface{} {
	if len(newKV) == 0 {
		return oldKV
	}
	newLen := len(oldKV) + len(newKV)
	hasMissingValue := newLen%2 != 0
	if hasMissingValue {
		newLen++
	}
	// The new LogSink must have its own slice.
	kv := make([]interface{}, 0, newLen)
	kv = append(kv, oldKV...)
	kv = append(kv, newKV...)
	if hasMissingValue {
		kv = append(kv, missingValue)
	}
	return kv
}

// TrimDuplicates deduplicates elements provided in multiple key/value tuple
// slices, whilst maintaining the distinction between where the items are
// contained.
func TrimDuplicates(kvLists ...[]interface{}) [][]interface{} {
	// maintain a map of all seen keys
	seenKeys := map[interface{}]struct{}{}
	// build the same number of output slices as inputs
	outs := make([][]interface{}, len(kvLists))
	// iterate over the input slices backwards, as 'later' kv specifications
	// of the same key will take precedence over earlier ones
	for i := len(kvLists) - 1; i >= 0; i-- {
		// initialise this output slice
		outs[i] = []interface{}{}
		// obtain a reference to the kvList we are processing
		// and make sure it has an even number of entries
		kvList := kvLists[i]
		if len(kvList)%2 != 0 {
			kvList = append(kvList, missingValue)
		}

		// start iterating at len(kvList) - 2 (i.e. the 2nd last item) for
		// slices that have an even number of elements.
		// We add (len(kvList) % 2) here to handle the case where there is an
		// odd number of elements in a kvList.
		// If there is an odd number, then the last element in the slice will
		// have the value 'null'.
		for i2 := len(kvList) - 2 + (len(kvList) % 2); i2 >= 0; i2 -= 2 {
			k := kvList[i2]
			// if we have already seen this key, do not include it again
			if _, ok := seenKeys[k]; ok {
				continue
			}
			// make a note that we've observed a new key
			seenKeys[k] = struct{}{}
			// attempt to obtain the value of the key
			var v interface{}
			// i2+1 should only ever be out of bounds if we handling the first
			// iteration over a slice with an odd number of elements
			if i2+1 < len(kvList) {
				v = kvList[i2+1]
			}
			// add this KV tuple to the *start* of the output list to maintain
			// the original order as we are iterating over the slice backwards
			outs[i] = append([]interface{}{k, v}, outs[i]...)
		}
	}
	return outs
}

const missingValue = "(MISSING)"

// KVListFormat serializes all key/value pairs into the provided buffer.
// A space gets inserted before the first pair and between each pair.
func KVListFormat(b *bytes.Buffer, keysAndValues ...interface{}) {
	for i := 0; i < len(keysAndValues); i += 2 {
		var v interface{}
		k := keysAndValues[i]
		if i+1 < len(keysAndValues) {
			v = keysAndValues[i+1]
		} else {
			v = missingValue
		}
		b.WriteByte(' ')
		// Keys are assumed to be well-formed according to
		// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/migration-to-structured-logging.md#name-arguments
		// for the sake of performance. Keys with spaces,
		// special characters, etc. will break parsing.
		if k, ok := k.(string); ok {
			// Avoid one allocation when the key is a string, which
			// normally it should be.
			b.WriteString(k)
		} else {
			b.WriteString(fmt.Sprintf("%s", k))
		}

		// The type checks are sorted so that more frequently used ones
		// come first because that is then faster in the common
		// cases. In Kubernetes, ObjectRef (a Stringer) is more common
		// than plain strings
		// (https://github.com/kubernetes/kubernetes/pull/106594#issuecomment-975526235).
		switch v := v.(type) {
		case fmt.Stringer:
			writeStringValue(b, true, StringerToString(v))
		case string:
			writeStringValue(b, true, v)
		case error:
			writeStringValue(b, true, ErrorToString(v))
		case []byte:
			// In https://github.com/kubernetes/klog/pull/237 it was decided
			// to format byte slices with "%+q". The advantages of that are:
			// - readable output if the bytes happen to be printable
			// - non-printable bytes get represented as unicode escape
			//   sequences (\uxxxx)
			//
			// The downsides are that we cannot use the faster
			// strconv.Quote here and that multi-line output is not
			// supported. If developers know that a byte array is
			// printable and they want multi-line output, they can
			// convert the value to string before logging it.
			b.WriteByte('=')
			b.WriteString(fmt.Sprintf("%+q", v))
		default:
			writeStringValue(b, false, fmt.Sprintf("%+v", v))
		}
	}
}

// StringerToString converts a Stringer to a string,
// handling panics if they occur.
func StringerToString(s fmt.Stringer) (ret string) {
	defer func() {
		if err := recover(); err != nil {
			ret = fmt.Sprintf("<panic: %s>", err)
		}
	}()
	ret = s.String()
	return
}

// ErrorToString converts an error to a string,
// handling panics if they occur.
func ErrorToString(err error) (ret string) {
	defer func() {
		if err := recover(); err != nil {
			ret = fmt.Sprintf("<panic: %s>", err)
		}
	}()
	ret = err.Error()
	return
}

func writeStringValue(b *bytes.Buffer, quote bool, v string) {
	data := []byte(v)
	index := bytes.IndexByte(data, '\n')
	if index == -1 {
		b.WriteByte('=')
		if quote {
			// Simple string, quote quotation marks and non-printable characters.
			b.WriteString(strconv.Quote(v))
			return
		}
		// Non-string with no line breaks.
		b.WriteString(v)
		return
	}

	// Complex multi-line string, show as-is with indention like this:
	// I... "hello world" key=<
	// <tab>line 1
	// <tab>line 2
	//  >
	//
	// Tabs indent the lines of the value while the end of string delimiter
	// is indented with a space. That has two purposes:
	// - visual difference between the two for a human reader because indention
	//   will be different
	// - no ambiguity when some value line starts with the end delimiter
	//
	// One downside is that the output cannot distinguish between strings that
	// end with a line break and those that don't because the end delimiter
	// will always be on the next line.
	b.WriteString("=<\n")
	for index != -1 {
		b.WriteByte('\t')
		b.Write(data[0 : index+1])
		data = data[index+1:]
		index = bytes.IndexByte(data, '\n')
	}
	if len(data) == 0 {
		// String ended with line break, don't add another.
		b.WriteString(" >")
	} else {
		// No line break at end of last line, write rest of string and
		// add one.
		b.WriteByte('\t')
		b.Write(data)
		b.WriteString("\n >")
	}
}


text:
import { createStore, compose, applyMiddleware } from 'redux';
import { persistStore, autoRehydrate } from 'redux-persist';
import reduxPersistCrosstab from 'redux-persist-crosstab';
import reduxPersistTransformImmutable from 'redux-persist-transform-immutable';
import thunkMiddleware from 'redux-thunk';
import { createSelector } from 'reselect';

import * as actions from '../actions';
import reducers from '../reducers';
import * as selectors from '../selectors';

let finalCreateStore;
if (__DEV__) {
  finalCreateStore = compose(
    applyMiddleware(thunkMiddleware),
    autoRehydrate(),
    require('../containers/DevTools').default.instrument(),
  )(createStore);
} else {
  finalCreateStore = compose(
    applyMiddleware(thunkMiddleware),
    autoRehydrate(),
  )(createStore);
}

const store = finalCreateStore(reducers);
export default store;

if (module.hot) {
  module.hot.accept('../reducers', () => {
    store.replaceReducer(require('../reducers'));
  });
}

// TODO: come up with a way to invalidate old data, if it's incompatible
reduxPersistCrosstab(
  persistStore(store, {
    whitelist: ['session'],
    transforms: [reduxPersistTransformImmutable()],
  }),
);

// TODO: move this stuff elsewhere
let messageTimeout = null;
const messageSelector = createSelector(
  selectors.messages,
  (messages) => {
    if (messages.count() && !messageTimeout) {
      messageTimeout = setTimeout(
        () => {
          messageTimeout = null;
          store.dispatch(actions.messageShift());
        },
        5000,
      );
    }
  },
);
store.subscribe(() => messageSelector(store.getState()));


text:
using UnityEngine;
using System.Collections;

public class FaderScript : MonoBehaviour, CustomActionListener, IActionNotifier
{
	bool destroyFaderOnEnd;

	public void init(Color para_startColor, Color para_fadeToColor, float para_effectDuration, bool para_destroyFaderOnEnd)
	{
		destroyFaderOnEnd = para_destroyFaderOnEnd;

		SpriteRenderer sRend = transform.GetComponent<SpriteRenderer>();
		sRend.color = para_startColor;
		sRend.enabled = true;

		ColorTransition ct = transform.gameObject.AddComponent<ColorTransition>();
		ct.registerListener("FaderScript",this);
		ct.init(para_fadeToColor,para_effectDuration);
	}

	public void respondToEvent(string para_sourceID, string para_eventID, System.Object para_eventData)
	{
		if(para_eventID == "ColorTransition")
		{
			notifyAllListeners(transform.name,"FadeEffectDone",null);
			if(destroyFaderOnEnd)
			{
				Destroy(transform.gameObject);
			}
		}
	}

	// Action Notifier Methods.
	IActionNotifier acNotifier = new ConcActionNotifier();
	public void registerListener(string para_name, CustomActionListener para_listener) { acNotifier.registerListener(para_name,para_listener); }
	public void unregisterListener(string para_name) { acNotifier.unregisterListener(para_name); }
	public void notifyAllListeners(string para_sourceID, string para_eventID, System.Object para_eventData)	{ acNotifier.notifyAllListeners(para_sourceID,para_eventID,para_eventData);	}
}


text:
from .aws import Action as BaseAction
from .aws import BaseARN

service_name = "Amazon Lookout for Vision"
prefix = "lookoutvision"

class Action(BaseAction):
    def __init__(self, action: str = None) -> None:
        super().__init__(prefix, action)

class ARN(BaseARN):
    def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
        super().__init__(
            service=prefix, resource=resource, region=region, account=account
        )

CreateDataset = Action("CreateDataset")
CreateModel = Action("CreateModel")
CreateProject = Action("CreateProject")
DeleteDataset = Action("DeleteDataset")
DeleteModel = Action("DeleteModel")
DeleteProject = Action("DeleteProject")
DescribeDataset = Action("DescribeDataset")
DescribeModel = Action("DescribeModel")
DescribeModelPackagingJob = Action("DescribeModelPackagingJob")
DescribeProject = Action("DescribeProject")
DescribeTrialDetection = Action("DescribeTrialDetection")
DetectAnomalies = Action("DetectAnomalies")
ListDatasetEntries = Action("ListDatasetEntries")
ListModelPackagingJobs = Action("ListModelPackagingJobs")
ListModels = Action("ListModels")
ListProjects = Action("ListProjects")
ListTagsForResource = Action("ListTagsForResource")
ListTrialDetections = Action("ListTrialDetections")
StartModel = Action("StartModel")
StartModelPackagingJob = Action("StartModelPackagingJob")
StartTrialDetection = Action("StartTrialDetection")
StopModel = Action("StopModel")
TagResource = Action("TagResource")
UntagResource = Action("UntagResource")
UpdateDatasetEntries = Action("UpdateDatasetEntries")


text:
require 'simplecov'
SimpleCov.start

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'fogbugz/commands'


text:
package db.dao;

import static org.mockito.Mockito.*;

import javax.persistence.EntityManager;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import application.main;
import db.model.Product;

import static org.junit.Assert.*;
import static org.mockito.Mock.*;

@RunWith(SpringRunner.class)
@SpringBootTest( classes=main.class )
@DataJpaTest( showSql=true )
public class ProductsDAOTest {
	@Autowired
	TestEntityManager entityManager;

	@Autowired
	ProductsDAO pDAO;

	/**
	 * I have the luxury of using a temporary db thats blown away and re-created at start time, so try to find a product well outside that range.
	 * @throws Exception
	 */
	@Test
	public void Test() throws Exception {
		Product p = pDAO.getProductById( 200 );

		assertEquals( null, p );
	}

	@Test
	public void AttemptToCreateNewProduct() throws Exception {
		Product p = new Product();

		p.setName       ( "TestProduct1234567" );
		p.setDescription( "TestProduct1234567" );
		p.setCategory   ( null );
		p.setPrice      ( (float)1.56 );

		pDAO.create(p);
	}

	@Test
	public void AttemptToUpdateProduct() throws Exception {
		Product p = new Product();

		p.setName       ( "TestProduct1234567" );
		p.setDescription( "TestProduct1234567" );
		p.setPrice      ( (float)1.56 );

		pDAO.create( p );

//		System.out.println( "id: " + p.getId() + " name: " + p.getName() );

		p.setName       ( "TestProduct12367" );
		p.setDescription( "TestProduct12367" );
		p.setPrice      ( (float)1.45 );

		Product p2 = pDAO.update( p );

		assertNotNull( p2 );

//		System.out.println( "id: " + p2.getId() + " name: " + p2.getName() );
	}
}


text:
export class Configuration {

    /*-------------------------------------------------------------------------
     * comments
     *-----------------------------------------------------------------------*/
    public static KEY_DOCOMMENT: string = 'comments';
    public static ACTIVATE_ON_ENTER: string = 'activateOnEnter';

    /*-------------------------------------------------------------------------
     * files
     *-----------------------------------------------------------------------*/
    public static KEY_FILES: string = 'files';
    public static EOL: string = 'eol';

    /*-------------------------------------------------------------------------
     * editor
     *-----------------------------------------------------------------------*/
    public static KEY_EDITOR: string = 'editor';
    public static INSERT_SPACES: string = 'insertSpaces';
    public static DETECT_IDENTATION: string = 'detectIndentation';

    public activateOnEnter: boolean;
    public eol: string;
    public insertSpaces: boolean;
    public detectIdentation: boolean;

}


text:
/* JSONP tests */

function jsonp(url, callback) {

	var callbackName = 'jsonp_callback_foo' + Math.round(100000 * Math.random());

	window[callbackName] = function(data) {

		delete window[callbackName];
		document.body.removeChild(script);
		callback(data);

	};

	var script = document.createElement('script');
	script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
	document.body.appendChild(script);

}

//var url = 'http://localhost/upload-api/api/';

//jsonp(url, function (data) {
//
//	console.log(data);
//
//});


text:
package com.rozdoum.socialcomponents.utils;

import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.AlphaAnimation;

@SuppressWarnings("UnnecessaryLocalVariable")
public class AnimationUtils {

    public final static int DEFAULT_DELAY = 0;
    public final static int SHORT_DURATION = 200;
    public final static int ALPHA_SHORT_DURATION = 400;

    /**
     * Reduces the X & Y
     *
     * @param v the view to be scaled
     *
     * @return the ViewPropertyAnimation to manage the animation
     */
    public static ViewPropertyAnimator hideViewByScale (View v) {

        ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(DEFAULT_DELAY).setDuration(SHORT_DURATION)
          .scaleX(0).scaleY(0);

        return propertyAnimator;
    }

    public static boolean isViewHiddenByScale(View v) {
        return v.getScaleX() == 0 && v.getScaleY() == 0;
    }

    /**
     * Shows a view by scaling
     *
     * @param v the view to be scaled
     *
     * @return the ViewPropertyAnimation to manage the animation
     */
    public static ViewPropertyAnimator showViewByScale (View v) {

        ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(DEFAULT_DELAY)
            .scaleX(1).scaleY(1);

        return propertyAnimator;
    }

    /**
     * Shows a view by scaling
     *
     * @param v the view to be scaled
     *
     * @return the ViewPropertyAnimation to manage the animation
     */
    public static ViewPropertyAnimator showViewByScaleWithoutDelay (View v) {

        ViewPropertyAnimator propertyAnimator = v.animate()
                .scaleX(1).scaleY(1);

        return propertyAnimator;
    }

    public static ViewPropertyAnimator hideViewByScaleAndVisibility (final View v) {

        ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(DEFAULT_DELAY).setDuration(SHORT_DURATION)
                .scaleX(0).scaleY(0).withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        v.setVisibility(View.GONE);
                    }
                });

        return propertyAnimator;
    }

    public static AlphaAnimation hideViewByAlpha(final View v) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(ALPHA_SHORT_DURATION);
        v.setAnimation(alphaAnimation);
        return alphaAnimation;
    }

    public static ViewPropertyAnimator showViewByScaleAndVisibility (View v) {
        v.setVisibility(View.VISIBLE);

        ViewPropertyAnimator propertyAnimator = v.animate().setStartDelay(DEFAULT_DELAY)
                .scaleX(1).scaleY(1);

        return propertyAnimator;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SmtpRedirector.Server.Data
{
    public class MailMessage
    {
        public Guid Id { get; set; }
        public DateTime RecievedDateTime { get; set; }
        public string SourceHostname { get; set; }
        public IPAddress SourceIpAddress { get; set; }
        public ISet<Recipient> Recipients { get; set; }
        public EmailAddress FromAddress { get; set; }
        public EmailBody Body { get; set; }
        public ISet<Header> Headers { get; set; }

        public MailMessage(EmailAddress fromAddress)
        {
            FromAddress = fromAddress;
        }

    }

    public class Header
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }

    public class EmailBody
    {
    }
}


text:
@protocol BaseChecksTemplate <NSObject>

- (void)hookChecks;
- (void)unhookChecks;
- (void)runChecks;

@end


text:
@interface MRCRepoViewCodeTableViewCell ()

@property (weak, nonatomic, readwrite) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic, readwrite) IBOutlet UIButton *viewCodeButton;

@property (weak, nonatomic) IBOutlet UIView *wapperView;
@property (weak, nonatomic) IBOutlet UIView *separatorView;
@property (strong, nonatomic) UIView *separatorViewTopBorder;

@end

@implementation MRCRepoViewCodeTableViewCell

- (void)awakeFromNib {
    self.viewCodeButton.tintColor = HexRGB(colorI3);
}

- (void)layoutSubviews {
    [super layoutSubviews];

    self.wapperView.layer.borderColor  = HexRGB(colorB2).CGColor;
    self.wapperView.layer.borderWidth  = MRC_1PX_WIDTH;
    self.wapperView.layer.cornerRadius = 3;

    [self.separatorViewTopBorder removeFromSuperview];
    self.separatorViewTopBorder = [self.separatorView createViewBackedTopBorderWithHeight:MRC_1PX_WIDTH andColor:HexRGB(colorB2)];
    [self.separatorView addSubview:self.separatorViewTopBorder];
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Services;
using Umbraco.New.Cms.Core.Installer;
using Umbraco.New.Cms.Core.Models.Installer;
using Umbraco.New.Cms.Core.Services.Installer;

namespace Umbraco.Cms.Tests.UnitTests.Umbraco.New.Cms.Core.Services;

[TestFixture]
public class InstallServiceTests
{
    [Test]
    public void RequiresInstallRuntimeToInstall()
    {
        var runtimeStateMock = new Mock<IRuntimeState>();
        runtimeStateMock.Setup(x => x.Level).Returns(RuntimeLevel.Run);
        var stepCollection = new NewInstallStepCollection(Enumerable.Empty<IInstallStep>);

        var sut = new InstallService(Mock.Of<ILogger<InstallService>>(), stepCollection, runtimeStateMock.Object);

        Assert.ThrowsAsync<InvalidOperationException>(async () => await sut.Install(new InstallData()));
    }

    [Test]
    public async Task OnlyRunsStepsThatRequireExecution()
    {
        var steps = new[]
        {
            new TestInstallStep { ShouldRun = true },
            new TestInstallStep { ShouldRun = false },
            new TestInstallStep { ShouldRun = true },
        };

        var sut = CreateInstallService(steps);
        await sut.Install(new InstallData());

        foreach (var step in steps)
        {
            Assert.AreEqual(step.ShouldRun, step.HasRun);
        }
    }

    [Test]
    public async Task StepsRunInCollectionOrder()
    {
        List<TestInstallStep> runOrder = new List<TestInstallStep>();

        var steps = new[]
        {
            new TestInstallStep { Id = 1 },
            new TestInstallStep { Id = 2 },
            new TestInstallStep { Id = 3 },
        };

        // Add an method delegate that will add the step itself, that way we can know the executed order.
        foreach (var step in steps)
        {
            step.AdditionalExecution = _ =>
            {
                runOrder.Add(step);
                return Task.CompletedTask;
            };
        }

        var sut = CreateInstallService(steps);
        await sut.Install(new InstallData());

        // The ID's are strictly not necessary, but it makes potential debugging easier.
        var expectedRunOrder = steps.Select(x => x.Id);
        var actualRunOrder = runOrder.Select(x => x.Id);
        Assert.AreEqual(expectedRunOrder, actualRunOrder);
    }

    private InstallService CreateInstallService(IEnumerable<IInstallStep> steps)
    {
        var logger = Mock.Of<ILogger<InstallService>>();
        var stepCollection = new NewInstallStepCollection(() => steps);
        var runtimeStateMock = new Mock<IRuntimeState>();
        runtimeStateMock.Setup(x => x.Level).Returns(RuntimeLevel.Install);

        return new InstallService(logger, stepCollection, runtimeStateMock.Object);
    }

    private class TestInstallStep : IInstallStep
    {
        public bool HasRun;

        public bool ShouldRun = true;

        public int Id;

        public Func<InstallData, Task> AdditionalExecution;

        public Task ExecuteAsync(InstallData model)
        {
            HasRun = true;

            AdditionalExecution?.Invoke(model);
            return Task.CompletedTask;
        }

        public Task<bool> RequiresExecutionAsync(InstallData model) => Task.FromResult(ShouldRun);
    }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'omniauth-eklase'
require 'rack/test'
require 'webmock/rspec'
require 'byebug'

RSpec.configure do |config|
  config.include Rack::Test::Methods
  config.include WebMock::API
end


text:
var good = require('good')
exports.register = good;
exports.options = {
  requestPayload: true,
    reporters: [{
        reporter: require('good-console'),
        events: { log: '*', response: '*', error: '*', request: '*', tail: '*' }
    }]
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %-5level %logger{36}[%line] - %msg %mdc %n</pattern>
        </encoder>
    </appender>

    <!-- 建议设置为WARN或更低级别,此Logger主要用于Struts显示以404错误代码返回的Could not find action or result信息,用于排除编码错误-->
    <logger name="org.apache.struts2.dispatcher" level="WARN" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="lab" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <logger name="jdbc.sqlonly" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    <!-- 打印大量结果集对于运行效率影响较大,开发过程建议默认关闭,在遇到问题需要分析问题是可设置为DEBUG -->
    <logger name="jdbc.resultsettable" level="WARN" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>

    <root level="WARN">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Boucerosia umbellata Wight & Arn.

### Remarks
null


text:
@implementation BorderedLabel

- (void)awakeFromNib{
    self.layer.borderColor = [UIColor blackColor].CGColor;
    self.layer.borderWidth = 3.f;
    self.font = [UIFont fontWithName:@"ComicBook" size:15];
}

- (CGSize)intrinsicContentSize{
    CGSize superSize = [super intrinsicContentSize];
    return CGSizeMake(superSize.width+20, superSize.height+15);
}

- (void)drawTextInRect:(CGRect)rect{
    [super drawTextInRect: CGRectInset(self.bounds, 10, 0)];
}

@end


text:
'use strict';

var DataSet = require('./index.js');

var test = require('tape');
var document = require('global/document');

test('can fetch records out of DS', function t(assert) {
    var elem = document.body;
    var ds = DataSet(elem);

    ds.foo = 'bar';

    var ds2 = DataSet(elem);

    assert.equal(ds2.foo, 'bar');

    assert.end();
});

test('can fetch pre existing records out of DOM', function t(assert) {
    var elem = document.createElement('div');
    elem.setAttribute('data-foo', 'bar');
    elem.setAttribute('data-baz', 'oh yeah');

    var ds = DataSet(elem);
    assert.equal(ds.foo, 'bar');
    assert.deepEqual(ds.baz, 'oh yeah');

    assert.end();
});

test('setting dash names', function t(assert) {
    var elem = document.createElement('div');
    DataSet(elem)['foo-bar'] = 'baz';
    var elem2 = document.createElement('div');
    elem2.setAttribute('data-foo-bar', 'baz');

    var ds = DataSet(elem);
    var ds2 = DataSet(elem2);

    assert.equal(ds['foo-bar'], 'baz');
    assert.equal(ds2['foo-bar'], 'baz');

    assert.end();
});


text:
module Stargate
  module Request
    class MetaRequest < BasicRequest
      def initialize
        super("")
      end

      def list_tables
        @path << "/"
      end

      def create_table
        @path << "/tables"
      end

      def version
        @path << "/version"
      end

      def cluster_version
        @path << "/version/cluster"
      end
    end
  end
end


text:
<!doctype html>

<title>cordova errgen tester</title>

cordova errgen tester


text:
for run in {1..100}
do
python generator.py >input.txt
python naive.py <input.txt >naive_output.txt
python my.py <input.txt >output.txt
python comparer.py
done


text:
Widgets

          <button class="btn btn-sm btn-info" ng-click="createWidget(newWidget)">+ Create</button>

              ID
              Name
              Color
              Price
              Melts?
              Inventory
              Edit?

              {{widget.id}}
              {{widget.name}}
              {{widget.color}}
              {{widget.price}}
              {{widget.melts}}
              {{widget.inventory}}
              <button class="btn btn-sm btn-info" ng-click="showEditWidget(widget)">Edit</button>

Create/Edit Template

        <form class="form-horizontal">

          <legend>Create Widget</legend>

          Name
            <input id="widget-name" name="widget-name" type="text" placeholder="foo-bar" class="input-medium" ng-model="newWidget.name">

            Price
              $
              <input id="widget-price" name="widget-price" class="input-medium" placeholder="0.00" type="text" ng-model="newWidget.price">

          Color
            <select id="widget-color" name="widget-color" class="input-large" ng-model="newWidget.color">
              <option>red</option>
              <option>purple</option>
              <option>black</option>
              <option>green</option>
              <option>magenta</option>
              <option>white</option>
              <option>depends on the viewing angle</option>
            </select>

            Melts
            <input type="checkbox" name="widget-properties" id="widget-properties-0" value="melts" ng-model="newWidget.melts">

            Inventory
            <input id="widget-count" name="widget-count" type="text" placeholder="#?" class="input-small" ng-model="newWidget.inventory">

        </form>


text:
@interface InputingValidator : NSObject

+ (BOOL)validatePhone:(UITextField *)inputField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;

@end


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>John 5 (WEB)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />

World English BibleJohn 5<
=
>

5

1 Whoever believes that Jesus is the Christ has been born of God. Whoever loves the Father also loves the child who is born of him.
2 By this we know that we love the children of God, when we love God and keep his commandments.
3 For this is loving God, that we keep his commandments. His commandments are not grievous.
4 For whatever is born of God overcomes the world. This is the victory that has overcome the world: your faith.
5 Who is he who overcomes the world, but he who believes that Jesus is the Son of God?
6 This is he who came by water and blood, Jesus Christ; not with the water only, but with the water and the blood. It is the Spirit who testifies, because the Spirit is the truth.
7 For there are three who testify+:
8 the Spirit, the water, and the blood; and the three agree as one.
9 If we receive the witness of men, the witness of God is greater; for this is God's testimony which he has testified concerning his Son.
10 He who believes in the Son of God has the testimony in himself. He who doesn't believe God has made him a liar, because he has not believed in the testimony that God has given concerning his Son.
11 The testimony is this, that God gave to us eternal life, and this life is in his Son.
12 He who has the Son has the life. He who doesn't have God's Son doesn't have the life.
13 These things I have written to you who believe in the name of the Son of God, that you may know that you have eternal life, and that you may continue to believe in the name of the Son of God.

14 This is the boldness which we have toward him, that, if we ask anything according to his will, he listens to us.
15 And if we know that he listens to us, whatever we ask, we know that we have the petitions which we have asked of him.

16 If anyone sees his brother sinning a sin not leading to death, he shall ask, and God will give him life for those who sin not leading to death. There is a sin leading to death. I don't say that he should make a request concerning this.
17 All unrighteousness is sin, and there is a sin not leading to death.
18 We know that whoever is born of God doesn't sin, but he who was born of God keeps himself, and the evil one doesn't touch him.
19 We know that we are of God, and the whole world lies in the power of the evil one.
20 We know that the Son of God has come, and has given us an understanding, that we know him who is true, and we are in him who is true, in his Son Jesus Christ. This is the true God, and eternal life.

21 Little children, keep yourselves from idols.

+undefined

<
=
>


text:
@interface PodsDummy_HUPhotoPicker : NSObject
@end
@implementation PodsDummy_HUPhotoPicker
@end


text:
{% extends "base.html" %}
{% load i18n %}

{% block title %}{% trans "Participate" %}{% endblock %}

{% block content %}

{{ heading }}

{% trans "If the administrator approves your request, you will be notified by email" %}

{% trans "You can go back to home or back to your profile" %}

{% endblock %}


text:
package com.linkedin.pinot.core.realtime.impl.dictionary;

import java.util.Arrays;
import javax.annotation.Nonnull;

public class DoubleOnHeapMutableDictionary extends BaseOnHeapMutableDictionary {
  private double _min = Double.MAX_VALUE;
  private double _max = Double.MIN_VALUE;

  @Override
  public int indexOf(Object rawValue) {
    if (rawValue instanceof String) {
      return getDictId(Double.valueOf((String) rawValue));
    } else {
      return getDictId(rawValue);
    }
  }

  @Override
  public void index(@Nonnull Object rawValue) {
    if (rawValue instanceof Double) {
      // Single value
      indexValue(rawValue);
      updateMinMax((Double) rawValue);
    } else {
      // Multi value
      Object[] values = (Object[]) rawValue;
      for (Object value : values) {
        indexValue(value);
        updateMinMax((Double) value);
      }
    }
  }

  @SuppressWarnings("Duplicates")
  @Override
  public boolean inRange(@Nonnull String lower, @Nonnull String upper, int dictIdToCompare, boolean includeLower,
      boolean includeUpper) {
    double lowerDouble = Double.parseDouble(lower);
    double upperDouble = Double.parseDouble(upper);
    double valueToCompare = (Double) get(dictIdToCompare);

    if (includeLower) {
      if (valueToCompare < lowerDouble) {
        return false;
      }
    } else {
      if (valueToCompare <= lowerDouble) {
        return false;
      }
    }

    if (includeUpper) {
      if (valueToCompare > upperDouble) {
        return false;
      }
    } else {
      if (valueToCompare >= upperDouble) {
        return false;
      }
    }

    return true;
  }

  @Nonnull
  @Override
  public Double getMinVal() {
    return _min;
  }

  @Nonnull
  @Override
  public Double getMaxVal() {
    return _max;
  }

  @Nonnull
  @Override
  public double[] getSortedValues() {
    int numValues = length();
    double[] sortedValues = new double[numValues];

    for (int i = 0; i < numValues; i++) {
      sortedValues[i] = (Double) get(i);
    }

    Arrays.sort(sortedValues);
    return sortedValues;
  }

  @Override
  public int getIntValue(int dictId) {
    return ((Double) get(dictId)).intValue();
  }

  @Override
  public long getLongValue(int dictId) {
    return ((Double) get(dictId)).longValue();
  }

  @Override
  public float getFloatValue(int dictId) {
    return ((Double) get(dictId)).floatValue();
  }

  @Override
  public double getDoubleValue(int dictId) {
    return (Double) get(dictId);
  }

  private void updateMinMax(double value) {
    if (value < _min) {
      _min = value;
    }
    if (value > _max) {
      _max = value;
    }
  }
}


text:
// -*-  Mode:ObjC; c-basic-offset:4; tab-width:8; indent-tabs-mode:nil -*-

#import "KeywordViewController2.h"
#import "SearchController.h"

@interface KeywordViewController2()
{
    SearchController *mSearchController;
}
@end

@implementation KeywordViewController2

@synthesize selectedShelf, initialText;

+ (KeywordViewController2 *)keywordViewController:(NSString*)title
{
    KeywordViewController2 *vc = [[KeywordViewController2 alloc]
                                     initWithNibName:@"KeywordView2"
                                     bundle:nil];
    vc.title = title;

    return vc;
}

- (void)setInitialText:(NSString*)s
{
	if (s != initialText) {
		initialText = s;
	}
	textField.text = initialText;
}

- (instancetype)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
    self = [super initWithNibName:nibName bundle:bundle];
    if (self) {
        webApiFactory = [[WebApiFactory alloc] init];

        if (IS_IPAD) {
            textField = [[UITextField alloc] initWithFrame:CGRectMake(160, 10, 500, 28)];
        } else {
            textField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 190, 28)];
        }
        //textField.backgroundColor = [UIColor grayColor];
        textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        textField.font = [UIFont systemFontOfSize: 14.0];
        textField.textColor = [UIColor blackColor];
        textField.backgroundColor = [UIColor clearColor];
        textField.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;

        textField.placeholder = self.title;
        textField.clearButtonMode = UITextFieldViewModeAlways;

		textField.returnKeyType = UIReturnKeySearch;
		textField.delegate = self;

        [self _setupCategories];

        // key type
        searchKeyType = SearchKeyTitle;
        searchKeyTypes = @[@"Title", @"Author", @"Artist", @"All"];
    }
    return self;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[self doneAction:nil];
	return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
												 initWithTitle:@"Search" style:UIBarButtonItemStyleDone
											     target:self action:@selector(doneAction:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                                 initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                 target:self
                                                 action:@selector(cancelAction:)];
}

- (void)_setupCategories
{
    WebApi *api = [webApiFactory allocWebApi];

    searchIndices = [api categoryStrings];

    searchSelectedIndex = [api defaultCategoryIndex];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated
{
    [textField becomeFirstResponder];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (IBAction)doneAction:(id)sender
{
    // 検索
    if (textField.text.length < 2) {
        [Common showAlertDialog:@"Error" message:@"Title is too short"];
        return;
    }

    [textField resignFirstResponder];

    mSearchController = [SearchController newController];
    mSearchController.delegate = self;
    mSearchController.viewController = self;
    mSearchController.selectedShelf = selectedShelf;

    WebApi *api = [webApiFactory allocWebApi];
    NSString *searchIndex = searchIndices[searchSelectedIndex];

    [mSearchController search:api key:textField.text searchKeyType:searchKeyType index:searchIndex];

}

- (void)searchControllerFinish:(SearchController*)controller result:(BOOL)result
{
    if (result) {
        //textField.text = nil;
    }
    mSearchController = nil;
}

- (IBAction)cancelAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

/////

// セクション数
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 1;
}

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSString *text;

    switch (indexPath.row) {
    case 0: // text view
        cell = [self containerCellWithTitle:@"Keyword" view:textField];
        break;

    case 1: // search key types
        text = searchKeyTypes[searchKeyType - 1];
        cell = [self containerCellWithTitle:@"Type" text:text];
        break;

    case 2: // category (index)
        text = searchIndices[searchSelectedIndex];
        cell = [self containerCellWithTitle:@"Category" text:text];
        break;

    case 3: // service id
        text = [webApiFactory serviceIdString];
        cell = [self containerCellWithTitle:@"Service" text:text];
        break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GenSelectListViewController *vc = nil;
    [tv deselectRowAtIndexPath:indexPath animated:NO];

    switch (indexPath.row) {
    case 1: // key type
        vc = [GenSelectListViewController
                 genSelectListViewController:self
                 array:searchKeyTypes
                 title:NSLocalizedString(@"Type", @"")];
        vc.selectedIndex = searchKeyType - 1;
        vc.identifier = 0;
        break;

    case 2: // category (index)
        vc = [GenSelectListViewController
                 genSelectListViewController:self
                 array:searchIndices
                 title:NSLocalizedString(@"Category", @"")];
        vc.selectedIndex = searchSelectedIndex;
        vc.identifier = 1;
        break;

    case 3: // serviceId
        vc = [GenSelectListViewController
                 genSelectListViewController:self
                 array:[webApiFactory serviceIdStrings]
                 title:NSLocalizedString(@"Select locale", @"")];
        vc.selectedIndex = webApiFactory.serviceId;
        vc.identifier = 2;
        break;
    }

    if (vc) {
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)genSelectListViewChanged:(GenSelectListViewController*)vc
{
    switch (vc.identifier) {
    case 0: // search key type
        searchKeyType = (SearchKeyType)(vc.selectedIndex + 1);
        break;

    case 1: // serchIndex
        searchSelectedIndex = vc.selectedIndex;
        break;

    case 2: // serviceId
        webApiFactory.serviceId = vc.selectedIndex;
        [webApiFactory saveDefaults];
        [self _setupCategories];
        break;
    }
    [tableView reloadData];
}

- (UITableViewCell *)containerCellWithTitle:(NSString*)title view:(UIView *)view
{
    KeywordViewCell *cell = [KeywordViewCell getCell:title tableView:tableView identifier:title];
    [cell attachView:view];
    return cell;
}

- (UITableViewCell *)containerCellWithTitle:(NSString*)title text:(NSString *)text
{
    KeywordViewCell *cell = [KeywordViewCell getCell:title tableView:tableView identifier:title];

    UILabel *value;
    if (IS_IPAD) {
        value = [[UILabel alloc] initWithFrame:CGRectMake(160, 6, 500, 32)];
    } else {
        value = [[UILabel alloc] initWithFrame:CGRectMake(110, 6, 190, 32)];
    }
    value.text = NSLocalizedString(text, @"");
    value.font = [UIFont systemFontOfSize: 14.0];
    value.textColor = [UIColor blackColor];
    value.backgroundColor = [UIColor clearColor];
    value.autoresizingMask = 0;//UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [cell attachView:value];
    return cell;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return [Common isSupportedOrientation:interfaceOrientation];
}

@end

////
// KeywordViewCell

@implementation KeywordViewCell

+ (KeywordViewCell *)getCell:(NSString *)title tableView:(UITableView*)tableView identifier:(NSString *)identifier
{
    KeywordViewCell *cell = (KeywordViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[KeywordViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }

    UILabel *tlabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 6, 90, 32)];
    tlabel.text = NSLocalizedString(title, @"");
    tlabel.font = [UIFont systemFontOfSize: 14.0];
    tlabel.textColor = [UIColor blueColor];
    tlabel.backgroundColor = [UIColor clearColor];
    tlabel.textAlignment = NSTextAlignmentLeft;
    tlabel.autoresizingMask = 0;//UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [cell.contentView addSubview:tlabel];

    return cell;
}

- (void)attachView:(UIView *)view
{
    [attachedView removeFromSuperview];

    attachedView = view;
    [self addSubview:view];
}

@end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('stories', '0013_auto_20160227_2100'),
    ]

    operations = [
        migrations.RunSQL('ALTER TABLE stories_questiongroup ADD COLUMN name varchar(100)')
    ]


text:
<?php
// create custom plugin settings menu
add_action('admin_menu', 'emt_create_menu');

function emt_create_menu()
{

    //create new top-level menu
    add_options_page('External Media Tab Settings', 'External Media', 'administrator', 'externalmediatab_settings_page', 'emt_settings_page');

    //call register settings function
    add_action('admin_init', 'register_mysettings');
}

function register_mysettings()
{
    //register our settings
    register_setting('emt-settings-group', 'resource_path');
}

function emt_settings_page()
{
    ?>

External Resource Linker

    <form method="post" action="options.php">
        <?php settings_fields('emt-settings-group'); ?>
        <?php do_settings_sections('emt-settings-group'); ?>

            External Assets Path
            http://<input style="width: 300px;" type="text" name="resource_path" value="<?php echo esc_attr(get_option('resource_path')); ?>" />

        <?php submit_button(); ?>

    </form>

    <?php
}


text:
package com.bretpatterson.schemagen.graphql.impl.common;

import com.bretpatterson.schemagen.graphql.ITypeFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.base.Throwables;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * A very simple object mapper that uses Jackson JSon serialization
 */
public class JacksonTypeFactory implements ITypeFactory {
	ObjectMapper objectMapper;

	public JacksonTypeFactory(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	@Override
	public Object convertToType(Type type, Object arg) {
		try {
			return objectMapper.readValue(objectMapper.writeValueAsString(arg), TypeFactory.defaultInstance().constructType(type));
		} catch(IOException ex) {
			return Throwables.propagate(ex);
		}

	}
}


text:
import { Component } from '@angular/core';
import {ROUTER_DIRECTIVES, RouteConfig, CanActivate} from '@angular/router-deprecated';

import {GamesService} from '../../services/api/games.service';
import {SocketApiService} from '../../services/socketApi.service';
import {GamesList} from './gamesList.component';
import {GameDetail} from './gameDetail.component';

@Component({
    providers: [GamesService, SocketApiService],
    template: `
        <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES]
})
@CanActivate((next, prev) => {
    // TODO: Implement when we have DI here to get hold of our authenticationService
    // https://github.com/angular/angular/issues/4112
    // For now it is not much of a problem since we will be hiding the link to this component
    // and the back end won't serve any content anyway
    return true;
})
@RouteConfig([
    { path: '/', name: 'GamesList', component: GamesList, useAsDefault: true },
    { path: '/:id', name: 'GameDetail', component: GameDetail }
])
export class Games {}


text:
<!doctype html>
<html>
<meta charset="utf-8" />
<title>Cuttlefish, The Card Game</title>
<style>
html {
  height: 100%;
  background: rgb(0, 44, 68) url(cuttlefish.svg) center center no-repeat;
}
</style>
<body>
</body>
</html>


text:
(function () {
    'use strict';
    define(['app'], function (app) {
        app.controller('newsCtrl', newsCtrl);

        newsCtrl.$inject = ['$routeParams'];

        function newsCtrl($routeParams) {
            /* js hint valid this: true*/
            var vm = this;
            vm.stateId = $routeParams;

        }
    });
}());


text:
@interface XCTRerunPolicy : NSObject <NSSecureCoding>
{
    long long _rerunMode;
    long long _maximumIterations;
}

+ (_Bool)supportsSecureCoding;
+ (long long)rerunModeFromString:(id)arg1;
+ (id)stringFromRerunMode:(long long)arg1;
+ (id)defaultRerunPolicy;
@property(readonly) long long maximumIterations; // @synthesize maximumIterations=_maximumIterations;
@property(readonly) long long rerunMode; // @synthesize rerunMode=_rerunMode;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (_Bool)isDefaultPolicy;
- (unsigned long long)hash;
- (_Bool)isEqual:(id)arg1;
- (id)dictionaryRepresentation;
- (id)description;
- (id)initWithDictionary:(id)arg1;
- (id)initWithFixedIterations:(long long)arg1;
- (id)initWithMaximumIterationsUntilSuccess:(long long)arg1;
- (id)initWithMaximumIterationsUntilFailure:(long long)arg1;
- (id)initWithRerunMode:(long long)arg1 maximumIterations:(long long)arg2;

@end


text:
package org.guvnor.common.services.builder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.guvnor.common.services.project.builder.model.BuildResults;
import org.guvnor.common.services.project.builder.model.IncrementalBuildResults;
import org.guvnor.common.services.project.builder.service.BuildService;
import org.guvnor.common.services.project.model.Package;
import org.guvnor.common.services.project.model.Project;
import org.guvnor.common.services.project.service.ProjectService;
import org.guvnor.common.services.shared.config.AppConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.vfs.Path;
import org.uberfire.commons.services.cdi.ApplicationStarted;
import org.uberfire.workbench.events.ResourceChange;

/**
 * Listener for changes to project resources to handle incremental builds
 */
@ApplicationScoped
public class ResourceChangeIncrementalBuilder {

    private static final String INCREMENTAL_BUILD_PROPERTY_NAME = "build.enable-incremental";

    protected static final Logger logger = LoggerFactory.getLogger( ResourceChangeIncrementalBuilder.class );

    @Inject
    protected ProjectService<? extends Project> projectService;

    @Inject
    private AppConfigService appConfigService;

    @Inject
    private IncrementalBuilderExecutorManagerFactory executorManagerProducer;

    private IncrementalBuilderExecutorManager executorManager = null;

    protected boolean isIncrementalEnabled = false;

    @PostConstruct
    private void setup() {
        isIncrementalEnabled = isIncrementalBuildEnabled();
    }

    public void configureOnEvent( @Observes ApplicationStarted applicationStartedEvent ) {
        isIncrementalEnabled = isIncrementalBuildEnabled();
        getExecutor();
    }

    private boolean isIncrementalBuildEnabled() {
        final String value = appConfigService.loadPreferences().get( INCREMENTAL_BUILD_PROPERTY_NAME );
        return Boolean.parseBoolean( value );
    }

    @PreDestroy
    private void destroyExecutorService() {
        if ( executorManager != null && !isEjb( executorManager, IncrementalBuilderExecutorManager.class ) ) {
            executorManager.shutdown();
        }
    }

    private boolean isEjb( Object o,
                           Class<?> expected ) {
        if ( o.getClass() != expected ) {
            return true;
        }

        return false;
    }

    private synchronized IncrementalBuilderExecutorManager getExecutor() {
        if ( executorManager == null ) {
            executorManager = executorManagerProducer.getExecutorManager();
        }
        return executorManager;
    }

    public void addResource( final Path resource ) {
        //Do nothing if incremental builds are disabled
        if ( !isIncrementalEnabled ) {
            return;
        }

        logger.info( "Incremental build request received for: " + resource.toURI() + " (added)." );

        //If resource is not within a Package it cannot be used for an incremental build
        final Package pkg = projectService.resolvePackage( resource );
        if ( pkg == null ) {
            return;
        }

        //Schedule an incremental build
        getExecutor().execute( new AsyncIncrementalBuilder() {

            @Override
            public void execute( final ProjectService projectService,
                                 final BuildService buildService,
                                 final Event<IncrementalBuildResults> incrementalBuildResultsEvent,
                                 final Event<BuildResults> buildResultsEvent ) {
                try {
                    logger.info( "Incremental build request being processed: " + resource.toURI() + " (added)." );
                    final Project project = projectService.resolveProject( resource );

                    //Fall back to a Full Build in lieu of an Incremental Build if the Project has not been previously built
                    if ( buildService.isBuilt( project ) ) {
                        final IncrementalBuildResults results = buildService.addPackageResource( resource );
                        incrementalBuildResultsEvent.fire( results );
                    } else {
                        final BuildResults results = buildService.build( project );
                        buildResultsEvent.fire( results );
                    }

                } catch ( Exception e ) {
                    logger.error( e.getMessage(),
                                  e );
                }
            }

            @Override
            public String getDescription() {
                return "Incremental Build [" + resource.toURI() + " (added)]";
            }
        } );
    }

    public void deleteResource( final Path resource ) {
        //Do nothing if incremental builds are disabled
        if ( !isIncrementalEnabled ) {
            return;
        }

        logger.info( "Incremental build request received for: " + resource.toURI() + " (deleted)." );

        //If resource is not within a Package it cannot be used for an incremental build
        final Package pkg = projectService.resolvePackage( resource );
        if ( pkg == null ) {
            return;
        }

        //Schedule an incremental build
        getExecutor().execute( new AsyncIncrementalBuilder() {

            @Override
            public void execute( final ProjectService projectService,
                                 final BuildService buildService,
                                 final Event<IncrementalBuildResults> incrementalBuildResultsEvent,
                                 final Event<BuildResults> buildResultsEvent ) {
                try {
                    logger.info( "Incremental build request being processed: " + resource.toURI() + " (deleted)." );
                    final Project project = projectService.resolveProject( resource );

                    //Fall back to a Full Build in lieu of an Incremental Build if the Project has not been previously built
                    if ( buildService.isBuilt( project ) ) {
                        final IncrementalBuildResults results = buildService.deletePackageResource( resource );
                        incrementalBuildResultsEvent.fire( results );
                    } else {
                        final BuildResults results = buildService.build( project );
                        buildResultsEvent.fire( results );
                    }

                } catch ( Exception e ) {
                    logger.error( e.getMessage(),
                                  e );
                }
            }

            @Override
            public String getDescription() {
                return "Incremental Build [" + resource.toURI() + " (deleted)]";
            }
        } );
    }

    public void updateResource( final Path resource ) {
        //Do nothing if incremental builds are disabled
        if ( !isIncrementalEnabled ) {
            return;
        }

        logger.info( "Incremental build request received for: " + resource.toURI() + " (updated)." );

        //The pom.xml cannot be processed incrementally
        if ( isProjectResourceUpdateNeeded( resource ) ) {
            scheduleProjectResourceUpdate( resource );
        } else {
            //If resource is not within a Package it cannot be used for an incremental build
            final Package pkg = projectService.resolvePackage( resource );
            if ( pkg == null ) {
                return;
            }
            schedulePackageResourceUpdate( resource );
        }
    }

    protected boolean isProjectResourceUpdateNeeded( Path resource ) {
        return projectService.isPom( resource );
    }

    //Schedule a re-build of a Project (changes to pom.xml or kmodule.xml require a full build)
    protected void scheduleProjectResourceUpdate( final Path resource ) {
        final Project project = projectService.resolveProject( resource );
        getExecutor().execute( new AsyncIncrementalBuilder() {

            @Override
            public void execute( final ProjectService projectService,
                                 final BuildService buildService,
                                 final Event<IncrementalBuildResults> incrementalBuildResultsEvent,
                                 final Event<BuildResults> buildResultsEvent ) {
                try {
                    logger.info( "Incremental build request being processed: " + project.getRootPath() + " (updated)." );
                    final BuildResults results = buildService.build( project );
                    buildResultsEvent.fire( results );

                } catch ( Exception e ) {
                    logger.error( e.getMessage(),
                                  e );
                }
            }

            @Override
            public String getDescription() {
                return "Incremental Build [" + resource.toURI() + " (updated)]";
            }
        } );
    }

    //Schedule an incremental build for a package resource
    protected void schedulePackageResourceUpdate( final Path resource ) {
        getExecutor().execute( new AsyncIncrementalBuilder() {

            @Override
            public void execute( final ProjectService projectService,
                                 final BuildService buildService,
                                 final Event<IncrementalBuildResults> incrementalBuildResultsEvent,
                                 final Event<BuildResults> buildResultsEvent ) {
                try {
                    logger.info( "Incremental build request being processed: " + resource.toURI() + " (updated)." );
                    final Project project = projectService.resolveProject( resource );

                    //Fall back to a Full Build in lieu of an Incremental Build if the Project has not been previously built
                    if ( buildService.isBuilt( project ) ) {
                        final IncrementalBuildResults results = buildService.updatePackageResource( resource );
                        incrementalBuildResultsEvent.fire( results );
                    } else {
                        final BuildResults results = buildService.build( project );
                        buildResultsEvent.fire( results );
                    }

                } catch ( Exception e ) {
                    logger.error( e.getMessage(),
                                  e );
                }
            }

            @Override
            public String getDescription() {
                return "Incremental Build [" + resource.toURI() + " (updated)]";
            }
        } );
    }

    public void batchResourceChanges( final Map<Path, Collection<ResourceChange>> batch ) {
        //Do nothing if incremental builds are disabled
        if ( !isIncrementalEnabled ) {
            return;
        }

        logger.info( "Batch incremental build request received." );

        //Block changes together with their respective project as Builder operates at the Project level
        final Map<Project, Map<Path, Collection<ResourceChange>>> projectBatchChanges = new HashMap<Project, Map<Path, Collection<ResourceChange>>>();

        for ( Map.Entry<Path, Collection<ResourceChange>> pathCollectionEntry : batch.entrySet() ) {
            for ( final ResourceChange change : pathCollectionEntry.getValue() ) {
                final Path resource = pathCollectionEntry.getKey();

                //If resource is not within a Package it cannot be used for an incremental build
                final Project project = projectService.resolveProject( resource );
                final Package pkg = projectService.resolvePackage( resource );
                if ( project != null && pkg != null ) {
                    if ( !projectBatchChanges.containsKey( project ) ) {
                        projectBatchChanges.put( project,
                                                 new HashMap<Path, Collection<ResourceChange>>() );
                    }
                    final Map<Path, Collection<ResourceChange>> projectChanges = projectBatchChanges.get( project );
                    if ( !projectChanges.containsKey( pathCollectionEntry.getKey() ) ) {
                        projectChanges.put( pathCollectionEntry.getKey(), new ArrayList<ResourceChange>() );
                    }
                    projectChanges.get( pathCollectionEntry.getKey() ).add( change );
                    logger.info( "- Batch content: " + pathCollectionEntry.getKey().toURI() + " (" + change.getType().toString() + ")." );
                }
            }
        }

        //Schedule an incremental build for each Project
        for ( final Map.Entry<Project, Map<Path, Collection<ResourceChange>>> e : projectBatchChanges.entrySet() ) {
            getExecutor().execute( new AsyncIncrementalBuilder() {

                @Override
                public void execute( final ProjectService projectService,
                                     final BuildService buildService,
                                     final Event<IncrementalBuildResults> incrementalBuildResultsEvent,
                                     final Event<BuildResults> buildResultsEvent ) {
                    try {
                        logger.info( "Batch incremental build request being processed." );
                        final Project project = e.getKey();
                        final Map<Path, Collection<ResourceChange>> changes = e.getValue();

                        //Fall back to a Full Build in lieu of an Incremental Build if the Project has not been previously built
                        if ( buildService.isBuilt( project ) ) {
                            final IncrementalBuildResults results = buildService.applyBatchResourceChanges( project,
                                                                                changes );
                            incrementalBuildResultsEvent.fire( results );
                        } else {
                            final BuildResults results = buildService.build( project );
                            buildResultsEvent.fire( results );
                        }

                    } catch ( Exception e ) {
                        logger.error( e.getMessage(),
                                      e );
                    }
                }

                @Override
                public String getDescription() {
                    return "Batch incremental build [" + e.getKey().getProjectName() + "]";
                }
            } );
        }
    }

}