text:
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

#include <php.h>

#include "php_leaver.h"
#include "Logger.h"

zend_array *leaver_logger_get_appenders(zval *logger)
{
    zend_array *appenders;
    zval *z_appenders;

    z_appenders = zend_read_property(leaver_logger_ce, logger, ZEND_STRL("appenders"), 1, NULL);

    if (Z_TYPE_P(z_appenders) == IS_ARRAY) {
        appenders = Z_ARR_P(z_appenders);
    } else {
        ALLOC_HASHTABLE(appenders);
        zend_hash_init(appenders, 4, NULL, ZVAL_PTR_DTOR, 0);

        ZVAL_ARR(z_appenders, appenders);

        zend_update_property(leaver_logger_ce, logger, ZEND_STRL("appenders"), z_appenders);
    }

    return appenders;
}

char *leaver_logger_message_replace(char *msg, size_t msg_len, zend_string *search, zend_string *replace)
{
    char *search_str;
    size_t search_len;
    char *start, *tmp, *result;
    size_t result_len;
    const char *found;

    search_len = search->len + 2;
    search_str = emalloc(search_len + 1);
    search_str[0] = '{';
    strcpy(search_str + 1, search->val);
    search_str[search_len - 1] = '}';
    search_str[search_len] = '\0';

    result = msg;
    result_len = msg_len;
    start = result;

    while ((found = php_memnstr(start, search_str, search_len, result + result_len))) {
        // New length.
        result_len = result_len + replace->len - search_len;
        tmp = emalloc(result_len + 1);

        strncpy(tmp, result, found - result);
        tmp[found - result] = '\0';
        strcat(tmp, replace->val);
        strcat(tmp, found + search_len);

        start = tmp + (found - result) + replace->len;
        result = tmp;
    }

    efree(search_str);

    return result != msg ? result : NULL;
}

// Replaces placeholders with values from the context array.
zend_string *leaver_logger_format_message(zend_string *message, zend_array *context)
{
    zend_string *key;
    zval *z_value;
    zend_string *result;
    char *str, *tmp;

    if (0 == message->len) {
        zend_interned_empty_string_init(&result);
        return result;
    }

    // Duplicates the message string for repeated replacement.
    str = estrdup(message->val);

    ZEND_HASH_FOREACH_STR_KEY_VAL(context, key, z_value) {
        if (key && 0 != strcasecmp(key->val, "exception")) {
            zend_string *value = zval_get_string(z_value);

            tmp = leaver_logger_message_replace(str, strlen(str), key, value);
            if (tmp) {
                efree(str);
                str = tmp;
            }

            zend_string_release(value);
        }
    } ZEND_HASH_FOREACH_END();

    result = zend_string_init(str, strlen(str), 0);
    efree(str);

    return result;
}

void leaver_logger_log(zend_array *appenders, zend_long level, zend_string *message, zend_array *context)
{
    zval *z_appender, *z_exception = NULL;
    zval retval;
    zval is_enable_params[1], append_params[3];
    zend_function *func_append = NULL;

    if (context) {
        message = leaver_logger_format_message(message, context);
        z_exception = zend_hash_str_find(context, ZEND_STRL("exception"));
    } else {
        zend_string_addref(message);
    }

    ZVAL_LONG(&is_enable_params[0], level);
    ZVAL_LONG(&append_params[0], level);
    ZVAL_STR(&append_params[1], message);
    if (z_exception) {
        ZVAL_COPY(&append_params[2], z_exception);
    } else {
        ZVAL_NULL(&append_params[2]);
    }

    ZEND_HASH_FOREACH_VAL(appenders, z_appender) {
                leaver_call_method_with_params(z_appender, "append", 3, append_params, &retval, &func_append);
            } ZEND_HASH_FOREACH_END();

    zval_ptr_dtor(&append_params[1]);
    zval_ptr_dtor(&append_params[2]);

    if (Z_TYPE(retval) != IS_UNDEF) {
        zval_ptr_dtor(&retval);
    }
}

void leaver_logger_common_method(INTERNAL_FUNCTION_PARAMETERS, zend_long level)
{
    zval *this = getThis();
    zend_string *message;
    zend_array *context = NULL;
    zend_array *appenders;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S|h", &message, &context)) {
        return;
    }

    appenders = leaver_logger_get_appenders(this);

    leaver_logger_log(appenders, level, message, context);
}

zend_class_entry *leaver_logger_ce;

// public \Leaver\Logger::addAppender(\Leaver\Appender $appender) : void
ZEND_BEGIN_ARG_INFO_EX(leaver_logger_addAppender_arginfo, 0, 0, 1)
    ZEND_ARG_OBJ_INFO(0, appender, Leaver\\Appender, 0)
ZEND_END_ARG_INFO()

PHP_METHOD(leaver_logger, addAppender)
{
    zval *this = getThis();
    zval *z_appender;
    zval z_appender_name;
    zend_array *appenders;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "z", &z_appender)) {
        return;
    }

    leaver_call_method_without_params(z_appender, "getname", &z_appender_name, NULL);

    Z_ADDREF_P(z_appender);

    appenders = leaver_logger_get_appenders(this);

    if (Z_TYPE(z_appender_name) == IS_STRING) {
        // Use string key.
        zend_hash_update(appenders, Z_STR(z_appender_name), z_appender);
    } else {
        // Use index.
        zend_hash_next_index_insert(appenders, z_appender);
    }
}

ZEND_BEGIN_ARG_INFO_EX(leaver_logger_common_logs_arginfo, 0, 0, 1)
    ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
    ZEND_ARG_ARRAY_INFO(0, context, 1)
ZEND_END_ARG_INFO()

// public \Leaver\Logger::debug(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, debug)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_DEBUG_INT);
}

// public \Leaver\Logger::info(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, info)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_INFO_INT);
}

// public \Leaver\Logger::notice(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, notice)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_DEBUG_INT);
}

// public \Leaver\Logger::warning(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, warning)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_DEBUG_INT);
}

// public \Leaver\Logger::error(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, error)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_DEBUG_INT);
}

// public \Leaver\Logger::critical(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, critical)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_CRITICAL_INT);
}

// public \Leaver\Logger::alert(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, alert)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_ALERT_INT);
}

// public \Leaver\Logger::emergency(string $message, array $context = NULL) : void
PHP_METHOD(leaver_logger, emergency)
{
    leaver_logger_common_method(INTERNAL_FUNCTION_PARAM_PASSTHRU, LEAVER_LEVEL_EMERGENCY_INT);
}

// public \Leaver\Logger::log(int $level, string $message, array $context = NULL) : void
ZEND_BEGIN_ARG_INFO_EX(leaver_logger_log_arginfo, 0, 0, 1)
    ZEND_ARG_TYPE_INFO(0, level, IS_LONG, 0)
    ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
    ZEND_ARG_ARRAY_INFO(0, context, 1)
ZEND_END_ARG_INFO()

PHP_METHOD(leaver_logger, log)
{
    zval *this = getThis();
    zend_long level;
    zend_string *message;
    zend_array *context = NULL;
    zend_array *appenders;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "lS|h", &level, &message, &context)) {
        return;
    }

    appenders = leaver_logger_get_appenders(this);

    leaver_logger_log(appenders, level, message, context);
}

zend_function_entry leaver_logger_methods[] = {
    PHP_ME(leaver_logger, addAppender, leaver_logger_addAppender_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, debug, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, info, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, notice, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, warning, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, error, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, critical, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, alert, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, emergency, leaver_logger_common_logs_arginfo, ZEND_ACC_PUBLIC)
    PHP_ME(leaver_logger, log, leaver_logger_log_arginfo, ZEND_ACC_PUBLIC)
    PHP_FE_END
};

LEAVER_CREATE_FUNCTION(logger)
{
    zend_class_entry ce;

    INIT_CLASS_ENTRY(ce, "Leaver\\Logger", leaver_logger_methods);
    leaver_logger_ce = zend_register_internal_class_ex(&ce, NULL);

    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_ALL), LEAVER_LEVEL_ALL_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_DEBUG), LEAVER_LEVEL_DEBUG_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_INFO), LEAVER_LEVEL_INFO_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_NOTICE), LEAVER_LEVEL_NOTICE_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_WARNING), LEAVER_LEVEL_WARNING_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_ERROR), LEAVER_LEVEL_ERROR_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_CRITICAL), LEAVER_LEVEL_CRITICAL_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_ALERT), LEAVER_LEVEL_ALERT_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_EMERGENCY), LEAVER_LEVEL_EMERGENCY_INT);
    zend_declare_class_constant_long(leaver_logger_ce, ZEND_STRL(LEAVER_LEVEL_OFF), LEAVER_LEVEL_OFF_INT);

    zend_declare_property_null(leaver_logger_ce, ZEND_STRL("appenders"), ZEND_ACC_PRIVATE);

    return SUCCESS;
}


text:
<?php

namespace Che\LogStock\Tests;

use Che\LogStock\LoggerFactoryBuilder;
use Che\LogStock\LoggerManager;
use PHPUnit_Framework_TestCase as TestCase;

/**
 * Tests for LoggerManager
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 */
class LoggerManagerTest extends TestCase
{
    /**
     * @test if no factory was set a default factory is created with builder
     */
    public function defaultFactory()
    {
        $builder = new LoggerFactoryBuilder();

        $this->assertEquals($builder->build(), LoggerManager::getFactory());
    }

    /**
     * @test logger manager use logger from factory
     */
    public function loggerFromFactory()
    {
        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $factory = $this->getMock('Che\LogStock\Factory\LoggerFactory');
        $factory->expects($this->once())->method('getLogger')->with('_name_')->will($this->returnValue($logger));

        LoggerManager::registerFactory($factory);
        $this->assertEquals($logger, LoggerManager::getLogger('_name_'));
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Module contains ignite version utility class.
"""
import re
from distutils.version import LooseVersion

from ignitetest import __version__

class IgniteVersion(LooseVersion):
    """
    Container for Ignite versions which makes versions simple to compare.

    distutils.version.LooseVersion (and StrictVersion) has robust comparison and ordering logic.

    Example:

        v27 = IgniteVersion("2.7.0")
        v28 = IgniteVersion("2.8.1")
        assert v28 > v27  # assertion passes!
    """

    DEV_VERSION = "dev"
    DEFAULT_PROJECT = "ignite"

    def __init__(self, vstring=None):
        if vstring == self.DEV_VERSION:
            self.project = self.DEFAULT_PROJECT
            version = vstring
        else:
            match = re.match(r'([a-zA-Z]*)-*([\d(dev)]+.*)', vstring)
            self.project = self.DEFAULT_PROJECT if not match.group(1) else match.group(1)
            version = match.group(2)

        self.is_dev = (version.lower() == __version__.lower()) or version == self.DEV_VERSION

        if self.is_dev:
            version = __version__  # we may also parse pom file to gain correct version (in future)

        super().__init__(version)

    def __str__(self):
        return "%s-%s" % (self.project, "dev" if self.is_dev else super().__str__())

    def _cmp(self, other):
        if isinstance(other, str):
            other = IgniteVersion(other)

        # todo solve comparability issues and uncomment the following
        # if self.project != other.project:
        #     raise Exception("Incomperable versons v1=%s, v2=%s because of different projects" % (self, other))

        return super()._cmp(other)

    def __repr__(self):
        return "IgniteVersion ('%s')" % str(self)

DEV_BRANCH = IgniteVersion(__version__)

# 2.7.x versions
V_2_7_6 = IgniteVersion("2.7.6")
LATEST_2_7 = V_2_7_6

# 2.8.x versions
V_2_8_0 = IgniteVersion("2.8.0")
V_2_8_1 = IgniteVersion("2.8.1")
LATEST_2_8 = V_2_8_1

# 2.9.x versions
V_2_9_0 = IgniteVersion("2.9.0")
V_2_9_1 = IgniteVersion("2.9.1")
LATEST_2_9 = V_2_9_1

# 2.10.x versions
V_2_10_0 = IgniteVersion("2.10.0")
LATEST_2_10 = V_2_10_0

# 2.11.x versions
V_2_11_0 = IgniteVersion("2.11.0")
V_2_11_1 = IgniteVersion("2.11.1")
LATEST_2_11 = V_2_11_1

# 2.12.x versions
V_2_12_0 = IgniteVersion("2.12.0")
LATEST_2_12 = V_2_12_0

# 2.13.x versions
V_2_13_0 = IgniteVersion("2.13.0")
LATEST_2_13 = V_2_13_0

# if you updated the LATEST version
# please check DEV version in 'tests/ignitetest/__init__.py'
LATEST = LATEST_2_13
OLDEST = V_2_7_6


text:
<?php
namespace Inventory\Infrastructure\Doctrine;

use Application\Entity\NmtInventoryItem;
use Application\Infrastructure\AggregateRepository\AbstractDoctrineRepository;
use Inventory\Domain\Item\BaseItem;
use Inventory\Domain\Item\GenericItem;
use Inventory\Domain\Item\ItemSnapshot;
use Inventory\Domain\Item\Component\BaseComponent;
use Inventory\Domain\Item\Repository\ItemCmdRepositoryInterface;
use Inventory\Domain\Item\Repository\ItemComponentCmdRepositoryInterface;
use Inventory\Domain\Item\Repository\ItemVariantCmdRepositoryInterface;
use Inventory\Domain\Item\Variant\BaseVariant;
use Inventory\Domain\Item\Variant\BaseVariantAttribute;
use Inventory\Infrastructure\Mapper\ItemMapper;
use Webmozart\Assert\Assert;
use InvalidArgumentException;

/**
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class ItemCmdRepositoryImpl extends AbstractDoctrineRepository implements ItemCmdRepositoryInterface
{

    const ROOT_ENTITY_NAME = "\Application\Entity\NmtInventoryItem";

    private $itemVariantRepository;

    private $itemComponentRepository;

    /*
     * |=============================
     * | Delegation
     * |
     * |=============================
     */

    // +++++++++++++++++++++
    // Component
    // +++++++++++++++++++++
    public function storeComponentCollection(GenericItem $rootEntity, $generateSysNumber = True)
    {
        $this->assertItemComponentRepository();
        return $this->getItemComponentRepository()->storeComponentCollection($rootEntity, $generateSysNumber);
    }

    public function storeComponenent(GenericItem $rootEntity, BaseComponent $localEntity, $generateSysNumber = True)
    {
        $this->assertItemComponentRepository();
        return $this->getItemComponentRepository()->storeComponenent($rootEntity, $localEntity, $generateSysNumber);
    }

    public function removeComponent(GenericItem $rootEntity, BaseComponent $localEntity, $isPosting = false)
    {
        $this->assertItemComponentRepository();
        return $this->getItemComponentRepository()->removeComponent($rootEntity, $localEntity);
    }

    // +++++++++++++++++++++
    // Variant
    // +++++++++++++++++++++

    /**
     *
     * {@inheritdoc}
     * @see \Inventory\Domain\Item\Repository\ItemVariantCmdRepositoryInterface::storeVariantCollection()
     */
    public function storeVariantCollection(GenericItem $rootEntity, $generateSysNumber = True)
    {
        $this->assertItemVariantRepository();
        return $this->getItemVariantRepository()->storeVariantCollection($rootEntity);
    }

    public function storeWholeVariant(GenericItem $rootEntity, BaseVariant $localEntity, $generateSysNumber = True)
    {
        $this->assertItemVariantRepository();
        return $this->getItemVariantRepository()->storeWholeVariant($rootEntity, $localEntity, $generateSysNumber);
    }

    public function storeVariant(GenericItem $rootEntity, BaseVariant $localEntity, $generateSysNumber = True)
    {
        $this->assertItemVariantRepository();
        return $this->getItemVariantRepository()->storeVariant($rootEntity, $localEntity, $generateSysNumber);
    }

    public function storeAttribute(BaseVariant $rootEntity, $localEntity, $generateSysNumber = True)
    {
        $this->assertItemVariantRepository();
        return $this->getItemVariantRepository()->storeAttribute($rootEntity, $localEntity, $generateSysNumber);
    }

    public function removeAttribute(BaseVariant $rootEntity, BaseVariantAttribute $localEntity, $isPosting = false)
    {
        $this->assertItemVariantRepository();
        return $this->getItemVariantRepository()->removeAttribute($rootEntity, $localEntity);
    }

    /*
     * |=============================
     * | Item
     * |
     * |=============================
     */

    /**
     *
     * {@inheritdoc}
     * @see \Inventory\Domain\Item\Repository\ItemCmdRepositoryInterface::store()
     */
    public function store(GenericItem $rootEntity, $generateSysNumber = True)
    {
        Assert::notNull($rootEntity, "GenericItem not retrieved.");
        $rootSnapshot = $this->_getRootSnapshot($rootEntity);

        $increaseVersion = false;

        /**
         *
         * @var \Application\Entity\NmtInventoryItem $entity ;
         *
         */
        if ($rootEntity->getId() > 0) {
            $entity = $this->getDoctrineEM()->find(self::ROOT_ENTITY_NAME, $rootEntity->getId());
            if ($entity == null) {
                throw new InvalidArgumentException(sprintf("Doctrine entity not found. %s", $rootEntity->getId()));
            }

            // just in case, it is not updated.
            if ($entity->getToken() == null) {
                $entity->setToken($entity->getUuid());
            }

            $increaseVersion = true;
        } else {
            $rootClassName = self::ROOT_ENTITY_NAME;
            $entity = new $rootClassName();
        }

        // Populate with data
        $entity = ItemMapper::mapSnapshotEntity($this->getDoctrineEM(), $rootSnapshot, $entity);

        if ($generateSysNumber) {
            $entity->setSysNumber($this->generateSysNumber($entity));
        }

        if ($increaseVersion) {
            // Optimistic Locking
            if ($rootSnapshot->getId() > 0) {
                $entity->setRevisionNo($entity->getRevisionNo() + 1);
            }
        }

        $this->doctrineEM->persist($entity);
        $this->doctrineEM->flush();

        $rootSnapshot->id = $entity->getId();
        $rootSnapshot->sysNumber = $entity->getSysNumber();
        return $rootSnapshot;
    }

    /*
     * |=================================
     * | Assert underlying repository
     * |
     * |==================================
     */
    private function assertItemVariantRepository()
    {
        if ($this->getItemVariantRepository() == null) {
            throw new InvalidArgumentException("Item Variant repository is not found!");
        }
    }

    private function assertItemComponentRepository()
    {
        if ($this->getItemComponentRepository() == null) {
            throw new InvalidArgumentException("Item Component repository is not found!");
        }
    }

    /**
     *
     * {@inheritdoc}
     * @see \Inventory\Domain\Item\Repository\ItemCmdRepositoryInterface::getItemComponentRepository()
     */
    public function getItemComponentRepository()
    {
        if ($this->itemComponentRepository == null) {
            throw new InvalidArgumentException("Item Component repository is not found!");
        }
        return $this->itemComponentRepository;
    }

    /**
     *
     * @return \Inventory\Domain\Item\Repository\ItemVariantCmdRepositoryInterface
     */
    public function getItemVariantRepository()
    {
        if ($this->itemVariantRepository == null) {
            throw new InvalidArgumentException("Item Variant repository is not found!");
        }
        return $this->itemVariantRepository;
    }

    /*
     * |=================================
     * | Setter and getter
     * |
     * |==================================
     */

    /**
     *
     * @param BaseItem $rootEntity
     * @throws InvalidArgumentException
     * @return \Application\Entity\NmtInventoryItem|object|NULL
     */
    private function assertAndReturnItem(BaseItem $rootEntity)
    {
        if ($rootEntity == null) {
            throw new InvalidArgumentException("BaseCompany not given.");
        }

        $rootEntityDoctrine = $this->getDoctrineEM()->find(self::ROOT_ENTITY_NAME, $rootEntity->getId());

        if (! $rootEntityDoctrine instanceof NmtInventoryItem) {
            throw new InvalidArgumentException("Doctrine root entity not given!");
        }

        return $rootEntityDoctrine;
    }

    /**
     *
     * @param GenericItem $rootEntity
     * @throws InvalidArgumentException
     * @return \Inventory\Domain\Item\ItemSnapshot
     */
    private function _getRootSnapshot(GenericItem $rootEntity)
    {
        /**
         *
         * @var ItemSnapshot $rootSnapshot ;
         */
        $rootSnapshot = $rootEntity->makeSnapshot();
        if (! $rootSnapshot instanceof ItemSnapshot) {
            throw new InvalidArgumentException("Root snapshot not created!");
        }

        return $rootSnapshot;
    }

    /**
     *
     * @param ItemVariantCmdRepositoryInterface $itemVariantRepository
     */
    public function setItemVariantRepository(ItemVariantCmdRepositoryInterface $itemVariantRepository)
    {
        $this->itemVariantRepository = $itemVariantRepository;
    }

    /**
     *
     * @param ItemComponentCmdRepositoryInterface $itemComponentRepository
     */
    public function setItemComponentRepository(ItemComponentCmdRepositoryInterface $itemComponentRepository)
    {
        $this->itemComponentRepository = $itemComponentRepository;
    }
}


text:
(function() {
  'use strict';

  Polymer({
    is: 'extensions-drop-overlay',
    created: function() {
      this.hidden = true;
      if (loadTimeData.getBoolean('offStoreInstallEnabled'))
        return;
      var dragTarget = document.documentElement;
      this.dragWrapperHandler_ =
          new extensions.DragAndDropHandler(true, dragTarget);
      dragTarget.addEventListener('extension-drag-started', function() {
        this.hidden = false;
      }.bind(this));
      dragTarget.addEventListener('extension-drag-ended', function() {
        this.hidden = true;
      }.bind(this));
      this.dragWrapper_ =
          new cr.ui.DragWrapper(dragTarget, this.dragWrapperHandler_);
    },
  });
})();


text:
ImageStorage

Resource that shows how much storage a registered DLCS Image uses.

/customers/{0}/spaces/{1}/images/{2}/storage

Supported operations

Method	Label	Expects	Returns	Statuses

GET	Retrieve a Image Storage		vocab:ImageStorage	200 OK, 404 Not found

Supported properties

thumbnailSize

Storage space taken up by this item's thumbnails

domain	range	readonly	writeonly

vocab:ImageStorage	xsd:nonNegativeInteger	True	False

size

Storage space taken up by the DLCS artifacts for this item

domain	range	readonly	writeonly

vocab:ImageStorage	xsd:nonNegativeInteger	True	False

lastChecked

When these figures were last computed

domain	range	readonly	writeonly

vocab:ImageStorage	xsd:dateTime	True	False

checkingInProgress

If a computation of these figures is currently running

domain	range	readonly	writeonly

vocab:ImageStorage	xsd:boolean	True	False


text:
namespace OpenProtocolInterpreter.PLCUserData
{
    /// <summary>
    /// User data unsubscribe
    /// <para>Unsubscribe for the user data.</para>
    /// <para>Message sent by: Integrator</para>
    /// <para>
    ///     Answer: <see cref="Communication.Mid0005"/> Command accepted or
    ///         <see cref="Communication.Mid0004"/> Command error, Subscription already exists
    /// </para>
    /// </summary>
    public class Mid0244 : Mid, IPLCUserData, IIntegrator
    {
        private const int LAST_REVISION = 1;
        public const int MID = 244;

        public Mid0244() : base(MID, LAST_REVISION) { }
    }
}


text:
package org.locationtech.geomesa.kudu.spark

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.io.NullWritable
import org.apache.hadoop.mapred.JobConf
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.geotools.data.{Query, Transaction}
import org.locationtech.geomesa.index.conf.QueryHints
import org.locationtech.geomesa.index.planning.QueryPlanner
import org.locationtech.geomesa.kudu.data.{KuduDataStore, KuduDataStoreFactory}
import org.locationtech.geomesa.spark.{DataStoreConnector, SpatialRDD, SpatialRDDProvider}
import org.locationtech.geomesa.utils.geotools.FeatureUtils
import org.locationtech.geomesa.utils.io.WithClose
import org.opengis.feature.simple.SimpleFeature

class KuduSpatialRDDProvider extends SpatialRDDProvider {

  override def canProcess(params: java.util.Map[String, _ <: java.io.Serializable]): Boolean =
    KuduDataStoreFactory.canProcess(params)

  override def rdd(conf: Configuration, sc: SparkContext, params: Map[String, String], query: Query): SpatialRDD = {

    import org.locationtech.geomesa.index.conf.QueryHints.RichHints

    val ds = DataStoreConnector[KuduDataStore](params)
    // force loose bbox to be false
    query.getHints.put(QueryHints.LOOSE_BBOX, false)

    // get the query plan to set up the iterators, ranges, etc
    lazy val sft = ds.getSchema(query.getTypeName)
    lazy val transform = {
      QueryPlanner.setQueryTransforms(query, sft)
      query.getHints.getTransformSchema
    }

    if (ds == null || sft == null) {
      SpatialRDD(sc.emptyRDD[SimpleFeature], transform.getOrElse(sft))
    } else {
      val jobConf = new JobConf(conf)
      GeoMesaKuduInputFormat.configure(jobConf, params, query)
      GeoMesaKuduInputFormat.addCredentials(jobConf, ds.client)
      val rdd = sc.newAPIHadoopRDD(jobConf, classOf[GeoMesaKuduInputFormat],
        classOf[NullWritable], classOf[SimpleFeature]).map(_._2)
      SpatialRDD(rdd, transform.getOrElse(sft))
    }
  }

  override def save(rdd: RDD[SimpleFeature], params: Map[String, String], typeName: String): Unit = {
    val ds = DataStoreConnector[KuduDataStore](params)
    require(ds.getSchema(typeName) != null,
      "Feature type must exist before calling save. Call `createSchema` on the DataStore first.")
    unsafeSave(rdd, params, typeName)
  }

  /**
    * Writes this RDD to a GeoMesa table.
    * The type must exist in the data store, and all of the features in the RDD must be of this type.
    * This method assumes that the schema exists.
    *
    * @param rdd rdd
    * @param params data store connection parameters
    * @param typeName feature type name
    */
  def unsafeSave(rdd: RDD[SimpleFeature], params: Map[String, String], typeName: String): Unit = {
    rdd.foreachPartition { iter =>
      val ds = DataStoreConnector[KuduDataStore](params)
      WithClose(ds.getFeatureWriterAppend(typeName, Transaction.AUTO_COMMIT)) { writer =>
        iter.foreach(FeatureUtils.write(writer, _, useProvidedFid = true))
      }
    }
  }
}


text:
namespace Google.Cloud.Eventarc.V1.Snippets
{
    // [START eventarc_v1_generated_Eventarc_GetChannelConnection_async_flattened]
    using Google.Cloud.Eventarc.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedEventarcClientSnippets
    {
        /// <summary>Snippet for GetChannelConnectionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetChannelConnectionAsync()
        {
            // Create client
            EventarcClient eventarcClient = await EventarcClient.CreateAsync();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/channelConnections/[CHANNEL_CONNECTION]";
            // Make the request
            ChannelConnection response = await eventarcClient.GetChannelConnectionAsync(name);
        }
    }
    // [END eventarc_v1_generated_Eventarc_GetChannelConnection_async_flattened]
}


text:
gtown-calendar-jc
=================

a simple command line calendar


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

import com.facebook.airlift.stats.CounterStat;
import com.google.common.cache.LoadingCache;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;

public class HiveMetastoreCacheStats
        implements MetastoreCacheStats
{
    private final CounterStat partitionsWithColumnCountGreaterThanThreshold = new CounterStat();
    private LoadingCache<?, ?> partitionCache;

    @Override
    public void setPartitionCache(LoadingCache<?, ?> partitionCache)
    {
        this.partitionCache = partitionCache;
    }

    @Override
    public void incrementPartitionsWithColumnCountGreaterThanThreshold()
    {
        partitionsWithColumnCountGreaterThanThreshold.update(1);
    }

    @Managed
    @Override
    public long getPartitionCacheHit()
    {
        return partitionCache.stats().hitCount();
    }

    @Managed
    @Override
    public long getPartitionCacheMiss()
    {
        return partitionCache.stats().missCount();
    }

    @Managed
    @Override
    public long getPartitionCacheEviction()
    {
        return partitionCache.stats().evictionCount();
    }

    @Managed
    @Override
    public long getPartitionCacheSize()
    {
        return partitionCache.size();
    }

    @Managed
    @Nested
    @Override
    public CounterStat getPartitionsWithColumnCountGreaterThanThreshold()
    {
        return partitionsWithColumnCountGreaterThanThreshold;
    }
}


text:
"""
@package mi.instrument.subc_control.onecam.ooicore.test.test_driver
@file m-instrument/mi/instrument/subc_control/onecam/ooicore/driver.py
@author Tapana Gupta
@brief Test cases for ooicore driver

USAGE:
 Make tests verbose and provide stdout
   * From the IDK
       $ bin/test_driver
       $ bin/test_driver -u [-t testname]
       $ bin/test_driver -i [-t testname]
       $ bin/test_driver -q [-t testname]
"""

__author__ = 'Tapana Gupta'
__license__ = 'Apache 2.0'

from nose.plugins.attrib import attr
from mock import Mock

from mi.core.log import get_logger

log = get_logger()

# MI imports.
from mi.idk.unit_test import InstrumentDriverTestCase, ParameterTestConfigKey
from mi.idk.unit_test import InstrumentDriverUnitTestCase
from mi.idk.unit_test import InstrumentDriverIntegrationTestCase
from mi.idk.unit_test import InstrumentDriverQualificationTestCase
from mi.idk.unit_test import DriverTestMixin

from mi.core.instrument.chunker import StringChunker
from mi.core.instrument.instrument_driver import DriverConfigKey

from mi.instrument.subc_control.onecam.ooicore.driver import InstrumentDriver, Command
from mi.instrument.subc_control.onecam.ooicore.driver import DataParticleType
from mi.instrument.subc_control.onecam.ooicore.driver import CAMHDAdreadStatusParticleKey
from mi.instrument.subc_control.onecam.ooicore.driver import ProtocolState
from mi.instrument.subc_control.onecam.ooicore.driver import ProtocolEvent
from mi.instrument.subc_control.onecam.ooicore.driver import Capability
from mi.instrument.subc_control.onecam.ooicore.driver import Parameter
from mi.instrument.subc_control.onecam.ooicore.driver import CAMHDProtocol
from mi.instrument.subc_control.onecam.ooicore.driver import Prompt
from mi.instrument.subc_control.onecam.ooicore.driver import NEWLINE

###
#   Driver parameters for the tests
###
InstrumentDriverTestCase.initialize(
    driver_module='mi.instrument.subc_control.onecam.ooicore.driver',
    driver_class="InstrumentDriver",
    instrument_agent_resource_id = '4RKRRG',
    instrument_agent_name = 'subc_control_onecam_ooicore',
    instrument_agent_packet_config = DataParticleType(),

    driver_startup_config = {
        DriverConfigKey.PARAMETERS: {}
    }
)

#################################### RULES ####################################
#                                                                             #
# Common capabilities in the base class                                       #
#                                                                             #
# Instrument specific stuff in the derived class                              #
#                                                                             #
# Generator spits out either stubs or comments describing test this here,     #
# test that there.                                                            #
#                                                                             #
# Qualification tests are driven through the instrument_agent                 #
#                                                                             #
###############################################################################

###
#   Driver constant definitions
###

###############################################################################
#                           DRIVER TEST MIXIN        		                  #
#     Defines a set of constants and assert methods used for data particle    #
#     verification 														      #
#                                                                             #
#  In python mixin classes are classes designed such that they wouldn't be    #
#  able to stand on their own, but are inherited by other classes generally   #
#  using multiple inheritance.                                                #
#                                                                             #
# This class defines a configuration structure for testing and common assert  #
# methods for validating data particles.									  #
###############################################################################
class DriverTestMixinSub(DriverTestMixin):

    InstrumentDriver = InstrumentDriver

    # Create some short names for the parameter test config
    TYPE = ParameterTestConfigKey.TYPE
    READONLY = ParameterTestConfigKey.READONLY
    STARTUP = ParameterTestConfigKey.STARTUP
    DA = ParameterTestConfigKey.DIRECT_ACCESS
    VALUE = ParameterTestConfigKey.VALUE
    REQUIRED = ParameterTestConfigKey.REQUIRED
    DEFAULT = ParameterTestConfigKey.DEFAULT
    STATES = ParameterTestConfigKey.STATES

    VALID_ADREAD_RESPONSE = 'ADVAL{"time": 1373996308, "data": [{"name": "abc", "val": 12.3, "units": "degrees"}, {"name": "def", "val": 45.6, "units": "minutes"}]}' + NEWLINE

    _driver_capabilities = {
        # capabilities defined in the IOS
        Capability.START_AUTOSAMPLE: {STATES: [ProtocolState.COMMAND]},
        Capability.STOP_AUTOSAMPLE: {STATES: [ProtocolState.AUTOSAMPLE]},
        Capability.ACQUIRE_STATUS: {STATES: [ProtocolState.COMMAND, ProtocolState.AUTOSAMPLE]},
        Capability.GET_STATUS_STREAMING: {STATES: [ProtocolState.COMMAND, ProtocolState.AUTOSAMPLE]},
        Capability.START_STREAMING: {STATES: [ProtocolState.COMMAND]},
        Capability.STOP_STREAMING: {STATES: [ProtocolState.COMMAND, ProtocolState.AUTOSAMPLE]},

    }

    ###
    #  Parameter and Type Definitions
    ###
    _driver_parameters = {
        # Parameters defined in the IOS

        Parameter.ENDPOINT: {TYPE: str, READONLY: True, DA: False, STARTUP: False, DEFAULT: '128.95.97.233', VALUE: '128.95.97.233'},
        Parameter.PAN_POSITION: {TYPE: float, READONLY: False, DA: False, STARTUP: False, DEFAULT: 180.0, VALUE: 180.0},
        Parameter.TILT_POSITION: {TYPE: float, READONLY: False, DA: False, STARTUP: False, DEFAULT: 90.0, VALUE: 90.0},
        Parameter.PAN_TILT_SPEED: {TYPE: float, READONLY: False, DA: False, STARTUP: False, DEFAULT: 10.0, VALUE: 10.0},
        Parameter.HEADING: {TYPE: float, READONLY: True, DA: False, STARTUP: False, DEFAULT: 0.0, VALUE: 0.0},
        Parameter.PITCH: {TYPE: float, READONLY: True, DA: False, STARTUP: False, DEFAULT: 0.0, VALUE: 0.0},
        Parameter.LIGHT_1_LEVEL: {TYPE: int, READONLY: False, DA: False, STARTUP: False, DEFAULT: 50, VALUE: 50},
        Parameter.LIGHT_2_LEVEL: {TYPE: int, READONLY: False, DA: False, STARTUP: False, DEFAULT: 50, VALUE: 50},
        Parameter.ZOOM_LEVEL: {TYPE: int, READONLY: False, DA: False, STARTUP: False, DEFAULT: 0, VALUE: 0},
        Parameter.LASERS_STATE: {TYPE: str, READONLY: False, DA: False, STARTUP: False, DEFAULT: 'off', VALUE: 'off'},
        Parameter.SAMPLE_INTERVAL: {TYPE: str, READONLY: False, DA: False, STARTUP: False, DEFAULT: '00:30:00', VALUE: '00:30:00'},
        Parameter.STATUS_INTERVAL: {TYPE: str, READONLY: False, DA: False, STARTUP: False, DEFAULT: '00:00:00', VALUE: '00:00:00'},
        Parameter.AUTO_CAPTURE_DURATION: {TYPE: str, READONLY: False, DA: False, STARTUP: False, DEFAULT: '00:05:00', VALUE: '00:05:00'},

    }

    _adread_parameters = {

        CAMHDAdreadStatusParticleKey.CHANNEL_NAME: {TYPE: list, VALUE: ['abc', 'def'], REQUIRED: True},
        CAMHDAdreadStatusParticleKey.CHANNEL_VALUE: {TYPE: list, VALUE: [12.3, 45.6], REQUIRED: True},
        CAMHDAdreadStatusParticleKey.VALUE_UNITS: {TYPE: list, VALUE: ['degrees', 'minutes'], REQUIRED: True},

    }

    def assert_adread_status_particle(self, data_particle, verify_values=False):
        """
        Verify CAMDS health status data particle
        @param data_particle: CAMDS health status DataParticle
        @param verify_values: bool, should we verify parameter values
        """
        self.assert_data_particle_keys(CAMHDAdreadStatusParticleKey, self._adread_parameters)
        self.assert_data_particle_header(data_particle, DataParticleType.ADREAD_STATUS)
        self.assert_data_particle_parameters(data_particle, self._adread_parameters)

###############################################################################
#                                UNIT TESTS                                   #
#         Unit tests test the method calls and parameters using Mock.         #
#                                                                             #
#   These tests are especially useful for testing parsers and other data      #
#   handling.  The tests generally focus on small segments of code, like a    #
#   single function call, but more complex code using Mock objects.  However  #
#   if you find yourself mocking too much maybe it is better as an            #
#   integration test.                                                         #
#                                                                             #
#   Unit tests do not start up external processes like the port agent or      #
#   driver process.                                                           #
###############################################################################
@attr('UNIT', group='mi')
class DriverUnitTest(InstrumentDriverUnitTestCase, DriverTestMixinSub):
    def setUp(self):
        InstrumentDriverUnitTestCase.setUp(self)

    def test_driver_enums(self):
        """
        Verify that all driver enumeration has no duplicate values that might cause confusion.  Also
        do a little extra validation for the Capabilites
        """
        self.assert_enum_has_no_duplicates(DataParticleType())
        self.assert_enum_has_no_duplicates(ProtocolState())
        self.assert_enum_has_no_duplicates(ProtocolEvent())
        self.assert_enum_has_no_duplicates(Parameter())
        self.assert_enum_has_no_duplicates(Command())

        # Test capabilites for duplicates, them verify that capabilities is a subset of proto events
        self.assert_enum_has_no_duplicates(Capability())
        self.assert_enum_complete(Capability(), ProtocolEvent())

    def test_driver_schema(self):
        """
        get the driver schema and verify it is configured properly
        """
        driver = self.InstrumentDriver(self._got_data_event_callback)
        self.assert_driver_schema(driver, self._driver_parameters, self._driver_capabilities)

    def test_chunker(self):
        """
        Test the chunker and verify the particles created.
        """
        chunker = StringChunker(CAMHDProtocol.sieve_function)

        self.assert_chunker_sample(chunker, self.VALID_ADREAD_RESPONSE)

    def test_got_data(self):
        """
        Verify sample data passed through the got data method produces the correct data particles
        """
        # Create and initialize the instrument driver with a mock port agent
        driver = InstrumentDriver(self._got_data_event_callback)
        self.assert_initialize_driver(driver)

        self.assert_raw_particle_published(driver, True)

        # Start validating data particles
        self.assert_particle_published(driver, self.VALID_ADREAD_RESPONSE, self.assert_adread_status_particle, True)

    def test_protocol_filter_capabilities(self):
        """
        This tests driver filter_capabilities.
        Iterate through available capabilities, and verify that they can pass successfully through the filter.
        Test silly made up capabilities to verify they are blocked by filter.
        """
        my_event_callback = Mock()
        protocol = CAMHDProtocol(Prompt, NEWLINE, my_event_callback)
        driver_capabilities = Capability.list()
        test_capabilities = Capability.list()

        # Add a bogus capability that will be filtered out.
        test_capabilities.append("BOGUS_CAPABILITY")

        # Verify "BOGUS_CAPABILITY was filtered out
        self.assertEquals(driver_capabilities, protocol._filter_capabilities(test_capabilities))

    def test_capabilities(self):
        """
        Verify the FSM reports capabilities as expected.  All states defined in this dict must
        also be defined in the protocol FSM.
        """
        capabilities = {
            ProtocolState.UNKNOWN: ['DRIVER_EVENT_DISCOVER'],
            ProtocolState.COMMAND: ['DRIVER_EVENT_ACQUIRE_STATUS',
                                    'DRIVER_EVENT_GET',
                                    'DRIVER_EVENT_SET',
                                    'DRIVER_EVENT_START_AUTOSAMPLE',
                                    'DRIVER_EVENT_START_STREAMING',
                                    'DRIVER_EVENT_STOP_STREAMING',
                                    'DRIVER_EVENT_GET_STATUS_STREAMING',
                                    'DRIVER_EVENT_START_DIRECT'],
            ProtocolState.AUTOSAMPLE: ['DRIVER_EVENT_GET',
                                       'DRIVER_EVENT_STOP_AUTOSAMPLE',
                                       'DRIVER_EVENT_ACQUIRE_SAMPLE',
                                       'DRIVER_EVENT_ACQUIRE_STATUS',
                                       'DRIVER_EVENT_STOP_STREAMING',
                                       'DRIVER_EVENT_GET_STATUS_STREAMING'],
            ProtocolState.DIRECT_ACCESS: ['DRIVER_EVENT_STOP_DIRECT', 'EXECUTE_DIRECT']
        }

        driver = InstrumentDriver(self._got_data_event_callback)
        self.assert_capabilities(driver, capabilities)

###############################################################################
#                            INTEGRATION TESTS                                #
#     Integration test test the direct driver / instrument interaction        #
#     but making direct calls via zeromq.                                     #
#     - Common Integration tests test the driver through the instrument agent #
#     and common for all drivers (minimum requirement for ION ingestion)      #
###############################################################################
@attr('INT', group='mi')
class DriverIntegrationTest(InstrumentDriverIntegrationTestCase):
    def setUp(self):
        InstrumentDriverIntegrationTestCase.setUp(self)

###############################################################################
#                            QUALIFICATION TESTS                              #
# Device specific qualification tests are for doing final testing of ion      #
# integration.  The generally aren't used for instrument debugging and should #
# be tackled after all unit and integration tests are complete                #
###############################################################################
@attr('QUAL', group='mi')
class DriverQualificationTest(InstrumentDriverQualificationTestCase):
    def setUp(self):
        InstrumentDriverQualificationTestCase.setUp(self)


text:
"""
Doga.parsers.payload

This module parse payload string and collect information from that.
info involves (method, host, resource path, section, http_type, useragent).
"""

import re
import sys

class PayloadParser:

    def __init__(self, log_generator):
        self.log_generator = log_generator

        self.method = '(GET|HEAD|POST|PUT|DELETE|TRACE|OPTIONS|CONNECT|PATCH)'
        self.path = '(\/.*)'
        self.http_type = '(HTTP\/1.[0-1])'

        self.req_regex = "%s\s%s\s%s" % (
            self.method, self.path, self.http_type)
        self.host_regex = "Host:\s(.*)\r"
        self.useragent_regex = "User-Agent:\s(.*)\r"

    def parse(self, data, ports):
        """ Parse request method, path, host, useragent, httptype etc.

        param: data(str) : packet payload string
        param: ports(list) : list object having source and destination ports
        """

        req_str = re.search(self.req_regex, data)
        host_str = re.search(self.host_regex, data)
        useragent_str = re.search(self.useragent_regex, data)

        try:
            method = req_str.group(1)
            path = req_str.group(2)
            http_type = req_str.group(3)
            host = host_str.group(1)
            useragent = useragent_str.group(1)
            section = path.split('?')[0]

            self.log_generator.generate(
                method, path, http_type, host, useragent, section)
        except:
            pass


text:
/* Capitalization rules for HPFS */

/* In OS/2, HPFS filenames preserve upper and lower case letter distinctions
   but filename matching ignores case.  That is, creating a file "Foo"
   actually creates a file named "Foo" which can be looked up as "Foo",
   "foo", or "FOO", among other possibilities.

   Also, HPFS is internationalized -- a table giving the uppercase
   equivalent of every character is stored in the filesystem, so that
   any national character set may be used.  If several different
   national character sets are in use, several tables are stored
   in the filesystem.

   It would be perfectly reasonable for Linux HPFS to act as a Unix
   filesystem and match "Foo" only if asked for "Foo" exactly.  But
   the sort order of HPFS directories is case-insensitive, so Linux
   still has to know the capitalization rules used by OS/2.  Because
   of this, it turns out to be more natural for us to be case-insensitive
   than not.

   Currently the standard character set used by Linux is Latin-1.
   Work is underway to permit people to use UTF-8 instead, therefore
   all code that depends on the character set is segregated here.

   (It would be wonderful if Linux HPFS could be independent of what
   character set is in use on the Linux side, but because of the
   necessary case folding this is impossible.)

   There is a map from Latin-1 into code page 850 for every printing
   character in Latin-1.  The NLS documentation of OS/2 shows that
   everybody has 850 available unless they don't have Western latin
   chars available at all (so fitting them to Linux without Unicode
   is a doomed exercise).

   It is not clear exactly how HPFS.IFS handles the situation when
   multiple code pages are in use.  Experiments show that

   - tables on the disk give uppercasing rules for the installed code pages

   - each directory entry is tagged with what code page was current
     when that name was created

   - doing just CHCP, without changing what's on the disk in any way,
     can change what DIR reports, and what name a case-folded match
     will match.

   This means, I think, that HPFS.IFS operates in the current code
   page, without regard to the uppercasing information recorded in
   the tables on the disk.  It does record the uppercasing rules
   it used, perhaps for CHKDSK, but it does not appear to use them
   itself.

   So: Linux, a Latin-1 system, will operate in code page 850.  We
   recode between 850 and Latin-1 when dealing with the names actually
   on the disk.  We don't use the uppercasing tables either.

   In a hypothetical UTF-8 implementation, one reasonable way to
   proceed that matches OS/2 (for least surprise) is: do case
   translation in UTF-8, and recode to/from one of the code pages
   available on the mounted filesystem.  Reject as invalid any name
   containing chars that can't be represented on disk by one of the
   code pages OS/2 is using.  Recoding from on-disk names to UTF-8
   could use the code page tags, though this is not what OS/2 does. */

static const unsigned char tb_cp850_to_latin1[128] =
{
  199, 252, 233, 226, 228, 224, 229, 231,
  234, 235, 232, 239, 238, 236, 196, 197,
  201, 230, 198, 244, 246, 242, 251, 249,
  255, 214, 220, 248, 163, 216, 215, 159,
  225, 237, 243, 250, 241, 209, 170, 186,
  191, 174, 172, 189, 188, 161, 171, 187,
  155, 156, 157, 144, 151, 193, 194, 192,
  169, 135, 128, 131, 133, 162, 165, 147,
  148, 153, 152, 150, 145, 154, 227, 195,
  132, 130, 137, 136, 134, 129, 138, 164,
  240, 208, 202, 203, 200, 158, 205, 206,
  207, 149, 146, 141, 140, 166, 204, 139,
  211, 223, 212, 210, 245, 213, 181, 254,
  222, 218, 219, 217, 253, 221, 175, 180,
  173, 177, 143, 190, 182, 167, 247, 184,
  176, 168, 183, 185, 179, 178, 142, 160,
};

#if 0
static const unsigned char tb_latin1_to_cp850[128] =
{
  186, 205, 201, 187, 200, 188, 204, 185,
  203, 202, 206, 223, 220, 219, 254, 242,
  179, 196, 218, 191, 192, 217, 195, 180,
  194, 193, 197, 176, 177, 178, 213, 159,
  255, 173, 189, 156, 207, 190, 221, 245,
  249, 184, 166, 174, 170, 240, 169, 238,
  248, 241, 253, 252, 239, 230, 244, 250,
  247, 251, 167, 175, 172, 171, 243, 168,
  183, 181, 182, 199, 142, 143, 146, 128,
  212, 144, 210, 211, 222, 214, 215, 216,
  209, 165, 227, 224, 226, 229, 153, 158,
  157, 235, 233, 234, 154, 237, 232, 225,
  133, 160, 131, 198, 132, 134, 145, 135,
  138, 130, 136, 137, 141, 161, 140, 139,
  208, 164, 149, 162, 147, 228, 148, 246,
  155, 151, 163, 150, 129, 236, 231, 152,
};
#endif

#define A_GRAVE 0300
#define THORN	0336
#define MULTIPLY 0327
#define a_grave 0340
#define thorn	0376
#define divide	0367

static inline unsigned latin1_upcase (unsigned c)
{
  if (c - 'a' <= 'z' - 'a'
      || (c - a_grave <= thorn - a_grave
	  && c != divide))
    return c - 'a' + 'A';
  else
    return c;
}

static inline unsigned latin1_downcase (unsigned c)
{
  if (c - 'A' <= 'Z' - 'A'
      || (c - A_GRAVE <= THORN - A_GRAVE
	  && c != MULTIPLY))
    return c + 'a' - 'A';
  else
    return c;
}

#if 0
static inline unsigned latin1_to_cp850 (unsigned c)
{
  if ((signed) c - 128 >= 0)
    return tb_latin1_to_cp850[c - 128];
  else
    return c;
}
#endif

static inline unsigned cp850_to_latin1 (unsigned c)
{
  if ((signed) c - 128 >= 0)
    return tb_cp850_to_latin1[c - 128];
  else
    return c;
}

unsigned hpfs_char_to_upper_linux (unsigned c)
{
  return latin1_upcase (cp850_to_latin1 (c));
}

unsigned linux_char_to_upper_linux (unsigned c)
{
  return latin1_upcase (c);
}

unsigned hpfs_char_to_lower_linux (unsigned c)
{
  return latin1_downcase (cp850_to_latin1 (c));
}

unsigned hpfs_char_to_linux (unsigned c)
{
  return cp850_to_latin1 (c);
}


text:
package org.bitbucket.jtransaction.transactions;

import org.bitbucket.jtransaction.common.Copyable;

/**
 * ResourceStatistics
 *
 * @author afs
 * @version 2013
*/

public final class ResourceStatistics implements Copyable<ResourceStatistics> {
    // instance variables
    private int reads, writes;
    private long lastRead, lastWrite;

    /**************************************************************************
     * Constructors
    **************************************************************************/

    /** Empty constructor of objects of class ResourceStatistics. */
    ResourceStatistics() { this(0, 0, 0, 0); }

    /** Parameter constructor of objects of class ResourceStatistics. */
    ResourceStatistics(int r, int w) {
        this(r, w, 0, 0);
    }

    /** Parameter constructor of objects of class ResourceStatistics. */
    ResourceStatistics(int r, int w, long rTime, long wTime) {
        reads       = r;
        writes      = w;
        lastRead    = rTime;
        lastWrite   = wTime;
    }

    /** Copy constructor of objects of class ResourceStatistics. */
    private ResourceStatistics(ResourceStatistics instance) {
        this(
            instance.getReadCount(),
            instance.getWriteCount(),
            instance.getLastReadTime(),
            instance.getLastWriteTime()
        );
    }

    /**************************************************************************
     * Getters
    **************************************************************************/

    /** */
    public int getReadCount() { return reads; }

    /** */
    public int getWriteCount() { return writes; }

    /** */
    long getLastReadTime() { return lastRead; }

    /** */
    long getLastWriteTime() { return lastWrite; }

    /**************************************************************************
     * Setters
    **************************************************************************/

    /** */
    void setReadCount(int r) { reads = r; }

    /** */
    void resetReadCount() { reads = 0; }

    /** */
    void setWriteCount(int w) { writes = w; }

    /** */
    void resetWriteCount() { writes = 0; }

    /** */
    void setLastReadTime(long t) { lastRead = t; }

    /** */
    void setLastReadTime() { lastRead = System.currentTimeMillis(); }

    /** */
    void setLastWriteTime(long t) { lastWrite = t; }

    /** */
    void setLastWriteTime() { lastWrite = System.currentTimeMillis(); }

    /**************************************************************************
     * Predicates
    **************************************************************************/

    /** */
    public boolean isAccessed() { return hasReads() || hasWrites(); }

    /** */
    public boolean hasReads() { return reads > 0; }

    /** */
    public boolean hasWrites() { return writes > 0; }

    /**************************************************************************
     * Public Methods
    **************************************************************************/

    /** Sums two statistics into one.
     * The resulting object has the sum of the counter values.
     * Returns the non-null object if one of the arguments is null.
    */
    public static ResourceStatistics sum(
            ResourceStatistics s1, ResourceStatistics s2
    ) {
        // If both are null, return empty statistics.
        if (s1 == null && s2 == null) { return new ResourceStatistics(); }
        // If the first is null, return the second.
        if (s1 == null) { return s2; }
        // If the second is null, return the first.
        if (s2 == null) { return s1; }
        // If none is null, combine and return new statistics.
        return new ResourceStatistics(
            s1.getReadCount()           +   s2.getReadCount(),
            s1.getWriteCount()          +   s2.getWriteCount(),
            Math.max(s1.getLastReadTime(),  s2.getLastReadTime()),
            Math.max(s1.getLastWriteTime(), s2.getLastWriteTime())
        );
    }

    /** */
    public void add(ResourceStatistics rs) {
        if (rs == null) { return; }
        reads += rs.getReadCount();
        writes += rs.getWriteCount();
        lastRead = Math.max(lastRead, rs.getLastReadTime());
        lastWrite = Math.max(lastWrite, rs.getLastWriteTime());
    }

    /**************************************************************************
     * Private Methods
    **************************************************************************/

    /** */
    void incrementReadCount() { ++reads; }

    /** */
    void incrementWriteCount() { ++writes; }

    /** */
    void incrementReadCount(int i) { reads += i; }

    /** */
    void incrementWriteCount(int i) { writes += i; }

    /**************************************************************************
     * Equals, HashCode, ToString & Clone
    **************************************************************************/

    /** Equivalence relation. Contract (for any non-null reference values
            reads, y, and z):
        * Reflereadsive: reads.equals(reads).
        * Symmetric: reads.equals(y) iff y.equals(reads).
        * Transitive: if reads.equals(y) and y.equals(z), then reads.equals(z).
        * Consistency: successive calls (with no modification of the equality
            fields) return the same result.
        * reads.equals(null) should return false.
    */
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || this.getClass() != o.getClass()) return false;
        ResourceStatistics n = (ResourceStatistics) o;
        return (reads == n.getReadCount() &&
                writes == n.getWriteCount());
    }

    /** Contract:
        * Consistency: successive calls (with no modification of the equality
            fields) return the same code.
        * Function: two equal objects have the same (unique) hash code.
        * (Optional) Injection: unequal objects have different hash codes.
    * Common practices:
        * boolean: calculate (f ? 0 : 1);
        * byte, char, short or int: calculate (int) f;
        * long: calculate (int) (f ^ (f >>> 32));
        * float: calculate Float.floatToIntBits(f);
        * double: calculate Double.doubleToLongBits(f)
            and handle the return value like every long value;
        * Object: use (f == null ? 0 : f.hashCode());
        * Array: recursion and combine the values.
    * Formula:
        hash = prime * hash + codeForField
    */
    @Override
    public int hashCode() { return 37 * writes + reads; }

    /** Returns a string representation of the object. */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("#RESOURCE_STATISTICS $ ");
        sb.append(reads);
        sb.append(" $ ");
        sb.append(writes);
        sb.append(" $ ");
        sb.append(lastRead);
        sb.append(" $ ");
        sb.append(lastWrite);
        return sb.toString();
    }

    /** Returns a JSON string representation of the object. */
    public String toJsonString() {
        StringBuilder sb = new StringBuilder("{\"reads\":");
        sb.append(reads);
        sb.append(",\"writes\":");
        sb.append(writes);
        sb.append(",\"lastRead\":");
        sb.append(lastRead);
        sb.append(",\"lastWrite\":");
        sb.append(lastWrite);
        sb.append('}');
        return sb.toString();
    }

    /** Returns a XML string representation of the object. */
    public String toXmlString() {
        StringBuilder sb = new StringBuilder("<ResourceStatistics reads=\"");
        sb.append(reads);
        sb.append("\" writes=\"");
        sb.append(writes);
        sb.append("\" lastRead=\"");
        sb.append(lastRead);
        sb.append("\" lastWrite=\"");
        sb.append(lastWrite);
        sb.append("\"></ResourceStatistics>");
        return sb.toString();
    }

    /** Creates and returns a (deep) copy of this object. */
    @Override
    public ResourceStatistics clone() { return new ResourceStatistics(this); }
}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */
package com.dibosh.experiments.androidbanglasupport;

public final class R {
	public static final class drawable {
		public static final int ic_action_search = 0x7f020000;
		public static final int ic_launcher = 0x7f020001;
	}
	public static final class string {
		public static final int app_name = 0x7f030000;
	}
	public static final class style {
		public static final int AppTheme = 0x7f040000;
	}
}


text:
//
//  ManagerProductController.m
//  @的你
//
//  Created by 吴明飞 on 16/3/31.
//  Copyright © 2016年 吴明飞. All rights reserved.
//

#import "ManagerProductController.h"
#import "ManagerTableView.h"
#import "AddGoodsController.h"
#import "ManagerProductCell.h"
#import "GoodsModel.h"

static NSInteger num = 1;

@interface ManagerProductController ()

@property (nonatomic, strong) ManagerTableView *tableView;

//**数据源数组*/
@property (nonatomic, copy) NSMutableArray *dataArray;
/**模型数组*/
@property (nonatomic, copy) NSMutableArray *modelArray;

@property (nonatomic, strong) UIImageView *backImage;
@property (nonatomic, strong) UILabel *textLabel;
@end

@implementation ManagerProductController

{
    BOOL _isResume;//恢复售卖
    BOOL _isOutOfStock;//缺货下架
}

- (UIImageView *)backImage {

    if (!_backImage) {

        self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(98 * kMulriple, 184 * kHMulriple, 180 * kMulriple, 180 * kHMulriple)];
        _backImage.image = [UIImage imageNamed:@"nosource"];
        _backImage.alpha = 0.5;
        [self.view addSubview:self.backImage];
    }
    return _backImage;
}

- (UILabel *)textLabel {

    if (!_textLabel) {

        self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(210 * kMulriple, 280 * kHMulriple, 90 * kMulriple, 25 * kHMulriple)];
        _textLabel.text = @"暂无数据";
        _textLabel.textColor = RGB(111, 111, 111);
        _textLabel.font = KFont;

        [self.view addSubview:self.textLabel];
    }
    return _textLabel;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];

    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:RGB(94, 94, 94)};
    self.navigationController.navigationBar.titleTextAttributes = dic;
    num = 1;

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self customNaviBar];

    //自定义试图用
    [self setupViews];
    //请求数据

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestModelData)];
    [self.tableView.mj_header beginRefreshing];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestModelData) name:@"AddGoodsSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestModelData) name:@"AlertGoodsSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestModelData) name:@"DeleteGoodsSuccess" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestModelData) name:@"ResumeGoodsSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestModelData) name:@"StockGoodsSuccess" object:nil];
}

- (void)setupViews {
    self.view.backgroundColor = RGB(238, 238, 238);

    self.tableView = [[ManagerTableView alloc] initWithFrame:CGRectMake(0, 64 * kHMulriple, self.view.bounds.size.width, self.view.bounds.size.height - 64 * kHMulriple) style:UITableViewStylePlain];

    self.tableView.cellHeight = 140 * kHMulriple;
    self.tableView.pagingEnabled = NO;
    [self.view addSubview:self.tableView];
}

- (void)requestModelData {

    num = 1;

    WS(weakself);
    [self.modelArray removeAllObjects];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:@"加载中..."];

    NSString *urlStr = [NSString stringWithFormat:@"/shop/product?page=%@", @(0)];

    [HttpHelper requestUrl:urlStr success:^(id json) {
        [SVProgressHUD dismiss];
        NSMutableArray *array = [NSMutableArray array];
        NSDictionary *dataDic = json[@"data"];
        NSArray *contentArr = dataDic[@"content"];
        for (NSDictionary *dic in contentArr) {
            GoodsModel *model = [[GoodsModel alloc] initWithDic:dic];
            [array addObject:model];
        }
        [weakself.modelArray addObjectsFromArray:array];

        [weakself LoadDataWithArray:weakself.modelArray];

        if (array.count < 5) {

            _tableView.mj_footer.hidden = YES;
        }

        if (array.count > 0) {

            _tableView.hidden = NO;
            [_textLabel removeFromSuperview];
            [_backImage removeFromSuperview];

        } else if (array.count == 0) {

            self.view.backgroundColor = RGB(200, 200, 200);
            [self.view addSubview:self.backImage];
            [self.view addSubview:self.textLabel];
            _tableView.hidden = YES;
        }

    } failure:^(NSError *error) {

    }];

    [self.tableView.mj_header endRefreshing];
}

- (void)loadMoreData {

    WS(weakself);

    NSString *urlStr = [NSString stringWithFormat:@"/shop/product?page=%@", @(num)];

    [HttpHelper requestUrl:urlStr success:^(id json) {
        [SVProgressHUD dismiss];

        NSMutableArray *array = [NSMutableArray array];
        NSDictionary *dataDic = json[@"data"];
        NSArray *contentArr = dataDic[@"content"];

        if (contentArr.count == 0) {

            _tableView.mj_footer.hidden = YES;
        } else {

            for (NSDictionary *dic in contentArr) {
                GoodsModel *model = [[GoodsModel alloc] initWithDic:dic];
                [array addObject:model];
            }
            [weakself.modelArray addObjectsFromArray:array];
            [weakself LoadDataWithArray:weakself.modelArray];

        }

    } failure:^(NSError *error) {

    }];

    [self.tableView.mj_footer endRefreshing];

    num = num + 1;
}

#pragma mark -- 刷新事件
- (void)LoadDataWithArray:(NSArray *)array{

    WS(weakself);

    [self.dataArray removeAllObjects];

    for (int i = 0; i < array.count; i++) {

        NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
        ManagerProductCell *cell = [ManagerProductCell creatCellWithTarget:self index:index tableView:self.tableView model:array[i]];

        // 将创建好的 cell 加入数组
        [self.dataArray addObject:cell];

        [self editCellTouchEventArray:array cell:cell];
        [self statusCellTouchEventArray:array cell:cell];

        // cell 上的删除点击事件
        [cell deleteCellWithIndex:^(NSInteger index) {
            GoodsModel *model = array[index];
            NSString *urlString = [NSString stringWithFormat:@"/shop/product/%@", model.id];

            [SVProgressHUD showWithStatus:@"删除中..."];
            [HttpHelper requestMethod:@"DELETE" urlString:urlString parma:nil success:^(id json) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];

                    [weakself.dataArray removeObjectAtIndex:index];
                    [weakself.modelArray removeObjectAtIndex:index];

                    // 刷新数据
                    [weakself LoadDataWithArray:weakself.modelArray];

                    [[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteGoodsSuccess" object:nil];

            } failure:^(NSError *error) {

            }];

    }];

    }

    [self.tableView setUpTheDataSourceWithArray:self.dataArray];

}

- (void)editCellTouchEventArray:(NSArray *)array cell:(ManagerProductCell *)cell {

    [cell editCellWithIndex:^(NSInteger index) {

        AddGoodsController *goodsVC = [[AddGoodsController alloc] init];
        goodsVC.model = array[index - 1000];
        [self.navigationController pushViewController:goodsVC animated:YES];
    }];
}

- (void)statusCellTouchEventArray:(NSArray *)array cell:(ManagerProductCell *)cell {

    [SVProgressHUD setMinimumDismissTimeInterval:1];

    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [cell statusCellWithIndex:^(NSInteger index) {

        GoodsModel *model = array[index - 5000];
        if ([cell.productStatusBtn.titleLabel.text isEqualToString:@"恢复售卖"]) {

            NSString *urlString = [NSString stringWithFormat:@"/shop/product/%@/publish", model.id];

            [HttpHelper requestMethod:@"PATCH" urlStr:urlString parma:nil success:^(id json) {

                [[NSNotificationCenter defaultCenter] postNotificationName:@"ResumeGoodsSuccess" object:nil];

                [SVProgressHUD showSuccessWithStatus:@"发布成功"];

                [cell.productStatusBtn.layer setBorderWidth:1 * kMulriple];   //边框宽度
                [cell.productStatusBtn.layer setBorderColor:RGB(237, 237, 237).CGColor];//边框颜色
                cell.productStatusBtn.titleLabel.font = [UIFont systemFontOfSize:17 * kMulriple];
                [cell.productStatusBtn setTitleColor:RGB(111, 111, 111) forState:UIControlStateNormal];
                [cell.productStatusBtn setTitle:@"缺货下架" forState:UIControlStateNormal];
                cell.productStatusBtn.backgroundColor = [UIColor whiteColor];

            } failure:^(NSError *error) {

                if (error) {

                  [SVProgressHUD showInfoWithStatus:@"发布失败"];
                }

            }];

        }

        if ([cell.productStatusBtn.titleLabel.text isEqualToString:@"缺货下架"]) {

            NSString *urlString = [NSString stringWithFormat:@"/shop/product/%@/unpublish", model.id];

            [HttpHelper requestMethod:@"PATCH" urlStr:urlString parma:nil success:^(id json) {

                [SVProgressHUD showSuccessWithStatus:@"下架成功"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"StockGoodsSuccess" object:nil];

                    [cell.productStatusBtn setTitle:@"恢复售卖" forState:UIControlStateNormal];
                    cell.productStatusBtn.backgroundColor = [UIColor redColor];
                    cell.productStatusBtn.titleLabel.font = [UIFont systemFontOfSize:17 * kMulriple];
                    [cell.productStatusBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

            } failure:^(NSError *error) {

                if (error) {

                    [SVProgressHUD showInfoWithStatus:@"下架失败"];
                }

            }];

        }
    }];
}

#pragma mark -- lazy load
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

//添加商品按钮方法
- (void)addBtnAction:(UIButton *)sender {

    AddGoodsController *goodsVC = [[AddGoodsController alloc] init];
    goodsVC.isSubmit = YES;
    [self.navigationController pushViewController:goodsVC animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (void)dealloc {
    num = 1;
    _modelArray = nil;
    _dataArray = nil;

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AddGoodsSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AlertGoodsSuccess" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"DeleteGoodsSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ResumeGoodsSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"StockGoodsSuccess" object:nil];
}

- (void)customNaviBar {
    //自定义导航栏
    UIView *naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWight, 64 * kHMulriple)];
    naviView.backgroundColor = RGB(83, 83, 83);

    //返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 25 * kHMulriple, 80 * kMulriple, 30 * kHMulriple);

    [backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];

    UIImageView *arrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(15 * kMulriple, 2.5 * kHMulriple, 15 * kMulriple, 25 * kHMulriple)];
    arrowImage.image = [UIImage imageNamed:@"arrowImage"];
    [backBtn addSubview:arrowImage];

    [naviView addSubview:backBtn];

    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(137 * kMulriple, 20 * kHMulriple, 100 * kMulriple, 40 * kHMulriple)];
    textLabel.text = @"商品管理";
    textLabel.textColor = [UIColor whiteColor];
    textLabel.font = [UIFont systemFontOfSize:20 * kMulriple];
    textLabel.centerX = naviView.width / 2;

    [naviView addSubview:textLabel];

    //搜索按钮
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(330 * kMulriple, 25 * kHMulriple, 40 * kMulriple, 30 * kMulriple);
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:17 * kMulriple];
    [addBtn addTarget:self action:@selector(addBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [naviView addSubview:addBtn];

    [self.view addSubview:naviView];

}

- (void)backBtnAction:(UIButton *)sender {

    [self.navigationController popViewControllerAnimated:YES];
}

@end


text:
ACCEPTED

#### According to
Euro+Med Plantbase

#### Published in
null

#### Original name
Inula viscosa var. angustifolia Bég.

### Remarks
null


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

namespace Articulate
{
	static class Constants
	{
		/// <summary>
		/// The DSN used by Raven to report exceptions to a Sentry instance for tracking
		/// </summary>
		public const string SentryDSN = "http://eb3dd1c4c34c4699a63aa7f94a6ffed1:71a20430f5ba41c0b90d1ed21a019178@sentry.sierrasoftworks.com/4";
	}
}


text:
var OAuth = require('oauth');
var needle = require('needle');
module.exports = {
    oauth: null,
    format: null,
    parameters: {},
    //yql-node used to output only xml, now the formatAsJSON chainloader should help.
    withOAuth: function (consumer_key, consumer_secret) {
        this.oauth = new OAuth.OAuth(
          'https://query.yahooapis.com/v1/yql/',
          'https://query.yahooapis.com/v1/yql/',
          consumer_key, //consumer key
          consumer_secret, //consumer secret
          '1.0',
          null,
          'HMAC-SHA1'
          );
        this.oauth.setClientOptions({ requestTokenHttpMethod: 'POST' });

        return this;
    },
    formatAsJSON: function () {
        this.format = 'json';
        return this;
    },
    formatAsXML: function () {
        this.format = 'xml';
        return this;
    },
    setQueryParameter: function(parameters) {
        this.parameters = Object.assign(this.parameters, parameters);
        return this;
    },

    execute: function (query, callback) {
        if (this.oauth != null) {
            this.oauth.post('https://query.yahooapis.com/v1/yql',
              '',
              '',
              Object.assign({ q: query, format: this.format || 'xml' }, this.parameters),
              callback);
        } else {
            needle
              .post("https://query.yahooapis.com/v1/public/yql",
                Object.assign({ q: query, format: this.format || 'xml' }, this.parameters),
                { multipart: false },
                function (err, res) {
                    callback(err, res.body);
                });
        }
    }
}


text:
from msrest.serialization import Model

class WebhookReceiver(Model):
    """A webhook receiver.

    :param name: The name of the webhook receiver. Names must be unique across
     all receivers within an action group.
    :type name: str
    :param service_uri: The URI where webhooks should be sent.
    :type service_uri: str
    """

    _validation = {
        'name': {'required': True},
        'service_uri': {'required': True},
    }

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'service_uri': {'key': 'serviceUri', 'type': 'str'},
    }

    def __init__(self, name, service_uri):
        self.name = name
        self.service_uri = service_uri


text:
package se.idioti.example.jaxws.soap.server;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

/**
 * This interface describes a karaoke-themed web service.
 *
 * @author "Johan Holmberg, Malmö university"
 * @since 1.0
 */
@WebService // This lets Java know that we're building a web service
@SOAPBinding(style = Style.RPC)  // This lets Java know that we're using SOAP
public interface Karaoke {
	@WebMethod String getSongAsString(String song);
}


text:
package com.qq.weixin.chat.api.entity.message;

import java.io.Serializable;

/**
 * 微信转账消息
 */
public class WXMoney extends WXMessage implements Serializable, Cloneable {

    @Override
    public boolean equals(Object o) {
        return super.equals(o);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public WXMoney clone() {
        return (WXMoney) super.clone();
    }
}


text:
package com.github.devicehive.rest;

import com.github.devicehive.rest.api.DeviceApi;
import com.github.devicehive.rest.model.Device;
import org.junit.Assert;
import org.junit.Test;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class DeviceApiTest extends Helper {
    @Test
    public void registerDevice() throws IOException {
        String deviceId = UUID.randomUUID().toString();
        boolean authenticated = authenticate();
        boolean deviceCreated = createDevice(deviceId);
        Assert.assertTrue(authenticated && deviceCreated);
        Assert.assertTrue(deleteDevices(deviceId));
    }

    @Test
    public void deleteDevice() throws IOException {
        String deviceId = UUID.randomUUID().toString();
        boolean authenticated = authenticate();
        boolean deviceCreated = createDevice(deviceId);
        Assert.assertTrue(authenticated && deviceCreated);

        DeviceApi api = client.createService(DeviceApi.class);
        Response<Void> response = api.delete(deviceId).execute();
        Assert.assertTrue(response.isSuccessful());
    }

    @Test
    public void getDeviceList() throws IOException {
        String deviceId = UUID.randomUUID().toString();
        boolean authenticated = authenticate();
        boolean deviceCreated = createDevice(deviceId);
        Assert.assertTrue(authenticated && deviceCreated);

        DeviceApi api = client.createService(DeviceApi.class);
        Response<List<Device>> response = api.list(null, null, null, null,
                null, null, 0, null).execute();
        Assert.assertTrue(response.isSuccessful());
    }

    @Test
    public void getDevice() throws IOException {
        String deviceId = UUID.randomUUID().toString();
        boolean authenticated = authenticate();
        boolean deviceCreated = createDevice(deviceId);
        Assert.assertTrue(authenticated && deviceCreated);

        DeviceApi api = client.createService(DeviceApi.class);
        Response<Device> response = api.get(deviceId).execute();
        Assert.assertTrue(response.isSuccessful());
        Assert.assertTrue(deleteDevices(deviceId));
    }

}


text:
{% raw %}{% extends "blog/blog_base.html" %}
{% load wagtailcore_tags wagtailimages_tags wagtailroutablepage_tags %}

{% block canonical_url %}
    <link rel="amphtml" href="{{ request.site.root_url }}{% routablepageurl page "amp" %}" />
{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block content %}
	{% include "utils/includes/social_share.html" %}

		{% include "blog/includes/blog_header.html" %}

		{% if self.feed_image %}
			{% image self.feed_image fill-1200x400 as feed_image %}

		{% endif %}

				    	{% include "blog/includes/blog_body.html" with body=self.body only %}

{% endblock %}{% endraw %}


text:
.class Landroid/support/v7/widget/ActivityChooserView$4;
.super Landroid/database/DataSetObserver;
.source "ActivityChooserView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/support/v7/widget/ActivityChooserView;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/support/v7/widget/ActivityChooserView;

# direct methods
.method constructor <init>(Landroid/support/v7/widget/ActivityChooserView;)V
    .locals 0

    .prologue
    .line 264
    iput-object p1, p0, Landroid/support/v7/widget/ActivityChooserView$4;->this$0:Landroid/support/v7/widget/ActivityChooserView;

    invoke-direct {p0}, Landroid/database/DataSetObserver;-><init>()V

    return-void
.end method

# virtual methods
.method public onChanged()V
    .locals 1

    .prologue
    .line 267
    invoke-super {p0}, Landroid/database/DataSetObserver;->onChanged()V

    .line 268
    iget-object v0, p0, Landroid/support/v7/widget/ActivityChooserView$4;->this$0:Landroid/support/v7/widget/ActivityChooserView;

    # invokes: Landroid/support/v7/widget/ActivityChooserView;->updateAppearance()V
    invoke-static {v0}, Landroid/support/v7/widget/ActivityChooserView;->access$400(Landroid/support/v7/widget/ActivityChooserView;)V

    .line 269
    return-void
.end method


text:
dojo.provide("dijit._base.place");

dojo.require("dojo.AdapterRegistry");

// ported from dojo.html.util

dijit.getViewport = function(){
	//	summary
	//	Returns the dimensions and scroll position of the viewable area of a browser window

	var _window = dojo.global;
	var _document = dojo.doc;

	// get viewport size
	var w = 0, h = 0;
	var de = _document.documentElement;
	var dew = de.clientWidth, deh = de.clientHeight;
	if(dojo.isMozilla){
		// mozilla
		// _window.innerHeight includes the height taken by the scroll bar
		// clientHeight is ideal but has DTD issues:
		// #4539: FF reverses the roles of body.clientHeight/Width and documentElement.clientHeight/Width based on the DTD!
		// check DTD to see whether body or documentElement returns the viewport dimensions using this algorithm:
		var minw, minh, maxw, maxh;
		var dbw = _document.body.clientWidth;
		if(dbw > dew){
			minw = dew;
			maxw = dbw;
		}else{
			maxw = dew;
			minw = dbw;
		}
		var dbh = _document.body.clientHeight;
		if(dbh > deh){
			minh = deh;
			maxh = dbh;
		}else{
			maxh = deh;
			minh = dbh;
		}
		w = (maxw > _window.innerWidth) ? minw : maxw;
		h = (maxh > _window.innerHeight) ? minh : maxh;
	}else if(!dojo.isOpera && _window.innerWidth){
		//in opera9, dojo.body().clientWidth should be used, instead
		//of window.innerWidth/document.documentElement.clientWidth
		//so we have to check whether it is opera
		w = _window.innerWidth;
		h = _window.innerHeight;
	}else if(dojo.isIE && de && deh){
		w = dew;
		h = deh;
	}else if(dojo.body().clientWidth){
		// IE5, Opera
		w = dojo.body().clientWidth;
		h = dojo.body().clientHeight;
	}

	// get scroll position
	var scroll = dojo._docScroll();

	return { w: w, h: h, l: scroll.x, t: scroll.y };	//	object
};

/*=====
dijit.__Position = function(){
	//	x: Integer
	//		horizontal coordinate in pixels, relative to document body
	//	y: Integer
	//		vertical coordinate in pixels, relative to document body

	thix.x = x;
	this.y = y;
}
=====*/

dijit.placeOnScreen = function(
	/* DomNode */			node,
	/* dijit.__Position */	pos,
	/* String[] */			corners,
	/* boolean? */			tryOnly){
	//	summary:
	//		Positions one of the node's corners at specified position
	//		such that node is fully visible in viewport.
	//	description:
	//		NOTE: node is assumed to be absolutely or relatively positioned.
	//	pos:
	//		Object like {x: 10, y: 20}
	//	corners:
	//		Array of Strings representing order to try corners in, like ["TR", "BL"].
	//		Possible values are:
	//			* "BL" - bottom left
	//			* "BR" - bottom right
	//			* "TL" - top left
	//			* "TR" - top right
	//	example:
	//		Try to place node's top right corner at (10,20).
	//		If that makes node go (partially) off screen, then try placing
	//		bottom left corner at (10,20).
	//	|	placeOnScreen(node, {x: 10, y: 20}, ["TR", "BL"])

	var choices = dojo.map(corners, function(corner){ return { corner: corner, pos: pos }; });

	return dijit._place(node, choices);
}

dijit._place = function(/*DomNode*/ node, /* Array */ choices, /* Function */ layoutNode){
	// summary:
	//		Given a list of spots to put node, put it at the first spot where it fits,
	//		of if it doesn't fit anywhere then the place with the least overflow
	// choices: Array
	//		Array of elements like: {corner: 'TL', pos: {x: 10, y: 20} }
	//		Above example says to put the top-left corner of the node at (10,20)
	//	layoutNode: Function(node, aroundNodeCorner, nodeCorner)
	//		for things like tooltip, they are displayed differently (and have different dimensions)
	//		based on their orientation relative to the parent.   This adjusts the popup based on orientation.

	// get {x: 10, y: 10, w: 100, h:100} type obj representing position of
	// viewport over document
	var view = dijit.getViewport();

	// This won't work if the node is inside a <div style="position: relative">,
	// so reattach it to dojo.doc.body.   (Otherwise, the positioning will be wrong
	// and also it might get cutoff)
	if(!node.parentNode || String(node.parentNode.tagName).toLowerCase() != "body"){
		dojo.body().appendChild(node);
	}

	var best = null;
	dojo.some(choices, function(choice){
		var corner = choice.corner;
		var pos = choice.pos;

		// configure node to be displayed in given position relative to button
		// (need to do this in order to get an accurate size for the node, because
		// a tooltips size changes based on position, due to triangle)
		if(layoutNode){
			layoutNode(node, choice.aroundCorner, corner);
		}

		// get node's size
		var style = node.style;
		var oldDisplay = style.display;
		var oldVis = style.visibility;
		style.visibility = "hidden";
		style.display = "";
		var mb = dojo.marginBox(node);
		style.display = oldDisplay;
		style.visibility = oldVis;

		// coordinates and size of node with specified corner placed at pos,
		// and clipped by viewport
		var startX = (corner.charAt(1) == 'L' ? pos.x : Math.max(view.l, pos.x - mb.w)),
			startY = (corner.charAt(0) == 'T' ? pos.y : Math.max(view.t, pos.y -  mb.h)),
			endX = (corner.charAt(1) == 'L' ? Math.min(view.l + view.w, startX + mb.w) : pos.x),
			endY = (corner.charAt(0) == 'T' ? Math.min(view.t + view.h, startY + mb.h) : pos.y),
			width = endX - startX,
			height = endY - startY,
			overflow = (mb.w - width) + (mb.h - height);

		if(best == null || overflow < best.overflow){
			best = {
				corner: corner,
				aroundCorner: choice.aroundCorner,
				x: startX,
				y: startY,
				w: width,
				h: height,
				overflow: overflow
			};
		}
		return !overflow;
	});

	node.style.left = best.x + "px";
	node.style.top = best.y + "px";
	if(best.overflow && layoutNode){
		layoutNode(node, best.aroundCorner, best.corner);
	}
	return best;
}

dijit.placeOnScreenAroundNode = function(
	/* DomNode */		node,
	/* DomNode */		aroundNode,
	/* Object */		aroundCorners,
	/* Function? */		layoutNode){

	//	summary:
	//		Position node adjacent or kitty-corner to aroundNode
	//		such that it's fully visible in viewport.
	//
	//	description:
	//		Place node such that corner of node touches a corner of
	//		aroundNode, and that node is fully visible.
	//
	//	aroundCorners:
	//		Ordered list of pairs of corners to try matching up.
	//		Each pair of corners is represented as a key/value in the hash,
	//		where the key corresponds to the aroundNode's corner, and
	//		the value corresponds to the node's corner:
	//
	//	|	{ aroundNodeCorner1: nodeCorner1, aroundNodeCorner2: nodeCorner2,  ...}
	//
	//		The following strings are used to represent the four corners:
	//			* "BL" - bottom left
	//			* "BR" - bottom right
	//			* "TL" - top left
	//			* "TR" - top right
	//
	//	layoutNode: Function(node, aroundNodeCorner, nodeCorner)
	//		For things like tooltip, they are displayed differently (and have different dimensions)
	//		based on their orientation relative to the parent.   This adjusts the popup based on orientation.
	//
	//	example:
	//	|	dijit.placeOnScreenAroundNode(node, aroundNode, {'BL':'TL', 'TR':'BR'});
	//		This will try to position node such that node's top-left corner is at the same position
	//		as the bottom left corner of the aroundNode (ie, put node below
	//		aroundNode, with left edges aligned).  If that fails it will try to put
	// 		the bottom-right corner of node where the top right corner of aroundNode is
	//		(ie, put node above aroundNode, with right edges aligned)
	//

	// get coordinates of aroundNode
	aroundNode = dojo.byId(aroundNode);
	var oldDisplay = aroundNode.style.display;
	aroundNode.style.display="";
	// #3172: use the slightly tighter border box instead of marginBox
	var aroundNodeW = aroundNode.offsetWidth; //mb.w;
	var aroundNodeH = aroundNode.offsetHeight; //mb.h;
	var aroundNodePos = dojo.coords(aroundNode, true);
	aroundNode.style.display=oldDisplay;

	// place the node around the calculated rectangle
	return dijit._placeOnScreenAroundRect(node,
		aroundNodePos.x, aroundNodePos.y, aroundNodeW, aroundNodeH,	// rectangle
		aroundCorners, layoutNode);
};

/*=====
dijit.__Rectangle = function(){
	//	x: Integer
	//		horizontal offset in pixels, relative to document body
	//	y: Integer
	//		vertical offset in pixels, relative to document body
	//	width: Integer
	//		width in pixels
	//	height: Integer
	//		height in pixels

	thix.x = x;
	this.y = y;
	thix.width = width;
	this.height = height;
}
=====*/

dijit.placeOnScreenAroundRectangle = function(
	/* DomNode */			node,
	/* dijit.__Rectangle */	aroundRect,
	/* Object */			aroundCorners,
	/* Function */			layoutNode){

	//	summary:
	//		Like dijit.placeOnScreenAroundNode(), except that the "around"
	//		parameter is an arbitrary rectangle on the screen (x, y, width, height)
	//		instead of a dom node.

	return dijit._placeOnScreenAroundRect(node,
		aroundRect.x, aroundRect.y, aroundRect.width, aroundRect.height,	// rectangle
		aroundCorners, layoutNode);
};

dijit._placeOnScreenAroundRect = function(
	/* DomNode */		node,
	/* Number */		x,
	/* Number */		y,
	/* Number */		width,
	/* Number */		height,
	/* Object */		aroundCorners,
	/* Function */		layoutNode){

	//	summary:
	//		Like dijit.placeOnScreenAroundNode(), except it accepts coordinates
	//		of a rectangle to place node adjacent to.

	// TODO: combine with placeOnScreenAroundRectangle()

	// Generate list of possible positions for node
	var choices = [];
	for(var nodeCorner in aroundCorners){
		choices.push( {
			aroundCorner: nodeCorner,
			corner: aroundCorners[nodeCorner],
			pos: {
				x: x + (nodeCorner.charAt(1) == 'L' ? 0 : width),
				y: y + (nodeCorner.charAt(0) == 'T' ? 0 : height)
			}
		});
	}

	return dijit._place(node, choices, layoutNode);
};

dijit.placementRegistry = new dojo.AdapterRegistry();
dijit.placementRegistry.register("node",
	function(n, x){
		return typeof x == "object" &&
			typeof x.offsetWidth != "undefined" && typeof x.offsetHeight != "undefined";
	},
	dijit.placeOnScreenAroundNode);
dijit.placementRegistry.register("rect",
	function(n, x){
		return typeof x == "object" &&
			"x" in x && "y" in x && "width" in x && "height" in x;
	},
	dijit.placeOnScreenAroundRectangle);

dijit.placeOnScreenAroundElement = function(
	/* DomNode */		node,
	/* Object */		aroundElement,
	/* Object */		aroundCorners,
	/* Function */		layoutNode){

	//	summary:
	//		Like dijit.placeOnScreenAroundNode(), except it accepts an arbitrary object
	//		for the "around" argument and finds a proper processor to place a node.

	return dijit.placementRegistry.match.apply(dijit.placementRegistry, arguments);
};


text:
require 'spec_helper'

feature "Enrollments" do
  scenario 'student request enrollment on a course and a manager accepts it' do
    make_dependencies!

    # Visit as unknown user
    visit root_url
    expect(page).to have_content 'Bem vindo aos cursos da Test Unit'
    expect(page).to have_content 'Rails for Designers'

    click_link 'Ver Curso'

    expect(page).to have_content 'MATRICULAR NESSE CURSO'
    expect(page).to have_content 'Já está matriculado? Faça o login'

    # Student login
    click_link 'Faça o login'

    fill_in 'user[email]', with: @student.email
    fill_in 'user[password]', with: @student.password
    click_button 'Entrar'

    expect(page).to have_content 'Rails for Designers'
    expect(page).to have_content 'MATRICULAR NESSE CURSO'
    expect(page).not_to have_content 'Já está matriculado? Faça o login'
    expect(page).not_to have_content 'Progresso'

    # Student enroll himself
    click_link 'MATRICULAR NESSE CURSO'

    expect(page).to have_content 'Pedido de matrícula realizado com sucesso!'

    click_link 'VOLTAR PARA PÁGINA DO CURSO'

    expect(page).to have_content 'MATRICULADO E AGUARDANDO APROVAÇÃO'

    click_link 'Intro'

    expect(page).to have_content 'Por enquanto você não pode acessar esta área.'

    click_link 'Sair'

    # Sign in manager
    sign_in_user(@manager)

    # Manager approve student request
    visit admin_unit_course_url(@unit, @course)
    click_link 'Painel'
    expect(page).to have_content '1 aluno está aguardando aprovação nesse curso.'
    click_link 'Ver novos alunos'
    expect(page).to have_content '1 pessoa está aguardando aprovação'
    within '#romulo' do
      click_link 'Aprovar'
    end

    click_link 'Sair'

    # Sign in as student
    visit root_url
    click_link 'Ver Curso'

    click_link 'Faça o login'
    fill_in 'user[email]', with: @student.email
    fill_in 'user[password]', with: @student.password
    click_button 'Entrar'

    # Show progress bar meaning student is enrolled
    expect(page).to have_content 'Progresso'
  end

  def make_dependencies!
    @manager = create_manager
    @unit = FactoryGirl.create(:unit, managers: [@manager])
    @course = FactoryGirl.create(:course, unit: @unit)
    @intro = Subject.create!(name: 'Intro', course: @course, published_at: Date.today)
    @views = Topic.create!(name: 'Views', subject: @intro)

    @student = FactoryGirl.create(:student, name: 'Rômulo', email: 'romulo@startae.com.br',
                                            works_on: 'ONG', scholarity_level: 'Mestrado',
                                            field_of_operation: 'Direito')
  end
end


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_6929979</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753463275</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Karpendonkse Plas</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Karpendonkse Plas</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Karpendonkse Plas</Appelation>
        <LocationNameType>lake</LocationNameType>
        <Comments>Karpendonksche Plas</Comments>
      </LocationName>
      <Coordinates>
        <Longitude>5.50055</Longitude>
        <Latitude>51.4531</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/6929979</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
package jenkins.util.java;

import static org.junit.Assert.*;
import static org.junit.Assume.*;
import org.junit.Test;
import org.jvnet.hudson.test.For;

@For(JavaUtils.class)
public class JavaUtilsTest {

    @Test
    public void verifyJava8() {
        assumeTrue("Test is for Java 8 only", System.getProperty("java.version").startsWith("1."));
        assertFalse("isRunningWithPostJava8() should return false on Java 8 and below", JavaUtils.isRunningWithPostJava8());
    }

    @Test
    public void verifyPostJava8() {
        assumeFalse("Test is for Java 9+ only", System.getProperty("java.version").startsWith("1."));
        assertTrue("isRunningWithPostJava8() should return true on Java 9 and above", JavaUtils.isRunningWithPostJava8());
    }
}


text:
class StateMachine;

class State{

    protected:

    Rectangles* window1rects;
    StateMachine* parent;

    SDLKey mode;
    bool ctrl, alt, shift;

    virtual void Activate();
    virtual void KeyboardDown();
    virtual void KeyboardUp();
    virtual void MouseMotion();
    virtual void MouseButtonDown();
    virtual void MouseButtonUp();
    virtual void Resize();
    virtual void Quit();

    public:

    virtual void eventHandler();

    void run();

    State(Rectangles* window1rectsIn, StateMachine* machineIn);
};

class mainState : public State{

    private:

    void Activate();
    void KeyboardDown();
    void KeyboardUp();
    void MouseMotion();
    void MouseButtonDown();
    void MouseButtonUp();
    void Resize();
    void Quit();

    public:

    mainState(Rectangles* theShapes, StateMachine* myParent);

};

class StateMachine{

private:
SDL_Surface *screen;

Rectangles* window1rects;
State* currentState;

public:

    StateMachine(State* stateIn);
    StateMachine();
    ~StateMachine();

    void changeState(State* nextState);

    SDL_Event* event;

};

#endif