text:
<?php

namespace tests\QATools\QATools\BEM\PropertyDecorator;

use QATools\QATools\BEM\Annotation\BEMAnnotation;
use Mockery as m;
use tests\QATools\QATools\PageObject\PropertyDecorator\DefaultPropertyDecoratorTest;

class BEMPropertyDecoratorTest extends DefaultPropertyDecoratorTest
{

	protected function setUp()
	{
		$this->locatorClass = '\\QATools\\QATools\\BEM\\ElementLocator\\BEMElementLocator';
		$this->decoratorClass = '\\QATools\\QATools\\BEM\\PropertyDecorator\\BEMPropertyDecorator';

		parent::setUp();
	}

	public function testBlockProxy()
	{
		$element_class = '\\QATools\\QATools\\BEM\\Element\\Block';

		$search_context = m::mock('\\QATools\\QATools\\BEM\\BEMPage');
		$this->locator->shouldReceive('getSearchContext')->andReturn($search_context);

		$node_element = $this->createNodeElement();
		$this->locator->shouldReceive('findAll')->once()->andReturn(array($node_element));

		$annotation = new BEMAnnotation();
		$annotation->block = 'block-name';
		$this->_expectBEMAnnotation($element_class, array($annotation));

		$decorator = m::mock('\\QATools\\QATools\\PageObject\\PropertyDecorator\\IPropertyDecorator');
		$this->pageFactory->shouldReceive('createDecorator')->once()->andReturn($decorator);
		$this->pageFactory->shouldReceive('initElements')->once()->andReturn($this->pageFactory);

		$proxy = $this->decorator->decorate($this->property);
		$this->assertProxy($proxy, '\\QATools\\QATools\\BEM\\Proxy\\BlockProxy', $search_context, $element_class);
		$this->assertNotEmpty($proxy->getNodes());
	}

	public function testElementProxy()
	{
		$element_class = '\\QATools\\QATools\\BEM\\Element\\Element';

		$search_context = m::mock('\\QATools\\QATools\\BEM\\Element\\IBlock');
		$this->locator->shouldReceive('getSearchContext')->andReturn($search_context);

		$node_elements = array($this->createNodeElement());
		$this->locator->shouldReceive('findAll')->once()->andReturn($node_elements);

		$annotation = new BEMAnnotation();
		$annotation->element = 'element-name';
		$this->_expectBEMAnnotation($element_class, array($annotation));

		$proxy = $this->decorator->decorate($this->property);
		$this->assertProxy($proxy, '\\QATools\\QATools\\BEM\\Proxy\\ElementProxy', $search_context, $element_class);
		$this->assertInstanceOf('\\QATools\\QATools\\PageObject\\Element\\IWebElement', $proxy->getWrappedElement());
	}

	/**
	 * @dataProvider bemPartDataProvider
	 * @expectedException \QATools\QATools\PageObject\Exception\AnnotationException
	 * @expectedExceptionCode \QATools\QATools\PageObject\Exception\AnnotationException::TYPE_REQUIRED
	 */
	public function testMissingAnnotationError($part_class)
	{
		$this->_expectBEMAnnotation($part_class, array());
		$this->decorator->decorate($this->property);
	}

	/**
	 * @dataProvider bemPartDataProvider
	 * @expectedException \QATools\QATools\PageObject\Exception\AnnotationException
	 * @expectedExceptionCode \QATools\QATools\PageObject\Exception\AnnotationException::TYPE_INCORRECT_USAGE
	 */
	public function testEmptyAnnotationError($part_class)
	{
		$annotation = new BEMAnnotation();
		$this->_expectBEMAnnotation($part_class, array($annotation));
		$this->decorator->decorate($this->property);
	}

	/**
	 * @dataProvider bemPartDataProvider
	 * @expectedException \QATools\QATools\PageObject\Exception\AnnotationException
	 * @expectedExceptionCode \QATools\QATools\PageObject\Exception\AnnotationException::TYPE_INCORRECT_USAGE
	 */
	public function testElementWithBlockAnnotationError($part_class)
	{
		$annotation = new BEMAnnotation();
		$annotation->block = 'block-name';
		$annotation->element = 'element-name';
		$this->_expectBEMAnnotation($part_class, array($annotation));
		$this->decorator->decorate($this->property);
	}

	/**
	 * Returns possible BEM parts.
	 *
	 * @return array
	 */
	public function bemPartDataProvider()
	{
		return array(
			array('\\QATools\\QATools\\BEM\\Element\\Block'),
			array('\\QATools\\QATools\\BEM\\Element\\Element'),
		);
	}

	/**
	 * @expectedException \QATools\QATools\PageObject\Exception\AnnotationException
	 * @expectedExceptionCode \QATools\QATools\PageObject\Exception\AnnotationException::TYPE_INCORRECT_USAGE
	 */
	public function testBlockUsedInWrongContext()
	{
		$search_context = m::mock('\\QATools\\QATools\\PageObject\\ISearchContext');
		$this->locator->shouldReceive('getSearchContext')->andReturn($search_context);

		$annotation = new BEMAnnotation();
		$annotation->block = 'block-name';
		$this->_expectBEMAnnotation('\\QATools\\QATools\\BEM\\Element\\Block', array($annotation));

		$this->decorator->decorate($this->property);
	}

	/**
	 * @expectedException \QATools\QATools\PageObject\Exception\AnnotationException
	 * @expectedExceptionCode \QATools\QATools\PageObject\Exception\AnnotationException::TYPE_INCORRECT_USAGE
	 */
	public function testElementUsedInWrongContext()
	{
		$search_context = m::mock('\\QATools\\QATools\\PageObject\\ISearchContext');
		$this->locator->shouldReceive('getSearchContext')->andReturn($search_context);

		$annotation = new BEMAnnotation();
		$annotation->element = 'element-name';
		$this->_expectBEMAnnotation('\\QATools\\QATools\\BEM\\Element\\Element', array($annotation));

		$this->decorator->decorate($this->property);
	}

	/**
	 * Expects, that annotations will be queried from property, which data type is $element_class.
	 *
	 * @param string $element_class Element class.
	 * @param array  $annotations   Annotations.
	 *
	 * @return void
	 */
	private function _expectBEMAnnotation($element_class, array $annotations)
	{
		$this->property->shouldReceive('isSimpleDataType')->andReturn(false);
		$this->property->shouldReceive('getDataType')->andReturn($element_class);

		$this->property
			->shouldReceive('getAnnotationsFromPropertyOrClass')
			->with('@bem')
			->once()
			->andReturn($annotations);
	}

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>jQuery Localtime Test Suite</title>

  <link rel="stylesheet" href="../libs/qunit/qunit.css" media="screen">

IMPORTANT NOTE

	These tests may fail if your local PC is not running on Europe/London time

jquery.localtime test script

		test markup, will be hidden
		2011-01-03T13:39Z
		2011-01-03T13:39Z
		2011-01-03T13:39Z
		2011-01-03T13:39Z

			2011-01-03T13:39Z
			2011-01-03T13:39Z

				2011-01-03T13:39Z
				2011-01-03T13:39Z

		<time id="timeTagTestDefault" datetime="2011-01-03T13:39Z" data-localtime-format>Sooner or later 1</time>
		<time id="timeTagTestNonDefault" datetime="2011-01-03T13:39Z" data-localtime-format="do MMM yyyy h:mmtt">Sooner or later 2</time>

redpajama_set_name: RedPajamaGithub


text:
"""
The scramblesuit module implements the ScrambleSuit obfuscation protocol.

The paper discussing the design and evaluation of the ScrambleSuit pluggable
transport protocol is available here:
http://www.cs.kau.se/philwint/scramblesuit/
"""

from twisted.internet import reactor

import obfsproxy.transports.base as base
import obfsproxy.common.log as logging

import random
import base64
import yaml
import argparse

import probdist
import mycrypto
import message
import const
import util
import packetmorpher
import ticket
import uniformdh
import state
import fifobuf

log = logging.get_obfslogger()

class ReadPassFile(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        with open(values) as f:
            setattr(namespace, self.dest, f.readline().strip())

class ScrambleSuitTransport( base.BaseTransport ):

    """
    Implement the ScrambleSuit protocol.

    The class implements methods which implement the ScrambleSuit protocol.  A
    large part of the protocol's functionality is outsources to different
    modules.
    """

    def __init__( self ):
        """
        Initialise a ScrambleSuitTransport object.
        """

        log.debug("Initialising %s." % const.TRANSPORT_NAME)

        super(ScrambleSuitTransport, self).__init__()

        # Load the server's persistent state from file.
        if self.weAreServer:
            self.srvState = state.load()

        # Initialise the protocol's state machine.
        log.debug("Switching to state ST_WAIT_FOR_AUTH.")
        self.protoState = const.ST_WAIT_FOR_AUTH

        # Buffer for outgoing data.
        self.sendBuf = ""

        # Buffer for inter-arrival time obfuscation.
        self.choppingBuf = fifobuf.Buffer()

        # AES instances to decrypt incoming and encrypt outgoing data.
        self.sendCrypter = mycrypto.PayloadCrypter()
        self.recvCrypter = mycrypto.PayloadCrypter()

        # Packet morpher to modify the protocol's packet length distribution.
        self.pktMorpher = packetmorpher.new(self.srvState.pktDist
                                            if self.weAreServer else None)

        # Inter-arrival time morpher to obfuscate inter arrival times.
        self.iatMorpher = self.srvState.iatDist if self.weAreServer else \
                          probdist.new(lambda: random.random() %
                                       const.MAX_PACKET_DELAY)

        # Used to extract protocol messages from encrypted data.
        self.protoMsg = message.MessageExtractor()

        # Used by the server-side: `True' if the ticket is already
        # decrypted but not yet authenticated.
        self.decryptedTicket = False

        # If we are in external mode we should already have a shared
        # secret set up because of validate_external_mode_cli().
        if self.weAreExternal:
            assert(self.uniformDHSecret)

        if self.weAreClient and not self.weAreExternal:
            # As a client in managed mode, we get the shared secret
            # from callback `handle_socks_args()' per-connection. Set
            # the shared secret to None for now.
            self.uniformDHSecret = None

        self.uniformdh = uniformdh.new(self.uniformDHSecret, self.weAreServer)

    @classmethod
    def setup( cls, transportConfig ):
        """
        Called once when obfsproxy starts.
        """

        log.error("\n\n################################################\n"
                  "Do NOT rely on ScrambleSuit for strong security!\n"
                  "################################################\n")

        util.setStateLocation(transportConfig.getStateLocation())

        cls.weAreClient = transportConfig.weAreClient
        cls.weAreServer = not cls.weAreClient
        cls.weAreExternal = transportConfig.weAreExternal

        # If we are server and in managed mode, we should get the
        # shared secret from the server transport options.
        if cls.weAreServer and not cls.weAreExternal:
            cfg  = transportConfig.getServerTransportOptions()
            if cfg and "password" in cfg:
                try:
                    cls.uniformDHSecret = base64.b32decode(util.sanitiseBase32(
                        cfg["password"]))
                except (TypeError, AttributeError) as error:
                    raise base.TransportSetupFailed(
                        "Password could not be base32 decoded (%s)" % error)

                cls.uniformDHSecret = cls.uniformDHSecret.strip()

        if cls.weAreServer:
            if not hasattr(cls, "uniformDHSecret"):
                log.debug("Using fallback password for descriptor file.")
                srv = state.load()
                cls.uniformDHSecret = srv.fallbackPassword

            if len(cls.uniformDHSecret) != const.SHARED_SECRET_LENGTH:
                raise base.TransportSetupFailed(
                    "Wrong password length (%d instead of %d)"
                    % len(cls.uniformDHSecret), const.SHARED_SECRET_LENGTH)

            if not const.STATE_LOCATION:
                raise base.TransportSetupFailed(
                    "No state location set. If you are using external mode, " \
                    "please set it using the --data-dir switch.")

            state.writeServerPassword(cls.uniformDHSecret)

    @classmethod
    def get_public_server_options( cls, transportOptions ):
        """
        Return ScrambleSuit's BridgeDB parameters, i.e., the shared secret.

        As a fallback mechanism, we return an automatically generated password
        if the bridge operator did not use `ServerTransportOptions'.
        """

        log.debug("Tor's transport options: %s" % str(transportOptions))

        if not "password" in transportOptions:
            log.warning("No password found in transport options (use Tor's " \
                        "`ServerTransportOptions' to set your own password)." \
                        "  Using automatically generated password instead.")
            srv = state.load()
            transportOptions = {"password":
                                base64.b32encode(srv.fallbackPassword)}
            cls.uniformDHSecret = srv.fallbackPassword

        return transportOptions

    def deriveSecrets( self, masterKey ):
        """
        Derive various session keys from the given `masterKey'.

        The argument `masterKey' is used to derive two session keys and nonces
        for AES-CTR and two HMAC keys.  The derivation is done using
        HKDF-SHA256.
        """

        assert len(masterKey) == const.MASTER_KEY_LENGTH

        log.debug("Deriving session keys from %d-byte master key." %
                  len(masterKey))

        # We need key material for two symmetric AES-CTR keys, nonces and
        # HMACs.  In total, this equals 144 bytes of key material.
        hkdf = mycrypto.HKDF_SHA256(masterKey, "", (32 * 4) + (8 * 2))
        okm = hkdf.expand()
        assert len(okm) >= ((32 * 4) + (8 * 2))

        # Set AES-CTR keys and nonces for our two AES instances.
        self.sendCrypter.setSessionKey(okm[0:32],  okm[32:40])
        self.recvCrypter.setSessionKey(okm[40:72], okm[72:80])

        # Set the keys for the two HMACs protecting our data integrity.
        self.sendHMAC = okm[80:112]
        self.recvHMAC = okm[112:144]

        if self.weAreServer:
            self.sendHMAC, self.recvHMAC = self.recvHMAC, self.sendHMAC
            self.sendCrypter, self.recvCrypter = self.recvCrypter, \
                                                 self.sendCrypter

    def circuitConnected( self ):
        """
        Initiate a ScrambleSuit handshake.

        This method is only relevant for clients since servers never initiate
        handshakes.  If a session ticket is available, it is redeemed.
        Otherwise, a UniformDH handshake is conducted.
        """

        # The server handles the handshake passively.
        if self.weAreServer:
            return

        # The preferred authentication mechanism is a session ticket.
        bridge = self.circuit.downstream.transport.getPeer()
        storedTicket = ticket.findStoredTicket(bridge)

        if storedTicket is not None:
            log.debug("Redeeming stored session ticket.")
            (masterKey, rawTicket) = storedTicket
            self.deriveSecrets(masterKey)
            self.circuit.downstream.write(ticket.createTicketMessage(rawTicket,
                                                                self.sendHMAC))

            # We switch to ST_CONNECTED opportunistically since we don't know
            # yet whether the server accepted the ticket.
            log.debug("Switching to state ST_CONNECTED.")
            self.protoState = const.ST_CONNECTED

            self.flushSendBuffer()

        # Conduct an authenticated UniformDH handshake if there's no ticket.
        else:
            log.debug("No session ticket to redeem.  Running UniformDH.")
            self.circuit.downstream.write(self.uniformdh.createHandshake())

    def sendRemote( self, data, flags=const.FLAG_PAYLOAD ):
        """
        Send data to the remote end after a connection was established.

        The given `data' is first encapsulated in protocol messages.  Then, the
        protocol message(s) are sent over the wire.  The argument `flags'
        specifies the protocol message flags with the default flags signalling
        payload.
        """

        log.debug("Processing %d bytes of outgoing data." % len(data))

        # Wrap the application's data in ScrambleSuit protocol messages.
        messages = message.createProtocolMessages(data, flags=flags)
        blurb = "".join([msg.encryptAndHMAC(self.sendCrypter,
                        self.sendHMAC) for msg in messages])

        # Flush data chunk for chunk to obfuscate inter-arrival times.
        if const.USE_IAT_OBFUSCATION:

            if len(self.choppingBuf) == 0:
                self.choppingBuf.write(blurb)
                reactor.callLater(self.iatMorpher.randomSample(),
                                  self.flushPieces)
            else:
                # flushPieces() is still busy processing the chopping buffer.
                self.choppingBuf.write(blurb)

        else:
            padBlurb = self.pktMorpher.getPadding(self.sendCrypter,
                                                  self.sendHMAC,
                                                  len(blurb))
            self.circuit.downstream.write(blurb + padBlurb)

    def flushPieces( self ):
        """
        Write the application data in chunks to the wire.

        The cached data is sent over the wire in chunks.  After every write
        call, control is given back to the Twisted reactor so it has a chance
        to flush the data.  Shortly thereafter, this function is called again
        to write the next chunk of data.  The delays in between subsequent
        write calls are controlled by the inter-arrival time obfuscator.
        """

        # Drain and send an MTU-sized chunk from the chopping buffer.
        if len(self.choppingBuf) > const.MTU:

            self.circuit.downstream.write(self.choppingBuf.read(const.MTU))

        # Drain and send whatever is left in the output buffer.
        else:
            blurb = self.choppingBuf.read()
            padBlurb = self.pktMorpher.getPadding(self.sendCrypter,
                                                  self.sendHMAC,
                                                  len(blurb))
            self.circuit.downstream.write(blurb + padBlurb)
            return

        reactor.callLater(self.iatMorpher.randomSample(), self.flushPieces)

    def processMessages( self, data ):
        """
        Acts on extracted protocol messages based on header flags.

        After the incoming `data' is decrypted and authenticated, this method
        processes the received data based on the header flags.  Payload is
        written to the local application, new tickets are stored, or keys are
        added to the replay table.
        """

        if (data is None) or (len(data) == 0):
            return

        # Try to extract protocol messages from the encrypted blurb.
        msgs  = self.protoMsg.extract(data, self.recvCrypter, self.recvHMAC)
        if (msgs is None) or (len(msgs) == 0):
            return

        for msg in msgs:
            # Forward data to the application.
            if msg.flags == const.FLAG_PAYLOAD:
                self.circuit.upstream.write(msg.payload)

            # Store newly received ticket.
            elif self.weAreClient and (msg.flags == const.FLAG_NEW_TICKET):
                assert len(msg.payload) == (const.TICKET_LENGTH +
                                            const.MASTER_KEY_LENGTH)
                peer = self.circuit.downstream.transport.getPeer()
                ticket.storeNewTicket(msg.payload[0:const.MASTER_KEY_LENGTH],
                                      msg.payload[const.MASTER_KEY_LENGTH:
                                                  const.MASTER_KEY_LENGTH +
                                                  const.TICKET_LENGTH], peer)

            # Use the PRNG seed to generate the same probability distributions
            # as the server.  That's where the polymorphism comes from.
            elif self.weAreClient and (msg.flags == const.FLAG_PRNG_SEED):
                assert len(msg.payload) == const.PRNG_SEED_LENGTH
                log.debug("Obtained PRNG seed.")
                prng = random.Random(msg.payload)
                pktDist = probdist.new(lambda: prng.randint(const.HDR_LENGTH,
                                                            const.MTU),
                                       seed=msg.payload)
                self.pktMorpher = packetmorpher.new(pktDist)
                self.iatMorpher = probdist.new(lambda: prng.random() %
                                               const.MAX_PACKET_DELAY,
                                               seed=msg.payload)

            else:
                log.warning("Invalid message flags: %d." % msg.flags)

    def flushSendBuffer( self ):
        """
        Flush the application's queued data.

        The application could have sent data while we were busy authenticating
        the remote machine.  This method flushes the data which could have been
        queued in the meanwhile in `self.sendBuf'.
        """

        if len(self.sendBuf) == 0:
            log.debug("Send buffer is empty; nothing to flush.")
            return

        # Flush the buffered data, the application is so eager to send.
        log.debug("Flushing %d bytes of buffered application data." %
                  len(self.sendBuf))

        self.sendRemote(self.sendBuf)
        self.sendBuf = ""

    def receiveTicket( self, data ):
        """
        Extract and verify a potential session ticket.

        The given `data' is treated as a session ticket.  The ticket is being
        decrypted and authenticated (yes, in that order).  If all these steps
        succeed, `True' is returned.  Otherwise, `False' is returned.
        """

        if len(data) < (const.TICKET_LENGTH + const.MARK_LENGTH +
                        const.HMAC_SHA256_128_LENGTH):
            return False

        potentialTicket = data.peek()

        # Now try to decrypt and parse the ticket.  We need the master key
        # inside to verify the HMAC in the next step.
        if not self.decryptedTicket:
            newTicket = ticket.decrypt(potentialTicket[:const.TICKET_LENGTH],
                                       self.srvState)
            if newTicket != None and newTicket.isValid():
                self.deriveSecrets(newTicket.masterKey)
                self.decryptedTicket = True
            else:
                return False

        # First, find the mark to efficiently locate the HMAC.
        mark = mycrypto.HMAC_SHA256_128(self.recvHMAC,
                                        potentialTicket[:const.TICKET_LENGTH])

        index = util.locateMark(mark, potentialTicket)
        if not index:
            return False

        # Now, verify if the HMAC is valid.
        existingHMAC = potentialTicket[index + const.MARK_LENGTH:
                                       index + const.MARK_LENGTH +
                                       const.HMAC_SHA256_128_LENGTH]
        authenticated = False
        for epoch in util.expandedEpoch():
            myHMAC = mycrypto.HMAC_SHA256_128(self.recvHMAC,
                                              potentialTicket[0:index + \
                                              const.MARK_LENGTH] + epoch)

            if util.isValidHMAC(myHMAC, existingHMAC, self.recvHMAC):
                authenticated = True
                break

            log.debug("HMAC invalid.  Trying next epoch value.")

        if not authenticated:
            log.warning("Could not verify the authentication message's HMAC.")
            return False

        # Do nothing if the ticket is replayed.  Immediately closing the
        # connection would be suspicious.
        if self.srvState.isReplayed(existingHMAC):
            log.warning("The HMAC was already present in the replay table.")
            return False

        data.drain(index + const.MARK_LENGTH + const.HMAC_SHA256_128_LENGTH)

        log.debug("Adding the HMAC authenticating the ticket message to the " \
                  "replay table: %s." % existingHMAC.encode('hex'))
        self.srvState.registerKey(existingHMAC)

        log.debug("Switching to state ST_CONNECTED.")
        self.protoState = const.ST_CONNECTED

        return True

    def receivedUpstream( self, data ):
        """
        Sends data to the remote machine or queues it to be sent later.

        Depending on the current protocol state, the given `data' is either
        directly sent to the remote machine or queued.  The buffer is then
        flushed once, a connection is established.
        """

        if self.protoState == const.ST_CONNECTED:
            self.sendRemote(data.read())

        # Buffer data we are not ready to transmit yet.
        else:
            self.sendBuf += data.read()
            log.debug("Buffered %d bytes of outgoing data." %
                      len(self.sendBuf))

    def sendTicketAndSeed( self ):
        """
        Send a session ticket and the PRNG seed to the client.

        This method is only called by the server after successful
        authentication.  Finally, the server's send buffer is flushed.
        """

        log.debug("Sending a new session ticket and the PRNG seed to the " \
                  "client.")

        self.sendRemote(ticket.issueTicketAndKey(self.srvState),
                        flags=const.FLAG_NEW_TICKET)
        self.sendRemote(self.srvState.prngSeed,
                        flags=const.FLAG_PRNG_SEED)
        self.flushSendBuffer()

    def receivedDownstream( self, data ):
        """
        Receives and processes data coming from the remote machine.

        The incoming `data' is dispatched depending on the current protocol
        state and whether we are the client or the server.  The data is either
        payload or authentication data.
        """

        if self.weAreServer and (self.protoState == const.ST_AUTH_FAILED):

            self.drainedHandshake += len(data)
            data.drain(len(data))

            if self.drainedHandshake > self.srvState.closingThreshold:
                log.info("Terminating connection after having received >= %d"
                         " bytes because client could not "
                         "authenticate." % self.srvState.closingThreshold)
                self.circuit.close()
                return

        elif self.weAreServer and (self.protoState == const.ST_WAIT_FOR_AUTH):

            # First, try to interpret the incoming data as session ticket.
            if self.receiveTicket(data):
                log.debug("Ticket authentication succeeded.")

                self.sendTicketAndSeed()

            # Second, interpret the data as a UniformDH handshake.
            elif self.uniformdh.receivePublicKey(data, self.deriveSecrets,
                    self.srvState):
                # Now send the server's UniformDH public key to the client.
                handshakeMsg = self.uniformdh.createHandshake()

                log.debug("Sending %d bytes of UniformDH handshake and "
                          "session ticket." % len(handshakeMsg))

                self.circuit.downstream.write(handshakeMsg)
                log.debug("UniformDH authentication succeeded.")

                log.debug("Switching to state ST_CONNECTED.")
                self.protoState = const.ST_CONNECTED

                self.sendTicketAndSeed()

            elif len(data) > const.MAX_HANDSHAKE_LENGTH:
                self.protoState = const.ST_AUTH_FAILED
                self.drainedHandshake = len(data)
                data.drain(self.drainedHandshake)
                log.info("No successful authentication after having " \
                         "received >= %d bytes.  Now ignoring client." % \
                         const.MAX_HANDSHAKE_LENGTH)
                return

            else:
                log.debug("Authentication unsuccessful so far.  "
                          "Waiting for more data.")
                return

        elif self.weAreClient and (self.protoState == const.ST_WAIT_FOR_AUTH):

            if not self.uniformdh.receivePublicKey(data, self.deriveSecrets):
                log.debug("Unable to finish UniformDH handshake just yet.")
                return

            log.debug("UniformDH authentication succeeded.")

            log.debug("Switching to state ST_CONNECTED.")
            self.protoState = const.ST_CONNECTED
            self.flushSendBuffer()

        if self.protoState == const.ST_CONNECTED:

            self.processMessages(data.read())

    @classmethod
    def register_external_mode_cli( cls, subparser ):
        """
        Register a CLI arguments to pass a secret or ticket to ScrambleSuit.

        Two options are made available over the command line interface: one to
        specify a ticket file and one to specify a UniformDH shared secret.
        """

        passArgs = subparser.add_mutually_exclusive_group(required=True)

        passArgs.add_argument("--password",
                               type=str,
                               help="Shared secret for UniformDH",
                               dest="uniformDHSecret")

        passArgs.add_argument("--password-file",
                               type=str,
                               help="File containing shared secret for UniformDH",
                               action=ReadPassFile,
                               dest="uniformDHSecret")

        super(ScrambleSuitTransport, cls).register_external_mode_cli(subparser)

    @classmethod
    def validate_external_mode_cli( cls, args ):
        """
        Assign the given command line arguments to local variables.
        """

        uniformDHSecret = None

        try:
            uniformDHSecret = base64.b32decode(util.sanitiseBase32(
                                     args.uniformDHSecret))
        except (TypeError, AttributeError) as error:
            log.error(error.message)
            raise base.PluggableTransportError("Given password '%s' is not " \
                    "valid Base32!  Run 'generate_password.py' to generate " \
                    "a good password." % args.uniformDHSecret)

        parentalApproval = super(
            ScrambleSuitTransport, cls).validate_external_mode_cli(args)
        if not parentalApproval:
            # XXX not very descriptive nor helpful, but the parent class only
            #     returns a boolean without telling us what's wrong.
            raise base.PluggableTransportError(
                "Pluggable Transport args invalid: %s" % args )

        if uniformDHSecret:
            rawLength = len(uniformDHSecret)
            if rawLength != const.SHARED_SECRET_LENGTH:
                raise base.PluggableTransportError(
                    "The UniformDH password must be %d bytes in length, ",
                    "but %d bytes are given."
                    % (const.SHARED_SECRET_LENGTH, rawLength))
            else:
                cls.uniformDHSecret = uniformDHSecret

    def handle_socks_args( self, args ):
        """
        Receive arguments `args' passed over a SOCKS connection.

        The SOCKS authentication mechanism is (ab)used to pass arguments to
        pluggable transports.  This method receives these arguments and parses
        them.  As argument, we only expect a UniformDH shared secret.
        """

        log.debug("Received the following arguments over SOCKS: %s." % args)

        if len(args) != 1:
            raise base.SOCKSArgsError("Too many SOCKS arguments "
                                      "(expected 1 but got %d)." % len(args))

        # The ScrambleSuit specification defines that the shared secret is
        # called "password".
        if not args[0].startswith("password="):
            raise base.SOCKSArgsError("The SOCKS argument must start with "
                                      "`password='.")

        # A shared secret might already be set if obfsproxy is in external
        # mode.
        if self.uniformDHSecret:
            log.warning("A UniformDH password was already specified over "
                        "the command line.  Using the SOCKS secret instead.")

        try:
            self.uniformDHSecret = base64.b32decode(util.sanitiseBase32(
                                          args[0].split('=')[1].strip()))
        except TypeError as error:
            log.error(error.message)
            raise base.PluggableTransportError("Given password '%s' is not " \
                    "valid Base32!  Run 'generate_password.py' to generate " \
                    "a good password." % args[0].split('=')[1].strip())

        rawLength = len(self.uniformDHSecret)
        if rawLength != const.SHARED_SECRET_LENGTH:
            raise base.PluggableTransportError("The UniformDH password "
                    "must be %d bytes in length but %d bytes are given." %
                    (const.SHARED_SECRET_LENGTH, rawLength))

        self.uniformdh = uniformdh.new(self.uniformDHSecret, self.weAreServer)

class ScrambleSuitClient( ScrambleSuitTransport ):

    """
    Extend the ScrambleSuit class.
    """

    def __init__( self ):
        """
        Initialise a ScrambleSuitClient object.
        """

        ScrambleSuitTransport.__init__(self)

class ScrambleSuitServer( ScrambleSuitTransport ):

    """
    Extend the ScrambleSuit class.
    """

    def __init__( self ):
        """
        Initialise a ScrambleSuitServer object.
        """

        ScrambleSuitTransport.__init__(self)


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AjaxControlToolkit.Design {

    public class ToggleButtonExtenderDesigner : ExtenderControlBaseDesigner<ToggleButtonExtender> {
    }

}


text:
package com.kwong.drinknight.user_data_page;

/**
 * Created by 锐锋 on 2017/8/25.
 */

public class UserData {

    String userName;
    String account;
    String gender;
    String phoneNumber;
    String password;
    String registerTime;
    int age;
    float height;
    float weight;
    String emailAddress;
    String imageName;

    String cup1ID;
    String cup2ID;
    String cup3ID;
    public String getCup1ID() {
        return cup1ID;
    }

    public void setCup1ID(String cup1ID) {
        this.cup1ID = cup1ID;
    }

    public void setCup2ID(String cup2ID) {
        this.cup2ID = cup2ID;
    }

    public void setCup3ID(String cup3ID) {
        this.cup3ID = cup3ID;
    }

    public String getCup2ID() {
        return cup2ID;
    }

    public String getCup3ID() {
        return cup3ID;
    }

    public UserData(){}
    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setRegisterTime(String registerTime) {
        this.registerTime = registerTime;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setHeight(float height) {
        this.height = height;
    }

    public void setWeight(float weight) {
        this.weight = weight;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getUserName() {

        return userName;
    }

    public String getAccount() {
        return account;
    }

    public String getGender() {
        return gender;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public String getPassword() {
        return password;
    }

    public String getRegisterTime() {
        return registerTime;
    }

    public int getAge() {
        return age;
    }

    public float getHeight() {
        return height;
    }

    public float getWeight() {
        return weight;
    }

    public String getEmailAddress() {
        return emailAddress;
    }
}


text:
package org.scrivo.markdownfx.options;

import org.scrivo.markdownfx.Messages;
import org.scrivo.markdownfx._MarkdownWriterFXApp;

import javafx.event.ActionEvent;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Window;

/**
 * Options dialog
 *
 * @author Karl Tauber
 */
public class OptionsDialog
	extends Dialog<Void>
{
	public OptionsDialog(Window owner) {
		setTitle(Messages.get("OptionsDialog.title"));
		initOwner(owner);

		initComponents();

		tabPane.getStyleClass().add(TabPane.STYLE_CLASS_FLOATING);

		DialogPane dialogPane = getDialogPane();
		dialogPane.setContent(tabPane);
		dialogPane.getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

		// save options on OK clicked
		dialogPane.lookupButton(ButtonType.OK).addEventHandler(ActionEvent.ACTION, e -> {
			save();
			e.consume();
		});

		// load options
		load();

		// select last tab
		int tabIndex = _MarkdownWriterFXApp.getState().getInt("lastOptionsTab", -1);
		if (tabIndex > 0 && tabIndex < tabPane.getTabs().size())
			tabPane.getSelectionModel().select(tabIndex);

		// remember last selected tab
		setOnHidden(e -> {
			_MarkdownWriterFXApp.getState().putInt("lastOptionsTab", tabPane.getSelectionModel().getSelectedIndex());
		});
	}

	private void load() {
		generalOptionsPane.load();
		markdownOptionsPane.load();
	}

	private void save() {
		generalOptionsPane.save();
		markdownOptionsPane.save();
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		tabPane = new TabPane();
		generalTab = new Tab();
		generalOptionsPane = new GeneralOptionsPane();
		markdownTab = new Tab();
		markdownOptionsPane = new MarkdownOptionsPane();

		//======== tabPane ========
		{
			tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);

			//======== generalTab ========
			{
				generalTab.setText(Messages.get("OptionsDialog.generalTab.text"));
				generalTab.setContent(generalOptionsPane);
			}

			//======== markdownTab ========
			{
				markdownTab.setText(Messages.get("OptionsDialog.markdownTab.text"));
				markdownTab.setContent(markdownOptionsPane);
			}

			tabPane.getTabs().addAll(generalTab, markdownTab);
		}
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	private TabPane tabPane;
	private Tab generalTab;
	private GeneralOptionsPane generalOptionsPane;
	private Tab markdownTab;
	private MarkdownOptionsPane markdownOptionsPane;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
}


text:
A starter template for a polymer.dart web app.

## Creating new elements

The `polymer` package includes a utility to generate new elements. From
within this project, run:

`pub run polymer:new_element <name>`

Author: El Hassen Dia,


text:
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on November 4, 2011 */

@font-face {
    font-family: 'AllerRegular';
    src: url('aller_rg-webfont.eot');
    src: url('aller_rg-webfont.eot?#iefix') format('embedded-opentype'),
         url('aller_rg-webfont.woff') format('woff'),
         url('aller_rg-webfont.ttf') format('truetype'),
         url('aller_rg-webfont.svg#AllerRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerBold';
    src: url('aller_bd-webfont.eot');
    src: url('aller_bd-webfont.eot?#iefix') format('embedded-opentype'),
         url('aller_bd-webfont.woff') format('woff'),
         url('aller_bd-webfont.ttf') format('truetype'),
         url('aller_bd-webfont.svg#AllerBold') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerBoldItalic';
    src: url('aller_bdit-webfont.eot');
    src: url('aller_bdit-webfont.eot?#iefix') format('embedded-opentype'),
         url('aller_bdit-webfont.woff') format('woff'),
         url('aller_bdit-webfont.ttf') format('truetype'),
         url('aller_bdit-webfont.svg#AllerBoldItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerDisplayRegular';
    src: url('allerdisplay-webfont.eot');
    src: url('allerdisplay-webfont.eot?#iefix') format('embedded-opentype'),
         url('allerdisplay-webfont.woff') format('woff'),
         url('allerdisplay-webfont.ttf') format('truetype'),
         url('allerdisplay-webfont.svg#AllerDisplayRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerItalic';
    src: url('aller_it-webfont.eot');
    src: url('aller_it-webfont.eot?#iefix') format('embedded-opentype'),
         url('aller_it-webfont.woff') format('woff'),
         url('aller_it-webfont.ttf') format('truetype'),
         url('aller_it-webfont.svg#AllerItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerLightRegular';
    src: url('aller_lt-webfont.eot');
    src: url('aller_lt-webfont.eot?#iefix') format('embedded-opentype'),
         url('aller_lt-webfont.woff') format('woff'),
         url('aller_lt-webfont.ttf') format('truetype'),
         url('aller_lt-webfont.svg#AllerLightRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerLightItalic';
    src: url('aller_ltit-webfont.eot');
    src: url('aller_ltit-webfont.eot?#iefix') format('embedded-opentype'),
         url('aller_ltit-webfont.woff') format('woff'),
         url('aller_ltit-webfont.ttf') format('truetype'),
         url('aller_ltit-webfont.svg#AllerLightItalic') format('svg');
    font-weight: normal;
    font-style: normal;

}


text:
package org.semanticweb.elk.owl.visitors;

import org.semanticweb.elk.owl.interfaces.ElkObjectOneOf;

/**
 * Visitor pattern interface for instances of {@link ElkObjectOneOf}.
 *
 * @author "Yevgeny Kazakov"
 *
 * @param <O>
 *            the type of the output of this visitor
 */
public interface ElkObjectOneOfVisitor<O> {

	public O visit(ElkObjectOneOf expression);

}


text:
local A, L = unpack(select(2, ...))
local M = A:NewModule("sortRaid", "AceTimer-3.0")
A.sortRaid = M
M.private = {
  deltaPlayers = {},
  deltaNewGroups = {},
  action = {},
  splitGroups = {{}, {}},
  keys = {},
  players = {},
}
local R = M.private

local DELAY_ACTION = 0.01
local CLASS_SORT_CHAR = {}
do
  for i, class in ipairs(CLASS_SORT_ORDER) do
    CLASS_SORT_CHAR[class] = string.char(64 + i)
  end
end

local format, floor, ipairs, pairs, sort, tinsert, tostring, wipe = format, floor, ipairs, pairs, sort, tinsert, tostring, wipe
local tconcat = table.concat
local SetRaidSubgroup, SwapRaidSubgroup = SetRaidSubgroup, SwapRaidSubgroup

-- The delta table is an array of players who are in the wrong group.
function M:BuildDelta(sortMode)
  -- Build temporary tables tracking players.
  local keys = wipe(R.keys)
  local players = wipe(R.players)
  local skipFirstGroups = sortMode.skipFirstGroups or 0
  local k
  for name, p in pairs(A.group:GetRoster()) do
    if (not p.isSitting and p.group > skipFirstGroups) or sortMode.isIncludingSitting then
      k = (p.class and CLASS_SORT_CHAR[p.class] or "Z")..(p.isUnknown and ("_"..name) or name)
      tinsert(keys, k)
      players[k] = p
    end
  end

  -- Sort keys.
  local d = A.sortModes:GetDefault()
  if d.onBeforeSort and d.onBeforeSort(sortMode, keys, players) then
    return true
  end
  if sortMode.onBeforeSort and sortMode.onBeforeSort(sortMode, keys, players) then
    return true
  end
  if sortMode.onSort then
    sortMode.onSort(sortMode, keys, players)
  elseif d.onSort then
    d.onSort(sortMode, keys, players)
  end

  -- Determine which group each player needs to be in.
  -- If they're in the wrong group, add them to the delta tables.
  wipe(R.deltaPlayers)
  wipe(R.deltaNewGroups)
  local numGroups = M:GetNumGroups(sortMode)
  local newGroup, iMod4
  for i, k in ipairs(keys) do
    if sortMode.isSplit then
      -- Assign everyone in the raid to a set of groups based on their ranking
      -- in the damage/healing meters. This is quick-and-dirty but it gets the
      -- job done. We don't attempt to balance ranged and melee.
      iMod4 = i % 4
      if A.options.splitOddEven then
        -- Split using odd/even groups (1,3,5,7/2,4,6,8).
        newGroup = floor((i - 1) / 10) * 2 + 1
        if iMod4 == 2 or iMod4 == 3 then
          -- Zig-zag (abbaabba...) for a more even distribution.
          newGroup = newGroup + 1
        end
      else
        -- Split using adjacent groups (1-2/3-4, 1-3/4-6, or 1-4/5-8).
        newGroup = floor((i - 1) / 10) + 1
        if iMod4 == 2 or iMod4 == 3 then
          newGroup = newGroup + floor(numGroups / 2)
        end
      end
    else
      -- Just sorting the raid, not splitting it.
      newGroup = floor((i - 1) / 5) + 1
    end
    newGroup = newGroup + (sortMode.groupOffset or 0)
    if newGroup ~= players[k].group and not players[k].isDummy then
      tinsert(R.deltaPlayers, players[k])
      tinsert(R.deltaNewGroups, newGroup)
    end
  end

  if A.DEBUG >= 2 then M:DebugPrintDelta() end
end

function M:GetNumGroups(sortMode)
  local numPlayers = A.group:GetSize()
  if not sortMode.isIncludingSitting then
    numPlayers = numPlayers - A.group:NumSitting()
  end
  local numGroups = floor((numPlayers - 1) / 5) + 1
  if sortMode.isSplit and numGroups % 2 == 1 then
    numGroups = numGroups + 1
  end
  return numGroups
end

function M:GetSplitGroups(sortMode)
  local numGroups = M:GetNumGroups(sortMode)
  if numGroups < 2 then
    return "1 "..L["word.and"].." 2"
  end
  if A.options.splitOddEven then
    wipe(R.splitGroups[1])
    wipe(R.splitGroups[2])
    for i = 1, numGroups do
      tinsert(R.splitGroups[(i % 2) + 1], tostring(i))
    end
    return tconcat(R.splitGroups[2], "/").." "..L["word.and"].." "..tconcat(R.splitGroups[1], "/")
  else
    numGroups = floor(numGroups / 2)
    return "1-"..numGroups.." "..L["word.and"].." "..(numGroups + 1).."-"..(numGroups * 2)
  end
end

function M:IsDeltaEmpty()
  return #R.deltaPlayers == 0
end

function M:CancelAction()
  if R.action.timer then
    M:CancelTimer(R.action.timer)
  end
  wipe(R.action)
end

local function startAction(name, newGroup, func, desc)
  M:CancelAction()
  R.action.name = name
  R.action.newGroup = newGroup
  R.action.timer = M:ScheduleTimer(func, DELAY_ACTION)
  R.action.desc = desc
end

-- Move the first player in the delta tables to their new group.
-- Populate action, which we'll be checking for in a future GROUP_ROSTER_UPDATE.
-- The action table contains the expected results of the WoW API call,
-- either SetRaidSubgroup or SwapRaidSubgroup.
-- We add in a slight delay to the API call to avoid confusing other addons
-- that rely on the GROUP_ROSTER_UPDATE event.
function M:ProcessDelta()
  M:CancelAction()
  if M:IsDeltaEmpty() then
    return
  end
  local rindex = R.deltaPlayers[1].rindex
  local newGroup = R.deltaNewGroups[1]
  local name = R.deltaPlayers[1].name
  -- Simplest case: the new group has room.
  if A.group:GetGroupSize(newGroup) < 5 then
    startAction(name, newGroup, function() SetRaidSubgroup(rindex, newGroup) end, "set "..rindex.." "..newGroup)
    return
  end
  -- Else find a partner to swap groups with.
  -- Best case: there is a one-to-one swap possible.
  for d = 2, #R.deltaPlayers do
    if R.deltaPlayers[d].group == newGroup and R.deltaNewGroups[d] == R.deltaPlayers[1].group then
      local rindex2 = R.deltaPlayers[d].rindex
      startAction(name, newGroup, function() SwapRaidSubgroup(rindex, rindex2) end, "swap "..rindex.." "..rindex2)
      return
    end
  end
  -- Else there is no one-to-one swap possible for this step.
  -- Just put the partner in the wrong group for now.
  -- They'll get sorted correctly on another iteration.
  for d = 2, #R.deltaPlayers do
    if R.deltaPlayers[d].group == newGroup then
      local rindex2 = R.deltaPlayers[d].rindex
      startAction(name, newGroup, function() SwapRaidSubgroup(rindex, rindex2) end, "swapX "..rindex.." "..rindex2)
      return
    end
  end
  -- Should never get here.
  A.console:Errorf(M, "unable to find slot for %s!", R.action.name)
end

function M:IsActionScheduled()
  return R.action.name and true or false
end

function M:DidActionFinish()
  if R.action.name and R.action.newGroup then
    local p = A.group:GetPlayer(R.action.name)
    return p and (p.group == R.action.newGroup)
  end
end

function M:DebugPrintDelta()
  A.console:Debugf(M, "delta=%d players in incorrect groups:", #R.deltaPlayers)
  if #R.deltaPlayers > 1 then
    local p
    for i = 1, #R.deltaPlayers do
      p = R.deltaPlayers[i]
      A.console:DebugMore(M, format("  %d: group=%d newGroup=%d rindex=%d name=%s", i, p.group, R.deltaNewGroups[i], p.rindex, p.name))
    end
  end
end

function M:DebugPrintAction()
  A.console:Debugf(M, "action: %s to %s: %s", tostring(R.action.name), tostring(R.action.newGroup), tostring(R.action.desc))
end


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Removing unique constraint on 'Member', fields ['ship']
        db.delete_unique(u'main_member', ['ship_id'])

        # Removing unique constraint on 'Member', fields ['location']
        db.delete_unique(u'main_member', ['location_id'])

        # Changing field 'Member.location'
        db.alter_column(u'main_member', 'location_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Location'], null=True))

        # Changing field 'Member.ship'
        db.alter_column(u'main_member', 'ship_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Ship'], null=True))

    def backwards(self, orm):

        # Changing field 'Member.location'
        db.alter_column(u'main_member', 'location_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.Location'], unique=True, null=True))
        # Adding unique constraint on 'Member', fields ['location']
        db.create_unique(u'main_member', ['location_id'])

        # Changing field 'Member.ship'
        db.alter_column(u'main_member', 'ship_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.Ship'], unique=True, null=True))
        # Adding unique constraint on 'Member', fields ['ship']
        db.create_unique(u'main_member', ['ship_id'])

    models = {
        u'main.location': {
            'Meta': {'object_name': 'Location'},
            'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'})
        },
        u'main.member': {
            'Meta': {'object_name': 'Member'},
            'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
            'join_ts': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Location']", 'null': 'True'}),
            'logoff_ts': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}),
            'ship': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['main.Ship']", 'null': 'True'})
        },
        u'main.ship': {
            'Meta': {'object_name': 'Ship'},
            'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'})
        }
    }

    complete_apps = ['main']


text:
package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.Vector;

@SuppressWarnings("unchecked")
public class Rat extends Rodent
{
	public String ID(){	return "Rat"; }
	public String name(){ return "Rat"; }
	public int shortestMale(){return 6;}
	public int shortestFemale(){return 6;}
	public int heightVariance(){return 6;}
	public int lightestWeight(){return 10;}
	public int weightVariance(){return 10;}
	public String racialCategory(){return "Rodent";}

	//                                an ey ea he ne ar ha to le fo no gi mo wa ta wi
	private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,4 ,4 ,1 ,0 ,1 ,1 ,1 ,0 };
	public int[] bodyMask(){return parts;}

	protected static Vector resources=new Vector();
	public void affectCharStats(MOB affectedMOB, CharStats affectableStats)
	{
		super.affectCharStats(affectedMOB, affectableStats);
		affectableStats.setRacialStat(CharStats.STAT_STRENGTH,4);
	}
	public Vector myResources()
	{
		synchronized(resources)
		{
			if(resources.size()==0)
			{
				resources.addElement(makeResource
					("some "+name().toLowerCase()+" hair",RawMaterial.RESOURCE_FUR));
				resources.addElement(makeResource
					("a pair of "+name().toLowerCase()+" teeth",RawMaterial.RESOURCE_BONE));
				resources.addElement(makeResource
					("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_BLOOD));
			}
		}
		Vector rsc=(Vector)resources.clone();
		Item meat=makeResource
		("some "+name().toLowerCase()+" flesh",RawMaterial.RESOURCE_MEAT);
		if((CMLib.dice().rollPercentage()<10)&&(!CMSecurity.isDisabled("AUTODISEASE")))
		{
			Ability A=CMClass.getAbility("Disease_SARS");
			if(A!=null)	meat.addNonUninvokableEffect(A);
		}
		rsc.addElement(meat);
		return rsc;
	}
}


text:
public class FootballMatchReports {
    public static String onField(int shirtNum) {
        String playerDescription = "";
        switch (shirtNum) {
            case 1:
                playerDescription = "goalie";
                break;
            case 2:
                playerDescription = "left back";
                break;
            case 5:
                playerDescription = "right back";
                break;
            case 3:
            case 4:
                playerDescription = "center back";
                break;
            case 6:
            case 7:
            case 8:
                playerDescription = "midfielder";
                break;
            case 9:
                playerDescription = "left wing";
                break;
            case 11:
                playerDescription = "right wing";
                break;
            case 10:
                playerDescription = "striker";
                break;
            default:
                throw new IllegalArgumentException();
        }
        return playerDescription;
    }
}


text:
package net.cortexmodders.lyoko.world.chunk;

import cpw.mods.fml.common.eventhandler.Event;
import net.minecraft.block.Block;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.NoiseGeneratorOctaves;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.terraingen.ChunkProviderEvent;

import java.util.List;
import java.util.Random;

/**
 * @author jadar
 */
public abstract class LyokoBaseChunkProvider implements IChunkProvider
{

    protected Random rand;

    protected NoiseGeneratorOctaves noiseGen1;
    protected NoiseGeneratorOctaves noiseGen2;
    protected NoiseGeneratorOctaves noiseGen3;
    protected NoiseGeneratorOctaves noiseGen4;
    public NoiseGeneratorOctaves noiseGen5;
    public NoiseGeneratorOctaves noiseGen6;
    public NoiseGeneratorOctaves mobSpawnerNoiseGen;

    protected World world;
    protected long seed;

    protected final boolean mapFeaturesEnabled;

    protected double[] noiseArray;
    protected double[] stoneNoise = new double[256];
    protected BiomeGenBase[] biomesForGeneration;

    public double[] noise1;
    public double[] noise2;
    public double[] noise3;
    public double[] noise4;
    public double[] noise5;

    public float[] parabolicField;
    public int[][] field = new int[32][32];

    public LyokoBaseChunkProvider(World world, long seed, boolean mapFeaturesEnabled)
    {
        this.world = world;
        this.rand = new Random(seed);
        this.mapFeaturesEnabled = mapFeaturesEnabled;
    }

    /**
     * generates a subset of the level's terrain data. Takes 7 arguments: the [empty] noise array, the position, and the
     * size.
     */
    protected double[] initializeNoiseField(double[] noiseArray, int xPos, int yPos, int zPos, int xSize, int ySize, int zSize)
    {
        ChunkProviderEvent.InitNoiseField event = new ChunkProviderEvent.InitNoiseField(this, noiseArray, xPos, yPos, zPos, xSize, ySize, zSize);
        MinecraftForge.EVENT_BUS.post(event);
        if (event.getResult() == Event.Result.DENY) return event.noisefield;

        if (noiseArray == null) {
            noiseArray = new double[xSize * ySize * zSize];
        }

        double d0 = 684.412D;
        double d1 = 2053.236D;
        this.noise4 = this.noiseGen4.generateNoiseOctaves(this.noise4, xPos, yPos, zPos, xSize, 1, zSize, 1.0D, 0.0D, 1.0D);
        this.noise5 = this.noiseGen5.generateNoiseOctaves(this.noise5, xPos, yPos, zPos, xSize, 1, zSize, 100.0D, 0.0D, 100.0D);
        this.noise1 = this.noiseGen3.generateNoiseOctaves(this.noise1, xPos, yPos, zPos, xSize, ySize, zSize, d0 / 80.0D, d1 / 60.0D, d0 / 80.0D);
        this.noise2 = this.noiseGen1.generateNoiseOctaves(this.noise2, xPos, yPos, zPos, xSize, ySize, zSize, d0, d1, d0);
        this.noise3 = this.noiseGen2.generateNoiseOctaves(this.noise3, xPos, yPos, zPos, xSize, ySize, zSize, d0, d1, d0);
        int k1 = 0;
        int l1 = 0;
        double[] adouble1 = new double[ySize];
        int i2;

        for (i2 = 0; i2 < ySize; ++i2) {
            adouble1[i2] = Math.cos((double) i2 * Math.PI * 6.0D / (double) ySize) * 2.0D;
            double d2 = (double) i2;

            if (i2 > ySize / 2) {
                d2 = (double) (ySize - 1 - i2);
            }

            if (d2 < 4.0D) {
                d2 = 4.0D - d2;
                adouble1[i2] -= d2 * d2 * d2 * 10.0D;
            }
        }

        for (i2 = 0; i2 < xSize; ++i2) {
            for (int k2 = 0; k2 < zSize; ++k2) {
                double d3 = (this.noise4[l1] + 256.0D) / 512.0D;

                if (d3 > 1.0D) {
                    d3 = 1.0D;
                }

                double d4 = 0.0D;
                double d5 = this.noise5[l1] / 8000.0D;

                if (d5 < 0.0D) {
                    d5 = -d5;
                }

                d5 = d5 * 3.0D - 3.0D;

                if (d5 < 0.0D) {
                    d5 /= 2.0D;

                    if (d5 < -1.0D) {
                        d5 = -1.0D;
                    }

                    d5 /= 1.4D;
                    d5 /= 2.0D;
                    d3 = 0.0D;
                } else {
                    if (d5 > 1.0D) {
                        d5 = 1.0D;
                    }

                    d5 /= 6.0D;
                }

                d3 += 0.5D;
                d5 = d5 * (double) ySize / 16.0D;
                ++l1;

                for (int j2 = 0; j2 < ySize; ++j2) {
                    double d6 = 0.0D;
                    double d7 = adouble1[j2];
                    double d8 = this.noise2[k1] / 512.0D;
                    double d9 = this.noise3[k1] / 512.0D;
                    double d10 = (this.noise1[k1] / 10.0D + 1.0D) / 2.0D;

                    if (d10 < 0.0D) {
                        d6 = d8;
                    } else if (d10 > 1.0D) {
                        d6 = d9;
                    } else {
                        d6 = d8 + (d9 - d8) * d10;
                    }

                    d6 -= d7;
                    double d11;

                    if (j2 > ySize - 4) {
                        d11 = (double) ((float) (j2 - (ySize - 4)) / 3.0F);
                        d6 = d6 * (1.0D - d11) + -10.0D * d11;
                    }

                    if ((double) j2 < d4) {
                        d11 = (d4 - (double) j2) / 4.0D;

                        if (d11 < 0.0D) {
                            d11 = 0.0D;
                        }

                        if (d11 > 1.0D) {
                            d11 = 1.0D;
                        }

                        d6 = d6 * (1.0D - d11) + -10.0D * d11;
                    }

                    noiseArray[k1] = d6;
                    ++k1;
                }
            }
        }

        return noiseArray;
    }

    public abstract void generateTerrain(int chunkX, int chunkZ, Block[] blocks, byte[] blockMeta);

    public abstract void modifyTerrain(int chunkX, int chunkZ, Block[] blocks, byte[] blockMeta);

    /* ========== IChunkProvider ========== */

    /**
     * Checks to see if a chunk exists at x, y
     *
     * @param var1
     * @param var2
     */
    @Override
    public boolean chunkExists(int var1, int var2)
    {
        return false;
    }

    public void replaceBlocksForBiome(int chunkX, int chunkZ, Block[] blocks, byte[] blockMeta, BiomeGenBase[] biomesForGeneration)
    {
        ChunkProviderEvent.ReplaceBiomeBlocks event = new ChunkProviderEvent.ReplaceBiomeBlocks(this, chunkX, chunkZ, blocks, blockMeta, biomesForGeneration);
        MinecraftForge.EVENT_BUS.post(event);
        if (event.getResult() == Event.Result.DENY) return;

        double d0 = 0.03125D;
        int posX = chunkX * 16;
        int posZ = chunkZ * 16;
        this.stoneNoise = this.noiseGen4.generateNoiseOctaves(this.stoneNoise, posX, posZ, 16, 16, d0 * 2.0D, d0 * 2.0D, 1.0D);

        for (int z = 0; z < 16; ++z) {
            for (int x = 0; x < 16; ++x) {
                BiomeGenBase biomegenbase = biomesForGeneration[x + z * 16];
                biomegenbase.genTerrainBlocks(this.world, this.rand, blocks, blockMeta, posX + z, posZ + x, this.stoneNoise[x + z * 16]);
            }
        }
    }

    /**
     * Will return back a chunk, if it doesn't exist and its not a MP client it will generates all the blocks for the
     * specified chunk from the map seed and chunk seed
     *
     * @param chunkX
     * @param chunkZ
     */
    @Override
    public Chunk provideChunk(int chunkX, int chunkZ)
    {
        this.rand.setSeed(chunkX * 341873128712L + chunkZ * 132897987541L);
        // Integer.MAX_VALUE * 2
        Block[] blocks = new Block[65536];
        byte[] blockMeta = new byte[65536];

        this.generateTerrain(chunkX, chunkZ, blocks, blockMeta);
        this.biomesForGeneration = this.world.getWorldChunkManager().loadBlockGeneratorData(this.biomesForGeneration, chunkX * 16, chunkZ * 16, 16, 16);

        this.replaceBlocksForBiome(chunkX, chunkZ, blocks, blockMeta, this.biomesForGeneration);

        Chunk chunk = new Chunk(this.world, blocks, blockMeta, chunkX, chunkZ);
        byte[] ba1 = chunk.getBiomeArray();

        for (int i = 0; i < ba1.length; i++) {
            ba1[i] = (byte) this.biomesForGeneration[i].biomeID;
        }

        chunk.generateSkylightMap();

        return chunk;
    }

    /**
     * loads or generates the chunk at the chunk location specified
     *
     * @param var1
     * @param var2
     */
    @Override
    public Chunk loadChunk(int var1, int var2)
    {
        return null;
    }

    /**
     * Populates chunk with ores etc etc
     *
     * @param var1
     * @param var2
     * @param var3
     */
    @Override
    public void populate(IChunkProvider var1, int var2, int var3)
    {

    }

    /**
     * Two modes of operation: if passed true, save all Chunks in one go.  If passed false, save up to two chunks.
     * Return true if all chunks have been saved.
     *
     * @param var1
     * @param var2
     */
    @Override
    public boolean saveChunks(boolean var1, IProgressUpdate var2)
    {
        return false;
    }

    /**
     * Unloads chunks that are marked to be unloaded. This is not guaranteed to unload every such chunk.
     */
    @Override
    public boolean unloadQueuedChunks()
    {
        return false;
    }

    /**
     * Returns if the IChunkProvider supports saving.
     */
    @Override
    public boolean canSave()
    {
        return false;
    }

    /**
     * Converts the instance data to a readable string.
     */
    @Override
    public String makeString()
    {
        return null;
    }

    /**
     * Returns a list of creatures of the specified type that can spawn at the given location.
     *
     * @param var1
     * @param var2
     * @param var3
     * @param var4
     */
    @Override
    public List getPossibleCreatures(EnumCreatureType var1, int var2, int var3, int var4)
    {
        return null;
    }

    @Override
    public ChunkPosition func_147416_a(World var1, String var2, int var3, int var4, int var5)
    {
        return null;
    }

    @Override
    public int getLoadedChunkCount()
    {
        return 0;
    }

    @Override
    public void recreateStructures(int var1, int var2)
    {

    }

    /**
     * Save extra data not associated with any Chunk.  Not saved during autosave, only during world unload.  Currently
     * unimplemented.
     */
    @Override
    public void saveExtraData()
    {

    }
}


text:
<?php
/**
 * Slim Framework (https://slimframework.com)
 *
 * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
 */

namespace Slim\Http;

/**
 * Provides a PSR-7 implementation of a reusable raw request body
 */
class RequestBody extends Body
{
    public function __construct()
    {
        $stream = fopen('php://temp', 'w+');
        stream_copy_to_stream(fopen('php://input', 'r'), $stream);
        rewind($stream);

        parent::__construct($stream);
    }
}


text:
This directory contains examples to use `go-input`. Each file has `main()` function, so run each.

For example, if you want to run `password.go`,

```bash
$ go run password.go
What is your password?
Enter a value: *******
```


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bartoszlipinski.viewpropertyobjectanimator">

</manifest>


text:
<!DOCTYPE html>

  <title>Your page title here</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="blog-stylesheet.css">

The Internet: Basics

Week 8 Technical Blog

Jan 25 2015

    "...the Internet is not something that you just dump something on. It's not a big truck. It's a series of tubes." --Ted Stevens

    While Ted Stevens quote may be amusing, it does ironically provide a good starting point for understanding the internet as a system and not a "thing". Just as "the grid" connects inidividual homes and businesses to a power source, so does the internet connect computers to each other. Put simply, the internet is a series of interconnected fiber optic cables and wires that allow computers around the world to communicate.

    Servers are computers that are directly connected to the internet, and thus can communicate directly with each other. It is important to understand that most computers, however, namely the computers the average person uses every day (called clients) are not directly connected to the internet, but rather, are indirectly connected through internet service providers (ISPs). If you use AOL, for instance, you would be connected to the internet through AOL as your internet service provider, and all of your internet activity would be routed through that ISP.

    So, how is it that all the information being circulated through the internet to and from different devices is able to find its way to the correct destination? This is where IP addresses and routers come in. All devices that are connected to the internet, whether they be computers, cell phones, servers, ISPs, or the devices that take in and direct information to and from these other devices (known as routers), have IP addresses. It may be useful to think of routers as intersections with special traffic cops that direct travelers (information) in a world where these travelers have mapquest instructions in hand but aren't smart enough to read them. Each time the traveler gets to a new intersection, the traffic cop looks at their mapquest printout, peels off the part of the instructions relating to the already arrived-at intersection, and sends the traveler down the next correct street to the next intersection. This process is repeated until the traveler arrives at their destination.


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Cutlass: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Cutlass

CUDA Templates for Linear Algebra Subroutines and Solvers

cutlass

gemm

LinearScalingDevicePtr

Params

cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params Member List

This is the complete list of members for cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params, including all inherited members.

alpha() const	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

beta() const	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

initialize(Scalar alpha, Scalar beta)	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

initialize(Scalar const *alpha, Scalar const *beta)	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

initialize(GemmDesc_ const &desc)	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

Params()	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

Params(Scalar alpha, Scalar beta)	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

Params(Scalar const *alpha_ptr, Scalar const *beta_ptr)	cutlass::gemm::LinearScalingDevicePtr< Scalar_, FragmentMultiplyAdd_ >::Params	inline

<address class="footer">
Generated on Fri Oct 26 2018 14:53:40 for Cutlass by

 1.8.14
</address>


text:
layout: about
title: Meet our team
permalink: /about/
---

Working together

The Hydrologic Research and Applications Toolbox is being developed by a diverse team of scientists and engineers in the Hydrometeorological Applications Program at the National Center for Atmospheric Research in close collaboration with multiple management agencies and Universities across the Nation and around the world.  Our overarching goal is to advance our understanding of the land surface and atmospheric processes to serve a range of hydrometeorological applications for the benefit of society.

<! --/row -->

<! --/container -->


text:
using std::string;

namespace parquet {

using ReadableFile = ::arrow::io::ReadableFile;

const char* data_dir = std::getenv("PARQUET_TEST_DATA");

std::string alltypes_plain() {
  std::string dir_string(data_dir);
  std::stringstream ss;
  ss << dir_string << "/"
     << "alltypes_plain.parquet";
  return ss.str();
}

std::string nation_dict_truncated_data_page() {
  std::string dir_string(data_dir);
  std::stringstream ss;
  ss << dir_string << "/"
     << "nation.dict-malformed.parquet";
  return ss.str();
}

class TestAllTypesPlain : public ::testing::Test {
 public:
  void SetUp() { reader_ = ParquetFileReader::OpenFile(alltypes_plain()); }

  void TearDown() {}

 protected:
  std::unique_ptr<ParquetFileReader> reader_;
};

TEST_F(TestAllTypesPlain, NoopConstructDestruct) {}

TEST_F(TestAllTypesPlain, TestBatchRead) {
  std::shared_ptr<RowGroupReader> group = reader_->RowGroup(0);

  // column 0, id
  std::shared_ptr<Int32Reader> col =
      std::dynamic_pointer_cast<Int32Reader>(group->Column(0));

  int16_t def_levels[4];
  int16_t rep_levels[4];
  int32_t values[4];

  // This file only has 8 rows
  ASSERT_EQ(8, reader_->metadata()->num_rows());
  // This file only has 1 row group
  ASSERT_EQ(1, reader_->metadata()->num_row_groups());
  // Size of the metadata is 730 bytes
  ASSERT_EQ(730, reader_->metadata()->size());
  // This row group must have 8 rows
  ASSERT_EQ(8, group->metadata()->num_rows());

  ASSERT_TRUE(col->HasNext());
  int64_t values_read;
  auto levels_read = col->ReadBatch(4, def_levels, rep_levels, values, &values_read);
  ASSERT_EQ(4, levels_read);
  ASSERT_EQ(4, values_read);

  // Now read past the end of the file
  ASSERT_TRUE(col->HasNext());
  levels_read = col->ReadBatch(5, def_levels, rep_levels, values, &values_read);
  ASSERT_EQ(4, levels_read);
  ASSERT_EQ(4, values_read);

  ASSERT_FALSE(col->HasNext());
}

TEST_F(TestAllTypesPlain, TestFlatScannerInt32) {
  std::shared_ptr<RowGroupReader> group = reader_->RowGroup(0);

  // column 0, id
  std::shared_ptr<Int32Scanner> scanner(new Int32Scanner(group->Column(0)));
  int32_t val;
  bool is_null;
  for (int i = 0; i < 8; ++i) {
    ASSERT_TRUE(scanner->HasNext());
    ASSERT_TRUE(scanner->NextValue(&val, &is_null));
    ASSERT_FALSE(is_null);
  }
  ASSERT_FALSE(scanner->HasNext());
  ASSERT_FALSE(scanner->NextValue(&val, &is_null));
}

TEST_F(TestAllTypesPlain, TestSetScannerBatchSize) {
  std::shared_ptr<RowGroupReader> group = reader_->RowGroup(0);

  // column 0, id
  std::shared_ptr<Int32Scanner> scanner(new Int32Scanner(group->Column(0)));

  ASSERT_EQ(128, scanner->batch_size());
  scanner->SetBatchSize(1024);
  ASSERT_EQ(1024, scanner->batch_size());
}

TEST_F(TestAllTypesPlain, DebugPrintWorks) {
  std::stringstream ss;

  std::list<int> columns;
  ParquetFilePrinter printer(reader_.get());
  printer.DebugPrint(ss, columns);

  std::string result = ss.str();
  ASSERT_GT(result.size(), 0);
}

TEST_F(TestAllTypesPlain, ColumnSelection) {
  std::stringstream ss;

  std::list<int> columns;
  columns.push_back(5);
  columns.push_back(0);
  columns.push_back(10);
  ParquetFilePrinter printer(reader_.get());
  printer.DebugPrint(ss, columns);

  std::string result = ss.str();
  ASSERT_GT(result.size(), 0);
}

TEST_F(TestAllTypesPlain, ColumnSelectionOutOfRange) {
  std::stringstream ss;

  std::list<int> columns;
  columns.push_back(100);
  ParquetFilePrinter printer1(reader_.get());
  ASSERT_THROW(printer1.DebugPrint(ss, columns), ParquetException);

  columns.clear();
  columns.push_back(-1);
  ParquetFilePrinter printer2(reader_.get());
  ASSERT_THROW(printer2.DebugPrint(ss, columns), ParquetException);
}

class TestLocalFile : public ::testing::Test {
 public:
  void SetUp() {
    std::string dir_string(data_dir);

    std::stringstream ss;
    ss << dir_string << "/"
       << "alltypes_plain.parquet";

    PARQUET_THROW_NOT_OK(ReadableFile::Open(ss.str(), &handle));
    fileno = handle->file_descriptor();
  }

  void TearDown() {}

 protected:
  int fileno;
  std::shared_ptr<::arrow::io::ReadableFile> handle;
};

class HelperFileClosed : public ArrowInputFile {
 public:
  explicit HelperFileClosed(
      const std::shared_ptr<::arrow::io::ReadableFileInterface>& file, bool* close_called)
      : ArrowInputFile(file), close_called_(close_called) {}

  void Close() override { *close_called_ = true; }

 private:
  bool* close_called_;
};

TEST_F(TestLocalFile, FileClosedOnDestruction) {
  bool close_called = false;
  {
    auto contents = SerializedFile::Open(
        std::unique_ptr<RandomAccessSource>(new HelperFileClosed(handle, &close_called)));
    std::unique_ptr<ParquetFileReader> result(new ParquetFileReader());
    result->Open(std::move(contents));
  }
  ASSERT_TRUE(close_called);
}

TEST_F(TestLocalFile, OpenWithMetadata) {
  // PARQUET-808
  std::stringstream ss;
  std::shared_ptr<FileMetaData> metadata = ReadMetaData(handle);

  auto reader = ParquetFileReader::Open(handle, default_reader_properties(), metadata);

  // Compare pointers
  ASSERT_EQ(metadata.get(), reader->metadata().get());

  std::list<int> columns;
  ParquetFilePrinter printer(reader.get());
  printer.DebugPrint(ss, columns, true);

  // Make sure OpenFile passes on the external metadata, too
  auto reader2 = ParquetFileReader::OpenFile(alltypes_plain(), false,
                                             default_reader_properties(), metadata);

  // Compare pointers
  ASSERT_EQ(metadata.get(), reader2->metadata().get());
}

TEST(TestFileReaderAdHoc, NationDictTruncatedDataPage) {
  // PARQUET-816. Some files generated by older Parquet implementations may
  // contain malformed data page metadata, and we can successfully decode them
  // if we optimistically proceed to decoding, even if there is not enough data
  // available in the stream. Before, we had quite aggressive checking of
  // stream reads, which are not found e.g. in Impala's Parquet implementation
  auto reader = ParquetFileReader::OpenFile(nation_dict_truncated_data_page(), false);
  std::stringstream ss;

  // empty list means print all
  std::list<int> columns;
  ParquetFilePrinter printer1(reader.get());
  printer1.DebugPrint(ss, columns, true);

  reader = ParquetFileReader::OpenFile(nation_dict_truncated_data_page(), true);
  std::stringstream ss2;
  ParquetFilePrinter printer2(reader.get());
  printer2.DebugPrint(ss2, columns, true);

  // The memory-mapped reads runs over the end of the column chunk and succeeds
  // by accident
  ASSERT_EQ(ss2.str(), ss.str());
}

TEST(TestJSONWithLocalFile, JSONOutput) {
  std::string jsonOutput = R"###({
  "FileName": "alltypes_plain.parquet",
  "Version": "0",
  "CreatedBy": "impala version 1.3.0-INTERNAL (build 8a48ddb1eff84592b3fc06bc6f51ec120e1fffc9)",
  "TotalRows": "8",
  "NumberOfRowGroups": "1",
  "NumberOfRealColumns": "11",
  "NumberOfColumns": "11",
  "Columns": [
     { "Id": "0", "Name": "id", "PhysicalType": "INT32", "LogicalType": "NONE" },
     { "Id": "1", "Name": "bool_col", "PhysicalType": "BOOLEAN", "LogicalType": "NONE" },
     { "Id": "2", "Name": "tinyint_col", "PhysicalType": "INT32", "LogicalType": "NONE" },
     { "Id": "3", "Name": "smallint_col", "PhysicalType": "INT32", "LogicalType": "NONE" },
     { "Id": "4", "Name": "int_col", "PhysicalType": "INT32", "LogicalType": "NONE" },
     { "Id": "5", "Name": "bigint_col", "PhysicalType": "INT64", "LogicalType": "NONE" },
     { "Id": "6", "Name": "float_col", "PhysicalType": "FLOAT", "LogicalType": "NONE" },
     { "Id": "7", "Name": "double_col", "PhysicalType": "DOUBLE", "LogicalType": "NONE" },
     { "Id": "8", "Name": "date_string_col", "PhysicalType": "BYTE_ARRAY", "LogicalType": "NONE" },
     { "Id": "9", "Name": "string_col", "PhysicalType": "BYTE_ARRAY", "LogicalType": "NONE" },
     { "Id": "10", "Name": "timestamp_col", "PhysicalType": "INT96", "LogicalType": "NONE" }
  ],
  "RowGroups": [
     {
       "Id": "0",  "TotalBytes": "671",  "Rows": "8",
       "ColumnChunks": [
          {"Id": "0", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "73", "CompressedSize": "73" },
          {"Id": "1", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "24", "CompressedSize": "24" },
          {"Id": "2", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "47", "CompressedSize": "47" },
          {"Id": "3", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "47", "CompressedSize": "47" },
          {"Id": "4", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "47", "CompressedSize": "47" },
          {"Id": "5", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "55", "CompressedSize": "55" },
          {"Id": "6", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "47", "CompressedSize": "47" },
          {"Id": "7", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "55", "CompressedSize": "55" },
          {"Id": "8", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "88", "CompressedSize": "88" },
          {"Id": "9", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "49", "CompressedSize": "49" },
          {"Id": "10", "Values": "8", "StatsSet": "False",
           "Compression": "UNCOMPRESSED", "Encodings": "RLE PLAIN_DICTIONARY PLAIN ", "UncompressedSize": "139", "CompressedSize": "139" }
        ]
     }
  ]
}
)###";

  std::stringstream ss;
  // empty list means print all
  std::list<int> columns;

  auto reader =
      ParquetFileReader::OpenFile(alltypes_plain(), false, default_reader_properties());
  ParquetFilePrinter printer(reader.get());
  printer.JSONPrint(ss, columns, "alltypes_plain.parquet");

  ASSERT_EQ(jsonOutput, ss.str());
}

}  // namespace parquet


text:
sudo openstack tripleo deploy \
    --templates /home/cloud-user/tripleo-heat-templates \
    --roles-file /home/cloud-user/tripleo/environments/cnv/roles-data.yaml \
    -n /home/cloud-user/tripleo-heat-templates/network_data.yaml \
    -e /home/cloud-user/tripleo-heat-templates/overcloud-resource-registry-puppet.yaml \
    -e /home/cloud-user/tripleo-heat-templates/environments/deployed-server-environment.yaml \
    -e /home/cloud-user/tripleo/environments/passwords.yaml \
    -e /home/cloud-user/tripleo/environments/stack-action-create.yaml \
    -e /home/cloud-user/tripleo/environments/osp16-docker-ha.yaml \
    -e /home/cloud-user/tripleo/environments/deploy-identifier.yaml \
    -e /home/cloud-user/tripleo/environments/cnv/role-counts.yaml \
    -e /home/cloud-user/tripleo/environments/cnv/hostnamemap.yaml \
    -e /home/cloud-user/tripleo/environments/cnv/network-environment.yaml \
    -e /home/cloud-user/tripleo/environments/cnv/deployed-server-port-map.yaml \
    -e /home/cloud-user/tripleo/environments/cnv/root-stack-name.yaml \
    -e /home/cloud-user/tripleo/environments/containers-rhosp16-prepare-parameter.yaml \
    -e /home/cloud-user/tripleo/environments/containers-rhosp16-latest.yaml \
    -e /home/cloud-user/tripleo/environments/glance-backend-file.yaml \
    --output-dir /home/cloud-user/tripleo-deploy \
    --output-only \
    --standalone \
    --local-ip 192.168.24.6


text:
package gnu.classpath.jdwp.transport;

import gnu.classpath.jdwp.transport.ITransport;
import gnu.classpath.jdwp.transport.TransportException;

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;

/**
 * A socket-based transport. This transport uses
 * configury string that looks like "name=dt_socket,
 * address=localhost:1234,server=y".
 *
 * @author Keith Seitz (keiths@redhat.com)
 */
class SocketTransport
  implements ITransport
{
  /**
   * Name of this transport
   */
  public static final String NAME = "dt_socket";

  // Configure properties
  private static final String _PROPERTY_ADDRESS = "address";
  private static final String _PROPERTY_SERVER = "server";

  // Port number
  private int _port;

  // Host name
  private String _host;

  // Are we acting as a server?
  private boolean _server = false;

  // Socket
  private Socket _socket;

  /**
   * Setup the connection configuration from the given properties
   *
   * @param  properties  the properties of the JDWP session
   * @throws TransportException for any configury errors
   */
  public void configure(HashMap properties)
    throws TransportException
  {
    // Get server [form: "y" or "n"]
    String p = (String) properties.get(_PROPERTY_SERVER);
    if (p != null)
      {
	if (p.toLowerCase().equals("y"))
	  _server = true;
      }

    // Get address [form: "hostname:port"]
    p = (String) properties.get(_PROPERTY_ADDRESS);
    if (p != null)
      {
	String[] s = p.split(":");
	if (s.length == 1)
	  {
	    // Port number only. Assume "localhost"
	    _port = Integer.parseInt(s[0]);
	    _host = "localhost";
	  }
	else
	  {
	    if (s[0].length() == 0)
	      _host = "localhost";
	    else
	      _host = s[0];
	    _port = Integer.parseInt(s[1]);
	  }
      }
  }

  /**
   * Initialize this socket connection. This includes
   * connecting to the host (or listening for it).
   *
   * @throws TransportException if a transport-related error occurs
   */
  public void initialize ()
    throws TransportException
  {
    try
      {
	if (_server)
	  {
	    // Get a server socket
	    ServerSocketFactory ssf = ServerSocketFactory.getDefault ();
	    ServerSocket ss = ssf.createServerSocket (_port, 1);
	    _socket = ss.accept ();
	  }
	else
	  {
	    // Get a client socket (the factory will connect it)
	    SocketFactory sf = SocketFactory.getDefault ();
	    _socket = sf.createSocket (_host, _port);
	  }
      }
    catch (IOException ioe)
      {
	// This will grab UnknownHostException, too.
	throw new TransportException (ioe);
      }
  }

  /**
   * Shutdown the socket. This could cause SocketExceptions
   * for anyone blocked on socket i/o
   */
  public void shutdown ()
  {
    try
      {
	_socket.close ();
      }
    catch (Throwable t)
      {
	// We don't really care about errors at this point
      }
  }

  /**
   * Returns an InputStream for the transport
   *
   * @throws IOException if an I/O error occurs creating the stream
   *                     or the socket is not connected
   */
  public InputStream getInputStream ()
    throws IOException
  {
    return _socket.getInputStream ();
  }

  /**
   * Returns an OutputStream for the transport
   *
   * @throws IOException if an I/O error occurs creating the stream
   *                     or the socket is not connected
   */
  public OutputStream getOutputStream ()
    throws IOException
  {
    return _socket.getOutputStream ();
  }
}