text:
package io.druid.segment.data;

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.Clock;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.druid.java.util.common.StringUtils;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

// AbstractBenchmark makes this ignored unless explicitly run
@RunWith(Parameterized.class)
public class BenchmarkIndexibleWrites extends AbstractBenchmark
{
  @Parameterized.Parameters
  public static Collection<Object[]> getParameters()
  {
    return ImmutableList.<Object[]>of(
        new Object[]{new ConcurrentStandardMap<Integer>()},
        new Object[]{new ConcurrentExpandable<Integer>()}
    );
  }

  public BenchmarkIndexibleWrites(ConcurrentIndexible<Integer> concurrentIndexible)
  {
    this.concurrentIndexible = concurrentIndexible;
  }

  private static interface ConcurrentIndexible<V>
  {
    public void set(Integer index, V object);

    public V get(Integer index);

    public void clear();
  }

  private static class ConcurrentStandardMap<V> implements ConcurrentIndexible<V>
  {
    private final ConcurrentHashMap<Integer, V> delegate = new ConcurrentHashMap<>();

    @Override
    public void set(Integer index, V object)
    {
      delegate.put(index, object);
    }

    @Override
    public V get(Integer index)
    {
      return delegate.get(index);
    }

    @Override
    public void clear()
    {
      delegate.clear();
    }
  }

  private static class ConcurrentExpandable<V> implements ConcurrentIndexible<V>
  {
    private static Integer INIT_SIZE = 1 << 10;
    private final AtomicReference<V[]> reference = new AtomicReference<>();
    private final AtomicLong resizeCount = new AtomicLong(0);
    private final Integer initSize;

    public ConcurrentExpandable()
    {
      this(INIT_SIZE);
    }

    @SuppressWarnings("unchecked")
    public ConcurrentExpandable(Integer initSize)
    {
      reference.set((V[]) new Object[initSize]);
      this.initSize = initSize;
    }

    @Override
    public V get(Integer index)
    {
      return reference.get()[index];
    }

    @SuppressWarnings("unchecked")
    @Override
    public void clear()
    {
      reference.set((V[]) new Object[initSize]);
    }

    private static Boolean wasCopying(Long val)
    {
      return (val & 1L) > 0;
    }

    @Override
    public void set(Integer index, V object)
    {
      ensureCapacity(index + 1);
      Long pre, post;
      do {
        pre = resizeCount.get();
        reference.get()[index] = object;
        post = resizeCount.get();
      } while (wasCopying(pre) || wasCopying(post) || (!pre.equals(post)));
    }

    private final Object resizeMutex = new Object();

    private void ensureCapacity(int capacity)
    {
      synchronized (resizeMutex) {
        if (reference.get().length < capacity) {
          // We increment twice per resize. Once before the copy starts and once after the swap.
          //
          // Any task who sees a resizeCount which is *odd* between the start and stop of their critical section
          // has access to a nebulous aggList and should try again
          //
          // Any task who sees a resizeCount which changes between the start and stop of their critical section
          // should also try again
          resizeCount.incrementAndGet();
          reference.set(Arrays.copyOf(reference.get(), reference.get().length<<1));
          resizeCount.incrementAndGet();
        }
      }
    }
  }

  private final ConcurrentIndexible<Integer> concurrentIndexible;
  private final Integer concurrentThreads = 1<<2;
  private final Integer totalIndexSize = 1<<20;

  @BenchmarkOptions(warmupRounds = 100, benchmarkRounds = 100, clock = Clock.REAL_TIME, callgc = true)
  @Ignore @Test
  /**
   * CALLEN - 2015-01-15 - OSX - Java 1.7.0_71-b14
   BenchmarkIndexibleWrites.testConcurrentWrites[0]: [measured 100 out of 200 rounds, threads: 1 (sequential)]
   round: 0.24 [+- 0.01], round.block: 0.00 [+- 0.00], round.gc: 0.02 [+- 0.00], GC.calls: 396, GC.time: 1.88, time.total: 50.60, time.warmup: 24.84, time.bench: 25.77
   BenchmarkIndexibleWrites.testConcurrentWrites[1]: [measured 100 out of 200 rounds, threads: 1 (sequential)]
   round: 0.15 [+- 0.01], round.block: 0.00 [+- 0.00], round.gc: 0.02 [+- 0.00], GC.calls: 396, GC.time: 2.11, time.total: 33.14, time.warmup: 16.09, time.bench: 17.05
   */
  public void testConcurrentWrites() throws ExecutionException, InterruptedException
  {
    final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(
        Executors.newFixedThreadPool(
            concurrentThreads,
            new ThreadFactoryBuilder()
                .setDaemon(false)
                .setNameFormat("indexible-writes-benchmark-%d")
                .build()
        )
    );
    final AtomicInteger index = new AtomicInteger(0);
    List<ListenableFuture<?>> futures = new LinkedList<>();

    final Integer loops = totalIndexSize / concurrentThreads;

    for (int i = 0; i < concurrentThreads; ++i) {
      futures.add(
          executorService.submit(
              new Runnable()
              {
                @Override
                public void run()
                {
                  for (int i = 0; i < loops; ++i) {
                    final Integer idx = index.getAndIncrement();
                    concurrentIndexible.set(idx, idx);
                  }
                }
              }
          )
      );
    }
    Futures.allAsList(futures).get();
    Assert.assertTrue(StringUtils.format("Index too small %d, expected %d across %d loops", index.get(), totalIndexSize, loops), index.get() >= totalIndexSize);
    for(int i = 0; i < index.get(); ++i){
      Assert.assertEquals(i, concurrentIndexible.get(i).intValue());
    }
    concurrentIndexible.clear();
    futures.clear();
    executorService.shutdown();
  }

  /**
   BenchmarkIndexibleWrites.TestConcurrentReads[0]: [measured 100 out of 200 rounds, threads: 1 (sequential)]
   round: 0.28 [+- 0.02], round.block: 0.00 [+- 0.00], round.gc: 0.02 [+- 0.00], GC.calls: 396, GC.time: 1.84, time.total: 59.98, time.warmup: 30.51, time.bench: 29.48
   BenchmarkIndexibleWrites.TestConcurrentReads[1]: [measured 100 out of 200 rounds, threads: 1 (sequential)]
   round: 0.12 [+- 0.01], round.block: 0.00 [+- 0.00], round.gc: 0.02 [+- 0.00], GC.calls: 396, GC.time: 2.05, time.total: 29.21, time.warmup: 14.65, time.bench: 14.55

   */
  @BenchmarkOptions(warmupRounds = 100, benchmarkRounds = 100, clock = Clock.REAL_TIME, callgc = true)
  @Ignore @Test
  public void testConcurrentReads() throws ExecutionException, InterruptedException
  {
    final ListeningExecutorService executorService = MoreExecutors.listeningDecorator(
        Executors.newFixedThreadPool(
            concurrentThreads,
            new ThreadFactoryBuilder()
                .setDaemon(false)
                .setNameFormat("indexible-writes-benchmark-reader-%d")
                .build()
        )
    );
    final AtomicInteger index = new AtomicInteger(0);
    final AtomicInteger queryableIndex = new AtomicInteger(0);
    List<ListenableFuture<?>> futures = new LinkedList<>();

    final Integer loops = totalIndexSize / concurrentThreads;

    final AtomicBoolean done = new AtomicBoolean(false);

    final CountDownLatch start = new CountDownLatch(1);

    for (int i = 0; i < concurrentThreads; ++i) {
      futures.add(
          executorService.submit(
              new Runnable()
              {
                @Override
                public void run()
                {
                  try {
                    start.await();
                  }
                  catch (InterruptedException e) {
                    throw Throwables.propagate(e);
                  }
                  final Random rndGen = new Random();
                  while(!done.get()){
                    Integer idx = rndGen.nextInt(queryableIndex.get() + 1);
                    Assert.assertEquals(idx, concurrentIndexible.get(idx));
                  }
                }
              }
          )
      );
    }

    {
      final Integer idx = index.getAndIncrement();
      concurrentIndexible.set(idx, idx);
      start.countDown();
    }
    for (int i = 1; i < totalIndexSize; ++i) {
      final Integer idx = index.getAndIncrement();
      concurrentIndexible.set(idx, idx);
      queryableIndex.incrementAndGet();
    }
    done.set(true);

    Futures.allAsList(futures).get();
    executorService.shutdown();

    Assert.assertTrue(StringUtils.format("Index too small %d, expected %d across %d loops", index.get(), totalIndexSize, loops), index.get() >= totalIndexSize);
    for(int i = 0; i < index.get(); ++i){
      Assert.assertEquals(i, concurrentIndexible.get(i).intValue());
    }
    concurrentIndexible.clear();
    futures.clear();
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright SemanticBits, Northwestern University and Akaza Research

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/caaers/LICENSE.txt for details.
-->
<CQLQuery xmlns="http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLQuery" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://CQL.caBIG/1/gov.nih.nci.cagrid.CQLQuery
C:\caGrid\cagrid-1-0\caGrid\projects\data\schema\Data\1_gov.nih.nci.cagrid.CQLQuery.xsd">
	<Target name="gov.nih.nci.cabio.domain.Gene">
		<Group logicRelation="AND">
			<Attribute name="symbol" value="BRCA%" predicate="LIKE"/>
		</Group>
	</Target>
</CQLQuery>

redpajama_set_name: RedPajamaGithub


text:
#import <Foundation/Foundation.h>

@interface NSDictionary (ZH)
/**将字典Data转换成NSDictionary*/
+ (NSDictionary *)dictionaryWithPlistData:(NSData *)plist;
/**将字典NSString转换成NSDictionary*/
+ (NSDictionary *)dictionaryWithPlistString:(NSString *)plist;

/**将字典转换成xml(plistData)*/
- (NSData *)plistData;

/**将字典转换成xml(plist字符串)*/
- (NSString *)plistString;

/**所有的keys值通过字符字典序列进行排序*/
- (NSArray *)allKeysSorted;

/**因为字典是无序的,所以在这里对keys进行排序,根据排序好的key对应的value组成数组并返回*/
- (NSArray *)allValuesSortedByKeys;

/**判断是否包含某个key值对应的value*/
- (BOOL)containsObjectForKey:(id)key;

/**拿出keys对应的value重新组成一个字典返回*/
- (NSDictionary *)entriesForKeys:(NSArray *)keys;

/**将字典转换过成json字符串,但是是一串没有格式化的字符串*/
- (NSString *)jsonStringEncoded;

/**将字典转换过成json字符串,并把json字符串格式化*/
- (NSString *)jsonPrettyStringEncoded;

/**将xml转换成NSDictionary*/
+ (NSDictionary *)dictionaryWithXML:(id)xml;

- (BOOL)boolValueForKey:(NSString *)key default:(BOOL)def;

- (char)charValueForKey:(NSString *)key default:(char)def;

- (unsigned char)unsignedCharValueForKey:(NSString *)key default:(unsigned char)def;

- (short)shortValueForKey:(NSString *)key default:(short)def;

- (unsigned short)unsignedShortValueForKey:(NSString *)key default:(unsigned short)def;

- (int)intValueForKey:(NSString *)key default:(int)def;

- (unsigned int)unsignedIntValueForKey:(NSString *)key default:(unsigned int)def;

- (long)longValueForKey:(NSString *)key default:(long)def;

- (unsigned long)unsignedLongValueForKey:(NSString *)key default:(unsigned long)def;

- (long long)longLongValueForKey:(NSString *)key default:(long long)def;

- (unsigned long long)unsignedLongLongValueForKey:(NSString *)key default:(unsigned long long)def;

- (float)floatValueForKey:(NSString *)key default:(float)def;

- (double)doubleValueForKey:(NSString *)key default:(double)def;

- (NSInteger)integerValueForKey:(NSString *)key default:(NSInteger)def;

- (NSUInteger)unsignedIntegerValueForKey:(NSString *)key default:(NSUInteger)def;

/**如果key值对应的value为NSNumber或者NSString类型的返回对应的NSNumber,否则返回默认的def
 这个一般用于获取json数据中的某个字段,如果这个字段不存在或者这个字段是number类型的,都可以进行防崩溃处理
 还可以不用我们去判断某个字段是字符串时需要转换成那种number类型
 */
- (NSNumber *)numberValueForKey:(NSString *)key default:(NSNumber *)def;

/**如果key值对应的value为String或者number类型的返回对应的NSSTring,否则返回默认的def
 这个一般用于获取json数据中的某个字段,如果这个字段不存在或者这个字段是number类型的,都可以进行防崩溃处理
 */
- (NSString *)stringValueForKey:(NSString *)key default:(NSString *)def;
@end

@interface NSMutableDictionary (ZH)
/**将字典Data转换成NSMutableDictionary*/
+ (NSMutableDictionary *)dictionaryWithPlistData:(NSData *)plist;

/**将plist文件数据转换成字典,先会进行尝试,如果发现plist文件数据存放的是字典,就返回解析数据*/
+ (NSMutableDictionary *)dictionaryWithPlistString:(NSString *)plist;

/**pop出一个元素,根据key值*/
- (id)popObjectForKey:(id)aKey;

/**pop出多个元素,根据keys值*/
- (NSDictionary *)popEntriesForKeys:(NSArray *)keys;
@end


text:
@startDocuBlock GetApiQueryProperties
@brief returns the configuration for the AQL query tracking

@RESTHEADER{GET /_api/query/properties, Returns the properties for the AQL query tracking, readQueryProperties}

@RESTDESCRIPTION
Returns the current query tracking configuration. The configuration is a
JSON object with the following properties:

- *enabled*: if set to *true*, then queries will be tracked. If set to
  *false*, neither queries nor slow queries will be tracked.

- *trackSlowQueries*: if set to *true*, then slow queries will be tracked
  in the list of slow queries if their runtime exceeds the value set in
  *slowQueryThreshold*. In order for slow queries to be tracked, the *enabled*
  property must also be set to *true*.

- *trackBindVars*: if set to *true*, then bind variables used in queries will
  be tracked.

- *maxSlowQueries*: the maximum number of slow queries to keep in the list
  of slow queries. If the list of slow queries is full, the oldest entry in
  it will be discarded when additional slow queries occur.

- *slowQueryThreshold*: the threshold value for treating a query as slow. A
  query with a runtime greater or equal to this threshold value will be
  put into the list of slow queries when slow query tracking is enabled.
  The value for *slowQueryThreshold* is specified in seconds.

- *maxQueryStringLength*: the maximum query string length to keep in the
  list of queries. Query strings can have arbitrary lengths, and this property
  can be used to save memory in case very long query strings are used. The
  value is specified in bytes.

@RESTRETURNCODES

@RESTRETURNCODE{200}
Is returned if properties were retrieved successfully.

@RESTRETURNCODE{400}
The server will respond with *HTTP 400* in case of a malformed request,

@endDocuBlock


text:
    <button type="button" class="close"
        data-ng-click="cancel()"
    >
        ×
        Close
    </button>

Change file '{{file.name}}' contents

    <form role="form">

            File contents
            <textarea id="fileContent" class="form-control" rows="8"
                data-ng-model="file.data"
            ></textarea>

    </form>

    <button class="btn btn-primary"
        data-ng-click="save(false)"
    >
        Save
    </button>

    <button class="btn btn-primary"
            data-ng-click="save(true)"
            >
        Save and close
    </button>

    <button class="btn btn-default pull-left"
        data-ng-click="cancel()"
    >
        Cancel
    </button>


text:
require "formula"

class Activemq < Formula
  homepage "http://activemq.apache.org/"
  url "http://www.apache.org/dyn/closer.cgi?path=/activemq/5.10.2/apache-activemq-5.10.2-bin.tar.gz"
  sha1 "7b5d797abf6d6767d2f5a17935d8cac829d230cd"

  def install
    rm_rf Dir["bin/linux-x86-*"]

    prefix.install_metafiles
    libexec.install Dir["*"]

    bin.write_exec_script libexec/"bin/activemq"
    bin.write_exec_script libexec/"bin/activemq-admin"
  end
end


text:
<?php

namespace Intervention\Image\Gd\Commands;

class WidenCommand extends ResizeCommand
{
    /**
     * Resize image proportionally to given width
     *
     * @param  \Intervention\Image\Image $image
     * @return boolean
     */
    public function execute($image)
    {
        $width = $this->argument(0)->type('digit')->required()->value();
        $additionalConstraints = $this->argument(1)->type('closure')->value();

        $this->arguments[0] = $width;
        $this->arguments[1] = null;
        $this->arguments[2] = function ($constraint) use ($additionalConstraints) {
            $constraint->aspectRatio();
            if (is_callable($additionalConstraints))
                $additionalConstraints($constraint);
        };

        return parent::execute($image);
    }
}


text:
package org.apache.camel.component.file;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit test that checks for the existence of the CamelFileNameConsumed header.
 */
public class FileConsumerConsumedFileNameTest extends ContextTestSupport {

    @Override
    @Before
    public void setUp() throws Exception {
        deleteDirectory("target/data/consumedfilename");
        super.setUp();
    }

    @Test
    public void testValidFilenameOnExchange() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.message(0).header(Exchange.FILE_NAME).isEqualTo("hello.txt");
        mock.message(0).header(Exchange.FILE_NAME_CONSUMED).isEqualTo("hello.txt");

        // the file name is also starting with target/data/consumedfilename
        template.sendBodyAndHeader("file:target/data/consumedfilename", "Hello World", Exchange.FILE_NAME, "hello.txt");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("file:target/data/consumedfilename?initialDelay=0&delay=10").to("mock:result");
            }
        };
    }

}


text:
package com.mossle.bpm.listener;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import com.mossle.bpm.persistence.domain.BpmConfUser;
import com.mossle.bpm.persistence.manager.BpmConfUserManager;
import com.mossle.bpm.support.DefaultTaskListener;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfUserTaskListener extends DefaultTaskListener {
    private static Logger logger = LoggerFactory
            .getLogger(ConfUserTaskListener.class);
    private BpmConfUserManager bpmConfUserManager;

    @Override
    public void onCreate(DelegateTask delegateTask) throws Exception {
        List<BpmConfUser> bpmConfUsers = bpmConfUserManager
                .find("from BpmConfUser where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
                        delegateTask.getProcessDefinitionId(), delegateTask
                                .getExecution().getCurrentActivityId());
        logger.debug("{}", bpmConfUsers);

        ExpressionManager expressionManager = Context
                .getProcessEngineConfiguration().getExpressionManager();

        try {
            for (BpmConfUser bpmConfUser : bpmConfUsers) {
                logger.debug("status : {}, type: {}", bpmConfUser.getStatus(),
                        bpmConfUser.getType());
                logger.debug("value : {}", bpmConfUser.getValue());

                String value = expressionManager
                        .createExpression(bpmConfUser.getValue())
                        .getValue(delegateTask).toString();

                if (bpmConfUser.getStatus() == 1) {
                    if (bpmConfUser.getType() == 0) {
                        delegateTask.setAssignee(value);
                    } else if (bpmConfUser.getType() == 1) {
                        delegateTask.addCandidateUser(value);
                    } else if (bpmConfUser.getType() == 2) {
                        delegateTask.addCandidateGroup(value);
                    }
                } else if (bpmConfUser.getStatus() == 2) {
                    if (bpmConfUser.getType() == 0) {
                        if (delegateTask.getAssignee().equals(value)) {
                            delegateTask.setAssignee(null);
                        }
                    } else if (bpmConfUser.getType() == 1) {
                        delegateTask.deleteCandidateUser(value);
                    } else if (bpmConfUser.getType() == 2) {
                        delegateTask.deleteCandidateGroup(value);
                    }
                }
            }
        } catch (Exception ex) {
            logger.debug(ex.getMessage(), ex);
        }
    }

    @Resource
    public void setBpmConfUserManager(BpmConfUserManager bpmConfUserManager) {
        this.bpmConfUserManager = bpmConfUserManager;
    }
}


text:
package com.gxq.learn.recontool.utils

import org.apache.spark.sql.types.IntegerType
import org.apache.spark.sql.types.TimestampType
import org.apache.spark.sql.types.DoubleType
import org.apache.spark.sql.types.DateType
import org.apache.spark.sql.types.DecimalType
import org.apache.spark.sql.types.ByteType
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.types.FloatType
import org.apache.spark.sql.types.ShortType
import org.apache.spark.sql.types.StringType
import org.apache.spark.sql.types.LongType
import org.apache.spark.sql.types.BooleanType
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.Metadata
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.Dataset
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.Row

object ReconUtil {
  def typeConvert(field: StructField) = {
    field.dataType match {
      case IntegerType => "INTEGER"
      case LongType    => "BIGINT"
      case DoubleType  => "DOUBLE PRECISION"
      case FloatType   => "REAL"
      case ShortType   => "INTEGER"
      case ByteType    => "SMALLINT" // Redshift does not support the BYTE type.
      case BooleanType => "BOOLEAN"
      case StringType =>
        if (field.metadata.contains("maxlength")) {
          s"VARCHAR(${field.metadata.getLong("maxlength")})"
        } else {
          "TEXT"
        }
      case TimestampType  => "TIMESTAMP"
      case DateType       => "DATE"
      case t: DecimalType => s"DECIMAL(${t.precision},${t.scale})"
      case _              => throw new IllegalArgumentException(s"Don't know how to save $field to JDBC")
    }
  }

  def getFileName(filePath: String) = {
    filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."))
  }

  def validateFilePath(filePath: String) = {
    Option(filePath) match {
      case Some(p) if (p.contains('.')) => p
      case None                         => throw new IllegalArgumentException("file path is empty, Please check...")
      case _                            => throw new IllegalArgumentException("file doesn't have extension Name(***.csv or ***.json). Please check...")
    }
  }

  def getTitleSchema(schemasMap: Map[String, String], titleArray: Array[String]): StructType = {
    val sFields = new Array[StructField](titleArray.length)
    for (i <- 0 until titleArray.length) {
      val dateTypeOption = schemasMap.get(titleArray(i))
      dateTypeOption match {
        case Some("Byte")       => sFields(i) = StructField(titleArray(i), ByteType, true, Metadata.empty)
        case Some("Short")      => sFields(i) = StructField(titleArray(i), ShortType, true, Metadata.empty)
        case Some("Int")        => sFields(i) = StructField(titleArray(i), IntegerType, true, Metadata.empty)
        case Some("Long")       => sFields(i) = StructField(titleArray(i), LongType, true, Metadata.empty)
        case Some("Float")      => sFields(i) = StructField(titleArray(i), FloatType, true, Metadata.empty)
        case Some("Double")     => sFields(i) = StructField(titleArray(i), DoubleType, true, Metadata.empty)
        case Some("Boolean")    => sFields(i) = StructField(titleArray(i), BooleanType, true, Metadata.empty)
        case Some("Timestamp")  => sFields(i) = StructField(titleArray(i), TimestampType, true, Metadata.empty)
        case Some("Date")       => sFields(i) = StructField(titleArray(i), DateType, true, Metadata.empty)
        case Some("BigDecimal") => sFields(i) = StructField(titleArray(i), DoubleType, true, Metadata.empty)
        case None               => sFields(i) = StructField(titleArray(i), StringType, true, Metadata.empty)
        case _                  => throw new IllegalArgumentException(dateTypeOption.toString() + " is not support.")
      }
    }
    val titleSchema = new StructType(sFields)
    titleSchema
  }

  def keyPrioritized(keysArray: Array[String], titleArray: Array[String]): Array[String] = {
    titleArray.filter(p => !keysArray.contains(p)).++:(keysArray)
  }

  private def rddDataConvert(titleArray: Array[String], schemasMap: Map[String, String], sourceRDD: RDD[String]): RDD[Row] = {
    sourceRDD.map(_.split(",", -1)).map(p => for (i <- 0 until p.length) yield {
      val dateType = schemasMap.get(titleArray(i))
      dateType match {
        case Some("Byte")       => { p(i).trim().toByte }
        case Some("Short")      => { this.processNull(p(i).trim()).toShort }
        case Some("Int")        => { this.processNull(p(i).trim()).toInt }
        case Some("Long")       => { this.processNull(p(i).trim()).toLong }
        case Some("Float")      => { this.processNull(p(i).trim()).toFloat }
        case Some("Double")     => { this.processNull(p(i).trim()).toDouble }
        case Some("Boolean")    => { this.processNull(p(i).trim()).toBoolean }
        case Some("BigDecimal") => { this.processNull(p(i).trim()).toDouble }
        case None               => { p(i).trim }
        case _                  => { p(i).trim }
      }
    }).map(Row(_: _*))
  }

  private def processNull(value: String): String = {
    var temp = value
    if (temp == "") {
      temp = "0"
    }
    temp
  }

  def createDataFrame(titleSchema: StructType, tableRDD: RDD[String], titleArray: Array[String], schemasMap: Map[String, String], ss: SparkSession, viewName: String): Dataset[Row] = {
    val tableFirst = tableRDD.first();
    val filterRDD = tableRDD.filter(_ != tableFirst)
    val tableDataRDD = this.rddDataConvert(titleArray, schemasMap, filterRDD)
    val tableDataDF = ss.createDataFrame(tableDataRDD, titleSchema)
    tableDataDF.createTempView(viewName)
    //tableDataDF.show()
    tableDataDF
  }
}


text:
package net.za.slyfox.minecraft.region;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.za.slyfox.minecraft.nbt.NbtCompound;
import net.za.slyfox.minecraft.nbt.NbtReader;
import net.za.slyfox.minecraft.nbt.spi.NbtProvider;

public class RegionReader {

	private final ChunkDataHeaderReader chunkDataHeaderReader;
	private final Logger log = LoggerFactory.getLogger(getClass());
	private final RegionHeaderReader regionHeaderReader;

	@Inject
	public RegionReader(ChunkDataHeaderReader chunkDataHeaderReader, RegionHeaderReader regionHeaderReader) {

		this.chunkDataHeaderReader = chunkDataHeaderReader;
		this.regionHeaderReader = regionHeaderReader;
	}

	public Region read(ByteBuffer buffer) {

		Region region = new Region();
		RegionHeader regionHeader = regionHeaderReader.read(buffer);
		region.setRegionHeader(regionHeader);
		return region;
	}

	public NbtCompound readChunk(ByteBuffer buffer, Region region, int x, int z) throws IOException {

		buffer.position((int)region.getRegionHeader().getOffset(x, z));
		ChunkDataHeader chunkDataHeader = chunkDataHeaderReader.read(buffer);

		ByteBuffer chunkBuffer = buffer.duplicate();
		chunkBuffer.limit(chunkBuffer.position() + chunkDataHeader.getSize());
		InputStream inputStream = new ByteBufferInputStream(chunkBuffer);
		switch(chunkDataHeader.getCompressionType()) {
			case GZIP:
				log.debug("Using GZIP compression");
				inputStream = new GZIPInputStream(inputStream);
				break;

			case ZLIB:
				log.debug("Using ZLIB compression");
				inputStream = new InflaterInputStream(inputStream);
				break;

			default:
				log.debug("Unknown compression type");
				break;
		}

		NbtReader nbtReader = NbtProvider.provider().createReader(inputStream);
		return nbtReader.read();
	}

	private static class ByteBufferInputStream extends InputStream {

		private final ByteBuffer buffer;

		public ByteBufferInputStream(ByteBuffer buffer) {

			this.buffer = buffer.duplicate();
		}

		@Override
		public int read() throws IOException {

			if(!buffer.hasRemaining()) {
				return -1;
			}

			return buffer.get();
		}

		@Override
		public int read(byte[] b) throws IOException {

			if(b.length == 0) {
				return 0;
			} else if(!buffer.hasRemaining()) {
				return -1;
			}

			int length = Math.min(b.length, buffer.remaining());
			buffer.get(b, 0, length);
			return length;
		}

		@Override
		public int read(byte[] b, int off, int len) throws IOException {

			if(len == 0) {
				return 0;
			} else if(!buffer.hasRemaining()) {
				return -1;
			}

			int length = Math.min(len, buffer.remaining());
			buffer.get(b, off, length);
			return length;
		}
	}
}


text:
title: Spring Break 2015 plans
categories:
    - echolink
---

We plan to put a simplex Echolink W1BUR-L on the air from a temporary antenna until we can get access to the rooftop antenna connection in the early summer.
This temporary setup will hopefully occur by March 2015.


text:
import irc

def parse_nick(nick):
	""" Separates nick from the mode characters.

	Examples:
		parse_nick('@_markus') => (_markus, 'o')
		parse_nick('+_markus') => ('_markus', 'v')
	"""

	converter = {'@' : 'o', '+' : 'v'}

	modes = converter.keys()
	first_character = nick[0]
	if first_character in modes:
		return (nick[1:], converter[first_character])
	else:
		return (nick, None)

def parse_nick_from_prefix(prefix):
	""" Parse nick from the beginning of message prefix

	Used by JOIN and PART message handlers.
	"""
	end_index  = prefix.find('!')
	return prefix[0:end_index]

def parse_messages_from(data):
	""" Separate server messages
	"""
	return data.split('\r\n')

def parse_message(message):
	""" Parse messages from IRC server.

	Message format is:
		[:prefix] command [[param1] param2] [:trailing]
	Only command is mandatory, other parts are optional.

	Args:
		Message: Server message that'll be parsed

	Returns:
		Message object containing the parsed information.

	"""
	if not message or message == '':
		return None

	prefix, command, params, trailing = None, None, None, None

	# parse prefix
	if message[0] == ':':
		end_index = message.find(' ')
		prefix = message[1:end_index]
		# remove the parsed section of the message and the whitespace
		message = message[end_index + 1:]

	# parse trailing
	start_index_of_trailing = message.find(':')
	if start_index_of_trailing != -1: # has trailing
		trailing = message[start_index_of_trailing + 1:]
		# update the message, only command and params left
		message = message[0:start_index_of_trailing]

	# remove redundant white space
	message = message.strip(' ')

	command_and_params = message.split(' ')
	command = command_and_params[0]
	params = command_and_params[1:]

	return irc.Message(prefix, command, params, trailing)


text:
package examples.demo

import java.awt.Dimension

import examples.demo.ui.{Circle, Shape, ShapesPanel}
import rescala._

import scala.swing.{MainFrame, SimpleSwingApplication, UIElement}

/**
  * So far, we showed Vars and Signals defined as a transformation
  * of one other Var or Signal. Signals can, however, also be derived
  * from a combination of multiple other Vars and Signals through
  * Signal expressions. To demonstrate Signal expressions, we extend
  * our animation to scale the moving circle's trajectory with the
  * drawing panel's size.
  *
  * The ShapePanel class offers Signals width and height, that
  * reflect the panel's current size at any point in time, similar
  * to how nsTime always reflects the current system clock. To be
  * able to use these members of ShapesPanel in the definition of
  * posX and posY, we must instantiate the ShapesPanel beforehand,
  * but the instantiation of ShapesPanel, uses posX and posY. But,
  * because ShapesPanel takes a Signal of a List of Shapes in its
  * constructor, we can resolve this circular dependency by
  * instantiating it with a Var containing an initially empty List,
  * and then update the Var to add the Circle at posX and posY at
  * the end. For this update, we use the Var's .transform method.
  *
  * With the ShapesPanel now instantiated at the very beginning,
  * its width and height signal are available when defining posX
  * and posY. We thus now change their definitions into Signal
  * expressions that use a third of the panels width and height
  * as the respective horizontal or vertical radius of the new
  * oval trajectory, with angle still defining the position of
  * the displayed circle on that trajectory.
  */
object DScaledClockCircle extends SimpleSwingApplication {
  val NanoSecond = 1000000000l

  val nsTime = Var(System.nanoTime())
  def tick() = nsTime.set(System.nanoTime())

  val shapes = Var[List[Shape]](List.empty)
  val panel = new ShapesPanel(shapes)

  val angle = nsTime.map( _.toDouble / NanoSecond * math.Pi)

  val posX = Signal {(panel.width() / 2 - 50).toDouble * math.sin(angle())}
  val posY = Signal {(panel.height() / 2 - 50).toDouble * math.cos(angle())}

  shapes.transform(new Circle(posX.map(_.toInt), posY.map(_.toInt), Var(50)) :: _)

  override lazy val top = {
    panel.preferredSize = new Dimension(400, 300)
    new MainFrame {
      title = "REScala Demo"
      contents = panel
      setLocationRelativeTo(new UIElement {override def peer = null})
    }
  }

  override def main(args: Array[String]): Unit = {
    super.main(args)

    while(!top.visible) Thread.sleep(5)
    while(top.visible) {
      Thread.sleep(1)
      tick()
    }
  }
}


text:
import RegistrationMetadata from './RegistrationMetadata';
import UnitOfWorkParameter from '../parameters/UnitOfWorkParameter';
import { assert } from './Guards';

export default function ScopedUnitOfWork (scopeName: string, ...args: Function[]) {
  assert('(ScopedUnitOfWork) args', args).is.not.empty();
  return function(target: Function, key: string, index: number) {
    assert('(ScopedUnitOfWork) target', target).is.a.function();
    const metadata = RegistrationMetadata.findOrCreate(target);
    const params = args.slice(0, args.length - 1);
    const service = args[args.length - 1];
    metadata.addInitialization(registration => registration.parameters[index] = new UnitOfWorkParameter(params, service, scopeName));
  };
}


text:
package edu.usc.goffish.gofs.formats.gml;

import it.unimi.dsi.fastutil.longs.*;

import java.io.*;
import java.util.*;

import edu.usc.goffish.gofs.*;
import edu.usc.goffish.gofs.partition.*;
import edu.usc.goffish.gofs.partition.components.*;
import edu.usc.goffish.gofs.util.*;

public class GMLPartition extends Partition implements ISerializablePartition {

	private final Iterable<InputStream> _gmlInstanceStreams;

	protected GMLPartition(int id, boolean directed, Collection<? extends ISubgraph> subgraphs, PropertySet vertexProperties, PropertySet edgeProperties, Iterable<InputStream> gmlInstanceStreams) {
		super(id, directed, subgraphs, vertexProperties, edgeProperties);

		if (gmlInstanceStreams == null) {
			throw new IllegalArgumentException();
		}

		_gmlInstanceStreams = gmlInstanceStreams;
	}

	/**
	 * Creates a partition backed by the specified GML data. The template is loaded into memory, the instances are
	 * loaded on demand. The resulting subgraphs contained by this partition do not support querying for instance data,
	 * as GML files are not sufficient for this query. Rather the expected use case is that this partition will be
	 * written to slices through the SliceManager, the SliceManager will be used to load the partition from slices, and
	 * that partition may be queried for instance data.
	 *
	 * @param partitionId
	 *            the id of the partition to create
	 * @param graphComponentizer
	 *            the componentizer to use to divide this graph into subgraphs
	 * @param gmlTemplateStream
	 *            an input stream containing the GML template
	 * @param gmlInstanceStreams
	 *            an Iterable of input streams for each GML instance file
	 * @return a partition constructed from the GML template, and backed by the GML instances
	 */
	public static GMLPartition parseGML(int partitionId, IGraphComponentizer graphComponentizer, InputStream gmlTemplateStream, Iterable<InputStream> gmlInstanceStreams) throws IOException {
		if (gmlTemplateStream == null) {
			throw new IllegalArgumentException();
		}
		if (gmlInstanceStreams == null) {
			throw new IllegalArgumentException();
		}

		GMLGraph graph = GMLGraph.read(gmlTemplateStream);

		// split into components
		Collection<? extends Collection<TemplateVertex>> components = graphComponentizer.componentize(graph.getTemplate());

		// create subgraphs from components
		ArrayList<ISubgraph> subgraphs = new ArrayList<>(components.size());
		int subgraphCount = 0;
		for (Collection<TemplateVertex> component : components) {
			TemplateGraph template = new TemplateGraph(graph.isDirected());
			for (TemplateVertex vertex : component) {
				template.addVertex(vertex);
			}

			long subgraphId = subgraphCount++ | (((long)partitionId) << 32);
			subgraphs.add(new GMLGraph(subgraphId, template, graph.getVertexProperties(), graph.getEdgeProperties()));
		}

		return new GMLPartition(partitionId, graph.isDirected(), subgraphs, graph.getVertexProperties(), graph.getEdgeProperties(), gmlInstanceStreams);
	}

	@Override
	public Iterable<Long2ObjectMap<? extends ISubgraphInstance>> getSubgraphsInstances() {
		return new Iterable<Long2ObjectMap<? extends ISubgraphInstance>>() {
			@Override
			public Iterator<Long2ObjectMap<? extends ISubgraphInstance>> iterator() {
				return new GMLInstanceIterator(_gmlInstanceStreams, getVertexProperties(), getEdgeProperties());
			}
		};
	}

	private class GMLInstanceIterator extends AbstractWrapperIterator<Long2ObjectMap<? extends ISubgraphInstance>> {

		private final Iterator<InputStream> _itStreams;
		private final PropertySet _vertexProperties;
		private final PropertySet _edgeProperties;

		public GMLInstanceIterator(Iterable<InputStream> gmlInstanceStreams, PropertySet vertexProperties, PropertySet edgeProperties) {
			if (gmlInstanceStreams == null) {
				throw new IllegalArgumentException();
			}
			if (vertexProperties == null) {
				throw new IllegalArgumentException();
			}
			if (edgeProperties == null) {
				throw new IllegalArgumentException();
			}

			_itStreams = gmlInstanceStreams.iterator();
			_vertexProperties = vertexProperties;
			_edgeProperties = edgeProperties;
		}

		@Override
		protected Long2ObjectMap<? extends ISubgraphInstance> advanceToNext() {
			if (!_itStreams.hasNext()) {
				return null;
			}

			try {
				return GMLInstance.read(_itStreams.next(), GMLPartition.this, _vertexProperties, _edgeProperties);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
}


text:
var express = require('express');
//var bodyParser = require('body-parser');
//var methodOverride = require('method-override');

var app = express();

app.get('/', function(req, res) {res.sendfile('index.html');});
app.get('/modal-start.html', function(req, res) {res.sendfile('modal-start.html');});
app.get('/modal-end.html', function(req, res) {res.sendfile('modal-end.html');});
app.get('/styles.css', function(req, res) {res.sendfile('styles.css');});

var server = app.listen(3000, function() {
	console.log('Listening on port %d', server.address().port);
});

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.send(500, 'Something broke!');
});

//app.use(bodyParser());
//app.use(methodOverride());
//app.use(app.router);
//app.use(function(err, req, res, next){
//  // logic
//});


text:
package org.apache.ambari.server.events.listeners.upgrade;

import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;

import java.lang.reflect.Field;

import org.apache.ambari.annotations.Experimental;
import org.apache.ambari.annotations.ExperimentalFeature;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.api.services.AmbariMetaInfo;
import org.apache.ambari.server.events.HostComponentVersionAdvertisedEvent;
import org.apache.ambari.server.events.publishers.VersionEventPublisher;
import org.apache.ambari.server.orm.dao.RepositoryVersionDAO;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.orm.entities.UpgradeEntity;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.ComponentInfo;
import org.apache.ambari.server.state.Service;
import org.apache.ambari.server.state.ServiceComponent;
import org.apache.ambari.server.state.ServiceComponentHost;
import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.UpgradeState;
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.EasyMockSupport;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import com.google.inject.Provider;

import junit.framework.Assert;

/**
 * StackVersionListener tests.
 */
@RunWith(EasyMockRunner.class)
public class StackVersionListenerTest extends EasyMockSupport {

  private static final String INVALID_NEW_VERSION = "1.2.3.4-5678";
  private static final String VALID_NEW_VERSION = "2.4.0.0-1000";
  private static final String SERVICE_COMPONENT_NAME = "Some component name";
  private static final String SERVICE_NAME = "Service name";
  private static final Long CLUSTER_ID = 1L;
  private static final String UNKNOWN_VERSION = "UNKNOWN";
  private static final String VALID_PREVIOUS_VERSION = "2.2.0.0";
  private static final RepositoryVersionEntity DUMMY_REPOSITORY_VERSION_ENTITY = new RepositoryVersionEntity();
  private static final UpgradeEntity DUMMY_UPGRADE_ENTITY = new UpgradeEntity();
  public static final String STACK_NAME = "HDP-2.4.0.0";
  public static final String STACK_VERSION = "2.4.0.0";

  private Cluster cluster;
  private ServiceComponentHost sch;
  private Service service;
  private ServiceComponent serviceComponent;
  private VersionEventPublisher publisher = new VersionEventPublisher();
  private StackId stackId;

  @TestSubject
  private StackVersionListener listener = new StackVersionListener(publisher);

  @Mock
  private Provider<AmbariMetaInfo> ambariMetaInfoProvider;

  @Mock
  private ComponentInfo componentInfo;

  @Mock
  private AmbariMetaInfo ambariMetaInfo;

  @Before
  public void setup() throws Exception {
    cluster = createNiceMock(Cluster.class);
    sch = createNiceMock(ServiceComponentHost.class);
    service = createNiceMock(Service.class);
    serviceComponent = createNiceMock(ServiceComponent.class);
    stackId = createNiceMock(StackId.class);

    expect(cluster.getService(SERVICE_NAME)).andReturn(service).anyTimes();
    expect(cluster.getDesiredStackVersion()).andReturn(stackId).anyTimes();
    expect(stackId.getStackName()).andReturn(STACK_NAME).anyTimes();
    expect(stackId.getStackVersion()).andReturn(STACK_VERSION).anyTimes();
    expect(cluster.getClusterId()).andReturn(CLUSTER_ID).atLeastOnce();

    expect(service.getServiceComponent(SERVICE_COMPONENT_NAME)).andReturn(serviceComponent).anyTimes();
    expect(serviceComponent.getDesiredStackVersion()).andReturn(stackId).anyTimes();
    expect(sch.getDesiredStackVersion()).andReturn(stackId).atLeastOnce();
    expect(sch.getServiceName()).andReturn(SERVICE_NAME).atLeastOnce();
    expect(sch.getServiceComponentName()).andReturn(SERVICE_COMPONENT_NAME).atLeastOnce();

    expect(ambariMetaInfoProvider.get()).andReturn(ambariMetaInfo).atLeastOnce();
    expect(ambariMetaInfo.getComponent(STACK_NAME, STACK_VERSION, SERVICE_NAME,
        SERVICE_COMPONENT_NAME)).andReturn(componentInfo).atLeastOnce();

    injectMocks(listener);
  }

  @Test
  public void testRecalculateHostVersionStateWhenVersionIsNullAndNewVersionIsNotBlank() throws AmbariException {
    expect(sch.getVersion()).andReturn(null).atLeastOnce();
    expect(serviceComponent.getDesiredVersion()).andReturn(INVALID_NEW_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setVersion(INVALID_NEW_VERSION);
    expectLastCall().once();
    expect(sch.recalculateHostVersionState()).andReturn(null).once();

    replayAll();

    sendEventAndVerify(INVALID_NEW_VERSION);
  }

  @Test
  public void testRecalculateHostVersionStateWhenVersionIsUnknownAndNewVersionIsNotBlank() throws AmbariException {
    expect(sch.getVersion()).andReturn(UNKNOWN_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setVersion(INVALID_NEW_VERSION);
    expectLastCall().once();
    expect(sch.recalculateHostVersionState()).andReturn(null).once();

    replayAll();

    sendEventAndVerify(INVALID_NEW_VERSION);
  }

  @Test
  public void testRecalculateClusterVersionStateWhenVersionIsNullAndNewVersionIsValid() throws AmbariException {
    expect(sch.getVersion()).andReturn(null).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setVersion(VALID_NEW_VERSION);
    expectLastCall().once();
    expect(sch.recalculateHostVersionState()).andReturn(DUMMY_REPOSITORY_VERSION_ENTITY).once();
    cluster.recalculateClusterVersionState(DUMMY_REPOSITORY_VERSION_ENTITY);
    expectLastCall().once();

    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testRecalculateClusterVersionStateWhenVersionIsUnknownAndNewVersionIsValid() throws AmbariException {
    expect(sch.getVersion()).andReturn(UNKNOWN_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setVersion(VALID_NEW_VERSION);
    expectLastCall().once();
    expect(sch.recalculateHostVersionState()).andReturn(DUMMY_REPOSITORY_VERSION_ENTITY).once();
    cluster.recalculateClusterVersionState(DUMMY_REPOSITORY_VERSION_ENTITY);
    expectLastCall().once();

    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testRecalculateHostVersionStateWhenComponentDesiredVersionIsUnknownAndNewVersionIsNotValid() throws AmbariException {
    expect(serviceComponent.getDesiredVersion()).andReturn(UNKNOWN_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    serviceComponent.setDesiredVersion(INVALID_NEW_VERSION);
    expectLastCall().once();
    sch.setUpgradeState(UpgradeState.NONE);
    expectLastCall().once();
    sch.setVersion(INVALID_NEW_VERSION);
    expectLastCall().once();
    expect(sch.recalculateHostVersionState()).andReturn(null).once();

    replayAll();

    sendEventAndVerify(INVALID_NEW_VERSION);
  }

  @Test
  public void testRecalculateClusterVersionStateWhenComponentDesiredVersionIsUnknownAndNewVersionIsValid() throws AmbariException {
    expect(serviceComponent.getDesiredVersion()).andReturn(UNKNOWN_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    serviceComponent.setDesiredVersion(VALID_NEW_VERSION);
    expectLastCall().once();
    sch.setUpgradeState(UpgradeState.NONE);
    expectLastCall().once();
    sch.setVersion(VALID_NEW_VERSION);
    expectLastCall().once();
    expect(sch.recalculateHostVersionState()).andReturn(DUMMY_REPOSITORY_VERSION_ENTITY).once();
    cluster.recalculateClusterVersionState(DUMMY_REPOSITORY_VERSION_ENTITY);
    expectLastCall().once();

    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testRecalculateClusterVersionStateWhenVersionNotAdvertised() throws AmbariException {
    expect(componentInfo.isVersionAdvertised()).andReturn(false).atLeastOnce();
    replayAll();
    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testNoActionTakenOnNullVersion() {
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    resetAll();
    replayAll();

    sendEventAndVerify(null);
  }

  @Test
  public void testSetUpgradeStateToCompleteWhenUpgradeIsInProgressAndNewVersionIsEqualToComponentDesiredVersion() {
    expect(cluster.getUpgradeInProgress()).andReturn(EasyMock.niceMock(UpgradeEntity.class)).atLeastOnce();
    expect(sch.getVersion()).andReturn(VALID_PREVIOUS_VERSION).atLeastOnce();
    expect(sch.getUpgradeState()).andReturn(UpgradeState.IN_PROGRESS).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setUpgradeState(UpgradeState.COMPLETE);
    expectLastCall().once();

    expect(serviceComponent.getDesiredVersion()).andStubReturn(VALID_NEW_VERSION);
    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testSetUpgradeStateToVersionMismatchWhenUpgradeIsInProgressAndNewVersionIsNotEqualToComponentDesiredVersion() {
    expect(cluster.getUpgradeInProgress()).andReturn(createNiceMock(UpgradeEntity.class)).atLeastOnce();
    expect(sch.getVersion()).andReturn(VALID_PREVIOUS_VERSION).atLeastOnce();
    expect(sch.getUpgradeState()).andReturn(UpgradeState.IN_PROGRESS).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setUpgradeState(UpgradeState.VERSION_MISMATCH);
    expectLastCall().once();

    expect(serviceComponent.getDesiredVersion()).andStubReturn(VALID_PREVIOUS_VERSION);
    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testSetUpgradeStateToCompleteWhenHostHasVersionMismatchAndNewVersionIsEqualToComponentDesiredVersionAndClusterUpgradeIsInProgress() {
    expect(sch.getVersion()).andReturn(VALID_PREVIOUS_VERSION).atLeastOnce();
    expect(sch.getUpgradeState()).andReturn(UpgradeState.VERSION_MISMATCH).atLeastOnce();
    expect(cluster.getUpgradeInProgress()).andReturn(DUMMY_UPGRADE_ENTITY).atLeastOnce();
    expect(serviceComponent.getDesiredVersion()).andStubReturn(VALID_NEW_VERSION);
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setUpgradeState(UpgradeState.COMPLETE);
    expectLastCall().once();

    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testSetUpgradeStateToNoneWhenHostHasVersionMismatchAndNewVersionIsEqualToComponentDesiredVersion() {
    expect(sch.getVersion()).andReturn(VALID_PREVIOUS_VERSION).atLeastOnce();
    expect(sch.getUpgradeState()).andReturn(UpgradeState.VERSION_MISMATCH).atLeastOnce();
    expect(serviceComponent.getDesiredVersion()).andStubReturn(VALID_NEW_VERSION);
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();
    sch.setUpgradeState(UpgradeState.NONE);
    expectLastCall().once();

    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  @Experimental(
      feature = ExperimentalFeature.STACK_UPGRADES_BETWEEN_VENDORS,
      comment = "Version Mismatch happened previously when not in an upgrade")
  public void testSetUpgradeStateToVersionMismatchByDefaultWhenHostAndNewVersionsAreValid() {
    expect(sch.getVersion()).andReturn(VALID_PREVIOUS_VERSION).atLeastOnce();
    expect(serviceComponent.getDesiredVersion()).andReturn(VALID_PREVIOUS_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();

    // !!! VERSION_MISMATCH might need to be allowed to happen when not in an
    // upgrade
    expect(cluster.getUpgradeInProgress()).andReturn(
        EasyMock.niceMock(UpgradeEntity.class)).atLeastOnce();
    expect(sch.getUpgradeState()).andReturn(UpgradeState.IN_PROGRESS).atLeastOnce();

    sch.setUpgradeState(UpgradeState.VERSION_MISMATCH);
    expectLastCall().once();

    replayAll();

    sendEventAndVerify(VALID_NEW_VERSION);
  }

  @Test
  public void testSetRepositoryVersion() throws Exception {
    expect(sch.getVersion()).andReturn(UNKNOWN_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();

    RepositoryVersionDAO dao = createNiceMock(RepositoryVersionDAO.class);
    RepositoryVersionEntity entity = createNiceMock(RepositoryVersionEntity.class);
    expect(entity.getVersion()).andReturn("2.4.0.0").once();
    expect(dao.findByPK(1L)).andReturn(entity).once();
    expect(dao.merge(entity)).andReturn(entity).once();

    replayAll();

    String newVersion = VALID_NEW_VERSION;

    HostComponentVersionAdvertisedEvent event = new HostComponentVersionAdvertisedEvent(cluster, sch, newVersion, 1L);
    // !!! avoid injector for test class
    Field field = StackVersionListener.class.getDeclaredField("repositoryVersionDAO");
    field.setAccessible(true);
    field.set(listener, dao);

    listener.onAmbariEvent(event);

    verifyAll();
  }

  /**
   * Tests that the {@link RepositoryVersionEntity} is not updated if there is
   * an upgrade, even if the repo ID is passed back and the versions don't
   * match.
   *
   * @throws Exception
   */
  @Test
  public void testRepositoryVersionNotSetDuringUpgrade() throws Exception {
    expect(sch.getVersion()).andReturn(UNKNOWN_VERSION).atLeastOnce();
    expect(componentInfo.isVersionAdvertised()).andReturn(true).atLeastOnce();

    // this call will make it seem like there is an upgrade in progress
    expect(cluster.getUpgradeInProgress()).andReturn(
        createNiceMock(UpgradeEntity.class)).atLeastOnce();

    // create the DAO - nothing will be called on it, so make it strict
    RepositoryVersionDAO dao = createStrictMock(RepositoryVersionDAO.class);

    replayAll();

    // !!! avoid injector for test class

    Field field = StackVersionListener.class.getDeclaredField("repositoryVersionDAO");
    field.setAccessible(true);
    field.set(listener, dao);

    HostComponentVersionAdvertisedEvent event = new HostComponentVersionAdvertisedEvent(cluster,
        sch, VALID_NEW_VERSION, 1L);

    // make sure that a repo ID will come back
    Assert.assertNotNull(event.getRepositoryVersionId());

    listener.onAmbariEvent(event);

    verifyAll();
  }

  private void sendEventAndVerify(String newVersion) {
    HostComponentVersionAdvertisedEvent event = new HostComponentVersionAdvertisedEvent(cluster, sch, newVersion);
    listener.onAmbariEvent(event);

    verifyAll();
  }
}


text:
/**
 * Problem: Sum up all root-to-leaf paths
 *
 * Solution: Use DFS to sum bottom up.
 */

public class SumRootToLeaf{
	public int sumNumbers(TreeNode root){
		return sumHelper(root,0);
	}

	public int sumHelper(TreeNode root, int prevSum){
		if(root == null){
			return 0;
		}
		int sum = prevSum*10 + root.val;

		//reach a leaf and return sum
		if(root.left==null && root.right==null){
			return sum;
		}
		//branch deeper
		return sumHelper(root.left,sum) + sumHelper(root.right, sum);
	}
}


text:
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using BeerDrinkin.DataObjects;
using BeerDrinkin.Models;
using Microsoft.ApplicationInsights;
using System.Collections.Generic;
using BeerDrinkin.Service.Helpers;

namespace BeerDrinkin.Controllers
{
    public class BeerController : TableController<Beer>
    {
        BeerDrinkinContext context;
        TelemetryClient telemetryClient;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            context = new BeerDrinkinContext();
            DomainManager = new EntityDomainManager<Beer>(context, Request);
            telemetryClient = new TelemetryClient();
        }

        [QueryableExpand("Brewery, Image")]
        public IQueryable<Beer> GetAllBeerItem()
        {
            telemetryClient.TrackEvent("GetAllBeers");
            return Query();
        }

        [QueryableExpand("Brewery, Image")]
        public SingleResult<Beer> GetBeerItem(string id)
        {
            var properties = new Dictionary<string, string>();
            properties.Add("BeerId", id);
            telemetryClient.TrackEvent("GetBeer", properties);

            return Lookup(id);
        }

        [Authorize]
        public Task<Beer> PatchBeerItem(string id, Delta<Beer> patch)
        {
            return UpdateAsync(id, patch);
        }

        [Authorize]
        public async Task<IHttpActionResult> PostBeerItem(Beer item)
        {
            var properties = new Dictionary<string, string>();
            properties.Add("BeerId", item.Id);
            properties.Add("BeerName", item.Name);
            telemetryClient.TrackEvent("SaveBeer", properties);

            Beer current = await InsertAsync(item);
            return CreatedAtRoute("Tables", new { id = current.Id }, current);
        }

        [Authorize]
        public Task DeleteBeerItem(string id)
        {
            var properties = new Dictionary<string, string>();
            properties.Add("BeerId", id);
            telemetryClient.TrackEvent("DeleteBeer", properties);

            return DeleteAsync(id);
        }
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace Apollo.UIRender.View.Controllers
{
    public class ForTestController : ApiController
    {
        //
        // GET: /ForTest/

        // GET api/values
        public IQueryable<string> Get()
        {
            return new string[] { "value1", "value2" }.AsQueryable();
        }

        // GET api/values/5
        public object Get(int id)
        {
            return new { id = id, name = 1 };
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
            //寫入資料
            Hashtable db = new Hashtable();
            db.Add(value, value); //Sample for Test
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
            //測試抓取資料
            int Id = id;
            string Value = value;
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
            //測試抓取資料
            int Id = id;
        }
    }
}


text:
package com.cleveroad.loopbar.adapter;

import android.graphics.drawable.Drawable;

/**
 * Interface for item in LoopBar
 */
public interface ICategoryItem {

    /**
     * Returns image for displaying in Item
     *
     * @return Instance of {@link Drawable}
     */
    Drawable getCategoryIconDrawable();

    /**
     * Returns text for displaying in Item
     *
     * @return Instance of {@link String}
     */
    String getCategoryName();
}


text:
namespace aria2 {

class DHTMessageFactoryImplTest:public CppUnit::TestFixture {

  CPPUNIT_TEST_SUITE(DHTMessageFactoryImplTest);
  CPPUNIT_TEST(testCreatePingMessage);
  CPPUNIT_TEST(testCreatePingReplyMessage);
  CPPUNIT_TEST(testCreateFindNodeMessage);
  CPPUNIT_TEST(testCreateFindNodeReplyMessage);
  CPPUNIT_TEST(testCreateFindNodeReplyMessage6);
  CPPUNIT_TEST(testCreateGetPeersMessage);
  CPPUNIT_TEST(testCreateGetPeersReplyMessage);
  CPPUNIT_TEST(testCreateGetPeersReplyMessage6);
  CPPUNIT_TEST(testCreateAnnouncePeerMessage);
  CPPUNIT_TEST(testCreateAnnouncePeerReplyMessage);
  CPPUNIT_TEST(testReceivedErrorMessage);
  CPPUNIT_TEST_SUITE_END();
public:
  std::unique_ptr<DHTMessageFactoryImpl> factory;

  std::unique_ptr<DHTRoutingTable> routingTable;

  std::shared_ptr<DHTNode> localNode;

  std::unique_ptr<DHTNode> remoteNode_;
  std::unique_ptr<DHTNode> remoteNode6_;

  unsigned char transactionID[DHT_TRANSACTION_ID_LENGTH];

  unsigned char remoteNodeID[DHT_ID_LENGTH];

  void setUp()
  {
    localNode = std::make_shared<DHTNode>();
    factory = make_unique<DHTMessageFactoryImpl>(AF_INET);
    factory->setLocalNode(localNode);
    memset(transactionID, 0xff, DHT_TRANSACTION_ID_LENGTH);
    memset(remoteNodeID, 0x0f, DHT_ID_LENGTH);
    routingTable = make_unique<DHTRoutingTable>(localNode);
    factory->setRoutingTable(routingTable.get());

    remoteNode_ = make_unique<DHTNode>(remoteNodeID);
    remoteNode_->setIPAddress("192.168.0.1");
    remoteNode_->setPort(6881);

    remoteNode6_ = make_unique<DHTNode>(remoteNodeID);
    remoteNode6_->setIPAddress("2001::2001");
    remoteNode6_->setPort(6881);
  }

  void tearDown() {}

  void testCreatePingMessage();
  void testCreatePingReplyMessage();
  void testCreateFindNodeMessage();
  void testCreateFindNodeReplyMessage();
  void testCreateFindNodeReplyMessage6();
  void testCreateGetPeersMessage();
  void testCreateGetPeersReplyMessage();
  void testCreateGetPeersReplyMessage6();
  void testCreateAnnouncePeerMessage();
  void testCreateAnnouncePeerReplyMessage();
  void testReceivedErrorMessage();
};

CPPUNIT_TEST_SUITE_REGISTRATION(DHTMessageFactoryImplTest);

void DHTMessageFactoryImplTest::testCreatePingMessage()
{
  Dict dict;
  dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
  dict.put("y", "q");
  dict.put("q", "ping");
  auto aDict = Dict::g();
  aDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
  dict.put("a", std::move(aDict));

  auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6881);
  auto m = dynamic_cast<DHTPingMessage*>(r.get());

  CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
  CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
  CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                       util::toHex(m->getTransactionID()));
}

void DHTMessageFactoryImplTest::testCreatePingReplyMessage()
{
  Dict dict;
  dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
  dict.put("y", "r");
  auto rDict = Dict::g();
  rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
  dict.put("r", std::move(rDict));

  auto r = factory->createResponseMessage("ping", &dict,
                                          remoteNode_->getIPAddress(),
                                          remoteNode_->getPort());
  auto m = dynamic_cast<DHTPingReplyMessage*>(r.get());

  CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
  CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
  CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                       util::toHex(m->getTransactionID()));
}

void DHTMessageFactoryImplTest::testCreateFindNodeMessage()
{
  Dict dict;
  dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
  dict.put("y", "q");
  dict.put("q", "find_node");
  auto aDict = Dict::g();
  aDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
  unsigned char targetNodeID[DHT_ID_LENGTH];
  memset(targetNodeID, 0x11, DHT_ID_LENGTH);
  aDict->put("target", String::g(targetNodeID, DHT_ID_LENGTH));
  dict.put("a", std::move(aDict));

  auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6881);
  auto m = dynamic_cast<DHTFindNodeMessage*>(r.get());

  CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
  CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
  CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                       util::toHex(m->getTransactionID()));
  CPPUNIT_ASSERT_EQUAL(util::toHex(targetNodeID, DHT_ID_LENGTH),
                       util::toHex(m->getTargetNodeID(), DHT_ID_LENGTH));
}

void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage()
{
  try {
    Dict dict;
    dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
    dict.put("y", "r");
    auto rDict = Dict::g();
    rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
    std::string compactNodeInfo;
    std::shared_ptr<DHTNode> nodes[8];
    for(size_t i = 0; i < DHTBucket::K; ++i) {
      nodes[i] = std::make_shared<DHTNode>();
      nodes[i]->setIPAddress("192.168.0."+util::uitos(i+1));
      nodes[i]->setPort(6881+i);

      unsigned char buf[COMPACT_LEN_IPV6];
      CPPUNIT_ASSERT_EQUAL
        (COMPACT_LEN_IPV4,
         bittorrent::packcompact
         (buf, nodes[i]->getIPAddress(), nodes[i]->getPort()));
      compactNodeInfo +=
        std::string(&nodes[i]->getID()[0], &nodes[i]->getID()[DHT_ID_LENGTH])+
        std::string(&buf[0], &buf[COMPACT_LEN_IPV4]);
    }
    rDict->put("nodes", compactNodeInfo);
    dict.put("r", std::move(rDict));

    auto r = factory->createResponseMessage("find_node", &dict,
                                            remoteNode_->getIPAddress(),
                                            remoteNode_->getPort());
    auto m = dynamic_cast<DHTFindNodeReplyMessage*>(r.get());

    CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
    CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
    CPPUNIT_ASSERT_EQUAL((size_t)DHTBucket::K, m->getClosestKNodes().size());
    CPPUNIT_ASSERT(*nodes[0] == *m->getClosestKNodes()[0]);
    CPPUNIT_ASSERT(*nodes[7] == *m->getClosestKNodes()[7]);
    CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                         util::toHex(m->getTransactionID()));
  } catch(Exception& e) {
    CPPUNIT_FAIL(e.stackTrace());
  }
}

void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage6()
{
  factory = make_unique<DHTMessageFactoryImpl>(AF_INET6);
  factory->setLocalNode(localNode);
  factory->setRoutingTable(routingTable.get());
  try {
    Dict dict;
    dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
    dict.put("y", "r");
    auto rDict = Dict::g();
    rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
    std::string compactNodeInfo;
    std::shared_ptr<DHTNode> nodes[8];
    for(size_t i = 0; i < DHTBucket::K; ++i) {
      nodes[i] = std::make_shared<DHTNode>();
      nodes[i]->setIPAddress("2001::000"+util::uitos(i+1));
      nodes[i]->setPort(6881+i);

      unsigned char buf[COMPACT_LEN_IPV6];
      CPPUNIT_ASSERT_EQUAL
        (COMPACT_LEN_IPV6,
         bittorrent::packcompact
         (buf, nodes[i]->getIPAddress(), nodes[i]->getPort()));
      compactNodeInfo +=
        std::string(&nodes[i]->getID()[0], &nodes[i]->getID()[DHT_ID_LENGTH])+
        std::string(&buf[0], &buf[COMPACT_LEN_IPV6]);
    }
    rDict->put("nodes6", compactNodeInfo);
    dict.put("r", std::move(rDict));

    auto r = factory->createResponseMessage("find_node", &dict,
                                            remoteNode_->getIPAddress(),
                                            remoteNode_->getPort());
    auto m = dynamic_cast<DHTFindNodeReplyMessage*>(r.get());

    CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
    CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
    CPPUNIT_ASSERT_EQUAL((size_t)DHTBucket::K, m->getClosestKNodes().size());
    CPPUNIT_ASSERT(*nodes[0] == *m->getClosestKNodes()[0]);
    CPPUNIT_ASSERT(*nodes[7] == *m->getClosestKNodes()[7]);
    CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                         util::toHex(m->getTransactionID()));
  } catch(Exception& e) {
    CPPUNIT_FAIL(e.stackTrace());
  }
}

void DHTMessageFactoryImplTest::testCreateGetPeersMessage()
{
  Dict dict;
  dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
  dict.put("y", "q");
  dict.put("q", "get_peers");
  auto aDict = Dict::g();
  aDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
  unsigned char infoHash[DHT_ID_LENGTH];
  memset(infoHash, 0x11, DHT_ID_LENGTH);
  aDict->put("info_hash", String::g(infoHash, DHT_ID_LENGTH));
  dict.put("a", std::move(aDict));

  auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6881);
  auto m = dynamic_cast<DHTGetPeersMessage*>(r.get());

  CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
  CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
  CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                       util::toHex(m->getTransactionID()));
  CPPUNIT_ASSERT_EQUAL(util::toHex(infoHash, DHT_ID_LENGTH),
                       util::toHex(m->getInfoHash(), DHT_ID_LENGTH));
}

void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage()
{
  try {
    Dict dict;
    dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
    dict.put("y", "r");
    auto rDict = Dict::g();
    rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
    std::string compactNodeInfo;
    std::shared_ptr<DHTNode> nodes[8];
    for(size_t i = 0; i < DHTBucket::K; ++i) {
      nodes[i] = std::make_shared<DHTNode>();
      nodes[i]->setIPAddress("192.168.0."+util::uitos(i+1));
      nodes[i]->setPort(6881+i);

      unsigned char buf[COMPACT_LEN_IPV6];
      CPPUNIT_ASSERT_EQUAL
        (COMPACT_LEN_IPV4,
         bittorrent::packcompact
         (buf, nodes[i]->getIPAddress(), nodes[i]->getPort()));
      compactNodeInfo +=
        std::string(&nodes[i]->getID()[0], &nodes[i]->getID()[DHT_ID_LENGTH])+
        std::string(&buf[0], &buf[COMPACT_LEN_IPV4]);
    }
    rDict->put("nodes", compactNodeInfo);

    std::deque<std::shared_ptr<Peer> > peers;
    auto valuesList = List::g();
    for(size_t i = 0; i < 4; ++i) {
      auto peer = std::make_shared<Peer>("192.168.0."+util::uitos(i+1),
                                         6881+i);
      unsigned char buffer[COMPACT_LEN_IPV6];
      CPPUNIT_ASSERT_EQUAL
        (COMPACT_LEN_IPV4,
         bittorrent::packcompact
         (buffer, peer->getIPAddress(), peer->getPort()));
      valuesList->append(String::g(buffer, COMPACT_LEN_IPV4));
      peers.push_back(peer);
    }
    rDict->put("values", std::move(valuesList));
    rDict->put("token", "token");
    dict.put("r", std::move(rDict));

    auto r = factory->createResponseMessage("get_peers", &dict,
                                            remoteNode_->getIPAddress(),
                                            remoteNode_->getPort());
    auto m = dynamic_cast<DHTGetPeersReplyMessage*>(r.get());

    CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
    CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
    CPPUNIT_ASSERT_EQUAL(std::string("token"), m->getToken());
    CPPUNIT_ASSERT_EQUAL((size_t)DHTBucket::K, m->getClosestKNodes().size());
    CPPUNIT_ASSERT(*nodes[0] == *m->getClosestKNodes()[0]);
    CPPUNIT_ASSERT(*nodes[7] == *m->getClosestKNodes()[7]);
    CPPUNIT_ASSERT_EQUAL((size_t)4, m->getValues().size());
    for(int i = 0; i < 4; ++i) {
      CPPUNIT_ASSERT_EQUAL(peers[i]->getIPAddress(),
                           m->getValues()[i]->getIPAddress());
      CPPUNIT_ASSERT_EQUAL(peers[i]->getPort(), m->getValues()[i]->getPort());
    }
    CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                         util::toHex(m->getTransactionID()));
  } catch(Exception& e) {
    CPPUNIT_FAIL(e.stackTrace());
  }
}

void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage6()
{
  factory = make_unique<DHTMessageFactoryImpl>(AF_INET6);
  factory->setLocalNode(localNode);
  factory->setRoutingTable(routingTable.get());
  try {
    Dict dict;
    dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
    dict.put("y", "r");
    auto rDict = Dict::g();
    rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
    std::string compactNodeInfo;
    std::shared_ptr<DHTNode> nodes[8];
    for(size_t i = 0; i < DHTBucket::K; ++i) {
      nodes[i] = std::make_shared<DHTNode>();
      nodes[i]->setIPAddress("2001::000"+util::uitos(i+1));
      nodes[i]->setPort(6881+i);

      unsigned char buf[COMPACT_LEN_IPV6];
      CPPUNIT_ASSERT_EQUAL
        (COMPACT_LEN_IPV6,
         bittorrent::packcompact
         (buf, nodes[i]->getIPAddress(), nodes[i]->getPort()));
      compactNodeInfo +=
        std::string(&nodes[i]->getID()[0], &nodes[i]->getID()[DHT_ID_LENGTH])+
        std::string(&buf[0], &buf[COMPACT_LEN_IPV6]);
    }
    rDict->put("nodes6", compactNodeInfo);

    std::deque<std::shared_ptr<Peer>> peers;
    auto valuesList = List::g();
    for(size_t i = 0; i < 4; ++i) {
      auto peer = std::make_shared<Peer>("2001::100"+util::uitos(i+1), 6881+i);
      unsigned char buffer[COMPACT_LEN_IPV6];
      CPPUNIT_ASSERT_EQUAL
        (COMPACT_LEN_IPV6,
         bittorrent::packcompact
         (buffer, peer->getIPAddress(), peer->getPort()));
      valuesList->append(String::g(buffer, COMPACT_LEN_IPV6));
      peers.push_back(peer);
    }
    rDict->put("values", std::move(valuesList));
    rDict->put("token", "token");
    dict.put("r", std::move(rDict));

    auto r = factory->createResponseMessage("get_peers", &dict,
                                            remoteNode_->getIPAddress(),
                                            remoteNode_->getPort());
    auto m = dynamic_cast<DHTGetPeersReplyMessage*>(r.get());

    CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
    CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
    CPPUNIT_ASSERT_EQUAL(std::string("token"), m->getToken());
    CPPUNIT_ASSERT_EQUAL((size_t)DHTBucket::K, m->getClosestKNodes().size());
    CPPUNIT_ASSERT(*nodes[0] == *m->getClosestKNodes()[0]);
    CPPUNIT_ASSERT(*nodes[7] == *m->getClosestKNodes()[7]);
    CPPUNIT_ASSERT_EQUAL((size_t)4, m->getValues().size());
    for(int i = 0; i < 4; ++i) {
      CPPUNIT_ASSERT_EQUAL(peers[i]->getIPAddress(),
                           m->getValues()[i]->getIPAddress());
      CPPUNIT_ASSERT_EQUAL(peers[i]->getPort(), m->getValues()[i]->getPort());
    }
    CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                         util::toHex(m->getTransactionID()));
  } catch(Exception& e) {
    CPPUNIT_FAIL(e.stackTrace());
  }
}

void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage()
{
  try {
    Dict dict;
    dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
    dict.put("y", "q");
    dict.put("q", "announce_peer");
    auto aDict = Dict::g();
    aDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
    unsigned char infoHash[DHT_ID_LENGTH];
    memset(infoHash, 0x11, DHT_ID_LENGTH);
    aDict->put("info_hash", String::g(infoHash, DHT_ID_LENGTH));
    std::string token = "ffff";
    uint16_t port = 6881;
    aDict->put("port", Integer::g(port));
    aDict->put("token", token);
    dict.put("a", std::move(aDict));

    remoteNode_->setPort(6882);

    auto r = factory->createQueryMessage(&dict, "192.168.0.1", 6882);
    auto m = dynamic_cast<DHTAnnouncePeerMessage*>(r.get());

    CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
    CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
    CPPUNIT_ASSERT_EQUAL(token, m->getToken());
    CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                         util::toHex(m->getTransactionID()));
    CPPUNIT_ASSERT_EQUAL(util::toHex(infoHash, DHT_ID_LENGTH),
                         util::toHex(m->getInfoHash(), DHT_ID_LENGTH));
    CPPUNIT_ASSERT_EQUAL(port, m->getTCPPort());
  } catch(Exception& e) {
    CPPUNIT_FAIL(e.stackTrace());
  }
}

void DHTMessageFactoryImplTest::testCreateAnnouncePeerReplyMessage()
{
  Dict dict;
  dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
  dict.put("y", "r");
  auto rDict = Dict::g();
  rDict->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
  dict.put("r", std::move(rDict));

  auto r = factory->createResponseMessage("announce_peer", &dict,
                                          remoteNode_->getIPAddress(),
                                          remoteNode_->getPort());
  auto m = dynamic_cast<DHTAnnouncePeerReplyMessage*>(r.get());

  CPPUNIT_ASSERT(*localNode == *m->getLocalNode());
  CPPUNIT_ASSERT(*remoteNode_ == *m->getRemoteNode());
  CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
                       util::toHex(m->getTransactionID()));
}

void DHTMessageFactoryImplTest::testReceivedErrorMessage()
{
  Dict dict;
  dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
  dict.put("y", "e");
  auto list = List::g();
  list->append(Integer::g(404));
  list->append("Not found");
  dict.put("e", std::move(list));

  try {
    factory->createResponseMessage("announce_peer", &dict,
                                   remoteNode_->getIPAddress(),
                                   remoteNode_->getPort());
    CPPUNIT_FAIL("exception must be thrown.");
  } catch(RecoverableException& e) {
    std::cerr << e.stackTrace() << std::endl;
  }
}

} // namespace aria2


text:
package com.quollwriter.ui;

import java.awt.*;
import java.awt.event.*;

import java.io.File;

import java.net.*;

import java.text.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;
import javax.swing.table.*;
import javax.swing.tree.*;

import com.gentlyweb.utils.*;

import com.gentlyweb.xml.*;

import com.quollwriter.*;

import com.quollwriter.data.*;
import com.quollwriter.data.comparators.*;

import com.quollwriter.exporter.*;

import com.quollwriter.ui.components.*;
import com.quollwriter.ui.renderers.*;
import com.quollwriter.events.*;

public class TagsEditor extends Box implements ProjectEventListener
{

    private DefaultTableModel typeModel = null;
    private AbstractViewer viewer = null;
    private JLabel error = null;

    public TagsEditor (AbstractViewer pv)
    {

        super (BoxLayout.Y_AXIS);

        this.viewer = pv;

        Environment.addUserProjectEventListener (this);

    }

    @Override
    public void eventOccurred (ProjectEvent ev)
    {

        if (ev.getType ().equals (ProjectEvent.TAG))
        {

            this.reloadTypes ();

        }

    }

    public void init ()
    {

        final TagsEditor _this = this;

        this.setAlignmentX (Component.LEFT_ALIGNMENT);
        this.setOpaque (true);
        this.setBackground (null);
        this.add (Box.createVerticalStrut (5));

        this.add (UIUtils.createBoldSubHeader (Environment.getUIString (LanguageStrings.tags,
                                                                        LanguageStrings.actions,
                                                                        LanguageStrings.manage,
                                                                        LanguageStrings.newtag,
                                                                        LanguageStrings.title),
                                                //String.format ("New %s",
                                                  //            this.getTypesName ()),
                                               null));

        JTextPane tp = UIUtils.createHelpTextPane (Environment.getUIString (LanguageStrings.tags,
                                                                            LanguageStrings.actions,
                                                                            LanguageStrings.manage,
                                                                            LanguageStrings.newtag,
                                                                            LanguageStrings.text),
                                                   /*
                                                   String.format ("Enter the new %s to add below, separate the %s with commas or semi-colons.",
                                                                  this.getTypesName ().toLowerCase (),
                                                                  this.getTypesName ().toLowerCase ()),
                                                                  */
                                                   this.viewer);

        tp.setBorder (UIUtils.createPadding (5,
                                       5,
                                       0,
                                       5));

        this.add (tp);

        final JTextField newTypes = UIUtils.createTextField ();
        newTypes.setAlignmentX (Component.LEFT_ALIGNMENT);

        final JTable typeTable = UIUtils.createTable ();
        typeTable.setTableHeader (null);
        typeTable.setToolTipText (Environment.getUIString (LanguageStrings.tags,
                                                           LanguageStrings.actions,
                                                           LanguageStrings.manage,
                                                           LanguageStrings.table,
                                                           LanguageStrings.tooltip));
                                  //"Double click to edit, press Enter when done.");
        typeTable.setDefaultRenderer (Object.class,
                                      new DefaultTableCellRenderer ()
        {

            @Override
            public Component getTableCellRendererComponent (JTable table,
                                                            Object value,
                                                            boolean isSelected,
                                                            boolean hasFocus,
                                                            int     row,
                                                            int     column)
            {

                super.getTableCellRendererComponent (table,
                                                     value,
                                                     isSelected,
                                                     hasFocus,
                                                     row,
                                                     column);

                this.setText (((Tag) value).getName ());

                this.setBorder (UIUtils.createPadding (0, 3, 0, 3));

                return this;

            }

        });

        typeTable.setDefaultEditor (Object.class,
                                    new DefaultCellEditor (new JTextField ())
        {

            private Tag tag = null;

            @Override
            public int getClickCountToStart ()
            {

                return 2;

            }

            @Override
            public Component getTableCellEditorComponent (JTable  table,
                                                          Object  value,
                                                          boolean isSelected,
                                                          int     row,
                                                          int     column)
            {

                this.tag = (Tag) value;

                JTextField t = (JTextField) this.getComponent ();

                t.setText (this.tag.getName ().trim ());

                t.setBorder (UIUtils.createPadding (0, 3, 0, 3));

                return t;

            }

            @Override
            public boolean stopCellEditing ()
            {

                java.util.List<String> prefix = new ArrayList ();
                prefix.add (LanguageStrings.tags);
                prefix.add (LanguageStrings.actions);
                prefix.add (LanguageStrings.manage);
                prefix.add (LanguageStrings.table);
                prefix.add (LanguageStrings.edit);

                _this.error.setVisible (false);

                UIUtils.resizeParent (_this);

                String newName = ((JTextField) this.getComponent ()).getText ().trim ();

                if (newName.length () == 0)
                {

                    return _this.showError (Environment.getUIString (prefix,
                                                                     LanguageStrings.errors,
                                                                     LanguageStrings.novalue));
                    //"Tag must have a value!");

                }

                try
                {

                    Tag ot = Environment.getTagByName (newName);

                    // See if we have another tag with that name.
                    if ((ot != null)
                        &&
                        (ot != this.tag)
                       )
                    {

                        return _this.showError (Environment.getUIString (prefix,
                                                                         LanguageStrings.errors,
                                                                         LanguageStrings.novalue));
                                                //String.format ("Already have a tag called <b>%s</b>.",
                                                  //             ot.getName ()));

                    }

                } catch (Exception e) {

                    Environment.logError ("Unable to get tag for name: " + newName,
                                          e);

                    return _this.showError (Environment.getUIString (prefix,
                                                                     LanguageStrings.actionerror));
                                            //"Unable to check tag.");

                }

                this.tag.setName (newName);

                try
                {

                    Environment.saveTag (this.tag);

                } catch (Exception e) {

                    Environment.logError ("Unable to update tag: " +
                                          this.tag,
                                          e);

                    return _this.showError (Environment.getUIString (prefix,
                                                                     LanguageStrings.actionerror));
                                            //"Unable to update tag.");

                }

                _this.error.setVisible (false);

                UIUtils.resizeParent (_this.error);

                return super.stopCellEditing ();

            }

            @Override
            public void cancelCellEditing ()
            {

                _this.error.setVisible (false);

                UIUtils.resizeParent (_this.error);

                super.cancelCellEditing ();

            }

            @Override
            public Object getCellEditorValue ()
            {

                return this.tag;

            }

        });

        typeTable.addMouseListener (new MouseEventHandler ()
        {

            @Override
            public void fillPopup (final JPopupMenu m,
                                   final MouseEvent ev)
            {

                final int rowInd = typeTable.rowAtPoint (ev.getPoint ());

                if (rowInd < 0)
                {

                    return;

                }

                typeTable.setRowSelectionInterval (rowInd,
                                                   rowInd);

                m.add (UIUtils.createMenuItem (Environment.getUIString (LanguageStrings.tags,
                                                                        LanguageStrings.actions,
                                                                        LanguageStrings.manage,
                                                                        LanguageStrings.table,
                                                                        LanguageStrings.popupmenu,
                                                                        LanguageStrings.items,
                                                                        LanguageStrings.edit),
                                                                        //"Edit",
                                               Constants.EDIT_ICON_NAME,
                                               new ActionListener ()
                                               {

                                                    @Override
                                                    public void actionPerformed (ActionEvent ev)
                                                    {

                                                        typeTable.editCellAt (rowInd,
                                                                              0);

                                                    }

                                               }));

            }

        });

        this.typeModel = (DefaultTableModel) typeTable.getModel ();

        this.reloadTypes ();

        Box fb = new Box (BoxLayout.Y_AXIS);
        fb.setAlignmentX (Component.LEFT_ALIGNMENT);
        fb.add (newTypes);

        fb.add (Box.createVerticalStrut (5));
        fb.setBorder (UIUtils.createPadding (5,
                                       5,
                                       20,
                                       5));

        final JButton add = new JButton (Environment.getUIString (LanguageStrings.tags,
                                                                  LanguageStrings.actions,
                                                                  LanguageStrings.manage,
                                                                  LanguageStrings.newtag,
                                                                  LanguageStrings.add));
                                         //"Add");

        JButton[] buts = new JButton[] { add };

        final ActionAdapter aa = new ActionAdapter ()
        {

            public void actionPerformed (ActionEvent ev)
            {

                String n = newTypes.getText ();

                StringTokenizer t = new StringTokenizer (n,
                                                         ",;");

                while (t.hasMoreTokens ())
                {

                    String w = t.nextToken ().trim ();

                    if (w.length () == 0)
                    {

                        continue;

                    }

                    try
                    {

                        if (Environment.getTagByName (w) != null)
                        {

                            continue;

                        }

                    } catch (Exception e) {

                        Environment.logError ("Unable to get tag for name: " + w,
                                              e);

                        continue;

                    }

                    DefaultTableModel m = (DefaultTableModel) typeTable.getModel ();

                    Tag tag = new Tag ();
                    tag.setName (w);

                    try
                    {

                        Environment.saveTag (tag);

                    } catch (Exception e) {

                        Environment.logError ("Unable to add tag: " +
                                              tag,
                                              e);

                        UIUtils.showErrorMessage (_this.viewer,
                                                  Environment.getUIString (LanguageStrings.tags,
                                                                           LanguageStrings.actions,
                                                                           LanguageStrings.manage,
                                                                           LanguageStrings.newtag,
                                                                           LanguageStrings.actionerror));
                                                  //"Unable to add tag.");

                        return;

                    }

                    Vector r = new Vector ();
                    r.add (tag);
                    m.insertRow (0,
                                 r);

                }

                newTypes.setText ("");

            }

        };

        add.addActionListener (aa);

        UIUtils.addDoActionOnReturnPressed (newTypes,
                                            aa);

        fb.add (UIUtils.createButtonBar2 (buts, Component.LEFT_ALIGNMENT));

        this.add (fb);

        java.util.List<String> prefix = new ArrayList ();
        prefix.add (LanguageStrings.tags);
        prefix.add (LanguageStrings.actions);
        prefix.add (LanguageStrings.manage);
        prefix.add (LanguageStrings.table);

        this.add (UIUtils.createBoldSubHeader (Environment.getUIString (prefix,
                                                                        LanguageStrings.title),
                                               null));

        fb = new Box (BoxLayout.Y_AXIS);
        fb.setAlignmentX (Component.LEFT_ALIGNMENT);
        fb.setBorder (UIUtils.createPadding (5,
                                       5,
                                       0,
                                       5));

        tp = UIUtils.createHelpTextPane (Environment.getUIString (prefix,
                                                                  LanguageStrings.text),
                                         this.viewer);
        tp.setBorder (null);
        fb.add (tp);
        fb.add (Box.createVerticalStrut (10));

        final JScrollPane ppsp = UIUtils.createScrollPane (typeTable);

        typeTable.setPreferredScrollableViewportSize (new Dimension (-1,
                                                                     (typeTable.getRowHeight () + 3) * 5));

        this.error = UIUtils.createErrorLabel ("");//Please enter a value.");
        this.error.setVisible (false);

        this.error.setBorder (UIUtils.createPadding (5, 0, 5, 5));

        fb.add (this.error);

        fb.add (ppsp);

        final JButton remove = new JButton (Environment.getUIString (LanguageStrings.tags,
                                                                     LanguageStrings.actions,
                                                                     LanguageStrings.manage,
                                                                     LanguageStrings.table,
                                                                     LanguageStrings.remove));
                                                                           //"Remove Selected");

        buts = new JButton[] { remove };

        remove.addActionListener (new ActionAdapter ()
        {

            public void actionPerformed (ActionEvent ev)
            {

                DefaultTableModel m = (DefaultTableModel) typeTable.getModel ();

                int[] selection = typeTable.getSelectedRows ();

                for (int i = selection.length - 1; i > -1; i--)
                {

                    Tag tag = (Tag) m.getValueAt (selection[i],
                                                  0);

                    // Remove the row.
                    m.removeRow (selection[i]);

                    try
                    {

                        Environment.deleteTag (tag);

                    } catch (Exception e) {

                        Environment.logError ("Unable to delete tag: " +
                                              tag,
                                              e);

                        UIUtils.showErrorMessage (_this.viewer,
                                                  Environment.getUIString (LanguageStrings.tags,
                                                                           LanguageStrings.actions,
                                                                           LanguageStrings.manage,
                                                                           LanguageStrings.table,
                                                                           LanguageStrings.delete,
                                                                           LanguageStrings.actionerror));
                                                  //"Unable to delete tag.");

                        return;

                    }

                }

                ((DefaultListSelectionModel) typeTable.getSelectionModel ()).clearSelection ();

            }

        });

        fb.add (Box.createVerticalStrut (5));

        fb.add (UIUtils.createButtonBar2 (buts, Component.LEFT_ALIGNMENT));

        this.add (fb);

        JButton finish = new JButton (Environment.getUIString (LanguageStrings.tags,
                                                               LanguageStrings.actions,
                                                               LanguageStrings.manage,
                                                               LanguageStrings.finish));
                                      //"Finish");

        finish.addActionListener (new ActionAdapter ()
        {

            public void actionPerformed (ActionEvent ev)
            {

                _this.error.setVisible (false);

                UIUtils.closePopupParent (_this.getParent ());

            }

        });

        buts = new JButton[] { finish };

        JPanel bp = UIUtils.createButtonBar2 (buts,
                                              Component.CENTER_ALIGNMENT);
        bp.setOpaque (false);

        this.add (Box.createVerticalStrut (10));

        this.add (bp);

        //return b;

    }

    private boolean showError (String m)
    {

        this.error.setText (m);

        this.error.setVisible (true);

        UIUtils.resizeParent (this.error);

        return false;

    }

    public void reloadTypes ()
    {

        Set<Tag> tags = null;

        try
        {

            tags = Environment.getAllTags ();

        } catch (Exception e) {

            Environment.logError ("Unable to get all tags",
                                  e);

            UIUtils.showErrorMessage (this.viewer,
                                      Environment.getUIString (LanguageStrings.tags,
                                                               LanguageStrings.actions,
                                                               LanguageStrings.manage,
                                                               LanguageStrings.table,
                                                               LanguageStrings.loadallerror));
//                                      "Unable to get the tags.");

            return;

        }

        Vector tagsData = new Vector ();

        TreeSet<Tag> nt = new TreeSet (NamedObjectSorter.getInstance ());

        nt.addAll (tags);

        for (Tag t : nt)
        {

            Vector d = new Vector ();
            d.add (t);

            tagsData.add (d);

        }

        Vector<String> cols = new Vector ();
        cols.add ("Tag");

        this.typeModel.setDataVector (tagsData,
                                      cols);

    }

    public String getHeaderIconType ()
    {

        return Constants.TAG_ICON_NAME;

    }

}