text:
require 'net/http'
require 'uri'

  # Get your API Key here: https://www.serpwoo.com/q/api/ (should be logged in)
  API_key	= "API_KEY_HERE"

    def open(url)
      Net::HTTP.get(URI.parse(url))
    end

  page_content = open("https://api.serpwoo.com/v1/projects/?key=#{API_key}")

  #Print Result
  puts page_content

redpajama_set_name: RedPajamaGithub


text:
class LeTitle < ActiveRecord::Base
  validates_length_of :name, :within => 0..20
  validates_uniqueness_of :name, :message => :already_exists

  validates_length_of :description, :maximum => 80

  #-----------------------------------------------------------------------------
  # Base methods:
  #-----------------------------------------------------------------------------
  #++

  # Computes a shorter description for the name associated with this data
  def get_full_name
    self.name.to_s
  end

  # Computes a verbose or formal description for the name associated with this data
  def get_verbose_name
    [
      (name.empty? ? nil : name),
      (description.empty? ? nil : description)
    ].compact.join(": ")
  end
  #-----------------------------------------------------------------------------
  #++
end


text:
layout: post
title: "Daily Digest #59"
type: digest
tags:
    - daily
    - development
description: ""
publish: true
---

- [6 creative ways to solve problems with Linux containers and Docker](https://www.oreilly.com/ideas/6-creative-ways-to-solve-problems-with-linux-containers-and-docker?utm_source=jakartadev.org)
- [I Love Anti Pattern](https://dev.to/levimoreira/i-love-anti-patterns-1bj1)
- [Running distributed Erlang & Elixir applications on Docker](https://hackernoon.com/running-distributed-erlang-elixir-applications-on-docker-b211d95affbe)
- [Analysing 1.4 billion rows with python](https://hackernoon.com/analysing-1-4-billion-rows-with-python-6cec86ca9d73)
- [AWS Command line: S3 content from stdin or to stdout](https://loige.co/aws-command-line-s3-content-from-stdin-or-to-stdout/)
- [Erlang Runtime System](https://happi.github.io/theBeamBook/)


text:
package org.mrgeo.resources.mrspyramid;

import org.mrgeo.services.mrspyramid.MrsPyramidService;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;

@Path("/metadata")
public class MetadataResource
{
    @Context
    MrsPyramidService service;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{output: .*+}")
    public Response getMetadata(@PathParam("output") final String imgName)
    {
        try
        {
            return Response.status(Status.OK).entity( service.getMetadata(imgName) ).build();
        }
        catch (final IOException e)
        {
            final String error = e.getMessage() != null ? e.getMessage() : "";
            return Response.serverError().entity(error).build();
        }
    }
}


text:
require 'cucumber/formatter/console'
require 'fileutils'

module Cucumber
  module Formatter
    # The formatter used for <tt>--format pretty</tt> (the default formatter).
    #
    # This formatter prints features to plain text - exactly how they were parsed,
    # just prettier. That means with proper indentation and alignment of table columns.
    #
    # If the output is STDOUT (and not a file), there are bright colours to watch too.
    #
    class Pretty < Ast::Visitor
      include FileUtils
      include Console
      attr_writer :indent

      def initialize(step_mother, io, options)
        super(step_mother)
        @io = io
        @options = options
        @exceptions = []
        @indent = 0
        @prefixes = options[:prefixes] || {}
      end

      def visit_features(features)
        super
        print_summary(features) unless @options[:autoformat]
      end

      def visit_feature(feature)
        @exceptions = []
        @indent = 0
        if @options[:autoformat]
          file = File.join(@options[:autoformat], feature.file)
          dir = File.dirname(file)
          mkdir_p(dir) unless File.directory?(dir)
          File.open(file, Cucumber.file_mode('w')) do |io|
            @io = io
            super
          end
        else
          super
        end
      end

      def visit_comment(comment)
        comment.accept(self)
      end

      def visit_comment_line(comment_line)
        @io.puts(comment_line.indent(@indent))
        @io.flush
      end

      def visit_tags(tags)
        tags.accept(self)
        if @indent == 1
          @io.puts
          @io.flush
        end
      end

      def visit_tag_name(tag_name)
        tag = format_string("@#{tag_name}", :tag).indent(@indent)
        @io.print(tag)
        @io.flush
        @indent = 1
      end

      def visit_feature_name(name)
        @io.puts(name)
        @io.puts
        @io.flush
      end

      def visit_feature_element(feature_element)
        record_tag_occurrences(feature_element, @options)
        @indent = 2
        @scenario_indent = 2
        super
        @io.puts
        @io.flush
      end

      def visit_background(background)
        @indent = 2
        @scenario_indent = 2
        @in_background = true
        super
        @in_background = nil
        @io.puts
        @io.flush
      end

      def visit_background_name(keyword, name, file_colon_line, source_indent)
        visit_feature_element_name(keyword, name, file_colon_line, source_indent)
      end

      def visit_examples_array(examples_array)
        @indent = 4
        @io.puts
        examples_array[0..-2].each { |ea| super(ea) }
        @last_example = true
        super(examples_array.last)
        @last_example = nil
      end

      def visit_examples_name(keyword, name)
        names = name.strip.empty? ? [name.strip] : name.split("\n")
        @io.puts("    #{keyword} #{names[0]}")
        names[1..-1].each {|s| @io.puts "      #{s}" } unless names.empty?
        @io.flush
        @indent = 6
        @scenario_indent = 6
      end

      def visit_outline_table(outline_table)
        super
        @indent = 4
        @io.puts unless @last_example
      end

      def visit_scenario_name(keyword, name, file_colon_line, source_indent)
        visit_feature_element_name(keyword, name, file_colon_line, source_indent)
      end

      def visit_feature_element_name(keyword, name, file_colon_line, source_indent)
        @io.puts if @scenario_indent == 6
        names = name.empty? ? [name] : name.split("\n")
        line = "#{keyword} #{names[0]}".indent(@scenario_indent)
        @io.print(line)
        if @options[:source]
          line_comment = " # #{file_colon_line}".indent(source_indent)
          @io.print(format_string(line_comment, :comment))
        end
        @io.puts
        names[1..-1].each {|s| @io.puts "    #{s}"}
        @io.flush
      end

      def visit_step(step)
        @indent = 6
        super
      end

      def visit_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background)
        if exception
          return if @exceptions.index(exception)
          @exceptions << exception
        end
        return if status != :failed && @in_background ^ background
        @status = status
        super
      end

      def visit_step_name(keyword, step_match, status, source_indent, background)
        source_indent = nil unless @options[:source]
        formatted_step_name = format_step(keyword, step_match, status, source_indent)
        @io.puts(formatted_step_name.indent(@scenario_indent + 2))
      end

      def visit_multiline_arg(multiline_arg)
        return if @options[:no_multiline]
        @table = multiline_arg
        super
      end

      def visit_exception(exception, status)
        print_exception(exception, status, @indent)
        @io.flush
      end

      def visit_table_row(table_row)
        @col_index = 0
        @io.print '  |'.indent(@indent-2)
        super
        @io.puts
        if table_row.exception && !@exceptions.index(table_row.exception)
          print_exception(table_row.exception, :failed, @indent)
        end
      end

      def visit_py_string(string)
        s = %{"""\n#{string}\n"""}.indent(@indent)
        s = s.split("\n").map{|l| l =~ /^\s+$/ ? '' : l}.join("\n")
        @io.puts(format_string(s, @status))
        @io.flush
      end

      def visit_table_cell(cell)
        super
        @col_index += 1
      end

      def visit_table_cell_value(value, status)
        status ||= @status || :passed
        width = @table.col_width(@col_index)
        cell_text = value.to_s || ''
        padded = cell_text + (' ' * (width - cell_text.jlength))
        prefix = cell_prefix(status)
        @io.print(' ' + format_string("#{prefix}#{padded}", status) + ::Term::ANSIColor.reset(" |"))
        @io.flush
      end

      private

      def cell_prefix(status)
        @prefixes[status]
      end

      def print_summary(features)
        print_stats(features)
        print_snippets(@options)
        print_passing_wip(@options)
        print_tag_limit_warnings(@options)
      end

    end
  end
end


text:
package network

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"github.com/Azure/go-autorest/tracing"
	"net/http"
)

// ExpressRoutePortsLocationsClient is the network Client
type ExpressRoutePortsLocationsClient struct {
	BaseClient
}

// NewExpressRoutePortsLocationsClient creates an instance of the ExpressRoutePortsLocationsClient client.
func NewExpressRoutePortsLocationsClient(subscriptionID string) ExpressRoutePortsLocationsClient {
	return NewExpressRoutePortsLocationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewExpressRoutePortsLocationsClientWithBaseURI creates an instance of the ExpressRoutePortsLocationsClient client.
func NewExpressRoutePortsLocationsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortsLocationsClient {
	return ExpressRoutePortsLocationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// Get retrieves a single ExpressRoutePort peering location, including the list of available bandwidths available at
// said peering location.
// Parameters:
// locationName - name of the requested ExpressRoutePort peering location.
func (client ExpressRoutePortsLocationsClient) Get(ctx context.Context, locationName string) (result ExpressRoutePortsLocation, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.Get")
		defer func() {
			sc := -1
			if result.Response.Response != nil {
				sc = result.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	req, err := client.GetPreparer(ctx, locationName)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", nil, "Failure preparing request")
		return
	}

	resp, err := client.GetSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", resp, "Failure sending request")
		return
	}

	result, err = client.GetResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "Get", resp, "Failure responding to request")
	}

	return
}

// GetPreparer prepares the Get request.
func (client ExpressRoutePortsLocationsClient) GetPreparer(ctx context.Context, locationName string) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"locationName":   autorest.Encode("path", locationName),
		"subscriptionId": autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2018-08-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsLocationsClient) GetSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
	return autorest.SendWithSender(client, req, sd...)
}

// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsLocationsClient) GetResponder(resp *http.Response) (result ExpressRoutePortsLocation, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// List retrieves all ExpressRoutePort peering locations. Does not return available bandwidths for each location.
// Available bandwidths can only be obtained when retrieving a specific peering location.
func (client ExpressRoutePortsLocationsClient) List(ctx context.Context) (result ExpressRoutePortsLocationListResultPage, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.List")
		defer func() {
			sc := -1
			if result.erpllr.Response.Response != nil {
				sc = result.erpllr.Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.fn = client.listNextResults
	req, err := client.ListPreparer(ctx)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", nil, "Failure preparing request")
		return
	}

	resp, err := client.ListSender(req)
	if err != nil {
		result.erpllr.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", resp, "Failure sending request")
		return
	}

	result.erpllr, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "List", resp, "Failure responding to request")
	}

	return
}

// ListPreparer prepares the List request.
func (client ExpressRoutePortsLocationsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"subscriptionId": autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2018-08-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations", pathParameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsLocationsClient) ListSender(req *http.Request) (*http.Response, error) {
	sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client))
	return autorest.SendWithSender(client, req, sd...)
}

// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsLocationsClient) ListResponder(resp *http.Response) (result ExpressRoutePortsLocationListResult, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}

// listNextResults retrieves the next set of results, if any.
func (client ExpressRoutePortsLocationsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortsLocationListResult) (result ExpressRoutePortsLocationListResult, err error) {
	req, err := lastResults.expressRoutePortsLocationListResultPreparer(ctx)
	if err != nil {
		return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", nil, "Failure preparing next results request")
	}
	if req == nil {
		return
	}
	resp, err := client.ListSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", resp, "Failure sending next results request")
	}
	result, err = client.ListResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsLocationsClient", "listNextResults", resp, "Failure responding to next results request")
	}
	return
}

// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExpressRoutePortsLocationsClient) ListComplete(ctx context.Context) (result ExpressRoutePortsLocationListResultIterator, err error) {
	if tracing.IsEnabled() {
		ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsLocationsClient.List")
		defer func() {
			sc := -1
			if result.Response().Response.Response != nil {
				sc = result.page.Response().Response.Response.StatusCode
			}
			tracing.EndSpan(ctx, sc, err)
		}()
	}
	result.page, err = client.List(ctx)
	return
}


text:
/*------------------------------------------------------------------------------
  @group Textmate Chrome
------------------------------------------------------------------------------*/

.github #tm_webpreview_header{
  color:#eee;
  background:#333;
  border-bottom:2px solid #ccc;
}

.github #tm_webpreview_header #gradient{
  display:none;
}

.github #tm_webpreview_header p{
  margin:0 0 15px 0 !important;
}

/* @end */

/*------------------------------------------------------------------------------
  @group Wiki Styles
------------------------------------------------------------------------------*/

.github {
  font-family:Helvetica !important;
  background: #f8f8f8;
  margin: 20px 40px;
  padding: 3px;
  width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.github article {
  background: #fff;
  border: 2px solid #cacaca;
  padding: 30px;
}

.github h1, h2, h3, h4, h5, h6 {
  border: 0 !important;
}

.github h1 {
  font-size: 170% !important;
  border-top: 4px solid #aaa !important;
  padding-top: .5em !important;
  margin-top: 1.5em !important;
}

  .github h1:first-child {
    margin-top: 0 !important;
    padding-top: .25em !important;
    border-top: none !important;
  }

.github h2 {
  font-size: 150% !important;
  margin-top: 1.5em !important;
  border-top: 4px solid #e0e0e0 !important;
  padding-top: .5em !important;
}

.github h3 {
  margin-top: 1em !important;
}

.github p {
  margin: 1em 0 !important;
  line-height: 1.5em !important;
}

.github ul {
  margin: 1em 0 1em 2em !important;
}

  .github ul {
    margin-top: 0 !important;
    margin-bottom: 0 !important;
  }

.github ol {
  margin: 1em 0 1em 2em !important;
}

  .github ol ol {
    margin-top: 0 !important;
    margin-bottom: 0 !important;
  }

.github ul ul,
.github ul ol,
.github ol ol,
.github ol ul {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
}

.github blockquote {
  margin: 1em 0 !important;
  border-left: 5px solid #ddd !important;
  padding-left: .6em !important;
  color: #555 !important;
}

.github dt {
  font-weight: bold !important;
  margin-left: 1em !important;
}

.github dd {
  margin-left: 2em !important;
  margin-bottom: 1em !important;
}

.github table {
  margin: 1em 0 !important;
}

  .github table th {
    border-bottom: 1px solid #bbb !important;
    padding: .2em 1em !important;
  }

  .github table td {
    border-bottom: 1px solid #ddd !important;
    padding: .2em 1em !important;
  }

.github pre {
  margin: 1em 0 !important;
  font-size: 90% !important;
  background-color: #f8f8ff !important;
  border: 1px solid #dedede !important;
  padding: .5em !important;
  line-height: 1.5em !important;
  color: #444 !important;
  overflow: auto !important;
}

  .github pre code {
    padding: 0 !important;
    font-size: 100% !important;
    background-color: #f8f8ff !important;
    border: none !important;
  }

.github code {
  font-size: 90% !important;
  background-color: #f8f8ff !important;
  color: #444 !important;
  padding: 0 .2em !important;
  border: 1px solid #dedede !important;
}

/* console */

.github pre.console {
  margin: 1em 0 !important;
  font-size: 90% !important;
  background-color: black !important;
  padding: .5em !important;
  line-height: 1.5em !important;
  color: white !important;
}

  .github pre.console code {
    padding: 0 !important;
    font-size: 100% !important;
    background-color: black !important;
    border: none !important;
    color: white !important;
  }

  .github pre.console span {
    color: #888 !important;
  }

  .github pre.console span.command {
    color: yellow !important;
  }

/* @end */


text:
#ifndef _WINDOW_H
#define _WINDOW_H

#include <QMainWindow>
#include <QApplication>

#include "ui_Window.h"

namespace Ui {
class Window;
}

class DriverStation;

class Window : public QMainWindow
{
    Q_OBJECT

public:
    explicit Window (QWidget* parent = 0);
    ~Window();

public slots:
    void updateEnabled (int unused);
    void syncButtons (bool enabled);
    void setProtocol (int protocol);
    void setTeamStation (int station);
    void updateControlMode (int unused);
    void setVoltage (const float voltage);

private:
    Ui::Window* ui;
    DriverStation* ds;
};

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web;
using ServiceStack.Text;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.WebHost.Endpoints.Extensions;

namespace ServiceStack.ServiceHost
{
	public static class HttpRequestExtensions
	{
		/// <summary>
		/// Gets string value from Items[name] then Cookies[name] if exists.
		/// Useful when *first* setting the users response cookie in the request filter.
		/// To access the value for this initial request you need to set it in Items[].
		/// </summary>
		/// <returns>string value or null if it doesn't exist</returns>
		public static string GetItemOrCookie(this IHttpRequest httpReq, string name)
		{
			object value;
			if (httpReq.Items.TryGetValue(name, out value)) return value.ToString();

			Cookie cookie;
			if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value;

			return null;
		}

		/// <summary>
		/// Gets request paramater string value by looking in the following order:
		/// - QueryString[name]
		/// - FormData[name]
		/// - Cookies[name]
		/// - Items[name]
		/// </summary>
		/// <returns>string value or null if it doesn't exist</returns>
		public static string GetParam(this IHttpRequest httpReq, string name)
		{
			string value;
			if ((value = httpReq.Headers[HttpHeaders.XParamOverridePrefix + name]) != null) return value;
			if ((value = httpReq.QueryString[name]) != null) return value;
			if ((value = httpReq.FormData[name]) != null) return value;

			Cookie cookie;
			if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value;

			object oValue;
			if (httpReq.Items.TryGetValue(name, out oValue)) return oValue.ToString();

			return null;
		}

		public static string GetParentAbsolutePath(this IHttpRequest httpReq)
		{
			return httpReq.GetAbsolutePath().ToParentPath();
		}

		public static string GetAbsolutePath(this IHttpRequest httpReq)
		{
			var resolvedPathInfo = httpReq.PathInfo;

			var pos = httpReq.RawUrl.IndexOf(resolvedPathInfo, StringComparison.InvariantCultureIgnoreCase);
			if (pos == -1)
				throw new ArgumentException(
					String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl));

			return httpReq.RawUrl.Substring(0, pos + resolvedPathInfo.Length);
		}

		public static string GetParentPathUrl(this IHttpRequest httpReq)
		{
			return httpReq.GetPathUrl().ToParentPath();
		}

		public static string GetPathUrl(this IHttpRequest httpReq)
		{
			var resolvedPathInfo = httpReq.PathInfo;

			var pos = resolvedPathInfo == String.Empty
				? httpReq.AbsoluteUri.Length
				: httpReq.AbsoluteUri.IndexOf(resolvedPathInfo, StringComparison.InvariantCultureIgnoreCase);

			if (pos == -1)
				throw new ArgumentException(
					String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl));

			return httpReq.AbsoluteUri.Substring(0, pos + resolvedPathInfo.Length);
		}

		public static string GetUrlHostName(this IHttpRequest httpReq)
		{
			var aspNetReq = httpReq as HttpRequestWrapper;
			if (aspNetReq != null)
			{
				return aspNetReq.UrlHostName;
			}
			var uri = httpReq.AbsoluteUri;

			var pos = uri.IndexOf("://") + "://".Length;
			var partialUrl = uri.Substring(pos);
			var endPos = partialUrl.IndexOf('/');
			if (endPos == -1) endPos = partialUrl.Length;
			var hostName = partialUrl.Substring(0, endPos).Split(':')[0];
			return hostName;
		}

		public static string GetPhysicalPath(this IHttpRequest httpReq)
		{
			var aspNetReq = httpReq as HttpRequestWrapper;
			if (aspNetReq != null)
			{
				return aspNetReq.Request.PhysicalPath;
			}

			var filePath = httpReq.ApplicationFilePath.CombineWith(httpReq.PathInfo);
			return filePath;
		}

		public static string GetApplicationUrl(this HttpRequest httpReq)
		{
			var appPath = httpReq.ApplicationPath;
			var baseUrl = httpReq.Url.Scheme + "://" + httpReq.Url.Host;
			if (httpReq.Url.Port != 80) baseUrl += ":" + httpReq.Url.Port;
			var appUrl = baseUrl.CombineWith(appPath);
			return appUrl;
		}

		public static string GetHttpMethodOverride(this IHttpRequest httpReq)
		{
			var httpMethod = httpReq.HttpMethod;

			if (httpMethod != HttpMethods.Post)
				return httpMethod;

			var overrideHttpMethod =
				httpReq.Headers[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty()
				?? httpReq.FormData[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty()
				?? httpReq.QueryString[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty();

			if (overrideHttpMethod != null)
			{
				if (overrideHttpMethod != HttpMethods.Get && overrideHttpMethod != HttpMethods.Post)
					httpMethod = overrideHttpMethod;
			}

			return httpMethod;
		}

		public static string GetFormatModifier(this IHttpRequest httpReq)
		{
			var format = httpReq.QueryString["format"];
			if (format == null) return null;
			var parts = format.SplitOnFirst('.');
			return parts.Length > 1 ? parts[1] : null;
		}

		public static bool HasNotModifiedSince(this IHttpRequest httpReq, DateTime? dateTime)
		{
			if (!dateTime.HasValue) return false;
			var strHeader = httpReq.Headers[HttpHeaders.IfModifiedSince];
			try
			{
				if (strHeader != null)
				{
					var dateIfModifiedSince = DateTime.ParseExact(strHeader, "r", null);
					var utcFromDate = dateTime.Value.ToUniversalTime();
					//strip ms
					utcFromDate = new DateTime(
						utcFromDate.Ticks - (utcFromDate.Ticks % TimeSpan.TicksPerSecond),
						utcFromDate.Kind
					);

					return utcFromDate <= dateIfModifiedSince;
				}
				return false;
			}
			catch
			{
				return false;
			}
		}

		public static bool DidReturn304NotModified(this IHttpRequest httpReq, DateTime? dateTime, IHttpResponse httpRes)
		{
			if (httpReq.HasNotModifiedSince(dateTime))
			{
				httpRes.StatusCode = (int) HttpStatusCode.NotModified;
				return true;
			}
			return false;
		}

		public static string GetJsonpCallback(this IHttpRequest httpReq)
		{
			return httpReq == null ? null : httpReq.QueryString["callback"];
		}

		public static Dictionary<string, string> CookiesAsDictionary(this IHttpRequest httpReq)
		{
			var map = new Dictionary<string, string>();
			var aspNet = httpReq.OriginalRequest as HttpRequest;
			if (aspNet != null)
			{
				foreach (var name in aspNet.Cookies.AllKeys)
				{
					var cookie = aspNet.Cookies[name];
					if (cookie == null) continue;
					map[name] = cookie.Value;
				}
			}
			else
			{
				var httpListener = httpReq.OriginalRequest as HttpListenerRequest;
				if (httpListener != null)
				{
					for (var i = 0; i < httpListener.Cookies.Count; i++)
					{
						var cookie = httpListener.Cookies[i];
						if (cookie == null || cookie.Name == null) continue;
						map[cookie.Name] = cookie.Value;
					}
				}
			}
			return map;
		}

	}
}


text:
module Graphics.LWGL.Api
    ( glActiveTexture
    , glBindBuffer
    , glBindFramebuffer
    , glBindTexture
    , glBindVertexArray
    , glClearColor
    , glClear
    , glCullFace
    , glBufferData
    , glDisableVertexAttribArray
    , glDisable
    , glDrawArrays
    , glDrawBuffer
    , glDrawElements
    , glEnableVertexAttribArray
    , glEnable
    , glFramebufferTexture2D
    , glGenerateMipmap
    , glGenBuffers
    , glGenFramebuffers
    , glGenTextures
    , glGenVertexArray
    , glGetUniformLocation
    , glPolygonMode
    , glTexImage2D
    , glTexParameteri
    , glUniform1f
    , glUniform1i
    , glUniform3fv
    , glUniformMatrix4fv
    , glUseProgram
    , glViewport
    , glVertexAttribPointer
    ) where

import           Foreign             (Ptr, nullPtr, peekArray, plusPtr,
                                      withArray)
import           Foreign.C           (withCString)
import qualified Graphics.GL         as GL
import           Prelude             hiding (toEnum)

import           Graphics.LWGL.Types

-- | Select active texture unit.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glActiveTexture.xhtml>
glActiveTexture :: TextureUnit -> IO ()
glActiveTexture = GL.glActiveTexture . toEnum

-- | Bind a named buffer object
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindBuffer.xhtml>
glBindBuffer :: BufferTarget -> BufferObject -> IO ()
glBindBuffer bufferTarget (BufferObject bufferObject) =
    GL.glBindBuffer (toEnum bufferTarget) bufferObject

-- | Bind a framebuffer to a framebuffer target
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindFramebuffer.xhtml>
glBindFramebuffer :: FrameBufferTarget -> FrameBuffer -> IO ()
glBindFramebuffer bufferTarget (FrameBuffer frameBuffer) =
    GL.glBindFramebuffer (toEnum bufferTarget) frameBuffer

-- | Bind a named texture to a texturing target.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTexture.xhtml>
glBindTexture :: TextureTarget -> Texture -> IO ()
glBindTexture textureTarget (Texture texture) =
    GL.glBindTexture (toEnum textureTarget) texture

-- | Bind a vertex array object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindVertexArray.xhtml>
glBindVertexArray :: VertexArrayObject -> IO ()
glBindVertexArray (VertexArrayObject vertexArrayObject) =
    GL.glBindVertexArray vertexArrayObject

-- | Specify clear values for the color buffers.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glClearColor.xml>
glClearColor :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> IO ()
glClearColor = GL.glClearColor

-- | Clear buffers to preset values.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glClear.xhtml>
glClear :: [ClearBufferMask] -> IO ()
glClear = GL.glClear . combineBits

-- | Specify whether front- or back-facing facets can be culled.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glCullFace.xhtml>
glCullFace :: PolygonFace -> IO ()
glCullFace = GL.glCullFace . toEnum

-- | Creates and initializes a buffer object's data store.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBufferData.xhtml>
glBufferData :: BufferTarget -> Int -> Ptr a -> BufferUsage -> IO ()
glBufferData bufferTarget size ptr bufferUsage =
    GL.glBufferData (toEnum bufferTarget) (fromIntegral size) ptr (toEnum bufferUsage)

-- | Disable a generic vertex attribute array.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glEnableVertexAttribArray.xhtml>
glDisableVertexAttribArray :: AttributeIndex -> IO ()
glDisableVertexAttribArray (AttributeIndex index) =
    GL.glDisableVertexAttribArray index

-- | Disable server-side GL capabilities.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glEnable.xhtml>
glDisable :: EnableCapability -> IO ()
glDisable = GL.glDisable . toEnum

-- | Render primitives from array data.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDrawArrays.xhtml>
glDrawArrays :: PrimitiveType -> Int -> Int -> IO ()
glDrawArrays primitiveType first count =
    GL.glDrawArrays (toEnum primitiveType) (fromIntegral first) (fromIntegral count)

-- | Specify which color buffers are to be drawn into.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDrawBuffer.xhtml>
glDrawBuffer :: DrawBufferMode -> IO ()
glDrawBuffer = GL.glDrawBuffer . toEnum

-- | Render primitives from array data.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDrawElements.xhtml>
glDrawElements :: PrimitiveType -> Int -> DrawElementsType -> Ptr a -> IO ()
glDrawElements primitiveType count drawElementsType =
    GL.glDrawElements (toEnum primitiveType) (fromIntegral count) (toEnum drawElementsType)

-- | Enable a generic vertex attribute array.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glEnableVertexAttribArray.xhtml>
glEnableVertexAttribArray :: AttributeIndex -> IO ()
glEnableVertexAttribArray (AttributeIndex index) =
    GL.glEnableVertexAttribArray index

-- | Enable server-side GL capabilities.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glEnable.xhtml>
glEnable :: EnableCapability -> IO ()
glEnable = GL.glEnable . toEnum

-- | Attach a level of a texture object as a logical buffer of a framebuffer object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glFramebufferTexture.xhtml>
glFramebufferTexture2D :: FrameBufferTarget -> FrameBufferAttachment
                       -> TextureTarget -> Texture -> Int -> IO ()
glFramebufferTexture2D bufferTarget bufferAttachment textureTarget
                       (Texture texture) level =
    GL.glFramebufferTexture2D (toEnum bufferTarget) (toEnum bufferAttachment)
                              (toEnum textureTarget) texture (fromIntegral level)

-- | Generate mipmaps for a specified texture object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGenerateMipmap.xhtml>
glGenerateMipmap :: TextureTarget -> IO ()
glGenerateMipmap = GL.glGenerateMipmap . toEnum

-- | Generate buffer object names
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glGenBuffers.xml>
glGenBuffers :: Int -> IO [BufferObject]
glGenBuffers num = do
    let array = replicate num 0
    withArray array $ \ptr -> do
        GL.glGenBuffers (fromIntegral num) ptr
        map BufferObject <$> peekArray num ptr

-- | Generate framebuffer object names.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGenFramebuffers.xhtml>
glGenFramebuffers :: Int -> IO [FrameBuffer]
glGenFramebuffers num = do
    let array = replicate num 0
    withArray array $ \ptr -> do
        GL.glGenFramebuffers (fromIntegral num) ptr
        map FrameBuffer <$> peekArray num ptr

-- | Generate texture names.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGenTextures.xhtml>
glGenTextures :: Int -> IO [Texture]
glGenTextures num = do
    let array = replicate num 0
    withArray array $ \ptr -> do
        GL.glGenTextures (fromIntegral num) ptr
        map Texture <$> peekArray num ptr

-- | Generate vertex array object names.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGenVertexArrays.xhtml>
glGenVertexArray :: Int -> IO [VertexArrayObject]
glGenVertexArray num = do
    let array = replicate num 0
    withArray array $ \ptr -> do
        GL.glGenVertexArrays (fromIntegral num) ptr
        map VertexArrayObject <$> peekArray num ptr

-- | Returns the location of a uniform variable.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGetUniformLocation.xhtml>
glGetUniformLocation :: Program -> String -> IO Location
glGetUniformLocation (Program program) name =
    withCString name $ \cstring ->
        Location <$> GL.glGetUniformLocation program cstring

-- | Select a polygon rasterization mode.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glPolygonMode.xhtml>
glPolygonMode :: PolygonFace -> PolygonMode -> IO ()
glPolygonMode face = GL.glPolygonMode (toEnum face) . toEnum

-- | Specify a two-dimensional texture image.
--
-- | Note: No border parameter. Always zero.
-- | See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml>
glTexImage2D :: TextureTarget
             -> ImageDetailLevel
             -> ImageComponentCount
             -> Width
             -> Height
             -> PixelFormat
             -> PixelType
             -> Ptr a
             -> IO ()
glTexImage2D textureTarget detailLevel componentCount
             width height format type_ =
    GL.glTexImage2D (toEnum textureTarget) detailLevel (toInt componentCount)
                    width height 0 (toEnum format) (toEnum type_)

-- | Set texture parameters.
--
-- | See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml>
glTexParameteri :: TextureTarget -> TextureParameterName
                -> TextureParameterValue -> IO ()
glTexParameteri textureTarget parameterName parameterValue =
    GL.glTexParameteri (toEnum textureTarget) (toEnum parameterName)
                       (toInt parameterValue)

-- | Specify the value of a uniform variable for the current program object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml>
glUniform1f :: Location -> Float -> IO ()
glUniform1f (Location location) = GL.glUniform1f location

-- | Specify the value of a uniform variable for the current program object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml>
glUniform1i :: Location -> Int -> IO ()
glUniform1i (Location location) = GL.glUniform1i location . fromIntegral

-- | Specify the value of a uniform variable for the current program object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml>
glUniform3fv :: Location -> Int -> Ptr GLfloat -> IO ()
glUniform3fv (Location location) count =
    GL.glUniform3fv location (fromIntegral count)

-- | Specify the value of a uniform variable for the current program object.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml>
glUniformMatrix4fv :: Location -> Int -> Bool -> Ptr GLfloat -> IO ()
glUniformMatrix4fv (Location location) count transpose =
    GL.glUniformMatrix4fv location (fromIntegral count) (toBoolean transpose)

-- | Installs a program object as part of current rendering state.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glUseProgram.xml>
glUseProgram :: Program -> IO ()
glUseProgram (Program program) = GL.glUseProgram program

-- | Set the viewport
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glViewport.xhtml>
glViewport :: Int -> Int -> Int -> Int -> IO ()
glViewport x y width height =
    GL.glViewport (fromIntegral x) (fromIntegral y)
                  (fromIntegral width) (fromIntegral height)

-- | Define an array of generic vertex attribute data.
--
-- See <https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml>
glVertexAttribPointer :: AttributeIndex
                      -> ComponentCount
                      -> VertexAttribPointerType
                      -> Bool
                      -> Int
                      -> Int -- This is byte index into buffer
                      -> IO ()
glVertexAttribPointer (AttributeIndex index) count pointerType
                      normalize stride offset = do
    let pointer = nullPtr `plusPtr` offset
    GL.glVertexAttribPointer index (toInt count) (toEnum pointerType)
                             (toBoolean normalize) (fromIntegral stride) pointer


text:
"""Module for parsing and manipulating data from ENDF evaluations.

All the classes and functions in this module are based on document
ENDF-102 titled "Data Formats and Procedures for the Evaluated Nuclear
Data File ENDF-6". The latest version from June 2009 can be found at
http://www-nds.iaea.org/ndspub/documents/endf/endf102/endf102.pdf

"""
from __future__ import print_function, division, unicode_literals

import io
import re
import os
from math import pi
from collections import OrderedDict, Iterable

from six import string_types
import numpy as np
from numpy.polynomial.polynomial import Polynomial

from .data import ATOMIC_SYMBOL
from .function import Tabulated1D, INTERPOLATION_SCHEME
from openmc.stats.univariate import Uniform, Tabular, Legendre

LIBRARIES = {0: 'ENDF/B', 1: 'ENDF/A', 2: 'JEFF', 3: 'EFF',
             4: 'ENDF/B High Energy', 5: 'CENDL', 6: 'JENDL',
             31: 'INDL/V', 32: 'INDL/A', 33: 'FENDL', 34: 'IRDF',
             35: 'BROND', 36: 'INGDB-90', 37: 'FENDL/A', 41: 'BROND'}

SUM_RULES = {1: [2, 3],
             3: [4, 5, 11, 16, 17, 22, 23, 24, 25, 27, 28, 29, 30, 32, 33, 34, 35,
                 36, 37, 41, 42, 44, 45, 152, 153, 154, 156, 157, 158, 159, 160,
                 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172,
                 173, 174, 175, 176, 177, 178, 179, 180, 181, 183, 184, 185,
                 186, 187, 188, 189, 190, 194, 195, 196, 198, 199, 200],
             4: list(range(50, 92)),
             16: list(range(875, 892)),
             18: [19, 20, 21, 38],
             27: [18, 101],
             101: [102, 103, 104, 105, 106, 107, 108, 109, 111, 112, 113, 114,
                   115, 116, 117, 155, 182, 191, 192, 193, 197],
             103: list(range(600, 650)),
             104: list(range(650, 700)),
             105: list(range(700, 750)),
             106: list(range(750, 800)),
             107: list(range(800, 850))}

ENDF_FLOAT_RE = re.compile(r'([\s\-\+]?\d*\.\d+)([\+\-]\d+)')

def float_endf(s):
    """Convert string of floating point number in ENDF to float.

    The ENDF-6 format uses an 'e-less' floating point number format,
    e.g. -1.23481+10. Trying to convert using the float built-in won't work
    because of the lack of an 'e'. This function allows such strings to be
    converted while still allowing numbers that are not in exponential notation
    to be converted as well.

    Parameters
    ----------
    s : str
        Floating-point number from an ENDF file

    Returns
    -------
    float
        The number

    """
    return float(ENDF_FLOAT_RE.sub(r'\1e\2', s))

def get_text_record(file_obj):
    """Return data from a TEXT record in an ENDF-6 file.

    Parameters
    ----------
    file_obj : file-like object
        ENDF-6 file to read from

    Returns
    -------
    str
        Text within the TEXT record

    """
    return file_obj.readline()[:66]

def get_cont_record(file_obj, skipC=False):
    """Return data from a CONT record in an ENDF-6 file.

    Parameters
    ----------
    file_obj : file-like object
        ENDF-6 file to read from
    skipC : bool
        Determine whether to skip the first two quantities (C1, C2) of the CONT
        record.

    Returns
    -------
    list
        The six items within the CONT record

    """
    line = file_obj.readline()
    if skipC:
        C1 = None
        C2 = None
    else:
        C1 = float_endf(line[:11])
        C2 = float_endf(line[11:22])
    L1 = int(line[22:33])
    L2 = int(line[33:44])
    N1 = int(line[44:55])
    N2 = int(line[55:66])
    return [C1, C2, L1, L2, N1, N2]

def get_head_record(file_obj):
    """Return data from a HEAD record in an ENDF-6 file.

    Parameters
    ----------
    file_obj : file-like object
        ENDF-6 file to read from

    Returns
    -------
    list
        The six items within the HEAD record

    """
    line = file_obj.readline()
    ZA = int(float_endf(line[:11]))
    AWR = float_endf(line[11:22])
    L1 = int(line[22:33])
    L2 = int(line[33:44])
    N1 = int(line[44:55])
    N2 = int(line[55:66])
    return [ZA, AWR, L1, L2, N1, N2]

def get_list_record(file_obj):
    """Return data from a LIST record in an ENDF-6 file.

    Parameters
    ----------
    file_obj : file-like object
        ENDF-6 file to read from

    Returns
    -------
    list
        The six items within the header
    list
        The values within the list

    """
    # determine how many items are in list
    items = get_cont_record(file_obj)
    NPL = items[4]

    # read items
    b = []
    for i in range((NPL - 1)//6 + 1):
        line = file_obj.readline()
        n = min(6, NPL - 6*i)
        for j in range(n):
            b.append(float_endf(line[11*j:11*(j + 1)]))

    return (items, b)

def get_tab1_record(file_obj):
    """Return data from a TAB1 record in an ENDF-6 file.

    Parameters
    ----------
    file_obj : file-like object
        ENDF-6 file to read from

    Returns
    -------
    list
        The six items within the header
    openmc.data.Tabulated1D
        The tabulated function

    """
    # Determine how many interpolation regions and total points there are
    line = file_obj.readline()
    C1 = float_endf(line[:11])
    C2 = float_endf(line[11:22])
    L1 = int(line[22:33])
    L2 = int(line[33:44])
    n_regions = int(line[44:55])
    n_pairs = int(line[55:66])
    params = [C1, C2, L1, L2]

    # Read the interpolation region data, namely NBT and INT
    breakpoints = np.zeros(n_regions, dtype=int)
    interpolation = np.zeros(n_regions, dtype=int)
    m = 0
    for i in range((n_regions - 1)//3 + 1):
        line = file_obj.readline()
        to_read = min(3, n_regions - m)
        for j in range(to_read):
            breakpoints[m] = int(line[0:11])
            interpolation[m] = int(line[11:22])
            line = line[22:]
            m += 1

    # Read tabulated pairs x(n) and y(n)
    x = np.zeros(n_pairs)
    y = np.zeros(n_pairs)
    m = 0
    for i in range((n_pairs - 1)//3 + 1):
        line = file_obj.readline()
        to_read = min(3, n_pairs - m)
        for j in range(to_read):
            x[m] = float_endf(line[:11])
            y[m] = float_endf(line[11:22])
            line = line[22:]
            m += 1

    return params, Tabulated1D(x, y, breakpoints, interpolation)

def get_tab2_record(file_obj):
    # Determine how many interpolation regions and total points there are
    params = get_cont_record(file_obj)
    n_regions = params[4]

    # Read the interpolation region data, namely NBT and INT
    breakpoints = np.zeros(n_regions, dtype=int)
    interpolation = np.zeros(n_regions, dtype=int)
    m = 0
    for i in range((n_regions - 1)//3 + 1):
        line = file_obj.readline()
        to_read = min(3, n_regions - m)
        for j in range(to_read):
            breakpoints[m] = int(line[0:11])
            interpolation[m] = int(line[11:22])
            line = line[22:]
            m += 1

    return params, Tabulated2D(breakpoints, interpolation)

def get_evaluations(filename):
    """Return a list of all evaluations within an ENDF file.

    Parameters
    ----------
    filename : str
        Path to ENDF-6 formatted file

    Returns
    -------
    list
        A list of :class:`openmc.data.endf.Evaluation` instances.

    """
    evaluations = []
    with open(filename, 'r') as fh:
        while True:
            pos = fh.tell()
            line = fh.readline()
            if line[66:70] == '  -1':
                break
            fh.seek(pos)
            evaluations.append(Evaluation(fh))
    return evaluations

class Evaluation(object):
    """ENDF material evaluation with multiple files/sections

    Parameters
    ----------
    filename_or_obj : str or file-like
        Path to ENDF file to read or an open file positioned at the start of an
        ENDF material

    Attributes
    ----------
    info : dict
        Miscallaneous information about the evaluation.
    target : dict
        Information about the target material, such as its mass, isomeric state,
        whether it's stable, and whether it's fissionable.
    projectile : dict
        Information about the projectile such as its mass.
    reaction_list : list of 4-tuples
        List of sections in the evaluation. The entries of the tuples are the
        file (MF), section (MT), number of records (NC), and modification
        indicator (MOD).

    """
    def __init__(self, filename_or_obj):
        if isinstance(filename_or_obj, string_types):
            fh = open(filename_or_obj, 'r')
        else:
            fh = filename_or_obj
        self.section = {}
        self.info = {}
        self.target = {}
        self.projectile = {}
        self.reaction_list = []

        # Determine MAT number for this evaluation
        MF = 0
        while MF == 0:
            position = fh.tell()
            line = fh.readline()
            MF = int(line[70:72])
        self.material = int(line[66:70])
        fh.seek(position)

        while True:
            # Find next section
            while True:
                position = fh.tell()
                line = fh.readline()
                MAT = int(line[66:70])
                MF = int(line[70:72])
                MT = int(line[72:75])
                if MT > 0 or MAT == 0:
                    fh.seek(position)
                    break

            # If end of material reached, exit loop
            if MAT == 0:
                fh.readline()
                break

            section_data = ''
            while True:
                line = fh.readline()
                if line[72:75] == '  0':
                    break
                else:
                    section_data += line
            self.section[MF, MT] = section_data

        self._read_header()

    def _read_header(self):
        file_obj = io.StringIO(self.section[1, 451])

        # Information about target/projectile
        items = get_head_record(file_obj)
        self.target['atomic_number'] = items[0] // 1000
        self.target['mass_number'] = items[0] % 1000
        self.target['mass'] = items[1]
        self._LRP = items[2]
        self.target['fissionable'] = (items[3] == 1)
        try:
            global LIBRARIES
            library = LIBRARIES[items[4]]
        except KeyError:
            library = 'Unknown'
        self.info['modification'] = items[5]

        # Control record 1
        items = get_cont_record(file_obj)
        self.target['excitation_energy'] = items[0]
        self.target['stable'] = (int(items[1]) == 0)
        self.target['state'] = items[2]
        self.target['isomeric_state'] = items[3]
        self.info['format'] = items[5]
        assert self.info['format'] == 6

        # Control record 2
        items = get_cont_record(file_obj)
        self.projectile['mass'] = items[0]
        self.info['energy_max'] = items[1]
        library_release = items[2]
        self.info['sublibrary'] = items[4]
        library_version = items[5]
        self.info['library'] = (library, library_version, library_release)

        # Control record 3
        items = get_cont_record(file_obj)
        self.target['temperature'] = items[0]
        self.info['derived'] = (items[2] > 0)
        NWD = items[4]
        NXC = items[5]

        # Text records
        text = [get_text_record(file_obj) for i in range(NWD)]
        if len(text) >= 5:
            self.target['zsymam'] = text[0][0:11]
            self.info['laboratory'] = text[0][11:22]
            self.info['date'] = text[0][22:32]
            self.info['author'] = text[0][32:66]
            self.info['reference'] = text[1][1:22]
            self.info['date_distribution'] = text[1][22:32]
            self.info['date_release'] = text[1][33:43]
            self.info['date_entry'] = text[1][55:63]
            self.info['identifier'] = text[2:5]
            self.info['description'] = text[5:]

        # File numbers, reaction designations, and number of records
        for i in range(NXC):
            line = file_obj.readline()
            mf = int(line[22:33])
            mt = int(line[33:44])
            nc = int(line[44:55])
            try:
                mod = int(line[55:66])
            except ValueError:
                # In JEFF 3.2, a few isotopes of U have MOD values that are
                # missing. This prevents failure on these isotopes.
                mod = 0
            self.reaction_list.append((mf, mt, nc, mod))

    @property
    def gnd_name(self):
        symbol = ATOMIC_SYMBOL[self.target['atomic_number']]
        A = self.target['mass_number']
        m = self.target['isomeric_state']
        if m > 0:
            return '{}{}_m{}'.format(symbol, A, m)
        else:
            return '{}{}'.format(symbol, A)

class Tabulated2D(object):
    """Metadata for a two-dimensional function.

    This is a dummy class that is not really used other than to store the
    interpolation information for a two-dimensional function. Once we refactor
    to adopt GND-like data containers, this will probably be removed or
    extended.

    Parameters
    ----------
    breakpoints : Iterable of int
        Breakpoints for interpolation regions
    interpolation : Iterable of int
        Interpolation scheme identification number, e.g., 3 means y is linear in
        ln(x).

    """
    def __init__(self, breakpoints, interpolation):
        self.breakpoints = breakpoints
        self.interpolation = interpolation


text:
package com.al.morsecodeconverter;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.al.morsecodeconverter.worker.MorseCodeWorker;

/**
 * This class takes in Morse Code and converts that into English Text.
 * @author AL
 *
 */
public class MorseActivity extends Activity
{

    String className = getClass().getSimpleName();

    MorseCodeWorker workerClass = new MorseCodeWorker();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_morse);

	//This represents the morse code input of the user.
	final TextView morseInputView = (TextView) findViewById(R.id.inputMorse);

	//This converts the morse code into english text.
	Button convertBtn = (Button) findViewById(R.id.convertMorse);

	//Performs the action for the coversion button.
	convertBtn.setOnClickListener(new View.OnClickListener()
	{
	    /*This listener takes in the values from the input field and converts the code. */
	    @Override
	    public void onClick(View v)
	    {
		TextView textDisplay = (TextView) findViewById(R.id.morseCodeDisplay);;
		String morseText = morseInputView.getText().toString();
		if(morseText != null)
		{
		    textDisplay.setText(workerClass.toText(morseText));
		}

	    }
	});
    }
}


text:
class Change_Drive : public CommandGroup {
public:
	Change_Drive();
};


text:
package cn.com.git.usdp.modules.sys.web;

import cn.com.git.usdp.core.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by tz on 2017/2/8.
 */
@Controller
@RequestMapping("decorators")
public class LayoutController extends BaseController {

    @RequestMapping("layout/{template}")
    public String header(@PathVariable String template) {
        return SYSTEM_THEME_STYLE + "/layouts/" + template;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 2: 346 (1883)

#### Original name
Sphaeria fulgida Cooke & Peck, 1878

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<!-- This file contains resource definitions for displayed strings, allowing
     them to be changed based on the locale and options. -->

<resources>
    <!-- App -->
    <string name="enlight_activity">Sourcerer01j</string>

    <!-- UI -->
    <string name="text_paused_cellular">Would you like to enable downloading over cellular connections? Depending on your data plan, this may cost you money.</string>
    <string name="text_paused_cellular_2">If you choose not to enable downloading over cellular connections, the download will automatically resume when wi-fi is available.</string>
    <string name="text_button_resume_cellular">Resume download</string>
    <string name="text_button_wifi_settings">Wi-Fi settings</string>
    <string name="text_verifying_download">Verifying Download</string>
    <string name="text_validation_complete">XAPK File Validation Complete.  Select OK to exit.</string>
    <string name="text_validation_failed">XAPK File Validation Failed.</string>
    <string name="text_button_pause">Pause Download</string>
    <string name="text_button_resume">Resume Download</string>
    <string name="text_button_cancel">Cancel</string>
    <string name="text_button_cancel_verify">Cancel Verification</string>

</resources>


text:
#ifndef DocumentLifecycleObserver_h
#define DocumentLifecycleObserver_h

#include "core/dom/Document.h"
#include "platform/LifecycleObserver.h"

namespace blink {

class DocumentLifecycleNotifier;

class DocumentLifecycleObserver : public LifecycleObserver<Document, DocumentLifecycleObserver, DocumentLifecycleNotifier> {
public:
    virtual void documentWasDetached() { }
#if !ENABLE(OILPAN)
    virtual void documentWasDisposed() { }
#endif

protected:
    explicit DocumentLifecycleObserver(Document* document)
        : LifecycleObserver(document)
    {
    }
};

} // namespace blink

#endif // DocumentLifecycleObserver_h


text:
.. _whatsnew_0232:

What's New in 0.23.2 (July 5, 2018)
-----------------------------------

{{ header }}

This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes
and bug fixes. We recommend that all users upgrade to this version.

.. note::

   Pandas 0.23.2 is first pandas release that's compatible with
   Python 3.7 (:issue:`20552`)

.. warning::

   Starting January 1, 2019, pandas feature releases will support Python 3 only.
   See :ref:`install.dropping-27` for more.

.. contents:: What's new in v0.23.2
    :local:
    :backlinks: none

.. _whatsnew_0232.enhancements:

Logical Reductions over Entire DataFrame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:meth:`DataFrame.all` and :meth:`DataFrame.any` now accept ``axis=None`` to reduce over all axes to a scalar (:issue:`19976`)

.. ipython:: python

   df = pd.DataFrame({"A": [1, 2], "B": [True, False]})
   df.all(axis=None)

This also provides compatibility with NumPy 1.15, which now dispatches to ``DataFrame.all``.
With NumPy 1.15 and pandas 0.23.1 or earlier, :func:`numpy.all` will no longer reduce over every axis:

.. code-block:: python

   >>> # NumPy 1.15, pandas 0.23.1
   >>> np.any(pd.DataFrame({"A": [False], "B": [False]}))
   A    False
   B    False
   dtype: bool

With pandas 0.23.2, that will correctly return False, as it did with NumPy < 1.15.

.. ipython:: python

   np.any(pd.DataFrame({"A": [False], "B": [False]}))

.. _whatsnew_0232.fixed_regressions:

Fixed Regressions
~~~~~~~~~~~~~~~~~

- Fixed regression in :meth:`to_csv` when handling file-like object incorrectly (:issue:`21471`)
- Re-allowed duplicate level names of a ``MultiIndex``. Accessing a level that has a duplicate name by name still raises an error (:issue:`19029`).
- Bug in both :meth:`DataFrame.first_valid_index` and :meth:`Series.first_valid_index` raised for a row index having duplicate values (:issue:`21441`)
- Fixed printing of DataFrames with hierarchical columns with long names (:issue:`21180`)
- Fixed regression in :meth:`~DataFrame.reindex` and :meth:`~DataFrame.groupby`
  with a MultiIndex or multiple keys that contains categorical datetime-like values (:issue:`21390`).
- Fixed regression in unary negative operations with object dtype (:issue:`21380`)
- Bug in :meth:`Timestamp.ceil` and :meth:`Timestamp.floor` when timestamp is a multiple of the rounding frequency (:issue:`21262`)
- Fixed regression in :func:`to_clipboard` that defaulted to copying dataframes with space delimited instead of tab delimited (:issue:`21104`)

Build Changes
~~~~~~~~~~~~~

- The source and binary distributions no longer include test data files, resulting in smaller download sizes. Tests relying on these data files will be skipped when using ``pandas.test()``. (:issue:`19320`)

.. _whatsnew_0232.bug_fixes:

Bug Fixes
~~~~~~~~~

**Conversion**

- Bug in constructing :class:`Index` with an iterator or generator (:issue:`21470`)
- Bug in :meth:`Series.nlargest` for signed and unsigned integer dtypes when the minimum value is present (:issue:`21426`)

**Indexing**

- Bug in :meth:`Index.get_indexer_non_unique` with categorical key (:issue:`21448`)
- Bug in comparison operations for :class:`MultiIndex` where error was raised on equality / inequality comparison involving a MultiIndex with ``nlevels == 1`` (:issue:`21149`)
- Bug in :meth:`DataFrame.drop` behaviour is not consistent for unique and non-unique indexes (:issue:`21494`)
- Bug in :func:`DataFrame.duplicated` with a large number of columns causing a 'maximum recursion depth exceeded' (:issue:`21524`).

**I/O**

- Bug in :func:`read_csv` that caused it to incorrectly raise an error when ``nrows=0``, ``low_memory=True``, and ``index_col`` was not ``None`` (:issue:`21141`)
- Bug in :func:`json_normalize` when formatting the ``record_prefix`` with integer columns (:issue:`21536`)

**Categorical**

- Bug in rendering :class:`Series` with ``Categorical`` dtype in rare conditions under Python 2.7 (:issue:`21002`)

**Timezones**

- Bug in :class:`Timestamp` and :class:`DatetimeIndex` where passing a :class:`Timestamp` localized after a DST transition would return a datetime before the DST transition (:issue:`20854`)
- Bug in comparing :class:`DataFrame` with tz-aware :class:`DatetimeIndex` columns with a DST transition that raised a ``KeyError`` (:issue:`19970`)
- Bug in :meth:`DatetimeIndex.shift` where an ``AssertionError`` would raise when shifting across DST (:issue:`8616`)
- Bug in :class:`Timestamp` constructor where passing an invalid timezone offset designator (``Z``) would not raise a ``ValueError`` (:issue:`8910`)
- Bug in :meth:`Timestamp.replace` where replacing at a DST boundary would retain an incorrect offset (:issue:`7825`)
- Bug in :meth:`DatetimeIndex.reindex` when reindexing a tz-naive and tz-aware :class:`DatetimeIndex` (:issue:`8306`)
- Bug in :meth:`DatetimeIndex.resample` when downsampling across a DST boundary (:issue:`8531`)

**Timedelta**

- Bug in :class:`Timedelta` where non-zero timedeltas shorter than 1 microsecond were considered False (:issue:`21484`)

.. _whatsnew_0.23.2.contributors:

Contributors
~~~~~~~~~~~~

.. contributors:: v0.23.1..v0.23.2


text:
#ifndef UTIL_EXTRACTEDDEVICESTATE_H_INCLUDED
#define UTIL_EXTRACTEDDEVICESTATE_H_INCLUDED

#include <fstream>
#include <map>
#include <vector>

namespace cuda {

	typedef std::vector<char> ByteVector;

	class ExtractedDeviceState {
	public:

		class MemoryAllocation {
		public:
			MemoryAllocation(const void *ptr = 0, size_t size = 0);

			void serialize(std::ostream &out) const;
			void deserialize(const hydrazine::json::Visitor &visitor);

			size_t size() const;

		public:

			//! \brief references the allocation on the device
			const void *devicePointer;

			//! \brief binary representation of data
			ByteVector data;
		};

		class GlobalAllocation {
		public:
			GlobalAllocation(const void *ptr = 0, size_t size = 0,
				const std::string& moduleName = "",
				const std::string& globalName = "");

			void serialize(std::ostream &out) const;
			void deserialize(const hydrazine::json::Visitor &visitor);

			size_t size() const;

			std::string key() const;

		public:
			//! \brief The module that the allocation is stored in
			std::string module;

			//! \brief The name of the global allocation
			std::string name;

			//! \brief binary representation of data
			ByteVector data;
		};

		typedef std::map<std::string, ir::Texture*>       TextureMap;
		typedef std::map<std::string, GlobalAllocation*>  GlobalVariableMap;
		typedef std::map<const void *, MemoryAllocation*> GlobalAllocationMap;

		/*!

		*/
		class Module {
		public:

			Module();

			~Module();

			void clear();

			void serialize(std::ostream &out,
				const std::string & prefix = "") const;
			void deserialize(const hydrazine::json::Visitor &visitor);

		private:

			void serializeTexture(const ir::Texture &texture,
				std::ostream &out, const std::string & prefix = "") const;
			void deserializeTexture(ir::Texture &texture,
				const hydrazine::json::Visitor &visitor);

		public:
			//! \brief module loaded into this name
			std::string name;

			//! \brief file to which PTX representation of module is written
			std::string ptx;

			//! \brief textures contained in the module
			TextureMap textures;
		};

		class KernelLaunch {
		public:

			void serialize(std::ostream &out) const;
			void deserialize(const hydrazine::json::Visitor &visitor);

		public:
			//! \brief name of module owning kernel
			std::string moduleName;

			//! \brief name of kernel
			std::string kernelName;

			//! \brief dimensions of CTAs
			ir::Dim3 blockDim;

			//! \brief dimensions of grid
			ir::Dim3 gridDim;

			//! \brief shared memory size
			size_t sharedMemorySize;

			//! \brief static shared memory size
			size_t staticSharedMemorySize;

			//! \brief block of memory denoting parameter memory
			ByteVector parameterMemory;
		};

		class Application {
		public:

			Application();

			void serialize(std::ostream &out) const;
			void deserialize(const hydrazine::json::Visitor &visitor);

		public:
			//! \brief name of application
			std::string name;

			//! \brief name of target CUDA device
			std::string cudaDevice;

		};

		typedef std::map<std::string, Module*> ModuleMap;

	public:

		ExtractedDeviceState(std::istream &in);
		ExtractedDeviceState();
		~ExtractedDeviceState();

		void serialize(std::ostream &out) const;
		void deserialize(std::istream &in);

		void clear();
		void clearData();

	public:

		//! \brief data specific to an application
		Application application;

		//! \brief maps module names onto structure capturing module state
		ModuleMap modules;

		//! \brief values of global allocations before kernel launch
		GlobalAllocationMap globalAllocations;

		//! \brief values of global variables before the kernel launch
		GlobalVariableMap globalVariables;

		//! \brief values of global allocations after kernel launch
		GlobalAllocationMap postLaunchGlobalAllocations;

		//! \brief values of global variables after the kernel launch
		GlobalVariableMap postLaunchGlobalVariables;

		//! \brief parameters of CUDA launch
		KernelLaunch launch;
	};

}

#endif


text: <ngx-knob [value]="value" [options]="knOptions"></ngx-knob>


text:
.class public final Lcom/tencent/connect/dataprovider/ErrorCode;
.super Ljava/lang/Object;

# static fields
.field public static final FileIsEmpty:I = -0x9

.field public static final FileNotExist:I = -0x8

.field public static final FileNotInSdCard:I = -0x5

.field public static final FileSizeTooLarge:I = -0x6

.field public static final NotFoundReturnActivity:I = -0x3

.field public static final NotFoundTargetApp:I = -0x4

.field public static final NotFromTencentApp:I = -0x2

.field public static final NotSupportThisDataType:I = -0x1

.field public static final PathIsNull:I = -0x7

.field public static final SdCardNotExist:I = -0xa

.field public static final Success:I

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  The contents of this file are subject to the Terracotta Public License Version
  2.0 (the "License"); You may not use this file except in compliance with the
  License. You may obtain a copy of the License at

  http://terracotta.org/legal/terracotta-public-license.

  Software distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
  the specific language governing rights and limitations under the License.

  The Covered Software is OffHeap Resource.

  The Initial Developer of the Covered Software is
  Terracotta, Inc., a Software AG company
-->

<ohr:offheap-resources
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xmlns:ohr='http://www.terracotta.org/config/offheap-resource'>

  <ohr:resource name="primary" unit="MB">64</ohr:resource>
</ohr:offheap-resources>


text:
#include <aws/ec2/model/DescribeSnapshotAttributeRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::EC2::Model;
using namespace Aws::Utils;

DescribeSnapshotAttributeRequest::DescribeSnapshotAttributeRequest() :
    m_dryRun(false),
    m_dryRunHasBeenSet(false),
    m_snapshotIdHasBeenSet(false),
    m_attributeHasBeenSet(false)
{
}

Aws::String DescribeSnapshotAttributeRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DescribeSnapshotAttribute&";
  if(m_dryRunHasBeenSet)
  {
    ss << "DryRun=" << m_dryRun << "&";
  }

  if(m_snapshotIdHasBeenSet)
  {
    ss << "SnapshotId=" << StringUtils::URLEncode(m_snapshotId.c_str()) << "&";
  }

  if(m_attributeHasBeenSet)
  {
    ss << "Attribute=" << SnapshotAttributeNameMapper::GetNameForSnapshotAttributeName(m_attribute) << "&";
  }

  ss << "Version=2015-10-01";
  return ss.str();
}


text:
//-----------------------------------------------------------------------
// <copyright file="TestSources.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using Activities;
using ScheduledActivities;
using ScheduledActivities.Schedules;
using ScheduledWorkItems;

namespace ScheduledActivityUnitTests
{
    /// Contains ScheduledActivitySource implementations for testing
    internal static class TestSources
    {
        /// Base class for test ScheduledActivitySource implementations
        /// <remarks>
        /// Bare implementation which returns null for both abstract members of
        /// ScheduledActivitySource. Used primarily as a base for testing required attributes.
        /// </remarks>
        public abstract class NullScheduledActivitySourceBase : ScheduledActivitySource
        {
            /// Creates new scheduled activity requests
            public override void CreateScheduledRequests()
            {
            }

            /// Handler for activity results
            /// <param name="request">The activity request</param>
            /// <param name="result">The activity result</param>
            public override void OnActivityResult(ActivityRequest request, ActivityResult result)
            {
            }
        }

        /// Valid ScheduledActivitySource
        /// <remarks>Scheduled to run every 10 milliseconds.</remarks>
        [SourceName("ValidActivitySource"), Schedule(typeof(IntervalSchedule), 0, 0, 0, 0, 50)]
        public class ValidActivitySource : NullScheduledActivitySourceBase
        {
            /// Gets the last activity result handled
            public ActivityResult LastResult { get; private set; }

            /// Creates a scheduled activity request
            public override void CreateScheduledRequests()
            {
                var request = new ActivityRequest
                {
                    Task = "Test",
                    Values = { }
                };
                this.SubmitRequest(request, ActivityRuntimeCategory.Interactive, false);
            }

            /// Handler for activity results
            /// <param name="request">The activity request</param>
            /// <param name="result">The activity result</param>
            public override void OnActivityResult(ActivityRequest request, ActivityResult result)
            {
                this.LastResult = result;
            }
        }

        /// Invalid ScheduledActivitySource missing the SourceName and Schedule attributes
        public class MissingSourceNameAndScheduleActivitySource : NullScheduledActivitySourceBase
        {
        }

        /// Invalid ScheduledActivitySource missing the SourceName attribute
        [Schedule(typeof(IntervalSchedule), 0, 0, 1)]
        public class MissingSourceNameActivitySource : NullScheduledActivitySourceBase
        {
        }

        /// Invalid ScheduledActivitySource missing the SourceName attribute
        [SourceName("MissingSchedule")]
        public class MissingScheduleActivitySource : NullScheduledActivitySourceBase
        {
        }

        /// Invalid ScheduledActivitySource with missing schedule args
        [SourceName("MissingScheduleArgs"), Schedule(typeof(IntervalSchedule))]
        public class MissingScheduleArgsActivitySource : NullScheduledActivitySourceBase
        {
        }

        /// Invalid ScheduledActivitySource with invalid schedule args
        [SourceName("InvalidScheduleArgs"), Schedule(typeof(IntervalSchedule), 327.46)]
        public class InvalidScheduleArgsActivitySource : NullScheduledActivitySourceBase
        {
        }

        /// Invalid ScheduledActivitySource with invalid schedule args
        [SourceName("InvalidScheduleArgValues"), Schedule(typeof(IntervalSchedule), "Not A Valid TimeSpan String")]
        public class InvalidScheduleArgValueActivitySource : NullScheduledActivitySourceBase
        {
        }
    }
}


text:
package org.terasology.logic.console.commandSystem.annotations;

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

/**
 * Marks a method parameter to have the value of the commands' sender
 *
 * @author Limeth
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Sender {
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.klose.concurrency.state.dependency;

/**
 *
 * @author klose
 * @param <V>
 */
public abstract class BaseBoundedBuffer<V> {
    private final V[] buf;
    private int tail;
    private int head;
    private int count;

    @SuppressWarnings("unchecked")
    protected BaseBoundedBuffer(int capacity) {
        this.buf = (V[]) new Object[capacity];
    }

    protected synchronized final void doPut(V v) {
        buf[tail] = v;
        if (++tail == buf.length) {
            tail = 0;
        }
        ++count;
    }

    protected synchronized final V doTake() {
        V v = buf[head];
        buf[head] = null;
        if (++head == buf.length) {
            head = 0;
        }
        --count;
        return v;
    }

    public synchronized final boolean isFull() {
        return count == buf.length;
    }

    public synchronized final boolean isEmpty() {
        return count == 0;
    }

}


text:
batchable
=========

Handle consecutive function calls at once.

```
npm install batchable --save
```

## Usage

```js
import batchable from 'batchable';

// Batched function is called when current call stack has cleared.
let batchedGreet = batchable((calls) => {
  // calls is an array of arguments objects converted to array.
  let names = calls.map(c => c[0]);
  let last = names.pop();

  console.log(`Hello ${names.join(', ')} and ${last}!`);

  calls.forEach(c => c[1]());
});

function greet(name = 'stranger', callback = () => {}) {
  batchedGreet(name, callback);
};

greet('Tim');
greet('Johnny');
greet('Peter', () => console.log('Peter has been greeted!'));

// -> Hello Tim, Johnny and Peter!
// -> Peter has been greeted!
```


text:
package com.qingbo.gingko.integration.shiro;

import static org.junit.Assert.assertTrue;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(locations = {
		"classpath:shiro.xml",
		})
public class SecurityTester extends BaseTester {
	@Test
	public void login() {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("admin", "123456");
        try {
            subject.login(token);
            assertTrue(subject.isAuthenticated());
            assertTrue(subject.hasRole("A"));
            subject.checkPermission("*:*");
            subject.checkPermission("user:*");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
        }
	}
}


text:
package org.inferred.freebuilder.processor.model;

import com.google.common.collect.ImmutableList;

import org.inferred.freebuilder.processor.source.Partial;

import java.util.List;

import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ElementVisitor;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;

public abstract class TypeParameterElementImpl implements TypeParameterElement {

  public static TypeParameterElementImpl newTypeParameterElement(String variableName) {
    return Partial.of(TypeParameterElementImpl.class, variableName);
  }

  private final String variableName;

  TypeParameterElementImpl(String variableName) {
    this.variableName = variableName;
  }

  @Override
  public TypeVariable asType() {
    return TypeVariableImpl.newTypeVariable(variableName);
  }

  @Override
  public ElementKind getKind() {
    return ElementKind.TYPE_PARAMETER;
  }

  @Override
  public Name getSimpleName() {
    return new NameImpl(variableName);
  }

  @Override
  public <R, P> R accept(ElementVisitor<R, P> v, P p) {
    return v.visitTypeParameter(this, p);
  }

  @Override
  public List<TypeMirror> getBounds() {
    return ImmutableList.of();
  }

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


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Linn. Soc. London, Bot. II 1: 126 (1876)

#### Original name
Hexagonia kurzii Curr.

### Remarks
null


text:
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using Microsoft.PSharp;

namespace ReplicatingStorage
{
    internal class Environment : Machine
    {
        #region events

        public class NotifyNode : Event
        {
            public MachineId Node;

            public NotifyNode(MachineId node)
                : base()
            {
                this.Node = node;
            }
        }

        public class FaultInject : Event { }

        private class CreateFailure : Event { }
        private class LocalEvent : Event { }

        #endregion

        #region fields

        private MachineId NodeManager;
        private int NumberOfReplicas;

        private List<MachineId> AliveNodes;
        private int NumberOfFaults;

        private MachineId Client;

        /// <summary>
        /// The failure timer.
        /// </summary>
        private MachineId FailureTimer;

        #endregion

        #region states

        [Start]
        [OnEntry(nameof(EntryOnInit))]
        [OnEventGotoState(typeof(LocalEvent), typeof(Configuring))]
        class Init : MachineState { }

        void EntryOnInit()
        {
            this.NumberOfReplicas = 3;
            this.NumberOfFaults = 1;
            this.AliveNodes = new List<MachineId>();

            this.Monitor<LivenessMonitor>(new LivenessMonitor.ConfigureEvent(this.NumberOfReplicas));

            this.NodeManager = this.CreateMachine(typeof(NodeManager));
            this.Client = this.CreateMachine(typeof(Client));

            this.Raise(new LocalEvent());
        }

        [OnEntry(nameof(ConfiguringOnInit))]
        [OnEventGotoState(typeof(LocalEvent), typeof(Active))]
        [DeferEvents(typeof(FailureTimer.TimeoutEvent))]
        class Configuring : MachineState { }

        void ConfiguringOnInit()
        {
            this.Send(this.NodeManager, new NodeManager.ConfigureEvent(this.Id, this.NumberOfReplicas));
            this.Send(this.Client, new Client.ConfigureEvent(this.NodeManager));
            this.Raise(new LocalEvent());
        }

        [OnEventDoAction(typeof(NotifyNode), nameof(UpdateAliveNodes))]
        [OnEventDoAction(typeof(FailureTimer.TimeoutEvent), nameof(InjectFault))]
        class Active : MachineState { }

        void UpdateAliveNodes()
        {
            var node = (this.ReceivedEvent as NotifyNode).Node;
            this.AliveNodes.Add(node);

            if (this.AliveNodes.Count == this.NumberOfReplicas &&
                this.FailureTimer == null)
            {
                this.FailureTimer = this.CreateMachine(typeof(FailureTimer));
                this.Send(this.FailureTimer, new FailureTimer.ConfigureEvent(this.Id));
            }
        }

        void InjectFault()
        {
            if (this.NumberOfFaults == 0 ||
                this.AliveNodes.Count == 0)
            {
                return;
            }

            int nodeId = this.RandomInteger(this.AliveNodes.Count);
            var node = this.AliveNodes[nodeId];

            this.Logger.WriteLine("\n [Environment] injecting fault.\n");

            this.Send(node, new FaultInject());
            this.Send(this.NodeManager, new NodeManager.NotifyFailure(node));
            this.AliveNodes.Remove(node);

            this.NumberOfFaults--;
            if (this.NumberOfFaults == 0)
            {
                this.Send(this.FailureTimer, new Halt());
            }
        }

        #endregion
    }
}


text:
<!DOCTYPE html>
<style>
  path {
    animation: inset-anim 2s linear;
  }
  @keyframes inset-anim {
    from { clip-path: inset(10%); }
    to   { clip-path: inset(20%); }
  }
</style>
<script src="../resources/text-based-repaint.js"></script>
<script>
  outputRepaintRects = false;
  onload = runRepaintTest;
  function repaintTest() {
  };
</script>
Test for crbug.com/448227: This test passes if it does not crash.
<svg>
  <path d="M0 0"/>
</svg>


text:
package com.alevat.apeman.repositories;

import com.alevat.apeman.PersistenceTestApplication;
import com.alevat.apeman.entities.Project;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.inject.Inject;
import java.util.List;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = PersistenceTestApplication.class)
public class ProjectRepositoryTest {

    @Inject
    private ProjectRepository repository;

    @Test
    public void save_ShouldSetUuid() {
        Project project = new Project();
        Project savedProject = repository.save(project);
        assertThat(savedProject.getUuid(), is(notNullValue()));
    }

    @Test
    public void findAll_ShouldFindSavedProject() {
        Project project = new Project();
        Project savedProject = repository.save(project);
        List<Project> projects = repository.findAll();
        assertThat(projects, hasItem(savedProject));
    }

}


text:
using namespace llvm;

namespace {

ErrorOr<int> t1() { return 1; }
ErrorOr<int> t2() { return errc::invalid_argument; }

TEST(ErrorOr, SimpleValue) {
  ErrorOr<int> a = t1();
  // FIXME: This is probably a bug in gtest. EXPECT_TRUE should expand to
  // include the !! to make it friendly to explicit bool operators.
  EXPECT_TRUE(!!a);
  EXPECT_EQ(1, *a);

  ErrorOr<int> b = a;
  EXPECT_EQ(1, *b);

  a = t2();
  EXPECT_FALSE(a);
  EXPECT_EQ(a.getError(), errc::invalid_argument);
#ifdef EXPECT_DEBUG_DEATH
  EXPECT_DEBUG_DEATH(*a, "Cannot get value when an error exists");
#endif
}

ErrorOr<std::unique_ptr<int> > t3() {
  return std::unique_ptr<int>(new int(3));
}

TEST(ErrorOr, Types) {
  int x;
  ErrorOr<int&> a(x);
  *a = 42;
  EXPECT_EQ(42, x);

  // Move only types.
  EXPECT_EQ(3, **t3());
}

struct B {};
struct D : B {};

TEST(ErrorOr, Covariant) {
  ErrorOr<B*> b(ErrorOr<D*>(nullptr));
  b = ErrorOr<D*>(nullptr);

  ErrorOr<std::unique_ptr<B> > b1(ErrorOr<std::unique_ptr<D> >(nullptr));
  b1 = ErrorOr<std::unique_ptr<D> >(nullptr);

  ErrorOr<std::unique_ptr<int>> b2(ErrorOr<int *>(nullptr));
  ErrorOr<int *> b3(nullptr);
  ErrorOr<std::unique_ptr<int>> b4(b3);
}

TEST(ErrorOr, Comparison) {
  ErrorOr<int> x(errc::no_such_file_or_directory);
  EXPECT_EQ(x, errc::no_such_file_or_directory);
}

TEST(ErrorOr, ImplicitConversion) {
  ErrorOr<std::string> x("string literal");
  EXPECT_TRUE(!!x);
}

TEST(ErrorOr, ImplicitConversionCausesMove) {
  struct Source {};
  struct Destination {
    Destination(const Source&) {}
    Destination(Source&&) = delete;
  };
  Source s;
  ErrorOr<Destination> x = s;
  EXPECT_TRUE(!!x);
}

TEST(ErrorOr, ImplicitConversionNoAmbiguity) {
  struct CastsToErrorCode {
    CastsToErrorCode() = default;
    CastsToErrorCode(std::error_code) {}
    operator std::error_code() { return errc::invalid_argument; }
  } casts_to_error_code;
  ErrorOr<CastsToErrorCode> x1(casts_to_error_code);
  ErrorOr<CastsToErrorCode> x2 = casts_to_error_code;
  ErrorOr<CastsToErrorCode> x3 = {casts_to_error_code};
  ErrorOr<CastsToErrorCode> x4{casts_to_error_code};
  ErrorOr<CastsToErrorCode> x5(errc::no_such_file_or_directory);
  ErrorOr<CastsToErrorCode> x6 = errc::no_such_file_or_directory;
  ErrorOr<CastsToErrorCode> x7 = {errc::no_such_file_or_directory};
  ErrorOr<CastsToErrorCode> x8{errc::no_such_file_or_directory};
  EXPECT_TRUE(!!x1);
  EXPECT_TRUE(!!x2);
  EXPECT_TRUE(!!x3);
  EXPECT_TRUE(!!x4);
  EXPECT_FALSE(x5);
  EXPECT_FALSE(x6);
  EXPECT_FALSE(x7);
  EXPECT_FALSE(x8);
}

// ErrorOr<int*> x(nullptr);
// ErrorOr<std::unique_ptr<int>> y = x; // invalid conversion
static_assert(
    !std::is_convertible<const ErrorOr<int *> &,
                         ErrorOr<std::unique_ptr<int>>>::value,
    "do not invoke explicit ctors in implicit conversion from lvalue");

// ErrorOr<std::unique_ptr<int>> y = ErrorOr<int*>(nullptr); // invalid
//                                                           // conversion
static_assert(
    !std::is_convertible<ErrorOr<int *> &&,
                         ErrorOr<std::unique_ptr<int>>>::value,
    "do not invoke explicit ctors in implicit conversion from rvalue");

// ErrorOr<int*> x(nullptr);
// ErrorOr<std::unique_ptr<int>> y;
// y = x; // invalid conversion
static_assert(!std::is_assignable<ErrorOr<std::unique_ptr<int>>,
                                  const ErrorOr<int *> &>::value,
              "do not invoke explicit ctors in assignment");

// ErrorOr<std::unique_ptr<int>> x;
// x = ErrorOr<int*>(nullptr); // invalid conversion
static_assert(!std::is_assignable<ErrorOr<std::unique_ptr<int>>,
                                  ErrorOr<int *> &&>::value,
              "do not invoke explicit ctors in assignment");
} // end anon namespace


text:
CodeMirror.defineMode("while", function() {
  return {
    token: function(stream) {
      var ch = stream.next();
      stream.skipToEnd();
      return null;
    }
  };
});

CodeMirror.defineMIME("text/x-while", "while");


text:
import os
import requests
import json

__author__ = 'Andrea Rossi'
__description = '''\
    DataHub is a web application for easily organising translation resources.
    It is developed within the project ModernMT and is specifically tailored
    with the needs of translation resources management in mind.
    DataHub main features include:
        - storing resources;
        - searching for resources;
        - downloading resources;
        - resource statistics;
    These operations can be performed either from the application GUI or through REST APIs.

    For more details, visit our github page: 'https://github.com/ModernMT/DataHub'
'''

#
class DataHub:
    def __init__(self, host='datahub.mmt.rocks', port=80):
        self.api = Api(host, port)
        self.auth = None

    # ================ API CALLING METHODS ================ #

    def authenticate(self, username=None, password=None):
        self.auth = self.api.login(username, password)['credentials']
        return self.auth

    def validate_auth(self, access_token):
        if self.api.check_auth(access_token):
            self.auth = access_token
        return self.auth

    def generate_collection(self, source, target, source_words, target_words):
        return self.api.get_collection(source, target, source_words, target_words, self.auth)

    def download_collection(self, collection, destination_folder, destination_filename):
        return self.api.download_collection(str(collection["id"]), collection["name"],
                                            destination_folder, destination_filename, self.auth)

# ================ SCRIPT-AVAILABLE API ================ #
class Api:
    def __init__(self, host, port):
        self._api_url = 'http://' + os.path.join(host + ":" + str(port), "api")

    def login(self, username, password):
        url = os.path.join(self._api_url, "login")
        data = {'username': username, 'password': password}
        response = requests.post(url=url, data=data)
        if response.status_code != 200:
            raise DataHubException("Authentication error: %s" % json.loads(response.content))
        return json.loads(response.text)

    def check_auth(self, access_token):
        url = os.path.join(self._api_url, "users", "me")
        response = requests.get(url=url, headers={"Authorization": access_token})
        if response.status_code != 200:
            raise DataHubException("Authentication error: %s" % json.loads(response.content))
        return True

    def get_collection(self, source, target, source_words, target_words, auth):
        url = os.path.join(self._api_url, "collections")
        data = {'source': source, 'target': target, 'sourceWords': source_words, 'targetWords': target_words}
        response = requests.get(url=url, params=data, headers={"Authorization": auth})
        if response.status_code != 200:
            raise DataHubException("Api error: %s" % json.loads(response.content))
        return json.loads(response.text)

    def download_collection(self, collection_id, collection_name, destination_folder, destination_filename, auth):
        if destination_filename is None:
            destination_filename = "datahub_collection_" + collection_name + ".zip"

        destination_filepath = os.path.join(destination_folder, destination_filename)
        url = os.path.join(self._api_url, "collections", collection_id, "corpora")
        response = requests.get(url=url, headers={"Authorization": auth}, stream=True)

        with open(destination_filepath, 'wb') as f:
            for chunk in response.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)

        if response.status_code != 200:
            raise DataHubException(response.reason)
        return destination_filepath

class DataHubException(Exception):
    def __init__(self, *args, **kwargs):
        super(DataHubException, self).__init__(*args, **kwargs)


text:
package com.orientechnologies.orient.core.db.record.ridbag.sbtree;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import com.orientechnologies.common.profiler.OProfilerMBean;
import com.orientechnologies.common.serialization.types.OBooleanSerializer;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.index.sbtree.OSBTreeMapEntryIterator;
import com.orientechnologies.orient.core.index.sbtree.OTreeInternal;
import com.orientechnologies.orient.core.index.sbtree.local.OSBTreeException;
import com.orientechnologies.orient.core.index.sbtreebonsai.local.OBonsaiBucketPointer;
import com.orientechnologies.orient.core.index.sbtreebonsai.local.OSBTreeBonsai;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLinkSerializer;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocalAbstract;

/**
 * Persistent Set<OIdentifiable> implementation that uses the SBTree to handle entries in persistent way.
 *
 * @author Artem Orobets
 */
public class OIndexRIDContainerSBTree implements Set<OIdentifiable> {
  public static final String                    INDEX_FILE_EXTENSION = ".irs";
  private OSBTreeBonsai<OIdentifiable, Boolean> tree;

  protected static final OProfilerMBean         PROFILER             = Orient.instance().getProfiler();

  public OIndexRIDContainerSBTree(long fileId) {
    tree = new OSBTreeBonsai<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, false);

    tree.create(fileId, OLinkSerializer.INSTANCE, OBooleanSerializer.INSTANCE,
        (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying());
  }

  public OIndexRIDContainerSBTree(long fileId, OBonsaiBucketPointer rootPointer) {
    tree = new OSBTreeBonsai<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, false);
    tree.load(fileId, rootPointer, (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying());
  }

  public OIndexRIDContainerSBTree(String file, OBonsaiBucketPointer rootPointer) {
    tree = new OSBTreeBonsai<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, false);

    final OStorageLocalAbstract storage = (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage()
        .getUnderlying();
    final long fileId;
    try {
      fileId = storage.getDiskCache().openFile(file + INDEX_FILE_EXTENSION);
    } catch (IOException e) {
      throw new OSBTreeException("Exception during loading of sbtree " + file, e);
    }
    tree.load(fileId, rootPointer, storage);
  }

  public OBonsaiBucketPointer getRootPointer() {
    return tree.getRootBucketPointer();
  }

  @Override
  public int size() {
    return (int) tree.size();
  }

  @Override
  public boolean isEmpty() {
    return tree.size() == 0L;
  }

  @Override
  public boolean contains(Object o) {
    return o instanceof OIdentifiable && contains((OIdentifiable) o);
  }

  public boolean contains(OIdentifiable o) {
    return tree.get(o) != null;
  }

  @Override
  public Iterator<OIdentifiable> iterator() {
    return new TreeKeyIterator(tree, false);
  }

  @Override
  public Object[] toArray() {
    // TODO replace with more efficient implementation

    final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size());

    for (OIdentifiable identifiable : this) {
      list.add(identifiable);
    }

    return list.toArray();
  }

  @Override
  public <T> T[] toArray(T[] a) {
    // TODO replace with more efficient implementation.

    final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size());

    for (OIdentifiable identifiable : this) {
      list.add(identifiable);
    }

    return list.toArray(a);
  }

  @Override
  public boolean add(OIdentifiable oIdentifiable) {
    return this.tree.put(oIdentifiable, Boolean.TRUE);
  }

  @Override
  public boolean remove(Object o) {
    return o instanceof OIdentifiable && remove((OIdentifiable) o);
  }

  public boolean remove(OIdentifiable o) {
    return tree.remove(o) != null;
  }

  @Override
  public boolean containsAll(Collection<?> c) {
    for (Object e : c)
      if (!contains(e))
        return false;
    return true;
  }

  @Override
  public boolean addAll(Collection<? extends OIdentifiable> c) {
    boolean modified = false;
    for (OIdentifiable e : c)
      if (add(e))
        modified = true;
    return modified;
  }

  @Override
  public boolean retainAll(Collection<?> c) {
    boolean modified = false;
    Iterator<OIdentifiable> it = iterator();
    while (it.hasNext()) {
      if (!c.contains(it.next())) {
        it.remove();
        modified = true;
      }
    }
    return modified;
  }

  @Override
  public boolean removeAll(Collection<?> c) {
    boolean modified = false;
    for (Object o : c) {
      modified |= remove(o);
    }

    return modified;
  }

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

  public void delete() {
    tree.delete();
  }

  public String getName() {
    return tree.getName();
  }

  private static class TreeKeyIterator implements Iterator<OIdentifiable> {
    private final boolean                                   autoConvertToRecord;
    private OSBTreeMapEntryIterator<OIdentifiable, Boolean> entryIterator;

    public TreeKeyIterator(OTreeInternal<OIdentifiable, Boolean> tree, boolean autoConvertToRecord) {
      entryIterator = new OSBTreeMapEntryIterator<OIdentifiable, Boolean>(tree);
      this.autoConvertToRecord = autoConvertToRecord;
    }

    @Override
    public boolean hasNext() {
      return entryIterator.hasNext();
    }

    @Override
    public OIdentifiable next() {
      final OIdentifiable identifiable = entryIterator.next().getKey();
      if (autoConvertToRecord)
        return identifiable.getRecord();
      else
        return identifiable;
    }

    @Override
    public void remove() {
      entryIterator.remove();
    }
  }
}