text:
from __future__ import generators
from pygr.leelabdb import *
import pygr.coordinator

def map_clusters(server,**kwargs):
    "map clusters one by one"
    hg17=BlastDB(ifile=server.open_resource('hg17','r')) # CONSTRUCT RESOURCE FOR US IF NEEDED
    # LOAD DB SCHEMA
    (clusters,exons,splices,genomic_seq,spliceGraph,alt5Graph,alt3Graph,mrna,protein,
     clusterExons,clusterSplices)=getSpliceGraphFromDB(spliceCalcs['HUMAN_SPLICE'])
    for cluster_id in server:
        g=genomic_seq[cluster_id]
        m=hg17.megablast(g,maxseq=1,minIdentity=98) # MASK, BLAST, READ INTO m
        # SAVE ALIGNMENT m TO DATABASE TABLE test.mytable USING cursor
        createTableFromRepr(m.repr_dict(),
                            'GENOME_ALIGNMENT.hg17_cluster_jan02',
                            clusters.cursor,
                            {'src_id':'varchar(12)','dest_id':'varchar(12)'})
        yield cluster_id # WE MUST FUNCTION AS GENERATOR

def serve_clusters():
    "serve up cluster_id one by one"
    cursor=getUserCursor('HUMAN_SPLICE')
    t=SQLTable('HUMAN_SPLICE.genomic_cluster_jan02',cursor)
    for id in t:
        yield id

if __name__=='__main__':
    coordinator.start_client_or_server(map_clusters,serve_clusters,['hg17'],__file__)


text:
package de.axeclbr.shoushiling.menu

object MenuCreator extends MainMenu with GameModeMenu with TurnChoiceMenu

redpajama_set_name: RedPajamaGithub


text:
What's React?
Super quick, honest

var HelloMessage = React.createClass({displayName: "HelloMessage",
  render: function() {
    return React.createElement("div", null, "Hello ", this.props.name);
  }
});
React.render(React.createElement(HelloMessage, {name: "John"}), mountNode);

Hello John

            React Real Quick for those that don't know what it is (from facebook):

            JUST THE UI

            Lots of people use React as the V in MVC. Since React makes no assumptions about the rest of your technology stack, it's easy to try it out on a small feature in an existing project.

            React abstracts away the DOM from you.

            React implements one-way reactive data flow (vs two-way typical in most 'View' stacks)


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('pages', '0021_auto_20170505_1656'),
    ]

    operations = [
        migrations.AlterField(
            model_name='formfield',
            name='field_type',
            field=models.CharField(choices=[('singleline', 'Single line text'), ('multiline', 'Multi-line text'), ('email', 'Email'), ('number', 'Number'), ('url', 'URL'), ('checkbox', 'Checkbox'), ('checkboxes', 'Checkboxes'), ('dropdown', 'Drop down'), ('multiselect', 'Multiple select'), ('radio', 'Radio buttons'), ('date', 'Date'), ('datetime', 'Date/time')], max_length=16, verbose_name='field type'),
        ),
    ]


text:
<?php

namespace MicrosoftAzure\Storage\Tests\Unit\Blob\Models;

use MicrosoftAzure\Storage\Common\Internal\Utilities;
use MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult;
use MicrosoftAzure\Storage\Common\Models\RangeDiff;
use MicrosoftAzure\Storage\Tests\Framework\TestResources;

/**
 * Unit tests for class ListPageBlobRangesDiffResult
 *
 * @category  Microsoft
 * @package   MicrosoftAzure\Storage\Tests\Unit\Blob\Models
 * @author    Azure Storage PHP SDK <dmsh@microsoft.com>
 * @copyright 2017 Microsoft Corporation
 * @license   https://github.com/azure/azure-storage-php/LICENSE
 * @link      https://github.com/azure/azure-storage-php
 */
class ListPageBlobRangesDiffResultTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::getRanges
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::setRanges
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::setContentLength
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::getContentLength
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::setETag
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::getETag
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::setLastModified
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::getLastModified
     * @covers MicrosoftAzure\Storage\Blob\Models\ListPageBlobRangesDiffResult::create
     */
    public function testCreate()
    {
        // Setup
        $headers   = TestResources::listPageRangeHeaders();
        $bodyArray = TestResources::listPageRangeDiffBodyInArray();
        // Prepare expected page range
        $rawPageRanges = array();
        if (!empty($bodyArray['PageRange'])) {
            $rawPageRanges = Utilities::getArray($bodyArray['PageRange']);
        }

        $rawClearRanges = array();
        if (!empty($bodyArray['ClearRange'])) {
            $rawClearRanges = Utilities::getArray($bodyArray['ClearRange']);
        }

        $pageRanges = array();

        foreach ($rawPageRanges as $value) {
            $pageRanges[] = new RangeDiff(
                intval($value['Start']),
                intval($value['End']),
                false
            );
        }

        foreach ($rawClearRanges as $value) {
            $rawClearRanges[] = new RangeDiff(
                intval($value['Start']),
                intval($value['End']),
                true
            );
        }

        // Prepare expected last modified date
        $expectedLastModified = Utilities::rfc1123ToDateTime($headers['Last-Modified']);

        // Test
        $result = ListPageBlobRangesDiffResult::create($headers, $bodyArray);

        //Assert
        $this->assertEquals($pageRanges, $result->getRanges());
        $this->assertEquals($expectedLastModified, $result->getLastModified());
        $this->assertEquals($headers['Etag'], $result->getETag());
        $this->assertEquals($headers['x-ms-blob-content-length'], $result->getContentLength());
    }
}


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

<title>vue.forme.Point</title>
<meta name="date" content="2015-01-08">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

vue.forme.Point

Classes

PointEntrePoint

PointInterVector

PointVector


text:
module K4compiler

  class Base

    # @return [Hash]
    def self.options
      return {}
    end

    def initialize(config)
      @config_ = config
    end

    # @return [K4compiler::Config]
    def config
      return @config_
    end

    # compile
    def compile
      raise NotImplementedError.new("Compile method implement in child classes.")
    end
  end
end


text:
package com.cc.jcg.hierarchy;

import java.util.Set;

public interface ParentNode<NI> {

    NI getNodeItem();

    Set<Node<NI>> getChildNodes();
}


text:
package sun.security.ssl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.ByteBuffer;
import javax.net.ssl.SSLHandshakeException;

/**
 * {@code OutputRecord} implementation for {@code SSLSocket}.
 */
final class SSLSocketOutputRecord extends OutputRecord implements SSLRecord {
    private OutputStream deliverStream = null;

    SSLSocketOutputRecord(HandshakeHash handshakeHash) {
        this(handshakeHash, null);
    }

    SSLSocketOutputRecord(HandshakeHash handshakeHash,
            TransportContext tc) {
        super(handshakeHash, SSLCipher.SSLWriteCipher.nullTlsWriteCipher());
        this.tc = tc;
        this.packetSize = SSLRecord.maxRecordSize;
        this.protocolVersion = ProtocolVersion.NONE;
    }

    @Override
    void encodeAlert(byte level, byte description) throws IOException {
        recordLock.lock();
        try {
            if (isClosed()) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.warning("outbound has closed, ignore outbound " +
                        "alert message: " + Alert.nameOf(description));
                }
                return;
            }

            // use the buf of ByteArrayOutputStream
            count = headerSize + writeCipher.getExplicitNonceSize();

            write(level);
            write(description);
            if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                SSLLogger.fine("WRITE: " + protocolVersion.name +
                        " " + ContentType.ALERT.name +
                        "(" + Alert.nameOf(description) + ")" +
                        ", length = " + (count - headerSize));
            }

            // Encrypt the fragment and wrap up a record.
            encrypt(writeCipher, ContentType.ALERT.id, headerSize);

            // deliver this message
            deliverStream.write(buf, 0, count);    // may throw IOException
            deliverStream.flush();                 // may throw IOException

            if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                SSLLogger.fine("Raw write",
                        (new ByteArrayInputStream(buf, 0, count)));
            }

            // reset the internal buffer
            count = 0;
        } finally {
            recordLock.unlock();
        }
    }

    @Override
    void encodeHandshake(byte[] source,
            int offset, int length) throws IOException {
        recordLock.lock();
        try {
            if (isClosed()) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.warning("outbound has closed, ignore outbound " +
                            "handshake message",
                            ByteBuffer.wrap(source, offset, length));
                }
                return;
            }

            if (firstMessage) {
                firstMessage = false;

                if ((helloVersion == ProtocolVersion.SSL20Hello) &&
                    (source[offset] == SSLHandshake.CLIENT_HELLO.id) &&
                                            //  5: recode header size
                    (source[offset + 4 + 2 + 32] == 0)) {
                                            // V3 session ID is empty
                                            //  4: handshake header size
                                            //  2: client_version in ClientHello
                                            // 32: random in ClientHello

                    ByteBuffer v2ClientHello = encodeV2ClientHello(
                            source, (offset + 4), (length - 4));

                    // array offset is zero
                    byte[] record = v2ClientHello.array();
                    int limit = v2ClientHello.limit();
                    handshakeHash.deliver(record, 2, (limit - 2));

                    if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                        SSLLogger.fine(
                                "WRITE: SSLv2 ClientHello message" +
                                ", length = " + limit);
                    }

                    // deliver this message
                    //
                    // Version 2 ClientHello message should be plaintext.
                    //
                    // No max fragment length negotiation.
                    deliverStream.write(record, 0, limit);
                    deliverStream.flush();

                    if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                        SSLLogger.fine("Raw write",
                                (new ByteArrayInputStream(record, 0, limit)));
                    }

                    return;
                }
            }

            byte handshakeType = source[0];
            if (handshakeHash.isHashable(handshakeType)) {
                handshakeHash.deliver(source, offset, length);
            }

            int fragLimit = getFragLimit();
            int position = headerSize + writeCipher.getExplicitNonceSize();
            if (count == 0) {
                count = position;
            }

            if ((count - position) < (fragLimit - length)) {
                write(source, offset, length);
                return;
            }

            for (int limit = (offset + length); offset < limit;) {

                int remains = (limit - offset) + (count - position);
                int fragLen = Math.min(fragLimit, remains);

                // use the buf of ByteArrayOutputStream
                write(source, offset, fragLen);
                if (remains < fragLimit) {
                    return;
                }

                if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                    SSLLogger.fine(
                            "WRITE: " + protocolVersion.name +
                            " " + ContentType.HANDSHAKE.name +
                            ", length = " + (count - headerSize));
                }

                // Encrypt the fragment and wrap up a record.
                encrypt(writeCipher, ContentType.HANDSHAKE.id, headerSize);

                // deliver this message
                deliverStream.write(buf, 0, count);    // may throw IOException
                deliverStream.flush();                 // may throw IOException

                if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                    SSLLogger.fine("Raw write",
                            (new ByteArrayInputStream(buf, 0, count)));
                }

                // reset the offset
                offset += fragLen;

                // reset the internal buffer
                count = position;
            }
        } finally {
            recordLock.unlock();
        }
    }

    @Override
    void encodeChangeCipherSpec() throws IOException {
        recordLock.lock();
        try {
            if (isClosed()) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.warning("outbound has closed, ignore outbound " +
                        "change_cipher_spec message");
                }
                return;
            }

            // use the buf of ByteArrayOutputStream
            count = headerSize + writeCipher.getExplicitNonceSize();

            write((byte)1);         // byte 1: change_cipher_spec(

            // Encrypt the fragment and wrap up a record.
            encrypt(writeCipher, ContentType.CHANGE_CIPHER_SPEC.id, headerSize);

            // deliver this message
            deliverStream.write(buf, 0, count);        // may throw IOException
            // deliverStream.flush();                  // flush in Finished

            if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                SSLLogger.fine("Raw write",
                        (new ByteArrayInputStream(buf, 0, count)));
            }

            // reset the internal buffer
            count = 0;
        } finally {
            recordLock.unlock();
        }
    }

    @Override
    public void flush() throws IOException {
        recordLock.lock();
        try {
            int position = headerSize + writeCipher.getExplicitNonceSize();
            if (count <= position) {
                return;
            }

            if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                SSLLogger.fine(
                        "WRITE: " + protocolVersion.name +
                        " " + ContentType.HANDSHAKE.name +
                        ", length = " + (count - headerSize));
            }

            // Encrypt the fragment and wrap up a record.
            encrypt(writeCipher, ContentType.HANDSHAKE.id, headerSize);

            // deliver this message
            deliverStream.write(buf, 0, count);    // may throw IOException
            deliverStream.flush();                 // may throw IOException

            if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                SSLLogger.fine("Raw write",
                        (new ByteArrayInputStream(buf, 0, count)));
            }

            // reset the internal buffer
            count = 0;      // DON'T use position
        } finally {
            recordLock.unlock();
        }
    }

    @Override
    void deliver(byte[] source, int offset, int length) throws IOException {
        recordLock.lock();
        try {
            if (isClosed()) {
                throw new SocketException(
                        "Connection or outbound has been closed");
            }

            if (writeCipher.authenticator.seqNumOverflow()) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl")) {
                    SSLLogger.fine(
                        "sequence number extremely close to overflow " +
                        "(2^64-1 packets). Closing connection.");
                }

                throw new SSLHandshakeException("sequence number overflow");
            }

            boolean isFirstRecordOfThePayload = true;
            for (int limit = (offset + length); offset < limit;) {
                int fragLen;
                if (packetSize > 0) {
                    fragLen = Math.min(maxRecordSize, packetSize);
                    fragLen = writeCipher.calculateFragmentSize(
                            fragLen, headerSize);

                    fragLen = Math.min(fragLen, Record.maxDataSize);
                } else {
                    fragLen = Record.maxDataSize;
                }

                // Calculate more impact, for example TLS 1.3 padding.
                fragLen = calculateFragmentSize(fragLen);

                if (isFirstRecordOfThePayload && needToSplitPayload()) {
                    fragLen = 1;
                    isFirstRecordOfThePayload = false;
                } else {
                    fragLen = Math.min(fragLen, (limit - offset));
                }

                // use the buf of ByteArrayOutputStream
                int position = headerSize + writeCipher.getExplicitNonceSize();
                count = position;
                write(source, offset, fragLen);

                if (SSLLogger.isOn && SSLLogger.isOn("record")) {
                    SSLLogger.fine(
                            "WRITE: " + protocolVersion.name +
                            " " + ContentType.APPLICATION_DATA.name +
                            ", length = " + (count - position));
                }

                // Encrypt the fragment and wrap up a record.
                encrypt(writeCipher,
                        ContentType.APPLICATION_DATA.id, headerSize);

                // deliver this message
                deliverStream.write(buf, 0, count);    // may throw IOException
                deliverStream.flush();                 // may throw IOException

                if (SSLLogger.isOn && SSLLogger.isOn("packet")) {
                    SSLLogger.fine("Raw write",
                            (new ByteArrayInputStream(buf, 0, count)));
                }

                // reset the internal buffer
                count = 0;

                if (isFirstAppOutputRecord) {
                    isFirstAppOutputRecord = false;
                }

                offset += fragLen;
            }
        } finally {
            recordLock.unlock();
        }
    }

    @Override
    void setDeliverStream(OutputStream outputStream) {
        recordLock.lock();
        try {
            this.deliverStream = outputStream;
        } finally {
            recordLock.unlock();
        }
    }

    /*
     * Need to split the payload except the following cases:
     *
     * 1. protocol version is TLS 1.1 or later;
     * 2. bulk cipher does not use CBC mode, including null bulk cipher suites.
     * 3. the payload is the first application record of a freshly
     *    negotiated TLS session.
     * 4. the CBC protection is disabled;
     *
     * By default, we counter chosen plaintext issues on CBC mode
     * ciphersuites in SSLv3/TLS1.0 by sending one byte of application
     * data in the first record of every payload, and the rest in
     * subsequent record(s). Note that the issues have been solved in
     * TLS 1.1 or later.
     *
     * It is not necessary to split the very first application record of
     * a freshly negotiated TLS session, as there is no previous
     * application data to guess.  To improve compatibility, we will not
     * split such records.
     *
     * This avoids issues in the outbound direction.  For a full fix,
     * the peer must have similar protections.
     */
    private boolean needToSplitPayload() {
        return (!protocolVersion.useTLS11PlusSpec()) &&
                writeCipher.isCBCMode() && !isFirstAppOutputRecord &&
                Record.enableCBCProtection;
    }

    private int getFragLimit() {
        int fragLimit;
        if (packetSize > 0) {
            fragLimit = Math.min(maxRecordSize, packetSize);
            fragLimit =
                    writeCipher.calculateFragmentSize(fragLimit, headerSize);

            fragLimit = Math.min(fragLimit, Record.maxDataSize);
        } else {
            fragLimit = Record.maxDataSize;
        }

        // Calculate more impact, for example TLS 1.3 padding.
        fragLimit = calculateFragmentSize(fragLimit);

        return fragLimit;
    }
}


text:
<?php
namespace Mill\Compiler;

use Mill\Compiler;
use Mill\Compiler\ErrorMap\Formats\Markdown;
use Mill\Parser\Annotations\ErrorAnnotation;
use Mill\Parser\Annotations\ReturnAnnotation;
use Mill\Parser\Resource\Action;

class ErrorMap extends Compiler
{
    /** @var array Compiled error map. */
    protected $error_map = [];

    /**
     * Take compiled API documentation and compile an error map over the life of the API.
     *
     * @throws \Exception
     */
    public function compile(): void
    {
        parent::compile();

        ksort($this->error_map);

        foreach ($this->error_map as $version => $groups) {
            foreach ($groups as $group => $resources) {
                foreach ($resources as $identifier => $errors) {
                    usort($this->error_map[$version][$group][$identifier], function (array $a, array $b): int {
                        // If the error codes match, then fallback to sorting by the path.
                        if ($a['error_code'] == $b['error_code']) {
                            // If the paths match, then fallback to sorting by their methods.
                            if ($a['path'] == $b['path']) {
                                return ($a['method'] < $b['method']) ? -1 : 1;
                            }

                            return ($a['path'] < $b['path']) ? -1 : 1;
                        }

                        return ($a['error_code'] < $b['error_code']) ? -1 : 1;
                    });
                }

                ksort($this->error_map[$version][$group]);
            }
        }
    }

    /**
     * {{@inheritdoc}}
     */
    protected function transposeAction(
        string $version,
        string $group,
        string $identifier,
        Action\Documentation $action
    ): void {
        // Groups can have children via the `\` delimiter, but for the error map we only care about the top-level group.
        if (strpos($group, '\\') != false) {
            $parts = explode('\\', $group);
            $group = array_shift($parts);
        }

        /** @var ReturnAnnotation|ErrorAnnotation $response */
        foreach ($action->getResponses() as $response) {
            if (!$response instanceof ErrorAnnotation) {
                continue;
            }

            $error_code = $response->getErrorCode();
            if (empty($error_code)) {
                continue;
            }

            $path = $action->getPath();
            $this->error_map[$version][$group][$error_code][] = [
                'path' => $path->getCleanPath(),
                'method' => $action->getMethod(),
                'http_code' => $response->getHttpCode(),
                'error_code' => $error_code,
                'description' => $response->getDescription()
            ];
        }
    }

    /**
     * @return array
     */
    public function getCompiled(): array
    {
        if (empty($this->error_map)) {
            $this->compile();
        }

        return $this->error_map;
    }

    /**
     * Take compiled API documentation and convert it into a Markdown-based changelog over the life of the API.
     *
     * @return array
     * @throws \Exception
     */
    public function toMarkdown(): array
    {
        $markdown = new Markdown($this->application, $this->version);
        $markdown->setLoadPrivateDocs($this->load_private_docs);
        $markdown->setLoadVendorTagDocs($this->load_vendor_tag_docs);

        return $markdown->getCompiled();
    }
}


text:
<!--
@WIN-DENY:EVENT_OBJECT_FOCUS*
@UIA-WIN-DENY:AutomationFocusChanged*
-->
<!DOCTYPE html>
<input id="step" type="range" min="0" max="10" value="4" step="4">
<script>
  var go_passes = [
    () => document.querySelector('#step').setAttribute('step', 2),
    () => document.querySelector('#step').removeAttribute('step'),
    // This |step| value should also trigger a property changed event
    // for UIA_RangeValueValuePropertyId
    () => document.querySelector('#step').setAttribute('step', 3),
  ];

  var current_pass = 0;
  function go() {
    go_passes[current_pass++].call();
    return current_pass < go_passes.length;
  }
</script>


text:
package com.intellij.lang.ant.config.actions;

import com.intellij.icons.AllIcons;
import com.intellij.lang.ant.AntBundle;
import com.intellij.lang.ant.config.AntBuildListener;
import com.intellij.lang.ant.config.execution.AntBuildMessageView;
import com.intellij.lang.ant.config.execution.ExecutionHandler;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import org.jetbrains.annotations.NotNull;

public final class RunAction extends AnAction {
  private final AntBuildMessageView myAntBuildMessageView;

  public RunAction(AntBuildMessageView antBuildMessageView) {
    super(AntBundle.message("rerun.ant.action.name"), null, AllIcons.Actions.Rerun);
    myAntBuildMessageView = antBuildMessageView;
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    ExecutionHandler.runBuild(
      myAntBuildMessageView.getBuildFile(),
      myAntBuildMessageView.getTargets(),
      myAntBuildMessageView,
      e.getDataContext(), myAntBuildMessageView.getAdditionalProperties(), AntBuildListener.NULL);
  }

  @Override
  public void update(@NotNull AnActionEvent event){
    Presentation presentation = event.getPresentation();
    presentation.setEnabled(myAntBuildMessageView.isStopped());
  }
}


text:
from __future__ import absolute_import, unicode_literals

from oauthlib.common import unicode_type
from oauthlib.oauth1.rfc5849.signature import (collect_parameters,
                                               construct_base_string,
                                               normalize_base_string_uri,
                                               normalize_parameters,
                                               sign_hmac_sha1,
                                               sign_hmac_sha1_with_client,
                                               sign_plaintext,
                                               sign_plaintext_with_client,
                                               sign_rsa_sha1,
                                               sign_rsa_sha1_with_client)

from ...unittest import TestCase

try:
    from urllib import quote
except ImportError:
    from urllib.parse import quote

class SignatureTests(TestCase):
    class MockClient(dict):
        def __getattr__(self, name):
            return self[name]

        def __setattr__(self, name, value):
            self[name] = value

        def decode(self):
            for k, v in self.items():
                self[k] = v.decode('utf-8')

    uri_query = "b5=%3D%253D&a3=a&c%40=&a2=r%20b&c2=&a3=2+q"
    authorization_header = """OAuth realm="Example",
    oauth_consumer_key="9djdj82h48djs9d2",
    oauth_token="kkk9d7dh3k39sjv7",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="137131201",
    oauth_nonce="7d8f3e4a",
    oauth_signature="djosJKDKJSD8743243%2Fjdk33klY%3D" """.strip()
    body = "content=This+is+being+the+body+of+things"
    http_method = b"post"
    base_string_url = quote("http://example.com/request?b5=%3D%253D"
                            "&a3=a&c%40=&a2=r%20b").encode('utf-8')
    normalized_encoded_request_parameters = quote(
        'OAuth realm="Example",'
        'oauth_consumer_key="9djdj82h48djs9d2",'
        'oauth_token="kkk9d7dh3k39sjv7",'
        'oauth_signature_method="HMAC-SHA1",'
        'oauth_timestamp="137131201",'
        'oauth_nonce="7d8f3e4a",'
        'oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"'
    ).encode('utf-8')
    client_secret = b"ECrDNoq1VYzzzzzzzzzyAK7TwZNtPnkqatqZZZZ"
    resource_owner_secret = b"just-a-string    asdasd"
    control_base_string = (
        "POST&http%253A%2F%2Fexample.com%2Frequest%253F"
        "b5%253D%25253D%2525253D%2526"
        "a3%253D"
        "a%2526"
        "c%252540%253D%2526"
        "a2%253D"
        "r%252520b&"
        "OAuth%2520realm%253D%2522Example%2522%252C"
        "oauth_consumer_key%253D%25229djdj82h48djs9d2%2522%252C"
        "oauth_token%253D%2522kkk9d7dh3k39sjv7%2522%252C"
        "oauth_signature_method%253D%2522HMAC-SHA1%2522%252C"
        "oauth_timestamp%253D%2522137131201%2522%252C"
        "oauth_nonce%253D%25227d8f3e4a%2522%252C"
        "oauth_signature%253D%2522bYT5CMsGcbgUdFHObYMEfcx6bsw%25253D%2522")

    def setUp(self):
        self.client = self.MockClient(
            client_secret = self.client_secret,
            resource_owner_secret = self.resource_owner_secret
        )

    def test_construct_base_string(self):
        """
        Example text to be turned into a base string::

            POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.1
            Host: example.com
            Content-Type: application/x-www-form-urlencoded
            Authorization: OAuth realm="Example",
                           oauth_consumer_key="9djdj82h48djs9d2",
                           oauth_token="kkk9d7dh3k39sjv7",
                           oauth_signature_method="HMAC-SHA1",
                           oauth_timestamp="137131201",
                           oauth_nonce="7d8f3e4a",
                           oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"

        Sample Base string generated and tested against::

            POST&http%253A%2F%2Fexample.com%2Frequest%253Fb5%253D%25253D%252525
            3D%2526a3%253Da%2526c%252540%253D%2526a2%253Dr%252520b&OAuth%2520re
            alm%253D%2522Example%2522%252Coauth_consumer_key%253D%25229djdj82h4
            8djs9d2%2522%252Coauth_token%253D%2522kkk9d7dh3k39sjv7%2522%252Coau
            th_signature_method%253D%2522HMAC-SHA1%2522%252Coauth_timestamp%253
            D%2522137131201%2522%252Coauth_nonce%253D%25227d8f3e4a%2522%252Coau
            th_signature%253D%2522bYT5CMsGcbgUdFHObYMEfcx6bsw%25253D%2522
        """
        self.assertRaises(ValueError, construct_base_string,
                          self.http_method,
                          self.base_string_url,
                          self.normalized_encoded_request_parameters)
        self.assertRaises(ValueError, construct_base_string,
                          self.http_method.decode('utf-8'),
                          self.base_string_url,
                          self.normalized_encoded_request_parameters)
        self.assertRaises(ValueError, construct_base_string,
                          self.http_method.decode('utf-8'),
                          self.base_string_url.decode('utf-8'),
                          self.normalized_encoded_request_parameters)

        base_string = construct_base_string(
            self.http_method.decode('utf-8'),
            self.base_string_url.decode('utf-8'),
            self.normalized_encoded_request_parameters.decode('utf-8')
        )

        self.assertEqual(self.control_base_string, base_string)

    def test_normalize_base_string_uri(self):
        """
        Example text to be turned into a normalized base string uri::

            GET /?q=1 HTTP/1.1
            Host: www.example.net:8080

        Sample string generated::

            https://www.example.net:8080/
        """

        # test for unicode failure
        uri = b"www.example.com:8080"
        self.assertRaises(ValueError, normalize_base_string_uri, uri)

        # test for missing scheme
        uri = "www.example.com:8080"
        self.assertRaises(ValueError, normalize_base_string_uri, uri)

        # test a URI with the default port
        uri = "http://www.example.com:80/"
        self.assertEqual(normalize_base_string_uri(uri),
                         "http://www.example.com/")

        # test a URI missing a path
        uri = "http://www.example.com"
        self.assertEqual(normalize_base_string_uri(uri),
                         "http://www.example.com/")

        # test a relative URI
        uri = "/a-host-relative-uri"
        host = "www.example.com"
        self.assertRaises(ValueError, normalize_base_string_uri, (uri, host))

        # test overriding the URI's netloc with a host argument
        uri = "http://www.example.com/a-path"
        host = "alternatehost.example.com"
        self.assertEqual(normalize_base_string_uri(uri, host),
                         "http://alternatehost.example.com/a-path")

    def test_collect_parameters(self):
        """We check against parameters multiple times in case things change
        after more parameters are added.
        """
        self.assertEqual(collect_parameters(), [])

        # Check against uri_query
        parameters = collect_parameters(uri_query=self.uri_query)
        correct_parameters = [('b5', '=%3D'),
                              ('a3', 'a'),
                              ('c@', ''),
                              ('a2', 'r b'),
                              ('c2', ''),
                              ('a3', '2 q')]
        self.assertEqual(sorted(parameters), sorted(correct_parameters))

        headers = {'Authorization': self.authorization_header}
        # check against authorization header as well
        parameters = collect_parameters(
            uri_query=self.uri_query, headers=headers)
        parameters_with_realm = collect_parameters(
            uri_query=self.uri_query, headers=headers, with_realm=True)
        # Redo the checks against all the parameters. Duplicated code but
        # better safety
        correct_parameters += [
            ('oauth_nonce', '7d8f3e4a'),
            ('oauth_timestamp', '137131201'),
            ('oauth_consumer_key', '9djdj82h48djs9d2'),
            ('oauth_signature_method', 'HMAC-SHA1'),
            ('oauth_token', 'kkk9d7dh3k39sjv7')]
        correct_parameters_with_realm = (
            correct_parameters + [('realm', 'Example')])
        self.assertEqual(sorted(parameters), sorted(correct_parameters))
        self.assertEqual(sorted(parameters_with_realm),
                         sorted(correct_parameters_with_realm))

        # Add in the body.
        # TODO: Add more content for the body. Daniel Greenfeld 2012/03/12
        # Redo again the checks against all the parameters. Duplicated code
        # but better safety
        parameters = collect_parameters(
            uri_query=self.uri_query, body=self.body, headers=headers)
        correct_parameters += [
            ('content', 'This is being the body of things')]
        self.assertEqual(sorted(parameters), sorted(correct_parameters))

    def test_normalize_parameters(self):
        """ We copy some of the variables from the test method above."""

        headers = {'Authorization': self.authorization_header}
        parameters = collect_parameters(
            uri_query=self.uri_query, body=self.body, headers=headers)
        normalized = normalize_parameters(parameters)

        # Unicode everywhere and always
        self.assertIsInstance(normalized, unicode_type)

        # Lets see if things are in order
        # check to see that querystring keys come in alphanumeric order:
        querystring_keys = ['a2', 'a3', 'b5', 'content', 'oauth_consumer_key',
                            'oauth_nonce', 'oauth_signature_method',
                            'oauth_timestamp', 'oauth_token']
        index = -1  # start at -1 because the 'a2' key starts at index 0
        for key in querystring_keys:
            self.assertGreater(normalized.index(key), index)
            index = normalized.index(key)

    # Control signature created using openssl:
    # echo -n $(cat <message>) | openssl dgst -binary -hmac <key> | base64
    control_signature = "Uau4O9Kpd2k6rvh7UZN/RN+RG7Y="

    def test_sign_hmac_sha1(self):
        """Verifying HMAC-SHA1 signature against one created by OpenSSL."""

        self.assertRaises(ValueError, sign_hmac_sha1, self.control_base_string,
                          self.client_secret, self.resource_owner_secret)

        sign = sign_hmac_sha1(self.control_base_string,
                              self.client_secret.decode('utf-8'),
                              self.resource_owner_secret.decode('utf-8'))
        self.assertEqual(len(sign), 28)
        self.assertEqual(sign, self.control_signature)

    def test_sign_hmac_sha1_with_client(self):
        self.assertRaises(ValueError,
            sign_hmac_sha1_with_client,
            self.control_base_string,
            self.client)

        self.client.decode()
        sign = sign_hmac_sha1_with_client(
            self.control_base_string, self.client)

        self.assertEqual(len(sign), 28)
        self.assertEqual(sign, self.control_signature)

    control_base_string_rsa_sha1 = (
        b"POST&http%253A%2F%2Fexample.com%2Frequest%253Fb5%253D"
        b"%25253D%2525253D%2526a3%253Da%2526c%252540%253D%2526"
        b"a2%253Dr%252520b&OAuth%2520realm%253D%2522Example%25"
        b"22%252Coauth_consumer_key%253D%25229djdj82h48djs9d2"
        b"%2522%252Coauth_token%253D%2522kkk9d7dh3k39sjv7%2522"
        b"%252Coauth_signature_method%253D%2522HMAC-SHA1%2522"
        b"%252Coauth_timestamp%253D%2522137131201%2522%252Coau"
        b"th_nonce%253D%25227d8f3e4a%2522%252Coauth_signature"
        b"%253D%2522bYT5CMsGcbgUdFHObYMEfcx6bsw%25253D%2522")

    # Generated using: $ openssl genrsa -out <key>.pem 1024
    # PEM encoding requires the key to be concatenated with
    # linebreaks.
    rsa_private_key = b"""-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDk1/bxyS8Q8jiheHeYYp/4rEKJopeQRRKKpZI4s5i+UPwVpupG
AlwXWfzXwSMaKPAoKJNdu7tqKRniqst5uoHXw98gj0x7zamu0Ck1LtQ4c7pFMVah
5IYGhBi2E9ycNS329W27nJPWNCbESTu7snVlG8V8mfvGGg3xNjTMO7IdrwIDAQAB
AoGBAOQ2KuH8S5+OrsL4K+wfjoCi6MfxCUyqVU9GxocdM1m30WyWRFMEz2nKJ8fR
p3vTD4w8yplTOhcoXdQZl0kRoaDzrcYkm2VvJtQRrX7dKFT8dR8D/Tr7dNQLOXfC
DY6xveQczE7qt7Vk7lp4FqmxBsaaEuokt78pOOjywZoInjZhAkEA9wz3zoZNT0/i
rf6qv2qTIeieUB035N3dyw6f1BGSWYaXSuerDCD/J1qZbAPKKhyHZbVawFt3UMhe
542UftBaxQJBAO0iJy1I8GQjGnS7B3yvyH3CcLYGy296+XO/2xKp/d/ty1OIeovx
C60pLNwuFNF3z9d2GVQAdoQ89hUkOtjZLeMCQQD0JO6oPHUeUjYT+T7ImAv7UKVT
Suy30sKjLzqoGw1kR+wv7C5PeDRvscs4wa4CW9s6mjSrMDkDrmCLuJDtmf55AkEA
kmaMg2PNrjUR51F0zOEFycaaqXbGcFwe1/xx9zLmHzMDXd4bsnwt9kk+fe0hQzVS
JzatanQit3+feev1PN3QewJAWv4RZeavEUhKv+kLe95Yd0su7lTLVduVgh4v5yLT
Ga6FHdjGPcfajt+nrpB1n8UQBEH9ZxniokR/IPvdMlxqXA==
-----END RSA PRIVATE KEY-----
"""
    @property
    def control_signature_rsa_sha1(self):
        # Base string saved in "<message>". Signature obtained using:
        # $ echo -n $(cat <message>) | openssl dgst -sign <key>.pem | base64
        # where echo -n suppresses the last linebreak.
        return (
            "zV5g8ArdMuJuOXlH8XOqfLHS11XdthfIn4HReDm7jz8JmgLabHGmVBqCkCfZoFJPH"
            "dka7tLvCplK/jsV4FUOnftrJOQhbXguuBdi87/hmxOFKLmQYqqlEW7BdXmwKLZcki"
            "qq3qE5XziBgKSAFRkxJ4gmJAymvJBtrJYN9728rK8="
        )

    def test_sign_rsa_sha1(self):
        """Verify RSA-SHA1 signature against one created by OpenSSL."""
        base_string = self.control_base_string_rsa_sha1

        private_key = self.rsa_private_key

        control_signature = self.control_signature_rsa_sha1

        sign = sign_rsa_sha1(base_string, private_key)
        self.assertEqual(sign, control_signature)
        sign = sign_rsa_sha1(base_string.decode('utf-8'), private_key)
        self.assertEqual(sign, control_signature)

    def test_sign_rsa_sha1_with_client(self):
        base_string = self.control_base_string_rsa_sha1

        self.client.rsa_key = self.rsa_private_key

        control_signature = self.control_signature_rsa_sha1

        sign = sign_rsa_sha1_with_client(base_string, self.client)

        self.assertEqual(sign, control_signature)

        self.client.decode() ## Decode `rsa_private_key` from UTF-8

        sign = sign_rsa_sha1_with_client(base_string, self.client)

        self.assertEqual(sign, control_signature)

    control_signature_plaintext = (
        "ECrDNoq1VYzzzzzzzzzyAK7TwZNtPnkqatqZZZZ&"
        "just-a-string%20%20%20%20asdasd")

    def test_sign_plaintext(self):
        """ """

        self.assertRaises(ValueError, sign_plaintext, self.client_secret,
                          self.resource_owner_secret)
        sign = sign_plaintext(self.client_secret.decode('utf-8'),
                              self.resource_owner_secret.decode('utf-8'))
        self.assertEqual(sign, self.control_signature_plaintext)

    def test_sign_plaintext_with_client(self):
        self.assertRaises(ValueError, sign_plaintext_with_client,
                          None, self.client)

        self.client.decode()

        sign = sign_plaintext_with_client(None, self.client)

        self.assertEqual(sign, self.control_signature_plaintext)


text:
import React from 'react';
import ReactDOM from 'react-dom';
import ControlPanel from './views/ControlPanel';
import './index.css';

import store from './Store.js';
import Provider from './Provider.js';

ReactDOM.render(
  <Provider store={store}>
    <ControlPanel />
  </Provider>,
  document.getElementById('root')
);


text: - [Setup at CoreOS](coreos.md)


text:
package foodtruck.model;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import org.joda.time.DateTime;

/**
 * @author aviolette
 * @since 9/16/16
 */
public class AlexaExchange extends ModelEntity {
  private ImmutableMap<String, String> slots;
  private String intentName;
  private boolean sessionEnded;
  private DateTime requestTime;
  private DateTime completeTime;
  private boolean hadReprompt;
  private boolean hadCard;

  private AlexaExchange(Builder builder) {
    super(builder.key);
    this.slots = builder.slots;
    this.intentName = builder.intentName;
    this.sessionEnded = builder.sessionEnded;
    this.requestTime = builder.requestTime;
    this.completeTime = builder.completeTime;
    this.hadCard = builder.hadCard;
    this.hadReprompt = builder.hadReprompt;
  }

  public static Builder builder() {
    return new Builder();
  }

  public ImmutableMap<String, String> getSlots() {
    return slots;
  }

  public ImmutableList<String> getSlotEntries() {
    return slots.values().asList();
  }

  public String getIntentName() {
    return intentName;
  }

  public boolean isSessionEnded() {
    return sessionEnded;
  }

  public DateTime getRequestTime() {
    return requestTime;
  }

  public DateTime getCompleteTime() {
    return completeTime;
  }

  public boolean getHadCard() {
    return hadCard;
  }

  public boolean getHadReprompt() {
    return hadReprompt;
  }

  public static class Builder {
    private Long key = -1L;
    private String intentName;
    private ImmutableMap<String, String> slots = ImmutableMap.of();
    private boolean sessionEnded;
    private DateTime requestTime;
    private DateTime completeTime;
    private boolean hadReprompt;
    private boolean hadCard;

    public Builder() {
    }

    public Builder(AlexaExchange exchange) {
      this.key = (Long) exchange.key;
      this.intentName = exchange.intentName;
      this.slots = exchange.slots;
      this.sessionEnded = exchange.sessionEnded;
      this.completeTime = exchange.completeTime;
    }

    public Builder key(long key) {
      this.key = key;
      return this;
    }

    public Builder slots(ImmutableMap<String, String> slots) {
      this.slots = slots;
      return this;
    }

    public Builder sessionEnded(boolean sessionEnded) {
      this.sessionEnded = sessionEnded;
      return this;
    }

    public Builder requestTime(DateTime requestTime) {
      this.requestTime = requestTime;
      return this;
    }

    public Builder intentName(String intentName) {
      this.intentName = intentName;
      return this;
    }

    public Builder completeTime(DateTime completeTime) {
      this.completeTime = completeTime;
      return this;
    }

    public AlexaExchange build() {
      return new AlexaExchange(this);
    }

    public Builder requested(DateTime requested) {
      this.requestTime = requested;
      return this;
    }

    public Builder hadCard(boolean hadCard) {
      this.hadCard = hadCard;
      return this;
    }

    public Builder hadReprompt(boolean hadReprompt) {
      this.hadReprompt = hadReprompt;
      return this;
    }
  }
}


text:
import ingress, { IngressApp, Context } from './app'
import { Route } from './router/router'
import {
  Ingress,
  ListenOptions,
  Addon,
  Usable,
  SetupTeardown,
  AppState,
  usableForwardRef,
} from './ingress'

export default ingress
export { IngressApp, Route, Ingress, Context, AppState }
export { ListenOptions, Addon, Usable, SetupTeardown, usableForwardRef }
export { StatusCode } from '@ingress/http-status'

//Supporting Symbols
export { BaseContext, DefaultContext, BaseAuthContext, Request, Response, Type } from './context'

export { Authenticate } from './annotations/authenticate'
export { fromConnect } from './annotations/from-connect'
export { AfterRequest } from './annotations/after-request'

export { compose } from 'app-builder'

//SOMEDAY: alias this
export { createAnnotationFactory } from 'reflect-annotations'

export * from './websocket/namespace'
export * from './websocket/upgrade'
export * from './websocket/backchannel'

export {
  PathFactory,
  Handler,
  Body,
  Header,
  Parse,
  Path,
  Query,
  ParseOptions,
  ParseAnnotation,
  HeaderParamAnnotation,
  UpgradeRouteAnnotation,
  Upgrade,
  RouteParamAnnotation,
  TypeConverter,
  PredicateTypeConverter,
  ExactTypeConverter,
  ParamAnnotation,
  RouteMetadata,
} from './router/router'


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.taverna.commandline.options (Apache Taverna Command-line Tool 3.1.0-incubating API)</title>
<meta name="date" content="2016-06-30">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.taverna.commandline.options

Interfaces

CommandLineOptions


text:
<?php // Settings to display in a form for a user to configure.

$default_name = NULL;
if ( 'add' == $mode ) {
	$default_name = 'My Local';
}
$settings_form->add_setting( array(
	'type'		=>		'text',
	'name'		=>		'title',
	'title'		=>		__( 'Destination name', 'it-l10n-backupbuddy' ),
	'tip'		=>		__( 'Name of the new destination to create. This is for your convenience only.', 'it-l10n-backupbuddy' ),
	'rules'		=>		'required|string[1-45]',
	'default'	=>		$default_name,
) );

if ( pb_backupbuddy::_GET('add') != '' ) { // set default only when adding.
	$default_path = ABSPATH;
} else {
	$default_path = '';
}
$settings_form->add_setting( array(
	'type'		=>		'text',
	'name'		=>		'path',
	'title'		=>		__( 'Local file path', 'it-l10n-backupbuddy' ),
	'tip'		=>		__( 'Provide the full path to the location\'s directory. This must map to the web location for the destination URL.', 'it-l10n-backupbuddy' ),
	'default'	=>		$default_path,
	'css'		=>		'width: 100%;',
	'rules'		=>		'required|string[1-100]',
) );

if ( pb_backupbuddy::_GET('add') != '' ) { // set default only when adding.
	$default_url = rtrim( site_url(), '/\\' ) . '/';
} else {
	$default_url = '';
}
$settings_form->add_setting( array(
	'type'		=>		'text',
	'name'		=>		'url',
	'title'		=>		__( 'Migration URL', 'it-l10n-backupbuddy' ) . '
Optional, for migrations',
	'tip'		=>		__( 'Enter the URL corresponding to the local destination path. This URL must lead to the location where files uploaded to this remote destination would end up. If the destination is in a subdirectory make sure to match it in the corresponding URL.', 'it-l10n-backupbuddy' ),
	'css'		=>		'width: 100%;',
	'default'	=>		$default_url,
	'classes'	=>		'migration_url',
	'rules'		=>		'string[0-100]',
) );

$settings_form->add_setting( array(
	'type'		=>		'text',
	'name'		=>		'archive_limit',
	'title'		=>		__( 'Archive limit', 'it-l10n-backupbuddy' ),
	'tip'		=>		__( '[Example: 5] - Enter 0 for no limit. This is the maximum number of archives to be stored in this specific destination. If this limit is met the oldest backups will be deleted.', 'it-l10n-backupbuddy' ),
	'rules'		=>		'required|int[0-9999999]',
	'css'		=>		'width: 50px;',
	'after'		=>		' backups',
) );


text:
/*
 * File:   errorcodes.h
 * Author: Arvid
 *
 * Created on April 13, 2012, 9:09 AM
 */

#ifndef ERRORCODES_H
#define ERRORCODES_H

#ifdef	__cplusplus
extern "C" {
#endif

/**
* This static variable holds an error code if the return value from connect is false.
* This variable is always set to 0 in the beginning of the connect sequence.
* The returned code can be used to inform the user of the detailed connect error.
* The value can hold one of the defined error codes below OR an error according to errno
*/

extern int connectErrorCode;

#define ERRORSTART 10000
#define PREECONNECTERROR ERRORSTART + 1
#define UNDEFINEDCONNECTERROR ERRORSTART + 2
#define POSTCONNECTERROR ERRORSTART + 3
#define DNSERROR ERRORSTART + 4      /* general DNS ERROR */
#define DNSNAMENOTFOUND ERRORSTART + 5 /* EAI_NONAME */
#define CONNECTERROR ERRORSTART + 6  /* a connect error if errno is not define during tcp connect */
#define MCSCONNECTINITIALERROR ERRORSTART + 7
#define TLSCONNECTERROR ERRORSTART + 8
#define AUTHENTICATIONERROR ERRORSTART + 9

#ifdef	__cplusplus
}
#endif

#endif	/* ERRORCODES_H */


text:
package dhcpv6

// This module defines the OptRelayMsg structure.
// https://www.ietf.org/rfc/rfc3315.txt

import (
	"fmt"
)

type OptRelayMsg struct {
	relayMessage DHCPv6
}

func (op *OptRelayMsg) Code() OptionCode {
	return OptionRelayMsg
}

func (op *OptRelayMsg) ToBytes() []byte {
	return op.relayMessage.ToBytes()
}

func (op *OptRelayMsg) RelayMessage() DHCPv6 {
	return op.relayMessage
}

func (op *OptRelayMsg) SetRelayMessage(relayMessage DHCPv6) {
	op.relayMessage = relayMessage
}

func (op *OptRelayMsg) String() string {
	return fmt.Sprintf("OptRelayMsg{relaymsg=%v}", op.relayMessage)
}

// build an OptRelayMsg structure from a sequence of bytes.
// The input data does not include option code and length bytes.
func ParseOptRelayMsg(data []byte) (*OptRelayMsg, error) {
	var err error
	var opt OptRelayMsg
	opt.relayMessage, err = FromBytes(data)
	if err != nil {
		return nil, err
	}
	return &opt, nil
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Reactive;
using Xunit;

namespace Octokit.Tests.Reactive
{
    public class ObservableAssigneesClientTests
    {
        private const string owner = "owner";
        private const string name = "name";
        private const string assignee = "assignee";
        private const long repositoryId = 1;

        public class TheGetAllMethod
        {
            private readonly Uri _expectedUri;
            private readonly Uri _expectedUriWithRepositoryId;

            public TheGetAllMethod()
            {
                var uri = string.Format("repos/{0}/{1}/assignees", owner, name);
                var uriWithRepositoryId = string.Format("repositories/{0}/assignees", repositoryId);

                _expectedUri = new Uri(uri, UriKind.Relative);
                _expectedUriWithRepositoryId = new Uri(uriWithRepositoryId, UriKind.Relative);
            }

            [Fact]
            public void RequestsCorrectUrl()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                client.GetAllForRepository(owner, name);

                gitHubClient.Connection.Received(1).Get<List<User>>(_expectedUri,
                    Arg.Is<Dictionary<string, string>>(dictionary => dictionary.Count == 0), null);
            }

            [Fact]
            public void RequestsCorrectUrlWithRepositoryId()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                client.GetAllForRepository(repositoryId);

                gitHubClient.Connection.Received(1).Get<List<User>>(_expectedUriWithRepositoryId,
                    Arg.Is<Dictionary<string, string>>(dictionary => dictionary.Count == 0), null);
            }

            [Fact]
            public void RequestsCorrectUrlWithApiOption()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                var options = new ApiOptions
                {
                    PageSize = 1,
                    StartPage = 1,
                    PageCount = 1
                };
                client.GetAllForRepository(owner, name, new ApiOptions { PageSize = 1, StartPage = 1 });
                client.GetAllForRepository(owner, name, options);

                gitHubClient.Connection.Received(2).Get<List<User>>(_expectedUri,
                    Arg.Is<Dictionary<string, string>>(dictionary => dictionary.Count == 2), null);
            }

            [Fact]
            public void RequestsCorrectUrlWithRepositoryIdWithApiOption()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                var options = new ApiOptions
                {
                    PageSize = 1,
                    StartPage = 1,
                    PageCount = 1
                };

                client.GetAllForRepository(repositoryId, options);

                gitHubClient.Connection.Received(1).Get<List<User>>(_expectedUriWithRepositoryId,
                    Arg.Is<Dictionary<string, string>>(dictionary => dictionary.Count == 2), null);
            }

            [Fact]
            public async Task EnsuresNonNullArguments()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(null, name));
                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(owner, null));
                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(owner, name, null));

                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(1, null));

                Assert.Throws<ArgumentException>(() => client.GetAllForRepository(string.Empty, name));
                Assert.Throws<ArgumentException>(() => client.GetAllForRepository(owner, string.Empty));
            }
        }

        public class TheCheckAssigneeMethod
        {
            [Fact]
            public void CallsCheckAssigneeOnClient()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                client.CheckAssignee(owner, name, assignee);

                gitHubClient.Issue.Assignee.Received(1).CheckAssignee(owner, name, assignee);
            }

            [Fact]
            public void CallsCheckAssigneeOnClientWithRepositoryId()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                client.CheckAssignee(repositoryId, assignee);

                gitHubClient.Issue.Assignee.Received(1).CheckAssignee(repositoryId, assignee);
            }

            [Fact]
            public void EnsuresNonNullArguments()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(null, name, assignee));
                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(owner, null, assignee));
                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(owner, name, null));

                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(1, null));

                Assert.Throws<ArgumentException>(() => client.CheckAssignee(string.Empty, name, assignee));
                Assert.Throws<ArgumentException>(() => client.CheckAssignee(owner, string.Empty, assignee));
                Assert.Throws<ArgumentException>(() => client.CheckAssignee(owner, name, string.Empty));

                Assert.Throws<ArgumentException>(() => client.CheckAssignee(1, string.Empty));
            }
        }

        public class TheAddAssigneesMethod
        {
            [Fact]
            public void RequestsCorrectUrl()
            {
                var newAssignees = new AssigneesUpdate(new List<string>() { "assignee1", "assignee2" });
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                client.AddAssignees("fake", "repo", 2, newAssignees);

                gitHubClient.Issue.Assignee.Received().AddAssignees("fake", "repo", 2, newAssignees);
            }

            [Fact]
            public void EnsuresNonNullArguments()
            {
                var githubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(githubClient);
                var newAssignees = new AssigneesUpdate(new List<string>() { "assignee1", "assignee2" });

                Assert.Throws<ArgumentNullException>(() => client.AddAssignees(null, "name", 2, newAssignees));
                Assert.Throws<ArgumentNullException>(() => client.AddAssignees("name", null, 2, newAssignees));
                Assert.Throws<ArgumentNullException>(() => client.AddAssignees("owner", "name", 2, null));

                Assert.Throws<ArgumentException>(() => client.AddAssignees("owner", "", 2, newAssignees));
                Assert.Throws<ArgumentException>(() => client.AddAssignees("", "name", 2, newAssignees));
            }
        }

        public class TheRemoveAssigneesMethod
        {
            [Fact]
            public void RequestsCorrectUrl()
            {
                var newAssignees = new AssigneesUpdate(new List<string>() { "assignee1", "assignee2" });
                var gitHubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(gitHubClient);

                client.RemoveAssignees("fake", "repo", 2, newAssignees);

                gitHubClient.Issue.Assignee.Received().RemoveAssignees("fake", "repo", 2, newAssignees);
            }

            [Fact]
            public void EnsuresNonNullArguments()
            {
                var githubClient = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(githubClient);
                var newAssignees = new AssigneesUpdate(new List<string>() { "assignee1", "assignee2" });

                Assert.Throws<ArgumentNullException>(() => client.RemoveAssignees(null, "name", 2, newAssignees));
                Assert.Throws<ArgumentNullException>(() => client.RemoveAssignees("owner", null, 2, newAssignees));
                Assert.Throws<ArgumentNullException>(() => client.RemoveAssignees("owner", "name", 2, null));

                Assert.Throws<ArgumentException>(() => client.RemoveAssignees("owner", "", 2, newAssignees));
                Assert.Throws<ArgumentException>(() => client.RemoveAssignees("", "name", 2, newAssignees));
            }
        }

        public class TheCtor
        {
            [Fact]
            public void EnsuresNonNullArguments()
            {
                Assert.Throws<ArgumentNullException>(
                () => new ObservableAssigneesClient(null));
            }
        }
    }
}


text:
import os
import shutil
import subprocess
import sys

import pytest

import pyarrow as pa

here = os.path.dirname(os.path.abspath(__file__))

setup_template = """if 1:
    from distutils.core import setup
    from Cython.Build import cythonize

    import numpy as np

    import pyarrow as pa

    ext_modules = cythonize({pyx_file!r})
    compiler_opts = {compiler_opts!r}
    custom_ld_path = {test_ld_path!r}

    for ext in ext_modules:
        # XXX required for numpy/numpyconfig.h,
        # included from arrow/python/api.h
        ext.include_dirs.append(np.get_include())
        ext.include_dirs.append(pa.get_include())
        ext.libraries.extend(pa.get_libraries())
        ext.library_dirs.extend(pa.get_library_dirs())
        if custom_ld_path:
            ext.library_dirs.append(custom_ld_path)
        ext.extra_compile_args.extend(compiler_opts)

    setup(
        ext_modules=ext_modules,
    )
"""

@pytest.mark.skipif(
    'ARROW_HOME' not in os.environ,
    reason='ARROW_HOME environment variable not defined')
def test_cython_api(tmpdir):
    """
    Basic test for the Cython API.
    """
    pytest.importorskip('Cython')

    ld_path_default = os.path.join(os.environ['ARROW_HOME'], 'lib')

    test_ld_path = os.environ.get('PYARROW_TEST_LD_PATH', ld_path_default)

    with tmpdir.as_cwd():
        # Set up temporary workspace
        pyx_file = 'pyarrow_cython_example.pyx'
        shutil.copyfile(os.path.join(here, pyx_file),
                        os.path.join(str(tmpdir), pyx_file))
        # Create setup.py file
        if os.name == 'posix':
            compiler_opts = ['-std=c++11']
        else:
            compiler_opts = []
        setup_code = setup_template.format(pyx_file=pyx_file,
                                           compiler_opts=compiler_opts,
                                           test_ld_path=test_ld_path)
        with open('setup.py', 'w') as f:
            f.write(setup_code)

        # Compile extension module
        subprocess.check_call([sys.executable, 'setup.py',
                               'build_ext', '--inplace'])

        # Check basic functionality
        orig_path = sys.path[:]
        sys.path.insert(0, str(tmpdir))
        try:
            mod = __import__('pyarrow_cython_example')
            arr = pa.array([1, 2, 3])
            assert mod.get_array_length(arr) == 3
            with pytest.raises(TypeError, match="not an array"):
                mod.get_array_length(None)
        finally:
            sys.path = orig_path


text:
<!doctype html>

  <title>audio events - canplay, then canplaythrough</title>

spec reference

  <audio id="a" autoplay controls>
  </audio>


text:
> Cloudflare Text Component

## Installation

```sh
$ npm install cf-component-text
```

## Usage

```jsx
import React from 'react';
import Text from 'cf-component-text';

const TextComponent = () => (
  <div>
    <p>Specify a <code>size</code></p>
    <Text size="normal">Hello World</Text>
    <Text size="small">Hello World</Text>

    <p>and/or an <code>align</code></p>
    <Text align="start">Hello World</Text>
    <Text align="center">Hello World</Text>
    <Text align="justify">Hello World</Text>
    <Text align="end">Hello World</Text>

    <p>and/or a <code>type</code></p>
    <Text type="info">Hello World</Text>
    <Text type="success">Hello World</Text>
    <Text type="warning">Hello World</Text>
    <Text type="error">Hello World</Text>
    <Text type="muted">Hello World</Text>

    <p>and/or a <code>case</code></p>
    <Text case="capitalize">hello world</Text>
    <Text case="titlecase">hello world</Text>
    <Text case="lowercase">Hello World</Text>
    <Text case="uppercase">Hello World</Text>
  </div>
);

export default TextComponent;
```


text:
package com.pmc.LoginInfo;

import com.mongodb.*;
import com.mongodb.util.JSON;
import com.pmc.CommonDBManager.CommonDBManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

import java.net.UnknownHostException;
import java.util.List;

/**
 * Created by luluteam on 2015/7/8.
 */
public class LoginInfoService {
    public WriteResult saveLoginInfoByJSON(String JSONStr) throws UnknownHostException {
        // TODO Auto-generated method stub

        DBCollection activityRouteInfoCollection = CommonDBManager.MongoDBConnect("LoginInfo");
        DBObject dbObecjt = (DBObject) JSON.parse(JSONStr);
        WriteResult result =  activityRouteInfoCollection.insert(dbObecjt);

        return result;
    }

    public JSONObject getLoginInfo(String appId) throws Exception {
        DBCollection loginInfoCollcetion = CommonDBManager.MongoDBConnect("LoginInfo");

        DBObject query = new BasicDBObject();
        query.put("appId", appId);
        DBObject result = loginInfoCollcetion.findOne(query);
        String appName = (String)result.get("appName");

        BasicDBObject key = new BasicDBObject();
        key.put("date", true);
        BasicDBObject condition = new BasicDBObject();
        condition.put("appId", appId);
        BasicDBObject initial = new BasicDBObject();
        int count = 0;
        initial.put("value", count);
        String reduceString = "function(obj, prev){prev.value += 1}";
        DBObject dbo = loginInfoCollcetion.group(key, condition, initial, reduceString);
        JSONArray groupList = new JSONArray(dbo.toString());

        JSONArray namesArray = new JSONArray();
        JSONArray valuesArray = new JSONArray();
        for (int i = 0; i < groupList.length(); i++) {
            JSONObject obj = (JSONObject)groupList.get(i);
            namesArray.put(obj.get("date"));
            valuesArray.put(obj.get("value"));
        }
        JSONObject retObject = new JSONObject();
        JSONArray dataArray = new JSONArray();
        JSONObject dataObject = new JSONObject();
        retObject.put("appName", appName);
        dataObject.put("appVersion","ËùÓа汾ÐÅÏ¢");
        dataObject.put("names", namesArray);
        dataObject.put("values",valuesArray);
        dataArray.put(dataObject);
        retObject.put("data", dataArray);
        return retObject;
    }

    @Test
    public void testGetLoginInfo() throws Exception {
        getLoginInfo("85d4a553-ee8d-4136-80ab-2469adcae44d-abcdefg");
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxDolForm');

class BxInvFormCheckerHelper extends BxDolFormCheckerHelper
{
	static public function checkEmails($s)
    {
    	$aEmails = preg_split("/[\s\n,;]+/", $s);
    	foreach($aEmails as $sEmail)
    		if(!empty($sEmail) && !self::checkEmail($sEmail))
    			return false;

        return true;
    }
}

/** @} */


text:
#ifdef TARGET_LPC1768

#include <usb/usb.h>
#include <usb/usbcfg.h>
#include <usb/usbhw.h>
#include <usb/usbcore.h>
#include <usb/cdc.h>
#include <usb/cdcuser.h>
#include <usb/mscuser.h>
#include <CDCSerial.h>
#include <usb/mscuser.h>

#include "../../inc/MarlinConfig.h"
#include "../../core/millis_t.h"

#include "../../sd/cardreader.h"

extern uint32_t MSC_SD_Init(uint8_t pdrv);

extern "C" {
  #include <debug_frmwrk.h>
  extern "C" int isLPC1769();
  extern "C" void disk_timerproc();
}

void SysTick_Callback() { disk_timerproc(); }

TERN_(POSTMORTEM_DEBUGGING, extern void install_min_serial());

void HAL_init() {

  // Init LEDs
  #if PIN_EXISTS(LED)
    SET_DIR_OUTPUT(LED_PIN);
    WRITE_PIN_CLR(LED_PIN);
    #if PIN_EXISTS(LED2)
      SET_DIR_OUTPUT(LED2_PIN);
      WRITE_PIN_CLR(LED2_PIN);
      #if PIN_EXISTS(LED3)
        SET_DIR_OUTPUT(LED3_PIN);
        WRITE_PIN_CLR(LED3_PIN);
        #if PIN_EXISTS(LED4)
          SET_DIR_OUTPUT(LED4_PIN);
          WRITE_PIN_CLR(LED4_PIN);
        #endif
      #endif
    #endif

    // Flash status LED 3 times to indicate Marlin has started booting
    LOOP_L_N(i, 6) {
      TOGGLE(LED_PIN);
      delay(100);
    }
  #endif

  // Init Servo Pins
  #define INIT_SERVO(N) OUT_WRITE(SERVO##N##_PIN, LOW)
  #if HAS_SERVO_0
    INIT_SERVO(0);
  #endif
  #if HAS_SERVO_1
    INIT_SERVO(1);
  #endif
  #if HAS_SERVO_2
    INIT_SERVO(2);
  #endif
  #if HAS_SERVO_3
    INIT_SERVO(3);
  #endif

  //debug_frmwrk_init();
  //_DBG("\n\nDebug running\n");
  // Initialize the SD card chip select pins as soon as possible
  #if PIN_EXISTS(SD_SS)
    OUT_WRITE(SD_SS_PIN, HIGH);
  #endif

  #if PIN_EXISTS(ONBOARD_SD_CS) && ONBOARD_SD_CS_PIN != SD_SS_PIN
    OUT_WRITE(ONBOARD_SD_CS_PIN, HIGH);
  #endif

  #ifdef LPC1768_ENABLE_CLKOUT_12M
   /**
    * CLKOUTCFG register
    * bit 8 (CLKOUT_EN) = enables CLKOUT signal. Disabled for now to prevent glitch when enabling GPIO.
    * bits 7:4 (CLKOUTDIV) = set to 0 for divider setting of /1
    * bits 3:0 (CLKOUTSEL) = set to 1 to select main crystal oscillator as CLKOUT source
    */
    LPC_SC->CLKOUTCFG = (0<<8)|(0<<4)|(1<<0);
    // set P1.27 pin to function 01 (CLKOUT)
    PINSEL_CFG_Type PinCfg;
    PinCfg.Portnum = 1;
    PinCfg.Pinnum = 27;
    PinCfg.Funcnum = 1;    // function 01 (CLKOUT)
    PinCfg.OpenDrain = 0;  // not open drain
    PinCfg.Pinmode = 2;    // no pull-up/pull-down
    PINSEL_ConfigPin(&PinCfg);
    // now set CLKOUT_EN bit
    SBI(LPC_SC->CLKOUTCFG, 8);
  #endif

  USB_Init();                               // USB Initialization
  USB_Connect(false);                       // USB clear connection
  delay(1000);                              // Give OS time to notice
  USB_Connect(true);

  TERN_(HAS_SD_HOST_DRIVE, MSC_SD_Init(0)); // Enable USB SD card access

  const millis_t usb_timeout = millis() + 2000;
  while (!USB_Configuration && PENDING(millis(), usb_timeout)) {
    delay(50);
    HAL_idletask();
    #if PIN_EXISTS(LED)
      TOGGLE(LED_PIN);     // Flash quickly during USB initialization
    #endif
  }

  HAL_timer_init();

  TERN_(POSTMORTEM_DEBUGGING, install_min_serial()); // Install the min serial handler
}

// HAL idle task
void HAL_idletask() {
  #if HAS_SHARED_MEDIA
    // If Marlin is using the SD card we need to lock it to prevent access from
    // a PC via USB.
    // Other HALs use IS_SD_PRINTING() and IS_SD_FILE_OPEN() to check for access but
    // this will not reliably detect delete operations. To be safe we will lock
    // the disk if Marlin has it mounted. Unfortunately there is currently no way
    // to unmount the disk from the LCD menu.
    // if (IS_SD_PRINTING() || IS_SD_FILE_OPEN())
    if (card.isMounted())
      MSC_Aquire_Lock();
    else
      MSC_Release_Lock();
  #endif
  // Perform USB stack housekeeping
  MSC_RunDeferredCommands();
}

#endif // TARGET_LPC1768


text:
import CsError from './csError';

class InboxHasNoScriptError extends CsError {
  constructor() {
    super(['This inbox has no script to retrieve.']);
  }
}

export default InboxHasNoScriptError;


text:
import abc
from pomdpy.pomdp.point import Point

class DiscreteAction(Point):

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

    def __hash__(self):
        return self.bin_number

    def __eq__(self, other_discrete_action):
        return self.bin_number == other_discrete_action.bin_number

    @abc.abstractmethod
    def print_action(self):
        """
        Pretty prints the action type
        :return:
        """

    @abc.abstractmethod
    def to_string(self):
        """
        Returns a String version of the action type
        :return:
        """
    @abc.abstractmethod
    def copy(self):
        """
        Returns a proper copy of the Discrete Action
        :return:
        """


text:
package core;

import game.control.GameControl;
import game.control.ScreenControl;
import game.screens.ComboScreen;
import game.screens.CreditsScreen;
import game.screens.FinishScreen;
import game.screens.HelpScreen;
import game.screens.MenuScreen;
import game.screens.SoulsDecorator;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;

public class Window extends Application {
    public static boolean music = false;

    // make the stage acessible
    private static Scene scene;
    private static boolean newStage = false;

    // class members
    private AnimationTimer gameloop;
    private int passedTicks = 0;
    private double lastNanoTime = System.nanoTime();
    private double time = 0;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        // stage settings
        stage.setTitle(Global.TITLE);
        stage.setResizable(false);
        stage.centerOnScreen();

        // event handling
        stage.setOnCloseRequest(event -> {
            gameloop.stop();
            // save game state here
        });

        stage.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
            Events.addCode(event);
        });

        stage.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
            Events.removeCode(event);
        });

        ScreenControl ctrl = ScreenControl.getCtrl();
        ctrl.setScreen("menu", new SoulsDecorator(MenuScreen.getScreen()));
        ctrl.addScreen("combo", new ComboScreen());
        ctrl.addScreen("credits", new SoulsDecorator(CreditsScreen.getScreen()));
        ctrl.addScreen("help", new SoulsDecorator(new HelpScreen("menu", 2000)));

        ctrl.addScreen("game won", new SoulsDecorator(new FinishScreen(true)));
        ctrl.addScreen("game over", new SoulsDecorator(new FinishScreen(false)));
        // ctrl.addScreen("", );

        // precompute the game initialization
        GameControl.getControl();

        gameloop = new AnimationTimer() {

            @Override
            public void handle(long currentNanoTime) {
                // calculate time since last update.
                time += (currentNanoTime - lastNanoTime) / 1000000000.0;
                lastNanoTime = currentNanoTime;
                passedTicks = (int) Math.floor(time * 60.0);
                time -= passedTicks / 60.0;

                // adjust stage if necessary
                if (Window.newStage) {
                    newStage = false;

                    stage.setScene(scene);
                }

                if (Events.isESC()) {
                    ctrl.setScreen("menu");
                }

                // compute a frame
                ctrl.tick(passedTicks);
                ctrl.render();
            }
        };

        stage.show();
        gameloop.start();
    }

    public static void setScene(Scene scene) {
        Window.newStage = true;
        Window.scene = scene;
    }
}


text:
package it.f2informatica.core.validator;

import it.f2informatica.core.model.ExperienceModel;
import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

@Component
public class ConsultantExperienceValidator extends AbstractValidator {

	@Override
	public boolean supports(Class<?> clazz) {
		return ExperienceModel.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", FIELD_MANDATORY);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "position", FIELD_MANDATORY);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "locality", FIELD_MANDATORY);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthFrom", FIELD_MANDATORY);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "yearFrom", FIELD_MANDATORY);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", FIELD_MANDATORY);
		doFurtherValidations(target, errors);
	}

	private void doFurtherValidations(Object target, Errors errors) {
		if (errors.hasErrors()) {
			return;
		}

		ExperienceModel experience = (ExperienceModel) target;
		if (!experience.isCurrent()) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthTo", FIELD_MANDATORY);
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "yearTo", FIELD_MANDATORY);
			checkPeriodCorrectness(experience, errors);
		}
	}

	private void checkPeriodCorrectness(ExperienceModel experience, Errors errors) {
		DateTime periodFrom = new DateTime().withMonthOfYear(getMonth(experience.getMonthFrom())).withYear(getYear(experience.getYearFrom()));
		DateTime periodTo = new DateTime().withMonthOfYear(getMonth(experience.getMonthTo())).withYear(getYear(experience.getYearTo()));
		if (periodTo.isBefore(periodFrom)) {
			errors.rejectValue("monthTo", "experience.err.invalidperiods");
			errors.rejectValue("yearTo", "experience.err.invalidperiods");
		}
	}

	private int getMonth(String month) {
		return Integer.parseInt(month) + 1;
	}

	private int getYear(String year) {
		return Integer.parseInt(year);
	}

}


text:
$("select").change(function (){
   $("#filterForm").submit();
});


text:
<!DOCTYPE html>

  <title>Your app name</title>
  <meta charset="utf-8">


text:
\section{Soll-Ist-Zeit-Vergleich}
Während des ganzen Projektes haben wir in Jira vor jeder Phase die jeweiligen Tasks definiert und den Aufwand dazu geschätzt (Soll). Weiter haben wir dann auch die effektive Zeit zu den Tasks erfasst (Ist).
\subsection{Inception}
\begin{tabbing}[H]
    \hspace*{3cm}\=\hspace*{5cm}\=\hspace*{3cm}\=\hspace*{3cm}\= \kill
    Start: \> 14.09.2015 \>	Ende: \> 23.09.2015 \\
\end{tabbing}
\begin{figure}[H]
\centering
\includegraphics[width=390pt]{images/inception.png}
\caption[Inception]{Inception}
\end{figure}
\newpage
\subsection{Elaboration1}
\begin{tabbing}[H]
    \hspace*{3cm}\=\hspace*{5cm}\=\hspace*{3cm}\=\hspace*{3cm}\= \kill
    Start: \> 23.09.2015 \> Ende: \> 19.10.2015 \\
\end{tabbing}
\begin{figure}[H]
\includegraphics[width=390pt]{images/elab1.png}
\caption[Elaboration1]{Elaboration1}
\end{figure}

\subsection{Elaboration2}
\begin{tabbing}[H]
    \hspace*{3cm}\=\hspace*{5cm}\=\hspace*{3cm}\=\hspace*{3cm}\= \kill
    Start: \> 19.10.2015 \> Ende: \>  04.11.2015 \\
\end{tabbing}
\begin{figure}[H]
\centering
\includegraphics[width=390pt]{images/elab2.png}
\caption[Elaboration2]{Elaboration2}
\end{figure}

\subsection{Construction1}
\begin{tabbing}[H]
    \hspace*{3cm}\=\hspace*{5cm}\=\hspace*{3cm}\=\hspace*{3cm}\= \kill
    Start: \> 04.11.2015 \>	Ende: \>  25.11.2015 \\
\end{tabbing}
\begin{figure}[H]
\centering
\includegraphics[width=390pt]{images/construction1.png}
\caption[Construction1]{Construction1}
\end{figure}

\subsection{Construction2}
\begin{tabbing}[H]
    \hspace*{3cm}\=\hspace*{5cm}\=\hspace*{3cm}\=\hspace*{3cm}\= \kill
    Start: \> 04.11.2015 \>	Ende: \>  11.11.2015 \\
\end{tabbing}
\begin{figure}[H]
\centering
\includegraphics[width=390pt]{images/construction1.png}
\caption[Construction2]{Construction2}
\end{figure}

\subsection{Transition}
\begin{tabbing}[H]
    \hspace*{3cm}\=\hspace*{5cm}\=\hspace*{3cm}\=\hspace*{3cm}\= \kill
    Start: \> 11.12.2015 \> Ende: \>  18.12.2015 \\
\end{tabbing}
\begin{figure}[H]
\centering
\includegraphics[width=390pt]{images/transition.png}
\caption[Transition]{Transition}
\end{figure}

\subsection{Übersicht}
\begin{table}[H]
\centering
    \begin{tabular}{|p{5cm}|p{2cm}|p{2cm}|p{2cm}|}
    \hline
    \rowcolor{lightblue}
	Phase & Soll & Ist & Differenz \\ \hline
	Inception & 36.00 &	45.50 &	9.50 \\ \hline
	Elaboration1 & 111.00 & 150.50	& 39.50 \\ \hline
	Elaboration2 & 98.00 & 105.75 & 7.75 \\ \hline
	Construction1 & 110.00 & 122.50 & 12.50 \\ \hline
	Construction1 & 58.00 & 88.50 & 30.50 \\ \hline
	Transition & 34.00 & 52.00 & 18.00 \\ \hline
	\rowcolor{lightblue}
	Total & 447.00 & 564.75 & 117.75 \\ \hline
    \end{tabular}
    \caption[Phasen]{Phasen}
\end{table}
\medskip
Schätzen ist wie bekannt, ein relativ schwierige Angelegenheit. So haben wir den Aufwand für die jeweiligen Tasks meist zu tief eingestuft. Stark ins Gewicht fiel die Evaluation und Implementierung des Bilderkennungsalgorithmus.

\newpage


text:
import { escape } from 'vs/base/common/strings';
import { localize } from 'vs/nls';

export default (): string => `

${escape(localize('completeInEnglish', "Please complete the form in English."))}

			${escape(localize('issueTypeLabel', "This is a"))}
			<select id="issue-type" class="inline-form-control">

			</select>

			${escape(localize('issueSourceLabel', "File on"))}*
			<select id="issue-source" class="inline-form-control" required>

			</select>

${escape(localize('issueSourceEmptyValidation', "An issue source is required."))}

${escape(localize('disableExtensionsLabelText', "Try to reproduce the problem after {0}. If the problem only reproduces when extensions are active, it is likely an issue with an extension."))
		.replace('{0}', `<span tabIndex=0 role="button" id="disableExtensions" class="workbenchCommand">${escape(localize('disableExtensions', "disabling all extensions and reloading the window"))}</span>`)}

				${escape(localize('chooseExtension', "Extension"))} *
				<select id="extension-selector" class="inline-form-control">

				</select>

${escape(localize('extensionWithNonstandardBugsUrl', "The issue reporter is unable to create issues for this extension. Please visit {0} to report an issue."))
		.replace('{0}', `<span tabIndex=0 role="button" id="extensionBugsLink" class="workbenchCommand"><!-- To be dynamically filled --></span>`)}

					${escape(localize('extensionWithNoBugsUrl', "The issue reporter is unable to create issues for this extension, as it does not specify a URL for reporting issues. Please check the marketplace page of this extension to see if other instructions are available."))}

			${escape(localize('issueTitleLabel', "Title"))} *
			<input id="issue-title" type="text" class="inline-form-control" placeholder="${escape(localize('issueTitleRequired', "Please enter a title."))}" required>

${escape(localize('titleEmptyValidation', "A title is required."))}

${escape(localize('titleLengthValidation', "The title is too long."))}

			<textarea name="description" id="description" placeholder="${escape(localize('details', "Please enter details."))}" required></textarea>

${escape(localize('descriptionEmptyValidation', "A description is required."))}

			<input class="sendData" type="checkbox" id="includeSystemInfo" checked/>
			${escape(localize({
			key: 'sendSystemInfo',
			comment: ['{0} is either "show" or "hide" and is a button to toggle the visibility of the system information']
		}, "Include my system information ({0})")).replace('{0}', `<a href="#" class="showInfo">${escape(localize('show', "show"))}</a>`)}

			<input class="sendData" type="checkbox" id="includeProcessInfo" checked/>
			${escape(localize({
			key: 'sendProcessInfo',
			comment: ['{0} is either "show" or "hide" and is a button to toggle the visibility of the process info']
		}, "Include my currently running processes ({0})")).replace('{0}', `<a href="#" class="showInfo">${escape(localize('show', "show"))}</a>`)}

			<input class="sendData" type="checkbox" id="includeWorkspaceInfo" checked/>
			${escape(localize({
			key: 'sendWorkspaceInfo',
			comment: ['{0} is either "show" or "hide" and is a button to toggle the visibility of the workspace information']
		}, "Include my workspace metadata ({0})")).replace('{0}', `<a href="#" class="showInfo">${escape(localize('show', "show"))}</a>`)}

			<input class="sendData" type="checkbox" id="includeExtensions" checked/>
			${escape(localize({
			key: 'sendExtensions',
			comment: ['{0} is either "show" or "hide" and is a button to toggle the visibility of the enabled extensions list']
		}, "Include my enabled extensions ({0})")).replace('{0}', `<a href="#" class="showInfo">${escape(localize('show', "show"))}</a>`)}

			<input class="sendData" type="checkbox" id="includeExperiments" checked/>
			${escape(localize({
			key: 'sendExperiments',
			comment: ['{0} is either "show" or "hide" and is a button to toggle the visibility of the current experiment information']
		}, "Include A/B experiment info ({0})")).replace('{0}', `<a href="#" class="showInfo">${escape(localize('show', "show"))}</a>`)}

`;


text:
// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: jglaser

/*! \file GPUVector.h
    \brief Defines the GPUVector and GlobalVector classes
*/

#ifdef __HIPCC__
#error This header cannot be compiled by nvcc
#endif

#pragma once
#include "GPUArray.h"
#include <algorithm>

// The factor with which the array size is incremented
#define RESIZE_FACTOR 9.f / 8.f

//! Forward declarations
template<class T> class GPUVector;

template<class T> class GlobalVector;

//! Class for managing a vector of elements on the GPU mirrored to the CPU
/*! The GPUVectorBase class is a simple container for a variable number of elements. Its interface
   is inspired by std::vector and it offers methods to insert new elements at the end of the list,
   and to remove them from there.

    It uses a GPUArray as the underlying storage class, thus the data in a GPUVectorBase can also be
   accessed directly using ArrayHandles.

    In the current implementation, a GPUVectorBase can only grow (but not shrink) in size until it
   is destroyed.

    \ingroup data_structs
*/
template<class T, class Array> class GPUVectorBase : public Array
    {
    public:
    //! Frees memory
    virtual ~GPUVectorBase() = default;

    //! Copy constructor
    GPUVectorBase(const GPUVectorBase& from);
    //! = operator
    GPUVectorBase& operator=(const GPUVectorBase& rhs);

    //! swap this GPUVectorBase with another
    inline void swap(GPUVectorBase& from);

    /*!
      \returns the current size of the vector
    */
    size_t size() const
        {
        return m_size;
        }

    //! Resize the GPUVectorBase
    /*! \param new_size New number of elements
     */
    virtual void resize(size_t new_size);

    //! Resize the GPUVectorBase
    /*! \param new_size New number of elements
     *  \param const value to initialize newly added elements with
     */
    virtual void resize(size_t new_size, const T& value);

    //! Insert an element at the end of the vector
    /*! \param val The new element
     */
    virtual void push_back(const T& val);

    //! Remove an element from the end of the list
    virtual void pop_back();

    //! Remove an element by index
    virtual void erase(size_t i);

    //! Clear the list
    virtual void clear();

    //! Proxy class to provide access to the data elements of the vector
    class data_proxy
        {
        public:
        //! Constructor
        data_proxy(const GPUVectorBase<T, Array>& _vec, const size_t _n) : vec(_vec), n(_n) { }

        //! Type cast
        operator T() const
            {
            auto dispatch = vec.acquireHost(access_mode::read);
            T* data = dispatch.get();
            T val = data[n];
            return val;
            }

        //! Assignment
        data_proxy& operator=(T rhs)
            {
            auto dispatch = vec.acquireHost(access_mode::readwrite);
            T* data = dispatch.get();
            data[n] = rhs;
            return *this;
            }

        private:
        const GPUVectorBase<T, Array>& vec; //!< The vector that is accessed
        size_t n;                           //!< The index of the element to access
        };

    //! Get a proxy-reference to a list element
    data_proxy operator[](size_t n)
        {
        assert(n < m_size);
        return data_proxy(*this, n);
        }

    //! Get a proxy-reference to a list element (const version)
    data_proxy operator[](size_t n) const
        {
        assert(n < m_size);
        return data_proxy(*this, n);
        }

    protected:
    //! Default constructor
    GPUVectorBase();

    //! Constructs an empty GPUVectorBase
    GPUVectorBase(std::shared_ptr<const ExecutionConfiguration> exec_conf);

    //! Constructs a GPUVectorBase
    GPUVectorBase(size_t size, std::shared_ptr<const ExecutionConfiguration> exec_conf);

    //! Constructs a GPUVectorBase of given size, initialized with a constant value
    GPUVectorBase(unsigned int size,
                  const T& value,
                  std::shared_ptr<const ExecutionConfiguration> exec_conf);

#ifdef ENABLE_HIP
    //! Constructs an empty GPUVectorBase
    GPUVectorBase(std::shared_ptr<const ExecutionConfiguration> exec_conf, bool mapped);

    //! Constructs a GPUVectorBase
    GPUVectorBase(size_t size,
                  std::shared_ptr<const ExecutionConfiguration> exec_conf,
                  bool mapped);
#endif

    private:
    size_t m_size; //!< Number of elements

    //! Helper function to reallocate the GPUArray (using amortized array resizing)
    void reallocate(size_t new_size);

    //! Acquire the underlying GPU array on the host
    ArrayHandleDispatch<T> acquireHost(const access_mode::Enum mode) const;

    friend class data_proxy;
    };

//******************************************
// GPUVectorBase implementation
// *****************************************

//! Default constructor
/*! \warning When using this constructor, a properly initialized GPUVectorBase with an exec_conf
   needs to be swapped in later, after construction of the GPUVectorBase.
 */
template<class T, class Array> GPUVectorBase<T, Array>::GPUVectorBase() : Array(), m_size(0) { }

/*! \param exec_conf Shared pointer to the execution configuration
 */
template<class T, class Array>
GPUVectorBase<T, Array>::GPUVectorBase(std::shared_ptr<const ExecutionConfiguration> exec_conf)
    : Array(0, exec_conf), m_size(0)
    {
    }

/*! \param size Number of elements to allocate initial memory for in the array
    \param exec_conf Shared pointer to the execution configuration
*/
template<class T, class Array>
GPUVectorBase<T, Array>::GPUVectorBase(size_t size,
                                       std::shared_ptr<const ExecutionConfiguration> exec_conf)
    : Array(size, exec_conf), m_size(size)
    {
    }

/*! \param size Number of elements to allocate initial memory for in the array
    \param value constant value to initialize the array with
    \param exec_conf Shared pointer to the execution configuration
*/
template<class T, class Array>
GPUVectorBase<T, Array>::GPUVectorBase(unsigned int size,
                                       const T& value,
                                       std::shared_ptr<const ExecutionConfiguration> exec_conf)
    : Array(size, exec_conf), m_size(size)
    {
    auto dispatch = acquireHost(access_mode::readwrite);
    T* data = dispatch.get();
    for (unsigned int i = 0; i < size; ++i)
        data[i] = value;
    }

template<class T, class Array>
GPUVectorBase<T, Array>::GPUVectorBase(const GPUVectorBase& from) : Array(from), m_size(from.m_size)
    {
    }

template<class T, class Array>
GPUVectorBase<T, Array>& GPUVectorBase<T, Array>::operator=(const GPUVectorBase& rhs)
    {
    if (this != &rhs) // protect against invalid self-assignment
        {
        m_size = rhs.m_size;
        // invoke base class operator
        (Array)* this = rhs;
        }

    return *this;
    }

/*! \param from GPUVectorBase to swap \a this with
 */
template<class T, class Array> void GPUVectorBase<T, Array>::swap(GPUVectorBase<T, Array>& from)
    {
    std::swap(m_size, from.m_size);
    Array::swap(from);
    }

/*! \param size New requested size of allocated memory
 *
 * Internally, this method uses amortized resizing of allocated memory to
 * avoid excessive copying of data. The GPUArray is only reallocated if necessary,
 * i.e. if the requested size is larger than the current size, which is a power of two.
 */
template<class T, class Array> void GPUVectorBase<T, Array>::reallocate(size_t size)
    {
    if (size > Array::getNumElements())
        {
        // reallocate
        size_t new_allocated_size = Array::getNumElements() ? Array::getNumElements() : 1;

        // double the size as often as necessary
        while (size > new_allocated_size)
            new_allocated_size = ((size_t)(((double)new_allocated_size) * RESIZE_FACTOR)) + 1;

        // actually resize the underlying GPUArray
        Array::resize(new_allocated_size);
        }
    }

/*! \param new_size New size of vector
 \post The GPUVectorBase will be re-allocated if necessary to hold the new elements.
       The newly allocated memory is \b not initialized. It is responsibility of the caller to
 ensure correct initialization, e.g. using clear()
*/
template<class T, class Array> void GPUVectorBase<T, Array>::resize(size_t new_size)
    {
    // allocate memory by amortized O(N) resizing
    if (new_size > 0)
        reallocate(new_size);
    else
        // for zero size, we at least allocate the memory
        reallocate(1);

    // set new size
    m_size = new_size;
    }

/*!
 \post The GPUVectorBase will be re-allocated if necessary to hold the new elements.
       The newly allocated memory is initialized with a constant value.
*/
template<class T, class Array> void GPUVectorBase<T, Array>::resize(size_t new_size, const T& value)
    {
    size_t old_size = m_size;
    resize(new_size);
    auto dispatch = acquireHost(access_mode::readwrite);
    T* data = dispatch.get();
    for (size_t i = old_size; i < new_size; ++i)
        data[i] = value;
    }

//! Insert an element at the end of the vector
template<class T, class Array> void GPUVectorBase<T, Array>::push_back(const T& val)
    {
    reallocate(m_size + 1);

    auto dispatch = acquireHost(access_mode::readwrite);
    T* data = dispatch.get();
    data[m_size++] = val;
    }

//! Remove an element from the end of the list
template<class T, class Array> void GPUVectorBase<T, Array>::pop_back()
    {
    assert(m_size);
    m_size--;
    }

//! Remove an element in the middle
template<class T, class Array> void GPUVectorBase<T, Array>::erase(size_t i)
    {
    assert(i < m_size);
    auto dispatch = acquireHost(access_mode::readwrite);

    T* data = dispatch.get();
    T* res = data;
    for (size_t n = 0; n < m_size; ++n)
        {
        if (n != i)
            {
            *res = *data;
            res++;
            }
        data++;
        }
    m_size--;
    }

//! Clear the list
template<class T, class Array> void GPUVectorBase<T, Array>::clear()
    {
    m_size = 0;
    }

/*! \param mode Access mode for the GPUArray
 */
template<class T, class Array>
ArrayHandleDispatch<T> GPUVectorBase<T, Array>::acquireHost(const access_mode::Enum mode) const
    {
#ifdef ENABLE_HIP
    return GPUArrayBase<T, Array>::acquire(access_location::host, access_mode::readwrite, false);
#else
    return Array::acquire(access_location::host, access_mode::readwrite);
#endif
    }

//! Forward declarations
template<class T> class GPUArray;

template<class T> class GlobalArray;

//******************************************
// Specialization for zero copy memory (GPUArray)
//******************************************

template<class T> class GPUVector : public GPUVectorBase<T, GPUArray<T>>
    {
    public:
    //! Default constructor
    GPUVector() { }

    //! Constructs an empty GPUVector
    GPUVector(std::shared_ptr<const ExecutionConfiguration> exec_conf)
        : GPUVectorBase<T, GPUArray<T>>(exec_conf)
        {
        }

    //! Constructs a GPUVector
    GPUVector(size_t size, std::shared_ptr<const ExecutionConfiguration> exec_conf)
        : GPUVectorBase<T, GPUArray<T>>(size, exec_conf)
        {
        }

    //! Constructs a GPUVector
    GPUVector(unsigned int size,
              const T& value,
              std::shared_ptr<const ExecutionConfiguration> exec_conf)
        : GPUVectorBase<T, GPUArray<T>>(size, value, exec_conf)
        {
        }
    };

//******************************************
// Specialization for managed memory (GlobalArray)
//******************************************

template<class T> class GlobalVector : public GPUVectorBase<T, GlobalArray<T>>
    {
    public:
    //! Default constructor
    GlobalVector() { }

    //! Constructs an empty GlobalVector
    GlobalVector(std::shared_ptr<const ExecutionConfiguration> exec_conf)
        : GPUVectorBase<T, GlobalArray<T>>(exec_conf)
        {
        }

    //! Constructs a GPUVector
    GlobalVector(size_t size, std::shared_ptr<const ExecutionConfiguration> exec_conf)
        : GPUVectorBase<T, GlobalArray<T>>(size, exec_conf)
        {
        }

    //! Constructs a GlobalVector
    GlobalVector(unsigned int size,
                 const T& value,
                 std::shared_ptr<const ExecutionConfiguration> exec_conf)
        : GPUVectorBase<T, GlobalArray<T>>(size, value, exec_conf)
        {
        }

    //! Set the tag
    void setTag(const std::string& tag)
        {
        static_cast<GlobalArray<T>&>(*this).setTag(tag);
        }

    //! Get the underlying raw pointer
    const T* get() const
        {
        return static_cast<GlobalArray<T> const&>(*this).get();
        }
    };


text:
package object

import (
	"fmt"

	"golang.org/x/net/context"

	"github.com/vmware/govmomi/vim25"
	"github.com/vmware/govmomi/vim25/methods"
	"github.com/vmware/govmomi/vim25/mo"
	"github.com/vmware/govmomi/vim25/types"
)

type VirtualApp struct {
	*ResourcePool
}

func NewVirtualApp(c *vim25.Client, ref types.ManagedObjectReference) *VirtualApp {
	return &VirtualApp{
		ResourcePool: NewResourcePool(c, ref),
	}
}

func (p VirtualApp) String() string {
	if p.InventoryPath == "" {
		return p.Common.String()
	}
	return fmt.Sprintf("%v @ %v", p.Common, p.InventoryPath)
}

func (p VirtualApp) Name(ctx context.Context) (string, error) {
	var o mo.VirtualApp

	err := p.Properties(ctx, p.Reference(), []string{"name"}, &o)
	if err != nil {
		return "", err
	}

	return o.Name, nil
}

func (p VirtualApp) CreateChildVM_Task(ctx context.Context, config types.VirtualMachineConfigSpec, host *HostSystem) (*Task, error) {
	req := types.CreateChildVM_Task{
		This:   p.Reference(),
		Config: config,
	}

	if host != nil {
		ref := host.Reference()
		req.Host = &ref
	}

	res, err := methods.CreateChildVM_Task(ctx, p.c, &req)
	if err != nil {
		return nil, err
	}

	return NewTask(p.c, res.Returnval), nil
}