text:
from __future__ import division
import sys
sys.dont_write_bytecode = True
# import math

class NaiveBayes(object):

    def __init__(self, data, features_set):
        self.data = data
        self.features = features_set

    """processes and builds prior probabilities, probabilities of evidences and
     probabilities of likelyhood.

    """

    def process(self):
        self.probs = {}
        self.all_labels = list(set([a[0] for a in self.data]))
        print(self.all_labels)
        self.probs['labels_c'] = {}
        self.probs['labels_p'] = {}
        self.probs['features_c'] = {}
        self.probs['features_p'] = {}
        self.probs['likelyhood_p'] = {}
        self.probs['likelyhood_c'] = {}

        # transposed features for calculating evidence probabilities
        k = zip(*map(lambda n: n[1], self.data))

        # calculating prior probabilities
        for a in self.data:
            if self.probs['labels_c'].has_key(a[0]):
                self.probs['labels_c'][a[0]] += 1
            else:
                self.probs['labels_c'][a[0]] = 1
            self.probs['labels_p'][a[0]] = self.probs['labels_c'][a[0]] / len(self.data)

        # calculating evidence probabilities
        for i in range(0, len(k)):
            current_feature = k[i]
            self.probs['features_c'][self.features[i]] = len(filter(lambda q: q > 0, current_feature))
            self.probs['features_c']['not_'+self.features[i]] = len(filter(lambda q: q < 1, current_feature))
            self.probs['features_p'][self.features[i]] = self.probs['features_c'][self.features[i]]/len(self.data)
            self.probs['features_p']['not_'+self.features[i]] = self.probs['features_c']['not_'+self.features[i]]/len(self.data)

        # calculating likelyhood probabilities
        for i in range(0, len(self.features)):
            self.probs['likelyhood_c'][self.features[i]] = {}
            self.probs['likelyhood_p'][self.features[i]] = {}
            self.probs['likelyhood_c']['not_'+self.features[i]] = {}
            self.probs['likelyhood_p']['not_'+self.features[i]] = {}
            for b in self.data:
                if b[1][i] == 1:
                    if self.probs['likelyhood_c'][self.features[i]].has_key(b[0]):
                        self.probs['likelyhood_c'][self.features[i]][b[0]] += 1
                    else:
                        self.probs['likelyhood_c'][self.features[i]][b[0]] = 1
                    self.probs['likelyhood_p'][self.features[i]][b[0]] = self.probs['likelyhood_c'][self.features[i]][b[0]]/self.probs['labels_c'][b[0]]
                else:
                    if self.probs['likelyhood_c']['not_'+self.features[i]].has_key(b[0]):
                        self.probs['likelyhood_c']['not_'+self.features[i]][b[0]] += 1
                    else:
                        self.probs['likelyhood_c']['not_'+self.features[i]][b[0]] = 1
                    self.probs['likelyhood_p']['not_'+self.features[i]][b[0]] = self.probs['likelyhood_c']['not_'+self.features[i]][b[0]]/self.probs['labels_c'][b[0]]

    # predictor method
    # calculates conditional probabilities for all the unique labels and
    # returns the one with max score.
    def predict(self, vector, key_only=False):
        all_features_rep = []
        for i in range(0, len(vector)):
            if vector[i]:
                all_features_rep.append(self.features[i])
            else:
                all_features_rep.append('not_'+self.features[i])

        divisor = 1
        for a in all_features_rep:
            divisor *= self.probs['features_p'][a]

        results = {}
        for i in range(0, len(self.all_labels)):
            t = 1
            for j in range(0, len(all_features_rep)):
                if self.probs['likelyhood_p'][all_features_rep[j]].has_key(self.all_labels[i]):
                    t *= self.probs['likelyhood_p'][all_features_rep[j]][self.all_labels[i]]
                else:
                    t *= 0
            results[self.all_labels[i]] = (self.probs['labels_p'][self.all_labels[i]]*t)/divisor

        if key_only:
            return max(results, key=results.get)
        else:
            return results


text:
<!DOCTYPE html>

  	<meta charset="utf-8">
    <title>Hello Electron React!</title>
    <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.css" />

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit } from '@angular/core';
declare var $: any;

@Component({
    selector: 'module-header',
    templateUrl: '/app/widgets/header/header.component.html'
})
export class ModHeaderComponent implements OnInit {
    constructor() { }

    ngOnInit() {
        setTimeout(function() {
            $(document).ready(function() {
                $("#myBtn").click(function() {
                    $("#myModal").modal();
                });
            });
        }, 0);
    }
}


text:
package org.apache.storm.daemon.supervisor;

import java.io.IOException;
import java.util.Map;

import org.apache.storm.generated.LocalAssignment;
import org.apache.storm.messaging.IContext;
import org.apache.storm.utils.LocalState;

/**
 * Launch Containers in local mode.
 */
public class LocalContainerLauncher extends ContainerLauncher {
    private final Map<String, Object> _conf;
    private final String _supervisorId;
    private final IContext _sharedContext;

    public LocalContainerLauncher(Map<String, Object> conf, String supervisorId, IContext sharedContext) {
        _conf = conf;
        _supervisorId = supervisorId;
        _sharedContext = sharedContext;
    }

    @Override
    public Container launchContainer(int port, LocalAssignment assignment, LocalState state) throws IOException {
        LocalContainer ret = new LocalContainer(_conf, _supervisorId, port, assignment, _sharedContext);
        ret.setup();
        ret.launch();
        return ret;
    }

    @Override
    public Container recoverContainer(int port, LocalAssignment assignment, LocalState state) throws IOException {
        //We are in the same process we cannot recover anything
        throw new ContainerRecoveryException("Local Mode Recovery is not supported");
    }

    @Override
    public Killable recoverContainer(String workerId, LocalState localState) throws IOException {
        //We are in the same process we cannot recover anything
        throw new ContainerRecoveryException("Local Mode Recovery is not supported");
    }
}


text:
namespace gameplay
{

static AudioController* getInstance(lua_State* state)
{
    void* userdata = luaL_checkudata(state, 1, "AudioController");
    luaL_argcheck(state, userdata != NULL, 1, "'AudioController' expected.");
    return (AudioController*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}

static int lua_AudioController__gc(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                void* userdata = luaL_checkudata(state, 1, "AudioController");
                luaL_argcheck(state, userdata != NULL, 1, "'AudioController' expected.");
                gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)userdata;
                if (object->owns)
                {
                    AudioController* instance = (AudioController*)object->instance;
                    SAFE_DELETE(instance);
                }

                return 0;
            }

            lua_pushstring(state, "lua_AudioController__gc - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

void luaRegister_AudioController()
{
    const luaL_Reg lua_members[] =
    {
        {NULL, NULL}
    };
    const luaL_Reg* lua_statics = NULL;
    std::vector<std::string> scopePath;

    gameplay::ScriptUtil::registerClass("AudioController", lua_members, NULL, lua_AudioController__gc, lua_statics, scopePath);

}

}


text:
namespace pythonic
{

  namespace __builtin__
  {

    template <class Iterable>
    types::list<
        typename std::remove_cv<typename Iterable::iterator::value_type>::type>
    sorted(Iterable const &seq);

    template <class Iterable, class C>
    types::list<
        typename std::remove_cv<typename Iterable::iterator::value_type>::type>
    sorted(Iterable const &seq, C const &cmp);

    DECLARE_FUNCTOR(pythonic::__builtin__, sorted);
  }
}

#endif


text:
class UserStat < ActiveRecord::Base

  belongs_to :user

  # Updates the denormalized view counts for all users
  def self.update_view_counts

    # NOTE: we only update the counts for users we have seen in the last hour
    #  this avoids a very expensive query that may run on the entire user base
    #  we also ensure we only touch the table if data changes

    # Update denormalized topics_entered
    exec_sql "UPDATE user_stats SET topics_entered = X.c
             FROM
            (SELECT v.user_id,
                    COUNT(DISTINCT parent_id) AS c
             FROM views AS v
             WHERE parent_type = 'Topic' AND v.user_id IN (
                SELECT u1.id FROM users u1 where u1.last_seen_at > :seen_at
             )
             GROUP BY v.user_id) AS X
            WHERE
                    X.user_id = user_stats.user_id AND
                    X.c <> topics_entered
    ", seen_at: 1.hour.ago

    # Update denormalzied posts_read_count
    exec_sql "UPDATE user_stats SET posts_read_count = X.c
              FROM
              (SELECT pt.user_id,
                      COUNT(*) AS c
               FROM post_timings AS pt
               WHERE pt.user_id IN (
                  SELECT u1.id FROM users u1 where u1.last_seen_at > :seen_at
               )
               GROUP BY pt.user_id) AS X
               WHERE X.user_id = user_stats.user_id AND
                     X.c <> posts_read_count
    ", seen_at: 1.hour.ago
  end

  def update_topic_reply_count
    self.topic_reply_count =
        Topic
        .where(['id in (
              SELECT topic_id FROM posts p
              JOIN topics t2 ON t2.id = p.topic_id
              WHERE p.deleted_at IS NULL AND
                t2.user_id <> p.user_id AND
                p.user_id = ?
              )', self.user_id])
        .count
  end

  MAX_TIME_READ_DIFF = 100
  # attempt to add total read time to user based on previous time this was called
  def update_time_read!
    if last_seen = last_seen_cached
      diff = (Time.now.to_f - last_seen.to_f).round
      if diff > 0 && diff < MAX_TIME_READ_DIFF
        UserStat.where(user_id: id, time_read: time_read).update_all ["time_read = time_read + ?", diff]
      end
    end
    cache_last_seen(Time.now.to_f)
  end

  private

  def last_seen_key
    @last_seen_key ||= "user-last-seen:#{id}"
  end

  def last_seen_cached
    $redis.get(last_seen_key)
  end

  def cache_last_seen(val)
    $redis.set(last_seen_key, val)
  end

end

# == Schema Information
#
# Table name: user_stats
#
#  user_id           :integer          not null, primary key
#  has_custom_avatar :boolean          default(FALSE), not null
#  topics_entered    :integer          default(0), not null
#  time_read         :integer          default(0), not null
#  days_visited      :integer          default(0), not null
#  posts_read_count  :integer          default(0), not null
#  likes_given       :integer          default(0), not null
#  likes_received    :integer          default(0), not null
#  topic_reply_count :integer          default(0), not null
#


text:
using namespace PS;
using namespace LM;
TEST(GradientDescent, LogistRegression) {
  // load data
  typedef double V;
  Config cf; readFileToProtoOrDie("../src/test/grad_desc.conf", &cf);
  auto data = readMatricesOrDie<V>(cf.training_data());
  CHECK_EQ(data.size(), 2);
  auto X = data[1];

  // allocate memories
  SArray<V> w(X->cols()), Xw(X->rows()),  g(X->cols());
  w.setZero();

  auto loss = Loss<V>::create(cf.loss());

  V eta = cf.learning_rate().eta();
  for (int i = 0; i < 11; ++i) {
    Xw.eigenArray() = *X * w.eigenArray();
    loss->compute({data[0], data[1], Xw.matrix()}, {g.matrix()});
    w.eigenArray() -= eta * g.eigenArray();

    V objv = loss->evaluate({data[0], Xw.matrix()});
    LL << objv;
  }
}


text:
import { useState } from 'react';

import { c } from 'ttag';

import Icon from '../icon/Icon';
import Input, { Props } from './Input';

/**
 * @deprecated please use PasswordInputTwo instead
 */
const PasswordInput = ({ disabled = false, ...rest }: Props) => {
    const [type, setType] = useState('password');
    const toggle = () => {
        setType(type === 'password' ? 'text' : 'password');
    };
    return (
        <Input
            type={type}
            disabled={disabled}
            icon={
                <button
                    title={type === 'password' ? c('Label').t`Reveal password` : c('Label').t`Hide password`}
                    className="inline-flex flex-item-noshrink"
                    tabIndex={-1}
                    disabled={disabled}
                    type="button"
                    onClick={toggle}
                >
                    <Icon className="mauto" name={type === 'password' ? 'eye' : 'eye-slash'} />
                </button>
            }
            {...rest}
            autoCapitalize="off"
            autoCorrect="off"
            spellCheck="false"
        />
    );
};

export default PasswordInput;


text:
package kinds

import (
	"reflect"
	"testing"

	"github.com/pkg/errors"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/intstr"
	"sigs.k8s.io/cli-utils/pkg/testutil"
)

func TestLookup(t *testing.T) {
	emptyScheme := runtime.NewScheme()
	coreScheme := runtime.NewScheme()
	if err := corev1.AddToScheme(coreScheme); err != nil {
		t.Fatal(err)
	}

	testCases := []struct {
		name          string
		object        runtime.Object
		scheme        *runtime.Scheme
		expected      schema.GroupVersionKind
		expectedError error
	}{
		{
			name: "unstructured pre-populated GVK not in scheme",
			object: &unstructured.Unstructured{
				Object: map[string]interface{}{
					"apiVersion": Service().GroupVersion().String(),
					"kind":       Service().Kind,
					"metadata": map[string]interface{}{
						"name": "test-name",
					},
					"spec": map[string]interface{}{
						"selector": map[string]interface{}{
							"app.kubernetes.io/name": "MyApp",
						},
						"ports": []interface{}{
							map[string]interface{}{
								"protocol":   "TCP",
								"port":       80,
								"targetPort": 9376,
							},
						},
					},
				},
			},
			scheme:   emptyScheme,
			expected: Service(),
		},
		{
			name: "unstructured pre-populated GVK in scheme",
			object: &unstructured.Unstructured{
				Object: map[string]interface{}{
					"apiVersion": Service().GroupVersion().String(),
					"kind":       Service().Kind,
					"metadata": map[string]interface{}{
						"name": "test-name",
					},
					"spec": map[string]interface{}{
						"selector": map[string]interface{}{
							"app.kubernetes.io/name": "MyApp",
						},
						"ports": []interface{}{
							map[string]interface{}{
								"protocol":   "TCP",
								"port":       80,
								"targetPort": 9376,
							},
						},
					},
				},
			},
			scheme:   coreScheme,
			expected: Service(),
		},
		{
			name: "typed pre-populated GVK not in scheme",
			object: &corev1.Service{
				TypeMeta: metav1.TypeMeta{
					APIVersion: Service().GroupVersion().String(),
					Kind:       Service().Kind,
				},
				ObjectMeta: metav1.ObjectMeta{
					Name: "test-name",
				},
				Spec: corev1.ServiceSpec{
					Selector: map[string]string{
						"app.kubernetes.io/name": "MyApp",
					},
					Ports: []corev1.ServicePort{
						{
							Protocol:   corev1.ProtocolTCP,
							Port:       80,
							TargetPort: intstr.FromInt(9376),
						},
					},
				},
			},
			scheme: emptyScheme,
			expectedError: testutil.EqualError(
				errors.Wrap(
					runtime.NewNotRegisteredErrForType(emptyScheme.Name(),
						reflect.TypeOf(corev1.Service{})),
					"failed to lookup object type")),
		},
		{
			name: "typed pre-populated GVK in scheme",
			object: &corev1.Service{
				TypeMeta: metav1.TypeMeta{
					APIVersion: Service().GroupVersion().String(),
					Kind:       Service().Kind,
				},
				ObjectMeta: metav1.ObjectMeta{
					Name: "test-name",
				},
				Spec: corev1.ServiceSpec{
					Selector: map[string]string{
						"app.kubernetes.io/name": "MyApp",
					},
					Ports: []corev1.ServicePort{
						{
							Protocol:   corev1.ProtocolTCP,
							Port:       80,
							TargetPort: intstr.FromInt(9376),
						},
					},
				},
			},
			scheme:   coreScheme,
			expected: Service(),
		},
		{
			name: "typed unpopulated GVK not in scheme",
			object: &corev1.Service{
				ObjectMeta: metav1.ObjectMeta{
					Name: "test-name",
				},
				Spec: corev1.ServiceSpec{
					Selector: map[string]string{
						"app.kubernetes.io/name": "MyApp",
					},
					Ports: []corev1.ServicePort{
						{
							Protocol:   corev1.ProtocolTCP,
							Port:       80,
							TargetPort: intstr.FromInt(9376),
						},
					},
				},
			},
			scheme: emptyScheme,
			expectedError: testutil.EqualError(
				errors.Wrap(
					runtime.NewNotRegisteredErrForType(emptyScheme.Name(),
						reflect.TypeOf(corev1.Service{})),
					"failed to lookup object type")),
		},
		{
			name: "typed unpopulated GVK in scheme",
			object: &corev1.Service{
				ObjectMeta: metav1.ObjectMeta{
					Name: "test-name",
				},
				Spec: corev1.ServiceSpec{
					Selector: map[string]string{
						"app.kubernetes.io/name": "MyApp",
					},
					Ports: []corev1.ServicePort{
						{
							Protocol:   corev1.ProtocolTCP,
							Port:       80,
							TargetPort: intstr.FromInt(9376),
						},
					},
				},
			},
			scheme:   coreScheme,
			expected: Service(),
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			actual, err := Lookup(tc.object, tc.scheme)
			testutil.AssertEqual(t, tc.expectedError, err)
			testutil.AssertEqual(t, tc.expected, actual)
		})
	}
}


text:
require "ostruct"

require "wp_api_client/version"
require "wp_api_client/configuration"

require "wp_api_client/entities/base"

require "wp_api_client/entities/user"
require "wp_api_client/entities/post"
require "wp_api_client/entities/meta"
require "wp_api_client/entities/taxonomy"
require "wp_api_client/entities/term"
require "wp_api_client/entities/image"
require "wp_api_client/entities/error"
require "wp_api_client/entities/types"

require "wp_api_client/client"
require "wp_api_client/concurrent_client"
require "wp_api_client/connection"
require "wp_api_client/collection"
require "wp_api_client/relationship"

module WpApiClient

  def self.get_client
    @client ||= Client.new(Connection.new(configuration))
  end

  # for tests
  def self.reset!
    @client = nil
  end

  class RelationNotDefined < StandardError; end
  class ErrorResponse < StandardError

    attr_reader :error
    attr_reader :status

    def initialize(json)
      @error = OpenStruct.new(json)
      @status = @error.data["status"]
    end
  end
end


text:
from sahara.i18n import _
from sahara.plugins import provisioning as p

class FakePluginProvider(p.ProvisioningPluginBase):

    def get_title(self):
        return "Fake Plugin"

    def get_description(self):
        return _("It's a fake plugin that aimed to work on the CirrOS images. "
                 "It doesn't install Hadoop. It's needed to be able to test "
                 "provisioning part of Sahara codebase itself.")

    def get_versions(self):
        return ["0.1"]

    def get_node_processes(self, hadoop_version):
        return {
            "HDFS": ["namenode", "datanode"],
            "MapReduce": ["tasktracker", "jobtracker"],
        }

    def get_configs(self, hadoop_version):
        # no need to expose any configs, it could be checked using real plugins
        return []

    def configure_cluster(self, cluster):
        # noop
        pass

    def start_cluster(self, cluster):
        # noop
        pass


text:
/*!
\ingroup PkgMesh_3SecondaryConcepts
\cgalConcept

The concept `LabeledImage_3` describes the requirements for the second template
parameter of the class `CGAL::Labeled_image_mesh_domain_3<Image,BGT>`
which represents mesh domains defined by 3D labeled images. A 3D labeled
image is a 3D array of elements of an integral
type `Type`. `Type` can be `bool`, `char`, `short`,
`int`, or `long` (signed or not). Such an array is
associated to a 3D axis-aligned regular grid, in
\f$ \mathbb{R}^3\f$. A cell of this grid is denoted by <I>voxel</I>. A voxel is
an iso-cuboid of size `vx()`, `vy()`, and `vz()`.

\cgalHasModel `CGAL::Image_3<Kernel, T>`, for any \cgal kernel `K` and any integral type `T`

*/

class LabeledImage_3 {
public:

/// \name Types
/// @{

/*!
Type of voxel data. Must be an
integral type.
*/
typedef unspecified_type Type;

/*!
Ring number type.
*/
typedef unspecified_type RT;

/// @}

/// \name Operations
/// @{

/*!
First dimension of the 3D array,
i.e., the number of voxels along the x coordinate axis.
*/
int xdim();

/*!
Second dimension of the 3D array.
*/
int ydim();

/*!
Third dimension of the 3D array.
*/
int zdim();

/*!
Size of each voxel along x coordinate axis.
*/
RT vx();

/*!
Size of each voxel along y coordinate axis.
*/
RT vy();

/*!
Size of each voxel along z coordinate axis.
*/
RT vz();

/*!
Pointer to the first element of the 3D
image. The size of the array must be `xdim()`\f$ \times\f$`ydim()`\f$ \times\f$`zdim()`.
*/
const Type* data();

/// @}

}; /* end LabeledImage_3 */


text:
<?php

/**
 * Description of dataFactory
 *
 * @author houceml
 */

namespace Lamari\ReporterLBundle\DataFactory;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Lamari\ReporterLBundle\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class dataFactory
{

    protected $serializer;

    public function __construct(Serializer $serializer = null, $encoders = array()) {

        if ((!is_null($serializer) and ( !$this->supportsDecoding('json')
                or ! $this->supportsDecoding('xml')
                or ! $this->supportsDecoding('csv'))) or is_null($serializer)) {

            $encoders = array(new XmlEncoder(), new JsonEncoder(), new CsvEncoder());

            $norm = new ObjectNormalizer();
            $normalizers = array($norm);
            $this->serializer = new Serializer($normalizers, $encoders);

        } else {
            $this->serializer = $serializer;
        }

    }

    public function serialize($data, $type = 'json') {
        return $this->serializer->serialize($data, $type);
    }

}


text:
/**
 * @author maurobuselli@gmail.com

 */
(function () {
  'use strict';

  angular.module('AngularPanelsApp.theme.components')
      .directive('pageTop', pageTop);

  /** @ngInject */
  function pageTop() {
    return {
      restrict: 'E',
      templateUrl: 'app/theme/components/pageTop/pageTop.html'
    };
  }

})();


text:
package bookshop2.supplier.data.bookOrderLog;

import java.util.List;

import javax.persistence.EntityManager;

import org.aries.Assert;
import org.aries.common.AbstractTestCase;
import org.aries.runtime.RequestContext;
import org.aries.tx.BytemanHelper;
import org.aries.tx.BytemanRule;
import org.aries.tx.BytemanUtil;
import org.aries.tx.ServiceModuleTestControl;
import org.aries.tx.TransactionParticipantManager;
import org.aries.tx.TransactionTestControl;
import org.aries.tx.Transactional;
import org.aries.util.FieldUtil;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import bookshop2.Order;
import bookshop2.supplier.BookOrderLogRepository;
import bookshop2.supplier.BookOrderLogRepositoryImpl;
import bookshop2.supplier.SupplierContext;
import bookshop2.supplier.SupplierDataTestFixture;
import bookshop2.supplier.bean.BookOrdersManager;
import bookshop2.supplier.bean.BookOrdersManagerImpl;
import bookshop2.supplier.entity.BookOrdersEntity;
import bookshop2.util.Bookshop2Fixture;

//@RunWith(MockitoJUnitRunner.class)
public class BookOrderLogManagerIT extends AbstractTestCase {

	private static TransactionTestControl transactionControl;

	private static ServiceModuleTestControl bookOrderLogControl;

	private BookOrderLog bookOrderLog;

	private BookOrderLogHelper bookOrderLogHelper;

	private BookOrderLogManager bookOrderLogManager;

	private BookOrderLogRepository bookOrderLogRepository;

	private BookOrdersManager bookOrdersManager;

	@Rule
	public BytemanHelper byteman = BytemanHelper.create(BookOrderLogManagerIT.class);

	@BeforeClass
	public static void beforeClass() throws Exception {
		BytemanUtil.initialize();
		createTransactionControl();
		createBookInventoryControl();
	}

	protected static void createTransactionControl() throws Exception {
		transactionControl = new TransactionTestControl();
		transactionControl.setupTransactionManager();
	}

	protected static void createBookInventoryControl() throws Exception {
		bookOrderLogControl = new ServiceModuleTestControl(transactionControl);
		bookOrderLogControl.setDatabaseName("bookshop2_supplier_db");
		bookOrderLogControl.setDataSourceName("bookshop2_supplier_ds");
		bookOrderLogControl.setPersistenceUnitName("bookOrderLog");
		bookOrderLogControl.setupDataLayer();
	}

	@AfterClass
	public static void afterCLass() throws Exception {
		transactionControl.tearDown();
		bookOrderLogControl.tearDown();
	}

	@Before
	public void setUp() throws Exception {
		transactionControl.setUp();
		bookOrderLogControl.setUp();
		createBookOrderLogManager();
		createBookOrderLogHelper();
		bookOrderLogControl.startServices();
	}

	@After
	public void tearDown() throws Exception {
		bookOrderLogHelper = null;
		bookOrderLogManager = null;
		bookOrderLogControl.stopServices();
		bookOrderLogControl.tearDown();
		transactionControl.tearDown();
	}

//	protected void openEntityManager() throws Exception {
//	FieldUtil.setFieldValue(bookOrdersDao, "em", bookOrderLogControl.createEntityManager());
//}

//	protected void closeEntityManager() throws Exception {
//		bookOrderLogControl.resetEntityManager();
//	}

//	public SupplierContext createSupplierContext() {
//		SupplierContext supplierContext = new SupplierContext();
//		return supplierContext;
//	}

	public RequestContext createRequestContext() {
		RequestContext requestContext = new RequestContext();
		return requestContext;
	}

	protected void createBookOrderLogHelper() throws Exception {
		bookOrderLogHelper = new BookOrderLogHelper();
		EntityManager createEntityManager = bookOrderLogControl.createEntityManager();
		FieldUtil.setFieldValue(bookOrderLogHelper, "entityManager", createEntityManager);
		bookOrderLogHelper.initialize(bookOrderLogControl);
	}

	public void createBookOrderLogManager() throws Exception {
		bookOrderLogManager = new BookOrderLogManager();
		FieldUtil.setFieldValue(bookOrderLogManager, "requestContext", createRequestContext());
		FieldUtil.setFieldValue(bookOrderLogManager, "bookOrderLog", createBookOrderLog());
	}

	public BookOrderLog createBookOrderLog() throws Exception {
		bookOrderLog = new BookOrderLog();
		FieldUtil.setFieldValue(bookOrderLog, "bookOrderLogRepository", createBookOrderLogRepository());
		return bookOrderLog;
	}

	public BookOrderLogRepository createBookOrderLogRepository() throws Exception {
		bookOrderLogRepository = new BookOrderLogRepositoryImpl();
		FieldUtil.setFieldValue(bookOrderLogRepository, "bookOrdersManager", createBooksOrdersManager());
		return bookOrderLogRepository;
	}

	public BookOrdersManager createBooksOrdersManager() throws Exception {
		bookOrdersManager = new BookOrdersManagerImpl();
		EntityManager entityManager = bookOrderLogControl.createEntityManager();
		FieldUtil.setFieldValue(bookOrdersManager, "entityManager", entityManager);
		FieldUtil.setFieldValue(bookOrdersManager, "bookOrdersDao", SupplierDataTestFixture.createBookOrdersDao());
		FieldUtil.setFieldValue(bookOrdersManager, "bookOrdersMapper", SupplierDataTestFixture.getBookOrdersMapper());
		bookOrdersManager.initialize();
		return bookOrdersManager;
	}

	protected BookOrdersEntity createBookOrdersEntity() throws Exception {
		BookOrdersEntity entity = bookOrderLogHelper.createBookOrdersEntity();
		return entity;
	}

	@Test
	//@Ignore
	public void testReserveBooks_TxCommit() throws Exception {
		String testName = "testReserveBooks_TxCommit";
		log.info(testName+": started");

		bookOrderLogHelper.assureRemoveAll();
		transactionControl.beginTransaction();

		List<Order> expectedBookOrders = Bookshop2Fixture.createList_Order();

		try {
			bookOrderLogManager.addToBookOrders(expectedBookOrders);
			transactionControl.commitTransaction();
			transactionControl.assertCommitted();

		} catch (Exception e) {
			e.printStackTrace();
			transactionControl.rollbackTransaction();
		}

		Bookshop2Fixture.assertSameOrder(expectedBookOrders, bookOrderLogManager.getAllBookOrders());
		bookOrderLogHelper.verifyBookOrdersCount(expectedBookOrders.size());
		log.info(testName+": done");
	}

	@Test
	//@Ignore
	@BytemanRule(name = "rule1",
			targetClass = "BookOrderLogManager",
			targetMethod = "addToBookOrders",
			targetLocation = "AT EXIT",
			action = "throw new java.lang.RuntimeException(\"error1\")"
	)
	public void testReserveBooks_TxRollback() throws Exception {
		String testName = "testReserveBooks_TxRollback";
		log.info(testName+": started");

		bookOrderLogHelper.assureRemoveAll();
		transactionControl.beginTransaction();

		List<Order> expectedBookOrders = Bookshop2Fixture.createList_Order();

		try {
			bookOrderLogManager.addToBookOrders(expectedBookOrders);
			fail("Exception should be thrown");

		} catch (Exception e) {
			Assert.equals(e.getMessage(), "error1");
			transactionControl.rollbackTransaction();
			transactionControl.assertRolledBack();
		}

		Assert.isEmpty(bookOrderLogManager.getAllBookOrders());
		bookOrderLogHelper.verifyBookOrdersCount(0);
		log.info(testName+": done");
	}

	@Test
	@Ignore
	public void testAddReservedBooks_GlobalTxCommit() throws Exception {
		bookOrderLogControl.assureDeleteAll();

		String transactionId = transactionControl.beginGlobalTransaction();
		Transactional transactional = transactionControl.createMockTransactional(bookOrderLogManager);
		TransactionParticipantManager.getInstance().enroll(transactional, transactionId);

		List<Order> expectedBookOrders = Bookshop2Fixture.createList_Order();

		try {
			//bookOrderLogManager.setTransactionId(transactionId);
			bookOrderLogManager.addToBookOrders(expectedBookOrders);
			bookOrderLogManager.updateState();
			transactionControl.commitGlobalTransaction();
			transactionControl.assertCommitted(transactional);

		} catch (Exception e) {
			e.printStackTrace();
			transactionControl.rollbackGlobalTransaction();
			transactionControl.assertRolledBack(transactional);
		}

		Bookshop2Fixture.assertSameOrder(expectedBookOrders, bookOrderLogManager.getAllBookOrders());
		bookOrderLogHelper.verifyBookOrdersCount(1);
	}

	@Test
	@Ignore
	@BytemanRule(name = "rule2",
		targetClass = "BookInventoryManager",
		targetMethod = "addToReservedBooks",
		targetLocation = "AT EXIT",
		action = "throw new java.lang.RuntimeException(\"error2\")")
	public void testReserveBooks_GlobalTxRollback() throws Exception {
		try {
			bookOrderLogControl.assureDeleteAll();

			String transactionId = transactionControl.beginGlobalTransaction();
			Transactional transactional = transactionControl.createMockTransactional(bookOrderLogManager);
			TransactionParticipantManager.getInstance().enroll(transactional, transactionId);

			List<Order> expectedBookOrders = Bookshop2Fixture.createList_Order();

			try {
				bookOrderLogManager.addToBookOrders(expectedBookOrders);
				bookOrderLogManager.updateState();
				transactionControl.rollbackGlobalTransaction();
				transactionControl.assertRolledBack(transactional);

			} catch (Exception e) {
				e.printStackTrace();
			}

			Assert.isEmpty(bookOrderLogManager.getAllBookOrders());
			transactionControl.assertRolledBack(transactional);
			bookOrderLogHelper.verifyBookOrdersCount(0);

		} catch (Exception e) {
			e.printStackTrace();
			transactionControl.rollbackGlobalTransaction();
		}
	}

//	protected Long assureAddReservedBooks() throws Exception {
//		BookEntity bookOrdersEntity = createBookEntity();
//		Long id = assureAddReservedBooks(bookOrdersEntity);
//		return id;
//	}
//
//	protected Long assureAddReservedBooks(BookEntity bookOrders) throws Exception {
//		openEntityManager();
//		beginTransaction();
//		Long id = reservedBooksDao.addReservedBooks(bookOrders);
//		commitTransaction();
//		verifyReservedBooksExists(id);
//		closeEntityManager();
//		return id;
//	}
//
//	protected void assureDeleteReservedBooks(Long id) throws Exception {
//		BookEntity bookOrders = reservedBooksDao.getReservedBooksById(id);
//		assureDeleteReservedBooks(bookOrders);
//	}
//
//	protected void assureDeleteReservedBooks(BookEntity bookOrders) throws Exception {
//		openEntityManager();
//		beginTransaction();
//		reservedBooksDao.deleteReservedBooks(bookOrders);
//		commitTransaction();
//		verifyReservedBooksNotExists(bookOrders);
//		closeEntityManager();
//	}
//
//
//	protected void verifyReservedBooksCount(int expectedCount) throws Exception {
//		List<BookEntity> reservedBooks = reservedBooksDao.getAllReservedBooksRecords();
//		verifyReservedBooksCount(reservedBooks, expectedCount);
//	}
//
//	protected void verifyReservedBooksCount(Collection<BookEntity> reservedBooks, int expectedCount) throws Exception {
//		Assert.notNull(reservedBooks, "Result not found");
//		if (expectedCount > 0)
//			Assert.notNull(reservedBooks, "ReservedBooks records should exist");
//		Assert.equals(expectedCount, reservedBooks.size(), "ReservedBooks record count not correct");
//	}
//
//	protected void verifyReservedBooksExists(BookEntity reservedBooks) throws Exception {
//		verifyReservedBooksExists(reservedBooks.getId());
//	}
//
//	protected void verifyReservedBooksExists(Long id) throws Exception {
//		BookEntity bookOrders = reservedBooksDao.getReservedBooksById(id);
//		Assert.notNull(bookOrders, "ReservedBooks should exist");
//		Assert.equals(bookOrders.getId(), id, "Ids should be same");
//	}
//
//	protected void verifyReservedBooksNotExists(BookEntity reservedBooks) throws Exception {
//		verifyReservedBooksNotExists(reservedBooks.getId());
//	}
//
//	protected void verifyReservedBooksNotExists(Long id) throws Exception {
//		BookEntity reservedBooks = reservedBooksDao.getReservedBooksById(id);
//		Assert.isNull(reservedBooks, "ReservedBooks should not exist");
//	}

}


text:
<?php
namespace Omea\GestionTelco\EvenementsBundle\Exception;

/**
 * This exception replace the AccessDeniedException
 */
class AccessDeniedException extends \RuntimeException
{
    const ACCESS_DENIED_EXCEPTION = 3000;

    /**
     * @param string $message
     * @param integer $code
     * @param \Exception | null $previous
     */
    public function __construct($message, $code = AccessDeniedException::ACCESS_DENIED_EXCEPTION, $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
	mongoose = require('mongoose'),
	faker = require('faker'),
	Organization = mongoose.model('Organization'),
	User = mongoose.model('User'),
	Plant = mongoose.model('Plant');

/**
 * Globals
 */
var user, plant, organization;

/**
 * Unit tests
 */
describe('Plant Model Unit Tests:', function() {
	beforeEach(function(done) {

		user = new User({
			firstName: faker.name.firstName(),
			lastName: faker.name.lastName(),
			displayName: faker.name.firstName() + faker.name.lastName(),
			email: faker.internet.email(),
			username: faker.internet.userName(),
			password: faker.internet.password()
		});

		organization = new Organization({
			name: faker.company.companyName(),
			user: user._id
		})

		user.save(function() {
			plant = new Plant({
				organization: organization._id,
				commonName: faker.commerce.productName(),
				scientificName: faker.commerce.productMaterial(),
				unitSize: faker.commerce.productAdjective(),
				unitPrice: faker.commerce.price(),
				unitAvailability: [{
					date: new Date(),
					quantity: faker.random.number()
				}]
			});

			done();
		});
	});

	describe('Method Save', function() {
		it('should be able to save without problems', function(done) {
			return plant.save(function(err) {
				should.not.exist(err);
				done();
			});
		});

		it('should be able to show an error when try to save without name', function(done) {
			plant.commonName = '';
			return plant.save(function(err) {
				should.exist(err);
				done();
			});
		});
	});

	afterEach(function(done) {
		Plant.remove().exec();
		User.remove().exec();
		Organization.remove().exec();
		done();
	});
});


text:
module.exports = [
    "@angular/platform-browser-dynamic",
    "@angular/platform-browser",
    "@angular/core",
    "@angular/http",
    "@angular/router",
    "@angular/forms",

    "rxjs/Rx",
];


text:
@interface SCBGrowlClient : NSObject <GrowlApplicationBridgeDelegate>

+ (id)sharedClient;
- (void)notifyNewMessageWithTitle:(NSString *)title
                      description:(NSString *)description
                         isSticky:(BOOL)isSticky
                         userInfo:(NSDictionary *)userInfo;
- (void)notifySystemEventWithTitle:(NSString *)title
                       description:(NSString *)description
                          isSticky:(BOOL)isSticky;

@end


text:
A flexible header that tracks a scroll view will expand and contract its height in reaction to
scroll view events. A flexible header can also shift off-screen in reaction to scroll view events
by changing the flexible header's behavior.

#### Swift
```swift
headerViewController.headerView.shiftBehavior = .enabled
```

#### Objective-C
```objc
headerViewController.headerView.shiftBehavior = MDCFlexibleHeaderShiftBehaviorEnabled;
```

> Important: when a flexible header shifts off-screen it **will not hide the content views**. Your
> content views are responsible for hiding themselves in reaction to the flexible header shifting
> off-screen. Read the section on [Reacting to frame changes](#reacting-to-frame-changes) for more
> information.

It is also possible to hide the status bar when shifting the flexible header off-screen. Enable this
behavior by setting the `enabledWithStatusBar` behavior and implementing
`childViewControllerForStatusBarHidden` on the parent view controller.

#### Swift
```swift
headerViewController.headerView.shiftBehavior = .enabledWithStatusBar

override func childViewControllerForStatusBarHidden() -> UIViewController? {
  return headerViewController
}
```

#### Objective-C
```objc
headerViewController.headerView.shiftBehavior = MDCFlexibleHeaderShiftBehaviorEnabledWithStatusBar;

- (UIViewController *)childViewControllerForStatusBarHidden {
  return _headerViewController;
}
```


text:
<?php

use Illuminate\Database\Seeder;
use App\Blog;
use App\Tag;

class TaggablesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('taggables')->truncate();

        $tags = Tag::all();
        $blogs = Blog::all();
        foreach ($blogs as $blog) {

            $tags->shuffle();

            $randomTags = $tags->random(3);
            $blog->tags()->attach($randomTags);
        }
    }
}


text:
package ch.bfh.bti7081.s2016.red.SolidAlpha.model;
import ch.bfh.bti7081.s2016.red.SolidAlpha.persistence.Store;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * Created by herren on 5/11/16.
 */
public class BaseEntity implements Serializable {

    protected BaseEntity()
    {

    }

    public void delete(){

        EntityManager em = Store.getInstance().getEntityManager();
        em.getTransaction().begin();
        BaseEntity toBeRemoved = em.merge(this);
        em.remove(toBeRemoved);
        em.getTransaction().commit();

    }

    public void save()
    {
        Store.getInstance().addEntity(this);
    }

}


text:
package ua.com.gfalcon.gesem.dao.norms;

import org.springframework.data.repository.PagingAndSortingRepository;
import ua.com.gfalcon.gesem.domain.norms.WorksType;

/**
 * @author Oleksii Khalikov
 * @version 1.0
 * @since 1.0
 */
public interface WorksTypeDAO extends PagingAndSortingRepository<WorksType, Long> {
}


text:
package backtype.storm.tuple;

import backtype.storm.utils.Utils;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;

public class MessageId {
    private Map<Long, Long> _anchorsToIds;

    @Deprecated
    public static long generateId() {
        return Utils.secureRandomLong();
    }

    public static long generateId(Random rand) {
        return rand.nextLong();
    }

    public static MessageId makeUnanchored() {
        return makeId(new HashMap<Long, Long>());
    }

    public static MessageId makeId(Map<Long, Long> anchorsToIds) {
        return new MessageId(anchorsToIds);
    }

    public static MessageId makeRootId(long id, long val) {
        Map<Long, Long> anchorsToIds = new HashMap<Long, Long>();
        anchorsToIds.put(id, val);
        return new MessageId(anchorsToIds);
    }

    protected MessageId(Map<Long, Long> anchorsToIds) {
        _anchorsToIds = anchorsToIds;
    }

    public Map<Long, Long> getAnchorsToIds() {
        return _anchorsToIds;
    }

    public Set<Long> getAnchors() {
        return _anchorsToIds.keySet();
    }

    @Override
    public int hashCode() {
        return _anchorsToIds.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (other instanceof MessageId) {
            return _anchorsToIds.equals(((MessageId) other)._anchorsToIds);
        } else {
            return false;
        }
    }

    @Override
    public String toString() {
        return _anchorsToIds.toString();
    }

    public void serialize(Output out) throws IOException {
        out.writeInt(_anchorsToIds.size(), true);
        for (Entry<Long, Long> anchorToId : _anchorsToIds.entrySet()) {
            out.writeLong(anchorToId.getKey());
            out.writeLong(anchorToId.getValue());
        }
    }

    public static MessageId deserialize(Input in) throws IOException {
        int numAnchors = in.readInt(true);
        Map<Long, Long> anchorsToIds = new HashMap<Long, Long>();
        for (int i = 0; i < numAnchors; i++) {
            anchorsToIds.put(in.readLong(), in.readLong());
        }
        return new MessageId(anchorsToIds);
    }
}


text:
## PDF to JSON API in Java and PDF.co Web API PDF.co Web API is the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=PDF.co%20Web%20API%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=PDF.co%20Web%20API%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore Documentation](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Explore Source Code Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://app.pdf.co/signup?utm_source=github-readme)
[Security](https://pdf.co/security)
[Explore Web API Documentation](https://apidocs.pdf.co?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### **Main.java:**

```
package com.company;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;

import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main
{
    // The authentication key (API Key).
    // Get your own by registering at https://app.pdf.co
    final static String API_KEY = "***********************************";

    // Source PDF file
    final static Path SourceFile = Paths.get(".\\sample.pdf");
    // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
    final static String Pages = "";
    // PDF document password. Leave empty for unprotected documents.
    final static String Password = "";
    // Destination JSON file name
    final static Path DestinationFile = Paths.get(".\\result.json");

    public static void main(String[] args) throws IOException
    {
        // Create HTTP client instance
        OkHttpClient webClient = new OkHttpClient();

        // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
        // * If you already have a direct file URL, skip to the step 3.

        // Prepare URL for `Get Presigned URL` API call
        String query = String.format(
                "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=%s",
                SourceFile.getFileName());

        // Prepare request
        Request request = new Request.Builder()
                .url(query)
                .addHeader("x-api-key", API_KEY) // (!) Set API Key
                .build();
        // Execute request
        Response response = webClient.newCall(request).execute();

        if (response.code() == 200)
        {
            // Parse JSON response
            JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();

            boolean error = json.get("error").getAsBoolean();
            if (!error)
            {
                // Get URL to use for the file upload
                String uploadUrl = json.get("presignedUrl").getAsString();
                // Get URL of uploaded file to use with later API calls
                String uploadedFileUrl = json.get("url").getAsString();

                // 2. UPLOAD THE FILE TO CLOUD.

                if (uploadFile(webClient, API_KEY, uploadUrl, SourceFile))
                {
                    // 3. CONVERT UPLOADED PDF FILE TO JSON

                    PdfToJson(webClient, API_KEY, DestinationFile, Password, Pages, uploadedFileUrl);
                }
            }
            else
            {
                // Display service reported error
                System.out.println(json.get("message").getAsString());
            }
        }
        else
        {
            // Display request error
            System.out.println(response.code() + " " + response.message());
        }
    }

    public static void PdfToJson(OkHttpClient webClient, String apiKey, Path destinationFile,
        String password, String pages, String uploadedFileUrl) throws IOException
    {
		/*
		Some of advanced options available through profiles:
		(it can be single/double-quoted and contain comments.)
		{
			"profiles": [
				{
					"profile1": {
						"SaveImages": "None", // Whether to extract images. Values: "None", "Embed".
						"ImageFormat": "PNG", // Image format for extracted images. Values: "PNG", "JPEG", "GIF", "BMP".
						"SaveVectors": false, // Whether to extract vector objects (vertical and horizontal lines). Values: true / false
						"ExtractInvisibleText": true, // Invisible text extraction. Values: true / false
						"ExtractShadowLikeText": true, // Shadow-like text extraction. Values: true / false
						"LineGroupingMode": "None", // Values: "None", "GroupByRows", "GroupByColumns", "JoinOrphanedRows"
						"ColumnDetectionMode": "ContentGroupsAndBorders", // Values: "ContentGroupsAndBorders", "ContentGroups", "Borders", "BorderedTables"
						"Unwrap": false, // Unwrap grouped text in table cells. Values: true / false
						"ShrinkMultipleSpaces": false, // Shrink multiple spaces in table cells that affect column detection. Values: true / false
						"DetectNewColumnBySpacesRatio": 1, // Spacing ratio that affects column detection.
						"CustomExtractionColumns": [ 0, 50, 150, 200, 250, 300 ], // Explicitly specify columns coordinates for table extraction.
						"CheckPermissions": true, // Ignore document permissions. Values: true / false
					}
				}
			]
		}
		*/

        // Sample profile that sets advanced conversion options
        // Advanced options are properties of JSONExtractor class from ByteScout JSON Extractor SDK used in the back-end:
        // https://cdn.bytescout.com/help/BytescoutPDFExtractorSDK/html/84356d44-6249-3251-2da8-83c1f34a2f39.htm
        String profiles = "{ 'profiles': [ { 'profile1': { 'TrimSpaces': 'False', 'PreserveFormattingOnTextExtraction': 'True' } } ] }";

        // Prepare URL for `PDF To JSON` API call
        String query = "https://api.pdf.co/v1/pdf/convert/to/json";

        // Make correctly escaped (encoded) URL
        URL url = null;
        try
        {
            url = new URI(null, query, null).toURL();
        }
        catch (URISyntaxException e)
        {
            e.printStackTrace();
        }

        // Create JSON payload
		String jsonPayload = String.format("{\"name\": \"%s\", \"password\": \"%s\", \"pages\": \"%s\", \"url\": \"%s\", \"profiles\": \"%s\"}",
                destinationFile.getFileName(),
                password,
                pages,
                uploadedFileUrl,
                profiles);

        // Prepare request body
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);

        // Prepare request
        Request request = new Request.Builder()
            .url(url)
            .addHeader("x-api-key", API_KEY) // (!) Set API Key
            .addHeader("Content-Type", "application/json")
            .post(body)
            .build();

        // Execute request
        Response response = webClient.newCall(request).execute();

        if (response.code() == 200)
        {
            // Parse JSON response
            JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();

            boolean error = json.get("error").getAsBoolean();
            if (!error)
            {
                // Get URL of generated JSON file
                String resultFileUrl = json.get("url").getAsString();

                // Download JSON file
                downloadFile(webClient, resultFileUrl, destinationFile.toFile());

                System.out.printf("Generated JSON file saved as \"%s\" file.", destinationFile.toString());
            }
            else
            {
                // Display service reported error
                System.out.println(json.get("message").getAsString());
            }
        }
        else
        {
            // Display request error
            System.out.println(response.code() + " " + response.message());
        }
    }

    public static boolean uploadFile(OkHttpClient webClient, String apiKey, String url, Path sourceFile) throws IOException
    {
        // Prepare request body
        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), sourceFile.toFile());

        // Prepare request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-api-key", apiKey) // (!) Set API Key
                .addHeader("content-type", "application/octet-stream")
                .put(body)
                .build();

        // Execute request
        Response response = webClient.newCall(request).execute();

        return (response.code() == 200);
    }

    public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException
    {
        // Prepare request
        Request request = new Request.Builder()
                .url(url)
                .build();
        // Execute request
        Response response = webClient.newCall(request).execute();

        byte[] fileBytes = response.body().bytes();

        // Save downloaded bytes to file
        OutputStream output = new FileOutputStream(destinationFile);
        output.write(fileBytes);
        output.flush();
        output.close();

        response.close();
    }
}

```

<!-- code block end -->


text:
// This file is part of the ustl library, an STL implementation.
//
// Copyright (C) 2005 by Mike Sharov <msharov@users.sourceforge.net>
// This file is free software, distributed under the MIT License.
//
// ustring.cpp
//
//	STL basic_string equivalent functionality.
//

#include "ustring.h"
#include "mistream.h"
#include "mostream.h"
#include "ualgo.h"
#include <stdio.h>	// for vsnprintf (in string::format)
#ifdef __SYMBIAN32__
#  include "printfsupport.h" // Actual vsnprintf in symbian.
#endif

namespace ustl {

//----------------------------------------------------------------------

const uoff_t string::npos;
const string::size_type string::size_Terminator;
const string::value_type string::c_Terminator;
const char string::empty_string[string::size_Terminator] = "";

typedef utf8in_iterator<string::const_iterator> utf8icstring_iterator;
typedef utf8in_iterator<string::iterator> utf8istring_iterator;
typedef utf8out_iterator<string::iterator> utf8ostring_iterator;

//----------------------------------------------------------------------

/// Creates an empty string.
string::string (void)
: memblock ()
{
    link (empty_string, 0U);
}

/// Assigns itself the value of string \p s
string::string (const string& s)
: memblock()
{
    if (s.is_linked())
	link (s.c_str(), s.size());
    else
	assign (s);
}

/// Links to \p s
string::string (const_pointer s)
: memblock ()
{
    if (!s)
	s = empty_string;
    link (s, strlen(s));
}

/// Creates a string of length \p n filled with character \p c.
string::string (size_type n, value_type c)
: memblock ()
{
    resize (n);
    fill_n (begin(), n, c);
}

/// Resize the string to \p n characters. New space contents is undefined.
void string::resize (size_type n)
{
    memblock::resize (n);
    at(n) = c_Terminator;
}

/// Assigns itself the value of string \p s
void string::assign (const_pointer s)
{
    if (!s)
	s = empty_string;
    assign (s, strlen (s));
}

/// Assigns itself the value of string \p s of length \p len.
void string::assign (const_pointer s, size_type len)
{
    while (len && s[len - 1] == c_Terminator)
	-- len;
    resize (len);
    copy (s, len);
}

/// Appends to itself the value of string \p s of length \p len.
void string::append (const_pointer s)
{
    if (!s)
	s = empty_string;
    append (s, strlen (s));
}

/// Appends to itself the value of string \p s of length \p len.
void string::append (const_pointer s, size_type len)
{
    while (len && s[len - 1] == c_Terminator)
	-- len;
    resize (size() + len);
    copy_n (s, len, end() - len);
}

/// Appends to itself \p n characters of value \p c.
void string::append (size_type n, value_type c)
{
    resize (size() + n);
    fill_n (end() - n, n, c);
}

/// Copies into itself at offset \p start, the value of string \p p of length \p n.
string::size_type string::copyto (pointer p, size_type n, const_iterator start) const
{
    assert (p && n);
    if (!start)
	start = begin();
    const size_type btc = min(n - size_Terminator, size());
    copy_n (start, btc, p);
    p[btc] = c_Terminator;
    return (btc + size_Terminator);
}

/// Returns comparison value regarding string \p s.
/// The return value is:
/// \li 1 if this string is greater (by value, not length) than string \p s
/// \li 0 if this string is equal to string \p s
/// \li -1 if this string is less than string \p s
///
/*static*/ int string::compare (const_iterator first1, const_iterator last1, const_iterator first2, const_iterator last2)
{
    assert (first1 <= last1 && (first2 <= last2 || !last2) && "Negative ranges result in memory allocation errors.");
    const size_type len1 = distance (first1, last1), len2 = distance (first2, last2);
    const int rvbylen = sign (int(len1 - len2));
    int rv = memcmp (first1, first2, min (len1, len2));
    return (rv ? rv : rvbylen);
}

/// Returns true if this string is equal to string \p s.
bool string::operator== (const_pointer s) const
{
    if (!s)
	s = empty_string;
    return (size() == strlen(s) && 0 == memcmp (c_str(), s, size()));
}

/// Returns the beginning of character \p i.
string::iterator string::utf8_iat (uoff_t i)
{
    utf8istring_iterator cfinder (begin());
    cfinder += i;
    return (cfinder.base());
}

/// Inserts wide character \p c at \p ip \p n times as a UTF-8 string.
///
/// \p ip is a character position, not a byte position, and must fall in
/// the 0 through length() range.
/// The first argument is not an iterator because it is rather difficult
/// to get one. You'd have to use ((utf8begin() + n).base()) as the first
/// argument, which is rather ugly. Besides, then this insert would be
/// ambiguous with the regular character insert.
///
void string::insert (const uoff_t ip, wchar_t c, size_type n)
{
    iterator ipp (utf8_iat (ip));
    ipp = iterator (memblock::insert (memblock::iterator(ipp), n * Utf8Bytes(c)));
    fill_n (utf8out (ipp), n, c);
    *end() = c_Terminator;
}

/// Inserts sequence of wide characters at \p ip.
void string::insert (const uoff_t ip, const wchar_t* first, const wchar_t* last, const size_type n)
{
    iterator ipp (utf8_iat (ip));
    size_type nti = distance (first, last), bti = 0;
    for (uoff_t i = 0; i < nti; ++ i)
	bti += Utf8Bytes(first[i]);
    ipp = iterator (memblock::insert (memblock::iterator(ipp), n * bti));
    utf8ostring_iterator uout (utf8out (ipp));
    for (uoff_t j = 0; j < n; ++ j)
	for (uoff_t k = 0; k < nti; ++ k, ++ uout)
	    *uout = first[k];
    *end() = c_Terminator;
}

/// Inserts character \p c into this string at \p start.
string::iterator string::insert (iterator start, const_reference c, size_type n)
{
    start = iterator (memblock::insert (memblock::iterator(start), n));
    fill_n (start, n, c);
    *end() = c_Terminator;
    return (start);
}

/// Inserts \p count instances of string \p s at offset \p start.
string::iterator string::insert (iterator start, const_pointer s, size_type n)
{
    if (!s)
	s = empty_string;
    return (insert (start, s, s + strlen(s), n));
}

/// Inserts [first,last] \p n times.
string::iterator string::insert (iterator start, const_pointer first, const_pointer last, size_type n)
{
    assert (first <= last);
    assert (begin() <= start && end() >= start);
    assert ((first < begin() || first >= end() || size() + abs_distance(first,last) < capacity()) && "Insertion of self with autoresize is not supported");
    start = iterator (memblock::insert (memblock::iterator(start), distance(first, last) * n));
    fill (memblock::iterator(start), first, distance(first, last), n);
    *end() = c_Terminator;
    return (start);
}

/// Erases \p size bytes at \p start.
string::iterator string::erase (iterator ep, size_type n)
{
    string::iterator rv = memblock::erase (memblock::iterator(ep), n);
    *end() = c_Terminator;
    return (rv);
}

/// Erases \p size characters at \p start.
/// \p start is a character position, not a byte position, and must be
/// in the 0..length() range.
///
void string::erase (uoff_t ep, size_type n)
{
    iterator first (utf8_iat(ep));
    size_t nbytes (utf8_iat(ep + n) - first);
    memblock::erase (first, nbytes);
    *end() = c_Terminator;
}

/// Replaces range [\p start, \p start + \p len] with string \p s.
void string::replace (iterator first, iterator last, const_pointer s)
{
    if (!s)
	s = empty_string;
    replace (first, last, s, s + strlen(s));
}

/// Replaces range [\p start, \p start + \p len] with \p count instances of string \p s.
void string::replace (iterator first, iterator last, const_pointer i1, const_pointer i2, size_type n)
{
    assert (first <= last);
    assert (n || distance(first, last));
    assert (first >= begin() && first <= end() && last >= first && last <= end());
    assert ((i1 < begin() || i1 >= end() || abs_distance(i1,i2) * n + size() < capacity()) && "Replacement by self can not autoresize");
    const size_type bte = distance(first, last), bti = distance(i1, i2) * n;
    if (bti < bte)
	first = iterator (memblock::erase (memblock::iterator(first), bte - bti));
    else if (bte < bti)
	first = iterator (memblock::insert (memblock::iterator(first), bti - bte));
    fill (memblock::iterator(first), i1, distance(i1, i2), n);
    *end() = c_Terminator;
}

/// Returns the offset of the first occurence of \p c after \p pos.
uoff_t string::find (const_reference c, uoff_t pos) const
{
    const_iterator found = ::ustl::find (iat(pos), end(), c);
    return (found < end() ? distance(begin(),found) : npos);
}

/// Returns the offset of the first occurence of substring \p s of length \p n after \p pos.
uoff_t string::find (const string& s, uoff_t pos) const
{
    if (s.empty() || s.size() > size() - pos)
	return (npos);
    const uoff_t endi = s.size() - 1;
    const_reference endchar = s[endi];
    uoff_t lastPos = endi;
    while (lastPos-- && s[lastPos] != endchar)
    	;
    const size_type skip = endi - lastPos;
    const_iterator i = iat(pos) + endi;
    for (; i < end() && (i = ::ustl::find (i, end(), endchar)) < end(); i += skip)
	if (memcmp (i - endi, s.c_str(), s.size()) == 0)
	    return (distance (begin(), i) - endi);
    return (npos);
}

/// Returns the offset of the last occurence of character \p c before \p pos.
uoff_t string::rfind (const_reference c, uoff_t pos) const
{
    for (int i = min(pos,size()-1); i >= 0; --i)
	if (at(i) == c)
	    return (i);
    return (npos);
}

/// Returns the offset of the last occurence of substring \p s of size \p n before \p pos.
uoff_t string::rfind (const string& s, uoff_t pos) const
{
    const_iterator d = iat(pos) - 1;
    const_iterator sp = begin() + s.size() - 1;
    const_iterator m = s.end() - 1;
    for (uoff_t i = 0; d > sp && i < s.size(); -- d)
	for (i = 0; i < s.size(); ++ i)
	    if (m[-i] != d[-i])
		break;
    return (d > sp ? distance (begin(), d + 2 - s.size()) : npos);
}

/// Returns the offset of the first occurence of one of characters in \p s of size \p n after \p pos.
uoff_t string::find_first_of (const string& s, uoff_t pos) const
{
    for (uoff_t i = min(pos,size()); i < size(); ++ i)
	if (s.find (at(i)) != npos)
	    return (i);
    return (npos);
}

/// Returns the offset of the first occurence of one of characters in \p s of size \p n after \p pos.
uoff_t string::find_first_of (char c, uoff_t pos) const
{
    for (uoff_t i = min(pos,size()); i < size(); ++ i) {
		if (c == at(i))
			return (i);
    }
    return (npos);
}

/// Returns the offset of the first occurence of one of characters not in \p s of size \p n after \p pos.
uoff_t string::find_first_not_of (const string& s, uoff_t pos) const
{
    for (uoff_t i = min(pos,size()); i < size(); ++ i)
	if (s.find (at(i)) == npos)
	    return (i);
    return (npos);
}

/// Returns the offset of the last occurence of one of characters in \p s of size \p n before \p pos.
uoff_t string::find_last_of (const string& s, uoff_t pos) const
{
    for (int i = min(pos,size()-1); i >= 0; -- i)
	if (s.find (at(i)) != npos)
	    return (i);
    return (npos);
}

/// Returns the offset of the last occurence of one of characters not in \p s of size \p n before \p pos.
uoff_t string::find_last_not_of (const string& s, uoff_t pos) const
{
    for (int i = min(pos,size()-1); i >= 0; -- i)
	if (s.find (at(i)) == npos)
	    return (i);
    return (npos);
}

/// Equivalent to a vsprintf on the string.
int string::vformat (const char* fmt, va_list args)
{
#if HAVE_VA_COPY
    va_list args2;
#else
    #define args2 args
    #undef __va_copy
    #define __va_copy(x,y)
#endif
    size_t rv = size();
#ifdef __SYMBIAN32__
    rv = size() + 256;		// To avoid vsprintf overflowing
#else
    rv = size();
#endif
    do {
    	reserve (rv);
    	__va_copy (args2, args);
    	rv = vsnprintf (data(), memblock::capacity(), fmt, args2);
    	rv = min (rv, memblock::capacity());
    } while (rv > capacity());
    resize (min (rv, capacity()));
    return (rv);
}

/// Equivalent to a sprintf on the string.
int string::format (const char* fmt, ...)
{
    va_list args;
    va_start (args, fmt);
    const int rv = vformat (fmt, args);
    va_end (args);
    return (rv);
}

/// Returns the number of bytes required to write this object to a stream.
size_t string::stream_size (void) const
{
    return (Utf8Bytes(size()) + size());
}

/// Reads the object from stream \p os
void string::read (istream& is)
{
    char szbuf [8];
    is >> szbuf[0];
    size_t szsz (Utf8SequenceBytes (szbuf[0]) - 1), n = 0;
    is.verify_remaining ("read", "ustl::string", szsz);
    is.read (szbuf + 1, szsz);
    n = *utf8in(szbuf);
    is.verify_remaining ("read", "ustl::string", n);
    resize (n);
    is.read (data(), size());
}

/// Writes the object to stream \p os
void string::write (ostream& os) const
{
    const written_size_type sz (size());
    assert (sz == size() && "No support for writing strings larger than 4G");

    char szbuf [8];
    utf8out_iterator<char*> szout (szbuf);
    *szout = sz;
    size_t szsz = distance (szbuf, szout.base());

    os.verify_remaining ("write", "ustl::string", szsz + sz);
    os.write (szbuf, szsz);
    os.write (cdata(), sz);
}

/// Returns a hash value for [first, last)
/*static*/ hashvalue_t string::hash (const char* first, const char* last)
{
    hashvalue_t h = 0;
    // This has the bits flowing into each other from both sides of the number
    for (; first < last; ++ first)
	h = *first + ((h << 7) | (h >> BitsInType(hashvalue_t) - 7));
    return (h);
}

} // namespace ustl


text:
package edu.harvard.iq.dataverse.api.errorhandlers;

import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * Produces custom 500 messages for the API.
 * @author michael
 */
@Provider
public class ArrayOutOfBoundsExceptionHandler implements ExceptionMapper<java.lang.ArrayIndexOutOfBoundsException>{

    private static final Logger logger = Logger.getLogger(ServeletExceptionHandler.class.getName());

    @Context
    HttpServletRequest request;

    @Override
    public Response toResponse(java.lang.ArrayIndexOutOfBoundsException ex){
        String incidentId = UUID.randomUUID().toString();
        logger.log(Level.SEVERE, "API internal error " + incidentId +": ArrayOutOfBounds:" + ex.getMessage(), ex);
        return Response.status(500)
                .entity( Json.createObjectBuilder()
                             .add("status", "ERROR")
                             .add("code", 500)
                             .add("message", "Internal server error. More details available at the server logs.")
                             .add("incidentId", incidentId)
                        .build())
                .type("application/json").build();
    }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Microsoft.Win32.SafeHandles
{
#if REGISTRY_ASSEMBLY
    public
#else
    internal
#endif
    sealed partial class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        internal SafeRegistryHandle() : base(true) { }

        public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle)
        {
            SetHandle(preexistingHandle);
        }
    }
}


text:
// Iostreams base classes -*- C++ -*-

// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING.  If not, write to the Free
// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.

// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.

//
// ISO C++ 14882: 27.4  Iostreams base classes
//

/** @file ios_base.h
 *  This is an internal header file, included by other library headers.
 *  You should not attempt to use it directly.
 */

#ifndef _IOS_BASE_H
#define _IOS_BASE_H 1

#pragma GCC system_header

#include <bits/atomicity.h>
#include <bits/localefwd.h>
#include <bits/locale_classes.h>

namespace std
{
  // The following definitions of bitmask types are enums, not ints,
  // as permitted (but not required) in the standard, in order to provide
  // better type safety in iostream calls.  A side effect is that
  // expressions involving them are no longer compile-time constants.
  enum _Ios_Fmtflags { _S_ios_fmtflags_end = 1L << 16 };

  inline _Ios_Fmtflags
  operator&(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
  { return _Ios_Fmtflags(static_cast<int>(__a) & static_cast<int>(__b)); }

  inline _Ios_Fmtflags
  operator|(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
  { return _Ios_Fmtflags(static_cast<int>(__a) | static_cast<int>(__b)); }

  inline _Ios_Fmtflags
  operator^(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
  { return _Ios_Fmtflags(static_cast<int>(__a) ^ static_cast<int>(__b)); }

  inline _Ios_Fmtflags
  operator|=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b)
  { return __a = __a | __b; }

  inline _Ios_Fmtflags
  operator&=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b)
  { return __a = __a & __b; }

  inline _Ios_Fmtflags
  operator^=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b)
  { return __a = __a ^ __b; }

  inline _Ios_Fmtflags
  operator~(_Ios_Fmtflags __a)
  { return _Ios_Fmtflags(~static_cast<int>(__a)); }

  enum _Ios_Openmode { _S_ios_openmode_end = 1L << 16 };

  inline _Ios_Openmode
  operator&(_Ios_Openmode __a, _Ios_Openmode __b)
  { return _Ios_Openmode(static_cast<int>(__a) & static_cast<int>(__b)); }

  inline _Ios_Openmode
  operator|(_Ios_Openmode __a, _Ios_Openmode __b)
  { return _Ios_Openmode(static_cast<int>(__a) | static_cast<int>(__b)); }

  inline _Ios_Openmode
  operator^(_Ios_Openmode __a, _Ios_Openmode __b)
  { return _Ios_Openmode(static_cast<int>(__a) ^ static_cast<int>(__b)); }

  inline _Ios_Openmode
  operator|=(_Ios_Openmode& __a, _Ios_Openmode __b)
  { return __a = __a | __b; }

  inline _Ios_Openmode
  operator&=(_Ios_Openmode& __a, _Ios_Openmode __b)
  { return __a = __a & __b; }

  inline _Ios_Openmode
  operator^=(_Ios_Openmode& __a, _Ios_Openmode __b)
  { return __a = __a ^ __b; }

  inline _Ios_Openmode
  operator~(_Ios_Openmode __a)
  { return _Ios_Openmode(~static_cast<int>(__a)); }

  enum _Ios_Iostate { _S_ios_iostate_end = 1L << 16 };

  inline _Ios_Iostate
  operator&(_Ios_Iostate __a, _Ios_Iostate __b)
  { return _Ios_Iostate(static_cast<int>(__a) & static_cast<int>(__b)); }

  inline _Ios_Iostate
  operator|(_Ios_Iostate __a, _Ios_Iostate __b)
  { return _Ios_Iostate(static_cast<int>(__a) | static_cast<int>(__b)); }

  inline _Ios_Iostate
  operator^(_Ios_Iostate __a, _Ios_Iostate __b)
  { return _Ios_Iostate(static_cast<int>(__a) ^ static_cast<int>(__b)); }

  inline _Ios_Iostate
  operator|=(_Ios_Iostate& __a, _Ios_Iostate __b)
  { return __a = __a | __b; }

  inline _Ios_Iostate
  operator&=(_Ios_Iostate& __a, _Ios_Iostate __b)
  { return __a = __a & __b; }

  inline _Ios_Iostate
  operator^=(_Ios_Iostate& __a, _Ios_Iostate __b)
  { return __a = __a ^ __b; }

  inline _Ios_Iostate
  operator~(_Ios_Iostate __a)
  { return _Ios_Iostate(~static_cast<int>(__a)); }

  enum _Ios_Seekdir { _S_ios_seekdir_end = 1L << 16 };

  // 27.4.2  Class ios_base
  /**
   *  @brief  The very top of the I/O class hierarchy.
   *
   *  This class defines everything that can be defined about I/O that does
   *  not depend on the type of characters being input or output.  Most
   *  people will only see @c ios_base when they need to specify the full
   *  name of the various I/O flags (e.g., the openmodes).
  */
  class ios_base
  {
  public:

    // 27.4.2.1.1  Class ios_base::failure
    /// These are thrown to indicate problems.  Doc me.
    class failure : public exception
    {
    public:
      // _GLIBCXX_RESOLVE_LIB_DEFECTS
      // 48.  Use of non-existent exception constructor
      explicit
      failure(const string& __str) throw();

      // This declaration is not useless:
      // http://gcc.gnu.org/onlinedocs/gcc-3.0.2/gcc_6.html#SEC118
      virtual
      ~failure() throw();

      virtual const char*
      what() const throw();

    private:
      string _M_msg;
    };

    // 27.4.2.1.2  Type ios_base::fmtflags
    /**
     *  @brief This is a bitmask type.
     *
     *  @c "_Ios_Fmtflags" is implementation-defined, but it is valid to
     *  perform bitwise operations on these values and expect the Right
     *  Thing to happen.  Defined objects of type fmtflags are:
     *  - boolalpha
     *  - dec
     *  - fixed
     *  - hex
     *  - internal
     *  - left
     *  - oct
     *  - right
     *  - scientific
     *  - showbase
     *  - showpoint
     *  - showpos
     *  - skipws
     *  - unitbuf
     *  - uppercase
     *  - adjustfield
     *  - basefield
     *  - floatfield
    */
    typedef _Ios_Fmtflags fmtflags;

    /// Insert/extract @c bool in alphabetic rather than numeric format.
    static const fmtflags boolalpha =   fmtflags(__ios_flags::_S_boolalpha);

    /// Converts integer input or generates integer output in decimal base.
    static const fmtflags dec =         fmtflags(__ios_flags::_S_dec);

    /// Generate floating-point output in fixed-point notation.
    static const fmtflags fixed =       fmtflags(__ios_flags::_S_fixed);

    /// Converts integer input or generates integer output in hexadecimal base.
    static const fmtflags hex =         fmtflags(__ios_flags::_S_hex);

    /// Adds fill characters at a designated internal point in certain
    /// generated output, or identical to @c right if no such point is
    /// designated.
    static const fmtflags internal =    fmtflags(__ios_flags::_S_internal);

    /// Adds fill characters on the right (final positions) of certain
    /// generated output.  (I.e., the thing you print is flush left.)
    static const fmtflags left =        fmtflags(__ios_flags::_S_left);

    /// Converts integer input or generates integer output in octal base.
    static const fmtflags oct =         fmtflags(__ios_flags::_S_oct);

    /// Adds fill characters on the left (initial positions) of certain
    /// generated output.  (I.e., the thing you print is flush right.)
    static const fmtflags right =       fmtflags(__ios_flags::_S_right);

    /// Generates floating-point output in scientific notation.
    static const fmtflags scientific =  fmtflags(__ios_flags::_S_scientific);

    /// Generates a prefix indicating the numeric base of generated integer
    /// output.
    static const fmtflags showbase =    fmtflags(__ios_flags::_S_showbase);

    /// Generates a decimal-point character unconditionally in generated
    /// floating-point output.
    static const fmtflags showpoint =   fmtflags(__ios_flags::_S_showpoint);

    /// Generates a + sign in non-negative generated numeric output.
    static const fmtflags showpos =     fmtflags(__ios_flags::_S_showpos);

    /// Skips leading white space before certain input operations.
    static const fmtflags skipws =      fmtflags(__ios_flags::_S_skipws);

    /// Flushes output after each output operation.
    static const fmtflags unitbuf =     fmtflags(__ios_flags::_S_unitbuf);

    /// Replaces certain lowercase letters with their uppercase equivalents
    /// in generated output.
    static const fmtflags uppercase =   fmtflags(__ios_flags::_S_uppercase);

    /// A mask of left|right|internal.  Useful for the 2-arg form of @c setf.
    static const fmtflags adjustfield = fmtflags(__ios_flags::_S_adjustfield);

    /// A mask of dec|oct|hex.  Useful for the 2-arg form of @c setf.
    static const fmtflags basefield =   fmtflags(__ios_flags::_S_basefield);

    /// A mask of scientific|fixed.  Useful for the 2-arg form of @c setf.
    static const fmtflags floatfield =  fmtflags(__ios_flags::_S_floatfield);

    // 27.4.2.1.3  Type ios_base::iostate
    /**
     *  @brief This is a bitmask type.
     *
     *  @c "_Ios_Iostate" is implementation-defined, but it is valid to
     *  perform bitwise operations on these values and expect the Right
     *  Thing to happen.  Defined objects of type iostate are:
     *  - badbit
     *  - eofbit
     *  - failbit
     *  - goodbit
    */
    typedef _Ios_Iostate iostate;

    /// Indicates a loss of integrity in an input or output sequence (such
    /// as an irrecoverable read error from a file).
    static const iostate badbit =	iostate(__ios_flags::_S_badbit);

    /// Indicates that an input operation reached the end of an input sequence.
    static const iostate eofbit =	iostate(__ios_flags::_S_eofbit);

    /// Indicates that an input operation failed to read the expected
    /// characters, or that an output operation failed to generate the
    /// desired characters.
    static const iostate failbit =	iostate(__ios_flags::_S_failbit);

    /// Indicates all is well.
    static const iostate goodbit =	iostate(0);

    // 27.4.2.1.4  Type ios_base::openmode
    /**
     *  @brief This is a bitmask type.
     *
     *  @c "_Ios_Openmode" is implementation-defined, but it is valid to
     *  perform bitwise operations on these values and expect the Right
     *  Thing to happen.  Defined objects of type openmode are:
     *  - app
     *  - ate
     *  - binary
     *  - in
     *  - out
     *  - trunc
    */
    typedef _Ios_Openmode openmode;

    /// Seek to end before each write.
    static const openmode app =		openmode(__ios_flags::_S_app);

    /// Open and seek to end immediately after opening.
    static const openmode ate =		openmode(__ios_flags::_S_ate);

    /// Perform input and output in binary mode (as opposed to text mode).
    /// This is probably not what you think it is; see
    /// http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#3 and
    /// http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#7 for more.
    static const openmode binary =	openmode(__ios_flags::_S_bin);

    /// Open for input.  Default for @c ifstream and fstream.
    static const openmode in =		openmode(__ios_flags::_S_in);

    /// Open for output.  Default for @c ofstream and fstream.
    static const openmode out =		openmode(__ios_flags::_S_out);

    /// Open for input.  Default for @c ofstream.
    static const openmode trunc =	openmode(__ios_flags::_S_trunc);

    // 27.4.2.1.5  Type ios_base::seekdir
    /**
     *  @brief This is an enumerated type.
     *
     *  @c "_Ios_Seekdir" is implementation-defined.  Defined values
     *  of type seekdir are:
     *  - beg
     *  - cur, equivalent to @c SEEK_CUR in the C standard library.
     *  - end, equivalent to @c SEEK_END in the C standard library.
    */
    typedef _Ios_Seekdir seekdir;

    /// Request a seek relative to the beginning of the stream.
    static const seekdir beg =		seekdir(0);

    /// Request a seek relative to the current position within the sequence.
    static const seekdir cur =		seekdir(SEEK_CUR);

    /// Request a seek relative to the current end of the sequence.
    static const seekdir end =		seekdir(SEEK_END);

#ifdef _GLIBCXX_DEPRECATED
    // Annex D.6
    typedef int io_state;
    typedef int open_mode;
    typedef int seek_dir;

    typedef std::streampos streampos;
    typedef std::streamoff streamoff;
#endif

    // Callbacks;
    /**
     *  @brief  The set of events that may be passed to an event callback.
     *
     *  erase_event is used during ~ios() and copyfmt().  imbue_event is used
     *  during imbue().  copyfmt_event is used during copyfmt().
    */
    enum event
    {
      erase_event,
      imbue_event,
      copyfmt_event
    };

    /**
     *  @brief  The type of an event callback function.
     *  @param  event  One of the members of the event enum.
     *  @param  ios_base  Reference to the ios_base object.
     *  @param  int  The integer provided when the callback was registered.
     *
     *  Event callbacks are user defined functions that get called during
     *  several ios_base and basic_ios functions, specifically imbue(),
     *  copyfmt(), and ~ios().
    */
    typedef void (*event_callback) (event, ios_base&, int);

    /**
     *  @brief  Add the callback __fn with parameter __index.
     *  @param  __fn  The function to add.
     *  @param  __index  The integer to pass to the function when invoked.
     *
     *  Registers a function as an event callback with an integer parameter to
     *  be passed to the function when invoked.  Multiple copies of the
     *  function are allowed.  If there are multiple callbacks, they are
     *  invoked in the order they were registered.
    */
    void
    register_callback(event_callback __fn, int __index);

  protected:
    //@{
    /**
     *  @if maint
     *  ios_base data members (doc me)
     *  @endif
    */
    streamsize		_M_precision;
    streamsize		_M_width;
    fmtflags		_M_flags;
    iostate		_M_exception;
    iostate		_M_streambuf_state;
    //@}

    // 27.4.2.6  Members for callbacks
    // 27.4.2.6  ios_base callbacks
    struct _Callback_list
    {
      // Data Members
      _Callback_list*		_M_next;
      ios_base::event_callback	_M_fn;
      int			_M_index;
      _Atomic_word		_M_refcount;  // 0 means one reference.

      _Callback_list(ios_base::event_callback __fn, int __index,
		     _Callback_list* __cb)
      : _M_next(__cb), _M_fn(__fn), _M_index(__index), _M_refcount(0) { }

      void
      _M_add_reference() { __gnu_cxx::__atomic_add(&_M_refcount, 1); }

      // 0 => OK to delete.
      int
      _M_remove_reference()
      { return __gnu_cxx::__exchange_and_add(&_M_refcount, -1); }
    };

     _Callback_list*	_M_callbacks;

    void
    _M_call_callbacks(event __ev) throw();

    void
    _M_dispose_callbacks(void);

    // 27.4.2.5  Members for iword/pword storage
    struct _Words
    {
      void*	_M_pword;
      long	_M_iword;
      _Words() : _M_pword(0), _M_iword(0) { }
    };

    // Only for failed iword/pword calls.
    _Words		_M_word_zero;

    // Guaranteed storage.
    // The first 5 iword and pword slots are reserved for internal use.
    static const int	_S_local_word_size = 8;
    _Words		_M_local_word[_S_local_word_size];

    // Allocated storage.
    int			_M_word_size;
    _Words*		_M_word;

    _Words&
    _M_grow_words(int __index, bool __iword);

    // Members for locale and locale caching.
    locale		_M_ios_locale;

    void
    _M_init();

  public:

    // 27.4.2.1.6  Class ios_base::Init
    // Used to initialize standard streams. In theory, g++ could use
    // -finit-priority to order this stuff correctly without going
    // through these machinations.
    class Init
    {
      friend class ios_base;
    public:
      Init();
      ~Init();

    private:
      static _Atomic_word	_S_refcount;
      static bool		_S_synced_with_stdio;
    };

    // [27.4.2.2] fmtflags state functions
    /**
     *  @brief  Access to format flags.
     *  @return  The format control flags for both input and output.
    */
    inline fmtflags
    flags() const { return _M_flags; }

    /**
     *  @brief  Setting new format flags all at once.
     *  @param  fmtfl  The new flags to set.
     *  @return  The previous format control flags.
     *
     *  This function overwrites all the format flags with @a fmtfl.
    */
    inline fmtflags
    flags(fmtflags __fmtfl)
    {
      fmtflags __old = _M_flags;
      _M_flags = __fmtfl;
      return __old;
    }

    /**
     *  @brief  Setting new format flags.
     *  @param  fmtfl  Additional flags to set.
     *  @return  The previous format control flags.
     *
     *  This function sets additional flags in format control.  Flags that
     *  were previously set remain set.
    */
    inline fmtflags
    setf(fmtflags __fmtfl)
    {
      fmtflags __old = _M_flags;
      _M_flags |= __fmtfl;
      return __old;
    }

    /**
     *  @brief  Setting new format flags.
     *  @param  fmtfl  Additional flags to set.
     *  @param  mask  The flags mask for @a fmtfl.
     *  @return  The previous format control flags.
     *
     *  This function clears @a mask in the format flags, then sets
     *  @a fmtfl @c & @a mask.  An example mask is @c ios_base::adjustfield.
    */
    inline fmtflags
    setf(fmtflags __fmtfl, fmtflags __mask)
    {
      fmtflags __old = _M_flags;
      _M_flags &= ~__mask;
      _M_flags |= (__fmtfl & __mask);
      return __old;
    }

    /**
     *  @brief  Clearing format flags.
     *  @param  mask  The flags to unset.
     *
     *  This function clears @a mask in the format flags.
    */
    inline void
    unsetf(fmtflags __mask) { _M_flags &= ~__mask; }

    /**
     *  @brief  Flags access.
     *  @return  The precision to generate on certain output operations.
     *
     *  @if maint
     *  Be careful if you try to give a definition of "precision" here; see
     *  DR 189.
     *  @endif
    */
    inline streamsize
    precision() const { return _M_precision; }

    /**
     *  @brief  Changing flags.
     *  @param  prec  The new precision value.
     *  @return  The previous value of precision().
    */
    inline streamsize
    precision(streamsize __prec)
    {
      streamsize __old = _M_precision;
      _M_precision = __prec;
      return __old;
    }

    /**
     *  @brief  Flags access.
     *  @return  The minimum field width to generate on output operations.
     *
     *  "Minimum field width" refers to the number of characters.
    */
    inline streamsize
    width() const { return _M_width; }

    /**
     *  @brief  Changing flags.
     *  @param  wide  The new width value.
     *  @return  The previous value of width().
    */
    inline streamsize
    width(streamsize __wide)
    {
      streamsize __old = _M_width;
      _M_width = __wide;
      return __old;
    }

    // [27.4.2.4] ios_base static members
    /**
     *  @brief  Interaction with the standard C I/O objects.
     *  @param  sync  Whether to synchronize or not.
     *  @return  True if the standard streams were previously synchronized.
     *
     *  The synchronization referred to is @e only that between the standard
     *  C facilities (e.g., stdout) and the standard C++ objects (e.g.,
     *  cout).  User-declared streams are unaffected.  See
     *  http://gcc.gnu.org/onlinedocs/libstdc++/27_io/howto.html#8 for more.
    */
    static bool
    sync_with_stdio(bool __sync = true);

    // [27.4.2.3] ios_base locale functions
    /**
     *  @brief  Setting a new locale.
     *  @param  loc  The new locale.
     *  @return  The previous locale.
     *
     *  Sets the new locale for this stream, and then invokes each callback
     *  with imbue_event.
    */
    locale
    imbue(const locale& __loc);

    /**
     *  @brief  Locale access
     *  @return  A copy of the current locale.
     *
     *  If @c imbue(loc) has previously been called, then this function
     *  returns @c loc.  Otherwise, it returns a copy of @c std::locale(),
     *  the global C++ locale.
    */
    inline locale
    getloc() const { return _M_ios_locale; }

    /**
     *  @brief  Locale access
     *  @return  A reference to the current locale.
     *
     *  Like getloc above, but returns a reference instead of
     *  generating a copy.
    */
    inline const locale&
    _M_getloc() const { return _M_ios_locale; }

    // [27.4.2.5] ios_base storage functions
    /**
     *  @brief  Access to unique indices.
     *  @return  An integer different from all previous calls.
     *
     *  This function returns a unique integer every time it is called.  It
     *  can be used for any purpose, but is primarily intended to be a unique
     *  index for the iword and pword functions.  The expectation is that an
     *  application calls xalloc in order to obtain an index in the iword and
     *  pword arrays that can be used without fear of conflict.
     *
     *  The implementation maintains a static variable that is incremented and
     *  returned on each invocation.  xalloc is guaranteed to return an index
     *  that is safe to use in the iword and pword arrays.
    */
    static int
    xalloc() throw();

    /**
     *  @brief  Access to integer array.
     *  @param  __ix  Index into the array.
     *  @return  A reference to an integer associated with the index.
     *
     *  The iword function provides access to an array of integers that can be
     *  used for any purpose.  The array grows as required to hold the
     *  supplied index.  All integers in the array are initialized to 0.
     *
     *  The implementation reserves several indices.  You should use xalloc to
     *  obtain an index that is safe to use.  Also note that since the array
     *  can grow dynamically, it is not safe to hold onto the reference.
    */
    inline long&
    iword(int __ix)
    {
      _Words& __word = (__ix < _M_word_size)
			? _M_word[__ix] : _M_grow_words(__ix, true);
      return __word._M_iword;
    }

    /**
     *  @brief  Access to void pointer array.
     *  @param  __ix  Index into the array.
     *  @return  A reference to a void* associated with the index.
     *
     *  The pword function provides access to an array of pointers that can be
     *  used for any purpose.  The array grows as required to hold the
     *  supplied index.  All pointers in the array are initialized to 0.
     *
     *  The implementation reserves several indices.  You should use xalloc to
     *  obtain an index that is safe to use.  Also note that since the array
     *  can grow dynamically, it is not safe to hold onto the reference.
    */
    inline void*&
    pword(int __ix)
    {
      _Words& __word = (__ix < _M_word_size)
			? _M_word[__ix] : _M_grow_words(__ix, false);
      return __word._M_pword;
    }

    // Destructor
    /**
     *  Invokes each callback with erase_event.  Destroys local storage.
     *
     *  Note that the ios_base object for the standard streams never gets
     *  destroyed.  As a result, any callbacks registered with the standard
     *  streams will not get invoked with erase_event (unless copyfmt is
     *  used).
    */
    virtual ~ios_base();

  protected:
    ios_base();

  // _GLIBCXX_RESOLVE_LIB_DEFECTS
  // 50.  Copy constructor and assignment operator of ios_base
  private:
    ios_base(const ios_base&);

    ios_base&
    operator=(const ios_base&);
  };

  // [27.4.5.1] fmtflags manipulators
  /// Calls base.setf(ios_base::boolalpha).
  inline ios_base&
  boolalpha(ios_base& __base)
  {
    __base.setf(ios_base::boolalpha);
    return __base;
  }

  /// Calls base.unsetf(ios_base::boolalpha).
  inline ios_base&
  noboolalpha(ios_base& __base)
  {
    __base.unsetf(ios_base::boolalpha);
    return __base;
  }

  /// Calls base.setf(ios_base::showbase).
  inline ios_base&
  showbase(ios_base& __base)
  {
    __base.setf(ios_base::showbase);
    return __base;
  }

  /// Calls base.unsetf(ios_base::showbase).
  inline ios_base&
  noshowbase(ios_base& __base)
  {
    __base.unsetf(ios_base::showbase);
    return __base;
  }

  /// Calls base.setf(ios_base::showpoint).
  inline ios_base&
  showpoint(ios_base& __base)
  {
    __base.setf(ios_base::showpoint);
    return __base;
  }

  /// Calls base.unsetf(ios_base::showpoint).
  inline ios_base&
  noshowpoint(ios_base& __base)
  {
    __base.unsetf(ios_base::showpoint);
    return __base;
  }

  /// Calls base.setf(ios_base::showpos).
  inline ios_base&
  showpos(ios_base& __base)
  {
    __base.setf(ios_base::showpos);
    return __base;
  }

  /// Calls base.unsetf(ios_base::showpos).
  inline ios_base&
  noshowpos(ios_base& __base)
  {
    __base.unsetf(ios_base::showpos);
    return __base;
  }

  /// Calls base.setf(ios_base::skipws).
  inline ios_base&
  skipws(ios_base& __base)
  {
    __base.setf(ios_base::skipws);
    return __base;
  }

  /// Calls base.unsetf(ios_base::skipws).
  inline ios_base&
  noskipws(ios_base& __base)
  {
    __base.unsetf(ios_base::skipws);
    return __base;
  }

  /// Calls base.setf(ios_base::uppercase).
  inline ios_base&
  uppercase(ios_base& __base)
  {
    __base.setf(ios_base::uppercase);
    return __base;
  }

  /// Calls base.unsetf(ios_base::uppercase).
  inline ios_base&
  nouppercase(ios_base& __base)
  {
    __base.unsetf(ios_base::uppercase);
    return __base;
  }

  /// Calls base.setf(ios_base::unitbuf).
  inline ios_base&
  unitbuf(ios_base& __base)
  {
     __base.setf(ios_base::unitbuf);
     return __base;
  }

  /// Calls base.unsetf(ios_base::unitbuf).
  inline ios_base&
  nounitbuf(ios_base& __base)
  {
     __base.unsetf(ios_base::unitbuf);
     return __base;
  }

  // [27.4.5.2] adjustfield anipulators
  /// Calls base.setf(ios_base::internal, ios_base::adjustfield).
  inline ios_base&
  internal(ios_base& __base)
  {
     __base.setf(ios_base::internal, ios_base::adjustfield);
     return __base;
  }

  /// Calls base.setf(ios_base::left, ios_base::adjustfield).
  inline ios_base&
  left(ios_base& __base)
  {
    __base.setf(ios_base::left, ios_base::adjustfield);
    return __base;
  }

  /// Calls base.setf(ios_base::right, ios_base::adjustfield).
  inline ios_base&
  right(ios_base& __base)
  {
    __base.setf(ios_base::right, ios_base::adjustfield);
    return __base;
  }

  // [27.4.5.3] basefield anipulators
  /// Calls base.setf(ios_base::dec, ios_base::basefield).
  inline ios_base&
  dec(ios_base& __base)
  {
    __base.setf(ios_base::dec, ios_base::basefield);
    return __base;
  }

  /// Calls base.setf(ios_base::hex, ios_base::basefield).
  inline ios_base&
  hex(ios_base& __base)
  {
    __base.setf(ios_base::hex, ios_base::basefield);
    return __base;
  }

  /// Calls base.setf(ios_base::oct, ios_base::basefield).
  inline ios_base&
  oct(ios_base& __base)
  {
    __base.setf(ios_base::oct, ios_base::basefield);
    return __base;
  }

  // [27.4.5.4] floatfield anipulators
  /// Calls base.setf(ios_base::fixed, ios_base::floatfield).
  inline ios_base&
  fixed(ios_base& __base)
  {
    __base.setf(ios_base::fixed, ios_base::floatfield);
    return __base;
  }

  /// Calls base.setf(ios_base::scientific, ios_base::floatfield).
  inline ios_base&
  scientific(ios_base& __base)
  {
    __base.setf(ios_base::scientific, ios_base::floatfield);
    return __base;
  }
} // namespace std

#endif /* _IOS_BASE_H */


text:
import { expect } from 'chai';
import { DuplicateAliasError } from '../../errors/duplicate-alias.error';
import { DuplicateNameError } from '../../errors/duplicate-name.error';
import { OrbitalFactory } from '../../orbital-factory';
import { MultipleAliases } from '../shared/cli/cli-with-multiple-aliases';
import { MultipleNames } from '../shared/cli/cli-with-multiple-names';

describe('Command Executor', () => {
    it('should throw if there are multiple commands with same alias', () => {
        const execution = () => {
            OrbitalFactory
                .bootstrap(MultipleAliases)
                .execute(['good-cli', 'alpha']);
        };
        expect(execution)
            .to.throw(DuplicateAliasError);
    });

    it('should throw if there are multiple commands with same name', () => {
        const execution = () => {
            OrbitalFactory
                .bootstrap(MultipleNames)
                .execute(['good-cli', 'alpha']);
        };
        expect(execution)
            .to.throw(DuplicateNameError);
    });
});