text:
/**
 * Package which contains all views
 */
package com.imie.component.view;

import com.imie.component.entity.Invoice;
import com.imie.component.form.InvoiceEditor;
import com.imie.component.repository.InvoiceRepository;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.FontAwesome;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

/**
 * <b>Invoice View</b>
 *
 * @author kevin boussard
 * @version 1.0
 */
@SpringView(name = InvoiceView.VIEW_NAME)
public class InvoiceView extends VerticalLayout implements View {

    public static final String VIEW_NAME = "invoice";

    private final InvoiceRepository repo;

    private final InvoiceEditor editor;

    private final Grid grid;

    private final TextField filter;

    private final Button addNewBtn;

    @Autowired
    public InvoiceView(InvoiceRepository repo, InvoiceEditor editor) {
        this.repo = repo;
        this.editor = editor;
        this.grid = new Grid();
        this.filter = new TextField();
        this.addNewBtn = new Button("New invoice", FontAwesome.PLUS);
    }

    @PostConstruct
    void init() {

        // build layout
        HorizontalLayout actions = new HorizontalLayout(filter, addNewBtn);
        VerticalLayout mainLayout = new VerticalLayout(actions, grid, editor);
        addComponent(mainLayout);

        // Configure layouts and components
        actions.setSpacing(true);
        mainLayout.setMargin(true);
        mainLayout.setSpacing(true);

        grid.setHeight(300, Unit.PIXELS);
        grid.setWidth(100, Unit.PERCENTAGE);

        filter.setInputPrompt("Filter by last name");

        // Hook logic to components

        // Replace listing with filtered content when user changes filter
        filter.addTextChangeListener(e -> listInvoices(e.getText()));

        // Connect selected Customer to editor or hide if none is selected
        grid.addSelectionListener(e -> {
            if (e.getSelected().isEmpty()) {
                editor.setVisible(false);
            }
            else {
                editor.editInvoice((Invoice) grid.getSelectedRow());
            }
        });

        // Instantiate and edit new Product the new button is clicked
        addNewBtn.addClickListener(e -> editor.editInvoice(new Invoice()));

        // Listen changes made by the editor, refresh data from backend
        editor.setChangeHandler(() -> {
            editor.setVisible(false);
            listInvoices(filter.getValue());
        });

        // Initialize listing
        listInvoices(null);
    }

    private void listInvoices(String text) {
        if (StringUtils.isEmpty(text)) {
            grid.setContainerDataSource(
                    new BeanItemContainer(Invoice.class, repo.findAll()));
        }
        else {
            grid.setContainerDataSource(new BeanItemContainer(Invoice.class,
                    repo.findAll()));
        }
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        // the view is constructed in the init() method()
    }

}


text:
class Deposit < Payment
  before_save :set_sign
  validate :maximum_credit_amount, :not_before_credit_agreement_starts

  private
    def not_before_credit_agreement_starts
      errors.add(:date, :not_before, date: I18n.l(credit_agreement.valid_from)) if date < credit_agreement.valid_from
    end

    def maximum_credit_amount
      errors.add(:amount, :to_much, max: error_max) if change_amount > max
    end

    def set_sign
      self.sign = 1
    end

    def max
      credit_agreement.amount - Deposit.where(credit_agreement_id: credit_agreement_id).sum(:amount)
    end

    def change_amount
      return amount if new_record?
      amount - amount_was
    end

    def error_max
      return max if new_record?
      max + amount_was
    end
end

redpajama_set_name: RedPajamaGithub


text:
namespace Colorful
{
	using UnityEngine;

	[HelpURL("http://www.thomashourdel.com/colorful/doc/color-correction/bleach-bypass.html")]
	[ExecuteInEditMode]
	[AddComponentMenu("Colorful FX/Color Correction/Bleach Bypass")]
	public class BleachBypass : BaseEffect
	{
		[Range(0f, 1f), Tooltip("Blending factor.")]
		public float Amount = 1f;

		protected override void OnRenderImage(RenderTexture source, RenderTexture destination)
		{
			if (Amount <= 0f)
			{
				Graphics.Blit(source, destination);
				return;
			}

			Material.SetFloat("_Amount", Amount);
			Graphics.Blit(source, destination, Material);
		}

		protected override string GetShaderName()
		{
			return "Hidden/Colorful/Bleach Bypass";
		}
	}
}


text:
import copy
import ssl
import time
from unittest import mock

from dogpile.cache import proxy
from oslo_config import cfg
from oslo_utils import uuidutils
from pymemcache import KeepaliveOpts

from oslo_cache import _opts
from oslo_cache import core as cache
from oslo_cache import exception
from oslo_cache.tests import test_cache

NO_VALUE = cache.NO_VALUE
TEST_GROUP = uuidutils.generate_uuid(dashed=False)
TEST_GROUP2 = uuidutils.generate_uuid(dashed=False)

def _copy_value(value):
    if value is not NO_VALUE:
        value = copy.deepcopy(value)
    return value

class TestProxy(proxy.ProxyBackend):
    def get(self, key):
        value = _copy_value(self.proxied.get(key))
        if value is not NO_VALUE:
            if isinstance(value[0], TestProxyValue):
                value[0].cached = True
        return value

class TestProxyValue(object):
    def __init__(self, value):
        self.value = value
        self.cached = False

class CacheRegionTest(test_cache.BaseTestCase):

    def setUp(self):
        super(CacheRegionTest, self).setUp()
        self.region = cache.create_region()
        cache.configure_cache_region(self.config_fixture.conf, self.region)
        self.region.wrap(TestProxy)
        self.region_kwargs = cache.create_region(
            function=cache.kwarg_function_key_generator)
        cache.configure_cache_region(self.config_fixture.conf,
                                     self.region_kwargs)
        self.region_kwargs.wrap(TestProxy)
        self.test_value = TestProxyValue('Decorator Test')

    def _add_test_caching_option(self):
        self.config_fixture.register_opt(
            cfg.BoolOpt('caching', default=True), group='cache')

    def _add_dummy_config_group(self):
        self.config_fixture.register_opt(
            cfg.IntOpt('cache_time'), group=TEST_GROUP)
        self.config_fixture.register_opt(
            cfg.IntOpt('cache_time'), group=TEST_GROUP2)

    def _get_cacheable_function(self, region=None):
        region = region if region else self.region
        memoize = cache.get_memoization_decorator(
            self.config_fixture.conf, region, group='cache')

        @memoize
        def cacheable_function(value=0, **kw):
            return value

        return cacheable_function

    def test_region_built_with_proxy_direct_cache_test(self):
        # Verify cache regions are properly built with proxies.
        test_value = TestProxyValue('Direct Cache Test')
        self.region.set('cache_test', test_value)
        cached_value = self.region.get('cache_test')
        self.assertTrue(cached_value.cached)

    def test_cache_region_no_error_multiple_config(self):
        # Verify configuring the CacheRegion again doesn't error.
        cache.configure_cache_region(self.config_fixture.conf, self.region)
        cache.configure_cache_region(self.config_fixture.conf, self.region)

    def _get_cache_fallthrough_fn(self, cache_time):
        memoize = cache.get_memoization_decorator(
            self.config_fixture.conf,
            self.region,
            group='cache',
            expiration_group=TEST_GROUP2)

        class _test_obj(object):
            def __init__(self, value):
                self.test_value = value

            @memoize
            def get_test_value(self):
                return self.test_value

        def _do_test(value):

            test_obj = _test_obj(value)

            # Ensure the value has been cached
            test_obj.get_test_value()
            # Get the now cached value
            cached_value = test_obj.get_test_value()
            self.assertTrue(cached_value.cached)
            self.assertEqual(value.value, cached_value.value)
            self.assertEqual(cached_value.value, test_obj.test_value.value)
            # Change the underlying value on the test object.
            test_obj.test_value = TestProxyValue(
                uuidutils.generate_uuid(dashed=False))
            self.assertEqual(cached_value.value,
                             test_obj.get_test_value().value)
            # override the system time to ensure the non-cached new value
            # is returned
            new_time = time.time() + (cache_time * 2)
            with mock.patch.object(time, 'time',
                                   return_value=new_time):
                overriden_cache_value = test_obj.get_test_value()
                self.assertNotEqual(cached_value.value,
                                    overriden_cache_value.value)
                self.assertEqual(test_obj.test_value.value,
                                 overriden_cache_value.value)

        return _do_test

    def test_cache_no_fallthrough_expiration_time_fn(self):
        self._add_dummy_config_group()
        # Since we do not re-configure the cache region, for ease of testing
        # this value is set the same as the expiration_time default in the
        # [cache] group
        cache_time = 600
        expiration_time = cache._get_expiration_time_fn(
            self.config_fixture.conf, TEST_GROUP)
        do_test = self._get_cache_fallthrough_fn(cache_time)
        # Run the test with the dummy group cache_time value
        self.config_fixture.config(cache_time=cache_time,
                                   group=TEST_GROUP)
        test_value = TestProxyValue(uuidutils.generate_uuid(dashed=False))
        self.assertEqual(cache_time, expiration_time())
        do_test(value=test_value)

    def test_cache_fallthrough_expiration_time_fn(self):
        self._add_dummy_config_group()
        # Since we do not re-configure the cache region, for ease of testing
        # this value is set the same as the expiration_time default in the
        # [cache] group
        cache_time = 599
        expiration_time = cache._get_expiration_time_fn(
            self.config_fixture.conf, TEST_GROUP)
        do_test = self._get_cache_fallthrough_fn(cache_time)
        # Run the test with the dummy group cache_time value set to None and
        # the global value set.
        self.config_fixture.config(cache_time=None, group=TEST_GROUP)
        test_value = TestProxyValue(
            uuidutils.generate_uuid(dashed=False))
        self.assertIsNone(expiration_time())
        do_test(value=test_value)

    def test_should_cache_fn_global_cache_enabled(self):
        # Verify should_cache_fn generates a sane function for subsystem and
        # functions as expected with caching globally enabled.
        cacheable_function = self._get_cacheable_function()

        self.config_fixture.config(group='cache', enabled=True)
        cacheable_function(self.test_value)
        cached_value = cacheable_function(self.test_value)
        self.assertTrue(cached_value.cached)

    def test_should_cache_fn_global_cache_disabled(self):
        # Verify should_cache_fn generates a sane function for subsystem and
        # functions as expected with caching globally disabled.
        cacheable_function = self._get_cacheable_function()

        self.config_fixture.config(group='cache', enabled=False)
        cacheable_function(self.test_value)
        cached_value = cacheable_function(self.test_value)
        self.assertFalse(cached_value.cached)

    def test_should_cache_fn_global_cache_disabled_group_cache_enabled(self):
        # Verify should_cache_fn generates a sane function for subsystem and
        # functions as expected with caching globally disabled and the specific
        # group caching enabled.
        cacheable_function = self._get_cacheable_function()

        self._add_test_caching_option()
        self.config_fixture.config(group='cache', enabled=False)
        self.config_fixture.config(group='cache', caching=True)

        cacheable_function(self.test_value)
        cached_value = cacheable_function(self.test_value)
        self.assertFalse(cached_value.cached)

    def test_should_cache_fn_global_cache_enabled_group_cache_disabled(self):
        # Verify should_cache_fn generates a sane function for subsystem and
        # functions as expected with caching globally enabled and the specific
        # group caching disabled.
        cacheable_function = self._get_cacheable_function()

        self._add_test_caching_option()
        self.config_fixture.config(group='cache', enabled=True)
        self.config_fixture.config(group='cache', caching=False)

        cacheable_function(self.test_value)
        cached_value = cacheable_function(self.test_value)
        self.assertFalse(cached_value.cached)

    def test_should_cache_fn_global_cache_enabled_group_cache_enabled(self):
        # Verify should_cache_fn generates a sane function for subsystem and
        # functions as expected with caching globally enabled and the specific
        # group caching enabled.
        cacheable_function = self._get_cacheable_function()

        self._add_test_caching_option()
        self.config_fixture.config(group='cache', enabled=True)
        self.config_fixture.config(group='cache', caching=True)

        cacheable_function(self.test_value)
        cached_value = cacheable_function(self.test_value)
        self.assertTrue(cached_value.cached)

    def test_cache_dictionary_config_builder(self):
        """Validate we build a sane dogpile.cache dictionary config."""
        self.config_fixture.config(group='cache',
                                   config_prefix='test_prefix',
                                   backend='oslo_cache.dict',
                                   expiration_time=86400,
                                   backend_argument=['arg1:test',
                                                     'arg2:test:test',
                                                     'arg3.invalid'])

        config_dict = cache._build_cache_config(self.config_fixture.conf)
        self.assertEqual(
            self.config_fixture.conf.cache.backend,
            config_dict['test_prefix.backend'])
        self.assertEqual(
            self.config_fixture.conf.cache.expiration_time,
            config_dict['test_prefix.expiration_time'])
        self.assertEqual('test', config_dict['test_prefix.arguments.arg1'])
        self.assertEqual('test:test',
                         config_dict['test_prefix.arguments.arg2'])
        self.assertNotIn('test_prefix.arguments.arg3', config_dict)

    def test_cache_dictionary_config_builder_global_disabled(self):
        """Validate the backend is reset to default if caching is disabled."""
        self.config_fixture.config(group='cache',
                                   enabled=False,
                                   config_prefix='test_prefix',
                                   backend='oslo_cache.dict')

        self.assertFalse(self.config_fixture.conf.cache.enabled)
        config_dict = cache._build_cache_config(self.config_fixture.conf)
        self.assertEqual(
            _opts._DEFAULT_BACKEND,
            config_dict['test_prefix.backend'])

    def test_cache_dictionary_config_builder_tls_disabled(self):
        """Validate the backend is reset to default if caching is disabled."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   tls_cafile='path_to_ca_file',
                                   tls_keyfile='path_to_key_file',
                                   tls_certfile='path_to_cert_file',
                                   tls_allowed_ciphers='allowed_ciphers')

        with mock.patch.object(ssl, 'create_default_context'):
            config_dict = cache._build_cache_config(self.config_fixture.conf)

            self.assertFalse(self.config_fixture.conf.cache.tls_enabled)
            ssl.create_default_context.assert_not_called()
            self.assertNotIn('test_prefix.arguments.tls_context', config_dict)

    def test_cache_dictionary_config_builder_tls_enabled(self):
        """Validate the backend is reset to default if caching is disabled."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   tls_enabled=True)

        fake_context = mock.Mock()
        with mock.patch.object(ssl, 'create_default_context',
                               return_value=fake_context):
            config_dict = cache._build_cache_config(self.config_fixture.conf)

            self.assertTrue(self.config_fixture.conf.cache.tls_enabled)

            ssl.create_default_context.assert_called_with(cafile=None)
            fake_context.load_cert_chain.assert_not_called()
            fake_context.set_ciphers.assert_not_called()

            self.assertEqual(
                fake_context,
                config_dict['test_prefix.arguments.tls_context'],
            )

    def test_cache_dictionary_config_builder_tls_enabled_with_config(self):
        """Validate the backend is reset to default if caching is disabled."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   tls_enabled=True,
                                   tls_cafile='path_to_ca_file',
                                   tls_keyfile='path_to_key_file',
                                   tls_certfile='path_to_cert_file',
                                   tls_allowed_ciphers='allowed_ciphers')

        fake_context = mock.Mock()
        with mock.patch.object(ssl, 'create_default_context',
                               return_value=fake_context):
            config_dict = cache._build_cache_config(self.config_fixture.conf)

            self.assertTrue(self.config_fixture.conf.cache.tls_enabled)

            ssl.create_default_context.assert_called_with(
                cafile='path_to_ca_file',
            )
            fake_context.load_cert_chain.assert_called_with(
                'path_to_cert_file',
                'path_to_key_file',
            )
            fake_context.set_ciphers.assert_called_with(
                'allowed_ciphers'
            )

            self.assertEqual(
                fake_context,
                config_dict['test_prefix.arguments.tls_context'],
            )

    def test_cache_pymemcache_socket_kalive_enabled_with_wrong_backend(self):
        """Validate we build a config without the retry option when retry
        is disabled.
        """
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='oslo_cache.dict',
                                   enable_socket_keepalive=True)

        self.assertRaises(
            exception.ConfigurationError,
            cache._build_cache_config,
            self.config_fixture.conf
        )

    def test_cache_pymemcache_socket_keepalive_disabled(self):
        """Validate we build a dogpile.cache dict config without keepalive."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   socket_keepalive_idle=2,
                                   socket_keepalive_interval=2,
                                   socket_keepalive_count=2)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertFalse(
            self.config_fixture.conf.cache.enable_socket_keepalive)
        self.assertNotIn(
            'test_prefix.arguments.socket_keepalive', config_dict)

    def test_cache_pymemcache_socket_keepalive_enabled(self):
        """Validate we build a dogpile.cache dict config with keepalive."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   enable_socket_keepalive=True)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertTrue(
            self.config_fixture.conf.cache.enable_socket_keepalive)

        self.assertIsInstance(
            config_dict['test_prefix.arguments.socket_keepalive'],
            KeepaliveOpts
        )

    def test_cache_pymemcache_socket_keepalive_with_config(self):
        """Validate we build a socket keepalive with the right config."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   enable_socket_keepalive=True,
                                   socket_keepalive_idle=12,
                                   socket_keepalive_interval=38,
                                   socket_keepalive_count=42)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertTrue(
            self.config_fixture.conf.cache.enable_socket_keepalive)

        self.assertTrue(
            config_dict['test_prefix.arguments.socket_keepalive'],
            KeepaliveOpts
        )
        self.assertEqual(
            12,
            config_dict['test_prefix.arguments.socket_keepalive'].idle
        )
        self.assertEqual(
            38,
            config_dict['test_prefix.arguments.socket_keepalive'].intvl
        )
        self.assertEqual(
            42,
            config_dict['test_prefix.arguments.socket_keepalive'].cnt
        )

    def test_cache_pymemcache_retry_enabled_with_wrong_backend(self):
        """Validate we build a config without the retry option when retry
        is disabled.
        """
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='oslo_cache.dict',
                                   enable_retry_client=True,
                                   retry_attempts=2,
                                   retry_delay=2)

        self.assertRaises(
            exception.ConfigurationError,
            cache._build_cache_config,
            self.config_fixture.conf
        )

    def test_cache_pymemcache_retry_disabled(self):
        """Validate we build a config without the retry option when retry
        is disabled.
        """
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   retry_attempts=2,
                                   retry_delay=2)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        opts = ['enable_retry_client', 'retry_attempts', 'retry_delay']

        for el in opts:
            self.assertNotIn('test_prefix.arguments.{}'.format(el),
                             config_dict)

    def test_cache_pymemcache_retry_enabled(self):
        """Validate we build a dogpile.cache dict config with retry."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   enable_retry_client=True)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        opts = ['enable_retry_client', 'retry_attempts', 'retry_delay']

        for el in opts:
            self.assertIn('test_prefix.arguments.{}'.format(el), config_dict)

    def test_cache_pymemcache_retry_with_opts(self):
        """Validate we build a valid config for the retry client."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   enable_retry_client=True,
                                   retry_attempts=42,
                                   retry_delay=42)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertTrue(
            self.config_fixture.conf.cache.enable_retry_client)

        self.assertEqual(
            config_dict['test_prefix.arguments.retry_attempts'],
            42
        )

        self.assertEqual(
            config_dict['test_prefix.arguments.retry_delay'],
            42
        )

    def test_cache_pymemcache_retry_with_extra_opts(self):
        """Validate we build a valid config for the retry client."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='dogpile.cache.pymemcache',
                                   enable_retry_client=True,
                                   retry_attempts=42,
                                   retry_delay=42,
                                   hashclient_retry_attempts=100,
                                   hashclient_retry_delay=100,
                                   dead_timeout=100)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertTrue(
            self.config_fixture.conf.cache.enable_retry_client)

        self.assertEqual(
            config_dict['test_prefix.arguments.retry_attempts'],
            42
        )

        self.assertEqual(
            config_dict['test_prefix.arguments.retry_delay'],
            42
        )

        self.assertEqual(
            config_dict['test_prefix.arguments.hashclient_retry_attempts'],
            100
        )

        self.assertEqual(
            config_dict['test_prefix.arguments.hashclient_retry_delay'],
            100
        )

        self.assertEqual(
            config_dict['test_prefix.arguments.dead_timeout'],
            100
        )

    def test_cache_dictionary_config_builder_flush_on_reconnect_enabled(self):
        """Validate we build a sane dogpile.cache dictionary config."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='oslo_cache.dict',
                                   memcache_pool_flush_on_reconnect=True)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertTrue(self.config_fixture.conf.cache.
                        memcache_pool_flush_on_reconnect)
        self.assertTrue(config_dict['test_prefix.arguments'
                                    '.pool_flush_on_reconnect'])

    def test_cache_dictionary_config_builder_flush_on_reconnect_disabled(self):
        """Validate we build a sane dogpile.cache dictionary config."""
        self.config_fixture.config(group='cache',
                                   enabled=True,
                                   config_prefix='test_prefix',
                                   backend='oslo_cache.dict',
                                   memcache_pool_flush_on_reconnect=False)

        config_dict = cache._build_cache_config(self.config_fixture.conf)

        self.assertFalse(self.config_fixture.conf.cache.
                         memcache_pool_flush_on_reconnect)
        self.assertFalse(config_dict['test_prefix.arguments'
                                     '.pool_flush_on_reconnect'])

    def test_cache_debug_proxy(self):
        single_value = 'Test Value'
        single_key = 'testkey'
        multi_values = {'key1': 1, 'key2': 2, 'key3': 3}

        self.region.set(single_key, single_value)
        self.assertEqual(single_value, self.region.get(single_key))

        self.region.delete(single_key)
        self.assertEqual(NO_VALUE, self.region.get(single_key))

        self.region.set_multi(multi_values)
        cached_values = self.region.get_multi(multi_values.keys())
        for value in multi_values.values():
            self.assertIn(value, cached_values)
        self.assertEqual(len(multi_values.values()), len(cached_values))

        self.region.delete_multi(multi_values.keys())
        for value in self.region.get_multi(multi_values.keys()):
            self.assertEqual(NO_VALUE, value)

    def test_configure_non_region_object_raises_error(self):
        self.assertRaises(exception.ConfigurationError,
                          cache.configure_cache_region,
                          self.config_fixture.conf,
                          "bogus")

    def test_kwarg_function_key_generator_no_kwargs(self):
        cacheable_function = self._get_cacheable_function(
            region=self.region_kwargs)

        self.config_fixture.config(group='cache', enabled=True)
        cacheable_function(self.test_value)
        cached_value = cacheable_function(self.test_value)
        self.assertTrue(cached_value.cached)

    def test_kwarg_function_key_generator_with_kwargs(self):
        cacheable_function = self._get_cacheable_function(
            region=self.region_kwargs)

        self.config_fixture.config(group='cache', enabled=True)
        cacheable_function(value=self.test_value)
        cached_value = cacheable_function(value=self.test_value)
        self.assertTrue(cached_value.cached)

class UTF8KeyManglerTests(test_cache.BaseTestCase):

    def test_key_is_utf8_encoded(self):
        key = 'fäké1'
        encoded = cache._sha1_mangle_key(key)
        self.assertIsNotNone(encoded)

    def test_key_is_bytestring(self):
        key = b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'
        encoded = cache._sha1_mangle_key(key)
        self.assertIsNotNone(encoded)

    def test_key_is_string(self):
        key = 'fake'
        encoded = cache._sha1_mangle_key(key)
        self.assertIsNotNone(encoded)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ModuleManager">
    <modules>
      <module name="MustBe.Consulo.Attributes" dirurl="file://$PROJECT_DIR$" current-layer="microsoft">
        <module-layer name="microsoft">
          <extension id="microsoft-csharp" unsafe-code="false" optimize-code="false" platform="ANY_CPU" language-version-module-name="" language-version-name="" />
          <extension id="microsoft-dotnet" sdk-module-name="" sdk-name="Microsoft .NET 2.0" target="LIBRARY" debug="true" allow-source-roots="false" file-name="$ModuleName$.$TargetFileExt$" output-dir="$ModuleProductionOutputDirPath$/ms" namespace-prefix="MustBe.Consulo.Attributes" />
          <content url="file://$MODULE_DIR$" />
          <orderEntry type="dot-net-library" name="mscorlib" />
          <orderEntry type="sourceFolder" />
        </module-layer>
        <module-layer name="mono">
          <extension id="mono-csharp" unsafe-code="false" optimize-code="false" platform="ANY_CPU" language-version-module-name="" language-version-name="" />
          <extension id="mono-dotnet" sdk-module-name="" sdk-name="Mono .NET 2.0" target="LIBRARY" debug="true" allow-source-roots="false" file-name="$ModuleName$.$TargetFileExt$" output-dir="$ModuleProductionOutputDirPath$/mono" namespace-prefix="MustBe.Consulo.Attributes" />
          <content url="file://$MODULE_DIR$" />
          <orderEntry type="dot-net-library" name="mscorlib" />
          <orderEntry type="sourceFolder" />
        </module-layer>
      </module>
    </modules>
  </component>
</project>


text:
<?php
require_once '../../server/connection.php';
include('../../server/pagination.php');

class Results {

	function __construct(){
    }

    public function getPassers($year){
		$config= new Config();
		$mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db);
		if ($mysqli->connect_errno) {
		    print json_encode(array('success' =>false,'msg' =>"Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error));
		    return;
		}else{
			$data = array();
			$query ="SELECT S.* ,(SELECT IFNULL(SUM(score),0) FROM result WHERE stud_id=S.studid) AS TotalScore FROM student S;";
			$result = $mysqli->query($query);
			while($row = $result->fetch_array(MYSQLI_ASSOC)){
				$studid = $row['studid'];

				$query1 ="SELECT S.studid,C.id as course_id,C.coursecode FROM student S, courses C
					WHERE (SELECT SUM(score) FROM result WHERE stud_id=S.studid) >= C.passing_score
					AND S.studid=(SELECT DISTINCT r.stud_id FROM result r WHERE YEAR(r.date) = '$year' AND r.stud_id = '$studid');";

				$result1 = $mysqli->query($query1);
				$data1 = array();
				while($row1 = $result1->fetch_array(MYSQLI_ASSOC)){
					array_push($data1,$row1);
				}
				$row['suggest_course'] = $data1;
				array_push($data,$row);
			}

			print json_encode(['success' =>true,'passers' =>$data],JSON_PRETTY_PRINT);
		}
	}

	public function getPassersByCourse($id,$year){
		$config= new Config();
		$mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db);
		if ($mysqli->connect_errno) {
		    print json_encode(array('success' =>false,'msg' =>"Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error));
		    return;
		}else{
			$query ="SELECT * FROM (SELECT S.* , C.id as course_id,C.coursecode,(SELECT IFNULL(SUM(score),0) FROM result WHERE stud_id=S.studid) AS TotalScore
				FROM student S, courses C WHERE (SELECT SUM(score) FROM result WHERE stud_id=S.studid) >= C.passing_score
				AND S.pref_course=$id) AS A WHERE A.studid IN (SELECT DISTINCT r.stud_id FROM result r WHERE YEAR(r.date) = '$year');";

			$result = $mysqli->query($query);
			$data = array();
			while($row = $result->fetch_array(MYSQLI_ASSOC)){
				array_push($data,$row);
			}
			print json_encode(['success' =>true,'passers' =>$data],JSON_PRETTY_PRINT);
		}
	}

	public function getResultsSummary($student_id){
		$config= new Config();
		$mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db);
		if ($mysqli->connect_errno) {
		    print json_encode(array('success' =>false,'msg' =>"Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error));
		    return;
		}else{

			$data = array();
			$data2 = array();

			$query ="SELECT DISTINCT s.category_id,(SELECT name FROM category WHERE id=s.category_id LIMIT 1) as category_name FROM status s WHERE s.stud_id = '$student_id' ORDER BY s.id;";
			$result = $mysqli->query($query);
			while($row = $result->fetch_array(MYSQLI_ASSOC)){
				$category_id = $row['category_id'];

				$query1 ="SELECT s.*,(SELECT content FROM question WHERE id = s.question_id LIMIT 1) AS questions,
    			(SELECT answer FROM choice WHERE id = s.choice_id LIMIT 1) AS yourchoice,
    			(SELECT answer FROM choice WHERE questionid = s.question_id AND choice = 'yes' LIMIT 1) AS correctans,
    			(SELECT id FROM choice WHERE questionid = s.question_id AND choice = 'yes' LIMIT 1) AS correctans_id
				FROM status s WHERE s.stud_id = '$student_id' AND s.category_id = $category_id ORDER BY s.id;";

				$result1 = $mysqli->query($query1);
				$data1 = array();
				while($row1 = $result1->fetch_array(MYSQLI_ASSOC)){
					if($row1['choice_id'] === $row1['correctans_id']){
						$row1['isCorrect'] = true;
					}else{
						$row1['isCorrect'] = false;
					}
					array_push($data1,$row1);
				}
				$row['quiz'] = $data1;
				array_push($data,$row);
			}

			$query2 ="SELECT c.*, (SELECT r.score FROM result r WHERE r.category_id=c.id AND r.stud_id='$student_id' LIMIT 1) AS score,(SELECT r.total FROM result r WHERE r.category_id=c.id AND r.stud_id='$student_id' LIMIT 1) AS total FROM category c;";
			$result2 = $mysqli->query($query2);
			while($row = $result2->fetch_array(MYSQLI_ASSOC)){
				array_push($data2,$row);
			}

			print json_encode(['success' =>true,'data' =>$data,'summary'=>$data2],JSON_PRETTY_PRINT);
		}
	}

	public function getResultsYear(){
		$config= new Config();
		$mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db);
		if ($mysqli->connect_errno) {
		    print json_encode(array('success' =>false,'msg' =>"Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error));
		    return;
		}else{
			$query ="SELECT DISTINCT YEAR(r.date) as cYear FROM entrance.result r;";
			$result = $mysqli->query($query);
			$data = array();
			while($row = $result->fetch_array(MYSQLI_ASSOC)){
				array_push($data,$row);
			}
			print json_encode(['success' =>true,'results_year' =>$data],JSON_PRETTY_PRINT);
		}
	}

}


text:
package riotapi.match;

public class Player {
    private String matchHistoryUri;
    private int profileIcon;
    private long summonerId;
    private String summonerName;

    public String get_matchHistoryUri() {
        return matchHistoryUri;
    }

    public void set_matchHistoryUri(String matchHistoryUri) {
        this.matchHistoryUri = matchHistoryUri;
    }

    public int get_profileIcon() {
        return profileIcon;
    }

    public void set_profileIcon(int profileIcon) {
        this.profileIcon = profileIcon;
    }

    public long get_summonerId() {
        return summonerId;
    }

    public void set_summonerId(long summonerId) {
        this.summonerId = summonerId;
    }

    public String get_summonerName() {
        return summonerName;
    }

    public void set_summonerName(String summonerName) {
        this.summonerName = summonerName;
    }
}


text:
table.front-end-list{
    width: 100%;
    border-spacing: 1px;
    background-color: #f3f3f3;
    color: #666;
}

table.front-end-list thead th{
    text-align: center;
    background: #f7f7f7;
    color: #666;
    border-bottom: 1px solid #ccc;
    border-left: 1px solid #fff;
}

table.front-end-list td, table.front-end-list th{
    padding: 4px;
}

table.front-end-list thead th.align-left{
    text-align: left;
}

table.front-end-list thead th.align-center, table.front-end-list tbody td.align-center {
    text-align: center;
}

table.front-end-list tbody tr td{
    background: #fff;
    border: 1px solid #fff;
}

table.front-end-list td{
    padding-left: 8px;
}

div.list-footer{
    clear:both;
    text-decoration: none;
    text-align: center;
}

div.list-footer ul{
    list-style: none;
    display: inline-block;
}

div.list-footer ul li{
    display: inline-block;
}

div.list-footer div.limit{
    display: inline-block;
}

div.list-footer div.counter{
    display: inline-block;
}

div.filter-select.hide{
    display: none;
}

div.filter-select.show{
    display: block;
}

div.filter-search , div.filter-select {
    float: left;
    clear: both;
}

div.filter-select .fltlft{
    float: left;
    clear: both;
}

div.field-filter{
    float: left;
    margin: 10px;
}

#filter-bar div.fltrt div.button2-left .blank a {
    margin-top: 0 !important;
}

button.open{
    font-weight: bold;
}

div.field-filter:first-of-type{
    margin-left: 0;
}


text:
package org.apache.poi.xssf.usermodel;

/**
 * An anchor is what specifics the position of a shape within a client object
 * or within another containing shape.
 *
 * @author Yegor Kozlov
 */
public abstract class XSSFAnchor {

    public abstract int getDx1();
    public abstract void setDx1( int dx1 );
    public abstract int getDy1();
    public abstract void setDy1( int dy1 );
    public abstract int getDy2();
    public abstract void setDy2( int dy2 );
    public abstract int getDx2();
    public abstract void setDx2( int dx2 );

}


text:
<?php

namespace GoIntegro\Hateoas\JsonApi\Request;

class RequestAction
{
    const ACTION_FETCH = 'fetch',
        ACTION_CREATE = 'create',
        ACTION_UPDATE = 'update',
        ACTION_DELETE = 'delete';

    const TYPE_SINGLE = 'single',
        TYPE_MULTIPLE = 'multiple';

    const TARGET_RESOURCE = 'resource',
        TARGET_RELATIONSHIP = 'relationship';

    /**
     * @var string The kind of action; C-F-U-D.
     */
    public $name;
    /**
     * @var string Whether we want an individual or collection representation.
     * @see http://jsonapi.org/format/#document-structure-resource-representations
     */
    public $type;
    /**
     * @var string Whether we're acting upon the resource or its relationships.
     */
    public $target;
}


text:
<?php

namespace RTLer\Oauth2\Providers;

use Illuminate\Support\ServiceProvider;
use RTLer\Oauth2\Oauth2Server;

class Oauth2ServiceProvider extends ServiceProvider
{
    protected $options;

    public function __construct($app)
    {
        if (method_exists($app, 'configure')) {
            // @codeCoverageIgnoreStart
            $app->configure('oauth2');
            // @codeCoverageIgnoreEnd
        }

        $this->options = $app->make('config')->get('oauth2');

        parent::__construct($app);
    }

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../publish/config/oauth2.php' => base_path('config/oauth2.php'),
        ]);
        $this->publishes([
            __DIR__.'/../publish/Oauth2/UserVerifier.php' => base_path('app/Oauth2/UserVerifier.php'),
        ]);
        $this->publishes([
            __DIR__.'/../publish/migrations/2016_05_30_155444_CreateOauth2Tables.php' => base_path('database/migrations/2016_05_30_155444_CreateOauth2Tables.php'),
        ]);

        $this->commands([
            \RTLer\Oauth2\Commands\PersonalAccessClientCommand::class,
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Oauth2Server::class, function () {
            return new Oauth2Server($this->options);
        });
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Dashboard Login</title>

Sign in

        <form action="" method="POST">

            Username
            <input type="text" name="username" id="username">

            Password
            <input type="password" name="password" id="password">
            Failed communicating with the GSA.

          <input type="submit" class="g-button g-button-submit" value="Sign in">
        </form>

Dashboard

You must login to continue to the
        Dashboard. Please login with the administrator username and password
        used for your GSA.


text:
/**
 * This package contains interfaces for integration.
 *

 * It contains the {@link javax.cache.integration.CacheLoader} and
 * {@link javax.cache.integration.CacheWriter} interfaces that
 * allow loading from and writing to other systems respectively.
 *

 * A cache with a registered loader can be configured as a read-through cache, so
 * that access will automatically load missing entries. And similarly a cache
 * with a registered writer can be configured
 * as a write-through cache, so that changes are written through to an underlying
 * system.
 *

 * In addition a common idiom is to use a loader to initially
 * populate or refresh a cache. For that purpose there is the
 * {@link javax.cache.Cache#loadAll(java.util.Set, boolean, CompletionListener)}
 * method.
 *
 * @author Greg Luck
 * @since 1.0
 */
package javax.cache.integration;


text:
'use strict';

var app = require('../server/app');

// start sockets for this instance and start server
app.startServer().listen(app.get('port'), app.get('ip'), function serverStarted() {
  console.log('vendorApp started server on ip %s on port %d, in %s mode',
    app.get('ip'), app.get('port'), app.get('env'));
});

// expose app
exports = module.exports = app;


text:
namespace hoTools.EaServices.AddInSearch
{
    /// <summary>
    /// Tagged Values.
    /// </summary>
    public class Tv
    {
        public string Property;
        public string Value;
        public Tv(string property, string value)
        {
            Property = property;
            Value = value;
        }
    }
}


text:
ShadowMapPass::ShadowMapPass(uint32_t shadowMapResolution)
    : RenderPass("ShadowMapPass"), m_resolution(shadowMapResolution)
{
    for (int i = 0; i < MAX_DIR_LIGHT_COUNT; ++i)
    {
        m_framebuffers[i] = std::make_unique<Framebuffer>(shadowMapResolution, shadowMapResolution, false, GL_FLOAT, true);
        m_framebuffers[i]->bind();

        m_framebuffers[i]->checkFramebufferStatus();
        m_framebuffers[i]->unbind();
    }

    GL_ERROR_CHECK();

    m_fullscreenQuadRenderer = MeshRenderers::fullscreenQuad();
    m_quadShader = ResourceManager::getShader("shaders/simple/fullscreenQuad.vert", "shaders/simple/fullscreenQuad.frag", {"in_pos"});
    m_shader = ResourceManager::getShader("shaders/shadows/shadowMap.vert", "shaders/shadows/shadowMap.frag", {"in_pos"});
}

void ShadowMapPass::update()
{
    int lightCount = 0;
    for (auto dirLight : ECS::getEntitiesWithComponents<DirectionalLight, Transform>())
    {
        if (lightCount == MAX_DIR_LIGHT_COUNT)
            break;

        auto dirLightTransform = dirLight.getComponent<Transform>();
        auto dirLightComponent = dirLight.getComponent<DirectionalLight>();

        if (!dirLightComponent->shadowsEnabled)
        {
            lightCount++;
            continue;
        }

        m_framebuffers[lightCount]->bind();
        glDisable(GL_SCISSOR_TEST);

        glm::vec3 lightDir = dirLightTransform->getForward();
        glm::vec3 lightPos = dirLightTransform->getPosition();

        glm::vec3 up = glm::vec3(0.f, 1.f, 0.f);
        if (math::nearEq(std::abs(glm::dot(lightDir, up)), 1.0f))
            up = glm::vec3(0.0f, 0.0f, 1.0f);

        glm::mat4 view = glm::lookAt(lightPos, lightPos + lightDir, up);

        GL::setViewport(Rect(0.f, 0.f, static_cast<float>(m_resolution), static_cast<float>(m_resolution)));

        float hw = m_projectionSize.x * 0.5f;
        float hh = m_projectionSize.y * 0.5f;
        glm::mat4 proj = math::orthoLH(-hw, hw, -hh, hh, dirLightComponent->zNear, dirLightComponent->zFar);

        dirLightComponent->view = view;
        dirLightComponent->proj = proj;

        render(view, proj);

        dirLightComponent->shadowMap = getDepthTexture(lightCount);

        m_framebuffers[lightCount]->unbind();

        lightCount++;
    }

    GL::setViewport(Rect(0.0f, 0.0f, static_cast<float>(Screen::getWidth()), static_cast<float>(Screen::getHeight())));
}

void ShadowMapPass::render(glm::mat4 view, glm::mat4 proj) const
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    m_shader->bind();
    m_shader->setMatrix("u_view", view);
    m_shader->setMatrix("u_proj", proj);

    ECSUtil::renderEntities(m_shader.get());
}


text:
===========
Version 3.3
===========

Version 3.3 of mod_wsgi can be obtained from:

  http://modwsgi.googlecode.com/files/mod_wsgi-3.3.tar.gz

Bug Fixes
---------

1. Inactivity timeout not triggered at correct time when occurs for first
request after process is started. See

  http://code.google.com/p/modwsgi/issues/detail?id=182

2. Back off timer for failed connections to daemon process group wasn't
working correctly and no delay on reconnect attempts was being applied. See:

  http://code.google.com/p/modwsgi/issues/detail?id=195

3. Logging not appearing in Apache error log files when using daemon mode
and have multiple virtual hosts against same server name. See:

  http://code.google.com/p/modwsgi/issues/detail?id=204

4. Eliminate logging of !KeyError exception in threading module when processes
are shutdown when using Python 2.6.5 or 3.1.2 or later. This wasn't indicating
any real problem but was annoying all the same. See:

  http://code.google.com/p/modwsgi/issues/detail?id=197

5. Fix potential for crash when logging error message resulting from failed
group authorisation.

6. Fix compilation problems with Apache 2.3.6.

Features Changed
----------------

1. When compiled against ITK MPM for Apache, if using daemon mode, the
listener socket for daemon process will be marked as being owned by the
same user that daemon process runs. This will at least allow a request
handled under ITK MPM to be directed to daemon process owned by same user
as script. See issue:

  http://code.google.com/p/modwsgi/issues/detail?id=187

2. Add isatty() to log objects used for sys.stdout/sys.stderr and
wsgi.errors. The Python documentation says 'If a file-like object is not
associated with a real file, this method should not be implemented'. That
however is ambiguous as to whether one can omit it, or whether one should
raise an NotImplementedError exception. Either way, various code doesn't
cope with isatty() not existing or failing, so implement it and have it
return False to be safe.


text:
require 'spec_helper'
require "xml_schema_mapper/test_builder"

  # @attr requisitesPaperCertificate [RequisitesPaperCertificate]
  # @attr certificateAdoption [ActRecordToCertificateAdoption]

describe CertificateAdoptionMapper do

  include XmlSchemaMapper::TestBuilder::Helper

  subject { build_described_mapper }

  it "should be self-compatible xml <-> object" do
    described_class.parse(subject.to_xml).to_xml.should eql subject.to_xml
  end

end


text:
from django.db import connection

from common import BaseEvolutionOperations

class EvolutionOperations(BaseEvolutionOperations):
    def rename_column(self, opts, old_field, new_field):
        if old_field.column == new_field.column:
            # No Operation
            return []

        qn = connection.ops.quote_name
        params = (qn(opts.db_table), qn(old_field.column), qn(new_field.column))
        return ['ALTER TABLE %s RENAME COLUMN %s TO %s;' % params]


text:
//
//  AMPObject.h
//  AMPluginFramework
//
//  Created by Joe on 19/11/13.
//  Copyright (c) 2013 Bloop. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AMPObject : NSObject
{

}
/**
 *  The Airmail object. is the base object used to create the AMP models
 *
 *  @return the AM object
 */
- (id) object;
- (id) initWithObject:(NSObject*)obj;

/**
 *  Simple method to call selectors on the AM object
 *
 *  @param selector the AM selector
 *  @param object   the AM object
 *
 *  @return an id with the populated property
 */
- (id) callSelector:(SEL)selector;
- (id) callSelector:(SEL)selector obj:(id)object;
- (id) callSelector:(SEL)selector obj:(id)object obj:(id)object2;

@end


text:
import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.image_operations as img_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.zstack_test.zstack_test_image as zstack_image_header

image1 = None
image2 = None
disconnect = False
host = None

def test():
    global disconnect, host, image1, image2
    # query&get clusters
    cond = res_ops.gen_query_conditions('name', '=', "cluster1")
    cluster1 = res_ops.query_resource(res_ops.CLUSTER, cond)[0]

    cond = res_ops.gen_query_conditions('name', '=', "cluster2")
    cluster2 = res_ops.query_resource(res_ops.CLUSTER, cond)[0]

    # query&get hosts
    cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster1.uuid)
    cluster1_host = res_ops.query_resource(res_ops.HOST, cond)

    cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster2.uuid)
    cluster2_host = res_ops.query_resource(res_ops.HOST, cond)

    # query bs
    bss = res_ops.query_resource(res_ops.BACKUP_STORAGE)

    # disconnect mn_host1
    host = cluster1_host[0]
    host_ops.update_kvm_host(host.uuid, 'username', "root1")
    try:
        host_ops.reconnect_host(host.uuid)
    except:
        test_util.test_logger("host: [%s] is disconnected" % host.uuid)
    disconnect = True

    url = "http://172.20.1.22/mirror/diskimages/zstack_image_test3.qcow2"

    # add image to bs1
    img_option = test_util.ImageOption()
    img_option.set_name("bs1_image")
    img_option.set_url(url)
    img_option.set_format('qcow2')
    img_option.set_mediaType = 'RootVolumeTemplate'

    img_option.set_backup_storage_uuid_list([bss[0].uuid])
    image_inv = img_ops.add_root_volume_template(img_option)
    image1 = zstack_image_header.ZstackTestImage()
    image1.set_image(image_inv)

    # add image to bs2
    img_option.set_name("bs2_image")
    img_option.set_backup_storage_uuid_list([bss[0].uuid])
    image_inv = img_ops.add_root_volume_template(img_option)
    image2 = zstack_image_header.ZstackTestImage()
    image2.set_image(image_inv)

    image1.clean()
    image2.clean()

    host_ops.update_kvm_host(host.uuid, 'username', "root")
    host_ops.reconnect_host(host.uuid)

def error_cleanup():
    global host, disconnect, image1, image2
    if disconnect:
        host_ops.update_kvm_host(host.uuid, 'username', "root")
        host_ops.reconnect_host(host.uuid)
        disconnect = False

    if image1:
        image1.clean()

    if image2:
        image2.clean()

def env_recover():
    global host, disconnect, image1, image2
    if disconnect:
        host_ops.update_kvm_host(host.uuid, 'username', "root")
        host_ops.reconnect_host(host.uuid)
        disconnect = False

    if image1:
        image1.clean()

    if image2:
        image2.clean()


text:
require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest
	test "invalid signup information" do
		get signup_path
		before_count = User.count
		assert_no_difference 'User.count' do
			post users_path, user: { name: "",
															 email: "user@invalid",
															 password:                "foo",
															 password_confirmation:   "bar" }
		end
		assert_template 'users/new'
	end

	test "valid signup information" do
	  get signup_path
	  assert_difference 'User.count', 1 do
	    post_via_redirect users_path, user: { name:  "Example User",
	                                          email: "user@example.com",
	                                          password:              "password",
	                                          password_confirmation: "password" }
	  end
	  assert_template 'users/show'
	  assert is_logged_in?
	end
end


text:
class Foo(x: Int)

object Test {
  val res0 = new Foo("Hello") // error
}


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Xml.Linq;
using Goodreads.Extensions;

namespace Goodreads.Models.Response
{
    /// <summary>
    /// Represents a compare books as defined by the Goodreads API.
    /// </summary>
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public sealed class CompareBooksResult : ApiResponse
    {
        /// <summary>
        /// Count of books are not a common.
        /// </summary>
        public int NotInCommon { get; private set; }

        /// <summary>
        /// Your libary compare percent.
        /// </summary>
        public decimal YourLibraryPercent { get; private set; }

        /// <summary>
        /// Their libary compare percent.
        /// </summary>
        public decimal TheirLibraryPercent { get; private set; }

        /// <summary>
        /// Your total books count.
        /// </summary>
        public int YourTotalBooksCount { get; private set; }

        /// <summary>
        /// Their total books count.
        /// </summary>
        public int TheirTotalBooksCount { get; private set; }

        /// <summary>
        /// Count of common books.
        /// </summary>
        public int CommonCount { get; private set; }

        /// <summary>
        /// Compare reviews.
        /// </summary>
        public IReadOnlyList<CompareBookReview> Reviews { get; private set; }

        internal string DebuggerDisplay
        {
            get
            {
                return string.Format(
                    CultureInfo.InvariantCulture,
                    "Common: {0}. Not In common: {1}",
                    CommonCount,
                    NotInCommon);
            }
        }

        internal override void Parse(XElement element)
        {
            NotInCommon = element.ElementAsInt("not_in_common");
            YourLibraryPercent = element.ElementAsDecimal("your_library_percent");
            TheirLibraryPercent = element.ElementAsDecimal("their_library_percent");
            YourTotalBooksCount = element.ElementAsInt("your_total_books_count");
            TheirTotalBooksCount = element.ElementAsInt("their_total_books_count");
            CommonCount = element.ElementAsInt("common_count");

            var reviews = element.Element("reviews");
            if (reviews != null)
            {
                var list = new PaginatedList<CompareBookReview>();
                list.Parse(reviews);
                Reviews = list.List;
            }
        }
    }
}


text:
<?xml version="1.0"?>
<option name="disabled" default="false" example-value="true">
	<desc>
		Disables the <placeholder name="name"/> if set to true.

This option is also exposed as a data attribute: data-disabled="true".

	</desc>
	<type name="Boolean" />
</option>


text:
var Jueguin = Jueguin || {};

Jueguin.BootState = {
    init: function() {
    	this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
	    this.scale.pageAlignHorizontally = true;
	    this.scale.pageAlignVertically = true;
    },

    // preload: function() {
    // },

    create: function() {
    	this.state.start('Preload');
    }
};


text:
name             'nginx_test'
maintainer       'TangoGroup'
maintainer_email 'cookbooks@tangogroup.com'
license          'Apache 2.0'
description      'Installs/Configures nginx_test'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.1.0'


text:
var Packet = require('./packet');

function PacketHandler(gameServer, socket) {
    this.gameServer = gameServer;
    this.socket = socket;
    // todo Detect protocol version - we can do something about it later
    this.protocol = 0;

    this.pressQ = false;
    this.pressW = false;
    this.pressSpace = false;
	this.pressZ = false;
}

module.exports = PacketHandler;

PacketHandler.prototype.handleMessage = function(message) {
    function stobuf(buf) {
        var length = buf.length;
        var arrayBuf = new ArrayBuffer(length);
        var view = new Uint8Array(arrayBuf);

        for (var i = 0; i < length; i++) {
            view[i] = buf[i];
        }

        return view.buffer;
    }

    // Discard empty messages
    if (message.length == 0) {
        return;
    }

    var buffer = stobuf(message);
    var view = new DataView(buffer);
    var packetId = view.getUint8(0, true);

    switch (packetId) {
        case 0:
            // Set Nickname
            var nick = "";
            var maxLen = this.gameServer.config.playerMaxNickLength * 2; // 2 bytes per char
            for (var i = 1; i < view.byteLength && i <= maxLen; i += 2) {
                var charCode = view.getUint16(i, true);
                if (charCode == 0) {
                    break;
                }
                nick += String.fromCharCode(charCode);
            }
            this.setNickname(nick);
            break;
        case 1:
            // Spectate mode
            if (this.socket.playerTracker.cells.length <= 0) {
                // Make sure client has no cells
                this.gameServer.switchSpectator(this.socket.playerTracker);
                this.socket.playerTracker.spectate = true;
            }
            break;
        case 16:
			var client = this.socket.playerTracker;
            if (view.byteLength == 13) {
                client.mouse.x = view.getInt32(1, true) - client.scrambleX;
                client.mouse.y = view.getInt32(5, true) - client.scrambleX;
            } else if (view.byteLength == 9) {
                client.mouse.x = view.getInt16(1, true) - client.scrambleX;
                client.mouse.y = view.getInt16(3, true) - client.scrambleX;
            } else if (view.byteLength == 21) {
                client.mouse.x = view.getFloat64(1, true) - client.scrambleX;
                client.mouse.y = view.getFloat64(9, true) - client.scrambleX;
            }

            client.movePacketTriggered = true;
            break;
        case 17:
            // Space Press - Split cell
            this.pressSpace = true;
            break;
		case 113:
            // Z Press - CannonSplit
            this.pressZ = true;
            break;
        case 18:
            // Q Key Pressed
            this.pressQ = true;
            break;
        case 19:
            // Q Key Released
			this.pressQ = false;
            break;
		case 20:
            // W Key Released
			this.pressW = false;
            break;
        case 21:
            // W Press - Eject mass
            this.pressW = true;
            break;
        case 255:
            // Connection Start
            if (view.byteLength == 5) {
                var c = this.gameServer.config,
                		player = 0,
                		client;
                for (var i = 0; i < this.gameServer.clients.length; i++) {
                    client = this.gameServer.clients[i].playerTracker;
                    if ( ( client.disconnect <= 0 ) && ( client.spectate == false ) ) ++player;
                }
                // Boot Player if Server Full
                if ( player > c.serverMaxConnections )
                {
                    //this.socket.sendPacket(new Packet.ServerMsg(93));
                    this.socket.close();
                }
                this.socket.sendPacket(new Packet.SetBorder(c.borderLeft, c.borderRight, c.borderTop, c.borderBottom));
               // this.socket.sendPacket(new Packet.ServerInfo(process.uptime().toFixed(0),player,c.borderRight,c.foodMaxAmount,this.gameServer.config.serverGamemode));
            }
            break;
		 case 99:
            var message = "";
            var maxLen = this.gameServer.config.chatMaxMessageLength * 2; // 2 bytes per char
            var offset = 2;
            var flags = view.getUint8(1); // for future use (e.g. broadcast vs local message)
            if (flags & 2) {
                offset += 4;
            }
            if (flags & 4) {
                offset += 8;
            }
            if (flags & 8) {
                offset += 16;
            }
            for (var i = offset; i < view.byteLength && i <= maxLen; i += 2) {
                var charCode = view.getUint16(i, true);
                if (charCode == 0) {
                    break;
                }
                message += String.fromCharCode(charCode);
            }
			//////////////////
			if (this.gameServer.config.chatAntiSpam == 1)
			{
				if ((new Date() - this.socket.playerTracker.lastMsgSent) > this.gameServer.config.chatAntiSpamDelay)
				{
					this.socket.playerTracker.lastMsgSent = new Date();
					var packet = new Packet.Chat(this.socket.playerTracker, message);
					// Send to all clients (broadcast)
					for (var i = 0; i < this.gameServer.clients.length; i++) {
						this.gameServer.clients[i].sendPacket(packet);
					}
				}
			}
			else
			{
				var packet = new Packet.Chat(this.socket.playerTracker, message);
				// Send to all clients (broadcast)
				for (var i = 0; i < this.gameServer.clients.length; i++) {
					this.gameServer.clients[i].sendPacket(packet);
				}
			}
            break;
		case 111: /////////////////////////////////////////////////////////////////
			var skinName = "";
            for (var i = 1; i < view.byteLength; i += 2) {
                var charCode = view.getUint16(i, true);
                if (charCode == 0) {
                    break;
                }
                skinName += String.fromCharCode(charCode);
            }
			if (this.socket.playerTracker.skinName == "")
				this.socket.playerTracker.setSkinName(skinName);
            break;
		case 130:
			if (this.socket.playerTracker.pingpacketSent)
			{
				this.socket.playerTracker.pingTime = Date.now() - this.socket.playerTracker.pingPacketSendTime;
				if (this.socket.playerTracker.avgPing == 0)
					this.socket.playerTracker.avgPing = this.socket.playerTracker.pingTime;
				else
					this.socket.playerTracker.avgPing =  (this.socket.playerTracker.avgPing + this.socket.playerTracker.pingTime) /2;

				this.socket.playerTracker.pingpacketSent = false;
			}
            break;
        default:
            break;
    }
};

PacketHandler.prototype.setNickname = function(newNick) {
    var client = this.socket.playerTracker;
    if (client.cells.length < 1) {
        // Set name first
        client.setName(newNick);

        // Clear client's nodes
        this.socket.sendPacket(new Packet.ClearNodes());

        // If client has no cells... then spawn a player
        this.gameServer.gameMode.onPlayerSpawn(this.gameServer, client);

        // Turn off spectate mode
        client.spectate = false;
    }
};


text:
[![Build Status](https://travis-ci.org/Raybird/morningpet.svg?branch=master)](https://travis-ci.org/Raybird/morningpet)

### Practice [slimframework](http://www.slimframework.com/)


text:
'use strict';

//Configuring the Core module
angular.module('core').run(['Menus',
	function(Menus) {
    Menus.addMenuItem('topbar', 'Setup', 'setup', 'dropdown');
    Menus.addSubMenuItem('topbar', 'setup', 'Client', 'clients');
    Menus.addSubMenuItem('topbar', 'setup', 'Settings', 'settings');
    Menus.addSubMenuItem('topbar', 'setup', 'Products', 'products');
    Menus.addMenuItem('topbar', 'Transactions', 'transactions', 'dropdown');
    Menus.addSubMenuItem('topbar', 'transactions', 'Orders', 'orders');
    Menus.addSubMenuItem('topbar', 'transactions', 'Projects', 'projects');
    Menus.addSubMenuItem('topbar', 'transactions', 'Invoices', 'invoices');
    Menus.addSubMenuItem('topbar', 'transactions', 'Expenses', 'expenses');
  }
]);


text:
<?php

/**
 * @file
 * Contains \Drupal\config\Tests\ConfigSingleImportExportTest.
 */

namespace Drupal\config\Tests;

use Drupal\Component\Serialization\Yaml;
use Drupal\simpletest\WebTestBase;

/**
 * Tests the user interface for importing/exporting a single configuration.
 *
 * @group config
 */
class ConfigSingleImportExportTest extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'block',
    'config',
    'config_test'
  ];

  protected function setUp() {
    parent::setUp();

    $this->drupalPlaceBlock('page_title_block');
  }

  /**
   * Tests importing a single configuration file.
   */
  public function testImport() {
    $storage = \Drupal::entityManager()->getStorage('config_test');
    $uuid = \Drupal::service('uuid');

    $this->drupalLogin($this->drupalCreateUser(array('import configuration')));
    $import = <<<EOD
label: First
weight: 0
style: ''
status: '1'
EOD;
    $edit = array(
      'config_type' => 'config_test',
      'import' => $import,
    );
    // Attempt an import with a missing ID.
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertText(t('Missing ID key "@id_key" for this @entity_type import.', array('@id_key' => 'id', '@entity_type' => 'Test configuration')));

    // Perform an import with no specified UUID and a unique ID.
    $this->assertNull($storage->load('first'));
    $edit['import'] = "id: first\n" . $edit['import'];
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertRaw(t('Are you sure you want to create a new %name @type?', array('%name' => 'first', '@type' => 'test configuration')));
    $this->drupalPostForm(NULL, array(), t('Confirm'));
    $entity = $storage->load('first');
    $this->assertIdentical($entity->label(), 'First');
    $this->assertIdentical($entity->id(), 'first');
    $this->assertTrue($entity->status());
    $this->assertRaw(t('The configuration was imported successfully.'));

    // Attempt an import with an existing ID but missing UUID.
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertText(t('An entity with this machine name already exists but the import did not specify a UUID.'));

    // Attempt an import with a mismatched UUID and existing ID.
    $edit['import'] .= "\nuuid: " . $uuid->generate();
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertText(t('An entity with this machine name already exists but the UUID does not match.'));

    // Attempt an import with a custom ID.
    $edit['custom_entity_id'] = 'custom_id';
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertRaw(t('Are you sure you want to create a new %name @type?', array('%name' => 'custom_id', '@type' => 'test configuration')));
    $this->drupalPostForm(NULL, array(), t('Confirm'));
    $this->assertRaw(t('The configuration was imported successfully.'));

    // Perform an import with a unique ID and UUID.
    $import = <<<EOD
id: second
label: Second
weight: 0
style: ''
status: '0'
EOD;
    $edit = array(
      'config_type' => 'config_test',
      'import' => $import,
    );
    $second_uuid = $uuid->generate();
    $edit['import'] .= "\nuuid: " . $second_uuid;
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertRaw(t('Are you sure you want to create a new %name @type?', array('%name' => 'second', '@type' => 'test configuration')));
    $this->drupalPostForm(NULL, array(), t('Confirm'));
    $entity = $storage->load('second');
    $this->assertRaw(t('The configuration was imported successfully.'));
    $this->assertIdentical($entity->label(), 'Second');
    $this->assertIdentical($entity->id(), 'second');
    $this->assertFalse($entity->status());
    $this->assertIdentical($entity->uuid(), $second_uuid);

    // Perform an update.
    $import = <<<EOD
id: second
uuid: $second_uuid
label: 'Second updated'
weight: 0
style: ''
status: '0'
EOD;
    $edit = array(
      'config_type' => 'config_test',
      'import' => $import,
    );
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertRaw(t('Are you sure you want to update the %name @type?', array('%name' => 'second', '@type' => 'test configuration')));
    $this->drupalPostForm(NULL, array(), t('Confirm'));
    $entity = $storage->load('second');
    $this->assertRaw(t('The configuration was imported successfully.'));
    $this->assertIdentical($entity->label(), 'Second updated');

    // Try to perform an update which adds missing dependencies.
    $import = <<<EOD
id: second
uuid: $second_uuid
label: 'Second updated'
weight: 0
style: ''
status: '0'
dependencies:
  module:
    - does_not_exist
EOD;
    $edit = array(
      'config_type' => 'config_test',
      'import' => $import,
    );
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertRaw(t('Configuration %name depends on the %owner module that will not be installed after import.', ['%name' => 'config_test.dynamic.second', '%owner' => 'does_not_exist']));
  }

  /**
   * Tests importing a simple configuration file.
   */
  public function testImportSimpleConfiguration() {
    $this->drupalLogin($this->drupalCreateUser(array('import configuration')));
    $config = $this->config('system.site')->set('name', 'Test simple import');

    // Place branding block with site name into header region.
    $this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);

    $edit = array(
      'config_type' => 'system.simple',
      'config_name' => $config->getName(),
      'import' => Yaml::encode($config->get()),
    );
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertRaw(t('Are you sure you want to update the %name @type?', array('%name' => $config->getName(), '@type' => 'simple configuration')));
    $this->drupalPostForm(NULL, array(), t('Confirm'));
    $this->drupalGet('');
    $this->assertText('Test simple import');

    // Ensure that ConfigImporter validation is running when importing simple
    // configuration.
    $config_data = $this->config('core.extension')->get();
    // Simulate uninstalling the Config module.
    unset($config_data['module']['config']);
    $edit = array(
      'config_type' => 'system.simple',
      'config_name' => 'core.extension',
      'import' => Yaml::encode($config_data),
    );
    $this->drupalPostForm('admin/config/development/configuration/single/import', $edit, t('Import'));
    $this->assertText(t('Can not uninstall the Configuration module as part of a configuration synchronization through the user interface.'));

  }

  /**
   * Tests exporting a single configuration file.
   */
  public function testExport() {
    $this->drupalLogin($this->drupalCreateUser(array('export configuration')));

    $this->drupalGet('admin/config/development/configuration/single/export/system.simple');
    $this->assertFieldByXPath('//select[@name="config_type"]//option[@selected="selected"]', t('Simple configuration'), 'The simple configuration option is selected when specified in the URL.');
    // Spot check several known simple configuration files.
    $element = $this->xpath('//select[@name="config_name"]');
    $options = $this->getAllOptions($element[0]);
    $expected_options = array('system.site', 'user.settings');
    foreach ($options as &$option) {
      $option = (string) $option;
    }
    $this->assertIdentical($expected_options, array_intersect($expected_options, $options), 'The expected configuration files are listed.');

    $this->drupalGet('admin/config/development/configuration/single/export/system.simple/system.image');
    $this->assertFieldByXPath('//textarea[@name="export"]', "toolkit: gd\n", 'The expected system configuration is displayed.');

    $this->drupalGet('admin/config/development/configuration/single/export/date_format');
    $this->assertFieldByXPath('//select[@name="config_type"]//option[@selected="selected"]', t('Date format'), 'The date format entity type is selected when specified in the URL.');

    $this->drupalGet('admin/config/development/configuration/single/export/date_format/fallback');
    $this->assertFieldByXPath('//select[@name="config_name"]//option[@selected="selected"]', t('Fallback date format (fallback)'), 'The fallback date format config entity is selected when specified in the URL.');

    $fallback_date = \Drupal::entityManager()->getStorage('date_format')->load('fallback');
    $data = Yaml::encode($fallback_date->toArray());
    $this->assertFieldByXPath('//textarea[@name="export"]', $data, 'The fallback date format config entity export code is displayed.');
  }

}


text:
GENCODE = 'hg38_gencode27.bed'
LONGREAD_ONLY = 'gencode.longread_only_1k.txt'
LONGREAD_ONLY_FULL = 'hg38_gencode27.longread_only_1k.bed'

def generate_longread_only():
    longread_only = list()
    with open(LONGREAD_ONLY) as input:
        for line in input:
            longread_only.append(line.strip())

    gencode_map = dict()
    with open(GENCODE) as input:
        for line in input:
            line = line.split()
            id = line[3]
            gencode_map[id] = line

    chroms = dict()
    with open(LONGREAD_ONLY_FULL, 'w') as output:
        for lro in longread_only:
            gene = gencode_map[lro]
            output.write("\t".join(gene) + "\n")
            chrom = gene[0]
            if chrom in chroms: chroms[chrom] += 1
            else: chroms[chrom] = 1

    keys = chroms.keys()
    keys.sort()
    for key in keys:
        print("{}: {}".format(key, chroms[key]))

def get_coverage_stats():
    import glob
    print
    # for file in glob.glob("*.coverage"):
    for file in glob.glob("../workdir_cent/*.coverage"):
        coverage = 0.0
        overlap = 0.0
        with open(file) as input:
            for line in input:
                if "genome" not in line: continue
                line = line.split()
                if int(line[1]) != 0: coverage += float(line[4])
                if int(line[1]) > 1: overlap += float(line[4])
        print("{}\n\tcoverage: {}".format(file, coverage))

RMSK_LONGREAD = "INC_repeat_masker.INC_gencode_longread.bed"
def get_rmsk_percentages(rmsk):
    classes = dict()
    total = 0
    with open(rmsk) as input:
        for line in input:
            line = line.split()
            clazz = line[6]
            cover = int(line[2]) - int(line[1])
            total += cover
            if clazz in classes: classes[clazz] += cover
            else: classes[clazz] = cover

    print(rmsk)
    for k,v in classes.iteritems():
        print("%16s:\t%8d (%2d%%)" % (k, v, int(100.0*v/total)))

get_rmsk_percentages("INC_rmsk.INC_gencode.INC_repeatmask.EXC_gvcf_clbl.bed")
get_rmsk_percentages("../rmsk.bed   ")


text:
__author__ = 'IRSEN'
# -*- coding: utf-8 -*-

from model.group import Group
#  from timeit import timeit

def test_group_list(app, db):
    ui_list = app.group.get_group_list()
    def clean(group):
        return Group(id=group.id, name=group.name.strip())
    db_list = map(clean, db.get_group_list())
#   print(timeit(lambda: map(clean, db.get_group_list()), number=1000))  # вывести на консоль время выполнения
    assert sorted(ui_list, key=Group.id_or_max) == sorted(db_list, key=Group.id_or_max)


text:
package firehoseiface

import (
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/service/firehose"
)

// FirehoseAPI is the interface type for firehose.Firehose.
type FirehoseAPI interface {
	CreateDeliveryStreamRequest(*firehose.CreateDeliveryStreamInput) (*request.Request, *firehose.CreateDeliveryStreamOutput)

	CreateDeliveryStream(*firehose.CreateDeliveryStreamInput) (*firehose.CreateDeliveryStreamOutput, error)

	DeleteDeliveryStreamRequest(*firehose.DeleteDeliveryStreamInput) (*request.Request, *firehose.DeleteDeliveryStreamOutput)

	DeleteDeliveryStream(*firehose.DeleteDeliveryStreamInput) (*firehose.DeleteDeliveryStreamOutput, error)

	DescribeDeliveryStreamRequest(*firehose.DescribeDeliveryStreamInput) (*request.Request, *firehose.DescribeDeliveryStreamOutput)

	DescribeDeliveryStream(*firehose.DescribeDeliveryStreamInput) (*firehose.DescribeDeliveryStreamOutput, error)

	ListDeliveryStreamsRequest(*firehose.ListDeliveryStreamsInput) (*request.Request, *firehose.ListDeliveryStreamsOutput)

	ListDeliveryStreams(*firehose.ListDeliveryStreamsInput) (*firehose.ListDeliveryStreamsOutput, error)

	PutRecordRequest(*firehose.PutRecordInput) (*request.Request, *firehose.PutRecordOutput)

	PutRecord(*firehose.PutRecordInput) (*firehose.PutRecordOutput, error)

	PutRecordBatchRequest(*firehose.PutRecordBatchInput) (*request.Request, *firehose.PutRecordBatchOutput)

	PutRecordBatch(*firehose.PutRecordBatchInput) (*firehose.PutRecordBatchOutput, error)

	UpdateDestinationRequest(*firehose.UpdateDestinationInput) (*request.Request, *firehose.UpdateDestinationOutput)

	UpdateDestination(*firehose.UpdateDestinationInput) (*firehose.UpdateDestinationOutput, error)
}


text: This is the view for the Android.


text:
package me.rogers.bunny.rendering.lighting;

import org.lwjgl.util.vector.Vector3f;

public class Light {

    private Vector3f color;
    private Vector3f position;
    private Vector3f attenuation;

    public Light(Vector3f color, Vector3f position) {
        this(color, position, new Vector3f(1, 0, 0));
    }

    public Light(Vector3f color, Vector3f position, Vector3f attenuation) {
        this.color = color;
        this.position = position;
        this.attenuation = attenuation;
    }

    public Vector3f getColor() {
        return color;
    }

    public Vector3f getPosition() {
        return position;
    }

    public void setColor(Vector3f color) {
        this.color = color;
    }

    public void setPosition(Vector3f position) {
        this.position = position;
    }

    public Vector3f getAttenuation() {
        return attenuation;
    }

    public void setAttenuation(Vector3f attenuation) {
        this.attenuation = attenuation;
    }

}


text:
#include "sqliteInt.h"
#include "tcl.h"
#include <stdlib.h>
#include <string.h>

#ifndef SQLITE_OMIT_VIRTUALTABLE

typedef struct tclvar_vtab tclvar_vtab;
typedef struct tclvar_cursor tclvar_cursor;

/*
** A tclvar virtual-table object
*/
struct tclvar_vtab {
  sqlite3_vtab base;
  Tcl_Interp *interp;
};

/* A tclvar cursor object */
struct tclvar_cursor {
  sqlite3_vtab_cursor base;

  Tcl_Obj *pList1;     /* Result of [info vars ?pattern?] */
  Tcl_Obj *pList2;     /* Result of [array names [lindex $pList1 $i1]] */
  int i1;              /* Current item in pList1 */
  int i2;              /* Current item (if any) in pList2 */
};

/* Methods for the tclvar module */
static int tclvarConnect(
  sqlite3 *db,
  void *pAux,
  int argc, const char *const*argv,
  sqlite3_vtab **ppVtab,
  char **pzErr
){
  tclvar_vtab *pVtab;
  static const char zSchema[] =
     "CREATE TABLE whatever(name TEXT, arrayname TEXT, value TEXT)";
  pVtab = sqlite3MallocZero( sizeof(*pVtab) );
  if( pVtab==0 ) return SQLITE_NOMEM;
  *ppVtab = &pVtab->base;
  pVtab->interp = (Tcl_Interp *)pAux;
  sqlite3_declare_vtab(db, zSchema);
  return SQLITE_OK;
}
/* Note that for this virtual table, the xCreate and xConnect
** methods are identical. */

static int tclvarDisconnect(sqlite3_vtab *pVtab){
  sqlite3_free(pVtab);
  return SQLITE_OK;
}
/* The xDisconnect and xDestroy methods are also the same */

/*
** Open a new tclvar cursor.
*/
static int tclvarOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  tclvar_cursor *pCur;
  pCur = sqlite3MallocZero(sizeof(tclvar_cursor));
  *ppCursor = &pCur->base;
  return SQLITE_OK;
}

/*
** Close a tclvar cursor.
*/
static int tclvarClose(sqlite3_vtab_cursor *cur){
  tclvar_cursor *pCur = (tclvar_cursor *)cur;
  if( pCur->pList1 ){
    Tcl_DecrRefCount(pCur->pList1);
  }
  if( pCur->pList2 ){
    Tcl_DecrRefCount(pCur->pList2);
  }
  sqlite3_free(pCur);
  return SQLITE_OK;
}

/*
** Returns 1 if data is ready, or 0 if not.
*/
static int next2(Tcl_Interp *interp, tclvar_cursor *pCur, Tcl_Obj *pObj){
  Tcl_Obj *p;

  if( pObj ){
    if( !pCur->pList2 ){
      p = Tcl_NewStringObj("array names", -1);
      Tcl_IncrRefCount(p);
      Tcl_ListObjAppendElement(0, p, pObj);
      Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL);
      Tcl_DecrRefCount(p);
      pCur->pList2 = Tcl_GetObjResult(interp);
      Tcl_IncrRefCount(pCur->pList2);
      assert( pCur->i2==0 );
    }else{
      int n = 0;
      pCur->i2++;
      Tcl_ListObjLength(0, pCur->pList2, &n);
      if( pCur->i2>=n ){
        Tcl_DecrRefCount(pCur->pList2);
        pCur->pList2 = 0;
        pCur->i2 = 0;
        return 0;
      }
    }
  }

  return 1;
}

static int tclvarNext(sqlite3_vtab_cursor *cur){
  Tcl_Obj *pObj;
  int n = 0;
  int ok = 0;

  tclvar_cursor *pCur = (tclvar_cursor *)cur;
  Tcl_Interp *interp = ((tclvar_vtab *)(cur->pVtab))->interp;

  Tcl_ListObjLength(0, pCur->pList1, &n);
  while( !ok && pCur->i1<n ){
    Tcl_ListObjIndex(0, pCur->pList1, pCur->i1, &pObj);
    ok = next2(interp, pCur, pObj);
    if( !ok ){
      pCur->i1++;
    }
  }

  return 0;
}

static int tclvarFilter(
  sqlite3_vtab_cursor *pVtabCursor,
  int idxNum, const char *idxStr,
  int argc, sqlite3_value **argv
){
  tclvar_cursor *pCur = (tclvar_cursor *)pVtabCursor;
  Tcl_Interp *interp = ((tclvar_vtab *)(pVtabCursor->pVtab))->interp;

  Tcl_Obj *p = Tcl_NewStringObj("info vars", -1);
  Tcl_IncrRefCount(p);

  assert( argc==0 || argc==1 );
  if( argc==1 ){
    Tcl_Obj *pArg = Tcl_NewStringObj((char*)sqlite3_value_text(argv[0]), -1);
    Tcl_ListObjAppendElement(0, p, pArg);
  }
  Tcl_EvalObjEx(interp, p, TCL_EVAL_GLOBAL);
  if( pCur->pList1 ){
    Tcl_DecrRefCount(pCur->pList1);
  }
  if( pCur->pList2 ){
    Tcl_DecrRefCount(pCur->pList2);
    pCur->pList2 = 0;
  }
  pCur->i1 = 0;
  pCur->i2 = 0;
  pCur->pList1 = Tcl_GetObjResult(interp);
  Tcl_IncrRefCount(pCur->pList1);
  assert( pCur->i1==0 && pCur->i2==0 && pCur->pList2==0 );

  Tcl_DecrRefCount(p);
  return tclvarNext(pVtabCursor);
}

static int tclvarColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  Tcl_Obj *p1;
  Tcl_Obj *p2;
  const char *z1;
  const char *z2 = "";
  tclvar_cursor *pCur = (tclvar_cursor*)cur;
  Tcl_Interp *interp = ((tclvar_vtab *)cur->pVtab)->interp;

  Tcl_ListObjIndex(interp, pCur->pList1, pCur->i1, &p1);
  Tcl_ListObjIndex(interp, pCur->pList2, pCur->i2, &p2);
  z1 = Tcl_GetString(p1);
  if( p2 ){
    z2 = Tcl_GetString(p2);
  }
  switch (i) {
    case 0: {
      sqlite3_result_text(ctx, z1, -1, SQLITE_TRANSIENT);
      break;
    }
    case 1: {
      sqlite3_result_text(ctx, z2, -1, SQLITE_TRANSIENT);
      break;
    }
    case 2: {
      Tcl_Obj *pVal = Tcl_GetVar2Ex(interp, z1, *z2?z2:0, TCL_GLOBAL_ONLY);
      sqlite3_result_text(ctx, Tcl_GetString(pVal), -1, SQLITE_TRANSIENT);
      break;
    }
  }
  return SQLITE_OK;
}

static int tclvarRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  *pRowid = 0;
  return SQLITE_OK;
}

static int tclvarEof(sqlite3_vtab_cursor *cur){
  tclvar_cursor *pCur = (tclvar_cursor*)cur;
  return (pCur->pList2?0:1);
}

static int tclvarBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  int ii;

  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
    if( pCons->iColumn==0 && pCons->usable
           && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
      struct sqlite3_index_constraint_usage *pUsage;
      pUsage = &pIdxInfo->aConstraintUsage[ii];
      pUsage->omit = 0;
      pUsage->argvIndex = 1;
      return SQLITE_OK;
    }
  }

  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
    struct sqlite3_index_constraint const *pCons = &pIdxInfo->aConstraint[ii];
    if( pCons->iColumn==0 && pCons->usable
           && pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
      struct sqlite3_index_constraint_usage *pUsage;
      pUsage = &pIdxInfo->aConstraintUsage[ii];
      pUsage->omit = 1;
      pUsage->argvIndex = 1;
      return SQLITE_OK;
    }
  }

  return SQLITE_OK;
}

/*
** A virtual table module that provides read-only access to a
** Tcl global variable namespace.
*/
static sqlite3_module tclvarModule = {
  0,                         /* iVersion */
  tclvarConnect,
  tclvarConnect,
  tclvarBestIndex,
  tclvarDisconnect,
  tclvarDisconnect,
  tclvarOpen,                  /* xOpen - open a cursor */
  tclvarClose,                 /* xClose - close a cursor */
  tclvarFilter,                /* xFilter - configure scan constraints */
  tclvarNext,                  /* xNext - advance a cursor */
  tclvarEof,                   /* xEof - check for end of scan */
  tclvarColumn,                /* xColumn - read data */
  tclvarRowid,                 /* xRowid - read data */
  0,                           /* xUpdate */
  0,                           /* xBegin */
  0,                           /* xSync */
  0,                           /* xCommit */
  0,                           /* xRollback */
  0,                           /* xFindMethod */
  0,                           /* xRename */
};

/*
** Decode a pointer to an sqlite3 object.
*/
extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb);

/*
** Register the echo virtual table module.
*/
static int register_tclvar_module(
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite3 *db;
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
    return TCL_ERROR;
  }
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  sqlite3_create_module(db, "tclvar", &tclvarModule, (void *)interp);
#endif
  return TCL_OK;
}

#endif

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetesttclvar_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_VIRTUALTABLE
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "register_tclvar_module",   register_tclvar_module, 0 },
  };
  int i;
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName,
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
  }
#endif
  return TCL_OK;
}


text:
"""
Django test cases for this project.

.. autosummary::
   :toctree:

   test_ddh
   test_notify
   test_workflow

"""


text:
package com.spykins.assessment.MainScreen.mainView.view;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.spykins.assessment.MainScreen.MovieApp;
import com.spykins.assessment.MainScreen.detailScreen.view.DetailActivity;
import com.spykins.assessment.MainScreen.model.FavMovie;
import com.spykins.assessment.MainScreen.mainView.adapter.RecyclerViewAdapter;
import com.spykins.assessment.MainScreen.mainView.contract.MainActivityContract;
import com.spykins.assessment.R;

import java.util.List;

import javax.inject.Inject;

public class MainActivity extends AppCompatActivity implements MainActivityContract.View {

    @Inject MainActivityContract.Presenter presenter;
    private RecyclerViewAdapter recyclerViewAdapter;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ((MovieApp)getApplication()).getAppComponent().inject(this);
        setUpRecyclerView();
        presenter.setView(this);
        presenter.fetchData();
    }

    private void setUpRecyclerView() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerViewAdapter = new RecyclerViewAdapter(this);
        recyclerView.setAdapter(recyclerViewAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public void displayDataInView(List<FavMovie> body) {
        recyclerViewAdapter.swapList(body);
    }

    @Override
    public void onRecyclerItemClicked(FavMovie movie) {
        presenter.recyclerItemIsClicked(movie);
    }

    @Override
    public void navigateToDetailView(FavMovie movie) {
        Intent intent = DetailActivity.newInstance(MainActivity.this, movie);
        startActivity(intent);
        //Go to detail view
    }

    @Override
    public void displayError(String s) {
        Toast.makeText(this,"Problem occured while fetching data",Toast.LENGTH_LONG).show();
    }
}


text:
package test;

import org.testng.annotations.Test;
import org.testng.xml.XmlSuite;

/**
 * @author cbeust
 */
public class Misc extends BaseTest {

  @Test
  public void makeSureSetUpWithParameterWithNoParametersFails() {
    addClass("test.sample.SetUpWithParameterTest");
    setVerbose(0);
//    setParallel(XmlSuite.PARALLEL_METHODS);
    run();
    String[] passed = {
      };
      // @Configuration failures are not reported in the ITestListener
      String[] failed = {
      };
      String[] skipped = {
          "test",
      };
      verifyTests("Passed", passed, getPassedTests());
      verifyTests("Failed", failed, getFailedTests());
      verifyTests("Failed", skipped, getSkippedTests());
  }

}


text:
#ifndef STMTDDLPOPULATEINDEX_H
#define STMTDDLPOPULATEINDEX_H
/* -*-C++-*-
 *****************************************************************************
 *
 * File:         StmtDDLPopulateIndex.h
 * Description:  class representing Populate Index Statement parser nodes
 *
 *
 * Created:
 * Language:     C++
 *
 *
 *
 *
 *****************************************************************************
 */

#include "ElemDDLNode.h"
#include "NAString.h"
#include "StmtDDLNode.h"
#include "ComSmallDefs.h"

// -----------------------------------------------------------------------
// contents of this file
// -----------------------------------------------------------------------
class StmtDDLPopulateIndex;

// -----------------------------------------------------------------------
// forward references
// -----------------------------------------------------------------------
// None

// -----------------------------------------------------------------------
// Populate Index statement
// -----------------------------------------------------------------------
class StmtDDLPopulateIndex : public StmtDDLNode
{

public:

  // initialize constructor
  StmtDDLPopulateIndex(NABoolean populateAll, NABoolean populateAllUnique,
		       const NAString &anIndexName, // dummy name, if populateAll*
		       const QualifiedName & aTableName,
		       CollHeap    * heap = PARSERHEAP());

  // virtual destructor
  virtual ~StmtDDLPopulateIndex();

  // cast
  virtual StmtDDLPopulateIndex * castToStmtDDLPopulateIndex();

  //
  // accessors
  //

  // methods relating to parse tree
  virtual Int32 getArity() const;
  virtual ExprNode * getChild(Lng32 index);

  inline const QualifiedName & getOrigTableNameAsQualifiedName() const;
  inline       QualifiedName & getOrigTableNameAsQualifiedName();

  inline const NAString & getIndexName() const;
  inline const QualifiedName & getIndexNameAsQualifiedName() const;
  inline       QualifiedName & getIndexNameAsQualifiedName() ;

  inline const QualifiedName & getTableNameAsQualifiedName() const;
  inline       QualifiedName & getTableNameAsQualifiedName() ;

  // returns table name, in external format.
  const NAString getTableName() const;

  //  ExprNode * bindNode(BindWA * pBindWA);

  //
  // method for collecting information
  //

  void synthesize();

        // collects information in the parse sub-tree and
        // copy/move them to the current parse node.

  //
  // methods for tracing
  //

  virtual const NAString displayLabel1() const;
  virtual const NAString displayLabel2() const;
  //  virtual NATraceList getDetailInfo() const;
  virtual const NAString getText() const;

  virtual NABoolean explainSupported() { return TRUE; }

  NABoolean populateAll() { return populateAll_; }
  NABoolean populateAllUnique() { return populateAllUnique_; }

private:

  // ---------------------------------------------------------------------
  // private methods
  // ---------------------------------------------------------------------
  NABoolean populateAll_;
  NABoolean populateAllUnique_;

  //
  // please do not use the following methods
  //

  StmtDDLPopulateIndex();                                        // DO NOT USE
  StmtDDLPopulateIndex(const StmtDDLPopulateIndex &);              // DO NOT USE
  StmtDDLPopulateIndex & operator=(const StmtDDLPopulateIndex &);  // DO NOT USE

  // ---------------------------------------------------------------------
  // private data members
  // ---------------------------------------------------------------------

  // index name can only be a simple name
  NAString indexName_;
  QualifiedName indexQualName_;

  // the tablename specified by user in the create stmt.
  // This name is not fully qualified during bind phase.
  QualifiedName origTableQualName_;

  // The syntax of table name is
  // [ [ catalog-name . ] schema-name . ] table-name

  QualifiedName tableQualName_;

}; // class StmtDDLPopulateIndex

// -----------------------------------------------------------------------
// definitions of inline methods for class StmtDDLPopulateIndex
// -----------------------------------------------------------------------
inline QualifiedName &
StmtDDLPopulateIndex::getOrigTableNameAsQualifiedName()
{
  return origTableQualName_;
}

inline const QualifiedName &
StmtDDLPopulateIndex::getOrigTableNameAsQualifiedName() const
{
  return origTableQualName_;
}

inline QualifiedName &
StmtDDLPopulateIndex::getIndexNameAsQualifiedName()
{
  return indexQualName_;
}

inline const QualifiedName &
StmtDDLPopulateIndex::getIndexNameAsQualifiedName() const
{
  return indexQualName_;
}

inline QualifiedName &
StmtDDLPopulateIndex::getTableNameAsQualifiedName()
{
  return tableQualName_;
}

inline const QualifiedName &
StmtDDLPopulateIndex::getTableNameAsQualifiedName() const
{
  return tableQualName_;
}

// get index name
inline const NAString &
StmtDDLPopulateIndex::getIndexName() const
{
  return indexName_;
}

#endif // STMTDDLPOPULATEINDEX_H