text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Socket acceptor service requirements</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../index.html" title="Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="SignalSetService.html" title="Signal set service requirements">
<link rel="next" href="SocketService.html" title="Socket service requirements">

Socket acceptor
      service requirements

        A socket acceptor service must meet the requirements for an I/O
        object service, as well as the additional requirements listed below.

        In the table below, X denotes
        a socket acceptor service class for protocol Protocol, a
        and ao denote values of type
        X, b
        and c denote values of type
        X::implementation_type, p
        denotes a value of type Protocol,
        n denotes a value of type
        X::native_handle_type, e
        denotes a value of type Protocol::endpoint,
        ec denotes a value of type
        error_code, s denotes a value meeting SettableSocketOption requirements,
        g denotes a value meeting
        GettableSocketOption
        requirements, i denotes a
        value meeting IoControlCommand requirements,
        k denotes a value of type
        basic_socket<Protocol, SocketService>
        where SocketService is a
        type meeting socket service
        requirements, ah denotes
        a value meeting AcceptHandler requirements, and
        u and v
        denote identifiers.

Table 29. SocketAcceptorService requirements

<colgroup>
<col>
<col>
<col>
</colgroup>

                  expression

                  return type

                  assertion/note
 pre/post-condition

                  X::native_handle_type

                  The implementation-defined native representation of a socket acceptor.
                  Must satisfy the requirements of CopyConstructible
                  types (C++ Std, 20.1.3), and the requirements of Assignable types (C++ Std, 23.1).

                  a.construct(b);

                  From IoObjectService
                  requirements.
 post: !a.is_open(b).

                  a.destroy(b);

                  From IoObjectService
                  requirements. Implicitly cancels asynchronous operations, as if
                  by calling a.close(b,
                  ec).

a.move_construct(b, c);

                  From IoObjectService
                  requirements. The underlying native representation is moved from
                  c to b.

a.move_assign(b, ao, c);

                  From IoObjectService
                  requirements. Implicitly cancels asynchronous operations associated
                  with b, as if by
                  calling a.close(b,
                  ec).
                  Then the underlying native representation is moved from c to b.

a.open(b, p, ec);

                  error_code

                  pre: !a.is_open(b).
 post: !!ec ||
                  a.is_open(b).

a.assign(b, p, n, ec);

                  error_code

                  pre: !a.is_open(b).
 post: !!ec ||
                  a.is_open(b).

a.is_open(b);

                  bool

const X& u = a;
const X::implementation_type& v = b;
u.is_open(v);

                  bool

a.close(b, ec);

                  error_code

                  If a.is_open()
                  is true, causes any outstanding asynchronous operations to complete
                  as soon as possible. Handlers for cancelled operations shall be
                  passed the error code error::operation_aborted.

                  post: !a.is_open(b).

a.native_handle(b);

                  X::native_handle_type

a.cancel(b, ec);

                  error_code

                  pre: a.is_open(b).

                  Causes any outstanding asynchronous operations to complete as soon
                  as possible. Handlers for cancelled operations shall be passed
                  the error code error::operation_aborted.

a.set_option(b, s, ec);

                  error_code

                  pre: a.is_open(b).

a.get_option(b, g, ec);

                  error_code

                  pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.get_option(v, g, ec);

                  error_code

                  pre: a.is_open(b).

a.io_control(b, i, ec);

                  error_code

                  pre: a.is_open(b).

const typename Protocol::endpoint& u = e;
a.bind(b, u, ec);

                  error_code

                  pre: a.is_open(b).

a.local_endpoint(b, ec);

                  Protocol::endpoint

                  pre: a.is_open(b).

const X& u = a;
const X::implementation_type& v = b;
u.local_endpoint(v, ec);

                  Protocol::endpoint

                  pre: a.is_open(b).

a.accept(b, k, &e, ec);

                  error_code

                  pre: a.is_open(b)
                  && !k.is_open().

                  post: k.is_open()

a.accept(b, k, 0, ec);

                  error_code

                  pre: a.is_open(b)
                  && !k.is_open().

                  post: k.is_open()

a.async_accept(b, k, &e, ah);

                  pre: a.is_open(b)
                  && !k.is_open().

                  Initiates an asynchronous accept operation that is performed via
                  the io_service
                  object a.get_io_service()
                  and behaves according to asynchronous
                  operation requirements.

 The program must ensure
                  the objects k and
                  e are valid until
                  the handler for the asynchronous operation is invoked.

a.async_accept(b, k, 0, ah);

                  pre: a.is_open(b)
                  && !k.is_open().

                  Initiates an asynchronous accept operation that is performed via
                  the io_service
                  object a.get_io_service()
                  and behaves according to asynchronous
                  operation requirements.

 The program must ensure
                  the object k is
                  valid until the handler for the asynchronous operation is invoked.

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.spark.util

import java.util.concurrent.CountDownLatch

import scala.collection.mutable
import scala.concurrent.duration._
import scala.language.postfixOps

import org.scalatest.concurrent.Eventually._
import org.scalatest.concurrent.Timeouts

import org.apache.spark.SparkFunSuite

class EventLoopSuite extends SparkFunSuite with Timeouts {

  test("EventLoop") {
    val buffer = new mutable.ArrayBuffer[Int] with mutable.SynchronizedBuffer[Int]
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        buffer += event
      }

      override def onError(e: Throwable): Unit = {}
    }
    eventLoop.start()
    (1 to 100).foreach(eventLoop.post)
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert((1 to 100) === buffer.toSeq)
    }
    eventLoop.stop()
  }

  test("EventLoop: start and stop") {
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {}

      override def onError(e: Throwable): Unit = {}
    }
    assert(false === eventLoop.isActive)
    eventLoop.start()
    assert(true === eventLoop.isActive)
    eventLoop.stop()
    assert(false === eventLoop.isActive)
  }

  test("EventLoop: onError") {
    val e = new RuntimeException("Oops")
    @volatile var receivedError: Throwable = null
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        throw e
      }

      override def onError(e: Throwable): Unit = {
        receivedError = e
      }
    }
    eventLoop.start()
    eventLoop.post(1)
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(e === receivedError)
    }
    eventLoop.stop()
  }

  test("EventLoop: error thrown from onError should not crash the event thread") {
    val e = new RuntimeException("Oops")
    @volatile var receivedError: Throwable = null
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        throw e
      }

      override def onError(e: Throwable): Unit = {
        receivedError = e
        throw new RuntimeException("Oops")
      }
    }
    eventLoop.start()
    eventLoop.post(1)
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(e === receivedError)
      assert(eventLoop.isActive)
    }
    eventLoop.stop()
  }

  test("EventLoop: calling stop multiple times should only call onStop once") {
    var onStopTimes = 0
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
      }

      override def onError(e: Throwable): Unit = {
      }

      override def onStop(): Unit = {
        onStopTimes += 1
      }
    }

    eventLoop.start()

    eventLoop.stop()
    eventLoop.stop()
    eventLoop.stop()

    assert(1 === onStopTimes)
  }

  test("EventLoop: post event in multiple threads") {
    @volatile var receivedEventsCount = 0
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        receivedEventsCount += 1
      }

      override def onError(e: Throwable): Unit = {
      }

    }
    eventLoop.start()

    val threadNum = 5
    val eventsFromEachThread = 100
    (1 to threadNum).foreach { _ =>
      new Thread() {
        override def run(): Unit = {
          (1 to eventsFromEachThread).foreach(eventLoop.post)
        }
      }.start()
    }

    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(threadNum * eventsFromEachThread === receivedEventsCount)
    }
    eventLoop.stop()
  }

  test("EventLoop: onReceive swallows InterruptException") {
    val onReceiveLatch = new CountDownLatch(1)
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        onReceiveLatch.countDown()
        try {
          Thread.sleep(5000)
        } catch {
          case ie: InterruptedException => // swallow
        }
      }

      override def onError(e: Throwable): Unit = {
      }

    }
    eventLoop.start()
    eventLoop.post(1)
    failAfter(5 seconds) {
      // Wait until we enter `onReceive`
      onReceiveLatch.await()
      eventLoop.stop()
    }
    assert(false === eventLoop.isActive)
  }

  test("EventLoop: stop in eventThread") {
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        stop()
      }

      override def onError(e: Throwable): Unit = {
      }

    }
    eventLoop.start()
    eventLoop.post(1)
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(!eventLoop.isActive)
    }
  }

  test("EventLoop: stop() in onStart should call onStop") {
    @volatile var onStopCalled: Boolean = false
    val eventLoop = new EventLoop[Int]("test") {

      override def onStart(): Unit = {
        stop()
      }

      override def onReceive(event: Int): Unit = {
      }

      override def onError(e: Throwable): Unit = {
      }

      override def onStop(): Unit = {
        onStopCalled = true
      }
    }
    eventLoop.start()
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(!eventLoop.isActive)
    }
    assert(onStopCalled)
  }

  test("EventLoop: stop() in onReceive should call onStop") {
    @volatile var onStopCalled: Boolean = false
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        stop()
      }

      override def onError(e: Throwable): Unit = {
      }

      override def onStop(): Unit = {
        onStopCalled = true
      }
    }
    eventLoop.start()
    eventLoop.post(1)
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(!eventLoop.isActive)
    }
    assert(onStopCalled)
  }

  test("EventLoop: stop() in onError should call onStop") {
    @volatile var onStopCalled: Boolean = false
    val eventLoop = new EventLoop[Int]("test") {

      override def onReceive(event: Int): Unit = {
        throw new RuntimeException("Oops")
      }

      override def onError(e: Throwable): Unit = {
        stop()
      }

      override def onStop(): Unit = {
        onStopCalled = true
      }
    }
    eventLoop.start()
    eventLoop.post(1)
    eventually(timeout(5 seconds), interval(5 millis)) {
      assert(!eventLoop.isActive)
    }
    assert(onStopCalled)
  }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file
 * @brief  Sample implementation of code to validate a certificate chain.
 */

/******************************************************************************
 *
 *
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <qcc/platform.h>

#include <assert.h>
#include <signal.h>
#include <stdio.h>
#include <memory>

#include <qcc/Log.h>
#include <qcc/String.h>

#include <qcc/CryptoECC.h>
#include <qcc/CertificateECC.h>

#include <alljoyn/Status.h>
#include <alljoyn/Init.h>
#include <alljoyn/AuthListener.h>

#include "SampleCertificateChainEngine.h"

using namespace std;
using namespace qcc;
using namespace ajn;

/* This is a list of PEM-encoded CA certificates which forms our trusted root list.
 * If one of these certificates is ever seen on a chain, the chain is considered trusted.
 */
static const char* TRUSTED_ROOTS_PEM[] = {
    /* AllJoyn ECDHE Sample Unused Certificate Authority
     *
     * This is included to demonstrate having more than one trusted root, but as the
     * name implies, it doesn't issue any certificates in this sample. */
    "-----BEGIN CERTIFICATE-----\n"
    "MIIBijCCATCgAwIBAgIUVSjE1Fv/6jP30BfkRXmSoA8sEkIwCgYIKoZIzj0EAwIw\n"
    "PDE6MDgGA1UEAwwxQWxsSm95biBFQ0RIRSBTYW1wbGUgVW51c2VkIENlcnRpZmlj\n"
    "YXRlIEF1dGhvcml0eTAeFw0xNTA1MDcxNzE0MDdaFw0yNTA1MDQxNzE0MDdaMDwx\n"
    "OjA4BgNVBAMMMUFsbEpveW4gRUNESEUgU2FtcGxlIFVudXNlZCBDZXJ0aWZpY2F0\n"
    "ZSBBdXRob3JpdHkwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAS7SmQ19lKjLo2C\n"
    "yyqubmHPRNAo8Eo/i300UWhNAkurVy/WJ3zFMxYNwJeenZ46qJsYb4faZp3iuXF7\n"
    "mllsClzjoxAwDjAMBgNVHRMEBTADAQH/MAoGCCqGSM49BAMCA0gAMEUCIQD/zB3n\n"
    "0+gxUHOdZZadDfLQjMuFxR3LMzUqdBbYZudOGwIgKPT2KYGTW7P/H1hIM6wAyHBB\n"
    "lBOnPXqXjFLodiM+8zM=\n"
    "-----END CERTIFICATE-----\n",
    /* AllJoyn ECDHE Sample Certificate Authority
     * This CA issued the certificates used for the Client and Service in this sample. */
    "-----BEGIN CERTIFICATE-----\n"
    "MIIBezCCASKgAwIBAgIUDrFhHE80+zbEUOCNTxw219Nd1qwwCgYIKoZIzj0EAwIw\n"
    "NTEzMDEGA1UEAwwqQWxsSm95biBFQ0RIRSBTYW1wbGUgQ2VydGlmaWNhdGUgQXV0\n"
    "aG9yaXR5MB4XDTE1MDUwNzIyMTYzNloXDTI1MDUwNDIyMTYzNlowNTEzMDEGA1UE\n"
    "AwwqQWxsSm95biBFQ0RIRSBTYW1wbGUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MFkw\n"
    "EwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6AsCTTviTBWX0Jw2e8Cs8DhwxfRd37Yp\n"
    "IH5ALzBqwUN2sfG1odcthe6GKdE/9oVfy12SXOL3X2bi3yg1XFoWnaMQMA4wDAYD\n"
    "VR0TBAUwAwEB/zAKBggqhkjOPQQDAgNHADBEAiASuD0OrpDM8ziC5GzMbZWKNE/X\n"
    "eboedc0p6YsAZmry2AIgR23cKM4cKkc2bgUDbETNbDcOcwm+EWaK9E4CkOO/tBc=\n"
    "-----END CERTIFICATE-----\n"
};

static QStatus CountChunksFromEncoded(const String& encoded, const char* beginToken, const char* endToken, size_t* count)
{
    size_t pos;

    *count = 0;
    qcc::String remainder = encoded;
    for (;;) {
        pos = remainder.find(beginToken);
        if (pos == qcc::String::npos) {
            /* no more */
            return ER_OK;
        }
        remainder = remainder.substr(pos + strlen(beginToken));
        pos = remainder.find(endToken);
        if (pos == qcc::String::npos) {
            return ER_OK;
        }
        *count += 1;
        remainder = remainder.substr(pos + strlen(endToken));
    }
    /* Unreachable. */
}

static QStatus GetCertCount(const String& encoded, size_t* count)
{
    const char* const BEGIN_CERT_TAG = "-----BEGIN CERTIFICATE-----";
    const char* const END_CERT_TAG = "-----END CERTIFICATE-----";
    *count = 0;
    return CountChunksFromEncoded(encoded, BEGIN_CERT_TAG, END_CERT_TAG, count);
}

bool VerifyCertificateChain(const AuthListener::Credentials& creds)
{
    /* This certificate chain verification engine does the following:
     *
     * 1. Verifies all certificates in the chain are time-valid.
     * 2. Verifies that all CA's in the chain have the CA flag set to TRUE,
     * 3. Verifies the cryptographic binding between each certificate.
     * 4. Verifies the certificates chain up to one of the trusted roots.
     *
     * Other implementations may make app-dependent decisions, such as:
     * - checking for particular Key Usages or Extended Key Usages (EKUs) on certificates,
     * - verifying the certificate's subject name equals some known value. */

    /* If we didn't get a certificate chain, there's nothing to validate! */
    if (!creds.IsSet(AuthListener::CRED_CERT_CHAIN)) {
        printf("VerifyCertificateChain FAILED: No certificate chain provided!\n");
        return false;
    }

    /* Decode the list of roots into an array of CertificateX509 objects to later check against. */
    size_t numberOfRoots = sizeof(TRUSTED_ROOTS_PEM) / sizeof(TRUSTED_ROOTS_PEM[0]);
    CertificateX509* trustedRoots = new CertificateX509[numberOfRoots];
    CertificateX509* certChain = NULL;

    QStatus status = ER_OK;

    for (size_t i = 0; (ER_OK == status) && (i < numberOfRoots); i++) {
        status = trustedRoots[i].DecodeCertificatePEM(TRUSTED_ROOTS_PEM[i]);
        if (ER_OK != status) {
            /* Note that PRIuSIZET is not a standards-defined constant, but is defined in AllJoyn to select the
             * correct platform-dependent format specifier for type size_t.
             */
            printf("VerifyCertificateChain FAILED: Failed to decode trusted root at position %" PRIuSIZET ". Status is %s.\n",
                   i, QCC_StatusText(status));
        }
    }

    size_t chainLength = 0;
    if (ER_OK == status) {
        /* Decode the certificates in the chain into another array of CertificateX509 objects. */
        status = GetCertCount(creds.GetCertChain(), &chainLength);
        if (ER_OK != status) {
            printf("VerifyCertificateChain FAILED: Could not get length of certificate chain. Status is %s.\n", QCC_StatusText(status));
        }
    }

    if (ER_OK == status) {
        certChain = new CertificateX509[chainLength];
        status = CertificateX509::DecodeCertChainPEM(creds.GetCertChain(), certChain, chainLength);

        if (ER_OK != status) {
            printf("VerifyCertificateChain FAILED: Failed to decode certificate chain. Status is %s.\n", QCC_StatusText(status));
        }
    }

    /* Here is where you could check additional properties of the certificate, depending on your application and scenario's
     * needs.
     *
     * If you make use of the CN or OU fields of the Distinguished Name, remember that these are UTF-8 strings, so
     * make sure you use a string type that understands UTF-8! In particular, you should never interpret these
     * as null-terminated C strings, because a legal UTF-8 string could have a NUL character anywhere in it. */
    bool trusted = false;

    if (ER_OK == status) {
        for (size_t iCert = 0; iCert < chainLength; iCert++) {
            /* Every certificate must be time-valid. */
            status = certChain[iCert].VerifyValidity();
            if (ER_OK != status) {
                printf("VerifyCertificatechain FAILED; following certificate is not time valid:\n%s\n",
                       certChain[iCert].ToString().c_str());
                break;
            }

            /* If the current certificate is issued by a trusted root, we're done. */
            for (size_t iRoot = 0; iRoot < numberOfRoots; iRoot++) {
                if (trustedRoots[iRoot].IsIssuerOf(certChain[iCert])) {
                    printf("VerifyCertificateChain SUCCEEDED; trusted root certificate is:\n%s\n",
                           trustedRoots[iRoot].ToString().c_str());
                    trusted = true;
                    /* This break gets us out of this iRoot for loop. */
                    break;
                }
            }
            if (trusted) {
                /* And if we've decided the chain is trusted, break out of the iCert for loop too. */
                break;
            }

            /* If not, and there's a next certificate in the chain, check the chaining between the i'th certificate
             * and the i+1'th.
             */
            if ((iCert + 1) < chainLength) {
                /* First, the next certificate in the chain must be a CA certificate. */
                if (!certChain[iCert + 1].IsCA()) {
                    printf("VerifyCertificateChain FAILED: following certificate is not a CA certificate:\n%s\n",
                           certChain[iCert + 1].ToString().c_str());
                    break;
                }
                /* Now check the chaining. IsIssuerOf checks both that the issuer DN of the i'th certificate equals
                 * the subject DN of the i+1'th certificate in the chain, and verifies the cryptographic signature
                 * was produced by the i+1'th certificate. */
                if (!certChain[iCert + 1].IsIssuerOf(certChain[iCert])) {
                    /* Note that PRIuSIZET is not a standards-defined constant, but is defined in AllJoyn to select the
                     * correct platform-dependent format specifier for type size_t.
                     */
                    printf("VerifyCertificateChain FAILED: certificate at position %" PRIuSIZET " did not issue certificate at position %" PRIuSIZET "\n"
                           "Certificate[%" PRIuSIZET "]:\n%s\n"
                           "Certificate[%" PRIuSIZET "]:\n%s\n",
                           iCert + 1,
                           iCert,
                           iCert + 1,
                           certChain[iCert + 1].ToString().c_str(),
                           iCert,
                           certChain[iCert].ToString().c_str());
                    break;
                }
                /* This would be the place to check transitive EKUs or other chain properties, if desired. */
            }
        }
    }

    /* At this point one of three things has happened:
     * status is not ER_OK; something failed before we could even check the chain, and so we're failing;
     * status is ER_OK and trusted is false; we successfully checked the chain but no trusted root was found;
     * or status is ER_OK and trusted is true; we successfully checked the chain and found a trusted root in the path.
     *
     * Clean up and return the appropriate result.
     */

    delete[] trustedRoots;
    delete[] certChain;

    if (ER_OK != status) {
        /* In this case, we're returning false because of some internal failure. */
        return false;
    } else {
        /* Otherwise, return the trusted result. */
        if (!trusted) {
            printf("VerifyCertificateChain FAILED: did not see a trusted root in the chain.\n");
        }
        return trusted;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<title>
			<epc:pin ref="title" textonly="yes" />
			-
			<epc:phrase ref="archive_name" />
		</title>
		<link rel="icon" href="{$config{rel_path}}/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="{$config{rel_path}}/favicon.ico" type="image/x-icon" />
                <epc:phrase ref="bootstrap/head_imports:jQuery"/>

		<epc:pin ref="head" />

		<meta name="theme-color" content="{phrase('bootstrap/colors:meta_theme_color')}" />

		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no" />

		<epc:phrase ref="bootstrap/head_imports:bootstrap"/>

		<link rel="stylesheet" href="{$config{rel_path}}/bootstrap_assets/Styles/main.css" />
		<link rel="stylesheet" href="{$config{rel_path}}/bootstrap_assets/Styles/bs_overrides.css" />
		<link rel="stylesheet" href="{$config{rel_path}}/bootstrap_assets/Styles/ep_overrides.css" />

                <epc:phrase ref="bootstrap/stylesheets"/>
                <epc:phrase ref="bootstrap/stylesheets:local"/>

		<epc:pin ref="pagetop" />

	 		 <epc:phrase ref="bootstrap/branding_header:htmlTop"/>

	 		 <epc:phrase ref="bootstrap/branding_header:htmlBottom"/>

				<epc:pin ref="login_status" />

						<epc:pin ref="title" />

					<epc:pin ref="page" />

				<epc:phrase ref="template:about_eprints" />

	 	 	 <epc:phrase ref="bootstrap/branding_footer:html"/>

                <epc:phrase ref="bootstrap/scripts"/>


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccComputeFirewallPolicyRule_update(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"org_name":      fmt.Sprintf("organizations/%s", getTestOrgFromEnv(t)),
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccComputeFirewallPolicyRule_start(context),
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.default",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy"},
			},
			{
				Config: testAccComputeFirewallPolicyRule_update(context),
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.default",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy", "target_resources"},
			},
			{
				Config: testAccComputeFirewallPolicyRule_removeConfigs(context),
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.default",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy", "target_resources"},
			},
			{
				Config: testAccComputeFirewallPolicyRule_start(context),
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.default",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy"},
			},
		},
	})
}

func testAccComputeFirewallPolicyRule_start(context map[string]interface{}) string {
	return Nprintf(`
resource "google_service_account" "service_account" {
  account_id = "tf-test-sa-%{random_suffix}"
}

resource "google_service_account" "service_account2" {
  account_id = "tf-test-sa2-%{random_suffix}"
}

resource "google_compute_network" "network1" {
  name = "tf-test-%{random_suffix}"
  auto_create_subnetworks = false
}

resource "google_compute_network" "network2" {
  name = "tf-test-2-%{random_suffix}"
  auto_create_subnetworks = false
}

resource "google_folder" "folder" {
  display_name = "tf-test-folder-%{random_suffix}"
  parent       = "%{org_name}"
}

resource "google_compute_firewall_policy" "default" {
  parent      = google_folder.folder.name
  short_name  = "tf-test-policy-%{random_suffix}"
  description = "Resource created for Terraform acceptance testing"
}

resource "google_compute_firewall_policy_rule" "default" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9000
  enable_logging = true
  action = "allow"
  direction = "EGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports = [80, 8080]
    }
    dest_ip_ranges = ["11.100.0.1/32"]
  }
}
`, context)
}

func testAccComputeFirewallPolicyRule_update(context map[string]interface{}) string {
	return Nprintf(`
resource "google_service_account" "service_account" {
  account_id = "tf-test-sa-%{random_suffix}"
}

resource "google_service_account" "service_account2" {
  account_id = "tf-test-sa2-%{random_suffix}"
}

resource "google_compute_network" "network1" {
  name = "tf-test-%{random_suffix}"
  auto_create_subnetworks = false
}

resource "google_compute_network" "network2" {
  name = "tf-test-2-%{random_suffix}"
  auto_create_subnetworks = false
}

resource "google_folder" "folder" {
  display_name = "tf-test-folder-%{random_suffix}"
  parent       = "%{org_name}"
}

resource "google_compute_firewall_policy" "default" {
  parent      = google_folder.folder.name
  short_name  = "tf-test-policy-%{random_suffix}"
  description = "Resource created for Terraform acceptance testing"
}

resource "google_compute_firewall_policy_rule" "default" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9000
  enable_logging = true
  action = "allow"
  direction = "EGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports = [8080]
    }
    layer4_configs {
      ip_protocol = "udp"
      ports = [22]
    }
    dest_ip_ranges = ["11.100.0.1/32", "10.0.0.0/24"]
  }
  target_resources = [google_compute_network.network1.self_link, google_compute_network.network2.self_link]
  target_service_accounts = [google_service_account.service_account.email]
}
`, context)
}

func testAccComputeFirewallPolicyRule_removeConfigs(context map[string]interface{}) string {
	return Nprintf(`
resource "google_service_account" "service_account" {
  account_id = "tf-test-sa-%{random_suffix}"
}

resource "google_service_account" "service_account2" {
  account_id = "tf-test-sa2-%{random_suffix}"
}

resource "google_compute_network" "network1" {
  name = "tf-test-%{random_suffix}"
  auto_create_subnetworks = false
}

resource "google_compute_network" "network2" {
  name = "tf-test-2-%{random_suffix}"
  auto_create_subnetworks = false
}

resource "google_folder" "folder" {
  display_name = "tf-test-folder-%{random_suffix}"
  parent       = "%{org_name}"
}

resource "google_compute_firewall_policy" "default" {
  parent      = google_folder.folder.id
  short_name  = "tf-test-policy-%{random_suffix}"
  description = "Resource created for Terraform acceptance testing"
}

resource "google_compute_firewall_policy_rule" "default" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Test description"
  priority = 9000
  enable_logging = false
  action = "deny"
  direction = "INGRESS"
  disabled = true
  match {
    layer4_configs {
      ip_protocol = "udp"
      ports = [22]
    }
    src_ip_ranges = ["11.100.0.1/32", "10.0.0.0/24"]
  }
  target_resources = [google_compute_network.network1.self_link]
  target_service_accounts = [google_service_account.service_account.email, google_service_account.service_account2.email]
}
`, context)
}

func TestAccComputeFirewallPolicyRule_multipleRules(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"org_name":      fmt.Sprintf("organizations/%s", getTestOrgFromEnv(t)),
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccComputeFirewallPolicyRule_multiple(context),
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.rule1",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy"},
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.rule2",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy"},
			},
			{
				Config: testAccComputeFirewallPolicyRule_multipleAdd(context),
			},
			{
				ResourceName:      "google_compute_firewall_policy_rule.rule3",
				ImportState:       true,
				ImportStateVerify: true,
				// Referencing using ID causes import to fail
				ImportStateVerifyIgnore: []string{"firewall_policy"},
			},
			{
				Config: testAccComputeFirewallPolicyRule_multipleRemove(context),
			},
		},
	})
}

func testAccComputeFirewallPolicyRule_multiple(context map[string]interface{}) string {
	return Nprintf(`
resource "google_folder" "folder" {
  display_name = "tf-test-folder-%{random_suffix}"
  parent       = "%{org_name}"
}

resource "google_compute_firewall_policy" "default" {
  parent      = google_folder.folder.name
  short_name  = "tf-test-policy-%{random_suffix}"
  description = "Resource created for Terraform acceptance testing"
}

resource "google_compute_firewall_policy_rule" "rule1" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9000
  enable_logging = true
  action = "allow"
  direction = "EGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports = [80, 8080]
    }
    dest_ip_ranges = ["11.100.0.1/32"]
  }
}

resource "google_compute_firewall_policy_rule" "rule2" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9001
  enable_logging = false
  action = "deny"
  direction = "INGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports = [80, 8080]
    }
    layer4_configs {
      ip_protocol = "all"
    }
    src_ip_ranges = ["11.100.0.1/32"]
  }
}
`, context)
}

func testAccComputeFirewallPolicyRule_multipleAdd(context map[string]interface{}) string {
	return Nprintf(`
resource "google_folder" "folder" {
  display_name = "tf-test-folder-%{random_suffix}"
  parent       = "%{org_name}"
}

resource "google_compute_firewall_policy" "default" {
  parent      = google_folder.folder.id
  short_name  = "tf-test-policy-%{random_suffix}"
  description = "Description Update"
}

resource "google_compute_firewall_policy_rule" "rule1" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9000
  enable_logging = true
  action = "allow"
  direction = "EGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
    }
    dest_ip_ranges = ["11.100.0.1/32"]
  }
}

resource "google_compute_firewall_policy_rule" "rule2" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9001
  enable_logging = false
  action = "deny"
  direction = "INGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports = [80, 8080]
    }
    layer4_configs {
      ip_protocol = "all"
    }
    src_ip_ranges = ["11.100.0.1/32"]
  }
}

resource "google_compute_firewall_policy_rule" "rule3" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 40
  enable_logging = true
  action = "allow"
  direction = "INGRESS"
  disabled = true
  match {
    layer4_configs {
      ip_protocol = "udp"
      ports = [8000]
    }
    src_ip_ranges = ["11.100.0.1/32", "10.0.0.0/24"]
  }
}
`, context)
}

func testAccComputeFirewallPolicyRule_multipleRemove(context map[string]interface{}) string {
	return Nprintf(`
resource "google_folder" "folder" {
  display_name = "tf-test-folder-%{random_suffix}"
  parent       = "%{org_name}"
}

resource "google_compute_firewall_policy" "default" {
  parent      = google_folder.folder.name
  short_name  = "tf-test-policy-%{random_suffix}"
  description = "Resource created for Terraform acceptance testing"
}

resource "google_compute_firewall_policy_rule" "rule1" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 9000
  enable_logging = true
  action = "allow"
  direction = "EGRESS"
  disabled = false
  match {
    layer4_configs {
      ip_protocol = "tcp"
      ports = [80, 8080]
    }
    dest_ip_ranges = ["11.100.0.1/32"]
  }
}

resource "google_compute_firewall_policy_rule" "rule3" {
  firewall_policy = google_compute_firewall_policy.default.id
  description = "Resource created for Terraform acceptance testing"
  priority = 40
  enable_logging = true
  action = "allow"
  direction = "INGRESS"
  disabled = true
  match {
    layer4_configs {
      ip_protocol = "udp"
      ports = [8000]
    }
    src_ip_ranges = ["11.100.0.1/32", "10.0.0.0/24"]
  }
}
`, context)
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="nesterenya.com.psychologicaltests.TestActivity">

    <TextView
        android:text="Отвечайте на вопросы:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_result_extra"
        android:textSize="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Txt"
        android:id="@+id/tv_question"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/linearLayout"
        android:layout_below="@+id/layout_banner" />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_alignRight="@+id/tv_question"
        android:layout_alignEnd="@+id/tv_question"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tv_result_extra"
        android:id="@+id/layout_banner"></LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/tv_question"
        android:layout_alignEnd="@+id/tv_question"
        android:id="@+id/linearLayout">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:text="Нет"
            android:id="@+id/btn_negative"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_weight="0.5" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:text="Да"
            android:id="@+id/btn_positive"
            android:layout_toEndOf="@+id/btn_negative"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_weight="0.5" />
    </LinearLayout>

</RelativeLayout>


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

namespace System.Net.Http.Formatting
{
    internal enum MediaTypeHeaderValueRange
    {
        /// <summary>
        /// Not a media type range
        /// </summary>
        None = 0,

        /// <summary>
        /// A subtype media range, e.g. "application/*".
        /// </summary>
        SubtypeMediaRange,

        /// <summary>
        /// An all media range, e.g. "*/*".
        /// </summary>
        AllMediaRange,
    }
}


text:
module Q39 where

import Q31

primesR :: Int -> Int -> [Int]
primesR x y = case (tryPrimesR x y) of Left result   -> result
                                       Right message -> error message

tryPrimesR :: Int -> Int -> Either [Int] String
tryPrimesR x y
  | x <= 0    = Right "x <= 0 is not supported"
  | x > y     = Right "x > y is not supported"
  | otherwise = Left (filter (isPrime) [x..y])


text:
class User
  include Mongoid::Document
  include Authority::UserAbilities
  rolify
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me

  ## Database authenticatable
  field :username,           type: String, default: ""
  field :email,              type: String, default: ""
  field :encrypted_password, type: String, default: ""

  ## Recoverable
  field :reset_password_token,   type: String
  field :reset_password_sent_at, type: Time

  ## Rememberable
  field :remember_created_at, type: Time

  ## Trackable
  field :sign_in_count,      type: Integer, default: 0
  field :current_sign_in_at, type: Time
  field :last_sign_in_at,    type: Time
  field :current_sign_in_ip, type: String
  field :last_sign_in_ip,    type: String

  ## Confirmable
  # field :confirmation_token,   type: String
  # field :confirmed_at,         type: Time
  # field :confirmation_sent_at, type: Time
  # field :unconfirmed_email,    type: String # Only if using reconfirmable

  ## Lockable
  # field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
  # field :unlock_token,    type: String # Only if unlock strategy is :email or :both
  # field :locked_at,       type: Time

  embeds_many :events
  has_and_belongs_to_many :read_books, class_name: 'Book', inverse_of: :read_by
  has_and_belongs_to_many :currently_reading, class_name: 'Book', inverse_of: :currently_read_by
  has_and_belongs_to_many :library, class_name: 'Book', inverse_of: :in_library_of

  def in_library?( book )
    book.is_a?( Book ) ? self.library_ids.include?(book.id) : self.library.where( isbn: book.isbn ).count > 0
  end
end


text:
var path = require('path');

describe("Linked List", function() {
  var data = '';

  beforeEach(function(done) {
    neutrino.run(path.resolve('./examples/linkedlist/test.neu'), function(result) {
      data = result;
      done();
    });
  });

  it("should parse a linked list", function(done) {
    data = data.split('\n');
      expect(parseInt(data[0])).toEqual(2046);
      expect(parseInt(data[1])).toEqual(2042);
      expect(parseInt(data[2])).toEqual(2038);
      expect(data[3]).toEqual('Node at address: 2046, has value: 1');
      expect(data[4]).toEqual('Node at address: 2042, has value: 2');
      expect(data[5]).toEqual('Node at address: 2038, has value: 3');
      done();
  });

});


text:
use super::backend::{Sqlite, SqliteType};
use query_builder::{QueryBuilder, BuildQueryResult};
use types::HasSqlType;

pub struct SqliteQueryBuilder {
    pub sql: String,
    pub bind_params: Vec<(SqliteType, Option<Vec<u8>>)>,
}

impl SqliteQueryBuilder {
    pub fn new() -> Self {
        SqliteQueryBuilder {
            sql: String::new(),
            bind_params: Vec::new(),
        }
    }
}

impl QueryBuilder<Sqlite> for SqliteQueryBuilder {
    fn push_sql(&mut self, sql: &str) {
        self.sql.push_str(sql);
    }

    fn push_identifier(&mut self, identifier: &str) -> BuildQueryResult {
        self.push_sql("`");
        self.push_sql(&identifier.replace("`", "``"));
        self.push_sql("`");
        Ok(())
    }

    fn push_bound_value<T>(&mut self, bind: Option<Vec<u8>>) where
        Sqlite: HasSqlType<T>,
    {
        self.push_sql("?");
        self.bind_params.push((Sqlite::metadata(), bind));
    }
}


text:
use strict;
use warnings;
use Exporter;
use DBI;
use Asterisk::AGI;
use Config::Tiny;
use POSIX;
use lib '/var/lib/asterisk/agi-bin/fbilling-libs';
use Util;

## load data from configuration file
my $main_conf = Config::Tiny->new;
$main_conf = Config::Tiny->read('/etc/asterisk/fbilling.conf');
my $db_host = $main_conf->{database}->{host};
my $db_user = $main_conf->{database}->{username};
my $db_pass = $main_conf->{database}->{password};
my $db_name = $main_conf->{database}->{database};
my $debug_level = $main_conf->{general}->{log_level};
my $logfile = $main_conf->{general}->{log_location};

my $agi = Asterisk::AGI->new;
my $dbh = DBI->connect("dbi:mysql:$db_name:$db_host","$db_user","$db_pass");

############################################################################################
package Call;

# create new call instance
# requires cid, did, credit, tenant_id, permission_id, prefix_id, prefix_country (?), prefix, weight_id, tariff_cost
# returns self
sub new {
    my $class = shift;
    my $self = {};
    bless $self;
    $self->{"cid"} = shift;
    $self->{"did"} = shift;
    $self->{"account_credit"} = shift;
    $self->{"account_tennant_id"} = shift;
    $self->{"account_permission_id"} = shift;
    $self->{"prefix_id"} = shift;
    $self->{"prefix_prefix"} = shift;
    $self->{"prefix_country"} = shift;
    $self->{"prefix_weight_id"} = shift;
    $self->{"tariff_cost"} = shift;
    return $self;
}

# get maximum duration of call based on account and tariff data
# requires uniqueid
# returns array, containing maximum duration of call in seconds and milliseconds
sub max_duration {
    my $self = shift;
    my $uniqueid = shift;
    my @max_duration;
    my $max_durationms;         # maximum duration in ms, used for dialplan
    my $max_durationsec;        # maximum duration in seconds, used for check
    # see TODO section
    if ($self->{"tariff_cost"} == 0) {
        Util::log("NOTICE",$uniqueid,"This is free destination, proceeding...");
        @max_duration = (1800,1800000); # TODO make it pretty
    } else {
        $max_durationms = $max_durationsec = $self->{"account_credit"} / $self->{"tariff_cost"};
        $max_durationms = $max_durationms * 60000;
        $max_durationsec = $max_durationsec * 60;
        $max_durationms = int($max_durationms);
        $max_durationsec = int($max_durationsec);
        @max_duration = ($max_durationsec,$max_durationms);
    }
    return @max_duration;
}

# get permission data for this call
# requires uniqueid
# returns hash containing permission_id, permission_name, permission_is_active
sub get_permission_details {
    my $self = shift;
    my $uniqueid = shift;
    my %permission_details;
    my $query_get_permission_details = "SELECT * FROM billing_permissions where id = '$self->{account_permission_id}'";
    Util::log("NOTICE",$uniqueid,"Executing query to get permission details: $query_get_permission_details");
    my $sth_get_permission_details = $dbh->prepare($query_get_permission_details);
    $sth_get_permission_details->execute;
    my @row_get_permission_details = $sth_get_permission_details->fetchrow_array;
    if (scalar @row_get_permission_details == 0) {
        %permission_details = (
            "permission_id" => 0,
            "permission_name" => 0,
            "permission_is_active" => 0,
        );
    } else {
        %permission_details = (
            "permission_id" => $row_get_permission_details[0],
            "permission_name" => $row_get_permission_details[1],
            "permission_is_active" => $row_get_permission_details[2],
        );
    }
    return %permission_details;
}

# get if account has permission to make a call
# requires uniqueid
# returns 1 if account has ermision, 0 if not
sub get_permission {
    # see todo section of this file
    my $self = shift;
    my $uniqueid = shift;
    my $permission_ok = 1;
    my $query_get_permission = "SELECT * FROM billing_permission_weights WHERE permission_id = '$self->{account_permission_id}' AND weight_id = '$self->{prefix_weight_id}'";
    Util::log("NOTICE",$uniqueid,"Executing query to get permission: $query_get_permission");
    my $sth_get_permission = $dbh->prepare($query_get_permission);
    $sth_get_permission->execute;
    my @row_get_permission = $sth_get_permission->fetchrow_array;
    if (scalar @row_get_permission == 0) {
        $permission_ok = 0;
    }
    return $permission_ok;
}

# get cost based on tariff
# requires initial duration, cost
# returns call_cost
sub get_cost {
    my $self = shift;
    my $duration = shift;
    my $initial_cost = shift;
    $duration = $duration / 60;
    $duration = sprintf "%.2f", $duration;
    my $call_cost = $self->{"tariff_cost"} * $duration;
    $call_cost = $call_cost + $initial_cost;
    return $call_cost;
}

1;


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System.Collections.Generic;
using osu.Game.Rulesets.Replays;

namespace osu.Game.Rulesets.EmptyScrolling.Replays
{
    public class EmptyScrollingReplayFrame : ReplayFrame
    {
        public List<EmptyScrollingAction> Actions = new List<EmptyScrollingAction>();

        public EmptyScrollingReplayFrame(EmptyScrollingAction? button = null)
        {
            if (button.HasValue)
                Actions.Add(button.Value);
        }
    }
}


text:
package org.zeeman.thrifts.client;

import org.apache.commons.lang3.StringUtils;
import org.zeeman.thrifts.common.ThriftSException;
import org.zeeman.thrifts.common.Utils;
import org.zeeman.thrifts.common.annotations.ThriftSContract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * ThriftS client
 */
public class ThriftSClient {
    private final static Logger LOGGER = LoggerFactory.getLogger(ThriftSClient.class);

    private String host;
    private int port;
    private int timeout;

    /**
     * Initializes a new instance of the ThriftSClient class.
     *
     * @param host
     * @param port
     */
    public ThriftSClient(String host, int port) {
        this(host, port, 120);
    }

    /**
     * Initializes a new instance of the ThriftSClient class.
     *
     * @param host
     * @param port
     * @param timeout
     */
    public ThriftSClient(String host, int port, int timeout) {
        this.setHost(host);
        this.setPort(port);
        this.setTimeout(timeout);
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    /**
     * Create proxy
     *
     * @param contractType
     * @return
     */
    public Object createProxy(Class<?> contractType) throws ThriftSException {
        ThriftSContract contractAnnotation = contractType.getAnnotation(ThriftSContract.class);
        if (contractAnnotation == null) {
            throw new ThriftSException(String.format("Missing annotation(ThriftXContract) in '%s'.", contractType.getName()));
        }

        String serviceName = Utils.getServiceName(contractType);
        String serviceShortName = serviceName;

        if (StringUtils.isEmpty(serviceName)) {
            serviceName = contractType.getName();
            serviceShortName = contractType.getSimpleName();
        }

        LOGGER.debug("find service: {}", serviceName);

        InvocationHandler handler = new ThriftSRealProxy(this.getHost(),
                this.getPort(), serviceName, serviceShortName, this.getTimeout());

        return Proxy.newProxyInstance(handler.getClass().getClassLoader(),
                new Class[]{contractType}, handler);

    }

}


text:
export default function walk (parent, callback) {
    parent.nodes.forEach((node, index) => {
        const bubble = callback(node, index, parent);
        if (node.nodes && bubble !== false) {
            walk(node, callback);
        }
    });
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<java version="1.5.0_13" class="java.beans.XMLDecoder">
 <object class="org.apache.hadoop.hive.ql.plan.mapredWork">
  <void property="aliasToWork">
   <object class="java.util.HashMap">
    <void method="put">
     <string>src</string>
     <object class="org.apache.hadoop.hive.ql.exec.ForwardOperator">
      <void property="childOperators">
       <object class="java.util.ArrayList">
        <void method="add">
         <object class="org.apache.hadoop.hive.ql.exec.FilterOperator">
          <void property="childOperators">
           <object class="java.util.ArrayList">
            <void method="add">
             <object class="org.apache.hadoop.hive.ql.exec.SelectOperator">
              <void property="childOperators">
               <object class="java.util.ArrayList">
                <void method="add">
                 <object class="org.apache.hadoop.hive.ql.exec.FileSinkOperator">
                  <void property="conf">
                   <object class="org.apache.hadoop.hive.ql.plan.fileSinkDesc">
                    <void property="dirName">
                     <string>/tmp/dest1-1187471701</string>
                    </void>
                    <void property="properties">
                     <object class="java.util.Properties">
                      <void method="put">
                       <string>name</string>
                       <string>dest1</string>
                      </void>
                      <void method="put">
                       <string>serde</string>
                       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                      </void>
                      <void method="put">
                       <string>bucket_field_name</string>
                       <string></string>
                      </void>
                      <void method="put">
                       <string>serialization.format</string>
                       <string></string>
                      </void>
                      <void method="put">
                       <string>columns</string>
                       <string>key,value</string>
                      </void>
                      <void method="put">
                       <string>serialization.class</string>
                       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                      </void>
                      <void method="put">
                       <string>field_to_dimension</string>
                       <string></string>
                      </void>
                      <void method="put">
                       <string>bucket_count</string>
                       <string>-1</string>
                      </void>
                      <void method="put">
                       <string>serialization.lib</string>
                       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                      </void>
                      <void method="put">
                       <string>location</string>
                       <string>hdfs://hadooptest001.sf2p.facebook.com:9000/warehouse//dest1</string>
                      </void>
                     </object>
                    </void>
                    <void property="serdeClassName">
                     <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                    </void>
                   </object>
                  </void>
                 </object>
                </void>
               </object>
              </void>
              <void property="conf">
               <object class="org.apache.hadoop.hive.ql.plan.selectDesc">
                <void property="colList">
                 <object class="java.util.ArrayList">
                  <void method="add">
                   <object class="org.apache.hadoop.hive.ql.plan.expressionDesc">
                    <void property="exprType">
                     <string>FIELD</string>
                    </void>
                    <void property="fieldexpr">
                     <string>0.key</string>
                    </void>
                   </object>
                  </void>
                  <void method="add">
                   <object class="org.apache.hadoop.hive.ql.plan.expressionDesc">
                    <void property="exprType">
                     <string>FIELD</string>
                    </void>
                    <void property="fieldexpr">
                     <string>0.value</string>
                    </void>
                   </object>
                  </void>
                 </object>
                </void>
               </object>
              </void>
             </object>
            </void>
           </object>
          </void>
          <void property="conf">
           <object class="org.apache.hadoop.hive.ql.plan.filterDesc">
            <void property="predicate">
             <object class="org.apache.hadoop.hive.ql.plan.JEXLExpressionDesc">
              <void property="expression">
               <string> ( F_0 < 100)</string>
              </void>
              <void property="variableMap">
               <object class="java.util.HashMap">
                <void method="put">
                 <string>F_0</string>
                 <string>0.key</string>
                </void>
               </object>
              </void>
             </object>
            </void>
           </object>
          </void>
         </object>
        </void>
        <void method="add">
         <object class="org.apache.hadoop.hive.ql.exec.FilterOperator">
          <void property="childOperators">
           <object class="java.util.ArrayList">
            <void method="add">
             <object class="org.apache.hadoop.hive.ql.exec.SelectOperator">
              <void property="childOperators">
               <object class="java.util.ArrayList">
                <void method="add">
                 <object class="org.apache.hadoop.hive.ql.exec.FileSinkOperator">
                  <void property="conf">
                   <object class="org.apache.hadoop.hive.ql.plan.fileSinkDesc">
                    <void property="dirName">
                     <string>/tmp/dest21982641932</string>
                    </void>
                    <void property="properties">
                     <object class="java.util.Properties">
                      <void method="put">
                       <string>name</string>
                       <string>dest2</string>
                      </void>
                      <void method="put">
                       <string>serde</string>
                       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                      </void>
                      <void method="put">
                       <string>bucket_field_name</string>
                       <string></string>
                      </void>
                      <void method="put">
                       <string>serialization.format</string>
                       <string></string>
                      </void>
                      <void method="put">
                       <string>columns</string>
                       <string>key,value</string>
                      </void>
                      <void method="put">
                       <string>serialization.class</string>
                       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                      </void>
                      <void method="put">
                       <string>field_to_dimension</string>
                       <string></string>
                      </void>
                      <void method="put">
                       <string>bucket_count</string>
                       <string>-1</string>
                      </void>
                      <void method="put">
                       <string>serialization.lib</string>
                       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                      </void>
                      <void method="put">
                       <string>location</string>
                       <string>hdfs://hadooptest001.sf2p.facebook.com:9000/warehouse//dest2</string>
                      </void>
                     </object>
                    </void>
                    <void property="serdeClassName">
                     <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
                    </void>
                   </object>
                  </void>
                 </object>
                </void>
               </object>
              </void>
              <void property="conf">
               <object class="org.apache.hadoop.hive.ql.plan.selectDesc">
                <void property="colList">
                 <object class="java.util.ArrayList">
                  <void method="add">
                   <object class="org.apache.hadoop.hive.ql.plan.expressionDesc">
                    <void property="exprType">
                     <string>FIELD</string>
                    </void>
                    <void property="fieldexpr">
                     <string>0.value</string>
                    </void>
                   </object>
                  </void>
                 </object>
                </void>
               </object>
              </void>
             </object>
            </void>
           </object>
          </void>
          <void property="conf">
           <object class="org.apache.hadoop.hive.ql.plan.filterDesc">
            <void property="predicate">
             <object class="org.apache.hadoop.hive.ql.plan.JEXLExpressionDesc">
              <void property="expression">
               <string> ( F_0 >= 100)</string>
              </void>
              <void property="variableMap">
               <object class="java.util.HashMap">
                <void method="put">
                 <string>F_0</string>
                 <string>0.key</string>
                </void>
               </object>
              </void>
             </object>
            </void>
           </object>
          </void>
         </object>
        </void>
       </object>
      </void>
     </object>
    </void>
   </object>
  </void>
  <void property="moveWork">
   <object class="java.util.HashMap">
    <void method="put">
     <string>/tmp/dest1-1187471701</string>
     <string>/warehouse/dest1</string>
    </void>
    <void method="put">
     <string>/tmp/dest21982641932</string>
     <string>/warehouse/dest2</string>
    </void>
   </object>
  </void>
  <void property="pathToAliases">
   <object class="java.util.HashMap">
    <void method="put">
     <string>/warehouse/src</string>
     <object class="java.util.ArrayList">
      <void method="add">
       <string>src</string>
      </void>
     </object>
    </void>
   </object>
  </void>
  <void property="pathToTableInfo">
   <object class="java.util.HashMap">
    <void method="put">
     <string>/warehouse/src</string>
     <object class="org.apache.hadoop.hive.ql.plan.tableDesc">
      <void property="properties">
       <object class="java.util.Properties">
        <void method="put">
         <string>name</string>
         <string>src</string>
        </void>
        <void method="put">
         <string>serde</string>
         <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
        </void>
        <void method="put">
         <string>bucket_field_name</string>
         <string></string>
        </void>
        <void method="put">
         <string>serialization.format</string>
         <string></string>
        </void>
        <void method="put">
         <string>columns</string>
         <string>key,value</string>
        </void>
        <void method="put">
         <string>serialization.class</string>
         <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
        </void>
        <void method="put">
         <string>field_to_dimension</string>
         <string></string>
        </void>
        <void method="put">
         <string>bucket_count</string>
         <string>-1</string>
        </void>
        <void method="put">
         <string>serialization.lib</string>
         <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
        </void>
        <void method="put">
         <string>location</string>
         <string>hdfs://hadooptest001.sf2p.facebook.com:9000/warehouse//src</string>
        </void>
       </object>
      </void>
      <void property="serdeClassName">
       <string>org.apache.hadoop.hive.serde.simple_meta.MetadataTypedColumnsetSerDe</string>
      </void>
     </object>
    </void>
   </object>
  </void>
 </object>
</java>


text:
// Type definitions for react-split-pane v0.1.64
// Project: https://github.com/tomkp/react-split-pane
// Definitions by: Roger Chen <https://github.com/rcchen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

/// <reference types="react"/>

declare namespace ReactSplitPane {
    interface ReactSplitPaneProps {
        allowResize?: boolean;
        className?: string;
        /**
         * Either a number (in pixels) or string (percentage)
         */
        defaultSize?: number | string;
        /**
         * Either a number (in pixels) or string (percentage)
         */
        maxSize?: number | string;
        /**
         * Either a number (in pixels) or string (percentage)
         */
        minSize?: number | string;
        onChange?: Function;
        onDragFinished?: Function;
        onDragStarted?: Function;
        primary?: string;
        onResizerClick?: Function;
        onResizerDoubleClick?: Function;

        /**
         * Either a number (in pixels) or string (percentage)
         */
        size?: number | string;
        split?: string;
        step?: number;
        /* Styling to be applied to both panes */
        paneStyle?: React.CSSProperties;
        /* Styling to be applied to the first pane, with precedence over paneStyle */
        pane1Style?: React.CSSProperties;
        /* Styling to be applied to the second pane, with precedence over paneStyle */
        pane2Style?: React.CSSProperties;
        /* Class name to be applied to resizer bar */
        resizerClassName?: string;
        /* Styling to be applied to the resizer bar */
        resizerStyle?: React.CSSProperties;
    }

    interface ReactSplitPaneClass extends React.ComponentClass<ReactSplitPaneProps> { }
}

declare module "react-split-pane" {
    var split: ReactSplitPane.ReactSplitPaneClass;
    export = split;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/easy_youtube.iml" filepath="$PROJECT_DIR$/easy_youtube.iml" />
      <module fileurl="file://$PROJECT_DIR$/easy_youtube_library/easy_youtube_library.iml" filepath="$PROJECT_DIR$/easy_youtube_library/easy_youtube_library.iml" />
      <module fileurl="file://$PROJECT_DIR$/easy_youtube_sample/easy_youtube_sample.iml" filepath="$PROJECT_DIR$/easy_youtube_sample/easy_youtube_sample.iml" />
    </modules>
  </component>
</project>


text:
"""All public modules of FedLearner."""

from fedlearner import common
from fedlearner import data_join
from fedlearner import proxy
from fedlearner import trainer
from fedlearner import fedavg


text:
<?xml version="1.0" encoding="UTF-8"?>
<testResults version="1.2">
<sample s="true" lb="JDBC_DROP_TABLE" rc="42501 -5501" rm="java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: USERS in statement [drop table USERS]" tn="setUp Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>RA_IgnoreError</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
</sample>
<sample s="true" lb="JDBC_CREATE_TABLE" rc="200" rm="OK" tn="setUp Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>RA_IgnoreError</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
</sample>
<sample s="true" lb="JDBC_INSERT" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
</sample>
<sample s="true" lb="JDBC_SELECT" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>JA_checkResult</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <sample s="true" lb="Debug PostProcessor" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="0" na="0"/>
</sample>
<sample s="true" lb="JDBC_SELECT_PREPARED" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <assertionResult>
    <name>JA_checkResult</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <sample s="true" lb="Debug PostProcessor" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="0" na="0"/>
</sample>
<sample s="true" lb="JDBC_COMMIT" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1"/>
<sample s="true" lb="JDBC_INSERT_VICTOR_HUGO" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>Response Assertion</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <sample s="true" lb="Debug PostProcessor" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="0" na="0"/>
</sample>
<sample s="true" lb="JDBC_CHECK_COUNT_2" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>JA_checkResult</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <sample s="true" lb="Debug PostProcessor" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="0" na="0"/>
</sample>
<sample s="true" lb="JDBC_ROLLBACK" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1"/>
<sample s="true" lb="JDBC_CHECK_COUNT_1" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="1" na="1">
  <assertionResult>
    <name>JA_checkResult</name>
    <failure>false</failure>
    <error>false</error>
  </assertionResult>
  <sample s="true" lb="Debug PostProcessor" rc="200" rm="OK" tn="Thread Group 1-1" dt="text" sc="1" ec="0" ng="0" na="0"/>
</sample>
<sample s="true" lb="CheckTransaction" rc="200" rm="Number of samples in transaction : 4, number of failing samples : 0" tn="Thread Group 1-1" dt="" sc="1" ec="0" ng="1" na="1"/>

</testResults>


text:
package org.jasig.cas.mock;

import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.ExpirationPolicy;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.util.DefaultUniqueTicketIdGenerator;
import org.jasig.cas.util.UniqueTicketIdGenerator;

import java.util.Date;

/**
 * Mock service ticket.
 *
 * @author Marvin S. Addison
 * @version $Revision: $
 */
public class MockServiceTicket implements ServiceTicket {
    private static final UniqueTicketIdGenerator ID_GENERATOR = new DefaultUniqueTicketIdGenerator();

    private final String id;

    private final Date created;

    private final Service service;

    private final TicketGrantingTicket parent;

    public MockServiceTicket(final String id, final Service service, final TicketGrantingTicket parent) {
        this.service = service;
        this.id = id;
        this.parent = parent;
        created = new Date();
    }

    public Service getService() {
        return service;
    }

    public boolean isFromNewLogin() {
        return false;
    }

    public boolean isValidFor(final Service service) {
        return this.service.equals(service);
    }

    public TicketGrantingTicket grantTicketGrantingTicket(
            final String id,
            final Authentication authentication,
            final ExpirationPolicy expirationPolicy) {
        return null;
    }

    public String getId() {
        return id;
    }

    public boolean isExpired() {
        return false;
    }

    public TicketGrantingTicket getGrantingTicket() {
        return parent;
    }

    public long getCreationTime() {
        return created.getTime();
    }

    public int getCountOfUses() {
        return 0;
    }
}


text:
package disk

import (
	"bytes"
	"context"
	"encoding/binary"

	"github.com/shirou/gopsutil/v3/internal/common"
	"golang.org/x/sys/unix"
)

func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) {
	var ret []PartitionStat

	// get length
	count, err := unix.Getfsstat(nil, unix.MNT_WAIT)
	if err != nil {
		return ret, err
	}

	fs := make([]unix.Statfs_t, count)
	if _, err = unix.Getfsstat(fs, unix.MNT_WAIT); err != nil {
		return ret, err
	}

	for _, stat := range fs {
		opts := []string{"rw"}
		if stat.F_flags&unix.MNT_RDONLY != 0 {
			opts = []string{"rw"}
		}
		if stat.F_flags&unix.MNT_SYNCHRONOUS != 0 {
			opts = append(opts, "sync")
		}
		if stat.F_flags&unix.MNT_NOEXEC != 0 {
			opts = append(opts, "noexec")
		}
		if stat.F_flags&unix.MNT_NOSUID != 0 {
			opts = append(opts, "nosuid")
		}
		if stat.F_flags&unix.MNT_NODEV != 0 {
			opts = append(opts, "nodev")
		}
		if stat.F_flags&unix.MNT_ASYNC != 0 {
			opts = append(opts, "async")
		}
		if stat.F_flags&unix.MNT_SOFTDEP != 0 {
			opts = append(opts, "softdep")
		}
		if stat.F_flags&unix.MNT_NOATIME != 0 {
			opts = append(opts, "noatime")
		}
		if stat.F_flags&unix.MNT_WXALLOWED != 0 {
			opts = append(opts, "wxallowed")
		}

		d := PartitionStat{
			Device:     common.IntToString(stat.F_mntfromname[:]),
			Mountpoint: common.IntToString(stat.F_mntonname[:]),
			Fstype:     common.IntToString(stat.F_fstypename[:]),
			Opts:       opts,
		}

		ret = append(ret, d)
	}

	return ret, nil
}

func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) {
	ret := make(map[string]IOCountersStat)

	r, err := unix.SysctlRaw("hw.diskstats")
	if err != nil {
		return nil, err
	}
	buf := []byte(r)
	length := len(buf)

	count := int(uint64(length) / uint64(sizeOfDiskstats))

	// parse buf to Diskstats
	for i := 0; i < count; i++ {
		b := buf[i*sizeOfDiskstats : i*sizeOfDiskstats+sizeOfDiskstats]
		d, err := parseDiskstats(b)
		if err != nil {
			continue
		}
		name := common.IntToString(d.Name[:])

		if len(names) > 0 && !common.StringsHas(names, name) {
			continue
		}

		ds := IOCountersStat{
			ReadCount:  d.Rxfer,
			WriteCount: d.Wxfer,
			ReadBytes:  d.Rbytes,
			WriteBytes: d.Wbytes,
			Name:       name,
		}
		ret[name] = ds
	}

	return ret, nil
}

// BT2LD(time)     ((long double)(time).sec + (time).frac * BINTIME_SCALE)

func parseDiskstats(buf []byte) (Diskstats, error) {
	var ds Diskstats
	br := bytes.NewReader(buf)
	//	err := binary.Read(br, binary.LittleEndian, &ds)
	err := common.Read(br, binary.LittleEndian, &ds)
	if err != nil {
		return ds, err
	}

	return ds, nil
}

func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
	stat := unix.Statfs_t{}
	err := unix.Statfs(path, &stat)
	if err != nil {
		return nil, err
	}
	bsize := stat.F_bsize

	ret := &UsageStat{
		Path:        path,
		Fstype:      getFsType(stat),
		Total:       (uint64(stat.F_blocks) * uint64(bsize)),
		Free:        (uint64(stat.F_bavail) * uint64(bsize)),
		InodesTotal: (uint64(stat.F_files)),
		InodesFree:  (uint64(stat.F_ffree)),
	}

	ret.InodesUsed = (ret.InodesTotal - ret.InodesFree)
	ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0
	ret.Used = (uint64(stat.F_blocks) - uint64(stat.F_bfree)) * uint64(bsize)
	ret.UsedPercent = (float64(ret.Used) / float64(ret.Total)) * 100.0

	return ret, nil
}

func getFsType(stat unix.Statfs_t) string {
	return common.IntToString(stat.F_fstypename[:])
}

func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
	return "", common.ErrNotImplementedError
}

func LabelWithContext(ctx context.Context, name string) (string, error) {
	return "", common.ErrNotImplementedError
}


text:
class Artisjokke_drawer2 : public Artisjokke_drawer
{
public:
  Maubach_tree * tree  () const ;
  Needle_inserter * needle_inserter_;

  Artisjokke_drawer2(Mesh_connectivity *top, Deformation_state*def);

protected:
  virtual void opengl_visualize_mesh_connectivity();
  virtual void set_needle ();
  virtual void process_key (char );
  virtual void draw_needle ();

};

#endif
#endif


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.displayvideo.v1.model;

/**
 * Model definition for ListInsertionOrdersResponse.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Display & Video 360 API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ListInsertionOrdersResponse extends com.google.api.client.json.GenericJson {

  /**
   * The list of insertion orders. This list will be absent if empty.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<InsertionOrder> insertionOrders;

  static {
    // hack to force ProGuard to consider InsertionOrder used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(InsertionOrder.class);
  }

  /**
   * A token to retrieve the next page of results. Pass this value in the page_token field in the
   * subsequent call to `ListInsertionOrders` method to retrieve the next page of results.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String nextPageToken;

  /**
   * The list of insertion orders. This list will be absent if empty.
   * @return value or {@code null} for none
   */
  public java.util.List<InsertionOrder> getInsertionOrders() {
    return insertionOrders;
  }

  /**
   * The list of insertion orders. This list will be absent if empty.
   * @param insertionOrders insertionOrders or {@code null} for none
   */
  public ListInsertionOrdersResponse setInsertionOrders(java.util.List<InsertionOrder> insertionOrders) {
    this.insertionOrders = insertionOrders;
    return this;
  }

  /**
   * A token to retrieve the next page of results. Pass this value in the page_token field in the
   * subsequent call to `ListInsertionOrders` method to retrieve the next page of results.
   * @return value or {@code null} for none
   */
  public java.lang.String getNextPageToken() {
    return nextPageToken;
  }

  /**
   * A token to retrieve the next page of results. Pass this value in the page_token field in the
   * subsequent call to `ListInsertionOrders` method to retrieve the next page of results.
   * @param nextPageToken nextPageToken or {@code null} for none
   */
  public ListInsertionOrdersResponse setNextPageToken(java.lang.String nextPageToken) {
    this.nextPageToken = nextPageToken;
    return this;
  }

  @Override
  public ListInsertionOrdersResponse set(String fieldName, Object value) {
    return (ListInsertionOrdersResponse) super.set(fieldName, value);
  }

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

}


text:
package com.boztalay.battleship.cli;

import com.boztalay.battleship.engine.BattleshipEngine;
import com.boztalay.battleship.engine.Field;
import com.boztalay.battleship.engine.Player;
import com.boztalay.battleship.engine.Ship;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * Responsible mainly for handling user interaction
 * and running the game loop.
 */
public class BattleshipCLI {
    private static final int FIELD_SIZE = 10;
    private static final int NUM_PLAYERS = 2;

    private BattleshipEngine battleshipEngine;

    public void playBattleship() throws IOException, BattleshipEngine.WrongStateException {
        System.out.println("Welcome to Battleship!\n");

        initializeBattleshipEngineAndCreatePlayers();
        placeShips();
        playGame();
    }

    private void initializeBattleshipEngineAndCreatePlayers() throws BattleshipEngine.WrongStateException {
        battleshipEngine = new BattleshipEngine();
        battleshipEngine.setFieldSize(FIELD_SIZE);
        battleshipEngine.addShipTypeToPlace(Ship.ShipType.CARRIER);
        battleshipEngine.addShipTypeToPlace(Ship.ShipType.BATTLESHIP);
        battleshipEngine.addShipTypeToPlace(Ship.ShipType.SUBMARINE);
        battleshipEngine.addShipTypeToPlace(Ship.ShipType.CRUISER);
        battleshipEngine.addShipTypeToPlace(Ship.ShipType.DESTROYER);

        for(int i = 1; i <= NUM_PLAYERS; i++) {
            System.out.print("Player " + i + ", what's your name? ");
            String playerName = ConsoleUtils.readLine();
            battleshipEngine.createPlayer(playerName);
        }
    }

    private void placeShips() throws BattleshipEngine.WrongStateException {
        battleshipEngine.beginPlacement();

        while(!battleshipEngine.haveAllPlayersFinishedPlacing()) {
            battleshipEngine.startPlacingShipsForNextPlayer();
            Player player = battleshipEngine.getPlayerPlacingShips();

            System.out.println("\n" + player.getName() + ", place your ships!");
            System.out.println("For each ship, specify its placement with \"x,y,orientation\"");
            System.out.println("For example, a vertical ship at 2,2 would be \"2,2," + Ship.ShipOrientation.VERTICAL.shortName + "\". Use '" + Ship.ShipOrientation.HORIZONTAL.shortName + "' for horizontal.");
            System.out.println("Press enter to continue");
            ConsoleUtils.waitForUserToPressEnter();

            placeShipsForCurrentPlayer(player);

            FieldDisplay.displayFieldForPlayer(player);
            System.out.println("All of your ships have been placed! Press enter to continue");
            ConsoleUtils.waitForUserToPressEnter();

            ConsoleUtils.clearConsole();
        }
    }

    private void placeShipsForCurrentPlayer(Player player) throws BattleshipEngine.WrongStateException {
        while(!battleshipEngine.hasPlayerFinishedPlacing()) {
            Ship.ShipType shipTypeToPlace = battleshipEngine.getNextShipTypeToPlace();
            FieldDisplay.displayFieldForPlayer(player);

            while(true) {
                System.out.print("Place your " + shipTypeToPlace.name + " at: ");
                String placement = ConsoleUtils.readLine();

                try {
                    if(!isPlacementStringValid(placement)) {
                        throw new Field.InvalidShipPlacementException();
                    } else {
                        Ship shipToPlace = parsePlacementStringIntoShip(placement, shipTypeToPlace);
                        battleshipEngine.placeShipForCurrentPlayer(shipToPlace);
                        break;
                    }
                } catch(Field.InvalidShipPlacementException e) {
                    System.out.println("That wasn't a valid placement!");
                }
            }

            System.out.println();
        }
    }

    private void playGame() throws BattleshipEngine.WrongStateException {
        battleshipEngine.beginPlaying();

        while(true) {
            battleshipEngine.prepareForRound();

            while(!battleshipEngine.haveAllPlayersTakenTheirTurn()) {
                battleshipEngine.startNextPlayersTurn();
                Player playerGoing = battleshipEngine.getPlayerTakingTurn();

                if(playerGoing.areAllShipsSunk()) {
                    continue;
                }

                playTurnForCurrentPlayer(playerGoing);

                ConsoleUtils.clearConsole();

                Player winningPlayer = battleshipEngine.getWinningPlayer();
                if(winningPlayer != null) {
                    displayWinner(winningPlayer);
                    return;
                }
            }
        }
    }

    private void playTurnForCurrentPlayer(Player playerGoing) throws BattleshipEngine.WrongStateException {
        System.out.println(playerGoing.getName() + ", you're up! Press enter to continue");
        ConsoleUtils.waitForUserToPressEnter();

        while(!battleshipEngine.haveAllEnemyPlayersBeenFiredUpon()) {
            battleshipEngine.advanceToNextEnemyPlayer();
            Player enemyPlayer = battleshipEngine.getCurrentEnemyPlayer();

            if(enemyPlayer.areAllShipsSunk()) {
                continue;
            }

            fireAtCurrentEnemy(playerGoing, enemyPlayer);
        }
    }

    private void fireAtCurrentEnemy(Player playerGoing, Player enemyPlayer) throws BattleshipEngine.WrongStateException {
        FieldDisplay.displayFieldForPlayer(playerGoing);
        System.out.println();
        FieldDisplay.displayFieldForPlayerWithoutShips(enemyPlayer);

        while(true) {
            System.out.print("Enter the coordinate to fire at (x,y): ");
            String coordinate = ConsoleUtils.readLine();

            try {
                if(!isShotCoordinateStringValid(coordinate)) {
                    throw new Field.InvalidShotException();
                }

                String[] coordinateComponents = coordinate.split(",");
                int shotX = Integer.valueOf(coordinateComponents[0]);
                int shotY = Integer.valueOf(coordinateComponents[1]);

                Ship shipHit = battleshipEngine.fireOnCurrentEnemyPlayerAt(shotX, shotY);

                System.out.println();
                if(shipHit != null) {
                    System.out.println("That was a hit!");
                    if(shipHit.isSunk()) {
                        System.out.println("You sunk " + enemyPlayer.getName() + "'s " + shipHit.getName() + "!");
                    }
                } else {
                    System.out.println("That was a miss!");
                }

                System.out.println("Press enter to continue");
                ConsoleUtils.waitForUserToPressEnter();

                break;
            } catch(Field.InvalidShotException e) {
                System.out.println("That wasn't a valid shot!");
            }
        }
    }

    private boolean isPlacementStringValid(String placement) {
        return Pattern.matches("[0-9]+,[0-9]+,(" + Ship.ShipOrientation.HORIZONTAL.shortName + "|" + Ship.ShipOrientation.VERTICAL.shortName + ")", placement);
    }

    private Ship parsePlacementStringIntoShip(String placement, Ship.ShipType shipType) {
        String[] placementComponents = placement.split(",");

        int shipX = Integer.valueOf(placementComponents[0]);
        int shipY = Integer.valueOf(placementComponents[1]);

        Ship.ShipOrientation shipOrientation = Ship.ShipOrientation.HORIZONTAL;
        if(placementComponents[2].equals(String.valueOf(Ship.ShipOrientation.VERTICAL.shortName))) {
            shipOrientation = Ship.ShipOrientation.VERTICAL;
        }

        return new Ship(shipX, shipY, shipOrientation, shipType);
    }

    private boolean isShotCoordinateStringValid(String coordinate) {
        return Pattern.matches("[0-9]+,[0-9]+", coordinate);
    }

    private void displayWinner(Player winner) {
        System.out.println(winner.getName() + " won! Congrats!\n");

        for(Player player : battleshipEngine.getPlayers()) {
            FieldDisplay.displayFieldForPlayer(player);
            System.out.println();
        }
    }
}


text:
cask "league-of-legends" do
  version "1.0"
  sha256 :no_check

  url "https://lol.secure.dyn.riotcdn.net/channels/public/x/installer/current/live.na.zip",
      verified: "lol.secure.dyn.riotcdn.net/"
  name "League of Legends"
  desc "Multiplayer online battle arena game"
  homepage "https://na.leagueoflegends.com/en-us/"

  livecheck do
    skip "unversioned URL"
  end

  installer manual: "Install League of Legends na.app"

  uninstall delete: "/Applications/League of Legends.app"

  zap trash: [
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.riotgames.maccontainer.sfl*",
    "~/Library/Application Support/Riot Games/Install League of Legends",
    "~/Library/Application Support/Riot Games/League of Legends",
    "~/Library/Caches/com.riotgames.LeagueofLegends.LeagueClient",
    "~/Library/Logs/Riot Games/Install League of Legends na",
    "~/Library/Preferences/com.riotgames.LeagueofLegends.LeagueClientUxHelper.plist",
    "~/Library/Saved Application State/com.riotgames.LeagueofLegends.GameClient.savedState",
    "~/Library/Saved Application State/com.riotgames.LeagueofLegends.LeagueClientUx.savedState",
    "/Users/Shared/Riot Games/Metadata/league_of_legends.live.game_patch",
    "/Users/Shared/Riot Games/Metadata/league_of_legends.live",
  ],
      rmdir: [
        "~/Documents/League of Legends",
        "~/Library/Application Support/Riot Games",
        "/Users/Shared/Riot Games",
      ]
end


text:
package de.codesourcery.lsystems.rendering;

import java.awt.Color;
import java.awt.Point;

import de.codesourcery.lsystems.rendering.Turtle2D.FloatPolygon;

/**
 * A rendering context provides implementations for
 * 2-dimensional turtle drawing operations.
 *
 * @author tobias.gierke@code-sourcery.de
 */
public interface RenderingContext2D
{
	/**
	 * Draws a line with a specific color.
	 *
	 * @param color
	 * @param p1
	 * @param p2
	 */
	void drawLine( Color color , Vec2 p1, Vec2 p2 );

	/**
	 * Draws a circle with a specific color and radius.
	 *
	 * @param color
	 * @param center
	 * @param radius
	 */
	void drawCircle( Color color , Vec2 center, float radius);

	/**
	 * Draws a filled circle with a specific color and radius.
	 *
	 * @param color
	 * @param center
	 * @param radius
	 */
	void drawFilledCircle( Color color , Vec2 center, float radius);

	/**
	 * Converts a point in model coordinates to screen coordinates.
	 *
	 * @param modelX
	 * @param modelY
	 * @param point
	 */
	public void toScreenCoordinates(float modelX,float modelY,Point point);

	public void drawPolygon(Color color,FloatPolygon polygon);

	public void drawFilledPolygon(Color color,FloatPolygon polygon);
}


text:
package org.keycloak.quarkus.runtime.configuration.mappers;

import org.keycloak.config.MetricsOptions;

import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper.fromOption;

final class MetricsPropertyMappers {

    private MetricsPropertyMappers(){}

    public static PropertyMapper[] getMetricsPropertyMappers() {
        return new PropertyMapper[] {
                fromOption(MetricsOptions.METRICS_ENABLED)
                        .to("quarkus.smallrye-metrics.extensions.enabled")
                        .paramLabel(Boolean.TRUE + "|" + Boolean.FALSE)
                        .build()
        };
    }

}


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('profiles', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Request',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.TextField(default=b'Type your title here')),
                ('description', models.TextField(default=b'Type your description here')),
                ('origin', models.CharField(choices=[(b'Seattle', b'Seattle'), (b'Portland', b'Portland')], default=b'Seattle', max_length=25)),
                ('destination', models.CharField(choices=[(b'Seattle', b'Seattle'), (b'Portland', b'Portland')], default=b'Seattle', max_length=25)),
                ('date_created', models.DateTimeField(blank=True, default=datetime.datetime.now)),
                ('courier', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='requests', to='profiles.Profile')),
                ('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sent_from', to='profiles.Profile')),
            ],
        ),
    ]