text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#endregion

using System;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;

namespace Google.ProtocolBuffers
{
    public class InteropLiteTest
    {
        [Test]
        public void TestConvertFromFullMinimal()
        {
            TestInteropPerson person = TestInteropPerson.CreateBuilder()
                .SetId(123)
                .SetName("abc")
                .Build();
            Assert.IsTrue(person.IsInitialized);

            TestInteropPersonLite copy = TestInteropPersonLite.ParseFrom(person.ToByteArray());

            Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
        }

        [Test]
        public void TestConvertFromFullComplete()
        {
            TestInteropPerson person = TestInteropPerson.CreateBuilder()
                .SetId(123)
                .SetName("abc")
                .SetEmail("abc@123.com")
                .AddRangeCodes(new[] {1, 2, 3})
                .AddPhone(TestInteropPerson.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
                .AddPhone(TestInteropPerson.Types.PhoneNumber.CreateBuilder().SetNumber("555-5678").Build())
                .AddAddresses(
                    TestInteropPerson.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland").
                        SetState("NA").SetZip(12345).Build())
                .SetExtension(UnittestExtrasFull.EmployeeId,
                              TestInteropEmployeeId.CreateBuilder().SetNumber("123").Build())
                .Build();
            Assert.IsTrue(person.IsInitialized);

            ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
            UnittestExtrasLite.RegisterAllExtensions(registry);
            byte[] fullBytes = person.ToByteArray();

            TestInteropPersonLite copy = TestInteropPersonLite.ParseFrom(fullBytes, registry);
            byte[] liteBytes = copy.ToByteArray();

            Assert.AreEqual(fullBytes, liteBytes);
        }

        [Test]
        public void TestConvertFromLiteMinimal()
        {
            TestInteropPersonLite person = TestInteropPersonLite.CreateBuilder()
                .SetId(123)
                .SetName("abc")
                .Build();
            Assert.IsTrue(person.IsInitialized);

            TestInteropPerson copy = TestInteropPerson.ParseFrom(person.ToByteArray());

            Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
        }

        [Test]
        public void TestConvertFromLiteComplete()
        {
            TestInteropPersonLite person = TestInteropPersonLite.CreateBuilder()
                .SetId(123)
                .SetName("abc")
                .SetEmail("abc@123.com")
                .AddRangeCodes(new[] {1, 2, 3})
                .AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
                .AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber("555-5678").Build())
                .AddAddresses(
                    TestInteropPersonLite.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland")
                        .SetState("NA").SetZip(12345).Build())
                .SetExtension(UnittestExtrasLite.EmployeeIdLite,
                              TestInteropEmployeeIdLite.CreateBuilder().SetNumber("123").Build())
                .Build();
            Assert.IsTrue(person.IsInitialized);

            ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
            UnittestExtrasFull.RegisterAllExtensions(registry);

            TestInteropPerson copy = TestInteropPerson.ParseFrom(person.ToByteArray(), registry);

            Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
        }

        public ByteString AllBytes
        {
            get
            {
                byte[] bytes = new byte[256];
                for (int i = 0; i < bytes.Length; i++)
                    bytes[i] = (byte) i;
                return ByteString.CopyFrom(bytes);
            }
        }

        [Test]
        public void TestCompareStringValues()
        {
            TestInteropPersonLite person = TestInteropPersonLite.CreateBuilder()
                .SetId(123)
                .SetName("abc")
                .SetEmail("abc@123.com")
                .AddRangeCodes(new[] {1, 2, 3})
                .AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
                .AddPhone(
                    TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber(
                        System.Text.Encoding.UTF8.GetString(AllBytes.ToByteArray(), 0, AllBytes.Length)).Build())
                .AddAddresses(
                    TestInteropPersonLite.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland")
                        .SetState("NA").SetZip(12345).Build())
                .SetExtension(UnittestExtrasLite.EmployeeIdLite,
                              TestInteropEmployeeIdLite.CreateBuilder().SetNumber("123").Build())
                .Build();
            Assert.IsTrue(person.IsInitialized);

            ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
            UnittestExtrasFull.RegisterAllExtensions(registry);

            TestInteropPerson copy = TestInteropPerson.ParseFrom(person.ToByteArray(), registry);

            Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());

            TestInteropPerson.Builder copyBuilder = TestInteropPerson.CreateBuilder();
            TextFormat.Merge(
                person.ToString().Replace("[protobuf_unittest_extra.employee_id_lite]",
                                          "[protobuf_unittest_extra.employee_id]"), registry, copyBuilder);

            copy = copyBuilder.Build();
            Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());

            string liteText = person.ToString().TrimEnd().Replace("\r", "");
            string fullText = copy.ToString().TrimEnd().Replace("\r", "");
            //map the extension type
            liteText = liteText.Replace("[protobuf_unittest_extra.employee_id_lite]",
                                        "[protobuf_unittest_extra.employee_id]");
            //lite version does not indent
            while (fullText.IndexOf("\n ", StringComparison.Ordinal) >= 0)
                fullText = fullText.Replace("\n ", "\n");

            Assert.AreEqual(fullText, liteText);
        }
    }
}


text:
<!DOCTYPE html>
<html>
  <body>
    <script src="../../web-animations.js"></script>
    <script src="../../smil-in-javascript.js"></script>
    <script src="../harness.js"></script>
    <script src="xlink-href-check.js"></script>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="500">
  <!-- The animation tag, e.g. set, can appear inside defs (height) or outside defs (width). -->

  <defs>
    <set xlink:href="#polyfillRect" attributeName="height" to="200"/>
  </defs>
  <rect id="polyfillRect" x="0" y="0" width="100" height="100" fill="green"/>
  <set xlink:href="#polyfillRect" attributeName="width" to="200"/>

  <defs>
    <nativeSet xlink:href="#nativeRect" attributeName="height" to="200"/>
  </defs>
  <rect id="nativeRect" x="0" y="210" width="100" height="100" fill="green"/>
  <nativeSet xlink:href="#nativeRect" attributeName="width" to="200"/>
</svg>

  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
<?php
// Call Zend_Form_Element_SelectTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_Form_Element_SelectTest::main");
}

require_once dirname(__FILE__) . '/../../../TestHelper.php';

require_once 'Zend/Form/Element/Select.php';

/**
 * Test class for Zend_Form_Element_Select
 */
class Zend_Form_Element_SelectTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        $suite  = new PHPUnit_Framework_TestSuite("Zend_Form_Element_SelectTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        $this->element = new Zend_Form_Element_Select('foo');
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
    }

    public function getView()
    {
        require_once 'Zend/View.php';
        $view = new Zend_View();
        $view->addHelperPath(dirname(__FILE__) . '/../../../../library/Zend/View/Helper');
        return $view;
    }

    public function testSelectElementSubclassesXhtmlElement()
    {
        $this->assertTrue($this->element instanceof Zend_Form_Element_Xhtml);
    }

    public function testSelectElementInstanceOfBaseElement()
    {
        $this->assertTrue($this->element instanceof Zend_Form_Element);
    }

    public function testSelectElementIsNotAnArrayByDefault()
    {
        $this->assertFalse($this->element->isArray());
    }

    public function testSelectElementUsesSelectHelperInViewHelperDecoratorByDefault()
    {
        $this->_checkZf2794();

        $decorator = $this->element->getDecorator('viewHelper');
        $this->assertTrue($decorator instanceof Zend_Form_Decorator_ViewHelper);
        $decorator->setElement($this->element);
        $helper = $decorator->getHelper();
        $this->assertEquals('formSelect', $helper);
    }

    public function testCanDisableIndividualSelectOptions()
    {
        $this->element->setMultiOptions(array(
                'foo' => 'foo',
                'bar' => array(
                    'baz' => 'Baz',
                    'bat' => 'Bat'
                ),
                'test' => 'Test',
            ))
            ->setAttrib('disable', array('baz', 'test'));
        $html = $this->element->render($this->getView());
        $this->assertNotRegexp('/<select[^>]*?(disabled="disabled")/', $html, $html);
        foreach (array('baz', 'test') as $test) {
            if (!preg_match('/(<option[^>]*?(value="' . $test . '")[^>]*>)/', $html, $m)) {
                $this->fail('Unable to find matching disabled option for ' . $test);
            }
            $this->assertRegexp('/<option[^>]*?(disabled="disabled")/', $m[1]);
        }
        foreach (array('foo', 'bat') as $test) {
            if (!preg_match('/(<option[^>]*?(value="' . $test . '")[^>]*>)/', $html, $m)) {
                $this->fail('Unable to find matching option for ' . $test);
            }
            $this->assertNotRegexp('/<option[^>]*?(disabled="disabled")/', $m[1], var_export($m, 1));
        }
    }

    /**
     * No explicit assertions; just checking for error conditions
     *
     * @see ZF-2847
     */
    public function testTranslationShouldNotRaiseWarningsWithNestedGroups()
    {
        require_once 'Zend/Translate.php';
        require_once 'Zend/View.php';
        $translate = new Zend_Translate('array', array('Select Test', 'Select Test Translated'), 'en');
        $this->element
             ->setLabel('Select Test')
             ->setMultiOptions(array(
                 'Group 1' => array(
                     '1-1' => 'Hi 1-1',
                     '1-2' => 'Hi 1-2',
                 ),
                 'Group 2' => array(
                     '2-1' => 'Hi 2-1',
                     '2-2' => 'Hi 2-2',
                 ),
             ))
             ->setTranslator($translate)
             ->setView(new Zend_View());
        $html = $this->element->render();
    }

    /**
     * @see   ZF-3953
     * @group ZF-3953
     */
    public function testUsingZeroAsValueShouldSelectAppropriateOption()
    {
        $this->element->setMultiOptions(array(
            array('key' => '1', 'value' => 'Yes'),
            array('key' => '0', 'value' => 'No'),
            array('key' => 'somewhat', 'value' => 'Somewhat'),
        ));
        $this->element->setValue(0);
        $html = $this->element->render($this->getView());

        if (!preg_match('#(<option[^>]*(?:value="somewhat")[^>]*>)#s', $html, $matches)) {
            $this->fail('Could not find option: ' . $html);
        }
        $this->assertNotContains('selected', $matches[1]);
    }

    /**
     * Used by test methods susceptible to ZF-2794, marks a test as incomplete
     *
     * @link   http://framework.zend.com/issues/browse/ZF-2794
     * @return void
     */
    protected function _checkZf2794()
    {
        if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.1.4', '=')) {
            $this->markTestIncomplete('Error occurs for PHP 5.1.4 on Windows');
        }
    }
}

// Call Zend_Form_Element_SelectTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Form_Element_SelectTest::main") {
    Zend_Form_Element_SelectTest::main();
}


text:
title: Perform New Updates on a Document Using model.findOneAndUpdate()
---
## Perform New Updates on a Document Using model.findOneAndUpdate()

This is a stub. Help our community expand it.

This quick style guide will help ensure your pull request gets accepted.


text:
import sys

import numpy

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [
    Extension("nerven.epoc._parse",
        sources=["src/nerven/epoc/_parse.pyx"],
        include_dirs=[".", numpy.get_include()]),
]

setup(name='nerven',
      version='0.1',
      author='Sharif Olorin',
      author_email='sio@tesser.org',
      requires=[
          'wxmpl',
          'numpy',
          ],
      cmdclass={'build_ext' : build_ext},
      ext_modules=ext_modules,
      package_dir={'' : 'src'},
      packages=['nerven', 'nerven.epoc', 'nerven.writer'],
      package_data={'nerven' : ['img/*.png']},
      scripts=['src/nerven_gui'],
      data_files=[('bin', ['src/nerven_gui'])],
      )


text:
"use strict";

var BraintreeError = require("../lib/braintree-error");
var analytics = require("../lib/analytics");
var errors = require("./errors");
var Promise = require("../lib/promise");
var methods = require("../lib/methods");
var convertMethodsToError = require("../lib/convert-methods-to-error");
var wrapPromise = require("@braintree/wrap-promise");

/**
 * @typedef {object} ApplePay~tokenizePayload
 * @property {string} nonce The payment method nonce.
 * @property {object} details Additional details.
 * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
 * @property {string} details.cardHolderName The name of the card holder.
 * @property {string} details.dpanLastTwo Last two digits of card number.
 * @property {string} description A human-readable description.
 * @property {string} type The payment method type, always `ApplePayCard`.
 * @property {object} binData Information about the card based on the bin.
 * @property {string} binData.commercial Possible values: 'Yes', 'No', 'Unknown'.
 * @property {string} binData.countryOfIssuance The country of issuance.
 * @property {string} binData.debit Possible values: 'Yes', 'No', 'Unknown'.
 * @property {string} binData.durbinRegulated Possible values: 'Yes', 'No', 'Unknown'.
 * @property {string} binData.healthcare Possible values: 'Yes', 'No', 'Unknown'.
 * @property {string} binData.issuingBank The issuing bank.
 * @property {string} binData.payroll Possible values: 'Yes', 'No', 'Unknown'.
 * @property {string} binData.prepaid Possible values: 'Yes', 'No', 'Unknown'.
 * @property {string} binData.productId The product id.
 */

/**
 * An Apple Pay Payment Authorization Event object.
 * @typedef {object} ApplePayPaymentAuthorizedEvent
 * @external ApplePayPaymentAuthorizedEvent
 * @see {@link https://developer.apple.com/reference/applepayjs/applepaypaymentauthorizedevent ApplePayPaymentAuthorizedEvent}
 */

/**
 * An Apple Pay Payment Request object.
 * @typedef {object} ApplePayPaymentRequest
 * @external ApplePayPaymentRequest
 * @see {@link https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest PaymentRequest}
 */

/**
 * @class
 * @param {object} options Options
 * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.applePay.create} instead.
 * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
 */
function ApplePay(options) {
  this._instantiatedWithClient = Boolean(!options.useDeferredClient);
  this._client = options.client;
  this._createPromise = options.createPromise;

  if (this._client) {
    this._setMerchantIdentifier();
  }
}

ApplePay.prototype._waitForClient = function () {
  if (this._client) {
    return Promise.resolve();
  }

  return this._createPromise.then(
    function (client) {
      this._client = client;

      this._setMerchantIdentifier();
    }.bind(this)
  );
};

ApplePay.prototype._setMerchantIdentifier = function () {
  var applePayConfig =
    this._client.getConfiguration().gatewayConfiguration.applePayWeb;

  if (!applePayConfig) {
    return;
  }
  /**
   * @name ApplePay#merchantIdentifier
   * @description A special merchant ID which represents the merchant association with Braintree. Required when using `ApplePaySession.canMakePaymentsWithActiveCard`.
   * @example
   * var promise = ApplePaySession.canMakePaymentsWithActiveCard(applePayInstance.merchantIdentifier);
   * promise.then(function (canMakePaymentsWithActiveCard) {
   *   if (canMakePaymentsWithActiveCard) {
   *     // Set up Apple Pay buttons
   *   }
   * });
   */
  Object.defineProperty(this, "merchantIdentifier", {
    value: applePayConfig.merchantIdentifier,
    configurable: false,
    writable: false,
  });
};

/**
 * Merges a payment request with Braintree defaults to return an {external:ApplePayPaymentRequest}.
 *
 * The following properties are assigned to `paymentRequest` if not already defined. Their default values come from the Braintree gateway.
 * - `countryCode`
 * - `currencyCode`
 * - `merchantCapabilities`
 * - `supportedNetworks`
 * @public
 * @param {external:ApplePayPaymentRequest} paymentRequest The payment request details to apply on top of those from Braintree.
 * @returns {external:ApplePayPaymentRequest|Promise} The decorated `paymentRequest` object. If `useDeferredClient` is used along with an `authorization`, this method will return a promise that resolves with the `paymentRequest` object.
 * @example
 * var applePay = require('braintree-web/apple-pay');
 *
 * applePay.create({client: clientInstance}, function (applePayErr, applePayInstance) {
 *   if (applePayErr) {
 *     // Handle error here
 *     return;
 *   }
 *
 *   var paymentRequest = applePayInstance.createPaymentRequest({
 *     total: {
 *       label: 'My Company',
 *       amount: '19.99'
 *     }
 *   });
 *
 *   var session = new ApplePaySession(3, paymentRequest);
 *
 *   // ...
 * @example
With deferred client

 * var applePay = require('braintree-web/apple-pay');
 *
 * applePay.create({
 *   authorization: 'client-token-or-tokenization-key',
 *   useDeferredClient: true
 * }, function (applePayErr, applePayInstance) {
 *   if (applePayErr) {
 *     // Handle error here
 *     return;
 *   }
 *
 *   applePayInstance.createPaymentRequest({
 *     total: {
 *       label: 'My Company',
 *       amount: '19.99'
 *     }
 *   }).then(function (paymentRequest) {
 *     var session = new ApplePaySession(3, paymentRequest);
 *
 *     // ...
 *   });
 */
ApplePay.prototype.createPaymentRequest = function (paymentRequest) {
  if (this._instantiatedWithClient) {
    return this._createPaymentRequestSynchronously(paymentRequest);
  }

  return this._waitForClient().then(
    function () {
      return this._createPaymentRequestSynchronously(paymentRequest);
    }.bind(this)
  );
};

ApplePay.prototype._createPaymentRequestSynchronously = function (
  paymentRequest
) {
  var applePay =
    this._client.getConfiguration().gatewayConfiguration.applePayWeb;
  var defaults = {
    countryCode: applePay.countryCode,
    currencyCode: applePay.currencyCode,
    merchantCapabilities: applePay.merchantCapabilities || ["supports3DS"],
    supportedNetworks: applePay.supportedNetworks.map(function (network) {
      return network === "mastercard" ? "masterCard" : network;
    }),
  };

  return Object.assign({}, defaults, paymentRequest);
};

/**
 * Validates your merchant website, as required by `ApplePaySession` before payment can be authorized.
 * @public
 * @param {object} options Options
 * @param {string} options.validationURL The validationURL from an `ApplePayValidateMerchantEvent`.
 * @param {string} options.displayName The canonical name for your store. Use a non-localized name. This parameter should be a UTF-8 string that is a maximum of 128 characters. The system may display this name to the user.
 * @param {callback} [callback] The second argument, data, is the Apple Pay merchant session object. If no callback is provided, `performValidation` returns a promise.
 * Pass the merchant session to your Apple Pay session's `completeMerchantValidation` method.
 * @returns {(Promise|void)} Returns a promise if no callback is provided.
 * @example
 * var applePay = require('braintree-web/apple-pay');
 *
 * applePay.create({client: clientInstance}, function (applePayErr, applePayInstance) {
 *   if (applePayErr) {
 *     // Handle error here
 *     return;
 *   }
 *
 *   var paymentRequest = applePayInstance.createPaymentRequest({
 *     total: {
 *       label: 'My Company',
 *       amount: '19.99'
 *     }
 *   });
 *   var session = new ApplePaySession(3, paymentRequest);
 *
 *   session.onvalidatemerchant = function (event) {
 *     applePayInstance.performValidation({
 *       validationURL: event.validationURL,
 *       displayName: 'My Great Store'
 *     }, function (validationErr, validationData) {
 *       if (validationErr) {
 *         console.error(validationErr);
 *         session.abort();
 *         return;
 *       }
 *
 *       session.completeMerchantValidation(validationData);
 *     });
 *   };
 * });
 */
ApplePay.prototype.performValidation = function (options) {
  var self = this;

  if (!options || !options.validationURL) {
    return Promise.reject(
      new BraintreeError(errors.APPLE_PAY_VALIDATION_URL_REQUIRED)
    );
  }

  return this._waitForClient()
    .then(function () {
      var applePayWebSession = {
        validationUrl: options.validationURL,
        domainName: options.domainName || window.location.hostname,
        merchantIdentifier:
          options.merchantIdentifier || self.merchantIdentifier,
      };

      if (options.displayName != null) {
        applePayWebSession.displayName = options.displayName;
      }

      return self._client.request({
        method: "post",
        endpoint: "apple_pay_web/sessions",
        data: {
          _meta: { source: "apple-pay" },
          applePayWebSession: applePayWebSession,
        },
      });
    })
    .then(function (response) {
      analytics.sendEvent(self._client, "applepay.performValidation.succeeded");

      return Promise.resolve(response);
    })
    .catch(function (err) {
      analytics.sendEvent(self._client, "applepay.performValidation.failed");

      if (err.code === "CLIENT_REQUEST_ERROR") {
        return Promise.reject(
          new BraintreeError({
            type: errors.APPLE_PAY_MERCHANT_VALIDATION_FAILED.type,
            code: errors.APPLE_PAY_MERCHANT_VALIDATION_FAILED.code,
            message: errors.APPLE_PAY_MERCHANT_VALIDATION_FAILED.message,
            details: {
              originalError: err.details.originalError,
            },
          })
        );
      }

      return Promise.reject(
        new BraintreeError({
          type: errors.APPLE_PAY_MERCHANT_VALIDATION_NETWORK.type,
          code: errors.APPLE_PAY_MERCHANT_VALIDATION_NETWORK.code,
          message: errors.APPLE_PAY_MERCHANT_VALIDATION_NETWORK.message,
          details: {
            originalError: err,
          },
        })
      );
    });
};

/**
 * Tokenizes an Apple Pay payment. This will likely be called in your `ApplePaySession`'s `onpaymentauthorized` callback.
 * @public
 * @param {object} options Options
 * @param {object} options.token The `payment.token` property of an {@link external:ApplePayPaymentAuthorizedEvent}.
 * @param {callback} [callback] The second argument, data, is a {@link ApplePay~tokenizePayload|tokenizePayload}. If no callback is provided, `tokenize` returns a promise that resolves with a {@link ApplePay~tokenizePayload|tokenizePayload}.
 * @returns {(Promise|void)} Returns a promise if no callback is provided.
 * @example
 * var applePay = require('braintree-web/apple-pay');
 *
 * applePay.create({client: clientInstance}, function (applePayErr, applePayInstance) {
 *   if (applePayErr) {
 *     // Handle error here
 *     return;
 *   }
 *
 *   var paymentRequest = applePayInstance.createPaymentRequest({
 *     total: {
 *       label: 'My Company',
 *       amount: '19.99'
 *     }
 *   });
 *   var session = new ApplePaySession(3, paymentRequest);
 *
 *   session.onpaymentauthorized = function (event) {
 *     applePayInstance.tokenize({
 *       token: event.payment.token
 *     }, function (tokenizeErr, tokenizedPayload) {
 *       if (tokenizeErr) {
 *         session.completePayment(ApplePaySession.STATUS_FAILURE);
 *         return;
 *       }
 *       // Send the tokenizedPayload to your server here!
 *
 *       // Once the transaction is complete, call completePayment
 *       // to close the Apple Pay sheet
 *       session.completePayment(ApplePaySession.STATUS_SUCCESS);
 *     });
 *   };
 *
 *   // ...
 * });
 */
ApplePay.prototype.tokenize = function (options) {
  var self = this;

  if (!options.token) {
    return Promise.reject(
      new BraintreeError(errors.APPLE_PAY_PAYMENT_TOKEN_REQUIRED)
    );
  }

  return this._waitForClient()
    .then(function () {
      return self._client.request({
        method: "post",
        endpoint: "payment_methods/apple_payment_tokens",
        data: {
          _meta: {
            source: "apple-pay",
          },
          applePaymentToken: Object.assign({}, options.token, {
            // The gateway requires this key to be base64-encoded.
            paymentData: btoa(JSON.stringify(options.token.paymentData)),
          }),
        },
      });
    })
    .then(function (response) {
      analytics.sendEvent(self._client, "applepay.tokenize.succeeded");

      return Promise.resolve(response.applePayCards[0]);
    })
    .catch(function (err) {
      analytics.sendEvent(self._client, "applepay.tokenize.failed");

      return Promise.reject(
        new BraintreeError({
          type: errors.APPLE_PAY_TOKENIZATION.type,
          code: errors.APPLE_PAY_TOKENIZATION.code,
          message: errors.APPLE_PAY_TOKENIZATION.message,
          details: {
            originalError: err,
          },
        })
      );
    });
};

/**
 * Cleanly tear down anything set up by {@link module:braintree-web/apple-pay.create|create}.
 * @public
 * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
 * @example
 * applePayInstance.teardown();
 * @example
With callback

 * applePayInstance.teardown(function () {
 *   // teardown is complete
 * });
 * @returns {(Promise|void)} Returns a promise if no callback is provided.
 */
ApplePay.prototype.teardown = function () {
  convertMethodsToError(this, methods(ApplePay.prototype));

  return Promise.resolve();
};

module.exports = wrapPromise.wrapPrototype(ApplePay);


text:
class BowlingGame:
  def roll(self, rollValue):
      self.__updateScore(rollValue)
      frameScore = rollValue + self.__lastRoll
      self.__saveRollForNextTime(rollValue)
      self.__markifSpareForNextTime(frameScore)
      self.__markIfStrikeForNextTime(rollValue)

  def __markIfStrikeForNextTime(self, rollValue):
      if rollValue == 10 and self.__isSecoundRollInFrame():
        self.__isStrike = True
        self.__resetRollForNewFrame()

  def totalScore(self):
      return self.__totalScore

  def __updateScore(self, rollValue):
      self.__addRollValueToScore(rollValue)
      self.__addBonusIfSpare(rollValue)
      self.__addBonusIfStrike(rollValue)

  def __addRollValueToScore(self, rollValue):
      self.__totalScore = self.__totalScore + rollValue

  def __addBonusIfSpare(self, rollValue):
      if self.__isSpare:
        self.__totalScore = self.__totalScore + rollValue

  def __addBonusIfStrike(self, rollValue):
      if self.__isStrike and self.__isSecoundRollInFrame():
        self.__totalScore =  self.__totalScore + rollValue + self.__lastRoll
        self.__isStrike == False

  def __markifSpareForNextTime(self, frameScore):
      if(frameScore == 10):
        self.__isSpare = True
      else:
        self.__isSpare = False

  def __saveRollForNextTime(self, rollValue):
        if self.__isSecoundRollInFrame():
          self.__resetRollForNewFrame()
        else:
          self.__lastRoll = rollValue

  def __isSecoundRollInFrame(self):
      return self.__lastRoll >= 0

  def __resetRollForNewFrame(self):
      self.__lastRoll = -1

  def __setRollValue(self):
      self.__lastRoll = rollValue

  __totalScore = 0
  __lastRoll = -1
  __isSpare = False
  __isStrike = False


text:
package com.sun.tools.xjc.servlet.reaper;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Launches {@link Compiler} from the form input.
 *
 * @author
 *  Ryan Shoemaker
 */
public class DiskManagerServlet extends HttpServlet {

    // each compiler session will have a tmp directory whose name
    // begins with this string
    static final String SESSION_DIR_PREFIX = "jaxbOnTheWeb";

    // session directories will be considered "stale" when their
    // last modification time is more than this many milliseconds
    // ago.
    public static final long TIMEOUT = 1000 * 60 * 60;

    // the background thread that periodically wakes up and looks
    // for disk space to reclaim.
    private static Reaper reaperThread;

    // this is the root output directory for all client sessions
    private static File rootTmpDir;

    // text used for the reset button and parameter name
    private static final String RESET_BUTTON = "Reset";

    /**
     * Allocates a new temporary directory for anyone who needs
     * time-limited quota-controlled disk storage area.
     */
    public synchronized static File createOutDir() throws IOException {
        File outDir = File.createTempFile(SESSION_DIR_PREFIX, "");
        outDir.delete();
        // to avoid another thread from stealing the unique name when one thread
        // is here, this method is made synchronized.
        outDir.mkdir();
        return outDir;
    }

    /* (non-Javadoc)
     * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
            // get the root tmp dir
            File tmpFile = File.createTempFile("foo", "");
            rootTmpDir = tmpFile.getParentFile();
            tmpFile.delete();

            // create
            reaperThread = new Reaper();
            reaperThread.setPriority(Thread.MIN_PRIORITY);
            reaperThread.start();
        } catch (IOException ioe) {
            throw new ServletException(ioe);
        }
    }

    /* (non-Javadoc)
     * @see javax.servlet.Servlet#destroy()
     */
    public void destroy() {
        super.destroy();

        // cleanup the disk
        deleteAllTmpStorage();

        // kill the reaper thread
        reaperThread.destroy();
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void doGet(
        HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

        doIt(request, response);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    protected void doPost(
        HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

        doIt(request, response);
    }

    private static int hits = 0;
    private void doIt(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

        String value = request.getParameter(RESET_BUTTON);
        if (value != null) {
            // we don't care about the value
            deleteAllTmpStorage();
        }

        // cause the reaper thread to calculate the latest stats
        reaperThread.update();

        // TODO: format report

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(
            "
DiskManager,v1.22," + ++hits + "
\n"
                + "
Tmp dir: "
                + reaperThread.getTmpDir()
                + "\n"
                + "
Last reap reclaimed: "
                + reaperThread.getReapedSpace()
                + "b\n"
                + "
Current disk usage: "
                + reaperThread.getDiskUsage()
                + "b\n"
                + generateResetButton()
                + "\n
"
                + dumpParams( request )
                + "");

    }

    /**
     * @param request
     * @return
     */
    private String dumpParams(HttpServletRequest request) {
        StringBuffer params = new StringBuffer();
        params.append( "
params
");
        for( Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
            String param = (String)e.nextElement();
            params.append( "name: " + param + " value: " + request.getParameter( param ) + "
\n" );
        }
        return params.toString();
    }

    /**
     * generate the html code for the "reset" button.
     *
     * @return the button code
     */
    private String generateResetButton() {
        StringBuffer resetCode = new StringBuffer();
        resetCode.append("
");
        resetCode.append("\tClick the 'reset' button to completely erase all tmp JAXB files\n");
//        resetCode.append("\t<form method=\"post\" action=\"diskmanager?" + RESET_BUTTON + "=true\">\n");
        resetCode.append("\t<form method=\"post\" action=\"diskmanager\">\n");
        resetCode.append("\t\t<input type=\"SUBMIT\" name=\"" + RESET_BUTTON + "\" value=\"" + RESET_BUTTON + "\">\n");
        resetCode.append("\t</form>\n");
        resetCode.append("
\n");
        return resetCode.toString();
    }

    /**
     * Accessor for the root directory containing all of the tmp files.
     *
     * @return the root tmp directory
     */
    public static File getRootTmpDir() {
        return rootTmpDir;
    }

    /**
     * causes all temp storage to be deleted.  This method is called when
     * someone clicks the "reset" button in the DiskManager page and when
     * the destroy method is invoked.
     */
    private void deleteAllTmpStorage() {
        reaperThread.deleteAll();
    }

}


text:
class AddEmergencyPhonenumberToCustomerLeads < ActiveRecord::Migration
  def change
    add_column :customer_leads, :emergency_phone_number, :string
  end
end


text:
<?php

/**
 * This is the model class for table "customer_group".
 *
 * The followings are the available columns in table 'customer_group':
 * @property integer $customer_group_id
 * @property string $customer_group_code
 * @property string $tax_class_id
 */
class Mage2CustomerGroupPeer extends Mage2ActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{customer_group}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('customer_group_code', 'required'),
			array('customer_group_code', 'length', 'max'=>32),
			array('tax_class_id', 'length', 'max'=>10),
		);
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Mage2CustomerGroupPeer the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}


text:
class VarReplace

    def initialize(vars)
        @vars = vars
    end

    def subs!(str)

        if str == nil
            str=""
        end

        if @vars == nil
            return
        end

        @vars.each do |a_var,a_value|
            subs="\#\{#{a_var}\}"
            str.gsub!(subs,a_value.to_s)
        end
    end

    def subs(str)

        str_tmp = str == nil ? "" : String.new(str)

        subs!(str_tmp)

        return str_tmp
    end

    def to_s()
        return @vars.to_s
    end

end

class VarSub

    ERR_CIRCULAR_REFERENCE="circular reference with two variables"
    ERR_NO_SUCH_VAR="No such variable"

    def initialize(definition)

        @definition = definition
        @process = Array.new
    end

    def parse

        order_list = Array.new
        @definition.each_key do |var|
            order_list.concat(processParsing(var))
        end
        var_found = Hash.new

        order_list.each do |var|
            if var_found.has_key?(var)
                next
            end
            @process << var
            var_found[var] = 0
        end
    end

    def get
        return @process
    end

    private

    def uniq(array)

        result = Hash.new

        array.each do |value|
            result[value] = 0
        end

        return result.each_key.to_a

    end

    def processParsing(var,level=0)
        if level >= 500
            raise "Too may loop in processParsing"
        end
        unless @definition.has_key?(var)
            raise "#{var} does not exist"
        end

        result = Array.new
        vars = @definition[var].scan /\#\{([^\}]+)\}/

        vars.each do |var_c|

            result = result.concat(processParsing(var_c[0],level+1))
        end
        result << var

        return result
    end

end


text:
Facter.add(:mac_timezone) do
  confine kernel: "Darwin"
  setcode do
    string = Facter::Util::Resolution.exec("/usr/sbin/systemsetup -gettimezone")
    string[11..string.length]
  end
end


text:
using System.Numerics;
using GraphQLParser.AST;

namespace GraphQL.Types
{
    /// <summary>
    /// The BigInt scalar graph type represents a signed integer with any number of digits.
    /// By default <see cref="SchemaTypes"/> maps all <see cref="BigInteger"/> .NET values to this scalar graph type.
    /// </summary>
    public class BigIntGraphType : ScalarGraphType
    {
        /// <inheritdoc/>
        public override object? ParseLiteral(GraphQLValue value) => value switch
        {
            GraphQLIntValue x => BigInt.Parse(x.Value),
            GraphQLNullValue _ => null,
            _ => ThrowLiteralConversionError(value)
        };

        /// <inheritdoc/>
        public override bool CanParseLiteral(GraphQLValue value) => value switch
        {
            GraphQLIntValue _ => true,
            GraphQLNullValue _ => true,
            _ => false
        };

        /// <inheritdoc/>
        public override object? ParseValue(object? value) => value switch
        {
            BigInteger _ => value,
            null => null,
            int i => new BigInteger(i),
            sbyte sb => new BigInteger(sb),
            byte b => new BigInteger(b),
            short s => new BigInteger(s),
            ushort us => new BigInteger(us),
            uint ui => new BigInteger(ui),
            long l => new BigInteger(l),
            ulong ul => new BigInteger(ul),
            _ => ThrowValueConversionError(value)
        };
    }
}


text:
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace DevTrends.MvcDonutCaching
{
    public class KeyGenerator : IKeyGenerator
    {
        internal const string RouteDataKeyAction     = "action";
        internal const string RouteDataKeyController = "controller";
        internal const string DataTokensKeyArea      = "area";

        private readonly IKeyBuilder _keyBuilder;

        public KeyGenerator(IKeyBuilder keyBuilder)
        {
            if (keyBuilder == null)
            {
                throw new ArgumentNullException("keyBuilder");
            }

            _keyBuilder = keyBuilder;
        }

        /// <summary>
        /// Generates a key given the <see cref="context"/> and <see cref="cacheSettings"/>.
        /// </summary>
        /// <param name="context">The controller context.</param>
        /// <param name="cacheSettings">The cache settings.</param>
        /// <returns>A string that can be used as an output cache key</returns>
        [CanBeNull]
        public string GenerateKey(ControllerContext context, CacheSettings cacheSettings)
        {
            var routeData = context.RouteData;

            if (routeData == null)
            {
                return null;
            }

            string actionName = null,
                controllerName = null;

            if (
                routeData.Values.ContainsKey(RouteDataKeyAction) &&
                routeData.Values[RouteDataKeyAction] != null)
            {
                actionName = routeData.Values[RouteDataKeyAction].ToString();
            }

            if (
                routeData.Values.ContainsKey(RouteDataKeyController) &&
                routeData.Values[RouteDataKeyController] != null)
            {
                controllerName = routeData.Values[RouteDataKeyController].ToString();
            }

            if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName))
            {
                return null;
            }

            string areaName = null;

            if (
                routeData.DataTokens.ContainsKey(DataTokensKeyArea) &&
                routeData.DataTokens[DataTokensKeyArea] != null
            )
            {
                areaName = routeData.DataTokens[DataTokensKeyArea].ToString();
            }

            // remove controller, action and DictionaryValueProvider which is added by the framework for child actions
            var filteredRouteData = routeData.Values.Where(
                x => x.Key.ToLowerInvariant() != RouteDataKeyController &&
                     x.Key.ToLowerInvariant() != RouteDataKeyAction &&
                     x.Key.ToLowerInvariant() != DataTokensKeyArea &&
                     !(x.Value is DictionaryValueProvider<object>)
            ).ToList();

            if (!string.IsNullOrWhiteSpace(areaName))
            {
                filteredRouteData.Add(new KeyValuePair<string, object>(DataTokensKeyArea, areaName));
            }

            var routeValues = new RouteValueDictionary(filteredRouteData.ToDictionary(x => x.Key.ToLowerInvariant(), x => x.Value));

            if (!context.IsChildAction)
            {
                // note that route values take priority over form values and form values take priority over query string values
                if ((cacheSettings.Options & OutputCacheOptions.IgnoreFormData) != OutputCacheOptions.IgnoreFormData)
                {
                    foreach (var formKey in context.HttpContext.Request.Form.AllKeys)
                    {
                        if (routeValues.ContainsKey(formKey.ToLowerInvariant()))
                        {
                            continue;
                        }

                        var item = context.HttpContext.Request.Form[formKey];
                        routeValues.Add(
                            formKey.ToLowerInvariant(),
                            item != null
                                ? item.ToLowerInvariant()
                                : string.Empty
                        );
                    }
                }

                if ((cacheSettings.Options & OutputCacheOptions.IgnoreQueryString) != OutputCacheOptions.IgnoreQueryString)
                {
                    foreach (var queryStringKey in context.HttpContext.Request.QueryString.AllKeys)
                    {
                        // queryStringKey is null if url has as name without value. e.g. test.com?q
                        if (queryStringKey == null || routeValues.ContainsKey(queryStringKey.ToLowerInvariant()))
                        {
                            continue;
                        }

                        var item = context.HttpContext.Request.QueryString[queryStringKey];
                        routeValues.Add(
                            queryStringKey.ToLowerInvariant(),
                            item != null
                                ? item.ToLowerInvariant()
                                : string.Empty
                        );
                    }
                }
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByParam))
            {
                if (cacheSettings.VaryByParam.ToLowerInvariant() == "none")
                {
                    routeValues.Clear();
                }
                else if (cacheSettings.VaryByParam != "*")
                {
                    var parameters = cacheSettings.VaryByParam.ToLowerInvariant().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    routeValues = new RouteValueDictionary(routeValues.Where(x => parameters.Contains(x.Key))
                        .ToDictionary(x => x.Key, x => x.Value));
                }
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByCustom))
            {
                // If there is an existing route value with the same key as varybycustom, we should overwrite it
                routeValues[cacheSettings.VaryByCustom.ToLowerInvariant()] =
                            context.HttpContext.ApplicationInstance.GetVaryByCustomString(HttpContext.Current, cacheSettings.VaryByCustom);
            }

            if (!string.IsNullOrEmpty(cacheSettings.VaryByHeader))
            {
                var headers = cacheSettings.VaryByHeader.ToLowerInvariant().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                var existingHeaders = context.HttpContext.Request.Headers.AllKeys.Where(x => headers.Contains(x.ToLowerInvariant()));
                foreach (var header in existingHeaders)
                {
                    routeValues[header] = context.HttpContext.Request.Headers[header];
                }
            }

            var key = _keyBuilder.BuildKey(controllerName, actionName, routeValues);

            return key;
        }
    }
}


text:
package test.types.DynAnyTypes;

//
// IDL:test/types/DynAnyTypes/TestValue4:1.0
//
final public class TestValue4Holder implements org.omg.CORBA.portable.Streamable
{
    public TestValue4 value;

    public
    TestValue4Holder()
    {
    }

    public
    TestValue4Holder(TestValue4 initial)
    {
        value = initial;
    }

    public void
    _read(org.omg.CORBA.portable.InputStream in)
    {
        value = TestValue4Helper.read(in);
    }

    public void
    _write(org.omg.CORBA.portable.OutputStream out)
    {
        TestValue4Helper.write(out, value);
    }

    public org.omg.CORBA.TypeCode
    _type()
    {
        return TestValue4Helper.type();
    }
}