text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-prophets-and-apostles/faust-james-esdras-1920-2007" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-prophets-and-apostles/faust-james-esdras-1920-2007</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Faust, James Esdras 1920-2007</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-prophets-and-apostles/faust-james-esdras-1920-2007</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-prophets-and-apostles/faust-james-esdras-1920-2007</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
require 'spec_helper'

describe SQL::Generator::Direction, '#visit_axiom_relation_operation_sorted_descending' do
  subject { object.visit_axiom_relation_operation_sorted_descending(direction) }

  let(:described_class) { Class.new(SQL::Generator::Visitor) { include SQL::Generator::Direction } }
  let(:direction)       { Attribute::Integer.new(:id).desc                                         }
  let(:object)          { described_class.new                                                      }

  it_should_behave_like 'a generated SQL expression'

  its(:to_s) { should eql('"id" DESC') }
end

redpajama_set_name: RedPajamaGithub


text:
//
//  JXIMAP.m
//  JXMail
//
//  Created by andy on 9/8/14.
//  Copyright (c) 2014 JianXiang Jin. All rights reserved.
//

#import "JXIMAP.h"

@implementation JXIMAP

- (id)init
{
    if (self = [super init]) {
        _session = [[MCOIMAPSession alloc] init];
        _session.hostname = IMAP_HOSTNAME;
        _session.port = IMAP_PORT;
        _session.connectionType = MCOConnectionTypeTLS;

        if ([JXAccountManager shareManager].currentAccount) {
            JXAccount *account = [JXAccountManager shareManager].currentAccount;
            _session.username = account.username;
            _session.password = account.password;
        }
    }
    return self;
}

/**
 *  验证用户信息
 */
- (void)checkAccount:(JXAccount *)account accountBlock:(JXCheckAccountBlock)checkAccountBlock
{
    _session.username = account.username;
    _session.password = account.password;

    // 验证用户基本信息
	[[_session checkAccountOperation] start:^(NSError *error) {

        // 验证成功
		if (error == nil) {

            [JXAccountManager shareManager].currentAccount = account;
            [[JXAccountManager shareManager] addAccount:account];

            checkAccountBlock(nil);

        // 验证失败
		} else {

            checkAccountBlock(error);
		}

    }];
}

/**
 *  接收邮件
 */
- (void)receive:(JXReceiveBlock)receiveBlock
{
    MCOIMAPMessagesRequestKind requestKind = (MCOIMAPMessagesRequestKind)
	(  MCOIMAPMessagesRequestKindHeaders
     | MCOIMAPMessagesRequestKindStructure
     | MCOIMAPMessagesRequestKindInternalDate
     | MCOIMAPMessagesRequestKindHeaderSubject
     | MCOIMAPMessagesRequestKindFlags);

    NSString *folder = MAIL_FOLDER_INBOX;
    MCOIndexSet *uids =
    [MCOIndexSet indexSetWithRange:MCORangeMake(1, UINT64_MAX)];

    MCOIMAPFetchMessagesOperation *fetchOperation =
    [_session fetchMessagesByUIDOperationWithFolder:folder
                                           requestKind:requestKind
                                                  uids:uids];
    [fetchOperation start:^(NSError * error, NSArray * fetchedMessages, MCOIndexSet * vanishedMessages) {

        if (error) {
            receiveBlock(error, nil);
            return ;
        }

        receiveBlock(nil, fetchedMessages);
    }];
}

/**
 *  发送邮件
 */
- (void)sendMail:(JXMailPacket *)packet compelete:(JXSendBlock)sendBlock
{

}

@end


text:
import {DevelopmentModeLog, DevelopmentModeLogButtonSet} from './development-ui';
import {EventType, dispatch} from './events';
import {ProgressBar} from './progress-bar';
import {Services} from '../../../src/services';
import {dev} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {getMode} from '../../../src/mode';
import {matches} from '../../../src/dom';
import {renderAsElement} from './simple-template';

const MUTE_CLASS = 'i-amphtml-story-mute-audio-control';

const UNMUTE_CLASS = 'i-amphtml-story-unmute-audio-control';

/** @private @const {!./simple-template.ElementDef} */
const TEMPLATE = {
  tag: 'aside',
  attrs: dict(
      {'class': 'i-amphtml-story-system-layer i-amphtml-story-system-reset'}),
  children: [
    {
      tag: 'div',
      attrs: dict({'class': 'i-amphtml-story-ui-left'}),
      children: [
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': UNMUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': MUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
      ],
    },
    {
      tag: 'div',
      attrs: dict({'class': 'i-amphtml-story-ui-right'}),
      children: [
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': UNMUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
        {
          tag: 'div',
          attrs: dict({
            'role': 'button',
            'class': MUTE_CLASS + ' i-amphtml-story-button',
          }),
        },
      ],
    },
  ],
};

/**
 * System Layer (i.e. UI Chrome) for <amp-story>.
 * Chrome contains:
 *   - mute/unmute button
 *   - story progress bar
 *   - bookend close butotn
 */
export class SystemLayer {
  /**
   * @param {!Window} win
   */
  constructor(win) {
    /** @private {!Window} */
    this.win_ = win;

    /** @private {boolean} */
    this.isBuilt_ = false;

    /** @private {?Element} */
    this.root_ = null;

    /** @private {?Element} */
    this.muteAudioBtn_ = null;

    /** @private {?Element} */
    this.unmuteAudioBtn_ = null;

    /** @private {?Element} */
    this.leftButtonTray_ = null;

    /** @private @const {!ProgressBar} */
    this.progressBar_ = ProgressBar.create(win);

    /** @private {!DevelopmentModeLog} */
    this.developerLog_ = DevelopmentModeLog.create(win);

    /** @private {!DevelopmentModeLogButtonSet} */
    this.developerButtons_ = DevelopmentModeLogButtonSet.create(win);
  }

  /**
   * @param {!Array<string>} pageIds the ids of each page in the story
   * @return {!Element}
   */
  build(pageIds) {
    if (this.isBuilt_) {
      return this.getRoot();
    }

    this.isBuilt_ = true;

    this.root_ = renderAsElement(this.win_.document, TEMPLATE);

    this.root_.insertBefore(
        this.progressBar_.build(pageIds), this.root_.lastChild);

    this.leftButtonTray_ =
        this.root_.querySelector('.i-amphtml-story-ui-left');

    this.buildForDevelopmentMode_();

    this.addEventHandlers_();

    return this.getRoot();
  }

  /**
   * @private
   */
  buildForDevelopmentMode_() {
    if (!getMode().development) {
      return;
    }

    this.leftButtonTray_.appendChild(this.developerButtons_.build(
        this.developerLog_.toggle.bind(this.developerLog_)));
    this.root_.appendChild(this.developerLog_.build());
  }

  /**
   * @private
   */
  addEventHandlers_() {
    // TODO(alanorozco): Listen to tap event properly (i.e. fastclick)
    this.root_.addEventListener('click', e => {
      const target = dev().assertElement(e.target);

      if (matches(target, `.${MUTE_CLASS}, .${MUTE_CLASS} *`)) {
        this.onMuteAudioClick_(e);
      } else if (matches(target, `.${UNMUTE_CLASS}, .${UNMUTE_CLASS} *`)) {
        this.onUnmuteAudioClick_(e);
      }
    });
  }

  /**
   * @return {!Element}
   */
  getRoot() {
    return dev().assertElement(this.root_);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onMuteAudioClick_(e) {
    this.dispatch_(EventType.MUTE, e);
  }

  /**
   * @param {!Event} e
   * @private
   */
  onUnmuteAudioClick_(e) {
    this.dispatch_(EventType.UNMUTE, e);
  }

  /**
   * @param {string} eventType
   * @param {!Event=} opt_event
   * @private
   */
  dispatch_(eventType, opt_event) {
    if (opt_event) {
      dev().assert(opt_event).stopPropagation();
    }

    dispatch(this.getRoot(), eventType, /* opt_bubbles */ true);
  }

  /**
   * @param {string} pageId The page id of the new active page.
   * @public
   */
  setActivePageId(pageId) {
    // TODO(newmuis) avoid passing progress logic through system-layer
    this.progressBar_.setActiveSegmentId(pageId);
  }

  /**
   * @param {string} pageId The id of the page whose progress should be
   *     changed.
   * @param {number} progress A number from 0.0 to 1.0, representing the
   *     progress of the current page.
   * @public
   */
  updateProgress(pageId, progress) {
    // TODO(newmuis) avoid passing progress logic through system-layer
    this.progressBar_.updateProgress(pageId, progress);
  }

  /**
   * @param {!./logging.AmpStoryLogEntryDef} logEntry
   * @private
   */
  logInternal_(logEntry) {
    this.developerButtons_.log(logEntry);
    this.developerLog_.log(logEntry);
  }

  /**
   * Logs an array of entries to the developer logs.
   * @param {!Array<!./logging.AmpStoryLogEntryDef>} logEntries
   */
  logAll(logEntries) {
    if (!getMode().development) {
      return;
    }

    Services.vsyncFor(this.win_).mutate(() => {
      logEntries.forEach(logEntry => this.logInternal_(logEntry));
    });
  }

  /**
   * Logs a single entry to the developer logs.
   * @param {!./logging.AmpStoryLogEntryDef} logEntry
   */
  log(logEntry) {
    if (!getMode().development) {
      return;
    }

    this.logInternal_(logEntry);
  }

  /**
   * Clears any state held by the developer log or buttons.
   */
  resetDeveloperLogs() {
    if (!getMode().development) {
      return;
    }

    this.developerButtons_.clear();
    this.developerLog_.clear();
  }

  /**
   * Sets the string providing context for the developer logs window.  This is
   * often the name or ID of the element that all logs are for (e.g. the page).
   * @param {string} contextString
   */
  setDeveloperLogContextString(contextString) {
    if (!getMode().development) {
      return;
    }

    this.developerLog_.setContextString(contextString);
  }

  /**
   * Toggles the visibility of the developer log.
   * @private
   */
  toggleDeveloperLog_() {
    if (!getMode().development) {
      return;
    }

    this.developerLog_.toggle();
  }

  /**
   * Hides the developer log in the UI.
   */
  hideDeveloperLog() {
    if (!getMode().development) {
      return;
    }

    this.developerLog_.hide();
  }
}


text:
"use strict";

(function() {

// <input type="file" multiple/>
dom.playlistInputFile.change( function() {
	ui.listDragOver( dom.screen );
	api.playlist.addFiles( this.files, true );
});

dom.ctrlOpenBtn.click( api.playlist.dialogueFiles );

// This shortcut doesn't work on Firefox (security purpose).
api.keyboard.shortcut( "ctrl+o", function() {
	if ( window.isFirefox ) {
		api.error.throw( "CTRLO_SHORTCUT" );
	}
	api.playlist.dialogueFiles();
});

var
	dragX,
	dragY,
	autoplay,
	isDragging,
	jqFileDragging,
	dragOutside,
	fileHeight
;

function dragend() {
	if ( jqFileDragging ) {
		ui.fileReattach( jqFileDragging );
		if ( autoplay ) {
			api.playlist.select( jqFileDragging[ 0 ] );
		}
		jqFileDragging = null;
	}
	ui.listDragOver( null );
	isDragging = false;
	dragOutside = false;
}

function updateFileHeight() {
	fileHeight = Math.max(
		ui.jqFiles.outerHeight(),
		ui.jqFiles.eq( 1 ).outerHeight()
	);
}

dom.body.on({

	// When we are dragging over the player (not the playlist).
	dragover: function( e ) {
		var
			jq,
			listY,
			x = e.pageX,
			y = e.pageY
		;

		isDragging = true;

		// This if prevent ondragover to be called every ~100ms.
		if ( x !== dragX || y !== dragY ) {
			dragX = x;
			dragY = y;

			// Drag on the player.
			if ( !ui.listIsOpen || x < ( 1 - ui.percListWidth / 100 ) * ui.pxScreenWidth ) {
				autoplay = true;
				ui.listDragOver( dom.screen );

			// Drag on the playlist.
			} else {
				autoplay = false;
				listY = dom.playlistList.position().top;
				if ( y >= listY ) {
					y = y - listY + dom.playlistList[ 0 ].scrollTop;
					updateFileHeight();
					jq = ui.jqFiles.eq( Math.round( y / fileHeight ) );
					ui.listDragOver( jq[ 0 ] ? jq[ 0 ].jqThis : dom.playlistList );
				}
			}
		}

		// Prevent the browser to load the file directly in the tab.
		// e.preventDefault in the "drop" event is not enough.
		return false;
	},

	drop: function( e ) {
		e = e.originalEvent;
		var data = e && e.dataTransfer;

		if ( jqFileDragging ) {
			dragend();
		} else if ( data ) {
			// Chrome :
			if ( data.items ) {
				api.playlist.extractAddFiles( data.items, autoplay );
			// Everyone else :
			} else if ( data.files ) {
				if ( !data.files.length ) {
					// Folder detection for IE
					api.error.throw( "NO_FOLDERS" );
				} else {
					// Others browsers
					api.playlist.addFiles( data.files, autoplay );
				}
			}
		}
		isDragging =
		dragOutside = false;
		return false;
	},

	// dragstart/end concerns the internal dragndrop.
	// So they aren't called when you are dragging some files from your disk.
	dragstart: function( e ) {
		// If we drag out something directly out the window
		// the dragover event don't have the time to be fired.
		dragOutside = true;
		ui.listDragOver( dom.playlistList );

		isDragging = true;
		jqFileDragging = e.target.jqThis;
		ui.fileDetach( jqFileDragging );
	},
	dragend: function() {
		dragend();
		return false;
	},

	// cf. https://github.com/lolmaus/jquery.dragbetter
	// Detect when the mouse leave the window while dragging.
	dragbetterenter: function() {
		dragOutside = false;
	},
	dragbetterleave: function() {
		if ( isDragging ) {
			dragOutside = true;
			autoplay = false;
			ui.listDragOver( dom.playlistList );
		}
	},

	// Detect when we have dropped an intern file outside of the window.
	mousemove: function() {
		if ( dragOutside ) {
			dragend();
		}
	}
});

})();


text:
module example {

  import Pool = entitas.Pool;
  import Group = entitas.Group;
  import Entity = entitas.Entity;
  import Matcher = entitas.Matcher;
  import Exception = entitas.Exception;
  import TriggerOnEvent = entitas.TriggerOnEvent;
  import IInitializeSystem = entitas.IInitializeSystem;
  import IExecuteSystem = entitas.IExecuteSystem;
  import ISetPool = entitas.ISetPool;

  export class CollisionSystem implements IInitializeSystem, IExecuteSystem, ISetPool {

    protected pool: Pool;
    protected group: Group;
    protected bullets: Group;
    protected enemies: Group;
    private collisionPairs: Array<CollisionPair>;

    public setPool(pool: Pool) {
      this.pool = pool;
    }

    /**
     * Check for Collision
     */
    public execute() {
      var collisionPairs = this.collisionPairs;
      for (var i = 0, l = collisionPairs.length; l > i; i++) {
        collisionPairs[i].checkForCollisions();
      }
    }

    /**
     * Create collision handlers
     */
    public initialize() {
      this.pool.setScore(0);
      this.bullets = this.pool.getGroup(Matcher.Bullet);
      this.enemies = this.pool.getGroup(Matcher.Enemy);

      /** Check for bullets hitting enemy ship */
      this.collisionPairs = [];
      this.collisionPairs.push(new CollisionPair(this, this.bullets, this.enemies, {

        handleCollision: (bullet: Entity, ship: Entity) => {
          var bp: PositionComponent = bullet.position;
          var health: HealthComponent = ship.health;
          var position: PositionComponent = ship.position;
          var x = bp.x;
          var y = bp.y;

          this.pool.createSmallExplosion(x, y);
          var i = 5;
          while (--i > 0) this.pool.createParticle(x, y);

          bullet.setDestroy(true);
          health.health -= 1;
          if (health.health < 0) {
            var score: ScoreComponent = <ScoreComponent>(this.pool.score);
            this.pool.replaceScore(score.value + ship.health.maximumHealth);
            ship.setDestroy(true);
            this.pool.createBigExplosion(position.x, position.y);
          }
        }
      }));
    }
  }

  /**
   *
   */
  class CollisionPair {
    private groupEntitiesA: Group;
    private groupEntitiesB: Group;
    private handler: CollisionHandler;
    private cs: CollisionSystem;

    constructor(cs: CollisionSystem, group1, group2, handler: CollisionHandler) {
      this.groupEntitiesA = group1;
      this.groupEntitiesB = group2;
      this.handler = handler;
      this.cs = cs;
    }

    public checkForCollisions() {
      var handler = this.handler;
      var groupEntitiesA = this.groupEntitiesA.getEntities();
      var groupEntitiesB = this.groupEntitiesB.getEntities();
      var sizeA = groupEntitiesA.length;
      var sizeB = groupEntitiesB.length;

      for (var a = 0; sizeA > a; a++) {
        var entityA: Entity = groupEntitiesA[a];
        for (var b = 0; sizeB > b; b++) {
          var entityB: Entity = groupEntitiesB[b];
          if (this.collisionExists(entityA, entityB)) {
            handler.handleCollision(entityA, entityB);
          }
        }
      }
    }

    private collisionExists(e1: Entity, e2: Entity): boolean {

      if (e1 === null || e2 === null) return false;

      var p1: PositionComponent = e1.position;
      var p2: PositionComponent = e2.position;

      var b1: BoundsComponent = e1.bounds;
      var b2: BoundsComponent = e2.bounds;

      var a = p1.x - p2.x;
      var b = p1.y - p2.y;
      return Math.sqrt(a * a + b * b) - (b1.radius) < (b2.radius);
    }
  }

  interface CollisionHandler {
    handleCollision(a: Entity, b: Entity);
  }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var formatRelativeLocale = {
  lastWeek: "'last' eeee 'at' p",
  yesterday: "'yesterday at' p",
  today: "'today at' p",
  tomorrow: "'tomorrow at' p",
  nextWeek: "eeee 'at' p",
  other: 'P'
};

var formatRelative = function (token, _date, _baseDate, _options) {
  return formatRelativeLocale[token];
};

var _default = formatRelative;
exports.default = _default;
module.exports = exports.default;


text:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClientService } from '../shared/http-module/http.service';
import { BoardModel } from './../models/board.model';

@Injectable()
export class BoardService {
  constructor(private http: HttpClientService) {}

  /**
   * Usage: this is used to get the board API url from spacetemplate response
   * @param spaceTemplateApiUrl
   */
  getBoardApiUrl(spaceTemplateApiUrl: string) {
    return this.http.get<{ data: any }>(spaceTemplateApiUrl).pipe(
      map((resp) => resp.data),
      map((template) => template.relationships.workitemboards.links.related),
    );
  }

  /**
   * Usage: this is to get the list board for a sapce
   * @param boardUrl
   */
  getBoards(boardUrl: string): Observable<BoardModel> {
    return this.http.get<{ data: any; included: any[] }>(boardUrl).pipe(
      map((resp) => {
        return {
          data: resp.data,
          included: resp.included,
        };
      }),
    );
  }
}


text:
:host {
    display: block;
}

nof-action   {
    outline: none;
    display: block;
    float: left;
    padding: var(--space-3);
    margin-left: var(--space-1); /*Else hover outline is hidden on the left-most menu*/
    margin-right: var(--space-4);
    margin-bottom: var(--space-3); /*Else hover outline is hidden on the bottom*/
    font-weight: var(--font-weight-2)er;
    font-size: var(--font-size-2);
}


text:
package org.springframework.cloud.task.timestamp;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.annotation.Bean;

/**
 * Spring Boot Application that has tasks enabled.
 */
@EnableTask
@SpringBootApplication
@EnableConfigurationProperties({TimestampTaskProperties.class})
public class TaskApplication {

	private static final Log logger = LogFactory.getLog(TaskApplication.class);

	public static void main(String[] args) {
		SpringApplication.run(TaskApplication.class, args);
	}

	@Bean
	public TimestampTask timeStampTask() {
		return new TimestampTask();
	}

	/**
	 * A commandline runner that prints a timestamp.
	 */
	public static class TimestampTask implements CommandLineRunner {

		@Autowired
		private TimestampTaskProperties config;

		@Override
		public void run(String... strings) throws Exception {
			DateFormat dateFormat = new SimpleDateFormat(this.config.getFormat());
			logger.info(dateFormat.format(new Date()));
		}
	}
}


text:
Pilfer::Application.routes.draw do
  get '/dashboard', :to => 'dashboard#show', :as => :dashboard

  resources :apps do
    resources :profiles, :only => :show do
      member do
        get 'file'
      end
    end
  end

  post 'api/profiles' => 'api/profiles#create', :as => :api_profiles

  root :to => 'welcome#show', :as => :home_page
end


text:
@class NSString, SChartTheme;

@interface ShinobiCharts : NSObject
{
    NSString *_licenseKey;
    SChartTheme *_theme;
}

+ (id)theme;
+ (void)setTheme:(id)arg1;
+ (id)licenseKey;
+ (void)setLicenseKey:(id)arg1;
+ (id)sharedInstance;
@property(retain, nonatomic) SChartTheme *theme; // @synthesize theme=_theme;
@property(retain, nonatomic) NSString *licenseKey; // @synthesize licenseKey=_licenseKey;
- (void)dealloc;
- (id)init;

@end


text:
namespace Apache.Ignite.Core.Impl.Binary.IO
{
    using System;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Text;
    using Apache.Ignite.Core.Impl.Memory;

    /// <summary>
    /// Binary onheap stream.
    /// </summary>
    internal unsafe class BinaryHeapStream : IBinaryStream
    {
        /** Byte: zero. */
        private const byte ByteZero = 0;

        /** Byte: one. */
        private const byte ByteOne = 1;

        /** LITTLE_ENDIAN flag. */
        private static readonly bool LittleEndian = BitConverter.IsLittleEndian;

        /** Position. */
        private int _pos;

        /** Data array. */
        private byte[] _data;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="cap">Initial capacity.</param>
        public BinaryHeapStream(int cap)
        {
            Debug.Assert(cap >= 0);

            _data = new byte[cap];
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="data">Data array.</param>
        public BinaryHeapStream(byte[] data)
        {
            Debug.Assert(data != null);

            _data = data;
        }

        /// <summary>
        /// Internal routine to write byte array.
        /// </summary>
        /// <param name="val">Byte array.</param>
        /// <param name="data">Data pointer.</param>
        private static void WriteByteArray0(byte[] val, byte* data)
        {
            fixed (byte* val0 = val)
            {
                CopyMemory(val0, data, val.Length);
            }
        }

        /// <summary>
        /// Internal routine to read byte array.
        /// </summary>
        /// <param name="len">Array length.</param>
        /// <param name="data">Data pointer.</param>
        /// <returns>Byte array</returns>
        private static byte[] ReadByteArray0(int len, byte* data)
        {
            byte[] res = new byte[len];

            fixed (byte* res0 = res)
            {
                CopyMemory(data, res0, len);
            }

            return res;
        }

        /** <inheritdoc /> */
        public void WriteBool(bool val)
        {
            WriteByte(val ? ByteOne : ByteZero);
        }

        /** <inheritdoc /> */
        public bool ReadBool()
        {
            return ReadByte() == ByteOne;
        }

        /// <summary>
        /// Internal routine to write bool array.
        /// </summary>
        /// <param name="val">Bool array.</param>
        /// <param name="data">Data pointer.</param>
        private static void WriteBoolArray0(bool[] val, byte* data)
        {
            fixed (bool* val0 = val)
            {
                CopyMemory((byte*)val0, data, val.Length);
            }
        }

        /// <summary>
        /// Internal routine to read bool array.
        /// </summary>
        /// <param name="len">Array length.</param>
        /// <param name="data">Data pointer.</param>
        /// <returns>Bool array</returns>
        private static bool[] ReadBoolArray0(int len, byte* data)
        {
            bool[] res = new bool[len];

            fixed (bool* res0 = res)
            {
                CopyMemory(data, (byte*)res0, len);
            }

            return res;
        }

        /// <summary>
        /// Internal routine to write short value.
        /// </summary>
        /// <param name="val">Short value.</param>
        /// <param name="data">Data pointer.</param>
        private static void WriteShort0(short val, byte* data)
        {
            if (LittleEndian)
                *((short*)data) = val;
            else
            {
                byte* valPtr = (byte*)&val;

                data[0] = valPtr[1];
                data[1] = valPtr[0];
            }
        }

        /// <summary>
        /// Internal routine to read short value.
        /// </summary>
        /// <param name="data">Data pointer.</param>
        /// <returns>Short value</returns>
        private static short ReadShort0(byte* data)
        {
            short val;

            if (LittleEndian)
                val = *((short*)data);
            else
            {
                byte* valPtr = (byte*)&val;

                valPtr[0] = data[1];
                valPtr[1] = data[0];
            }

            return val;
        }

        /// <summary>
        /// Internal routine to write short array.
        /// </summary>
        /// <param name="val">Short array.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        private static void WriteShortArray0(short[] val, byte* data, int cnt)
        {
            if (LittleEndian)
            {
                fixed (short* val0 = val)
                {
                    CopyMemory((byte*)val0, data, cnt);
                }
            }
            else
            {
                byte* curPos = data;

                for (int i = 0; i < val.Length; i++)
                {
                    short val0 = val[i];

                    byte* valPtr = (byte*)&(val0);

                    *curPos++ = valPtr[1];
                    *curPos++ = valPtr[0];
                }
            }
        }

        /// <summary>
        /// Internal routine to read short array.
        /// </summary>
        /// <param name="len">Array length.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Short array</returns>
        private static short[] ReadShortArray0(int len, byte* data, int cnt)
        {
            short[] res = new short[len];

            if (LittleEndian)
            {
                fixed (short* res0 = res)
                {
                    CopyMemory(data, (byte*)res0, cnt);
                }
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    short val;

                    byte* valPtr = (byte*)&val;

                    valPtr[1] = *data++;
                    valPtr[0] = *data++;

                    res[i] = val;
                }
            }

            return res;
        }

        /** <inheritdoc /> */
        public void WriteChar(char val)
        {
            WriteShort(*(short*)(&val));
        }

        /** <inheritdoc /> */
        public char ReadChar()
        {
            short val = ReadShort();

            return *(char*)(&val);
        }

        /// <summary>
        /// Internal routine to write char array.
        /// </summary>
        /// <param name="val">Char array.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        private static void WriteCharArray0(char[] val, byte* data, int cnt)
        {
            if (LittleEndian)
            {
                fixed (char* val0 = val)
                {
                    CopyMemory((byte*)val0, data, cnt);
                }
            }
            else
            {
                byte* curPos = data;

                for (int i = 0; i < val.Length; i++)
                {
                    char val0 = val[i];

                    byte* valPtr = (byte*)&(val0);

                    *curPos++ = valPtr[1];
                    *curPos++ = valPtr[0];
                }
            }
        }

        /// <summary>
        /// Internal routine to read char array.
        /// </summary>
        /// <param name="len">Count.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Char array</returns>
        private static char[] ReadCharArray0(int len, byte* data, int cnt)
        {
            char[] res = new char[len];

            if (LittleEndian)
            {
                fixed (char* res0 = res)
                {
                    CopyMemory(data, (byte*)res0, cnt);
                }
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    char val;

                    byte* valPtr = (byte*)&val;

                    valPtr[1] = *data++;
                    valPtr[0] = *data++;

                    res[i] = val;
                }
            }

            return res;
        }

        /// <summary>
        /// Internal routine to write int value.
        /// </summary>
        /// <param name="val">Int value.</param>
        /// <param name="data">Data pointer.</param>
        private static void WriteInt0(int val, byte* data)
        {
            if (LittleEndian)
                *((int*)data) = val;
            else
            {
                byte* valPtr = (byte*)&val;

                data[0] = valPtr[3];
                data[1] = valPtr[2];
                data[2] = valPtr[1];
                data[3] = valPtr[0];
            }
        }

        /// <summary>
        /// Internal routine to read int value.
        /// </summary>
        /// <param name="data">Data pointer.</param>
        /// <returns>Int value</returns>
        public static int ReadInt0(byte* data) {
            int val;

            if (LittleEndian)
                val = *((int*)data);
            else
            {
                byte* valPtr = (byte*)&val;

                valPtr[0] = data[3];
                valPtr[1] = data[2];
                valPtr[2] = data[1];
                valPtr[3] = data[0];
            }

            return val;
        }

        /// <summary>
        /// Internal routine to write int array.
        /// </summary>
        /// <param name="val">Int array.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        private static void WriteIntArray0(int[] val, byte* data, int cnt)
        {
            if (LittleEndian)
            {
                fixed (int* val0 = val)
                {
                    CopyMemory((byte*)val0, data, cnt);
                }
            }
            else
            {
                byte* curPos = data;

                for (int i = 0; i < val.Length; i++)
                {
                    int val0 = val[i];

                    byte* valPtr = (byte*)&(val0);

                    *curPos++ = valPtr[3];
                    *curPos++ = valPtr[2];
                    *curPos++ = valPtr[1];
                    *curPos++ = valPtr[0];
                }
            }
        }

        /// <summary>
        /// Internal routine to read int array.
        /// </summary>
        /// <param name="len">Count.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Int array</returns>
        private static int[] ReadIntArray0(int len, byte* data, int cnt)
        {
            int[] res = new int[len];

            if (LittleEndian)
            {
                fixed (int* res0 = res)
                {
                    CopyMemory(data, (byte*)res0, cnt);
                }
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    int val;

                    byte* valPtr = (byte*)&val;

                    valPtr[3] = *data++;
                    valPtr[2] = *data++;
                    valPtr[1] = *data++;
                    valPtr[0] = *data++;

                    res[i] = val;
                }
            }

            return res;
        }

        /** <inheritdoc /> */
        public void WriteFloat(float val)
        {
            int val0 = *(int*)(&val);

            WriteInt(val0);
        }

        /** <inheritdoc /> */
        public float ReadFloat()
        {
            int val = ReadInt();

            return BinaryUtils.IntToFloatBits(val);
        }

        /// <summary>
        /// Internal routine to write float array.
        /// </summary>
        /// <param name="val">Int array.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        private static void WriteFloatArray0(float[] val, byte* data, int cnt)
        {
            if (LittleEndian)
            {
                fixed (float* val0 = val)
                {
                    CopyMemory((byte*)val0, data, cnt);
                }
            }
            else
            {
                byte* curPos = data;

                for (int i = 0; i < val.Length; i++)
                {
                    float val0 = val[i];

                    byte* valPtr = (byte*)&(val0);

                    *curPos++ = valPtr[3];
                    *curPos++ = valPtr[2];
                    *curPos++ = valPtr[1];
                    *curPos++ = valPtr[0];
                }
            }
        }

        /// <summary>
        /// Internal routine to read float array.
        /// </summary>
        /// <param name="len">Count.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Float array</returns>
        private static float[] ReadFloatArray0(int len, byte* data, int cnt)
        {
            float[] res = new float[len];

            if (LittleEndian)
            {
                fixed (float* res0 = res)
                {
                    CopyMemory(data, (byte*)res0, cnt);
                }
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    int val;

                    byte* valPtr = (byte*)&val;

                    valPtr[3] = *data++;
                    valPtr[2] = *data++;
                    valPtr[1] = *data++;
                    valPtr[0] = *data++;

                    res[i] = val;
                }
            }

            return res;
        }

        /// <summary>
        /// Internal routine to write long value.
        /// </summary>
        /// <param name="val">Long value.</param>
        /// <param name="data">Data pointer.</param>
        private static void WriteLong0(long val, byte* data)
        {
            if (LittleEndian)
                *((long*)data) = val;
            else
            {
                byte* valPtr = (byte*)&val;

                data[0] = valPtr[7];
                data[1] = valPtr[6];
                data[2] = valPtr[5];
                data[3] = valPtr[4];
                data[4] = valPtr[3];
                data[5] = valPtr[2];
                data[6] = valPtr[1];
                data[7] = valPtr[0];
            }
        }

        /// <summary>
        /// Internal routine to read long value.
        /// </summary>
        /// <param name="data">Data pointer.</param>
        /// <returns>Long value</returns>
        private static long ReadLong0(byte* data)
        {
            long val;

            if (LittleEndian)
                val = *((long*)data);
            else
            {
                byte* valPtr = (byte*)&val;

                valPtr[0] = data[7];
                valPtr[1] = data[6];
                valPtr[2] = data[5];
                valPtr[3] = data[4];
                valPtr[4] = data[3];
                valPtr[5] = data[2];
                valPtr[6] = data[1];
                valPtr[7] = data[0];
            }

            return val;
        }

        /// <summary>
        /// Internal routine to write long array.
        /// </summary>
        /// <param name="val">Long array.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        private static void WriteLongArray0(long[] val, byte* data, int cnt)
        {
            if (LittleEndian)
            {
                fixed (long* val0 = val)
                {
                    CopyMemory((byte*)val0, data, cnt);
                }
            }
            else
            {
                byte* curPos = data;

                for (int i = 0; i < val.Length; i++)
                {
                    long val0 = val[i];

                    byte* valPtr = (byte*)&(val0);

                    *curPos++ = valPtr[7];
                    *curPos++ = valPtr[6];
                    *curPos++ = valPtr[5];
                    *curPos++ = valPtr[4];
                    *curPos++ = valPtr[3];
                    *curPos++ = valPtr[2];
                    *curPos++ = valPtr[1];
                    *curPos++ = valPtr[0];
                }
            }
        }

        /// <summary>
        /// Internal routine to read long array.
        /// </summary>
        /// <param name="len">Count.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Long array</returns>
        private static long[] ReadLongArray0(int len, byte* data, int cnt)
        {
            long[] res = new long[len];

            if (LittleEndian)
            {
                fixed (long* res0 = res)
                {
                    CopyMemory(data, (byte*)res0, cnt);
                }
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    long val;

                    byte* valPtr = (byte*)&val;

                    valPtr[7] = *data++;
                    valPtr[6] = *data++;
                    valPtr[5] = *data++;
                    valPtr[4] = *data++;
                    valPtr[3] = *data++;
                    valPtr[2] = *data++;
                    valPtr[1] = *data++;
                    valPtr[0] = *data++;

                    res[i] = val;
                }
            }

            return res;
        }

        /** <inheritdoc /> */
        public void WriteDouble(double val)
        {
            long val0 = *(long*)(&val);

            WriteLong(val0);
        }

        /** <inheritdoc /> */
        public double ReadDouble()
        {
            long val = ReadLong();

            return BinaryUtils.LongToDoubleBits(val);
        }

        /// <summary>
        /// Internal routine to write double array.
        /// </summary>
        /// <param name="val">Double array.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        private static void WriteDoubleArray0(double[] val, byte* data, int cnt)
        {
            if (LittleEndian)
            {
                fixed (double* val0 = val)
                {
                    CopyMemory((byte*)val0, data, cnt);
                }
            }
            else
            {
                byte* curPos = data;

                for (int i = 0; i < val.Length; i++)
                {
                    double val0 = val[i];

                    byte* valPtr = (byte*)&(val0);

                    *curPos++ = valPtr[7];
                    *curPos++ = valPtr[6];
                    *curPos++ = valPtr[5];
                    *curPos++ = valPtr[4];
                    *curPos++ = valPtr[3];
                    *curPos++ = valPtr[2];
                    *curPos++ = valPtr[1];
                    *curPos++ = valPtr[0];
                }
            }
        }

        /// <summary>
        /// Internal routine to read double array.
        /// </summary>
        /// <param name="len">Count.</param>
        /// <param name="data">Data pointer.</param>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Double array</returns>
        private static double[] ReadDoubleArray0(int len, byte* data, int cnt)
        {
            double[] res = new double[len];

            if (LittleEndian)
            {
                fixed (double* res0 = res)
                {
                    CopyMemory(data, (byte*)res0, cnt);
                }
            }
            else
            {
                for (int i = 0; i < len; i++)
                {
                    double val;

                    byte* valPtr = (byte*)&val;

                    valPtr[7] = *data++;
                    valPtr[6] = *data++;
                    valPtr[5] = *data++;
                    valPtr[4] = *data++;
                    valPtr[3] = *data++;
                    valPtr[2] = *data++;
                    valPtr[1] = *data++;
                    valPtr[0] = *data++;

                    res[i] = val;
                }
            }

            return res;
        }

        /** <inheritdoc /> */
        public void Write(byte[] src, int off, int cnt)
        {
            fixed (byte* src0 = src)
            {
                Write(src0 + off, cnt);
            }
        }

        /** <inheritdoc /> */
        public void Read(byte[] dest, int off, int cnt)
        {
            fixed (byte* dest0 = dest)
            {
                Read(dest0 + off, cnt);
            }
        }

        /// <summary>
        /// Internal write routine.
        /// </summary>
        /// <param name="src">Source.</param>
        /// <param name="cnt">Count.</param>
        /// <param name="data">Data (dsetination).</param>
        private void WriteInternal(byte* src, int cnt, byte* data)
        {
            CopyMemory(src, data + _pos, cnt);
        }

        /// <summary>
        /// Internal read routine.
        /// </summary>
        /// <param name="src">Source</param>
        /// <param name="dest">Destination.</param>
        /// <param name="cnt">Count.</param>
        /// <returns>Amount of bytes written.</returns>
        private void ReadInternal(byte* src, byte* dest, int cnt)
        {
            int cnt0 = Math.Min(Remaining, cnt);

            CopyMemory(src + _pos, dest, cnt0);

            ShiftRead(cnt0);
        }

        /** <inheritdoc /> */
        public int Position
        {
            get { return _pos; }
        }

        /** <inheritdoc /> */
        public int Remaining
        {
            get { return _data.Length - _pos; }
        }

        /// <summary>
        /// Internal array.
        /// </summary>
        internal byte[] InternalArray
        {
            get { return _data; }
        }

        /// <inheritdoc />
        /// <exception cref="System.ArgumentException">
        /// Unsupported seek origin:  + origin
        /// or
        /// Seek before origin:  + newPos
        /// </exception>
        public int Seek(int offset, SeekOrigin origin)
        {
            int newPos;

            switch (origin)
            {
                case SeekOrigin.Begin:
                    {
                        newPos = offset;

                        break;
                    }

                case SeekOrigin.Current:
                    {
                        newPos = _pos + offset;

                        break;
                    }

                default:
                    throw new ArgumentException("Unsupported seek origin: " + origin);
            }

            if (newPos < 0)
                throw new ArgumentException("Seek before origin: " + newPos);

            EnsureWriteCapacity(newPos);

            _pos = newPos;

            return _pos;
        }

        /** <inheritdoc /> */
        public void Flush()
        {
            // No-op.
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
            Justification = "There is no finalizer.")]
        public void Dispose()
        {
            // No-op.
        }

        /// <summary>
        /// Ensure capacity for write and shift position.
        /// </summary>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Position before shift.</returns>
        private int EnsureWriteCapacityAndShift(int cnt)
        {
            int pos0 = _pos;

            EnsureWriteCapacity(_pos + cnt);

            ShiftWrite(cnt);

            return pos0;
        }

        /// <summary>
        /// Ensure capacity for read and shift position.
        /// </summary>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Position before shift.</returns>
        private int EnsureReadCapacityAndShift(int cnt)
        {
            int pos0 = _pos;

            EnsureReadCapacity(cnt);

            ShiftRead(cnt);

            return pos0;
        }

        /// <summary>
        /// Shift position due to write
        /// </summary>
        /// <param name="cnt">Bytes count.</param>
        private void ShiftWrite(int cnt)
        {
            _pos += cnt;
        }

        /// <summary>
        /// Shift position due to read.
        /// </summary>
        /// <param name="cnt">Bytes count.</param>
        private void ShiftRead(int cnt)
        {
            _pos += cnt;
        }

        /// <summary>
        /// Calculate new capacity.
        /// </summary>
        /// <param name="curCap">Current capacity.</param>
        /// <param name="reqCap">Required capacity.</param>
        /// <returns>New capacity.</returns>
        private static int Capacity(int curCap, int reqCap)
        {
            int newCap;

            if (reqCap < 256)
                newCap = 256;
            else
            {
                newCap = curCap << 1;

                if (newCap < reqCap)
                    newCap = reqCap;
            }

            return newCap;
        }

        /// <summary>
        /// Unsafe memory copy routine.
        /// </summary>
        /// <param name="src">Source.</param>
        /// <param name="dest">Destination.</param>
        /// <param name="len">Length.</param>
        private static void CopyMemory(byte* src, byte* dest, int len)
        {
            PlatformMemoryUtils.CopyMemory(src, dest, len);
        }

        /** <inheritdoc /> */
        public void WriteByte(byte val)
        {
            int pos0 = EnsureWriteCapacityAndShift(1);

            _data[pos0] = val;
        }

        /** <inheritdoc /> */
        public byte ReadByte()
        {
            int pos0 = EnsureReadCapacityAndShift(1);

            return _data[pos0];
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteByteArray(byte[] val)
        {
            int pos0 = EnsureWriteCapacityAndShift(val.Length);

            fixed (byte* data0 = _data)
            {
                WriteByteArray0(val, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        public byte[] ReadByteArray(int cnt)
        {
            int pos0 = EnsureReadCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                return ReadByteArray0(cnt, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteBoolArray(bool[] val)
        {
            int pos0 = EnsureWriteCapacityAndShift(val.Length);

            fixed (byte* data0 = _data)
            {
                WriteBoolArray0(val, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        public bool[] ReadBoolArray(int cnt)
        {
            int pos0 = EnsureReadCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                return ReadBoolArray0(cnt, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        public void WriteShort(short val)
        {
            int pos0 = EnsureWriteCapacityAndShift(2);

            fixed (byte* data0 = _data)
            {
                WriteShort0(val, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        public short ReadShort()
        {
            int pos0 = EnsureReadCapacityAndShift(2);

            fixed (byte* data0 = _data)
            {
                return ReadShort0(data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteShortArray(short[] val)
        {
            int cnt = val.Length << 1;

            int pos0 = EnsureWriteCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                WriteShortArray0(val, data0 + pos0, cnt);
            }
        }

        /** <inheritdoc /> */
        public short[] ReadShortArray(int cnt)
        {
            int cnt0 = cnt << 1;

            int pos0 = EnsureReadCapacityAndShift(cnt0);

            fixed (byte* data0 = _data)
            {
                return ReadShortArray0(cnt, data0 + pos0, cnt0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteCharArray(char[] val)
        {
            int cnt = val.Length << 1;

            int pos0 = EnsureWriteCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                WriteCharArray0(val, data0 + pos0, cnt);
            }
        }

        /** <inheritdoc /> */
        public char[] ReadCharArray(int cnt)
        {
            int cnt0 = cnt << 1;

            int pos0 = EnsureReadCapacityAndShift(cnt0);

            fixed (byte* data0 = _data)
            {
                return ReadCharArray0(cnt, data0 + pos0, cnt0);
            }
        }

        /** <inheritdoc /> */
        public void WriteInt(int val)
        {
            int pos0 = EnsureWriteCapacityAndShift(4);

            fixed (byte* data0 = _data)
            {
                WriteInt0(val, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        public void WriteInt(int writePos, int val)
        {
            EnsureWriteCapacity(writePos + 4);

            fixed (byte* data0 = _data)
            {
                WriteInt0(val, data0 + writePos);
            }
        }

        /** <inheritdoc /> */
        public int ReadInt()
        {
            int pos0 = EnsureReadCapacityAndShift(4);

            fixed (byte* data0 = _data)
            {
                return ReadInt0(data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteIntArray(int[] val)
        {
            int cnt = val.Length << 2;

            int pos0 = EnsureWriteCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                WriteIntArray0(val, data0 + pos0, cnt);
            }
        }

        /** <inheritdoc /> */
        public int[] ReadIntArray(int cnt)
        {
            int cnt0 = cnt << 2;

            int pos0 = EnsureReadCapacityAndShift(cnt0);

            fixed (byte* data0 = _data)
            {
                return ReadIntArray0(cnt, data0 + pos0, cnt0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteFloatArray(float[] val)
        {
            int cnt = val.Length << 2;

            int pos0 = EnsureWriteCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                WriteFloatArray0(val, data0 + pos0, cnt);
            }
        }

        /** <inheritdoc /> */
        public float[] ReadFloatArray(int cnt)
        {
            int cnt0 = cnt << 2;

            int pos0 = EnsureReadCapacityAndShift(cnt0);

            fixed (byte* data0 = _data)
            {
                return ReadFloatArray0(cnt, data0 + pos0, cnt0);
            }
        }

        /** <inheritdoc /> */
        public void WriteLong(long val)
        {
            int pos0 = EnsureWriteCapacityAndShift(8);

            fixed (byte* data0 = _data)
            {
                WriteLong0(val, data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        public long ReadLong()
        {
            int pos0 = EnsureReadCapacityAndShift(8);

            fixed (byte* data0 = _data)
            {
                return ReadLong0(data0 + pos0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteLongArray(long[] val)
        {
            int cnt = val.Length << 3;

            int pos0 = EnsureWriteCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                WriteLongArray0(val, data0 + pos0, cnt);
            }
        }

        /** <inheritdoc /> */
        public long[] ReadLongArray(int cnt)
        {
            int cnt0 = cnt << 3;

            int pos0 = EnsureReadCapacityAndShift(cnt0);

            fixed (byte* data0 = _data)
            {
                return ReadLongArray0(cnt, data0 + pos0, cnt0);
            }
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public void WriteDoubleArray(double[] val)
        {
            int cnt = val.Length << 3;

            int pos0 = EnsureWriteCapacityAndShift(cnt);

            fixed (byte* data0 = _data)
            {
                WriteDoubleArray0(val, data0 + pos0, cnt);
            }
        }

        /** <inheritdoc /> */
        public double[] ReadDoubleArray(int cnt)
        {
            int cnt0 = cnt << 3;

            int pos0 = EnsureReadCapacityAndShift(cnt0);

            fixed (byte* data0 = _data)
            {
                return ReadDoubleArray0(cnt, data0 + pos0, cnt0);
            }
        }

        /** <inheritdoc /> */
        public int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding)
        {
            int pos0 = EnsureWriteCapacityAndShift(byteCnt);

            int written;

            fixed (byte* data0 = _data)
            {
                written = BinaryUtils.StringToUtf8Bytes(chars, charCnt, byteCnt, encoding, data0 + pos0);
            }

            return written;
        }

        /** <inheritdoc /> */
        public void Write(byte* src, int cnt)
        {
            EnsureWriteCapacity(_pos + cnt);

            fixed (byte* data0 = _data)
            {
                WriteInternal(src, cnt, data0);
            }

            ShiftWrite(cnt);
        }

        /** <inheritdoc /> */
        public void Read(byte* dest, int cnt)
        {
            fixed (byte* data0 = _data)
            {
                ReadInternal(data0, dest, cnt);
            }
        }

        /** <inheritdoc /> */
        public byte[] GetArray()
        {
            return _data;
        }

        /** <inheritdoc /> */
        public bool CanGetArray
        {
            get { return true; }
        }

        /** <inheritdoc /> */
        public byte[] GetArrayCopy()
        {
            byte[] copy = new byte[_pos];

            Buffer.BlockCopy(_data, 0, copy, 0, _pos);

            return copy;
        }

        /** <inheritdoc /> */
        public bool IsSameArray(byte[] arr)
        {
            return _data == arr;
        }

        /** <inheritdoc /> */
        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
        public T Apply<TArg, T>(IBinaryStreamProcessor<TArg, T> proc, TArg arg)
        {
            Debug.Assert(proc != null);

            fixed (byte* data0 = _data)
            {
                return proc.Invoke(data0, arg);
            }
        }

        /// <summary>
        /// Ensure capacity for write.
        /// </summary>
        /// <param name="cnt">Bytes count.</param>
        private void EnsureWriteCapacity(int cnt)
        {
            if (cnt > _data.Length)
            {
                int newCap = Capacity(_data.Length, cnt);

                byte[] data0 = new byte[newCap];

                // Copy the whole initial array length here because it can be changed
                // from Java without position adjusting.
                Buffer.BlockCopy(_data, 0, data0, 0, _data.Length);

                _data = data0;
            }
        }

        /// <summary>
        /// Ensure capacity for write and shift position.
        /// </summary>
        /// <param name="cnt">Bytes count.</param>
        /// <returns>Position before shift.</returns>
        private void EnsureReadCapacity(int cnt)
        {
            if (_data.Length - _pos < cnt)
                throw new EndOfStreamException("Not enough data in stream [expected=" + cnt +
                                               ", remaining=" + (_data.Length - _pos) + ']');
        }
    }
}


text:
package com.ib.contracts;

import com.ib.client.Contract;

public class OptContract extends Contract {

  public OptContract(String symbol, String expiry, double strike, String right) {
    m_symbol = symbol;
    m_secType = "OPT";
    m_exchange = "SMART";
    m_currency = "USD";
    m_expiry = expiry;
    m_strike = strike;
    m_right = right;
  }

  public OptContract(String symbol, String exchange, String expiry, double strike, String right) {
    m_symbol = symbol;
    m_secType = "OPT";
    m_exchange = exchange;
    m_currency = "USD";
    m_expiry = expiry;
    m_strike = strike;
    m_right = right;
  }

}


text:
        <meta charset="utf-8">
        <link rel="stylesheet" href="../node_modules/mocha/mocha.css" />


text:
namespace syncer {
namespace {

const char kSyncServerSyncPath[] = "/command/";

#define ENUM_CASE(x)    \
  case HttpResponse::x: \
    return #x;          \
    break

const char* GetServerConnectionCodeString(
    HttpResponse::ServerConnectionCode code) {
  switch (code) {
    ENUM_CASE(NONE);
    ENUM_CASE(CONNECTION_UNAVAILABLE);
    ENUM_CASE(IO_ERROR);
    ENUM_CASE(SYNC_SERVER_ERROR);
    ENUM_CASE(SYNC_AUTH_ERROR);
    ENUM_CASE(SERVER_CONNECTION_OK);
  }
  NOTREACHED();
  return "";
}

#undef ENUM_CASE

}  // namespace

HttpResponse::HttpResponse()
    : server_status(NONE),
      net_error_code(-1),
      http_status_code(-1),
      content_length(-1),
      payload_length(-1) {}

// static
HttpResponse HttpResponse::Uninitialized() {
  return HttpResponse();
}

// static
HttpResponse HttpResponse::ForNetError(int net_error_code) {
  HttpResponse response;
  response.server_status = CONNECTION_UNAVAILABLE;
  response.net_error_code = net_error_code;
  return response;
}

// static
HttpResponse HttpResponse::ForIoError() {
  HttpResponse response;
  response.server_status = IO_ERROR;
  return response;
}

// static
HttpResponse HttpResponse::ForHttpError(int http_status_code) {
  HttpResponse response;
  response.server_status = http_status_code == net::HTTP_UNAUTHORIZED
                               ? SYNC_AUTH_ERROR
                               : SYNC_SERVER_ERROR;
  response.http_status_code = http_status_code;
  return response;
}

// static
HttpResponse HttpResponse::ForSuccess() {
  HttpResponse response;
  response.server_status = SERVER_CONNECTION_OK;
  return response;
}

ServerConnectionManager::ServerConnectionManager()
    : proto_sync_path_(kSyncServerSyncPath),
      server_response_(HttpResponse::Uninitialized()) {}

ServerConnectionManager::~ServerConnectionManager() = default;

bool ServerConnectionManager::SetAccessToken(const std::string& access_token) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!access_token.empty()) {
    access_token_.assign(access_token);
    return true;
  }

  access_token_.clear();

  // The access token could be non-empty in cases like server outage/bug. E.g.
  // token returned by first request is considered invalid by sync server and
  // because of token server's caching policy, etc, same token is returned on
  // second request. Need to notify sync frontend again to request new token,
  // otherwise backend will stay in SYNC_AUTH_ERROR state while frontend thinks
  // everything is fine and takes no actions.
  SetServerResponse(HttpResponse::ForHttpError(net::HTTP_UNAUTHORIZED));
  return false;
}

void ServerConnectionManager::ClearAccessToken() {
  access_token_.clear();
}

void ServerConnectionManager::SetServerResponse(
    const HttpResponse& server_response) {
  // Notify only if the server status changed, except for SYNC_AUTH_ERROR: In
  // that case, always notify in order to poke observers to do something about
  // it.
  bool notify =
      (server_response.server_status == HttpResponse::SYNC_AUTH_ERROR ||
       server_response_.server_status != server_response.server_status);
  server_response_ = server_response;
  if (notify) {
    NotifyStatusChanged();
  }
}

void ServerConnectionManager::NotifyStatusChanged() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  for (auto& observer : listeners_)
    observer.OnServerConnectionEvent(
        ServerConnectionEvent(server_response_.server_status));
}

bool ServerConnectionManager::PostBufferWithCachedAuth(
    const std::string& buffer_in,
    std::string* buffer_out,
    HttpResponse* http_response) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  std::string path =
      MakeSyncServerPath(proto_sync_path(), MakeSyncQueryString(client_id_));
  bool result = PostBufferToPath(buffer_in, path, access_token_, buffer_out,
                                 http_response);
  SetServerResponse(*http_response);
  return result;
}

void ServerConnectionManager::AddListener(
    ServerConnectionEventListener* listener) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  listeners_.AddObserver(listener);
}

void ServerConnectionManager::RemoveListener(
    ServerConnectionEventListener* listener) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  listeners_.RemoveObserver(listener);
}

std::ostream& operator<<(std::ostream& s, const struct HttpResponse& hr) {
  s << " Response Code (bogus on error): " << hr.http_status_code;
  s << " Content-Length (bogus on error): " << hr.content_length;
  s << " Server Status: " << GetServerConnectionCodeString(hr.server_status);
  return s;
}

}  // namespace syncer


text: .. include:: ../Devs.rst


text: pragma journal_mode=persist


text:
!|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
!BOP
! !ROUTINE: POP
! !INTERFACE:

 program POP

! !DESCRIPTION:
! This is the main driver for the Parallel Ocean Program (POP).
!
! !REVISION HISTORY:
! CVS:$Id: POP.F90,v 1.8 2003/01/28 23:21:19 pwjones Exp $
! CVS:$Name: POP_2_0_1 $

! !USES:

   use kinds_mod, only: int_kind, r8
   use communicate, only: my_task, master_task
! use constants, only:
   use domain, only: distrb_clinic
   use timers, only: timer_print_all, get_timer, timer_start, timer_stop
   use time_management, only: init_time_flag, check_time_flag, sigAbort, &
       nsteps_run, stdout, sigExit, exit_pop, set_time_flag
   use step_mod, only: step
   use initial, only: initialize_pop
   use xdisplay, only: lxdisplay, clear_display
   use diagnostics, only: check_KE
   use output, only: output_driver
! use exit_mod, only:
   use solvers, only: solv_sum_iters
! use io, only:

   implicit none

!EOP
!BOC
!-----------------------------------------------------------------------
!
! local variables
!
!-----------------------------------------------------------------------

   integer (int_kind) :: &
      timer_total, &! timer number for total time
      timer_step, &! timer number for step
      ierr, &! error flag
      fstop_now, &! flag id for stop_now flag
      nscan

!SIGCATCH integer (int_kind) :: &
!SIGCATCH sigterm = 15, &! system kill signal
!SIGCATCH sigxcpu = 24, &! system signal for little CPU time left
!SIGCATCH flag = -1 ! flag needed by system handling
!SIGCATCH
!SIGCATCH integer, external :: set_term ! routine which determines action
!SIGCATCH ! when kill signal received
!SIGCATCH integer, external :: signal ! signal catching routine

!-----------------------------------------------------------------------
!
! call system routine to catch kill signals and route them to the
! routine set_term to be processed
! signal 15 is terminate
! signal 24 is almost out of cpu time
! this implementation is system dependent so not guaranteed to
! work on any machine
!
!-----------------------------------------------------------------------

!SIGCATCH ierr = signal (sigterm, set_term, flag)
!SIGCATCH ierr = signal (sigxcpu, set_term, flag)

!-----------------------------------------------------------------------
!
! initialize the model run
!
!-----------------------------------------------------------------------

   call initialize_POP

   fstop_now = init_time_flag('stop_now')
   nscan = 0

!-----------------------------------------------------------------------
!
! start up the main timer
!
!-----------------------------------------------------------------------

   call get_timer(timer_total,'TOTAL',1,distrb_clinic%nprocs)
   call timer_start(timer_total)

   call get_timer(timer_step,'STEP',1,distrb_clinic%nprocs)

!-----------------------------------------------------------------------
!
! advance the model in time
!
!-----------------------------------------------------------------------

   do while (.not. check_time_flag(fstop_now))

      call timer_start(timer_step)
      call step
      call timer_stop(timer_step)

      nscan = nscan + solv_sum_iters

      !***
      !*** exit if energy is blowing
      !***

      if (check_KE(100.0_r8)) then
         call set_time_flag(fstop_now,.true.)
         call output_driver
         call exit_POP(sigAbort,'ERROR: k.e. > 100 ')
      endif

!-----------------------------------------------------------------------
!
! write restart dumps and archiving
!
!-----------------------------------------------------------------------

      call output_driver

   enddo

!-----------------------------------------------------------------------
!
! write an end restart if we are through the stepping loop
! without an error
!
!-----------------------------------------------------------------------

   nscan = nscan/nsteps_run
   if (my_task == master_task) &
      write(stdout,*) ' average # scans =', nscan

!-----------------------------------------------------------------------
!
! print timing information and clean up various environments if
! they have been used
!
!-----------------------------------------------------------------------

   call timer_stop(timer_total)
   call timer_print_all(stats=.true.)

   if (lxdisplay) call clear_display
   call exit_POP(sigExit,'Successful completion of POP run')

!-----------------------------------------------------------------------
!EOC

 end program POP

!***********************************************************************
!SIGCATCH!BOP
!SIGCATCH! !ROUTINE: set_term
!SIGCATCH! !INTERFACE:
!SIGCATCH
!SIGCATCH subroutine set_term (theSignal)
!SIGCATCH
!SIGCATCH! !DESCRIPTION:
!SIGCATCH! This routine is used by the system signal catching routine to
!SIGCATCH! set stop_now to true when SIGTERM (15) or (24) is received
!SIGCATCH! from the operating system. The main code then usually has
!SIGCATCH! a few minutes to check this flag, write a restart dump and
!SIGCATCH! terminate gracefully. This routine is system dependent so
!SIGCATCH! can only be used by manually uncommenting code.
!SIGCATCH!
!SIGCATCH! !REVISION HISTORY:
!SIGCATCH! unsupported
!SIGCATCH
!SIGCATCH! !USES:
!SIGCATCH
!SIGCATCH use kinds_mod
!SIGCATCH use domain
!SIGCATCH use communicate
!SIGCATCH use time_management
!SIGCATCH use io
!SIGCATCH
!SIGCATCH implicit none
!SIGCATCH
!SIGCATCH! !INPUT PARAMETERS:
!SIGCATCH
!SIGCATCH integer (int_kind), intent(in) :: &
!SIGCATCH theSignal ! signal caught by system routine
!SIGCATCH
!SIGCATCH!EOP
!SIGCATCH!BOC
!SIGCATCH!----------------------------------------------------------------------
!SIGCATCH
!SIGCATCH select case (theSignal)
!SIGCATCH case(15) ! kill signal (SIGTERM)
!SIGCATCH
!SIGCATCH call set_time_flag(stop_now,.true.)
!SIGCATCH write (stdout,*) 'CAUGHT SIGNAL 15 (KILL) FROM SYSTEM'
!SIGCATCH write (stdout,*) '  TASK = ',my_task
!SIGCATCH
!SIGCATCH case(24) ! out of CPU time (system dependent)
!SIGCATCH
!SIGCATCH call set_time_flag(stop_now,.true.)
!SIGCATCH write (stdout,*) 'CAUGHT SIGNAL 24 (SIGXCPU) FROM SYSTEM'
!SIGCATCH write (stdout,*) '  TASK = ',my_task
!SIGCATCH
!SIGCATCH end select
!SIGCATCH
!SIGCATCH!----------------------------------------------------------------------
!SIGCATCH!EOC
!SIGCATCH
!SIGCATCH end subroutine set_term

!|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||


text:
package org.slc.sli.modeling.tools.xsdgen;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.slc.sli.modeling.uml.Type;

/**
 * @author jstokes
 */
public class TypeComparatorTest {
    @Test
    public void testCompare() throws Exception {
        final TypeComparator comparator = TypeComparator.SINGLETON;
        final Type mockType1 = Mockito.mock(Type.class);
        final Type mockType2 = Mockito.mock(Type.class);

        Mockito.when(mockType1.getName()).thenReturn("a");
        Mockito.when(mockType2.getName()).thenReturn("z");
        Assert.assertTrue(comparator.compare(mockType1, mockType2) < 0);

        Mockito.when(mockType1.getName()).thenReturn("z");
        Mockito.when(mockType2.getName()).thenReturn("a");
        Assert.assertTrue(comparator.compare(mockType1, mockType2) > 0);

        Mockito.when(mockType1.getName()).thenReturn("a");
        Mockito.when(mockType2.getName()).thenReturn("a");
        Assert.assertTrue(comparator.compare(mockType1, mockType2) == 0);

        @SuppressWarnings("unused")
        final boolean bool = mockType1.equals(mockType2);

        Mockito.verify(mockType1, Mockito.atLeastOnce()).getName();
        Mockito.verify(mockType2, Mockito.atLeastOnce()).getName();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testValueOf() {
        final TypeComparator comparator = TypeComparator.valueOf("test");
    }
}


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 edu.pitt.dbmi.deepphe.summarization.orm.i2b2meta;

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

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;

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

public class I2b2MetaDataSourceManager {

    private static final Logger logger = LoggerFactory
            .getLogger(I2b2MetaDataSourceManager.class);

    private String hibernateDialect = org.hibernate.dialect.Oracle10gDialect.class
            .getName();
    private String hibernateDriver = oracle.jdbc.OracleDriver.class.getName();
    private String hibernateConnectionUrl = "jdbc:oracle:thin:@dbmi-i2b2-dev05.dbmi.pitt.edu:1521:XE";
    private String hibernateUserName = "i2b2metadata";
    private String hibernateUserPassword = "demouser";

    //Very dangerous to have this set to create or update. Only available for
    //explicit use by the installer or other utility methods. Must always
    //default to null to avoid accidental database modifications.
    private String hibernateHbm2ddlAuto = "none";

    private String hibernateShowSql = "true";
    private String hibernateCacheUseSecondLevelCache = "false";

    private Configuration configuration;

    private SessionFactory sessionFactory;

    private Session session;

    public I2b2MetaDataSourceManager() {
    }

    private void buildConfiguration() {
        configuration = new Configuration();
        configuration.setProperty("hibernate.dialect", getHibernateDialect());
        configuration.setProperty("hibernate.connection.driver_class",
                getHibernateDriver());
        configuration.setProperty("hibernate.show_sql", getHibernateShowSql());
        configuration.setProperty("hibernate.connection.url",
                getHibernateConnectionUrl());
        configuration.setProperty("hibernate.connection.username",
                getHibernateUserName());
        configuration.setProperty("hibernate.connection.password",
                getHibernateUserPassword());
        configuration.setProperty("hibernate.cache.use_second_level_cache", getHibernateCacheUseSecondLevelCache());
        if (getHibernateHbm2ddlAuto() != null) {
            configuration.setProperty("hibernate.hbm2ddl.auto",
                    getHibernateHbm2ddlAuto());
        }
        addAnnotatedClasses();
    }

    /**
     * get or create configuration object to further customize it before calling
     * getSession()
     *
     * @return
     */
    public Configuration getConfiguration() {
        if (configuration == null) {
            buildConfiguration();
        }
        return configuration;
    }

    private void addAnnotatedClasses() {
        configuration.addAnnotatedClass(DeeppheOntology.class);
        configuration.addAnnotatedClass(OntProcessStatus.class);
        configuration.addAnnotatedClass(TableAccess.class);
    }

    public void addAnnotatedClsesForPackage() {
        logger.debug("Entered addAnnotatedClsesForPackage for " + getClass().getName());
        try {
            String pkgName = getClass().getPackage().getName();
            ClassPath classPath = ClassPath.from(getClass().getClassLoader());
            final ArrayList<Class<?>> clses = new ArrayList<>();
            Set<ClassInfo> clsInfos = classPath
            .getTopLevelClassesRecursive(pkgName);
            for (ClassInfo clsInfo : clsInfos) {
            	if (!clsInfo.getName().equals(getClass().getName())) {
            		clses.add(clsInfo.load());
            	}
            }
            if (clses.isEmpty()) {
                logger.error("Failed to load hibernate clses");
            } else {
            	for (Class<?> cls : clses) {
            		 System.err.println("Configuring " + cls.getName() + " into Hibernate");
                     logger.info("Configuring " + cls.getName() + " into Hibernate");
                     configuration.addAnnotatedClass(cls);
            	}
            }
        } catch (IOException e) {
        }
        logger.debug("Exited addAnnotatedClsesForPackage for " + getClass().getName());
    }

    /*
     * SessionFactory
     */
    @SuppressWarnings("deprecation")
	private boolean buildSessionFactory(Configuration configuration) {
        sessionFactory = configuration.buildSessionFactory();
        return !sessionFactory.isClosed();
    }

    /*
     * Session
     */
    public Session getSession() {
        if (session == null) {
            if (configuration == null) {
                buildConfiguration();
            }
            if (sessionFactory == null) {
                buildSessionFactory(configuration);
            }

            session = sessionFactory.openSession();
        }
        return session;
    }

    /*
     * Clean up
     */
    private void closeSession() throws HibernateException {
        if (session != null && session.isOpen()) {
            session.close();
            session = null;
        }
    }

    private void closeSessionFactory() throws HibernateException {
        if (sessionFactory != null && !sessionFactory.isClosed()) {
            sessionFactory.close();
        }
        sessionFactory = null;
    }

    public void destroy() {
        closeSession();
        closeSessionFactory();
        logger.debug("destroyed " + getClass().getName() + " : session and sessionFactory removed.");
    }

    @Override
    protected void finalize() throws Throwable {
        destroy();
        super.finalize();
    }

    public String getHibernateDialect() {
        return hibernateDialect;
    }

    public void setHibernateDialect(String hibernateDialect) {
        this.hibernateDialect = hibernateDialect;
    }

    public String getHibernateDriver() {
        return hibernateDriver;
    }

    public void setHibernateDriver(String hibernateDriver) {
        this.hibernateDriver = hibernateDriver;
    }

    public String getHibernateConnectionUrl() {
        return hibernateConnectionUrl;
    }

    public void setHibernateConnectionUrl(String hibernateConnectionUrl) {
        this.hibernateConnectionUrl = hibernateConnectionUrl;
    }

    public String getHibernateUserName() {
        return hibernateUserName;
    }

    public void setHibernateUserName(String hibernateUserName) {
        this.hibernateUserName = hibernateUserName;
    }

    public String getHibernateUserPassword() {
        return hibernateUserPassword;
    }

    public void setHibernateUserPassword(String hibernateUserPassword) {
        this.hibernateUserPassword = hibernateUserPassword;
    }

    public String getHibernateHbm2ddlAuto() {
        return hibernateHbm2ddlAuto;
    }

    public void setHibernateHbm2ddlAuto(String hibernateHbm2ddlAuto) {
        this.hibernateHbm2ddlAuto = hibernateHbm2ddlAuto;
    }

    public String getHibernateShowSql() {
        return hibernateShowSql;
    }

    public void setHibernateShowSql(String hibernateShowSql) {
        this.hibernateShowSql = hibernateShowSql;
    }

    public String getHibernateCacheUseSecondLevelCache() {
        return hibernateCacheUseSecondLevelCache;
    }

    public void setHibernateCacheUseSecondLevelCache(
            String hibernateCacheUseSecondLevelCache) {
        this.hibernateCacheUseSecondLevelCache = hibernateCacheUseSecondLevelCache;
    }

}


text:
package org.schema.api.model.thing.medicalEntity.medicalTherapy;

import org.schema.api.model.thing.medicalEntity.medicalTherapy.MedicalTherapy;

public class RadiationTherapy extends MedicalTherapy
{
}


text:
package org.apache.flink.runtime.jobmaster.slotpool;

import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutorServiceAdapter;
import org.apache.flink.runtime.instance.SimpleSlotContext;
import org.apache.flink.runtime.jobmaster.AllocatedSlotReport;
import org.apache.flink.runtime.jobmaster.JobMasterId;
import org.apache.flink.runtime.jobmaster.RpcTaskManagerGateway;
import org.apache.flink.runtime.jobmaster.SlotInfo;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.resourcemanager.utils.TestingResourceManagerGateway;
import org.apache.flink.runtime.slots.ResourceRequirement;
import org.apache.flink.runtime.slots.ResourceRequirements;
import org.apache.flink.runtime.taskexecutor.TestingTaskExecutorGatewayBuilder;
import org.apache.flink.runtime.taskexecutor.slot.SlotOffer;
import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation;
import org.apache.flink.runtime.util.ResourceCounter;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.clock.SystemClock;

import org.apache.flink.shaded.guava30.com.google.common.collect.Iterables;

import org.junit.jupiter.api.Test;

import javax.annotation.Nonnull;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;

import static org.assertj.core.api.Assertions.assertThat;

/** Tests for the {@link DeclarativeSlotPoolService}. */
class DeclarativeSlotPoolServiceTest {

    private static final JobID jobId = new JobID();
    private static final JobMasterId jobMasterId = JobMasterId.generate();
    private final ComponentMainThreadExecutor mainThreadExecutor =
            ComponentMainThreadExecutorServiceAdapter.forMainThread();
    private static final String address = "localhost";

    @Test
    void testUnknownTaskManagerRegistration() throws Exception {
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService()) {
            final ResourceID unknownTaskManager = ResourceID.generate();

            assertThat(
                            declarativeSlotPoolService.isTaskManagerRegistered(
                                    unknownTaskManager.getResourceID()))
                    .isFalse();
        }
    }

    @Test
    void testKnownTaskManagerRegistration() throws Exception {
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService()) {
            final ResourceID knownTaskManager = ResourceID.generate();
            declarativeSlotPoolService.registerTaskManager(knownTaskManager);

            assertThat(
                            declarativeSlotPoolService.isTaskManagerRegistered(
                                    knownTaskManager.getResourceID()))
                    .isTrue();
        }
    }

    @Test
    void testReleaseTaskManager() throws Exception {
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService()) {
            final ResourceID knownTaskManager = ResourceID.generate();
            declarativeSlotPoolService.registerTaskManager(knownTaskManager);
            declarativeSlotPoolService.releaseTaskManager(
                    knownTaskManager, new FlinkException("Test cause"));

            assertThat(
                            declarativeSlotPoolService.isTaskManagerRegistered(
                                    knownTaskManager.getResourceID()))
                    .isFalse();
        }
    }

    @Test
    void testSlotOfferingOfUnknownTaskManagerIsIgnored() throws Exception {
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService()) {
            final Collection<SlotOffer> slotOffers =
                    Collections.singletonList(
                            new SlotOffer(new AllocationID(), 0, ResourceProfile.UNKNOWN));

            final LocalTaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation();

            final Collection<SlotOffer> acceptedSlots =
                    declarativeSlotPoolService.offerSlots(
                            taskManagerLocation,
                            new RpcTaskManagerGateway(
                                    new TestingTaskExecutorGatewayBuilder()
                                            .createTestingTaskExecutorGateway(),
                                    jobMasterId),
                            slotOffers);

            assertThat(acceptedSlots).isEmpty();
        }
    }

    @Test
    void testSlotOfferingOfKnownTaskManager() throws Exception {
        final AtomicReference<Collection<? extends SlotOffer>> receivedSlotOffers =
                new AtomicReference<>();
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService(
                        new TestingDeclarativeSlotPoolFactory(
                                new TestingDeclarativeSlotPoolBuilder()
                                        .setOfferSlotsFunction(
                                                (slotOffers,
                                                        taskManagerLocation,
                                                        taskManagerGateway,
                                                        aLong) -> {
                                                    receivedSlotOffers.set(slotOffers);
                                                    return new ArrayList<>(slotOffers);
                                                })))) {
            final LocalTaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation();

            declarativeSlotPoolService.registerTaskManager(taskManagerLocation.getResourceID());

            final Collection<SlotOffer> slotOffers =
                    Collections.singletonList(
                            new SlotOffer(new AllocationID(), 0, ResourceProfile.UNKNOWN));

            declarativeSlotPoolService.offerSlots(
                    taskManagerLocation,
                    new RpcTaskManagerGateway(
                            new TestingTaskExecutorGatewayBuilder()
                                    .createTestingTaskExecutorGateway(),
                            jobMasterId),
                    slotOffers);

            assertThat(receivedSlotOffers.get()).isEqualTo(slotOffers);
        }
    }

    @Test
    void testConnectToResourceManagerDeclaresRequiredResources() throws Exception {
        final Collection<ResourceRequirement> requiredResources =
                Arrays.asList(
                        ResourceRequirement.create(ResourceProfile.UNKNOWN, 2),
                        ResourceRequirement.create(ResourceProfile.ZERO, 4));

        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService(
                        new TestingDeclarativeSlotPoolFactory(
                                new TestingDeclarativeSlotPoolBuilder()
                                        .setGetResourceRequirementsSupplier(
                                                () -> requiredResources)))) {
            final TestingResourceManagerGateway resourceManagerGateway =
                    new TestingResourceManagerGateway();

            final CompletableFuture<ResourceRequirements> declaredResourceRequirements =
                    new CompletableFuture<>();

            resourceManagerGateway.setDeclareRequiredResourcesFunction(
                    (jobMasterId, resourceRequirements) -> {
                        declaredResourceRequirements.complete(resourceRequirements);
                        return CompletableFuture.completedFuture(Acknowledge.get());
                    });

            declarativeSlotPoolService.connectToResourceManager(resourceManagerGateway);

            final ResourceRequirements resourceRequirements = declaredResourceRequirements.join();

            assertThat(resourceRequirements.getResourceRequirements()).isEqualTo(requiredResources);
            assertThat(resourceRequirements.getJobId()).isEqualTo(jobId);
            assertThat(resourceRequirements.getTargetAddress()).isEqualTo(address);
        }
    }

    @Test
    void testCreateAllocatedSlotReport() throws Exception {
        final LocalTaskManagerLocation taskManagerLocation1 = new LocalTaskManagerLocation();
        final LocalTaskManagerLocation taskManagerLocation2 = new LocalTaskManagerLocation();
        final SimpleSlotContext simpleSlotContext2 = createSimpleSlotContext(taskManagerLocation2);
        final Collection<SlotInfo> slotInfos =
                Arrays.asList(createSimpleSlotContext(taskManagerLocation1), simpleSlotContext2);
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService(
                        new TestingDeclarativeSlotPoolFactory(
                                new TestingDeclarativeSlotPoolBuilder()
                                        .setGetAllSlotsInformationSupplier(() -> slotInfos)))) {

            final AllocatedSlotReport allocatedSlotReport =
                    declarativeSlotPoolService.createAllocatedSlotReport(
                            taskManagerLocation2.getResourceID());

            assertThat(allocatedSlotReport.getAllocatedSlotInfos())
                    .allMatch(
                            context ->
                                    context.getAllocationId()
                                                    .equals(simpleSlotContext2.getAllocationId())
                                            && context.getSlotIndex()
                                                    == simpleSlotContext2.getPhysicalSlotNumber());
        }
    }

    @Test
    void testFailAllocationReleasesSlot() throws Exception {
        final CompletableFuture<AllocationID> releasedSlot = new CompletableFuture<>();
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService(
                        new TestingDeclarativeSlotPoolFactory(
                                new TestingDeclarativeSlotPoolBuilder()
                                        .setReleaseSlotFunction(
                                                (allocationID, exception) -> {
                                                    releasedSlot.complete(allocationID);
                                                    return ResourceCounter.empty();
                                                })))) {
            final ResourceID taskManagerId = ResourceID.generate();
            final AllocationID allocationId = new AllocationID();

            declarativeSlotPoolService.registerTaskManager(taskManagerId);

            declarativeSlotPoolService.failAllocation(
                    taskManagerId, allocationId, new FlinkException("Test cause"));

            assertThat(releasedSlot.join()).isEqualTo(allocationId);
        }
    }

    @Test
    void testFailLastAllocationOfTaskManagerReturnsIt() throws Exception {
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService()) {
            final ResourceID taskManagerId = ResourceID.generate();

            declarativeSlotPoolService.registerTaskManager(taskManagerId);
            final Optional<ResourceID> emptyTaskManager =
                    declarativeSlotPoolService.failAllocation(
                            taskManagerId, new AllocationID(), new FlinkException("Test cause"));

            assertThat(
                            emptyTaskManager.orElseThrow(
                                    () -> new Exception("Expected empty task manager")))
                    .isEqualTo(taskManagerId);
        }
    }

    @Test
    void testCloseReleasesAllSlotsForAllRegisteredTaskManagers() throws Exception {
        final Queue<ResourceID> releasedSlotsFor = new ArrayDeque<>(2);
        try (DeclarativeSlotPoolService declarativeSlotPoolService =
                createDeclarativeSlotPoolService(
                        new TestingDeclarativeSlotPoolFactory(
                                new TestingDeclarativeSlotPoolBuilder()
                                        .setReleaseSlotsFunction(
                                                (resourceID, e) -> {
                                                    releasedSlotsFor.offer(resourceID);
                                                    return ResourceCounter.empty();
                                                })))) {

            final List<ResourceID> taskManagerResourceIds =
                    Arrays.asList(
                            ResourceID.generate(), ResourceID.generate(), ResourceID.generate());

            for (ResourceID taskManagerResourceId : taskManagerResourceIds) {
                declarativeSlotPoolService.registerTaskManager(taskManagerResourceId);
            }

            declarativeSlotPoolService.close();

            assertThat(releasedSlotsFor)
                    .containsExactlyInAnyOrderElementsOf(taskManagerResourceIds);
        }
    }

    @Test
    void testReleaseFreeSlotsOnTaskManager() throws Exception {
        try (DeclarativeSlotPoolService slotPoolService = createDeclarativeSlotPoolService()) {
            final LocalTaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation();
            slotPoolService.registerTaskManager(taskManagerLocation.getResourceID());

            final ResourceProfile resourceProfile =
                    ResourceProfile.newBuilder().setCpuCores(1).build();

            SlotOffer slotOffer1 = new SlotOffer(new AllocationID(), 0, resourceProfile);
            SlotOffer slotOffer2 = new SlotOffer(new AllocationID(), 1, resourceProfile);

            final DeclarativeSlotPool slotPool = slotPoolService.getDeclarativeSlotPool();
            slotPool.setResourceRequirements(ResourceCounter.withResource(resourceProfile, 2));

            final DefaultDeclarativeSlotPoolTest.FreeSlotConsumer freeSlotConsumer =
                    new DefaultDeclarativeSlotPoolTest.FreeSlotConsumer();

            final Collection<SlotOffer> slotOffers = Arrays.asList(slotOffer1, slotOffer2);

            slotPoolService.offerSlots(
                    taskManagerLocation,
                    new RpcTaskManagerGateway(
                            new TestingTaskExecutorGatewayBuilder()
                                    .setFreeSlotFunction(freeSlotConsumer)
                                    .createTestingTaskExecutorGateway(),
                            jobMasterId),
                    slotOffers);

            // slot1 is reserved, slot2 is free.
            slotPool.reserveFreeSlot(slotOffer1.getAllocationId(), resourceProfile);

            slotPoolService.releaseFreeSlotsOnTaskManager(
                    taskManagerLocation.getResourceID(), new FlinkException("Test cause"));

            assertThat(slotPool.getFreeSlotsInformation()).isEmpty();
            assertThat(
                            Iterables.getOnlyElement(slotPool.getAllSlotsInformation())
                                    .getAllocationId())
                    .isEqualTo(slotOffer1.getAllocationId());
            assertThat(Iterables.getOnlyElement(freeSlotConsumer.drainFreedSlots()))
                    .isEqualTo(slotOffer2.getAllocationId());
        }
    }

    private DeclarativeSlotPoolService createDeclarativeSlotPoolService() throws Exception {
        return createDeclarativeSlotPoolService(new DefaultDeclarativeSlotPoolFactory());
    }

    private DeclarativeSlotPoolService createDeclarativeSlotPoolService(
            DeclarativeSlotPoolFactory declarativeSlotPoolFactory) throws Exception {
        final DeclarativeSlotPoolService declarativeSlotPoolService =
                new DeclarativeSlotPoolService(
                        jobId,
                        declarativeSlotPoolFactory,
                        SystemClock.getInstance(),
                        Time.seconds(20L),
                        Time.seconds(20L));

        declarativeSlotPoolService.start(jobMasterId, address, mainThreadExecutor);

        return declarativeSlotPoolService;
    }

    @Nonnull
    private SimpleSlotContext createSimpleSlotContext(
            LocalTaskManagerLocation taskManagerLocation1) {
        return new SimpleSlotContext(
                new AllocationID(),
                taskManagerLocation1,
                0,
                new RpcTaskManagerGateway(
                        new TestingTaskExecutorGatewayBuilder().createTestingTaskExecutorGateway(),
                        jobMasterId));
    }
}