text:
/* Internal Headers */
#include "Utils/UniversalSettings/ValueCollection.h"
#include "Utils/UniversalSettings/Exceptions.h"
#include "Utils/UniversalSettings/ParametrizedOptionValue.h"
/* External Headers */
#include <algorithm>
#include <cassert>

namespace Scine {
namespace Utils {
namespace UniversalSettings {

void ValueCollection::addGenericValue(std::string name, GenericValue value) {
  assert(!name.empty());
  if (valueExists(name)) {
    throw AlreadyExistingValueException(name);
  }
  values_.emplace_back(std::move(name), std::move(value));
}

GenericValue ValueCollection::getValue(const std::string& name) const {
  return getGenericValue(name);
}

void ValueCollection::modifyValue(const std::string& name, GenericValue value) {
  auto it = findName(name);
  if (it == values_.end()) {
    throw InexistingValueException(name);
  }
  it->second = std::move(value);
}

void ValueCollection::dropValue(const std::string& name) {
  auto it = findName(name);
  if (it == values_.end()) {
    throw InexistingValueException(name);
  }
  values_.erase(
      std::remove_if(std::begin(values_), std::end(values_), [&](const auto& pair) { return pair.first == name; }),
      std::end(values_));
}

void ValueCollection::addBool(std::string name, bool value) {
  addGenericValue(std::move(name), GenericValue::fromBool(value));
}

void ValueCollection::addInt(std::string name, int value) {
  addGenericValue(std::move(name), GenericValue::fromInt(value));
}

void ValueCollection::addDouble(std::string name, double value) {
  addGenericValue(std::move(name), GenericValue::fromDouble(value));
}

void ValueCollection::addString(std::string name, std::string value) {
  addGenericValue(std::move(name), GenericValue::fromString(std::move(value)));
}

void ValueCollection::addCollection(std::string name, ValueCollection value) {
  addGenericValue(std::move(name), GenericValue::fromCollection(std::move(value)));
}

void ValueCollection::addOptionWithSettings(std::string name, ParametrizedOptionValue value) {
  addGenericValue(std::move(name), GenericValue::fromOptionWithSettings(std::move(value)));
}

void ValueCollection::modifyBool(const std::string& name, bool value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isBool()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromBool(value));
}

void ValueCollection::modifyInt(const std::string& name, int value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isInt()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromInt(value));
}

void ValueCollection::modifyDouble(const std::string& name, double value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isDouble()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromDouble(value));
}

void ValueCollection::modifyString(const std::string& name, std::string value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isString()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromString(std::move(value)));
}

void ValueCollection::modifyCollection(const std::string& name, ValueCollection value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isCollection()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromCollection(std::move(value)));
}

void ValueCollection::modifyOptionsWithSettings(const std::string& name, ParametrizedOptionValue value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isOptionWithSettings()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromOptionWithSettings(std::move(value)));
}

bool ValueCollection::getBool(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toBool();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

int ValueCollection::getInt(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toInt();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

double ValueCollection::getDouble(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toDouble();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

std::string ValueCollection::getString(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toString();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

ValueCollection ValueCollection::getCollection(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toCollection();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

ParametrizedOptionValue ValueCollection::getOptionWithSettings(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toOptionWithSettings();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

void ValueCollection::addIntList(std::string name, GenericValue::IntList value) {
  addGenericValue(std::move(name), GenericValue::fromIntList(std::move(value)));
}

GenericValue::IntList ValueCollection::getIntList(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toIntList();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

void ValueCollection::modifyIntList(const std::string& name, GenericValue::IntList value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isIntList()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromIntList(std::move(value)));
}

void ValueCollection::addDoubleList(std::string name, GenericValue::DoubleList value) {
  addGenericValue(std::move(name), GenericValue::fromDoubleList(std::move(value)));
}

GenericValue::DoubleList ValueCollection::getDoubleList(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toDoubleList();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

void ValueCollection::modifyDoubleList(const std::string& name, GenericValue::DoubleList value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isDoubleList()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromDoubleList(std::move(value)));
}

void ValueCollection::addStringList(std::string name, GenericValue::StringList value) {
  addGenericValue(std::move(name), GenericValue::fromStringList(std::move(value)));
}

GenericValue::StringList ValueCollection::getStringList(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toStringList();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

void ValueCollection::modifyStringList(const std::string& name, GenericValue::StringList value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isStringList()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromStringList(std::move(value)));
}

void ValueCollection::addCollectionList(std::string name, GenericValue::CollectionList value) {
  addGenericValue(std::move(name), GenericValue::fromCollectionList(std::move(value)));
}

GenericValue::CollectionList ValueCollection::getCollectionList(const std::string& name) const {
  const auto& genericValue = getGenericValue(name);
  try {
    return genericValue.toCollectionList();
  }
  catch (InvalidValueConversionException&) {
    throw ValueHasDifferentTypeException(name);
  }
}

void ValueCollection::modifyCollectionList(const std::string& name, GenericValue::CollectionList value) {
  const auto& genericValue = getGenericValue(name);
  if (!genericValue.isCollectionList()) {
    throw InvalidValueConversionException();
  }
  modifyValue(name, GenericValue::fromCollectionList(std::move(value)));
}

ValueCollection::Container::const_iterator ValueCollection::findName(const std::string& name) const {
  auto it = std::find_if(values_.begin(), values_.end(), [&name](const auto& p) { return p.first == name; });
  return it;
}

ValueCollection::Container::iterator ValueCollection::findName(const std::string& name) {
  auto it = std::find_if(values_.begin(), values_.end(), [&name](const auto& p) { return p.first == name; });
  return it;
}

const GenericValue& ValueCollection::getGenericValue(const std::string& name) const {
  auto it = findName(name);
  if (it == values_.end())
    throw InexistingValueException(name);

  const auto& genericValue = it->second;
  return genericValue;
}

int ValueCollection::count() const {
  return static_cast<int>(values_.size());
}

int ValueCollection::size() const {
  return static_cast<int>(values_.size());
}

bool ValueCollection::empty() const {
  return values_.empty();
}

std::vector<std::string> ValueCollection::getKeys() const {
  std::vector<std::string> keys;
  for (const auto& v : values_) {
    keys.push_back(v.first);
  }
  return keys;
}

bool ValueCollection::valueExists(const std::string& name) const {
  return findName(name) != values_.end();
}

inline bool equalToDefault(const std::string& key, const GenericValue& value) {
  auto descriptor = OptionListDescriptor(key);
  return value == descriptor.getDefaultGenericValue();
}

bool operator==(const ValueCollection& lhs, const ValueCollection& rhs) {
  return lhs.getDivergingKeys(rhs, true).empty();
}

bool operator!=(const ValueCollection& lhs, const ValueCollection& rhs) {
  return !(lhs == rhs);
}

std::vector<std::string> ValueCollection::getDivergingKeys(const ValueCollection& otherSettings,
                                                           bool onlyFirstDivergingKey) const {
  std::vector<std::string> result;
  if (this->empty() && otherSettings.empty()) {
    return result;
  }
  auto lhsKeys = this->getKeys();
  auto rhsKeys = otherSettings.getKeys();
  for (const auto& key : lhsKeys) {
    // key not present or key present in both, but value is different
    if (!otherSettings.valueExists(key) || this->getValue(key) != otherSettings.getValue(key)) {
      result.push_back(key);
      if (onlyFirstDivergingKey) {
        return result;
      }
    }
  }

  // identical the other way around
  for (const auto& key : rhsKeys) {
    if (!this->valueExists(key) || this->getValue(key) != otherSettings.getValue(key)) {
      result.push_back(key);
      if (onlyFirstDivergingKey) {
        return result;
      }
    }
  }
  // erase duplicates
  std::sort(result.begin(), result.end());
  result.erase(std::unique(result.begin(), result.end()), result.end());
  return result;
}

} /* namespace UniversalSettings */
} /* namespace Utils */
} /* namespace Scine */


text:
# Usage examples

## Wildcards
In this example, running `grunt jshint:all` (or `grunt jshint` because `jshint` is a [multi task][]) will lint the project's Gruntfile as well as all JavaScript files in the `lib` and `test` directories and their subdirectores, using the default JSHint options.

```js
// Project configuration.
grunt.initConfig({
  jshint: {
    all: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js']
  }
});
```

## Linting before and after concatenating
In this example, running `grunt jshint` will lint both the "beforeconcat" set and "afterconcat" sets of files. This is not ideal, because `dist/output.js` may get linted before it gets created via the [grunt-contrib-concat plugin](https://github.com/gruntjs/grunt-contrib-concat) `concat` task.

In this case, you should lint the "beforeconcat" files first, then concat, then lint the "afterconcat" files, by running `grunt jshint:beforeconcat concat jshint:afterconcat`.

```js
// Project configuration.
grunt.initConfig({
  concat: {
    dist: {
      src: ['src/foo.js', 'src/bar.js'],
      dest: 'dist/output.js'
    }
  },
  jshint: {
    beforeconcat: ['src/foo.js', 'src/bar.js'],
    afterconcat: ['dist/output.js']
  }
});
```

## Specifying JSHint options and globals

In this example, custom JSHint options are specified. Note that when `grunt jshint:uses_defaults` is run, those files are linted using the default options, but when `grunt jshint:with_overrides` is run, those files are linted using _merged_ task/target options.

```js
// Project configuration.
grunt.initConfig({
  jshint: {
    options: {
      curly: true,
      eqeqeq: true,
      eqnull: true,
      browser: true,
      globals: {
        jQuery: true
      },
    },
    uses_defaults: ['dir1/**/*.js', 'dir2/**/*.js'],
    with_overrides: {
      options: {
        curly: false,
        undef: true,
      },
      files: {
        src: ['dir3/**/*.js', 'dir4/**/*.js']
      },
    }
  },
});
```

#### Merging JSHint options and globals with a jshintrc file

A simple way to use a project-specific `jshintrc` file, augmented with specific options for some targets.

```js
// Project configuration.
grunt.initConfig({
  jshint: {
    options: {
      jshintrc: '.jshintrc',
    },
    webapp: {
      options: {
        globals: {
          jQuery: true,
        },
      },
      files: ['www/**/*.js'],
    },
    server: {
      options: {
        node: true,
      },
      files: ['api/**/*.js'],
    },
  },
});
```

redpajama_set_name: RedPajamaGithub


text:
"""Test cases for py.test plugin

   TODO: pytest_purkinje plugin is active during test execution;
         -p no:pytest_purkinje does not disable it. This causes
         error messages because there is no purkinje server available
"""

from __future__ import absolute_import
from builtins import str
import shutil
import os
import pytest
import flotsam.file_util as fu
import json
import time
from .conftest import TESTDATA_DIR
import pytest_purkinje.testmonitorplugin as sut
import purkinje_messages.message as msg
from mock import Mock

TEST_WEBSOCKET_URL = 'ws://example.org/'

@pytest.fixture
def mock_ws(monkeypatch):
    ws = Mock()
    m = Mock(return_value=ws)
    monkeypatch.setattr(sut.websocket, 'create_connection', m)
    return ws

@pytest.fixture
def plugin(mock_ws):
    return sut.TestMonitorPlugin(TEST_WEBSOCKET_URL)

@pytest.fixture
def report():
    return Mock(fs_path='dummy_path',
                nodeid='dummy_path::test_1',
                outcome='passed',
                when='call')

def test_1(plugin):
    assert plugin._websocket.create_connection.called_once_with('xyz')
    assert plugin.is_websocket_connected()

def test_send_event(plugin):
    mock_event = Mock()
    plugin.send_event(mock_event)
    assert mock_event.serialize.called
    assert plugin._websocket.send.called

def test_send_event_does_not_raise(plugin):
    # ensure that test execution will continue
    mock_event = Mock()

    def do_raise():
        raise Exception('Dummy exception')

    mock_event.serialize.side_effect = do_raise
    plugin.send_event(mock_event)
    assert not plugin._websocket.send.called

def test_suite_name(plugin, monkeypatch):
    monkeypatch.setattr(sut.os,
                        'getcwd',
                        Mock(return_value='/abc/xyz'))
    monkeypatch.setattr(sut.socket,
                        'gethostname',
                        Mock(return_value='testhost'))
    expected = 'testhost: /abc/xyz'
    assert plugin.suite_name() == expected

def test_suite_hash(plugin, monkeypatch):
    monkeypatch.setattr(plugin, 'suite_name',
                        Mock(return_value='testsuite_1'))
    assert plugin.suite_hash() == 'd50c6441c9f5bd95c8e6dbde301b2b11'

def test_pytest_sessionstart(plugin, monkeypatch):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    monkeypatch.setattr(plugin,
                        'suite_name',
                        Mock(return_value='testhost: /abc/xyz'))

    plugin.pytest_sessionstart()
    assert not plugin.send_event.called

def test_pytest_sessionfinish(plugin, monkeypatch):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    plugin.pytest_sessionfinish()
    assert plugin.send_event.called
    assert len(plugin.send_event.call_args_list) == 2

    m1 = plugin.send_event.call_args_list[0][0][0]
    assert type(m1) == msg.SessionTerminatedEvent

    m2 = plugin.send_event.call_args_list[1][0][0]
    assert type(m2) == msg.ConnectionTerminationEvent

def test_works_if_no_connection(plugin):
    plugin._websocket = None
    assert not plugin.is_websocket_connected()
    mock_event = Mock()
    plugin.send_event(mock_event)
    assert not plugin.is_websocket_connected()

def test_pytest_runtest_logreport(plugin, report, monkeypatch):
    start_time = time.time()
    monkeypatch.setattr(plugin, 'send_event', Mock())
    monkeypatch.setattr(sut.time,
                        'time',
                        Mock(return_value=start_time + 5))

    monkeypatch.setattr(plugin, '_test_cases', {report.nodeid: start_time})
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 2

    arg = plugin.send_event.call_args_list[0][0][0]
    assert type(arg) == msg.SessionStartedEvent

    event = plugin.send_event.call_args_list[1][0][0]
    assert type(event) == msg.TestCaseFinishedEvent
    assert event['duration'] == 5000
    assert len(plugin.reports) == 1
    assert plugin.reports[0] == report

def test_pytest_runtest_logreport_starts_session_only_once(
        report,
        plugin,
        monkeypatch):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    monkeypatch.setattr(plugin,
                        '_test_cases',
                        {report.nodeid: time.time()})
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 2

def test_pytest_runtest_logreport_store_tc_start_time(plugin,
                                                      monkeypatch,
                                                      report):
    start_time = time.time()
    monkeypatch.setattr(plugin, 'send_event', Mock())
    monkeypatch.setattr(sut.time,
                        'time',
                        Mock(return_value=start_time))
    report.when = 'setup'
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 0
    assert len(plugin.reports) == 0
    assert report.nodeid in plugin._test_cases
    assert plugin._test_cases[report.nodeid] == start_time

def test_pytest_runtest_logreport_ignore_tc_not_found(plugin,
                                                      monkeypatch,
                                                      report):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    monkeypatch.setattr(plugin, '_test_cases', {})
    report.when = 'call'
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 0
    assert len(plugin.reports) == 0
    assert report.nodeid not in plugin._test_cases

def test_pytest_runtest_logreport_no_detail(plugin, report, monkeypatch):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    report.nodeid = report.fs_path
    report.keywords = {}
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 0
    assert len(plugin.reports) == 0

def test_pytest_runtest_logreport_pep8(plugin, report, monkeypatch):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    report.nodeid = report.fs_path
    report.keywords = {'pep8': 1}
    report.when = 'setup'
    report.outcome = 'skipped'
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 2
    assert len(plugin.reports) == 1

@pytest.mark.parametrize('phase', ['setup', 'teardown'])
def test_pytest_runtest_logreport_ignore_phase(
        phase, plugin, report, monkeypatch):
    monkeypatch.setattr(plugin, 'send_event', Mock())
    report.when = phase
    plugin.pytest_runtest_logreport(report)
    assert len(plugin.send_event.call_args_list) == 0
    assert len(plugin.reports) == 0

def test_empty_single_pass(tmpdir, plugin, monkeypatch):
    test_proj_path = str(tmpdir) + '/singlepass'
    shutil.copytree(TESTDATA_DIR + '/testproj/singlepass',
                    test_proj_path)

    # TODO
    # Deletion of __pycache__ is necessary, or py.test will fail with the
    # following error message:
    #     #
    # import file mismatch:
    # imported module 'simple_test' has this __file__ attribute:
    # /home/bb/devel/python/purkinje/testdata/
    # testproj/singlepass/simple_test.py
    # which is not the same as the test file we want to collect:
    # /tmp/pytest-84/test_empty_single_pass0/singlepass/simple_test.py
    # HINT: remove __pycache__ / .pyc files and/or use a unique basename
    # for your test file modules
    fu.ensure_deleted(test_proj_path + '/__pycache__')

    orig_path = os.getcwd()
    try:
        os.chdir(test_proj_path)
        mock_ws = Mock()
        monkeypatch.setattr(sut.websocket, 'create_connection', mock_ws)
        assert plugin.is_websocket_connected()
        test_result = pytest.main([test_proj_path],
                                  plugins=[plugin])

        send_args = plugin._websocket.send.call_args_list
        assert len(send_args) == 4

        [json.dumps(x[0]) for x in send_args]

        assert test_result == 0

        reps = plugin.reports
        assert len(reps) == 1
        rep0 = reps[0]
        assert rep0.fspath == 'simple_test.py'
        assert rep0.outcome == 'passed'

    finally:
        os.chdir(orig_path)

def test_pytest_addoption():
    parser = Mock()
    sut.pytest_addoption(parser)
    print(parser.addoption.call_args_list)
    assert parser.addoption.call_args_list[0][0][0] == '--websocket_host'
    assert parser.addoption.call_args_list[1][0][0] == '--websocket_port'

def test_pytest_configure():
    config = Mock()
    sut.pytest_configure(config)
    assert config.pluginmanager.register.called


text:
namespace base {
class TaskRunner;
}

namespace content {

class CONTENT_EXPORT WorkerThreadRegistry {
 public:
  WorkerThreadRegistry();

  int PostTaskToAllThreads(const base::Closure& task);
  static WorkerThreadRegistry* Instance();

  void DidStartCurrentWorkerThread();
  void WillStopCurrentWorkerThread();

  // Always returns a non-null task runner regardless of whether the
  // corresponding worker thread is gone or not. If the thread is already gone
  // the tasks posted onto the task runner will be silently discarded.
  base::TaskRunner* GetTaskRunnerFor(int worker_id);

 private:
  friend class WorkerThread;
  friend class WorkerThreadRegistryTest;

  bool PostTask(int id, const base::Closure& task);

  using IDToTaskRunnerMap = std::map<base::PlatformThreadId, base::TaskRunner*>;

  ~WorkerThreadRegistry();

  // It is possible for an IPC message to arrive for a worker thread that has
  // already gone away. In such cases, it is still necessary to provide a
  // task-runner for that particular thread, because otherwise the message will
  // end up being handled as per usual in the main-thread, causing incorrect
  // results. |task_runner_for_dead_worker_| is used to handle such messages,
  // which silently discards all the tasks it receives.
  scoped_refptr<base::TaskRunner> task_runner_for_dead_worker_;

  IDToTaskRunnerMap task_runner_map_;
  base::Lock task_runner_map_lock_;
};

}  // namespace content

#endif  // CONTENT_CHILD_WORKER_THREAD_REGISTRY_H_


text:
use crate::rwops::RWops;
use libc::c_char;
use std::error;
use std::ffi::{CStr, CString, NulError};
use std::fmt;
use std::io;
use std::path::Path;

use crate::common::{validate_int, IntegerOrSdlError};
use crate::get_error;
use crate::joystick;
use crate::GameControllerSubsystem;
use std::mem::transmute;

use crate::sys;

#[derive(Debug, Clone)]
pub enum AddMappingError {
    InvalidMapping(NulError),
    InvalidFilePath(String),
    ReadError(String),
    SdlError(String),
}

impl fmt::Display for AddMappingError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::AddMappingError::*;

        match *self {
            InvalidMapping(ref e) => write!(f, "Null error: {}", e),
            InvalidFilePath(ref value) => write!(f, "Invalid file path ({})", value),
            ReadError(ref e) => write!(f, "Read error: {}", e),
            SdlError(ref e) => write!(f, "SDL error: {}", e),
        }
    }
}

impl error::Error for AddMappingError {
    fn description(&self) -> &str {
        use self::AddMappingError::*;

        match *self {
            InvalidMapping(_) => "invalid mapping",
            InvalidFilePath(_) => "invalid file path",
            ReadError(_) => "read error",
            SdlError(ref e) => e,
        }
    }
}

impl GameControllerSubsystem {
    /// Retrieve the total number of attached joysticks *and* controllers identified by SDL.
    #[doc(alias = "SDL_NumJoysticks")]
    pub fn num_joysticks(&self) -> Result<u32, String> {
        let result = unsafe { sys::SDL_NumJoysticks() };

        if result >= 0 {
            Ok(result as u32)
        } else {
            Err(get_error())
        }
    }

    /// Return true if the joystick at index `joystick_index` is a game controller.
    #[inline]
    #[doc(alias = "SDL_IsGameController")]
    pub fn is_game_controller(&self, joystick_index: u32) -> bool {
        match validate_int(joystick_index, "joystick_index") {
            Ok(joystick_index) => unsafe {
                sys::SDL_IsGameController(joystick_index) != sys::SDL_bool::SDL_FALSE
            },
            Err(_) => false,
        }
    }

    /// Attempt to open the controller at index `joystick_index` and return it.
    /// Controller IDs are the same as joystick IDs and the maximum number can
    /// be retrieved using the `SDL_NumJoysticks` function.
    #[doc(alias = "SDL_GameControllerOpen")]
    pub fn open(&self, joystick_index: u32) -> Result<GameController, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        let joystick_index = validate_int(joystick_index, "joystick_index")?;
        let controller = unsafe { sys::SDL_GameControllerOpen(joystick_index) };

        if controller.is_null() {
            Err(SdlError(get_error()))
        } else {
            Ok(GameController {
                subsystem: self.clone(),
                raw: controller,
            })
        }
    }

    /// Return the name of the controller at index `joystick_index`.
    #[doc(alias = "SDL_GameControllerNameForIndex")]
    pub fn name_for_index(&self, joystick_index: u32) -> Result<String, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        let joystick_index = validate_int(joystick_index, "joystick_index")?;
        let c_str = unsafe { sys::SDL_GameControllerNameForIndex(joystick_index) };

        if c_str.is_null() {
            Err(SdlError(get_error()))
        } else {
            Ok(unsafe {
                CStr::from_ptr(c_str as *const _)
                    .to_str()
                    .unwrap()
                    .to_owned()
            })
        }
    }

    /// If state is `true` controller events are processed, otherwise
    /// they're ignored.
    #[doc(alias = "SDL_GameControllerEventState")]
    pub fn set_event_state(&self, state: bool) {
        unsafe { sys::SDL_GameControllerEventState(state as i32) };
    }

    /// Return `true` if controller events are processed.
    #[doc(alias = "SDL_GameControllerEventState")]
    pub fn event_state(&self) -> bool {
        unsafe {
            sys::SDL_GameControllerEventState(sys::SDL_QUERY as i32) == sys::SDL_ENABLE as i32
        }
    }

    /// Add a new controller input mapping from a mapping string.
    #[doc(alias = "SDL_GameControllerAddMapping")]
    pub fn add_mapping(&self, mapping: &str) -> Result<MappingStatus, AddMappingError> {
        use self::AddMappingError::*;
        let mapping = match CString::new(mapping) {
            Ok(s) => s,
            Err(err) => return Err(InvalidMapping(err)),
        };

        let result =
            unsafe { sys::SDL_GameControllerAddMapping(mapping.as_ptr() as *const c_char) };

        match result {
            1 => Ok(MappingStatus::Added),
            0 => Ok(MappingStatus::Updated),
            _ => Err(SdlError(get_error())),
        }
    }

    /// Load controller input mappings from a file.
    pub fn load_mappings<P: AsRef<Path>>(&self, path: P) -> Result<i32, AddMappingError> {
        use self::AddMappingError::*;

        let rw = RWops::from_file(path, "r").map_err(InvalidFilePath)?;
        self.load_mappings_from_rw(rw)
    }

    /// Load controller input mappings from a [`Read`](std::io::Read) object.
    pub fn load_mappings_from_read<R: io::Read>(
        &self,
        read: &mut R,
    ) -> Result<i32, AddMappingError> {
        use self::AddMappingError::*;

        let mut buffer = Vec::with_capacity(1024);
        let rw = RWops::from_read(read, &mut buffer).map_err(ReadError)?;
        self.load_mappings_from_rw(rw)
    }

    /// Load controller input mappings from an SDL [`RWops`] object.
    #[doc(alias = "SDL_GameControllerAddMappingsFromRW")]
    pub fn load_mappings_from_rw<'a>(&self, rw: RWops<'a>) -> Result<i32, AddMappingError> {
        use self::AddMappingError::*;

        let result = unsafe { sys::SDL_GameControllerAddMappingsFromRW(rw.raw(), 0) };
        match result {
            -1 => Err(SdlError(get_error())),
            _ => Ok(result),
        }
    }

    #[doc(alias = "SDL_GameControllerMappingForGUID")]
    pub fn mapping_for_guid(&self, guid: joystick::Guid) -> Result<String, String> {
        let c_str = unsafe { sys::SDL_GameControllerMappingForGUID(guid.raw()) };

        c_str_to_string_or_err(c_str)
    }

    #[inline]
    /// Force controller update when not using the event loop
    #[doc(alias = "SDL_GameControllerUpdate")]
    pub fn update(&self) {
        unsafe { sys::SDL_GameControllerUpdate() };
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[repr(i32)]
pub enum Axis {
    LeftX = sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTX as i32,
    LeftY = sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTY as i32,
    RightX = sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTX as i32,
    RightY = sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTY as i32,
    TriggerLeft = sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERLEFT as i32,
    TriggerRight = sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERRIGHT as i32,
}

impl Axis {
    /// Return the Axis from a string description in the same format
    /// used by the game controller mapping strings.
    #[doc(alias = "SDL_GameControllerGetAxisFromString")]
    pub fn from_string(axis: &str) -> Option<Axis> {
        let id = match CString::new(axis) {
            Ok(axis) => unsafe {
                sys::SDL_GameControllerGetAxisFromString(axis.as_ptr() as *const c_char)
            },
            // string contains a nul byte - it won't match anything.
            Err(_) => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_INVALID,
        };

        Axis::from_ll(id)
    }

    /// Return a string for a given axis in the same format using by
    /// the game controller mapping strings
    #[doc(alias = "SDL_GameControllerGetStringForAxis")]
    pub fn string(self) -> String {
        let axis: sys::SDL_GameControllerAxis;
        unsafe {
            axis = transmute(self);
        }

        let string = unsafe { sys::SDL_GameControllerGetStringForAxis(axis) };

        c_str_to_string(string)
    }

    pub fn from_ll(bitflags: sys::SDL_GameControllerAxis) -> Option<Axis> {
        Some(match bitflags {
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_INVALID => return None,
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTX => Axis::LeftX,
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTY => Axis::LeftY,
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTX => Axis::RightX,
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTY => Axis::RightY,
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERLEFT => Axis::TriggerLeft,
            sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERRIGHT => Axis::TriggerRight,
            _ => panic!("unhandled controller axis"),
        })
    }

    pub fn to_ll(self) -> sys::SDL_GameControllerAxis {
        match self {
            Axis::LeftX => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTX,
            Axis::LeftY => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTY,
            Axis::RightX => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTX,
            Axis::RightY => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTY,
            Axis::TriggerLeft => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERLEFT,
            Axis::TriggerRight => sys::SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERRIGHT,
        }
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[repr(i32)]
pub enum Button {
    A = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_A as i32,
    B = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_B as i32,
    X = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_X as i32,
    Y = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_Y as i32,
    Back = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_BACK as i32,
    Guide = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_GUIDE as i32,
    Start = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_START as i32,
    LeftStick = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSTICK as i32,
    RightStick = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSTICK as i32,
    LeftShoulder = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSHOULDER as i32,
    RightShoulder = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSHOULDER as i32,
    DPadUp = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_UP as i32,
    DPadDown = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_DOWN as i32,
    DPadLeft = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_LEFT as i32,
    DPadRight = sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_RIGHT as i32,
}

impl Button {
    /// Return the Button from a string description in the same format
    /// used by the game controller mapping strings.
    #[doc(alias = "SDL_GameControllerGetButtonFromString")]
    pub fn from_string(button: &str) -> Option<Button> {
        let id = match CString::new(button) {
            Ok(button) => unsafe {
                sys::SDL_GameControllerGetButtonFromString(button.as_ptr() as *const c_char)
            },
            // string contains a nul byte - it won't match anything.
            Err(_) => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_INVALID,
        };

        Button::from_ll(id)
    }

    /// Return a string for a given button in the same format using by
    /// the game controller mapping strings
    #[doc(alias = "SDL_GameControllerGetStringForButton")]
    pub fn string(self) -> String {
        let button: sys::SDL_GameControllerButton;
        unsafe {
            button = transmute(self);
        }

        let string = unsafe { sys::SDL_GameControllerGetStringForButton(button) };

        c_str_to_string(string)
    }

    pub fn from_ll(bitflags: sys::SDL_GameControllerButton) -> Option<Button> {
        Some(match bitflags {
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_INVALID => return None,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_A => Button::A,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_B => Button::B,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_X => Button::X,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_Y => Button::Y,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_BACK => Button::Back,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_GUIDE => Button::Guide,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_START => Button::Start,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSTICK => Button::LeftStick,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSTICK => Button::RightStick,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSHOULDER => {
                Button::LeftShoulder
            }
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSHOULDER => {
                Button::RightShoulder
            }
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_UP => Button::DPadUp,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_DOWN => Button::DPadDown,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_LEFT => Button::DPadLeft,
            sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_RIGHT => Button::DPadRight,
            _ => panic!("unhandled controller button"),
        })
    }

    pub fn to_ll(self) -> sys::SDL_GameControllerButton {
        match self {
            Button::A => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_A,
            Button::B => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_B,
            Button::X => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_X,
            Button::Y => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_Y,
            Button::Back => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_BACK,
            Button::Guide => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_GUIDE,
            Button::Start => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_START,
            Button::LeftStick => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSTICK,
            Button::RightStick => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSTICK,
            Button::LeftShoulder => {
                sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSHOULDER
            }
            Button::RightShoulder => {
                sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSHOULDER
            }
            Button::DPadUp => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_UP,
            Button::DPadDown => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_DOWN,
            Button::DPadLeft => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_LEFT,
            Button::DPadRight => sys::SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
        }
    }
}

/// Possible return values for `add_mapping`
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum MappingStatus {
    Added = 1,
    Updated = 0,
}

/// Wrapper around the `SDL_GameController` object
pub struct GameController {
    subsystem: GameControllerSubsystem,
    raw: *mut sys::SDL_GameController,
}

impl GameController {
    #[inline]
    pub fn subsystem(&self) -> &GameControllerSubsystem {
        &self.subsystem
    }

    /// Return the name of the controller or an empty string if no
    /// name is found.
    #[doc(alias = "SDL_GameControllerName")]
    pub fn name(&self) -> String {
        let name = unsafe { sys::SDL_GameControllerName(self.raw) };

        c_str_to_string(name)
    }

    /// Return a String describing the controller's button and axis
    /// mappings
    #[doc(alias = "SDL_GameControllerMapping")]
    pub fn mapping(&self) -> String {
        let mapping = unsafe { sys::SDL_GameControllerMapping(self.raw) };

        c_str_to_string(mapping)
    }

    /// Return true if the controller has been opened and currently
    /// connected.
    #[doc(alias = "SDL_GameControllerGetAttached")]
    pub fn attached(&self) -> bool {
        unsafe { sys::SDL_GameControllerGetAttached(self.raw) != sys::SDL_bool::SDL_FALSE }
    }

    /// Return the joystick instance id of this controller
    #[doc(alias = "SDL_GameControllerGetJoystick")]
    pub fn instance_id(&self) -> u32 {
        let result = unsafe {
            let joystick = sys::SDL_GameControllerGetJoystick(self.raw);
            sys::SDL_JoystickInstanceID(joystick)
        };

        if result < 0 {
            // Should only fail if the joystick is NULL.
            panic!("{}", get_error())
        } else {
            result as u32
        }
    }

    /// Get the position of the given `axis`
    #[doc(alias = "SDL_GameControllerGetAxis")]
    pub fn axis(&self, axis: Axis) -> i16 {
        // This interface is a bit messed up: 0 is a valid position
        // but can also mean that an error occured.
        // Fortunately, an error can only occur if the controller pointer is NULL.
        // There should be no apparent reason for this to change in the future.

        let raw_axis: sys::SDL_GameControllerAxis;
        unsafe {
            raw_axis = transmute(axis);
        }

        unsafe { sys::SDL_GameControllerGetAxis(self.raw, raw_axis) }
    }

    /// Returns `true` if `button` is pressed.
    #[doc(alias = "SDL_GameControllerGetButton")]
    pub fn button(&self, button: Button) -> bool {
        // This interface is a bit messed up: 0 is a valid position
        // but can also mean that an error occured.
        // Fortunately, an error can only occur if the controller pointer is NULL.
        // There should be no apparent reason for this to change in the future.

        let raw_button: sys::SDL_GameControllerButton;
        unsafe {
            raw_button = transmute(button);
        }

        unsafe { sys::SDL_GameControllerGetButton(self.raw, raw_button) != 0 }
    }

    /// Set the rumble motors to their specified intensities, if supported.
    /// Automatically resets back to zero after `duration_ms` milliseconds have passed.
    ///
    /// # Notes
    ///
    /// The value range for the intensities is 0 to 0xFFFF.
    ///
    /// Do *not* use `std::u32::MAX` or similar for `duration_ms` if you want
    /// the rumble effect to keep playing for a long time, as this results in
    /// the effect ending immediately after starting due to an overflow.
    /// Use some smaller, "huge enough" number instead.
    #[doc(alias = "SDL_GameControllerRumble")]
    pub fn set_rumble(
        &mut self,
        low_frequency_rumble: u16,
        high_frequency_rumble: u16,
        duration_ms: u32,
    ) -> Result<(), IntegerOrSdlError> {
        let result = unsafe {
            sys::SDL_GameControllerRumble(
                self.raw,
                low_frequency_rumble,
                high_frequency_rumble,
                duration_ms,
            )
        };

        if result != 0 {
            Err(IntegerOrSdlError::SdlError(get_error()))
        } else {
            Ok(())
        }
    }
}

impl Drop for GameController {
    #[doc(alias = "SDL_GameControllerClose")]
    fn drop(&mut self) {
        unsafe { sys::SDL_GameControllerClose(self.raw) }
    }
}

/// Convert C string `c_str` to a String. Return an empty string if
/// `c_str` is NULL.
fn c_str_to_string(c_str: *const c_char) -> String {
    if c_str.is_null() {
        String::new()
    } else {
        unsafe {
            CStr::from_ptr(c_str as *const _)
                .to_str()
                .unwrap()
                .to_owned()
        }
    }
}

/// Convert C string `c_str` to a String. Return an SDL error if
/// `c_str` is NULL.
fn c_str_to_string_or_err(c_str: *const c_char) -> Result<String, String> {
    if c_str.is_null() {
        Err(get_error())
    } else {
        Ok(unsafe {
            CStr::from_ptr(c_str as *const _)
                .to_str()
                .unwrap()
                .to_owned()
        })
    }
}


text:
<?php

namespace Tests\Behat\Gherkin\Loader;

use Behat\Gherkin\Loader\YamlFileLoader;
use PHPUnit\Framework\TestCase;

class YamlFileLoaderTest extends TestCase
{
    private $loader;

    protected function setUp(): void
    {
        $this->loader = new YamlFileLoader();
    }

    public function testSupports()
    {
        $this->assertFalse($this->loader->supports(__DIR__));
        $this->assertFalse($this->loader->supports(__FILE__));
        $this->assertFalse($this->loader->supports('string'));
        $this->assertFalse($this->loader->supports(__DIR__ . '/file.yml'));
        $this->assertTrue($this->loader->supports(__DIR__ . '/../Fixtures/etalons/addition.yml'));
    }

    public function testLoadAddition()
    {
        $basePath = __DIR__ . '/../Fixtures';
        $this->loader->setBasePath($basePath);
        $features = $this->loader->load('etalons/addition.yml');

        $this->assertEquals(1, count($features));
        $this->assertEquals(realpath($basePath . DIRECTORY_SEPARATOR . 'etalons' . DIRECTORY_SEPARATOR . 'addition.yml'), $features[0]->getFile());
        $this->assertEquals('Addition', $features[0]->getTitle());
        $this->assertEquals(2, $features[0]->getLine());
        $this->assertEquals('en', $features[0]->getLanguage());
        $expectedDescription = <<<EOS
In order to avoid silly mistakes
As a math idiot
I want to be told the sum of two numbers
EOS;
        $this->assertEquals($expectedDescription, $features[0]->getDescription());

        $scenarios = $features[0]->getScenarios();

        $this->assertEquals(2, count($scenarios));
        $this->assertInstanceOf('Behat\Gherkin\Node\ScenarioNode', $scenarios[0]);
        $this->assertEquals(7, $scenarios[0]->getLine());
        $this->assertEquals('Add two numbers', $scenarios[0]->getTitle());
        $steps = $scenarios[0]->getSteps();
        $this->assertEquals(4, count($steps));
        $this->assertEquals(9, $steps[1]->getLine());
        $this->assertEquals('And', $steps[1]->getType());
        $this->assertEquals('And', $steps[1]->getKeyword());
        $this->assertEquals('Given', $steps[1]->getKeywordType());
        $this->assertEquals('I have entered 12 into the calculator', $steps[1]->getText());

        $this->assertInstanceOf('Behat\Gherkin\Node\ScenarioNode', $scenarios[1]);
        $this->assertEquals(13, $scenarios[1]->getLine());
        $this->assertEquals('Div two numbers', $scenarios[1]->getTitle());
        $steps = $scenarios[1]->getSteps();
        $this->assertEquals(4, count($steps));
        $this->assertEquals(16, $steps[2]->getLine());
        $this->assertEquals('When', $steps[2]->getType());
        $this->assertEquals('When', $steps[2]->getKeyword());
        $this->assertEquals('When', $steps[2]->getKeywordType());
        $this->assertEquals('I press div', $steps[2]->getText());
    }
}


text:
package com.splicemachine.tutorials.tsdbanalytics.dataobjects;

import kafka.serializer.Decoder;
import kafka.utils.VerifiableProperties;

import org.apache.commons.io.Charsets;

import com.google.gson.Gson;

/**
 * Decoder Class for ImpressionLog, used with Kafka Queue.
 * The ImpressionLog is encoded as Json String by the Producer.
 * The Consumer converts the Json String to an ImpressionLog object
 *
 * @author Jyotsna Ramineni
 */

public class ImpressionLogDecoder implements Decoder<ImpressionLog> {

    public ImpressionLogDecoder() {
        this(null);
    }

    public ImpressionLogDecoder(VerifiableProperties props) {
        /* This constructor must be present for successful compile. */
    }

    @Override
    public ImpressionLog fromBytes(byte[] bytes) {
        String jsonString = new String(bytes, Charsets.UTF_8);
        Gson gson = new Gson();
        final ImpressionLog impressionLog = gson.fromJson(jsonString, ImpressionLog.class);
        return impressionLog;
    }

}


text:
<?php

$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Catalog\Model\Category');
$category->isObjectNew(true);
$category->setId(
    '444'
)->setName(
    'Category 1'
)->setAttributeSetId(
    '3'
)->setParentId(
    2
)->setPath(
    '1/2'
)->setLevel(
    '2'
)->setDefaultSortBy(
    'name'
)->setIsActive(
    true
)->setPosition(
    '5'
)->save();


text:
// -*-Mode: C++;-*-

// * BeginRiceCopyright *****************************************************
//
// $HeadURL: https://hpctoolkit.googlecode.com/svn/branches/hpctoolkit-hpcserver/src/tool/hpcserver/FileUtils.hpp $
// $Id: FileUtils.hpp 4294 2013-07-11 00:15:53Z felipet1326@gmail.com $
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2022, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *

//***************************************************************************
//
// File:
//   $HeadURL: https://hpctoolkit.googlecode.com/svn/branches/hpctoolkit-hpcserver/src/tool/hpcserver/FileUtils.hpp $
//
// Purpose:
//   [The purpose of this file]
//
// Description:
//   [The set of functions, macros, etc. defined in the file]
//
//***************************************************************************

#ifndef FILEUTILS_H_
#define FILEUTILS_H_

#include "sys/stat.h"
#include "dirent.h"
#include <iostream>
#include <vector>
#include <errno.h>
#include <string>
#include <cstring>
#include <stdint.h>

using namespace std;
namespace TraceviewerServer
{
#define NO_ERROR 0

	typedef int FileDescriptor;
	typedef uint64_t FileOffset;

	class FileUtils
	{
	public:
		//Combines UNIX-style paths, taking care to ensure that there is always exactly 1 / joining firstPart and secondPart
		static string combinePaths(string firstPart, string secondPart)
		{
			string firstPartWithoutEndingSlash;
			if (firstPart[firstPart.length()-1]=='/')
				firstPartWithoutEndingSlash = firstPart.substr(0,firstPart.length()-1);
			else
				firstPartWithoutEndingSlash = firstPart;
			string recondPartWithoutStartingSlash;
			if (secondPart[0]=='/')
				recondPartWithoutStartingSlash = secondPart.substr(1, secondPart.length()-1);
			else
				recondPartWithoutStartingSlash = secondPart;
			return firstPartWithoutEndingSlash + "/" + recondPartWithoutStartingSlash;

		}
		//Uses stat to check if the specified folder exists and if it is indeed a folder.
		static bool existsAndIsDir(string p)
		{
			struct stat DirInfo;
			int err = stat(p.c_str(), &DirInfo);
			bool isDir = S_ISDIR(DirInfo.st_mode);
			if ((err!=0)|| !isDir)
			{
				cerr<<"Either does not exist or is not directory: File " << p<< " Err: "<< err << " isDir: " << isDir << " mode: "<<DirInfo.st_mode<< " Error: " << strerror(errno) << endl;
			}
			return (err == 0) && isDir;
		}

		//Uses stat to check if the specified file exists
		static bool exists(string p)
		{
			struct stat DirInfo;
			int err = stat(p.c_str(), &DirInfo);
			return (err == 0);
		}
		//Gets the file size of a file (the file must exist)
		static FileOffset getFileSize(string p)
		{
			struct stat DirInfo;
			int err = stat(p.c_str(), &DirInfo);
			if (err != 0)
				cerr << "Tried to get file size when file does not exist!" << endl;
			return DirInfo.st_size;
		}
		//Gets a list of all files in the directory, excluding any subfolders in the directory
		static vector<string> getAllFilesInDir(string directory)
		{
			vector<string> validFiles;
			DIR* testDir;
			dirent* entry;
			testDir = opendir(directory.c_str());
			while ((entry = readdir(testDir)))
			{
				string fullPath = combinePaths(directory, string(entry->d_name));

				struct stat dirInfo;
				bool err = (stat(fullPath.c_str(), &dirInfo) != 0);
				bool isDir = S_ISDIR(dirInfo.st_mode);
				bool aFile = !(err || isDir);
				if (aFile)
					validFiles.push_back(fullPath);

			}
			closedir(testDir);
			return validFiles;
		}

		//Because atoi returns 0 when the string is invalid, there's no easy way
		//to distinguish between "0" and an invalid string. This method helps with
		//that by testing the string to ensure it is only whitespace and '0's.
		static bool stringActuallyZero(string toTest)
		{
			for (unsigned int var = 0; var < toTest.length(); var++)
			{
				if (toTest[var] != '0' && toTest[var] >= ' ')
					return false;
			}
			return true;
		}
	};

} /* namespace TraceviewerServer */
#endif /* FILEUTILS_H_ */


text:
<?php

/*

    MEDIAN EMBEDDED PLAYER PAGE
        cyle gage, emerson college, 2014

*/

// if ?ap is set, enable autoplay
if (isset($_GET['ap']) && trim($_GET['ap']) != 'false') {
	$autoplay = true;
} else {
	$autoplay = false;
}

// if ?cc is set, enable captions
if (isset($_GET['cc']) && trim($_GET['cc']) != 'false') {
	$force_subtitles = true;
} else {
	$force_subtitles = false;
}

require_once('/median-webapp/includes/error_functions.php');

if (!isset($_GET['mid']) || trim($_GET['mid']) == '' || !is_numeric($_GET['mid'])) {
	bailout('No Median Entry ID specified.', $current_user['userid'], null, null, false);
}

$mid = (int) $_GET['mid'] * 1;

require_once('/median-webapp/config/config.php');
require_once('/median-webapp/includes/permission_functions.php');
require_once('/median-webapp/includes/media_functions.php');

$login_required = doesMediaRequireLogin($mid);

require_once('/median-webapp/includes/login_check.php');

$media_info = getMediaInfo($mid);

if ($media_info == false) {
	// uhh media does not exist!
	bailout('Sorry, but the media entry with that ID does not exist!', $current_user['userid'], $mid, null, false);
}

// can the current user view this entry?
$can_view_result = canViewMedia($current_user['userid'], $mid);

if ($can_view_result < 1) {
    switch ($can_view_result) {
        case -100:
        if ($current_user['loggedin']) {
            bailout('Sorry, but this entry is restricted to a higher user level.', $current_user['userid'], $mid, null, false);
        } else {
            bailout('Sorry, but this entry is restricted to a higher user level. Try logging in to see this entry, you\'ll be brought back to this page after logging in.', 0, $mid, null, false);
        }
        break;
        case -200:
        if ($current_user['loggedin']) {
            bailout('Sorry, but this entry is class-only for a class you are not in.', $current_user['userid'], $mid, null, false);
        } else {
            bailout('Sorry, but this entry is class-only. Try logging in to see this entry, you\'ll be brought back to this page after logging in.', 0, $mid, null, false);
        }
        break;
        case -300:
        if ($current_user['loggedin']) {
            bailout('Sorry, but this entry is restricted to a certain group you are not in.', $current_user['userid'], $mid, null, false);
        } else {
            bailout('Sorry, but this entry is restricted to a certain group. Try logging in to see this entry, you\'ll be brought back to this page after logging in.', 0, $mid, null, false);
        }
        break;
        case -400:
        bailout('Sorry, but this entry has not yet been enabled. Please be patient, Median is working as fast as possible to get this entry ready!', $current_user['userid'], $mid, null, false);
        break;
        case 0:
        default:
        bailout('Sorry, but you are not allowed to view this entry for some reason.', $current_user['userid'], $mid, null, false);
    }
}

if (isset($media_info['pending']) && $media_info['pending'] == true) {
    bailout('Sorry, but this entry is pending, meaning the uploader has not actually submtited the wizard.', $current_user['userid'], $mid, null, false);
}

// password check!
if (isset($media_info['pwd']) && isset($_POST['p'])) {
    // check password!
    $pwd_check = checkMediaPassword($mid, trim($_POST['p']));
    if ($pwd_check != true) {
        bailout('Sorry, but the password you entered is incorrect.', $current_user['userid'], $mid, null, false);
    }
} else if (isset($media_info['pwd']) && !isset($_POST['p']) && $current_user['userlevel'] > 1) {
    // show password form
    require_once('/median-webapp/www/password.php');
    die();
}

// if this is on the Emerson website, Jason will send along a parentURL query string. capture it.
$embed_parent_frame_url = '';
if (isset($_GET['parentURL']) && trim($_GET['parentURL']) != '') {
	$embed_parent_frame_url = trim($_GET['parentURL']);
}

// update view count
updateViewCount($mid, $current_user['userid'], true, $embed_parent_frame_url); // third param is true for tracking embeds vs median-based viewing

// check if an iOS device is viewing this...
$is_ios = false;
if (stripos($_SERVER['HTTP_USER_AGENT'], 'ipad')) {
	$is_ios = true;
	$is_ipad = true;
	$is_iphone = false;
} else if (stripos($_SERVER['HTTP_USER_AGENT'], 'iphone')) {
	$is_ios = true;
	$is_iphone = true;
	$is_ipad = false;
}

$can_be_html5 = canBeHTML5($mid);
if ($media_info['mt'] == 'clip') {
	$can_be_html5 = false;
}
?><!doctype html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Embedded Content - Median - <?php echo $median_institution_name; ?></title>
<link rel="stylesheet" href="/css/embed.css">

<?php

/*

    start player selection and display based on media type and client capability

*/

if ($media_info['mt'] == 'video' || $media_info['mt'] == 'clip') { // videos

    if ($is_ios) {
        if (!$can_be_html5) {
            // sorry, no HTML5
            ?>

Sorry, this entry cannot be played on iOS devices for security reasons. Read this help doc to find out why.

            <?php
        } else {
            // ok, load up an HTML5 version of the video
			$file_location = getHTMLFIVElink($media_info['mid']);
            if ($file_location != false) {
            ?>

            <video width="100%" height="100%" controls="controls" preload="metadata" <?php if ($autoplay) { echo 'autoplay="autoplay"'; } ?>>
                <source src="<?php echo $file_location; ?>"  type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />

Your browser or device does not support HTML5 H264 video, sorry.

            </video>

            <?php
            } else {
                ?>

Sorry, I could not find a version of the video for your platform.

                <?php
            }
        } // end HTML5 check
    } else {
        $manifest = getPlayerManifest($media_info['mid']);
        $flashvars = 'src='.$manifest;
        if (alwaysUseSubtitles($current_user['userid']) || $force_subtitles) {
            $flashvars .= '&cc=1';
        }
        if ($autoplay) {
            $flashvars .= '&ap=1';
        }
        ?>

            <object width="100%" height="100%">
                <param name="movie" value="<?php echo $median_base_url; ?>m6_video_player.swf"></param>
                <param name="flashvars" value="<?php echo $flashvars; ?>"></param>
                <param name="allowFullScreen" value="true"></param>
                <param name="allowscriptaccess" value="always"></param>
                <param name="wmode" value="transparent"></param>
                <embed
                    src="<?php echo $median_base_url; ?>m6_video_player.swf"
                    type="application/x-shockwave-flash"
                    allowscriptaccess="always"
                    allowfullscreen="true"
                    wmode="transparent"
                    width="100%"
                    height="100%"
                    flashvars="<?php echo $flashvars; ?>">
                </embed>
            </object>

        <?php
    } // end if iOS check

} else if ($media_info['mt'] == 'audio') { // audio

    // just display an <audio> tag for ALL devices
	$file_location = getHTMLFIVElink($media_info['mid']);
    if ($file_location != false) {
		?>

            <audio height="30" width="100%" src="<?php echo $file_location; ?>" controls="controls" preload="metadata" <?php if ($autoplay) { echo 'autoplay="autoplay"'; } ?>>
It seems your browser or device does not support audio, sorry.
</audio>

        <?php
    } else {
        ?>

Sorry, I could not find a version of the audio for your platform.

        <?php
    }

} else if ($media_info['mt'] == 'image') { // image

	$file_location = getHTMLFIVElink($media_info['mid']);

    // oh god. for now just show the damn image. i hate flash.
    ?>

<a href="<?php echo $file_location; ?>"><img src="<?php echo $file_location; ?>" />

    <?php

} else if ($media_info['mt'] == 'doc') { // document
    ?>

This is a link to a document. Median does not screen or filter these documents, so please be careful.

<a class="button success large" target="_blank" href="<?php echo $median_base_url; ?>download/<?php echo $media_info['mid']; ?>">Download Document »

    <?php
} else if ($media_info['mt'] == 'link') { // link
    ?>

This is a link to an external site. Median does not screen or filter these links, so please be careful.

Site URL: <?php echo $media_info['url']; ?>

<a class="button success large" href="<?php echo $media_info['url']; ?>" target="_blank">Go to site »

    <?php

} else { // uhhhh unknown

    ?>

Uhhhhhh...

    <?php

} // end player selection and display

?>


text:
import express from "express";
const router = new express.Router();

router.get("/", (req, res) => {
    res.render("coupling");
});

module.exports = router;


text:
package com.google.cloud.dataflow.sdk.testing;

import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.anything;
import static com.google.cloud.dataflow.sdk.testing.SerializableMatchers.not;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.coders.AtomicCoder;
import com.google.cloud.dataflow.sdk.coders.CoderException;
import com.google.cloud.dataflow.sdk.runners.DirectPipelineRunner;
import com.google.cloud.dataflow.sdk.transforms.Create;
import com.google.cloud.dataflow.sdk.transforms.SerializableFunction;
import com.google.cloud.dataflow.sdk.util.common.ElementByteSizeObserver;
import com.google.cloud.dataflow.sdk.values.PCollection;

import com.fasterxml.jackson.annotation.JsonCreator;

import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

/**
 * Test case for {@link DataflowAssert}.
 */
@RunWith(JUnit4.class)
public class DataflowAssertTest implements Serializable {
  @Rule
  public transient ExpectedException thrown = ExpectedException.none();

  private static class NotSerializableObject {

    @Override
    public boolean equals(Object other) {
      return (other instanceof NotSerializableObject);
    }

    @Override
    public int hashCode() {
      return 73;
    }
  }

  private static class NotSerializableObjectCoder extends AtomicCoder<NotSerializableObject> {
    private NotSerializableObjectCoder() { }
    private static final NotSerializableObjectCoder INSTANCE = new NotSerializableObjectCoder();

    @JsonCreator
    public static NotSerializableObjectCoder of() {
      return INSTANCE;
    }

    @Override
    public void encode(NotSerializableObject value, OutputStream outStream, Context context)
        throws CoderException, IOException {
    }

    @Override
    public NotSerializableObject decode(InputStream inStream, Context context)
        throws CoderException, IOException {
      return new NotSerializableObject();
    }

    @Override
    public boolean isRegisterByteSizeObserverCheap(NotSerializableObject value, Context context) {
      return true;
    }

    @Override
    public void registerByteSizeObserver(
        NotSerializableObject value, ElementByteSizeObserver observer, Context context)
        throws Exception {
      observer.update(0L);
    }
  }

  /**
   * A {@link DataflowAssert} about the contents of a {@link PCollection}
   * must not require the contents of the {@link PCollection} to be
   * serializable.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testContainsInAnyOrderNotSerializable() throws Exception {
    Pipeline pipeline = TestPipeline.create();

    PCollection<NotSerializableObject> pcollection = pipeline
        .apply(Create.of(
          new NotSerializableObject(),
          new NotSerializableObject())
            .withCoder(NotSerializableObjectCoder.of()));

    DataflowAssert.that(pcollection).containsInAnyOrder(
      new NotSerializableObject(),
      new NotSerializableObject());

    pipeline.run();
  }

  /**
   * A {@link DataflowAssert} about the contents of a {@link PCollection}
   * is allows to be verified by an arbitrary {@link SerializableFunction},
   * though.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testSerializablePredicate() throws Exception {
    Pipeline pipeline = TestPipeline.create();

    PCollection<NotSerializableObject> pcollection = pipeline
        .apply(Create.of(
          new NotSerializableObject(),
          new NotSerializableObject())
            .withCoder(NotSerializableObjectCoder.of()));

    DataflowAssert.that(pcollection).satisfies(
        new SerializableFunction<Iterable<NotSerializableObject>, Void>() {
          @Override
          public Void apply(Iterable<NotSerializableObject> contents) {
            return null; // no problem!
          }
        });

    pipeline.run();
  }

  /**
   * Basic test of succeeding {@link DataflowAssert} using a {@link SerializableMatcher}.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testBasicMatcherSuccess() throws Exception {
    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(42));
    DataflowAssert.that(pcollection).containsInAnyOrder(anything());
    pipeline.run();
  }

  /**
   * Basic test of failing {@link DataflowAssert} using a {@link SerializableMatcher}.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testBasicMatcherFailure() throws Exception {
    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(42));
    DataflowAssert.that(pcollection).containsInAnyOrder(not(anything()));
    runExpectingAssertionFailure(pipeline);
  }

  /**
   * Test that we throw an error at pipeline construction time when the user mistakenly uses
   * {@code DataflowAssert.thatSingleton().equals()} instead of the test method {@code .isEqualTo}.
   */
  @SuppressWarnings("deprecation") // test of deprecated function
  @Test
  public void testDataflowAssertEqualsSingletonUnsupported() throws Exception {
    thrown.expect(UnsupportedOperationException.class);
    thrown.expectMessage("isEqualTo");

    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(42));
    DataflowAssert.thatSingleton(pcollection).equals(42);
  }

  /**
   * Test that we throw an error at pipeline construction time when the user mistakenly uses
   * {@code DataflowAssert.that().equals()} instead of the test method {@code .containsInAnyOrder}.
   */
  @SuppressWarnings("deprecation") // test of deprecated function
  @Test
  public void testDataflowAssertEqualsIterableUnsupported() throws Exception {
    thrown.expect(UnsupportedOperationException.class);
    thrown.expectMessage("containsInAnyOrder");

    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(42));
    DataflowAssert.that(pcollection).equals(42);
  }

  /**
   * Test that {@code DataflowAssert.thatSingleton().hashCode()} is unsupported.
   * See {@link #testDataflowAssertEqualsSingletonUnsupported}.
   */
  @SuppressWarnings("deprecation") // test of deprecated function
  @Test
  public void testDataflowAssertHashCodeSingletonUnsupported() throws Exception {
    thrown.expect(UnsupportedOperationException.class);
    thrown.expectMessage(".hashCode() is not supported.");

    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(42));
    DataflowAssert.thatSingleton(pcollection).hashCode();
  }

  /**
   * Test that {@code DataflowAssert.thatIterable().hashCode()} is unsupported.
   * See {@link #testDataflowAssertEqualsIterableUnsupported}.
   */
  @SuppressWarnings("deprecation") // test of deprecated function
  @Test
  public void testDataflowAssertHashCodeIterableUnsupported() throws Exception {
    thrown.expect(UnsupportedOperationException.class);
    thrown.expectMessage(".hashCode() is not supported.");

    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(42));
    DataflowAssert.that(pcollection).hashCode();
  }

  /**
   * Basic test for {@code isEqualTo}.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testIsEqualTo() throws Exception {
    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(43));
    DataflowAssert.thatSingleton(pcollection).isEqualTo(43);
    pipeline.run();
  }

  /**
   * Basic test for {@code notEqualTo}.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testNotEqualTo() throws Exception {
    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(43));
    DataflowAssert.thatSingleton(pcollection).notEqualTo(42);
    pipeline.run();
  }

  /**
   * Tests that {@code containsInAnyOrder} is actually order-independent.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testContainsInAnyOrder() throws Exception {
    Pipeline pipeline = TestPipeline.create();
    PCollection<Integer> pcollection = pipeline.apply(Create.of(1, 2, 3, 4));
    DataflowAssert.that(pcollection).containsInAnyOrder(2, 1, 4, 3);
    pipeline.run();
  }

  /**
   * Tests that {@code containsInAnyOrder} fails when and how it should.
   */
  @Test
  @Category(RunnableOnService.class)
  public void testContainsInAnyOrderFalse() throws Exception {
    Pipeline pipeline = TestPipeline.create();

    PCollection<Integer> pcollection = pipeline
        .apply(Create.of(1, 2, 3, 4));

    DataflowAssert.that(pcollection).containsInAnyOrder(2, 1, 4, 3, 7);

    // The service runner does not give an exception we can usefully inspect.
    @Nullable
    Throwable exc = runExpectingAssertionFailure(pipeline);
    Pattern expectedPattern = Pattern.compile(
        "Expected: iterable over \\[((<4>|<7>|<3>|<2>|<1>)(, )?){5}\\] in any order");
    if (exc != null) {
      // A loose pattern, but should get the job done.
      assertTrue("Expected error message from DataflowAssert with substring matching "
          + expectedPattern + " but the message was \"" + exc.getMessage() + "\"",
          expectedPattern.matcher(exc.getMessage()).find());
    }
  }

  private static Throwable runExpectingAssertionFailure(Pipeline pipeline) {
    // Even though this test will succeed or fail adequately whether local or on the service,
    // it results in a different exception depending on the runner.
    if (pipeline.getRunner() instanceof DirectPipelineRunner) {
      // We cannot use thrown.expect(AssertionError.class) because the AssertionError
      // is first caught by JUnit and causes a test failure.
      try {
        pipeline.run();
      } catch (AssertionError exc) {
        return exc;
      }
    } else if (pipeline.getRunner() instanceof TestDataflowPipelineRunner) {
      // Separately, if this is run on the service, then the TestDataflowPipelineRunner throws
      // an IllegalStateException with a basic message.
      try {
        pipeline.run();
      } catch (IllegalStateException exc) {
        assertThat(exc.getMessage(), containsString("The dataflow failed."));
        return null;
      }
    }
    fail("assertion should have failed");
    throw new RuntimeException("unreachable");
  }
}


text:
@XmlSchema(namespace = "http://geode.apache.org/schema/lucene",
    xmlns = {@XmlNs(prefix = "lucene", namespaceURI = "http://geode.apache.org/schema/lucene")},
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.apache.geode.cache.lucene.management.configuration;

import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlSchema;


text:
#include "arm_math.h"

/**
 * @ingroup groupMath
 */

/**
 * @addtogroup offset
 * @{
 */

/**
 * @brief  Adds a constant offset to a Q31 vector.
 * @param[in]  *pSrc points to the input vector
 * @param[in]  offset is the offset to be added
 * @param[out]  *pDst points to the output vector
 * @param[in]  blockSize number of samples in the vector
 * @return none.
 *
 * <b>Scaling and Overflow Behavior:</b>
 * \par
 * The function uses saturating arithmetic.
 * Results outside of the allowable Q31 range [0x80000000 0x7FFFFFFF] are saturated.
 */

void arm_offset_q31(
  q31_t * pSrc,
  q31_t offset,
  q31_t * pDst,
  uint32_t blockSize)
{
  uint32_t blkCnt;                               /* loop counter */

#ifndef ARM_MATH_CM0_FAMILY

/* Run the below code for Cortex-M4 and Cortex-M3 */
  q31_t in1, in2, in3, in4;

  /*loop Unrolling */
  blkCnt = blockSize >> 2u;

  /* First part of the processing with loop unrolling.  Compute 4 outputs at a time.
   ** a second loop below computes the remaining 1 to 3 samples. */
  while(blkCnt > 0u)
  {
    /* C = A + offset */
    /* Add offset and then store the results in the destination buffer. */
    in1 = *pSrc++;
    in2 = *pSrc++;
    in3 = *pSrc++;
    in4 = *pSrc++;

    *pDst++ = __QADD(in1, offset);
    *pDst++ = __QADD(in2, offset);
    *pDst++ = __QADD(in3, offset);
    *pDst++ = __QADD(in4, offset);

    /* Decrement the loop counter */
    blkCnt--;
  }

  /* If the blockSize is not a multiple of 4, compute any remaining output samples here.
   ** No loop unrolling is used. */
  blkCnt = blockSize % 0x4u;

  while(blkCnt > 0u)
  {
    /* C = A + offset */
    /* Add offset and then store the result in the destination buffer. */
    *pDst++ = __QADD(*pSrc++, offset);

    /* Decrement the loop counter */
    blkCnt--;
  }

#else

  /* Run the below code for Cortex-M0 */

  /* Initialize blkCnt with number of samples */
  blkCnt = blockSize;

  while(blkCnt > 0u)
  {
    /* C = A + offset */
    /* Add offset and then store the result in the destination buffer. */
    *pDst++ = (q31_t) clip_q63_to_q31((q63_t) * pSrc++ + offset);

    /* Decrement the loop counter */
    blkCnt--;
  }

#endif /* #ifndef ARM_MATH_CM0_FAMILY */

}

/**
 * @} end of offset group
 */


text:
package org.apache.solr.update;

import java.io.File;

import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.IndexSchemaFactory;
import org.junit.Test;

/**
 * Testcase for {@link SolrIndexConfig}
 */
public class SolrIndexConfigTest extends SolrTestCaseJ4 {

  @Test
  public void testFailingSolrIndexConfigCreation() {
    try {
      SolrConfig solrConfig = new SolrConfig("bad-mp-solrconfig.xml");
      SolrIndexConfig solrIndexConfig = new SolrIndexConfig(solrConfig, null, null);
      IndexSchema indexSchema = IndexSchemaFactory.buildIndexSchema("schema.xml", solrConfig);
      solrIndexConfig.toIndexWriterConfig(indexSchema);
      fail("a mergePolicy should have an empty constructor in order to be instantiated in Solr thus this should fail ");
    } catch (Exception e) {
      // it failed as expected
    }
  }

  @Test
  public void testTieredMPSolrIndexConfigCreation() throws Exception {
    SolrConfig solrConfig = new SolrConfig("solr" + File.separator
        + "collection1", "solrconfig-mergepolicy.xml", null);
    SolrIndexConfig solrIndexConfig = new SolrIndexConfig(solrConfig, null,
        null);
    assertNotNull(solrIndexConfig);
    assertEquals("org.apache.lucene.index.TieredMergePolicy",
        solrIndexConfig.defaultMergePolicyClassName);
    IndexSchema indexSchema = IndexSchemaFactory.buildIndexSchema("schema.xml", solrConfig);
    solrIndexConfig.toIndexWriterConfig(indexSchema);
  }

}


text:
require 'spec_helper'

describe Github::Activity::Events, '#received' do
  let(:user)   { 'peter-murach' }
  let(:request_path) { "/users/#{user}/received_events" }
  let(:body) { fixture('events/events.json') }
  let(:status) { 200 }

  before {
    stub_get(request_path).to_return(:body => body, :status => status,
      :headers => {:content_type => "application/json; charset=utf-8"})
  }

  after { reset_authentication_for subject }

  context "resource found" do

    it "should fail to get resource without username" do
      expect { subject.received }.to raise_error(ArgumentError)
    end

    it "should get the resources" do
      subject.received user
      a_get(request_path).should have_been_made
    end

    it_should_behave_like 'an array of resources' do
      let(:requestable) { subject.received user }
    end

    it "should get event information" do
      events = subject.received user
      events.first.type.should == 'Event'
    end

    it "should yield to a block" do
      yielded = []
      result = subject.received(user) { |obj| yielded << obj }
      yielded.should == result
    end
  end

  context "all public resources found" do
    let(:request_path) { "/users/#{user}/received_events/public" }

    it "should get the resources" do
      subject.received user, :public => true
      a_get(request_path).should have_been_made
    end

    it_should_behave_like 'an array of resources' do
      let(:requestable) { subject.received user, :public => true }
    end

    it "should get event information" do
      events = subject.received user, :public => true
      events.first.type.should == 'Event'
    end

    it "should yield to a block" do
      yielded = []
      result = subject.received(user, :public => true) { |obj| yielded << obj }
      yielded.should == result
    end
  end

  it_should_behave_like 'request failure' do
    let(:requestable) { subject.received user }
  end
end # received


text:
namespace chrome {
namespace test {

using content::BrowserThread;

typedef std::vector<int> DeviceIndices;

// StorageMonitorWinTest -------------------------------------------------------

class StorageMonitorWinTest : public testing::Test {
 public:
  StorageMonitorWinTest();
  virtual ~StorageMonitorWinTest();

 protected:
  // testing::Test:
  virtual void SetUp() OVERRIDE;
  virtual void TearDown() OVERRIDE;

  void PreAttachDevices();

  // Runs all the pending tasks on UI thread, FILE thread and blocking thread.
  void RunUntilIdle();

  void DoMassStorageDeviceAttachedTest(const DeviceIndices& device_indices);
  void DoMassStorageDevicesDetachedTest(const DeviceIndices& device_indices);

  // Injects a device attach or detach change (depending on the value of
  // |test_attach|) and tests that the appropriate handler is called.
  void DoMTPDeviceTest(const string16& pnp_device_id, bool test_attach);

  // Gets the MTP details of the storage specified by the |storage_device_id|.
  // On success, returns true and fills in |pnp_device_id| and
  // |storage_object_id|.
  bool GetMTPStorageInfo(const std::string& storage_device_id,
                         string16* pnp_device_id,
                         string16* storage_object_id);

  scoped_ptr<TestStorageMonitorWin> monitor_;

  // Weak pointer; owned by the device notifications class.
  TestVolumeMountWatcherWin* volume_mount_watcher_;

  MockRemovableStorageObserver observer_;

 private:
  MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;
};

StorageMonitorWinTest::StorageMonitorWinTest()
    : ui_thread_(BrowserThread::UI, &message_loop_),
      file_thread_(BrowserThread::FILE, &message_loop_) {
}

StorageMonitorWinTest::~StorageMonitorWinTest() {
}

void StorageMonitorWinTest::SetUp() {
  ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI));
  volume_mount_watcher_ = new TestVolumeMountWatcherWin;
  monitor_.reset(new TestStorageMonitorWin(volume_mount_watcher_,
                                           new TestPortableDeviceWatcherWin));
  monitor_->Init();
  RunUntilIdle();
  monitor_->AddObserver(&observer_);
}

void StorageMonitorWinTest::TearDown() {
  RunUntilIdle();
  monitor_->RemoveObserver(&observer_);
  volume_mount_watcher_->ShutdownWorkerPool();
  monitor_.reset(NULL);
}

void StorageMonitorWinTest::PreAttachDevices() {
  monitor_.reset();
  volume_mount_watcher_ = new TestVolumeMountWatcherWin;
  volume_mount_watcher_->SetAttachedDevicesFake();

  int expect_attach_calls = 0;
  std::vector<base::FilePath> initial_devices =
      volume_mount_watcher_->GetAttachedDevicesCallback().Run();
  for (std::vector<base::FilePath>::const_iterator it = initial_devices.begin();
       it != initial_devices.end(); ++it) {
    bool removable;
    ASSERT_TRUE(volume_mount_watcher_->GetDeviceRemovable(*it, &removable));
    if (removable)
      expect_attach_calls++;
  }

  monitor_.reset(new TestStorageMonitorWin(volume_mount_watcher_,
                                           new TestPortableDeviceWatcherWin));
  monitor_->AddObserver(&observer_);
  monitor_->Init();

  EXPECT_EQ(0u, volume_mount_watcher_->devices_checked().size());

  // This dance is because attachment bounces through a couple of
  // closures, which need to be executed to finish the process.
  RunUntilIdle();
  volume_mount_watcher_->FlushWorkerPoolForTesting();
  RunUntilIdle();

  std::vector<base::FilePath> checked_devices =
      volume_mount_watcher_->devices_checked();
  sort(checked_devices.begin(), checked_devices.end());
  EXPECT_EQ(initial_devices, checked_devices);
  EXPECT_EQ(expect_attach_calls, observer_.attach_calls());
  EXPECT_EQ(0, observer_.detach_calls());
}

void StorageMonitorWinTest::RunUntilIdle() {
  volume_mount_watcher_->FlushWorkerPoolForTesting();
  message_loop_.RunUntilIdle();
}

void StorageMonitorWinTest::DoMassStorageDeviceAttachedTest(
    const DeviceIndices& device_indices) {
  DEV_BROADCAST_VOLUME volume_broadcast;
  volume_broadcast.dbcv_size = sizeof(volume_broadcast);
  volume_broadcast.dbcv_devicetype = DBT_DEVTYP_VOLUME;
  volume_broadcast.dbcv_unitmask = 0x0;
  volume_broadcast.dbcv_flags = 0x0;

  int expect_attach_calls = 0;
  for (DeviceIndices::const_iterator it = device_indices.begin();
       it != device_indices.end(); ++it) {
    volume_broadcast.dbcv_unitmask |= 0x1 << *it;
    bool removable;
    ASSERT_TRUE(volume_mount_watcher_->GetDeviceRemovable(
        VolumeMountWatcherWin::DriveNumberToFilePath(*it), &removable));
    if (removable)
      expect_attach_calls++;
  }
  monitor_->InjectDeviceChange(DBT_DEVICEARRIVAL,
                               reinterpret_cast<DWORD>(&volume_broadcast));

  RunUntilIdle();
  volume_mount_watcher_->FlushWorkerPoolForTesting();
  RunUntilIdle();

  EXPECT_EQ(expect_attach_calls, observer_.attach_calls());
  EXPECT_EQ(0, observer_.detach_calls());
}

void StorageMonitorWinTest::DoMassStorageDevicesDetachedTest(
    const DeviceIndices& device_indices) {
  DEV_BROADCAST_VOLUME volume_broadcast;
  volume_broadcast.dbcv_size = sizeof(volume_broadcast);
  volume_broadcast.dbcv_devicetype = DBT_DEVTYP_VOLUME;
  volume_broadcast.dbcv_unitmask = 0x0;
  volume_broadcast.dbcv_flags = 0x0;

  int pre_attach_calls = observer_.attach_calls();
  int expect_detach_calls = 0;
  for (DeviceIndices::const_iterator it = device_indices.begin();
       it != device_indices.end(); ++it) {
    volume_broadcast.dbcv_unitmask |= 0x1 << *it;
    StorageInfo info;
    ASSERT_TRUE(volume_mount_watcher_->GetDeviceInfo(
        VolumeMountWatcherWin::DriveNumberToFilePath(*it), &info));
    if (StorageInfo::IsRemovableDevice(info.device_id))
      expect_detach_calls++;
  }
  monitor_->InjectDeviceChange(DBT_DEVICEREMOVECOMPLETE,
                               reinterpret_cast<DWORD>(&volume_broadcast));
  RunUntilIdle();
  EXPECT_EQ(pre_attach_calls, observer_.attach_calls());
  EXPECT_EQ(expect_detach_calls, observer_.detach_calls());
}

void StorageMonitorWinTest::DoMTPDeviceTest(const string16& pnp_device_id,
                                            bool test_attach) {
  GUID guidDevInterface = GUID_NULL;
  HRESULT hr = CLSIDFromString(kWPDDevInterfaceGUID, &guidDevInterface);
  if (FAILED(hr))
    return;

  size_t device_id_size = pnp_device_id.size() * sizeof(char16);
  size_t size = sizeof(DEV_BROADCAST_DEVICEINTERFACE) + device_id_size;
  scoped_ptr_malloc<DEV_BROADCAST_DEVICEINTERFACE> dev_interface_broadcast(
      static_cast<DEV_BROADCAST_DEVICEINTERFACE*>(malloc(size)));
  DCHECK(dev_interface_broadcast.get());
  ZeroMemory(dev_interface_broadcast.get(), size);
  dev_interface_broadcast->dbcc_size = size;
  dev_interface_broadcast->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
  dev_interface_broadcast->dbcc_classguid = guidDevInterface;
  memcpy(dev_interface_broadcast->dbcc_name, pnp_device_id.data(),
         device_id_size);

  int expect_attach_calls = observer_.attach_calls();
  int expect_detach_calls = observer_.detach_calls();
  PortableDeviceWatcherWin::StorageObjectIDs storage_object_ids =
      TestPortableDeviceWatcherWin::GetMTPStorageObjectIds(pnp_device_id);
  for (PortableDeviceWatcherWin::StorageObjectIDs::const_iterator it =
       storage_object_ids.begin(); it != storage_object_ids.end(); ++it) {
    std::string unique_id;
    string16 name;
    string16 location;
    TestPortableDeviceWatcherWin::GetMTPStorageDetails(pnp_device_id, *it,
                                                       &location, &unique_id,
                                                       &name);
    if (test_attach && !name.empty() && !unique_id.empty())
      expect_attach_calls++;
    else if (!name.empty() && !unique_id.empty())
      expect_detach_calls++;
  }

  monitor_->InjectDeviceChange(
      test_attach ? DBT_DEVICEARRIVAL : DBT_DEVICEREMOVECOMPLETE,
      reinterpret_cast<DWORD>(dev_interface_broadcast.get()));

  RunUntilIdle();
  EXPECT_EQ(expect_attach_calls, observer_.attach_calls());
  EXPECT_EQ(expect_detach_calls, observer_.detach_calls());
}

bool StorageMonitorWinTest::GetMTPStorageInfo(
    const std::string& storage_device_id,
    string16* pnp_device_id,
    string16* storage_object_id) {
  return monitor_->GetMTPStorageInfoFromDeviceId(storage_device_id,
                                                 pnp_device_id,
                                                 storage_object_id);
}

TEST_F(StorageMonitorWinTest, RandomMessage) {
  monitor_->InjectDeviceChange(DBT_DEVICEQUERYREMOVE, NULL);
  RunUntilIdle();
}

TEST_F(StorageMonitorWinTest, DevicesAttached) {
  DeviceIndices device_indices;
  device_indices.push_back(1);  // B
  device_indices.push_back(5);  // F
  device_indices.push_back(7);  // H
  device_indices.push_back(13);  // N
  DoMassStorageDeviceAttachedTest(device_indices);

  StorageInfo info;
  EXPECT_TRUE(monitor_->volume_mount_watcher()->GetDeviceInfo(
      base::FilePath(ASCIIToUTF16("F:\\")), &info));
  EXPECT_EQ(ASCIIToUTF16("F:\\"), info.location);
  EXPECT_EQ("dcim:\\\\?\\Volume{F0000000-0000-0000-0000-000000000000}\\",
            info.device_id);
  EXPECT_EQ(ASCIIToUTF16("F:\\ Drive"), info.storage_label);

  EXPECT_FALSE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("G:\\")), &info));
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\")), &info));
  StorageInfo info1;
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\subdir")), &info1));
  StorageInfo info2;
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\subdir\\sub")), &info2));
  EXPECT_EQ(ASCIIToUTF16("F:\\ Drive"), info.storage_label);
  EXPECT_EQ(ASCIIToUTF16("F:\\ Drive"), info1.storage_label);
  EXPECT_EQ(ASCIIToUTF16("F:\\ Drive"), info2.storage_label);
}

TEST_F(StorageMonitorWinTest, PathMountDevices) {
  PreAttachDevices();

  volume_mount_watcher_->AddDeviceForTesting(
      base::FilePath(FILE_PATH_LITERAL("F:\\mount1")),
      "dcim:mount1", L"mount1", 100);
  volume_mount_watcher_->AddDeviceForTesting(
      base::FilePath(FILE_PATH_LITERAL("F:\\mount1\\subdir")),
      "dcim:mount1subdir", L"mount1subdir", 100);
  volume_mount_watcher_->AddDeviceForTesting(
      base::FilePath(FILE_PATH_LITERAL("F:\\mount2")),
      "dcim:mount2", L"mount2", 100);
  RunUntilIdle();
  EXPECT_EQ(9, monitor_->GetAttachedStorage().size());

  StorageInfo info;
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\dir")), &info));
  EXPECT_EQ(L"", info.name);
  EXPECT_EQ(L"F:\\ Drive", info.storage_label);
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\mount1")), &info));
  EXPECT_EQ(L"mount1", info.name);
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\mount1\\dir")), &info));
  EXPECT_EQ(L"mount1", info.name);
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\mount2\\dir")), &info));
  EXPECT_EQ(L"mount2", info.name);
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\mount1\\subdir")), &info));
  EXPECT_EQ(L"mount1subdir", info.name);
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\mount1\\subdir\\dir")), &info));
  EXPECT_EQ(L"mount1subdir", info.name);
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(
      base::FilePath(ASCIIToUTF16("F:\\mount1\\subdir\\dir\\dir")), &info));
  EXPECT_EQ(L"mount1subdir", info.name);
}

TEST_F(StorageMonitorWinTest, DevicesAttachedHighBoundary) {
  DeviceIndices device_indices;
  device_indices.push_back(25);

  DoMassStorageDeviceAttachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DevicesAttachedLowBoundary) {
  DeviceIndices device_indices;
  device_indices.push_back(0);

  DoMassStorageDeviceAttachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DevicesAttachedAdjacentBits) {
  DeviceIndices device_indices;
  device_indices.push_back(0);
  device_indices.push_back(1);
  device_indices.push_back(2);
  device_indices.push_back(3);

  DoMassStorageDeviceAttachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DevicesDetached) {
  PreAttachDevices();

  DeviceIndices device_indices;
  device_indices.push_back(1);
  device_indices.push_back(5);
  device_indices.push_back(7);
  device_indices.push_back(13);

  DoMassStorageDevicesDetachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DevicesDetachedHighBoundary) {
  PreAttachDevices();

  DeviceIndices device_indices;
  device_indices.push_back(25);

  DoMassStorageDevicesDetachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DevicesDetachedLowBoundary) {
  PreAttachDevices();

  DeviceIndices device_indices;
  device_indices.push_back(0);

  DoMassStorageDevicesDetachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DevicesDetachedAdjacentBits) {
  PreAttachDevices();

  DeviceIndices device_indices;
  device_indices.push_back(0);
  device_indices.push_back(1);
  device_indices.push_back(2);
  device_indices.push_back(3);

  DoMassStorageDevicesDetachedTest(device_indices);
}

TEST_F(StorageMonitorWinTest, DuplicateAttachCheckSuppressed) {
  // Make sure the original C: mount notification makes it all the
  // way through.
  RunUntilIdle();
  volume_mount_watcher_->FlushWorkerPoolForTesting();
  RunUntilIdle();

  volume_mount_watcher_->BlockDeviceCheckForTesting();
  base::FilePath kAttachedDevicePath =
      VolumeMountWatcherWin::DriveNumberToFilePath(8);  // I:

  DEV_BROADCAST_VOLUME volume_broadcast;
  volume_broadcast.dbcv_size = sizeof(volume_broadcast);
  volume_broadcast.dbcv_devicetype = DBT_DEVTYP_VOLUME;
  volume_broadcast.dbcv_flags = 0x0;
  volume_broadcast.dbcv_unitmask = 0x100;  // I: drive
  monitor_->InjectDeviceChange(DBT_DEVICEARRIVAL,
                               reinterpret_cast<DWORD>(&volume_broadcast));

  EXPECT_EQ(0u, volume_mount_watcher_->devices_checked().size());

  // Re-attach the same volume. We haven't released the mock device check
  // event, so there'll be pending calls in the UI thread to finish the
  // device check notification, blocking the duplicate device injection.
  monitor_->InjectDeviceChange(DBT_DEVICEARRIVAL,
                               reinterpret_cast<DWORD>(&volume_broadcast));

  EXPECT_EQ(0u, volume_mount_watcher_->devices_checked().size());
  volume_mount_watcher_->ReleaseDeviceCheck();
  RunUntilIdle();
  volume_mount_watcher_->ReleaseDeviceCheck();

  // Now let all attach notifications finish running. We'll only get one
  // finish-attach call.
  volume_mount_watcher_->FlushWorkerPoolForTesting();
  RunUntilIdle();

  std::vector<base::FilePath> checked_devices =
      volume_mount_watcher_->devices_checked();
  ASSERT_EQ(1u, checked_devices.size());
  EXPECT_EQ(kAttachedDevicePath, checked_devices[0]);

  // We'll receive a duplicate check now that the first check has fully cleared.
  monitor_->InjectDeviceChange(DBT_DEVICEARRIVAL,
                               reinterpret_cast<DWORD>(&volume_broadcast));
  volume_mount_watcher_->FlushWorkerPoolForTesting();
  volume_mount_watcher_->ReleaseDeviceCheck();
  RunUntilIdle();

  checked_devices = volume_mount_watcher_->devices_checked();
  ASSERT_EQ(2u, checked_devices.size());
  EXPECT_EQ(kAttachedDevicePath, checked_devices[0]);
  EXPECT_EQ(kAttachedDevicePath, checked_devices[1]);
}

TEST_F(StorageMonitorWinTest, DeviceInfoForPath) {
  PreAttachDevices();

  // An invalid path.
  EXPECT_FALSE(monitor_->GetStorageInfoForPath(base::FilePath(L"COM1:\\"),
                                               NULL));

  // An unconnected removable device.
  EXPECT_FALSE(monitor_->GetStorageInfoForPath(base::FilePath(L"E:\\"), NULL));

  // A connected removable device.
  base::FilePath removable_device(L"F:\\");
  StorageInfo device_info;
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(removable_device, &device_info));

  StorageInfo info;
  ASSERT_TRUE(volume_mount_watcher_->GetDeviceInfo(removable_device, &info));
  EXPECT_TRUE(StorageInfo::IsRemovableDevice(info.device_id));
  EXPECT_EQ(info.device_id, device_info.device_id);
  EXPECT_EQ(info.name, device_info.name);
  EXPECT_EQ(info.location, device_info.location);
  EXPECT_EQ(1000000, info.total_size_in_bytes);

  // A fixed device.
  base::FilePath fixed_device(L"N:\\");
  EXPECT_TRUE(monitor_->GetStorageInfoForPath(fixed_device, &device_info));

  ASSERT_TRUE(volume_mount_watcher_->GetDeviceInfo(
      fixed_device, &info));
  EXPECT_FALSE(StorageInfo::IsRemovableDevice(info.device_id));
  EXPECT_EQ(info.device_id, device_info.device_id);
  EXPECT_EQ(info.name, device_info.name);
  EXPECT_EQ(info.location, device_info.location);
}

// Test to verify basic MTP storage attach and detach notifications.
TEST_F(StorageMonitorWinTest, MTPDeviceBasicAttachDetach) {
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithValidInfo, true);
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithValidInfo, false);
}

// When a MTP storage device with invalid storage label and id is
// attached/detached, there should not be any device attach/detach
// notifications.
TEST_F(StorageMonitorWinTest, MTPDeviceWithInvalidInfo) {
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithInvalidInfo,
                  true);
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithInvalidInfo,
                  false);
}

// Attach a device with two data partitions. Verify that attach/detach
// notifications are sent out for each removable storage.
TEST_F(StorageMonitorWinTest, MTPDeviceWithMultipleStorageObjects) {
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithMultipleStorages,
                  true);
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithMultipleStorages,
                  false);
}

TEST_F(StorageMonitorWinTest, DriveNumberToFilePath) {
  EXPECT_EQ(L"A:\\", VolumeMountWatcherWin::DriveNumberToFilePath(0).value());
  EXPECT_EQ(L"Y:\\", VolumeMountWatcherWin::DriveNumberToFilePath(24).value());
  EXPECT_EQ(L"", VolumeMountWatcherWin::DriveNumberToFilePath(-1).value());
  EXPECT_EQ(L"", VolumeMountWatcherWin::DriveNumberToFilePath(199).value());
}

// Given a MTP storage persistent id, GetMTPStorageInfo() should fetch the
// device interface path and local storage object identifier.
TEST_F(StorageMonitorWinTest, GetMTPStorageInfoFromDeviceId) {
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithValidInfo, true);
  PortableDeviceWatcherWin::StorageObjects storage_objects =
      TestPortableDeviceWatcherWin::GetDeviceStorageObjects(
          TestPortableDeviceWatcherWin::kMTPDeviceWithValidInfo);
  for (PortableDeviceWatcherWin::StorageObjects::const_iterator it =
           storage_objects.begin();
       it != storage_objects.end(); ++it) {
    string16 pnp_device_id;
    string16 storage_object_id;
    ASSERT_TRUE(GetMTPStorageInfo(it->object_persistent_id, &pnp_device_id,
                                  &storage_object_id));
    EXPECT_EQ(string16(TestPortableDeviceWatcherWin::kMTPDeviceWithValidInfo),
              pnp_device_id);
    EXPECT_EQ(it->object_persistent_id,
              TestPortableDeviceWatcherWin::GetMTPStorageUniqueId(
                  pnp_device_id, storage_object_id));
  }
  DoMTPDeviceTest(TestPortableDeviceWatcherWin::kMTPDeviceWithValidInfo, false);
}

}  // namespace test
}  // namespace chrome