text:
import atexit
import functools
import os
import sys

import debtcollector.moves
import fixtures
from oslo_log import log as logging
import six
import testtools

from tempest import clients
from tempest.common import credentials_factory as credentials
import tempest.common.validation_resources as vresources
from tempest import config
from tempest.lib.common import cred_client
from tempest.lib.common import fixed_network
from tempest.lib import decorators
from tempest.lib import exceptions as lib_exc

LOG = logging.getLogger(__name__)

CONF = config.CONF

# TODO(oomichi): This test.idempotent_id should be removed after all projects
# switch to use decorators.idempotent_id.
idempotent_id = debtcollector.moves.moved_function(
    decorators.idempotent_id, 'idempotent_id', __name__,
    version='Mitaka', removal_version='?')

related_bug = debtcollector.moves.moved_function(
    decorators.related_bug, 'related_bug', __name__,
    version='Pike', removal_version='?')

attr = debtcollector.moves.moved_function(
    decorators.attr, 'attr', __name__,
    version='Pike', removal_version='?')

class InvalidServiceTag(lib_exc.TempestException):
    message = "Invalid service tag"

def get_service_list():
    service_list = {
        'compute': CONF.service_available.nova,
        'image': CONF.service_available.glance,
        'volume': CONF.service_available.cinder,
        # NOTE(masayukig): We have two network services which are neutron and
        # nova-network. And we have no way to know whether nova-network is
        # available or not. After the pending removal of nova-network from
        # nova, we can treat the network/neutron case in the same manner as
        # the other services.
        'network': True,
        # NOTE(masayukig): Tempest tests always require the identity service.
        # So we should set this True here.
        'identity': True,
        'object_storage': CONF.service_available.swift,
    }
    return service_list

def services(*args):
    """A decorator used to set an attr for each service used in a test case

    This decorator applies a testtools attr for each service that gets
    exercised by a test case.
    """
    def decorator(f):
        known_services = get_service_list()

        for service in args:
            if service not in known_services:
                raise InvalidServiceTag('%s is not a valid service' % service)
        decorators.attr(type=list(args))(f)

        @functools.wraps(f)
        def wrapper(self, *func_args, **func_kwargs):
            service_list = get_service_list()

            for service in args:
                if not service_list[service]:
                    msg = 'Skipped because the %s service is not available' % (
                        service)
                    raise testtools.TestCase.skipException(msg)
            return f(self, *func_args, **func_kwargs)
        return wrapper
    return decorator

def requires_ext(**kwargs):
    """A decorator to skip tests if an extension is not enabled

    @param extension
    @param service
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*func_args, **func_kwargs):
            if not is_extension_enabled(kwargs['extension'],
                                        kwargs['service']):
                msg = "Skipped because %s extension: %s is not enabled" % (
                    kwargs['service'], kwargs['extension'])
                raise testtools.TestCase.skipException(msg)
            return func(*func_args, **func_kwargs)
        return wrapper
    return decorator

def is_extension_enabled(extension_name, service):
    """A function that will check the list of enabled extensions from config

    """
    config_dict = {
        'compute': CONF.compute_feature_enabled.api_extensions,
        'volume': CONF.volume_feature_enabled.api_extensions,
        'network': CONF.network_feature_enabled.api_extensions,
        'object': CONF.object_storage_feature_enabled.discoverable_apis,
        'identity': CONF.identity_feature_enabled.api_extensions
    }
    if not config_dict[service]:
        return False
    if config_dict[service][0] == 'all':
        return True
    if extension_name in config_dict[service]:
        return True
    return False

def is_scheduler_filter_enabled(filter_name):
    """Check the list of enabled compute scheduler filters from config.

    This function checks whether the given compute scheduler filter is
    available and configured in the config file. If the
    scheduler_available_filters option is set to 'all' (Default value. which
    means default filters are configured in nova) in tempest.conf then, this
    function returns True with assumption that requested filter 'filter_name'
    is one of available filter in nova ("nova.scheduler.filters.all_filters").
    """

    filters = CONF.compute_feature_enabled.scheduler_available_filters
    if not filters:
        return False
    if 'all' in filters:
        return True
    if filter_name in filters:
        return True
    return False

at_exit_set = set()

def validate_tearDownClass():
    if at_exit_set:
        LOG.error(
            "tearDownClass does not call the super's "
            "tearDownClass in these classes: \n"
            + str(at_exit_set))

atexit.register(validate_tearDownClass)

class BaseTestCase(testtools.testcase.WithAttributes,
                   testtools.TestCase):
    """The test base class defines Tempest framework for class level fixtures.

    `setUpClass` and `tearDownClass` are defined here and cannot be overwritten
    by subclasses (enforced via hacking rule T105).

    Set-up is split in a series of steps (setup stages), which can be
    overwritten by test classes. Set-up stages are:
    - skip_checks
    - setup_credentials
    - setup_clients
    - resource_setup

    Tear-down is also split in a series of steps (teardown stages), which are
    stacked for execution only if the corresponding setup stage had been
    reached during the setup phase. Tear-down stages are:
    - clear_credentials (defined in the base test class)
    - resource_cleanup
    """

    setUpClassCalled = False

    # NOTE(andreaf) credentials holds a list of the credentials to be allocated
    # at class setup time. Credential types can be 'primary', 'alt', 'admin' or
    # a list of roles - the first element of the list being a label, and the
    # rest the actual roles
    credentials = []
    # Resources required to validate a server using ssh
    validation_resources = {}
    network_resources = {}

    # NOTE(sdague): log_format is defined inline here instead of using the oslo
    # default because going through the config path recouples config to the
    # stress tests too early, and depending on testr order will fail unit tests
    log_format = ('%(asctime)s %(process)d %(levelname)-8s '
                  '[%(name)s] %(message)s')

    # Client manager class to use in this test case.
    client_manager = clients.Manager

    # A way to adjust slow test classes
    TIMEOUT_SCALING_FACTOR = 1

    @classmethod
    def setUpClass(cls):
        # It should never be overridden by descendants
        if hasattr(super(BaseTestCase, cls), 'setUpClass'):
            super(BaseTestCase, cls).setUpClass()
        cls.setUpClassCalled = True
        # Stack of (name, callable) to be invoked in reverse order at teardown
        cls.teardowns = []
        # All the configuration checks that may generate a skip
        cls.skip_checks()
        try:
            # Allocation of all required credentials and client managers
            cls.teardowns.append(('credentials', cls.clear_credentials))
            cls.setup_credentials()
            # Shortcuts to clients
            cls.setup_clients()
            # Additional class-wide test resources
            cls.teardowns.append(('resources', cls.resource_cleanup))
            cls.resource_setup()
        except Exception:
            etype, value, trace = sys.exc_info()
            LOG.info("%s raised in %s.setUpClass. Invoking tearDownClass.",
                     etype, cls.__name__)
            cls.tearDownClass()
            try:
                six.reraise(etype, value, trace)
            finally:
                del trace  # to avoid circular refs

    @classmethod
    def tearDownClass(cls):
        # insert pdb breakpoint when pause_teardown is enabled
        if CONF.pause_teardown:
            cls.insert_pdb_breakpoint()
        at_exit_set.discard(cls)
        # It should never be overridden by descendants
        if hasattr(super(BaseTestCase, cls), 'tearDownClass'):
            super(BaseTestCase, cls).tearDownClass()
        # Save any existing exception, we always want to re-raise the original
        # exception only
        etype, value, trace = sys.exc_info()
        # If there was no exception during setup we shall re-raise the first
        # exception in teardown
        re_raise = (etype is None)
        while cls.teardowns:
            name, teardown = cls.teardowns.pop()
            # Catch any exception in tearDown so we can re-raise the original
            # exception at the end
            try:
                teardown()
            except Exception as te:
                sys_exec_info = sys.exc_info()
                tetype = sys_exec_info[0]
                # TODO(andreaf): Till we have the ability to cleanup only
                # resources that were successfully setup in resource_cleanup,
                # log AttributeError as info instead of exception.
                if tetype is AttributeError and name == 'resources':
                    LOG.info("tearDownClass of %s failed: %s", name, te)
                else:
                    LOG.exception("teardown of %s failed: %s", name, te)
                if not etype:
                    etype, value, trace = sys_exec_info
        # If exceptions were raised during teardown, and not before, re-raise
        # the first one
        if re_raise and etype is not None:
            try:
                six.reraise(etype, value, trace)
            finally:
                del trace  # to avoid circular refs

    def tearDown(self):
        super(BaseTestCase, self).tearDown()
        # insert pdb breakpoint when pause_teardown is enabled
        if CONF.pause_teardown:
            BaseTestCase.insert_pdb_breakpoint()

    @classmethod
    def insert_pdb_breakpoint(cls):
        """Add pdb breakpoint.

        This can help in debugging process, cleaning of resources is
        paused, so they can be examined.
        """
        import pdb
        pdb.set_trace()

    @classmethod
    def skip_checks(cls):
        """Class level skip checks.

        Subclasses verify in here all conditions that might prevent the
        execution of the entire test class.
        Checks implemented here may not make use API calls, and should rely on
        configuration alone.
        In general skip checks that require an API call are discouraged.
        If one is really needed it may be implemented either in the
        resource_setup or at test level.
        """
        identity_version = cls.get_identity_version()
        if 'admin' in cls.credentials and not credentials.is_admin_available(
                identity_version=identity_version):
            msg = "Missing Identity Admin API credentials in configuration."
            raise cls.skipException(msg)
        if 'alt' in cls.credentials and not credentials.is_alt_available(
                identity_version=identity_version):
            msg = "Missing a 2nd set of API credentials in configuration."
            raise cls.skipException(msg)
        if hasattr(cls, 'identity_version'):
            if cls.identity_version == 'v2':
                if not CONF.identity_feature_enabled.api_v2:
                    raise cls.skipException("Identity api v2 is not enabled")
            elif cls.identity_version == 'v3':
                if not CONF.identity_feature_enabled.api_v3:
                    raise cls.skipException("Identity api v3 is not enabled")

    @classmethod
    def setup_credentials(cls):
        """Allocate credentials and create the client managers from them.

        For every element of credentials param function creates tenant/user,
        Then it creates client manager for that credential.

        Network related tests must override this function with
        set_network_resources() method, otherwise it will create
        network resources(network resources are created in a later step).
        """
        for credentials_type in cls.credentials:
            # This may raise an exception in case credentials are not available
            # In that case we want to let the exception through and the test
            # fail accordingly
            if isinstance(credentials_type, six.string_types):
                manager = cls.get_client_manager(
                    credential_type=credentials_type)
                setattr(cls, 'os_%s' % credentials_type, manager)
                # NOTE(jordanP): Tempest should use os_primary, os_admin
                # and os_alt throughout its code base but we keep the aliases
                # around for a while for Tempest plugins. Aliases should be
                # removed eventually.
                # Setup some common aliases
                if credentials_type == 'primary':
                    cls.os = debtcollector.moves.moved_read_only_property(
                        'os', 'os_primary', version='Pike',
                        removal_version='Queens')
                    cls.manager =\
                        debtcollector.moves.moved_read_only_property(
                            'manager', 'os_primary', version='Pike',
                            removal_version='Queens')
                if credentials_type == 'admin':
                    cls.os_adm = debtcollector.moves.moved_read_only_property(
                        'os_adm', 'os_admin', version='Pike',
                        removal_version='Queens')
                    cls.admin_manager =\
                        debtcollector.moves.moved_read_only_property(
                            'admin_manager', 'os_admin', version='Pike',
                            removal_version='Queens')
                if credentials_type == 'alt':
                    cls.alt_manager =\
                        debtcollector.moves.moved_read_only_property(
                            'alt_manager', 'os_alt', version='Pike',
                            removal_version='Queens')
            elif isinstance(credentials_type, list):
                manager = cls.get_client_manager(roles=credentials_type[1:],
                                                 force_new=True)
                setattr(cls, 'os_roles_%s' % credentials_type[0], manager)

    @classmethod
    def setup_clients(cls):
        """Create links to the clients into the test object."""
        # TODO(andreaf) There is a fair amount of code that could me moved from
        # base / test classes in here. Ideally tests should be able to only
        # specify which client is `client` and nothing else.
        pass

    @classmethod
    def resource_setup(cls):
        """Class level resource setup for test cases."""
        if hasattr(cls, "os_primary"):
            cls.validation_resources = vresources.create_validation_resources(
                cls.os_primary, cls.validation_resources)
        else:
            LOG.warning("Client manager not found, validation resources not"
                        " created")

    @classmethod
    def resource_cleanup(cls):
        """Class level resource cleanup for test cases.

        Resource cleanup must be able to handle the case of partially setup
        resources, in case a failure during `resource_setup` should happen.
        """
        if cls.validation_resources:
            if hasattr(cls, "os_primary"):
                vresources.clear_validation_resources(cls.os_primary,
                                                      cls.validation_resources)
                cls.validation_resources = {}
            else:
                LOG.warning("Client manager not found, validation resources "
                            "not deleted")

    def setUp(self):
        super(BaseTestCase, self).setUp()
        if not self.setUpClassCalled:
            raise RuntimeError("setUpClass does not calls the super's"
                               "setUpClass in the "
                               + self.__class__.__name__)
        at_exit_set.add(self.__class__)
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout) * self.TIMEOUT_SCALING_FACTOR
        except ValueError:
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
                os.environ.get('OS_STDOUT_CAPTURE') == '1'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
                os.environ.get('OS_STDERR_CAPTURE') == '1'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        if (os.environ.get('OS_LOG_CAPTURE') != 'False' and
            os.environ.get('OS_LOG_CAPTURE') != '0'):
            self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                                   format=self.log_format,
                                                   level=None))

    @property
    def credentials_provider(self):
        return self._get_credentials_provider()

    @property
    def identity_utils(self):
        """A client that abstracts v2 and v3 identity operations.

        This can be used for creating and tearing down projects in tests. It
        should not be used for testing identity features.
        """
        if CONF.identity.auth_version == 'v2':
            client = self.os_admin.identity_client
            users_client = self.os_admin.users_client
            project_client = self.os_admin.tenants_client
            roles_client = self.os_admin.roles_client
            domains_client = None
        else:
            client = self.os_admin.identity_v3_client
            users_client = self.os_admin.users_v3_client
            project_client = self.os_admin.projects_client
            roles_client = self.os_admin.roles_v3_client
            domains_client = self.os_admin.domains_client

        try:
            domain = client.auth_provider.credentials.project_domain_name
        except AttributeError:
            domain = 'Default'

        return cred_client.get_creds_client(client, project_client,
                                            users_client,
                                            roles_client,
                                            domains_client,
                                            project_domain_name=domain)

    @classmethod
    def get_identity_version(cls):
        """Returns the identity version used by the test class"""
        identity_version = getattr(cls, 'identity_version', None)
        return identity_version or CONF.identity.auth_version

    @classmethod
    def _get_credentials_provider(cls):
        """Returns a credentials provider

        If no credential provider exists yet creates one.
        It always use the configuration value from identity.auth_version,
        since we always want to provision accounts with the current version
        of the identity API.
        """
        if (not hasattr(cls, '_creds_provider') or not cls._creds_provider or
                not cls._creds_provider.name == cls.__name__):
            force_tenant_isolation = getattr(cls, 'force_tenant_isolation',
                                             False)

            cls._creds_provider = credentials.get_credentials_provider(
                name=cls.__name__, network_resources=cls.network_resources,
                force_tenant_isolation=force_tenant_isolation)
        return cls._creds_provider

    @classmethod
    def get_client_manager(cls, credential_type=None, roles=None,
                           force_new=None):
        """Returns an OpenStack client manager

        Returns an OpenStack client manager based on either credential_type
        or a list of roles. If neither is specified, it defaults to
        credential_type 'primary'
        :param credential_type: string - primary, alt or admin
        :param roles: list of roles

        :returns: the created client manager
        :raises skipException: if the requested credentials are not available
        """
        if all([roles, credential_type]):
            msg = "Cannot get credentials by type and roles at the same time"
            raise ValueError(msg)
        if not any([roles, credential_type]):
            credential_type = 'primary'
        cred_provider = cls._get_credentials_provider()
        if roles:
            for role in roles:
                if not cred_provider.is_role_available(role):
                    skip_msg = (
                        "%s skipped because the configured credential provider"
                        " is not able to provide credentials with the %s role "
                        "assigned." % (cls.__name__, role))
                    raise cls.skipException(skip_msg)
            params = dict(roles=roles)
            if force_new is not None:
                params.update(force_new=force_new)
            creds = cred_provider.get_creds_by_roles(**params)
        else:
            credentials_method = 'get_%s_creds' % credential_type
            if hasattr(cred_provider, credentials_method):
                creds = getattr(cred_provider, credentials_method)()
            else:
                raise lib_exc.InvalidCredentials(
                    "Invalid credentials type %s" % credential_type)
        manager = cls.client_manager(credentials=creds.credentials)
        # NOTE(andreaf) Ensure credentials have user and project id fields.
        # It may not be the case when using pre-provisioned credentials.
        manager.auth_provider.set_auth()
        return manager

    @classmethod
    def clear_credentials(cls):
        """Clears creds if set"""
        if hasattr(cls, '_creds_provider'):
            cls._creds_provider.clear_creds()

    @classmethod
    def set_validation_resources(cls, keypair=None, floating_ip=None,
                                 security_group=None,
                                 security_group_rules=None):
        """Specify which ssh server validation resources should be created.

        Each of the argument must be set to either None, True or False, with
        None - use default from config (security groups and security group
               rules get created when set to None)
        False - Do not create the validation resource
        True - create the validation resource

        @param keypair
        @param security_group
        @param security_group_rules
        @param floating_ip
        """
        if not CONF.validation.run_validation:
            return

        if keypair is None:
            keypair = (CONF.validation.auth_method.lower() == "keypair")

        if floating_ip is None:
            floating_ip = (CONF.validation.connect_method.lower() ==
                           "floating")

        if security_group is None:
            security_group = CONF.validation.security_group

        if security_group_rules is None:
            security_group_rules = CONF.validation.security_group_rules

        if not cls.validation_resources:
            cls.validation_resources = {
                'keypair': keypair,
                'security_group': security_group,
                'security_group_rules': security_group_rules,
                'floating_ip': floating_ip}

    @classmethod
    def set_network_resources(cls, network=False, router=False, subnet=False,
                              dhcp=False):
        """Specify which network resources should be created

        @param network
        @param router
        @param subnet
        @param dhcp
        """
        # network resources should be set only once from callers
        # in order to ensure that even if it's called multiple times in
        # a chain of overloaded methods, the attribute is set only
        # in the leaf class
        if not cls.network_resources:
            cls.network_resources = {
                'network': network,
                'router': router,
                'subnet': subnet,
                'dhcp': dhcp}

    @classmethod
    def get_tenant_network(cls, credentials_type='primary'):
        """Get the network to be used in testing

        :param credentials_type: The type of credentials for which to get the
                                 tenant network

        :return: network dict including 'id' and 'name'
        """
        # Get a manager for the given credentials_type, but at least
        # always fall back on getting the manager for primary credentials
        if isinstance(credentials_type, six.string_types):
            manager = cls.get_client_manager(credential_type=credentials_type)
        elif isinstance(credentials_type, list):
            manager = cls.get_client_manager(roles=credentials_type[1:])
        else:
            manager = cls.get_client_manager()

        # Make sure cred_provider exists and get a network client
        networks_client = manager.compute_networks_client
        cred_provider = cls._get_credentials_provider()
        # In case of nova network, isolated tenants are not able to list the
        # network configured in fixed_network_name, even if they can use it
        # for their servers, so using an admin network client to validate
        # the network name
        if (not CONF.service_available.neutron and
                credentials.is_admin_available(
                    identity_version=cls.get_identity_version())):
            admin_creds = cred_provider.get_admin_creds()
            admin_manager = clients.Manager(admin_creds.credentials)
            networks_client = admin_manager.compute_networks_client
        return fixed_network.get_tenant_network(
            cred_provider, networks_client, CONF.compute.fixed_network_name)

    def assertEmpty(self, items, msg=None):
        """Asserts whether a sequence or collection is empty

        :param items: sequence or collection to be tested
        :param msg: message to be passed to the AssertionError
        :raises AssertionError: when items is not empty
        """
        if msg is None:
            msg = "sequence or collection is not empty: %s" % items
        self.assertFalse(items, msg)

    def assertNotEmpty(self, items, msg=None):
        """Asserts whether a sequence or collection is not empty

        :param items: sequence or collection to be tested
        :param msg: message to be passed to the AssertionError
        :raises AssertionError: when items is empty
        """
        if msg is None:
            msg = "sequence or collection is empty."
        self.assertTrue(items, msg)


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GetMessageTypeShould.cs" company="Epworth Consulting Ltd.">
//   © Epworth Consulting Ltd.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Atlas.ServiceBus.RabbitMQ.Tests.RabbitMQQueueNameConventionTests
{
   using System;

   using Atlas.ServiceBus.RabbitMQ.Implementations;

   using NUnit.Framework;

   public class GetMessageTypeShould
   {
      private RabbitMQQueueNameConvention componentUnderTest;

      [SetUp]
      public void SetupBeforeEachTest()
      {
         this.componentUnderTest = new RabbitMQQueueNameConvention();
      }

      [Test]
      public void ReturnMessageType()
      {
         var messageType = this.componentUnderTest.GetMessageType("Atlas.ServiceBus.RabbitMQ.Tests.RabbitMQQueueNameConventionTests.GetMessageTypeShould+TestMessage");

         Assert.That(messageType, Is.EqualTo(typeof(TestMessage)));
      }

      [Test]
      public void ThrowExceptionIfMessageTypeNotFound()
      {
         Assert.That(() => this.componentUnderTest.GetMessageType("UnknownQueue"), Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("Could not derive message type from queue name 'UnknownQueue'"));
      }

      public class TestMessage
      {
      }
   }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"log"
	"os"

	"net/http"

	"github.com/labstack/echo"
)

const (
	// ContentTypeJSON is the json content type.
	ContentTypeJSON = "application/json; charset=UTF-8"
	// HeaderContentLength is a header.
	HeaderContentLength = "Content-Length"
	// HeaderContentType is a header.
	HeaderContentType = "Content-Type"
	// HeaderServer is a header.
	HeaderServer = "Server"
	// ServerName is a header.
	ServerName = "golang"
	// MessageText is a string.
	MessageText = "Hello, World!"
)

var (
	// MessageBytes is the raw serialized message.
	MessageBytes = []byte(`{"message":"Hello, World!"}`)
)

type message struct {
	Message string `json:"message"`
}

func port() string {
	envPort := os.Getenv("PORT")
	if len(envPort) != 0 {
		return envPort
	}
	return "8080"
}

func jsonHandler(c echo.Context) error {
	return c.JSON(http.StatusOK, &message{Message: MessageText})
}

func main() {
	app := echo.New()

	app.GET("/json", jsonHandler)
	log.Fatal(app.Start(":" + port()))
}


text:
package io.github.microcks.minion.async;

import io.github.microcks.minion.async.producer.ProducerManager;

import io.quarkus.arc.Arc;
import io.quarkus.scheduler.Scheduled;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

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

@ApplicationScoped
/**
 * Bean responsible for Async mock messages producers scheduling.
 * @author laurent
 */
public class ProducerScheduler {

   /** Get a JBoss logging logger. */
   private final Logger logger = Logger.getLogger(getClass());

   private List<TriggerKey> triggerKeys = new ArrayList<>();

   @Inject
   Scheduler quartz;

   @Inject
   AsyncMockRepository mockRepository;

   @ConfigProperty(name= "minion.restricted-frequencies")
   Long[] restrictedFrequencies;

   /** Perform a dummy action. This one is actually necessary to activate the injection of Quartz scheduler. */
   @Scheduled(every = "24h")
   public void performAction() {
      logger.debug("Performing dummy action each day to allow Quartz activation");
   }

   /** Schedule all the producer jobs for configured frequencies. */
   public void scheduleAllProducerJobs() {
      for (Long frequency : restrictedFrequencies) {
         scheduleProducerForFrequency(frequency);
      }
   }

   /** Unschedule all producer jobs for configured frequencies. */
   public void unscheduleAllProducerJobs() {
      try {
         quartz.unscheduleJobs(triggerKeys);
         triggerKeys.clear();
      } catch (SchedulerException e) {
         logger.error("Failure while unscheduling all producer jobs", e);
      }
   }

   /** Inner class implementing Quartz Job and deleting job execution to ProducerManager bean. */
   public static class AsyncMockProducerJob implements Job {
      public void execute(JobExecutionContext context) throws JobExecutionException {
         Long frequency = context.getJobDetail().getJobDataMap().getLong("frequency");
         Arc.container().instance(ProducerManager.class).get().produceAsyncMockMessagesAt(frequency);
      }
   }

   /** Schedule a Quartz Job and associate trigger for specified frewqency. */
   private void scheduleProducerForFrequency(Long frequency) {
      logger.info("Scheduling a new Producer Job at frequency " + frequency);

      // Create a job detail which is holding its frequency as a param.
      JobDetail jobDetail = JobBuilder.newJob(AsyncMockProducerJob.class)
            .usingJobData("frequency", frequency).build();

      // Create a trigger for this job, executing each 'frequency' seconds.
      Trigger trigger = TriggerBuilder.newTrigger()
            .forJob(jobDetail)
            .withIdentity(String.valueOf(frequency))
            .startNow()
            .withSchedule(
                  SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds((int)(long)frequency)
                        .repeatForever()
            )
            .build();

      try {
         quartz.scheduleJob(jobDetail, trigger);
         triggerKeys.add(trigger.getKey());
      } catch (SchedulerException e) {
         logger.error("Failure while scheduling producer job for frequency " + frequency, e);
      }
   }
}


text:
default[:accounts][:home] = "/home"
default[:accounts][:shell] = "/bin/bash"
default[:accounts][:manage_home] = true

default[:accounts][:groups] = {}
default[:accounts][:users] = {}


text:
/**
 * test/util/service-name.spec.js
 *
 * @author  Denis Luchkin-Zhou <denis@ricepo.com>
 * @license MIT
 */

const Service = dofile('./lib/service');

const ServiceName = dofile('./lib/util/service-name');

describe('serviceName(service)', function() {

  it('should normalize name of a Service', function() {
    const derived = function FooBarService() { };
    derived.prototype = new Service(this.ignis);

    const actual = ServiceName(derived);

    expect(actual)
      .to.equal('foo-bar');
  });

});


text:
#if defined(USE_TI_XML) || defined(USE_TI_NETWORK)
#import "TiDOMDocFragProxy.h"

// Corresponds to Interface DocumentFragment of DOM2 Spec
@implementation TiDOMDocFragProxy

-(id)nodeValue
{
	// DOM spec says nodeValue must return null
	return [NSNull null];
}
@end
#endif


text:
package org.softeg.slartus.forpdaplus.profile;/*
 * Created by slinkin on 17.04.2014.
 */

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import org.softeg.slartus.forpdacommon.UrlExtensions;
import org.softeg.slartus.forpdaplus.BaseFragmentActivity;
import org.softeg.slartus.forpdaplus.Client;
import org.softeg.slartus.forpdaplus.IntentActivity;
import org.softeg.slartus.forpdaplus.R;
import org.softeg.slartus.forpdaplus.classes.AlertDialogBuilder;
import org.softeg.slartus.forpdaplus.classes.ProfileMenuFragment;
import org.softeg.slartus.forpdaplus.classes.common.ExtUrl;
import org.softeg.slartus.forpdaplus.common.Log;
import org.softeg.slartus.forpdaplus.listfragments.UserReputationFragment;
import org.softeg.slartus.forpdaplus.qms.QmsNewThreadActivity;
import org.softeg.slartus.forpdaplus.search.ui.SearchActivity;
import org.softeg.slartus.forpdaplus.search.ui.SearchSettingsDialogFragment;

public class ProfileWebViewActivity extends BaseFragmentActivity {
    public static final String USER_ID_KEY = "UserIdKey";
    public static final String USER_NAME_KEY = "UserNameKey";
    public static void startActivity(Context context, String userId) {
        startActivity(context, userId, null);
    }

    public static void startActivity(Context context, String userId, String userName) {
        Intent intent = new Intent(context, ProfileWebViewActivity.class);

        intent.putExtra(USER_ID_KEY, userId);
        intent.putExtra(USER_NAME_KEY, userName);
        intent.putExtra("activity", context.getClass().toString());
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        setContentView(R.layout.simple_fragment_activity);

        try {
            Bundle extras = getIntent().getExtras();
            ProfileWebViewFragment details = new ProfileWebViewFragment();
            details.setArguments(extras);

            MenuFragment menuFragment = new MenuFragment();
            menuFragment.setArguments(extras);

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment, details).add(menuFragment, "menufragment").commit();

        } catch (Throwable e) {
            Log.e(this, e);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            super.onBackPressed();
        }

        return super.onOptionsItemSelected(item);
    }

    public static final class MenuFragment extends ProfileMenuFragment {
        private String userId;
        private String userNick;

        @Override
        public void onCreate(android.os.Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            if (savedInstanceState != null) {
                if (savedInstanceState.containsKey(USER_ID_KEY))
                    userId = savedInstanceState.getString(USER_ID_KEY);
                if (savedInstanceState.containsKey(USER_NAME_KEY))
                    userNick = savedInstanceState.getString(USER_NAME_KEY);
            }
            if (getArguments() != null) {
                if (getArguments().containsKey(USER_ID_KEY))
                    userId = getArguments().getString(USER_ID_KEY);
                if (getArguments().containsKey(USER_NAME_KEY))
                    userNick = getArguments().getString(USER_NAME_KEY);
            }
            setHasOptionsMenu(true);// важно после получения аргументов это сделать!!!
        }

        @Override
        public void onSaveInstanceState(android.os.Bundle outState) {
            outState.putString(USER_ID_KEY, userId);
            outState.putString(USER_NAME_KEY, userNick);

            super.onSaveInstanceState(outState);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            super.onCreateOptionsMenu(menu,inflater);
            MenuItem item;

            if (Client.getInstance().getLogined() && userId != null && !userId.equals(Client.getInstance().UserId)) {
                item = menu.add(getString(R.string.MessagesQms)).setIcon(R.drawable.ic_menu_send);
                item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        QmsNewThreadActivity.showUserNewThread(getActivity(), userId, userNick);

                        return true;
                    }
                });
                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            }

            item = menu.add(getString(R.string.Reputation)).setIcon(R.drawable.ic_menu_view);
            item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem menuItem) {
                    new AlertDialogBuilder(getActivity())
                            .setTitle("Репутация")
                            .setSingleChoiceItems(new CharSequence[]{"+1", "Посмотреть", "-1", "Действия с репутацией"}, -1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    switch (i) {
                                        case 0:
                                            UserReputationFragment.plusRep(getActivity(), new Handler(), userId, userNick);
                                            break;
                                        case 1:
                                            UserReputationFragment.showActivity(getActivity(),userId);
                                            break;
                                        case 2:
                                            UserReputationFragment.minusRep(getActivity(), new Handler(), userId, userNick);
                                            break;
                                        case 3:
                                            UserReputationFragment.showActivity(getActivity(), userId,true);
                                            break;
                                    }
                                    dialogInterface.dismiss();
                                }
                            })
                            .create().show();

                    return true;
                }
            });
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

            item = menu.add(getString(R.string.FindUserTopics)).setIcon(R.drawable.ic_menu_forum_search);
            item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem menuItem) {
                    SearchActivity.startForumSearch(getActivity(),
                            SearchSettingsDialogFragment.
                                    createUserTopicsSearchSettings(userNick)
                    );
                    return true;
                }
            });
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

            item = menu.add(getString(R.string.FindUserPosts)).setIcon(R.drawable.ic_menu_post_search);
            item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem menuItem) {
                    SearchActivity.startForumSearch(getActivity(),
                            SearchSettingsDialogFragment.
                                    createUserPostsSearchSettings(userNick)
                    );
                    return true;
                }
            });
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

            item = menu.add("Ссылка на профиль").setIcon(R.drawable.ic_menu_browser);
            item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem menuItem) {
                    ExtUrl.showSelectActionDialog(getActivity(),"Ссылка на профиль","http://4pda.ru/forum/index.php?showuser=" + userId);
                    return true;
                }
            });
            item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);

        }
    }

}


text:
package eu.ydp.empiria.player.client.controller.variables.processor;

import com.google.common.collect.Lists;
import eu.ydp.empiria.player.client.controller.variables.objects.response.Response;
import eu.ydp.empiria.player.client.controller.variables.processor.results.InitialProcessingResultFactory;
import eu.ydp.empiria.player.client.controller.variables.processor.results.ModulesProcessingResults;
import eu.ydp.empiria.player.client.controller.variables.processor.results.model.DtoModuleProcessingResult;
import eu.ydp.empiria.player.client.controller.variables.processor.results.model.GeneralVariables;
import org.junit.Test;

import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

public class AnswerEvaluationSupplierTest {

    private Logger LOGGER = Logger.getLogger(VariableProcessingAdapter.class.getName());

    private AnswerEvaluationSupplier supplier = new AnswerEvaluationSupplier();

    @Test
    public void evaluateAnswer() {
        // given
        final String ID = "";
        Response response = createResponse(ID);
        List<Boolean> answerEvaluations = Lists.newArrayList(true, false, true);
        ModulesProcessingResults modulesProcessingResults = prepareModulesProcessingResults(ID, answerEvaluations);
        supplier.updateModulesProcessingResults(modulesProcessingResults);

        // when
        List<Boolean> evaluation = supplier.evaluateAnswer(response);

        // then
        assertThat(evaluation).isEqualTo(answerEvaluations);
    }

    private Response createResponse(final String ID) {
        Response response = mock(Response.class);
        when(response.getID()).thenReturn(ID);
        return response;
    }

    private ModulesProcessingResults prepareModulesProcessingResults(final String ID, List<Boolean> answerEvaluations) {
        ModulesProcessingResults modulesProcessingResults = new ModulesProcessingResults(new InitialProcessingResultFactory());
        DtoModuleProcessingResult results = modulesProcessingResults.getProcessingResultsForResponseId(ID);
        results.setGeneralVariables(new GeneralVariables(Lists.<String>newArrayList(), answerEvaluations, 0, 0));
        return modulesProcessingResults;
    }

    @Test
    public void evaluateAnswer_evaluationBeforeAnswerProcessing() {
        // given
        Response response = mock(Response.class);
        Handler handler = mock(Handler.class);
        LOGGER.addHandler(handler);

        // when
        List<Boolean> evaluation = supplier.evaluateAnswer(response);

        // then
        assertThat(evaluation.isEmpty()).isTrue();
        verify(handler).publish(any(LogRecord.class));

    }

}


text:
var app;
(function (app) {
    var admin;
    (function (admin) {
        var users;
        (function (users) {
            'use strict';
            var UserController = (function () {
                function UserController() {
                }
                return UserController;
            })();
            angular.module('blogitAdmin').controller('app.admin.users.UserController', UserController);
        })(users = admin.users || (admin.users = {}));
    })(admin = app.admin || (app.admin = {}));
})(app || (app = {}));
//# sourceMappingURL=user.controller.js.map


text:
using System;
using System.Net;
using System.Text;
using Cloudsdale.Managers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Cloudsdale.Models {
    public class Ban {
        public string reason { get; set; }
        public DateTime? due;
        public DateTime? created_at;
        public DateTime? updated_at;
        public bool? revoke;
        public string id;
        public string offender_id;
        public string enforcer_id;
        public string jurisdiction_id;
        public string jurisdiction_type;
        public bool? has_expired;
        public bool? is_active;
        public bool? is_transient;

        [JsonIgnore]
        public Cloud Cloud {
            get { return PonyvilleDirectory.GetCloud(jurisdiction_id); }
        }

        [JsonIgnore]
        public User User {
            get { return PonyvilleCensus.GetUser(offender_id); }
        }

        [JsonIgnore]
        public User Issuer {
            get { return PonyvilleCensus.GetUser(enforcer_id); }
        }

        [JsonIgnore]
        public DateTime Issued {
            get { return created_at ?? DateTime.Now; }
        }

        [JsonIgnore]
        public DateTime Due {
            get { return due ?? DateTime.MaxValue; }
        }

        [JsonIgnore]
        public string Status {
            get { return is_active == true ? "Ban active" : revoke == true ? "Revoked" : "Expired"; }
        }

        [JsonIgnore]
        public bool Active {
            get { return is_active == true; }
        }

        public void Revoke(Action complete) {
            var data = Encoding.UTF8.GetBytes(JObject.FromObject(new {
                id,
                cloud_id = jurisdiction_id,
                ban = new { revoke = true }
            }).ToString());
            var request = WebRequest.CreateHttp(new Uri("http://www.cloudsdale.org/v1/clouds/" + jurisdiction_id + "/bans/" + id));
            request.Method = "PUT";
            request.ContentType = "application/json";
            request.Headers["Content-Length"] = data.Length.ToString();
            request.BeginGetRequestStream(ar => {
                using (var requestStream = request.EndGetRequestStream(ar)) {
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();
                }

                request.BeginGetResponse(arr => {
                    using (var response = request.EndGetResponse(arr)) {
                        response.Close();
                    }
                    complete();
                }, null);
            }, null);
        }
    }
}


text:
#ifndef MIDIOutput_h
#define MIDIOutput_h

#include "core/dom/DOMTypedArray.h"
#include "modules/webmidi/MIDIPort.h"

namespace blink {

class ExceptionState;
class MIDIAccess;

class MIDIOutput final : public MIDIPort {
    DEFINE_WRAPPERTYPEINFO();
public:
    static MIDIOutput* create(MIDIAccess*, unsigned portIndex, const String& id, const String& manufacturer, const String& name, const String& version, bool isActive);
    virtual ~MIDIOutput();

    void send(DOMUint8Array*, double timestamp, ExceptionState&);
    void send(Uint8Array*, double timestamp, ExceptionState&);
    void send(Vector<unsigned>, double timestamp, ExceptionState&);

    // send() without optional |timestamp|.
    void send(DOMUint8Array*, ExceptionState&);
    void send(Vector<unsigned>, ExceptionState&);

    virtual void trace(Visitor*) override;

private:
    MIDIOutput(MIDIAccess*, unsigned portIndex, const String& id, const String& manufacturer, const String& name, const String& version, bool isActive);

    unsigned m_portIndex;
};

} // namespace blink

#endif // MIDIOutput_h


text:
import numpy as np
import cv2

class DetectionAreaFilter:

    def __init__(self):
        self._lower_yellow = np.array([20, 0, 170], dtype=np.uint8)
        self._upper_yellow = np.array([55, 255, 255], dtype=np.uint8)

        self._lower_white = np.array([0, 0, 220], dtype=np.uint8)
        self._upper_white = np.array([255, 25, 255], dtype=np.uint8)

        self._ignore_mask_color = 255

    def getColorMask(self, hsv_image):
        mask_yellow = cv2.inRange(hsv_image, self._lower_yellow, self._upper_yellow)
        mask_white = cv2.inRange(hsv_image, self._lower_white, self._upper_white)

        mask = cv2.add(mask_white, mask_yellow)
        return mask

    def applyDetectionArea(self, bw_image, width_adjustment=60, height_adjustment=65):
        im_height = bw_image.shape[0]
        im_half_height = im_height // 2
        im_width = bw_image.shape[1]
        im_half_width = im_width // 2

        area_left_bottom = (0, im_height)
        area_left_top = (im_half_width - width_adjustment, im_half_height + height_adjustment)
        area_right_top = (im_half_width + width_adjustment, im_half_height + height_adjustment)
        area_right_bottom = (im_width, im_height)

        detection_area = [area_left_bottom, area_left_top, area_right_top, area_right_bottom]
        vertices = np.array([detection_area], dtype=np.int32)

        mask = np.zeros_like(bw_image)
        cv2.fillPoly(mask, vertices, self._ignore_mask_color)

        masked_image = cv2.bitwise_and(bw_image, mask)
        return masked_image


text:
package io.github.exaberries.boa.dmx.artnet;

import java.io.IOException;
import java.net.DatagramPacket;

public class ArtNetServerReciveThread extends Thread {
	private boolean running;
	private ArtNetServer server;

	public ArtNetServerReciveThread(ArtNetServer server) {
		super("server-recive");
		this.server = server;
	}

	@Override
	public void run() {
		while (running) {
			DatagramPacket packet = new DatagramPacket(null, 0);
			try {
				server.getSocket().receive(packet);
			} catch (IOException e) {
				e.printStackTrace();
			}
			server.getRecived().add(packet);
		}
	}

	public synchronized void startRunning() {
		running = true;
	}

	public synchronized void stopRunning() {
		running = false;
	}
}


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

<TITLE>
org.apache.jmeter.sampler (Apache JMeter API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.jmeter.sampler

Classes

DebugSampler

DebugSamplerBeanInfo

TestAction


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.OData.Builder;
using System.Web.OData.Builder.TestModels;
using System.Web.OData.TestCommon;
using Microsoft.OData.Edm;
using Microsoft.TestCommon.Types;

namespace System.Web.OData.Routing
{
    public class ODataRoutingModel
    {
        public static IEdmModel GetModel()
        {
            HttpConfiguration configuration = new HttpConfiguration();
            configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver());
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder(configuration);
            builder.EntitySet<RoutingCustomer>("RoutingCustomers");
            builder.EntitySet<Product>("Products");
            builder.EntitySet<SalesPerson>("SalesPeople");
            builder.EntitySet<EmailAddress>("EmailAddresses");
            builder.EntitySet<üCategory>("üCategories");
            builder.EntitySet<EnumCustomer>("EnumCustomers");
            builder.Singleton<RoutingCustomer>("VipCustomer");
            builder.Singleton<Product>("MyProduct");
            builder.EntitySet<DateTimeOffsetKeyCustomer>("DateTimeOffsetKeyCustomers");
            builder.ComplexType<Dog>();
            builder.ComplexType<Cat>();

            ActionConfiguration getRoutingCustomerById = builder.Action("GetRoutingCustomerById");
            getRoutingCustomerById.Parameter<int>("RoutingCustomerId");
            getRoutingCustomerById.ReturnsFromEntitySet<RoutingCustomer>("RoutingCustomers");

            ActionConfiguration getSalesPersonById = builder.Action("GetSalesPersonById");
            getSalesPersonById.Parameter<int>("salesPersonId");
            getSalesPersonById.ReturnsFromEntitySet<SalesPerson>("SalesPeople");

            ActionConfiguration getAllVIPs = builder.Action("GetAllVIPs");
            ActionReturnsCollectionFromEntitySet<VIP>(builder, getAllVIPs, "RoutingCustomers");

            builder.EntityType<RoutingCustomer>().ComplexProperty<Address>(c => c.Address);
            builder.EntityType<RoutingCustomer>().Action("GetRelatedRoutingCustomers").ReturnsCollectionFromEntitySet<RoutingCustomer>("RoutingCustomers");

            ActionConfiguration getBestRelatedRoutingCustomer = builder.EntityType<RoutingCustomer>().Action("GetBestRelatedRoutingCustomer");
            ActionReturnsFromEntitySet<VIP>(builder, getBestRelatedRoutingCustomer, "RoutingCustomers");

            ActionConfiguration getVIPS = builder.EntityType<RoutingCustomer>().Collection.Action("GetVIPs");
            ActionReturnsCollectionFromEntitySet<VIP>(builder, getVIPS, "RoutingCustomers");

            builder.EntityType<RoutingCustomer>().Collection.Action("GetProducts").ReturnsCollectionFromEntitySet<Product>("Products");
            builder.EntityType<VIP>().Action("GetSalesPerson").ReturnsFromEntitySet<SalesPerson>("SalesPeople");
            builder.EntityType<VIP>().Collection.Action("GetSalesPeople").ReturnsCollectionFromEntitySet<SalesPerson>("SalesPeople");

            ActionConfiguration getMostProfitable = builder.EntityType<VIP>().Collection.Action("GetMostProfitable");
            ActionReturnsFromEntitySet<VIP>(builder, getMostProfitable, "RoutingCustomers");

            ActionConfiguration getVIPRoutingCustomers = builder.EntityType<SalesPerson>().Action("GetVIPRoutingCustomers");
            ActionReturnsCollectionFromEntitySet<VIP>(builder, getVIPRoutingCustomers, "RoutingCustomers");

            ActionConfiguration getVIPRoutingCustomersOnCollection = builder.EntityType<SalesPerson>().Collection.Action("GetVIPRoutingCustomers");
            ActionReturnsCollectionFromEntitySet<VIP>(builder, getVIPRoutingCustomersOnCollection, "RoutingCustomers");

            builder.EntityType<VIP>().HasRequired(v => v.RelationshipManager);
            builder.EntityType<ImportantProduct>().HasRequired(ip => ip.LeadSalesPerson);

            // function bound to an entity
            FunctionConfiguration topProductId = builder.EntityType<Product>().Function("TopProductId");
            topProductId.Returns<int>();

            FunctionConfiguration topProductIdByCity = builder.EntityType<Product>().Function("TopProductIdByCity");
            topProductIdByCity.Parameter<string>("city");
            topProductIdByCity.Returns<string>();

            FunctionConfiguration topProductIdByCityAndModel = builder.EntityType<Product>().Function("TopProductIdByCityAndModel");
            topProductIdByCityAndModel.Parameter<string>("city");
            topProductIdByCityAndModel.Parameter<int>("model");
            topProductIdByCityAndModel.Returns<string>();

            // function bound to a collection of entities
            FunctionConfiguration topProductOfAll = builder.EntityType<Product>().Collection.Function("TopProductOfAll");
            topProductOfAll.Returns<string>();

            FunctionConfiguration topProductOfAllByCity = builder.EntityType<Product>().Collection.Function("TopProductOfAllByCity");
            topProductOfAllByCity.Parameter<string>("city");
            topProductOfAllByCity.Returns<string>();

            FunctionConfiguration topProductOfAllByCityAndModel = builder.EntityType<Product>().Collection.Function("TopProductOfAllByCityAndModel");
            topProductOfAllByCityAndModel.Parameter<string>("city");
            topProductOfAllByCityAndModel.Parameter<int>("model");
            topProductOfAllByCityAndModel.Returns<string>();

            // Function bound to the base entity type and derived entity type
            builder.EntityType<RoutingCustomer>().Function("GetOrdersCount").Returns<string>();
            builder.EntityType<VIP>().Function("GetOrdersCount").Returns<string>();

            // Overloaded function only bound to the base entity type with one paramter
            var getOrderCount = builder.EntityType<RoutingCustomer>().Function("GetOrdersCount");
            getOrderCount.Parameter<int>("factor");
            getOrderCount.Returns<string>();

            // Function only bound to the derived entity type
            builder.EntityType<SpecialVIP>().Function("GetSpecialGuid").Returns<string>();

            // Function bound to the collection of the base and the derived entity type
            builder.EntityType<RoutingCustomer>().Collection.Function("GetAllEmployees").Returns<string>();
            builder.EntityType<VIP>().Collection.Function("GetAllEmployees").Returns<string>();

            // Bound function with enum type parameters
            var boundFunction = builder.EntityType<RoutingCustomer>().Collection.Function("BoundFuncWithEnumParameters");
            boundFunction.Parameter<SimpleEnum>("SimpleEnum");
            boundFunction.Parameter<FlagsEnum>("FlagsEnum");
            boundFunction.Returns<string>();

            // Bound function with enum type parameter for attribute routing
            var boundFunctionForAttributeRouting = builder.EntityType<RoutingCustomer>().Collection
                .Function("BoundFuncWithEnumParameterForAttributeRouting");
            boundFunctionForAttributeRouting.Parameter<SimpleEnum>("SimpleEnum");
            boundFunctionForAttributeRouting.Returns<string>();

            // Unbound function with enum type parameters
            var function = builder.Function("UnboundFuncWithEnumParameters");
            function.Parameter<LongEnum>("LongEnum");
            function.Parameter<FlagsEnum>("FlagsEnum");
            function.Returns<string>();

            // Unbound function
            builder.Function("UnboundFunction").ReturnsCollection<int>().IsComposable = true;

            // Action only bound to the derived entity type
            builder.EntityType<SpecialVIP>().Action("ActionBoundToSpecialVIP");

            // Action only bound to the derived entity type
            builder.EntityType<SpecialVIP>().Collection.Action("ActionBoundToSpecialVIPs");

            // Function only bound to the base entity collection type
            builder.EntityType<RoutingCustomer>().Collection.Function("FunctionBoundToRoutingCustomers").Returns<int>();

            // Function only bound to the derived entity collection type
            builder.EntityType<VIP>().Collection.Function("FunctionBoundToVIPs").Returns<int>();

            // Bound function with multiple parameters
            var functionBoundToProductWithMultipleParamters = builder.EntityType<Product>().Function("FunctionBoundToProductWithMultipleParamters");
            functionBoundToProductWithMultipleParamters.Parameter<int>("P1");
            functionBoundToProductWithMultipleParamters.Parameter<int>("P2");
            functionBoundToProductWithMultipleParamters.Parameter<string>("P3");
            functionBoundToProductWithMultipleParamters.Returns<int>();

            // Overloaded bound function with no parameter
            builder.EntityType<Product>().Function("FunctionBoundToProduct").Returns<int>();

            // Overloaded bound function with one parameter
            builder.EntityType<Product>().Function("FunctionBoundToProduct").Returns<int>().Parameter<int>("P1");

            // Overloaded bound function with multiple parameters
            var functionBoundToProduct = builder.EntityType<Product>().Function("FunctionBoundToProduct").Returns<int>();
            functionBoundToProduct.Parameter<int>("P1");
            functionBoundToProduct.Parameter<int>("P2");
            functionBoundToProduct.Parameter<string>("P3");

            // Unbound function with one parameter
            var unboundFunctionWithOneParamters = builder.Function("UnboundFunctionWithOneParamters");
            unboundFunctionWithOneParamters.Parameter<int>("P1");
            unboundFunctionWithOneParamters.ReturnsFromEntitySet<RoutingCustomer>("RoutingCustomers");
            unboundFunctionWithOneParamters.IsComposable = true;

            // Unbound function with multiple parameters
            var functionWithMultipleParamters = builder.Function("UnboundFunctionWithMultipleParamters");
            functionWithMultipleParamters.Parameter<int>("P1");
            functionWithMultipleParamters.Parameter<int>("P2");
            functionWithMultipleParamters.Parameter<string>("P3");
            functionWithMultipleParamters.Returns<int>();

            // Overloaded unbound function with no parameter
            builder.Function("OverloadUnboundFunction").Returns<int>();

            // Overloaded unbound function with one parameter
            builder.Function("OverloadUnboundFunction").Returns<int>().Parameter<int>("P1");

            // Overloaded unbound function with multiple parameters
            var overloadUnboundFunction = builder.Function("OverloadUnboundFunction").Returns<int>();
            overloadUnboundFunction.Parameter<int>("P1");
            overloadUnboundFunction.Parameter<int>("P2");
            overloadUnboundFunction.Parameter<string>("P3");

            return builder.GetEdmModel();
        }

        public static ActionConfiguration ActionReturnsFromEntitySet<TEntityType>(ODataModelBuilder builder, ActionConfiguration action, string entitySetName) where TEntityType : class
        {
            action.NavigationSource = CreateOrReuseEntitySet<TEntityType>(builder, entitySetName);
            action.ReturnType = builder.GetTypeConfigurationOrNull(typeof(TEntityType));
            return action;
        }

        public static ActionConfiguration ActionReturnsCollectionFromEntitySet<TElementEntityType>(ODataModelBuilder builder, ActionConfiguration action, string entitySetName) where TElementEntityType : class
        {
            Type clrCollectionType = typeof(IEnumerable<TElementEntityType>);
            action.NavigationSource = CreateOrReuseEntitySet<TElementEntityType>(builder, entitySetName);
            IEdmTypeConfiguration elementType = builder.GetTypeConfigurationOrNull(typeof(TElementEntityType));
            action.ReturnType = new CollectionTypeConfiguration(elementType, clrCollectionType);
            return action;
        }

        public static EntitySetConfiguration CreateOrReuseEntitySet<TElementEntityType>(ODataModelBuilder builder, string entitySetName) where TElementEntityType : class
        {
            EntitySetConfiguration entitySet = builder.EntitySets.SingleOrDefault(s => s.Name == entitySetName);

            if (entitySet == null)
            {
                builder.EntitySet<TElementEntityType>(entitySetName);
                entitySet = builder.EntitySets.Single(s => s.Name == entitySetName);
            }
            else
            {
                builder.EntityType<TElementEntityType>();
            }
            return entitySet;
        }

        public class RoutingCustomer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public virtual List<Product> Products { get; set; }
            public Address Address { get; set; }
            public Pet Pet { get; set; }
        }

        public class EmailAddress
        {
            [Key]
            public string Value { get; set; }
            public string Text { get; set; }
        }

        public class Address
        {
            public string Street { get; set; }
            public string City { get; set; }
            public string ZipCode { get; set; }
        }

        public class Pet
        {
            public string Name { get; set; }
            public DateTimeOffset Birth { get; set; }
        }

        public class Dog : Pet
        {
            public bool CanBark { get; set; }
            public int RunSpeed { get; set; }
        }

        public class Cat : Pet
        {
            public bool CanMeow { get; set; }
            public int ClimbHeight { get; set; }
        }

        public class Product
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public virtual List<RoutingCustomer> RoutingCustomers { get; set; }
        }

        public class SalesPerson
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public virtual List<VIP> ManagedRoutingCustomers { get; set; }
            public virtual List<ImportantProduct> ManagedProducts { get; set; }
        }

        public class VIP : RoutingCustomer
        {
            public virtual SalesPerson RelationshipManager { get; set; }
            public string Company { get; set; }
        }

        public class SpecialVIP : VIP
        {
            public Guid SpecialGuid { get; set; }
        }

        public class ImportantProduct : Product
        {
            public virtual SalesPerson LeadSalesPerson { get; set; }
        }

        public class üCategory
        {
            public int ID { get; set; }
        }

        public class EnumCustomer
        {
            public int ID { get; set; }
            public Color Color { get; set; }
        }

        public class DateTimeOffsetKeyCustomer
        {
            public DateTimeOffset ID { get; set; }
        }
    }
}


text:
@class BLCUser;

@interface BLCMedia : NSObject <NSCoding>

@property (nonatomic, strong) NSString *idNumber;
@property (nonatomic, strong) BLCUser *user;
@property (nonatomic, strong) NSURL *mediaURL;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *caption;
@property (nonatomic, strong) NSArray *comments;

- (instancetype) initWithDictionary:(NSDictionary *)mediaDictionary;

@end


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

def is_test_db():
    db_name = settings.DATABASES.get('default', {}).get('NAME', '')
    return (
        True if db_name.startswith('test_') or db_name == ":memory:" else False
    )

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
    ]

    operations = [
        migrations.CreateModel(
            name='FusionRow',
            fields=[
                ('object_id', models.PositiveIntegerField()),
                ('row_id', models.PositiveIntegerField(primary_key=True, serialize=False)),
                ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
            ],
        ),
        migrations.CreateModel(
            name='FusionTable',
            fields=[
                ('table_id', models.CharField(max_length=50, primary_key=True, serialize=False)),
                ('django_model', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType', unique=True)),
            ],
        ),
        migrations.AlterUniqueTogether(
            name='fusiontable',
            unique_together=set([('django_model', 'table_id')]),
        ),
        migrations.AlterUniqueTogether(
            name='fusionrow',
            unique_together=set([('content_type', 'object_id', 'row_id'), ('content_type', 'object_id')]),
        ),
    ]

    if is_test_db():
        operations.append(
            migrations.CreateModel(
                name='SampleModel',
                fields=[
                    ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                    ('date', models.DateField()),
                    ('integer', models.PositiveSmallIntegerField()),
                    ('datetime', models.DateTimeField()),
                    ('text', models.TextField()),
                    ('char', models.CharField(max_length=50)),
                ],
            )
        )


text:
module MnoEnterprise::Concerns::Controllers::PagesController
  extend ActiveSupport::Concern
  include MnoEnterprise::ImageHelper

  #==================================================================
  # Included methods
  #==================================================================
  # 'included do' causes the included code to be evaluated in the
  # context where it is included rather than being executed in the module's context
  included do
    before_filter :authenticate_user!, only: [:launch]
    before_filter :redirect_to_lounge_if_unconfirmed, only: [:launch]
    helper_method :main_logo_white_bg_path # To use in the provision view
  end

  #==================================================================
  # Instance methods
  #==================================================================
  # GET /launch/:id
  # Redirect to Mno Enterprise app launcher
  # Launching an app (from dashboard) should redirect to this action
  # The true goal of this action is to hide maestrano in the link behind
  # any dashboard app picture
  #
  # TODO: Access + existence checks could be added in the future. This is not
  # mandatory as Mno Enterprise will do it anyway
  def launch
    app_instance = MnoEnterprise::AppInstance.find_by(uid: params[:id])
    MnoEnterprise::EventLogger.info('app_launch', current_user.id, 'App launched', app_instance)
    redirect_to MnoEnterprise.router.launch_url(params[:id], {wtk: MnoEnterprise.jwt(user_id: current_user.uid)}.reverse_merge(request.query_parameters))
  end

  # GET /loading/:id
  # Loading lounge - wait for an app to be online
  def loading
    @app_instance = MnoEnterprise::AppInstance.where(uid: params[:id]).reload.first

    respond_to do |format|
      format.html { @app_instance_hash = app_instance_hash(@app_instance) }
      format.json { render json: app_instance_hash(@app_instance) }
    end
  end

  # GET /app_access_unauthorized
  def app_access_unauthorized
    @meta[:title] = "Unauthorized"
    @meta[:description] = "Application access not granted"
  end

  def billing_details_required
    @meta[:title] = "Billing Details Required"
    @meta[:description] = "Billing details have not been provided"
  end

  # GET /app_logout
  def app_logout
    @meta[:title] = "Logged out"
    @meta[:description] = "Logged out from application"
  end

  def terms
    @meta[:title] = 'Terms of Use'
    @meta[:description] = 'Terms of Use'

    ts = MnoEnterprise::App.order_by("updated_at.desc").first.try(:updated_at)
    @apps = if ts
      Rails.cache.fetch(['pages/terms/app-list', ts]) do
        # Temp solution as translated fields can not be filtered or sorted
        # MnoEnterprise::App.order_by("name.ac").reject{|i| i.terms_url.blank?}
        MnoEnterprise::App.all.reject{ |i| i.terms_url.blank? }.sort_by{ |a| a.name.downcase }
      end
    else
      []
    end
  end

  # Error page
  def error
    handle_mnohub_error(params[:error_code])
  end

  private
    def app_instance_hash(app_instance)
      return {} unless app_instance
      {
        id: app_instance.id,
        uid: app_instance.uid,
        name: app_instance.name,
        status: app_instance.status,
        durations: app_instance.durations,
        started_at: app_instance.started_at,
        stopped_at: app_instance.stopped_at,
        created_at: app_instance.created_at,
        server_time: Time.now.utc,
        is_online: app_instance.running?,
        errors: app_instance.errors ? app_instance.errors.full_messages : [],
        logo: app_instance.app.logo
      }
    end

end


text:
FieldBarcodeView = FieldView.extend({
  type: "barcode",
  input: "<button data-field='<%= fieldId %>' class='special_button fh_appform_button_action select col-xs-12' data-index='<%= index %>'  type='<%= inputType %>'>Scan Barcode</button>" +
    "<button data-field='<%= fieldId %>' class='special_button fh_appform_button_action remove col-xs-12' data-index='<%= index %>'  type='<%= inputType %>'><i class='icon-remove-circle'></i> Remove Barcode Entry</button>" +
    "<input class='fh_appform_field_input col-xs-12' data-field='<%= fieldId %>' data-index='<%= index %>' data-bfield='text' type='text' placeholder='Barcode Value' style='margin-top:5px' disabled/>" +
    "<input class='fh_appform_field_input col-xs-12' data-field='<%= fieldId %>' data-index='<%= index %>' data-bfield='format' type='text' placeholder='Barcode Format' style='margin-top:5px' disabled/>",
  initialize: function() {
    var self = this;

    self.barcodeObjects = [];
    FieldView.prototype.initialize.apply(self, arguments);
  },
  contentChanged: function(e) {
    var self = this;
    e.preventDefault();
    var inputTarget = $(e.target);
    var index = inputTarget.data('index');
    var wrapperObj = self.getWrapper(index);
    var barcodeTextEle = wrapperObj.find("input[data-bfield='text']");
    var barcodeFormatEle = wrapperObj.find("input[data-bfield='format']");
    var sectionIndex = self.options.sectionIndex;

    var result = {
      text: barcodeTextEle.val(),
      format: barcodeFormatEle.val()
    };

    //Dont need to do anything when the content changes.
    self.barcodeObjects[index] = result;

    self.updateOrRemoveValue({
      fieldId: self.model.getFieldId(),
      index: index,
      value: result,
      isStore: true,
      sectionIndex:sectionIndex
    }, function() {
      self.validateElement(index, result);
      self.checkRules();
    });
  },
  valueFromElement: function(index) {
    var self = this;
    return self.barcodeObjects[index] || {};
  },
  showButton: function(index, barcodeObject) {
    var self = this;
    var wrapperObj = self.getWrapper(index);
    var button = wrapperObj.find("button.select");
    var button_remove = wrapperObj.find("button.remove");

    var barcodeTextEle = wrapperObj.find("input[data-bfield='text']");
    var barcodeFormatEle = wrapperObj.find("input[data-bfield='format']");

    //If it is not a phonegap application, then the scan barcode button should not be shown
    if(!self.model.utils.isPhoneGapCamAvailable()){
      //Show the input text fields only instead. The user is allowed to enter values manually.
      wrapperObj.find("input[data-bfield='text']").attr("disabled", false);
      wrapperObj.find("input[data-bfield='format']").attr("disabled", false);
      button.text("Barcode Scanning Not Available");
      button.attr('disabled', true);
      button_remove.hide();
      return;
    }

    button.show();

    if (barcodeObject == null) {
      button_remove.hide();
    } else {
      barcodeTextEle.val(barcodeObject.text);
      barcodeFormatEle.val(barcodeObject.format);
      button_remove.show();
    }

    if (this.readonly) {
      button.hide();
      button_remove.hide();
    }

    button_remove.off('click');

    button_remove.on('click', function(e){
      var index = $(e.target).data('index');
      self.removeBarcode(index);
    });

    button.off('click');

    if(self.model.utils.isPhoneGapCamAvailable()){
      button.on('click', function(e) {
        self.scanBarcode(e, index);
      });
    }
  },
  removeBarcode: function(index){
    var self = this;

    if(typeof(index) === "number"){
      self.barcodeObjects[index] = null;
      var wrapperObj = self.getWrapper(index);
      wrapperObj.find("input[data-bfield='text']").val("");
      wrapperObj.find("input[data-bfield='format']").val("");
      self.showButton(index, null);
    } else {
      $fh.forms.log.e("Error: No index when removing barcode element");
    }
  },
  //Scanning a barcode from the device.
  scanBarcode: function(e, index){
    var self = this;
    $fh.forms.log.d("Scanning barcode");

    //Capturing a barcode using a phonegap plugin.
    function phonegapBarcode(){
      self.model.utils.captureBarcode({}, function(err, result){
        if(err){
          $fh.forms.log.e("Error scanning barcode: " + err);
          self.showButton(index, null);
        } else if(result.text && result.format){
          $fh.forms.log.d("Got Barcode Result: " + JSON.stringify(result));
          self.barcodeObjects[index] = {
            text: result.text.toString(),
            format: result.format.toString()
          };

          self.showButton(index,  self.barcodeObjects[index]);
        } else {
          $fh.forms.log.d("Barcode Scan Cancelled: " + JSON.stringify(result));
          self.showButton(index, null);
        }
      });
    }

    //Capturing a barcode using a webcam and processing
    function webBarcode(){

      //Web barcode decoding is not currently supported.
      //Using A Navigator Alert If Available.
      $fh.forms.backbone.alert("Barcode Decoding Only Available On-Device");

      $fh.forms.log.e("Web barcode decoding not currently supported");
    }

    //Checking for phonegap. This will try to use the plugin if it is available.
    if(self.model.utils.isPhoneGapCamAvailable()){
      phonegapBarcode();
    } else {
      webBarcode();
    }
  },
  valuePopulateToElement: function(index, value) {
    var self = this;
    if (value) {
      self.barcodeObjects[index] = value;
      self.showButton(index, value);
    }
  },
  onElementShow: function(index) {
    this.showButton(index, null);
  }
});


text:
package uk.co.gdickinson.smarthome.lambda.models;

import com.google.gson.annotations.SerializedName;

public enum ApplianceType {
  @SerializedName("CAMERA")
  CAMERA,

  @SerializedName("LIGHT")
  LIGHT,

  @SerializedName("SMARTLOCK")
  SMARTLOCK,

  @SerializedName("SMARTPLUG")
  SMARTPLUG,

  @SerializedName("SWITCH")
  SWITCH,

  @SerializedName("THERMOSTAT")
  THERMOSTAT,

  @SerializedName("ACTIVITY_TRIGGER")
  ACTIVITY_TRIGGER,

  @SerializedName("SCENE_TRIGGER")
  SCENE_TRIGGER
}


text:
require "json"
require "net/http"
require "socket"

module Helios
  HOSTNAME = Socket.gethostname
end

class Helios::Event
  attr_accessor :hostname, :timestamp, :event_type, :args
end

class Helios::AbstractClient
  def initialize
    @queue = Queue.new
    @started = false
    @thread = nil
  end

  def record_event(event)
    puts "enqueuing..."
    puts "thread: #{@thread}"
    @queue.push(event)
    @thread.run
  end

  def qsize
    @queue.size
  end

  def retry_event(event)
    # Copying the python client for now which has a comment here talking
    # about long term changes.
    record_event(event)
  end

  def record(kwargs)
    raise "pls to be providing :event kwargs" if kwargs[:event_type].nil?
    kwargs = kwargs.clone

    event = Helios::Event.new
    event.hostname = Helios::HOSTNAME
    event.timestamp = Time.now
    event.event_type = kwargs.delete(:event_type)
    event.args = kwargs
    puts "delegating to record_event"
    record_event(event)
  end

  def process_queue
    puts "process_queue"
    loop do
      puts "Waiting on queue..."
      event = @queue.pop
      puts "Got an event: #{event}"
      retry_event(event) if not process_event(event)
    end
  end

  def process_event(event)
    # must be implemented by subclasses
    raise NotImplementedError
  end

  def start
    return false if @started
    @started = true

    puts "Starting..."
    Thread.abort_on_exception = true
    @thread = Thread.new { process_queue }
    puts "after thread new: #{@thread.alive?} #{@queue.num_waiting}"
    puts "[after] thread: #{@thread}"
    # How do we make it a daemon? Do we even want to do that?  See the
    # abstractclient in python for more discussion.
    return true
  end
end

class Helios::AbstractHTTPClient < Helios::AbstractClient
  def build_url_and_data(event)
    url = build_url
    data = build_data(event)
    return url, data
  end

  private

  def build_url
    # TODO: Configurize
    return "http://localhost:2112/event/create"
  end

  def build_data(event)
    data = {
      "h" => event.hostname,
      "ts" => event.timestamp,
      "type" => event.event_type,
      "args" => event.args}
    return JSON.generate(data)
  end
end

class Helios::Client < Helios::AbstractHTTPClient
  def process_event(event)
    puts "Processing event #{event}"
    url, data = self.build_url_and_data(event)
    url = URI.parse(url)
    headers = {"Content-Type" => "application/json"}
    Net::HTTP.new(url.host, url.port).post(url.path, data, headers)
  end
end

module Helios
  CLIENT = Helios::Client.new
  CLIENT.start
end


text:
#import "SXGooglePlusUtil.h"
#import <GooglePlus/GooglePlus.h>
//#import <GTMOAuth2Authentication.h>
#import <GoogleOpenSource/GoogleOpenSource.h>

@interface SXGooglePlusSignInDelegate : NSObject <GPPSignInDelegate>
@property (nonatomic, weak) id<GPPSignInDelegate> previousDelegate;
@property (nonatomic, strong) NSArray *previousScope;
@property (nonatomic, strong) void(^callback)(NSString *accessToken, NSError *error);
- (void) restore;
@end

static SXGooglePlusSignInDelegate *delegate = nil;

@implementation SXGooglePlusUtil
+ (void) initialize
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        delegate = [[SXGooglePlusSignInDelegate alloc] init];
    });
}
+ (BOOL) isGooglePlusAvailable
{
    // Is SDK installed ?
    if (!NSClassFromString(@"GPPSignIn")) {
        return NO;
    }

    Class cls = NSClassFromString(@"GPPSignIn");
    id signIn = [cls sharedInstance];
    NSString *appId = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"GooglePlusAppID"];
    if ([signIn clientID] == nil && appId != nil) {
        [signIn setClientID:appId];
    }
    return appId != nil;
}

+ (void) login:(void(^)(NSString *accessToken, NSError *error))callback
{
    if (![self isGooglePlusAvailable])
        return;

    Class cls = NSClassFromString(@"GPPSignIn");
    id signIn = [cls sharedInstance];
    delegate.previousScope = [signIn scopes];
    delegate.previousDelegate = [signIn delegate];
    delegate.callback = callback;
    [signIn setDelegate:delegate];
    [signIn setScopes:@[GOOGLE_SCOPE_LOGIN, GOOGLE_SCOPE_EMAIL]];
    [signIn authenticate];
}

+ (void) logout
{
    if (![self isGooglePlusAvailable])
        return;

    Class cls = NSClassFromString(@"GPPSignIn");
    id signIn = [cls sharedInstance];
    [signIn signOut];
}

+ (BOOL) shareUrl:(NSString *) text url:(NSString*) url {
    if (![self isGooglePlusAvailable])
        return NO;
    [self login:^(NSString *accessToken, NSError *error) {
        Class sharer = NSClassFromString(@"GPPShare");

        id share = [sharer sharedInstance];
        id shareBuilder = [share nativeShareDialog];
        NSURL *urlToShare = [NSURL URLWithString:url];
        [shareBuilder setPrefillText:text];
        [shareBuilder setURLToShare:urlToShare];
        objc_msgSend(shareBuilder, @selector(open));
    }];
    return YES;
}

+ (BOOL) sendInvitation:(NSString *)text friends:(NSArray *) friends url:(NSString *)url deepLinkPath:(NSString *)deepLink {
    if (![self isGooglePlusAvailable])
        return NO;
    [self login:^(NSString *accessToken, NSError *error) {
        Class sharer = NSClassFromString(@"GPPShare");

        id share = [sharer sharedInstance];
        id shareBuilder = [share nativeShareDialog];
        NSURL *urlToShare;
        if (url != nil) {
            urlToShare = [NSURL URLWithString:url];
        } else {
            urlToShare = nil;
        }

        [shareBuilder setPrefillText:text];
        [shareBuilder setContentDeepLinkID:deepLink];
        if (urlToShare != nil) {
            [shareBuilder setURLToShare:urlToShare];
            [shareBuilder setCallToActionButtonWithLabel:@"ACCEPT" URL:urlToShare deepLinkID:deepLink];
        }

        if (friends != nil) {
            [shareBuilder setPreselectedPeopleIDs:friends];
        }

        objc_msgSend(shareBuilder, @selector(open));
    }];
    return YES;
}

+ (BOOL) handleURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (![self isGooglePlusAvailable])
        return NO;
    Class urlHandler = NSClassFromString(@"GPPURLHandler");
    return [urlHandler handleURL:url
                  sourceApplication:sourceApplication
                         annotation:annotation];

}
@end

@implementation SXGooglePlusSignInDelegate

- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
                   error:(NSError *)error
{
    if (self.callback)
        self.callback(auth.accessToken, error);
    [self restore];

}

- (void)didDisconnectWithError:(NSError *)error
{
    if (self.callback)
        self.callback(nil, error);
    [self restore];
}

- (void) restore
{
    Class cls = NSClassFromString(@"GPPSignIn");
    id signIn = [cls sharedInstance];
    [signIn setDelegate:self.previousDelegate];
    [signIn setScopes:self.previousScope];
}
@end


text:
import { JiraSharkPage } from './app.po';

describe('jira-shark App', () => {
  let page: JiraSharkPage;

  beforeEach(() => {
    page = new JiraSharkPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!!');
  });
});


text:
require 'Class'

local function getPropName( p )
	return p.name or ''
end
local function setPropName( p, n )
	p.name = n
end

Model( MOAIProp, 'MOAIProp' ):update{
	Field 'name' : type('string') :get( getPropName ) :set( setPropName )
}