text:
package org.eigenbase.sql.type;

import java.util.*;

import org.eigenbase.sql.*;
import org.eigenbase.util.*;

/**
 * This class allows multiple existing {@link SqlOperandTypeChecker} rules to be
 * combined into one rule. For example, allowing an operand to be either string
 * or numeric could be done by:
 *
 *

 *

 *
 * CompositeOperandsTypeChecking newCompositeRule =
 *  new CompositeOperandsTypeChecking(
 *    Composition.OR,
 *    new SqlOperandTypeChecker[]{stringRule, numericRule});
 *
 *

 *

 *
 * Similary a rule that would only allow a numeric literal can be done by:
 *
 *

 *

 *
 * CompositeOperandsTypeChecking newCompositeRule =
 *  new CompositeOperandsTypeChecking(
 *    Composition.AND,
 *    new SqlOperandTypeChecker[]{numericRule, literalRule});
 *
 *

 *

 *
 *
Finally, creating a signature expecting a string for the first operand and
 * a numeric for the second operand can be done by:
 *
 *

 *

 *
 * CompositeOperandsTypeChecking newCompositeRule =
 *  new CompositeOperandsTypeChecking(
 *    Composition.SEQUENCE,
 *    new SqlOperandTypeChecker[]{stringRule, numericRule});
 *
 *

 *

 *
 *
For SEQUENCE composition, the rules must be instances of
 * SqlSingleOperandTypeChecker, and signature generation is not supported. For
 * AND composition, only the first rule is used for signature generation.
 *
 * @author Wael Chatila
 * @version $Id$
 */
public class CompositeOperandTypeChecker
    implements SqlSingleOperandTypeChecker
{
    //~ Enums ------------------------------------------------------------------

    public enum Composition
    {
        AND, OR, SEQUENCE;
    }

    //~ Instance fields --------------------------------------------------------

    private final SqlOperandTypeChecker [] allowedRules;
    private final Composition composition;

    //~ Constructors -----------------------------------------------------------

    public CompositeOperandTypeChecker(
        Composition composition,
        SqlOperandTypeChecker ... allowedRules)
    {
        Util.pre(null != allowedRules, "null != allowedRules");
        Util.pre(allowedRules.length > 1, "Not a composite type");
        this.allowedRules = allowedRules;
        this.composition = composition;
    }

    //~ Methods ----------------------------------------------------------------

    public SqlOperandTypeChecker [] getRules()
    {
        return allowedRules;
    }

    public String getAllowedSignatures(SqlOperator op, String opName)
    {
        if (composition == Composition.SEQUENCE) {
            throw Util.needToImplement("must override getAllowedSignatures");
        }
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < allowedRules.length; i++) {
            SqlOperandTypeChecker rule = allowedRules[i];
            if (i > 0) {
                ret.append(SqlOperator.NL);
            }
            ret.append(rule.getAllowedSignatures(op, opName));
            if (composition == Composition.AND) {
                break;
            }
        }
        return ret.toString();
    }

    public SqlOperandCountRange getOperandCountRange()
    {
        if (composition == Composition.SEQUENCE) {
            return new SqlOperandCountRange(allowedRules.length);
        } else {
            // TODO jvs 2-June-2005:  technically, this is only correct
            // for OR, not AND; probably not a big deal
            Set<Integer> set = new TreeSet<Integer>();
            for (int i = 0; i < allowedRules.length; i++) {
                SqlOperandTypeChecker rule = allowedRules[i];
                SqlOperandCountRange range = rule.getOperandCountRange();
                if (range.isVariadic()) {
                    return SqlOperandCountRange.Variadic;
                }
                set.addAll(range.getAllowedList());
            }
            return new SqlOperandCountRange(new ArrayList<Integer>(set));
        }
    }

    public boolean checkSingleOperandType(
        SqlCallBinding callBinding,
        SqlNode node,
        int iFormalOperand,
        boolean throwOnFailure)
    {
        Util.pre(allowedRules.length >= 1, "allowedRules.length>=1");

        if (composition == Composition.SEQUENCE) {
            SqlSingleOperandTypeChecker singleRule =
                (SqlSingleOperandTypeChecker) allowedRules[iFormalOperand];
            return singleRule.checkSingleOperandType(
                callBinding,
                node,
                0,
                throwOnFailure);
        }

        int typeErrorCount = 0;

        boolean throwOnAndFailure =
            (composition == Composition.AND)
            && throwOnFailure;

        for (int i = 0; i < allowedRules.length; i++) {
            SqlSingleOperandTypeChecker rule =
                (SqlSingleOperandTypeChecker) allowedRules[i];
            if (!rule.checkSingleOperandType(
                    callBinding,
                    node,
                    iFormalOperand,
                    throwOnAndFailure))
            {
                typeErrorCount++;
            }
        }

        boolean ret = false;
        switch (composition) {
        case AND:
            ret = typeErrorCount == 0;
            break;
        case OR:
            ret = (typeErrorCount < allowedRules.length);
            break;
        default:

            //should never come here
            throw Util.unexpected(composition);
        }

        if (!ret && throwOnFailure) {
            //in the case of a composite OR we want to throw an error
            //describing in more detail what the problem was, hence doing
            //the loop again
            for (int i = 0; i < allowedRules.length; i++) {
                SqlSingleOperandTypeChecker rule =
                    (SqlSingleOperandTypeChecker) allowedRules[i];
                rule.checkSingleOperandType(
                    callBinding,
                    node,
                    iFormalOperand,
                    true);
            }

            //if no exception thrown, just throw a generic validation
            //signature error
            throw callBinding.newValidationSignatureError();
        }

        return ret;
    }

    public boolean checkOperandTypes(
        SqlCallBinding callBinding,
        boolean throwOnFailure)
    {
        int typeErrorCount = 0;

        for (int i = 0; i < allowedRules.length; i++) {
            SqlOperandTypeChecker rule = allowedRules[i];

            if (composition == Composition.SEQUENCE) {
                SqlSingleOperandTypeChecker singleRule =
                    (SqlSingleOperandTypeChecker) rule;
                if (i >= callBinding.getOperandCount()) {
                    break;
                }
                if (!singleRule.checkSingleOperandType(
                        callBinding,
                        callBinding.getCall().operands[i],
                        0,
                        false))
                {
                    typeErrorCount++;
                }
            } else {
                if (!rule.checkOperandTypes(callBinding, false)) {
                    typeErrorCount++;
                }
            }
        }

        boolean failed = true;
        switch (composition) {
        case AND:
        case SEQUENCE:
            failed = typeErrorCount > 0;
            break;
        case OR:
            failed = (typeErrorCount == allowedRules.length);
            break;
        }

        if (failed) {
            if (throwOnFailure) {
                //in the case of a composite OR we want to throw an error
                //describing in more detail what the problem was, hence doing
                //the loop again
                if (composition == Composition.OR) {
                    for (int i = 0; i < allowedRules.length; i++) {
                        allowedRules[i].checkOperandTypes(callBinding, true);
                    }
                }

                //if no exception thrown, just throw a generic validation
                //signature error
                throw callBinding.newValidationSignatureError();
            }
            return false;
        }
        return true;
    }
}

// End CompositeOperandTypeChecker.java


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using RotinaBot.Documents;
using RotinaBot.Domain;
using Takenet.MessagingHub.Client;
using Takenet.MessagingHub.Client.Extensions.Bucket;
using Takenet.MessagingHub.Client.Extensions.Delegation;
using Takenet.MessagingHub.Client.Extensions.Scheduler;
using Takenet.MessagingHub.Client.Host;
using Takenet.MessagingHub.Client.Sender;

namespace RotinaBot.Receivers
{
    public class FinishTaskCreation : BaseMessageReceiver
    {
        public FinishTaskCreation(
            IMessagingHubSender sender, IStateManager stateManager,
            Settings settings, RoutineRepository routineRepository, ReschedulerTask reschedulerTask)
            : base(sender, stateManager, settings, routineRepository, reschedulerTask)
        {
        }

        public override async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            await FinishTaskCreationAsync(message.From, cancellationToken);
            await InformTheTaskWasCreatedAsync(message.From, cancellationToken);
        }

        private async Task FinishTaskCreationAsync(Node owner, CancellationToken cancellationToken)
        {
            var routine = await GetRoutineAsync(owner, false, cancellationToken);
            var task = routine.Tasks.Last();
            task.IsActive = true;
            await SetRoutineAsync(routine, cancellationToken);

            ConfigureSchedule(new Tuple<Identity, RoutineTaskTimeValue>(routine.Owner, task.Time.Value), cancellationToken);
        }

        private async Task InformTheTaskWasCreatedAsync(Node owner, CancellationToken cancellationToken)
        {
            await Sender.SendMessageAsync(Settings.Phraseology.TheTaskWasRegistered, owner, cancellationToken);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package lambdasinaction.chap5;

public class Transaction{

	private Trader trader;
	private int year;
	private int value;

	public Transaction(Trader trader, int year, int value)
	{
		this.trader = trader;
		this.year = year;
		this.value = value;
	}

	public Trader getTrader(){
		return this.trader;
	}

	public int getYear(){
		return this.year;
	}

	public int getValue(){
		return this.value;
	}

	public String toString(){
	    return "{" + this.trader + ", " +
	           "year: "+this.year+", " +
	           "value:" + this.value +"}";
	}
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Deleting field 'TaskHistory.db_id'
        db.delete_column(u'notification_taskhistory', 'db_id_id')

    def backwards(self, orm):
        # Adding field 'TaskHistory.db_id'
        db.add_column(u'notification_taskhistory', 'db_id',
                      self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'database', null=True, to=orm['logical.Database'], on_delete=models.SET_NULL, blank=True),
                      keep_default=False)

    models = {
        u'notification.taskhistory': {
            'Meta': {'object_name': 'TaskHistory'},
            'arguments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'context': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'details': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'ended_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'task_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'task_name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'task_status': ('django.db.models.fields.CharField', [], {'default': "u'PENDING'", 'max_length': '100', 'db_index': 'True'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'user': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['notification']


text:
package com.caffetools.vizualization;

import com.caffetools.javacc.Token;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Caffe block
 */
public class CaffeBlock {
    public static final Log log = LogFactory.getLog(CaffeBlock.class);

    /** Label data field */
    public static final String NAME = "name";
    public static final String TYPE = "type";
    public static final String TOP = "top";
    public static final String BOTTOM = "bottom";

    private String blockKind;
    private Multimap<String, Object> properties ;

    public CaffeBlock(String kind) {
        this.blockKind = kind;
        this.properties = ArrayListMultimap.create();
    }

    public String getBlockKind() {
        return blockKind;
    }

    public void setBlockKind(String blockKind) {
        this.blockKind = blockKind;
    }

    public Multimap<String, Object> getProperties() {
        return properties;
    }

    public void add(Token t1, Token t2) {
        add(t1.image, t2.image);
    }

    public void add(String t1, Object t2){
        properties.put(unquote(t1), unquote(t2));
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder();
        b.append(blockKind);
        toStringBuilder(b, 0);
        return b.toString();
    }

    public void toStringBuilder(StringBuilder b, int pad) {
        b.append(" {\n");
        properties.entries().stream()
            .forEach(entry -> {
                b.append(StringUtils.repeat("\t", pad)).append(entry.getKey());
                if (entry.getValue() instanceof String) {
                    b.append("\t: ").append(entry.getValue()).append("\n");
                } else if (entry.getValue() instanceof CaffeBlock) {
                    ((CaffeBlock) entry.getValue()).toStringBuilder(b, pad + 1);
                }
            });

        b.append(StringUtils.repeat("\t", pad)).append("}\n");

    }

    public String toHtml(){
        StringBuilder b = new StringBuilder("
");
        b.append(blockKind).append("");
        toHtmlStringBuilder(b);
        return b.toString();
    }

    public void toHtmlStringBuilder(StringBuilder b) {
        b.append(" {\n
");
        properties.entries().stream()
            .forEach(entry ->{
                b.append("
").append("").append(entry.getKey()).append("");
                if(entry.getValue() instanceof String){
                    b.append(" : ").append(entry.getValue()).append("
\n");
                }
                else if(entry.getValue() instanceof CaffeBlock){
                    ((CaffeBlock)entry.getValue()).toHtmlStringBuilder(b);
                    b.append("
");
                }
            });

        b.append("
}\n");

    }

    public Collection<String> getPropertyStrings(String s) {
        List<String> l = new ArrayList<>();
        properties.get(s).stream().forEach(entry ->  {
            l.add((String) entry);
        });
        if(l.size()==0){
            log.info("Property '" + s + "' is null.");
            return Collections.emptyList();
        }
        return l;
    }

    public Collection<Object> getPropertyValues(String s) {
        return properties.get(s);
    }

    public String getName(){
        return getFirstValue(NAME);
    }

    public String getType(){
        return getFirstValue(TYPE);
    }

    public String getFirstValue(String name){
        final Collection<Object> names = properties.get(name);
        if(names.size()>0)
            return (String) names.iterator().next();
        else
            return null;
    }

    public static <T> T unquote(T s){
        if(s instanceof String) {
            String trim = ((String)s).trim();
            if (trim.charAt(0) == '"')
                trim = trim.substring(1);
            if (trim.charAt(trim.length() - 1) == '"')
                trim = trim.substring(0, trim.length() - 1);
            return (T)trim;
        }
        else
            return s;
    }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

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

Bootswap

Themes

Bootswatch Themes

Default

About

Download

Blog

Default

Official Bootstrap Theme

    Default
    Primary
    Success
    Info
    Warning
    Danger


text:
// ========================================================================
// $Id: InclusiveByteRange.java,v 1.11 2005/08/13 00:01:24 gregwilkins Exp $
// Copyright 2002-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================

package org.openqa.jetty.http;

import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.openqa.jetty.log.LogFactory;
import org.openqa.jetty.util.LazyList;
import org.openqa.jetty.util.LogSupport;

/* ------------------------------------------------------------ */
/** Byte range inclusive of end points.
 * <PRE>
 *
 *   parses the following types of byte ranges:
 *
 *       bytes=100-499
 *       bytes=-300
 *       bytes=100-
 *       bytes=1-2,2-3,6-,-2
 *
 *   given an entity length, converts range to string
 *
 *       bytes 100-499/500
 *
 * </PRE>
 *
 * Based on RFC2616 3.12, 14.16, 14.35.1, 14.35.2
 * @version $version$
 * @author Helmut Hissen
 */
public class InclusiveByteRange {
    private static Log log = LogFactory.getLog(InclusiveByteRange.class);

    long first = 0;
    long last  = 0;

    public InclusiveByteRange(long first, long last)
    {
        this.first = first;
        this.last = last;
    }

    public long getFirst()
    {
        return first;
    }

    public long getLast()
    {
        return last;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param headers Enumeration of Range header fields.
     * @param size Size of the resource.
     * @return LazyList of satisfiable ranges
     */
    public static List satisfiableRanges(Enumeration headers,long size)
    {
        Object satRanges=null;

        // walk through all Range headers
    headers:
        while (headers.hasMoreElements())
        {
            String header = (String) headers.nextElement();
            StringTokenizer tok = new StringTokenizer(header,"=,",false);
            String t=null;
            try
            {
                // read all byte ranges for this header
                while (tok.hasMoreTokens())
                {
                    t=tok.nextToken().trim();

                    long first = -1;
                    long last  = -1;
                    int d=t.indexOf('-');
                    if (d<0 || t.indexOf("-",d+1)>=0)
                    {
                        if ("bytes".equals(t))
                            continue;
                        log.warn("Bad range format: "+t);
                        continue headers;
                    }
                    else if (d==0)
                    {
                        if (d+1<t.length())
                            last = Long.parseLong(t.substring(d+1).trim());
                        else
                        {
                            log.warn("Bad range format: "+t);
                            continue headers;
                        }
                    }
                    else if (d+1<t.length())
                    {
                        first = Long.parseLong(t.substring(0,d).trim());
                        last = Long.parseLong(t.substring(d+1).trim());
                    }
                    else
                        first = Long.parseLong(t.substring(0,d).trim());

                    if (first == -1 && last == -1)
                        continue headers;

                    if (first != -1 && last != -1 && (first > last))
                        continue headers;

                    if (first<size)
                    {
                        InclusiveByteRange range = new
                            InclusiveByteRange(first, last);
                        satRanges=LazyList.add(satRanges,range);
                    }
                }
            }
            catch(Exception e)
            {
                log.warn("Bad range format: "+t);
                LogSupport.ignore(log,e);
            }
        }
        return LazyList.getList(satRanges,true);
    }

    /* ------------------------------------------------------------ */
    public long getFirst(long size)
    {
        if (first<0)
        {
            long tf=size-last;
            if (tf<0)
                tf=0;
            return tf;
        }
        return first;
    }

    /* ------------------------------------------------------------ */
    public long getLast(long size)
    {
        if (first<0)
            return size-1;

        if (last<0 ||last>=size)
            return size-1;
        return last;
    }

    /* ------------------------------------------------------------ */
    public long getSize(long size)
    {
        return getLast(size)-getFirst(size)+1;
    }

    /* ------------------------------------------------------------ */
    public String toHeaderRangeString(long size)
    {
        StringBuffer sb = new StringBuffer(40);
        sb.append("bytes ");
        sb.append(getFirst(size));
        sb.append('-');
        sb.append(getLast(size));
        sb.append("/");
        sb.append(size);
        return sb.toString();
    }

    /* ------------------------------------------------------------ */
    public static String to416HeaderRangeString(long size)
    {
        StringBuffer sb = new StringBuffer(40);
        sb.append("bytes */");
        sb.append(size);
        return sb.toString();
    }

    /* ------------------------------------------------------------ */
    public String toString()
    {
        StringBuffer sb = new StringBuffer(60);
        sb.append(Long.toString(first));
        sb.append(":");
        sb.append(Long.toString(last));
        return sb.toString();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to the Rhiot under one or more contributor license agreements.
	See the NOTICE file distributed with this work for additional information
	regarding copyright ownership. The licenses this file to You 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. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>io.rhiot</groupId>
		<artifactId>rhiot-gateway-components</artifactId>
		<version>0.1.4-SNAPSHOT</version>
	</parent>

	<name>Rhiot :: Gateway :: Camel components :: Kura</name>
	<packaging>bundle</packaging>
	<artifactId>camel-kura</artifactId>

	<properties>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>

		<!-- This module should use SLF4J version provided with Kura server. -->
		<slf4j.version>1.6.6</slf4j.version>

		<camel.osgi.export.pkg>
			io.rhiot.component.kura.*,
			io.rhiot.component.kura.cloud.*,
			io.rhiot.component.kura.datatransport.*,
			io.rhiot.component.kura.router.*,
			io.rhiot.component.kura.gpio.*,
			io.rhiot.component.kura.wifi.*
		</camel.osgi.export.pkg>
		<camel.osgi.export.service>
			org.apache.camel.spi.ComponentResolver;component=kura-gpio,
			org.apache.camel.spi.ComponentResolver;component=kura-wifi,
			org.apache.camel.spi.ComponentResolver;component=kura-cloud
		</camel.osgi.export.service>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-kura</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>org.eclipse.kura</groupId>
			<artifactId>org.eclipse.kura.api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.eclipse.kura</groupId>
			<artifactId>org.eclipse.kura.core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.eclipse.kura</groupId>
			<artifactId>org.eclipse.kura.core.net</artifactId>
		</dependency>
		<dependency>
			<groupId>org.eclipse.kura</groupId>
			<artifactId>org.eclipse.kura.linux.net</artifactId>
		</dependency>
		<dependency>
			<groupId>org.osgi</groupId>
			<artifactId>org.osgi.compendium</artifactId>
		</dependency>
		<!-- This module should use SLF4J version provided with Kura server. -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<!-- Testing API -->
		<dependency>
			<groupId>org.apache.felix</groupId>
			<artifactId>org.apache.felix.connect</artifactId>
			<scope>provided</scope>
		</dependency>

		<!-- Testing -->
		<dependency>
			<groupId>com.google.truth</groupId>
			<artifactId>truth</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<configuration>
					<instructions>
						<Import-Package>!org.apache.felix.connect.*,*</Import-Package>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>kura-repository</id>
			<name>Kura Maven Repository</name>
			<url>https://repo.eclipse.org/content/repositories/kura-releases/</url>
		</repository>
	</repositories>

</project>


text:
package org.apache.jackrabbit.oak.plugins.document;

import com.google.common.collect.ImmutableMap;

import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.plugins.nodetype.write.InitialContent;
import org.apache.jackrabbit.oak.plugins.segment.SegmentNodeStore;
import org.apache.jackrabbit.oak.plugins.segment.memory.MemoryStore;
import org.apache.jackrabbit.oak.security.SecurityProviderImpl;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.user.UserConfiguration;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.junit.Test;

public class InitializerTest extends AbstractMongoConnectionTest {

    @Test
    public void testInitializerMongo() throws CommitFailedException {
        NodeBuilder builder = mk.getNodeStore().getRoot().builder();
        new InitialContent().initialize(builder);

        SecurityProviderImpl provider = new SecurityProviderImpl(
                ConfigurationParameters.of(ImmutableMap.of(UserConfiguration.NAME,
                        ConfigurationParameters.of(ImmutableMap.of("anonymousId", "anonymous",
                                "adminId", "admin",
                                "usersPath", "/home/users",
                                "groupsPath", "/home/groups",
                                "defaultDepth", "1")))));
        provider.getConfiguration(UserConfiguration.class).getWorkspaceInitializer().initialize(
                builder, "default");
        builder.getNodeState();
    }

    @Test
    public void testInitializerSegment() throws CommitFailedException {
        NodeStore store = new SegmentNodeStore(new MemoryStore());

        NodeBuilder builder = store.getRoot().builder();
        new InitialContent().initialize(builder);

        SecurityProviderImpl provider = new SecurityProviderImpl(
                ConfigurationParameters.of(ImmutableMap.of(UserConfiguration.NAME,
                        ConfigurationParameters.of(ImmutableMap.of("anonymousId", "anonymous",
                                "adminId", "admin",
                                "usersPath", "/home/users",
                                "groupsPath", "/home/groups",
                                "defaultDepth", "1")))));
        provider.getConfiguration(UserConfiguration.class).getWorkspaceInitializer().initialize(
                builder, "default");
        builder.getNodeState();
    }

    @Test
    public void testInitializerMongoAfterInitialContent() throws CommitFailedException {
        NodeBuilder builder = mk.getNodeStore().getRoot().builder();
        // add initial content in separate merge
        new InitialContent().initialize(builder);
        mk.getNodeStore().merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);

        SecurityProviderImpl provider = new SecurityProviderImpl(
                ConfigurationParameters.of(ImmutableMap.of(UserConfiguration.NAME,
                        ConfigurationParameters.of(ImmutableMap.of("anonymousId", "anonymous",
                                "adminId", "admin",
                                "usersPath", "/home/users",
                                "groupsPath", "/home/groups",
                                "defaultDepth", "1")))));
        provider.getConfiguration(UserConfiguration.class).getWorkspaceInitializer().initialize(
                builder, "default");
        builder.getNodeState();
    }
}


text:
package main

import (
	"flag"
	"fmt"
	log "github.com/cihub/seelog"
	"github.com/samuel/go-zookeeper/zk"
	"os"
	"os/signal"
	"syscall"
	"time"
)

type KafkaCluster struct {
	Client    *KafkaClient
	Zookeeper *ZookeeperClient
}

type ApplicationContext struct {
	Config       *BurrowConfig
	Storage      *OffsetStorage
	Clusters     map[string]*KafkaCluster
	Server       *HttpServer
	Emailer      *Emailer
	HttpNotifier *HttpNotifier
	NotifierLock *zk.Lock
}

func loadNotifiers(app *ApplicationContext) error {
	// Set up the Emailer, if configured
	if len(app.Config.Email) > 0 {
		log.Info("Configuring Email notifier")
		emailer, err := NewEmailer(app)
		if err != nil {
			log.Criticalf("Cannot configure email notifier: %v", err)
			return err
		}
		app.Emailer = emailer
	}

	// Set up the HTTP Notifier, if configured
	if app.Config.Httpnotifier.Url != "" {
		log.Info("Configuring HTTP notifier")
		httpnotifier, err := NewHttpNotifier(app)
		if err != nil {
			log.Criticalf("Cannot configure HTTP notifier: %v", err)
			return err
		}
		app.HttpNotifier = httpnotifier
	}

	return nil
}

func startNotifiers(app *ApplicationContext) {
	// Do not proceed until we get the Zookeeper lock
	err := app.NotifierLock.Lock()
	if err != nil {
		log.Criticalf("Cannot get ZK notifier lock: %v", err)
		os.Exit(1)
	}
	log.Info("Acquired Zookeeper notifier lock")

	if app.Emailer != nil {
		log.Info("Starting Email notifier")
		app.Emailer.Start()
	}
	if app.HttpNotifier != nil {
		log.Info("Starting HTTP notifier")
		app.HttpNotifier.Start()
	}
}

func stopNotifiers(app *ApplicationContext) {
	// Ignore errors on unlock - we're quitting anyways, and it might not be locked
	app.NotifierLock.Unlock()

	if app.Emailer != nil {
		log.Info("Stopping Email notifier")
		app.Emailer.Stop()
	}
	if app.HttpNotifier != nil {
		log.Info("Stopping HTTP notifier")
		app.HttpNotifier.Stop()
	}
}

// Why two mains? Golang doesn't let main() return, which means defers will not run.
// So we do everything in a separate main, that way we can easily exit out with an error code and still run defers
func burrowMain() int {
	// The only command line arg is the config file
	var cfgfile = flag.String("config", "burrow.cfg", "Full path to the configuration file")
	flag.Parse()

	// Load and validate the configuration
	fmt.Fprintln(os.Stderr, "Reading configuration from", *cfgfile)
	appContext := &ApplicationContext{Config: ReadConfig(*cfgfile)}
	if err := ValidateConfig(appContext); err != nil {
		log.Criticalf("Cannot validate configuration: %v", err)
		return 1
	}

	// Create the PID file to lock out other processes. Defer removal so it's the last thing to go
	createPidFile(appContext.Config.General.LogDir + "/" + appContext.Config.General.PIDFile)
	defer removePidFile(appContext.Config.General.LogDir + "/" + appContext.Config.General.PIDFile)

	// Set up stderr/stdout to go to a separate log file
	openOutLog(appContext.Config.General.LogDir + "/burrow.out")
	fmt.Println("Started Burrow at", time.Now().Format("January 2, 2006 at 3:04pm (MST)"))

	// If a logging config is specified, replace the existing loggers
	if appContext.Config.General.LogConfig != "" {
		NewLogger(appContext.Config.General.LogConfig)
	}

	// Start a local Zookeeper client (used for application locks)
	log.Info("Starting Zookeeper client")
	zkhosts := make([]string, len(appContext.Config.Zookeeper.Hosts))
	for i, host := range appContext.Config.Zookeeper.Hosts {
		zkhosts[i] = fmt.Sprintf("%s:%v", host, appContext.Config.Zookeeper.Port)
	}
	zkconn, _, err := zk.Connect(zkhosts, time.Duration(appContext.Config.Zookeeper.Timeout)*time.Second)
	if err != nil {
		log.Criticalf("Cannot start Zookeeper client: %v", err)
		return 1
	}
	defer zkconn.Close()

	// Start an offsets storage module
	log.Info("Starting Offsets Storage module")
	appContext.Storage, err = NewOffsetStorage(appContext)
	if err != nil {
		log.Criticalf("Cannot configure offsets storage module: %v", err)
		return 1
	}
	defer appContext.Storage.Stop()

	// Start an HTTP server
	log.Info("Starting HTTP server")
	appContext.Server, err = NewHttpServer(appContext)
	if err != nil {
		log.Criticalf("Cannot start HTTP server: %v", err)
		return 1
	}
	defer appContext.Server.Stop()

	// Start Kafka clients and Zookeepers for each cluster
	appContext.Clusters = make(map[string]*KafkaCluster, len(appContext.Config.Kafka))
	for cluster, _ := range appContext.Config.Kafka {
		log.Infof("Starting Zookeeper client for cluster %s", cluster)
		zkconn, err := NewZookeeperClient(appContext, cluster)
		if err != nil {
			log.Criticalf("Cannot start Zookeeper client for cluster %s: %v", cluster, err)
			return 1
		}
		defer zkconn.Stop()

		log.Infof("Starting Kafka client for cluster %s", cluster)
		client, err := NewKafkaClient(appContext, cluster)
		if err != nil {
			log.Criticalf("Cannot start Kafka client for cluster %s: %v", cluster, err)
			return 1
		}
		defer client.Stop()

		appContext.Clusters[cluster] = &KafkaCluster{Client: client, Zookeeper: zkconn}
	}

	// Set up the Zookeeper lock for notification
	appContext.NotifierLock = zk.NewLock(zkconn, appContext.Config.Zookeeper.LockPath, zk.WorldACL(zk.PermAll))

	// Load the notifiers, but do not start them
	err = loadNotifiers(appContext)
	if err != nil {
		// Error was already logged
		return 1
	}

	// Notifiers are started in a goroutine if we get the ZK lock
	go startNotifiers(appContext)
	defer stopNotifiers(appContext)

	// Register signal handlers for exiting
	exitChannel := make(chan os.Signal, 1)
	signal.Notify(exitChannel, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGSTOP, syscall.SIGTERM)

	// Wait until we're told to exit
	<-exitChannel
	log.Info("Shutdown triggered")
	return 0
}

func main() {
	rv := burrowMain()
	if rv != 0 {
		fmt.Println("Burrow failed at", time.Now().Format("January 2, 2006 at 3:04pm (MST)"))
	} else {
		fmt.Println("Stopped Burrow at", time.Now().Format("January 2, 2006 at 3:04pm (MST)"))
	}
	os.Exit(rv)
}


text:
package specialclock.components;

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class SoundFilePlayer {
	public static void play(String filePath) {
		try {
            System.out.println("Sound Start");
            final AudioInputStream ais =
                    AudioSystem.getAudioInputStream(new File(filePath));
            ais.getFormat();
            final Clip line = AudioSystem.getClip();
            line.open(ais);
            line.start();
            System.out.println("Playing...");
            Thread.sleep(1);
            line.drain();
            line.stop();
            line.close();
            System.out.println("Sound End");
        } catch (final Exception e) {
            System.out.println(e);
        }
	}
}


text:
class OpLUT
{

	public s:string;
	public flags:number;
	public dest:boolean;
	public a:boolean;
	public b:boolean;
	public matrixwidth:number;
	public matrixheight:number;
	public ndwm:boolean;
	public scalar:boolean;
	public dm:boolean;
	public lod:boolean;

	constructor(s:string, flags:number, dest:boolean, a:boolean, b:boolean, matrixwidth:number, matrixheight:number, ndwm:boolean, scaler:boolean, dm:boolean, lod:boolean)
	{
		this.s = s;
		this.flags = flags;
		this.dest = dest;
		this.a = a;
		this.b = b;
		this.matrixwidth = matrixwidth;
		this.matrixheight = matrixheight;
		this.ndwm = ndwm;
		this.scalar = scaler;
		this.dm = dm;
		this.lod = lod;
	}
}

export = OpLUT;


text:
 Warning Log

**Namespace:** [OfficeDevPnP.Core.Diagnostics](OfficeDevPnP.Core.Diagnostics.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public static void Warning(String source, Exception ex, String message, params Object[] args)
```
### Parameters
#### source
  Type: System.String
  Source string

#### ex
  Type: System.Exception
  Exception object

#### message
  Type: System.String
  Message string

#### args
  Type: System.Object[]
  Arguments object

### Return Value
Type: void

## See also
- [Log](OfficeDevPnP.Core.Diagnostics.Log.md)
- [OfficeDevPnP.Core.Diagnostics](OfficeDevPnP.Core.Diagnostics.md)


text:
yii2-password
=============

[![Latest Stable Version](https://poser.pugx.org/kartik-v/yii2-password/v/stable)](https://packagist.org/packages/kartik-v/yii2-password)
[![License](https://poser.pugx.org/kartik-v/yii2-password/license)](https://packagist.org/packages/kartik-v/yii2-password)
[![Total Downloads](https://poser.pugx.org/kartik-v/yii2-password/downloads)](https://packagist.org/packages/kartik-v/yii2-password)
[![Monthly Downloads](https://poser.pugx.org/kartik-v/yii2-password/d/monthly)](https://packagist.org/packages/kartik-v/yii2-password)
[![Daily Downloads](https://poser.pugx.org/kartik-v/yii2-password/d/daily)](https://packagist.org/packages/kartik-v/yii2-password)

This extension provides a couple of great password management utilities for Yii Framework 2.0. The extension allows password strength validation through your model. In addition, it provides an advanced password input widget, that allows you to display/hide text and show the password strength.

### Latest Release

> NOTE: The latest version of the plugin v1.5.3 has been released. Refer the [CHANGE LOG](https://github.com/kartik-v/yii2-password/blob/master/CHANGE.md) for details.

### Prerequisites

- Ensure you have the right version of jQuery loaded (> v1.9.0).
- In case you are upgrading from an older release, its recommended that you clean up your web assets, local browser cache, and restart your browsers before using the extension.

### StrengthValidator
[```VIEW DEMO```](http://demos.krajee.com/password-details/strength-validator)
This is a password strength validator for your model attributes. The strength validator allows you to configure the following parameters for validating passwords or strings.

1. Whether password contains an username
2. Whether password contains an email string
3. Minimum number of characters
4. Maximum number of characters
5. Whether spaces are allowed
6. Minimum number of lower space characters
7. Minimum number of upper space characters
8. Minimum number of numeric / digit characters
9. Minimum number of special characters

Other features:

1. Includes 5 presets (simple, normal, fair, medium, and strong). Instead of setting each parameter above, you can call a preset which will auto-set each of the parameters above.
2. It includes both server and client validation.
3. This can work with the PasswordInput widget (described next) as per your needs. The strength validation routines for both are a bit different. The PasswordInput widget focuses on displaying the strength only, and does not restrict the user input in any way.

> NOTE: The StrengthValidator does not validate if the password field is required. You need to use Yii's ```required``` rule for this.

### PasswordInput
[```VIEW DEMO```](http://demos.krajee.com/password-details/password-input)
This is an advanced password input widget with configurable options and a dynamic strength meter based on the [Strength Meter JQuery Plugin](http://plugins.krajee.com/strength-meter) by Krajee. The widget provides various features as mentioned below:

1. Allows you to show/ hide a password text (using bootstrap styled input addons). You can configure this option to be shown or not.
2. Allows you to display an advanced password strength meter to calculate and show your password strength as you type.
3. Allows you to control and position/style your meter based on templates.
4. A password strength meter consists of the meter bar, the score, and the verdict.
5. Uses Bootstrap 3.0 styling wherever possible with inbuilt Yii 2.0 ActiveField functionality.
6. Works independent and complements the StrengthValidator.

### Demo
You can see a [demonstration here](http://demos.krajee.com/password) on usage of these functions with documentation and examples.

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

> Note: Check the [composer.json](https://github.com/kartik-v/yii2-password/blob/master/composer.json) for this extension's requirements and dependencies.
Read this [web tip /wiki](http://webtips.krajee.com/setting-composer-minimum-stability-application/) on setting the `minimum-stability` settings for your application's composer.json.

Either run

```
$ php composer.phar require kartik-v/yii2-password "@dev"
```

or add

```
"kartik-v/yii2-password": "@dev"
```

to the ```require``` section of your `composer.json` file.

## Usage

### StrengthValidator
```php
// add this in your model
use kartik\password\StrengthValidator;

// use the validator in your model rules
public function rules() {
    return [
       	[['username', 'password'], 'required'],
       	[['password'], StrengthValidator::className(), 'preset'=>'normal', 'userAttribute'=>'username']
    ];
}
```

### PasswordInput
```php
// add this in your view
use kartik\password\PasswordInput;
use kartik\widgets\ActiveForm; // optional

$form = ActiveForm::begin(['id' => 'login-form']);
echo $form->field($model,'username');
echo $form->field($model, 'password')->widget(PasswordInput::classname(), [
    'pluginOptions' => [
        'showMeter' => true,
        'toggleMask' => false
    ]
]);
```

## License

**yii2-password** is released under the BSD 3-Clause License. See the bundled `LICENSE.md` for details.


text:
package org.openjdk.tests.java.util.Collections;
/*
 * This file is available under and governed by the GNU General Public
 * License version 2.
 * It was taken from http://hg.openjdk.java.net/jdk8u/jdk8u60.
 * The file has the next changes:
 *  - changed tested collections to collections from usr.sfedorov.aht package
 *  - erased tests for equals/hashCode and null keys/values (if existed)
 *  - added compatibility to common hashcode/equals contract (if wasn't)
 *  - changed package
 *  - adopted to testng library (where it wasn't done before)
 *  - added this statement
 * [aht][https://github.com/fedorov-s-n/aht], 2015
 */
/*
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code 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
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 5045582
 * @summary binarySearch of Collections larger than 1<<30
 * @author Martin Buchholz
 */
import java.util.*;
import com.github.fedorov_s_n.aht.AHTMap;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class BigBinarySearch {

    // Allows creation of very "big" collections without using too
    // many real resources
    static class SparseIntegerList
            extends AbstractList<Integer>
            implements RandomAccess {

        private Map<Integer, Integer> m = new AHTMap<Integer, Integer>();

        public Integer get(int i) {
            if (i < 0) {
                throw new IndexOutOfBoundsException("" + i);
            }
            Integer v = m.get(i);
            return (v == null) ? Integer.valueOf(0) : v;
        }

        public int size() {
            return Collections.max(m.keySet()) + 1;
        }

        public Integer set(int i, Integer v) {
            if (i < 0) {
                throw new IndexOutOfBoundsException("" + i);
            }
            Integer ret = get(i);
            if (v == 0) {
                m.remove(i);
            } else {
                m.put(i, v);
            }
            return ret;
        }
    }

    /**
     * Check that binarySearch finds an element where we got it
     */
    private static void checkBinarySearch(List<Integer> l, int i) {
        assertEquals(i, Collections.binarySearch(l, l.get(i)));
    }

    /**
     * Check that binarySearch finds an element where we got it
     */
    private static void checkBinarySearch(List<Integer> l, int i,
            Comparator<Integer> comparator) {
        assertEquals(i, Collections.binarySearch(l, l.get(i), comparator));
    }

    @Test
    public void realMain() {
        final int n = (1 << 30) + 47;

        System.out.println("binarySearch(List<Integer>, Integer)");
        List<Integer> big = new SparseIntegerList();
        big.set(0, -44);
        big.set(1, -43);
        big.set(n - 2, 43);
        big.set(n - 1, 44);
        int[] ints = {0, 1, n - 2, n - 1};
        Comparator<Integer> reverse = Collections.reverseOrder();
        Comparator<Integer> natural = Collections.reverseOrder(reverse);

        for (int i : ints) {
            checkBinarySearch(big, i);
            checkBinarySearch(big, i, null);
            checkBinarySearch(big, i, natural);
        }
        for (int i : ints) {
            big.set(i, -big.get(i));
        }
        for (int i : ints) {
            checkBinarySearch(big, i, reverse);
        }
    }

}


text:
package org.apache.samza.task;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.samza.container.TaskName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TaskCoordinatorRequests is used in run loop to collect the coordinator
 * requests from tasks, including commit requests and shutdown requests.
 * It is thread safe so it can be updated from multiple task threads.
 */
public class CoordinatorRequests {
  private static final Logger log = LoggerFactory.getLogger(CoordinatorRequests.class);

  private final Set<TaskName> taskNames;
  private final Set<TaskName> taskShutdownRequests = new CopyOnWriteArraySet<>();
  private final Set<TaskName> taskCommitRequests = new CopyOnWriteArraySet<>();
  volatile private boolean shutdownNow = false;

  public CoordinatorRequests(Set<TaskName> taskNames) {
    this.taskNames = taskNames;
  }

  public void update(ReadableCoordinator coordinator) {
    if (coordinator.commitRequest().isDefined() || coordinator.shutdownRequest().isDefined()) {
      checkCoordinator(coordinator);
    }
  }

  public Set<TaskName> commitRequests() {
    return taskCommitRequests;
  }

  public boolean shouldShutdownNow() {
    return shutdownNow;
  }

  /**
   * A new TaskCoordinator object is passed to a task on every call to StreamTask.process
   * and WindowableTask.window. This method checks whether the task requested that we
   * do something that affects the run loop (such as commit or shut down), and updates
   * run loop state accordingly.
   */
  private void checkCoordinator(ReadableCoordinator coordinator) {
    if (coordinator.requestedCommitTask()) {
      log.debug("Task {} requested commit for current task only", coordinator.taskName());
      taskCommitRequests.add(coordinator.taskName());
    }

    if (coordinator.requestedCommitAll()) {
      log.debug("Task {} requested commit for all tasks in the container", coordinator.taskName());
      taskCommitRequests.addAll(taskNames);
    }

    if (coordinator.requestedShutdownOnConsensus()) {
      taskShutdownRequests.add(coordinator.taskName());
      log.info("Shutdown has now been requested by tasks {}", taskShutdownRequests);
    }

    if (coordinator.requestedShutdownNow() || taskShutdownRequests.size() == taskNames.size()) {
      log.info("Shutdown requested.");
      shutdownNow = true;
    }
  }
}


text:
API Reference
=============
.. automodule:: sprockets.logging
   :members:


text:
See here:

https://github.com/NPBruce/valkyrie/wiki/DeveloperGuide


text:
const { Router } = require('express');

const attachTo = (app, data) => {
    const router = new Router();
    const controller = require('./controller').init(data);

    router
        .get('/search', (req, res) => {
            return controller.searchOne(req, res);
        });

    app.use('/menu', router);
};

module.exports = { attachTo };


text:
//tag::cluster-groups[]
Ignite ignite = Ignition::Get();
ClusterGroup cluster = ignite.GetCluster().AsClusterGroup();
// All nodes on which cache with name "myCache" is deployed,
// either in client or server mode.
ClusterGroup cacheGroup = cluster.ForCacheNodes("myCache");
// All data nodes responsible for caching data for "myCache".
ClusterGroup dataGroup = cluster.ForDataNodes("myCache");
// All client nodes that access "myCache".
ClusterGroup clientGroup = cluster.ForClientNodes("myCache");
//end::cluster-groups[]


text:
<script type="text/javascript">
     window.location.replace("en/");
</script>


text:
#ifndef JNI_CAMERAANALYZER_COLORCHECKERTEST_H
#define JNI_CAMERAANALYZER_COLORCHECKERTEST_H

#include <jni.h>
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT jlong JNICALL
Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_createColorCheckerTest(
    JNIEnv*      env,
    jobject      thiz,
    jint         output_height,
    jint         output_width);

JNIEXPORT void JNICALL
Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_createColorCheckerClass(
    JNIEnv *env,
    jobject thiz,
    jlong buffer_address,
    jlong handler_address);

JNIEXPORT jlong JNICALL
Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_getColorCheckerRadiusAdd(
    JNIEnv *env,
    jobject thiz,
    jlong handler_address);

JNIEXPORT jlong JNICALL
Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_getColorCheckerCenterAdd(
    JNIEnv *env,
    jobject thiz,
    jlong handler_address);

JNIEXPORT jboolean JNICALL
Java_com_android_cts_verifier_camera_analyzer_ColorCheckerTest_processColorCheckerTest(
    JNIEnv*      env,
    jobject      thiz,
    jlong        handler_address);

#ifdef __cplusplus
}
#endif

#endif


text:
/*************************************************************************/
/*  test_gui.cpp                                                         */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef _3D_DISABLED

#include "test_gui.h"

#include "scene/main/scene_main_loop.h"
#include "os/os.h"
#include "scene/gui/control.h"
#include "scene/gui/button.h"
#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/scroll_bar.h"
#include "scene/gui/popup_menu.h"
#include "scene/gui/option_button.h"
#include "scene/gui/spin_box.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/progress_bar.h"
#include "scene/gui/panel.h"
#include "scene/gui/tab_container.h"
#include "scene/gui/tree.h"
#include "scene/gui/rich_text_label.h"
#include "scene/gui/texture_frame.h"
#include "io/image_loader.h"
#include "print_string.h"
#include "scene/2d/sprite.h"

#include "scene/main/viewport.h"
#include "scene/3d/camera.h"
#include "scene/3d/test_cube.h"

namespace TestGUI {

class TestMainLoop : public SceneTree {

	Control *control;

public:

	virtual void request_quit() {

		quit();

	}
	virtual void init() {

		SceneTree::init();

#if 0

		Viewport *vp = memnew( Viewport );
		vp->set_world( Ref<World>( memnew( World )));
		get_root()->add_child(vp);

		vp->set_rect(Rect2(0,0,256,256));
		vp->set_as_render_target(true);
		vp->set_render_target_update_mode(Viewport::RENDER_TARGET_UPDATE_ALWAYS);

		Camera *camera = memnew( Camera );
		vp->add_child(camera);
		camera->make_current();

		TestCube *testcube = memnew( TestCube );
		vp->add_child(testcube);
		testcube->set_transform(Transform( Matrix3().rotated(Vector3(0,1,0),Math_PI*0.25), Vector3(0,0,-8)));

		Sprite *sp = memnew( Sprite );
		sp->set_texture( vp->get_render_target_texture() );
//		sp->set_texture( ResourceLoader::load("res://ball.png") );
		sp->set_pos(Point2(300,300));
		get_root()->add_child(sp);

		return;
#endif

		Panel * frame = memnew( Panel );
		frame->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
		frame->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_END );
		frame->set_end( Point2(0,0) );

		Ref<Theme> t = memnew( Theme );
		frame->set_theme(t);

		get_root()->add_child( frame );

		Label *label = memnew( Label );

		label->set_pos( Point2( 80,90 ) );
		label->set_size( Point2( 170,80 ) );
		label->set_align( Label::ALIGN_FILL );
		//label->set_text("There");
		label->set_text("There was once upon a time a beautiful unicorn that loved to play with little girls...");

		frame->add_child(label);

		Button *button = memnew( Button );

		button->set_pos( Point2( 20,20 ) );
		button->set_size( Point2( 1,1 ) );
		button->set_text("This is a biggie button");

		frame->add_child( button );

#if 0
		Sprite *tf = memnew( Sprite );
		frame->add_child(tf);
		Image img;
		ImageLoader::load_image("LarvoClub.png",&img);

		img.resize(512,512);
		img.generate_mipmaps();
		img.compress(Image::COMPRESS_PVRTC4);
		Ref<ImageTexture> tt = memnew( ImageTexture );
		tt->create_from_image(img);
		tf->set_texture(tt);
		tf->set_pos(Point2(50,50));
		//tf->set_scale(Point2(0.3,0.3));

		return;
#endif

		Tree * tree = memnew( Tree );
		tree->set_columns(2);

		tree->set_pos( Point2( 230,210 ) );
		tree->set_size( Point2( 150,250 ) );

		TreeItem *item = tree->create_item();
		item->set_editable(0,true);
		item->set_text(0,"root");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		item->set_editable(0,true);
		item->set_text(0,"check");
		item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
		item->set_editable(1,true);
		item->set_text(1,"check2");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_range_config(0,0,20,0.1);
		item->set_range(0,2);
		item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
		item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
		item->set_editable(1,true);
		item->set_range_config(1,0,20,0.1);
		item->set_range(1,3);

		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_text(0,"Have,Many,Several,Options!");
		item->set_range(0,2);

		item = tree->create_item( item );
		item->set_editable(0,true);
		item->set_text(0,"Gershwin!");

		frame->add_child(tree);

		//control = memnew( Control );
		//root->add_child( control );

		LineEdit *line_edit = memnew( LineEdit );

		line_edit->set_pos( Point2( 30,190 ) );
		line_edit->set_size( Point2( 180,1 ) );

		frame->add_child(line_edit);

		HScrollBar *hscroll = memnew( HScrollBar );

		hscroll->set_pos( Point2( 30,290 ) );
		hscroll->set_size( Point2( 180,1 ) );
		hscroll->set_max(10);
		hscroll->set_page(4);

		frame->add_child(hscroll);

		SpinBox *spin = memnew( SpinBox );

		spin->set_pos( Point2( 30,260 ) );
		spin->set_size( Point2( 120,1 ) );

		frame->add_child(spin);
		hscroll->share(spin);

		ProgressBar *progress = memnew( ProgressBar );

		progress->set_pos( Point2( 30,330 ) );
		progress->set_size( Point2( 120,1 ) );

		frame->add_child(progress);
		hscroll->share(progress);

		MenuButton *menu_button = memnew( MenuButton );

		menu_button->set_text("I'm a menu!");
		menu_button->set_pos( Point2( 30,380 ) );
		menu_button->set_size( Point2( 1,1 ) );

		frame->add_child(menu_button);

		PopupMenu *popup = menu_button->get_popup();

		popup->add_item("Hello, testing");
		popup->add_item("My Dearest");
		popup->add_separator();
		popup->add_item("Popup");
		popup->add_check_item("Check Popup");
		popup->set_item_checked(4,true);

		OptionButton *options = memnew( OptionButton );

		options->add_item("Hello, testing");
		options->add_item("My Dearest");

		options->set_pos( Point2( 230,180 ) );
		options->set_size( Point2( 1,1 ) );

		frame->add_child(options);

		/*
		Tree * tree = memnew( Tree );
		tree->set_columns(2);

		tree->set_pos( Point2( 230,210 ) );
		tree->set_size( Point2( 150,250 ) );

		TreeItem *item = tree->create_item();
		item->set_editable(0,true);
		item->set_text(0,"root");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
		item->set_editable(0,true);
		item->set_text(0,"check");
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_range_config(0,0,20,0.1);
		item->set_range(0,2);
		item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
		item = tree->create_item( tree->get_root() );
		item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
		item->set_editable(0,true);
		item->set_text(0,"Have,Many,Several,Options!");
		item->set_range(0,2);

		frame->add_child(tree);
*/

		RichTextLabel *richtext = memnew( RichTextLabel );

		richtext->set_pos( Point2( 600,210 ) );
		richtext->set_size( Point2( 180,250 ) );
		richtext->set_anchor_and_margin(MARGIN_RIGHT,Control::ANCHOR_END,20);

		frame->add_child(richtext);

		richtext->add_text("Hello, My Friends!\n\nWelcome to the amazing world of ");

		richtext->add_newline();
		richtext->add_newline();

		richtext->push_color(Color(1,0.5,0.5));
		richtext->add_text("leprechauns");
		richtext->pop();

		richtext->add_text(" and ");
		richtext->push_color(Color(0,1.0,0.5));
		richtext->add_text("faeries.\n");
		richtext->pop();
		richtext->add_text("In this new episode, we will attemp to ");
		richtext->push_font(richtext->get_font("mono_font","Fonts"));
		richtext->push_color(Color(0.7,0.5,1.0));
		richtext->add_text("deliver something nice");
		richtext->pop();
		richtext->pop();
		richtext->add_text(" to all the viewers! Unfortunately, I need to ");
		richtext->push_underline();
		richtext->add_text("keep writing a lot of text");
		richtext->pop();
		richtext->add_text(" so the label control overflows and the scrollbar appears.\n");
		//richtext->push_indent(1);
		//richtext->add_text("By the way, testing indent levels! Yohohoho! Everything should appear to the right sightly here!\n");
		//richtext->pop();
		richtext->push_meta("http://www.scrollingcapabilities.xz");
		richtext->add_text("This allows to test for the scrolling capabilities ");
		richtext->pop();
		richtext->add_text("of the rich text label for huge text (not like this text will really be huge but, you know).\nAs long as it is so long that it will work nicely for a test/demo, then it's welcomed in my book...\nChanging subject, the day is cloudy today and I'm wondering if I'll get che chance to travel somewhere nice. Sometimes, watching the clouds from satellite images may give a nice insight about how pressure zones in our planet work, althogh it also makes it pretty obvious to see why most weather forecasts get it wrong so often.\nClouds are so difficult to predict!\nBut it's pretty cool how our civilization has adapted to having water falling from the sky each time it rains...");
		//richtext->add_text("Hello!\nGorgeous..");

		//richtext->push_meta("http://www.scrollingcapabilities.xz");
		///richtext->add_text("Hello!\n");
		//richtext->pop();

		richtext->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END);

		TabContainer * tabc = memnew( TabContainer );

		Control *ctl= memnew( Control );
		ctl->set_name("tab 1");
		tabc->add_child(ctl);

		ctl= memnew( Control );
		ctl->set_name("tab 2");
		tabc->add_child(ctl);
		label = memnew( Label );
		label->set_text("Some Label");
		label->set_pos( Point2(20,20) );
		ctl->add_child(label);;

		ctl= memnew( Control );
		ctl->set_name("tab 3");
		button = memnew( Button );
		button->set_text("Some Button");
		button->set_pos( Point2(30,50) );
		ctl->add_child(button);;

		tabc->add_child(ctl);

		frame->add_child(tabc);

		tabc->set_pos( Point2( 400,210 ) );
		tabc->set_size( Point2( 180,250 ) );

		Ref<ImageTexture> text = memnew( ImageTexture );
		text->load("test_data/concave.png");

		Sprite* sprite = memnew(Sprite);
		sprite->set_texture(text);
		sprite->set_pos(Point2(300, 300));
		frame->add_child(sprite);
		sprite->show();

		Sprite* sprite2 = memnew(Sprite);
		sprite->set_texture(text);
		sprite->add_child(sprite2);
		sprite2->set_pos(Point2(50, 50));
		sprite2->show();
	}

};

MainLoop* test() {

	return memnew( TestMainLoop );
}

}

#endif


text:
<?php

namespace Magento\Customer\Test\Block\Account\Dashboard;

use Magento\Mtf\Block\Block;

/**
 * Main block on customer account page.
 */
class Info extends Block
{
    /**
     * Css selector for Contact Information Edit Link.
     *
     * @var string
     */
    protected $contactInfoEditLink = '.block-dashboard-info .box-information .action.edit';

    /**
     * Css selector for Contact Information box content.
     *
     * @var string
     */
    protected $contactInfoBoxContent = '.box.box-information .box-content';

    /**
     * Css selector for Contact Information Change Password Link.
     *
     * @var string
     */
    protected $contactInfoChangePasswordLink = '.block-dashboard-info .box-information .action.change-password';

    /**
     * Css selector for Contact Information Change Email Link.
     *
     * @var string
     */
    protected $contactInfoChangeEmailLink = '.form-edit-account .fieldset.info .checkbox#change-email';

    /**
     * Css selector for Contact Information Change Password Checkbox.
     *
     * @var string
     */
    protected $contactInfoChangePasswordCheckbox = '.form-edit-account .fieldset.info .checkbox#change-password';

    /**
     * Dashboard Welcome block locator.
     *
     * @var string
     */
    protected $dashboardWelcome = '.block-dashboard-welcome .block-title';

    /**
     * Click on Contact Information Edit Link.
     *
     * @return void
     */
    public function openEditContactInfo()
    {
        $this->_rootElement->find($this->contactInfoEditLink)->click();
        $this->openChangeEmail();
    }

    /**
     * Click on Contact Information Edit Link.
     *
     * @return void
     */
    public function openChangePassword()
    {
        $this->_rootElement->find($this->contactInfoChangePasswordLink)->click();
    }

    /**
     * Get welcome text.
     *
     * @return string
     */
    public function getWelcomeText()
    {
        return $this->_rootElement->find($this->dashboardWelcome)->getText();
    }

    /**
     * Click on Change Email checkbox.
     *
     * @return void
     */
    public function openChangeEmail()
    {
        $this->_rootElement->find($this->contactInfoChangeEmailLink)->click();
    }

    /**
     * Click on Change Password checkbox.
     *
     * @return void
     */
    public function checkChangePassword()
    {
        $this->_rootElement->find($this->contactInfoChangePasswordCheckbox)->click();
    }

    /**
     * Get Contact Information block content.
     *
     * @return string
     */
    public function getContactInfoContent()
    {
        return $this->_rootElement->find($this->contactInfoBoxContent)->getText();
    }
}


text:
package org.jboss.arquillian.testenricher.resource;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.NamingException;

import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.test.spi.TestEnricher;

/**
 * Enricher that provide @Resource field and method argument injection.

 *

 * Field Resources will only be injected if the current value is NULL or primitive default value.
 *
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
public class ResourceInjectionEnricher implements TestEnricher
{
   private static final String RESOURCE_LOOKUP_PREFIX = "java:comp/env";
   private static final String ANNOTATION_NAME = "javax.annotation.Resource";

   private static final Logger log = Logger.getLogger(TestEnricher.class.getName());

   @Inject
   private Instance<Context> contextInst;

   /* (non-Javadoc)
    * @see org.jboss.arquillian.spi.TestEnricher#enrich(org.jboss.arquillian.spi.Context, java.lang.Object)
    */
   public void enrich(Object testCase)
   {
      if(SecurityActions.isClassPresent(ANNOTATION_NAME) && contextInst.get() != null)
      {
         injectClass(testCase);
      }
   }

   /* (non-Javadoc)
    * @see org.jboss.arquillian.spi.TestEnricher#resolve(org.jboss.arquillian.spi.Context, java.lang.reflect.Method)
    */
   public Object[] resolve(Method method)
   {
     return new Object[method.getParameterTypes().length];
   }

   protected void injectClass(Object testCase)
   {
      try
      {
         @SuppressWarnings("unchecked")
         Class<? extends Annotation> resourceAnnotation = (Class<? extends Annotation>)SecurityActions.getThreadContextClassLoader().loadClass(ANNOTATION_NAME);

         List<Field> annotatedFields = SecurityActions.getFieldsWithAnnotation(
               testCase.getClass(),
               resourceAnnotation);

         for(Field field : annotatedFields)
         {
            /*
             * only try to lookup fields that are not already set or primitives
             * (we don't really know if they have been set or not)
             */
            Object currentValue = field.get(testCase);
            if(shouldInject(field, currentValue))
            {
               try
               {
                  Object resource = resolveResource(field);
                  field.set(testCase, resource);
               }
               catch (Exception e)
               {
                  log.fine("Could not lookup for " + field + ", other Enrichers might, move on. Exception: " + e.getMessage());
               }
            }
         }

         List<Method> methods = SecurityActions.getMethodsWithAnnotation(
               testCase.getClass(),
               resourceAnnotation);

         for(Method method : methods)
         {
            if(method.getParameterTypes().length != 1)
            {
               throw new RuntimeException("@Resource only allowed on single argument methods");
            }
            if(!method.getName().startsWith("set"))
            {
               throw new RuntimeException("@Resource only allowed on 'set' methods");
            }
            Object resource = resolveResource(method);
            method.invoke(testCase, resource);
         }
      }
      catch (Exception e)
      {
         throw new RuntimeException("Could not inject members", e);
      }
   }

   /**
    * Looks up the JNDI resource for any given annotated element.
    * @param element any annotated element (field, method, etc.)
    * @return the located resource
    * @throws Exception
    */
   protected Object resolveResource(AnnotatedElement element) throws Exception
   {
      Object resolvedResource = null;
      // This implementation is based on previous behavior in injectClass()
      if (Field.class.isAssignableFrom(element.getClass()))
      {
         resolvedResource = lookup(getResourceName((Field) element));
      }
      else if (Method.class.isAssignableFrom(element.getClass()))
      {
         resolvedResource = lookup(getResourceName(element.getAnnotation(Resource.class)));
      }
      return resolvedResource;
   }

   private boolean shouldInject(Field field, Object currentValue)
   {
      Class<?> type = field.getType();
      if(type.isPrimitive())
      {
         if(isPrimitiveNull(currentValue))
         {
            log.fine("Primitive field " + field.getName() + " has been detected to have the default primitive value, " +
            		"can not determine if it has already been injected. Re-injecting field.");
            return true;
         }
      }
      else
      {
         if(currentValue == null)
         {
            return true;
         }
      }
      return false;
   }

   private boolean isPrimitiveNull(Object currentValue)
   {
      String stringValue = String.valueOf(currentValue);
      if("0".equals(stringValue) || "0.0".equals(stringValue) || "false".equals(stringValue))
      {
         return true;
      }
      else if(Character.class.isInstance(currentValue))
      {
         if( Character.class.cast(currentValue) == (char)0)
         {
            return true;
         }
      }
      return false;
   }

   protected Object lookup(String jndiName) throws Exception
   {
      // TODO: figure out test context ?
      Context context = getContainerContext();
      return context.lookup(jndiName);
   }

   /**
    * Obtains the appropriate context for the test.  Can be overriden by
    * enrichers for each container to provide the correct context.
    * @return the test context
    * @throws NamingException
    */
   protected Context getContainerContext() throws NamingException
   {
      return contextInst.get();
   }

   protected String getResourceName(Field field)
   {
      Resource resource = field.getAnnotation(Resource.class);
      String resourceName = getResourceName(resource);
      if(resourceName != null)
      {
       return resourceName;
      }
      String propertyName = field.getName();
      String className = field.getDeclaringClass().getName();
      return RESOURCE_LOOKUP_PREFIX + "/" + className + "/" + propertyName;
   }

   protected String getResourceName(Resource resource)
   {
      String mappedName = resource.mappedName();
      if (!mappedName.equals(""))
      {
         return mappedName;
      }
      String name = resource.name();
      if (!name.equals(""))
      {
         return RESOURCE_LOOKUP_PREFIX + "/" + name;
      }
      return null;
   }
}


text:
package zss.tool;

@Version("2018.09.18")
public class ArrayTool {
    private ArrayTool() {
    }

    public static int sum(final int... values)
    {
        int value = 0;
        for (int i = 0; i < values.length; i++)
        {
            value += values[i];
        }
        return value;
    }

    public static int minimum(final int... values) {
        int value = values[0];
        for (int i = 1; i < values.length; i++) {
            value = Math.min(value, values[i]);
        }
        return value;
    }
}


text:
package org.apache.spark.watchdogs;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.concurrent.TimeUnit;

import org.apache.spark.SparkContext;
import org.apache.spark.SparkStageInfoImpl;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.JavaSparkStatusTracker;
import org.apache.spark.scheduler.DAGScheduler;
import org.junit.Test;

public class SparkStageHangingWatchdogTest {

	JavaSparkContext ctx = mock(JavaSparkContext.class);
	JavaSparkStatusTracker tracker = mock(JavaSparkStatusTracker.class);

	@Test
	public void testNoStages() throws Exception {
		SparkStageHangingWatchdog checker = new SparkStageHangingWatchdog(ctx, "appId", 3);

		when(ctx.statusTracker()).thenReturn(tracker);

		assertTrue(checker.check().isOk());
	}

	@Test
	public void testNoStages2() throws Exception {
		SparkStageHangingWatchdog checker = new SparkStageHangingWatchdog(ctx, "appId", 3);

		when(ctx.statusTracker()).thenReturn(tracker);

		when(tracker.getActiveStageIds()).thenReturn(new int[]{});

		assertTrue(checker.check().isOk());
	}

	@Test
	public void testStageOk() throws Exception {
		SparkStageHangingWatchdog checker = new SparkStageHangingWatchdog(ctx, "appId", 3);

		when(ctx.statusTracker()).thenReturn(tracker);

		when(tracker.getActiveStageIds()).thenReturn(new int[]{1});

		when(tracker.getStageInfo(1)).thenReturn(new SparkStageInfoImpl(1, 0, System.currentTimeMillis(), null, 0, 0, 0, 0));

		assertTrue(checker.check().isOk());
	}

	@Test
	public void testStageNotOk() throws Exception {
		SparkStageHangingWatchdog checker = new SparkStageHangingWatchdog(ctx, "appId", 3);

		when(ctx.statusTracker()).thenReturn(tracker);

		when(tracker.getActiveStageIds()).thenReturn(new int[]{1});

		when(tracker.getStageInfo(1)).thenReturn(new SparkStageInfoImpl(1, 0, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(4), null, 0, 0, 0, 0));

		assertFalse(checker.check().isOk());
	}

	@Test
	public void testTwoStageNotOk() throws Exception {
		SparkStageHangingWatchdog checker = new SparkStageHangingWatchdog(ctx, "appId", 3);

		when(ctx.statusTracker()).thenReturn(tracker);
		SparkContext scalaContext = mock(SparkContext.class);
		when(ctx.sc()).thenReturn(scalaContext);

		DAGScheduler dagScheduler = mock(DAGScheduler.class);
		when(scalaContext.dagScheduler()).thenReturn(dagScheduler);

		when(tracker.getActiveStageIds()).thenReturn(new int[]{1, 2});

		when(tracker.getStageInfo(1)).thenReturn(new SparkStageInfoImpl(1, 0, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(4), null, 0, 0, 0, 0));
		when(tracker.getStageInfo(2)).thenReturn(new SparkStageInfoImpl(2, 0, System.currentTimeMillis() - TimeUnit.HOURS.toMillis(4), null, 0, 0, 0, 0));

		WatchdogResult watchdogResult = checker.check();
		assertFalse(watchdogResult.isOk());

		watchdogResult.getFix().get().run();

		verify(dagScheduler).cancelStage(1);
		verify(dagScheduler).cancelStage(2);

	}

	@Test
	public void testStageAbsent() throws Exception {
		SparkStageHangingWatchdog checker = new SparkStageHangingWatchdog(ctx, "appId", 3);

		when(ctx.statusTracker()).thenReturn(tracker);

		when(tracker.getActiveStageIds()).thenReturn(new int[]{1});

		when(tracker.getStageInfo(1)).thenReturn(null);

		assertTrue(checker.check().isOk());
	}
}


text:
/**
 * Created by christian@    kartoza on 03/15.
 */
/*global $, jQuery, L, window, console*/
var map;
var campus_lookup = [];
var campus_features = [];
var campus_layer;
var highlighted_feature;
var fit_bounds_options = {
    maxZoom: 10
};
var markerIcon = L.ExtraMarkers.icon({
    icon: 'fa-graduation-cap',
    markerColor: 'blue',
    iconColor: 'white',
    shape: 'circle',
    prefix: 'fa'
});
var highlightMarkerIcon = L.ExtraMarkers.icon({
    icon: 'fa-graduation-cap',
    markerColor: 'white',
    iconColor: 'blue',
    shape: 'circle',
    prefix: 'fa'
});
var markerPrivateInstitutionIcon = L.ExtraMarkers.icon({
    icon: 'fa-graduation-cap',
    markerColor: 'red',
    iconColor: 'white',
    shape: 'circle',
    prefix: 'fa'
});
var highlightMarkerPrivateInstitutionIcon = L.ExtraMarkers.icon({
    icon: 'fa-graduation-cap',
    markerColor: 'white',
    iconColor: 'red',
    shape: 'circle',
    prefix: 'fa'
});

jQuery.download = function (url, data, method) {
    /* Taken from http://www.filamentgroup.com/lab/jquery-plugin-for-requesting-ajax-like-file-downloads.html*/
    'use strict';
    //url and data options required
    if (url && data) {
        //data can be string of parameters or array/object
        data = typeof data === 'string' ? data : jQuery.param(data);
        //split params into form inputs
        var inputs = '';
        jQuery.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        //send request
        jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
            .appendTo('body').submit().remove();
    }
};

function toggle_side_panel() {
    'use strict';
    var map_div = $('#map'),
        side_panel = $('#side_panel'),
        show_hide_div = $('#show_hide');
    /* hide */
    if (side_panel.is(":visible")) {
        show_hide_div.removeClass('glyphicon-chevron-right');
        show_hide_div.addClass('glyphicon-chevron-left');
        side_panel.removeClass('col-lg-4');
        side_panel.hide();
        map_div.removeClass('col-lg-8');
        map_div.addClass('col-lg-12');
        map.invalidateSize();
    } else { /* show */
        show_hide_div.addClass('glyphicon-chevron-right');
        show_hide_div.removeClass('glyphicon-chevron-left');
        side_panel.addClass('col-lg-4');
        side_panel.show();
        map_div.removeClass('col-lg-12');
        map_div.addClass('col-lg-8');
        map.invalidateSize();
    }
}

function show_map() {
    'use strict';
    $('#navigationbar').css('height', window.innerHeight * 0.1);
    $('#map').css('height', window.innerHeight * 0.9);
    map = L.map('map').setView([-33.9200, 18.8600], 8);
    L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpeg', {
        attribution: 'Tiles by MapQuest — Map data © OpenStreetMap contributors, CC-BY-SA',
        subdomains: '1234'
    }).addTo(map);

    // make popup center on open
    map.on('popupopen', function (e) {
        var px = map.project(e.popup._latlng); // find the pixel location on the map where the popup anchor is
        px.y -= e.popup._container.clientHeight / 2; // find the height of
        // the popup container, divide by 2, subtract from the Y axis of marker location
        map.panTo(map.unproject(px), {animate: true}); // pan to new center
        var icon;
        var marker = e.popup._source;
        if (marker._public_institute) {
            icon = highlightMarkerIcon;
        } else {
            icon = highlightMarkerPrivateInstitutionIcon;
        }
        marker.setIcon(icon);
    });
    map.on('popupclose', function(e) {
        var icon;
        var marker = e.popup._source;
        if (marker._public_institute) {
            icon = markerIcon;
        } else {
            icon = markerPrivateInstitutionIcon;
        }
        marker.setIcon(icon);
    });

    // create geoJson Layer
    campus_layer = L.geoJson(null, {
        pointToLayer: function (feature, latlng) {
            var icon;
            if (feature.properties.public_institute) {
                icon = markerIcon;
            } else {
                icon = markerPrivateInstitutionIcon;
            }
            var marker = L.marker(latlng, {
                icon: icon
            });
            marker._public_institute = feature.properties.public_institute;
            return L.featureGroup([marker]);
        },
        style: style,
        onEachFeature: onEachFeature
    }).addTo(map);

    // Add share control
    map.addControl(new L.Control.Share());
    var legend = L.control({position: 'bottomleft'});
    legend.onAdd = function (map) {
        var div = L.DomUtil.create('div', 'info legend');
            var public_marker = markerIcon.createIcon();
            public_marker.style.transform = "translate(15px, 0px)";
            var private_marker = markerPrivateInstitutionIcon.createIcon();
            private_marker.style.transform = "translate(60px, 0px)";
            div.innerHTML += (
                "
" +
                "
Public - Private" +
                "
" +
                "
" +
                "
" +
                public_marker.outerHTML +
                private_marker.outerHTML +
                "
");

        return div;
        };
    legend.addTo(map);
}

/*jslint unparam: true*/
function style(feature) {
    'use strict';
    return {
        weight: 2,
        opacity: 1,
        color: 'blue',
        dashArray: '',
        fillOpacity: 0.5,
        fillColor: 'blue'
    };
}
/*jslint unparam: false*/

function highlightFeature(e) {
    'use strict';
    var layer = e.target;
    if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
    }
}

function resetHighlight(e) {
    'use strict';
    //var marker = e.target;
    //marker.setIcon(markerIcon);
    var layer = e.target;
}

function zoomToFeature(e) {
    'use strict';
    var layer = e.target;
    map.fitBounds(layer.getBounds(), fit_bounds_options);
}

/*jslint unparam: true*/
function onEachFeature(feature, layer) {
    'use strict';
    layer.bindPopup(feature.properties.popup_content);
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        dblclick: zoomToFeature
    });
    campus_features[feature.properties.id] = layer;
}
/*jslint unparam: false*/

function set_offset() {
    'use strict';
    var navbar, navbar_height, map, content, map_offset, content_offset;
    navbar = $('.navbar');
    navbar_height = navbar.height();
    map = $('#map');
    content = $('#content');

    if (map.length) {
        map_offset = map.offset();
        map.offset({top: navbar_height, left: map_offset.left});
    }
    if (content.length) {
        content_offset = content.offset();
        content.offset({top: navbar_height, left: content_offset.left});
    }

}

function add_campus(campus_json, campus_id, public_institute) {
    'use strict';
    campus_json.features[0].properties.id = campus_id;
    campus_json.features[0].properties.public_institute = public_institute;
    campus_layer.addData(campus_json);
    campus_lookup[campus_id] = campus_json;
}

function SelectFeature(campus_id) {
    try {
        var feature = campus_lookup[campus_id].features[0];
        var coordinate = feature.geometry.coordinates;
        feature.properties.selected = true;
        var e = {
            target: campus_features[feature.properties.id]
        };
        if (highlighted_feature) {
            resetHighlight(highlighted_feature);
        }
        highlightFeature(e);
        highlighted_feature = e;
        zoomToFeature(e);
        openCampusPopup(campus_id);
    }
    catch (e) {
        console.log(e);
    }
}

function CampusItemToggle(el) {
    var panel = $(el).closest('.panel-primary').find('.panel-collapse');
    panel.toggleClass('collapse');
    var icon = $(el).find("i");
    if (panel.hasClass('collapse')) {
        icon.removeClass('mdi-navigation-expand-less');
        icon.addClass('mdi-navigation-expand-more');
    }
    else {
        icon.removeClass('mdi-navigation-expand-more');
        icon.addClass('mdi-navigation-expand-less');
    }
}

function openCampusPopup(campus_id) {
    var feature = campus_features[campus_id];
    feature.openPopup();
}

/* Search bar logic */
function initSearchTermChanged() {
    var terms = $("#search-terms").val();
    var search_clear = $("#search-clear");
    var search_terms = $("#search-terms");
    if (search_terms.val().length == 0) {
        search_clear.hide();
    }
    search_terms.keyup(function (e) {
        var terms = search_terms.val()
        if (terms.length == 0) {
            search_clear.hide();
        }
        else {
            search_clear.show();
        }
    });
    search_clear.click(function (e) {
        e.preventDefault();
        search_terms.val("");
        search_clear.hide();
    });
}


text:
{{<govuk_template}}

{{$head}}
  {{>includes/elements_head}}

    <link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />

{{/head}}

{{$propositionHeader}}
  {{>includes/govuk_firstregprop}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

  Back

   to the previous question

  <form action="q1-flow" method="get" class="form">

    {{#vars}}
    <input type="hidden" name="importer" value="{{importer}}">
    {{/vars}}

    <input type="hidden" name="nextlink" value="q3-newness">

      VAT: Have you notified the HMRC using NOVA?

      <input id="radio-inline-1" type="radio" name="vat" value="no">
      No

      <input id="radio-inline-2" type="radio" name="vat" value="yes">
      Yes

      <input type="submit" class="button" value="Continue">

        Previous answers

      {{#vars}}

        Who is importing the vehicle?
        {{importer}}
        Change

    {{/vars}}

Start again

  </form>

{{/content}}

{{$bodyEnd}}
  {{>includes/elements_scripts}}
{{/bodyEnd}}

{{/govuk_template}}


text:
package org.kie.remote.services.rest.api;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;

@Path("/task")
@Api(value="/task", description="Human Task operations")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public interface TaskResource {

    @GET
    @Path("/query")
    @Deprecated
    @ApiOperation(value = "Query tasks",
        notes = "Returns a list of TaskSummary instances")
    public Response query();

    @GET
    @Path("/{taskId: [0-9-]+}")
    @ApiOperation(value = "Get a specific task",
        notes = "Returns a Task")
    @ApiResponses(value = {
            @ApiResponse(code = 404, message = "Task can not be found") })
    public Response getTask( @PathParam("taskId") long taskId );

    @POST
    @Path("/{taskId: [0-9-]+}/{oper: [a-zA-Z]+}")
    @ApiOperation(value = "Get a specific task",
        notes = "Returns a Task")
    @ApiResponses(value = {
            @ApiResponse(code = 404, message = "Task can not be found") })
    public Response doTaskOperation(
            @PathParam("taskId") long taskId,
            @ApiParam(value = "Operation names", required = true,
            allowableValues = "activate, claim, claimnextavailable, complete, delegate, exit, fail, forward, nominate, release, resume, skip, start, stop, suspend",
            allowMultiple = false)
            @PathParam("oper") String operation );

    @GET
    @Path("/{taskId: [0-9-]+}/content")
    @ApiOperation(value = "Get the content associated with a specific task",
    notes = "Returns Task content")
    @ApiResponses(value = {
            @ApiResponse(code = 404, message = "Task can not be found") })
    public Response getTaskContentByTaskId( @PathParam("taskId") long taskId );

    @GET
    @Path("/{taskId: [0-9-]+}/showTaskForm")
    public Response getTaskFormByTaskId( @PathParam("taskId") long taskId );

    @GET
    @Path("/content/{contentId: [0-9-]+}")
    @ApiOperation(value = "Get a specific task content",
        notes = "Returns task content")
    @ApiResponses(value = {
            @ApiResponse(code = 404, message = "Content can not be found") })
    public Response getTaskContentByContentId( @PathParam("contentId") long contentId );

    @POST
    @Path("/history/bam/clear")
    public Response clearTaskBamHistory();

}