text:
namespace Edison.Framework
{
    public enum HtmlIdentifierType
    {
        ID,
        Name,
        Tag,
        Class
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniRx;
using UniRx.Triggers;

public class BattleHP : MonoBehaviour {

	Player player;
	RectTransform rt;
	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void OnEnable()
	{
		rt = GetComponent<RectTransform> ();
		Invoke ("SubscribeHPStream", 1f);
	}
	void SubscribeHPStream()
	{
		Debug.Log ("SubscribeHPStream");

		foreach(GameObject go in Object.FindObjectsOfType(typeof(GameObject)))
		{
			Player pl = go.GetComponent<Player> ();
			if (pl == null)
				continue;

			//player = transform.parent.parent.GetComponent<Player> ();
			pl.hp.CurrentHP.Subscribe (
				f => {
					Debug.Log ("CurrentHP:" + f.ToString ());
					float p = f / pl.hp.MaxHP;
					rt.localScale = new Vector3 (p, 1, 1);
				}
			).AddTo(this);
			break;
		}

	}
	void Update () {

	}
}


text:
package org.drools.core.command;

import org.drools.core.command.impl.ContextImpl;
import org.drools.core.runtime.impl.ExecutionResultImpl;
import org.kie.api.KieBase;
import org.kie.api.runtime.Context;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.RequestContext;
import org.kie.internal.command.ContextManager;

import java.util.Collections;;
import java.util.HashMap;
import java.util.Map;

public class RequestContextImpl extends ContextImpl implements RequestContext {

    private Context appContext;
    private Context conversationContext;

    private ConversationContextManager cvnManager;

    private Map<String, Object> output = new HashMap<>();

    private Object result;

    private String lastSet;

    private Exception exception;

    public RequestContextImpl() {
        register( ExecutionResultImpl.class, new ExecutionResultImpl() );
    }

    public RequestContextImpl(long requestId, ContextManager ctxManager, ConversationContextManager cvnManager) {
        super(Long.toString(requestId), ctxManager);
        this.cvnManager = cvnManager;
        register( ExecutionResultImpl.class, new ExecutionResultImpl() );
    }

    public Context getApplicationContext() {
        return appContext;
    }

    public void setApplicationContext(Context appContext) {
        this.appContext = (ContextImpl)appContext;
    }

    public Context getConversationContext() {
        return conversationContext;
    }

    public void setConversationContext(Context conversationContext ) {
        this.conversationContext = conversationContext;
    }

    public ConversationContextManager getConversationManager() {
        return cvnManager;
    }

    @Override
    public Object get(String identifier) {
        if(identifier == null || identifier.equals("")){
            return null;
        }

        Object object = null;

        if ( has(identifier)) {
            object = super.get( identifier );
        } else if (conversationContext != null && conversationContext.has(identifier)) {
            object = conversationContext.get( identifier );
        } else if (appContext != null && appContext.has(identifier)) {
            object = appContext.get( identifier );
        }

        return object;
    }

    @Override
    public Object getResult() {
        return result;
    }

    @Override
    public void setResult( Object result ) {
        this.result = result;
    }

    @Override
    public RequestContext with( KieBase kieBase ) {
        register( KieBase.class, kieBase );
        return this;
    }

    @Override
    public RequestContext with( KieSession kieSession ) {
        register( KieSession.class, kieSession );
        return this;
    }

    public String getLastSet() {
        return lastSet;
    }

    public void setLastSetOrGet(String lastSet) {
        this.lastSet = lastSet;
    }

    @Override
    public Map<String, Object> getOutputs() {
        return Collections.unmodifiableMap(output);
    }

    @Override
    public void setOutput(String identifier, Object value) {
        output.put(identifier, value);
    }

    @Override
    public void removeOutput(String identifier) {
        output.remove(identifier);
    }

    public Exception getException() {
        return exception;
    }

    public void setException(Exception exception) {
        this.exception = exception;
    }

    @Override
    public String toString() {
        return "ContextImpl{" +
               "name='" + getName() + '\'' +
               '}';
    }
}


text:
package com.google.cloud.dialogflow.v2beta1.samples;

// [START dialogflow_v2beta1_generated_knowledgebasessettings_getknowledgebase_sync]
import com.google.cloud.dialogflow.v2beta1.KnowledgeBasesSettings;
import java.time.Duration;

public class SyncGetKnowledgeBase {

  public static void main(String[] args) throws Exception {
    syncGetKnowledgeBase();
  }

  public static void syncGetKnowledgeBase() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    KnowledgeBasesSettings.Builder knowledgeBasesSettingsBuilder =
        KnowledgeBasesSettings.newBuilder();
    knowledgeBasesSettingsBuilder
        .getKnowledgeBaseSettings()
        .setRetrySettings(
            knowledgeBasesSettingsBuilder.getKnowledgeBaseSettings().getRetrySettings().toBuilder()
                .setTotalTimeout(Duration.ofSeconds(30))
                .build());
    KnowledgeBasesSettings knowledgeBasesSettings = knowledgeBasesSettingsBuilder.build();
  }
}
// [END dialogflow_v2beta1_generated_knowledgebasessettings_getknowledgebase_sync]


text:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

import glob
import platform

sourcefiles = ['src/python/termboxmodule.pyx'] + glob.glob('src/*.c')

with open('src/python/termboxconfig.pyx', 'w') as f:
    f.write("DEF PY_MAJOR_VERSION = %s\n" % platform.python_version()[0])

setup(
    name = 'termbox',
    version = '1.0.1a1',
    description = 'A simple and clean ncurses alternative',
    author = 'nsf',
    author_email = 'no.smile.face@gmail.com',
    url = 'http://code.google.com/p/termbox/',
    license = 'MIT',
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension('termbox', sourcefiles)],
)


text:
#include "systems/LuaScriptSystem.h"
#include "components/ScriptComponent.h"
#include "Entity.h"
#include "Logger.h"
#include "Engine.h"
#include "lua/LuaInterface.h"
#include "lua.hpp"
#include "FileLoader.h"

namespace Gsage {

  const std::string LuaScriptSystem::ID = "lua";

  LuaScriptSystem::LuaScriptSystem()
    : mState(0)
    , mWorkdir(".")
  {
    mSystemInfo.put("type", LuaScriptSystem::ID);
  }

  LuaScriptSystem::~LuaScriptSystem()
  {
  }

  bool LuaScriptSystem::initialize(const DataProxy& settings) {
    mWorkdir = mEngine->env().get("workdir", ".");
    EngineSystem::initialize(settings);
    return true;
  }

  void LuaScriptSystem::configUpdated() {
    EngineSystem::configUpdated();
    std::pair<DataProxy, bool> hooks = mConfig.get<DataProxy>("hooks");
    if(hooks.second) {
      for(auto& pair : hooks.first) {
        std::string hook = pair.second.getValueOptional<std::string>("");
        if(hook.empty()) {
          LOG(WARNING) << "Got empty hook " << pair.first;
          continue;
        }

        if(!runScript(hook))
        {
          LOG(ERROR) << "Startup hook run failed";
        }
      }
    }
  }

  bool LuaScriptSystem::fillComponentData(ScriptComponent* component, const DataProxy& data)
  {
    bool createdComponent = ComponentStorage<ScriptComponent>::fillComponentData(component, data);
    if(!createdComponent)
      return false;

    if(component->getBehavior().empty())
    {
      sol::table t = mState->create_table();
      component->setData(t);
      return true;
    }

    return true;
  }

  bool LuaScriptSystem::setLuaState(lua_State* L)
  {
    if(mState && mState->lua_state() == L)
      return true;

    mState = new sol::state_view(L);
    return true;
  }

  void LuaScriptSystem::update(const double& time)
  {
    if(!mState)
      return;

    for(Listener& listener : mUpdateListeners)
    {
      auto res = listener.function(time);
      if(!res.valid()) {
        sol::error err = res;
        removeUpdateListener(listener.function);
        LOG(ERROR) << "Failed to call update listener: " << err.what() << "\n\t" << lua_tostring(mState->lua_state(), -1) << ", force unsubscribe";
      }
    }

    ComponentStorage<ScriptComponent>::update(time);
  }

  void LuaScriptSystem::updateComponent(ScriptComponent* component, Entity* entity, const double& time)
  {
    if(!component->getSetupExecuted())
    {
      runFunction(component, component->getSetupFunction());
      LOG(INFO) << entity->getId() << " executing script";
      runScript(component, component->getSetupScript());
      component->setSetupExecuted(true);
    }

    if(!component->getBehavior().empty() && component->getBtree() == sol::lua_nil) {
      sol::function initializeBtree = (*mState)["btree"]["initialize"].get<sol::function>();
      sol::table btree = initializeBtree(component->getOwner()->getId(), component->getBehavior());
      component->setBtree(btree);
      sol::table context = btree["context"];

      component->setData(context);

      LOG(INFO) << "Successfuly registered script component for entity " << component->getOwner()->getId();
    }

    if(component->hasBehavior())
    {
      sol::table& btree = component->getBtree();
      btree["update"](btree, time);
    }
  }

  bool LuaScriptSystem::removeComponent(ScriptComponent* component)
  {
    const std::string id = component->getOwner()->getId();
    bool stopped = true;
    if(mState && component->hasBehavior())
    {
      sol::function stopBtree = (*mState)["btree"]["deinitialize"].get<sol::function>();
      auto res = stopBtree(id);
      if(!res.valid()) {
        sol::error err = res;
        LOG(ERROR) << "Failed to stop btree " << err.what();
      }

      if(!runScript(component, component->getTearDownScript()))
      {
        LOG(ERROR) << "Failed to tear down script component (tear down script)";
        stopped = false;
      }
    }

    bool res = ComponentStorage<ScriptComponent>::removeComponent(component);
    return res && stopped;
  }

  bool LuaScriptSystem::runFunction(ScriptComponent* component, sol::function func)
  {
    if(func.valid()) {
      std::string id = component->getOwner()->getId();
      LOG(INFO) << id << " executing function";
      try {
        auto res = func(component->getOwner());
        return res.valid();
      } catch(sol::error e) {
        LOG(ERROR) << "Failed to run function " << e.what();
        return false;
      }
    }
    return true;
  }

  bool LuaScriptSystem::runScript(ScriptComponent* component, const std::string& script)
  {
    try {
      auto res = mState->script(getScriptData(script).c_str());
      if(!res.valid())
      {
        sol::error err = res;
        LOG(ERROR) << "Failed to execute lua script " << err.what();
        return false;
      }

      sol::object r = res.get<sol::object>();
      if(r.get_type() != sol::type::function) {
        return true;
      }

      // If script returns a function, it means that it wants to have a sandbox

      sol::function callback = r;
      auto callResult = callback(component->getOwner());
      if(!callResult.valid()) {
        sol::error err = callResult;
        LOG(ERROR) << "Failed to execute lua script " << err.what();
        return false;
      }
    } catch(sol::error e) {
      LOG(ERROR) << "Failed to execute lua script " << e.what();
      return false;
    } catch(...) {
      LOG(ERROR) << "Failed to execute lua script: unknown error";
      return false;
    }

    return true;
  }

  std::string LuaScriptSystem::getScriptData(const std::string& data)
  {
    std::vector<std::string> parts = split(data, ':');
    std::string scriptData;
    if (parts.size() == 2 && parts[0] == "@File")
    {
      if(!FileLoader::getSingletonPtr()->load(parts[1], scriptData)) {
        LOG(ERROR) << "Failed to read script file: " << parts[1];
        return "";
      }
    } else {
      scriptData = data;
    }
    return scriptData;
  }

  bool LuaScriptSystem::runScript(const std::string& script)
  {
    if(script == "") {
      return true;
    }

    try {
      auto res = mState->script(getScriptData(script).c_str());
      if(!res.valid()) {
        return false;
      }
    } catch(sol::error e) {
      LOG(ERROR) << "Failed to execute lua script " << e.what();
      return false;
    }

    return true;
  }

  bool LuaScriptSystem::addUpdateListener(const sol::object& function, bool global)
  {
    if(std::find_if(mUpdateListeners.begin(), mUpdateListeners.end(), [function] (Listener l) { return l.function == function; } ) != mUpdateListeners.end())
      return true;

    if(function.get_type() == sol::type::function) {
      mUpdateListeners.emplace_back(function.as<sol::function>(), global);
    } else {
      LOG(WARNING) << "Tried to add update listener object of unsupported type";
      return false;
    }

    return true;
  }

  bool LuaScriptSystem::removeUpdateListener(const sol::object& object)
  {
    sol::function function = object.as<sol::function>();

    UpdateListeners::iterator element = std::find_if(mUpdateListeners.begin(), mUpdateListeners.end(), [function] (Listener l) { return l.function == function; } );
    if(element == mUpdateListeners.end())
      return false;

    mUpdateListeners.erase(element);
    return true;
  }

  void LuaScriptSystem::unloadComponents()
  {
    setEnabled(false);
    for (auto i = mUpdateListeners.begin(); i != mUpdateListeners.end();) {
      if(i->global) {
        ++i;
        continue;
      }

      i = mUpdateListeners.erase(i);
    }
    ComponentStorage<ScriptComponent>::unloadComponents();
    setEnabled(true);
  }
}


text:
package collections

// Defines the elements in the collection are comparable.
// To be implemented by all sortable collections.
type Comparable interface {
	// GetComparator returns the comparator associated with the collection
	GetComparator() *Comparator
}


text:
SCRIPT_DIR=$(cd $(dirname ${BASH_SOURCE[0]:-$0}); pwd)
BASE_DIR=$(cd "$SCRIPT_DIR/../../.."; pwd)
WORK_DIR="target/sphinx-tmp"
pushd "$BASE_DIR" > /dev/null
rm -rf $WORK_DIR
mkdir -p $WORK_DIR
cd $WORK_DIR
curl -LO "http://downloads.sourceforge.net/project/jython/jython/2.5.2/jython_installer-2.5.2.jar"
curl -O "http://peak.telecommunity.com/dist/ez_setup.py"
java -jar jython_installer-2.5.2.jar -s -d jython -t standard
./jython/bin/jython ez_setup.py
./jython/bin/easy_install docutils pygments jinja2 sphinx rst2pdf

# reportlab's default setup doesn work under Jython, so let's install it manually
# we'll also patch it along the way
curl -O http://pypi.python.org/packages/source/r/reportlab/reportlab-2.5.tar.gz
tar zxf reportlab-2.5.tar.gz
patch -d reportlab*/src/reportlab -p6 < "$BASE_DIR/src/main/build/reportlab.patch"
pushd reportlab* > /dev/null
rm -rf src/rl_addons
../jython/bin/jython setup.py install
popd > /dev/null

# we also need to patch rst2pdf
patch -d jython/Lib/site-packages/rst2pdf* -p6 < "$BASE_DIR/src/main/build/rst2pdf.patch"
rm jython/Lib/site-packages/rst2pdf*/rst2pdf/pdfbuilder\$py.class
./jython/bin/jython -mcompileall jython/Lib/site-packages/rst2pdf*/rst2pdf/
popd > /dev/null


text:
import os, sys, re, json, base64
from boto.ec2.connection import EC2Connection
from subprocess import call
from fabric import api
from fabric.api import cd, run, put, sudo
from os import environ as env
from time import sleep

# Remove SSH private key as it needs more processing
CONFIG = json.loads(re.sub(r'("DOCKER_CI_KEY".+?"(.+?)",)','',
    env['CONFIG_JSON'], flags=re.DOTALL))

# Populate environment variables
for key in CONFIG:
    env[key] = CONFIG[key]

# Load SSH private key
env['DOCKER_CI_KEY'] = re.sub('^.+"DOCKER_CI_KEY".+?"(.+?)".+','\\1',
    env['CONFIG_JSON'],flags=re.DOTALL)

AWS_TAG = env.get('AWS_TAG','docker-ci')
AWS_KEY_NAME = 'dotcloud-dev'       # Same as CONFIG_JSON['DOCKER_CI_PUB']
AWS_AMI = 'ami-d582d6bc'            # Ubuntu 13.04
AWS_REGION = 'us-east-1'
AWS_TYPE = 'm1.small'
AWS_SEC_GROUPS = 'gateway'
AWS_IMAGE_USER = 'ubuntu'
DOCKER_PATH = '/go/src/github.com/dotcloud/docker'
DOCKER_CI_PATH = '/docker-ci'
CFG_PATH = '{}/buildbot'.format(DOCKER_CI_PATH)

class AWS_EC2:
    '''Amazon EC2'''
    def __init__(self, access_key, secret_key):
        '''Set default API parameters'''
        self.handler = EC2Connection(access_key, secret_key)
    def create_instance(self, tag, instance_type):
        reservation = self.handler.run_instances(**instance_type)
        instance = reservation.instances[0]
        sleep(10)
        while instance.state != 'running':
            sleep(5)
            instance.update()
            print "Instance state: %s" % (instance.state)
        instance.add_tag("Name",tag)
        print "instance %s done!" % (instance.id)
        return instance.ip_address
    def get_instances(self):
        return self.handler.get_all_instances()
    def get_tags(self):
        return dict([(i.instances[0].id, i.instances[0].tags['Name'])
            for i in self.handler.get_all_instances() if i.instances[0].tags])
    def del_instance(self, instance_id):
        self.handler.terminate_instances(instance_ids=[instance_id])

def json_fmt(data):
    '''Format json output'''
    return json.dumps(data, sort_keys = True, indent = 2)

# Create EC2 API handler
ec2 = AWS_EC2(env['AWS_ACCESS_KEY'], env['AWS_SECRET_KEY'])

# Stop processing if AWS_TAG exists on EC2
if AWS_TAG in ec2.get_tags().values():
    print ('Instance: {} already deployed. Not further processing.'
        .format(AWS_TAG))
    exit(1)

ip = ec2.create_instance(AWS_TAG, {'image_id':AWS_AMI, 'instance_type':AWS_TYPE,
    'security_groups':[AWS_SEC_GROUPS], 'key_name':AWS_KEY_NAME})

# Wait 30 seconds for the machine to boot
sleep(30)

# Create docker-ci ssh private key so docker-ci docker container can communicate
# with its EC2 instance
os.makedirs('/root/.ssh')
open('/root/.ssh/id_rsa','w').write(env['DOCKER_CI_KEY'])
os.chmod('/root/.ssh/id_rsa',0600)
open('/root/.ssh/config','w').write('StrictHostKeyChecking no\n')

api.env.host_string = ip
api.env.user = AWS_IMAGE_USER
api.env.key_filename = '/root/.ssh/id_rsa'

# Correct timezone
sudo('echo "America/Los_Angeles" >/etc/timezone')
sudo('dpkg-reconfigure --frontend noninteractive tzdata')

# Load public docker-ci key
sudo("echo '{}' >> /root/.ssh/authorized_keys".format(env['DOCKER_CI_PUB']))

# Create docker nightly release credentials file
credentials = {
    'AWS_ACCESS_KEY': env['PKG_ACCESS_KEY'],
    'AWS_SECRET_KEY': env['PKG_SECRET_KEY'],
    'GPG_PASSPHRASE': env['PKG_GPG_PASSPHRASE'],
    'INDEX_AUTH': env['INDEX_AUTH']}
open(DOCKER_CI_PATH + '/nightlyrelease/release_credentials.json', 'w').write(
    base64.b64encode(json.dumps(credentials)))

# Transfer docker
sudo('mkdir -p ' + DOCKER_CI_PATH)
sudo('chown {}.{} {}'.format(AWS_IMAGE_USER, AWS_IMAGE_USER, DOCKER_CI_PATH))
call('/usr/bin/rsync -aH {} {}@{}:{}'.format(DOCKER_CI_PATH, AWS_IMAGE_USER, ip,
    os.path.dirname(DOCKER_CI_PATH)), shell=True)

# Install Docker and Buildbot dependencies
sudo('addgroup docker')
sudo('usermod -a -G docker ubuntu')
sudo('mkdir /mnt/docker; ln -s /mnt/docker /var/lib/docker')
sudo('wget -q -O - https://get.docker.io/gpg | apt-key add -')
sudo('echo deb https://get.docker.io/ubuntu docker main >'
    ' /etc/apt/sources.list.d/docker.list')
sudo('echo -e "deb http://archive.ubuntu.com/ubuntu raring main universe\n'
    'deb http://us.archive.ubuntu.com/ubuntu/ raring-security main universe\n"'
    ' > /etc/apt/sources.list; apt-get update')
sudo('DEBIAN_FRONTEND=noninteractive apt-get install -q -y wget python-dev'
    ' python-pip supervisor git mercurial linux-image-extra-$(uname -r)'
    ' aufs-tools make libfontconfig libevent-dev')
sudo('wget -O - https://go.googlecode.com/files/go1.1.2.linux-amd64.tar.gz | '
    'tar -v -C /usr/local -xz; ln -s /usr/local/go/bin/go /usr/bin/go')
sudo('GOPATH=/go go get -d github.com/dotcloud/docker')
sudo('pip install -r {}/requirements.txt'.format(CFG_PATH))

# Install docker and testing dependencies
sudo('apt-get install -y -q lxc-docker')
sudo('curl -s https://phantomjs.googlecode.com/files/'
    'phantomjs-1.9.1-linux-x86_64.tar.bz2 | tar jx -C /usr/bin'
    ' --strip-components=2 phantomjs-1.9.1-linux-x86_64/bin/phantomjs')

# Preventively reboot docker-ci daily
sudo('ln -s /sbin/reboot /etc/cron.daily')

# Build docker-ci containers
sudo('cd {}; docker build -t docker .'.format(DOCKER_PATH))
sudo('cd {}/nightlyrelease; docker build -t dockerbuilder .'.format(
    DOCKER_CI_PATH))

# Download docker-ci testing container
sudo('docker pull mzdaniel/test_docker')

# Setup buildbot
sudo('mkdir /data')
sudo('{0}/setup.sh root {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}'
    ' {11} {12}'.format(CFG_PATH, DOCKER_PATH, env['BUILDBOT_PWD'],
    env['IRC_PWD'], env['IRC_CHANNEL'], env['SMTP_USER'],
    env['SMTP_PWD'], env['EMAIL_RCP'], env['REGISTRY_USER'],
    env['REGISTRY_PWD'], env['REGISTRY_BUCKET'], env['REGISTRY_ACCESS_KEY'],
    env['REGISTRY_SECRET_KEY']))


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Resource\Metadata;

use Doctrine\Common\Inflector\Inflector;

final class Metadata implements MetadataInterface
{
    /** @var string */
    private $name;

    /** @var string */
    private $applicationName;

    /** @var string */
    private $driver;

    /** @var string */
    private $templatesNamespace;

    /** @var array */
    private $parameters;

    private function __construct(string $name, string $applicationName, array $parameters)
    {
        $this->name = $name;
        $this->applicationName = $applicationName;

        $this->driver = $parameters['driver'];
        $this->templatesNamespace = array_key_exists('templates', $parameters) ? $parameters['templates'] : null;

        $this->parameters = $parameters;
    }

    public static function fromAliasAndConfiguration(string $alias, array $parameters): self
    {
        [$applicationName, $name] = self::parseAlias($alias);

        return new self($name, $applicationName, $parameters);
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias(): string
    {
        return $this->applicationName . '.' . $this->name;
    }

    /**
     * {@inheritdoc}
     */
    public function getApplicationName(): string
    {
        return $this->applicationName;
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * {@inheritdoc}
     */
    public function getHumanizedName(): string
    {
        return strtolower(trim(preg_replace(['/([A-Z])/', '/[_\s]+/'], ['_$1', ' '], $this->name)));
    }

    /**
     * {@inheritdoc}
     */
    public function getPluralName(): string
    {
        return Inflector::pluralize($this->name);
    }

    /**
     * {@inheritdoc}
     */
    public function getDriver(): string
    {
        return $this->driver;
    }

    /**
     * {@inheritdoc}
     */
    public function getTemplatesNamespace(): ?string
    {
        return $this->templatesNamespace;
    }

    /**
     * {@inheritdoc}
     */
    public function getParameter(string $name)
    {
        if (!$this->hasParameter($name)) {
            throw new \InvalidArgumentException(sprintf('Parameter "%s" is not configured for resource "%s".', $name, $this->getAlias()));
        }

        return $this->parameters[$name];
    }

    /**
     * {@inheritdoc}
     */
    public function hasParameter(string $name): bool
    {
        return array_key_exists($name, $this->parameters);
    }

    /**
     * {@inheritdoc}
     */
    public function getParameters(): array
    {
        return $this->parameters;
    }

    /**
     * {@inheritdoc}
     */
    public function getClass(string $name): string
    {
        if (!$this->hasClass($name)) {
            throw new \InvalidArgumentException(sprintf('Class "%s" is not configured for resource "%s".', $name, $this->getAlias()));
        }

        return $this->parameters['classes'][$name];
    }

    /**
     * {@inheritdoc}
     */
    public function hasClass(string $name): bool
    {
        return isset($this->parameters['classes'][$name]);
    }

    /**
     * {@inheritdoc}
     */
    public function getServiceId(string $serviceName): string
    {
        return sprintf('%s.%s.%s', $this->applicationName, $serviceName, $this->name);
    }

    /**
     * {@inheritdoc}
     */
    public function getPermissionCode(string $permissionName): string
    {
        return sprintf('%s.%s.%s', $this->applicationName, $this->name, $permissionName);
    }

    private static function parseAlias(string $alias): array
    {
        if (false === strpos($alias, '.')) {
            throw new \InvalidArgumentException(sprintf('Invalid alias "%s" supplied, it should conform to the following format "<applicationName>.<name>".', $alias));
        }

        return explode('.', $alias);
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Microsoft.Owin.Infrastructure
{
    [System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
    internal struct HeaderSegment : IEquatable<HeaderSegment>
    {
        private readonly StringSegment _formatting;
        private readonly StringSegment _data;

        // <summary>
        // Initializes a new instance of the <see cref="T:System.Object"/> class.
        // </summary>
        public HeaderSegment(StringSegment formatting, StringSegment data)
        {
            _formatting = formatting;
            _data = data;
        }

        public StringSegment Formatting
        {
            get { return _formatting; }
        }

        public StringSegment Data
        {
            get { return _data; }
        }

        #region Equality members

        public bool Equals(HeaderSegment other)
        {
            return _formatting.Equals(other._formatting) && _data.Equals(other._data);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            return obj is HeaderSegment && Equals((HeaderSegment)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (_formatting.GetHashCode() * 397) ^ _data.GetHashCode();
            }
        }

        public static bool operator ==(HeaderSegment left, HeaderSegment right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(HeaderSegment left, HeaderSegment right)
        {
            return !left.Equals(right);
        }

        #endregion
    }

    [System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
    internal struct HeaderSegmentCollection : IEnumerable<HeaderSegment>, IEquatable<HeaderSegmentCollection>
    {
        private readonly string[] _headers;

        public HeaderSegmentCollection(string[] headers)
        {
            _headers = headers;
        }

        #region Equality members

        public bool Equals(HeaderSegmentCollection other)
        {
            return Equals(_headers, other._headers);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            return obj is HeaderSegmentCollection && Equals((HeaderSegmentCollection)obj);
        }

        public override int GetHashCode()
        {
            return (_headers != null ? _headers.GetHashCode() : 0);
        }

        public static bool operator ==(HeaderSegmentCollection left, HeaderSegmentCollection right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(HeaderSegmentCollection left, HeaderSegmentCollection right)
        {
            return !left.Equals(right);
        }

        #endregion

        public Enumerator GetEnumerator()
        {
            return new Enumerator(_headers);
        }

        IEnumerator<HeaderSegment> IEnumerable<HeaderSegment>.GetEnumerator()
        {
            return GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        internal struct Enumerator : IEnumerator<HeaderSegment>
        {
            private readonly string[] _headers;
            private int _index;

            private string _header;
            private int _headerLength;
            private int _offset;

            private int _leadingStart;
            private int _leadingEnd;
            private int _valueStart;
            private int _valueEnd;
            private int _trailingStart;

            private Mode _mode;

            private static readonly string[] NoHeaders = new string[0];

            public Enumerator(string[] headers)
            {
                _headers = headers ?? NoHeaders;
                _header = string.Empty;
                _headerLength = -1;
                _index = -1;
                _offset = -1;
                _leadingStart = -1;
                _leadingEnd = -1;
                _valueStart = -1;
                _valueEnd = -1;
                _trailingStart = -1;
                _mode = Mode.Leading;
            }

            private enum Mode
            {
                Leading,
                Value,
                ValueQuoted,
                Trailing,
                Produce,
            }

            private enum Attr
            {
                Value,
                Quote,
                Delimiter,
                Whitespace
            }

            public HeaderSegment Current
            {
                get
                {
                    return new HeaderSegment(
                        new StringSegment(_header, _leadingStart, _leadingEnd - _leadingStart),
                        new StringSegment(_header, _valueStart, _valueEnd - _valueStart));
                }
            }

            object IEnumerator.Current
            {
                get { return Current; }
            }

            public void Dispose()
            {
            }

            public bool MoveNext()
            {
                while (true)
                {
                    if (_mode == Mode.Produce)
                    {
                        _leadingStart = _trailingStart;
                        _leadingEnd = -1;
                        _valueStart = -1;
                        _valueEnd = -1;
                        _trailingStart = -1;

                        if (_offset == _headerLength &&
                            _leadingStart != -1 &&
                            _leadingStart != _offset)
                        {
                            // Also produce trailing whitespace
                            _leadingEnd = _offset;
                            return true;
                        }
                        _mode = Mode.Leading;
                    }

                    // if end of a string
                    if (_offset == _headerLength)
                    {
                        ++_index;
                        _offset = -1;
                        _leadingStart = 0;
                        _leadingEnd = -1;
                        _valueStart = -1;
                        _valueEnd = -1;
                        _trailingStart = -1;

                        // if that was the last string
                        if (_index == _headers.Length)
                        {
                            // no more move nexts
                            return false;
                        }

                        // grab the next string
                        _header = _headers[_index] ?? string.Empty;
                        _headerLength = _header.Length;
                    }
                    while (true)
                    {
                        ++_offset;
                        char ch = _offset == _headerLength ? (char)0 : _header[_offset];
                        // todo - array of attrs
                        Attr attr = char.IsWhiteSpace(ch) ? Attr.Whitespace : ch == '\"' ? Attr.Quote : (ch == ',' || ch == (char)0) ? Attr.Delimiter : Attr.Value;

                        switch (_mode)
                        {
                            case Mode.Leading:
                                switch (attr)
                                {
                                    case Attr.Delimiter:
                                        _leadingEnd = _offset;
                                        _mode = Mode.Produce;
                                        break;
                                    case Attr.Quote:
                                        _leadingEnd = _offset;
                                        _valueStart = _offset;
                                        _mode = Mode.ValueQuoted;
                                        break;
                                    case Attr.Value:
                                        _leadingEnd = _offset;
                                        _valueStart = _offset;
                                        _mode = Mode.Value;
                                        break;
                                    case Attr.Whitespace:
                                        // more
                                        break;
                                }
                                break;
                            case Mode.Value:
                                switch (attr)
                                {
                                    case Attr.Quote:
                                        _mode = Mode.ValueQuoted;
                                        break;
                                    case Attr.Delimiter:
                                        _valueEnd = _offset;
                                        _trailingStart = _offset;
                                        _mode = Mode.Produce;
                                        break;
                                    case Attr.Value:
                                        // more
                                        break;
                                    case Attr.Whitespace:
                                        _valueEnd = _offset;
                                        _trailingStart = _offset;
                                        _mode = Mode.Trailing;
                                        break;
                                }
                                break;
                            case Mode.ValueQuoted:
                                switch (attr)
                                {
                                    case Attr.Quote:
                                        _mode = Mode.Value;
                                        break;
                                    case Attr.Delimiter:
                                        if (ch == (char)0)
                                        {
                                            _valueEnd = _offset;
                                            _trailingStart = _offset;
                                            _mode = Mode.Produce;
                                        }
                                        break;
                                    case Attr.Value:
                                    case Attr.Whitespace:
                                        // more
                                        break;
                                }
                                break;
                            case Mode.Trailing:
                                switch (attr)
                                {
                                    case Attr.Delimiter:
                                        _mode = Mode.Produce;
                                        break;
                                    case Attr.Quote:
                                        // back into value
                                        _trailingStart = -1;
                                        _valueEnd = -1;
                                        _mode = Mode.ValueQuoted;
                                        break;
                                    case Attr.Value:
                                        // back into value
                                        _trailingStart = -1;
                                        _valueEnd = -1;
                                        _mode = Mode.Value;
                                        break;
                                    case Attr.Whitespace:
                                        // more
                                        break;
                                }
                                break;
                        }
                        if (_mode == Mode.Produce)
                        {
                            return true;
                        }
                    }
                }
            }

            public void Reset()
            {
                _index = 0;
                _offset = 0;
                _leadingStart = 0;
                _leadingEnd = 0;
                _valueStart = 0;
                _valueEnd = 0;
            }
        }
    }

    [System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
    internal struct StringSegment : IEquatable<StringSegment>
    {
        private readonly string _buffer;
        private readonly int _offset;
        private readonly int _count;

        // <summary>
        // Initializes a new instance of the <see cref="T:System.Object"/> class.
        // </summary>
        public StringSegment(string buffer, int offset, int count)
        {
            _buffer = buffer;
            _offset = offset;
            _count = count;
        }

        public string Buffer
        {
            get { return _buffer; }
        }

        public int Offset
        {
            get { return _offset; }
        }

        public int Count
        {
            get { return _count; }
        }

        public string Value
        {
            get { return _offset == -1 ? null : _buffer.Substring(_offset, _count); }
        }

        public bool HasValue
        {
            get { return _offset != -1 && _count != 0 && _buffer != null; }
        }

        #region Equality members

        public bool Equals(StringSegment other)
        {
            return string.Equals(_buffer, other._buffer) && _offset == other._offset && _count == other._count;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            return obj is StringSegment && Equals((StringSegment)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = (_buffer != null ? _buffer.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ _offset;
                hashCode = (hashCode * 397) ^ _count;
                return hashCode;
            }
        }

        public static bool operator ==(StringSegment left, StringSegment right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(StringSegment left, StringSegment right)
        {
            return !left.Equals(right);
        }

        #endregion

        public bool StartsWith(string text, StringComparison comparisonType)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            int textLength = text.Length;
            if (!HasValue || _count < textLength)
            {
                return false;
            }

            return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0;
        }

        public bool EndsWith(string text, StringComparison comparisonType)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            int textLength = text.Length;
            if (!HasValue || _count < textLength)
            {
                return false;
            }

            return string.Compare(_buffer, _offset + _count - textLength, text, 0, textLength, comparisonType) == 0;
        }

        public bool Equals(string text, StringComparison comparisonType)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            int textLength = text.Length;
            if (!HasValue || _count != textLength)
            {
                return false;
            }

            return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0;
        }

        public string Substring(int offset, int length)
        {
            return _buffer.Substring(_offset + offset, length);
        }

        public StringSegment Subsegment(int offset, int length)
        {
            return new StringSegment(_buffer, _offset + offset, length);
        }

        public override string ToString()
        {
            return Value ?? string.Empty;
        }
    }

    internal static partial class OwinHelpers
    {
        private static readonly Action<string, string, object> AddCookieCallback = (name, value, state) =>
        {
            var dictionary = (IDictionary<string, string>)state;
            if (!dictionary.ContainsKey(name))
            {
                dictionary.Add(name, value);
            }
        };

        private static readonly char[] SemicolonAndComma = new[] { ';', ',' };

        internal static IDictionary<string, string> GetCookies(IOwinRequest request)
        {
            var cookies = request.Get<IDictionary<string, string>>("Microsoft.Owin.Cookies#dictionary");
            if (cookies == null)
            {
                cookies = new Dictionary<string, string>(StringComparer.Ordinal);
                request.Set("Microsoft.Owin.Cookies#dictionary", cookies);
            }

            string text = GetHeader(request.Headers, "Cookie");
            if (request.Get<string>("Microsoft.Owin.Cookies#text") != text)
            {
                cookies.Clear();
                ParseDelimited(text, SemicolonAndComma, AddCookieCallback, cookies);
                request.Set("Microsoft.Owin.Cookies#text", text);
            }
            return cookies;
        }

        internal static void ParseDelimited(string text, char[] delimiters, Action<string, string, object> callback, object state)
        {
            int textLength = text.Length;
            int equalIndex = text.IndexOf('=');
            if (equalIndex == -1)
            {
                equalIndex = textLength;
            }
            int scanIndex = 0;
            while (scanIndex < textLength)
            {
                int delimiterIndex = text.IndexOfAny(delimiters, scanIndex);
                if (delimiterIndex == -1)
                {
                    delimiterIndex = textLength;
                }
                if (equalIndex < delimiterIndex)
                {
                    while (scanIndex != equalIndex && char.IsWhiteSpace(text[scanIndex]))
                    {
                        ++scanIndex;
                    }
                    string name = text.Substring(scanIndex, equalIndex - scanIndex);
                    string value = text.Substring(equalIndex + 1, delimiterIndex - equalIndex - 1);
                    callback(
                        Uri.UnescapeDataString(name.Replace('+', ' ')),
                        Uri.UnescapeDataString(value.Replace('+', ' ')),
                        state);
                    equalIndex = text.IndexOf('=', delimiterIndex);
                    if (equalIndex == -1)
                    {
                        equalIndex = textLength;
                    }
                }
                scanIndex = delimiterIndex + 1;
            }
        }
    }

    internal static partial class OwinHelpers
    {
        public static string GetHeader(IDictionary<string, string[]> headers, string key)
        {
            string[] values = GetHeaderUnmodified(headers, key);
            return values == null ? null : string.Join(",", values);
        }

        public static IEnumerable<string> GetHeaderSplit(IDictionary<string, string[]> headers, string key)
        {
            string[] values = GetHeaderUnmodified(headers, key);
            return values == null ? null : GetHeaderSplitImplementation(values);
        }

        private static IEnumerable<string> GetHeaderSplitImplementation(string[] values)
        {
            foreach (var segment in new HeaderSegmentCollection(values))
            {
                if (segment.Data.HasValue)
                {
                    yield return DeQuote(segment.Data.Value);
                }
            }
        }

        public static string[] GetHeaderUnmodified(IDictionary<string, string[]> headers, string key)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            string[] values;
            return headers.TryGetValue(key, out values) ? values : null;
        }

        public static void SetHeader(IDictionary<string, string[]> headers, string key, string value)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (string.IsNullOrWhiteSpace(value))
            {
                headers.Remove(key);
            }
            else
            {
                headers[key] = new[] { value };
            }
        }

        public static void SetHeaderJoined(IDictionary<string, string[]> headers, string key, params string[] values)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (values == null || values.Length == 0)
            {
                headers.Remove(key);
            }
            else
            {
                headers[key] = new[] { string.Join(",", values.Select(value => QuoteIfNeeded(value))) };
            }
        }

        // Quote items that contain comas and are not already quoted.
        private static string QuoteIfNeeded(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                // Ignore
            }
            else if (value.Contains(','))
            {
                if (value[0] != '"' || value[value.Length - 1] != '"')
                {
                    value = '"' + value + '"';
                }
            }

            return value;
        }

        private static string DeQuote(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                // Ignore
            }
            else if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"')
            {
                value = value.Substring(1, value.Length - 2);
            }

            return value;
        }

        public static void SetHeaderUnmodified(IDictionary<string, string[]> headers, string key, params string[] values)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException("key");
            }
            if (values == null || values.Length == 0)
            {
                headers.Remove(key);
            }
            else
            {
                headers[key] = values;
            }
        }

        public static void SetHeaderUnmodified(IDictionary<string, string[]> headers, string key, IEnumerable<string> values)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }
            headers[key] = values.ToArray();
        }

        public static void AppendHeader(IDictionary<string, string[]> headers, string key, string values)
        {
            if (string.IsNullOrWhiteSpace(values))
            {
                return;
            }

            string existing = GetHeader(headers, key);
            if (existing == null)
            {
                SetHeader(headers, key, values);
            }
            else
            {
                headers[key] = new[] { existing + "," + values };
            }
        }

        public static void AppendHeaderJoined(IDictionary<string, string[]> headers, string key, params string[] values)
        {
            if (values == null || values.Length == 0)
            {
                return;
            }

            string existing = GetHeader(headers, key);
            if (existing == null)
            {
                SetHeaderJoined(headers, key, values);
            }
            else
            {
                headers[key] = new[] { existing + "," + string.Join(",", values.Select(value => QuoteIfNeeded(value))) };
            }
        }

        public static void AppendHeaderUnmodified(IDictionary<string, string[]> headers, string key, params string[] values)
        {
            if (values == null || values.Length == 0)
            {
                return;
            }

            string[] existing = GetHeaderUnmodified(headers, key);
            if (existing == null)
            {
                SetHeaderUnmodified(headers, key, values);
            }
            else
            {
                SetHeaderUnmodified(headers, key, existing.Concat(values));
            }
        }
    }

    internal static partial class OwinHelpers
    {
        private static readonly Action<string, string, object> AppendItemCallback = (name, value, state) =>
        {
            var dictionary = (IDictionary<string, List<String>>)state;

            List<string> existing;
            if (!dictionary.TryGetValue(name, out existing))
            {
                dictionary.Add(name, new List<string>(1) { value });
            }
            else
            {
                existing.Add(value);
            }
        };

        private static readonly char[] AmpersandAndSemicolon = new[] { '&', ';' };

        internal static IDictionary<string, string[]> GetQuery(IOwinRequest request)
        {
            var query = request.Get<IDictionary<string, string[]>>("Microsoft.Owin.Query#dictionary");
            if (query == null)
            {
                query = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
                request.Set("Microsoft.Owin.Query#dictionary", query);
            }

            string text = request.QueryString.Value;
            if (request.Get<string>("Microsoft.Owin.Query#text") != text)
            {
                query.Clear();
                var accumulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
                ParseDelimited(text, AmpersandAndSemicolon, AppendItemCallback, accumulator);
                foreach (var kv in accumulator)
                {
                    query.Add(kv.Key, kv.Value.ToArray());
                }
                request.Set("Microsoft.Owin.Query#text", text);
            }
            return query;
        }

#if !NET40
        internal static IFormCollection GetForm(string text)
        {
            IDictionary<string, string[]> form = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
            var accumulator = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
            ParseDelimited(text, new[] { '&' }, AppendItemCallback, accumulator);
            foreach (var kv in accumulator)
            {
                form.Add(kv.Key, kv.Value.ToArray());
            }
            return new FormCollection(form);
        }
#endif

        internal static string GetJoinedValue(IDictionary<string, string[]> store, string key)
        {
            string[] values = GetUnmodifiedValues(store, key);
            return values == null ? null : string.Join(",", values);
        }

        internal static string[] GetUnmodifiedValues(IDictionary<string, string[]> store, string key)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }
            string[] values;
            return store.TryGetValue(key, out values) ? values : null;
        }
    }

    internal static partial class OwinHelpers
    {
        internal static string GetHost(IOwinRequest request)
        {
            IHeaderDictionary headers = request.Headers;

            string host = GetHeader(headers, "Host");
            if (!string.IsNullOrWhiteSpace(host))
            {
                return host;
            }

            string localIpAddress = request.LocalIpAddress ?? "localhost";
            var localPort = request.Get<string>(OwinConstants.CommonKeys.LocalPort);
            return string.IsNullOrWhiteSpace(localPort) ? localIpAddress : (localIpAddress + ":" + localPort);
        }
    }
}


text:
package rappsilber.ms.dataAccess.msm;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import rappsilber.config.RunConfig;
import rappsilber.ms.ToleranceUnit;
import rappsilber.ms.dataAccess.utils.RobustFileInputStream;
import rappsilber.ms.spectra.Spectra;
import rappsilber.ms.statistics.utils.ObjectContainer;
import rappsilber.utils.Util;

/**
 * An alternative form of the ZipMSMListIterator, that can work with RobustFileInputStream.
 * @author Lutz Fischer <l.fischer@ed.ac.uk>
 */
public class ZipStreamIterator extends AbstractMSMAccess {
    private File inputfile;
    private InputStream instream;
    private Spectra currentSpectra = null;
    private Spectra nextSpectra = null;
    private AbstractMSMAccess currentAccess;
    private int countReadSpectra;
    private ZipInputStream zipinput;

    ToleranceUnit tolerance;
    RunConfig config;
    int minCharge;

    private class ZipEntryStream extends InputStream {

        @Override
        public int read() throws IOException {
            return zipinput.read();
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            return zipinput.read(b, off, len);
        }

        @Override
        public void close() throws IOException {
            zipinput.closeEntry();
        }
    }

    public ZipStreamIterator(File infile, ToleranceUnit tolerance, RunConfig config, int minCharge) throws IOException, ParseException {
        this(new RobustFileInputStream(infile), tolerance, config, minCharge);

        this.inputfile = infile;
        setInputPath(infile.getAbsolutePath());

    }

    public ZipStreamIterator(InputStream instream, ToleranceUnit tolerance, RunConfig config, int minCharge) throws IOException, ParseException {
        this.tolerance = tolerance;
        this.config = config;
        this.minCharge = minCharge;
        open(instream);
        readNext();
    }

    protected void open(InputStream instream1) throws IOException {
        this.instream = instream1;
        zipinput = new ZipInputStream(instream1);
    }

    @Override
    public Spectra current() {
        return currentSpectra;
    }

    @Override
    public void gatherData() throws FileNotFoundException {
        m_MaxPrecursorMass=0;
        m_scanCount = 0;
        Spectra s;
        while ((s = next()) != null) {
            m_MaxPrecursorMass = Math.max(m_MaxPrecursorMass, s.getPrecurserMass());
            m_scanCount ++;
        }
        setReadSpectra(0);
        try {
            restart();
        } catch (IOException ex) {
            Logger.getLogger(ZipMSMListIterator.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

    @Override
    public int countReadSpectra() {
        return countReadSpectra;
    }

    public void setReadSpectra(int count) {
        this.countReadSpectra = count;
    }

    @Override
    public boolean canRestart() {
        return inputfile != null;
    }

    @Override
    public void restart() throws IOException {
        try {
            zipinput.close();
        } catch (IOException ioe) {}
        currentAccess = null;
        nextSpectra=null;
        currentSpectra = null;
        open(new RobustFileInputStream(inputfile));
        try {
            readNext();
        } catch (ParseException ex) {
            Logger.getLogger(ZipStreamIterator.class.getName()).log(Level.SEVERE, null, ex);
            throw new IOException(ex);
        }
    }

    @Override
    public void close() {
        try {
            zipinput.close();
        } catch (IOException ex) {
            Logger.getLogger(ZipStreamIterator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

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

    @Override
    public Spectra next() {
        currentSpectra = nextSpectra;
        if (currentSpectra != null) {
            try {
                readNext();
            } catch (IOException | ParseException ex) {
                Logger.getLogger(ZipStreamIterator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return currentSpectra;
    }

    private void readNext() throws IOException, ParseException {
        if (currentAccess != null) {
            if (currentAccess.hasNext()) {
                nextSpectra = currentAccess.next();
                return;
            }
            currentAccess.close();
        }
        ZipEntry ze;

        while ((ze = zipinput.getNextEntry()) != null) {
            if (!ze.isDirectory()) {
                double ratio = ze.getSize()/ze.getCompressedSize();
                if (ratio > 100)
                    throw new RuntimeException("Zip-file contains something, that would extract to " + Util.twoDigits.format(ratio) + " times the size.\n" +
                            "Assuming an error occoured!");
                if (ze.getName().toLowerCase().endsWith(".zip")) {
                    currentAccess = new ZipStreamIterator(new ZipEntryStream(), tolerance, config, minCharge);
                } else
                    currentAccess = AbstractMSMAccess.getMSMIterator(ze.getName(), new ZipEntryStream(), tolerance, minCharge, config);
                if (currentAccess != null && currentAccess.hasNext()) {
                    nextSpectra = currentAccess.next();
                    return;
                }

            }
        }
        nextSpectra = null;
    }

}


text:
package info.youhavethewrong.dashboard.resources;

import com.yammer.dropwizard.views.View;

public class CommitView extends View {

	private Commit commit;

	public CommitView(Commit commit) {
		super("commit.ftl");
		this.setCommit(commit);
	}

	public Commit getCommit() {
		return commit;
	}

	public void setCommit(Commit commit) {
		this.commit = commit;
	}
}


text:
package org.callistasoftware.netcare.commons.auth.spi.implementation;

import org.callistasoftware.netcare.commons.auth.api.CareGiverInterface;
import org.callistasoftware.netcare.commons.auth.api.CareUnitInterface;
import org.callistasoftware.netcare.commons.auth.api.MedicalPersonalUser;
import org.callistasoftware.netcare.commons.auth.spi.AuthorizationService;
import org.callistasoftware.netcare.commons.auth.spi.vo.AuthCareGiverImpl;
import org.callistasoftware.netcare.commons.auth.spi.vo.AuthCareUnitImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import org.callistasoftware.netcare.commons.auth.hsawsresponder.v3.GetCareUnitResponseType;
import org.callistasoftware.netcare.commons.auth.hsawsresponder.v3.GetHsaUnitResponseType;
import org.callistasoftware.netcare.commons.auth.hsawsresponder.v3.GetMiuForPersonResponseType;
import org.callistasoftware.netcare.commons.auth.hsawsresponder.v3.GetMiuForPersonType;
import org.callistasoftware.netcare.commons.auth.hsawsresponder.v3.MiuInformationType;

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

@Service
public class GetAuthorizationServiceImplHSA implements AuthorizationService {
    private static final Logger log = LoggerFactory.getLogger(GetAuthorizationServiceImplHSA.class);

    @Autowired
    private HSAWebServiceCalls client;

    private SecurityContext securityContext;

    void setSecurityContext(final SecurityContext context) {
    	this.securityContext = context;
    }

    SecurityContext getSecurityContext() {
    	if (this.securityContext == null) {
    		return SecurityContextHolder.getContext();
    	}

    	return this.securityContext;
    }

    void setClient(final HSAWebServiceCalls client) {
    	this.client = client;
    }

    public List<CareUnitInterface> getAuthorizedCareUnitsForHosPerson(String hosPersonHsaId) throws Exception {
        // Initialize result value
        List<CareUnitInterface> careUnits = new ArrayList<CareUnitInterface>();

        // Set hos person hsa ID
        GetMiuForPersonType parameters = new GetMiuForPersonType();
        parameters.setHsaIdentity(hosPersonHsaId);

        try {
            GetMiuForPersonResponseType response = client.callMiuRights(parameters);

            for (MiuInformationType miu : response.getMiuInformation()) {
                // Check that MiuPurpose is "Vård och behandling"
                if (miu.getMiuPurpose().equalsIgnoreCase("Vård och behandling")) {
                    // Add data as a new CareUnit and CareGiver
                    AuthCareUnitImpl unit = new AuthCareUnitImpl();
                    unit.setHsaId(miu.getCareUnitHsaIdentity());
                    unit.setName(miu.getCareUnitName());
                    AuthCareGiverImpl giver = new AuthCareGiverImpl();
                    giver.setHsaId(miu.getCareGiver());
                    giver.setName(miu.getCareGiverName());
                    unit.setCareGiver(giver);
                    careUnits.add(unit);
                }
            }

        } catch (Exception ex) {
            log.error("Exception=" + ex.getMessage());
            throw new Exception(ex);
        }
        return careUnits;
    }

	public boolean isAuthorizedForCareUnit(final MedicalPersonalUser user, String hsaId) {

		if (this.hasAccessTo(user, hsaId)) {
			return true;
		}

		/*
		 * Check parent and add to list
		 */
		try {
			final GetCareUnitResponseType cu = this.client.callGetCareunit(hsaId);
			final String parent = cu.getCareUnitHsaIdentity();
			if (parent != null && parent.trim().length() > 0) {

				final CareGiverInterface careGiver = user.getCareUnit(parent).getCareGiver();
				final GetHsaUnitResponseType response = this.client.callGetHsaunit(hsaId);

				final AuthCareUnitImpl impl = new AuthCareUnitImpl();
				impl.setHsaId(hsaId);
				impl.setName(response.getName());
				impl.setCareGiver(careGiver);

				user.addCareUnit(impl);

				return this.isAuthorizedForCareUnit(user, hsaId);

			} else {
				return false;
			}

		} catch (Exception e) {
			throw new RuntimeException("Exception when trying to contact HSA for user permission", e);
		}
	}

	private boolean hasAccessTo(final MedicalPersonalUser user, final String careUnitId) {
		log.debug("Checking permission on careUnit {}", careUnitId);
        for(CareUnitInterface careUnit : user.getCareUnits()) {
            if(careUnit.getHsaId().equals(careUnitId)) {
                log.debug("User does have permission on careUnit {}", careUnitId);
                return true;
            }
        }

        log.debug("User does not have permission on careUnit {}", careUnitId);
        return false;
	}
}


text:
import WebSocket = require('ws');
import IServerOptions = WebSocket.IServerOptions;
import Server = WebSocket.Server;
import { LiveBookConfig, LiveOrderbook } from '../core/LiveOrderbook';
import * as Commands from './WSCommands';
import { Command, newError, ResponseMessage, wrapMessage } from './WSCommands';
import { ConsoleLoggerFactory, Logger } from '../utils/Logger';
import { ExchangeFeed } from '../exchanges/ExchangeFeed';
import { FeedFactory as coinbaseProFeedFactory } from '../factories/coinbaseProFactories';
import { FeedFactory as bitfinexFeedFactory } from '../factories/bitfinexFactories';
import { FeedFactory as poloniexFeedFactory } from '../factories/poloniexFactories';
import { SnapshotMessage, TickerMessage } from '../core/Messages';
import { createTickerTrigger, Trigger } from '../core/Triggers';

let server: Server;
const logger: Logger = ConsoleLoggerFactory();

export const serverOptions: IServerOptions = {
    host: 'localhost',
    port: 3220,
    clientTracking: true
};

export function dataFeedFactory(): Server {
    if (server === undefined) {
        server = new Server(serverOptions);
        logger.log('info', `Websocket server listening on port ${server.options.port}`);
        server.on('connection', (_socket: WebSocket) => {
            logger.log('debug', 'Websocket connection made to ' + server.options.host);
        });
    }
    return server;
}

export interface ExchangeConnection {
    feed: ExchangeFeed;
    products: string[];
    tickerTriggers: { [product: string]: Trigger<TickerMessage> };
    liveBooks: { [product: string]: LiveOrderbook };
}

function createLiveBook(feed: ExchangeFeed, product: string): LiveOrderbook {
    const config: LiveBookConfig = {
        logger: logger,
        strictMode: false,
        product: product
    };
    const book = new LiveOrderbook(config);
    feed.pipe(book);
    return book;
}

export class DataFeed {
    private readonly socket: WebSocket;
    private readonly exchanges: { [exchange: string]: ExchangeConnection } = {};

    constructor(socket: WebSocket) {
        this.socket = socket;
        socket.on('error', (err: Error) => {
            if (err) {
                console.error(err);
            }
            this.close();
        });

        socket.on('message', (data: any) => {
            try {
                const msg = JSON.parse(data);
                this.handleIncomingCommand(msg);
            } catch (err) {
                const out = {
                    type: 'error',
                    reason: err.message,
                    received: data
                };
                this.send(out);
                this.close();
                return;
            }
        });
    }

    handleIncomingCommand(msg: Command) {
        // Handle subscription requests and delegate to relevant stream factories
        switch (msg.type) {
            case 'attach':
                this.attachToExchange(msg as Commands.AttachCommand);
                break;
            case 'subscribe':
                this.subscribeToProduct(msg as Commands.OrderbookCommand);
                break;
            case 'unsubscribe':
                this.unsubscribeFromProduct(msg as Commands.OrderbookCommand);
                break;
            case 'snapshot':
                this.sendOrderbookState(msg as Commands.OrderbookCommand);
                break;
            case 'ticker':
                this.sendTicker(msg as Commands.OrderbookCommand);
                break;
            default:
                const reply = newError('Unknown command', msg);
                this.send(reply);
        }
    }

    send(msg: Command) {
        if (!this.socket || this.socket.readyState <= 0) {
            logger.log('error', 'Websocket is not connected. Cannot send message', msg);
            return;
        }
        this.socket.send(JSON.stringify(msg), (err: Error) => {
            if (err && (!(err as any).readyState && !(err as any).socket)) {
                this.close();
            }
        });
    }

    close() {
        this.socket.close();
    }

    attachToExchange(msg: Commands.AttachCommand) {
        let factoryFn: () => Promise<ExchangeFeed> = null;
        const products = msg.products;
        const lcExchange = msg.exchange.toLowerCase();
        switch (lcExchange) {
            case 'coinbase-pro':
                factoryFn = coinbaseProFeedFactory.bind(null, logger, products);
                break;
            case 'bitfinex':
                factoryFn = bitfinexFeedFactory.bind(null, logger, products);
                break;
            case 'poloniex':
                factoryFn = poloniexFeedFactory.bind(null, logger, products);
                break;
        }
        if (factoryFn === null) {
            this.send(newError(`${msg.exchange} is not a supported exchange`, msg));
            return;
        }
        factoryFn().then((feed: ExchangeFeed) => {
            this.initExchange(lcExchange, products, feed);
            this.send({
                type: 'attached',
                exchange: lcExchange,
                product: products,
                tag: msg.tag
            } as Command);
        }).catch((err: Error) => {
            this.send(newError(`Could not connect to ${msg.exchange}. ${err.message}`, msg));
        });
    }

    getConnectedExchange(cmd: Commands.ExchangeCommand): ExchangeConnection {
        const exchange: ExchangeConnection = this.exchanges[cmd.exchange.toLowerCase()];
        if (!exchange) {
            this.send(newError(`Not connected to exchange ${cmd.exchange}. Have you tried to attach to it first?`, cmd));
            return null;
        }
        return exchange;
    }

    getLiveBook(cmd: Commands.OrderbookCommand): LiveOrderbook {
        const exchange = this.getConnectedExchange(cmd);
        if (!exchange) {
            return null;
        }
        const book = exchange.liveBooks[cmd.product];
        if (!book) {
            this.send(newError(`We are connected to the ${cmd.exchange}, but not subscribed to the ${cmd.product}`, cmd));
            return null;
        }
        return book;
    }

    private subscribeToProduct(cmd: Commands.OrderbookCommand) {
        const exchange = this.getConnectedExchange(cmd);
        if (!exchange) {
            return;
        }
        const trigger = createTickerTrigger(exchange.feed, cmd.product, false).setAction((event: TickerMessage) => {
            this.send(wrapMessage(event, cmd));
        });
        exchange.tickerTriggers[cmd.product] = trigger;
        const response: ResponseMessage = {
            type: 'subscribe',
            tag: cmd.tag,
            command: cmd,
            result: 'success'
        };
        this.send(response);
    }

    private unsubscribeFromProduct(cmd: Commands.OrderbookCommand) {
        const exchange = this.getConnectedExchange(cmd);
        if (!exchange) {
            return;
        }
        if (!exchange.tickerTriggers[cmd.product]) {
            this.send(newError(`${cmd.product} on ${cmd.exchange} is not currently subscribed to ticker events`, cmd));
            return;
        }
        const trigger = exchange.tickerTriggers[cmd.product];
        trigger.cancel();
        const response: ResponseMessage = {
            type: 'unsubscribe',
            tag: cmd.tag,
            command: cmd,
            result: 'success'
        };
        this.send(response);
    }

    private initExchange(exchange: string, products: string[], feed: ExchangeFeed) {
        this.exchanges[exchange] = {
            feed: feed,
            products: products,
            tickerTriggers: {},
            liveBooks: {}
        };
        this.exchanges[exchange].products = products;
        products.forEach((product: string) => {
            this.exchanges[exchange].liveBooks[product] = createLiveBook(feed, product);
        });
    }

    private sendTicker(cmd: Commands.OrderbookCommand) {
        const book = this.getLiveBook(cmd);
        if (!book) {
            return;
        }
        const ticker: TickerMessage = {type: 'ticker', time: new Date(), ...book.ticker};
        this.send(wrapMessage(ticker, cmd));
    }

    private sendOrderbookState(cmd: Commands.OrderbookCommand) {
        const book = this.getLiveBook(cmd);
        if (!book) {
            return;
        }
        const msg: SnapshotMessage = {
            type: 'snapshot',
            time: new Date(),
            productId: cmd.product,
            ...book.state()
        };
        this.send(wrapMessage(msg, cmd));
    }
}


text:
namespace OCIO = OCIO_NAMESPACE;

namespace GTTest1
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_LOG;
// These are {R, G, B, master, center, width};
static const OCIO::GradingRGBMSW midtones{ 0.3, 1.0, 1.8,  1.2, 0.47, 0.6 };
}

void GradingToneLogMidtones(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest1::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest1::style);
    tone.m_midtones = GTTest1::midtones;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(2e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_midtones_fwd)
{
    GradingToneLogMidtones(test, OCIO::TRANSFORM_DIR_FORWARD, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_midtones_fwd_dynamic)
{
    GradingToneLogMidtones(test, OCIO::TRANSFORM_DIR_FORWARD, true);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_midtones_rev)
{
    GradingToneLogMidtones(test, OCIO::TRANSFORM_DIR_INVERSE, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_midtones_rev_dynamic)
{
    GradingToneLogMidtones(test, OCIO::TRANSFORM_DIR_INVERSE, true);
}

namespace GTTest2
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_LOG;
// These are {R, G, B, master, start, pivot};
static const OCIO::GradingRGBMSW highlights{ 0.3, 1.0, 1.8, 1.4, -0.1, 0.9 };
}

void GradingToneLogHighlights(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest2::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest2::style);
    tone.m_highlights = GTTest2::highlights;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(2e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_highlights_fwd)
{
    GradingToneLogHighlights(test, OCIO::TRANSFORM_DIR_FORWARD, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_highlights_fwd_dynamic)
{
    GradingToneLogHighlights(test, OCIO::TRANSFORM_DIR_FORWARD, true);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_highlights_rev)
{
    GradingToneLogHighlights(test, OCIO::TRANSFORM_DIR_INVERSE, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_highlights_rev_dynamic)
{
    GradingToneLogHighlights(test, OCIO::TRANSFORM_DIR_INVERSE, true);
}

namespace GTTest3
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_VIDEO;
// These are {R, G, B, master, start, pivot};
static const OCIO::GradingRGBMSW shadows{ 0.3, 1., 1.79, 0.6, 0.8, -0.1 };
}

void GradingToneVideoShadows(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest3::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest3::style);
    tone.m_shadows = GTTest3::shadows;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(3e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_shadows_fwd)
{
    GradingToneVideoShadows(test, OCIO::TRANSFORM_DIR_FORWARD, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_shadows_fwd_dynamic)
{
    GradingToneVideoShadows(test, OCIO::TRANSFORM_DIR_FORWARD, true);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_shadows_rev)
{
    GradingToneVideoShadows(test, OCIO::TRANSFORM_DIR_INVERSE, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_shadows_rev_dynamic)
{
    GradingToneVideoShadows(test, OCIO::TRANSFORM_DIR_INVERSE, true);
}

namespace GTTest4
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_VIDEO;
// These are {R, G, B, master, start, width};
static const OCIO::GradingRGBMSW whites{ 0.3, 1., 1.9, 0.6, -0.2, 1.4 };
}

void GradingToneVideoWhites(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest4::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest4::style);
    tone.m_whites = GTTest4::whites;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(3e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_white_detail_fwd)
{
    GradingToneVideoWhites(test, OCIO::TRANSFORM_DIR_FORWARD, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_white_detail_fwd_dynamic)
{
    GradingToneVideoWhites(test, OCIO::TRANSFORM_DIR_FORWARD, true);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_white_detail_rev)
{
    GradingToneVideoWhites(test, OCIO::TRANSFORM_DIR_INVERSE, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_video_white_detail_rev_dynamic)
{
    GradingToneVideoWhites(test, OCIO::TRANSFORM_DIR_INVERSE, true);
}

namespace GTTest5
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_LOG;
// These are {R, G, B, master, start, width};
static const OCIO::GradingRGBMSW blacks{ 0.3, 1., 1.9, 0.6, 0.8, 0.9 };
}

void GradingToneLogBlacks(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest5::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest5::style);
    tone.m_blacks = GTTest5::blacks;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(3e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_black_detail_fwd)
{
    GradingToneLogBlacks(test, OCIO::TRANSFORM_DIR_FORWARD, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_black_detail_fwd_dynamic)
{
    GradingToneLogBlacks(test, OCIO::TRANSFORM_DIR_FORWARD, true);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_black_detail_rev)
{
    GradingToneLogBlacks(test, OCIO::TRANSFORM_DIR_INVERSE, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_black_detail_rev_dynamic)
{
    GradingToneLogBlacks(test, OCIO::TRANSFORM_DIR_INVERSE, true);
}

namespace GTTest6
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_LOG;
static constexpr double scontrast = 1.8;
static constexpr double scontrast2 = 0.3;
}

void GradingToneLogSContrast(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic,
                             double scontrast)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest6::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest6::style);
    tone.m_scontrast = scontrast;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(3e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast_fwd)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_FORWARD, false,
                            GTTest6::scontrast);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast_fwd_dynamic)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_FORWARD, true,
                            GTTest6::scontrast);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast2_fwd)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_FORWARD, false,
                            GTTest6::scontrast2);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast2_fwd_dynamic)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_FORWARD, true,
                            GTTest6::scontrast2);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast_rev)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_INVERSE, false,
                            GTTest6::scontrast);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast_rev_dynamic)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_INVERSE, true,
                            GTTest6::scontrast);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast2_rev)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_INVERSE, false,
                            GTTest6::scontrast2);
}

OCIO_ADD_GPU_TEST(GradingTone, style_log_scontrast2_rev_dynamic)
{
    GradingToneLogSContrast(test, OCIO::TRANSFORM_DIR_INVERSE, true,
                            GTTest6::scontrast2);
}

namespace GTTest7
{
static constexpr OCIO::GradingStyle style = OCIO::GRADING_LIN;
// These are {R, G, B, master, center, width};
const OCIO::GradingRGBMSW midtones{ 0.3, 1.4, 1.8, 1., 1., 8. };
}

void GradingToneLinMidtones(OCIOGPUTest & test, OCIO::TransformDirection dir, bool dynamic)
{
    auto gt = OCIO::GradingToneTransform::Create(GTTest7::style);
    gt->setDirection(dir);
    if (dynamic)
    {
        gt->makeDynamic();
    }

    OCIO::GradingTone tone(GTTest7::style);
    tone.m_midtones = GTTest7::midtones;
    gt->setValue(tone);
    test.setProcessor(gt);

    test.setErrorThreshold(5e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);
    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_lin_midtones_fwd)
{
    GradingToneLinMidtones(test, OCIO::TRANSFORM_DIR_FORWARD, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_lin_midtones_fwd_dynamic)
{
    GradingToneLinMidtones(test, OCIO::TRANSFORM_DIR_FORWARD, true);
}

OCIO_ADD_GPU_TEST(GradingTone, style_lin_midtones_rev)
{
    GradingToneLinMidtones(test, OCIO::TRANSFORM_DIR_INVERSE, false);
}

OCIO_ADD_GPU_TEST(GradingTone, style_lin_midtones_rev_dynamic)
{
    GradingToneLinMidtones(test, OCIO::TRANSFORM_DIR_INVERSE, true);
}

// TODO: add inverse tests.

namespace
{

class GTRetest
{
public:
    GTRetest() = delete;

    explicit GTRetest(OCIOGPUTest & test)
        : m_test(test)
    {
        OCIO::ConstProcessorRcPtr & processor = test.getProcessor();

        if (processor->hasDynamicProperty(OCIO::DYNAMIC_PROPERTY_GRADING_TONE))
        {
            auto dp = processor->getDynamicProperty(OCIO::DYNAMIC_PROPERTY_GRADING_TONE);
            m_dynProp = OCIO::DynamicPropertyValue::AsGradingTone(dp);
        }
    }

protected:

    void initializeGPUDynamicProperties()
    {
        // Wait for the shader to be created to call this (first retest).
        // Shader is created once, thus updating the dynamic property on the processor will not
        // be reflected on the shader because dynamic properties are decoupled between processor
        // and shader.
        auto & shaderDesc = m_test.getShaderDesc();
        if (shaderDesc->hasDynamicProperty(OCIO::DYNAMIC_PROPERTY_GRADING_TONE))
        {
            auto dp = shaderDesc->getDynamicProperty(OCIO::DYNAMIC_PROPERTY_GRADING_TONE);
            m_dynPropGPU = OCIO::DynamicPropertyValue::AsGradingTone(dp);
        }
    }

    OCIOGPUTest & m_test;
    // Keep dynamic property values for tests modifying their current value.
    OCIO::DynamicPropertyGradingToneRcPtr m_dynProp;
    OCIO::DynamicPropertyGradingToneRcPtr m_dynPropGPU;
};

}

OCIO_ADD_GPU_TEST(GradingTone, style_log_dynamic_retests)
{
    OCIO::GradingToneTransformRcPtr gt = OCIO::GradingToneTransform::Create(OCIO::GRADING_LOG);
    gt->makeDynamic();

    OCIO::GradingTone gtlog{ OCIO::GRADING_LOG };
    gt->setValue(gtlog);
    test.setProcessor(gt);

    class MyGTRetest : public GTRetest
    {
    public:
        explicit MyGTRetest(OCIOGPUTest & test) : GTRetest(test)
        {
        }

        void retest1()
        {
            initializeGPUDynamicProperties();
            auto vals = m_dynProp->getValue();
            vals.m_midtones = GTTest1::midtones;
            m_dynProp->setValue(vals);
            m_dynPropGPU->setValue(vals);
        }
        void retest2()
        {
            auto vals = m_dynProp->getValue();
            vals.m_highlights = GTTest2::highlights;
            vals.m_whites = GTTest4::whites;
            m_dynProp->setValue(vals);
            m_dynPropGPU->setValue(vals);
        }
        void retest3()
        {
            auto vals = m_dynProp->getValue();
            vals.m_blacks = GTTest5::blacks;
            m_dynProp->setValue(vals);
            m_dynPropGPU->setValue(vals);
        }
        void retest4()
        {
            OCIO::GradingTone identity{ OCIO::GRADING_LOG };
            m_dynProp->setValue(identity);
            m_dynPropGPU->setValue(identity);
        }
    };

    // Use shared_ptr so that object would stay until test is deleted.
    std::shared_ptr<MyGTRetest> gtretest = std::make_shared<MyGTRetest>(test);

    // This adds a reference count to the shared_ptr.
    OCIOGPUTest::RetestSetupCallback f1 = std::bind(&MyGTRetest::retest1, gtretest);
    OCIOGPUTest::RetestSetupCallback f2 = std::bind(&MyGTRetest::retest2, gtretest);
    OCIOGPUTest::RetestSetupCallback f3 = std::bind(&MyGTRetest::retest3, gtretest);
    OCIOGPUTest::RetestSetupCallback f4 = std::bind(&MyGTRetest::retest4, gtretest);

    test.addRetest(f1);
    test.addRetest(f2);
    test.addRetest(f3);
    test.addRetest(f4);

    test.setErrorThreshold(5e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);

    test.setTestInfinity(false);
    test.setTestNaN(false);
}

OCIO_ADD_GPU_TEST(GradingTone, two_transforms_retests)
{
    OCIO::GradingToneTransformRcPtr gtDyn = OCIO::GradingToneTransform::Create(OCIO::GRADING_LOG);
    gtDyn->makeDynamic();

    OCIO::GradingTone gtlog{ OCIO::GRADING_LOG };
    gtDyn->setValue(gtlog);

    auto gtNonDyn = OCIO::GradingToneTransform::Create(GTTest6::style);

    OCIO::GradingTone tone{ OCIO::GRADING_LIN };
    tone.m_scontrast = 1.8;
    tone.m_midtones = OCIO::GradingRGBMSW(0.3, 1.4, 1.8, 1., 1., 8.);

    gtNonDyn->setValue(tone);

    auto group = OCIO::GroupTransform::Create();
    group->appendTransform(gtDyn);
    group->appendTransform(gtNonDyn);
    test.setProcessor(group);

    class MyGTRetest : public GTRetest
    {
    public:
        explicit MyGTRetest(OCIOGPUTest & test) : GTRetest(test)
        {
        }

        void retest1()
        {
            initializeGPUDynamicProperties();
            auto vals = m_dynProp->getValue();
            vals.m_midtones = GTTest1::midtones;
            m_dynProp->setValue(vals);
            m_dynPropGPU->setValue(vals);
        }
        void retest2()
        {
            auto vals = m_dynProp->getValue();
            vals.m_highlights = GTTest2::highlights;
            vals.m_whites = GTTest4::whites;
            m_dynProp->setValue(vals);
            m_dynPropGPU->setValue(vals);
        }
        void retest3()
        {
            auto vals = m_dynProp->getValue();
            vals.m_blacks = GTTest5::blacks;
            m_dynProp->setValue(vals);
            m_dynPropGPU->setValue(vals);
        }
        void retest4()
        {
            OCIO::GradingTone identity{ OCIO::GRADING_LOG };
            m_dynProp->setValue(identity);
            m_dynPropGPU->setValue(identity);
        }
    };

    // Use shared_ptr so that object would stay until test is deleted.
    std::shared_ptr<MyGTRetest> gtretest = std::make_shared<MyGTRetest>(test);

    // This adds a reference count to the shared_ptr.
    OCIOGPUTest::RetestSetupCallback f1 = std::bind(&MyGTRetest::retest1, gtretest);
    OCIOGPUTest::RetestSetupCallback f2 = std::bind(&MyGTRetest::retest2, gtretest);
    OCIOGPUTest::RetestSetupCallback f3 = std::bind(&MyGTRetest::retest3, gtretest);
    OCIOGPUTest::RetestSetupCallback f4 = std::bind(&MyGTRetest::retest4, gtretest);

    test.addRetest(f1);
    test.addRetest(f2);
    test.addRetest(f3);
    test.addRetest(f4);

    test.setErrorThreshold(5e-5f);
    test.setExpectedMinimalValue(1.0f);
    test.setRelativeComparison(true);
    test.setTestWideRange(true);

    test.setTestInfinity(false);
    test.setTestNaN(false);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="notification_sound_default">"Výchozí zvuk oznámení"</string>
    <string name="alarm_sound_default">"Výchozí zvuk budíku"</string>
</resources>


text:
<?php
/**
 * @see KumbiaView
 */
require_once CORE_PATH . 'kumbia/kumbia_view.php';

/**
 * Esta clase permite extender o modificar la clase ViewBase de Kumbiaphp.
 *
 * @category KumbiaPHP
 * @package View
 */
class View extends KumbiaView {

    /**
     * Método que muestra el contenido de una vista
     */
    public static function content() {
        Flash::output();
        parent::content();
    }

    /**
     * Método para mostrar los mensajes e impresiones del request
     */
    public static function flash() {
        return self::partial('flash');
    }

    /**
     * Método para mostrar el proceso actual en las vistar
     */
    public static function process($moduleName, $processName=null, $setTitle=true) {
        return self::partial('process', false, array('modulo'=>$moduleName, 'proceso'=>$processName));
    }

    public static function processAdminLTE($moduleName, $processName=null, $setTitle=true, $page_area=NULL) {
        return self::partial('AdminLTE/process', false, array('modulo'=>$moduleName, 'proceso'=>$processName, 'titulo'=>$setTitle));
    }
    /**
     * Método para dar una respuesta como ajax
     */
    public static function ajax() {
        View::select(NULL, NULL);
        return self::partial('ajax');
    }

    /**
     * Método que muestra una vista para redireccionar si se trabaja con ajax la app
     *
     * @param string $url Url a redireccionar
     * @param boolean $isLogin Indica si redirecciona al login o no
     * @param string $text Texto a mostrar en la redirección
     * @return string
     */
    public static function redirect($url, $isLogin=FALSE, $text='') {
        View::select(NULL, NULL);
        return self::partial('redirect', FALSE, array('url'=>$url, 'isLogin'=>$isLogin, 'text'=>$text));
    }

    /**
     * Método para enviar un json
     */
    public function json() {
        View::select(NULL, 'json');
    }

    /**
     * Método para mostrar el mensaje de actualizacion
     */
    public static function appUpdate() {
        View::select(NULL, NULL);
        return self::partial('dbkm_update');
    }

    /**
     * Método para mostrar una ventana de error
     */
    public static function error($template='backend/error') {
        self::$_path = '_shared/errors/';
        self::select('popup', $template);
    }

    /**
     * Método para saber si existe una vista de eror
     */
    public static function hasError($template='backend/error') {
        return (self::$_template == $template) ? true : false;
    }

    /**
     * Método que muestra el reporte según el formato. Si es un formato desconocido muesra la página de error
     *
     * @param string $formato Formato a mostrar: html, pdf, xls, xml, ticket, etc
     * @return boolean
     */
    public static function report($formato) {

        $formato    = Filter::get($formato,'string');
        $tipos      = explode('|', TYPE_REPORTS);
        $templates  = array();
        foreach($tipos as $tmp) {
            $r = explode('.', $tmp);
            if(count($r) > 1) {
                $templates[$r[0]] = $r[1];
            }
        }

        if(array_key_exists($formato, $templates)) {
            $template       = 'backend/'.$templates[$formato];
            $tmp_formato    = $formato.'.'.$templates[$formato];
        } else {
            $template = NULL;
            $tmp_formato    = $formato;
        }

        if($formato == 'error') {
            self::error();
        } else if( !in_array($tmp_formato, $tipos) OR $formato == null) {
            Flash::error('Error: El formato del reporte es incorrecto.');
            self::error();
        } else {
            self::response($formato, $template);
        }

    }

}


text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner</title>
  <link rel="shortcut icon" type="image/png" href=".grunt/grunt-contrib-jasmine/jasmine_favicon.png">

  <link rel="stylesheet" type="text/css" href=".grunt/grunt-contrib-jasmine/jasmine.css">

</head>
<body>

  <script src=".grunt/grunt-contrib-jasmine/es5-shim.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/jasmine.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/jasmine-html.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/json2.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/boot.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/app/src/Person.js"></script>

  <script src="app/test/person.spec.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/grunt-template-jasmine-istanbul/reporter.js"></script>

  <script src=".grunt/grunt-contrib-jasmine/reporter.js"></script>

</body>
</html>


text:
ouzo-migrations
===============

PHP MIgrations ala ActiveRecord migration


text:
<project default="all">
	<property name="module-name" value="tatala-java-example" />
  <property name="module-version" value="0.3.0" />
	<property name="obj-dir" location="target/classes" />
	<property name="lib-dir" location="lib" />
	<property name="src-dir" location="src" />
	<property name="target-dir" location="target" />

	<target name="clean">
		<delete dir="${obj-dir}" />
		<mkdir dir="${obj-dir}" />
	</target>

	<target name="compile" depends="clean">
		<javac srcdir="${src-dir}" destdir="${obj-dir}" debug="on">
			<classpath>
				<pathelement path="${classpath}" />
				<fileset dir="${lib-dir}">
					<include name="**/*.jar" />
				</fileset>
			</classpath>
		</javac>
    <copy file="${src-dir}/main/resources/log4j.xml" todir="${obj-dir}" />
	</target>

	<target name="jar" depends="compile">
		<jar destfile="${target-dir}/${module-name}-${module-version}.jar" basedir="${obj-dir}" />
	</target>

	<target name="all" depends="jar" />

</project>


text:
require File.dirname(__FILE__) + '/../test_helper'

describe Perseus::Parser do

  before do
    @basic_styles   = fixture(:basic)
    @complex_styles = fixture(:complex)
  end

  after do
    @parser = nil
  end

  describe '#parse' do
    describe 'basic styles' do

      before do
        @parser = Perseus::Parser.new(@basic_styles)
      end

      it 'parsing should be repeatable' do
        @parser.parse.wont_be_empty
        @parser.parse.wont_be_empty
      end

      it 'should return an Array' do
        @parser.parse.must_be_kind_of Array
      end

      it 'should return an Array of root nodes' do
        @parser.parse.first.must_be_kind_of Perseus::Selector
      end

      it 'the root selector should have only one child' do
        @parser.parse.size.must_equal 1
      end

    end

    describe 'complex styles' do

      before do
        @parser = Perseus::Parser.new(@complex_styles)
      end

      it 'the root selector should have two children' do
        @parser.parse.size.must_equal 2
      end

      it 'should return an Array' do
        @parser.parse.must_be_kind_of Array
      end

      it 'should return an Array of root nodes' do
        @parser.parse.first.must_be_kind_of Perseus::Selector
      end

      it 'the first root node must be have the text .bat' do
        @parser.parse.first.text.must_equal '.foo'
      end

    end

    describe '#parse_node' do

      before do
        @parser = Perseus::Parser.new('')
        # TODO: use mock? (messy in this case)
        @node   = Sass::Tree::RuleNode.new(['#foo'])
      end

      it 'must return a Perseus::Selector' do
        @parser.parse_node(@node).must_be_kind_of Perseus::Selector
      end

      # TODO: additional tests

    end

    describe '#extract_options_from_comment' do

      before do
        @parser = Perseus::Parser.new('')
      end

      # TODO: replace with higher level tests, instance_eval is iffy
      it 'should extract options add push them into the options buffer' do
        comment = MiniTest::Mock.new
        comment.expect :value, ['// @foo: bar']
        @parser.extract_options_from_comment(comment)
        @parser.instance_eval { @options_buffer }.must_include 'foo'
        @parser.instance_eval { @options_buffer['foo'] }.must_equal 'bar'
      end

    end

  end

end