text:
#ifndef AZURE_HTTP_PROXY_SERVER_CONNECTION_HPP
#define AZURE_HTTP_PROXY_SERVER_CONNECTION_HPP

#include <array>
#include <chrono>
#include <experimental/net>
#include <optional>

#include "encrypt.hpp"
#include "http_header_parser.hpp"
#include "http_proxy_server_connection_context.hpp"

namespace net = std::experimental::net;

namespace azure_proxy {

const std::size_t BUFFER_LENGTH = 2048;

class http_proxy_server_connection : public std::enable_shared_from_this<http_proxy_server_connection> {
    net::strand<net::io_context::executor_type> strand;
    net::ip::tcp::socket proxy_client_socket;
    net::ip::tcp::socket origin_server_socket;
    net::ip::tcp::resolver resolver;
    net::ip::tcp::resolver::results_type resolve_results;
    net::basic_waitable_timer<std::chrono::steady_clock> timer;
    std::array<char, BUFFER_LENGTH> upgoing_buffer_read;
    std::array<char, BUFFER_LENGTH> upgoing_buffer_write;
    std::array<char, BUFFER_LENGTH> downgoing_buffer_read;
    std::array<char, BUFFER_LENGTH> downgoing_buffer_write;
    rsa rsa_pri;
    std::vector<unsigned char> encrypted_cipher_info;
    std::unique_ptr<stream_encryptor> encryptor;
    std::unique_ptr<stream_decryptor> decryptor;
    std::string request_data;
    std::string modified_request_data;
    std::string response_data;
    std::string modified_response_data;
    std::optional<http_request_header> request_header;
    std::optional<http_response_header> response_header;
    http_proxy_server_connection_context connection_context;
    http_proxy_server_connection_read_request_context read_request_context;
    http_proxy_server_connection_read_response_context read_response_context;
private:
    http_proxy_server_connection(net::io_context& io_ctx, net::ip::tcp::socket&& proxy_client_socket);
public:
    ~http_proxy_server_connection();
    static std::shared_ptr<http_proxy_server_connection> create(net::io_context& io_ctx, net::ip::tcp::socket&& client_socket);
    void start();
private:
    void async_read_data_from_proxy_client(std::size_t at_least_size = 1, std::size_t at_most_size = BUFFER_LENGTH);
    void async_read_data_from_origin_server(bool set_timer = true, std::size_t at_least_size = 1, std::size_t at_most_size = BUFFER_LENGTH);
    void async_connect_to_origin_server();
    void async_write_request_header_to_origin_server();
    void async_write_response_header_to_proxy_client();
    void async_write_data_to_origin_server(const char* write_buffer, std::size_t offset, std::size_t size);
    void async_write_data_to_proxy_client(const char* write_buffer, std::size_t offset, std::size_t size);
    void start_tunnel_transfer();
    void report_error(const std::string& status_code, const std::string& status_description, const std::string& error_message);
    void report_authentication_failed();

    void set_timer();
    bool cancel_timer();

    void on_resolved(net::ip::tcp::resolver::results_type::const_iterator endpoint_iterator);
    void on_connect();
    void on_proxy_client_data_arrived(std::size_t bytes_transferred);
    void on_origin_server_data_arrived(std::size_t bytes_transferred);
    void on_proxy_client_data_written();
    void on_origin_server_data_written();
    void on_error(const std::error_code& error);
    void on_timeout();
};

} // namespace azure_proxy

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Persistent Session Observer
 *
 * @category   Mage
 * @package    Mage_Persistent
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Persistent_Model_Observer_Session
{
    /**
     * Create/Update and Load session when customer log in
     *
     * @param Varien_Event_Observer $observer
     */
    public function synchronizePersistentOnLogin(Varien_Event_Observer $observer)
    {
        /** @var $customer Mage_Customer_Model_Customer */
        $customer = $observer->getEvent()->getCustomer();
        // Check if customer is valid (remove persistent cookie for invalid customer)
        if (!$customer || !$customer->getId() || !Mage::helper('persistent/session')->isRememberMeChecked()) {
            Mage::getModel('persistent/session')->removePersistentCookie();
            return;
        }

        $persistentLifeTime = Mage::helper('persistent')->getLifeTime();
        // Delete persistent session, if persistent could not be applied
        if (Mage::helper('persistent')->isEnabled() && ($persistentLifeTime <= 0)) {
            // Remove current customer persistent session
            Mage::getModel('persistent/session')->deleteByCustomerId($customer->getId());
            return;
        }

        /** @var $sessionModel Mage_Persistent_Model_Session */
        $sessionModel = Mage::helper('persistent/session')->getSession();

        // Check if session is wrong or not exists, so create new session
        if (!$sessionModel->getId() || ($sessionModel->getCustomerId() != $customer->getId())) {
            $sessionModel = Mage::getModel('persistent/session')
                ->setLoadExpired()
                ->loadByCustomerId($customer->getId());
            if (!$sessionModel->getId()) {
                $sessionModel = Mage::getModel('persistent/session')
                    ->setCustomerId($customer->getId())
                    ->save();
            }

            Mage::helper('persistent/session')->setSession($sessionModel);
        }

        // Set new cookie
        if ($sessionModel->getId()) {
            Mage::getSingleton('core/cookie')->set(
                Mage_Persistent_Model_Session::COOKIE_NAME,
                $sessionModel->getKey(),
                $persistentLifeTime
            );
        }
    }

    /**
     * Unload persistent session (if set in config)
     *
     * @param Varien_Event_Observer $observer
     */
    public function synchronizePersistentOnLogout(Varien_Event_Observer $observer)
    {
        if (!Mage::helper('persistent')->isEnabled() || !Mage::helper('persistent')->getClearOnLogout()) {
            return;
        }

        /** @var $customer Mage_Customer_Model_Customer */
        $customer = $observer->getEvent()->getCustomer();
        // Check if customer is valid
        if (!$customer || !$customer->getId()) {
            return;
        }

        Mage::getModel('persistent/session')->removePersistentCookie();

        // Unset persistent session
        Mage::helper('persistent/session')->setSession(null);
    }

    /**
     * Synchronize persistent session info
     *
     * @param Varien_Event_Observer $observer
     */
    public function synchronizePersistentInfo(Varien_Event_Observer $observer)
    {
        if (!Mage::helper('persistent')->isEnabled() || !Mage::helper('persistent/session')->isPersistent()) {
            return;
        }

        /** @var $sessionModel Mage_Persistent_Model_Session */
        $sessionModel = Mage::helper('persistent/session')->getSession();

        /** @var $request Mage_Core_Controller_Request_Http */
        $request = $observer->getEvent()->getFront()->getRequest();

        // Quote Id could be changed only by logged in customer
        if (Mage::getSingleton('customer/session')->isLoggedIn()
            || ($request && $request->getActionName() == 'logout' && $request->getControllerName() == 'account')
        ) {
            $sessionModel->save();
        }
    }

    /**
     * Set Checked status of "Remember Me"
     *
     * @param Varien_Event_Observer $observer
     */
    public function setRememberMeCheckedStatus(Varien_Event_Observer $observer)
    {
        if (!Mage::helper('persistent')->canProcess($observer)
            || !Mage::helper('persistent')->isEnabled() || !Mage::helper('persistent')->isRememberMeEnabled()
        ) {
            return;
        }

        /** @var $controllerAction Mage_Core_Controller_Varien_Action */
        $controllerAction = $observer->getEvent()->getControllerAction();
        if ($controllerAction) {
            $rememberMeCheckbox = $controllerAction->getRequest()->getPost('persistent_remember_me');
            Mage::helper('persistent/session')->setRememberMeChecked((bool)$rememberMeCheckbox);
            if (
                $controllerAction->getFullActionName() == 'checkout_onepage_saveBilling'
                    || $controllerAction->getFullActionName() == 'customer_account_createpost'
            ) {
                Mage::getSingleton('checkout/session')->setRememberMeChecked((bool)$rememberMeCheckbox);
            }
        }
    }

    /**
     * Renew persistent cookie
     *
     * @param Varien_Event_Observer $observer
     */
    public function renewCookie(Varien_Event_Observer $observer)
    {
        if (!Mage::helper('persistent')->canProcess($observer)
            || !Mage::helper('persistent')->isEnabled() || !Mage::helper('persistent/session')->isPersistent()
        ) {
            return;
        }

        /** @var $controllerAction Mage_Core_Controller_Front_Action */
        $controllerAction = $observer->getEvent()->getControllerAction();

        if (Mage::getSingleton('customer/session')->isLoggedIn()
            || $controllerAction->getFullActionName() == 'customer_account_logout'
        ) {
            Mage::getSingleton('core/cookie')->renew(
                Mage_Persistent_Model_Session::COOKIE_NAME,
                Mage::helper('persistent')->getLifeTime()
            );
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Pelago\Emogrifier\Tests\Support\Traits;

use Pelago\Emogrifier\Tests\Support\Constraint\IsEquivalentCss;
use Pelago\Emogrifier\Tests\Support\Constraint\StringContainsCss;
use Pelago\Emogrifier\Tests\Support\Constraint\StringContainsCssCount;
use PHPUnit\Framework\TestCase;

/**
 * Provides assertion methods for use with CSS content where whitespace may vary.
 *
 * @mixin TestCase
 */
trait AssertCss
{
    /**
     * Like `assertSame` but allows for addition or removal of some unnecessary whitespace in the CSS.
     *
     * @param string $expected
     * @param string $actual
     * @param string $message
     */
    private static function assertEquivalentCss(string $expected, string $actual, string $message = ''): void
    {
        $constraint = new IsEquivalentCss($expected);

        self::assertThat($actual, $constraint, $message);
    }

    /**
     * Like `assertNotSame` but allows for addition or removal of some unnecessary whitespace in the CSS.
     *
     * @param string $expected
     * @param string $actual
     * @param string $message
     */
    private static function assertNotEquivalentCss(string $expected, string $actual, string $message = ''): void
    {
        $constraint = self::logicalNot(new IsEquivalentCss($expected));

        self::assertThat($actual, $constraint, $message);
    }

    /**
     * Like `assertContains` but allows for removal of some unnecessary whitespace from the CSS.
     *
     * @param string $needle
     * @param string $haystack
     * @param string $message
     */
    private static function assertContainsCss(string $needle, string $haystack, string $message = ''): void
    {
        $constraint = new StringContainsCss($needle);

        self::assertThat($haystack, $constraint, $message);
    }

    /**
     * Like `assertNotContains` and also enforces the assertion with removal of some unnecessary whitespace from the
     * CSS.
     *
     * @param string $needle
     * @param string $haystack
     * @param string $message
     */
    private static function assertNotContainsCss(string $needle, string $haystack, string $message = ''): void
    {
        $constraint = self::logicalNot(new StringContainsCss($needle));

        static::assertThat($haystack, $constraint, $message);
    }

    /**
     * Asserts that a string of CSS occurs exactly a certain number of times in the result, allowing for removal of some
     * unnecessary whitespace.
     *
     * @param int $expectedCount
     * @param string $needle
     * @param string $haystack
     * @param string $message
     */
    private static function assertContainsCssCount(
        int $expectedCount,
        string $needle,
        string $haystack,
        string $message = ''
    ): void {
        $constraint = new StringContainsCssCount($expectedCount, $needle);

        self::assertThat($haystack, $constraint, $message);
    }

    /**
     * @param string $css
     *
     * @return IsEquivalentCss
     */
    private static function isEquivalentCss(string $css): IsEquivalentCss
    {
        return new IsEquivalentCss($css);
    }

    /**
     * @param string $needle
     *
     * @return StringContainsCss
     */
    private static function stringContainsCss(string $needle): StringContainsCss
    {
        return new StringContainsCss($needle);
    }

    /**
     * @param int $expectedCount
     * @param string $needle
     *
     * @return StringContainsCssCount
     */
    private static function stringContainsCssCount(int $expectedCount, string $needle): StringContainsCssCount
    {
        return new StringContainsCssCount($expectedCount, $needle);
    }
}


text:
import base64
import datetime
import json

from protorpc import message_types
from protorpc import messages
from protorpc import util
import unittest2

from apitools.base.py import encoding
from apitools.base.py import exceptions

class SimpleMessage(messages.Message):
  field = messages.StringField(1)
  repfield = messages.StringField(2, repeated=True)

class BytesMessage(messages.Message):
  field = messages.BytesField(1)
  repfield = messages.BytesField(2, repeated=True)

class TimeMessage(messages.Message):
  timefield = message_types.DateTimeField(3)

@encoding.MapUnrecognizedFields('additional_properties')
class AdditionalPropertiesMessage(messages.Message):

  class AdditionalProperty(messages.Message):
    key = messages.StringField(1)
    value = messages.StringField(2)

  additional_properties = messages.MessageField(
      AdditionalProperty, 1, repeated=True)

class CompoundPropertyType(messages.Message):
  index = messages.IntegerField(1)
  name = messages.StringField(2)

class MessageWithEnum(messages.Message):

  class ThisEnum(messages.Enum):
    VALUE_ONE = 1
    VALUE_TWO = 2

  field_one = messages.EnumField(ThisEnum, 1)
  field_two = messages.EnumField(ThisEnum, 2, default=ThisEnum.VALUE_TWO)
  ignored_field = messages.EnumField(ThisEnum, 3)

@encoding.MapUnrecognizedFields('additional_properties')
class AdditionalMessagePropertiesMessage(messages.Message):

  class AdditionalProperty(messages.Message):
    key = messages.StringField(1)
    value = messages.MessageField(CompoundPropertyType, 2)

  additional_properties = messages.MessageField(
      'AdditionalProperty', 1, repeated=True)

class HasNestedMessage(messages.Message):
  nested = messages.MessageField(AdditionalPropertiesMessage, 1)
  nested_list = messages.StringField(2, repeated=True)

class ExtraNestedMessage(messages.Message):
  nested = messages.MessageField(HasNestedMessage, 1)

class MessageWithRemappings(messages.Message):

  class SomeEnum(messages.Enum):
    enum_value = 1
    second_value = 2

  enum_field = messages.EnumField(SomeEnum, 1)
  double_encoding = messages.EnumField(SomeEnum, 2)
  another_field = messages.StringField(3)
  repeated_enum = messages.EnumField(SomeEnum, 4, repeated=True)
  repeated_field = messages.StringField(5, repeated=True)

encoding.AddCustomJsonEnumMapping(MessageWithRemappings.SomeEnum,
                                  'enum_value', 'wire_name')
encoding.AddCustomJsonFieldMapping(MessageWithRemappings,
                                   'double_encoding', 'doubleEncoding')
encoding.AddCustomJsonFieldMapping(MessageWithRemappings,
                                   'another_field', 'anotherField')
encoding.AddCustomJsonFieldMapping(MessageWithRemappings,
                                   'repeated_field', 'repeatedField')

class EncodingTest(unittest2.TestCase):

  def testCopyProtoMessage(self):
    msg = SimpleMessage(field='abc')
    new_msg = encoding.CopyProtoMessage(msg)
    self.assertEqual(msg.field, new_msg.field)
    msg.field = 'def'
    self.assertNotEqual(msg.field, new_msg.field)

  def testBytesEncoding(self):
    b64_str = 'AAc+'
    b64_msg = '{"field": "%s"}' % b64_str
    urlsafe_b64_str = 'AAc-'
    urlsafe_b64_msg = '{"field": "%s"}' % urlsafe_b64_str
    data = base64.b64decode(b64_str)
    msg = BytesMessage(field=data)
    self.assertEqual(msg, encoding.JsonToMessage(BytesMessage, urlsafe_b64_msg))
    self.assertEqual(msg, encoding.JsonToMessage(BytesMessage, b64_msg))
    self.assertEqual(urlsafe_b64_msg, encoding.MessageToJson(msg))

    enc_rep_msg = '{"repfield": ["%(b)s", "%(b)s"]}' % {'b': urlsafe_b64_str}
    rep_msg = BytesMessage(repfield=[data, data])
    self.assertEqual(rep_msg, encoding.JsonToMessage(BytesMessage, enc_rep_msg))
    self.assertEqual(enc_rep_msg, encoding.MessageToJson(rep_msg))

  def testIncludeFields(self):
    msg = SimpleMessage()
    self.assertEqual('{}', encoding.MessageToJson(msg))
    self.assertEqual(
        '{"field": null}',
        encoding.MessageToJson(msg, include_fields=['field']))
    self.assertEqual(
        '{"repfield": []}',
        encoding.MessageToJson(msg, include_fields=['repfield']))

  def testNestedIncludeFields(self):
    msg = HasNestedMessage(
        nested=AdditionalPropertiesMessage(
            additional_properties=[]))
    self.assertEqual(
        '{"nested": null}',
        encoding.MessageToJson(msg, include_fields=['nested']))
    self.assertEqual(
        '{"nested": {"additional_properties": []}}',
        encoding.MessageToJson(
            msg, include_fields=['nested.additional_properties']))
    msg = ExtraNestedMessage(nested=msg)
    self.assertEqual(
        '{"nested": {"nested": null}}',
        encoding.MessageToJson(msg, include_fields=['nested.nested']))
    self.assertEqual(
        '{"nested": {"nested_list": []}}',
        encoding.MessageToJson(msg, include_fields=['nested.nested_list']))
    self.assertEqual(
        '{"nested": {"nested": {"additional_properties": []}}}',
        encoding.MessageToJson(
            msg, include_fields=['nested.nested.additional_properties']))

  def testAdditionalPropertyMapping(self):
    msg = AdditionalPropertiesMessage()
    msg.additional_properties = [
        AdditionalPropertiesMessage.AdditionalProperty(
            key='key_one', value='value_one'),
        AdditionalPropertiesMessage.AdditionalProperty(
            key='key_two', value='value_two'),
    ]

    encoded_msg = encoding.MessageToJson(msg)
    self.assertEqual(
        {'key_one': 'value_one', 'key_two': 'value_two'},
        json.loads(encoded_msg))

    new_msg = encoding.JsonToMessage(type(msg), encoded_msg)
    self.assertEqual(
        set(('key_one', 'key_two')),
        set([x.key for x in new_msg.additional_properties]))
    self.assertIsNot(msg, new_msg)

    new_msg.additional_properties.pop()
    self.assertEqual(1, len(new_msg.additional_properties))
    self.assertEqual(2, len(msg.additional_properties))

  def testAdditionalMessageProperties(self):
    json_msg = '{"input": {"index": 0, "name": "output"}}'
    result = encoding.JsonToMessage(
        AdditionalMessagePropertiesMessage, json_msg)
    self.assertEqual(1, len(result.additional_properties))
    self.assertEqual(0, result.additional_properties[0].value.index)

  def testNestedFieldMapping(self):
    nested_msg = AdditionalPropertiesMessage()
    nested_msg.additional_properties = [
        AdditionalPropertiesMessage.AdditionalProperty(
            key='key_one', value='value_one'),
        AdditionalPropertiesMessage.AdditionalProperty(
            key='key_two', value='value_two'),
    ]
    msg = HasNestedMessage(nested=nested_msg)

    encoded_msg = encoding.MessageToJson(msg)
    self.assertEqual(
        {'nested': {'key_one': 'value_one', 'key_two': 'value_two'}},
        json.loads(encoded_msg))

    new_msg = encoding.JsonToMessage(type(msg), encoded_msg)
    self.assertEqual(
        set(('key_one', 'key_two')),
        set([x.key for x in new_msg.nested.additional_properties]))

    new_msg.nested.additional_properties.pop()
    self.assertEqual(1, len(new_msg.nested.additional_properties))
    self.assertEqual(2, len(msg.nested.additional_properties))

  def testValidEnums(self):
    message_json = '{"field_one": "VALUE_ONE"}'
    message = encoding.JsonToMessage(MessageWithEnum, message_json)
    self.assertEqual(MessageWithEnum.ThisEnum.VALUE_ONE, message.field_one)
    self.assertEqual(MessageWithEnum.ThisEnum.VALUE_TWO, message.field_two)
    self.assertEqual(json.loads(message_json),
                     json.loads(encoding.MessageToJson(message)))

  def testIgnoredEnums(self):
    json_with_typo = '{"field_one": "VALUE_OEN"}'
    message = encoding.JsonToMessage(MessageWithEnum, json_with_typo)
    self.assertEqual(None, message.field_one)
    self.assertEqual(('VALUE_OEN', messages.Variant.ENUM),
                     message.get_unrecognized_field_info('field_one'))
    self.assertEqual(json.loads(json_with_typo),
                     json.loads(encoding.MessageToJson(message)))

    empty_json = ''
    message = encoding.JsonToMessage(MessageWithEnum, empty_json)
    self.assertEqual(None, message.field_one)

  def testIgnoredEnumsWithDefaults(self):
    json_with_typo = '{"field_two": "VALUE_OEN"}'
    message = encoding.JsonToMessage(MessageWithEnum, json_with_typo)
    self.assertEqual(MessageWithEnum.ThisEnum.VALUE_TWO, message.field_two)
    self.assertEqual(json.loads(json_with_typo),
                     json.loads(encoding.MessageToJson(message)))

  def testUnknownNestedRoundtrip(self):
    json_message = '{"field": "abc", "submessage": {"a": 1, "b": "foo"}}'
    message = encoding.JsonToMessage(SimpleMessage, json_message)
    self.assertEqual(json.loads(json_message),
                     json.loads(encoding.MessageToJson(message)))

  def testJsonDatetime(self):
    msg = TimeMessage(timefield=datetime.datetime(
        2014, 7, 2, 23, 33, 25, 541000,
        tzinfo=util.TimeZoneOffset(datetime.timedelta(0))))
    self.assertEqual(
        '{"timefield": "2014-07-02T23:33:25.541000+00:00"}',
        encoding.MessageToJson(msg))

  def testEnumRemapping(self):
    msg = MessageWithRemappings(
        enum_field=MessageWithRemappings.SomeEnum.enum_value)
    json_message = encoding.MessageToJson(msg)
    self.assertEqual('{"enum_field": "wire_name"}', json_message)
    self.assertEqual(
        msg, encoding.JsonToMessage(MessageWithRemappings, json_message))

  def testRepeatedEnumRemapping(self):
    msg = MessageWithRemappings(
        repeated_enum=[
            MessageWithRemappings.SomeEnum.enum_value,
            MessageWithRemappings.SomeEnum.second_value,
        ])
    json_message = encoding.MessageToJson(msg)
    self.assertEqual('{"repeated_enum": ["wire_name", "second_value"]}',
                     json_message)
    self.assertEqual(
        msg, encoding.JsonToMessage(MessageWithRemappings, json_message))

  def testFieldRemapping(self):
    msg = MessageWithRemappings(another_field='abc')
    json_message = encoding.MessageToJson(msg)
    self.assertEqual('{"anotherField": "abc"}', json_message)
    self.assertEqual(
        msg, encoding.JsonToMessage(MessageWithRemappings, json_message))

  def testRepeatedFieldRemapping(self):
    msg = MessageWithRemappings(repeated_field=['abc', 'def'])
    json_message = encoding.MessageToJson(msg)
    self.assertEqual('{"repeatedField": ["abc", "def"]}', json_message)
    self.assertEqual(
        msg, encoding.JsonToMessage(MessageWithRemappings, json_message))

  def testMultipleRemapping(self):
    msg = MessageWithRemappings(
        double_encoding=MessageWithRemappings.SomeEnum.enum_value)
    json_message = encoding.MessageToJson(msg)
    self.assertEqual('{"doubleEncoding": "wire_name"}', json_message)
    self.assertEqual(
        msg, encoding.JsonToMessage(MessageWithRemappings, json_message))

  def testNoRepeatedRemapping(self):
    self.assertRaises(
        exceptions.InvalidDataError,
        encoding.AddCustomJsonFieldMapping,
        MessageWithRemappings, 'double_encoding', 'something_else')
    self.assertRaises(
        exceptions.InvalidDataError,
        encoding.AddCustomJsonFieldMapping,
        MessageWithRemappings, 'enum_field', 'anotherField')
    self.assertRaises(
        exceptions.InvalidDataError,
        encoding.AddCustomJsonEnumMapping,
        MessageWithRemappings.SomeEnum, 'enum_value', 'another_name')
    self.assertRaises(
        exceptions.InvalidDataError,
        encoding.AddCustomJsonEnumMapping,
        MessageWithRemappings.SomeEnum, 'second_value', 'wire_name')

  def testMessageToRepr(self):
    # pylint:disable=bad-whitespace, Using the same string returned by
    # MessageToRepr, with the module names fixed.
    msg = SimpleMessage(field='field',repfield=['field','field',],)
    self.assertEqual(
        encoding.MessageToRepr(msg),
        r"%s.SimpleMessage(field='field',repfield=['field','field',],)" % (
            __name__,))
    self.assertEqual(
        encoding.MessageToRepr(msg, no_modules=True),
        r"SimpleMessage(field='field',repfield=['field','field',],)")

  def testMessageToReprWithTime(self):
    msg = TimeMessage(timefield=datetime.datetime(
        2014, 7, 2, 23, 33, 25, 541000,
        tzinfo=util.TimeZoneOffset(datetime.timedelta(0))))
    self.assertEqual(
        encoding.MessageToRepr(msg, multiline=True),
        # pylint:disable=line-too-long, Too much effort to make MessageToRepr
        # wrap lines properly.
        """\
%s.TimeMessage(
    timefield=datetime.datetime(2014, 7, 2, 23, 33, 25, 541000, tzinfo=protorpc.util.TimeZoneOffset(datetime.timedelta(0))),
)""" % __name__)
    self.assertEqual(
        encoding.MessageToRepr(msg, multiline=True, no_modules=True),
        # pylint:disable=line-too-long, Too much effort to make MessageToRepr
        # wrap lines properly.
        """\
TimeMessage(
    timefield=datetime.datetime(2014, 7, 2, 23, 33, 25, 541000, tzinfo=TimeZoneOffset(datetime.timedelta(0))),
)""")

if __name__ == '__main__':
  unittest2.main()


text:
<?php

declare(strict_types=1);

namespace Scheb\Tombstone\Logger\Formatter;

use Scheb\Tombstone\Core\Model\StackTrace;
use Scheb\Tombstone\Core\Model\StackTraceFrame;
use Scheb\Tombstone\Core\Model\Vampire;

class JsonFormatter implements FormatterInterface
{
    public function format(Vampire $vampire): string
    {
        return json_encode([
            'arguments' => $vampire->getArguments(),
            'file' => $vampire->getFile()->getReferencePath(),
            'line' => $vampire->getLine(),
            'method' => $vampire->getMethod(),
            'stackTrace' => $this->getStackTraceValues($vampire->getStackTrace()),
            'metadata' => $vampire->getMetadata(),
            'invocationDate' => $vampire->getInvocationDate(),
            'invoker' => $vampire->getInvoker(),
        ]).PHP_EOL;
    }

    private function getStackTraceValues(StackTrace $stackTrace): array
    {
        return array_map(function (StackTraceFrame $frame): array {
            return [
                'file' => $frame->getFile()->getReferencePath(),
                'line' => $frame->getLine(),
                'method' => $frame->getMethod(),
            ];
        }, iterator_to_array($stackTrace));
    }
}


text:
var resolve = require("path").resolve
var writeFileSync = require("graceful-fs").writeFileSync

var mkdirp = require("mkdirp")
var mr = require("npm-registry-mock")
var osenv = require("osenv")
var rimraf = require("rimraf")
var test = require("tap").test

var common = require("../common-tap.js")
var toNerfDart = require("../../lib/config/nerf-dart.js")

var pkg = resolve(__dirname, "shrinkwrap-scoped-auth")
var outfile = resolve(pkg, "_npmrc")
var modules = resolve(pkg, "node_modules")
var tarballPath = "/scoped-underscore/-/scoped-underscore-1.3.1.tgz"
var tarballURL = common.registry + tarballPath
var tarball = resolve(__dirname, "../fixtures/scoped-underscore-1.3.1.tgz")

var server

var EXEC_OPTS = {
  cwd : pkg
}

function mocks (server) {
  var auth = "Bearer 0xabad1dea"
  server.get(tarballPath, { authorization : auth }).replyWithFile(200, tarball)
  server.get(tarballPath).reply(401, {
    error  : "unauthorized",
    reason : "You are not authorized to access this db."
  })
}

test("setup", function (t) {
  mr({ port : common.port, plugin : mocks }, function (err, s) {
    server = s
    t.ok(s, "set up mock registry")
    setup()
    t.end()
  })
})

test("authed npm install with shrinkwrapped scoped package", function (t) {
  common.npm(
    [
      "install",
      "--loglevel", "silent",
      "--fetch-retries", 0,
      "--userconfig", outfile
    ],
    EXEC_OPTS,
    function (err, code, stdout, stderr) {
      t.ifError(err, "test runner executed without error")
      t.equal(code, 0, "npm install exited OK")
      t.notOk(stderr, "no output on stderr")
      t.equal(
        stdout,
        "@scoped/underscore@1.3.1 node_modules/@scoped/underscore\n",
        "module installed where expected"
      )

      t.end()
    }
  )
})

test("cleanup", function (t) {
  server.close()
  cleanup()
  t.end()
})

var contents = "@scoped:registry="+common.registry+"\n" +
               toNerfDart(common.registry)+":_authToken=0xabad1dea\n"

var json = {
  name : "test-package-install",
  version : "1.0.0"
}

var shrinkwrap = {
  name : "test-package-install",
  version : "1.0.0",
  dependencies : {
    "@scoped/underscore" : {
      resolved : tarballURL,
      from     : ">=1.3.1 <2",
      version  : "1.3.1"
    }
  }
}

function setup () {
  cleanup()
  mkdirp.sync(modules)
  writeFileSync(resolve(pkg, "package.json"), JSON.stringify(json, null, 2)+"\n")
  writeFileSync(outfile, contents)
  writeFileSync(
    resolve(pkg, "npm-shrinkwrap.json"),
    JSON.stringify(shrinkwrap, null, 2)+"\n"
  )
}

function cleanup() {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg)
}


text:
/* tslint:disable:no-unused-variable */
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DebugElement} from '@angular/core';

import {ProjectTableComponent} from './project-table.component';

describe('ProjectTableComponent', () => {
    let component: ProjectTableComponent;
    let fixture: ComponentFixture<ProjectTableComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ ProjectTableComponent ]
        })
        .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ProjectTableComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});


text:
def cleanup_application_node(tree):
    """ The only node that should be a child of the application node is the
    resources node. """

    children = []

    for child in tree.children:
        if child.name != "resources":
            child.parent = None
        else:
            children.append(child)

    tree.children = children


text:
using System;
using NUnit.Framework;

namespace codility_trial_tasks_pit_depth.test
{
    [TestFixture]
    public class SolutionTests
    {
        [Test]
        public void Solution_Run_Test1()
        {
            Assert.AreNotEqual(true, false);
        }
    }
}


text:
package echoes.act8;

import java.nio.ByteOrder;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class EchoesMessageEncoder extends ProtocolEncoderAdapter {

    public void encode(IoSession session, Object message,
            ProtocolEncoderOutput out) throws Exception
    {
        EchoesMessage m = (EchoesMessage) message;

        int cap = 1 + 4 + m.getLength();
        ByteBuffer d = ByteBuffer.allocate(cap);
        d.order(ByteOrder.LITTLE_ENDIAN);

        d.put(m.getMark());
        d.putInt(m.getLength());
        d.put(m.getData());
        d.flip();

        out.write(d);
    }
}


text:
package com.getui.logful.server.entity;

import com.getui.logful.server.Constants;
import com.getui.logful.server.util.StringUtil;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

@Document(collection = "log_message")
public class LogMessage {

    public static final int STATE_NORMAL = 0x01;

    public static final int STATE_SUCCESSFUL = 0x02;

    @Id
    private String id;

    private String platform;

    private String uid;

    private String appId;

    /**
     * Logger name
     */
    private String loggerName;

    private long timestamp;

    private String tag;

    private String message;

    /**
     * Log message layout template
     */
    private String msgLayout;

    private int level;

    /**
     * 是否上传到 graylog
     */
    private int status;

    /**
     * 别名
     */
    private String alias;

    private String attachment;

    private Date writeDate;

    public LogMessage() {
        this.status = STATE_NORMAL;
    }

    public static LogMessage create(int platform, String uid, String appId,
                                    String loggerName, String msgLayout,
                                    int level, long timestamp, String tag,
                                    String msg, String alias, String attachment) {
        LogMessage logMessage = new LogMessage();
        logMessage.setPlatform(StringUtil.platformString(platform));
        logMessage.setUid(uid);
        logMessage.setAppId(appId);
        logMessage.setLoggerName(loggerName);
        logMessage.setMsgLayout(msgLayout);
        logMessage.setLevel(level);
        logMessage.setTimestamp(timestamp);
        logMessage.setTag(tag);
        logMessage.setMessage(msg);
        logMessage.setStatus(STATE_NORMAL);
        logMessage.setAlias(alias);
        logMessage.setAttachment(attachment);
        logMessage.setWriteDate(new Date());
        return logMessage;
    }

    public static LogMessage create(CrashFileMeta fileMeta) {
        return LogMessage.create(fileMeta.getPlatform(), fileMeta.getUid(),
                fileMeta.getAppId(), "crash", null, Constants.FATAL,
                fileMeta.getDate().getTime(), "CRASH_FILE_ID",
                fileMeta.getId(), fileMeta.getAlias(), null);
    }

    public Date getWriteDate() {
        return writeDate;
    }

    public void setWriteDate(Date writeDate) {
        this.writeDate = writeDate;
    }

    public String getPlatform() {
        return platform;
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getLoggerName() {
        return loggerName;
    }

    public void setLoggerName(String loggerName) {
        this.loggerName = loggerName;
    }

    public String getMsgLayout() {
        return msgLayout;
    }

    public void setMsgLayout(String msgLayout) {
        this.msgLayout = msgLayout;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getLevel() {
        return level;
    }

    public LogMessage setLevel(int level) {
        this.level = level;
        return this;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public LogMessage setTimestamp(long timestamp) {
        this.timestamp = timestamp;
        return this;
    }

    public String getTag() {
        return tag;
    }

    public LogMessage setTag(String tag) {
        this.tag = tag;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public LogMessage setMessage(String message) {
        this.message = message;
        return this;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getAlias() {
        return alias;
    }

    public void setAlias(String alias) {
        this.alias = alias;
    }

    public String getAttachment() {
        return attachment;
    }

    public void setAttachment(String attachment) {
        this.attachment = attachment;
    }
}


text:
using buzz::Jid;
using buzz::Status;
using buzz::XmppRosterModule;
using buzz::XmlElement;
using buzz::XmppSubscriptionRequestType;
using buzz::XmppRosterModule;
using buzz::XmppPresence;
using buzz::XmppRosterContact;

namespace tuenti {

static bool IsUtf8FirstByte(int c) {
  return (((c) & 0x80) == 0) ||  // is single byte
         ((unsigned char) ((c) - 0xc0) < 0x3e);  // or is lead byte
}

static bool IsXmlSpace(int ch) {
  return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}

static bool ListContainsToken(const std::string & list,
    const std::string & token) {
  size_t i = list.find(token);
  if (i == std::string::npos || token.empty())
    return false;
  bool boundary_before = (i == 0 || IsXmlSpace(list[i - 1]));
  bool boundary_after = (i == list.length() - token.length()
      || IsXmlSpace(list[i + token.length()]));
  return boundary_before && boundary_after;
}

RosterHandler::RosterHandler(){
  LOG(LS_INFO) << "RosterHandler::RosterHandler()";
}
  //! A request for a subscription has come in.
  //! Typically, the UI will ask the user if it is okay to let the requester
  //! get presence notifications for the user.  The response is send back
  //! by calling ApproveSubscriber or CancelSubscriber.
void RosterHandler::SubscriptionRequest(XmppRosterModule* roster,
                                   const Jid& requesting_jid,
                                   XmppSubscriptionRequestType type,
                                   const XmlElement* raw_xml){
  LOG(LS_INFO) << "RosterHandler::SubscriptionRequest()";
}

  //! Some type of presence error has occured
void RosterHandler::SubscriptionError(XmppRosterModule* roster, const Jid& from,
                                      const XmlElement* raw_xml){
  LOG(LS_INFO) << "RosterHandler::SubscriptionError()";
}

void RosterHandler::RosterError(XmppRosterModule* roster,
                                const XmlElement* raw_xml){
  LOG(LS_INFO) << "RosterHandler::RosterError()";
}

  //! New presence information has come in
  //! The user is notified with the presence object directly.  This info is also
  //! added to the store accessable from the engine.
void RosterHandler::IncomingPresenceChanged(XmppRosterModule* roster,
                               const XmppPresence* presence){
  LOG(LS_INFO) << "RosterHandler::IncomingPresenceChanged()";

  const XmlElement* elem = presence->raw_xml();
  Status s;
  FillStatus(presence->jid(), elem, &s);

  SignalPresenceChanged(presence->jid().BareJid().Str(), presence->available(),
		  presence->presence_show());
}

  //! A contact has changed
  //! This indicates that the data for a contact may have changed.  No
  //! contacts have been added or removed.
void RosterHandler::ContactChanged(XmppRosterModule* roster,
                      const XmppRosterContact* old_contact,
                      size_t index){
  LOG(LS_INFO) << "RosterHandler::ContactChanged()";
}

  //! A set of contacts have been added
  //! These contacts may have been added in response to the original roster
  //! request or due to a "roster push" from the server.
void RosterHandler::ContactsAdded(XmppRosterModule* roster,
                     size_t index, size_t number){
  LOG(LS_INFO) << "RosterHandler::ContactsAdded()";
  for (size_t i = 0; i < number; ++i) {
	  const XmppRosterContact *contact = roster->GetRosterContact(index+i);
	  const XmppPresence *presence = roster->GetIncomingPresenceForJid(contact->jid(), i);

	  int available = 0;
	  int show = 0;
	  if (presence != NULL) {
		  available = presence->available();
		  show = presence->presence_show();
	  }
	  SignalContactAdded(contact->jid().Str(), contact->name(), available, show);
  }
}

  //! A contact has been removed
  //! This contact has been removed form the list.
void RosterHandler::ContactRemoved(XmppRosterModule* roster,
                      const XmppRosterContact* removed_contact,
                      size_t index){
  LOG(LS_INFO) << "RosterHandler::ContactRemoved()";
}

void RosterHandler::FillStatus(const Jid& from, const XmlElement* stanza,
    Status* s) {
  s->set_jid(from);
  if (stanza->Attr(buzz::QN_TYPE) == buzz::STR_UNAVAILABLE) {
    s->set_available(false);
  } else {
    s->set_available(true);
    const XmlElement * status = stanza->FirstNamed(buzz::QN_STATUS);
    if (status != NULL) {
      s->set_status(status->BodyText());

      // Truncate status messages longer than 300 bytes
      if (s->status().length() > 300) {
        size_t len = 300;

        // Be careful not to split legal utf-8 chars in half
        while (!IsUtf8FirstByte(s->status()[len]) && len > 0) {
          len -= 1;
        }
        std::string truncated(s->status(), 0, len);
        s->set_status(truncated);
      }
    }

    //TODO:: fix priority and by importing FromString from the correct place
    //const XmlElement * priority = stanza->FirstNamed(buzz::QN_PRIORITY);
    //if (priority != NULL) {
    //  int pri = 0;
    //  if (talk_base::FromString(priority->BodyText(), &pri)) {
    //    s->set_priority(pri);
    //  }
    //}
    //
    //

    const XmlElement * show = stanza->FirstNamed(buzz::QN_SHOW);
    if (show == NULL || show->FirstChild() == NULL) {
      s->set_show(Status::SHOW_ONLINE);
    } else {
      if (show->BodyText() == "away") {
        s->set_show(Status::SHOW_AWAY);
      } else if (show->BodyText() == "xa") {
        s->set_show(Status::SHOW_XA);
      } else if (show->BodyText() == "dnd") {
        s->set_show(Status::SHOW_DND);
      } else if (show->BodyText() == "chat") {
        s->set_show(Status::SHOW_CHAT);
      } else {
        s->set_show(Status::SHOW_ONLINE);
      }
    }

#ifdef TUENTI_CUSTOM_BUILD
    const XmlElement * td = stanza->FirstNamed(buzz::QN_TUENTI_DATA);
    if (td != NULL) {
      const XmlElement * caps = td->FirstNamed(buzz::QN_TUENTI_CAPS);
      const XmlElement * voice_v1 = caps->FirstNamed(buzz::QN_TUENTI_VOICE);
      if (voice_v1 != NULL) {
        s->set_voice_capability(true);
        s->set_know_capabilities(true);
        s->set_caps_node("http://www.google.com/xmpp/client/caps");
        s->set_version("1.0");
      }
    }
#else
    const XmlElement * caps = stanza->FirstNamed(buzz::QN_CAPS_C);
    if (caps != NULL) {
      std::string node = caps->Attr(buzz::QN_NODE);
      std::string ver = caps->Attr(buzz::QN_VER);
      std::string exts = caps->Attr(buzz::QN_EXT);

      s->set_know_capabilities(true);
      s->set_caps_node(node);
      s->set_version(ver);

      if (ListContainsToken(exts, "voice-v1")) {
        s->set_voice_capability(true);
      }
      if (ListContainsToken(exts, "video-v1")) {
        s->set_video_capability(true);
      }
    }
#endif

    const XmlElement* delay = stanza->FirstNamed(buzz::kQnDelayX);
    if (delay != NULL) {
      // Ideally we would parse this according to the Psuedo ISO-8601 rules
      // that are laid out in JEP-0082:
      // http://www.jabber.org/jeps/jep-0082.html
      std::string stamp = delay->Attr(buzz::kQnStamp);
      s->set_sent_time(stamp);
    }

    const XmlElement* nick = stanza->FirstNamed(buzz::QN_NICKNAME);
    if (nick) {
      s->set_nick(nick->BodyText());
    }
  }
}
}  // namespace tuenti


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta charset='utf-8'>
<title>Jeux de Sport</title>
<meta name="description" content="Funlabo est un site dédié aux jeux de sports en tout genre." />
<meta name="keywords" content="jeux de sport,sport,sports,foot,voiture,moto,basket,golf,jeu,jeux" />
<meta property="og:title" content="Jeux de Sport" />
<meta property="og:description" content="Funlabo est un site dédié aux jeux de sports en tout genre." />
<meta property="og:site_name" content="funlabo.com" />
<meta property="og:image" content="http://www.funlabo.com/m/img/logo-sharing.jpg" />
<meta property="og:url" content="http://www.funlabo.com/" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@FunLabo_com" />
<meta name="twitter:title" content="Jeux de Sport" />
<meta name="twitter:description" content="Funlabo est un site dédié aux jeux de sports en tout genre." />
<meta name="twitter:image" content="http://www.funlabo.com/m/img/logo-sharing.jpg" />

<link href="http://www.funlabo.com/m/style.css" rel="stylesheet" type="text/css" media="all" />

<link href="http://www.funlabo.com/feed" rel="alternate" title="ATOM" type="application/atom+xml" />
<link href="http://www.funlabo.com/feed.rss" rel="alternate" title="RSS" type="application/rss+xml" />

Jeux de Sport

Funlabo est un site dédié aux jeux de sports en tout genre.

Plus de 400 jeux sont présentés dans 47 disciplines différentes.

Tous les jeux sont gratuits et disponibles sans téléchargements.

Jeux de Foot

Jeux de Voiture

Jeux de Moto

Jeux de Golf

Jeux de Basket

Jeux de Formule 1

Jeux de Tennis

Jeux de Ping Pong

Jeux de Billard

Jeux d'Athlétisme

Jeux de Sports de Glisse

Bowling

Jeux d'aviation

Jeux de Lancer

Jeux de Volley

Voici d'autres catégories :

      - Air Hockey

      - Jeux de Baseball

      - Jeux de Skate

      - Jeux de Boxe

      - Jeux de Ski

      - Jeux de Course

      - Jeux de Hockey

      - Jeux de Football américain

Si vous n'avez pas encore trouvé votre bonheur, essayez ici

Air Hockey

Athlétisme

Aviation

Baseball

Basket

Billard

Bowling

Boxe

Course

Foot

Football américain

Formule 1

Glisse

Golf

Hockey

Lancer

Moto

Ping Pong

Skate

Ski

Tennis

Voiture

Volley

Autres Sports

<form action="http://www.funlabo.com/recherche.htm" id="q">
    <input type="hidden" name="cx" value="partner-pub-1883270274468008:bcpbn9-8md1" />
    <input type="hidden" name="cof" value="FORID:9" />
    <input type="hidden" name="ie" value="ISO-8859-1" />
    <input type="text" name="q" value="Rechercher..." onFocus="if(this.value=='Rechercher...')this.value='';" onBlur="if(this.value=='')this.value='Rechercher...';" id="qt" />
    <input type="submit" name="sa" value=" " id="qs" />
</form>

        Follow @FunLabo_com

©2007-2013 Funlabo.com -  Contact -  Aide -  Plan du Site -

Partenaires :
        Jeux d'Action -
        Jeux d'Animaux -
        Jeux d'Aventure -
        Jeux de Stratégie

International :
Allemagne - Espagne

Test  - Test :


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Tiponorma;

/**
 * TiponormaSearch represents the model behind the search form about `app\models\Tiponorma`.
 */
class TiponormaSearch extends Tiponorma
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'usuariocrea', 'usuariomodifica'], 'integer'],
            [['tiponorma', 'fechacrea', 'fechamodifica'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Tiponorma::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'usuariocrea' => $this->usuariocrea,
            'fechacrea' => $this->fechacrea,
            'usuariomodifica' => $this->usuariomodifica,
            'fechamodifica' => $this->fechamodifica,
        ]);

        $query->andFilterWhere(['like', 'tiponorma', $this->tiponorma]);

        return $dataProvider;
    }
}


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

    <TITLE>
        InterleaveControl (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.control.InterleaveControl class">

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

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

        org.apache.jmeter.control

    Class InterleaveControl

java.lang.Object
  org.apache.jmeter.testelement.AbstractTestElement
      org.apache.jmeter.control.GenericController
          org.apache.jmeter.control.InterleaveControl

All Implemented Interfaces:

Cloneable, Controller,
        Serializable, TestElement

Direct Known Subclasses:

RandomController

public class InterleaveControl

extends GenericController

implements Serializable

See Also:

Serialized Form

            Field Summary

            static int
        IGNORE_SUB_CONTROLLERS

            static int
        USE_SUB_CONTROLLERS

        Fields inherited from class org.apache.jmeter.control.GenericController

        current, subControllersAndSamplers

        Fields inherited from interface org.apache.jmeter.testelement.TestElement

        COMMENTS, ENABLED, GUI_CLASS, NAME, TEST_CLASS

            Constructor Summary

        InterleaveControl()

                      Constructor for the InterleaveControl object

            Method Summary

            protected  void
        currentReturnedNull(Controller c)

                      If the controller is done, remove it from the
            list,
            otherwise increment to next entry in list.

             int
        getStyle()

            protected  void
        incrementCurrent()

                      Increments the current pointer; called by
            currentReturnedNull to move the
            controller on to its next child.

            protected  boolean
        isSkipNext()

             Sampler
        next()

            Determines the next sampler to be processed.

            protected  Sampler
        nextIsAController(Controller controller)

                      Called by next() if the element is a Controller,
            and returns the next sampler from the controller.

            protected  Sampler
        nextIsASampler(Sampler element)

                      Increment the current pointer and return the
            element.

            protected  Sampler
        nextIsNull()

                      If the current is null, reset and continue
            searching.

             void
        reInitialize()

                      Resets the controller:

            resetCurrent() (i.e. current=0)
            increment iteration count
            sets first=true
            recoverRunningVersion() to set the controller back to the initial state

            protected  void
        setCurrentElement(TestElement currentElement)

                      Empty implementation - does nothing.

            protected  void
        setSkipNext(boolean skipNext)

             void
        setStyle(int style)

        Methods inherited from class org.apache.jmeter.control.GenericController

        addIterationListener,
            addTestElement,
            fireIterationStart,
            fireIterEvents,
            getCurrentElement,
            getIterCount, getSubControllers,
            incrementIterCount,
            initialize, isDone, isFirst, removeCurrentElement,
            resetCurrent, resetIterCount,
            setDone, setFirst

        Methods inherited from class org.apache.jmeter.testelement.AbstractTestElement

        addProperty,
            canRemove, clear, clearTemporary,
            clone, emptyTemporary,
            equals,
            getComment, getName, getProperty,
            getPropertyAsBoolean,
            getPropertyAsBoolean,
            getPropertyAsDouble,
            getPropertyAsFloat,
            getPropertyAsInt,
            getPropertyAsInt,
            getPropertyAsLong,
            getPropertyAsString,
            getPropertyAsString,
            getThreadContext,
            getThreadName,
            hashCode, isEnabled,
            isRunningVersion,
            isTemporary,
            logProperties,
            mergeIn,
            propertyIterator,
            recoverRunningVersion,
            removeProperty,
            setComment,
            setName,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setRunningVersion,
            setTemporary,
            setThreadContext,
            setThreadName,
            traverse,
            traverseCollection,
            traverseMap,
            traverseProperty

        Methods inherited from class java.lang.Object

        finalize, getClass, notify, notifyAll, toString, wait, wait, wait

        Methods inherited from interface org.apache.jmeter.testelement.TestElement

        canRemove, clear, clone, getComment, getName, getProperty,
            getPropertyAsBoolean,
            getPropertyAsBoolean,
            getPropertyAsDouble,
            getPropertyAsFloat,
            getPropertyAsInt,
            getPropertyAsInt,
            getPropertyAsLong,
            getPropertyAsString,
            getPropertyAsString,
            getThreadContext,
            getThreadName, isEnabled, isRunningVersion,
            isTemporary,
            propertyIterator,
            recoverRunningVersion,
            removeProperty,
            setComment,
            setName,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setProperty,
            setRunningVersion,
            setTemporary,
            setThreadContext,
            setThreadName,
            traverse

            Field Detail

    IGNORE_SUB_CONTROLLERS

public static final int IGNORE_SUB_CONTROLLERS

See Also:

            Constant
                Field Values

    USE_SUB_CONTROLLERS

public static final int USE_SUB_CONTROLLERS

See Also:

Constant
            Field Values

            Constructor Detail

    InterleaveControl

public InterleaveControl()

Constructor for the InterleaveControl object

            Method Detail

    reInitialize

public void reInitialize()

Description copied from class: GenericController

Resets the controller:

resetCurrent() (i.e. current=0)

increment iteration count

sets first=true

recoverRunningVersion() to set the controller back to the initial state

Overrides:

reInitialize
                in class GenericController

    setStyle

public void setStyle(int style)

    getStyle

public int getStyle()

    next

public Sampler next()

Description copied from class: GenericController

        Determines the next sampler to be processed.

            If isDone, returns null.

            Gets the list element using current pointer.
            If this is null, calls GenericController.nextIsNull().

            If the list element is a sampler, calls GenericController.nextIsASampler(Sampler),
            otherwise calls GenericController.nextIsAController(Controller)

            If any of the called methods throws NextIsNullException, returns null,
            otherwise the value obtained above is returned.

Specified by:

next in
                interface Controller

Overrides:

next in
                class GenericController

Returns:

the next sampler or null

    nextIsAController

protected Sampler nextIsAController(Controller controller)
                             throws NextIsNullException

Description copied from class: GenericController

Called by next() if the element is a Controller,
        and returns the next sampler from the controller.
        If this is null, then updates the current pointer and makes recursive call to next().

Overrides:

nextIsAController
                in class GenericController

Parameters:

controller -

Returns:

the next sampler

Throws:

NextIsNullException

    nextIsASampler

protected Sampler nextIsASampler(Sampler element)
                          throws NextIsNullException

Description copied from class: GenericController

Increment the current pointer and return the element.
        Called by next() if the element is a sampler.
        (May be overriden by sub-classes).

Overrides:

nextIsASampler
                in class GenericController

Parameters:

element -

Returns:

input element

Throws:

NextIsNullException

    nextIsNull

protected Sampler nextIsNull()

If the current is null, reset and continue searching. The searchStart
        attribute will break us off when we start a repeat.

Overrides:

nextIsNull
                in class GenericController

Returns:

null (always, for this class)

See Also:

GenericController.nextIsNull()

    setCurrentElement

protected void setCurrentElement(TestElement currentElement)
                          throws NextIsNullException

Description copied from class: GenericController

Empty implementation - does nothing.

Overrides:

setCurrentElement
                in class GenericController

Parameters:

currentElement -

Throws:

NextIsNullException

    currentReturnedNull

protected void currentReturnedNull(Controller c)

Description copied from class: GenericController

If the controller is done, remove it from the list,
        otherwise increment to next entry in list.

Overrides:

currentReturnedNull
                in class GenericController

Parameters:

c - controller

    isSkipNext

protected boolean isSkipNext()

Returns:

skipNext

    setSkipNext

protected void setSkipNext(boolean skipNext)

Parameters:

skipNext -

    incrementCurrent

protected void incrementCurrent()

Description copied from class: GenericController

Increments the current pointer; called by currentReturnedNull to move the
        controller on to its next child.

Overrides:

incrementCurrent
                in class GenericController

                    Overview
                    Package
                      Class

                    Tree

                    Deprecated
                    Index
                    Help

            Apache JMeter

             PREV CLASS
             NEXT CLASS

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

Copyright © 1998-2009 Apache Software Foundation. All Rights Reserved.


text:
define(function() {
  // Ensure only one model in the collection is active at any time
  var activeToggled = function(model, value) {
    if (value === true) {
      this.forEach(function(m) {
        if (m.get('active') === true && m !== model) {
          m.set('active', false);
        }
      });
    }
  };

  return function(collection) {
    collection.listenTo(collection, 'change:active', activeToggled, collection);
  };
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.twitter4j</groupId>
  <artifactId>twitter4j</artifactId>
  <version>4.0.12-hubspot-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>twitter4j</name>
  <description>A Java library for the Twitter API</description>
  <url>http://twitter4j.org/</url>

  <properties>
    <hubspot.twitter4j.current.version>4.0.12-hubspot-SNAPSHOT</hubspot.twitter4j.current.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <modules>
    <module>twitter4j-async</module>
    <module>twitter4j-core</module>
    <module>twitter4j-examples</module>
    <module>twitter4j-appengine</module>
    <module>twitter4j-http2-support</module>
    <module>twitter4j-stream</module>
    <module>twitter4j-media-support</module>
  </modules>

  <licenses>
    <license>
      <name>Apache License 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <scm>
    <url>https://github.com/yusuke/twitter4j</url>
    <connection>scm:git:https://github.com/yusuke/twitter4j.git</connection>
    <developerConnection>scm:git:https://github.com/yusuke/twitter4j.git</developerConnection>
    <tag>${hubspot.twitter4j.current.version}</tag>
  </scm>

  <developers>
    <developer>
      <id>yusuke</id>
      <name>Yusuke</name>
      <email>yusuke@mac.com</email>
      <url>http://samuraism.jp/</url>
      <roles>
        <role>lead</role>
        <role>architect</role>
        <role>developer</role>
      </roles>
      <timezone>9</timezone>
    </developer>
  </developers>

  <issueManagement>
    <system>YouTrack</system>
    <url>http://issue.twitter4j.org/youtrack/issues?q=project%3A+Twitter4J</url>
  </issueManagement>

  <mailingLists>
    <mailingList>
      <name>Twitter4J</name>
      <subscribe>twitter4j-subscribe@googlegroups.com</subscribe>
      <unsubscribe>twitter4j-unsubscribe@googlegroups.com</unsubscribe>
      <post>twitter4j@googlegroups.com</post>
      <archive>http://groups.google.com/group/twitter4j</archive>
    </mailingList>
  </mailingLists>

  <distributionManagement>
    <repository>
      <id>sonatype-nexus-staging</id>
      <name>Nexus Release Repository</name>
      <uniqueVersion>false</uniqueVersion>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
    <snapshotRepository>
      <id>org.twitter4j</id>
      <name>twitter4j.org Repository</name>
      <uniqueVersion>false</uniqueVersion>
      <url>file:${user.home}/maven2/</url>
    </snapshotRepository>
  </distributionManagement>

  <profiles>
    <profile>
      <id>release-sign-artifacts</id>
      <activation>
        <property>
          <name>performRelease</name>
          <value>true</value>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>1.4</version>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.2</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12.4</version>
      </plugin>
    </plugins>
  </build>
</project>


text:
#include <sector.h>
#include <sys/time.h>
#include <iostream>

using namespace std;

int main(int argc, char** /*argv*/)
{
   if (1 != argc)
   {
      cout << "usage: wordcount" << endl;
      return 0;
   }

   Sector client;
   if (Utility::login(client) < 0)
      return -1;

   vector<string> files;
   files.insert(files.end(), "/html");

   SphereStream s;
   if (s.init(files) < 0)
   {
      cout << "unable to locate input data files. quit.\n";
      Utility::logout(client);
      return -1;
   }

   SphereStream temp;
   temp.setOutputPath("/wordcount", "word_bucket");
   temp.init(256);

   SphereProcess* myproc = client.createSphereProcess();

   if (myproc->loadOperator("./funcs/wordbucket.so") < 0)
   {
      cout << "cannot find workbucket.so\n";
      Utility::logout(client);
      return -1;
   }

   timeval t;
   gettimeofday(&t, 0);
   cout << "start time " << t.tv_sec << endl;

   int result = myproc->run(s, temp, "wordbucket", 0);
   if (result < 0)
   {
      Utility::print_error(result);
      Utility::logout(client);
      return -1;
   }

   myproc->waitForCompletion();

   gettimeofday(&t, 0);
   cout << "stage 1 accomplished " << t.tv_sec << endl;

   for (vector<string>::iterator i = temp.m_vFiles.begin(); i != temp.m_vFiles.end(); ++ i)
      cout << *i << endl;

   for (vector<int64_t>::iterator i = temp.m_vSize.begin(); i != temp.m_vSize.end(); ++ i)
      cout << *i << endl;

/*
   //NOT FINISHED. PROCESS EACH BUCKET AND GENERATE INDEX

   SphereStream output;
   output.init(0);
   myproc->setProcNumPerNode(2);
   if (myproc->run(temp, output, "index", 0, NULL, 0) < 0)
   {
      cout << "failed to find any computing resources." << endl;
      return -1;
   }

   myproc->waitForCompletion();

   gettimeofday(&t, 0);
   cout << "stage 2 accomplished " << t.tv_sec << endl;
*/
   cout << "SPE COMPLETED " << endl;

   myproc->close();
   client.releaseSphereProcess(myproc);

   Utility::logout(client);

   return 0;
}


text:
var GooglePlus = function(){

	var share = function( url ){
		window.open('https://plus.google.com/share?url='+encodeURIComponent(url),'google-dialog','width=626,height=436');
	};

	return {
		share: share
	}

}();


text:
#ifndef ThreadGlobalData_h
#define ThreadGlobalData_h

#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/Noncopyable.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/ThreadSpecific.h"
#include "wtf/Threading.h"
#include "wtf/text/StringHash.h"

using WTF::ThreadSpecific;

namespace WebCore {

    class EventNames;
    class ThreadLocalInspectorCounters;
    class ThreadTimers;

    struct CachedResourceRequestInitiators;
    struct TECConverterWrapper;

    class ThreadGlobalData {
        WTF_MAKE_NONCOPYABLE(ThreadGlobalData);
    public:
        ThreadGlobalData();
        ~ThreadGlobalData();
        void destroy(); // called on workers to clean up the ThreadGlobalData before the thread exits.

        const CachedResourceRequestInitiators& cachedResourceRequestInitiators() { return *m_cachedResourceRequestInitiators; }
        EventNames& eventNames() { return *m_eventNames; }
        ThreadTimers& threadTimers() { return *m_threadTimers; }

        ThreadLocalInspectorCounters& inspectorCounters() { return *m_inspectorCounters; }

    private:
        OwnPtr<CachedResourceRequestInitiators> m_cachedResourceRequestInitiators;
        OwnPtr<EventNames> m_eventNames;
        OwnPtr<ThreadTimers> m_threadTimers;

#ifndef NDEBUG
        bool m_isMainThread;
#endif

        OwnPtr<ThreadLocalInspectorCounters> m_inspectorCounters;

        static ThreadSpecific<ThreadGlobalData>* staticData;
        friend ThreadGlobalData& threadGlobalData();
    };

inline ThreadGlobalData& threadGlobalData()
{
    // FIXME: Workers are not necessarily the only feature that make per-thread global data necessary.
    // We need to check for e.g. database objects manipulating strings on secondary threads.

    // ThreadGlobalData is used on main thread before it could possibly be used on secondary ones, so there is no need for synchronization here.
    if (!ThreadGlobalData::staticData)
        ThreadGlobalData::staticData = new ThreadSpecific<ThreadGlobalData>;
    return **ThreadGlobalData::staticData;
}

} // namespace WebCore

#endif // ThreadGlobalData_h