text:
require 'sinatra'
require File.expand_path(File.join(File.dirname(__FILE__), 'sinatra_test_cases'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'helpers', 'exceptions'))

include NewRelic::TestHelpers::Exceptions

configure do
  # display exceptions so we see what's going on
  disable :show_exceptions

  # create a condition (sintra's version of a before_filter) that returns the
  # value that was passed into it.
  set :my_condition do |boolean|
    condition do
      halt 404 unless boolean
    end
  end
end

get '/user/login' do
  "please log in"
end

# this action will always return 404 because of the condition.
get '/user/:id', :my_condition => false do |id|
  "Welcome #{id}"
end

get '/raise' do
  raise "Uh-oh"
end

# check that pass works properly
set(:pass_condition) { |_| condition { pass { halt 418, "I'm a teapot." } } }
get('/pass', :pass_condition => true) { }

get '/pass' do
  "I'm not a teapot."
end

error(NewRelic::TestHelpers::Exceptions::TestError) { halt 200, 'nothing happened' }
set(:error_condition) { |_| condition { raise NewRelic::TestHelpers::Exceptions::TestError } }
get('/error', :error_condition => true) { }

set(:precondition_check) do |_|
  condition do
    raise "Boo" if $precondition_already_checked
    $precondition_already_checked = true
  end
end
get('/precondition', :precondition_check => true) do
  'precondition only happened once'
end

get '/route/:name' do |name|
  # usually this would be a db test or something
  pass if name != 'match'
  'first route'
end

get '/route/no_match' do
  'second route'
end

before '/filtered' do
  @filtered = true
end

get '/filtered' do
  @filtered ? 'got filtered' : 'nope'
end

newrelic_ignore '/ignored'
get '/ignored' do
  "don't trace me bro"
end

get(/\/regex.*/) do
  "Yeah, regex's!"
end

post '/files' do
  "file uploaded"
end

module Sinatra
  class Application < Base
    # Override to not accidentally start the app in at_exit handler
    set :run, Proc.new { false }
  end
end

class SinatraClassicTest < Minitest::Test
  include SinatraTestCases

  def app
    Sinatra::Application
  end
end

redpajama_set_name: RedPajamaGithub


text:
package orwir.starter.logic.api;

import io.reactivex.Flowable;

public interface Keeper {

    Flowable<Boolean> online();

    //void getSomeService();

}


text:
- It's like awesome-* but clean and polished.
- Only add well maintained and professionally battle tested libs

We want to [find a nice way to make people fluent with a lib](https://gitlab.com/ThomasCrvsr/practical-resources/issues/9).

## General

- :warning: **To add, remove, or change things on the list**: submit a pull request

Here is a checklist to follow before adding anything (techno / links):

- Code functions as documented and expected
- Generally useful to the wider community of programmers (including you !)
- Actively maintained
    - Regular, recent commits
    - Or, for finished projects, issues and pull requests are responded to
- Stable or progressing toward stable
- Thoroughly documented (README, comments, etc.)
- Tests, where practical

## To add a techno

A *techno* is a programming language, a framework, the `truc` from `awesome-truc` lists.

- :memo: The general documentation for a techno is `technos/<name>/resources.md`
- :gift: Add some basic resources about the new techno (official site and tutorial...)
- :art: If you could have a gif to your PR, that will make reviewers happy and they may be nice to you :kissing:

## To add a link

A link is a resource regarding a specific techno.

- :memo: The general documentation for a techno is `technos/<name>/resources.md`
- :ballot_box_with_check: Check that it doesn't exist
- :ballot_box_with_check: Add a link with the name of the ressource
- :ballot_box_with_check: Please add a description
- :wink: You can help organize the files !

## To add a snippet

Snippets are here the "tips and tricks" part. You should add one if:

- You have spend too much time on something and have a nice solution
- A quick way so solve a problem
- A general info on how to use some part of a resource

Here you go:

- :ballot_box_with_check: Create a nicely named file under `technos/<name>/snippets/`
- :ballot_box_with_check: Organize the file the way you want (it can be a description + a code block, a question / answer style...)

## Building the site

The site is generated from files using [Hakyll](https://jaspervdj.be/hakyll/).

In order to be able to build the site generator, you have to install [stack](https://docs.haskellstack.org/en/stable/README/).

Once you have `stack` in your PATH, here are the commands what you can use :

- `make setup` : use stack to setup everything you'll need to build the project
- `make build-generator` : build the site generator. (This could take a while when building the project for the first time as stack will install all dependencies)
- `make build` : generate the website. All generated files will be in `public/`
- `make clean` : clean hakyll cache. Try this when the cache is corrupted
- `make watch` : Watch the source files and build the site every time something has changed. Also serve the site at [http://localhost:8000](http://localhost:8000).


text:
System.register(['aurelia-binding'], function (_export) {
  'use strict';

  var bindingMode, DebounceBindingBehavior;

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

  function debounce(newValue) {
    var _this = this;

    var state = this.debounceState;
    if (state.immediate) {
      state.immediate = false;
      this.debouncedMethod(newValue);
      return;
    }
    clearTimeout(state.timeoutId);
    state.timeoutId = setTimeout(function () {
      return _this.debouncedMethod(newValue);
    }, state.delay);
  }

  return {
    setters: [function (_aureliaBinding) {
      bindingMode = _aureliaBinding.bindingMode;
    }],
    execute: function () {
      DebounceBindingBehavior = (function () {
        function DebounceBindingBehavior() {
          _classCallCheck(this, DebounceBindingBehavior);
        }

        DebounceBindingBehavior.prototype.bind = function bind(binding, source) {
          var delay = arguments.length <= 2 || arguments[2] === undefined ? 200 : arguments[2];

          var methodToDebounce = 'updateTarget';
          if (binding.callSource) {
            methodToDebounce = 'callSource';
          } else if (binding.updateSource && binding.mode === bindingMode.twoWay) {
              methodToDebounce = 'updateSource';
            }

          binding.debouncedMethod = binding[methodToDebounce];
          binding.debouncedMethod.originalName = methodToDebounce;

          binding[methodToDebounce] = debounce;

          binding.debounceState = {
            delay: delay,
            timeoutId: null,
            immediate: methodToDebounce === 'updateTarget' };
        };

        DebounceBindingBehavior.prototype.unbind = function unbind(binding, source) {
          var methodToRestore = binding.debouncedMethod.originalName;
          binding[methodToRestore] = binding.debouncedMethod;
          binding.debouncedMethod = null;
          clearTimeout(binding.debounceState.timeoutId);
          binding.debounceState = null;
        };

        return DebounceBindingBehavior;
      })();

      _export('DebounceBindingBehavior', DebounceBindingBehavior);
    }
  };
});


text:
<?php

namespace Oro\Bundle\FormBundle\Tests\Unit\Model;

use Oro\Bundle\FormBundle\Form\Handler\FormHandlerInterface;
use Oro\Bundle\FormBundle\Model\Update;
use Oro\Bundle\FormBundle\Provider\FormTemplateDataProviderInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

class UpdateTest extends \PHPUnit\Framework\TestCase
{
    public function testUpdateMethods()
    {
        $data = new \stdClass();
        /** @var FormInterface $form */
        $form = $this->createMock(FormInterface::class);
        /** @var FormHandlerInterface|MockObject $formHandler */
        $formHandler = $this->createMock(FormHandlerInterface::class);
        /** @var FormTemplateDataProviderInterface|MockObject $formTemplateDataProvider */
        $formTemplateDataProvider = $this->createMock(FormTemplateDataProviderInterface::class);
        $update = new  Update();

        $update->setFormData($data);
        $update->setFrom($form);
        $update->setHandler($formHandler);
        $update->setTemplateDataProvider($formTemplateDataProvider);

        $this->assertSame($data, $update->getFormData());
        $this->assertSame($form, $update->getForm());

        /** @var Request|MockObject $request */
        $request = $this->createMock(Request::class);

        $formHandler->expects($this->once())
            ->method('process')->with($data, $form, $request)->willReturn(true);
        $this->assertTrue($update->handle($request), 'Handling result bubbled without changes.');

        $formTemplateDataProvider->expects($this->once())
            ->method('getData')->with($data, $form, $request)->willReturn(['data' => 'value']);
        $this->assertEquals(
            ['data' => 'value'],
            $update->getTemplateData($request),
            'Provider result bubbled without changes.'
        );
    }
}


text:
import glob
import os

from django.conf import settings
from django.utils.functional import cached_property

class Node(object):

    def __init__(self, path, parent=None, count=1):
        self.parent = parent
        if self.parent:
            self.id = parent.id * 100 + count
        else:
            self.id = count
        self._path = path
        self._is_dir = os.path.isdir(self.path)

    @property
    def path(self):
        return self._path

    @cached_property
    def name(self):
        if self.is_dir():
            if self.parent:
                return os.path.relpath(self.path, self.parent.path)
            return self.path
        return os.path.basename(self.path)

    @cached_property
    def children(self):
        path = os.path.join(self._path, '*')
        return [Node(path, parent=self, count=i) for i, path in enumerate(glob.glob(path), 1)]

    @property
    def url_path(self):
        return os.path.relpath(self.path, settings.DATA_DIR)

    def is_dir(self):
        return self._is_dir


text:
package vistor_2;

import java.util.Vector;

/*=========================================*/
/* This is a visitor classs in the class   */
/* diagram of the visitor design pattern   */
/*=========================================*/

public class PartsInfoVisitor implements Visitor {

	private String partInfo;
	private String allOders=" ";

	public void visitComputerCase(ComputerCase e) {
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitPowerSupply(PowerSupply e) {
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitMotherboard(Motherboard e) {
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitMicroprocessor(Microprocessor e) {
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitMemory(Memory e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitDriveController(DriveController e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitHardDiskDrive(HardDiskDrive e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	 public void visitCDDrive(CDDrive  e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitDVDDevice (DVDDevice  e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitMonitor (Monitor  e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitKeyboard (Keyboard  e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitMouse (Mouse  e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitVideoCard(VideoCard e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	public void visitFan(Fan e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}
	//
	public void visitSoundBox(SoundBox e){
		partInfo = e.getDescription();
		allOders = allOders + "\n " + partInfo;
	}

	public String getPartDescription(String partName) {
	   return partInfo;
	}

	public String printAllOrderInfo(){
	   return allOders;
	}
}


text:
import { React, Component } from './ui/utils';

import UI from './ui';
import { createSystem } from './system';
import { initializeSystem } from './content';

export default class Game extends Component {
  constructor() {
    super();

    this.system = createSystem();
    initializeSystem(this.system);
    // TODO initialize/load world state
  }

  render() {
    return <UI system={this.system} />
  }
}


text:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
GEODEBUILDDIR="${SCRIPTDIR}/../geode-build"

set -e

if [ -z "${GEODE_BRANCH}" ]; then
  GEODE_BRANCH=$(git rev-parse --abbrev-ref HEAD)
fi

if [ "${GEODE_BRANCH}" = "HEAD" ]; then
  echo "Unable to determine branch for deployment. Quitting..."
  exit 1
fi

echo "Sanitized Geode Fork = ${SANITIZED_GEODE_FORK}"
echo "Sanitized Geode Branch = ${SANITIZED_GEODE_BRANCH}"

#echo "DEBUG INFO *****************************"
#echo "Pipeline prefix = ${PIPELINE_PREFIX}"
#echo "Docker image prefix = ${DOCKER_IMAGE_PREFIX}"

pushd ${SCRIPTDIR} 2>&1 > /dev/null

  cat > repository.yml <<YML
repository:
  project: 'geode'
  fork: ${GEODE_FORK}
  branch: ${GEODE_BRANCH}
  upstream_fork: ${UPSTREAM_FORK}
  public: ${REPOSITORY_PUBLIC}
YML

  python3 ../render.py jinja.template.yml --variable-file ../shared/jinja.variables.yml repository.yml --environment ../shared/ --output ${SCRIPTDIR}/generated-pipeline.yml || exit 1

popd 2>&1 > /dev/null
cp ${SCRIPTDIR}/generated-pipeline.yml ${OUTPUT_DIRECTORY}/generated-pipeline.yml

grep -n . ${OUTPUT_DIRECTORY}/generated-pipeline.yml

cat > ${OUTPUT_DIRECTORY}/pipeline-vars.yml <<YML
geode-build-branch: ${GEODE_BRANCH}
geode-fork: ${GEODE_FORK}
geode-repo-name: ${GEODE_REPO_NAME}
upstream-fork: ${UPSTREAM_FORK}
pipeline-prefix: "${PIPELINE_PREFIX}"
public-pipelines: ${PUBLIC_PIPELINES}
gcp-project: ${GCP_PROJECT}
docker-image-prefix: "${PIPELINE_PREFIX}"
YML


text:
/* */
(function(process) {
  "use strict";
  var __extends = (this && this.__extends) || function(d, b) {
    for (var p in b)
      if (b.hasOwnProperty(p))
        d[p] = b[p];
    function __() {
      this.constructor = d;
    }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
  var tryCatch_1 = require('../util/tryCatch');
  var errorObject_1 = require('../util/errorObject');
  var OuterSubscriber_1 = require('../OuterSubscriber');
  var subscribeToResult_1 = require('../util/subscribeToResult');
  function audit(durationSelector) {
    return this.lift(new AuditOperator(durationSelector));
  }
  exports.audit = audit;
  var AuditOperator = (function() {
    function AuditOperator(durationSelector) {
      this.durationSelector = durationSelector;
    }
    AuditOperator.prototype.call = function(subscriber, source) {
      return source._subscribe(new AuditSubscriber(subscriber, this.durationSelector));
    };
    return AuditOperator;
  }());
  var AuditSubscriber = (function(_super) {
    __extends(AuditSubscriber, _super);
    function AuditSubscriber(destination, durationSelector) {
      _super.call(this, destination);
      this.durationSelector = durationSelector;
      this.hasValue = false;
    }
    AuditSubscriber.prototype._next = function(value) {
      this.value = value;
      this.hasValue = true;
      if (!this.throttled) {
        var duration = tryCatch_1.tryCatch(this.durationSelector)(value);
        if (duration === errorObject_1.errorObject) {
          this.destination.error(errorObject_1.errorObject.e);
        } else {
          this.add(this.throttled = subscribeToResult_1.subscribeToResult(this, duration));
        }
      }
    };
    AuditSubscriber.prototype.clearThrottle = function() {
      var _a = this,
          value = _a.value,
          hasValue = _a.hasValue,
          throttled = _a.throttled;
      if (throttled) {
        this.remove(throttled);
        this.throttled = null;
        throttled.unsubscribe();
      }
      if (hasValue) {
        this.value = null;
        this.hasValue = false;
        this.destination.next(value);
      }
    };
    AuditSubscriber.prototype.notifyNext = function(outerValue, innerValue, outerIndex, innerIndex) {
      this.clearThrottle();
    };
    AuditSubscriber.prototype.notifyComplete = function() {
      this.clearThrottle();
    };
    return AuditSubscriber;
  }(OuterSubscriber_1.OuterSubscriber));
})(require('process'));


text:
---
Title: Card Item Type service
Added: v2.0.0
Status: Active
Last reviewed: 2018-11-20
---

# [Card Item Type service](lib/core/src/lib/card-view/services/card-item-types.service.ts "Defined in card-item-types.service.ts")

Maps type names to field component types for the [Card View component](../components/card-view.component.md).

## Class members

### Methods

-   **getComponentTypeResolver**(type: `string`, defaultValue: `Type<any>` = `this.defaultValue`): [`DynamicComponentResolveFunction`](lib/core/src/lib/services/dynamic-component-mapper.service.ts)

    Gets the currently active [DynamicComponentResolveFunction](lib/core/src/lib/services/dynamic-component-mapper.service.ts) for a field type.
    -   _type:_ `string`  - The type whose resolver you want
    -   _defaultValue:_ `Type<any>`  - Default type returned for types that are not yet mapped
    -   **Returns** [`DynamicComponentResolveFunction`](lib/core/src/lib/services/dynamic-component-mapper.service.ts) - Resolver function
-   **register**(components: `Function`, override: `boolean` = `false`)

    Register multiple components
    -   _components:_ `Function`  -
    -   _override:_ `boolean`  -
-   **resolveComponentType**(model: [`DynamicComponentModel`](lib/core/src/lib/services/dynamic-component-mapper.service.ts), defaultValue: `Type<any>` = `this.defaultValue`): `Type<any>`

    Finds the component type that is needed to render a form field.
    -   _model:_ [`DynamicComponentModel`](lib/core/src/lib/services/dynamic-component-mapper.service.ts)  - [Form](../../../lib/process-services/src/lib/task-list/models/form.model.ts) field model for the field to render
    -   _defaultValue:_ `Type<any>`  - Default type returned for field types that are not yet mapped.
    -   **Returns** `Type<any>` - Component type
-   **setComponentTypeResolver**(type: `string`, resolver: [`DynamicComponentResolveFunction`](lib/core/src/lib/services/dynamic-component-mapper.service.ts), override: `boolean` = `true`)

    Sets or optionally replaces a [DynamicComponentResolveFunction](lib/core/src/lib/services/dynamic-component-mapper.service.ts) for a field type.
    -   _type:_ `string`  - The type whose resolver you want to set
    -   _resolver:_ [`DynamicComponentResolveFunction`](lib/core/src/lib/services/dynamic-component-mapper.service.ts)  - The new resolver function
    -   _override:_ `boolean`  - The new resolver will only replace an existing one if this parameter is true

## Details

The [Card View component](../components/card-view.component.md) uses this service to find the component
type that is required to display a particular field type (text, date, etc). The service
maps a type name string to a corresponding [`DynamicComponentResolveFunction`](lib/core/src/lib/services/dynamic-component-mapper.service.ts) that takes a
model object as a parameter and returns the component type needed to display that model.

The default mapping is shown below:

| Type string | Component |
| ----------- | --------- |
| 'text' | [`CardViewTextItemComponent`](lib/core/src/lib/card-view/components/card-view-textitem/card-view-textitem.component.ts) |
| 'int' | [`CardViewTextItemComponent`](lib/core/src/lib/card-view/components/card-view-textitem/card-view-textitem.component.ts) |
| 'float' | [`CardViewTextItemComponent`](lib/core/src/lib/card-view/components/card-view-textitem/card-view-textitem.component.ts) |
| 'date' | [`CardViewDateItemComponent`](lib/core/src/lib/card-view/components/card-view-dateitem/card-view-dateitem.component.ts) |
| 'datetime' | [`CardViewDateItemComponent`](lib/core/src/lib/card-view/components/card-view-dateitem/card-view-dateitem.component.ts) |
| 'bool' | [`CardViewBoolItemComponent`](lib/core/src/lib/card-view/components/card-view-boolitem/card-view-boolitem.component.ts) |
| 'map' | [`CardViewMapItemComponent`](lib/core/src/lib/card-view/components/card-view-mapitem/card-view-mapitem.component.ts) |

### Adding new type mappings

You can define your own custom field types for the Card View (see the
[Card View Item interface](../interfaces/card-view-item.interface.md) page for full details of how to do this).
When you have defined the field component, you need to register it with the [Card Item Types service](lib/core/src/lib/card-view/services/card-item-types.service.ts)
so that the [Card View component](../components/card-view.component.md) can make use of it:

```ts
@Component({
    ...
    providers: [ CardItemTypeService ] /* If you don't want to pollute the main instance of the CardItemTypeService service */
    ...
})
export class SomeParentComponent {

    constructor(private cardItemTypeService: CardItemTypeService) {
        cardItemTypeService.setComponentTypeResolver('star-date', () => CardViewStarDateItemComponent);
    }
}
```

## See also

-   [Card View component](../components/card-view.component.md)
-   [Card View Item interface](../interfaces/card-view-item.interface.md)


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

using System;
using System.Text;

// Ivi type mapping
using ViStatus = System.Int32;
using ViSession = System.IntPtr;
using ViString = System.String;
using ViBoolean = System.Boolean;
using ViInt8 = System.Byte;
using ViInt16 = System.Int16;
using ViInt32 = System.Int32;
using ViAttr = System.UInt32;
using ViInt64 = System.Int64;
using ViReal64 = System.Double;

namespace IVI.C.NET.Adapter.IviCInterop
{
    public interface IviUpconverter : IviDriver
    {
        /*- IviUpconverterBase Functions -*/
        ViStatus ConfigureIFInputAttenuation(ViSession vi,
                                              ViReal64 attenuation);

        ViStatus ConfigureRFOutputEnabled(ViSession vi,
                                           ViBoolean enabled);

        ViStatus ConfigureRFOutputFrequency(ViSession vi,
                                             ViReal64 frequency);

        ViStatus GetIFInputName(ViSession vi,
                                 ViInt32 index,
                                 ViInt32 nameBufferSize,
                                 StringBuilder name);

        ViStatus GetRFOutputName(ViSession vi,
                                  ViInt32 index,
                                  ViInt32 nameBufferSize,
                                  StringBuilder name);

        ViStatus SetActiveIFInput(ViSession vi,
                                   ViString name);

        ViStatus SetActiveRFOutput(ViSession vi,
                                    ViString name);

        ViStatus WaitUntilReady(ViSession vi,
                                 ViInt32 maxTimeMilliseconds);

        /*- IviUpconverterOutputGain Functions -*/
        ViStatus ConfigureRFOutputGain(ViSession vi,
                                        ViReal64 gain);

        /*- IviUpconverterOutputPowerLevel Functions -*/
        ViStatus ConfigureRFOutputLevel(ViSession vi,
                                         ViReal64 level);

        /*- IviUpconverterModulateAM Functions -*/
        ViStatus ConfigureAM(ViSession vi,
                              ViString source,
                              ViInt32 scaling,
                              ViReal64 depth);

        ViStatus ConfigureAMEnabled(ViSession vi,
                                     ViBoolean enabled);

        ViStatus ConfigureAMExternalCoupling(ViSession vi,
                                              ViInt32 coupling);

        /*- IviUpconverterModulateFM Functions -*/
        ViStatus ConfigureFM(ViSession vi,
                              ViString source,
                              ViReal64 deviation);

        ViStatus ConfigureFMEnabled(ViSession vi,
                                     ViBoolean enabled);

        ViStatus ConfigureFMExternalCoupling(ViSession vi,
                                              ViInt32 coupling);

        /*- IviUpconverterModulatePM Functions -*/
        ViStatus ConfigurePM(ViSession vi,
                              ViString source,
                              ViReal64 deviation);

        ViStatus ConfigurePMEnabled(ViSession vi,
                                     ViBoolean enabled);

        ViStatus ConfigurePMExternalCoupling(ViSession vi,
                                              ViInt32 coupling);

        /*- IviUpconverterAnalogModulationSource Functions -*/
        ViStatus GetAnalogModulationSourceName(ViSession vi,
                                                ViInt32 index,
                                                ViInt32 nameBufferSize,
                                                StringBuilder name);

        /*- IviUpconverterModulatePulse Functions -*/
        ViStatus ConfigurePulseModulationEnabled(ViSession vi,
                                                  ViBoolean enabled);

        ViStatus ConfigurePulseModulationExternalPolarity(ViSession vi,
                                                           ViInt32 polarity);

        /*- IviUpconverterBypass Functions -*/
        ViStatus ConfigureBypass(ViSession vi,
                                  ViBoolean bypass);

        /*- IviUpconverterOutputReadyTrigger Functions -*/
        ViStatus ConfigureRFOutputReadyTrigger(ViSession vi,
                                                ViString outputTrigger);

        /*- IviUpconverterSweep Functions -*/
        ViStatus ConfigureSweep(ViSession vi,
                                 ViInt32 mode,
                                 ViString triggerSource);

        /*- IviUpconverterFrequencySweep Functions -*/
        ViStatus ConfigureFrequencySweepCenterSpan(ViSession vi,
                                                    ViReal64 center,
                                                    ViReal64 span);

        ViStatus ConfigureFrequencySweepStartStop(ViSession vi,
                                                   ViReal64 start,
                                                   ViReal64 stop);

        ViStatus ConfigureFrequencySweepTime(ViSession vi,
                                              ViReal64 sweepTime);

        /*- IviUpconverterPowerSweep Functions -*/
        ViStatus ConfigurePowerSweepStartStop(ViSession vi,
                                               ViReal64 start,
                                               ViReal64 stop);

        ViStatus ConfigurePowerSweepTime(ViSession vi,
                                          ViReal64 sweepTime);

        /*- IviUpconverterGainSweep Functions -*/
        ViStatus ConfigureGainSweepStartStop(ViSession vi,
                                              ViReal64 start,
                                              ViReal64 stop);

        ViStatus ConfigureGainSweepTime(ViSession vi,
                                         ViReal64 sweepTime);

        /*- IviUpconverterFrequencyStep Functions -*/
        ViStatus ConfigureFrequencyStepDwell(ViSession vi,
                                              ViBoolean singleStepEnabled,
                                              ViReal64 dwell);

        ViStatus ConfigureFrequencyStepStartStop(ViSession vi,
                                                  ViReal64 start,
                                                  ViReal64 stop,
                                                  ViInt32 scaling,
                                                  ViReal64 stepSize);

        ViStatus ResetFrequencyStep(ViSession vi);

        /*- IviUpconverterPowerStep Functions -*/
        ViStatus ConfigurePowerStepDwell(ViSession vi,
                                          ViBoolean singleStepEnabled,
                                          ViReal64 dwell);

        ViStatus ConfigurePowerStepStartStop(ViSession vi,
                                              ViReal64 start,
                                              ViReal64 stop,
                                              ViReal64 stepSize);

        ViStatus ResetPowerStep(ViSession vi);

        /*- IviUpconverterGainStep Functions -*/
        ViStatus ConfigureGainStepDwell(ViSession vi,
                                         ViBoolean singleStepEnabled,
                                         ViReal64 dwell);

        ViStatus ConfigureGainStepStartStop(ViSession vi,
                                             ViReal64 start,
                                             ViReal64 stop,
                                             ViReal64 stepSize);

        ViStatus ResetGainStep(ViSession vi);

        /*- IviUpconverterList Functions -*/
        ViStatus ClearAllLists(ViSession vi);

        ViStatus ConfigureListDwell(ViSession vi,
                                     ViBoolean singleStepEnabled,
                                     ViReal64 dwell);

        ViStatus CreateFrequencyList(ViSession vi,
                                      ViString name,
                                      ViInt32 frequencyBufferSize,
                                      ViReal64[] frequency);

        ViStatus CreateFrequencyPowerList(ViSession vi,
                                           ViString name,
                                           ViInt32 bufferSize,
                                           ViReal64[] frequency,
                                           ViReal64[] power);

        ViStatus CreateFrequencyGainList(ViSession vi,
                                          ViString name,
                                          ViInt32 bufferSize,
                                          ViReal64[] frequency,
                                          ViReal64[] gain);

        ViStatus CreatePowerList(ViSession vi,
                                  ViString name,
                                  ViInt32 powerBufferSize,
                                  ViReal64[] power);

        ViStatus CreateGainList(ViSession vi,
                                 ViString name,
                                 ViInt32 gainBufferSize,
                                 ViReal64[] gain);

        ViStatus ResetList(ViSession vi);

        /*- IviUpconverterALC Functions -*/
        ViStatus ConfigureALC(ViSession vi,
                               ViInt32 source,
                               ViReal64 bandwidth);

        /*- IviUpconverterCalibration Functions -*/
        ViStatus Calibrate(ViSession vi);

        ViStatus IsCalibrationComplete(ViSession vi,
                                        ref ViInt32 status);

        /*- IviUpconverterAttenuatorHold Functions -*/
        ViStatus ConfigureAttenuatorHoldEnabled(ViSession vi,
                                                 ViBoolean enabled);

        /*- IviUpconverterReferenceOscillator Functions -*/
        ViStatus ConfigureReferenceOscillator(ViSession vi,
                                               ViInt32 source,
                                               ViReal64 frequency);

        ViStatus ConfigureReferenceOscillatorOutputEnabled(ViSession vi,
                                                            ViBoolean enabled);

        /*- IviUpconverterSoftwareTrigger Functions -*/
        ViStatus SendSoftwareTrigger(ViSession vi);

        /*- IviUpconverterModulateIQ Functions -*/
        ViStatus CalibrateIQ(ViSession vi);

        ViStatus ConfigureIQEnabled(ViSession vi,
                                     ViBoolean enabled);

        /*- IviUpconverterIQImpairment Functions -*/
        ViStatus ConfigureIQImpairment(ViSession vi,
                                        ViReal64 IOffset,
                                        ViReal64 QOffset,
                                        ViReal64 ratio,
                                        ViReal64 skew);

        ViStatus ConfigureIQImpairmentEnabled(ViSession vi,
                                               ViBoolean enabled);
    }
}


text:
import isCubeNumber = require( './index' );

// TESTS //

// The function returns a boolean...
{
	isCubeNumber( 3 ); // $ExpectType boolean
	isCubeNumber( 0.2 ); // $ExpectType boolean
}

// The compiler throws an error if the function is provided an unsupported number of arguments...
{
	isCubeNumber(); // $ExpectError
	isCubeNumber( 0.2, 123 ); // $ExpectError
}

// Attached to main export is an isPrimitive method which returns a boolean...
{
	// tslint:disable-next-line:no-construct
	isCubeNumber.isPrimitive( new Number( 0.2 ) ); // $ExpectType boolean
	isCubeNumber.isPrimitive( 0.2 ); // $ExpectType boolean
}

// The compiler throws an error if the isPrimitive method is provided an unsupported number of arguments...
{
	isCubeNumber.isPrimitive(); // $ExpectError
	isCubeNumber.isPrimitive( 0.2, 123 ); // $ExpectError
}

// Attached to main export is an isPrimitive method which returns a boolean...
{
	// tslint:disable-next-line:no-construct
	isCubeNumber.isObject( new Number( 0.2 ) ); // $ExpectType boolean
	isCubeNumber.isObject( 0.2 ); // $ExpectType boolean
}

// The compiler throws an error if the isObject method is provided an unsupported number of arguments...
{
	isCubeNumber.isObject(); // $ExpectError
	isCubeNumber.isObject( 0.2, 123 ); // $ExpectError
}


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

    <string name="nothing">no</string>
	<string name="app_name">PPecrou</string>
    <string name="action_settings">Settings</string>
    <string name="action_reset">Reset</string>
    <string name="action_actualise">Actualise</string>
    <string name="hello_world">Hello world!</string>
    <string name="pince">Pince</string>
    <string name="pas">Pas</string>
    <string name="eurocode">Euro Code</string>
    <string name="cm66">CM66</string>
    <string name="boulonordinaire">Boulon Ordinaire</string>
    <string name="boulonHR">Boulon HR</string>
    <string name="d0">d0</string>
    <string name="t">t</string>

</resources>


text:
package quasar.precog.common

import quasar.blueeyes._
import quasar.precog._
import quasar.precog.util.{BitSetUtil, ByteBufferMonad, ByteBufferPool, RawBitSet}

import java.nio.{ByteBuffer, CharBuffer}
import java.nio.charset.{CharsetEncoder, CoderResult}
import java.math.{BigDecimal => BigDec}
import java.time.{LocalDateTime, ZonedDateTime}
import java.time.format.DateTimeFormatter

import scala.annotation.tailrec
import scala.specialized

import scalaz._

/**
  * Codecs allow a writer to deal with the case where we have a buffer overflow
  * when attempting to write all data to the buffer. This lets the writer return
  * some state indicating more data needs to be written. This state is then
  * given to a `writeMore` method so it can finish the writing. It may take
  * several calls to `writeMore` before it all is finally written.
  */
trait Codec[@specialized(Boolean, Long, Double) A] { self =>
  type S

  /** Returns the exact encoded size of `a`. */
  def encodedSize(a: A): Int

  /** Returns an upper bound on the size of `a`. */
  def maxSize(a: A): Int = encodedSize(a)

  /**
    * Returns a lower bound on the space required in a buffer so that `a` can
    * be written.
    */
  def minSize(a: A): Int = 8

  /**
    * Initiate a write. If a is successfully written (in its entirety) to
    * `buffer`, then `None` is returned. Otherwise, `Some(s)` is returned,
    * indicating that some more data (ie. `s`) still needs to be written using
    * `writeMore(s, _)`. This last condition will normally happen when we run
    * out of space in the buffer, so `a` was only partially written.
    */
  def writeInit(a: A, buffer: ByteBuffer): Option[S]

  /**
    * Writes the remaining data from a call to `writeInit` to `buffer`. If this
    * is written completely and successfully, `None` is returned. Otherwise,
    * `Some(s2)` is returned, which contains more data to be written with
    * `writeMore`.
    */
  def writeMore(s: S, buffer: ByteBuffer): Option[S]

  /**
    * Writes `a` using a `ByteBufferMonad`. This is much slower than just using
    * writeInit/writeMore.
    */
  def write[M[_]](a: A)(implicit M: ByteBufferMonad[M]): M[Unit] = {
    import scalaz.syntax.monad._

    val min = minSize(a)

    def loop(s: S): M[Unit] =
      for {
        buf <- M.getBuffer(min)
        _ <- writeMore(s, buf) map (loop(_)) getOrElse ().point[M]
      } yield ()

    for {
      buf <- M.getBuffer(min)
      _ <- writeInit(a, buf) map (loop(_)) getOrElse ().point[M]
    } yield ()
  }

  /**
    * Writes `a` entirely to a series of `ByteBuffer`s returned by `acquire`.
    * The returned set of `ByteBuffer`s is in reverse order, so that calls
    * to `writeAll` can be chained by passing in the previous result to `used`.
    */
  def writeAll(a: A)(acquire: () => ByteBuffer, used: List[ByteBuffer] = Nil): List[ByteBuffer] = {
    @inline
    @tailrec def loop(s: Option[S], buffers: List[ByteBuffer]): List[ByteBuffer] = s match {
      case None => buffers
      case Some(s) =>
        val buf = acquire()
        loop(writeMore(s, buf), buf :: buffers)
    }

    used match {
      case buffers @ (buf :: _) if buf.remaining() >= minSize(a) =>
        loop(writeInit(a, buf), buffers)

      case buffers =>
        val buf = acquire()
        loop(writeInit(a, buf), buf :: buffers)
    }
  }

  /**
    * Performs an *unsafe* write of `a` to `buffer`. This does not perform any
    * safety checks and assumes `buffer` has at least `encodedSize(a)` bytes
    * remaining. The behaviour if this is not the case is undefined.
    */
  def writeUnsafe(a: A, buffer: ByteBuffer): Unit

  /**
    * Reads a value of type `A` from `buffer`. This should generally follow the
    * contract that `writeUnsafe(a, buffer); read(buffer) == a`.
    */
  def read(buffer: ByteBuffer): A

  /**
    * This is similar to `read(buffer)`, except that a value does not actually
    * need to be returned.
    */
  def skip(buffer: ByteBuffer): Unit = read(buffer)

  def as[B](to: B => A, from: A => B): Codec[B] = new Codec[B] {
    type S = self.S

    def encodedSize(b: B)      = self.encodedSize(to(b))
    override def maxSize(b: B) = self.maxSize(to(b))
    override def minSize(b: B) = self.minSize(to(b))

    def writeUnsafe(b: B, buf: ByteBuffer) = self.writeUnsafe(to(b), buf)
    def writeInit(b: B, buf: ByteBuffer)   = self.writeInit(to(b), buf)
    def writeMore(s: S, buf: ByteBuffer)   = self.writeMore(s, buf)

    def read(src: ByteBuffer): B = from(self.read(src))
  }
}

object Codec {

  @inline final def apply[A](implicit codec: Codec[A]): Codec[A] = codec

  private val byteBufferPool = new ByteBufferPool()

  implicit def IndexedSeqCodec[A](implicit elemCodec: Codec[A]) = new IndexedSeqCodec(elemCodec)

  implicit def arrayCodec[@specialized(Boolean, Long, Double) A: Codec: CTag]: Codec[Array[A]] = ArrayCodec(Codec[A])

  /**
    * A utility method for getting the encoded version of `a` as an array of
    * bytes.
    */
  def writeToArray[A](a: A)(implicit codec: Codec[A]): Array[Byte] = {
    import ByteBufferPool._

    byteBufferPool.run(for {
      _ <- codec.write[ByteBufferPoolS](a)
      bytes <- flipBytes
      _ <- release
    } yield bytes)
  }

  private final val FALSE_VALUE = 0.toByte
  private final val TRUE_VALUE  = 1.toByte

  @tailrec
  def writePackedInt(n: Int, buf: ByteBuffer): Unit =
    if ((n & ~0x7F) != 0) {
      buf.put((n & 0x7F | 0x80).toByte)
      writePackedInt(n >> 7, buf)
    } else {
      buf.put((n & 0x7F).toByte)
    }

  def readPackedInt(buf: ByteBuffer): Int = {
    @tailrec def loop(n: Int, offset: Int): Int = {
      val b = buf.get()
      if ((b & 0x80) != 0) {
        loop(n | ((b & 0x7F) << offset), offset + 7)
      } else {
        n | ((b & 0x7F) << offset)
      }
    }
    loop(0, 0)
  }

  @tailrec
  def sizePackedInt(n: Int, size: Int = 1): Int =
    if ((n & ~0x7F) != 0) {
      sizePackedInt(n >>> 7, size + 1)
    } else size

  case class CompositeCodec[A, B, C](codecA: Codec[A], codecB: Codec[B], from: C => (A, B), to: (A, B) => C) extends Codec[C] {
    type S = Either[(codecA.S, B), codecB.S]

    def encodedSize(c: C) = {
      val (a, b) = from(c)
      codecA.encodedSize(a) + codecB.encodedSize(b)
    }

    override def minSize(c: C) = codecA.minSize(from(c)._1) max codecB.minSize(from(c)._2)
    override def maxSize(c: C) = {
      val (a, b) = from(c)
      codecA.maxSize(a) + codecB.maxSize(b)
    }

    def writeUnsafe(c: C, buf: ByteBuffer) {
      val (a, b) = from(c)
      codecA.writeUnsafe(a, buf)
      codecB.writeUnsafe(b, buf)
    }

    def writeInit(c: C, buf: ByteBuffer): Option[S] = {
      val (a, b) = from(c)
      (codecA.writeInit(a, buf) map (s => Left((s, b)))) orElse (codecB.writeInit(b, buf) map (Right(_)))
    }

    def writeMore(more: S, buf: ByteBuffer) = more match {
      case Left((s, b)) => (codecA.writeMore(s, buf) map (s => Left((s, b)))) orElse (codecB.writeInit(b, buf) map (Right(_)))
      case Right(s)     => codecB.writeMore(s, buf) map (Right(_))
    }

    def read(buf: ByteBuffer): C = to(codecA.read(buf), codecB.read(buf))
    override def skip(buf: ByteBuffer) {
      codecA.skip(buf)
      codecB.skip(buf)
    }
  }

  trait FixedWidthCodec[@specialized(Boolean, Long, Double) A] extends Codec[A] {
    type S = A

    def size: Int

    def encodedSize(a: A)      = size
    override def maxSize(a: A) = size
    override def minSize(a: A) = size

    def writeInit(a: A, b: ByteBuffer): Option[A] =
      if (b.remaining >= size) {
        writeUnsafe(a, b)
        None
      } else {
        Some(a)
      }

    def writeMore(a: A, b: ByteBuffer): Option[A] = writeInit(a, b)
    override def skip(buf: ByteBuffer) {
      buf.position(buf.position() + size)
    }
  }

  case class ConstCodec[A](a: A) extends FixedWidthCodec[A] {
    val size = 0
    def writeUnsafe(a: A, sink: ByteBuffer): Unit = ()
    def read(buffer: ByteBuffer): A               = a
    override def skip(buf: ByteBuffer) {}
  }

  implicit case object ByteCodec extends FixedWidthCodec[Byte] {
    val size = 1
    def writeUnsafe(x: Byte, sink: ByteBuffer) { sink.put(x) }
    def read(src: ByteBuffer): Byte = src.get()
  }

  implicit case object BooleanCodec extends FixedWidthCodec[Boolean] {
    val size = 1
    def writeUnsafe(x: Boolean, sink: ByteBuffer) {
      if (x) sink.put(TRUE_VALUE) else sink.put(FALSE_VALUE)
    }
    def read(src: ByteBuffer): Boolean = src.get() match {
      case TRUE_VALUE  => true
      case FALSE_VALUE => false
      case invalid     => sys.error("Error reading boolean: expecting %d or %d, found %d" format (TRUE_VALUE, FALSE_VALUE, invalid))
    }
  }

  case object LongCodec extends FixedWidthCodec[Long] {
    val size = 8
    def writeUnsafe(n: Long, sink: ByteBuffer) { sink.putLong(n) }
    def read(src: ByteBuffer): Long = src.getLong()
  }

  implicit case object PackedLongCodec extends Codec[Long] {
    type S = Long

    override def maxSize(n: Long) = 10
    override def minSize(n: Long) = 10

    def encodedSize(sn: Long) = {
      @tailrec def loop(size: Int, n: Long): Int = {
        if ((n & ~0x7FL) != 0) loop(size + 1, n >> 7) else size
      }

      val n = if (sn < 0) ~sn else sn
      if ((n & ~0x3FL) != 0) loop(2, n >> 6) else 1
    }

    def writeInit(n: Long, buf: ByteBuffer): Option[S] = {
      if (buf.remaining() < 10) {
        Some(n)
      } else {
        writeUnsafe(n, buf)
        None
      }
    }

    def writeMore(n: Long, buf: ByteBuffer): Option[S] = writeInit(n, buf)

    def writeUnsafe(sn: Long, buf: ByteBuffer) {

      @inline
      @tailrec
      def loop(n: Long): Unit = if (n != 0) {
        buf.put(if ((n & ~0x7FL) != 0) (n & 0x7FL | 0x80L).toByte else (n & 0x7FL).toByte)
        loop(n >> 7)
      }

      var n = sn
      val lo = if (sn < 0) {
        n = ~sn
        n & 0x3FL | 0x40L
      } else {
        n & 0x3FL
      }

      if ((~0x3FL & n) != 0) {
        buf.put((lo | 0x80L).toByte)
        loop(n >> 6)
      } else {
        buf.put(lo.toByte)
      }
    }

    def read(buf: ByteBuffer): Long = {
      @inline
      @tailrec def loop(offset: Int, n: Long): Long = {
        val lo = buf.get().toLong
        val nn = n | ((lo & 0x7FL) << offset)
        if ((lo & 0x80L) != 0) loop(offset + 7, nn) else nn
      }

      val lo = buf.get().toLong
      val n  = if ((lo & 0x80L) != 0) loop(6, lo & 0x3FL) else (lo & 0x3FL)
      if ((lo & 0x40L) != 0) ~n else n
    }

    override def skip(buf: ByteBuffer) {
      while ((buf.get() & ~0x7F) != 0) {
        // Spin.
      }
    }
  }

  implicit val LocalDateTimeCodec =
    Codec[Long].as[LocalDateTime](_.getMillis, dateTime.fromMillis)

  implicit val ZonedDateTimeCodec = {
    val formatter = DateTimeFormatter.ISO_ZONED_DATE_TIME
    Utf8Codec.as[ZonedDateTime](_.format(formatter), ZonedDateTime.parse(_, formatter))
  }

  implicit val PeriodCodec =
    Codec[Long].as[Period](_.getMillis, period.fromMillis)

  implicit case object DoubleCodec extends FixedWidthCodec[Double] {
    val size = 8
    def writeUnsafe(n: Double, sink: ByteBuffer) { sink.putDouble(n) }
    def read(src: ByteBuffer): Double = src.getDouble()
  }

  implicit case object Utf8Codec extends Codec[String] {

    type S = Either[String, (CharBuffer, CharsetEncoder)]

    override def maxSize(s: String) = s.length * 4 + 5
    override def minSize(s: String) = 5

    def encodedSize(s: String): Int = {
      val size0 = strEncodedSize(s)
      size0 + sizePackedInt(size0)
    }

    private def strEncodedSize(s: String): Int = {
      var i    = 0
      var size = 0
      while (i < s.length) {
        val ch = s.codePointAt(i)
        if (ch < 0x80) {
          size += 1
        } else if (ch < 0x800) {
          size += 2
        } else if (ch < 0x10000) {
          size += 3
        } else {
          size += 4
          i += 1
        }
        i += 1
      }
      size
    }

    def writeUnsafe(a: String, sink: ByteBuffer) {
      val bytes = a.getBytes(Utf8Charset)
      writePackedInt(bytes.length, sink)
      sink.put(a.getBytes(Utf8Charset))
    }

    def writeInit(a: String, sink: ByteBuffer): Option[S] = {
      if (sink.remaining < 5) Some(Left(a))
      else {
        writePackedInt(strEncodedSize(a), sink)

        val source  = CharBuffer.wrap(a)
        val encoder = Utf8Charset.newEncoder

        if (encoder.encode(source, sink, true) == CoderResult.OVERFLOW) {
          Some(Right((source, encoder)))
        } else {
          None
        }
      }
    }

    def writeMore(more: S, sink: ByteBuffer): Option[S] = more match {
      case Left(a) => writeInit(a, sink)
      case Right((source, encoder)) =>
        if ((encoder.encode(source, sink, true) == CoderResult.OVERFLOW) ||
            (encoder.flush(sink) == CoderResult.OVERFLOW)) {
          Some(Right((source, encoder)))
        } else {
          None
        }
    }

    def read(src: ByteBuffer): String = {
      val bytes = new Array[Byte](readPackedInt(src))
      src.get(bytes)
      new String(bytes, Utf8Charset)
    }

    override def skip(buf: ByteBuffer) {
      val len = readPackedInt(buf)
      buf.position(buf.position() + len)
    }

    def compare(a: ByteBuffer, b: ByteBuffer): Int = {
      val alen = readPackedInt(a)
      val blen = readPackedInt(b)
      var cmp = 0
      var pos = 0
      val len = if (alen < blen) alen else blen
      while (cmp == 0 && pos < len) {
        cmp = (a.get() & 0xFF) - (b.get() & 0xFF)
        pos += 1
      }

      a.position(a.position() + (alen - pos))
      b.position(b.position() + (blen - pos))

      if (cmp == 0) {
        alen - blen
      } else {
        cmp
      }
    }
  }

  implicit val JBigDecimalCodec = CompositeCodec[Array[Byte], Long, BigDec](
    arrayCodec[Byte],
    PackedLongCodec,
    x => (x.unscaledValue.toByteArray, x.scale.toLong),
    (u, s) => new BigDec(new java.math.BigInteger(u), s.toInt))

  implicit val BigDecimalCodec = JBigDecimalCodec.as[BigDecimal](_.underlying, BigDecimal(_, java.math.MathContext.UNLIMITED))

  final class IndexedSeqCodec[A](val elemCodec: Codec[A]) extends Codec[IndexedSeq[A]] {

    type S = Either[IndexedSeq[A], (elemCodec.S, List[A])]

    override def minSize(as: IndexedSeq[A]): Int = 5
    override def maxSize(as: IndexedSeq[A]): Int =
      as.foldLeft(0) { (acc, a) =>
        acc + elemCodec.maxSize(a)
      } + 5

    def encodedSize(as: IndexedSeq[A]): Int = {
      val size = as.foldLeft(0) { (acc, a) =>
        acc + elemCodec.encodedSize(a)
      }
      size + sizePackedInt(as.size)
    }

    def writeUnsafe(as: IndexedSeq[A], sink: ByteBuffer) {
      writePackedInt(as.length, sink)
      as foreach { elemCodec.writeUnsafe(_, sink) }
    }

    @tailrec
    private def writeArray(as: List[A], sink: ByteBuffer): Option[S] = as match {
      case a :: as =>
        elemCodec.writeInit(a, sink) match {
          case Some(s) => Some(Right((s, as)))
          case None    => writeArray(as, sink)
        }
      case _ => None
    }

    def writeInit(as: IndexedSeq[A], sink: ByteBuffer): Option[S] = {
      if (sink.remaining < 5) Some(Left(as))
      else {
        writePackedInt(as.length, sink)
        writeArray(as.toList, sink)
      }
    }

    def writeMore(more: S, sink: ByteBuffer): Option[S] = more match {
      case Left(as)       => writeInit(as, sink)
      case Right((s, as)) => elemCodec.writeMore(s, sink) map (Right(_, as)) orElse writeArray(as.toList, sink)
    }

    def read(src: ByteBuffer): IndexedSeq[A] =
      ((0 until readPackedInt(src)) map (_ => elemCodec.read(src))).toIndexedSeq

    override def skip(buf: ByteBuffer) {
      (0 until readPackedInt(buf)) foreach { _ =>
        elemCodec.skip(buf)
      }
    }
  }
  case class ArrayCodec[@specialized(Boolean, Long, Double) A: CTag](elemCodec: Codec[A]) extends Codec[Array[A]] {
    type S = Either[Array[A], (elemCodec.S, Array[A], Int)]

    override def minSize(as: Array[A]): Int = 5
    override def maxSize(as: Array[A]): Int = {
      @tailrec
      def loop(row: Int, size: Int): Int =
        if (row < as.length) {
          loop(row + 1, size + elemCodec.maxSize(as(row)))
        } else size

      loop(0, 5)
    }

    def encodedSize(as: Array[A]): Int = {
      @tailrec
      def loop(row: Int, size: Int): Int =
        if (row < as.length) {
          loop(row + 1, size + elemCodec.encodedSize(as(row)))
        } else size
      loop(0, sizePackedInt(as.length))
    }

    def writeUnsafe(as: Array[A], sink: ByteBuffer) {
      writePackedInt(as.length, sink)
      @tailrec
      def loop(row: Int): Unit = if (row < as.length) {
        elemCodec.writeUnsafe(as(row), sink)
        loop(row + 1)
      }
      loop(0)
    }

    @tailrec
    private def writeArray(as: Array[A], row: Int, sink: ByteBuffer): Option[S] =
      if (row < as.length) {
        elemCodec.writeInit(as(row), sink) match {
          case Some(s) => Some(Right((s, as, row + 1)))
          case None    => writeArray(as, row + 1, sink)
        }
      } else None

    def writeInit(as: Array[A], sink: ByteBuffer): Option[S] = {
      if (sink.remaining < 5) Some(Left(as))
      else {
        writePackedInt(as.length, sink)
        writeArray(as, 0, sink)
      }
    }

    def writeMore(more: S, sink: ByteBuffer): Option[S] = more match {
      case Left(as)            => writeInit(as, sink)
      case Right((s, as, row)) => elemCodec.writeMore(s, sink) map (s => Right((s, as, row))) orElse writeArray(as, row, sink)
    }

    def read(src: ByteBuffer): Array[A] = {
      val dst = new Array[A](readPackedInt(src))
      var row = 0
      while (row < dst.length) {
        dst(row) = elemCodec.read(src)
        row += 1
      }
      dst
    }

    override def skip(buf: ByteBuffer) {
      val length = readPackedInt(buf)
      var i = 0
      while (i < length) { elemCodec.skip(buf); i += 1 }
    }
  }

  /** A Codec that can (un)wrap CValues of type CValueType. */
  case class CValueCodec[A](cType: CValueType[A])(implicit val codec: Codec[A]) extends Codec[CWrappedValue[A]] {
    type S = codec.S
    def encodedSize(a: CWrappedValue[A])                   = codec.encodedSize(a.value)
    def writeUnsafe(a: CWrappedValue[A], sink: ByteBuffer) = codec.writeUnsafe(a.value, sink)
    def writeInit(a: CWrappedValue[A], sink: ByteBuffer)   = codec.writeInit(a.value, sink)
    def writeMore(s: S, sink: ByteBuffer)                  = codec.writeMore(s, sink)
    def read(src: ByteBuffer)                              = cType(codec.read(src))
    override def skip(buf: ByteBuffer)                     = codec.skip(buf)
  }

  // Problem: This can't be specialised.
  trait StatefulCodec {
    type A
    val codec: Codec[A]

    def init(a: A, sink: ByteBuffer): Option[State] =
      codec.writeInit(a, sink) map (State(_))

    case class State(s: codec.S) {
      def more(sink: ByteBuffer): Option[State] = codec.writeMore(s, sink) map (State(_))
    }
  }

  def wrappedWriteInit[AA](a: AA, sink: ByteBuffer)(implicit _codec: Codec[AA]): Option[StatefulCodec#State] =
    (new StatefulCodec {
      type A = AA
      val codec = _codec
    }).init(a, sink)

  implicit val BitSetCodec = ArrayCodec[Long](LongCodec)(implicitly).as[BitSet](_.getBits, BitSetUtil.fromArray)

  case class SparseBitSetCodec(size: Int) extends Codec[BitSet] {

    // The maxBytes is max. bits / 8 = (highestOneBit(size) << 3) / 8
    private val maxBytes = java.lang.Integer.highestOneBit(size) max 1

    type S = (Array[Byte], Int)

    def encodedSize(bs: BitSet)      = writeBitSet(bs).size
    override def maxSize(bs: BitSet) = maxBytes

    def writeUnsafe(bs: BitSet, sink: ByteBuffer) {
      sink.put(writeBitSet(bs))
    }

    def writeInit(bs: BitSet, sink: ByteBuffer): Option[S] = {
      val spaceLeft = sink.remaining()
      val bytes     = writeBitSet(bs)

      if (spaceLeft >= bytes.length) {
        sink.put(bytes)
        None
      } else {
        sink.put(bytes, 0, spaceLeft)
        Some((bytes, spaceLeft))
      }
    }

    def writeMore(more: S, sink: ByteBuffer): Option[S] = {
      val (bytes, offset) = more
      val bytesLeft       = bytes.length - offset
      val spaceLeft       = sink.remaining()

      if (spaceLeft >= bytesLeft) {
        sink.put(bytes, offset, bytesLeft)
        None
      } else {
        sink.put(bytes, offset, spaceLeft)
        Some((bytes, offset + spaceLeft))
      }
    }

    def read(src: ByteBuffer): BitSet = readBitSet(src)

    override def skip(buf: ByteBuffer) {
      var b = buf.get()
      while ((b & 3) != 0 && (b & 12) != 0 && (b & 48) != 0 && (b & 192) != 0) {
        b = buf.get()
      }
    }

    def writeBitSet(bs: BitSet): Array[Byte] = {
      val bytes = new Array[Byte](maxBytes)

      def set(offset: Int) {
        val i = offset >>> 3
        bytes(i) = ((1 << (offset & 0x7)) | bytes(i).toInt).toByte
      }

      def rec(bs: List[Int], l: Int, r: Int, offset: Int): Int = {
        val c = (l + r) / 2

        if (l == r) {
          offset
        } else if (r - l == 1) {
          if (bs == (l :: Nil)) {
            set(offset)
          }
          set(offset + 1)
          offset + 2
        } else {
          bs partition (_ < c) match {
            case (Nil, Nil) =>
              offset
            case (Nil, hi) =>
              set(offset + 1)
              rec(hi, c, r, offset + 2)
            case (lo, Nil) =>
              set(offset)
              rec(lo, l, c, offset + 2)
            case (lo, hi) =>
              set(offset)
              set(offset + 1)
              rec(hi, c, r, rec(lo, l, c, offset + 2))
          }
        }
      }

      val len = rec(bs.toList, 0, size, 0)
      java.util.Arrays.copyOf(bytes, (len >>> 3) + 1) // The +1 covers the extra 2 '0' bits.
    }

    def readBitSet(src: ByteBuffer): BitSet = {
      val pos = src.position()
      @inline def get(offset: Int): Boolean =
        (src.get(pos + (offset >>> 3)) & (1 << (offset & 7))) != 0

      val bits = new BitSet
      def read(l: Int, r: Int, offset: Int): Int = {
        if (l == r) {
          offset
        } else if (r - l == 1) {
          if (get(offset)) {
            bits(l) = true
          }
          offset + 2
        } else {
          val c = (l + r) / 2
          (get(offset), get(offset + 1)) match {
            case (false, false) => offset + 2
            case (false, true)  => read(c, r, offset + 2)
            case (true, false)  => read(l, c, offset + 2)
            case (true, true)   => read(c, r, read(l, c, offset + 2))
          }
        }
      }

      val offset = read(0, size, 0)
      src.position(pos + (offset >>> 3) + 1)
      bits
    }
  }

  case class SparseRawBitSetCodec(size: Int) extends Codec[Array[Int]] {

    // The maxBytes is max. bits / 8 = (highestOneBit(size) << 3) / 8
    private val maxBytes = java.lang.Integer.highestOneBit(size) max 1

    type S = (Array[Byte], Int)

    def encodedSize(bs: Array[Int])      = writeBitSet(bs).size
    override def maxSize(bs: Array[Int]) = maxBytes

    def writeUnsafe(bs: Array[Int], sink: ByteBuffer) {
      sink.put(writeBitSet(bs))
    }

    def writeInit(bs: Array[Int], sink: ByteBuffer): Option[S] = {
      val spaceLeft = sink.remaining()
      val bytes     = writeBitSet(bs)

      if (spaceLeft >= bytes.length) {
        sink.put(bytes)
        None
      } else {
        sink.put(bytes, 0, spaceLeft)
        Some((bytes, spaceLeft))
      }
    }

    def writeMore(more: S, sink: ByteBuffer): Option[S] = {
      val (bytes, offset) = more
      val bytesLeft       = bytes.length - offset
      val spaceLeft       = sink.remaining()

      if (spaceLeft >= bytesLeft) {
        sink.put(bytes, offset, bytesLeft)
        None
      } else {
        sink.put(bytes, offset, spaceLeft)
        Some((bytes, offset + spaceLeft))
      }
    }

    def read(src: ByteBuffer): Array[Int] = readBitSet(src)

    override def skip(buf: ByteBuffer) {
      var b = buf.get()
      while ((b & 3) != 0 && (b & 12) != 0 && (b & 48) != 0 && (b & 192) != 0) {
        b = buf.get()
      }
    }

    def writeBitSet(bs: Array[Int]): Array[Byte] = {
      val bytes = new Array[Byte](maxBytes)

      def set(offset: Int) {
        val i = offset >>> 3
        bytes(i) = ((1 << (offset & 0x7)) | bytes(i).toInt).toByte
      }

      val arr = RawBitSet.toArray(bs)
      def rec_(start: Int, end: Int, l: Int, r: Int, offset: Int): Int = {

        if (l == r) return offset

        if (r - l == 1) {
          if (arr(start) == l) set(offset)
          set(offset + 1)
          return offset + 2
        }

        val c = (l + r) / 2
        var i = start
        while (arr(i) < c && i < end) i += 1

        if (i == start) {
          if (i == end) {
            offset
          } else {
            set(offset + 1)
            rec_(i, end, c, r, offset + 2)
          }
        } else {
          if (i == end) {
            set(offset)
            rec_(start, i, l, c, offset + 2)
          } else {
            set(offset)
            set(offset + 1)
            rec_(i, end, c, r, rec_(start, i, l, c, offset + 2))
          }
        }
      }

      def rec(bs: List[Int], l: Int, r: Int, offset: Int): Int = {
        val c = (l + r) / 2

        if (l == r) {
          offset
        } else if (r - l == 1) {
          if (bs == (l :: Nil)) {
            set(offset)
          }
          set(offset + 1)
          offset + 2
        } else {
          bs partition (_ < c) match {
            case (Nil, Nil) =>
              offset
            case (Nil, hi) =>
              set(offset + 1)
              rec(hi, c, r, offset + 2)
            case (lo, Nil) =>
              set(offset)
              rec(lo, l, c, offset + 2)
            case (lo, hi) =>
              set(offset)
              set(offset + 1)
              rec(hi, c, r, rec(lo, l, c, offset + 2))
          }
        }
      }

      val len = rec(RawBitSet.toList(bs), 0, size, 0)
      java.util.Arrays.copyOf(bytes, (len >>> 3) + 1) // The +1 covers the extra 2 '0' bits.
    }

    def readBitSet(src: ByteBuffer): Array[Int] = {
      val pos = src.position()
      @inline def get(offset: Int): Boolean =
        (src.get(pos + (offset >>> 3)) & (1 << (offset & 7))) != 0

      val bits = RawBitSet.create(size)

      def read(l: Int, r: Int, offset: Int): Int = {
        if (l == r) {
          offset
        } else if (r - l == 1) {
          if (get(offset)) {
            RawBitSet.set(bits, l)
          }
          offset + 2
        } else {
          val c = (l + r) / 2
          (get(offset), get(offset + 1)) match {
            case (false, false) => offset + 2
            case (false, true)  => read(c, r, offset + 2)
            case (true, false)  => read(l, c, offset + 2)
            case (true, true)   => read(c, r, read(l, c, offset + 2))
          }
        }
      }

      val offset = read(0, size, 0)
      src.position(pos + (offset >>> 3) + 1)
      bits
    }
  }
}


text:
package de.csw.ontomaven.util;

import java.io.*;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.semanticweb.owlapi.formats.OWLXMLDocumentFormat;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.util.OWLEntityRemover;

/**
 *
 */
public class AspectManager {

	private OWLOntologyManager manager;
	private OWLOntology ontology;
	private String[] userAspects;
	private String aspectsIRI;
	private List<OWLAnnotationAssertionAxiom> annotationAssertions;
	private List<OWLAnnotation> annotations;
	private List<String> aspects;
	private int originalAxiomsCount;
	private int originalEntitiesCount;
	private boolean keepNonAspectAxioms;

	public OWLOntology getOntology() {
		return ontology;
	}

	public OWLOntologyManager getManager() {
		return manager;
	}

	/**
	 * Standard constructor for {@link AspectManager}
	 *
	 * @param ontologyManager which created the ontology
	 * @param ontology to work with
	 * @param userAspects list of aspects the user defined
	 */
	public AspectManager(OWLOntologyManager ontologyManager, String aspectsIRI,
			OWLOntology ontology, String[] userAspects, boolean keepNonAspectAxioms) {
		this.manager = ontologyManager;
		this.ontology = ontology;
		this.userAspects = userAspects;
		this.aspectsIRI = aspectsIRI;
		this.keepNonAspectAxioms = keepNonAspectAxioms;

		// Defining and filling annotation assertions list
		annotationAssertions = new LinkedList<OWLAnnotationAssertionAxiom>();
		findAllAnnotationAssertions();

		// Defining and filling annotations list. First assertions then annotations
		// because assertions can also have annotations but annotations cannot
		// have assertions. We also will search in found assertions for annotations
		annotations = new LinkedList<OWLAnnotation>();
		findAllAnnotations();

		// Defining and filling aspects list. The method searchs in assertions and
		// annotations for aspect names and collects them.
		aspects = new LinkedList<String>();
		findAllAspectNames();

		originalAxiomsCount = ontology.getAxiomCount();
		originalEntitiesCount = ontology.getSignature().size();
	}

	/**
	 * Lets applying all axiom aspects and entity aspects on the ontology
	 * by removing the axioms and entities which are not effective because
	 * of an unvalid aspect.
	 */
	public void applyAllAspects() {

		// search for annotated axioms
		for(OWLAxiom axiom: ontology.getAxioms()){
			if (!isEffectiveAxiom(axiom) && axiom.getAxiomType().getName() != "AnnotationAssertion")
				manager.removeAxiom(ontology, axiom);
		}

		//search for Annotation Assertions
		for (OWLEntity entity: ontology.getSignature()){

			// Creating entityRemover, which removes an entity and its users
			Set<OWLOntology> ontologies = new HashSet<OWLOntology>();
			ontologies.add(ontology);
			OWLEntityRemover entityRemover = new OWLEntityRemover(ontologies);

			if(!isEffectiveEntity(entity))
				entity.accept(entityRemover);

			// Applying changes. There will be probably more changes as the
			// removing uneffective entities, because the remover removes also
			// also axioms and other entities which need this entity
			manager.applyChanges(entityRemover.getChanges());
		}

		// write ontology to stream and read it, so declarations will be created
		ByteArrayOutputStream out =  new ByteArrayOutputStream();
		try {
			manager.saveOntology(ontology, new OWLXMLDocumentFormat(), out);
		} catch (OWLOntologyStorageException e) {
			e.printStackTrace();
		}
		ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
		try {
			manager.removeOntology(ontology);
			ontology = manager.loadOntologyFromOntologyDocument(in);
		} catch (OWLOntologyCreationException e) {
			e.printStackTrace();
		}
	}

	private boolean isEffectiveEntity(OWLEntity entity) {
		boolean isEffective = true;
		for (OWLAnnotationAssertionAxiom assertion:
			ontology.getAnnotationAssertionAxioms(entity.getIRI())){
			if (isAspectAssertion(assertion)){
				if(!isEffectiveAspectAssertion(assertion))
					return true; // OR: one assertion says yes
				 else
					isEffective = false;
			}
		}
		return isEffective;
	}

	private boolean isEffectiveAspectAssertion(
			OWLAnnotationAssertionAxiom assertion) {
		boolean isEffective = false; // Means: having axiom is effective
		boolean isEffectiveConceringInnerAnnotations = true;

		// First: Check if it is is effective, because it is not an user aspect.
		// If no: return true, you don't have to check inner annotations to
		// realize an AND. If yes, maybe inner aspects are not effective.
		if (!isUserAspect(getAspectNameOfAssertion(assertion))){
			isEffective = true;
		} else {
			return false;
		}

		// Second: Check if inner annotations are effective. If yes, the parent
		// assertion is uneffective. Because the parent assertion and inner
		// annotation build an AND. The parent annotation is effective, if
		// inner annotations does not restrict it.
		for (OWLAnnotation innerAnnotation: assertion.getAnnotations()){
			if (isAspectAnnotation(innerAnnotation)){
				if (isEffektiveAspectAnnotation(innerAnnotation)){
					isEffectiveConceringInnerAnnotations = true;
				} else {
					isEffectiveConceringInnerAnnotations = false;
					break; // Realizes an OR. If one inner annotations says, that
						   // alows the parent to be effective, its enough.
				}
			}
		}

		// If it is effective and no inner annotation hinder it, return true
		if (isEffective && isEffectiveConceringInnerAnnotations)
			return true;
		return false;
	}

	/**
	 * Checks for a given axiom, if it is effective in spite of the
	 * annotations, which could be aspect annotations and the aspects could
	 * be uneffective. The axiom is not effective, when at least one
	 * annotation makes it uneffective and no annotations make it effective.
	 *
	 * @param axiom for that to check
	 * @return if axiom effective
	 */
	private boolean isEffectiveAxiom(OWLAxiom axiom) {
		boolean isEffektive = keepNonAspectAxioms;
		for (OWLAnnotation annotation : axiom.getAnnotations()) {
			if (isAspectAnnotation(annotation)) {
				if (!isEffektiveAspectAnnotation(annotation))
					return true; // OR: if one aspect says yes, then yes
				else
					isEffektive = false;
			}
		}
		return isEffektive;
	}

	/**
	 * Checks for a given annotation, if it is an aspect annotation and
	 * makes an axiom uneffective, because the aspect is not an user aspect
	 *
	 * @param annotation for that the effectivity will be checked
	 * @return if annotation is an effective aspect annotation
	 */
	private boolean isEffektiveAspectAnnotation(OWLAnnotation annotation) {

		boolean isEffective = false; // Means: having axiom is effective
		boolean isEffectiveConceringInnerAnnotations = true;

		// First: Check if it is an is effective, because it is not an user
		// aspect. If no: return true, you don't have to check inner
		// annotations to realize an AND. If yes, maybe inner aspects are
		// not effective.
		if (!isUserAspect(getAspectNameOfAnnotation(annotation))){
			isEffective = true;
		} else {
			return false;
		}

		// Second: Check if inner annotations are effective. If yes, the parent
		// annotation is uneffective. Because the parent and inner annotation
		// build an AND. The parent annotation is effective, if inner annotations
		// does not restrict it.
		for (OWLAnnotation innerAnnotation: annotation.getAnnotations()){
			if (isAspectAnnotation(innerAnnotation)){
				if (isEffektiveAspectAnnotation(innerAnnotation)){
					isEffectiveConceringInnerAnnotations = true;
				} else {
					isEffectiveConceringInnerAnnotations = false;
					break; // Realizes an OR. If one inner annotations says, that
						   // alows the parent to be effective, its enough.
				}
			}
		}

		// If it is effective and no inner annotation hinder it, return true
		if (isEffective && isEffectiveConceringInnerAnnotations)
			return true;
		return false;
	}

	/**
	 * Returns all names of in the ontology contained aspects.
	 * @return names of aspects
	 */
	public List<String> getAllAspectNames(){
		return aspects;
	}

	/**
	 * Search recursiv in all axioms and annotationassertionaxioms for
	 * annotations and add them to variable annotations
	 */
	private void findAllAnnotations(){
		for (OWLAxiom owlAxiom : ontology.getAxioms()) {
			for (OWLAnnotation annotation : owlAxiom.getAnnotations())
				annotations.addAll(getRecursivAllAnnotations(annotation));
		}

		for (OWLAnnotationAssertionAxiom assertion: annotationAssertions){
			for (OWLAnnotation annotation : assertion.getAnnotations())
				annotations.addAll(getRecursivAllAnnotations(annotation));
		}
	}

	/**
	 * Search in all entities in the ontology for annotationsassertions
	 * and adds them to the variable annotationassertions
	 */
	private void findAllAnnotationAssertions(){
		for (OWLEntity entity: ontology.getSignature())
			annotationAssertions.addAll(ontology.getAnnotationAssertionAxioms(entity.getIRI()));
	}

	/**
	 * Finds in the found annotations and annotationassertions all names
	 * of aspects, if these are aspect annotations or assertions. The
	 * aspect names will be added to the variable aspects
	 * Because aspects can have inheritance, the method searchs against
	 * in all annotations and assertions, if at least one new aspect name
	 * is found. Because there could be another aspects which is a sub
	 * aspect of the found aspect. Every aspect name will be added only once.
	 */
	private void findAllAspectNames() {
		for (OWLAnnotation foundAnnotation : annotations) {
			if (isAspectAnnotation(foundAnnotation) && !aspects
							.contains(getAspectNameOfAnnotation(foundAnnotation))) {
				aspects.add(getAspectNameOfAnnotation(foundAnnotation));
			}
		}
		for (OWLAnnotationAssertionAxiom assertion : annotationAssertions) {
			if (isAspectAssertion(assertion)
					&& !aspects.contains(getAspectNameOfAssertion(assertion))) {
				aspects.add(getAspectNameOfAssertion(assertion));
			}
		}
	}

	private String getAspectNameOfAssertion( OWLAnnotationAssertionAxiom assertion) {
		return assertion.getValue().toString();
	}

	private boolean isAspectAssertion(OWLAnnotationAssertionAxiom assertion) {
		OWLAnnotationProperty property = assertion.getProperty();
		if (property != null) {
			IRI propertyIRI = assertion.getProperty().getIRI();
			if (propertyIRI != null) {
				if (propertyIRI.toString().equals(aspectsIRI))
					return true;
				for (String containedAspect: aspects){
					if (propertyIRI.toString().equals(containedAspect))
						return true;
				}
			}
		}
		return false;
	}

	/**
	 * Returns for a annotation the list of the annotations of it and itself
	 *
	 * @param parentAnnotation for that inner annotations will be returned
	 * @return list of contained annotations
	 */
	private List<OWLAnnotation> getRecursivAllAnnotations(
			OWLAnnotation parentAnnotation) {
		List<OWLAnnotation> foundAnnotations = new LinkedList<OWLAnnotation>();
		foundAnnotations.add(parentAnnotation);
		for (OWLAnnotation childAnnotation : parentAnnotation.getAnnotations()) {
			foundAnnotations.addAll(getRecursivAllAnnotations(childAnnotation));
		}
		return foundAnnotations;
	}

	/**
	 * Checks for an aspect, if it is contained in the list of user aspects.
	 *
	 * @param aspect name
	 *
	 * @return if aspect contained in user aspects
	 */
	private boolean isUserAspect(String aspect) {
		for (String userAspect : userAspects) {
			if (aspect.equals(userAspect)){
				return true;
			}
		}
		return false;
	}

	/**
	 * Checks for an {@link OWLAnnotation} if it has an
	 * {@link OWLAnnotationProperty} which have an {@link IRI} ending with
	 * "hasAspect"
	 *
	 * @param annotation to be checked for
	 *
	 * @return if annotation has an property ending with "hasAspect"
	 */
	private boolean isAspectAnnotation(OWLAnnotation annotation) {
		OWLAnnotationProperty property = annotation.getProperty();
		if (property != null) {
			IRI propertyIRI = annotation.getProperty().getIRI();
			if (propertyIRI != null) {
				if (propertyIRI.toString().equals(aspectsIRI))
					return true;
				for (String containedAspect: aspects){
					if (propertyIRI.toString().equals(containedAspect))
						return true;
				}
			}
		}
		return false;
	}

	/**
	 * Returns the name of an aspect of an {@link OWLAnnotation}. The name of
	 * the aspect is the value of the annotation. The method should be used
	 * if you know, that the annotation has an aspect property
	 *
	 * @param annotation
	 *
	 * @return name of an aspect (annotation value)
	 */
	private String getAspectNameOfAnnotation(OWLAnnotation annotation) {
		return annotation.getValue().toString().replace("\"", "");
	}

	/**
	 * Returns the number of the removed axioms by building the difference
	 * between the existing axioms and the original axioms.
	 *
	 * @return number of removed axioms
	 */
	public int getRemovedAxiomsCount(){
		return originalAxiomsCount - ontology.getAxiomCount();
	}

	/**
	 * Returns the number of the removed entities by building the difference
	 * between the existing entities and the original entities.
	 *
	 * @return number of deleted entities
	 */
	public int getRemovedEntitiesCount(){
		return originalEntitiesCount - ontology.getSignature().size();
	}

	public void removeAspects(){

		for(OWLAnnotationAssertionAxiom assertion: annotationAssertions){
			if (isAspectAssertion(assertion)){
				manager.removeAxiom(ontology, assertion);
			}
		}

		for (OWLAxiom axiom: ontology.getAxioms()){
			Set<OWLAnnotation> notAspectAnnotations =
					new HashSet<OWLAnnotation>();
			for (OWLAnnotation annotation: axiom.getAnnotations()){
				if (!isAspectAnnotation(annotation))
					notAspectAnnotations.add(annotation);
			}

			OWLAxiom newAxiom = axiom.getAxiomWithoutAnnotations()
					.getAnnotatedAxiom(notAspectAnnotations);

			manager.applyChange(new RemoveAxiom(ontology, axiom));
			manager.applyChange(new AddAxiom(ontology, newAxiom));
		}
	}

	public List<String> getAspectNamesOfAxiom(OWLAxiom axiom) {
		// First: finding all annotations
		List<OWLAnnotation> annotationsOfThisAxiom =
				new LinkedList<OWLAnnotation>();
		for (OWLAnnotation annotation : axiom.getAnnotations())
			annotations.addAll(getRecursivAllAnnotations(annotation));

		// Second: Filtering the aspect annotations
		List<String> foundAspects = new LinkedList<String>();
		for (OWLAnnotation annotation: annotationsOfThisAxiom){
			if (isAspectAnnotation(annotation))
				foundAspects.add(getAspectNameOfAnnotation(annotation));
		}

		return foundAspects;
	}
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('problem', '__first__'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='CaseResult',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('running_time', models.IntegerField(default=0)),
                ('running_memory', models.IntegerField(default=0)),
                ('status', models.CharField(default=b'QUE', max_length=3, choices=[(b'PD', b'Pending'), (b'SE', b'System Error'), (b'CL', b'Compiling'), (b'CE', b'Compilation Error'), (b'JD', b'Judging'), (b'AC', b'Accepted'), (b'PE', b'Presentation Error'), (b'WA', b'Wrong Answer'), (b'RE', b'Runtime Error'), (b'TLE', b'Time Limit Exceed'), (b'MLE', b'Memory Limit Exceed'), (b'OLE', b'Output Limit Exceed'), (b'EXT', b'Extended Judge Result'), (b'NUM', b'Judge Score')])),
                ('position', models.IntegerField()),
                ('output', models.CharField(default=0, max_length=128)),
            ],
        ),
        migrations.CreateModel(
            name='Submission',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('create_time', models.DateTimeField(auto_now_add=True)),
                ('score', models.IntegerField(default=0)),
                ('status', models.CharField(default=b'QUE', max_length=3, choices=[(b'PD', b'Pending'), (b'SE', b'System Error'), (b'CL', b'Compiling'), (b'CE', b'Compilation Error'), (b'JD', b'Judging'), (b'AC', b'Accepted'), (b'PE', b'Presentation Error'), (b'WA', b'Wrong Answer'), (b'RE', b'Runtime Error'), (b'TLE', b'Time Limit Exceed'), (b'MLE', b'Memory Limit Exceed'), (b'OLE', b'Output Limit Exceed'), (b'EXT', b'Extended Judge Result'), (b'NUM', b'Judge Score')])),
                ('running_time', models.IntegerField(default=0)),
                ('running_memory', models.IntegerField(default=0)),
                ('info', models.TextField(blank=True)),
                ('code', models.TextField()),
                ('language', models.CharField(default=b'gcc', max_length=10, choices=[(b'CPP03', b'GNU C++'), (b'C', b'GNU C'), (b'JAVA8', b'java'), (b'CPP11', b'GNU C++ 11'), (b'PY2', b'Python 2.7')])),
                ('problem', models.ForeignKey(to='problem.Problem')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='caseresult',
            name='submission',
            field=models.ForeignKey(related_name='cases', to='submission.Submission'),
        ),
    ]


text:
namespace file_based_test_driver {

// TestCaseOutputs represents the outputs of one text-based test case (such as
// the ones processed by RunTestCasesFromFiles in file_based_test_driver.h).
// It supports serializing/parsing a TestCaseOutputs to/from its text format.
//
// Inside a TestCaseOutputs we have the following hierarchy:
// mode
//   -> result type
//       -> output
//
// 'mode' can either be 'all modes', which is represented by an empty string, or
// a specific mode value. Each mode can have a distinct set of 'result type'
// values. Empty result type is allowed, meaning it's the main output.
//
// TestCaseOutputs can have at most one output for each ('mode', 'result type')
// combination. If an 'all modes' output (mode = '') exists, mode specific
// outputs cannot be added for the same result type. Similarly, if a mode
// specific output exists for a result type, the 'all modes' output cannot be
// added for the same result type.
//
// TestCaseOutputs example:
// mode A
//   -> "" # main result type
//         -> main result type output
//   -> result type 1
//         -> output A1
// mode B
//   -> "" # main result type
//        -> main result type output
//   -> result type 2
//        -> output B2
// ""  # all modes
//   -> result type 3
//        -> all mode output for result type 3
//
// The text format of a TestCaseOutputs contains the combined outputs.
// If the outputs of multiple modes are same for a 'result type', they are
// combined into one output string. The first line of a combined output
// contains the 'result type' and the modes of the output, if they are not
// empty.
//
// Text output of the above example:
//
// <>[mode A][mode B]        # result type = ""
// main result type output
// --
// <result type 1>[mode A]
// output A1
// --
// <result type 2>[mode B]
// output B2
// --
// <result type 3>         # all modes: mode = ""
// all mode output for result type 3
//
class TestCaseOutputs {
 public:
  TestCaseOutputs() = default;
  ~TestCaseOutputs() = default;

  TestCaseOutputs(const TestCaseOutputs&) = default;
  TestCaseOutputs& operator=(const TestCaseOutputs&) = default;

  bool operator==(const TestCaseOutputs& other) const {
    return outputs_ == other.outputs_ &&
           disabled_modes_ == other.disabled_modes_ &&
           possible_modes_ == other.possible_modes_;
  }

  // Parses the test outputs from 'parts'. Each string in 'parts' contains
  // one output. The output's result type and test modes may be specified in
  // its first line. The patterns are:
  // 1. Both result type and test modes are specified, e.g.,
  //    <result type>[test mode 1][test mode 2]
  //    my test output
  // 2. Only test modes are specified. This is the main result (result type="")
  //    of the test case, e.g.,
  //    <>[test mode 1][test mode 2]
  //    my test output
  // 3. Only result type is specified. The output for all modes are same, e.g.,
  //    <result type>
  //    my test output
  // 4. no result type or test modes are specified. This means the main result
  //    is same for all test modes, e.g.,
  //    my test output
  // 5. A part may also contain all the possible modes for this test. This will
  //    be a one line output with prefix 'Possible Modes:' followed by a list of
  //    test modes, e.g.,
  //    Possible Modes: [possible mode 1][possible mode 2]
  absl::Status ParseFrom(const std::vector<std::string>& parts);

  // Returns outputs that are combined by result type and test modes. This is
  // the opposite operation of 'ParseFrom'.
  // If 'include_possible_modes' is true and 'possible_modes_' is not empty,
  // combined_outputs[0] will contain all the possible test modes with prefix
  // "Possible Modes:", e.g.,
  // 'Possible Modes: [possible mode 1][possible mode 2]'.
  absl::Status GetCombinedOutputs(
      bool include_possible_modes,
      std::vector<std::string>* combined_outputs) const;

  // Adds a test output for 'test_mode' and 'result_type'. Only one output can
  // be added for each ('test_mode', 'result_type') combination. If 'output'
  // does not end with a newline, this function adds one.
  //
  // 'test_mode' cannot be empty when adding outputs.
  // However when adding an output for 'result_type', if an 'all modes'
  // (test_mode="") output for 'result_type' already exists in this
  // TestCaseOutputs,this function will return error.
  absl::Status RecordOutput(const TestCaseMode& test_mode,
                            absl::string_view result_type,
                            absl::string_view output);

  // Disables a test mode.
  // Existing outputs for the disabled mode will be removed.
  absl::Status DisableTestMode(const TestCaseMode& disabled_mode);

  // Returns the disabled test modes.
  const TestCaseMode::UnorderedSet& disabled_modes() const {
    return disabled_modes_;
  }

  // Sets the possible modes for this test. The modes in 'possible_modes' cannot
  // be empty. 'possible_modes' must include all the modes that are already
  // in 'outputs_'.
  absl::Status SetPossibleModes(
      const std::initializer_list<TestCaseMode>& possible_modes);
  absl::Status SetPossibleModes(TestCaseMode::Set possible_modes);

  const TestCaseMode::Set& possible_modes() const { return possible_modes_; }

  bool IsEmpty() const { return outputs_.empty(); }

  // Merges a list of actual TestCaseOutputs into an expected TestCaseOutputs.
  // The TestCaseOutputs in 'actual_outputs' should not contain 'all modes'
  // outputs. 'expected_outputs' may contain 'all modes' outputs.
  //
  // The merging works like this:
  // 1) Collect all the test modes mentioned in 'expected_outputs' and
  //    'actual_outputs' (if 'possible_modes_' is set, this is
  //    'possible_modes_') and the disabled modes
  //    mentioned in 'actual_outputs'.
  //    If multiple actual outputs have 'possible_modes_', they must be same.
  //    If any of the actual outputs specifies 'possible_modes_', only these
  //    modes will be added to the test mode list ('test_modes').
  //    Remove the disabled modes from the test mode list ('test_modes').
  // 2) Copy 'expected_outputs' into 'merged_outputs' and remove all the outputs
  //    for disabled modes from 'merged_outputs'.
  // 3) Break out the 'all modes' output in 'merged_outputs' into modes in
  //    'test_modes'.
  // 4) For each TestCaseOutputs X in 'actual_outputs'
  //      For each mode in the X, if it's not disabled:
  //        Replace the outputs for that mode in 'merged_outputs' with the
  //        outputs from X.
  // 5) Regenerate the 'all modes' output in 'merged_outputs', i.e., for a
  //    result type, if all outputs are same for the modes in 'test_modes',
  //    remove the mode specific outputs and add an 'all modes' output.
  static absl::Status MergeOutputs(
      const TestCaseOutputs& expected_outputs,
      const std::vector<TestCaseOutputs>& actual_outputs,
      TestCaseOutputs* merged_outputs);

 private:
  // Represents the output of a single Mode output. This contains a mapping
  // of results_type to the actual text output for the test for that mode and
  // result_type.
  class ModeResults {
   public:
    bool operator==(const ModeResults& other) const {
      return result_type_to_output_ == other.result_type_to_output_;
    }

    // Removes the associated output for 'result_type'. Returns false if
    // no output has been added for 'result_type'.
    ABSL_MUST_USE_RESULT bool RemoveResultType(absl::string_view result_type) {
      auto it = result_type_to_output_.find(result_type);
      if (it == result_type_to_output_.end()) return false;

      result_type_to_output_.erase(it);
      return true;
    }

    // Fetches the text for 'result_type' and returns it in 'output'.
    // Returns false if the given 'result_type' doesn't exist.
    ABSL_MUST_USE_RESULT bool GetOutputForResultType(
        absl::string_view result_type, std::string* output) const {
      auto it = result_type_to_output_.find(result_type);
      if (it == result_type_to_output_.end()) return false;

      *output = it->second;
      return true;
    }

    // Adds 'output' as text for the given 'result_type' if it doesn't exist.
    // Returns true if 'output' was added.
    ABSL_MUST_USE_RESULT bool AddOutput(absl::string_view result_type,
                                        absl::string_view output) {
      return file_based_test_driver_base::InsertIfNotPresent(&result_type_to_output_,
                                     std::string(result_type),
                                     std::string(output));
    }

    bool empty() const { return result_type_to_output_.empty(); }

    absl::node_hash_map<std::string, std::string>::const_iterator begin()
        const {
      return result_type_to_output_.begin();
    }

    absl::node_hash_map<std::string, std::string>::const_iterator end() const {
      return result_type_to_output_.end();
    }

   private:
    absl::node_hash_map<std::string, std::string> result_type_to_output_;
  };

  using TestModeOutputsMap = TestCaseMode::UnorderedMap<ModeResults>;

  // Adds a test output for 'test_mode' and 'result_type'. Only one output can
  // be added for each ('test_mode', 'result_type') combination.
  //
  // If 'test_mode' is not empty, returns error if an 'all modes' (test_mode="")
  // output already exists for the result type.
  // If 'test_mode' is empty (all modes), returns error if a mode specific
  // output exists for this result type.
  absl::Status AddOutputInternal(const TestCaseMode& test_mode,
                                 absl::string_view result_type,
                                 absl::string_view output);

  // Whether this TestCaseOutputs has 'all modes' outputs (empty test mode).
  bool HasAllModesResult() const;

  // Returns all the test modes mentioned in this TestCaseOutputs.
  TestCaseMode::UnorderedSet GetTestModes() const;

  // Breaks out the 'all modes' outputs into the modes in 'test_modes'.
  absl::Status BreakOutAllModesOutputs(
      const TestCaseMode::UnorderedSet& test_modes);

  // For each result type, if all outputs are same for the modes in
  // 'test_modes', removes the mode specific outputs and adds an 'all modes'
  // output. Returns error if there are outputs for modes other than those in
  // 'test_modes'.
  absl::Status GenerateAllModesOutputs(
      const TestCaseMode::UnorderedSet& test_modes);

  // For each mode M in 'outputs', if it is also in 'test_modes', replace
  // all the outputs for M in 'outputs_' with the outputs from 'outputs'.
  absl::Status InsertOrUpdateOutputsForTestModes(
      const TestCaseOutputs& outputs,
      const TestCaseMode::UnorderedSet& test_modes);

  // Returns an error if any of 'outputs_' contains a mode not in
  // 'possible_modes_'.
  absl::Status ValidatePossibleModes() const;

  // Mode specific test outputs
  // Maps from test mode to test outputs. Each test mode can have multiple
  // test outputs, identified by result types. Result
  // type for the main test output can be an empty string.
  // Test outputs that are same for all modes will be stored in outputs_[""].
  TestModeOutputsMap outputs_;

  // The test modes that are disabled by the test settings.
  TestCaseMode::UnorderedSet disabled_modes_;

  // All the possible modes for this test. When a test callback returns an
  // actual TestCaseOutputs, it can add all the possible modes for the test in
  // 'possible_modes_'. And we will use them to break the 'all modes' outputs
  // when merging the actual TestCaseOutputs with the expected outputs. The
  // actual TestCaseOutputs itself does not need to contain outputs for all the
  // possible modes.
  // If 'possible_modes_' is specified, it should contain all the test modes
  // that appear in 'outputs_'.
  // If 'possible_modes_' is empty, we will try to infer the possible
  // modes from the actual TestCaseOutputs and the expected TestCaseOutputs.
  // However we may not able to get the complete list if the test callback does
  // not run in all modes and the actual TestCaseOutputs contains partial
  // results. In this case the merged output may not be complete.
  TestCaseMode::Set possible_modes_;

  // Allow alternation builder to poke at some of the internals.
  friend class AlternationSetWithModes;
};

}  // namespace file_based_test_driver

#endif  // THIRD_PARTY_FILE_BASED_TEST_DRIVER_TEST_CASE_OUTPUTS_H_


text:
<?php

namespace DependencyInversionPrinciple;

class Gateway2 implements GatewayInterface
{
    /**
     * E.g. Guzzle or some other http client
     *
     * @var
     */
    private $client;

    /**
     * @param ChargeableInterface $chargeable
     * @param PaymentMethodInterface $paymentMethod
     * @return string
     * @throws GatewayException
     */
    public function charge(ChargeableInterface $chargeable, PaymentMethodInterface $paymentMethod)
    {
        $result = $this->client->post('/purchase', [
            'amount' => $chargeable->getChargeableAmount(),
            'token' => $paymentMethod->getToken(),
        ]);

        if ($result->isOk())
        {
            return $result->getTransactionId();
        }

        throw new GatewayException($result->getErrorInfo());
    }
}


text:
<?php

namespace Sylius\Bundle\FlowBundle\Process\Scenario;

use Sylius\Bundle\FlowBundle\Process\Builder\ProcessBuilderInterface;

/**
 * Interface for process scenario.
 *
 * This interface should be implemented by all scenario you define.
 * For example, that can be a checkout or installation process scenario.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
interface ProcessScenarioInterface
{
    /**
     * Builds the whole process.
     *
     * @param ProcessBuilderInterface $builder
     */
    public function build(ProcessBuilderInterface $builder);
}