text:
require('../../support/spec_helper');

describe("Cucumber.SupportCode.StepDefinition", function () {
  var Cucumber = requireLib('cucumber');
  var stepDefinition, pattern, stepDefinitionCode;

  beforeEach(function () {
    pattern            = createSpyWithStubs("pattern", {test: null});
    stepDefinitionCode = createSpy("step definition code");
    spyOn(global, 'RegExp');
    stepDefinition = Cucumber.SupportCode.StepDefinition(pattern, {}, stepDefinitionCode);
  });

  describe("getPatternRegexp()", function () {
    describe("when the pattern is a RegExp", function () {
      it("does not instantiate a RegExp", function () {
        expect(global.RegExp).not.toHaveBeenCalled();
      });

      it("returns the pattern itself", function () {
        expect(stepDefinition.getPatternRegexp()).toBe(pattern);
      });
    });

    describe("when the pattern is a String", function () {
      var regexp, quotedDollarParameterSubstitutedPattern, safeString, regexpString;

      beforeEach(function () {
        regexp                                  = createSpy("regexp");
        regexpString                            = "regexp string";
        safeString                              = createSpyWithStubs("safe string");
        quotedDollarParameterSubstitutedPattern = createSpyWithStubs("quoted dollar param substituted pattern", {replace: regexpString});
        spyOnStub(pattern, 'replace').and.returnValue(safeString);
        spyOnStub(safeString, 'replace').and.returnValue(quotedDollarParameterSubstitutedPattern);
        global.RegExp.and.returnValue(regexp);
      });

      it("escapes unsafe regexp characters from the string", function () {
        stepDefinition.getPatternRegexp();
        expect(pattern.replace).toHaveBeenCalledWith(Cucumber.SupportCode.StepDefinition.UNSAFE_STRING_CHARACTERS_REGEXP, Cucumber.SupportCode.StepDefinition.PREVIOUS_REGEXP_MATCH);
      });

      it("replaces quoted dollar-prefixed parameters with the regexp equivalent", function () {
        stepDefinition.getPatternRegexp();
        expect(safeString.replace).toHaveBeenCalledWith(Cucumber.SupportCode.StepDefinition.QUOTED_DOLLAR_PARAMETER_REGEXP, Cucumber.SupportCode.StepDefinition.QUOTED_DOLLAR_PARAMETER_SUBSTITUTION);
      });

      it("replaces other dollar-prefixed parameter with the regexp equivalent", function () {
        stepDefinition.getPatternRegexp();
        expect(quotedDollarParameterSubstitutedPattern.replace).toHaveBeenCalledWith(Cucumber.SupportCode.StepDefinition.DOLLAR_PARAMETER_REGEXP, Cucumber.SupportCode.StepDefinition.DOLLAR_PARAMETER_SUBSTITUTION);
      });

      it("instantiates a new RegExp", function () {
        stepDefinition.getPatternRegexp();
        expect(global.RegExp).toHaveBeenCalledWith("^" + regexpString + "$");
      });

      it("returns the new RegExp", function () {
        expect(stepDefinition.getPatternRegexp()).toBe(regexp);
      });
    });
  });

  describe("matchesStepName()", function () {
    var patternRegexp, stepName, matchResult;

    beforeEach(function () {
      stepName      = createSpy("step name");
      matchResult   = createSpy("step match result (boolean)");
      patternRegexp = createSpyWithStubs("pattern regexp", {test: matchResult});
      spyOn(stepDefinition, 'getPatternRegexp').and.returnValue(patternRegexp);
    });

    it("gets the pattern regexp", function () {
      stepDefinition.matchesStepName(stepName);
      expect(stepDefinition.getPatternRegexp).toHaveBeenCalled();
    });

    it("tests the string against the step name", function () {
      stepDefinition.matchesStepName(stepName);
      expect(patternRegexp.test).toHaveBeenCalledWith(stepName);
    });

    it("returns the match result", function () {
      expect(stepDefinition.matchesStepName(stepName)).toBe(matchResult);
    });
  });

  describe("invoke()", function () {
    var step, world, scenario, defaultTimeout, callback;
    var parameters, exceptionHandler;
    var timestamp = 0;

    beforeEach(function () {
      step                          = createSpy("step");
      world                         = createSpy("world");
      scenario                      = createSpyWithStubs("scenario", {getAttachments: undefined});
      defaultTimeout                = 5 * 1000;
      callback                      = createSpy("callback");
      parameters                    = createSpy("code execution parameters");
      exceptionHandler              = createSpy("exception handler");
      spyOn(Cucumber.Util.Exception, 'registerUncaughtExceptionHandler');
      spyOn(stepDefinition, 'buildCodeCallback').and.callFake(function (codeCallback) { return codeCallback; });
      spyOn(stepDefinition, 'buildInvocationParameters').and.returnValue(parameters);
      spyOn(stepDefinition, 'buildExceptionHandlerToCodeCallback').and.returnValue(exceptionHandler);
      spyOn(stepDefinitionCode, 'apply');

      if (process.hrtime) {
        spyOn(process, 'hrtime').and.callFake(function (time) {
          if (time) {
            return [0 - time[0], (timestamp * 1e6) - time[1]];
          }
          else {
            return [0, timestamp * 1e6];
          }
        });
      }
      else {
        spyOn(global, 'Date').and.callFake(function () {
          return {
            getTime: function () {
              return timestamp;
            }
          };
        });
      }
    });

    it("builds the step invocation parameters", function () {
      stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
      expect(stepDefinition.buildInvocationParameters).toHaveBeenCalled();
      expect(stepDefinition.buildInvocationParameters).toHaveBeenCalledWithValueAsNthParameter(step, 1);
      expect(stepDefinition.buildInvocationParameters).toHaveBeenCalledWithValueAsNthParameter(scenario, 2);
      expect(stepDefinition.buildInvocationParameters).toHaveBeenCalledWithAFunctionAsNthParameter(3);
    });

    it("builds an exception handler for the code callback", function () {
      stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
      expect(stepDefinition.buildExceptionHandlerToCodeCallback).toHaveBeenCalledWithAFunctionAsNthParameter(1);

      var codeExecutionCallbackPassedToParameterBuilder = stepDefinition.buildInvocationParameters.calls.mostRecent().args[2];
      var codeExecutionCallbackPassedToExceptionHandlerBuilder = stepDefinition.buildExceptionHandlerToCodeCallback.calls.mostRecent().args[0];
      expect(codeExecutionCallbackPassedToExceptionHandlerBuilder).toBe(codeExecutionCallbackPassedToParameterBuilder);
    });

    it("registers the exception handler for uncaught exceptions", function () {
      stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
      expect(Cucumber.Util.Exception.registerUncaughtExceptionHandler).toHaveBeenCalledWith(exceptionHandler);
    });

    it("calls the step definition code with the parameters and World as 'this'", function () {
      stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
      expect(stepDefinitionCode.apply).toHaveBeenCalledWith(world, parameters);
    });

    it("builds the code callback", function () {
      stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
      expect(stepDefinition.buildCodeCallback).toHaveBeenCalled();
      expect(stepDefinition.buildCodeCallback).toHaveBeenCalledWithAFunctionAsNthParameter(1);
    });

    describe("callback used to build the code callback", function () {
      var codeExecutionCallback, stepResult, attachments;

      beforeEach(function () {
        stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
        codeExecutionCallback = stepDefinition.buildCodeCallback.calls.mostRecent().args[0];
        stepResult            = createSpy("step result");
        attachments           = createSpy("attachments");
        spyOn(Cucumber.Runtime, 'StepResult').and.returnValue(stepResult);
        spyOn(Cucumber.Util.Exception, 'unregisterUncaughtExceptionHandler');
      });

      it("is passed to the step definition code", function () {
        expect(stepDefinition.buildInvocationParameters.calls.mostRecent().args[2]).toBe(codeExecutionCallback);
      });

      describe("when called without an error", function () {
        beforeEach(function () {
          timestamp = 1;
          spyOnStub(scenario, 'getAttachments').and.returnValue(attachments);
          codeExecutionCallback();
        });

        it("gets the attachments from the scenario", function () {
          expect(scenario.getAttachments).toHaveBeenCalled();
        });

        it("creates a successful step result", function () {
          expect(Cucumber.Runtime.StepResult).toHaveBeenCalledWith({
            step: step,
            stepDefinition: stepDefinition,
            duration: 1e6,
            attachments: attachments,
            status: Cucumber.Status.PASSED
          });
        });

        it("unregisters the exception handler", function () {
          expect(Cucumber.Util.Exception.unregisterUncaughtExceptionHandler).toHaveBeenCalledWith(exceptionHandler);
        });

        it("calls back", function () {
          expect(callback).toHaveBeenCalledWith(stepResult);
        });

        afterEach(function () {
          timestamp = 0;
        });
      });

      describe("when called with an error", function () {
        var failureReason;

        beforeEach(function () {
          timestamp = 1;
          spyOnStub(scenario, 'getAttachments').and.returnValue(attachments);
          failureReason = 'an error';
          codeExecutionCallback(failureReason);
        });

        it("gets the attachments from the scenario", function () {
          expect(scenario.getAttachments).toHaveBeenCalled();
        });

        it("creates a failing step result", function () {
          expect(Cucumber.Runtime.StepResult).toHaveBeenCalledWith({
            step: step,
            stepDefinition: stepDefinition,
            failureException: failureReason,
            duration: 1e6,
            attachments: attachments,
            status: Cucumber.Status.FAILED
          });
        });

        it("unregisters the exception handler", function () {
          expect(Cucumber.Util.Exception.unregisterUncaughtExceptionHandler).toHaveBeenCalledWith(exceptionHandler);
        });

        it("calls back", function () {
          expect(callback).toHaveBeenCalledWith(stepResult);
        });

        afterEach(function () {
          timestamp = 0;
        });
      });

      describe("pending()", function () {
        var pendingReason;

        beforeEach(function () {
          pendingReason     = createSpy("pending reason");
          spyOnStub(scenario, "getAttachments").and.returnValue(attachments);
        });

        it("gets the attachments from the scenario", function () {
          codeExecutionCallback.pending(pendingReason);
          expect(scenario.getAttachments).toHaveBeenCalled();
        });

        it("creates a pending step result", function () {
          codeExecutionCallback.pending(pendingReason);
          expect(Cucumber.Runtime.StepResult).toHaveBeenCalledWith({
            step: step,
            stepDefinition: stepDefinition,
            pendingReason: pendingReason,
            attachments: attachments,
            status: Cucumber.Status.PENDING
          });
        });

        it("unregisters the exception handler", function () {
          codeExecutionCallback.pending(pendingReason);
          expect(Cucumber.Util.Exception.unregisterUncaughtExceptionHandler).toHaveBeenCalledWith(exceptionHandler);
        });

        it("calls back", function () {
          codeExecutionCallback.pending(pendingReason);
          expect(callback).toHaveBeenCalledWith(stepResult);
        });
      });
    });

    describe("when the step definition code throws an exception", function () {
      var failureException;

      beforeEach(function () {
        failureException = new Error("failing step definition exception");
        stepDefinitionCode.apply.and.throwError(failureException);
      });

      it("handles the exception with the exception handler", function () {
        stepDefinition.invoke(step, world, scenario, defaultTimeout, callback);
        expect(exceptionHandler).toHaveBeenCalledWith(failureException);
      });
    });
  });

  describe("buildCodeCallback", function () {
    it("is just a pass through", function () {
      var callback = createSpy("callback");
      var returnValue = stepDefinition.buildCodeCallback(callback);
      expect(returnValue).toBe(callback);
    });
  });

  describe("buildInvocationParameters()", function () {
    var patternRegexp, step, stepName, stepAttachmentContents;
    var matches, scenario, callback;

    beforeEach(function () {
      stepName               = createSpy("step name to match");
      matches                = createSpyWithStubs("matches", {shift: null, push: null});
      patternRegexp          = createSpyWithStubs("pattern regexp", {test: matches});
      stepAttachmentContents = createSpy("step attachment contents");
      step                   = createSpyWithStubs("step", {hasAttachment: null, getName: stepName, getAttachmentContents: stepAttachmentContents});
      scenario               = createSpy("scenario");
      callback               = createSpy("callback");
      spyOn(stepDefinition, 'getPatternRegexp').and.returnValue(patternRegexp);
      spyOnStub(patternRegexp, 'exec').and.returnValue(matches);
    });

    it("gets the step name", function () {
      stepDefinition.buildInvocationParameters(step, scenario, callback);
      expect(step.getName).toHaveBeenCalled();
    });

    it("gets the pattern regexp", function () {
      stepDefinition.buildInvocationParameters(step, scenario, callback);
      expect(stepDefinition.getPatternRegexp).toHaveBeenCalled();
    });

    it("executes the pattern regexp against the step name", function () {
      stepDefinition.buildInvocationParameters(step, scenario, callback);
      expect(patternRegexp.exec).toHaveBeenCalledWith(stepName);
    });

    it("removes the whole matched string of the regexp result array (to only keep matching groups)", function () {
      stepDefinition.buildInvocationParameters(step, scenario, callback);
      expect(matches.shift).toHaveBeenCalled();
    });

    it("checks whether the step has an attachment or not", function () {
      stepDefinition.buildInvocationParameters(step, scenario, callback);
      expect(step.hasAttachment).toHaveBeenCalled();
    });

    describe("when the step has an attachment", function () {
      beforeEach(function () {
        step.hasAttachment.and.returnValue(true);
      });

      it("gets the attachment contents", function () {
        stepDefinition.buildInvocationParameters(step, scenario, callback);
        expect(step.getAttachmentContents).toHaveBeenCalled();
      });

      it("adds the attachment contents to the parameter array", function () {
        stepDefinition.buildInvocationParameters(step, scenario, callback);
        expect(matches.push).toHaveBeenCalledWith(stepAttachmentContents);
      });
    });

    describe("when the step has no attachment", function () {
      beforeEach(function () {
        step.hasAttachment.and.returnValue(false);
      });

      it("does not get the attachment contents", function () {
        stepDefinition.buildInvocationParameters(step, scenario, callback);
        expect(step.getAttachmentContents).not.toHaveBeenCalled();
      });

      it("does not add the attachement contents to the parameter array", function () {
        stepDefinition.buildInvocationParameters(step, scenario, callback);
        expect(matches.push).toHaveBeenCalledTimes(1);
      });
    });

    it("adds the callback to the parameter array", function () {
      stepDefinition.buildInvocationParameters(step, scenario, callback);
      expect(matches.push).toHaveBeenCalledWith(callback);
    });

    it("returns the parameters", function () {
      expect(stepDefinition.buildInvocationParameters(step, scenario, callback)).toBe(matches);
    });
  });

  describe("buildExceptionHandlerToCodeCallback()", function () {
    var codeCallback, exceptionHandler;

    beforeEach(function () {
      codeCallback = createSpy("code callback");
      exceptionHandler = stepDefinition.buildExceptionHandlerToCodeCallback(codeCallback);
    });

    it("returns an exception handler", function () {
      expect(exceptionHandler).toBeAFunction ();
    });

    describe("returned exception handler", function () {
      var exception;

      beforeEach(function () {
        exception = createSpy("exception");
      });

      it("calls back as a failure with the exception", function () {
        exceptionHandler(exception);
        expect(codeCallback).toHaveBeenCalledWith(exception);
      });
    });
  });
});


text:
package mil.nga.giat.geowave.adapter.vector.query;

import java.util.Iterator;
import java.util.Map.Entry;

import mil.nga.giat.geowave.adapter.vector.plugin.GeoWaveFeatureCollection;
import mil.nga.giat.geowave.adapter.vector.wms.accumulo.RenderedMaster;
import mil.nga.giat.geowave.core.index.PersistenceUtils;

import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

/**
 * This wraps RenderedMaster results from the Iterator within a SimpleFeature
 * object as the GeoTools data store expects. A special purpose renderer within
 * GeoTools will have to take these features and composite it into the resultant
 * map.
 *
 */
public class RenderIteratorWrapper implements
		Iterator<SimpleFeature>
{
	private final Iterator<Entry<Key, Value>> scannerIt;

	private SimpleFeature nextValue;
	private final SimpleFeatureType featureType;

	public RenderIteratorWrapper(
			final Iterator<Entry<Key, Value>> scannerIt ) {
		this.scannerIt = scannerIt;
		featureType = GeoWaveFeatureCollection.getDistributedRenderFeatureType();
		findNext();
	}

	private void findNext() {
		while (scannerIt.hasNext()) {
			final Entry<Key, Value> row = scannerIt.next();
			final SimpleFeature decodedValue = decodeRow(row);
			if (decodedValue != null) {
				nextValue = decodedValue;
				return;
			}
		}
		nextValue = null;
	}

	private SimpleFeature decodeRow(
			final Entry<Key, Value> row ) {
		final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
				featureType);
		featureBuilder.add(PersistenceUtils.fromBinary(
				row.getValue().get(),
				RenderedMaster.class));
		return featureBuilder.buildFeature(row.getKey().toString());
	}

	@Override
	public boolean hasNext() {
		return nextValue != null;
	}

	@Override
	public SimpleFeature next() {
		final SimpleFeature previousNext = nextValue;
		findNext();
		return previousNext;
	}

	@Override
	public void remove() {
		// TODO what should we do here considering the scanning iterator is
		// already past the current entry? it probably doesn't matter much as
		// this is not called in practice

		// scannerIt.remove();
	}

}

redpajama_set_name: RedPajamaGithub


text:
* Layout when wondow resized
* drop down, replace with new utility scene
* conformation alert
* greedy layout not working well
* empty scroll still moves the contents
* clj styles needs to be ordered

* Buttons should size themselves based on text?
* remote API to replace DRb
* Configurable Test infrastructure for each language
* rewrite 9-patch
* Test send method on productions
* Resolve JNA issue

Make text selectable
Drop shadows
Allow production styles and stages to be built in production.rb
bundler integration


text:
'use strict';

// Index definitions

module.exports =  {
    // Collection name
    players : {
        // Index setting, modify it on your need
        indexes : [
            {
                // Index keys
                keys : ['areaId'],
                // Value exclude from index. Values like '', -1 occurs too often, which can make the index too large.
                // 'null' or 'undefined' is ignored by default.
                valueIgnore : {
                    areaId : [''],
                },
            },
            {
                keys : ['teamId'],
                valueIgnore : {
                    teamId : [''],
                },
            },
        ]
    }
};


text:
#define MICROPY_HW_BOARD_NAME       "THUNDERPACK_v11"
#define MICROPY_HW_MCU_NAME         "STM32F411CE"

// Non-volatile memory config
#define CIRCUITPY_INTERNAL_NVM_SIZE        (0x4000)
#define CIRCUITPY_INTERNAL_NVM_START_ADDR  (0x08010000)
#define CIRCUITPY_INTERNAL_NVM_SECTOR      FLASH_SECTOR_4

// Putting the entire flash sector in the NVM byte array buffer
// would take up too much RAM. This limits how much of the sector we use.
#define NVM_BYTEARRAY_BUFFER_SIZE   512

// Flash config
#define FLASH_SIZE                  (0x80000)
#define FLASH_PAGE_SIZE             (0x4000)
#define BOARD_FLASH_SIZE            (FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE - 0x2000 - 0xC000)

#define HSE_VALUE                   ((uint32_t)24000000U)
#define BOARD_OVERWRITE_SWD         (1)
#define BOARD_NO_VBUS_SENSE         (1)

#define BOARD_HAS_LOW_SPEED_CRYSTAL (0)

// Status LEDs
#define MICROPY_HW_LED_STATUS       (&pin_PA02)

#define DEFAULT_I2C_BUS_SCL         (&pin_PB06)
#define DEFAULT_I2C_BUS_SDA         (&pin_PB07)

#define MICROPY_FATFS_EXFAT 0


text:
package com.bazaarvoice.jless.ast.node;

import com.bazaarvoice.jless.ast.visitor.NodeAdditionVisitor;
import com.bazaarvoice.jless.ast.visitor.NodeNavigationVisitor;

public class SelectorGroupNode extends InternalNode {

    public SelectorGroupNode(Node child) {
        super(child);
    }

    @Override
    protected boolean add(NodeAdditionVisitor visitor) {
        return visitor.add(this);
    }

    @Override
    protected boolean enter(NodeNavigationVisitor visitor) {
        return visitor.enter(this);
    }

    @Override
    protected boolean exit(NodeNavigationVisitor visitor) {
        return visitor.exit(this);
    }

    @Override
    protected boolean visitInvisible(NodeNavigationVisitor visitor) {
        return visitor.visitInvisible(this);
    }
}


text:
using CoreBlog.Web.Factory;
using CoreBlog.Web.Services;
using CoreBlog.Web.ViewModels.Post;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;

namespace CoreBlog.Web.Controllers
{
    [ResponseCache(CacheProfileName = "Default")]
    [Route("[controller]")]
    [Authorize(Policy = "Active")]
    public sealed partial class PostController : Controller
    {
        private IPostService postService { get; }

        public PostController(IPostService postService)
        {
            this.postService = postService;
        }

        [HttpGet("Open/{id:int}")]
        [AllowAnonymous]
        public IActionResult OpenPost(int id)
        {
            try
            {
                var post = postService.GetPostById(id);

                var postViewModel = ModelFactory.Create<PostViewModel>(post);

                return View(postViewModel);
            }
            catch (Exception)
            {
                //no such id
                return NotFound();
            }
        }

        [HttpGet("Create")]
        public IActionResult CreatePost()
        {
            return View();
        }
    }
}


text:
id: 1622
title: Pictures from Yaroslavl
date: 2009-11-04T23:02:13+00:00
author: Vicki
layout: post
guid: http://blog.vickiboykis.com/wlb/?p=1622
permalink: /2009/11/pictures-from-yaroslavl/
categories:
  - Uncategorized
tags:
  - flickr
  - Russia
---
I figured everyone would be tired of all the NaNoWriMo reporting, so here are a couple pictures from my home city of Yaroslavl, from of [nohobot on Flickr](http://www.flickr.com/photos/nohobotic/sets/72157606272098632/).  I hope you don't mind me using these, because [they are gorgeous and evoke a definite sense of longing](http://www.flickr.com/photos/nohobotic/sets/72157606272098632/). The NaNoWriMo Day 4 post is below.

[<img class="aligncenter size-full wp-image-1623" title="Yaroslavl3" src="https://raw.githubusercontent.com/veekaybee/wlb/gh-pages/assets/images/2009/11/Yaroslavl3.jpg" alt="Yaroslavl3" width="375" height="500" />](https://raw.githubusercontent.com/veekaybee/wlb/gh-pages/assets/images/2009/11/Yaroslavl3.jpg)


text:
// <copyright file="Program.cs" company="Berkeleybross">
// Copyright (c) Berkeleybross. All rights reserved.
// </copyright>

namespace PeregrineDb.PerformanceTests
{
    using System;
    using System.Data.SqlClient;
    using System.Reflection;
    using BenchmarkDotNet.Running;

    public static class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Using ConnectionString: " + GetBenchmarks.ConnectionString);
            EnsureDBSetup();
            Console.WriteLine("Database setup complete.");

            BenchmarkSwitcher.FromAssembly(typeof(Program).GetTypeInfo().Assembly).Run(args);
        }

        private static void EnsureDBSetup()
        {
            using (var cnn = new SqlConnection(GetBenchmarks.ConnectionString))
            {
                cnn.Open();
                var cmd = cnn.CreateCommand();
                cmd.CommandText = @"
If (Object_Id('Posts') Is Null)
Begin
	Create Table Posts
	(
		Id int identity primary key,
		[Text] varchar(max) not null,
		CreationDate datetime not null,
		LastChangeDate datetime not null,
		Counter1 int,
		Counter2 int,
		Counter3 int,
		Counter4 int,
		Counter5 int,
		Counter6 int,
		Counter7 int,
		Counter8 int,
		Counter9 int
	);

	Set NoCount On;
	Declare @i int = 0;

	While @i <= 5001
	Begin
		Insert Posts ([Text],CreationDate, LastChangeDate) values (replicate('x', 2000), GETDATE(), GETDATE());
		Set @i = @i + 1;
	End
End
";
                cmd.Connection = cnn;
                cmd.ExecuteNonQuery();
            }
        }

        private static void WriteLineColor(string message, ConsoleColor color)
        {
            var orig = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.WriteLine(message);
            Console.ForegroundColor = orig;
        }

        public static void WriteColor(string message, ConsoleColor color)
        {
            var orig = Console.ForegroundColor;
            Console.ForegroundColor = color;
            Console.Write(message);
            Console.ForegroundColor = orig;
        }
    }
}


text:
With the release of [Stateful Sets](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/) and custom [Storage Classes](http://kubernetes.io/docs/user-guide/persistent-volumes/#storageclasses), Kubernetes can automate all of the underlying infra required to run a MongoDB Replica Sets

*Note:* Stateful Sets are beta. **This requires Kubernetes 1.5.1**

## Before You Start

- Have a Kubernetes Cluster created with at least version 1.5.1
- Have admin access to the cluster

## Creating the Storage Class

The storage class will create the [Volumes](http://kubernetes.io/docs/user-guide/persistent-volumes) backing the MongoDB Replica Sets.

You can create Storage Classes with different provisioners depending on your Kubernetes environment. There are provisioners for [Google Cloud](http://kubernetes.io/docs/user-guide/persistent-volumes/#gce), [AWS](http://kubernetes.io/docs/user-guide/persistent-volumes/#aws), [Azure](http://kubernetes.io/docs/user-guide/persistent-volumes/#azure-disk), [GlusterFS](http://kubernetes.io/docs/user-guide/persistent-volumes/#glusterfs), [OpenStack Cinder](http://kubernetes.io/docs/user-guide/persistent-volumes/#openstack-cinder), [vSphere](http://kubernetes.io/docs/user-guide/persistent-volumes/#vsphere), [Ceph RBD](http://kubernetes.io/docs/user-guide/persistent-volumes/#ceph-rbd), and [Quobyte](http://kubernetes.io/docs/user-guide/persistent-volumes/#quobyte). Pick the right one for your deployment.

For example, this [YAML](googlecloud_ssd.yaml) uses a Google Cloud SSD Persistent Disk, and has the name "fast"

Create the Storage Class with the `kubectl` tool.

```
kubectl apply -f googlecloud_ssd.yaml
```

Replace `googlecloud_ssd.yaml` with another configuration file if you are not using Google Cloud. For example, if you are running Kubernetes on Azure, you can use the Azure SSD [YAML](azure_ssd.yaml). It uses the same name, "fast", so your application does not need to understand the underlying platform.

```
kubectl apply -f azure_ssd.yaml
```

Verify that the Storage Class is created

```
$ kubectl get storageclass
NAME      TYPE
fast       kubernetes.io/gce-pd
```

## Creating the Stateful Set

The [example YAML](mongo-statefulset.yaml) creates a [Headless Service](http://kubernetes.io/docs/user-guide/services/#headless-services) and a [Stateful Set](http://kubernetes.io/docs/concepts/abstractions/controllers/statefulsets/). It uses the Storage Class created in the previous step, and provisions a 100Gi volume per replica. Modify these values as you see fit.

```
kubectl apply -f mongo-statefulset.yaml
```

Verify that the Stateful Set is created
```
$ kubectl get statefulset
NAME      DESIRED   CURRENT   AGE
mongo     3         0         12m
```
The Stateful Set controller will spin up each replica one at a time. Eventually, all three will be created.

```
$ kubectl get statefulset
NAME      DESIRED   CURRENT   AGE
mongo     3         3         12m
```

You can also verify that the Volumes were created as well.

```
$ kubectl get pvc
NAME                               STATUS    VOLUME                                     CAPACITY   ACCESSMODES   AGE
mongo-persistent-storage-mongo-0   Bound     pvc-af87f9d5-d3ab-11e6-8cf2-42010af0018d   100Gi      RWO           12m
mongo-persistent-storage-mongo-1   Bound     pvc-af8cef48-d3ab-11e6-8cf2-42010af0018d   100Gi      RWO           12m
mongo-persistent-storage-mongo-2   Bound     pvc-af8f1d24-d3ab-11e6-8cf2-42010af0018d   100Gi      RWO           12m
```

## Connecting to the MongoDB Replica Set

Each MongoDB Replica Set will have its own DNS address. This will take the format `<pod-name>.<service-name>`.

For our example, the DNS addresses to use will be:

```
mongo-0.mongo
mongo-1.mongo
mongo-2.mongo
```

Put these in your connection url. For example:

```
mongodb://mongo-0.mongo,mongo-1.mongo,mongo-2.mongo:27017/dbname_?'
```


text:
The built-in functions for error, usually, returns `FALSE` and prints WARNING.
The library in these cases throws an exception.

Specific exception classes dependent of an implementation.
These must inherit of `axy\fs\ifs\errors\FSError`.

The only method of an exception object is `getTargetFileName()`.
It returns the name of a file due to which the error occurred (if it possible).

Exception messages dependent of an implementation.
For implementation which work via built-in functions, likely, the exception message will be a warning message.


text:
package tcl.lang;

/*
 * This is a stub class used in Jacl to represent objects created in
 * the Tcl Blend interpreter. Actually CObjects will never appear inside
 * Jacl. However, since TclObject (which is shared between the Tcl Blend
 * and Jacl implementations) makes some references to CObject, we include
 * a stub class here to make the compiler happy.
 *
 * None of the methods in this implementation will ever be called.
 */

class CObject implements InternalRep {

public void dispose()
{
    throw new TclRuntimeError("This shouldn't be called");
}

public InternalRep duplicate()
{
    throw new TclRuntimeError("This shouldn't be called");
}

final void makeReference(TclObject tobj)
{
    throw new TclRuntimeError("This shouldn't be called");
}

public String toString()
{
    throw new TclRuntimeError("This shouldn't be called");
}

} // end CObject


text:
import * as React from 'react';
import TooltipOptions from '../tooltip/tooltipoptions';

interface RadioButtonChangeTargetOptions {
    name: string;
    id: string;
    value: any;
    checked: boolean;
}

interface RadioButtonChangeParams {
    originalEvent: React.SyntheticEvent;
    value: any;
    checked: boolean;
    stopPropagation(): void;
    preventDefault(): void;
    target: RadioButtonChangeTargetOptions;
}

export interface RadioButtonProps {
    id?: string;
    inputRef?: React.Ref<HTMLInputElement>;
    inputId?: string;
    name?: string;
    value?: any;
    checked?: boolean;
    style?: object;
    className?: string;
    disabled?: boolean;
    required?: boolean;
    tabIndex?: number;
    tooltip?: string;
    tooltipOptions?: TooltipOptions;
    ariaLabelledBy?: string;
    onChange?(e: RadioButtonChangeParams): void;
}

export declare class RadioButton extends React.Component<RadioButtonProps, any> { }


text:
package com.sas.unravl.test;

import static org.junit.Assert.assertArrayEquals;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sas.unravl.UnRAVL;
import com.sas.unravl.UnRAVLException;
import com.sas.unravl.UnRAVLRuntime;
import com.sas.unravl.generators.Binary;
import com.sas.unravl.util.Json;

import java.io.IOException;

import org.junit.Test;

public class TestBinary extends TestBase {

    @Test
    public void simpleBinary() throws IOException, UnRAVLException {
        testBinary("{ 'binary' : [0, 1, 2, 3, 4 ] }", new byte[] { 0, 1, 2, 3,
                4 });
        testBinary("{ 'binary' : [0, 1, [2, 3], 4 ] }", new byte[] { 0, 1, 2,
                3, 4 });
        testBinary("{ 'binary' : [0, 1, '@src/test/java/B.txt', 4 ] }",
                new byte[] { 0, 1, 'B', '\n', 4 });
    }

    private void testBinary(String json, byte expected[]) throws IOException,
            UnRAVLException {
        ObjectNode node = Json.object(mockJson(json));
        UnRAVL script = new UnRAVL(new UnRAVLRuntime());
        Binary binary = new Binary(script, node, "binary");
        byte actual[] = binary.bytes();
        assertArrayEquals(expected, actual);
    }

    @Test(expected = IOException.class)
    public void noSuchFile() throws IOException, UnRAVLException {
        ObjectNode node = Json.object(mockJson("{'binary' : '@noSuchFile' }"));
        UnRAVL script = new UnRAVL(new UnRAVLRuntime());
        new Binary(script, node, "binary");
    }

    @Test(expected = IOException.class)
    public void noSuchURL() throws IOException, UnRAVLException {
        ObjectNode node = Json
                .object(mockJson("{'binary' : '@scheme://host:9090/no/such/resource.ext' }"));
        UnRAVL script = new UnRAVL(new UnRAVLRuntime());
        new Binary(script, node, "binary");
    }

}


text:
module Roomiverse {
	export class Player {
		context: any
		group: Phaser.Group
		graphics: Phaser.Graphics

		radius: number = 43
		velocity: Point = Point.create()
		inventory: Inventory

		constructor(context: any, group: Phaser.Group) {
			this.context = context

			this.group = this.context.add.group(group)
			this.group.x = this.context.world.centerX
			this.group.y = this.context.world.centerY

			this.graphics = this.context.add.graphics(0, 0, this.group)
			this.graphics.beginFill(0xffffff, 1)
			this.graphics.drawCircle(0, 0, this.radius)

			this.inventory = new Inventory(context, group)
		}

		tick(seconds: number) {
			this.velocity.scale(Math.pow(0.987, 1000 * seconds))
			this.moveBy(this.velocity.scaled(seconds))

			// keep player in room
			const leeway = this.radius / 2 + 3
			if(this.group.x < 400 + leeway) { this.group.x = 400 + leeway }
			if(this.group.y < 120 + leeway) { this.group.y = 120 + leeway }
			if(this.group.x > 880 - leeway) { this.group.x = 880 - leeway }
			if(this.group.y > 600 - leeway) { this.group.y = 600 - leeway }
		}

		accelBy(p: Point) {
			this.velocity.translateBy(p)
		}

		moveBy(p: Point) {
			this.group.x += p.x
			this.group.y += p.y
		}
	}
}


text:
"""
Script that builds one or more release apks.

Does the following things in several steps:

Step 1: (e.g., --beta):
    - Runs the selected (clean) Gradle builds (e.g. beta, amazon, or prod and releasesprod combined)

Step 2: (e.g., --beta --push):
    - Creates an annotated tag called 'releases/versionName'
    - Pushes the git tag to gerrit for history
    - TODO (Not implemented yet): Uploads certain bits to releases.mediawiki.org: releasesprod, beta

To run
1) tell people on #wikimedia-mobile you're about to bump the version,
   so hold off on merging to master
2) git checkout master
3) git pull
4) git reset --hard
5) python scripts/make-release.py --prod
Note: the apk file locations are printed to stdout
6) manual step: test the apk(s): adb install -r <apk file>
7) python scripts/make-release.py --prod --push
8) compile release note of prod using (replace "r/*" with "beta/*" or "amazon/*")
    git log --pretty=format:"%h | %cr | %s" --abbrev-commit --no-merges `git tag -l r/*|tail -1`..
9) Upload prod apk to store, releasesprod apk to releases.mediawiki.org

Requires the python module 'sh' and the environment variable ANDROID_HOME to run.
Ensure you have a clean working directory before running as well.

See also https://www.mediawiki.org/wiki/Wikimedia_Apps/Team/Release_process
"""
import argparse
import glob
import os
import re
import sh
import subprocess
import sys

PATH_PREFIX = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
GRADLEW = './gradlew'
VERSION_START = '2.1'

def p(*path_fragments):
    """
    Combine the path fragments with PATH_PREFIX as a base, and return
    the new full path
    """
    return os.path.join(PATH_PREFIX, *path_fragments)

def get_git_tag_name(target, version_name):
    """
    Returns name used for creating the tag
    """
    return target + '/' + version_name

def git_tag(target, version_name):
    """
    Creates an annotated git tag for this release
    """
    sh.git.tag('-a', get_git_tag_name(target, version_name), '-m', target)

def push_to_gerrit(target, version_name):
    """
    Pushes the git tag to gerrit
    """
    tag_name = get_git_tag_name(target, version_name)
    print('pushing tag ' + tag_name)
    sh.git.push('gerrit', tag_name)

def make_release(flavors, custom_channel, custom_app):
    sh.cd(PATH_PREFIX)
    # ./gradlew -q assembleDevDebug
    args = [GRADLEW,
            '-q',
            'clean',
            '-PcustomChannel=' + custom_channel,
            '-PcustomApplicationId=' + custom_app]
    tasks = ['assemble{0}Release'.format(flavor.title()) for flavor in flavors]
    args += tasks
    subprocess.call(args)

def copy_artifacts(flavor):
    folder_path = 'releases'
    sh.mkdir("-p", folder_path)
    version_name = get_version_name_from_apk(get_original_apk_file_name(flavor))
    copy_apk(flavor, version_name)

def get_original_apk_file_name(flavor):
    return 'app/build/outputs/apk/app-%s-release.apk' % flavor

def get_android_home():
    android_home = os.environ['ANDROID_HOME']
    if android_home:
        return android_home
    else:
        sys.exit('$ANDROID_HOME not set')

def grep_from_build_file(property_name, regex):
    build_gradle_file_name = 'app/build.gradle'
    with open(build_gradle_file_name, "r") as build_file:
        for line in build_file:
            found = re.search(regex, line)
            if found:
                res = found.groups()[0]
                return res
    sys.exit("Could not find %s in %s" % (property_name, build_gradle_file_name))

def get_build_tools_version_from_build_file():
    return grep_from_build_file('buildToolsVersion', r'buildToolsVersion\s+\'(\S+)\'')

def get_version_code_from_build_file():
    return grep_from_build_file('versionCode', r'versionCode\s+(\S+)')

def get_version_name_from_apk(apk_file):
    aapt = '%s/build-tools/%s/aapt' % (get_android_home(), get_build_tools_version_from_build_file())
    process = subprocess.check_output([aapt, 'dump', 'badging', apk_file])
    found = re.search(r'versionName=\'(\S+)\'', process)
    if found:
        apk_version_name = found.groups()[0]
        return apk_version_name
    else:
        sys.exit("Could not get version name from apk " + apk_file)

def copy_apk(flavor, version_name):
    folder_path = 'releases'
    sh.mkdir("-p", folder_path)
    output_file = '%s/wikipedia-%s.apk' % (folder_path, version_name)
    sh.cp(get_original_apk_file_name(flavor), output_file)
    print ' apk: %s' % output_file

def find_output_apk_for(label, version_code):
    folder_path = 'releases'
    file_pattern = '%s/wikipedia-%s.%s-%s-*.apk' % (folder_path, VERSION_START, version_code, label)
    apk_files = glob.glob(file_pattern)
    if len(apk_files) == 1:
        return apk_files[0]
    elif len(apk_files) == 0:
        sys.exit("Did not find apk files for %s" % file_pattern)
    else:
        sys.exit("Found too many(%d) files for %s" % (len(apk_files), file_pattern))

def main():
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--beta',
                       help='Step 1: Google Play Beta. git checkout BUMPTAG first!',
                       action='store_true')
    group.add_argument('--prod',
                       help='Step 1: Google Play stable.',
                       action='store_true')
    group.add_argument('--amazon',
                       help='Step 1: Amazon stable release.',
                       action='store_true')
    group.add_argument('--channel',
                       help='Step 1: Custom versionName&channel. OEMs w/ Play')
    group.add_argument('--app',
                       help='Step 1: Custom versionName&channel&applicationId '
                            '(aka. package name). OEMs wout/ Play.')
    parser.add_argument('--push', help='Step 2: create&push git tag to gerrit remote.',
                        action='store_true')
    args = parser.parse_args()
    custom_channel = 'ignore'
    custom_app = 'org.wikipedia'
    if args.beta:
        flavors = ['beta']
        targets = flavors
    elif args.prod:
        flavors = ['prod', 'releasesprod']
        targets = ['r']
    elif args.amazon:
        flavors = ['amazon']
        targets = flavors
    elif args.channel:
        flavors = ['custom']
        targets = [args.channel]
        custom_channel = args.channel
    elif args.app:
        flavors = ['custom']
        targets = [args.app]
        custom_channel = args.app
        custom_app = 'org.wikipedia.' + args.app
    else:
        print('Error. Please specify --beta, --prod, or --amazon')
        sys.exit(-1)

    if args.push:
        if custom_channel is 'ignore':
            label = targets[0]
        else:
            label = custom_channel
        apk_file = find_output_apk_for(label, get_version_code_from_build_file())
        version_name = get_version_name_from_apk(apk_file)
        for target in targets:
            git_tag(target, version_name)
            push_to_gerrit(target, version_name)
    else:
        make_release(flavors, custom_channel, custom_app)
        copy_artifacts(flavors[0])
        if flavors[0] == 'prod':
            copy_artifacts(flavors[1])
        print('Please test the APK. After that, run w/ --push flag, and release the tested APK.')
        print('A useful command for collecting the release notes:')
        print('git log --pretty=format:"%h | %cr | %s" --abbrev-commit --no-merges ' +
              '`git tag --list ' + targets[0] + '/* | tail -1`..')

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.Generic;
using System.Text;
using CoAP.Log;
using CoAP.Util;

namespace CoAP.EndPoint.Resources
{
    /// <summary>
    /// This class describes the functionality of a CoAP resource.
    /// </summary>
    public abstract class Resource : IComparable<Resource>
    {
        private static ILogger log = LogManager.GetLogger(typeof(Resource));

        private Int32 _totalSubResourceCount;
        private String _resourceIdentifier;
        private HashSet<LinkAttribute> _attributes;
        private Resource _parent;
        private SortedDictionary<String, Resource> _subResources;
        private Boolean _hidden;

        /// <summary>
        /// Initialize a resource.
        /// </summary>
        /// <param name="resourceIdentifier">The identifier of this resource</param>
        public Resource(String resourceIdentifier) : this(resourceIdentifier, false) { }

        /// <summary>
        /// Initialize a resource.
        /// </summary>
        /// <param name="resourceIdentifier">The identifier of this resource</param>
        /// <param name="hidden">True if this resource is hidden</param>
        public Resource(String resourceIdentifier, Boolean hidden)
        {
            this._resourceIdentifier = resourceIdentifier;
            this._hidden = hidden;
            this._attributes = new HashSet<LinkAttribute>();
        }

        /// <summary>
        /// Gets the URI of this resource.
        /// </summary>
        public String Path
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(Name);
                if (_parent == null)
                    sb.Append("/");
                else
                {
                    Resource res = _parent;
                    while (res != null)
                    {
                        sb.Insert(0, "/");
                        sb.Insert(0, res.Name);
                        res = res._parent;
                    }
                }
                return sb.ToString();
            }
        }

        public String Name
        {
            get { return _resourceIdentifier; }
            set { _resourceIdentifier = value; }
        }

        public ICollection<LinkAttribute> Attributes
        {
            get { return _attributes; }
        }

        public IList<LinkAttribute> GetAttributes(String name)
        {
            List<LinkAttribute> list = new List<LinkAttribute>();
            foreach (LinkAttribute attr in Attributes)
            {
                if (attr.Name.Equals(name))
                    list.Add(attr);
            }
            return list.AsReadOnly();
        }

        public Boolean SetAttribute(LinkAttribute attr)
        {
            // Adds depending on the Link Format rules
            return LinkFormat.AddAttribute(Attributes, attr);
        }

        public Boolean ClearAttribute(String name)
        {
            Boolean cleared = false;
            foreach (LinkAttribute attr in GetAttributes(name))
            {
                cleared |= _attributes.Remove(attr);
            }
            return cleared;
        }

        public Boolean Hidden
        {
            get { return _hidden; }
            set { _hidden = value; }
        }

        public IList<String> ResourceTypes
        {
            get
            {
                return GetStringValues(GetAttributes(LinkFormat.ResourceType));
            }
        }

        /// <summary>
        /// Gets or sets the type attribute of this resource.
        /// </summary>
        public String ResourceType
        {
            get
            {
                IList<LinkAttribute> attrs = GetAttributes(LinkFormat.ResourceType);
                return attrs.Count == 0 ? null : attrs[0].StringValue;
            }
            set
            {
                SetAttribute(new LinkAttribute(LinkFormat.ResourceType, value));
            }
        }

        /// <summary>
        /// Gets or sets the title attribute of this resource.
        /// </summary>
        public String Title
        {
            get
            {
                IList<LinkAttribute> attrs = GetAttributes(LinkFormat.Title);
                return attrs.Count == 0 ? null : attrs[0].StringValue;
            }
            set
            {
                ClearAttribute(LinkFormat.Title);
                SetAttribute(new LinkAttribute(LinkFormat.Title, value));
            }
        }

        public IList<String> InterfaceDescriptions
        {
            get
            {
                return GetStringValues(GetAttributes(LinkFormat.InterfaceDescription));
            }
        }

        /// <summary>
        /// Gets or sets the interface description attribute of this resource.
        /// </summary>
        public String InterfaceDescription
        {
            get
            {
                IList<LinkAttribute> attrs = GetAttributes(LinkFormat.InterfaceDescription);
                return attrs.Count == 0 ? null : attrs[0].StringValue;
            }
            set
            {
                SetAttribute(new LinkAttribute(LinkFormat.InterfaceDescription, value));
            }
        }

        public IList<Int32> GetContentTypeCodes
        {
            get
            {
                return GetIntValues(GetAttributes(LinkFormat.ContentType));
            }
        }

        /// <summary>
        /// Gets or sets the content type code attribute of this resource.
        /// </summary>
        public Int32 ContentTypeCode
        {
            get
            {
                IList<LinkAttribute> attrs = GetAttributes(LinkFormat.ContentType);
                return attrs.Count == 0 ? 0 : attrs[0].IntValue;
            }
            set
            {
                SetAttribute(new LinkAttribute(LinkFormat.ContentType, value));
            }
        }

        /// <summary>
        /// Gets or sets the maximum size estimate attribute of this resource.
        /// </summary>
        public Int32 MaximumSizeEstimate
        {
            get
            {
                IList<LinkAttribute> attrs = GetAttributes(LinkFormat.MaxSizeEstimate);
                return attrs.Count == 0 ? -1 : attrs[0].IntValue;
            }
            set
            {
                SetAttribute(new LinkAttribute(LinkFormat.MaxSizeEstimate, value));
            }
        }

        /// <summary>
        /// Gets or sets the observable attribute of this resource.
        /// </summary>
        public Boolean Observable
        {
            get
            {
                return GetAttributes(LinkFormat.Observable).Count > 0;
            }
            set
            {
                if (value)
                    SetAttribute(new LinkAttribute(LinkFormat.Observable, value));
                else
                    ClearAttribute(LinkFormat.Observable);
            }
        }

        /// <summary>
        /// Gets the total count of sub-resources, including children and children's children...
        /// </summary>
        public Int32 TotalSubResourceCount
        {
            get { return _totalSubResourceCount; }
        }

        /// <summary>
        /// Gets the count of sub-resources of this resource.
        /// </summary>
        public Int32 SubResourceCount
        {
            get { return null == _subResources ? 0 : _subResources.Count; }
        }

        /// <summary>
        /// Removes this resource from its parent.
        /// </summary>
        public void Remove()
        {
            if (_parent != null)
                _parent.RemoveSubResource(this);
        }

        /// <summary>
        /// Gets sub-resources of this resource.
        /// </summary>
        /// <returns></returns>
        public Resource[] GetSubResources()
        {
            if (null == _subResources)
                return new Resource[0];

            Resource[] resources = new Resource[_subResources.Count];
            this._subResources.Values.CopyTo(resources, 0);
            return resources;
        }

        public Resource GetResource(String path)
        {
            return GetResource(path, false);
        }

        public Resource GetResource(String path, Boolean last)
        {
            if (String.IsNullOrEmpty(path))
                return this;

            // find root for absolute path
            if (path.StartsWith("/"))
            {
                Resource root = this;
                while (root._parent != null)
                    root = root._parent;
                path = path.Equals("/") ? null : path.Substring(1);
                return root.GetResource(path);
            }

            Int32 pos = path.IndexOf('/');
            String head = null, tail = null;

            // note: "some/resource/" addresses a resource "" under "resource"
            if (pos == -1)
            {
                head = path;
            }
            else
            {
                head = path.Substring(0, pos);
                tail = path.Substring(pos + 1);
            }

            if (SubResources.ContainsKey(head))
                return SubResources[head].GetResource(tail, last);
            else if (last)
                return this;
            else
                return null;
        }

        private SortedDictionary<String, Resource> SubResources
        {
            get
            {
                if (_subResources == null)
                    _subResources = new SortedDictionary<String, Resource>();
                return _subResources;
            }
        }

        /// <summary>
        /// Adds a resource as a sub-resource of this resource.
        /// </summary>
        /// <param name="resource">The sub-resource to be added</param>
        public void AddSubResource(Resource resource)
        {
            if (null == resource)
                throw new ArgumentNullException("resource");

            // no absolute paths allowed, use root directly
            while (resource.Name.StartsWith("/"))
            {
                if (_parent != null)
                {
                    if (log.IsWarnEnabled)
                        log.Warn("Adding absolute path only allowed for root: made relative " + resource.Name);
                }
                resource.Name = resource.Name.Substring(1);
            }

            // get last existing resource along path
            Resource baseRes = GetResource(resource.Name, true);

            String path = this.Path;
            if (!path.EndsWith("/"))
                path += "/";
            path += resource.Name;

            path = path.Substring(baseRes.Path.Length);
            if (path.StartsWith("/"))
                path = path.Substring(1);

            if (path.Length == 0)
            {
                // resource replaces base
                if (log.IsInfoEnabled)
                    log.Info("Replacing resource " + baseRes.Path);
                foreach (Resource sub in baseRes.GetSubResources())
                {
                    sub._parent = resource;
                    resource.SubResources[sub.Name] = sub;
                }
                resource._parent = baseRes._parent;
                baseRes._parent.SubResources[baseRes.Name] = resource;
            }
            else
            {
                // resource is added to base

                String[] segments = path.Split('/');
                if (segments.Length > 1)
                {
                    if (log.IsDebugEnabled)
                        log.Debug("Splitting up compound resource " + resource.Name);
                    resource.Name = segments[segments.Length - 1];

                    // insert middle segments
                    Resource sub = null;
                    for (Int32 i = 0; i < segments.Length - 1; i++)
                    {
                        sub = baseRes.CreateInstance(segments[i]);
                        sub.Hidden = true;
                        baseRes.AddSubResource(sub);
                        baseRes = sub;
                    }
                }
                else
                    resource.Name = path;

                resource._parent = baseRes;
                baseRes.SubResources[resource.Name] = resource;

                if (log.IsDebugEnabled)
                    log.Debug("Add resource " + resource.Name);
            }

            // update number of sub-resources in the tree
            Resource p = resource._parent;
            while (p != null)
            {
                p._totalSubResourceCount++;
                p = p._parent;
            }
        }

        /// <summary>
        /// Removes a sub-resource from this resource by its identifier.
        /// </summary>
        /// <param name="resourcePath">the path of the sub-resource to remove</param>
        public void RemoveSubResource(String resourcePath)
        {
            RemoveSubResource(GetResource(resourcePath));
        }

        /// <summary>
        /// Removes a sub-resource from this resource.
        /// </summary>
        /// <param name="resource">the sub-resource to remove</param>
        public void RemoveSubResource(Resource resource)
        {
            if (null == resource)
                return;

            if (SubResources.Remove(resource._resourceIdentifier))
            {
                Resource p = resource._parent;
                while (p != null)
                {
                    p._totalSubResourceCount--;
                    p = p._parent;
                }

                resource._parent = null;
            }
        }

        public void CreateSubResource(Request request, String newIdentifier)
        {
            DoCreateSubResource(request, newIdentifier);
        }

        public Int32 CompareTo(Resource other)
        {
            return Path.CompareTo(other.Path);
        }

        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();
            Print(sb, 0);
            return sb.ToString();
        }

        private void Print(StringBuilder sb, Int32 indent)
        {
            for (Int32 i = 0; i < indent; i++)
                sb.Append(" ");
            sb.AppendFormat("+[{0}]",_resourceIdentifier);

            String title = Title;
            if (title != null)
                sb.AppendFormat(" {0}", title);
            sb.AppendLine();

            foreach (LinkAttribute attr in Attributes)
            {
                if (attr.Name.Equals(LinkFormat.Title))
                    continue;
                for (Int32 i = 0; i < indent + 3; i++)
                    sb.Append(" ");
                sb.AppendFormat("- ");
                attr.Serialize(sb);
                sb.AppendLine();
            }

            if (_subResources != null)
                foreach (Resource sub in _subResources.Values)
                {
                    sub.Print(sb, indent + 2);
                }
        }

        /// <summary>
        /// Creates a resouce instance with proper subtype.
        /// </summary>
        /// <returns></returns>
        protected abstract Resource CreateInstance(String name);
        protected abstract void DoCreateSubResource(Request request, String newIdentifier);

        private static IList<String> GetStringValues(IEnumerable<LinkAttribute> attributes)
        {
            List<String> list = new List<String>();
            foreach (LinkAttribute attr in attributes)
            {
                list.Add(attr.StringValue);
            }
            return list;
        }

        private static IList<Int32> GetIntValues(IEnumerable<LinkAttribute> attributes)
        {
            List<Int32> list = new List<Int32>();
            foreach (LinkAttribute attr in attributes)
            {
                list.Add(attr.IntValue);
            }
            return list;
        }
    }
}


text:
package org.apache.camel.spi;

import org.apache.camel.CamelContext;
import org.apache.camel.Component;

/**
 * Represents a resolver of components from a URI to be able to auto-load them using some discovery mechanism like
 * {@link org.apache.camel.impl.DefaultComponentResolver}
 */
public interface ComponentResolver {

    /**
     * Attempts to resolve the component for the given URI
     *
     * @param  name      the component name to resolve
     * @param  context   the context to load the component if it can be resolved
     * @return           the component which is added to the context or null if it cannot be resolved
     * @throws Exception is thrown if the component could not be loaded
     */
    Component resolveComponent(String name, CamelContext context) throws Exception;
}


text:
package com.gemstone.gemfire.internal.tools.gfsh.app.aggregator.functions.util;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.execute.FunctionContext;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.internal.GemFireVersion;
import com.gemstone.gemfire.internal.cache.BucketRegion;
import com.gemstone.gemfire.internal.cache.ForceReattemptException;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.tools.gfsh.aggregator.AggregateFunction;
import com.gemstone.gemfire.internal.tools.gfsh.aggregator.AggregateResults;
import com.gemstone.gemfire.internal.tools.gfsh.app.cache.data.MapMessage;

public class LocalRegionInfoFunction implements AggregateFunction, DataSerializable
{
	private static final long serialVersionUID = 1L;

	private String regionPath;

	private static boolean priorTo6011 = true;

	static {
		priorTo6011 = isPriorTo6011();
	}

	static boolean isPriorTo6011()
	{
		String gemfireVersion = GemFireVersion.getGemFireVersion();
		String split[] = gemfireVersion.split("\\.");
		int major = 0;
		int minor = 0;
		int update = 0;
		int update2 = 0;
		for (int i = 0; i < split.length; i++) {
			switch (i) {
			case 0:
				major = Integer.parseInt(split[i]);
				break;
			case 1:
				try {
					minor = Integer.parseInt(split[i]);
				} catch (NumberFormatException ex) {
					minor = Integer.parseInt(split[i].substring(0, 1));
				}
				break;
			case 2:
        try {
          update = Integer.parseInt(split[i]);
        } catch (NumberFormatException ex) {
          // non-number. ignore
        }
				break;
			case 3:
        try {
          update2 = Integer.parseInt(split[i]);
        } catch (NumberFormatException ex) {
          // non-number. ignore.
        }
				break;
			}
		}

		if (major < 6) {
			return true; // 7
		} else if (minor > 0) {
			return false; // 6.1
		} else if (update < 1) {
			return true; // 6.0.0
		} else if (update > 1) {
			return false; // 6.0.2
		} else if (update2 <= 0) {
			return true; // 6.0.1.0
		} else {
			return false; // 6.0.1.1
		}

	}

	public LocalRegionInfoFunction()
	{
	}

	public LocalRegionInfoFunction(String regionPath)
	{
		this.regionPath = regionPath;
	}

	public String getRegionPath()
	{
		return regionPath;
	}

	public void setRegionPath(String regionPath)
	{
		this.regionPath = regionPath;
	}

	public AggregateResults run(FunctionContext context)
	{
		AggregateResults results = new AggregateResults();
		Cache cache = CacheFactory.getAnyInstance();
		DistributedSystem ds = cache.getDistributedSystem();
		DistributedMember member = ds.getDistributedMember();

		Region region = cache.getRegion(regionPath);
		if (region == null) {
			results.setCode(AggregateResults.CODE_ERROR);
			results.setCodeMessage("Undefined region: " + regionPath);
			return results;
		}

		MapMessage message = new MapMessage();
		message.put("MemberId", member.getId());
		message.put("MemberName", ds.getName());
		message.put("Host", member.getHost());
		// message.put("IpAddress",
		// dataSet.getNode().getMemberId().getIpAddress().getHostAddress());
		// message.put("Port", parent.getNode().getMemberId().getPort());
		message.put("Pid", member.getProcessId());
		message.put("RegionPath", regionPath);

		boolean isPR = region instanceof PartitionedRegion;
		message.put("IsPR", isPR);
		if (isPR) {
			PartitionedRegion pr = (PartitionedRegion) region;
			SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy h:mm:ss.SSS a");
			message.put("LastAccessedTime", format.format(new Date(pr.getLastAccessedTime())));
			message.put("LastModifiedTime", format.format(new Date(pr.getLastModifiedTime())));

			// total local primary bucket size
			int totalRegionSize = 0;
			// if (priorTo6011) { // 5.7 - 6.0.1
			// The following call is not returning the primary bucket regions.
			// totalRegionSize = PartitionRegionHelper.getLocalData(pr).size();

			// getDataStore() is null if peer client
			if (pr.getDataStore() == null) {
				message.put("IsPeerClient", true);
			} else {
				List<Integer> bucketIdList = pr.getDataStore().getLocalPrimaryBucketsListTestOnly();
				for (Integer bucketId : bucketIdList) {
					BucketRegion bucketRegion;
					try {
						bucketRegion = pr.getDataStore().getInitializedBucketForId(null, bucketId);
						totalRegionSize += bucketRegion.size();
					} catch (ForceReattemptException e) {
						// ignore
					}
				}
				message.put("IsPeerClient", false);
			}

			// } else {
			// // The following call is not returning the primary bucket
			// regions.
			// // totalRegionSize =
			// PartitionRegionHelper.getLocalData(pr).size();
			//
			// Region localRegion = new LocalDataSet(pr,
			// pr.getDataStore().getAllLocalPrimaryBucketIds());
			// totalRegionSize = localRegion.size();
			// }
			message.put("RegionSize", totalRegionSize);

		} else {
			message.put("IsPeerClient", false);
			message.put("RegionSize", region.size());
			message.put("Scope", region.getAttributes().getScope().toString());
		}
		message.put("DataPolicy", region.getAttributes().getDataPolicy().toString());

		// info.evictionPolicy =
		// region.getAttributes().getEvictionAttributes().getAlgorithm();

		results.setDataObject(message);
		return results;
	}

	/**
	 * Returns a java.util.List of LocalRegionInfo objects;
	 */
	public Object aggregate(List list)
	{
		ArrayList resultList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			AggregateResults results = (AggregateResults) list.get(i);
			if (results.getCode() == AggregateResults.CODE_ERROR) {
				// MapMessage info = new MapMessage();
				// info.put("Code", results.getCode());
				// info.put("CodeMessage", results.getCodeMessage());
				// info.put("RegionPath", regionPath);
				// resultList.add(info);
				// break;
				// ignore - occurs only if undefined region
				continue;
			}
			if (results.getDataObject() != null) {
				resultList.add(results.getDataObject());
			}
		}
		return resultList;
	}

	public Object aggregateDistributedSystems(Object[] results)
	{
		ArrayList list = new ArrayList();
		for (int i = 0; i < results.length; i++) {
			list.add(results[i]);
		}
		return list;
	}

	public void fromData(DataInput input) throws IOException, ClassNotFoundException
	{
		regionPath = DataSerializer.readString(input);
	}

	public void toData(DataOutput output) throws IOException
	{
		DataSerializer.writeString(regionPath, output);
	}
}


text:
using System;
using System.Drawing;
using System.Text;
using Encog.ML.Data.Basic;
using Encog.Util.DownSample;

namespace Encog.ML.Data.Image
{
    /// <summary>
    /// An extension of the BasicMLData class that is designed to hold images for
    /// input into a neural network. This class should only be used with the
    /// ImageNeuralDataSet collection.
    ///
    /// This class provides the ability to associate images with the elements of a
    /// dataset. These images will be downsampled to the resolution specified in the
    /// ImageNeuralData set class that they are added to.
    /// </summary>
    public class ImageMLData : BasicMLData
    {
        /// <summary>
        /// Construct an object based on an image.
        /// </summary>
        /// <param name="image">The image to use.</param>
        public ImageMLData(Bitmap image)
            : base(1)
        {
            Image = image;
        }

        /// <summary>
        /// The image associated with this class.
        /// </summary>
        public Bitmap Image { get; set; }

        /// <summary>
        /// Downsample, and copy, the image contents into the data of this object.
        /// Calling this method has no effect on the image, as the same image can be
        /// downsampled multiple times to different resolutions.
        /// </summary>
        /// <param name="downsampler">The downsampler object to use.</param>
        /// <param name="findBounds">Should the bounds be located and cropped.</param>
        /// <param name="height">The height to downsample to.</param>
        /// <param name="width">The width to downsample to.</param>
        /// <param name="hi">The high value to normalize to.</param>
        /// <param name="lo">The low value to normalize to.</param>
        public void Downsample(IDownSample downsampler,
                               bool findBounds, int height, int width,
                               double hi, double lo)
        {
            if (findBounds)
            {
                downsampler.FindBounds();
            }
            double[] sample = downsampler.DownSample(Image, height,
                                                     width);

            for (int i = 0; i < sample.Length; i++)
            {
                sample[i] = ((sample[i] - 0)
                             /(255 - 0))
                            *(hi - lo) + lo;
            }

            _data = sample;
        }

        /// <summary>
        /// Return a string representation of this object.
        /// </summary>
        /// <returns>The string form of this object.</returns>
        public override String ToString()
        {
            var builder = new StringBuilder("[ImageNeuralData:");
            for (int i = 0; i < Data.Length; i++)
            {
                if (i != 0)
                {
                    builder.Append(',');
                }
                builder.Append(Data[i]);
            }
            builder.Append("]");
            return builder.ToString();
        }
    }
}


text:
package org.webinos.impl.nfc;

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

import org.meshpoint.anode.AndroidContext;
import org.meshpoint.anode.module.IModule;
import org.meshpoint.anode.module.IModuleContext;
import org.webinos.api.DeviceAPIError;
import org.webinos.api.nfc.NdefRecord;
import org.webinos.api.nfc.NfcEventListener;
import org.webinos.api.nfc.NfcModule;
import org.webinos.api.nfc.NfcTag;
import org.webinos.api.nfc.NfcTagTechnology;
import org.webinos.api.nfc.NfcTagTechnologyNdef;
import org.webinos.impl.nfc.NfcManager.NfcDiscoveryListener;

import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.util.Log;

public class NfcAnodeModule extends NfcModule implements IModule, NfcDiscoveryListener {

  private static String TAG = NfcAnodeModule.class.getName();

  private IModuleContext moduleContext;
  private Context androidContext;

  private NfcAdapter mNfcAdapter;

  protected NfcManager nfcMgr;
  protected NfcEventListener mNfcEventListener;

  @Override
  public Object startModule(IModuleContext ctx) {
    Log.v(TAG, "startModule");
    this.moduleContext = ctx;
    this.androidContext = ((AndroidContext) ctx).getAndroidContext();

    mNfcAdapter = NfcAdapter.getDefaultAdapter(androidContext);

    nfcMgr = NfcManager.getInstance(androidContext);

    return this;
  }

  @Override
  public void stopModule() {
    Log.v(TAG, "stopModule");
  }

  @Override
  public void setListener(NfcEventListener listener) {
    mNfcEventListener = listener;
    if (mNfcEventListener != null) {
      nfcMgr.addListener(this);
    } else {
      nfcMgr.removeListener(this);
    }
  }

  @Override
  public void addTextTypeFilter() {
    checkNfcAvailability();
    nfcMgr.addTextTypeFilter();
  }

  @Override
  public void addUriTypeFilter(String scheme) {
    checkNfcAvailability();
    nfcMgr.addUriTypeFilter(scheme);
  }

  @Override
  public void addMimeTypeFilter(String mimeType) {
    checkNfcAvailability();
    nfcMgr.addMimeTypeFilter(mimeType);
  }

  @Override
  public void removeTextTypeFilter() {
    checkNfcAvailability();
    nfcMgr.removeTextTypeFilter();
  }

  @Override
  public void removeUriTypeFilter(String scheme) {
    checkNfcAvailability();
    nfcMgr.removeUriTypeFilter(scheme);
  }

  @Override
  public void removeMimeTypeFilter(String mimeType) {
    checkNfcAvailability();
    nfcMgr.addMimeTypeFilter(mimeType);
  }

  private void checkNfcAvailability() {
    if (!isNfcAvailable()) {
      throw new NfcError(DeviceAPIError.NOT_SUPPORTED_ERR,
          "NFC is not supported on this device");
    }
  }

  @Override
  public void shareTag(NdefRecord[] ndefMessage) {
    checkNfcPushAvailability();
    setSharedTag(ndefMessage);
  }

  @Override
  public void unshareTag() {
    checkNfcPushAvailability();
    setSharedTag(null);
  }

  private void checkNfcPushAvailability() {
    if (!isNfcAvailable()) {
      throw new NfcError(DeviceAPIError.NOT_SUPPORTED_ERR,
          "NFC push is not supported on this device");
    }
  }

  @Override
  public boolean isNfcAvailable() {
    return (mNfcAdapter != null && mNfcAdapter.isEnabled());
  }

  @Override
  public boolean isNfcPushAvailable() {
    return isNfcAvailable();
  }

  @Override
  public void onTagDiscovered(Object tag) {
    if (tag instanceof Tag) {
      Tag androidTag = (Tag) tag;
      NfcTag event = new NfcTag();
      event.tagId = androidTag.getId();
      List<NfcTagTechnology> techList = new ArrayList<NfcTagTechnology>();
      for (String tech : androidTag.getTechList()) {
        if (tech.equals(Ndef.class.getName())) {
          android.nfc.tech.Ndef ndefTech = android.nfc.tech.Ndef
              .get(androidTag);
          techList.add(new NfcTagTechnologyNdefImpl(this.env, ndefTech));
        }
      }
      // event.techList = new NfcTagTechnology[techList.size()];
      // techList.toArray(event.techList);
      if (techList.size() > 0) {
        event.tech = (NfcTagTechnologyNdef) techList.get(0);
      }
      if (mNfcEventListener != null) {
        mNfcEventListener.handleEvent(event);
      }
    }
  }

  private void setSharedTag(NdefRecord[] ndefMessage) {
    nfcMgr
        .setSharedTag(NfcTagTechnologyNdefImpl.createNdefMessage(ndefMessage));
  }

  @Override
  public void launchScanningActivity(boolean autoDismiss) {
    nfcMgr.launchScanningActivity(autoDismiss);
  }
}


text:
package org.hbird.application.groundstations.exceptions;

public class InvalidGroundstationKml extends Exception {

	public InvalidGroundstationKml() {
	}

	public InvalidGroundstationKml(String message) {
		super(message);
	}

}


text:
package com.opengamma.analytics.math.interpolation;

import org.apache.commons.lang.Validate;

import com.opengamma.analytics.math.function.PiecewisePolynomialWithSensitivityFunction1D;
import com.opengamma.analytics.math.interpolation.data.ArrayInterpolator1DDataBundle;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundle;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DLogPiecewisePoynomialDataBundle;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.util.ArgumentChecker;

/**
 * Find a interpolant F(x) = exp( f(x) ) where f(x) is a Natural cubic spline with Monotonicity cubic fileter.
 *
 * The natural cubic spline is determined by {@link LogNaturalSplineHelper}, where the tridiagonal algorithm is used to solve a linear system. Since
 * {@link PiecewisePolynomialResultsWithSensitivity} in {@link Interpolator1DLogPiecewisePoynomialDataBundle} contains information on f(x) (NOT F(x)),
 * computation done by {@link PiecewisePolynomialWithSensitivityFunction1D} MUST be exponentiated.
 */
public class LogNaturalCubicMonotonicityPreservingInterpolator1D extends PiecewisePolynomialInterpolator1D {

  /** Serialization version */
  private static final long serialVersionUID = 1L;

  private static final PiecewisePolynomialWithSensitivityFunction1D FUNC = new PiecewisePolynomialWithSensitivityFunction1D();

  /**
   *
   */
  public LogNaturalCubicMonotonicityPreservingInterpolator1D() {
    super(new MonotonicityPreservingCubicSplineInterpolator(new LogNaturalSplineHelper()));
  }

  @Override
  public Double interpolate(final Interpolator1DDataBundle data, final Double value) {
    Validate.notNull(value, "value");
    Validate.notNull(data, "data bundle");
    Validate.isTrue(data instanceof Interpolator1DLogPiecewisePoynomialDataBundle);
    final Interpolator1DLogPiecewisePoynomialDataBundle polyData = (Interpolator1DLogPiecewisePoynomialDataBundle) data;
    final DoubleMatrix1D res = FUNC.evaluate(polyData.getPiecewisePolynomialResultsWithSensitivity(), value);
    return Math.exp(res.getEntry(0));
  }

  @Override
  public double firstDerivative(final Interpolator1DDataBundle data, final Double value) {
    Validate.notNull(value, "value");
    Validate.notNull(data, "data bundle");
    Validate.isTrue(data instanceof Interpolator1DLogPiecewisePoynomialDataBundle);
    final Interpolator1DLogPiecewisePoynomialDataBundle polyData = (Interpolator1DLogPiecewisePoynomialDataBundle) data;
    final DoubleMatrix1D resValue = FUNC.evaluate(polyData.getPiecewisePolynomialResultsWithSensitivity(), value);
    final DoubleMatrix1D resDerivative = FUNC.differentiate(polyData.getPiecewisePolynomialResultsWithSensitivity(), value);
    return Math.exp(resValue.getEntry(0)) * resDerivative.getEntry(0);
  }

  @Override
  public double[] getNodeSensitivitiesForValue(final Interpolator1DDataBundle data, final Double value) {
    Validate.notNull(value, "value");
    Validate.notNull(data, "data bundle");
    Validate.isTrue(data instanceof Interpolator1DLogPiecewisePoynomialDataBundle);
    final Interpolator1DLogPiecewisePoynomialDataBundle polyData = (Interpolator1DLogPiecewisePoynomialDataBundle) data;
    final double[] resSense = FUNC.nodeSensitivity(polyData.getPiecewisePolynomialResultsWithSensitivity(), value).getData();
    final double resValue = Math.exp(FUNC.evaluate(polyData.getPiecewisePolynomialResultsWithSensitivity(), value).getEntry(0));
    final double[] knotValues = data.getValues();
    final int nKnots = knotValues.length;
    final double[] res = new double[nKnots];
    for (int i = 0; i < nKnots; ++i) {
      res[i] = resSense[i] * resValue / knotValues[i];
    }
    return res;
  }

  @Override
  public Interpolator1DDataBundle getDataBundle(final double[] x, final double[] y) {
    Validate.notNull(y, "y");
    final int nData = y.length;
    final double[] logY = new double[nData];
    for (int i = 0; i < nData; ++i) {
      ArgumentChecker.isTrue(y[i] > 0., "y should be positive");
      logY[i] = Math.log(y[i]);
    }
    return new Interpolator1DLogPiecewisePoynomialDataBundle(new ArrayInterpolator1DDataBundle(x, logY, false),
        new MonotonicityPreservingCubicSplineInterpolator(new LogNaturalSplineHelper()));
  }

  @Override
  public Interpolator1DDataBundle getDataBundleFromSortedArrays(final double[] x, final double[] y) {
    Validate.notNull(y, "y");
    final int nData = y.length;
    final double[] logY = new double[nData];
    for (int i = 0; i < nData; ++i) {
      ArgumentChecker.isTrue(y[i] > 0., "y should be positive");
      logY[i] = Math.log(y[i]);
    }
    return new Interpolator1DLogPiecewisePoynomialDataBundle(new ArrayInterpolator1DDataBundle(x, logY, true),
        new MonotonicityPreservingCubicSplineInterpolator(new LogNaturalSplineHelper()));
  }
}


text:
window.console = window.console || {};
window.console.log = window.console.log || function () {
};
window.console.debug = window.console.debug || function () {
};
window.console.info = window.console.info || function () {
};
window.console.warn = window.console.warn || function () {
};
window.console.error = window.console.error || function () {
};

(function () {
  var modName, testName;

  //arg: { name }
  QUnit.testStart = function (t) {
    modName = t.module;
    testName = t.name;
  };

  //arg: { name, failed, passed, total }
  QUnit.testDone = function (t) {
    if (t.failed)
      console.log('Test "' + t.module + ': ' + t.name + '" completed: ' + (0 === t.failed ? 'pass' : 'FAIL') + '\n')
  };

  //{ result, actual, expected, message }
  QUnit.log = function (t) {
    if (!t.result)
      console.log('Test "' + modName + ': ' + testName + '" assertion failed. Expected <' + t.expected + '> Actual <' + t.actual + '>' + (t.message ? ': \'' + t.message + '\'' : ''));
  };
}());