text:
import unittest

try:
    import unittest.mock as mock
except ImportError:
    import mock
from oslo_config import cfg

from cloudbaseinit.plugins.common import constants
from cloudbaseinit.plugins.common import setuserpassword
from cloudbaseinit.tests.metadata import fake_json_response
from cloudbaseinit.tests import testutils

CONF = cfg.CONF

class SetUserPasswordPluginTests(unittest.TestCase):

    def setUp(self):
        self._setpassword_plugin = setuserpassword.SetUserPasswordPlugin()
        self.fake_data = fake_json_response.get_fake_metadata_json(
            '2013-04-04')

    @mock.patch('base64.b64encode')
    @mock.patch('cloudbaseinit.utils.crypt.CryptManager'
                '.load_ssh_rsa_public_key')
    def test_encrypt_password(self, mock_load_ssh_key, mock_b64encode):
        mock_rsa = mock.MagicMock()
        fake_ssh_pub_key = 'fake key'
        fake_password = 'fake password'
        mock_load_ssh_key.return_value = mock_rsa
        mock_rsa.__enter__().public_encrypt.return_value = 'public encrypted'
        mock_b64encode.return_value = 'encrypted password'

        response = self._setpassword_plugin._encrypt_password(
            fake_ssh_pub_key, fake_password)

        mock_load_ssh_key.assert_called_with(fake_ssh_pub_key)
        mock_rsa.__enter__().public_encrypt.assert_called_with(
            b'fake password')
        mock_b64encode.assert_called_with('public encrypted')
        self.assertEqual('encrypted password', response)

    def _test_get_ssh_public_key(self, data_exists):
        mock_service = mock.MagicMock()
        public_keys = self.fake_data['public_keys']
        mock_service.get_public_keys.return_value = public_keys.values()

        response = self._setpassword_plugin._get_ssh_public_key(mock_service)

        mock_service.get_public_keys.assert_called_with()
        self.assertEqual(list(public_keys.values())[0], response)

    def test_get_ssh_plublic_key(self):
        self._test_get_ssh_public_key(data_exists=True)

    def test_get_ssh_plublic_key_no_pub_keys(self):
        self._test_get_ssh_public_key(data_exists=False)

    def _test_get_password(self, inject_password):
        shared_data = {}
        expected_password = 'Passw0rd'
        if not inject_password:
            # The password should be the one created by
            # CreateUser plugin.
            shared_data[constants.SHARED_DATA_PASSWORD] = (
                mock.sentinel.create_user_password)

        mock_service = mock.MagicMock()
        mock_service.get_admin_password.return_value = expected_password

        with testutils.ConfPatcher('inject_user_password', inject_password):
            response = self._setpassword_plugin._get_password(mock_service,
                                                              shared_data)
        if inject_password:
            mock_service.get_admin_password.assert_called_with()
            expected_password = (expected_password, True)
        else:
            self.assertFalse(mock_service.get_admin_password.called)
            expected_password = (mock.sentinel.create_user_password, False)

        self.assertEqual(expected_password, response)

    def test_get_password_inject_true(self):
        self._test_get_password(inject_password=True)

    def test_get_password_inject_false(self):
        self._test_get_password(inject_password=False)

    @mock.patch('cloudbaseinit.plugins.common.setuserpassword.'
                'SetUserPasswordPlugin._get_ssh_public_key')
    @mock.patch('cloudbaseinit.plugins.common.setuserpassword.'
                'SetUserPasswordPlugin._encrypt_password')
    def _test_set_metadata_password(self, mock_encrypt_password,
                                    mock_get_key, ssh_pub_key):
        fake_passw0rd = 'fake Passw0rd'
        mock_service = mock.MagicMock()
        mock_get_key.return_value = ssh_pub_key
        mock_encrypt_password.return_value = 'encrypted password'
        mock_service.post_password.return_value = 'value'
        mock_service.can_post_password = True
        mock_service.is_password_set = False
        with testutils.LogSnatcher('cloudbaseinit.plugins.common.'
                                   'setuserpassword') as snatcher:
            response = self._setpassword_plugin._set_metadata_password(
                fake_passw0rd, mock_service)

        expected_logging = []
        if ssh_pub_key is None:
            expected_logging = [
                'No SSH public key available for password encryption'
            ]
            self.assertTrue(response)
        else:
            mock_get_key.assert_called_once_with(mock_service)
            mock_encrypt_password.assert_called_once_with(ssh_pub_key,
                                                          fake_passw0rd)
            mock_service.post_password.assert_called_with(
                'encrypted password')
            self.assertEqual('value', response)
        self.assertEqual(expected_logging, snatcher.output)

    def test_set_metadata_password_with_ssh_key(self):
        fake_key = 'fake key'
        self._test_set_metadata_password(ssh_pub_key=fake_key)

    def test_set_metadata_password_no_ssh_key(self):
        self._test_set_metadata_password(ssh_pub_key=None)

    def test_set_metadata_password_already_set(self):
        mock_service = mock.MagicMock()
        mock_service.is_password_set = True
        with testutils.LogSnatcher('cloudbaseinit.plugins.common.'
                                   'setuserpassword') as snatcher:
            response = self._setpassword_plugin._set_metadata_password(
                mock.sentinel.fake_password, mock_service)

        self.assertTrue(response)
        expected_logging = ['User\'s password already set in the '
                            'instance metadata and it cannot be '
                            'updated in the instance metadata']
        self.assertEqual(expected_logging, snatcher.output)

    @mock.patch('cloudbaseinit.plugins.common.setuserpassword.'
                'SetUserPasswordPlugin._change_logon_behaviour')
    @mock.patch('cloudbaseinit.plugins.common.setuserpassword.'
                'SetUserPasswordPlugin._get_password')
    def _test_set_password(self, mock_get_password,
                           mock_change_logon_behaviour,
                           password, can_update_password,
                           is_password_changed, injected=False):
        expected_password = password
        expected_logging = []
        user = 'fake_user'

        mock_get_password.return_value = (password, injected)

        mock_service = mock.MagicMock()
        mock_osutils = mock.MagicMock()
        mock_osutils.get_maximum_password_length.return_value = None
        mock_osutils.generate_random_password.return_value = expected_password
        mock_service.can_update_password = can_update_password
        mock_service.is_password_changed.return_value = is_password_changed

        with testutils.LogSnatcher('cloudbaseinit.plugins.common.'
                                   'setuserpassword') as snatcher:
            response = self._setpassword_plugin._set_password(
                mock_service, mock_osutils, user,
                mock.sentinel.shared_data)

        if can_update_password and not is_password_changed:
            expected_logging.append('Updating password is not required.')
            expected_password = None

        if not password:
            expected_logging.append('Generating a random user password')
            expected_password = password

        if not can_update_password or is_password_changed:
            mock_get_password.assert_called_once_with(
                mock_service, mock.sentinel.shared_data)

        self.assertEqual(expected_password, response)
        self.assertEqual(expected_logging, snatcher.output)
        if password and can_update_password and is_password_changed:
            mock_change_logon_behaviour.assert_called_once_with(
                user, password_injected=injected)

    def test_set_password(self):
        self._test_set_password(password='Password',
                                can_update_password=False,
                                is_password_changed=False)
        self._test_set_password(password=None,
                                can_update_password=False,
                                is_password_changed=False)
        self._test_set_password(password='Password',
                                can_update_password=True,
                                is_password_changed=True)
        self._test_set_password(password='Password',
                                can_update_password=True,
                                is_password_changed=False)

    @mock.patch('cloudbaseinit.plugins.common.setuserpassword.'
                'SetUserPasswordPlugin._set_password')
    @mock.patch('cloudbaseinit.plugins.common.setuserpassword.'
                'SetUserPasswordPlugin._set_metadata_password')
    @mock.patch('cloudbaseinit.osutils.factory.get_os_utils')
    def _test_execute(self, mock_get_os_utils, mock_set_metadata_password,
                      mock_set_password, is_password_set,
                      can_post_password, can_update_password=False):
        mock_service = mock.MagicMock()
        mock_osutils = mock.MagicMock()
        fake_shared_data = mock.MagicMock()
        fake_shared_data.get.return_value = 'fake username'
        mock_service.is_password_set = is_password_set
        mock_service.can_post_password = can_post_password
        mock_service.can_update_password = can_update_password
        mock_get_os_utils.return_value = mock_osutils
        mock_osutils.user_exists.return_value = True
        mock_set_password.return_value = 'fake password'

        with testutils.LogSnatcher('cloudbaseinit.plugins.common.'
                                   'setuserpassword') as snatcher:
            response = self._setpassword_plugin.execute(mock_service,
                                                        fake_shared_data)
        mock_get_os_utils.assert_called_once_with()
        fake_shared_data.get.assert_called_with(
            constants.SHARED_DATA_USERNAME, CONF.username)
        mock_osutils.user_exists.assert_called_once_with('fake username')
        mock_set_password.assert_called_once_with(mock_service, mock_osutils,
                                                  'fake username',
                                                  fake_shared_data)

        expected_logging = [
            "Password succesfully updated for user fake username",
        ]
        if can_post_password:
            mock_set_metadata_password.assert_called_once_with('fake password',
                                                               mock_service)
        else:
            expected_logging.append("Cannot set the password in the metadata "
                                    "as it is not supported by this service")
            self.assertFalse(mock_set_metadata_password.called)

        if can_update_password:
            self.assertEqual((2, False), response)
        else:
            self.assertEqual((1, False), response)

        self.assertEqual(expected_logging, snatcher.output)

    def test_execute(self):
        self._test_execute(is_password_set=False, can_post_password=False)
        self._test_execute(is_password_set=True, can_post_password=True)
        self._test_execute(is_password_set=False, can_post_password=True)
        self._test_execute(is_password_set=True, can_post_password=True,
                           can_update_password=True)

    @mock.patch.object(setuserpassword.osutils_factory, 'get_os_utils')
    @testutils.ConfPatcher('first_logon_behaviour',
                           setuserpassword.NEVER_CHANGE)
    def test_logon_behaviour_never_change(self, mock_get_os_utils):
        self._setpassword_plugin._change_logon_behaviour(
            mock.sentinel.username)

        self.assertFalse(mock_get_os_utils.called)

    @testutils.ConfPatcher('first_logon_behaviour',
                           setuserpassword.ALWAYS_CHANGE)
    @mock.patch.object(setuserpassword, 'osutils_factory')
    def test_logon_behaviour_always(self, mock_factory):
        self._setpassword_plugin._change_logon_behaviour(
            mock.sentinel.username)

        mock_get_os_utils = mock_factory.get_os_utils
        self.assertTrue(mock_get_os_utils.called)
        osutils = mock_get_os_utils.return_value
        osutils.change_password_next_logon.assert_called_once_with(
            mock.sentinel.username)

    @testutils.ConfPatcher('first_logon_behaviour',
                           setuserpassword.CLEAR_TEXT_INJECTED_ONLY)
    @mock.patch.object(setuserpassword, 'osutils_factory')
    def test_change_logon_behaviour_clear_text_password_not_injected(
            self, mock_factory):
        self._setpassword_plugin._change_logon_behaviour(
            mock.sentinel.username,
            password_injected=False)

        mock_get_os_utils = mock_factory.get_os_utils
        self.assertFalse(mock_get_os_utils.called)

    @testutils.ConfPatcher('first_logon_behaviour',
                           setuserpassword.CLEAR_TEXT_INJECTED_ONLY)
    @mock.patch.object(setuserpassword, 'osutils_factory')
    def test_logon_behaviour_clear_text_password_injected(
            self, mock_factory):
        self._setpassword_plugin._change_logon_behaviour(
            mock.sentinel.username,
            password_injected=True)

        mock_get_os_utils = mock_factory.get_os_utils
        self.assertTrue(mock_get_os_utils.called)
        osutils = mock_get_os_utils.return_value
        osutils.change_password_next_logon.assert_called_once_with(
            mock.sentinel.username)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 2: 419 (1924)

#### Original name
Graphina sophistica var. recta Müll. Arg.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.communote.plugins.api.rest.v30.resource.timelinenote.timelinenotediscussion (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">

com.communote.plugins.api.rest.v30.resource.timelinenote.timelinenotediscussion

Classes

GetTimelineNoteDiscussionParameter

TimelineNoteDiscussionResource


text:
<?php

namespace ApplicationTest\Service;

use Application\Entity\UserEntity;
use Application\Service\AuthService;
use Zend\Stdlib\ArrayUtils;

/**
 *
 * Class AuthServiceTest
 * @group Service
 */
class AuthServiceTest extends \ApplicationTest\Service\AbstractServiceTestCase
{

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

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

    public function setUp()
    {
        parent::setUp();
        $this->validData = [
            'email' => "joao@gmail.com",
            'password' => "aeRtX21"
        ];
        $this->invalidData = [
            'email' => 'joao',
            'password' => ''
        ];

        $user = new UserEntity();
        $user->email = $this->validData['email'];
        $user->password = password_hash($this->validData['password'], PASSWORD_DEFAULT);
        $user->name = 'João';
        $user->typeAuth = '1';
        $entityManager = $this->getApplicationServiceLocator()
            ->get('Doctrine\ORM\EntityManager');
        $entityManager->persist($user);
        $entityManager->flush();
    }

    public function testDataBaseValidateAuth()
    {
        $serviceAuth = $this->getApplicationServiceLocator()
            ->get('AuthService');
        $this->assertArrayHasKey("success", $serviceAuth->dataBaseAuth(
            $this->validData
        ));
        $response = $serviceAuth->dataBaseAuth($this->invalidData);
        $this->assertArrayHasKey("error", $response);
    }

    public function testInvalidLogin()
    {
        $serviceAuth = $this->getApplicationServiceLocator()
            ->get('AuthService');
        $response = $serviceAuth->dataBaseAuth(
            ['email' => 'maria@gmail.com', 'password' => '123345678']
        );
        $this->assertArrayHasKey("error", $response);
        $this->assertEquals('Usuário ou senha inválidos!', $response['error']);
    }

    public function testPassCriptDataBase()
    {
        $entityManager = $this->getApplicationServiceLocator()
            ->get('Doctrine\ORM\EntityManager');
        $users = $entityManager->getRepository(
            '\Application\Entity\UserEntity'
        )->findAll();
        $this->assertEquals(1, count($users));
        $user = $users[0];
        $this->assertEquals(1, $user->id);
        $this->assertEquals("João", $user->name);
        $this->assertNotEquals("aeRtX21", $user->password);
    }
}


text:
mbase Class
===========

.. autoclass:: flopy.mbase.BaseModel
   :members:
   :inherited-members:


text:
<template name="quote">

		"{{quotes.[0]}}"
		- {{author}}

</template>


text:
<?php
class Kwc_User_DeleteAccount_Form_Component extends Kwc_Form_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['placeholder']['submitButton'] = trlKwfStatic('Delete Account');
        $ret['plugins'] = array('Kwf_Component_Plugin_Login_Component');
        return $ret;
    }

    protected function _initForm()
    {
        parent::_initForm();
        $this->_form->setModel(new Kwf_Model_FnF());
    }

    protected function _afterSave(Kwf_Model_Row_Interface $row)
    {
        parent::_afterSave($row);
        $user = Kwf_Registry::get('userModel')->getKwfModel()->getAuthedUser();
        $user->deleted = 1;
        $user->save();

        Kwf_Auth::getInstance()->clearIdentity();
        setcookie('feAutologin', '', time() - 3600);
    }
}


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

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.modeshape.jcr.JcrRepository.QueryLanguage;
import org.modeshape.jdbc.util.ResultsComparator;

/**
 * This class can be used to execute a query and compare the results to what's expected.
 */
public class ConnectionResultsComparator extends ResultsComparator {

    protected Connection internalConnection = null;
    protected ResultSet internalResultSet = null;
    protected Statement internalStatement = null;
    private SQLException internalException = null;
    protected int updateCount = -1;

    protected ConnectionResultsComparator() {

    }

    private ConnectionResultsComparator( Connection conn ) {
        this.internalConnection = conn;
    }

    public static void executeTest( Connection conn,
                                    String sql,
                                    String expected,
                                    int expectedRowCount,
                                    String jcrSQL ) throws SQLException {
        ConnectionResultsComparator util = new ConnectionResultsComparator(conn);
        try {
            util.execute(sql, jcrSQL);
            util.assertResultsSetEquals(util.internalResultSet, expected);

            util.assertRowCount(expectedRowCount);

        } finally {
            util.closeResultSet();
            util.closeStatement();
        }
    }

    public static void executeTest( Connection conn,
                                    String sql,
                                    int expectedRowCount,
                                    String jcrSQL ) throws SQLException {
        ConnectionResultsComparator util = new ConnectionResultsComparator(conn);
        try {
            util.execute(sql, jcrSQL);
            util.assertRowCount(expectedRowCount);
        } finally {
            util.closeResultSet();
            util.closeStatement();
        }
    }

    public static void executeTest( Connection conn,
                                    String sql,
                                    String[] expected,
                                    int expectedRowCount,
                                    String jcrSQL ) throws SQLException {
        AssertionError lastError = null;
        for (int i = 0; i != 10; ++i) {
            ConnectionResultsComparator util = new ConnectionResultsComparator(conn);
            try {
                util.execute(sql, jcrSQL);
                util.assertResultsSetEquals(util.internalResultSet, expected);

                util.assertRowCount(expectedRowCount);
                return;
            } catch (AssertionError e) {
                lastError = e;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {
                    fail("Interrupted");
                    return;
                }
            } finally {
                util.closeResultSet();
                util.closeStatement();
            }
        }
        if (lastError != null) throw lastError;
    }

    public static void executeTest( Connection conn,
                                    String sql,
                                    String expected,
                                    int expectedRowCount ) throws SQLException {
        executeTest(conn, sql, expected, expectedRowCount, QueryLanguage.JCR_SQL2);

    }

    public static void executeTest( Connection conn,
                                    String sql,
                                    String[] expected,
                                    int expectedRowCount ) throws SQLException {
        executeTest(conn, sql, expected, expectedRowCount, QueryLanguage.JCR_SQL2);

    }

    public static void executeTestAndPrint( Connection conn,
                                            String sql,
                                            String jcrSQL ) throws SQLException {
        ConnectionResultsComparator util = new ConnectionResultsComparator(conn);
        try {
            util.execute(sql, jcrSQL);
            util.printResults();
        } finally {
            util.closeResultSet();
            util.closeStatement();
        }
    }

    public static void executeTestAndPrint( Connection conn,
                                            String sql ) throws SQLException {
        executeTestAndPrint(conn, sql, QueryLanguage.JCR_SQL2);
    }

    private boolean execute( String sql,
                             String jcrSQL ) throws SQLException {
        return execute(sql, new Object[] {}, jcrSQL);
    }

    private boolean execute( String sql,
                             Object[] params,
                             String jcrSQL ) throws SQLException {
        this.updateCount = -1;

        assertNotNull(this.internalConnection);
        assertTrue(!this.internalConnection.isClosed());
        boolean result = false;

        this.internalStatement = createStatement();
        if (internalStatement instanceof JcrStatement) {
            ((JcrStatement)this.internalStatement).setJcrSqlLanguage(jcrSQL);
        }
        result = this.internalStatement.execute(sql);
        assertTrue(result);

        this.internalResultSet = this.internalStatement.getResultSet();

        assertThat(this.internalResultSet, is(notNullValue()));
        assertThat(this.internalResultSet.isBeforeFirst(), is(true));
        assertThat(this.internalResultSet.isClosed(), is(false));

        return result;

    }

    protected Statement createStatement() throws SQLException {
        return this.internalConnection.createStatement();
    }

    public boolean exceptionOccurred() {
        return this.internalException != null;
    }

    public boolean exceptionExpected() {
        return false;
    }

    public SQLException getLastException() {
        return this.internalException;
    }

    public void printResults() {
        assertNotNull(this.internalResultSet);
        printResults(this.internalResultSet, this.compareColumns);
    }

    public void assertUpdateCount( int expected ) {
        assertEquals(expected, updateCount);
    }

    public int getRowCount() {
        assertNotNull(this.internalResultSet);
        return super.getRowCount(this.internalResultSet);

    }

    public void closeStatement() {
        closeResultSet();

        if (this.internalStatement != null) {
            try {
                this.internalStatement.close();
            } catch (SQLException e) {

            } finally {
                this.internalStatement = null;
            }
        }
    }

    public void closeResultSet() {
        this.internalException = null;

        if (this.internalResultSet != null) {
            try {

                this.internalResultSet.close();
            } catch (SQLException e) {

            } finally {
                this.internalResultSet = null;
            }
        }
    }

    public void cancelQuery() throws SQLException {
        assertNotNull(this.internalConnection);
        assertTrue(!this.internalConnection.isClosed());
        assertNotNull(this.internalStatement);
        this.internalStatement.cancel();
    }

}


text:
require 'spec_helper'

def attributes_to_sorted_array(src)
   Nokogiri::HTML::DocumentFragment.parse(src).children.first.attributes
end

module Deface
  describe Applicator do
    include_context "mock Rails.application"
    before { Dummy.all.clear }

    describe "with a single disabled override defined" do
      before { Deface::Override.new(:virtual_path => "posts/index", :name => "Posts#index", :remove => "p", :text => "
Argh!
", :disabled => true) }
      let(:source) { "
test
<%= raw(text) %>" }

      it "should return unmodified source" do
        expect(Dummy.apply(source, {:virtual_path => "posts/index"})).to eq("
test
<%= raw(text) %>")
      end
    end

    describe "with a single :copy override defined" do
      before { Deface::Override.new(:virtual_path => "posts/index", :name => "Posts#index", :insert_after => "p", :copy => "h1") }
      let(:source) { "
World

Hello
" }

      it "should return modified source" do
        expect(Dummy.apply(source, {:virtual_path => "posts/index"})).to eq("
World

Hello

World
")
      end
    end

    describe "with a single :copy using :start and :end" do
      before { Deface::Override.new(:virtual_path => "posts/index", :name => "Posts#index", :insert_before => "h1",
                                    :copy => {:start => "erb:contains('if true')", :end => "erb:contains('end')"}) }
      let(:source) { "
World
<% if true %>
True that!
<% end %>
Hello
" }

      it "should return modified source" do
        expect(Dummy.apply(source, {:virtual_path => "posts/index"})).to eq("<% if true %>
True that!
<% end %>
World
<% if true %>
True that!
<% end %>
Hello
")
      end
    end

    describe "with a single :cut override defined" do
      before { Deface::Override.new(:virtual_path => "posts/index", :name => "Posts#index", :insert_after => "p", :cut => "h1") }
      let(:source) { "
World

Hello
" }

      it "should return modified source" do
        expect(Dummy.apply(source, {:virtual_path => "posts/index"})).to eq("
Hello

World
")
      end
    end

    describe "with a single :cut using :start and :end" do
      before { Deface::Override.new(:virtual_path => "posts/index", :name => "Posts#index", :replace => "h1",
                                    :cut => {:start => "erb:contains('if true')", :end => "erb:contains('end')"}) }
      let(:source) { "
World
<% if true %>
True that!
<% end %>
Hello
" }

      it "should return modified source" do
        expect(Dummy.apply(source, {:virtual_path => "posts/index"})).to eq("<% if true %>
True that!
<% end %>
Hello
")
      end
    end

    describe "with mulitple sequenced overrides defined" do
      before do
        Deface::Override.new(:virtual_path => "posts/index", :name => "third", :insert_after => "li:contains('second')", :text => "
third
", :sequence => {:after => "second"})
        Deface::Override.new(:virtual_path => "posts/index", :name => "second", :insert_after => "li", :text => "
second
", :sequence => {:after => "first"})
        Deface::Override.new(:virtual_path => "posts/index", :name => "first", :replace => "li", :text => "
first
")
      end

      let(:source) { "

replaced

" }

      it "should return modified source" do
        expect(Dummy.apply(source, {:virtual_path => "posts/index"}).gsub("\n", "")).to eq("

first

second

third

")
      end
    end

    describe "with incompatible actions and :closing_selector" do
      let(:source) { "

first

second

third

" }

      it "should return modified source" do
        [:insert_before, :insert_after, :insert_top, :insert_bottom, :set_attributes, :remove_from_attributes, :add_to_attributes].each do |action|
          Deface::Override.all.clear
          Deface::Override.new(:virtual_path => "posts/index", :name => "first", action => "li", :closing_selector => "p", :text => "
first
")

          expect { Dummy.apply(source, {:virtual_path => "posts/index"}) }.to raise_error(Deface::NotSupportedError)
        end
      end
    end

  end
end


text:
#import <IBFoundation/IBICMultipartImageRepSlotValidationRecord.h>

@interface IBICAppIconRepSlotValidationRecord : IBICMultipartImageRepSlotValidationRecord
{
}

@end


text:
use crate::dep_graph::DepNodeIndex;
use crate::query::plumbing::{QueryCacheStore, QueryLookup};

use rustc_arena::TypedArena;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sharded::Sharded;
use rustc_data_structures::sync::WorkerLocal;
use std::default::Default;
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;

pub trait CacheSelector<K, V> {
    type Cache;
}

pub trait QueryStorage {
    type Value: Debug;
    type Stored: Clone;

    /// Store a value without putting it in the cache.
    /// This is meant to be used with cycle errors.
    fn store_nocache(&self, value: Self::Value) -> Self::Stored;
}

pub trait QueryCache: QueryStorage + Sized {
    type Key: Hash + Eq + Clone + Debug;
    type Sharded: Default;

    /// Checks if the query is already computed and in the cache.
    /// It returns the shard index and a lock guard to the shard,
    /// which will be used if the query is not in the cache and we need
    /// to compute it.
    fn lookup<'s, R, OnHit>(
        &self,
        state: &'s QueryCacheStore<Self>,
        key: &Self::Key,
        // `on_hit` can be called while holding a lock to the query state shard.
        on_hit: OnHit,
    ) -> Result<R, QueryLookup>
    where
        OnHit: FnOnce(&Self::Stored, DepNodeIndex) -> R;

    fn complete(
        &self,
        lock_sharded_storage: &mut Self::Sharded,
        key: Self::Key,
        value: Self::Value,
        index: DepNodeIndex,
    ) -> Self::Stored;

    fn iter(
        &self,
        shards: &Sharded<Self::Sharded>,
        f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex),
    );
}

pub struct DefaultCacheSelector;

impl<K: Eq + Hash, V: Clone> CacheSelector<K, V> for DefaultCacheSelector {
    type Cache = DefaultCache<K, V>;
}

pub struct DefaultCache<K, V>(PhantomData<(K, V)>);

impl<K, V> Default for DefaultCache<K, V> {
    fn default() -> Self {
        DefaultCache(PhantomData)
    }
}

impl<K: Eq + Hash, V: Clone + Debug> QueryStorage for DefaultCache<K, V> {
    type Value = V;
    type Stored = V;

    #[inline]
    fn store_nocache(&self, value: Self::Value) -> Self::Stored {
        // We have no dedicated storage
        value
    }
}

impl<K, V> QueryCache for DefaultCache<K, V>
where
    K: Eq + Hash + Clone + Debug,
    V: Clone + Debug,
{
    type Key = K;
    type Sharded = FxHashMap<K, (V, DepNodeIndex)>;

    #[inline(always)]
    fn lookup<'s, R, OnHit>(
        &self,
        state: &'s QueryCacheStore<Self>,
        key: &K,
        on_hit: OnHit,
    ) -> Result<R, QueryLookup>
    where
        OnHit: FnOnce(&V, DepNodeIndex) -> R,
    {
        let (lookup, lock) = state.get_lookup(key);
        let result = lock.raw_entry().from_key_hashed_nocheck(lookup.key_hash, key);

        if let Some((_, value)) = result {
            let hit_result = on_hit(&value.0, value.1);
            Ok(hit_result)
        } else {
            Err(lookup)
        }
    }

    #[inline]
    fn complete(
        &self,
        lock_sharded_storage: &mut Self::Sharded,
        key: K,
        value: V,
        index: DepNodeIndex,
    ) -> Self::Stored {
        lock_sharded_storage.insert(key, (value.clone(), index));
        value
    }

    fn iter(
        &self,
        shards: &Sharded<Self::Sharded>,
        f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex),
    ) {
        let shards = shards.lock_shards();
        for shard in shards.iter() {
            for (k, v) in shard.iter() {
                f(k, &v.0, v.1);
            }
        }
    }
}

pub struct ArenaCacheSelector<'tcx>(PhantomData<&'tcx ()>);

impl<'tcx, K: Eq + Hash, V: 'tcx> CacheSelector<K, V> for ArenaCacheSelector<'tcx> {
    type Cache = ArenaCache<'tcx, K, V>;
}

pub struct ArenaCache<'tcx, K, V> {
    arena: WorkerLocal<TypedArena<(V, DepNodeIndex)>>,
    phantom: PhantomData<(K, &'tcx V)>,
}

impl<'tcx, K, V> Default for ArenaCache<'tcx, K, V> {
    fn default() -> Self {
        ArenaCache { arena: WorkerLocal::new(|_| TypedArena::default()), phantom: PhantomData }
    }
}

impl<'tcx, K: Eq + Hash, V: Debug + 'tcx> QueryStorage for ArenaCache<'tcx, K, V> {
    type Value = V;
    type Stored = &'tcx V;

    #[inline]
    fn store_nocache(&self, value: Self::Value) -> Self::Stored {
        let value = self.arena.alloc((value, DepNodeIndex::INVALID));
        let value = unsafe { &*(&value.0 as *const _) };
        &value
    }
}

impl<'tcx, K, V: 'tcx> QueryCache for ArenaCache<'tcx, K, V>
where
    K: Eq + Hash + Clone + Debug,
    V: Debug,
{
    type Key = K;
    type Sharded = FxHashMap<K, &'tcx (V, DepNodeIndex)>;

    #[inline(always)]
    fn lookup<'s, R, OnHit>(
        &self,
        state: &'s QueryCacheStore<Self>,
        key: &K,
        on_hit: OnHit,
    ) -> Result<R, QueryLookup>
    where
        OnHit: FnOnce(&&'tcx V, DepNodeIndex) -> R,
    {
        let (lookup, lock) = state.get_lookup(key);
        let result = lock.raw_entry().from_key_hashed_nocheck(lookup.key_hash, key);

        if let Some((_, value)) = result {
            let hit_result = on_hit(&&value.0, value.1);
            Ok(hit_result)
        } else {
            Err(lookup)
        }
    }

    #[inline]
    fn complete(
        &self,
        lock_sharded_storage: &mut Self::Sharded,
        key: K,
        value: V,
        index: DepNodeIndex,
    ) -> Self::Stored {
        let value = self.arena.alloc((value, index));
        let value = unsafe { &*(value as *const _) };
        lock_sharded_storage.insert(key, value);
        &value.0
    }

    fn iter(
        &self,
        shards: &Sharded<Self::Sharded>,
        f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex),
    ) {
        let shards = shards.lock_shards();
        for shard in shards.iter() {
            for (k, v) in shard.iter() {
                f(k, &v.0, v.1);
            }
        }
    }
}


text:
import React, {Component, PropTypes} from 'react';
import themeable from 'react-themeable';

import TabbedArea from './TabbedArea';
import TabPane from './TabPane';
import Login from './Login';
import Forgot from './Forgot';
import Create from './Create';

const defaultTheme = {
  dialog: {
    backgroundColor: '#fff',
    width: '320px',
    margin: '3em auto',
    boxShadow: '0px 1px 8px #BEBEBE'
  },
  textBox: {
    boxSizing: 'border-box',
    display: 'block',
    margin: '15px 0px',
    width: '100%',
    padding: '6px 12px',
    color: '#555',
    backgroundColor: '#fff',
    border: '1px solid #ccc',
    borderRadius: '4px',
    lineHeight: '1.5',
    fontSize: '14px'
  },
  button: {
    width: '100%',
    color: '#fff',
    backgroundColor: '#428bca',
    borderColor: '#357ebd',
    borderRadius: '4px',
    border: '1px solid transparent',
    display: 'inline-block',
    marginBottom: '0',
    fontWeight: '400',
    lineHeight: '1.5',
    textAlign: 'center',
    verticalAlign: 'middle',
    cursor: 'pointer',
    whiteSpace: 'nowrap',
    padding: '6px 12px',
    fontSize: '14px'
  },
  helpText: {
    marginTop: '15px',
    paddingBottom: '10px',
    textAlign: 'center'
  },
  link: {
    color: '#428bca',
    textDecoration: 'none'
  }
};

export default class Dialog extends Component {

  static propTypes = {
    termsUrl: PropTypes.string,
    defaultTab: PropTypes.string,
    createAction: PropTypes.func,
    loginAction: PropTypes.func,
    forgotAction: PropTypes.func,
    createExtras: PropTypes.object
  }
  static defaultProps = { defaultTab: 'login' };
  state = {
    defaultTab: this.props.defaultTab,
    forgotEnabled: this.props.defaultTab === 'forgot',
    errorMessage: null
  };

  constructor(props) {
    super(props);
    this.switchForgot = this.switchForgot.bind(this);
    this.setErrorMessage = this.setErrorMessage.bind(this);
    this.indexChanged = this.indexChanged.bind(this);
  }

  setErrorMessage(errorMessage) {
    this.setState({errorMessage: errorMessage});
  }

  nameToIndex(state) {
    const si = {
      'login': 0,
      'create': 1,
      'forgot': 2
    };
    return si[state];
  }

  switchForgot(event) {
    event.preventDefault();
    this.setState({forgotEnabled: true});
    this.refs.tabbedArea.setIndex(this.nameToIndex('forgot'));
  }

  indexChanged() {
    // If tab index changes, forget the error message we were showing.
    this.setState({errorMessage: null});
  }

  renderForgot(themeStyle) {
    if (this.state.forgotEnabled) {
      return (
        <TabPane display="Forgot" theme={themeStyle}>
          <Forgot
            errorMessage={this.state.errorMessage}
            forgotAction={this.props.forgotAction}
            theme={themeStyle}
          />
        </TabPane>
      );
    }
    return null;
  }

  render() {
    const tabIndex = this.nameToIndex(this.state.defaultTab);
    const themeStyle = {...defaultTheme, ...this.props.theme};
    const theme = themeable(themeStyle);
    return (
      <div {...theme(1, 'dialog')}>
        <TabbedArea ref="tabbedArea" defaultIndex={tabIndex} indexChanged={this.indexChanged} theme={themeStyle}>
          <TabPane display="Login" theme={themeStyle}>
            <Login
              errorMessage={this.state.errorMessage}
              loginAction={this.props.loginAction}
              switchForgot={this.switchForgot}
              theme={themeStyle}
            />
          </TabPane>
          <TabPane display="Sign Up" theme={themeStyle}>
            <Create
              errorMessage={this.state.errorMessage}
              termsUrl={this.props.termsUrl}
              createAction={this.props.createAction}
              createExtras={this.props.createExtras}
              theme={themeStyle}
            />
          </TabPane>
          {this.renderForgot(themeStyle)}
        </TabbedArea>
      </div>
    );
  }

}


text:
require 'spec_helper'
require 'arug/trader/money'

module Arug
  module Trader
    describe Money do

      subject(:money) { Money.new(42.55, 'USD') }

      context "creating Money" do
        it "accepts string amounts" do
          expected_amount = BigDecimal.new("42.55")

          expect(Money.new('42.55', 'USD').amount).to eq expected_amount
        end

        it "accepts decimal amounts" do
          expected_amount = BigDecimal.new("42.55")

          expect(Money.new(42.55, 'USD').amount).to eq expected_amount
        end

        it "stores the currency in upper case" do
          expect(Money.new(1, 'usd').currency).to eq 'USD'
        end
      end

      context "rounding money" do
        subject(:money) { Money.new(1.013952, 'YEN') }

        let(:amount) { double(BigDecimal) }
        let(:rounded) { double(Money) }

        before do
          # This is an ugly hack because BigDecimal will not let us stub methods
          # on it's instances
          money.instance_variable_set(:@amount, double(BigDecimal))

          allow(money.amount).to receive(:round)
            .with(3, :floor)
            .and_return(amount)

          allow(Money).to receive(:new).and_return(rounded)
        end

        it "delegates the calculation to the amount" do
          expect(money.amount).to receive(:round)
            .with(3, :floor)
            .and_return(amount)

          money.round(3, :floor)
        end

        it "creates new money with the rounded amount" do
          expect(Money).to receive(:new)
            .with(amount, anything)
            .and_return(rounded)

          expect(money.round(3, :floor)).to be rounded
        end

        it "keeps the currency" do
          expect(Money).to receive(:new)
            .with(anything, 'YEN')
            .and_return(rounded)

          expect(money.round(3, :floor)).to be rounded
        end
      end

      it "is represented as a float by the amount as a float" do
        expect(Money.new(1.01, 'USD').to_f).to eq 1.01
      end

      it "is represented as a string by it's amount and currency" do
        expect(money.to_s).to eq "42.55 USD"
      end

      context "given two monies with equal amounts and the same currency" do
        subject(:moneyA) { Money.new(11.23, "USD") }

        let(:moneyB) { Money.new(11.23, "USD") }

        it "they are equal" do
          expect(moneyA).to eq moneyB
        end

        it "they are exactly equal" do
          expect(moneyA).to eql moneyB
        end

        it "have the same hash code" do
          expect(moneyA.hash).to eq moneyB.hash
        end
      end

      shared_examples "are considered different" do
        it "they are not equal" do
          expect(moneyA).not_to eq moneyB
        end

        it "they are not exactly equal" do
          expect(moneyA).not_to eq moneyB
        end

        it "they have different hash codes" do
          expect(moneyA.hash).not_to eq moneyB.hash
        end
      end

      context "given two monies with different amounts and the same currency" do
        subject(:moneyA) { Money.new(11.23, "USD") }

        let(:moneyB) { Money.new(11.22, "USD") }

        has_behavior "are considered different"
      end

      context "given two monies with the same amounts and different currency" do
        subject(:moneyA) { Money.new(11.23, "USD") }

        let(:moneyB) { Money.new(11.23, "EUR") }

        has_behavior "are considered different"
      end

      context "given a money and another object acting like a money" do
        subject(:moneyA) { Money.new(11.23, "USD") }

        let(:moneyB) {
          double(Money, amount: BigDecimal.new("11.23"), currency: "USD")
        }

        has_behavior "are considered different"
      end

      context "given a money and another object" do
        it "they are not equal" do
          m1 = Money.new(11.23, "USD")

          expect(m1).not_to eq 5
        end
      end

      it "can be multiplied by a number" do
        m1 = Money.new(1.01, "USD")

        expect(m1 * 2).to eq Money.new(2.02, "USD")
      end

      it "can be multiplied by a decimal" do
        m1 = Money.new(1.01, "USD")

        expect(m1 * 2.01).to eq Money.new(2.0301, "USD")
      end

      it "can be divided by a number" do
        m1 = Money.new(1.00, "USD")

        expect(m1 / 4).to eq Money.new(0.25, "USD")
      end

      it "can be divided by a decimal" do
        m1 = Money.new(5.25, "USD")

        expect(m1 / 2.1).to eq Money.new(2.50, "USD")
      end

      context "given two monies with the same currency" do
        subject(:moneyA) { Money.new(1.11, 'USD') }

        let(:moneyB) { Money.new(1.01, 'USD') }

        it "they can be added" do
          expect(moneyA + moneyB).to eq Money.new(2.12, 'USD')
        end

        it "they can be subtracted" do
          expect(moneyA - moneyB).to eq Money.new(0.10, 'USD')
        end

        it "they cannot be multiplied" do
          expect{ moneyA * moneyB }.to raise_error "Cannot multiply by money"
        end

        it "they cannot be divided" do
          expect{ moneyA / moneyB }.to raise_error "Cannot divide by money"
        end
      end

      context "given two monies with different currencies" do
        subject(:moneyA) { Money.new(1.11, 'USD') }

        let(:moneyB) { Money.new(1.01, 'EUR') }

        it "they cannot be added" do
          expect{ moneyA + moneyB }.to raise_error "Currency mismatch"
        end

        it "they cannot be subtracted" do
          expect{ moneyA - moneyB }.to raise_error "Currency mismatch"
        end

        it "they cannot be multiplied" do
          expect{ moneyA * moneyB }.to raise_error "Cannot multiply by money"
        end

        it "they cannot be divided" do
          expect{ moneyA / moneyB }.to raise_error "Cannot divide by money"
        end
      end

    end
  end
end


text:
using System;
using System.Linq;

namespace Microsoft.Azure.Management.Authorization
{
    /// <summary>
    /// List role assignments filter.
    /// </summary>
    public partial class ListAssignmentsFilterParameters
    {
        private string _assignedToPrincipalId;

        /// <summary>
        /// Optional. Returns role assignments directly assigned to the
        /// principal as well as assignments to the principal's groups
        /// (transitive). Currenly supported only for User Principals
        /// </summary>
        public string AssignedToPrincipalId
        {
            get { return this._assignedToPrincipalId; }
            set { this._assignedToPrincipalId = value; }
        }

        private bool _atScope;

        /// <summary>
        /// Optional. This returns all role assignments at or above.
        /// </summary>
        public bool AtScope
        {
            get { return this._atScope; }
            set { this._atScope = value; }
        }

        private string _principalId;

        /// <summary>
        /// Optional. Returns role assignment of the specific principal.
        /// </summary>
        public string PrincipalId
        {
            get { return this._principalId; }
            set { this._principalId = value; }
        }

        /// <summary>
        /// Initializes a new instance of the ListAssignmentsFilterParameters
        /// class.
        /// </summary>
        public ListAssignmentsFilterParameters()
        {
        }
    }
}


text:
require 'spec_helper.rb'

# set some constants to keep it DRY
PATH_CROWD_PROPS = "#{PATH_INSTALLATION_BASE}/atlassian-jira/WEB-INF/classes/crowd.properties".freeze

describe 'jira' do
  describe 'jira::sso' do
    let(:params) do
      {
        javahome: '/opt/java',
        version: '8.13.5',
        enable_sso: true
      }
    end

    context 'supported operating systems' do
      on_supported_os.each do |os, facts|
        context "on #{os}" do
          let(:facts) do
            facts
          end

          context 'default params' do
            it { is_expected.to compile.with_all_deps }
            it { is_expected.to contain_file("#{PATH_INSTALLATION_BASE}/atlassian-jira/WEB-INF/classes/seraph-config.xml") }
            it { is_expected.to contain_file(PATH_CROWD_PROPS) }
          end

          context 'with param application_name set to appname' do
            let(:params) do
              super().merge(
                application_name: 'appname'
              )
            end

            it do
              is_expected.to contain_file(PATH_CROWD_PROPS).
                with_content(%r{application.name                        appname})
            end
          end
          context 'with non default params' do
            let(:params) do
              super().merge(
                application_name: 'app',
                application_password: 'password',
                application_login_url: 'https://login.url/',
                crowd_server_url: 'https://crowd.url/',
                crowd_base_url: 'http://crowdbase.url'
              )
            end

            it { is_expected.to contain_file(PATH_CROWD_PROPS) }
            it do
              is_expected.to contain_file(PATH_CROWD_PROPS).
                with_content(%r{application.name                        app}).
                with_content(%r{application.password                    password}).
                with_content(%r{application.login.url                   https://login.url/}).
                with_content(%r{crowd.server.url                        https://crowd.url/}).
                with_content(%r{crowd.base.url                          http://crowdbase.url})
            end
          end
        end
      end
    end
  end
end


text:
<dom-module id="filter-test-response">

    <template>

Eredmény

                path paraméterek:
                <pretty-json class="flex-2" json-data="[[pathparams]]"></pretty-json>

                get paraméterek:
                <pretty-json class="flex-2" json-data="[[getparams]]"></pretty-json>

                body paraméterek:
                <pretty-json class="flex-2" json-data="[[bodyparams]]"></pretty-json>

                header adatok:
                <pretty-json class="flex-2" json-data="[[headerdata]]"></pretty-json>

    </template>
</dom-module>


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <LinearLayout
        android:layout_width="20dp"
        android:layout_height="26dp"
        android:gravity="right"
        android:layout_gravity="center"
        android:orientation="vertical" >

        <View
            android:layout_width="20dp"
            android:layout_height="2dp"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="6dp"
            android:background="@color/icon" />

        <View
            android:layout_width="15dp"
            android:layout_height="2dp"
            android:layout_marginBottom="2dp"
            android:background="@color/icon" />

        <View
            android:layout_width="15dp"
            android:layout_height="2dp"
            android:layout_marginBottom="2dp"
            android:background="@color/icon" />

        <View
            android:layout_width="15dp"
            android:layout_height="2dp"
            android:layout_marginBottom="2dp"
            android:background="@color/icon" />
    </LinearLayout>

</merge>


text:
import type { Sequelize } from '../../sequelize.js';
import { QueryInterface } from '../abstract/query-interface.js';
import type { IBMiQueryGenerator } from './query-generator.js';

export class IBMiQueryInterface extends QueryInterface {
  queryGenerator: IBMiQueryGenerator;

  constructor(sequelize: Sequelize, queryGenerator: IBMiQueryGenerator);
}


text:
package speedyrest.respositories;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mendix.core.Core;
import com.mendix.core.CoreException;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.IMendixObject;

import speedyrest.entities.SpeedyHeaders;
import speedyrest.proxies.ResponseCache;
import speedyrest.proxies.constants.Constants;

public class CacheRepository {

	public CacheRepository() {

	}

	public ResponseCache find(String cacheKey) throws CoreException {
		List<IMendixObject> objectList = Core.retrieveXPathQuery(Core.createSystemContext(), "//SpeedyREST.ResponseCache[Key='" + cacheKey + "']");
		if (objectList.size() == 0) {
			return new ResponseCache(Core.createSystemContext());
		}
		return ResponseCache.initialize(Core.createSystemContext(), objectList.get(0));
	}

	public void persist(ResponseCache responseCache) throws CoreException {
		responseCache.commit(Core.createSystemContext());
	}

	public ResponseCache createResponseCache(String key) {
		ResponseCache responseCache = new ResponseCache(Core.createSystemContext());
		responseCache.setKey(key);
		return responseCache;
	}

	public String getContent(ResponseCache responseCache) {
		return responseCache.getContent(Core.createSystemContext());
	}

	public String getKey(ResponseCache responseCache) {
		return responseCache.getKey(Core.createSystemContext());
	}

	public Date getDateTimeCreated(ResponseCache responseCache) throws CoreException {
		return responseCache.getMendixObject().getCreatedDate(Core.createSystemContext());
	}

	public void addContent(ResponseCache responseCache, String content) {
		String oldContent = getContent(responseCache);
		if (oldContent == null) {
			oldContent = new String("");
		}
		StringBuilder stringBuilder = new StringBuilder(oldContent);
		stringBuilder.append(content);
		responseCache.setContent(Core.createSystemContext(), stringBuilder.toString());
	}

	public SpeedyHeaders getHeaders(ResponseCache responseCache) {
		return deserializeHeaders(responseCache.getHeaders(Core.createSystemContext()));
	}

	public void addHeader(ResponseCache responseCache, String key, String value) {
		SpeedyHeaders speedyHeaders = getHeaders(responseCache);
		if (speedyHeaders == null) {
			speedyHeaders = new SpeedyHeaders();
		}

		speedyHeaders.addHeader(key, value);
		responseCache.setHeaders(Core.createSystemContext(), serializeHeaders(speedyHeaders));
	}

	public List<Cookie> getCookies(ResponseCache responseCache) {
		return deserializeCookies(responseCache.getCookies(Core.createSystemContext()));
	}

	public void addCookie(ResponseCache responseCache, Cookie cookie) {
		List<Cookie> cookies = getCookies(responseCache);
		cookies.add(cookie);
		responseCache.setCookies(Core.createSystemContext(), serializeCookies(cookies));
	}

	public long cacheTTL() {
		return  Constants.getCACHE_TTL();
	}

	public void clearCacheEntry(ResponseCache responseCache) {
		Core.delete(Core.createSystemContext(), responseCache.getMendixObject());
	}

	private SpeedyHeaders deserializeHeaders(String headerString) {
		Gson gson = new Gson();
		return gson.fromJson(headerString, SpeedyHeaders.class);
	}

	private String serializeHeaders(SpeedyHeaders speedyHeaders) {
		Gson gson = new Gson();
		return gson.toJson(speedyHeaders, SpeedyHeaders.class);
	}

	private List<Cookie> deserializeCookies(String cookieString) {
		Gson gson = new Gson();

		if (cookieString != null) {
			Type collectionType = new TypeToken<ArrayList<Cookie>>() {}.getType();
			return gson.fromJson(cookieString, collectionType);
		}

		return new ArrayList<Cookie>();
	}

	private String serializeCookies(List<Cookie> cookies) {
		if (!cookies.isEmpty()) {
			Gson gson = new Gson();
			Type collectionType = new TypeToken<ArrayList<Cookie>>() {}.getType();
			return gson.toJson(cookies, collectionType);
		}
		return new String();
	}
}


text:
/**
 * @callback Phaser.Types.Tweens.TimelineOnLoopCallback
 * @since 3.18.0
 *
 * @param {Phaser.Tweens.Timeline} timeline - The timeline.
 * @param {...any} param - Any value passed in `onLoopParams`.
 */


text:
package com.jigdraw.draw.activity;

import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import android.view.View;

/**
 * Unit test for draw activity class
 *
 * @author Jay Paulynice
 */
public class DrawActivityTest extends
        ActivityInstrumentationTestCase2<DrawActivity> {
    private static final String TAG = "DrawActivityTest";
    private DrawActivity activity;

    public DrawActivityTest() {
        super(DrawActivity.class);

    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        activity = getActivity();
    }

    public void testActivityNotNull() {
        Log.d(TAG, "testing activity not null...");
        assertNotNull(activity);
    }

    public void testControlsVisible() {
        Log.d(TAG, "testing ui controls visible...");
        for (View v : activity.getTopOptions()) {
            assertTrue(View.VISIBLE == v.getVisibility());
        }

        for (View b : activity.getBrushes()) {
            assertTrue(View.VISIBLE == b.getVisibility());
        }
    }
}


text:
import unittest

from streamlink.plugins.abweb import ABweb

class TestPluginABweb(unittest.TestCase):
    def test_can_handle_url(self):
        should_match = [
            'http://www.abweb.com/bis-tv-online/bistvo-tele-universal.aspx?chn=ab1',
            'http://www.abweb.com/BIS-TV-Online/bistvo-tele-universal.aspx?chn=ab1',
            'http://www.abweb.com/BIS-TV-Online/bistvo-tele-universal.aspx?chn=luckyjack',
            'https://www.abweb.com/BIS-TV-Online/bistvo-tele-universal.aspx?chn=action',
        ]
        for url in should_match:
            self.assertTrue(ABweb.can_handle_url(url), url)

    def test_can_handle_url_negative(self):
        should_not_match = [
            'http://www.abweb.com',
        ]
        for url in should_not_match:
            self.assertFalse(ABweb.can_handle_url(url), url)


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

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity">

        <LinearLayout
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:font="@{`alegreya`}"
                android:text="@string/example"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:font="@{`alegreya-bold`}"
                android:text="@string/example"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:font="@{`alegreya-italic`}"
                android:text="@string/example"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:font="@{`alegreya-bolditalic`}"
                android:text="@string/example"/>

        </LinearLayout>
    </FrameLayout>
</layout>


text:
package ecs

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// RecoverVirtualBorderRouter invokes the ecs.RecoverVirtualBorderRouter API synchronously
// api document: https://help.aliyun.com/api/ecs/recovervirtualborderrouter.html
func (client *Client) RecoverVirtualBorderRouter(request *RecoverVirtualBorderRouterRequest) (response *RecoverVirtualBorderRouterResponse, err error) {
	response = CreateRecoverVirtualBorderRouterResponse()
	err = client.DoAction(request, response)
	return
}

// RecoverVirtualBorderRouterWithChan invokes the ecs.RecoverVirtualBorderRouter API asynchronously
// api document: https://help.aliyun.com/api/ecs/recovervirtualborderrouter.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) RecoverVirtualBorderRouterWithChan(request *RecoverVirtualBorderRouterRequest) (<-chan *RecoverVirtualBorderRouterResponse, <-chan error) {
	responseChan := make(chan *RecoverVirtualBorderRouterResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.RecoverVirtualBorderRouter(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// RecoverVirtualBorderRouterWithCallback invokes the ecs.RecoverVirtualBorderRouter API asynchronously
// api document: https://help.aliyun.com/api/ecs/recovervirtualborderrouter.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) RecoverVirtualBorderRouterWithCallback(request *RecoverVirtualBorderRouterRequest, callback func(response *RecoverVirtualBorderRouterResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *RecoverVirtualBorderRouterResponse
		var err error
		defer close(result)
		response, err = client.RecoverVirtualBorderRouter(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// RecoverVirtualBorderRouterRequest is the request struct for api RecoverVirtualBorderRouter
type RecoverVirtualBorderRouterRequest struct {
	*requests.RpcRequest
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	ClientToken          string           `position:"Query" name:"ClientToken"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	UserCidr             string           `position:"Query" name:"UserCidr"`
	VbrId                string           `position:"Query" name:"VbrId"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
}

// RecoverVirtualBorderRouterResponse is the response struct for api RecoverVirtualBorderRouter
type RecoverVirtualBorderRouterResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
}

// CreateRecoverVirtualBorderRouterRequest creates a request to invoke RecoverVirtualBorderRouter API
func CreateRecoverVirtualBorderRouterRequest() (request *RecoverVirtualBorderRouterRequest) {
	request = &RecoverVirtualBorderRouterRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Ecs", "2014-05-26", "RecoverVirtualBorderRouter", "ecs", "openAPI")
	return
}

// CreateRecoverVirtualBorderRouterResponse creates a response to parse from RecoverVirtualBorderRouter response
func CreateRecoverVirtualBorderRouterResponse() (response *RecoverVirtualBorderRouterResponse) {
	response = &RecoverVirtualBorderRouterResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
Hopefully something will go here soon.
###Rundown/Deliverables
This is a coding project I have done for my information systems 2A course. It is a multi-form windows desktop application done in C#.
There are three forms. A Login form, and Admin form and A Booking form. The project requires the use of 2 arrays to store show names and cost.
Also, the use a dates is needed in the project.
###Extras
I want to add some cool extras into the project to make it more interesting for me to make.
Something cool with data storage and user accounts - maybe if I have time.

##Something else.
I am using this project as a springboard for an idea I have been playing around with. This is a test-prototype for a new way of working I have been thinking about.
I would like to build a system of working on something that takes ideas from Agile development techniques and applies them to a single person's workflow.
The idea is that system also allows for teamwork but does not rely on it. It should also be quite dynamic and help the user improve their workflows.

What I am doing with this project is using a few project management tools to simulate some major concepts (1 or 2) I have an see if they work in helping me develop this project.
I am using GitHub as my main web app but also http://waffle.io as a work dashboard to track my progress and spec out the project boundaries and deadlines.
I have done these things before but not for something with a definite end and no other team members. Here I want to primarily optimise my workflow and analyse in real-time what is going on.

##Conclusion / Post-mortem
So the project brief is located in the repo - you can read it there.
This method of working is not new for me. In the past I have used whiteboards, paper and Google Keep.
The method succeeds in a few ways. It allows me to break-up complex problems into a set of small steps.
I can also track and monitor what I am doing.
It also makes a project spec much easier to deal with and quicker to do.

There are problems I am hoping to solve with a proper software solution.
The major problem is keeping in the timeframe decided on.
Also scoping correctly at the beginning rather than adding snippets (GitHub issues) during the project implementation phase.
Doing this makes the project naturally grow and leads to feature creep.

###Waffle.IO
![Image of Waffle.io](http://jasonchalom.com/IS2AMultiFormProject/SomeData/WaffleScreenshot.PNG)
Waffle IO is not really the correct tool for the job.
That is what I learned from this. The biggest struggle was keeping in the correct time frame which I did not do.
![Image of GitHub Milestones](http://jasonchalom.com/IS2AMultiFormProject/SomeData/Milestones.PNG)

I did run out of time, but this method of working did succeed in a few ways.

I got to complete all the main tasks for this little university project.
![Image of GitHub Issues](http://jasonchalom.com/IS2AMultiFormProject/SomeData/Issues.PNG)

###AppVeyor
AppVeyor as a CI for .net projects is so much better than TravisCI.
TravisCI works well for linux stuff but the setup for .net is quite time consuming and gives you a lot of grief.
AppVeyor took 2 minutes to setup. Point it to the sln file and MSBUILD takes over and uses the correct build setings.

FIN.
----


text:
<?php declare(strict_types=1);

namespace ApiClients\Tests\Github\CommandBus\Handler\Repository;

use ApiClients\Client\Github\CommandBus\Command\Repository\BlobCommand;
use ApiClients\Client\Github\CommandBus\Handler\Repository\BlobHandler;
use ApiClients\Client\Github\Resource\TreeInterface;
use ApiClients\Foundation\Hydrator\Hydrator;
use ApiClients\Foundation\Transport\Service\RequestService;
use ApiClients\Middleware\Json\JsonStream;
use ApiClients\Tools\TestUtilities\TestCase;
use Prophecy\Argument;
use Psr\Http\Message\RequestInterface;
use React\EventLoop\Factory;
use function React\Promise\Stream\buffer;
use React\Stream\ThroughStream;
use RingCentral\Psr7\Response;
use function WyriHaximus\React\timedPromise;

/**
 * @internal
 */
final class BlobHandlerTest extends TestCase
{
    public function provideCommands()
    {
        /*yield [
            function () {
                $body = 'foo.bar';
                $loop = Factory::create();
                $stream = new ThroughStream();
                $loop->addTimer(1, function () use ($stream, $body) {
                    $stream->end($body);
                });
                $request = new RenderMarkdownCommand(
                    $stream,
                    'gfm',
                    'php-api-clients/github'
                );
                $expectedJson = [
                    'text' => $body,
                    'mode' => 'gfm',
                    'context' => 'php-api-clients/github',
                ];

                return [$loop, $request, $expectedJson];
            },
        ];*/

        yield [
            function () {
                $body = 'foo.bar';
                $loop = Factory::create();
                $stream = new ThroughStream();
                $loop->addTimer(1, function () use ($stream, $body) {
                    $stream->end($body);
                });
                $request = new BlobCommand(
                    'login/repo',
                    $stream
                );
                $expectedJson = [
                    'encoding' => 'base64',
                    'content' => \base64_encode($body),
                ];

                return [$loop, $request, $expectedJson];
            },
        ];
    }

    /**
     * @dataProvider provideCommands
     */
    public function testCommand(callable $callable)
    {
        list($loop, $command, $expectedjson) = $callable();
        $json = [
            'foo' => 'bar',
        ];
        $stream = null;
        $jsonStream = new JsonStream($json);

        $tree = $this->prophesize(TreeInterface::class)->reveal();

        $requestService = $this->prophesize(RequestService::class);
        $requestService->request(Argument::that(function (RequestInterface $request) use (&$stream) {
            buffer($request->getBody())->done(function ($json) use (&$stream) {
                $stream = $json;
            });

            return true;
        }))->willReturn(timedPromise($loop, 1, new Response(
            200,
            [],
            $jsonStream
        )));

        $hydrator = $this->prophesize(Hydrator::class);
        $hydrator->hydrate(TreeInterface::HYDRATE_CLASS, $json)->shouldBeCalled()->willReturn($tree);

        $handler = new BlobHandler($requestService->reveal(), $hydrator->reveal(), $loop);

        $result = $this->await($handler->handle($command), $loop);
        self::assertSame($tree, $result);
        self::assertSame($expectedjson, \json_decode($stream, true));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SessionM.MMC.API
{
    public class APIRoutes
    {
        private static string ConstructRoute(string suffix)
        {
            return APIConstants.serviceUrl() + "/apps/" + APIConstants.getApiKey() + suffix;
        }

        public static string createUserRoute() {
            return ConstructRoute("/users");
        }

        public static string fetchUserWithIdRoute()
        {
            return ConstructRoute("/users/");
        }

        public static string fetchUserWithExternalIdRoute()
        {
            return ConstructRoute("/external/users/");
        }

        public static string deleteUserWithIdRoute()
        {
            return fetchUserWithIdRoute();
        }

        public static string deleteUserUserWithExternalIdRoute()
        {
            return fetchUserWithExternalIdRoute();
        }

        public static string updateUserWithId()
        {
            return fetchUserWithIdRoute();
        }

        public static string addAttributesToUserModel()
        {
            return ConstructRoute("/models/user_profiles/attributes");
        }

        public static string fetchCurrentAttributesInUserModel()
        {
            return ConstructRoute("/models/user_profiles");
        }

        public static string fetchOffersRoute(string locale = null)
        {

            return ConstructRoute("/offers") +
                    (String.IsNullOrEmpty(locale) ? String.Empty : ("?locale=" + locale));
        }

        public static string fetchOffersWithIdRoute(String Id, string locale = null)
        {

            return ConstructRoute("/users/" + Id + "/offers") +
                    (String.IsNullOrEmpty(locale) ? String.Empty : ("?locale=" + locale));
        }

        public static string fetchOffersWithExternalIdRoute(String ExternalId, string locale = null)
        {

            return ConstructRoute("/external/users/" + ExternalId + "/offers") +
                    (String.IsNullOrEmpty(locale) ? String.Empty : ("?locale=" + locale));
        }

        public static string createNewOrderForOfferWithIdRoute(String offerId, String Id)
        {
            return ConstructRoute("/users/" + Id + "/offers/" + offerId + "/orders");
        }

        public static string createNewOrderForOfferWithExternalIdRoute(String offerId, String ExternalId)
        {
            return ConstructRoute("/external/users/" + ExternalId + "/offers/" + offerId + "/orders");
        }

        public static string sendEventWithExternalIdRoute(String ExternalId)
        {
            return ConstructRoute("/external/users/" + ExternalId + "/events");
        }

        public static string sendEventWithIdRoute(String Id)
        {
            return ConstructRoute("/users/" + Id + "/events");
        }

        public static string sendSMSWithLinkWithUserIdRoute(String userId, bool prependExternal = false)
        {
            return ConstructRoute(String.Format("{0}/users/" + userId + "/verifications/sms", prependExternal ? "/external" : ""));
        }

        public static string sendSMSWithLinkWithExternalIdRoute(String externalId)
        {
            return sendSMSWithLinkWithUserIdRoute(externalId, true);
        }

        public static string validateActivationCodeWithUserIdRoute(string userId, string verificationId)
        {
            return sendSMSWithLinkWithUserIdRoute(userId) + "/" + verificationId;
        }

        public static string validateActivationCodeWithExternalIdRoute(string externalId, string verificationId)
        {
            return sendSMSWithLinkWithUserIdRoute(externalId, true) + "/" + verificationId;
        }

        public static string validateActivationCodeWithUserIdRoute(string userId)
        {
            return validateActivationCodeWithUserIdRoute(userId, "verifycode");
        }

        public static string validateActivationCodeWithExternalIdRoute(string userId)
        {
            return validateActivationCodeWithExternalIdRoute(userId, "verifycode");
        }

        public static string addUserMetaDataWithUserIdRoute(string userId, bool prependExternal = false)
        {
            return ConstructRoute(String.Format("{0}/users/" + userId + "/data", prependExternal ? "/external" : ""));
        }

        public static string addUserMetaDataWithExternalIdRoute(String externalId)
        {
            return addUserMetaDataWithUserIdRoute(externalId, true);
        }

        public static string validateImageWithUserIdRoute(string userId, bool prependExternal = false)
        {
            return ConstructRoute(String.Format("{0}/users/" + userId + "/image_validations", prependExternal ? "/external" : ""));
        }

        public static string validateImageWithExternalIdRoute(string externalId)
        {
            return validateImageWithUserIdRoute(externalId, true);
        }

        public static string challengeQuestionWithUserIdRoute(string userId, bool prependExternal = false)
        {
            return ConstructRoute(String.Format("{0}/users/" + userId + "/challenges/skills_test_question", prependExternal ? "/external" : ""));
        }

        public static string challengeQuestionWithExternalIdRoute(string externalId)
        {
            return challengeQuestionWithUserIdRoute(externalId, true);
        }

        public static string pointHistoryWithUserIdRoute(string userId, string startDate, string endDate, Nullable<int> limit, string cursor, bool prependExternal = false)
        {
            string retVal = ConstructRoute(String.Format("{0}/users/" + userId + "/points/transactions", prependExternal ? "/external" : ""));
            List<string> getLineArgs = new List<string>();

            if (startDate != null)
            {
                getLineArgs.Add("start_date=" + startDate);
            }

            if (endDate != null)
            {
                getLineArgs.Add("end_date=" + endDate);
            }

            if (limit != null)
            {
                getLineArgs.Add("limit=" + limit);
            }

            if (cursor != null)
            {
                getLineArgs.Add("cursor=" + cursor);
            }

            retVal = getLineArgs.Count <= 0 ? retVal : (retVal + "?" + String.Join("&", getLineArgs.ToArray()));

            return retVal;
        }

        public static string pointHistoryWithExternalIdRoute(string externalId, string startDate, string endDate, Nullable<int> limit, string cursor)
        {
            return pointHistoryWithUserIdRoute(externalId, startDate, endDate, limit, cursor, true);
        }

        public static string challengeAnswerSubmissionWithUserIdRoute(string userId, int skillsTestQuestionId, int offerId, bool prependExternal = false)
        {
            return ConstructRoute(String.Format("{0}/users/" + userId + "/offers/" + offerId + "/challenges/skills_test_questions/" + skillsTestQuestionId, prependExternal ? "/external" : ""));
        }

        public static string challengeAnswerSubmissionWithExternalIdRoute(string externalId, int skillsTestQuestionId, int offerId)
        {
            return challengeAnswerSubmissionWithUserIdRoute(externalId, skillsTestQuestionId, offerId, true);
        }

        public static string validateVerificationIdWithUserIdRoute(string userId, string verificationId, bool prependExternal = false)
        {
            return ConstructRoute(String.Format("{0}/users/" + userId + "/verifications/sms/" + verificationId, prependExternal ? "/external" : ""));
        }

        public static string validateVerificationIdWithExternalIdRoute(string externalId, string verificationId)
        {
            return validateVerificationIdWithUserIdRoute(externalId, verificationId, true);
        }

        public static string addProxyIdWithExternalIdRoute(string externalId)
        {
            return ConstructRoute("/external/users/" + externalId);
        }

        public static string addRemoveProxyIdWithExternalIdRoute(string externalId)
        {
            return ConstructRoute("/external/users/" + externalId);
        }

    }
}


text:
<#
.EXAMPLE
    This example creates a new search service app in the local farm
#>

    Configuration Example
    {
        param(
            [Parameter(Mandatory = $true)]
            [PSCredential]
            $SetupAccount,

            [Parameter(Mandatory = $true)]
            [PSCredential]
            $SearchAccount
        )
        Import-DscResource -ModuleName SharePointDsc

        node localhost {
            SPSearchServiceSettings SearchServiceSettings
            {
                IsSingleInstance      = "Yes"
                PerformanceLevel      = "Maximum"
                ContactEmail          = "sharepoint@contoso.com"
                WindowsServiceAccount = $SearchAccount
                PsDscRunAsCredential  = $SetupAccount
            }
        }
    }


text:
package org.javafunk.funk.jackson.monad;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.javafunk.funk.jackson.FunkModule;
import org.javafunk.funk.matchers.OptionMatchers;
import org.javafunk.funk.monads.Option;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.javafunk.funk.matchers.OptionMatchers.hasValue;

public class OptionDeserializerTest {

    private static final TypeReference<?> OptionTypeRef = new TypeReference<Option<String>>() {};

    private ObjectMapper objectMapper;

    @Before
    public void createObjectMapper() {
        objectMapper = new ObjectMapper()
                .registerModule(new FunkModule());
    }

    @Test
    public void shouldDeserializeNone() throws Exception {
        // When
        Option<String> value = objectMapper.readValue("null", OptionTypeRef);

        // Then
        assertThat(value, OptionMatchers.<String>hasNoValue());
    }

    @Test
    public void shouldDeserializeSimpleString() throws Exception {
        // When
        Option<String> value = objectMapper.readValue("\"simpleString\"", OptionTypeRef);

        // Then
        assertThat(value, hasValue("simpleString"));
    }

    @Test
    public void shouldDeserializeInsideAnObject() throws Exception {
        // When
        OptionData data = objectMapper.readValue("{\"myString\":\"simpleString\"}", OptionData.class);

        // Then
        assertThat(data.myString, hasValue("simpleString"));
    }

    @Test
    public void shouldDeserializeComplexObject() throws Exception {
        // Given
        TypeReference<Option<OptionData>> type = new TypeReference<Option<OptionData>>() {};

        // When
        Option<OptionData> data = objectMapper.readValue("{\"myString\":\"simpleString\"}", type);

        // Then
        assertThat(data, OptionMatchers.<OptionData>hasValue());
        assertThat(data.get().myString, hasValue("simpleString"));
    }

    @Test
    public void shouldDeserializeGenerics() throws Exception {
        // Given
        TypeReference<Option<GenericData<String>>> type = new TypeReference<Option<GenericData<String>>>() {};

        // When
        Option<GenericData<String>> data = objectMapper.readValue("{\"myData\":\"simpleString\"}", type);

        // Then
        assertThat(data, OptionMatchers.<GenericData<String>>hasValue());
        assertThat(data.get().myData, hasValue("simpleString"));
    }

}


text:
<!--
  Test Description:
  Tests for amp-google-read-aloud-player tag.
-->
<!doctype html>
<html ⚡>

<head>
  <meta charset="utf-8">
  <title>amp-google-read-aloud-player example</title>
  <link rel="canonical" href="amps.html">
  <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
  <style amp-boilerplate>
    body {
      -webkit-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      -moz-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      -ms-animation: -amp-start 8s steps(1, end) 0s 1 normal both;
      animation: -amp-start 8s steps(1, end) 0s 1 normal both
    }

    @-webkit-keyframes -amp-start {
      from {
        visibility: hidden
      }

      to {
        visibility: visible
      }
    }

    @-moz-keyframes -amp-start {
      from {
        visibility: hidden
      }

      to {
        visibility: visible
      }
    }

    @-ms-keyframes -amp-start {
      from {
        visibility: hidden
      }

      to {
        visibility: visible
      }
    }

    @-o-keyframes -amp-start {
      from {
        visibility: hidden
      }

      to {
        visibility: visible
      }
    }

    @keyframes -amp-start {
      from {
        visibility: hidden
      }

      to {
        visibility: visible
      }
    }
  </style><noscript>
    <style amp-boilerplate>
      body {
        -webkit-animation: none;
        -moz-animation: none;
        -ms-animation: none;
        animation: none
      }
    </style>
  </noscript>
  <script async custom-element="amp-google-read-aloud-player" src="https://cdn.ampproject.org/v0/amp-google-read-aloud-player-0.1.js"></script>
  <script async src="https://cdn.ampproject.org/v0.js"></script>
</head>

<body>
  <!-- Valid: No data-url -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Valid: Has data-url -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1"
    data-url="https://blog.google/products/assistant/easier-access-web-pages-let-assistant-read-it-aloud/"
    data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Valid: Multiple values for data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1,UA-168915890-2" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Valid: Opposite digits sections for data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-1-168915890"
    data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Valid: Few digits data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-1-1" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Valid: English locale for data-locale -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1" data-voice="en.some-voice" data-locale="en">
  </amp-google-read-aloud-player>

  <!-- Valid: Spanish locale for data-locale -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1" data-voice="en.some-voice" data-locale="es">
  </amp-google-read-aloud-player>

  <!-- Invalid: No data-api-key -->
  <amp-google-read-aloud-player height="66" data-tracking-ids="UA-168915890-1" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: Missing UA prefix data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="123" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: No UA prefix for data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="168915890-1" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: Missing second number data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="ua-1" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: Surplus digit data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-1-1.2" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: Emptry data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: Surplus letters data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-1-1 XYZ" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: No data-tracking-ids -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: No data-voice -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1">
  </amp-google-read-aloud-player>

  <!-- Invalid: Local address value for data-url -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-url="index.html" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Invalid: http protocol for data-url -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-url="http://www.example.com/index.html" data-voice="en.some-voice">
  </amp-google-read-aloud-player>

  <!-- Valid: Four letters locale for data-locale -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-tracking-ids="UA-168915890-1" data-voice="en.some-voice" data-locale="en-US">
  </amp-google-read-aloud-player>

  <!-- Invalid: Local address value for data-intro -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-voice="en.some-voice" data-intro="file.mp3">
  </amp-google-read-aloud-player>

  <!-- Invalid: Local address value for data-outro -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-voice="en.some-voice" data-outro="file.mp3">
  </amp-google-read-aloud-player>

  <!-- Invalid: Local address value for data-ad-tag-url -->
  <amp-google-read-aloud-player height="66" data-api-key="YOUR_API_KEY" data-voice="en.some-voice" data-ad-tag-url="index.html">
  </amp-google-read-aloud-player>
</body>

</html>


text:
using JetBrains.Annotations;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Occurrences;
using JetBrains.ReSharper.Feature.Services.Tree;
using JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.Resources.Icons;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Feature.Services.Navigation;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy;
using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.Rider.Backend.Features.Usages;
using JetBrains.Rider.Backend.Platform.Icons;
using JetBrains.Rider.Model;
using JetBrains.UI.Icons;
using JetBrains.Util;

namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.Yaml.Feature.Usages
{
    [SolutionComponent]
    public class UnityYamlExtraGroupingRulesProvider : IRiderExtraGroupingRulesProvider
    {
        // IconHost is optional so that we don't fail if we're in tests
        public UnityYamlExtraGroupingRulesProvider(MetaFileGuidCache metaFileGuidCache = null, UnitySolutionTracker unitySolutionTracker = null, IconHost iconHost = null)
        {
            if (unitySolutionTracker != null && unitySolutionTracker.IsUnityProject.HasValue() && unitySolutionTracker.IsUnityProject.Value
                && iconHost != null && metaFileGuidCache != null)
            {
                ExtraRules = new IRiderUsageGroupingRule[]
                {
                    new GameObjectUsageGroupingRule(iconHost),
                    new ComponentUsageGroupingRule(metaFileGuidCache, iconHost),
                    new AnimationEventGroupingRule(iconHost),
                    new AnimatorGroupingRule(iconHost)
                };
            }
            else
            {
                ExtraRules = new IRiderUsageGroupingRule[0];
            }
        }

        public IRiderUsageGroupingRule[] ExtraRules { get; }
    }

    public abstract class UnityYamlUsageGroupingRuleBase : IRiderUsageGroupingRule
    {
        [CanBeNull] private readonly IconHost myIconHost;

        protected UnityYamlUsageGroupingRuleBase(string name, IconId iconId, [CanBeNull] IconHost iconHost,
            double sortingPriority)
        {
            Name = name;
            IconId = iconId;
            SortingPriority = sortingPriority;
            myIconHost = iconHost;
        }

        protected RdUsageGroup CreateModel(string text)
        {
            return new RdUsageGroup(Name, text, myIconHost?.Transform(IconId));
        }

        protected RdUsageGroup EmptyModel()
        {
            return new RdUsageGroup(Name, string.Empty, null);
        }

        public abstract RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor);
        public abstract void Navigate(IOccurrence occurrence);

        public string Name { get; }
        public IconId IconId { get; }
        public bool IsSeparable => true;
        public abstract bool IsNavigateable { get; }
        public bool Configurable => true;
        public bool PriorityDependsOnUsages => true;
        public double SortingPriority { get; }
        public bool DefaultValue { get; } = true;
        public IDeclaredElement GetDeclaredElement(IOccurrence occurrence) => null;
        public IProjectItem GetProjectItem(IOccurrence occurrence) => null;
    }

    public class AnimatorGroupingRule : UnityYamlUsageGroupingRuleBase
    {
        public AnimatorGroupingRule([NotNull] IconHost iconHost)
            : base("Animator", UnityFileTypeThemedIcons.FileAnimatorController.Id, iconHost, 10.0)
        {
        }

        public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
        {
            if (!(occurrence is UnityAnimatorScriptOccurence animationEventOccurence)) return EmptyModel();
            var text = animationEventOccurence.GetDisplayText()?.Text.Split('/');
            return text != null ? CreateModel(text.Join("\\")) : EmptyModel();
        }

        public override void Navigate(IOccurrence occurrence)
        {
            throw new System.NotImplementedException();
        }

        public override bool IsNavigateable => false;
    }

    public class AnimationEventGroupingRule : UnityYamlUsageGroupingRuleBase
    {
        public AnimationEventGroupingRule([NotNull] IconHost iconHost)
            : base("AnimationEvent", UnityFileTypeThemedIcons.FileAnimationClip.Id, iconHost, 9.0)
        {
        }

        public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
        {
            if (!(occurrence is UnityAnimationEventOccurence animationEventOccurence)) return EmptyModel();
            var text = animationEventOccurence.GetDisplayText()?.Text;
            return text != null ? CreateModel(text) : EmptyModel();
        }

        public override void Navigate(IOccurrence occurrence)
        {
            throw new System.NotImplementedException();
        }

        public override bool IsNavigateable => false;
    }

    // The priorities here put us after directory, file, namespace, type and member
    public class GameObjectUsageGroupingRule : UnityYamlUsageGroupingRuleBase
    {
        // Note that the name is in CamelCase and spaces are added in the frontend
        public GameObjectUsageGroupingRule([NotNull] IconHost iconHost)
            : base("UnityGameObject", UnityObjectTypeThemedIcons.UnityGameObject.Id, iconHost, 7.0)
        {
        }

        public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
        {
            using (CompilationContextCookie.GetExplicitUniversalContextIfNotSet())
            {
                if (occurrence is UnityAssetOccurrence assetOccurrence &&
                      !assetOccurrence.SourceFile.IsAsset() &&
                      !assetOccurrence.SourceFile.IsAnim() &&
                      !assetOccurrence.SourceFile.IsController())
                {
                    using (ReadLockCookie.Create())
                    {
                        var solution = occurrence.GetSolution();
                        var processor = solution.GetComponent<AssetHierarchyProcessor>();
                        var consumer = new UnityScenePathGameObjectConsumer();
                        processor.ProcessSceneHierarchyFromComponentToRoot(assetOccurrence.OwningElementLocation, consumer, true, true);
                        string name = "...";
                        if (consumer.NameParts.Count > 0)
                            name = string.Join("\\", consumer.NameParts);

                        return CreateModel(name);
                    }
                }
            }

            return EmptyModel();
        }

        public override void Navigate(IOccurrence occurrence)
        {
            throw new System.NotImplementedException();
        }

        public override bool IsNavigateable => false;
    }

    public class ComponentUsageGroupingRule : UnityYamlUsageGroupingRuleBase
    {
        private readonly MetaFileGuidCache myMetaFileGuidCache;

        // Note that the name is in CamelCase and spaces are added in the frontend
        public ComponentUsageGroupingRule(MetaFileGuidCache metaFileGuidCache, [NotNull] IconHost iconHost)
            : base("UnityComponent", UnityObjectTypeThemedIcons.UnityComponent.Id, iconHost, 8.0)
        {
            myMetaFileGuidCache = metaFileGuidCache;
        }

        public override RdUsageGroup CreateModel(IOccurrence occurrence, IOccurrenceBrowserDescriptor descriptor)
        {
            using (CompilationContextCookie.GetExplicitUniversalContextIfNotSet())
            {
                if (occurrence is UnityAssetOccurrence assetOccurrence &&
                    !assetOccurrence.SourceFile.IsAsset() &&
                    !assetOccurrence.SourceFile.IsAnim() &&
                    !assetOccurrence.SourceFile.IsController())
                {
                    var hierarchyContainer = assetOccurrence.GetSolution()?.GetComponent<AssetDocumentHierarchyElementContainer>();
                    var element = hierarchyContainer?.GetHierarchyElement(assetOccurrence.OwningElementLocation, true);
                    if (element is IComponentHierarchy componentHierarchyElement)
                        return CreateModel(AssetUtils.GetComponentName(myMetaFileGuidCache, componentHierarchyElement));
                }
            }

            return EmptyModel();
        }

        public override void Navigate(IOccurrence occurrence)
        {
            throw new System.NotImplementedException();
        }

        public override bool IsNavigateable => false;
    }
}