text:
layout: page
title: Madison Curtis's 19th Birthday
date: 2016-05-24
author: Bryan Douglas
tags: weekly links, java
status: published
summary: Vestibulum ante ipsum primis in.
banner: images/banner/wedding.jpg
booking:
  startDate: 10/31/2017
  endDate: 11/03/2017
  ctyhocn: PHLVYHX
  groupCode: MC1B
published: true
---
Praesent eget vestibulum massa. Nunc pulvinar ipsum mauris, in imperdiet est pellentesque sed. Nam ut magna laoreet, tincidunt lacus eget, volutpat felis. Pellentesque tempus neque vel malesuada iaculis. Etiam tincidunt non quam ac lobortis. Duis in mauris placerat, volutpat magna vitae, dignissim mauris. Vivamus ultricies convallis est. Nulla lorem dui, eleifend eu sem id, interdum placerat turpis. Aenean lobortis odio vel lorem mollis, sit amet euismod arcu egestas. Suspendisse a pretium quam, nec fermentum velit.
Cras at nisl pulvinar, pharetra ante sit amet, ultricies ipsum. Aliquam tincidunt maximus purus, ac imperdiet purus euismod in. Nam dui lorem, commodo eget pharetra vel, finibus vel metus. Sed ullamcorper magna non quam aliquam, non lobortis mauris dignissim. Praesent ultrices commodo enim sit amet suscipit. Morbi vel lorem sed turpis molestie lacinia. Fusce quis nulla nec enim tincidunt varius a vitae nisl. Nullam pellentesque diam blandit hendrerit rhoncus. Etiam cursus vitae odio non ultrices. Donec blandit ex non hendrerit placerat. Nulla fermentum egestas consectetur.

* Donec condimentum ante sit amet varius vehicula
* Sed maximus diam dignissim diam faucibus, nec pretium velit suscipit
* Nam non dolor hendrerit, ullamcorper massa id, tincidunt mauris
* Nunc lacinia lorem ac odio iaculis gravida
* Aenean accumsan mi non purus ultricies vulputate
* Sed at magna tristique, feugiat dolor id, imperdiet ex.

Aenean massa mauris, suscipit vitae ante at, rutrum cursus nisi. Aliquam quis leo et felis pharetra iaculis vitae eu augue. Nullam odio tellus, vulputate vel hendrerit sed, congue id ipsum. Duis eget enim at nisi interdum congue ut ac tellus. Vestibulum fermentum viverra feugiat. Mauris eu mauris quis dui interdum bibendum. Donec in sodales tellus. Curabitur eget ex mi. Maecenas iaculis mattis bibendum. Aenean dignissim ante erat, non sollicitudin arcu pretium ut.


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace DotNetRevolution.Core.Messaging
{
    public class MessageCatalog : IMessageCatalog
    {
        private readonly Dictionary<Type, IMessageEntry> _entries = new Dictionary<Type, IMessageEntry>();

        public MessageCatalog()
        {
        }

        public MessageCatalog(IReadOnlyCollection<IMessageEntry> entries)
        {
            Contract.Requires(entries != null);
            Contract.Requires(Contract.ForAll(entries, o => o != null));

            foreach (var entry in entries)
            {
                Contract.Assume(entry != null);

                Add(entry);
            }
        }

        public IMessageEntry GetEntry(Type messageType)
        {
            var result = _entries[messageType];
            Contract.Assume(result != null);

            return result;
        }

        public IMessageCatalog Add(IMessageEntry entry)
        {
            _entries.Add(entry.MessageType, entry);

            Contract.Assume(GetEntry(entry.MessageType) == entry);

            return this;
        }

        [ContractInvariantMethod]
        private void ObjectInvariants()
        {
            Contract.Invariant(_entries != null);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface JBStore ()

@property (weak, nonatomic) JBDispatcher *dispatcher;

@property (strong, nonatomic) NSMapTable *changeEventCallbacks;

@property (strong, nonatomic) NSDictionary *actionHandlersSelectorCache;
@property (assign, nonatomic) BOOL respondsToStoreWillHandleAction;
@property (assign, nonatomic) BOOL respondsToStoreDidHandleAction;

@end

@implementation JBStore

#pragma mark - JBDispatcherFriend

// Private initializer used by the JBDispatcher class
//
- (instancetype)initWithDispatcher_JBDispatcherFriendFunction:(JBDispatcher *)dispatcher {
    self = [super init];
    if (self) {
        _dispatcher = dispatcher;
        _changeEventCallbacks = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsWeakMemory valueOptions:NSPointerFunctionsCopyIn capacity:10];

        _respondsToStoreWillHandleAction = [self respondsToSelector:@selector(storeWillHandleAction:)];
        _respondsToStoreDidHandleAction = [self respondsToSelector:@selector(storeDidHandleAction:)];

        [self cacheActionHandlersSelectors];
    }
    return self;
}

// Private function called by the dispatcher when invoking action on the store.
//
- (void)invokeAction_JBDispatcherFriendFunction:(JBAction *)action {
    NSString *actionHandlerSelectorString = _actionHandlersSelectorCache[action.eventName];

    if (!actionHandlerSelectorString) return;

    if (_respondsToStoreWillHandleAction) [self storeWillHandleAction:action];

    SEL actionHandlerSelector = NSSelectorFromString(actionHandlerSelectorString);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:actionHandlerSelector withObject:action];
#pragma clang diagnostic pop

    if (_respondsToStoreDidHandleAction) [self storeDidHandleAction:action];
}

#pragma mark - JBStore

- (void)registerObject:(id)object forChangeEvents:(ChangeEventCallback)changeEventCallback {
    [_changeEventCallbacks setObject:changeEventCallback forKey:object];
}

- (void)unregisterObjectFromChangeEvents:(id)object {
    [_changeEventCallbacks removeObjectForKey:object];
}

- (void)emitChange {
    [self emitChangeWithError:nil];
}

- (void)emitChangeWithError:(NSError *)error {
    __weak __typeof(self) weakself = self;
    for (ChangeEventCallback changeEventCallback in [[_changeEventCallbacks objectEnumerator] allObjects]) {
        changeEventCallback(weakself, error);
    }
}

+ (NSDictionary *)actionHandlerNamesByActionEventNames {
    [NSException raise:@"Error" format:@"JBStore is an abstract class, you must implement your own JBStore subclasses that properly implement actionHandlerNamesByActionEventNames"];
    return nil;
}

#pragma mark - Private

- (void)cacheActionHandlersSelectors {
    NSMutableDictionary *actionSelectorsDic = [[NSMutableDictionary alloc] init];
    [[(id<JBStore>)[self class] actionHandlerNamesByActionEventNames] enumerateKeysAndObjectsUsingBlock:^(NSString   * _Nonnull key, NSString   * _Nonnull obj, BOOL * _Nonnull stop) {
        actionSelectorsDic[key] = [obj stringByAppendingString:@":"];
    }];
    _actionHandlersSelectorCache = [NSDictionary dictionaryWithDictionary:actionSelectorsDic];
}

@end


text:
package org.semispace.event;

/**
 * An event on an element in the semispace. The event as such is
 * distributed through notify (by terracotta).
 */
public abstract class SemiEvent {
    /**
     * The id of the object in the system
     */
    public abstract long getId();
}


text:
=====

This module allows the user to embed and run rqt progrms directly from the IDE.


text:
package main

import (
	"database/sql"
	"github.com/blackjack/syslog"
	"github.com/mikkolehtisalo/cvesync/blacklist"
	"github.com/mikkolehtisalo/cvesync/nvd"
	"github.com/mikkolehtisalo/cvesync/tracker"
	"github.com/mikkolehtisalo/cvesync/util"
)

var (
	config util.ServiceConfiguration
	blist  blacklist.BlackList
)

func sync(feed nvd.CVE, cwes nvd.CWE, ts tracker.Tracker) {
	db := util.Get_DB(config.DBFile)
	defer db.Close()

	// Initialize tracker
	ts.Init()

	// Reverse the order as the xml feed is sorted from newest to oldest
	for i := len(feed.Entries) - 1; i >= 0; i-- {
		entry := feed.Entries[i]
		// Is any of the mentioned products on the blacklist?
		if !blist.Blacklisted(entry) {
			sync_entry(entry, db, cwes, ts)
		} else {
			syslog.Infof("Not syncing %v because one of the products were blacklisted", entry.Id)
		}
	}
}

func sync_entry(entry nvd.Entry, db *sql.DB, cwes nvd.CWE, ts tracker.Tracker) {
	entry.CWE.CWECatalog = &cwes
	// Completely new?
	if !util.Exists(db, entry.Id) {
		syslog.Noticef("Adding new CVE %s", entry.Id)
		id, err := ts.Add(entry)
		if err != nil {
			syslog.Errf("Unable to add %v to issue tracker: %v", entry.Id, err)
			return
		}
		// Add to database, too
		util.DB_Add(db, entry.Id, entry.Last_Modified, id)
		// Already existing, but modified?
	} else if !util.Modified_Matches(db, entry.Id, entry.Last_Modified) {
		syslog.Noticef("Modifying old CVE %s", entry.Id)
		ticketid := util.DB_TicketID(db, entry.Id)
		err := ts.Update(entry, ticketid)
		if err != nil {
			syslog.Errf("Unable to modify %v in issue tracker: %v", entry.Id, err)
			return
		}
		// Update to database, too
		util.DB_Update(db, entry.Id, entry.Last_Modified)
	}
}

func main() {
	syslog.Openlog("cvesync", syslog.LOG_PID, syslog.LOG_DAEMON)
	syslog.Info("Cvesync started")

	config = util.Load_Config("/opt/cvesync/etc/settings.json")
	blist = blacklist.Load_Blacklist(config.BlackList)
	cve_feed := nvd.Get_CVE_feed(config.FeedURL, config.CAKeyFile)
	cwes := nvd.Get_CWEs(config.CWEfile)

	ts := tracker.Jira{}
	//ts := tracker.RT{}
	sync(cve_feed, cwes, &ts)

	syslog.Info("Cvesync ended")
}


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/ads/googleads/v12/errors/ad_customizer_error.proto", :syntax => :proto3) do
    add_message "google.ads.googleads.v12.errors.AdCustomizerErrorEnum" do
    end
    add_enum "google.ads.googleads.v12.errors.AdCustomizerErrorEnum.AdCustomizerError" do
      value :UNSPECIFIED, 0
      value :UNKNOWN, 1
      value :COUNTDOWN_INVALID_DATE_FORMAT, 2
      value :COUNTDOWN_DATE_IN_PAST, 3
      value :COUNTDOWN_INVALID_LOCALE, 4
      value :COUNTDOWN_INVALID_START_DAYS_BEFORE, 5
      value :UNKNOWN_USER_LIST, 6
    end
  end
end

module Google
  module Ads
    module GoogleAds
      module V12
        module Errors
          AdCustomizerErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v12.errors.AdCustomizerErrorEnum").msgclass
          AdCustomizerErrorEnum::AdCustomizerError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v12.errors.AdCustomizerErrorEnum.AdCustomizerError").enummodule
        end
      end
    end
  end
end


text:
package org.apache.lucene.misc;

import java.nio.file.Paths;
import java.util.Locale;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;

/**
 * Utility to get document frequency and total number of occurrences (sum of the tf for each doc)  of a term.
 */
public class GetTermInfo {

  public static void main(String[] args) throws Exception {

    FSDirectory dir = null;
    String inputStr = null;
    String field = null;

    if (args.length == 3) {
      dir = FSDirectory.open(Paths.get(args[0]));
      field = args[1];
      inputStr = args[2];
    } else {
      usage();
      System.exit(1);
    }

    getTermInfo(dir,new Term(field, inputStr));
  }

  public static void getTermInfo(Directory dir, Term term) throws Exception {
    IndexReader reader = DirectoryReader.open(dir);
    System.out.printf(Locale.ROOT, "%s:%s \t totalTF = %,d \t doc freq = %,d \n",
         term.field(), term.text(), reader.totalTermFreq(term), reader.docFreq(term));
  }

  private static void usage() {
    System.out
        .println("\n\nusage:\n\t"
            + "java " + GetTermInfo.class.getName() + " <index dir> field term \n\n");
  }
}


text:
class SDPColumn {
 public:
	int col;
	int optFragment;
	int operator<(const SDPColumn & rhs) const {
		return col < rhs.col;
	}
	int operator<(const int y) const {
		return col < y;
	}
	int operator==(const SDPColumn &rhs) const {
		return col == rhs.col;
	}
	int operator>(const SDPColumn &rhs) const {
		return (!(*this < rhs) && !(*this == rhs));
	}
};

#endif


text:
using System.Data.Common;
using System.Web.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Mindscape.Raygun4Net;

namespace SSW.MusicStore.API.Filters
{
    public class MvcExceptionActionFilter : ActionFilterAttribute
    {
        private readonly IConfigurationRoot config;

        public MvcExceptionActionFilter(IConfigurationRoot config)
        {
            this.config = config;
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);

            if (context.Exception == null)
            {
                return;
            }

            var dbException = context.Exception as DbException;
            if (dbException != null)
            {
                context.Result = new BadRequestObjectResult(dbException);
            }
            else
            {
                context.Result = new InternalServerErrorResult();
            }

            var apiKey = this.config["RaygunSettings:ApiKey"];
            if (string.IsNullOrEmpty(apiKey))
            {
                return;
            }

            //TODO: update this once Raygun supports ASPNET CORE RTM
            //var settings = new RaygunSettings { ApiKey = apiKey };

            //var client = new RaygunClient(settings);
            //client.Send(context.Exception);
        }
    }
}


text:
(function() {
'use strict';

/**
 * @ngdoc module
 * @name material.components.tooltip
 */
angular.module('material.components.tooltip', [
  'material.core'
])
  .directive('mdTooltip', MdTooltipDirective);

/**
 * @ngdoc directive
 * @name mdTooltip
 * @module material.components.tooltip
 * @description
 * Tooltips are used to describe elements that are interactive and primarily graphical (not textual).
 *
 * Place a `<md-tooltip>` as a child of the element it describes.
 *
 * A tooltip will activate when the user focuses, hovers over, or touches the parent.
 *
 * @usage
 * <hljs lang="html">
 * <md-icon icon="/img/icons/ic_play_arrow_24px.svg">
 *   <md-tooltip>
 *     Play Music
 *   </md-tooltip>
 * </md-icon>
 * </hljs>
 *
 * @param {expression=} md-visible Boolean bound to whether the tooltip is
 * currently visible.
 */
function MdTooltipDirective($timeout, $window, $$rAF, $document, $mdUtil, $mdTheming, $rootElement) {

  var TOOLTIP_SHOW_DELAY = 400;
  var TOOLTIP_WINDOW_EDGE_SPACE = 8;

  return {
    restrict: 'E',
    transclude: true,
    template:
      '

' +
      '

',
    scope: {
      visible: '=?mdVisible'
    },
    link: postLink
  };

  function postLink(scope, element, attr, contentCtrl) {
    $mdTheming(element);
    var parent = element.parent();

    // Look for the nearest parent md-content, stopping at the rootElement.
    var current = element.parent()[0];
    while (current && current !== $rootElement[0] && current !== document.body) {
      if (current.tagName && current.tagName.toLowerCase() == 'md-content') break;
      current = current.parentNode;
    }
    var tooltipParent = angular.element(current || document.body);

    // We will re-attach tooltip when visible
    element.detach();
    element.attr('role', 'tooltip');
    element.attr('id', attr.id || ('tooltip_' + $mdUtil.nextUid()));

    parent.on('focus mouseenter touchstart', function() {
      setVisible(true);
    });
    parent.on('blur mouseleave touchend touchcancel', function() {
      // Don't hide the tooltip if the parent is still focused.
      if ($document[0].activeElement === parent[0]) return;
      setVisible(false);
    });

    scope.$watch('visible', function(isVisible) {
      if (isVisible) showTooltip();
      else hideTooltip();
    });

    var debouncedOnResize = $$rAF.debounce(function windowResize() {
      // Reposition on resize
      if (scope.visible) positionTooltip();
    });
    angular.element($window).on('resize', debouncedOnResize);

    // Be sure to completely cleanup the element on destroy
    scope.$on('$destroy', function() {
      scope.visible = false;
      element.remove();
      angular.element($window).off('resize', debouncedOnResize);
    });

    // *******
    // Methods
    // *******

    // If setting visible to true, debounce to TOOLTIP_SHOW_DELAY ms
    // If setting visible to false and no timeout is active, instantly hide the tooltip.
    function setVisible(value) {
      setVisible.value = !!value;

      if (!setVisible.queued) {
        if (value) {
          setVisible.queued = true;
          $timeout(function() {
            scope.visible = setVisible.value;
            setVisible.queued = false;
          }, TOOLTIP_SHOW_DELAY);

        } else {
          $timeout(function() { scope.visible = false; });
        }
      }
    }

    function showTooltip() {
      // Insert the element before positioning it, so we can get position
      // (tooltip is hidden by default)
      element.removeClass('md-hide');
      parent.attr('aria-describedby', element.attr('id'));
      tooltipParent.append(element);

      // Wait until the element has been in the dom for two frames before
      // fading it in.
      // Additionally, we position the tooltip twice to avoid positioning bugs
      positionTooltip();
      $$rAF(function() {

        $$rAF(function() {
          positionTooltip();
          if (!scope.visible) return;
          element.addClass('md-show');
        });

      });
    }

    function hideTooltip() {
      element.removeClass('md-show').addClass('md-hide');
      parent.removeAttr('aria-describedby');
      $timeout(function() {
        if (scope.visible) return;
        element.detach();
      }, 200, false);
    }

    function positionTooltip() {
      var tipRect = $mdUtil.elementRect(element, tooltipParent);
      var parentRect = $mdUtil.elementRect(parent, tooltipParent);

      // Default to bottom position if possible
      var tipDirection = 'bottom';
      var newPosition = {
        left: parentRect.left + parentRect.width / 2 - tipRect.width / 2,
        top: parentRect.top + parentRect.height
      };

      // If element bleeds over left/right of the window, place it on the edge of the window.
      newPosition.left = Math.min(
        newPosition.left,
        tooltipParent.prop('scrollWidth') - tipRect.width - TOOLTIP_WINDOW_EDGE_SPACE
      );
      newPosition.left = Math.max(newPosition.left, TOOLTIP_WINDOW_EDGE_SPACE);

      // If element bleeds over the bottom of the window, place it above the parent.
      if (newPosition.top + tipRect.height > tooltipParent.prop('scrollHeight')) {
        newPosition.top = parentRect.top - tipRect.height;
        tipDirection = 'top';
      }

      element.css({top: newPosition.top + 'px', left: newPosition.left + 'px'});
      // Tell the CSS the size of this tooltip, as a multiple of 32.
      element.attr('width-32', Math.ceil(tipRect.width / 32));
      element.attr('md-direction', tipDirection);
    }

  }

}
})();


text:
import params from 'constants';

import math from 'math';
import lineUtils from 'line-utils';
import letterUtils from 'letter-utils';
import colors from 'colors';
import graphics from 'graphics';

//import mocks from 'mocks';

function strokeWidthTransform(imageData, cannyImage, sobelImage, darkOnLight){
  console.group(darkOnLight ? 'dark on light' : 'light on dark');
  console.time('total processing time');

  var strokeWidthMatrix = createStrokeWidthMatrix(cannyImage, sobelImage, darkOnLight);

  //first attempt on the raw stroke width transformation
  var letters = letterUtils.findLetters(strokeWidthMatrix);
  var lines = lineUtils.findLines(letters);

  //this is a clever thing Naptha does. Once we have line candidates
  //we can run a morphological dilation and use the result
  //to improve the quality by running again using that data
  var dilationMatrix = graphics.dilate(lines, imageData);
  var marker = colors.colorFilter(lines, imageData, dilationMatrix);

  letters = letterUtils.findLetters(strokeWidthMatrix, marker);
  lines = lineUtils.findLines(letters);

  console.log('found ' + lines.length + ' lines');

  console.timeEnd('total processing time');
  console.groupEnd();
  return lines;
}

function createStrokeWidthMatrix(cannyImage, sobelImage, darkOnLight){
  console.time('create stroke width matrix');

  var width = cannyImage.cols;
  var height = cannyImage.rows;

  var rays = [];
  var strokeWidthMatrix = new jsfeat.matrix_t(width, height, jsfeat.U8C1_t);
  //using the canny edges and the sobel gradient, we calculare the ray vectors
  //walking all the pixels of the image and operating on the white edge pixels
  for(var i = 0; i < width * height; i++){
    //we have to get only the white pixels
    //to calculate ray starts
    if(cannyImage.data[i] !== 0xff) { continue; }
    //calculate the angle of the gradient
    //var itheta = math.theta(i, sobelImage);
    var theta = math.theta(i, sobelImage);
    var origin = math.indexToPoint(i, width);
    var ray = createRay(cannyImage, i, origin.x, origin.y, theta, width, height, darkOnLight);
    rays.push(ray);
    calculateStrokeWidth(strokeWidthMatrix, sobelImage, ray, theta, origin.x, origin.y, width);
  }

  console.timeEnd('create stroke width matrix');
  return strokeWidthMatrix;
}

function calculateStrokeWidth(strokeWidthMatrix, sobelImage, ray, originTheta, originX, originY, width) {
  //a ray has at least one point, the starting point
  //there is no need to do boundary checks.

  //we get the angle of the gradient at the end of the ray
  var theta = math.theta(ray[ray.length - 1], sobelImage);
  var point = math.indexToPoint(ray[ray.length - 1], width);

  if(Math.abs(Math.abs(originTheta - theta) - Math.PI) < Math.PI / 2) {
    var strokeWidth = Math.sqrt(
      (point.x - originX) * (point.x - originX) +
      (point.y - originY) * (point.y - originY)
    ); // derive the stroke width

    //we iterate over the ray points and save the stroke width for
    //that point on a matrix.
    for(var i = 0; i < ray.length; i++){

      strokeWidth = strokeWidthMatrix.data[ray[i]] !== 0 && strokeWidthMatrix.data[ray[i]] < strokeWidth ?
        strokeWidthMatrix.data[ray[i]] :
        strokeWidth;
      //if we've been on this point before, we save the smallest value
      //strokeWidthMatrix.data[ray[i]] = math.nzmin(strokeWidthMatrix.data[ray[i]], strokeWidth);
      strokeWidthMatrix.data[ray[i]] = strokeWidth;
    }
  }
}

function createRay(cannyImage, index, originX, originY, theta, width, height, darkOnLight) {
  //we find the other end of the vector
  //extrapolate the ray, as libccv does using bresenham's line algorithm
  //http://en.wikipedia.org/wiki/Bresenham's_line_algorithm

  //direction of the gradient
  var direction = darkOnLight ? -1 : 1;

  //stating ray index
  var ray = [index];
  for(var i = 1; i < params.max_stroke; i++) {
    var x = Math.round(originX + Math.cos(theta) * direction * i);
    var y = Math.round(originY + Math.sin(theta) * direction * i);

    //we need to stop if we reach the boundaries of the image
    //without saving an invalid position
    if(x < 0 || y < 0 || x > width || y > height) {
      break;
    }

    var j = y * width + x;
    ray.push(j);

    //we've reached the other end of the stroke before
    //hitting the limit
    if(cannyImage.data[j] === 0xff) {
      break;
    }
  }

  //we return all the elements that conform the ray
  return ray;
}

var swt = {
  transform: function (imageData, cannyImage, sobelImage) {
    var darkOnLightLines = strokeWidthTransform(imageData, cannyImage, sobelImage, true);
    var lightOnDarkLines = strokeWidthTransform(imageData, cannyImage, sobelImage, false);

    var lines = darkOnLightLines
      .concat(lightOnDarkLines)
      .sort(function(a, b){
        return a.center.y - b.center.y;
      });

    return lines;
    // return mocks;
  }
};

export default swt;


text:
package dao;

import java.util.List;

import javax.persistence.Query;

import model.Usuario;

public class UsuarioDao extends DAO {

	public List<Usuario> listar(Object filtros, String ordem, int qtdTuplas) throws DAOException{
		return super.listarParametros(Usuario.class, filtros, ordem, qtdTuplas);
	}

	public Usuario usuarioPorEmail(String email) throws DAOException{
		try {

			Query query = criarQuery("from Usuario u where u.email = :param");
			query.setParameter("param", email);
			List<Usuario> list = query.getResultList();
			if(list != null && !list.isEmpty()){return list.get(0);}
			else{
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new DAOException(e.getMessage());
		}
	}

}


text:
<?php

/** Zend_Pdf_ElementFactory_Interface */
require_once 'Zend/Pdf/ElementFactory/Interface.php';

/** Zend_Pdf_ElementFactory_Proxy */
require_once 'Zend/Pdf/ElementFactory/Proxy.php';

/** Zend_Pdf_Element */
require_once 'Zend/Pdf/Element.php';

/** Zend_Pdf_Element_Array */
require_once 'Zend/Pdf/Element/Array.php';

/** Zend_Pdf_Element_String_Binary */
require_once 'Zend/Pdf/Element/String/Binary.php';

/** Zend_Pdf_Element_Boolean */
require_once 'Zend/Pdf/Element/Boolean.php';

/** Zend_Pdf_Element_Dictionary */
require_once 'Zend/Pdf/Element/Dictionary.php';

/** Zend_Pdf_Element_Name */
require_once 'Zend/Pdf/Element/Name.php';

/** Zend_Pdf_Element_Numeric */
require_once 'Zend/Pdf/Element/Numeric.php';

/** Zend_Pdf_Element_Object */
require_once 'Zend/Pdf/Element/Object.php';

/** Zend_Pdf_Element_Reference */
require_once 'Zend/Pdf/Element/Reference.php';

/** Zend_Pdf_Element_Object_Stream */
require_once 'Zend/Pdf/Element/Object/Stream.php';

/** Zend_Pdf_Element_String */
require_once 'Zend/Pdf/Element/String.php';

/** Zend_Pdf_Element_Null */
require_once 'Zend/Pdf/Element/Null.php';

/** Zend_Pdf_UpdateInfoContainer */
require_once 'Zend/Pdf/UpdateInfoContainer.php';

/**
 * PDF element factory.
 * Responsibility is to log PDF changes
 *
 * @package    Zend_Pdf
 * @copyright  Copyright (c) 2005-2007 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Pdf_ElementFactory implements Zend_Pdf_ElementFactory_Interface
{
    /**
     * List of the modified objects.
     * Also contains new and removed objects
     *
     * Array: ojbectNumber => Zend_Pdf_Element_Object
     *
     * @var array
     */
    private $_modifiedObjects = array();

    /**
     * List of the removed objects
     *
     * Array: ojbectNumber => Zend_Pdf_Element_Object
     *
     * @var array
     */
    private $_removedObjects = array();

    /**
     * List of registered objects.
     * Used for resources clean up when factory is destroyed.
     *
     * Array of Zend_Pdf_Element objects
     *
     * @var array
     */
    private $_registeredObjects = array();

    /**
     * PDF object counter.
     * Actually it's an object number for new PDF object
     *
     * @var integer
     */
    private $_objectCount;

    /**
     * List of the attached object factories.
     * Array of Zend_Pdf_ElementFactory_Interface objects
     *
     * @var array
     */
    private $_attachedFactories = array();

    /**
     * Factory internal id
     *
     * @var integer
     */
    private $_factoryId;

    /**
     * Identity, used for factory id generation
     *
     * @var integer
     */
    private static $_identity = 0;

    /**
     * Internal cache to save calculated shifts
     *
     * @var array
     */
    private $_shiftCalculationCache = array();

    /**
     * Object constructor
     *
     * @param integer $objCount
     */
    public function __construct($objCount)
    {
        $this->_objectCount       = (int)$objCount;
        $this->_factoryId         = self::$_identity++;
    }

    /**
     * Factory generator
     *
     * @param integer $objCount
     * @return Zend_Pdf_ElementFactory_Interface
     */
    static public function createFactory($objCount)
    {
        return new Zend_Pdf_ElementFactory_Proxy(new Zend_Pdf_ElementFactory($objCount));
    }

    /**
     * Close factory and clean-up resources
     *
     * @internal
     */
    public function close()
    {
        $this->_modifiedObjects   = null;
        $this->_removedObjects    = null;
        $this->_attachedFactories = null;

        foreach ($this->_registeredObjects as $obj) {
            $obj->cleanUp();
        }
        $this->_registeredObjects = null;
    }

    /**
     * Get source factory object
     *
     * @return Zend_Pdf_ElementFactory
     */
    public function resolve()
    {
        return $this;
    }

    /**
     * Get factory ID
     *
     * @return integer
     */
    public function getId()
    {
        return $this->_factoryId;
    }

    /**
     * Set object counter
     *
     * @param integer $objCount
     */
    public function setObjectCount($objCount)
    {
        $this->_objectCount = (int)$objCount;
    }

    /**
     * Get object counter
     *
     * @return integer
     */
    public function getObjectCount()
    {
        $count = $this->_objectCount;

        foreach ($this->_attachedFactories as $attached) {
            $count += $attached->getObjectCount() - 1; // -1 as "0" object is a special case and shared between factories
        }

        return $count;
    }

    /**
     * Attach factory to the current;
     *
     * @param Zend_Pdf_ElementFactory_Interface $factory
     */
    public function attach(Zend_Pdf_ElementFactory_Interface $factory)
    {
        if ( $factory === $this || isset($this->_attachedFactories[$factory->getId()])) {
            /**
             * Don't attach factory twice.
             * We do not check recusively because of nature of attach operation
             * (Pages are always attached to the Documents, Fonts are always attached
             * to the pages even if pages already use Document level object factory and so on)
             */
            return;
        }

        $this->_attachedFactories[$factory->getId()] = $factory;
    }

    /**
     * Calculate object enumeration shift.
     *
     * @internal
     * @param Zend_Pdf_ElementFactory_Interface $factory
     * @return integer
     */
    public function calculateShift(Zend_Pdf_ElementFactory_Interface $factory)
    {
        if ($factory === $this) {
            return 0;
        }

        if (isset($this->_shiftCalculationCache[$factory->_factoryId])) {
            return $this->_shiftCalculationCache[$factory->_factoryId];
        }

        $shift = $this->_objectCount - 1;

        foreach ($this->_attachedFactories as $subFactory) {
            $subFactoryShift = $subFactory->calculateShift($factory);

            if ($subFactoryShift != -1) {
                // context found
                $this->_shiftCalculationCache[$factory->_factoryId] = $shift + $subFactoryShift;
                return $shift + $subFactoryShift;
            } else {
                $shift += $subFactory->getObjectCount()-1;
            }
        }

        $this->_shiftCalculationCache[$factory->_factoryId] = -1;
        return -1;
    }

    /**
     * Retrive object enumeration shift.
     *
     * @param Zend_Pdf_ElementFactory_Interface $factory
     * @return integer
     * @throws Zend_Pdf_Exception
     */
    public function getEnumerationShift(Zend_Pdf_ElementFactory_Interface $factory)
    {
        if (($shift = $this->calculateShift($factory)) == -1) {
            throw new Zend_Pdf_Exception('Wrong object context');
        }

        return $shift;
    }

    /**
     * Mark object as modified in context of current factory.
     *
     * @param Zend_Pdf_Element_Object $obj
     * @throws Zend_Pdf_Exception
     */
    public function markAsModified(Zend_Pdf_Element_Object $obj)
    {
        if ($obj->getFactory() !== $this) {
            throw new Zend_Pdf_Exception('Object is not generated by this factory');
        }

        $this->_modifiedObjects[$obj->getObjNum()] = $obj;
    }

    /**
     * Remove object in context of current factory.
     *
     * @param Zend_Pdf_Element_Object $obj
     * @throws Zend_Pdf_Exception
     */
    public function remove(Zend_Pdf_Element_Object $obj)
    {
        if (!$obj->compareFactory($this)) {
            throw new Zend_Pdf_Exception('Object is not generated by this factory');
        }

        $this->_modifiedObjects[$obj->getObjNum()] = $obj;
        $this-> _removedObjects[$obj->getObjNum()] = $obj;
    }

    /**
     * Generate new Zend_Pdf_Element_Object
     *
     * @todo Reusage of the freed object. It's not a support of new feature, but only improvement.
     *
     * @param Zend_Pdf_Element $objectValue
     * @return Zend_Pdf_Element_Object
     */
    public function newObject(Zend_Pdf_Element $objectValue)
    {
        $obj = new Zend_Pdf_Element_Object($objectValue, $this->_objectCount++, 0, $this);
        $this->_modifiedObjects[$obj->getObjNum()] = $obj;
        return $obj;
    }

    /**
     * Generate new Zend_Pdf_Element_Object_Stream
     *
     * @todo Reusage of the freed object. It's not a support of new feature, but only improvement.
     *
     * @param mixed $objectValue
     * @return Zend_Pdf_Element_Object_Stream
     */
    public function newStreamObject($streamValue)
    {
        $obj = new Zend_Pdf_Element_Object_Stream($streamValue, $this->_objectCount++, 0, $this);
        $this->_modifiedObjects[$obj->getObjNum()] = $obj;
        return $obj;
    }

    /**
     * Enumerate modified objects.
     * Returns array of Zend_Pdf_UpdateInfoContainer
     *
     * @param Zend_Pdf_ElementFactory_Interface $rootFactory
     * @return array
     */
    public function listModifiedObjects($rootFactory = null)
    {
        if ($rootFactory == null) {
            $rootFactory = $this;
            $shift = 0;
        } else {
            $shift = $rootFactory->getEnumerationShift($this);
        }

        ksort($this->_modifiedObjects);

        $result = array();
        foreach ($this->_modifiedObjects as $objNum => $obj) {
            if (key_exists($objNum, $this->_removedObjects)) {
                $result[$objNum+$shift] = new Zend_Pdf_UpdateInfoContainer($objNum + $shift,
                                                                           $obj->getGenNum()+1,
                                                                           true);
            } else {
                $result[$objNum+$shift] = new Zend_Pdf_UpdateInfoContainer($objNum + $shift,
                                                                           $obj->getGenNum(),
                                                                           false,
                                                                           $obj->dump($rootFactory));
            }
        }

        foreach ($this->_attachedFactories as $factory) {
            $result += $factory->listModifiedObjects($rootFactory);
        }

        return $result;
    }

    /**
     * Register object in the factory
     *
     * It's used to clear "parent object" referencies when factory is closed and clean up resources
     *
     * @param Zend_Pdf_Element_Object $obj
     */
    public function registerObject($obj)
    {
        $this->_registeredObjects[] = $obj;
    }

    /**
     * Check if PDF file was modified
     *
     * @return boolean
     */
    public function isModified()
    {
        if (count($this->_modifiedObjects) != 0) {
            return true;
        }

        foreach ($this->_attachedFactories as $subFactory) {
            if ($subFactory->isModified()) {
                return true;
            }
        }

        return false;
    }
}


text:
#ifndef LIBMINIFI_INCLUDE_IO_CLIENTSOCKET_H_
#define LIBMINIFI_INCLUDE_IO_CLIENTSOCKET_H_

#include <cstdint>
#ifdef WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif /* WIN32_LEAN_AND_MEAN */
#include <WinSock2.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#endif /* WIN32 */
#include <mutex>
#include <atomic>
#include <string>
#include <memory>
#include <vector>
#include "io/BaseStream.h"
#include "core/Core.h"
#include "core/logging/Logger.h"
#include "io/validation.h"
#include "properties/Configure.h"
#include "io/NetworkPrioritizer.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace io {

#ifdef WIN32
using SocketDescriptor = SOCKET;
using ip4addr = in_addr;
#else
using SocketDescriptor = int;
using ip4addr = in_addr_t;
static constexpr SocketDescriptor INVALID_SOCKET = -1;
static constexpr int SOCKET_ERROR = -1;
#endif /* WIN32 */

/**
 * Return the last socket error message, based on errno on posix and WSAGetLastError() on windows
 */
std::string get_last_socket_error_message();

/**
 * @return >= 0 on posix, != INVALID_SOCKET on windows
 */
bool valid_socket(SocketDescriptor) noexcept;

/**
 * Context class for socket. This is currently only used as a parent class for TLSContext.  It is necessary so the Socket and TLSSocket constructors
 * can be the same.  It also gives us a common place to set timeouts, etc from the Configure object in the future.
 */
class SocketContext {
 public:
  SocketContext(const std::shared_ptr<Configure> &configure) {
  }
};
/**
 * Socket class.
 * Purpose: Provides a general purpose socket interface that abstracts
 * connecting information from users
 * Design: Extends DataStream and allows us to perform most streaming
 * operations against a BSD socket
 */
class Socket : public BaseStream {
 public:
  /**
   * Constructor that creates a client socket.
   * @param context the SocketContext
   * @param hostname hostname we are connecting to.
   * @param port port we are connecting to.
   */
  explicit Socket(const std::shared_ptr<SocketContext> &context, std::string hostname, uint16_t port);

  Socket(const Socket&) = delete;
  Socket(Socket&&) noexcept;

  Socket& operator=(const Socket&) = delete;
  Socket& operator=(Socket&& other) noexcept;

  /**
   * Static function to return the current machine's host name
   */
  static std::string getMyHostName() {
    static const std::string HOSTNAME = init_hostname();
    return HOSTNAME;
  }

  /**
   * Destructor
   */

  virtual ~Socket();

  virtual void closeStream();
  /**
   * Initializes the socket
   * @return result of the creation operation.
   */
  virtual int16_t initialize();

  virtual void setInterface(io::NetworkInterface interface) {
    local_network_interface_ = std::move(interface);
  }

  /**
   * Sets the non blocking flag on the file descriptor.
   */
  void setNonBlocking();

  std::string getHostname() const;

  /**
   * Return the port for this socket
   * @returns port
   */
  uint16_t getPort() const {
    return port_;
  }

  void setPort(uint16_t port) {
    port_ = port;
  }

  // data stream extensions
  /**
   * Reads data and places it into buf
   * @param buf buffer in which we extract data
   * @param buflen
   * @param retrieve_all_bytes determines if we should read all bytes before returning
   */
  virtual int readData(std::vector<uint8_t> &buf, int buflen) {
    return readData(buf, buflen, true);
  }
  /**
   * Reads data and places it into buf
   * @param buf buffer in which we extract data
   * @param buflen
   * @param retrieve_all_bytes determines if we should read all bytes before returning
   */
  virtual int readData(uint8_t *buf, int buflen) {
    return readData(buf, buflen, true);
  }

  /**
   * Reads data and places it into buf
   * @param buf buffer in which we extract data
   * @param buflen
   * @param retrieve_all_bytes determines if we should read all bytes before returning
   */
  virtual int readData(std::vector<uint8_t> &buf, int buflen, bool retrieve_all_bytes);
  /**
   * Reads data and places it into buf
   * @param buf buffer in which we extract data
   * @param buflen
   * @param retrieve_all_bytes determines if we should read all bytes before returning
   */
  virtual int readData(uint8_t *buf, int buflen, bool retrieve_all_bytes);

  /**
   * Write value to the stream using std::vector
   * @param buf incoming buffer
   * @param buflen buffer to write
   *
   */
  virtual int writeData(std::vector<uint8_t> &buf, int buflen);

  /**
   * writes value to stream
   * @param value value to write
   * @param size size of value
   */
  virtual int writeData(uint8_t *value, int size);

  /**
   * Writes a system word
   * @param value value to write
   */
  virtual int write(uint64_t value, bool is_little_endian = EndiannessCheck::IS_LITTLE);

  /**
   * Writes a uint32_t
   * @param value value to write
   */
  virtual int write(uint32_t value, bool is_little_endian = EndiannessCheck::IS_LITTLE);

  /**
   * Writes a system short
   * @param value value to write
   */
  virtual int write(uint16_t value, bool is_little_endian = EndiannessCheck::IS_LITTLE);

  /**
   * Reads a system word
   * @param value value to write
   */
  virtual int read(uint64_t &value, bool is_little_endian = EndiannessCheck::IS_LITTLE);

  /**
   * Reads a uint32_t
   * @param value value to write
   */
  virtual int read(uint32_t &value, bool is_little_endian = EndiannessCheck::IS_LITTLE);

  /**
   * Reads a system short
   * @param value value to write
   */
  virtual int read(uint16_t &value, bool is_little_endian = EndiannessCheck::IS_LITTLE);

 protected:

  /**
   * Constructor that accepts host name, port and listeners. With this
   * contructor we will be creating a server socket
   * @param context the SocketContext
   * @param hostname our host name
   * @param port connecting port
   * @param listeners number of listeners in the queue
   */
  explicit Socket(const std::shared_ptr<SocketContext> &context, std::string hostname, uint16_t port, uint16_t listeners);

  /**
   * Creates a vector and returns the vector using the provided
   * type name.
   * @param t incoming object
   * @returns vector.
   */
  template<typename T>
  std::vector<uint8_t> readBuffer(const T&);

  /**
   * Creates a connection using the addr object
   * @param ignored ignored
   * @param addr The IPv4 address to connect to
   * @returns 0 on success, -1 on error
   */
  virtual int8_t createConnection(const addrinfo *ignored, ip4addr &addr);

  /**
   * Iterates through {@code destination_addresses} and tries to connect to each address until it succeeds.
   * Supports both IPv4 and IPv6.
   * @param destination_addresses Destination addresses, typically from {@code getaddrinfo}.
   * @return 0 on success, -1 on error
   */
  virtual int8_t createConnection(const addrinfo *destination_addresses);

  /**
   * Sets socket options depending on the instance.
   * @param sock socket file descriptor.
   */
  virtual int16_t setSocketOptions(SocketDescriptor sock);

  /**
   * Attempt to select the socket file descriptor
   * @param msec timeout interval to wait
   * @returns file descriptor
   */
  virtual int16_t select_descriptor(uint16_t msec);

  std::recursive_mutex selection_mutex_;

  std::string requested_hostname_;
  std::string canonical_hostname_;
  uint16_t port_{ 0 };

  bool is_loopback_only_{ false };
  io::NetworkInterface local_network_interface_;

  // connection information
  SocketDescriptor socket_file_descriptor_{ INVALID_SOCKET }; // -1 on posix

  fd_set total_list_{};
  fd_set read_fds_{};
  std::atomic<uint16_t> socket_max_{ 0 };
  std::atomic<uint64_t> total_written_{ 0 };
  std::atomic<uint64_t> total_read_{ 0 };
  uint16_t listeners_{ 0 };

  bool nonBlocking_{ false };

  std::shared_ptr<logging::Logger> logger_;

 private:
#ifdef WIN32
  struct SocketInitializer
  {
    SocketInitializer() {
      static WSADATA s_wsaData;
      const int iWinSockInitResult = WSAStartup(MAKEWORD(2, 2), &s_wsaData);
      if (0 != iWinSockInitResult) {
        throw std::exception("Cannot start client");
      }
    }
    ~SocketInitializer() noexcept {
      WSACleanup();
    }
  };
  static void initialize_socket() {
    static SocketInitializer initialized;
  }
#else
  static void initialize_socket(){}
#endif /* WIN32 */

  static std::string init_hostname() {
    initialize_socket();
    char hostname[1024];
    gethostname(hostname, 1024);
    Socket mySock(nullptr, hostname, 0);
    mySock.initialize();
    const auto resolved_hostname = mySock.getHostname();
    return !IsNullOrEmpty(resolved_hostname) ? resolved_hostname : hostname;
  }
};

} /* namespace io */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
#endif /* LIBMINIFI_INCLUDE_IO_CLIENTSOCKET_H_ */


text:
The content of the mega menu can be altered by editing the [uql-menu.json file](https://github.com/uqlibrary/uqlibrary-reusable-components/blob/master/resources/uql-menu.json)

## Json

* A `json` file must use correct json syntax [Learn more](https://www.w3schools.com/js/js_json_syntax.asp)
* Best practice is to make the order of the menu match the order of the displayed menu

## Multi Columns

Mark items to go into column 2 or column 3 of a submenu by adding the following entry to the menu item:

`"col3": "yes"`

eg

`{
    "label": "Law",
    "subtext": "Walter Harrison Library",
    "href": "https://web.library.uq.edu.au/locations-hours/law-library-walter-harrison-library",
    "col3": "yes"
}`

If neither col2 nor col3 is found, the menu is assumed to be a single column menu.

## Gotchas

* Remember that each line must be separated by a comma within the braces
* If you put a col2 entry _after_ the last col3 entry within a submenu, display weirdness may happen - don't do that...
* Be careful changing from 2-cols to 3-cols - if you change the left hand menu the placement will need adjustment as it is currently sized to push `Locations & Hours` to the left. Developers may need to make changes


text:
package org.kie.workbench.common.stunner.core.client.canvas.controls;

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.listener.CanvasElementListener;
import org.kie.workbench.common.stunner.core.client.canvas.listener.CanvasShapeListener;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class CanvasControlRegistrationHandlerTest {

    private static final int CONTROLS_SIZE = 5;

    @Mock
    private AbstractCanvas canvas;

    @Mock
    private AbstractCanvasHandler canvasHandler;

    @Mock
    private ClientSession session;

    @Mock
    private MockAbstractCanvasSessionAwareControl sessionAwareControl;

    private CanvasControlRegistrationHandler tested;
    private final List<CanvasControl<AbstractCanvas>> canvasControls = new ArrayList<>(CONTROLS_SIZE);
    private final List<CanvasControl<AbstractCanvasHandler>> canvasHandlerControls = new ArrayList<>(CONTROLS_SIZE);

    @Before
    @SuppressWarnings("unchecked")
    public void setup() throws Exception {
        this.tested = new CanvasControlRegistrationHandler<>(canvas,
                                                             canvasHandler);
        for (int x = 0; x < CONTROLS_SIZE; x++) {
            canvasControls.add(mock(CanvasControl.class));
            canvasHandlerControls.add(mock(CanvasControl.class));
        }
        canvasControls.add(sessionAwareControl);
        canvasControls.forEach(tested::registerCanvasControl);
        canvasHandlerControls.forEach(tested::registerCanvasHandlerControl);
    }

    @Test
    public void testEnable() {
        tested.enable();
        verify(canvas,
               times(1)).addRegistrationListener(any(CanvasShapeListener.class));
        verify(canvasHandler,
               times(1)).addRegistrationListener(any(CanvasElementListener.class));
        canvasControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvas));
        });
        canvasHandlerControls.forEach(c -> verify(c,
                                                  times(1)).enable(eq(canvasHandler)));
    }

    @Test
    public void testDisable() {
        tested.enable();
        tested.disable();
        verify(canvas,
               times(1)).addRegistrationListener(any(CanvasShapeListener.class));
        verify(canvasHandler,
               times(1)).addRegistrationListener(any(CanvasElementListener.class));
        verify(canvas,
               times(1)).removeRegistrationListener(any(CanvasShapeListener.class));
        verify(canvasHandler,
               times(1)).removeRegistrationListener(any(CanvasElementListener.class));
        canvasControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvas));
            verify(c,
                   times(1)).disable();
        });
        canvasHandlerControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvasHandler));
            verify(c,
                   times(1)).disable();
        });
    }

    @Test
    public void testClear() {
        tested.enable();
        tested.clear();
        verify(canvas,
               times(1)).addRegistrationListener(any(CanvasShapeListener.class));
        verify(canvasHandler,
               times(1)).addRegistrationListener(any(CanvasElementListener.class));
        verify(canvas,
               times(1)).removeRegistrationListener(any(CanvasShapeListener.class));
        verify(canvasHandler,
               times(1)).removeRegistrationListener(any(CanvasElementListener.class));
        canvasControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvas));
            verify(c,
                   times(1)).disable();
        });
        canvasHandlerControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvasHandler));
            verify(c,
                   times(1)).disable();
        });
    }

    @Test
    public void testDestroy() {
        tested.enable();
        tested.destroy();
        verify(canvas,
               times(1)).addRegistrationListener(any(CanvasShapeListener.class));
        verify(canvasHandler,
               times(1)).addRegistrationListener(any(CanvasElementListener.class));
        verify(canvas,
               times(1)).removeRegistrationListener(any(CanvasShapeListener.class));
        verify(canvas,
               times(1)).clearRegistrationListeners();
        verify(canvasHandler,
               times(1)).clearRegistrationListeners();
        canvasControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvas));
            verify(c,
                   times(1)).disable();
        });
        canvasHandlerControls.forEach(c -> {
            verify(c,
                   times(1)).enable(eq(canvasHandler));
            verify(c,
                   times(1)).disable();
        });
    }

    @Test
    public void checkBindSessionOnSessionAwareControls() {
        tested.bind(session);

        verify(sessionAwareControl,
               times(1)).bind(eq(session));
    }

    @Test
    public void checkUnbindSessionOnSessionAwareControls() {
        tested.unbind();

        verify(sessionAwareControl,
               times(1)).unbind();
    }

    private interface MockAbstractCanvasSessionAwareControl extends CanvasControl<AbstractCanvas>,
                                                                    CanvasControl.SessionAware<ClientSession> {

    }
}


text:
<!DOCTYPE html>

    <title>object-src-applet-code</title>

    This test passes if there is a CSP violation saying the plugin was blocked.
    <applet code="/plugins/code.class"></applet>


text:
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: peer/admin.proto

/*
Package peer is a generated protocol buffer package.

It is generated from these files:
	peer/admin.proto
	peer/chaincode.proto
	peer/chaincode_event.proto
	peer/chaincode_shim.proto
	peer/configuration.proto
	peer/events.proto
	peer/peer.proto
	peer/proposal.proto
	peer/proposal_response.proto
	peer/query.proto
	peer/signed_cc_dep_spec.proto
	peer/transaction.proto

It has these top-level messages:
	ServerStatus
	LogLevelRequest
	LogLevelResponse
	ChaincodeID
	ChaincodeInput
	ChaincodeSpec
	ChaincodeDeploymentSpec
	ChaincodeInvocationSpec
	ChaincodeEvent
	ChaincodeMessage
	PutStateInfo
	GetStateByRange
	GetQueryResult
	GetHistoryForKey
	QueryStateNext
	QueryStateClose
	QueryResultBytes
	QueryResponse
	AnchorPeers
	AnchorPeer
	ChaincodeReg
	Interest
	Register
	Rejection
	Unregister
	SignedEvent
	Event
	PeerID
	PeerEndpoint
	SignedProposal
	Proposal
	ChaincodeHeaderExtension
	ChaincodeProposalPayload
	ChaincodeAction
	ProposalResponse
	Response
	ProposalResponsePayload
	Endorsement
	ChaincodeQueryResponse
	ChaincodeInfo
	ChannelQueryResponse
	ChannelInfo
	SignedChaincodeDeploymentSpec
	SignedTransaction
	ProcessedTransaction
	Transaction
	TransactionAction
	ChaincodeActionPayload
	ChaincodeEndorsedAction
*/
package peer

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import google_protobuf "github.com/golang/protobuf/ptypes/empty"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

type ServerStatus_StatusCode int32

const (
	ServerStatus_UNDEFINED ServerStatus_StatusCode = 0
	ServerStatus_STARTED   ServerStatus_StatusCode = 1
	ServerStatus_STOPPED   ServerStatus_StatusCode = 2
	ServerStatus_PAUSED    ServerStatus_StatusCode = 3
	ServerStatus_ERROR     ServerStatus_StatusCode = 4
	ServerStatus_UNKNOWN   ServerStatus_StatusCode = 5
)

var ServerStatus_StatusCode_name = map[int32]string{
	0: "UNDEFINED",
	1: "STARTED",
	2: "STOPPED",
	3: "PAUSED",
	4: "ERROR",
	5: "UNKNOWN",
}
var ServerStatus_StatusCode_value = map[string]int32{
	"UNDEFINED": 0,
	"STARTED":   1,
	"STOPPED":   2,
	"PAUSED":    3,
	"ERROR":     4,
	"UNKNOWN":   5,
}

func (x ServerStatus_StatusCode) String() string {
	return proto.EnumName(ServerStatus_StatusCode_name, int32(x))
}
func (ServerStatus_StatusCode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} }

type ServerStatus struct {
	Status ServerStatus_StatusCode `protobuf:"varint,1,opt,name=status,enum=protos.ServerStatus_StatusCode" json:"status,omitempty"`
}

func (m *ServerStatus) Reset()                    { *m = ServerStatus{} }
func (m *ServerStatus) String() string            { return proto.CompactTextString(m) }
func (*ServerStatus) ProtoMessage()               {}
func (*ServerStatus) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }

func (m *ServerStatus) GetStatus() ServerStatus_StatusCode {
	if m != nil {
		return m.Status
	}
	return ServerStatus_UNDEFINED
}

type LogLevelRequest struct {
	LogModule string `protobuf:"bytes,1,opt,name=log_module,json=logModule" json:"log_module,omitempty"`
	LogLevel  string `protobuf:"bytes,2,opt,name=log_level,json=logLevel" json:"log_level,omitempty"`
}

func (m *LogLevelRequest) Reset()                    { *m = LogLevelRequest{} }
func (m *LogLevelRequest) String() string            { return proto.CompactTextString(m) }
func (*LogLevelRequest) ProtoMessage()               {}
func (*LogLevelRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }

func (m *LogLevelRequest) GetLogModule() string {
	if m != nil {
		return m.LogModule
	}
	return ""
}

func (m *LogLevelRequest) GetLogLevel() string {
	if m != nil {
		return m.LogLevel
	}
	return ""
}

type LogLevelResponse struct {
	LogModule string `protobuf:"bytes,1,opt,name=log_module,json=logModule" json:"log_module,omitempty"`
	LogLevel  string `protobuf:"bytes,2,opt,name=log_level,json=logLevel" json:"log_level,omitempty"`
}

func (m *LogLevelResponse) Reset()                    { *m = LogLevelResponse{} }
func (m *LogLevelResponse) String() string            { return proto.CompactTextString(m) }
func (*LogLevelResponse) ProtoMessage()               {}
func (*LogLevelResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }

func (m *LogLevelResponse) GetLogModule() string {
	if m != nil {
		return m.LogModule
	}
	return ""
}

func (m *LogLevelResponse) GetLogLevel() string {
	if m != nil {
		return m.LogLevel
	}
	return ""
}

func init() {
	proto.RegisterType((*ServerStatus)(nil), "protos.ServerStatus")
	proto.RegisterType((*LogLevelRequest)(nil), "protos.LogLevelRequest")
	proto.RegisterType((*LogLevelResponse)(nil), "protos.LogLevelResponse")
	proto.RegisterEnum("protos.ServerStatus_StatusCode", ServerStatus_StatusCode_name, ServerStatus_StatusCode_value)
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// Client API for Admin service

type AdminClient interface {
	// Return the serve status.
	GetStatus(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*ServerStatus, error)
	StartServer(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*ServerStatus, error)
	GetModuleLogLevel(ctx context.Context, in *LogLevelRequest, opts ...grpc.CallOption) (*LogLevelResponse, error)
	SetModuleLogLevel(ctx context.Context, in *LogLevelRequest, opts ...grpc.CallOption) (*LogLevelResponse, error)
	RevertLogLevels(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*google_protobuf.Empty, error)
}

type adminClient struct {
	cc *grpc.ClientConn
}

func NewAdminClient(cc *grpc.ClientConn) AdminClient {
	return &adminClient{cc}
}

func (c *adminClient) GetStatus(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*ServerStatus, error) {
	out := new(ServerStatus)
	err := grpc.Invoke(ctx, "/protos.Admin/GetStatus", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *adminClient) StartServer(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*ServerStatus, error) {
	out := new(ServerStatus)
	err := grpc.Invoke(ctx, "/protos.Admin/StartServer", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *adminClient) GetModuleLogLevel(ctx context.Context, in *LogLevelRequest, opts ...grpc.CallOption) (*LogLevelResponse, error) {
	out := new(LogLevelResponse)
	err := grpc.Invoke(ctx, "/protos.Admin/GetModuleLogLevel", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *adminClient) SetModuleLogLevel(ctx context.Context, in *LogLevelRequest, opts ...grpc.CallOption) (*LogLevelResponse, error) {
	out := new(LogLevelResponse)
	err := grpc.Invoke(ctx, "/protos.Admin/SetModuleLogLevel", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *adminClient) RevertLogLevels(ctx context.Context, in *google_protobuf.Empty, opts ...grpc.CallOption) (*google_protobuf.Empty, error) {
	out := new(google_protobuf.Empty)
	err := grpc.Invoke(ctx, "/protos.Admin/RevertLogLevels", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for Admin service

type AdminServer interface {
	// Return the serve status.
	GetStatus(context.Context, *google_protobuf.Empty) (*ServerStatus, error)
	StartServer(context.Context, *google_protobuf.Empty) (*ServerStatus, error)
	GetModuleLogLevel(context.Context, *LogLevelRequest) (*LogLevelResponse, error)
	SetModuleLogLevel(context.Context, *LogLevelRequest) (*LogLevelResponse, error)
	RevertLogLevels(context.Context, *google_protobuf.Empty) (*google_protobuf.Empty, error)
}

func RegisterAdminServer(s *grpc.Server, srv AdminServer) {
	s.RegisterService(&_Admin_serviceDesc, srv)
}

func _Admin_GetStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(google_protobuf.Empty)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(AdminServer).GetStatus(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/protos.Admin/GetStatus",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(AdminServer).GetStatus(ctx, req.(*google_protobuf.Empty))
	}
	return interceptor(ctx, in, info, handler)
}

func _Admin_StartServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(google_protobuf.Empty)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(AdminServer).StartServer(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/protos.Admin/StartServer",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(AdminServer).StartServer(ctx, req.(*google_protobuf.Empty))
	}
	return interceptor(ctx, in, info, handler)
}

func _Admin_GetModuleLogLevel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(LogLevelRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(AdminServer).GetModuleLogLevel(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/protos.Admin/GetModuleLogLevel",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(AdminServer).GetModuleLogLevel(ctx, req.(*LogLevelRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _Admin_SetModuleLogLevel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(LogLevelRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(AdminServer).SetModuleLogLevel(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/protos.Admin/SetModuleLogLevel",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(AdminServer).SetModuleLogLevel(ctx, req.(*LogLevelRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _Admin_RevertLogLevels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(google_protobuf.Empty)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(AdminServer).RevertLogLevels(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/protos.Admin/RevertLogLevels",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(AdminServer).RevertLogLevels(ctx, req.(*google_protobuf.Empty))
	}
	return interceptor(ctx, in, info, handler)
}

var _Admin_serviceDesc = grpc.ServiceDesc{
	ServiceName: "protos.Admin",
	HandlerType: (*AdminServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "GetStatus",
			Handler:    _Admin_GetStatus_Handler,
		},
		{
			MethodName: "StartServer",
			Handler:    _Admin_StartServer_Handler,
		},
		{
			MethodName: "GetModuleLogLevel",
			Handler:    _Admin_GetModuleLogLevel_Handler,
		},
		{
			MethodName: "SetModuleLogLevel",
			Handler:    _Admin_SetModuleLogLevel_Handler,
		},
		{
			MethodName: "RevertLogLevels",
			Handler:    _Admin_RevertLogLevels_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "peer/admin.proto",
}

func init() { proto.RegisterFile("peer/admin.proto", fileDescriptor0) }

var fileDescriptor0 = []byte{
	// 418 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xac, 0x93, 0x41, 0x6f, 0xd3, 0x30,
	0x14, 0xc7, 0x9b, 0x42, 0x0b, 0x79, 0x1b, 0xcc, 0x58, 0x08, 0xaa, 0x4e, 0x08, 0x94, 0x13, 0x5c,
	0x1c, 0x69, 0x1c, 0x38, 0x20, 0x0e, 0xdd, 0x12, 0x06, 0x62, 0x4b, 0x23, 0x67, 0x15, 0x02, 0x09,
	0x4d, 0x49, 0xf3, 0xe6, 0x55, 0x38, 0x73, 0xb0, 0x9d, 0x4a, 0xfb, 0x3a, 0x7c, 0x2e, 0x3e, 0x0c,
	0x4a, 0xdc, 0x68, 0x13, 0xb0, 0x03, 0x82, 0x93, 0xf3, 0xde, 0xfb, 0xff, 0xff, 0x71, 0x7e, 0xb1,
	0x81, 0xd4, 0x88, 0x3a, 0xcc, 0xcb, 0x6a, 0x75, 0xc1, 0x6a, 0xad, 0xac, 0xa2, 0xe3, 0x6e, 0x31,
	0xd3, 0x5d, 0xa1, 0x94, 0x90, 0x18, 0x76, 0x65, 0xd1, 0x9c, 0x85, 0x58, 0xd5, 0xf6, 0xd2, 0x89,
	0x82, 0xef, 0x1e, 0x6c, 0x67, 0xa8, 0xd7, 0xa8, 0x33, 0x9b, 0xdb, 0xc6, 0xd0, 0x57, 0x30, 0x36,
	0xdd, 0xd3, 0xc4, 0x7b, 0xe6, 0x3d, 0xbf, 0xbf, 0xf7, 0xd4, 0x09, 0x0d, 0xbb, 0xae, 0x62, 0x6e,
	0x39, 0x50, 0x25, 0xf2, 0x8d, 0x3c, 0xf8, 0x04, 0x70, 0xd5, 0xa5, 0xf7, 0xc0, 0x5f, 0x24, 0x51,
	0xfc, 0xf6, 0x7d, 0x12, 0x47, 0x64, 0x40, 0xb7, 0xe0, 0x4e, 0x76, 0x32, 0xe3, 0x27, 0x71, 0x44,
	0x3c, 0x57, 0xcc, 0xd3, 0x34, 0x8e, 0xc8, 0x90, 0x02, 0x8c, 0xd3, 0xd9, 0x22, 0x8b, 0x23, 0x72,
	0x8b, 0xfa, 0x30, 0x8a, 0x39, 0x9f, 0x73, 0x72, 0xbb, 0xd5, 0x2c, 0x92, 0x0f, 0xc9, 0xfc, 0x63,
	0x42, 0x46, 0xc1, 0x31, 0xec, 0x1c, 0x29, 0x71, 0x84, 0x6b, 0x94, 0x1c, 0xbf, 0x35, 0x68, 0x2c,
	0x7d, 0x02, 0x20, 0x95, 0x38, 0xad, 0x54, 0xd9, 0x48, 0xec, 0xb6, 0xea, 0x73, 0x5f, 0x2a, 0x71,
	0xdc, 0x35, 0xe8, 0x2e, 0xb4, 0xc5, 0xa9, 0x6c, 0x2d, 0x93, 0x61, 0x37, 0xbd, 0x2b, 0x37, 0x11,
	0x41, 0x02, 0xe4, 0x2a, 0xce, 0xd4, 0xea, 0xc2, 0xe0, 0xbf, 0xe4, 0xed, 0xfd, 0x18, 0xc2, 0x68,
	0xd6, 0x82, 0xa7, 0xaf, 0xc1, 0x3f, 0x44, 0xbb, 0x21, 0xf9, 0x88, 0x39, 0xf0, 0xac, 0x07, 0xcf,
	0xe2, 0x16, 0xfc, 0xf4, 0xe1, 0x9f, 0x88, 0x06, 0x03, 0xfa, 0x06, 0xb6, 0x32, 0x9b, 0x6b, 0xeb,
	0xda, 0x7f, 0x6d, 0x7f, 0x07, 0x0f, 0x0e, 0xd1, 0xba, 0xfd, 0xf6, 0x9f, 0x47, 0x1f, 0xf7, 0xe2,
	0x5f, 0xf8, 0x4d, 0x27, 0xbf, 0x0f, 0x1c, 0x09, 0x97, 0x94, 0xfd, 0x9f, 0xa4, 0x03, 0xd8, 0xe1,
	0xb8, 0x46, 0x6d, 0xfb, 0xd9, 0xcd, 0x54, 0x6e, 0xe8, 0x07, 0x83, 0xfd, 0x2f, 0x10, 0x28, 0x2d,
	0xd8, 0xf9, 0x65, 0x8d, 0x5a, 0x62, 0x29, 0x50, 0xb3, 0xb3, 0xbc, 0xd0, 0xab, 0x65, 0xff, 0xe2,
	0xf6, 0xe4, 0xef, 0x6f, 0x77, 0x7f, 0x20, 0xcd, 0x97, 0x5f, 0x73, 0x81, 0x9f, 0x5f, 0x88, 0x95,
	0x3d, 0x6f, 0x0a, 0xb6, 0x54, 0x55, 0x78, 0xcd, 0x18, 0x3a, 0xa3, 0xbb, 0x0a, 0x26, 0x6c, 0x8d,
	0x85, 0xbb, 0x26, 0x2f, 0x7f, 0x06, 0x00, 0x00, 0xff, 0xff, 0x6e, 0xe6, 0xef, 0xb7, 0x41, 0x03,
	0x00, 0x00,
}


text:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#ifdef OS_WINDOWS

#include <Windows.h>

/*
	IN Visual Studio must be
	(Conf. Properties) -> General -> Character Set -> Not Set
*/
BOOL iterateFiles(LPCTSTR path, BOOL (*funcptrOp)(LPCTSTR, const WIN32_FIND_DATA *, int));

#else

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>

void list_directory_contents(const char *);

#endif


text:
/**
 * Created by Andrew on 20.9.16.
 */

import { EventEmitter, Output, Input, Component } from "@angular/core";
import { PageRequest, Page } from "../model";

/**
 *
 */
@Component({
    moduleId: module.id,
    selector: 'pagination-component',
    template: `
         1">

                        Previous
                        Previous

{{number + 1}}

                        Next
                        Next

    `
})
export class PaginationComponent
{
    @Input("page") currentPage: Page;
    @Output() pageRequested = new EventEmitter<PageRequest>();

    /**
     *
     */
    constructor()
    {
    }

    /**
     * TODO could probably do this better
     *
     * @returns {number[]}
     */
    get pageNumbers(): number[]
    {
        let pageNumberArray: number[] = [];

        if (this.currentPage)
        {
            let start: number = 0;
            let end: number = 0;

            if (this.currentPage.totalPages < 5)
            {
                start = 0;
                end = this.currentPage.totalPages;
            }
            else if (this.currentPage.number > this.currentPage.totalPages - 3)
            {
                start = this.currentPage.totalPages - 5;
                end = this.currentPage.totalPages;
            }
            else if (this.currentPage.number < 3)
            {
                start = 0;
                end = Math.min(this.currentPage.totalPages, 5);
            }
            else
            {
                start = this.currentPage.number - 2;
                end = Math.min(this.currentPage.totalPages, start + 5);
            }

            for (let idx = start; idx < end; idx++)
            {
                pageNumberArray.push(idx);
            }
        }

        return pageNumberArray;
    }

    /**
     *
     * @param pageNo
     */
    private requestPage(pageNo: number)
    {
        // validate the page number before requesting
        if (pageNo >= 0 || pageNo <= this.currentPage.totalPages)
        {
            let pageRequest: PageRequest = {
                page: pageNo,
                size: this.currentPage.size
            };

            this.pageRequested.emit(pageRequest);
        }
    }

    /**
     *
     * @param pageNo
     */
    public selectPage(pageNo: number): void
    {
        if (pageNo <= this.currentPage.totalPages)
        {
            this.requestPage(pageNo);
        }
    }

    /**
     *
     */
    public nextPage(): void
    {
        if (!this.currentPage.last)
        {
            this.requestPage(this.currentPage.number + 1);
        }
    }

    /**
     *
     */
    public previousPage(): void
    {
        if (!this.currentPage.first)
        {
            this.requestPage(this.currentPage.number - 1);
        }
    }

}


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#ifndef V8SharedArrayBuffer_h
#define V8SharedArrayBuffer_h

#include "bindings/core/v8/ScriptWrappable.h"
#include "bindings/core/v8/ToV8.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMWrapper.h"
#include "bindings/core/v8/WrapperTypeInfo.h"
#include "core/CoreExport.h"
#include "core/dom/DOMSharedArrayBuffer.h"
#include "platform/heap/Handle.h"

namespace blink {

class V8SharedArrayBuffer {
public:
    CORE_EXPORT static bool hasInstance(v8::Local<v8::Value>, v8::Isolate*);
    static v8::Local<v8::Object> findInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*);
    CORE_EXPORT static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*);
    static DOMSharedArrayBuffer* toImpl(v8::Local<v8::Object> object)
    {
        return toScriptWrappable(object)->toImpl<DOMSharedArrayBuffer>();
    }
    CORE_EXPORT static DOMSharedArrayBuffer* toImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>);
    CORE_EXPORT static const WrapperTypeInfo wrapperTypeInfo;
    static void refObject(ScriptWrappable*);
    static void derefObject(ScriptWrappable*);
    template<typename VisitorDispatcher>
    static void trace(VisitorDispatcher visitor, ScriptWrappable* scriptWrappable)
    {
    }
    static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0;
    static void installConditionallyEnabledProperties(v8::Local<v8::Object>, v8::Isolate*) { }
    static void preparePrototypeObject(v8::Isolate*, v8::Local<v8::Object> prototypeObject, v8::Local<v8::FunctionTemplate> interfaceTemplate) { }
};

template <>
struct V8TypeOf<DOMSharedArrayBuffer> {
    typedef V8SharedArrayBuffer Type;
};

} // namespace blink

#endif // V8SharedArrayBuffer_h


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

<title>HorizontalPosition (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

net.sf.jasperreports.engine.type

Enum HorizontalPosition

java.lang.Object

java.lang.Enum<HorizontalPosition>

net.sf.jasperreports.engine.type.HorizontalPosition

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<HorizontalPosition>, NamedEnum

public enum HorizontalPosition
extends java.lang.Enum<HorizontalPosition>
implements NamedEnum

Version:

$Id: HorizontalPosition.java 6530 2013-09-19 13:23:20Z lucianc $

Author:

Lucian Chirita (lucianc@users.sourceforge.net)

Enum Constant Summary

Enum Constants

Enum Constant and Description

CENTER

LEFT

RIGHT

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getName()

static HorizontalPosition
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static HorizontalPosition[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

LEFT

public static final HorizontalPosition LEFT

RIGHT

public static final HorizontalPosition RIGHT

CENTER

public static final HorizontalPosition CENTER

Method Detail

values

public static HorizontalPosition[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (HorizontalPosition c : HorizontalPosition.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in
the order they are declared

valueOf

public static HorizontalPosition valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

getName

public java.lang.String getName()

Specified by:

getName in interface NamedEnum

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
package alix.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * An efficient int-int Map implementation, encoded in a long array for key and
 * value. A special method is used to modify a value by addition. Used for word
 * vectors indexed by int. A local Cosine is implemented. Be careful, do not use
 * -2147483648 as a key (Integer.MIN_VALUE), is used to tag empty value, no
 * warning will be sent.
 *
 *
 * source:
 * http://java-performance.info/implementing-world-fastest-java-int-to-int-hash-map/
 */
public class IntIntMap implements Cloneable
{
  /** Binary mask to get upper int from data */
  private static long KEY_MASK = 0xFFFFFFFFL;
  public static final int NO_KEY = Integer.MIN_VALUE;
  public static final int NO_VALUE = Integer.MIN_VALUE;
  private static final long FREE_CELL;
  static { // build FREE_CELL value, to avoid errors
    FREE_CELL = entry(NO_KEY, NO_VALUE);
  }
  /** An automaton to parse a String version of the Map */
  private static Pattern loadre = Pattern.compile("([0-9]+):([0-9]+)");

  /** Int id of the vector */
  public final int code;
  /** Name of the vector */
  public final String label;

  /** Keys and values */
  private long[] data;
  /** Do we have 'free' key in the map? */
  private boolean hasFreeKey;
  /** Value of 'free' key */
  private int freeValue;

  /** Current map size */
  private int size;
  /** Fill factor, must be between (0 and 1) */
  private final float fillFactor;
  /** We will resize a map once it reaches this size */
  private int threshold;
  /** Mask to calculate the original position */
  private int mask;

  /** An iterator used to get keys and values */
  private int pointer = -1;
  /** The current entry of the pointer */
  private int[] entry = new int[2];

  /** A flag for recalculation */
  private boolean decache = true;
  /** Used for cosine */
  private double magnitude;
  /**
   * Array of keys, sorted by value order, biggest first, used as source to
   * calculate distances with catprint
   */
  private int[] docprint;
  /** {key, sort order} view of data, used for textcat distance */
  private IntIntMap catprint;

  public IntIntMap()
  {
    this(-1, null, 10);
  }

  public IntIntMap(final int code, final String label)
  {
    this(code, label, 10);
  }

  /**
   * Constructor with default fillFactor
   *
   * @param size
   */
  public IntIntMap(final int code, final String label, final int size)
  {
    this.code = code;
    this.label = label;
    /*
     * if ( fillFactor <= 0 || fillFactor >= 1 ) throw new IllegalArgumentException(
     * "FillFactor must be in (0, 1)" ); if ( size <= 0 ) throw new
     * IllegalArgumentException( "Size must be positive!" );
     */
    this.fillFactor = (float) 0.75;
    final int capacity = arraySize(size, fillFactor);
    mask = capacity - 1;
    data = new long[capacity];
    Arrays.fill(data, FREE_CELL);
    threshold = (int) (capacity * fillFactor);
  }

  /**
   * Get an entry by key FREE_CELL if not found
   */
  private long entry(final int key)
  {
    if (key == NO_KEY) return FREE_CELL;
    int idx = getStartIndex(key);
    long c = data[idx];
    // end of chain already
    if (c == FREE_CELL) return FREE_CELL;
    // we check FREE prior to this call
    if (key(c) == key) return c;
    while (true) {
      idx = getNextIndex(idx);
      c = data[idx];
      if (c == FREE_CELL) return FREE_CELL;
      if (key(c) == key) return c;
    }
  }

  /**
   * Check if a key is used
   *
   * @param key
   * @return
   */
  public boolean contains(final int key)
  {
    long c = entry(key);
    if (c == FREE_CELL) return false;
    return true;
  }

  /**
   * Get a value by key
   *
   * @param key
   * @return the value
   */
  public int get(final int key)
  {
    long c = entry(key);
    if (c == FREE_CELL) return NO_VALUE;
    return value(c);
  }

  /**
   * Put a value by key
   *
   * @param key
   * @param value
   * @return old value
   */
  public int put(final int key, final int value)
  {
    return put(key, value, false);
  }

  /**
   * Put an array of values, index in array is the key
   *
   * @param data
   * @return vector for chaining
   */
  public IntIntMap put(int[] data)
  {
    int length = data.length;
    // 0 is an empty
    for (int i = 0; i < length; i++)
      put(i + 1, data[i]);
    return this;
  }

  /**
   * Add value to a key, create it if not exists
   *
   * @param key
   * @param value
   *          new value
   * @return the vector, to chain input
   */
  public IntIntMap add(final int key, final int value)
  {
    put(key, value, true);
    return this;
  }

  /**
   * Add a vector to another
   *
   * @param toadd
   *          IntIntMap to add to this on
   * @return new size
   */
  public int add(IntIntMap toadd)
  {
    toadd.reset();
    while (toadd.next())
      add(toadd.key(), toadd.value());
    return size;
  }

  /**
   * Increment a key when it exists, create it if needed, return
   *
   * @param key
   * @return old value
   */
  public int inc(final int key)
  {
    return put(key, 1, true);
  }

  /**
   * Private access to the values for put, add, or inc
   *
   * @param key
   * @param value
   * @param add
   *          true: value is added to old one if key exists; false: value replace
   *          old value
   * @return old value
   */
  private int put(final int key, int value, boolean add)
  {
    decache = true;
    if (key == NO_KEY) {
      final int ret = freeValue;
      if (!hasFreeKey) ++size;
      hasFreeKey = true;
      freeValue = value;
      return ret;
    }

    int idx = getStartIndex(key);
    long c = data[idx];
    if (c == FREE_CELL) { // end of chain already
      data[idx] = entry(key, value);
      // size is set inside
      if (size >= threshold) rehash(data.length * 2);
      else++size;
      return NO_VALUE;
    }
    // we check FREE prior to this call
    else if (key(c) == key) {
      if (add) value += value(c);
      data[idx] = entry(key, value);
      return value(c);
    }

    while (true) {
      idx = getNextIndex(idx);
      c = data[idx];
      if (c == FREE_CELL) {
        data[idx] = entry(key, value);
        // size is set inside
        if (size >= threshold) rehash(data.length * 2);
        else++size;
        return NO_VALUE;
      }
      else if (key(c) == key) {
        if (add) value += value(c);
        data[idx] = entry(key, value);
        return value(c);
      }
    }
  }

  /**
   *
   * @param key
   * @return Old value
   */
  public int remove(final int key)
  {
    decache = true;
    if (key == NO_KEY) {
      if (!hasFreeKey) return NO_VALUE;
      hasFreeKey = false;
      final int ret = freeValue;
      freeValue = NO_VALUE;
      --size;
      return ret;
    }

    int idx = getStartIndex(key);
    long c = data[idx];
    if (c == FREE_CELL) return NO_VALUE; // end of chain already
    if (key(c) == key) {
      // we check FREE prior to this call
      --size;
      shiftKeys(idx);
      return value(c);
    }
    while (true) {
      idx = getNextIndex(idx);
      c = data[idx];
      if (c == FREE_CELL) return NO_VALUE;
      if (key(c) == key) {
        --size;
        shiftKeys(idx);
        return value(c);
      }
    }
  }

  /**
   * Get internal size
   *
   * @return
   */
  public int size()
  {
    return size;
  }

  /**
   * Build an entry for the data array
   *
   * @param key
   * @param value
   * @return the entry
   */
  private static long entry(int key, int value)
  {
    return ((key & KEY_MASK) | (((long) value) << 32));
  }

  /**
   * Get an int value from a long entry
   */
  private static int value(long entry)
  {
    return (int) (entry >> 32);
  }

  /**
   * Get the key from a long entry
   */
  private static int key(long entry)
  {
    return (int) (entry & KEY_MASK);
  }

  /**
   * Reset Iterator, start at -1 so that we know that pointer is not set on first
   * valid entry (remember, a hash may have lots of empty cells and will not start
   * at 0)
   */
  public void reset()
  {
    pointer = -1;
  }

  /**
   * Iterate throw data to go to next entry Jump empty cells, set entry by
   * reference.
   */
  public boolean next()
  {
    while (pointer + 1 < data.length) {
      pointer++;
      if (data[pointer] != FREE_CELL) {
        entry[0] = key(data[pointer]);
        entry[1] = value(data[pointer]);
        return true;
      }
    }
    reset();
    return false;
  }

  /**
   * Use after next(), get current key by iterator.
   */
  public int key()
  {
    return entry[0];
  }

  /**
   * Use after next(), get current value by iterator.
   */
  public int value()
  {
    return entry[1];
  }

  /**
   * Use after next(), get current entry by iterator.
   *
   * @return
   */
  public int[] entry()
  {
    return entry;
  }

  /**
   * Use after next(), set current entry by iterator.
   */
  public void set(int value)
  {
    data[pointer] = (data[pointer] & KEY_MASK | (((long) value) << 32));
  }

  /**
   *
   * @param ord
   * @return
   */
  private int shiftKeys(int pos)
  {
    // Shift entries with the same hash.
    int last, slot;
    int k;
    final long[] data = this.data;
    while (true) {
      pos = ((last = pos) + 1) & mask;
      while (true) {
        if ((k = key(data[pos])) == NO_KEY) {
          data[last] = FREE_CELL;
          return last;
        }
        slot = getStartIndex(k); // calculate the starting slot for the current key
        if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) break;
        pos = (pos + 1) & mask; // go to the next entry
      }
      data[last] = data[pos];
    }
  }

  private void rehash(final int newCapacity)
  {
    threshold = (int) (newCapacity * fillFactor);
    mask = newCapacity - 1;

    final int oldCapacity = data.length;
    final long[] oldData = data;

    data = new long[newCapacity];
    Arrays.fill(data, FREE_CELL);
    size = hasFreeKey ? 1 : 0;

    for (int i = oldCapacity; i-- > 0;) {
      final int oldKey = key(oldData[i]);
      if (oldKey != NO_KEY) put(oldKey, value(oldData[i]));
    }
  }

  private int getStartIndex(final int key)
  {
    return phiMix(key) & mask;
  }

  private int getNextIndex(final int currentIndex)
  {
    return (currentIndex + 1) & mask;
  }

  /**
   * Returns the least power of two smaller than or equal to 230 and
   * larger than or equal to Math.ceil( expected / f ).
   *
   * @param expected
   *          the expected number of elements in a hash table.
   * @param f
   *          the load factor.
   * @return the minimum possible size for a backing array.
   * @throws IllegalArgumentException
   *           if the necessary size is larger than 230.
   */
  private static int arraySize(final int expected, final float f)
  {
    final long s = Math.max(2, Calcul.nextSquare((long) Math.ceil(expected / f)));
    if (s > (1 << 30))
      throw new IllegalArgumentException("Too large (" + expected + " expected elements with load factor " + f + ")");
    return (int) s;
  }

  // taken from FastUtil
  private static final int INT_PHI = 0x9E3779B9;

  private static int phiMix(final int x)
  {
    final int h = x * INT_PHI;
    return h ^ (h >> 16);
  }

  /**
   * Output a two dimensions array, sorted by value, biggest first
   */
  public Pair[] toArray()
  {
    Pair[] list = new Pair[size];
    int i = 0;
    for (long entry : data) {
      if (entry == FREE_CELL) continue;
      list[i] = new Pair(key(entry), value(entry));
      i++;
    }
    Arrays.sort(list);
    return list;
  }

  public class Pair implements Comparable<Pair>
  {
    public final int key;
    public final int value;

    public Pair(final int key, final int value)
    {
      this.key = key;
      this.value = value;
    }

    /**
     * Default sort by value, biggest first
     */
    @Override
    public int compareTo(Pair o)
    {
      return Integer.compare(o.value, value);
    }

  }

  /**
   * Return an hash<key, order> optimized for textcat
   */
  private IntIntMap catprint()
  {
    if (decache) decache();
    if (catprint != null) return catprint;
    // textcat
    Pair[] pairs = toArray();
    int[] docprint = new int[size];
    int max = size;
    IntIntMap catprint = new IntIntMap(this.code, this.label, size);
    if (max != pairs.length) System.out.println("What ? size do no match: " + max + " != " + docprint.length);
    for (int i = 0; i < max; i++) {
      docprint[i] = pairs[i].key;
      catprint.put(pairs[i].key, i + 1); // 0==NULL
    }
    this.docprint = docprint;
    this.catprint = catprint;
    return catprint;
  }

  private int[] docprint()
  {
    catprint();
    return docprint;
  }

  /**
   * Load a String like saved by toString() a space separated intKey:intValue
   *
   * @param line
   */
  public IntIntMap load(CharSequence line)
  {
    Matcher m = loadre.matcher(line);
    while (m.find()) {
      this.add(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)));
    }
    return this;
  }

  /**
   * A String view of the vector, thought for efficiency to decode Usage of a
   * DataOutputStream has been excluded, a text format is preferred to a binary
   * format A space separated of key:value pair 2:4 6:2 14:4
   */
  @Override
  public String toString()
  {
    StringBuffer sb = new StringBuffer();
    int key;
    boolean first = true;
    for (long entry : data) {
      key = key(entry);
      if (key == NO_KEY) continue;
      if (first) first = false;
      else sb.append(" ");
      sb.append(key + ":" + value(entry));
    }
    return sb.toString();
  }

  /**
   * Equality
   */
  /*
   * @Override public boolean equals(Object obj) { if (!(obj instanceof IntIntMap))
   * return false; if (obj == this) return true; int[][] a =
   * ((IntIntMap)obj).toArray(); int[][] b = ((IntIntMap)obj).toArray(); if ( a.length
   * != b.length ) return false; Arrays.sort( a , new Comparator<int[]>() { public
   * int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); Arrays.sort( b
   * , new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { return
   * o1[0] - o2[0]; } }); int size = a.length; for ( int i = 0; i < size; i++) {
   * if (a[0] != b[0]) return false; if (a[1] != b[1]) return false; } return
   * true; }
   */

  /**
   * Cosine similarity with vector reduction to intersection only
   *
   * @param vek
   * @return the similarity score
   */
  public double intercos(IntIntMap vek)
  {
    double sum = 0;
    double mag1 = 0;
    int val1;
    double mag2 = 0;
    int val2;
    reset();
    while (next()) {
      val2 = vek.get(key());
      if (val2 == IntIntMap.NO_VALUE) continue;
      val1 = value();
      sum += val1 * val2;
      mag1 += val1 * val1;
      mag2 += val2 * val2;
    }
    if (mag1 == 0 || mag2 == 0) return 0;
    mag1 = Math.sqrt(mag1);
    mag2 = Math.sqrt(mag2);
    return sum / (mag1 * mag2);
  }

  /**
   * Cosine similarity with vector
   *
   * @param vek
   * @return the similarity score
   */
  public double cosine(IntIntMap vek)
  {
    double dotp = dotProduct(vek);
    if (dotp <= 0) System.out.println("Dot prod < 0 " + vek.label);
    return dotp / (this.magnitude() * vek.magnitude());
  }

  /**
   * Calculation of magnitude with cache
   *
   * @return the magnitude
   */
  public double magnitude()
  {
    if (decache) decache();
    if (magnitude >= 0) return magnitude;
    long mag = 0;
    long value; // needed to force casting
    reset();
    while (next()) {
      value = value();
      mag += value * value;
    }
    magnitude = Math.sqrt(mag);
    return magnitude;
  }

  /**
   * Delete all cached values
   */
  private void decache()
  {
    magnitude = -1;
    docprint = null;
    catprint = null;
    decache = false;
  }

  /**
   * Used in Cosine calculations
   *
   * @param vek
   * @return
   */
  private double dotProduct(IntIntMap other)
  {
    long sum = 0;
    long value;
    long ovalue;
    // loop on the smallest vector
    if (size < other.size) {
      reset();
      while (next()) {
        ovalue = other.get(key());
        if (ovalue <= 0) continue;
        value = value();
        sum += ovalue * value;
      }
    }
    else {
      other.reset();
      while (other.next()) {
        value = get(other.key());
        if (value <= 0) continue;
        ovalue = other.value();
        sum += ovalue * value;
      }
    }
    return sum;
  }

  /**
   * An alternative distance calculation, good for little
   *
   */
  public int textcat(IntIntMap vek)
  {
    IntIntMap catprint = vek.catprint(); // will update cache
    int[] docprint = docprint();
    int max = docprint.length;
    int dist = 0;
    for (int i = 0; i < max; i++) {
      int rank = catprint.get(docprint[i]) - 1;
      if (rank == IntIntMap.NO_VALUE) dist += max; // no value
      if (rank > i) dist += rank - i;
      else if (i < rank) dist += i - rank;
    }
    return dist;
  }

  /**
   * A data row to sort the important values in a cosine
   *
   * @author glorieux-f
   */
  public class SpecRow implements Comparable<SpecRow>
  {
    public final int key;
    public final int source;
    public final int sval;
    public final int tval;
    public final double spec;

    public SpecRow(final int key, final int source, final int sval, final int target, final int tval, double spec)
    {
      this.key = key;
      this.source = source;
      this.sval = sval;
      this.tval = tval;
      this.spec = spec;
    }

    @Override
    public int compareTo(SpecRow other)
    {
      return Double.compare(other.spec, spec);
    }

    @Override
    public String toString()
    {
      return key + ":(" + sval + "," + tval + "," + spec + ")";
    }
  }

  /**
   *
   * @return
   */
  public ArrayList<SpecRow> specs(IntIntMap other)
  {
    ArrayList<SpecRow> table = new ArrayList<SpecRow>();
    int key;
    final int source = this.code;
    int sval;
    final int target = other.code;
    int tval;
    double div = magnitude() * other.magnitude();
    // loop on the smallest vector
    if (size < other.size) {
      reset();
      while (next()) {
        key = key();
        tval = other.get(key);
        if (tval == IntIntMap.NO_VALUE) continue;
        sval = value();
        table.add(new SpecRow(key, source, sval, target, tval, 1000000.0 * sval * tval / div));
      }
    }
    else {
      other.reset();
      while (other.next()) {
        key = other.key();
        sval = get(key);
        if (sval == IntIntMap.NO_VALUE) continue;
        tval = other.value();
        table.add(new SpecRow(key, source, sval, target, tval, 1000000.0 * sval * tval / div));
      }
    }
    Collections.sort(table);
    return table;
  }

  /**
   * Just for testing, no reasons to use this object in CLI
   */
  public static void main(String[] args)
  {
    IntIntMap vec = new IntIntMap();
    for (int i = 0; i < 10; i++) {
      System.out.println(vec.inc(1));
    }
    /*
     * // test loading a string version ArrayList<IntIntMap> list = new
     * ArrayList<IntIntMap>(); list.add(new IntIntMap().load("1:1 2:1")); list.add(new
     * IntIntMap().load("1:1 2:1")); list.add(new IntIntMap().load("1:10 2:10"));
     * list.add(new IntIntMap().load("1:20 2:20 3:1")); int max = list.size(); for (int
     * i = 0; i < max; i++) { for (int j = 0; j < max; j++) { System.out.println( ""
     * + i + "–" + j + "   " + list.get(i).intercos(list.get(j)) + " " +
     * list.get(i).cosine(list.get(j)));
     * System.out.println(list.get(i).specs(list.get(j))); } }
     */
    /*
     * test if storing is OK IntIntMap vec = new IntIntMap(); for (int i=-50000; i <
     * 50000; i++) vec.put(i, i); for (int i=-50001; i < 50001; i++) { int get =
     * vec.get(i); if (i != get) System.out.println(i+" != "+get);; }
     * while(vec.next()) { vec.set(vec.value()+1); } for (int i=-50001; i < 50001;
     * i++) { int get = vec.get(i); if ( (i+1) != get) System.out.println(
     * (i+1)+" != "+get);; }
     */
  }

}