text:
#ifndef EVENT_TRIGGER_H
#define EVENT_TRIGGER_H

#include "catalog/dependency.h"
#include "catalog/objectaddress.h"
#include "catalog/pg_event_trigger.h"
#include "nodes/parsenodes.h"
#include "utils/aclchk_internal.h"
#include "tcop/deparse_utility.h"

typedef struct EventTriggerData
{
	NodeTag		type;
	const char *event;			/* event name */
	Node	   *parsetree;		/* parse tree */
	const char *tag;			/* command tag */
} EventTriggerData;

#define AT_REWRITE_ALTER_PERSISTENCE	0x01
#define AT_REWRITE_DEFAULT_VAL			0x02
#define AT_REWRITE_COLUMN_REWRITE		0x04
#define AT_REWRITE_ALTER_OID			0x08

/*
 * EventTriggerData is the node type that is passed as fmgr "context" info
 * when a function is called by the event trigger manager.
 */
#define CALLED_AS_EVENT_TRIGGER(fcinfo) \
	((fcinfo)->context != NULL && IsA((fcinfo)->context, EventTriggerData))

extern Oid	CreateEventTrigger(CreateEventTrigStmt *stmt);
extern void RemoveEventTriggerById(Oid ctrigOid);
extern Oid	get_event_trigger_oid(const char *trigname, bool missing_ok);

extern Oid	AlterEventTrigger(AlterEventTrigStmt *stmt);
extern ObjectAddress AlterEventTriggerOwner(const char *name, Oid newOwnerId);
extern void AlterEventTriggerOwner_oid(Oid, Oid newOwnerId);

extern bool EventTriggerSupportsObjectType(ObjectType obtype);
extern bool EventTriggerSupportsObjectClass(ObjectClass objclass);
extern bool EventTriggerSupportsGrantObjectType(GrantObjectType objtype);
extern void EventTriggerDDLCommandStart(Node *parsetree);
extern void EventTriggerDDLCommandEnd(Node *parsetree);
extern void EventTriggerSQLDrop(Node *parsetree);
extern void EventTriggerTableRewrite(Node *parsetree, Oid tableOid, int reason);

extern bool EventTriggerBeginCompleteQuery(void);
extern void EventTriggerEndCompleteQuery(void);
extern bool trackDroppedObjectsNeeded(void);
extern void EventTriggerSQLDropAddObject(const ObjectAddress *object,
							 bool original, bool normal);

extern void EventTriggerInhibitCommandCollection(void);
extern void EventTriggerUndoInhibitCommandCollection(void);

extern void EventTriggerCollectSimpleCommand(ObjectAddress address,
								 ObjectAddress secondaryObject,
								 Node *parsetree);

extern void EventTriggerAlterTableStart(Node *parsetree);
extern void EventTriggerAlterTableRelid(Oid objectId);
extern void EventTriggerCollectAlterTableSubcmd(Node *subcmd,
									ObjectAddress address);
extern void EventTriggerAlterTableEnd(void);

extern void EventTriggerCollectGrant(InternalGrant *istmt);
extern void EventTriggerCollectAlterOpFam(AlterOpFamilyStmt *stmt,
							  Oid opfamoid, List *operators,
							  List *procedures);
extern void EventTriggerCollectCreateOpClass(CreateOpClassStmt *stmt,
								 Oid opcoid, List *operators,
								 List *procedures);
extern void EventTriggerCollectAlterTSConfig(AlterTSConfigurationStmt *stmt,
								 Oid cfgId, Oid *dictIds, int ndicts);
extern void EventTriggerCollectAlterDefPrivs(AlterDefaultPrivilegesStmt *stmt);

#endif   /* EVENT_TRIGGER_H */


text:
const app = require('express')();
var path = require('path');

app.get('/', (req, res) => {
   res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(3000, () => console.log('Server running'));

redpajama_set_name: RedPajamaGithub


text:
struct Inner {
  int c[C_COUNT];
  short q;
};

struct StructWithArray {
  signed char c;
  Inner i;
  int a[A_COUNT];
  short b[B_COUNT];
  short z;
};

void NegateStructWithArray(StructWithArray &outer, int &other, Inner &inner);

#endif  // FULLY_HOMOMORPHIC_ENCRYPTION_TRANSPILER_EXAMPLES_STRUCTS_STRUCT_WITH_ARRAY_H_


text:
import os

import pytest
from pyjob.exception import PyJobError, PyJobTaskLockedError
from pyjob.script import ScriptCollector
from pyjob.task import ClusterTask, Task

class MockTask(Task):
    @property
    def info(self):
        return {}

    def close(self):
        pass

    def kill(self):
        pass

    def _run(self):
        pass

class MockClusterTask(ClusterTask, MockTask):
    JOB_ARRAY_INDEX = "$TEST"
    SCRIPT_DIRECTIVE = "#TEST"

    def _create_runscript(self):
        pass

    def _check_requirements(self):
        pass

class TestTask(object):
    def test_1(self):
        task = MockTask(None)
        assert task.pid is None
        assert not task.completed
        assert task.directory == os.getcwd()
        assert task.nprocesses == 1
        assert task.script == []
        assert not task.locked
        assert task.info == {}
        assert task.log == []

    def test_2(self):
        task = MockTask(None, directory="..")
        assert task.directory == os.path.abspath("..")
        assert task.pid is None
        assert not task.completed
        assert task.nprocesses == 1
        assert task.script == []
        assert not task.locked
        assert task.info == {}
        assert task.log == []

    def test_3(self):
        task = MockTask(None, processes=2)
        assert task.nprocesses == 2
        assert task.pid is None
        assert not task.completed
        assert task.directory == os.getcwd()
        assert task.script == []
        assert not task.locked
        assert task.info == {}
        assert task.log == []

    def test_4(self):
        task = MockTask(None)
        assert not task.locked
        with pytest.raises(PyJobError):
            task.run()
        assert not task.locked

    def test_5(self):
        task = MockTask(None)
        task.lock()
        assert task.locked
        with pytest.raises(PyJobTaskLockedError):
            task.run()

    def test_6(self):
        script = pytest.helpers.get_py_script(0, 1)
        task = MockTask(script)
        assert not task.locked
        task.run()
        assert task.locked
        with pytest.raises(PyJobTaskLockedError):
            task.run()
        pytest.helpers.unlink(task.script)

    def test_7(self):
        task = MockTask(None)
        assert not task.locked
        with pytest.raises(PyJobError):
            task.run()
        script = pytest.helpers.get_py_script(0, 1)
        task.add_script(script)
        task.run()
        pytest.helpers.unlink(task.script)

    def test_8(self):
        script = pytest.helpers.get_py_script(0, 1)
        task = MockTask(script)
        assert task.log == [script.path.replace(".py", ".log")]
        pytest.helpers.unlink(task.script)

    def test_9(self):
        scripts = [pytest.helpers.get_py_script(i, 1) for i in range(2)]
        [s.write() for s in scripts]
        task = MockTask([s.path for s in scripts])
        assert task.log == [s.replace(".py", ".log") for s in task.script]
        pytest.helpers.unlink(task.script)

    def test_10(self):
        task = MockTask([])
        scripts = [pytest.helpers.get_py_script(i, 1) for i in range(2)]
        for s in scripts:
            task.add_script(s)
        assert task.script == [s.path for s in scripts]
        pytest.helpers.unlink(task.script)

    def test_11(self):
        container = ScriptCollector(None)
        task = MockTask(container)
        assert task.script_collector is container

    def test_12(self):
        container = ScriptCollector(None)
        task = MockTask(container)
        assert task.script_collector is container
        assert len(task.script_collector) == 0
        task.add_script(pytest.helpers.get_py_script(0, 1))
        assert len(task.script_collector) == 1

    def test_13(self):
        container = ScriptCollector(pytest.helpers.get_py_script(10, 1))
        task = MockTask(container)
        task.add_script([pytest.helpers.get_py_script(i, 1) for i in range(5)])
        assert len(task.script_collector) == 6

    def test_14(self):
        container = ScriptCollector(pytest.helpers.get_py_script(10, 1))
        task = MockTask(container)
        assert len(task.script_collector) == 1
        task.lock()
        assert task.locked
        with pytest.raises(PyJobError):
            task.add_script(pytest.helpers.get_py_script(1, 1))
        assert len(task.script_collector) == 1

    def test_15(self):
        task = MockTask(None)
        assert task.get_time(1440) == "24:00:00"
        assert task.get_time(1470) == "24:30:00"
        assert task.get_time(120) == "02:00:00"
        assert task.get_time(150) == "02:30:00"
        with pytest.raises(PyJobError):
            task.get_time(0)
        assert task.pid is None
        assert not task.completed
        assert task.nprocesses == 1
        assert task.script == []
        assert not task.locked
        assert task.info == {}
        assert task.log == []

@pytest.mark.skipif(pytest.on_windows, reason="Unavailable on Windows")
class TestClusterTask(object):
    def test_get_array_bash_extension_1(self):
        task = MockClusterTask(None)
        fname = "test.jobs"
        open(fname, "w")
        assert task.get_array_bash_extension(fname, 0) == [
            'script=$(awk "NR==$TEST" test.jobs)',
            'log=$(echo $script | sed "s/\\.${script##*.}/\\.log/")',
            "$script > $log 2>&1",
        ]
        pytest.helpers.unlink([fname])

    def test_get_array_bash_extension_2(self):
        task = MockClusterTask(None)
        fname = "test.jobs"
        open(fname, "w")
        assert task.get_array_bash_extension(fname, 1) == [
            'script=$(awk "NR==$(($TEST + 1))" test.jobs)',
            'log=$(echo $script | sed "s/\\.${script##*.}/\\.log/")',
            "$script > $log 2>&1",
        ]
        pytest.helpers.unlink([fname])

    def test_get_array_bash_extension_3(self):
        task = MockClusterTask(None)
        with pytest.raises(ValueError):
            task.get_array_bash_extension(None, 1)

    def test_get_array_bash_extension_4(self):
        task = MockClusterTask(None)
        with pytest.raises(ValueError):
            task.get_array_bash_extension("/some/file", 0)

    def test_get_array_bash_extension_5(self):
        task = MockClusterTask(None)
        fname = "test.jobs"
        open(fname, "w")
        with pytest.raises(ValueError):
            task.get_array_bash_extension(fname, -1)
        pytest.helpers.unlink([fname])

    def test_ensure_exec_available_1(self):
        task = MockClusterTask(None)
        with pytest.raises(PyJobError):
            task._ensure_exec_available("qstat")

    def test_ensure_exec_available_2(self):
        task = MockClusterTask(None)
        task._ensure_exec_available("ls")


text:
using Pandaros.Settlers.Extender;
using System;
using System.Collections.Generic;

namespace Pandaros.Settlers.Jobs.Roaming
{
    public interface IRoamingJobObjective : INameable
    {
        float WorkTime { get; }
        ushort ItemIndex { get; }
        Dictionary<string, IRoamingJobObjectiveAction> ActionCallbacks { get; }
        string ObjectiveCategory { get; }

        void DoWork(Colony colony, RoamingJobState state);
    }

    public interface IRoamingJobObjectiveAction : INameable
    {
        float TimeToPreformAction { get; }
        string AudoKey { get; }
        ushort ObjectiveLoadEmptyIcon { get; }
        ushort PreformAction(Colony colony, RoamingJobState state);
    }
}


text:
import sys
import errno
import socket
import logging
import platform

# Define Constants
VERSION = '1.2.4'
SERVER_NAME = socket.gethostname()
SERVER_SOFTWARE = 'Rocket %s' % VERSION
HTTP_SERVER_SOFTWARE = '%s Python/%s' % (SERVER_SOFTWARE, sys.version.split(' ')[0])
BUF_SIZE = 16384
SOCKET_TIMEOUT = 1 # in secs
THREAD_STOP_CHECK_INTERVAL = 1 # in secs, How often should threads check for a server stop message?
IS_JYTHON = platform.system() == 'Java' # Handle special cases for Jython
IGNORE_ERRORS_ON_CLOSE = set([errno.ECONNABORTED, errno.ECONNRESET])
DEFAULT_LISTEN_QUEUE_SIZE = 5
DEFAULT_MIN_THREADS = 10
DEFAULT_MAX_THREADS = 0
DEFAULTS = dict(LISTEN_QUEUE_SIZE = DEFAULT_LISTEN_QUEUE_SIZE,
                MIN_THREADS = DEFAULT_MIN_THREADS,
                MAX_THREADS = DEFAULT_MAX_THREADS)

PY3K = sys.version_info[0] > 2

class NullHandler(logging.Handler):
    "A Logging handler to prevent library errors."
    def emit(self, record):
        pass

if PY3K:
    def b(val):
        """ Convert string/unicode/bytes literals into bytes.  This allows for
        the same code to run on Python 2.x and 3.x. """
        if isinstance(val, str):
            return val.encode()
        else:
            return val

    def u(val, encoding="us-ascii"):
        """ Convert bytes into string/unicode.  This allows for the
        same code to run on Python 2.x and 3.x. """
        if isinstance(val, bytes):
            return val.decode(encoding)
        else:
            return val

else:
    def b(val):
        """ Convert string/unicode/bytes literals into bytes.  This allows for
        the same code to run on Python 2.x and 3.x. """
        if isinstance(val, unicode):
            return val.encode()
        else:
            return val

    def u(val, encoding="us-ascii"):
        """ Convert bytes into string/unicode.  This allows for the
        same code to run on Python 2.x and 3.x. """
        if isinstance(val, str):
            return val.decode(encoding)
        else:
            return val

# Import Package Modules
from .main import Rocket, CherryPyWSGIServer

__all__ = ['VERSION', 'SERVER_SOFTWARE', 'HTTP_SERVER_SOFTWARE', 'BUF_SIZE',
           'IS_JYTHON', 'IGNORE_ERRORS_ON_CLOSE', 'DEFAULTS', 'PY3K', 'b', 'u',
           'Rocket', 'CherryPyWSGIServer', 'SERVER_NAME', 'NullHandler']


text:
<video
    id="0"
    class="sublime"
    poster="{{ item.featured_image|imageSize(0) }}"
    title="{{ item.name }}"
    width="{{ item.width }}" height="{{ item.height }}"
    data-sharing-url="http://trailernerd.com{{ url(item) }}"
    data-sharing-title="{{ item.name }}"
    data-sharing-text="{{ item.name }} from TrailerNerd.com"
    data-sharing-twitter-text="{{ item.name }} from TrailerNerd.com -"
    data-embed-type="auto"
    data-uid="0"
    data-autoresize="fit"
    preload="none"
    >
  <source src="{{ item.hd_video_url }}" data-quality="hd" />
  <source src="{{ item.sd_video_url }}" />
  <source src="{{ item.mobile_video_url }}" />
</video>


text:
[Steam](https://github.com/epistrephein/Steam) is a minimal and responsive theme for [Ghost](http://ghost.org/), forked from [Vapor](https://github.com/sethlilly/Vapor).

It features a clean and essential style with single column layout, beautiful typography, two colors, customizable partials and some nice javascript enhancements.

![Steam showcase](assets/screenshots/showcase-responsive.jpg)

## Installation
Clone the repository in the `/content/themes` folder of Ghost or upload the [latest release zip](https://github.com/epistrephein/Steam/releases/latest) from the settings. Restart Ghost and choose Steam in the design pane.

    $ git clone https://github.com/epistrephein/Steam.git

## Customization

#### Change the theme color
By default Steam uses a flat green theme color. The css for the colors are in a separate partial for easy customization: just edit `partials/theme-colors.hbs`, replacing `#33cc99` with your light shade and `#178b6b` with your dark shade.

Previous versions of Steam included premade colors partials that could just be turned on and off. These have since been removed for simplicity, so here are the values that were used if you want to keep your colors the way they were.

| Color  | Light     | Dark      |
|--------|-----------|-----------|
| Green  | `#33cc99` | `#178b6b` |
| Blue   | `#3498db` | `#2079b4` |
| Orange | `#ff9d00` | `#d88500` |
| Red    | `#f05948` | `#c62310` |

#### Customize the social icons
Facebook and Twitter icons in the footer are automatically displayed if defined in the general settings of Ghost.

If you want to add custom icons and links, duplicate any of them outside of the conditional tags and replace the url and the icon using the [Font Awesome list](http://fontawesome.io/icons/), e.g. to add a GitHub icon

```html
<a href="https://github.com/username" target="_blank" rel="noopener" title="GitHub"><i class="fa fa-2x fa-fw fa-github"></i> <span class="hidden">GitHub</span></a>
```

If you don't want the social icons section, replace `{{> footer-social}}` with `{{!> footer-social}}` in `default.hbs`.

#### Customize the blog signature
Replace the text, email address and author name in the file `partials/footer-author.hbs`.
To remove it, replace `{{> footer-author}}` with `{{!> footer-author}}` in `default.hbs`.

#### Hide post author section
If you don't want to show the author section (which is profile picture, bio, website and location) at the bottom of posts, replace `{{> post-author}}` with `{{!> post-author}}` in `post.hbs`.

#### Activate the comments
Replace `{{!> disqus}}` with `{{> disqus}}` in `post.hbs` and in `page.hbs` (if you want them in static pages too), then add your Disqus ID in `partials/disqus.hbs`.

#### Add Twitter, Google Webmaster and Facebook meta
Replace `{{!> meta}}` with `{{> meta}}` in `default.hbs`, then customize the content of `partials/meta.hbs`.

#### Activate Google Analytics
After you've created your Google Analytics account, change `{{!> google-analytics}}` to `{{> google-analytics}}` in `default.hbs`, ensuring to replace `YOUR_TRACKING_CODE` with your actual tracking code.

#### Custom favicon and apple-touch-icon
To customize the favicon and/or apple-touch-icon of your blog replace `favicon.ico`, the 16x16 and 32x32 `favicon.png` and the 180x180 `appletouchicon.png` in `/assets/img/`.

#### JavaScript
##### Smooth Scroll
Steam features [Smooth Scroll](https://github.com/cferdinandi/smooth-scroll) for nice scrolling animations. The default settings are in `js/steam.js`

```javascript
smoothScroll.init({
    speed: 800,
    easing: 'easeInOutCubic',
    updateURL: false,
    offset: 125,
});
```

Smooth Scroll is automatically injected in footnotes refs and backrefs when created via their markdown syntax.

```md
This is the body of the post with a footnote ref[ˆ1] somewhere.

[^1]: End of the post with the footnote text.
```

##### highlight.js
Steam also features [highlight.js](https://highlightjs.org) for syntax highlighting: you can disable it by removing the line

```javascript
hljs.initHighlightingOnLoad();
```

in `js/steam.js`

You can force a code block into a specific language highlighting by appending the lang name, e.g.:

    ```ruby
    puts "Hello, World!"
    ```

If you want to suppress the highlighting for a particular code block, you can use `nohighlight`:

    ```nohighlight
    $ git clone https://github.com/epistrephein/Steam.git
    ```

## Contributing
Bug reports and pull requests are welcome on [GitHub](https://github.com/epistrephein/Steam).

This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Code of Conduct](CODE_OF_CONDUCT.md).

You can contribute changes by forking the project and submitting a pull request. To get started:

1. Fork the repo
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new pull request

## License
This project is released under the terms of the MIT license. See [LICENSE](LICENSE) for further details.


text:
Buildpack Testrunner
=====================

#### This project has moved to https://github.com/heroku/heroku-buildpack-testrunner


text:
void sequential (int, int, int *);

#endif


text:
<?php

namespace Sylius\Component\Translation\Provider;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class LocaleProvider implements LocaleProviderInterface
{
    /**
     * @var string
     */
    private $currentLocale;

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

    /**
     * @param string $currentLocale
     * @param string $fallbackLocale
     */
    public function __construct($currentLocale, $fallbackLocale)
    {
        $this->currentLocale = $currentLocale;
        $this->fallbackLocale = $fallbackLocale;
    }

    /**
     * {@inheritdoc}
     */
    public function getCurrentLocale()
    {
        return $this->currentLocale;
    }

    /**
     * {@inheritdoc}
     */
    public function getFallbackLocale()
    {
        return $this->fallbackLocale;
    }
}


text:
require 'spec_helper'

describe VersionTester do
  before do
    @tester = Tester.new(example.metadata[:full_description])
    @source = @tester.tmpdir
    Tester.write_files(@source,
                        "same.txt" => "aa",
                        "changed.txt" => "aa",
                        "changed_size.txt" => "aa",
                        "missing.txt" => "aa")
    @metadata_file = File.join(@source, "test.json")
    KiCommand.new.execute(
        ["version-build",
         "--version-id", "my/component/23",
         "-f", @metadata_file,
         "-i", @source,
         "*"
        ])
  end

  after do
    @tester.after
  end

  it "should call supplied block when there are issues" do
    Tester.write_files(@source, "changed.txt" => "bb", "changed_size.txt" => "aaa")
    FileUtils.rm(File.join(@source, "missing.txt"))
    index = 0
    issues = [["wrong hash", "changed.txt"], ["wrong size", "changed_size.txt"], ["missing", "missing.txt"]]
    VersionTester.new.test_version(Version.create_version(@metadata_file, @source)) do |issue, version, file|
      [issue, file].should eq(issues[index])
       index+=1
    end
  end
end

describe VersionImporter do
  it "should warn about not supported arguments" do
    lambda{VersionImporter.new.import()}.should raise_error("Not supported: '[]'")
  end
end


text: Rails.application.config.filter_parameters += %i[password password_digest remember_token]


text:
package shootout;

import java.lang.management.ThreadMXBean;
import java.lang.management.ManagementFactory;

public class Timer
{
	ThreadMXBean bean = ManagementFactory.getThreadMXBean();

	long startRealTime;
	long startCpuTime;
	long startUserTime;
	long startSystemTime;
	long endRealTime;
	long endCpuTime;
	long endUserTime;
	long endSystemTime;

	public void start()
	{
		startRealTime = System.nanoTime();
		startCpuTime = _getCpuTime();
		startUserTime = _getUserTime();
		startSystemTime = _getSystemTime();
	}

	public void stop()
	{
		endRealTime = System.nanoTime();
		endCpuTime = _getCpuTime();
		endUserTime = _getUserTime();
		endSystemTime = _getSystemTime();
	}

	public long getRealTime()
	{
		return (endRealTime - startRealTime) / 1000000;
	}

	public long getCpuTime()
	{
		return (endCpuTime - startCpuTime) / 1000000;
	}

	public long getUserTime()
	{
		return (endUserTime - startUserTime) / 1000000;
	}

	public long getSystemTime()
	{
		return (endSystemTime - startSystemTime) / 1000000;
	}

	private long _getCpuTime()
	{
		return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadCpuTime() : 0L;
	}

	private long _getUserTime()
	{
		return bean.isCurrentThreadCpuTimeSupported() ? bean.getCurrentThreadUserTime() : 0L;
	}

	private long _getSystemTime()
	{
		return bean.isCurrentThreadCpuTimeSupported() ?	(bean.getCurrentThreadCpuTime() - bean.getCurrentThreadUserTime()) : 0L;
	}
}


text:
#include "rgbpickertool.h"

#include "tvectorimage.h"
#include "ttoonzimage.h"
#include "tools/cursors.h"
#include "tcolorstyles.h"
#include "toonz/cleanupcolorstyles.h"
#include "trasterimage.h"
#include "tgl.h"
#include "tenv.h"
#include "tstroke.h"

#include "toonz/palettecontroller.h"
#include "toonz/tpalettehandle.h"
#include "toonz/tscenehandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/stage2.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/preferences.h"

#include "toonzqt/icongenerator.h"
#include "toonzqt/dvdialog.h"

#include "tools/toolhandle.h"
#include "tools/stylepicker.h"
#include "tools/toolutils.h"
#include "tools/RGBpicker.h"

//iwsw  commented out temporarily
//#include "toonzqt/ghibli_3dlut_util.h"

#define NORMAL_PICK L"Normal"
#define RECT_PICK L"Rectangular"
#define FREEHAND_PICK L"Freehand"
#define POLYLINE_PICK L"Polyline"

TEnv::StringVar PickVectorType("InknpaintPickVectorType", "Normal");
TEnv::IntVar PickPassive("InknpaintPickPassive", 0);

namespace RGBPicker
{

//============================================================
// Pick RGB Tool
//------------------------------------------------------------

class UndoPickRGBM : public TUndo
{
	TPaletteP m_palette;
	int m_styleId;
	int m_styleParamIndex;
	TPixel32 m_oldValue, m_newValue;
	TXshSimpleLevelP m_level;
	bool m_colorAutoApplyEnabled;

public:
	UndoPickRGBM(TPalette *palette, int styleId, const TPixel32 newValue, const TXshSimpleLevelP &level)
		: m_palette(palette), m_styleId(styleId), m_newValue(newValue), m_level(level), m_colorAutoApplyEnabled(true)
	{
		PaletteController *controller = TTool::getApplication()->getPaletteController();
		m_colorAutoApplyEnabled = controller->isColorAutoApplyEnabled();
		m_styleParamIndex = controller->getCurrentPalette()->getStyleParamIndex();
		if (m_colorAutoApplyEnabled) {
			TColorStyle *cs = m_palette->getStyle(m_styleId);
			if (0 <= m_styleParamIndex && m_styleParamIndex < cs->getColorParamCount())
				m_oldValue = cs->getColorParamValue(m_styleParamIndex);
			else
				m_oldValue = cs->getMainColor();
		} else {
			m_oldValue = controller->getColorSample();
		}
	}

	void setColor(const TPixel32 &color) const
	{
		PaletteController *controller = TTool::getApplication()->getPaletteController();
		if (m_colorAutoApplyEnabled) {
			TColorStyle *cs = m_palette->getStyle(m_styleId);
			if (0 <= m_styleParamIndex && m_styleParamIndex < cs->getColorParamCount())
				cs->setColorParamValue(m_styleParamIndex, color);
			else
				cs->setMainColor(color);
			cs->invalidateIcon();
			controller->getCurrentPalette()->notifyColorStyleChanged();
			updateLevel();
		} else {
			controller->setColorSample(color);
		}
	}

	void undo() const
	{
		setColor(m_oldValue);
	}

	void redo() const
	{
		setColor(m_newValue);
	}

	int getSize() const { return sizeof(*this); }

	QString getHistoryString()
	{
		return QObject::tr("RGB Picker (R%1, G%2, B%3)")
			.arg(QString::number((int)m_newValue.r))
			.arg(QString::number((int)m_newValue.g))
			.arg(QString::number((int)m_newValue.b));
	}

private:
	void updateLevel() const
	{
		std::vector<TFrameId> fids;
		if (!m_level)
			return;
		m_level->getFids(fids);
		unsigned int i;
		for (i = 0; i < fids.size(); i++)
			IconGenerator::instance()->invalidate(m_level.getPointer(), fids[i]);
		IconGenerator::instance()->invalidateSceneIcon();
		TTool::getApplication()->getCurrentScene()->notifySceneChanged();
	}
};

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

void setCurrentColor(const TPixel32 &color)
{
	PaletteController *controller = TTool::getApplication()->getPaletteController();
	TPaletteHandle *ph = controller->getCurrentPalette();

	TColorStyle *cs = ph->getStyle();
	if (!cs)
		return;

	if (controller->isColorAutoApplyEnabled()) {
		TCleanupStyle *ccs = dynamic_cast<TCleanupStyle *>(cs);
		if (ccs)
			ccs->setCanUpdate(true);

		int index = ph->getStyleParamIndex();
		if (0 <= index && index < cs->getColorParamCount())
			cs->setColorParamValue(index, color);
		else
			cs->setMainColor(color);

		cs->invalidateIcon();
		ph->notifyColorStyleChanged();

		// per le palette animate
		int styleIndex = ph->getStyleIndex();
		TPalette *palette = ph->getPalette();
		if (palette && palette->isKeyframe(styleIndex, palette->getFrame()))
			palette->setKeyframe(styleIndex, palette->getFrame());

		if (ccs)
			ccs->setCanUpdate(false);
	} else
		controller->setColorSample(color);
}

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

void setCurrentColorWithUndo(const TPixel32 &color)
{
	TTool::Application *app = TTool::getApplication();
	TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
	int styleId = ph->getStyleIndex();
	TPalette *palette = ph->getPalette();
	TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
	if (palette)
		TUndoManager::manager()->add(new UndoPickRGBM(palette, styleId, color, level));

	setCurrentColor(color);

	if (level) {
		std::vector<TFrameId> fids;
		level->getFids(fids);
		invalidateIcons(level, fids);
	}
}

} // namespace RGBPicker

using namespace RGBPicker;

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

RGBPickerTool::RGBPickerTool()
	: TTool("T_RGBPicker"), m_currentStyleId(0), m_pickType("Type:"), m_drawingTrack(), m_workingTrack(), m_firstDrawingPos(), m_firstWorkingPos(), m_mousePosition(), m_thick(0.5), m_stroke(0), m_firstStroke(0), m_makePick(false), m_firstTime(true), m_passivePick("Passive Pick", false), m_toolOptionsBox(0)
{
	bind(TTool::CommonLevels);
	m_prop.bind(m_pickType);
	m_pickType.addValue(NORMAL_PICK);
	m_pickType.addValue(RECT_PICK);
	m_pickType.addValue(FREEHAND_PICK);
	m_pickType.addValue(POLYLINE_PICK);
	m_pickType.setId("Type");

	m_prop.bind(m_passivePick);
	m_passivePick.setId("PassivePick");
}

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

void RGBPickerTool::setToolOptionsBox(RGBPickerToolOptionsBox *toolOptionsBox)
{
	m_toolOptionsBox.push_back(toolOptionsBox);
}

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

void RGBPickerTool::updateTranslation()
{
	m_pickType.setQStringName(tr("Type:"));
	m_passivePick.setQStringName(tr("Passive Pick"));
}

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

// Used to notify and set the currentColor outside the draw() methods:
// using special style there was a conflict between the draw() methods of the tool
// and the genaration of the icon inside the style editor (makeIcon()) which use
// another glContext

void RGBPickerTool::onImageChanged()
{
	if (m_currentStyleId != 0 && m_makePick &&
		(m_pickType.getValue() == POLYLINE_PICK || m_pickType.getValue() == RECT_PICK)) {
		TTool::Application *app = TTool::getApplication();
		TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
		int styleId = ph->getStyleIndex();
		TPalette *palette = ph->getPalette();
		TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
		if (palette)
			TUndoManager::manager()->add(new UndoPickRGBM(palette, styleId, m_currentValue, level));
		setCurrentColor(m_currentValue);
		if (level) {
			std::vector<TFrameId> fids;
			level->getFids(fids);
			invalidateIcons(level, fids);
		}
	}
	m_makePick = false;
}

void RGBPickerTool::draw()
{
	double pixelSize2 = getPixelSize() * getPixelSize();
	m_thick = sqrt(pixelSize2) / 2.0;
	if (m_makePick) {
		if (m_currentStyleId != 0) {
			//Il pick in modalita' polyline e rectangular deve essere fatto soltanto dopo aver cancellato il
			//"disegno" della polyline altrimenti alcuni pixels neri delle spezzate che la
			//compongono vengono presi in considerazione nel calcolo del "colore medio"
			if (m_pickType.getValue() == POLYLINE_PICK && m_drawingPolyline.empty())
				doPolylinePick();
			else if (m_pickType.getValue() == RECT_PICK && m_drawingRect.isEmpty())
				pickRect();
		}
		return;
	}
	if (m_pickType.getValue() == RECT_PICK && !m_makePick) {
		TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg ? TPixel32::White : TPixel32::Red;
		ToolUtils::drawRect(m_drawingRect, color, 0x3F33, true);
	}
	if (m_pickType.getValue() == POLYLINE_PICK && !m_drawingPolyline.empty()) {
		TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg ? TPixel32::White : TPixel32::Black;
		tglColor(color);
		tglDrawCircle(m_drawingPolyline[0], 2);
		glBegin(GL_LINE_STRIP);
		for (UINT i = 0; i < m_drawingPolyline.size(); i++)
			tglVertex(m_drawingPolyline[i]);
		tglVertex(m_mousePosition);
		glEnd();
	}
}

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

void RGBPickerTool::leftButtonDown(const TPointD &pos, const TMouseEvent &e)
{
	TTool::Application *app = TTool::getApplication();
	TPaletteHandle *pltHandle = app->getPaletteController()->getCurrentPalette();
	m_currentStyleId = pltHandle->getStyleIndex();
	if (m_currentStyleId == 0)
		return;

	TColorStyle *colorStyle = pltHandle->getStyle();

	if (colorStyle)
		m_oldValue = colorStyle->getMainColor();

	if (m_pickType.getValue() == RECT_PICK) {
		m_selectingRect.x0 = e.m_pos.x;
		m_selectingRect.y0 = e.m_pos.y;
		m_selectingRect.x1 = e.m_pos.x;
		m_selectingRect.y1 = e.m_pos.y;
		m_drawingRect.x0 = pos.x;
		m_drawingRect.y0 = pos.y;
		m_drawingRect.x1 = pos.x;
		m_drawingRect.y1 = pos.y;
		invalidate();
		return;
	} else if (m_pickType.getValue() == FREEHAND_PICK) {
		startFreehand(pos, convert(e.m_pos));
		return;
	} else if (m_pickType.getValue() == POLYLINE_PICK) {
		addPointPolyline(pos, convert(e.m_pos));
		return;
	} else {
		pick(e.m_pos);
	}
}

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

void RGBPickerTool::leftButtonDrag(const TPointD &pos, const TMouseEvent &e)
{
	if (m_currentStyleId == 0)
		return;
	if (m_pickType.getValue() == RECT_PICK) {
		m_selectingRect.x1 = e.m_pos.x;
		m_selectingRect.y1 = e.m_pos.y;
		m_drawingRect.x1 = pos.x;
		m_drawingRect.y1 = pos.y;
		invalidate();
		return;
	} else if (m_pickType.getValue() == FREEHAND_PICK)
		freehandDrag(pos, convert(e.m_pos));
}

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

void RGBPickerTool::leftButtonUp(const TPointD &pos, const TMouseEvent &)
{
	if (m_currentStyleId == 0)
		return;
	if (m_pickType.getValue() == RECT_PICK) {
		m_makePick = true;
		m_drawingRect.empty();
	}
	if (m_pickType.getValue() == FREEHAND_PICK) {
		closeFreehand();
		if (m_currentStyleId != 0)
			pickStroke();
		delete m_stroke;
		m_stroke = 0;
	}
	invalidate();
}

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

void RGBPickerTool::leftButtonDoubleClick(const TPointD &pos, const TMouseEvent &e)
{
	if (m_currentStyleId == 0)
		return;
	if (m_pickType.getValue() == POLYLINE_PICK) {
		closePolyline(pos, convert(e.m_pos));
		std::vector<TThickPoint> strokePoints;
		for (UINT i = 0; i < m_workingPolyline.size() - 1; i++) {
			strokePoints.push_back(TThickPoint(m_workingPolyline[i], 1));
			strokePoints.push_back(TThickPoint(0.5 * (m_workingPolyline[i] + m_workingPolyline[i + 1]), 1));
		}
		strokePoints.push_back(TThickPoint(m_workingPolyline.back(), 1));
		m_drawingPolyline.clear();
		m_workingPolyline.clear();
		m_stroke = new TStroke(strokePoints);
		m_makePick = true;
		invalidate();
	}
}

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

void RGBPickerTool::mouseMove(const TPointD &pos, const TMouseEvent &e)
{
	/*--- Passiveに色を拾う機能 ---*/
	if (m_passivePick.getValue() == true) {
		TImageP image = TImageP(getImage(false));
		if (image) {
			TRectD area = TRectD(e.m_pos.x, e.m_pos.y, e.m_pos.x, e.m_pos.y);
			//TRectD area=TRectD(e.m_pos.x-1,e.m_pos.y-1,e.m_pos.x+1,e.m_pos.y+1);
			StylePicker picker(image);

			//iwsw commented out temporarily
			//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
			//	m_viewer->get3DLutUtil()->bindFBO();

			TPixel32 pix = picker.pickColor(area);

			//iwsw commented out temporarily
			//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
			//	m_viewer->get3DLutUtil()->releaseFBO();

			QColor col((int)pix.r, (int)pix.g, (int)pix.b);

			PaletteController *controller = TTool::getApplication()->getPaletteController();
			controller->notifyColorPassivePicked(col);
			//for (int i = 0; i<(int)m_toolOptionsBox.size(); i++)
			//{
			//	if (m_toolOptionsBox[i]->isVisible())
			//		m_toolOptionsBox[i]->updateRealTimePickLabel(col);
			//}
		}
	}
	if (m_pickType.getValue() == POLYLINE_PICK && !m_drawingPolyline.empty()) {
		m_mousePosition = pos;
		invalidate();
	}
}

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

void RGBPickerTool::pick(TPoint pos)
{
	TImageP image = TImageP(getImage(false));

	TTool::Application *app = TTool::getApplication();
	TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
	int styleId = ph->getStyleIndex();
	TPalette *palette = ph->getPalette();
	if (!palette)
		return;

	TRectD area = TRectD(pos.x - 1, pos.y - 1, pos.x + 1, pos.y + 1);
	StylePicker picker(image, palette);

	//iwsw commented out temporarily
	//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
	//	m_viewer->get3DLutUtil()->bindFBO();

	m_currentValue = picker.pickColor(area);

	//iwsw commented out temporarily
	//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
	//	m_viewer->get3DLutUtil()->releaseFBO();

	TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
	UndoPickRGBM *cmd = new UndoPickRGBM(palette, styleId, m_currentValue, level);
	TUndoManager::manager()->add(cmd);
	cmd->redo();
	/*
    setCurrentColor(m_currentValue);
    if(level)
    {
      vector<TFrameId> fids;
      level->getFids(fids);
      invalidateIcons(level,fids);
    }
    */
}
//---------------------------------------------------------

void RGBPickerTool::pickRect()
{
	TImageP image = TImageP(getImage(false));

	TTool::Application *app = TTool::getApplication();
	TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
	int styleId = ph->getStyleIndex();
	TPalette *palette = ph->getPalette();
	TRectD area = m_selectingRect;
	if (!palette)
		return;
	if (m_selectingRect.x0 > m_selectingRect.x1) {
		area.x1 = m_selectingRect.x0;
		area.x0 = m_selectingRect.x1;
	}
	if (m_selectingRect.y0 > m_selectingRect.y1) {
		area.y1 = m_selectingRect.y0;
		area.y0 = m_selectingRect.y1;
	}
	m_selectingRect.empty();
	if (area.getLx() <= 1 || area.getLy() <= 1)
		return;
	StylePicker picker(image, palette);

	//iwsw commented out temporarily
	//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
	//	m_viewer->get3DLutUtil()->bindFBO();

	m_currentValue = picker.pickColor(area);

	//iwsw commented out temporarily
	//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
	//	m_viewer->get3DLutUtil()->releaseFBO();
}

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

void RGBPickerTool::pickStroke()
{
	TImageP image = TImageP(getImage(false));

	TTool::Application *app = TTool::getApplication();
	TPaletteHandle *ph = app->getPaletteController()->getCurrentPalette();
	int styleId = ph->getStyleIndex();
	TPalette *palette = ph->getPalette();
	if (!palette)
		return;

	StylePicker picker(image, palette);
	TStroke *stroke = new TStroke(*m_stroke);

	//iwsw commented out temporarily
	//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
	//	m_viewer->get3DLutUtil()->bindFBO();

	m_currentValue = picker.pickColor(stroke);

	//iwsw commented out temporarily
	//if (m_viewer->get3DLutUtil() && Preferences::instance()->isDoColorCorrectionByUsing3DLutEnabled())
	//	m_viewer->get3DLutUtil()->releaseFBO();

	if (!(m_pickType.getValue() == POLYLINE_PICK)) {
		TXshSimpleLevel *level = app->getCurrentLevel()->getSimpleLevel();
		TUndoManager::manager()->add(new UndoPickRGBM(palette, styleId, m_currentValue, level));
		setCurrentColor(m_currentValue);
		if (level) {
			std::vector<TFrameId> fids;
			level->getFids(fids);
			invalidateIcons(level, fids);
		}
	}
}

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

bool RGBPickerTool::onPropertyChanged(std::string propertyName)
{
	if (propertyName == m_pickType.getName())
		PickVectorType = toString(m_pickType.getValue());
	else if (propertyName == m_passivePick.getName())
		PickPassive = m_passivePick.getValue();
	return true;
}

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

void RGBPickerTool::onActivate()
{
	if (m_firstTime) {
		m_pickType.setValue(toWideString((PickVectorType.getValue())));
		m_passivePick.setValue(PickPassive ? 1 : 0);
		m_firstTime = false;
	}
}

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

TPropertyGroup *RGBPickerTool::getProperties(int targetType) { return &m_prop; }

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

int RGBPickerTool::getCursorId() const
{
	int currentStyleId = getApplication()->getPaletteController()->getCurrentPalette()->getStyleIndex();
	if (currentStyleId == 0)
		return ToolCursor::ForbiddenCursor;
	if (ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg)
		return ToolCursor::PickerRGBWhite;
	else
		return ToolCursor::PickerRGB;
}

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

void RGBPickerTool::doPolylinePick()
{
	if (m_stroke && m_pickType.getValue() == POLYLINE_PICK) {
		pickStroke();
		delete m_stroke;
		m_stroke = 0;
	}
}

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

//!Viene aggiunto \b pos a \b m_track e disegnato il primo pezzetto del lazzo. Viene inizializzato \b m_firstPos
void RGBPickerTool::startFreehand(const TPointD &drawingPos, const TPointD &workingPos)
{
	m_drawingTrack.clear();
	m_workingTrack.clear();
	m_firstDrawingPos = drawingPos;
	m_firstWorkingPos = workingPos;
	double pixelSize2 = getPixelSize() * getPixelSize();
	m_drawingTrack.add(TThickPoint(drawingPos, m_thick), pixelSize2);
	m_workingTrack.add(TThickPoint(workingPos, m_thick), pixelSize2);
#if defined(MACOSX)
//m_viewer->prepareForegroundDrawing();
#endif
	TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg ? TPixel32::White : TPixel32::Black;
	tglColor(color);
	getViewer()->startForegroundDrawing();
	glPushMatrix();
	m_drawingTrack.drawLastFragments();
	glPopMatrix();
	getViewer()->endForegroundDrawing();
}

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

//!Viene aggiunto \b pos a \b m_track e disegnato un altro pezzetto del lazzo.
void RGBPickerTool::freehandDrag(const TPointD &drawingPos, const TPointD &workingPos)
{
#if defined(MACOSX)
//getViewer()->enableRedraw(false);
#endif

	getViewer()->startForegroundDrawing();
	TPixel color = ToonzCheck::instance()->getChecks() & ToonzCheck::eBlackBg ? TPixel32::White : TPixel32::Black;
	tglColor(color);
	glPushMatrix();
	tglMultMatrix(getMatrix());
	double pixelSize2 = getPixelSize() * getPixelSize();
	m_workingTrack.add(TThickPoint(workingPos, m_thick), pixelSize2);
	m_drawingTrack.add(TThickPoint(drawingPos, m_thick), pixelSize2);
	m_drawingTrack.drawLastFragments();
	glPopMatrix();
	getViewer()->endForegroundDrawing();
}

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

//!Viene chiuso il lazzo (si aggiunge l'ultimo punto ad m_track) e viene creato lo stroke rappresentante il lazzo.
void RGBPickerTool::closeFreehand()
{
#if defined(MACOSX)
//getViewer()->enableRedraw(true);
#endif
	if (m_drawingTrack.isEmpty() || m_workingTrack.isEmpty())
		return;
	double pixelSize2 = getPixelSize() * getPixelSize();
	m_drawingTrack.add(TThickPoint(m_firstDrawingPos, m_thick), pixelSize2);
	m_workingTrack.add(TThickPoint(m_firstWorkingPos, m_thick), pixelSize2);
	m_workingTrack.filterPoints();
	double error = (30.0 / 11) * sqrt(pixelSize2);
	m_stroke = m_workingTrack.makeStroke(error);
	m_stroke->setStyle(1);
}

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

//!Viene aggiunto un punto al vettore m_polyline.
void RGBPickerTool::addPointPolyline(const TPointD &drawingPos, const TPointD &workingPos)
{
	m_mousePosition = drawingPos;
	/*---drawingPosは中心からの座標 workingPosは画面左下からの座標---*/
	m_drawingPolyline.push_back(drawingPos);
	m_workingPolyline.push_back(workingPos);
}

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

//!Agginge l'ultimo pos a \b m_polyline e chiude la spezzata (aggiunge \b m_polyline.front() alla fine del vettore)
void RGBPickerTool::closePolyline(const TPointD &drawingPos, const TPointD &workingPos)
{
	if (m_drawingPolyline.size() <= 1 || m_workingPolyline.size() <= 1)
		return;
	if (m_drawingPolyline.back() != drawingPos)
		m_drawingPolyline.push_back(drawingPos);
	if (m_workingPolyline.back() != workingPos)
		m_workingPolyline.push_back(workingPos);
	if (m_drawingPolyline.back() != m_drawingPolyline.front())
		m_drawingPolyline.push_back(m_drawingPolyline.front());
	if (m_workingPolyline.back() != m_workingPolyline.front())
		m_workingPolyline.push_back(m_workingPolyline.front());
}

//---------------------------------------------------------
/*! Flipbook上でPassive Pickを有効にする
*/
void RGBPickerTool::showFlipPickedColor(const TPixel32 &pix)
{
	if (m_passivePick.getValue()) {
		QColor col((int)pix.r, (int)pix.g, (int)pix.b);
		PaletteController *controller = TTool::getApplication()->getPaletteController();
		controller->notifyColorPassivePicked(col);
	}
}

RGBPickerTool RGBpicktool;

//TTool *getPickRGBMTool() {return &pickRBGMTool;}


text:
package driver

import (
	"sort"
	"sync"
)

var driversMu sync.Mutex
var drivers = make(map[string]Driver)

// RegisterDriver register a driver so it can be created from its name. Drivers should
// call this from an init() function so that they registers themselves on
// import
func RegisterDriver(name string, driver Driver) {
	driversMu.Lock()
	defer driversMu.Unlock()
	if driver == nil {
		panic("driver: Register driver is nil")
	}
	if _, dup := drivers[name]; dup {
		panic("sql: Register called twice for driver " + name)
	}
	drivers[name] = driver
}

// GetDriver retrieves a registered driver by name
func GetDriver(name string) Driver {
	driversMu.Lock()
	defer driversMu.Unlock()
	driver := drivers[name]
	return driver
}

// Drivers returns a sorted list of the names of the registered drivers.
func Drivers() []string {
	driversMu.Lock()
	defer driversMu.Unlock()
	var list []string
	for name := range drivers {
		list = append(list, name)
	}
	sort.Strings(list)
	return list
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xmlns="http://java.sun.com/xml/ns/javaee"
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
		 version="2.5">

	<display-name>Synapse Web Services</display-name>

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>

	<!-- The context params that read by ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/shared-context.xml</param-value>
	</context-param>

	<!-- This is the filter to redirect http:// to https:// -->
	<filter>
		<filter-name>httpToHttpsFilter</filter-name>
		<filter-class>org.sagebionetworks.repo.web.filter.HttpToHttpsRedirectFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>httpToHttpsFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- This must remain the top-most filter in the filter chain.
	 It is our last chance to capture and log unexpected exceptions.
	 Without it, users could see errors that never make it into our logs.
	 See PLFM-3205 & PLFM-3206  -->
	<filter>
		<filter-name>unexpectedExceptionFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>unexpectedExceptionFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- This filter ensures all requests are within the size limit.
	See PLFM-4761  -->
	<filter>
		<filter-name>requestSizeThrottleFilter</filter-name>
		<filter-class>org.sagebionetworks.repo.web.filter.RequestSizeThrottleFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>requestSizeThrottleFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- This listener will load other application context file in addition
		to springweb-servlet.xml -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Some browsers do not support PUT and DELETE methods, this filter will
		examine the form field parameter _method -->
	<filter>
		<filter-name>httpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>httpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- This filter will look for the session token as a cookie, if it finds
		it, the token will be added to the header of the request -->
	<filter>
		<filter-name>cookieFilter</filter-name>
		<filter-class>org.sagebionetworks.authutil.CookieSessionTokenFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>cookieFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>authFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>authFilter</filter-name>
		<url-pattern>/auth/v1/secretKey</url-pattern>
		<url-pattern>/auth/v1/personalAccessToken</url-pattern>
		<url-pattern>/auth/v1/personalAccessToken/*</url-pattern>
		<url-pattern>/auth/v1/oauth2/alias</url-pattern>
		<url-pattern>/auth/v1/oauth2/client/*</url-pattern>
		<url-pattern>/auth/v1/oauth2/consent</url-pattern>
		<url-pattern>/auth/v1/oauth2/consentcheck</url-pattern>
		<url-pattern>/auth/v1/oauth2/userinfo</url-pattern>
		<url-pattern>/auth/v1/oauth2/audit/*</url-pattern>
		<url-pattern>/repo/v1/*</url-pattern>
		<url-pattern>/file/v1/*</url-pattern>
	</filter-mapping>

	<!-- Filter that authenticate the administrative and migration services using basic auth -->
	<filter>
		<filter-name>adminServiceAuthFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>adminServiceAuthFilter</filter-name>
		<url-pattern>/repo/v1/admin/*</url-pattern>
		<url-pattern>/repo/v1/migration/*</url-pattern>
	</filter-mapping>

	<!-- This filter will look for the session token as a cookie, if it finds
    it, the token will be added to the header of the request -->
	<filter>
		<filter-name>simpleCORSFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>simpleCORSFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>dockerClientAuthFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>dockerClientAuthFilter</filter-name>
		<url-pattern>/docker/v1/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>acceptTermsOfUseFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<!-- This applies to all paths that authenticate a Synapse user -->
	<filter-mapping>
		<filter-name>acceptTermsOfUseFilter</filter-name>
		<url-pattern>/auth/v1/secretKey</url-pattern>
		<url-pattern>/auth/v1/oauth2/alias</url-pattern>
		<url-pattern>/auth/v1/oauth2/client/*</url-pattern>
		<url-pattern>/auth/v1/oauth2/consent</url-pattern>
		<url-pattern>/auth/v1/oauth2/consentcheck</url-pattern>
		<url-pattern>/auth/v1/oauth2/userinfo</url-pattern>
		<url-pattern>/auth/v1/oauth2/audit/*</url-pattern>
		<url-pattern>/repo/v1/*</url-pattern>
		<url-pattern>/file/v1/*</url-pattern>
		<url-pattern>/docker/v1/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>dockerRegistryAuthFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>dockerRegistryAuthFilter</filter-name>
		<url-pattern>/dockerRegistryListener/v1/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>userConcurrentConnectionThrottleFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>userConcurrentConnectionThrottleFilter</filter-name>
		<url-pattern>/repo/v1/*</url-pattern>
		<url-pattern>/file/v1/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>userRequestFrequencyThrottleFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>userRequestFrequencyThrottleFilter</filter-name>
		<url-pattern>/repo/v1/*</url-pattern>
		<url-pattern>/file/v1/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>userApiFrequencyThrottleFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>userApiFrequencyThrottleFilter</filter-name>
		<url-pattern>/repo/v1/*</url-pattern>
		<url-pattern>/file/v1/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>jsonpCallbackFilter</filter-name>
		<!-- This filter allows JSONP to be returned for methods that are already
			returning JSON -->
		<filter-class>org.sagebionetworks.repo.web.filter.JsonpCallbackFilter</filter-class>
		<init-param>
			<param-name>default_value</param-name>
			<param-value>false</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>jsonpCallbackFilter</filter-name>
		<!-- This filter should only be used on publicly accessible methods to
			minimize the risks of Cross-site request forgery (CSRF) associated with JSONP.
			Only add patterns that are public! -->

		<url-pattern>/repo/v1/userGroupHeaders/*</url-pattern>
		<!-- This is the uri for looking up teams by name fragment -->
		<url-pattern>/repo/v1/teams</url-pattern>
		<!-- This is the uri for looking up team members by name fragment -->
		<url-pattern>/repo/v1/teamMembers/*</url-pattern>
		<!-- This is the uri for looking up team member count by name fragment -->
		<url-pattern>/repo/v1/teamMembers/count/*</url-pattern>
	</filter-mapping>

	<!-- Rather than using multiple DispatcherServlet each with their own Spring
		context we are now using a singleton DispatcherServlet. See: PLFM-2530 -->
	<servlet>
		<servlet-name>singleton</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- These two parameters are required to register an interceptor with
			the org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.
			Without them the handler simply will not be used. jmhill 12/10/11 -->
		<init-param>
			<param-name>detectAllHandlerMappings</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>throwExceptionIfNoHandlerFound</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>singleton</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>HSTSFilter</filter-name>
		<filter-class>org.sagebionetworks.repo.web.filter.HSTSFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HSTSFilter</filter-name>
		<url-pattern>*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>cloudMailInAuthFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter>
		<filter-name>cloudMailInAcceptPlainTextFilter</filter-name>
		<filter-class>org.sagebionetworks.repo.web.filter.CloudMailInAcceptPlainTextFilter</filter-class>
	</filter>

	<filter>
		<filter-name>cloudMailInContentTypeFilter</filter-name>
		<filter-class>org.sagebionetworks.repo.web.filter.CloudMailInCharacterEncodingFilter</filter-class>
	</filter>

    <!--  Note we tried applying the filter to both /cloudMailInMessage and /cloudMailInAuthorization,
    but CloudMailIn doesn't seem to pass the BasicAuthentication credentials when it calls the latter
    service.   -->
	<filter-mapping>
		<filter-name>cloudMailInAuthFilter</filter-name>
		<url-pattern>/repo/v1/cloudMailInMessage/*</url-pattern>
	</filter-mapping>

	<filter-mapping>
		<filter-name>cloudMailInContentTypeFilter</filter-name>
		<url-pattern>/repo/v1/cloudMailInMessage/*</url-pattern>
	</filter-mapping>

	<filter-mapping>
		<filter-name>cloudMailInAcceptPlainTextFilter</filter-name>
		<url-pattern>/repo/v1/cloudMailInMessage/*</url-pattern>
		<url-pattern>/repo/v1/cloudMailInAuthorization/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>oauthClientAuthFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!-- Make sure the init-params are passed through the proxy to the bean -->
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>oauthClientAuthFilter</filter-name>
		<url-pattern>/auth/v1/oauth2/token</url-pattern>
		<url-pattern>/auth/v1/oauth2/token/*</url-pattern>
		<url-pattern>/auth/v1/oauth2/revoke</url-pattern>
	</filter-mapping>

	<!-- appends a new sessionId cookie to the response if the user did not provide one in their request -->
	<filter>
		<filter-name>sessionIdCookieSetterFilter</filter-name>
		<filter-class>org.sagebionetworks.repo.web.filter.SessionIdCookieSetterFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>sessionIdCookieSetterFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>


text:
namespace {

const int kRouteId = 0;
const int kAudioSessionId = 3;
const int kVideoSessionId = 5;
const int kRequestId1 = 10;
const int kRequestId2 = 20;
const int kRequestId3 = 30;
const int kRequestId4 = 40;

class MockMediaStreamDispatcherEventHandler
    : public MediaStreamDispatcherEventHandler,
      public base::SupportsWeakPtr<MockMediaStreamDispatcherEventHandler> {
 public:
  MockMediaStreamDispatcherEventHandler()
      : request_id_(-1),
        audio_failed(false),
        video_failed(false) {}

  virtual void OnStreamGenerated(
      int request_id,
      const std::string &label,
      const media_stream::StreamDeviceInfoArray& audio_device_array,
      const media_stream::StreamDeviceInfoArray& video_device_array) OVERRIDE {
    request_id_ = request_id;
    label_ = label;
  }

  virtual void OnStreamGenerationFailed(int request_id) OVERRIDE {
    request_id_ = request_id;
  }

  virtual void OnAudioDeviceFailed(const std::string& label,
                                   int index) OVERRIDE {
    audio_failed = true;
  }

  virtual void OnVideoDeviceFailed(const std::string& label,
                                   int index) OVERRIDE {
    video_failed = true;
  }

  virtual void OnDevicesEnumerated(
      int request_id,
      const media_stream::StreamDeviceInfoArray& device_array) OVERRIDE {
    request_id_ = request_id;
  }

  virtual void OnDevicesEnumerationFailed(int request_id) OVERRIDE {
    request_id_ = request_id;
  }

  virtual void OnDeviceOpened(
      int request_id,
      const std::string& label,
      const media_stream::StreamDeviceInfo& video_device) OVERRIDE {
    request_id_ = request_id;
    label_ = label;
  }

  virtual void OnDeviceOpenFailed(int request_id) OVERRIDE {
    request_id_ = request_id;
  }

  int request_id_;
  std::string label_;
  bool audio_failed;
  bool video_failed;

  DISALLOW_COPY_AND_ASSIGN(MockMediaStreamDispatcherEventHandler);
};

}  // namespace

TEST(MediaStreamDispatcherTest, BasicStream) {
  scoped_ptr<MediaStreamDispatcher> dispatcher(new MediaStreamDispatcher(NULL));
  scoped_ptr<MockMediaStreamDispatcherEventHandler>
      handler(new MockMediaStreamDispatcherEventHandler);
  media_stream::StreamOptions components(true, true);
  std::string security_origin;

  int ipc_request_id1 = dispatcher->next_ipc_id_;
  dispatcher->GenerateStream(kRequestId1, handler.get()->AsWeakPtr(),
                             components, security_origin);
  int ipc_request_id2 = dispatcher->next_ipc_id_;
  EXPECT_NE(ipc_request_id1, ipc_request_id2);
  dispatcher->GenerateStream(kRequestId2, handler.get()->AsWeakPtr(),
                             components, security_origin);
  EXPECT_EQ(dispatcher->requests_.size(), size_t(2));

  media_stream::StreamDeviceInfoArray audio_device_array(1);
  media_stream::StreamDeviceInfo audio_device_info;
  audio_device_info.name = "Microphone";
  audio_device_info.stream_type =
      content::MEDIA_STREAM_DEVICE_TYPE_AUDIO_CAPTURE;
  audio_device_info.session_id = kAudioSessionId;
  audio_device_array[0] = audio_device_info;

  media_stream::StreamDeviceInfoArray video_device_array(1);
  media_stream::StreamDeviceInfo video_device_info;
  video_device_info.name = "Camera";
  video_device_info.stream_type =
      content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE;
  video_device_info.session_id = kVideoSessionId;
  video_device_array[0] = video_device_info;

  // Complete the creation of stream1.
  std::string stream_label1 = std::string("stream1");
  dispatcher->OnMessageReceived(MediaStreamMsg_StreamGenerated(
      kRouteId, ipc_request_id1, stream_label1,
      audio_device_array, video_device_array));
  EXPECT_EQ(handler->request_id_, kRequestId1);
  EXPECT_EQ(handler->label_, stream_label1);

  // Complete the creation of stream2.
  std::string stream_label2 = std::string("stream2");
  dispatcher->OnMessageReceived(MediaStreamMsg_StreamGenerated(
        kRouteId, ipc_request_id2, stream_label2,
        audio_device_array, video_device_array));
  EXPECT_EQ(handler->request_id_, kRequestId2);
  EXPECT_EQ(handler->label_, stream_label2);

  EXPECT_EQ(dispatcher->requests_.size(), size_t(0));
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(2));

  // Check the session_id of stream2.
  EXPECT_EQ(dispatcher->audio_session_id(stream_label2, 0), kAudioSessionId);
  EXPECT_EQ(dispatcher->video_session_id(stream_label2, 0), kVideoSessionId);

  // Stop stream2.
  dispatcher->StopStream(stream_label2);
  EXPECT_EQ(dispatcher->audio_session_id(stream_label2, 0),
            media_stream::StreamDeviceInfo::kNoId);
  EXPECT_EQ(dispatcher->video_session_id(stream_label2, 0),
            media_stream::StreamDeviceInfo::kNoId);

  // Stop stream1.
  dispatcher->StopStream(stream_label1);
  EXPECT_EQ(dispatcher->audio_session_id(stream_label1, 0),
            media_stream::StreamDeviceInfo::kNoId);
  EXPECT_EQ(dispatcher->video_session_id(stream_label1, 0),
            media_stream::StreamDeviceInfo::kNoId);
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(0));

  // Verify that the request have been completed.
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(0));
  EXPECT_EQ(dispatcher->requests_.size(), size_t(0));
}

TEST(MediaStreamDispatcherTest, BasicVideoDevice) {
  scoped_ptr<MediaStreamDispatcher> dispatcher(new MediaStreamDispatcher(NULL));
  scoped_ptr<MockMediaStreamDispatcherEventHandler>
      handler(new MockMediaStreamDispatcherEventHandler);
  std::string security_origin;

  int ipc_request_id1 = dispatcher->next_ipc_id_;
  dispatcher->EnumerateDevices(kRequestId1, handler.get()->AsWeakPtr(),
                               content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE,
                               security_origin);
  int ipc_request_id2 = dispatcher->next_ipc_id_;
  EXPECT_NE(ipc_request_id1, ipc_request_id2);
  dispatcher->EnumerateDevices(kRequestId2, handler.get()->AsWeakPtr(),
                               content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE,
                               security_origin);
  EXPECT_EQ(dispatcher->requests_.size(), size_t(2));

  media_stream::StreamDeviceInfoArray video_device_array(1);
  media_stream::StreamDeviceInfo video_device_info;
  video_device_info.name = "Camera";
  video_device_info.device_id = "device_path";
  video_device_info.stream_type =
      content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE;
  video_device_info.session_id = kVideoSessionId;
  video_device_array[0] = video_device_info;

  // Complete the enumeration of request 1.
  dispatcher->OnMessageReceived(MediaStreamMsg_DevicesEnumerated(
      kRouteId, ipc_request_id1, video_device_array));
  EXPECT_EQ(handler->request_id_, kRequestId1);

  // Complete the enumeration of request 2.
  dispatcher->OnMessageReceived(MediaStreamMsg_DevicesEnumerated(
      kRouteId, ipc_request_id2, video_device_array));
  EXPECT_EQ(handler->request_id_, kRequestId2);

  EXPECT_EQ(dispatcher->requests_.size(), size_t(0));
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(0));

  int ipc_request_id3 = dispatcher->next_ipc_id_;
  dispatcher->OpenDevice(kRequestId3, handler.get()->AsWeakPtr(),
                         video_device_info.device_id,
                         content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE,
                         security_origin);
  int ipc_request_id4 = dispatcher->next_ipc_id_;
  EXPECT_NE(ipc_request_id3, ipc_request_id4);
  dispatcher->OpenDevice(kRequestId4, handler.get()->AsWeakPtr(),
                         video_device_info.device_id,
                         content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE,
                         security_origin);
  EXPECT_EQ(dispatcher->requests_.size(), size_t(2));

  // Complete the OpenDevice of request 1.
  std::string stream_label1 = std::string("stream1");
  dispatcher->OnMessageReceived(MediaStreamMsg_DeviceOpened(
      kRouteId, ipc_request_id3, stream_label1, video_device_info));
  EXPECT_EQ(handler->request_id_, kRequestId3);

  // Complete the OpenDevice of request 2.
  std::string stream_label2 = std::string("stream2");
  dispatcher->OnMessageReceived(MediaStreamMsg_DeviceOpened(
      kRouteId, ipc_request_id4, stream_label2, video_device_info));
  EXPECT_EQ(handler->request_id_, kRequestId4);

  EXPECT_EQ(dispatcher->requests_.size(), size_t(0));
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(2));

  // Check the video_session_id.
  EXPECT_EQ(dispatcher->video_session_id(stream_label1, 0), kVideoSessionId);
  EXPECT_EQ(dispatcher->video_session_id(stream_label2, 0), kVideoSessionId);

  // Stop stream2.
  dispatcher->StopStream(stream_label2);
  EXPECT_EQ(dispatcher->video_session_id(stream_label2, 0),
            media_stream::StreamDeviceInfo::kNoId);

  // Stop stream1.
  dispatcher->StopStream(stream_label1);
  EXPECT_EQ(dispatcher->video_session_id(stream_label1, 0),
            media_stream::StreamDeviceInfo::kNoId);
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(0));

  // Verify that the request have been completed.
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(0));
  EXPECT_EQ(dispatcher->requests_.size(), size_t(0));
}

TEST(MediaStreamDispatcherTest, TestFailure) {
  scoped_ptr<MediaStreamDispatcher> dispatcher(new MediaStreamDispatcher(NULL));
  scoped_ptr<MockMediaStreamDispatcherEventHandler>
      handler(new MockMediaStreamDispatcherEventHandler);
  media_stream::StreamOptions components(true, true);
  std::string security_origin;

  // Test failure when creating a stream.
  int ipc_request_id1 = dispatcher->next_ipc_id_;
  dispatcher->GenerateStream(kRequestId1, handler.get()->AsWeakPtr(),
                             components, security_origin);
  dispatcher->OnMessageReceived(MediaStreamMsg_StreamGenerationFailed(
      kRouteId, ipc_request_id1));

  // Verify that the request have been completed.
  EXPECT_EQ(handler->request_id_, kRequestId1);
  EXPECT_EQ(dispatcher->requests_.size(), size_t(0));

  // Create a new stream.
  ipc_request_id1 = dispatcher->next_ipc_id_;
  dispatcher->GenerateStream(kRequestId1, handler.get()->AsWeakPtr(),
                             components, security_origin);

  media_stream::StreamDeviceInfoArray audio_device_array(1);
  media_stream::StreamDeviceInfo audio_device_info;
  audio_device_info.name = "Microphone";
  audio_device_info.stream_type =
      content::MEDIA_STREAM_DEVICE_TYPE_AUDIO_CAPTURE;
  audio_device_info.session_id = kAudioSessionId;
  audio_device_array[0] = audio_device_info;

  media_stream::StreamDeviceInfoArray video_device_array(1);
  media_stream::StreamDeviceInfo video_device_info;
  video_device_info.name = "Camera";
  video_device_info.stream_type =
      content::MEDIA_STREAM_DEVICE_TYPE_VIDEO_CAPTURE;
  video_device_info.session_id = kVideoSessionId;
  video_device_array[0] = video_device_info;

  // Complete the creation of stream1.
  std::string stream_label1 = std::string("stream1");
  dispatcher->OnMessageReceived(MediaStreamMsg_StreamGenerated(
      kRouteId, ipc_request_id1, stream_label1,
      audio_device_array, video_device_array));
  EXPECT_EQ(handler->request_id_, kRequestId1);
  EXPECT_EQ(handler->label_, stream_label1);
  EXPECT_EQ(dispatcher->video_session_id(stream_label1, 0), kVideoSessionId);

  // Test failure of the video device.
  dispatcher->OnMessageReceived(
      MediaStreamHostMsg_VideoDeviceFailed(kRouteId, stream_label1, 0));
  EXPECT_EQ(handler->video_failed, true);
  EXPECT_EQ(handler->audio_failed, false);
  // Make sure the audio device still exist but not the video device.
  EXPECT_EQ(dispatcher->audio_session_id(stream_label1, 0), kAudioSessionId);

  // Test failure of the audio device.
  dispatcher->OnMessageReceived(
      MediaStreamHostMsg_AudioDeviceFailed(kRouteId, stream_label1, 0));
  EXPECT_EQ(handler->audio_failed, true);

  // Stop stream1.
  dispatcher->StopStream(stream_label1);
  EXPECT_EQ(dispatcher->label_stream_map_.size(), size_t(0));
}


text:
namespace Glimpse.Core.Tab.Assist
{
    public interface ITabBuild
    {
        object Build();
    }
}


text:
package tt.another;

import lombok.experimental.Builder;

/**
 * Created by alex on 02.10.14.
 */
@Builder
public class BuilderExample {
	private String name;
	private int age;

}


text:
namespace BoatRacingSimulator.Models.Engines
{
    public class JetEngine : BoatEngine
    {
        private const int Multiplier = 5;

        public JetEngine(string model, int horsepower, int displacement)
            : base(model, horsepower, displacement)
        {
        }

        public override int Output
        {
            get
            {
                if (this.CachedOutput != 0)
                {
                    return this.CachedOutput;
                }

                this.CachedOutput = (this.Horsepower * Multiplier) + this.Displacement;
                return this.CachedOutput;
            }
        }
    }
}


text:
using Newtonsoft.Json;

namespace MultiSafepay.Model
{
    public class TemplateInputObject
    {
        [JsonProperty("border")]
        public string Border { get; set; }
        [JsonProperty("label")]
        public string Label { get; set; }
    }
}


text:
\hypertarget{classutilspp_1_1CountingBody}{\section{utilspp\-:\-:Counting\-Body$<$ Content\-Type, Count\-Policy $>$ Class Template Reference}
\label{classutilspp_1_1CountingBody}\index{utilspp\-::\-Counting\-Body$<$ Content\-Type, Count\-Policy $>$@{utilspp\-::\-Counting\-Body$<$ Content\-Type, Count\-Policy $>$}}
}

Inheritance diagram for utilspp\-:\-:Counting\-Body$<$ Content\-Type, Count\-Policy $>$\-:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=228pt]{classutilspp_1_1CountingBody__inherit__graph}
\end{center}
\end{figure}

Collaboration diagram for utilspp\-:\-:Counting\-Body$<$ Content\-Type, Count\-Policy $>$\-:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=228pt]{classutilspp_1_1CountingBody__coll__graph}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hypertarget{classutilspp_1_1CountingBody_a1cdd0127a4df9faacebcf6e6485a17d0}{{\bfseries Counting\-Body} (Content\-Type $\ast$body)}\label{classutilspp_1_1CountingBody_a1cdd0127a4df9faacebcf6e6485a17d0}

\item
\hypertarget{classutilspp_1_1CountingBody_ab614dec16baa509684b7ff64d8f1ab0e}{void {\bfseries inc} ()}\label{classutilspp_1_1CountingBody_ab614dec16baa509684b7ff64d8f1ab0e}

\item
\hypertarget{classutilspp_1_1CountingBody_a9a5eee9f042935a08b526c4dd4191b74}{void {\bfseries dec} ()}\label{classutilspp_1_1CountingBody_a9a5eee9f042935a08b526c4dd4191b74}

\item
\hypertarget{classutilspp_1_1CountingBody_ae6305c6f6e5765cecb318c2047994ab5}{Content\-Type $\ast$ {\bfseries get} ()}\label{classutilspp_1_1CountingBody_ae6305c6f6e5765cecb318c2047994ab5}

\end{DoxyCompactItemize}

The documentation for this class was generated from the following file\-:\begin{DoxyCompactItemize}
\item
include/utilspp/Smart\-Ptr.\-hpp\end{DoxyCompactItemize}


text:
// LICENSE : MIT
"use strict";
import UseCase from "../../framework/UseCase";
import editorRepository, {EditorRepository} from "../../infra/EditorRepository";
import AddQuoteTextUseCase from "./AddQuoteTextUseCase";
export default class SaveImageDataUseCase extends UseCase {
    static create() {
        return new this({editorRepository});
    }

    /**
     * @param {EditorRepository} editorRepository
     */
    constructor({editorRepository}) {
        super();
        this.editorRepository = editorRepository;
    }

    /**
     * @param fileName
     * @param currentTime
     * @param dataURL
     * @param transcript
     */
    execute({
        fileName,
        currentTime,
        dataURL,
        transcript
    }) {
        const editor = this.editorRepository.lastUsed();
        return editor.saveImageAsFile({fileName, dataURL}).then((imageFilePath) => {
            const quoteText = editor.createQuoteText({
                imageFilePath,
                currentTime,
                transcript
            });
            editor.appendText(quoteText);
            // dispatch "quote" and view should notify quote!
            const addQuoteUseCase = new AddQuoteTextUseCase();
            return this.context.useCase(addQuoteUseCase).execute(quoteText).then(() => {
                this.editorRepository.save(editor);
            });
        });
    }

}