text:
<?php

namespace SubscribePro\Tests\Service\Transaction;

use SubscribePro\Service\Transaction\TransactionInterface;
use SubscribePro\Service\Transaction\TransactionService;

class TransactionServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \SubscribePro\Service\Transaction\TransactionService
     */
    protected $transactionService;

    /**
     * @var \SubscribePro\Service\DataFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $transactionFactoryMock;

    /**
     * @var \SubscribePro\Http|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $httpClientMock;

    protected function setUp()
    {
        $this->httpClientMock = $this->getMockBuilder('SubscribePro\Http')
            ->disableOriginalConstructor()
            ->getMock();

        $this->transactionFactoryMock = $this->getMockBuilder('SubscribePro\Service\DataFactoryInterface')->getMock();

        $this->transactionService = new TransactionService($this->httpClientMock, $this->transactionFactoryMock);
    }

    public function testCreateTransaction()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionData = [
            TransactionInterface::ID => 123
        ];

        $this->transactionFactoryMock->expects($this->once())
            ->method('create')
            ->with($transactionData)
            ->willReturn($transactionMock);

        $this->assertSame($transactionMock, $this->transactionService->createTransaction($transactionData));
    }

    public function testLoadTransaction()
    {
        $itemId = 111;
        $itemData = [TransactionInterface::ID => $itemId];
        $transactionMock = $this->createTransactionMock();

        $this->httpClientMock->expects($this->once())
            ->method('get')
            ->with("/services/v1/vault/transactions/{$itemId}.json")
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $itemData]);

        $this->transactionFactoryMock->expects($this->once())
            ->method('create')
            ->with($itemData)
            ->willReturn($transactionMock);

        $this->assertSame($transactionMock, $this->transactionService->loadTransaction($itemId));
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required fields are set.
     */
    public function testFailToVerifyProfileIfNotValid()
    {
        $paymentProfileId = 1234;

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isVerifyDataValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->verifyProfile($paymentProfileId, $transactionMock);
    }

    public function testVerifyProfile()
    {
        $paymentProfileId = 5555;
        $formData = [TransactionInterface::AMOUNT => '1111'];
        $expectedImportData = [TransactionInterface::ID => '32323'];
        $url = "/services/v1/vault/paymentprofiles/{$paymentProfileId}/verify.json";

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isVerifyDataValid')->willReturn(true);
        $transactionMock->expects($this->once())->method('getVerifyFormData')->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($expectedImportData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $expectedImportData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->verifyProfile($paymentProfileId, $transactionMock)
        );
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required fields are set.
     */
    public function testFailToAuthorizeByProfileIfNotValid()
    {
        $paymentProfileId = 1234;

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->authorizeByProfile($paymentProfileId, $transactionMock);
    }

    public function testAuthorizeByProfile()
    {
        $paymentProfileId = 4451;
        $formData = [TransactionInterface::AMOUNT => '1230'];
        $expectedImportData = [TransactionInterface::ID => '111'];
        $url = "/services/v1/vault/paymentprofiles/{$paymentProfileId}/authorize.json";

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isValid')->willReturn(true);
        $transactionMock->expects($this->once())->method('getFormData')->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($expectedImportData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $expectedImportData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->authorizeByProfile($paymentProfileId, $transactionMock)
        );
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required fields are set.
     */
    public function testFailToPurchaseByProfileIfNotValid()
    {
        $paymentProfileId = 1234;

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->purchaseByProfile($paymentProfileId, $transactionMock);
    }

    public function testPurchaseByProfile()
    {
        $paymentProfileId = 1234;
        $formData = [TransactionInterface::AMOUNT => '1230'];
        $expectedImportData = [TransactionInterface::ID => '111'];
        $url = "/services/v1/vault/paymentprofiles/{$paymentProfileId}/purchase.json";

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isValid')->willReturn(true);
        $transactionMock->expects($this->once())->method('getFormData')->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($expectedImportData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $expectedImportData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->purchaseByProfile($paymentProfileId, $transactionMock)
        );
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required Transaction fields are set.
     */
    public function testFailToAuthorizeByTokenIfNotValidTransaction()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isTokenDataValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->authorizeByToken('token', $transactionMock, null);
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required Transaction fields are set.
     */
    public function testFailToAuthorizeByTokenWithAddressIfNotValidTransaction()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isTokenDataValid')
            ->willReturn(false);
        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->never())->method('isAsChildValid');

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->authorizeByToken('token', $transactionMock, $addressMock);
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required Address fields are set.
     */
    public function testFailToAuthorizeByTokenIfNotValidAddress()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isTokenDataValid')
            ->willReturn(true);

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())
            ->method('isAsChildValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->authorizeByToken('token', $transactionMock, $addressMock);
    }

    public function testAuthorizeByToken()
    {
        $resultData = [TransactionInterface::ID => '111'];
        $formData = [TransactionInterface::AMOUNT => '1230'];
        $token = 'simple-token';
        $url = '/services/v1/vault/tokens/simple-token/authorize.json';

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isTokenDataValid')->willReturn(true);
        $transactionMock->expects($this->once())
            ->method('getTokenFormData')
            ->with(null)
            ->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->authorizeByToken($token, $transactionMock, null)
        );
    }

    public function testAuthorizeByTokenWithAddress()
    {
        $resultData = [TransactionInterface::ID => '123'];
        $formData = [TransactionInterface::AMOUNT => '52525'];
        $token = 'token1';
        $url = '/services/v1/vault/tokens/token1/authorize.json';

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())->method('isAsChildValid')->willReturn(true);

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isTokenDataValid')->willReturn(true);
        $transactionMock->expects($this->once())
            ->method('getTokenFormData')
            ->with($addressMock)
            ->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->authorizeByToken($token, $transactionMock, $addressMock)
        );
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required Transaction fields are set.
     */
    public function testFailToPurchaseByTokenIfNotValidTransaction()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isTokenDataValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->purchaseByToken('token', $transactionMock, null);
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required Transaction fields are set.
     */
    public function testFailToPurchaseByTokenWithAddressIfNotValidTransaction()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isTokenDataValid')
            ->willReturn(false);
        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->never())->method('isAsChildValid');

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->purchaseByToken('token', $transactionMock, $addressMock);
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Not all required Address fields are set.
     */
    public function testFailToPurchaseByTokenIfNotValidAddress()
    {
        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isTokenDataValid')
            ->willReturn(true);

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())
            ->method('isAsChildValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->purchaseByToken('token', $transactionMock, $addressMock);
    }

    public function testPurchaseByToken()
    {
        $resultData = [TransactionInterface::ID => '444'];
        $formData = [TransactionInterface::AMOUNT => '222'];
        $token = 'simple-token';
        $url = "/services/v1/vault/tokens/{$token}/purchase.json";

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isTokenDataValid')->willReturn(true);
        $transactionMock->expects($this->once())
            ->method('getTokenFormData')
            ->with(null)
            ->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->purchaseByToken($token, $transactionMock, null)
        );
    }

    public function testPurchaseByTokenWithAddress()
    {
        $resultData = [TransactionInterface::ID => '44124'];
        $formData = [TransactionInterface::AMOUNT => '12312'];
        $token = 'token2';
        $url = "/services/v1/vault/tokens/{$token}/purchase.json";

        $addressMock = $this->createAddressMock();
        $addressMock->expects($this->once())->method('isAsChildValid')->willReturn(true);

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isTokenDataValid')->willReturn(true);
        $transactionMock->expects($this->once())
            ->method('getTokenFormData')
            ->with($addressMock)
            ->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->purchaseByToken($token, $transactionMock, $addressMock)
        );
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Currency code not specified for given amount.
     */
    public function testFailToCaptureIfNotValid()
    {
        $transactionId = '121';

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isServiceDataValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->capture($transactionId, $transactionMock);
    }

    public function testCapture()
    {
        $transactionId = '121';
        $url = "/services/v1/vault/transactions/{$transactionId}/capture.json";
        $resultData = [TransactionInterface::ID => $transactionId];

        $transactionMock = $this->createTransactionMock();
        $this->transactionFactoryMock->expects($this->once())
            ->method('create')
            ->with($resultData)
            ->willReturn($transactionMock);

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame($transactionMock, $this->transactionService->capture($transactionId));
    }

    public function testCaptureWithTransaction()
    {
        $transactionId = '121';
        $url = "/services/v1/vault/transactions/{$transactionId}/capture.json";
        $formData = [TransactionInterface::AMOUNT => '1230'];
        $resultData = [TransactionInterface::ID => $transactionId];

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isServiceDataValid')->willReturn(true);
        $transactionMock->expects($this->once())->method('getServiceFormData')->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->capture($transactionId, $transactionMock)
        );
    }

    /**
     * @expectedException \SubscribePro\Exception\EntityInvalidDataException
     * @expectedExceptionMessage Currency code not specified for given amount.
     */
    public function testFailToCreditIfNotValid()
    {
        $transactionId = 212;

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())
            ->method('isServiceDataValid')
            ->willReturn(false);

        $this->httpClientMock->expects($this->never())->method('post');

        $this->transactionService->credit($transactionId, $transactionMock);
    }

    public function testCredit()
    {
        $transactionId = 121;
        $resultData = [TransactionInterface::ID => $transactionId];

        $transactionMock = $this->createTransactionMock();
        $this->transactionFactoryMock->expects($this->once())
            ->method('create')
            ->with($resultData)
            ->willReturn($transactionMock);

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with("/services/v1/vault/transactions/{$transactionId}/credit.json", [])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame($transactionMock, $this->transactionService->credit($transactionId));
    }

    public function testCreditWithTransaction()
    {
        $transactionId = 123456;
        $url = "/services/v1/vault/transactions/{$transactionId}/credit.json";
        $formData = [TransactionInterface::AMOUNT => '1230'];
        $resultData = [TransactionInterface::ID => $transactionId];

        $transactionMock = $this->createTransactionMock();
        $transactionMock->expects($this->once())->method('isServiceDataValid')->willReturn(true);
        $transactionMock->expects($this->once())->method('getServiceFormData')->willReturn($formData);
        $transactionMock->expects($this->once())
            ->method('importData')
            ->with($resultData)
            ->willReturnSelf();

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with($url, [TransactionService::API_NAME_TRANSACTION => $formData])
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame(
            $transactionMock,
            $this->transactionService->credit($transactionId, $transactionMock)
        );
    }

    public function testVoid()
    {
        $itemId = 12321;
        $resultData = [TransactionInterface::ID => $itemId];

        $transactionMock = $this->createTransactionMock();
        $this->transactionFactoryMock->expects($this->once())
            ->method('create')
            ->with($resultData)
            ->willReturn($transactionMock);

        $this->httpClientMock->expects($this->once())
            ->method('post')
            ->with("/services/v1/vault/transactions/{$itemId}/void.json")
            ->willReturn([TransactionService::API_NAME_TRANSACTION => $resultData]);

        $this->assertSame($transactionMock, $this->transactionService->void($itemId));
    }

    /**
     * @return \SubscribePro\Service\Transaction\TransactionInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createTransactionMock()
    {
        return $this->getMockBuilder('SubscribePro\Service\Transaction\TransactionInterface')->getMock();
    }

    /**
     * @return \SubscribePro\Service\Address\AddressInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function createAddressMock()
    {
        return $this->getMockBuilder('SubscribePro\Service\Address\AddressInterface')->getMock();
    }
}


text:
namespace Tethys.App
{
    using System.Reflection;
    using System.Xml;

    /// <summary>
    /// This class stores the application configuration. At the beginning
    /// of the application all the properties are read from either the
    /// registry or an XML fileName. At the end of the application the data
    /// is stored again.
    /// </summary>
    public class TethysAppConfig : TethysAppConfigBase
    {
        #region PUBLIC PROPERTIES
        #endregion // PUBLIC PROPERTIES

        //// ---------------------------------------------------------------------

        #region CONSTRUCTION
        /// <summary>
        /// Initializes a new instance of the <see cref="TethysAppConfig"/> class.
        /// </summary>
        /// <param name="applicationAssembly">The application assembly.</param>
        public TethysAppConfig(Assembly applicationAssembly) : base(applicationAssembly)
        {
        } // TethysAppConfig()
        #endregion // CONSTRUCTION

        //// ---------------------------------------------------------------------

        #region PROTECTED METHODS
        #region VIRTUAL (EMPTY) METHODS
        /// <summary>
        /// Core function to write the application data.
        /// </summary>
        /// <param name="xmlWriter">The XML writer.</param>
        protected virtual void WriteData(TethysXmlTextWriter xmlWriter)
        {
        } // WriteData()

        /// <summary>
        /// Core function to read the application data.
        /// </summary>
        /// <param name="xmlReader">The XML reader.</param>
        protected virtual void ReadData(TethysXmlTextReader xmlReader)
        {
        } // ReadData()
        #endregion // VIRTUAL (EMPTY) METHODS
        #endregion // PROTECTED METHODS

        #region PUBLIC METHODS
        /// <summary>
        /// This function writes the (user dependent) application configuration
        /// to a XML fileName that is located in the path for the application data
        /// of a roaming user, i.e. something like:
        /// Base Path\CompanyName\ProductName\filename
        /// </summary>
        /// <param name="fileName">Name of the XML fileName to be used</param>
        /// <returns>
        /// The function returns true if all configuration data has
        /// been successfully written; otherwise false will be returned.
        /// </returns>
        /// <remarks>
        /// The function does not throw ANY exceptions. All exceptions will be
        /// caught inside of WriteXml().
        /// </remarks>
        public bool Write(string fileName)
        {
            // generate complete filename
            fileName = this.GetCompleteFilename(fileName);

            // Do NOT use UNICODE, because some of the target operating
            // system like Win 98, Win ME can't handle it
            // Do NOT use ASCII, since this does not support german umlaute.
            var xmlwriter = new TethysXmlTextWriter(fileName,
              this.Encoding);
            xmlwriter.XmlWriter.WriteStartDocument(false);
            xmlwriter.XmlWriter.Formatting = Formatting.Indented;
            xmlwriter.XmlWriter.Indentation = 2;

            this.WriteData(xmlwriter);

            xmlwriter.XmlWriter.Flush();
            xmlwriter.XmlWriter.Close();

            return true;
        } // WriteXml()

        /// <summary>
        /// This function reads the (user dependent) application configuration
        /// from a XML fileName that is located in the path for the application data
        /// of a roaming user, i.e. something like:
        ///   Base Path\CompanyName\ProductName\filename
        /// </summary>
        /// <remarks>
        /// This is the SAX-like version.
        /// The function does not throw ANY exceptions. All exceptions will be
        /// caught inside of ReadXml().
        /// </remarks>
        /// <param name="fileName">Name of the XML fileName to be used</param>
        /// <returns>The function returns true if all configuration data has
        /// been successfully read; otherwise false will be returned.
        /// </returns>
        public bool Read(string fileName)
        {
            // generate complete filename
            fileName = this.GetCompleteFilename(fileName);

            var xmlreader = new TethysXmlTextReader(fileName);
            xmlreader.WhitespaceHandling = WhitespaceHandling.None;

            try
            {
                this.ReadData(xmlreader);
            }
            finally
            {
                xmlreader.Close();
            } // finally
            return true;
        } // ReadXml()
        #endregion // PUBLIC METHODS
    } // TethysAppConfig
} // Tethys.App

// =================================
// Tethys: end of TethysAppConfig.cs
// =================================

redpajama_set_name: RedPajamaGithub


text:
import React, { useContext } from 'react'
import PropTypes from 'prop-types'
import { Modal, ModalVariant, Button } from '@patternfly/react-core'
import { MsgContext } from '_/intl'

const NavigationConfirmationModal = ({ show, onYes, onNo, additionalNote }) => {
  const { msg } = useContext(MsgContext)
  const idPrefix = 'close-dialog-confim'

  return (
    <Modal
      isOpen={show}
      title={msg.unsavedChangesConfirmMessage()}
      titleIconVariant='warning'
      variant={ModalVariant.small}
      onClose={onNo}
      position='top'
      actions={[
        <Button id={`${idPrefix}-button-yes`} key="confirm" variant="primary" onClick={onYes}>
          {msg.yes()}
        </Button>,
        <Button id={`${idPrefix}-button-no`} key="cancel" variant="link" onClick={onNo}>
          {msg.no()}
        </Button>,
      ]}
    >

{msg.allUnsavedWillBeLost()}

{additionalNote}

    </Modal>
  )
}
NavigationConfirmationModal.propTypes = {
  show: PropTypes.bool,
  onYes: PropTypes.func.isRequired,
  onNo: PropTypes.func.isRequired,
  additionalNote: PropTypes.string,
}
NavigationConfirmationModal.defaultProps = {
  show: false,
}

export default NavigationConfirmationModal


text:
package org.knowm.xchange.cryptonit2.dto.marketdata;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;

/** @author Matija Mazi */
public class CryptonitTransaction {

  private final long date;
  private final int tid;
  private final BigDecimal price;
  private final BigDecimal amount;
  private final int type;

  /**
   * Constructor
   *
   * @param date Unix timestamp date and time
   * @param tid Transaction id
   * @param price BTC price
   * @param amount BTC amount
   */
  public CryptonitTransaction(
      @JsonProperty("date") long date,
      @JsonProperty("tid") int tid,
      @JsonProperty("price") BigDecimal price,
      @JsonProperty("amount") BigDecimal amount,
      @JsonProperty("type") int type) {

    this.date = date;
    this.tid = tid;
    this.price = price;
    this.amount = amount;
    this.type = type;
  }

  public int getTid() {

    return tid;
  }

  public BigDecimal getPrice() {

    return price;
  }

  public BigDecimal getAmount() {

    return amount;
  }

  public long getDate() {

    return date;
  }

  public int getType() {

    return type;
  }

  @Override
  public String toString() {

    StringBuilder builder = new StringBuilder();
    builder.append("CryptonitTransaction [date=");
    builder.append(date);
    builder.append(", tid=");
    builder.append(tid);
    builder.append(", price=");
    builder.append(price);
    builder.append(", amount=");
    builder.append(amount);
    builder.append(", type=");
    builder.append(type);
    builder.append("]");
    return builder.toString();
  }
}


text:
        Setup
        PrimeNG setup consists of three steps; download, load and import. Various development configurations such as System.js or Webpack are supported.

Download

PrimeNG is available at npm, run the following commands to download the modules to your project. PrimeNG depends on PrimeUI so install it as well.

npm install primeng --save
npm install primeui --save

Load

PrimeNG is distributed in commonjs format and a module loader of your choice is required. Sample configuration with System.js would be as follows;

 System.config({
    defaultJSExtensions: true,
    packages: {
        "/angular2": {"defaultExtension": false}
    },
    map: {
        "/primeng": "node_modules/primeng"
    }
});

If you'd like to use webpack instead, scroll bottom to the webpack section.

Import

Components are imported from 'primeng/primeng' in your application code.

import {Accordion} from 'primeng/primeng';

Dependencies

PrimeUI provides optimized dependencies for PrimeNG via its distribution. These are the primeui-ng-all.js and primeui-ng-all.css files. The js file includes jquery, jquery-ui core, the PrimeUI widgets
    and the css file contains jquery-ui core along with structural css of PrimeUI widgets. The PrimeUI widgets in these two files are the ones utilized by PrimeNG not all the widgets. If you simply need the widgets and prefer your own jquery, use primeui-ng.js instead.
    Components also require font-awesome for icons and a theme of your choice for skinning.

<link rel="stylesheet" type="text/css" href="node_modules/primeui/themes/delta/theme.css" />
<link rel="stylesheet" type="text/css" href="PATH/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="node_modules/primeui/primeui-ng-all.min.css" />
<script src="node_modules/primeui/primeui-ng-all.min.js"></script>

jQuery (Optional)

In an Angular2 application, you don't need to use jQuery directly however some of the PrimeNG components are based on existing jQuery plugins (e.g. Schedule) although many others are native components.
        Dependencies section at the documentation of each component states the origin such as Native, jQuery/PrimeUI or an external library (e.g. charts.js). jQuery based ones in PrimeUI are optimized for PrimeNG integration using a technique called enhanced mode where plugin assumes dom is already created by PrimeNG component. As a result, jQuery plugin does not manipulate dom, only
        adds lightweight behaviors and low level requirements such as positioning. Changes as a result of one or two way binding are properly reflected between the UI and model. In addition components are destroyed whenever page is navigated away via router. In future
        as PrimeNG grows, remaining jQuery based ones will be replaced with native implementations where appropriate.

Quickstart with System.js

An example starter application based on angular2-quickstart is available at GitHub.

index.html

<html>

<head>
    <title>PrimeNG QuickStart</title>

    <!-- CSS for PrimeUI -->
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/themes/bootstrap/theme.css" />
    <link rel="stylesheet" type="text/css" href="app/resources/icons/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/primeui-ng-all.min.css" />

    <!-- 1. Load libraries -->
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- JS for PrimeUI -->
    <script src="node_modules/primeui/primeui-ng-all.min.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            defaultJSExtensions: true,
            packages: {
                "/angular2": {"defaultExtension": false}
            },
            map: {
                'primeng': 'node_modules/primeng'
            }
        });
        System.import('app/boot').then(null, console.error.bind(console));
    </script>

    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

</head>

<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>

</html>

boot.ts

import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';

bootstrap(AppComponent);

app.component.ts

Sample app component uses PrimeNG InputText.

import {Component} from 'angular2/core';
import {InputText} from 'primeng/primeng';

@Component({
	selector: 'my-app',
	template: `
        <h1>My First PrimeNG App</h1>
        <input type="text" pInputText/>
    `,
    directives: [InputText]
})
export class AppComponent {

}

Running npm install and then npm start, starts the lite-server, opens up a browser and runs the application.

Quickstart with Webpack

An example starter application with webpack is available at GitHub.

index.html

<html>

  <head>
    <title>PrimeNG QuickStart with Webpack</title>

    <link rel="stylesheet" type="text/css" href="node_modules/primeui/themes/delta/theme.css" />
    <link rel="stylesheet" type="text/css" href="app/resources/icons/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="node_modules/primeui/primeui-ng-all.min.css" />
    <link rel="stylesheet" type="text/css" href="app/resources/css/site.css"/>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
    <script src="dist/bundle.js"></script>
  </body>

</html>

package.json

{
  "name": "primeng-quickstart-webpack",
  "version": "v1.0.0-SNAPSHOT",
  "scripts": {
    "postinstall": "npm run typings install",
    "typings": "typings",
    "build": "webpack",
    "start": "webpack-dev-server --inline"
  },
  "license": "ISC",
  "dependencies": {
      "angular2": "2.0.0-beta.17",
      "systemjs": "0.19.26",
      "es6-shim": "^0.35.0",
      "reflect-metadata": "0.1.2",
      "rxjs": "5.0.0-beta.6",
      "zone.js": "0.6.12",
      "primeng": "1.0.0-beta.4",
      "primeui": "4.1.9"
  },
  "devDependencies": {
    "script-loader": "^0.6.1",
    "ts-loader": "^0.8.1",
    "typescript": "^1.8.10",
    "typings": "^0.8.1",
    "webpack": "^1.3.0",
    "webpack-dev-server": "^1.14.1"
  }
}

webpack.config.js

module.exports = {
  entry: './app/boot.ts',
  output: {
    filename: './dist/bundle.js'
  },
  resolve: {
    modulesDirectories: ['node_modules'],
    root: './app',
    extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'],
  },
  module: {
    loaders: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ],
    noParse: [ /zone\.js\/dist\/.+/, /angular2\/bundles\/.+/ ]
  }
};

boot.ts

import 'script!primeui/primeui-ng-all.min.js';
import 'angular2/bundles/angular2-polyfills';
import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import 'rxjs/Rx';

bootstrap(AppComponent);

app.component.ts

Sample app component uses PrimeNG InputText.

import {Component} from 'angular2/core';
import {InputText} from 'primeng/primeng';

@Component({
selector: 'my-app',
template: `
    <h1>My First PrimeNG App</h1>
    <input type="text" pInputText/>
`,
directives: [InputText]
})
export class AppComponent {

}

Running npm install and then npm start, starts the webpack-dev-server, opens up a browser and runs the application.

Angular2-Webpack-Starter

Angular2-Webpack-Start is a starter kit featuring an advanced development setup.
        We've our own fork that adds PrimeNG for the UI.

Angular2-Seed

Angular2-Seed is a modular seed project to kickstart an Angular2 app fast.
        Similarly to the webpack-starter, We've our own fork that adds PrimeNG for the UI.


text:
<?php

namespace ApiBundle\Api\Resource\Classroom;

use ApiBundle\Api\Resource\Filter;
use ApiBundle\Api\Resource\User\UserFilter;
use ApiBundle\Api\Util\AssetHelper;
use ApiBundle\Api\Util\Converter;
use ApiBundle\Api\Util\Money;
use AppBundle\Common\ServiceToolkit;

class ClassroomFilter extends Filter
{
    protected $simpleFields = array(
        'id', 'title', 'smallPicture', 'middlePicture', 'largePicture', 'price', 'studentNum', 'about'
    );

    protected $publicFields = array(
        'status', 'price', 'vipLevelId', 'headTeacher', 'teachers', 'assistants',
        'hitNum', 'auditorNum', 'studentNum', 'courseNum', 'threadNum', 'noteNum', 'postNum', 'service', 'recommended',
        'recommendedSeq', 'rating', 'ratingNum', 'maxRate', 'showable', 'buyable', 'expiryMode', 'expiryValue',
        'createdTime', 'updatedTime', 'creator', 'access'
    );

    protected function simpleFields(&$data)
    {
        $data['about'] = $this->convertAbsoluteUrl($data['about']);
        $this->transformCover($data);

        $data['price2'] = Money::convert($data['price']);
    }

    protected function publicFields(&$data)
    {
        if ($data['expiryMode'] == 'date') {
            Converter::timestampToDate($data['expiryStartDate']);
        }

        $data['service'] = ServiceToolkit::getServicesByCodes($data['service']);

        $userFilter = new UserFilter();
        $userFilter->setMode(Filter::SIMPLE_MODE);
        $userFilter->filter($data['creator']);
        $userFilter->filter($data['headTeacher']);
        $userFilter->filters($data['teachers']);
        $userFilter->filters($data['assistants']);
    }

    private function transformCover(&$data)
    {
        $data['smallPicture'] = AssetHelper::getFurl($data['smallPicture'], 'classroom.png');
        $data['middlePicture'] = AssetHelper::getFurl($data['middlePicture'], 'classroom.png');
        $data['largePicture'] = AssetHelper::getFurl($data['largePicture'], 'classroom.png');
        $data['cover'] = array(
            'small' => $data['smallPicture'],
            'middle' => $data['middlePicture'],
            'large' => $data['largePicture']
        );

        unset($data['smallPicture']);
        unset($data['middlePicture']);
        unset($data['largePicture']);
    }
}


text:
package com.cesarvaliente.androirwearnotifications.ui.utils;

/**
 * Created by cesar on 05/11/14.
 */
public class Constants {

    //Notification types Ids
    public static final int BASIC_NOTIFICATION_ID = 1;
    public static final int VOICE_NOTIFICATION_ID = 2;
    public static final int PAGES_NOTIFICATION_ID = 3;
    public static final int STACK_NOTIFICACION_ID = 4;

    //Extras
    public static final String RESULT_TEXT_EXTRA = "result_text_extra";
    public static final String EXTRA_VOICE_REPLY = "extra_voice_reply";

    //Stack notification stuff
    public static final String STACK_NOTIFICATION_GROUP_ID = "stack_notification_group_id";
    public static final int STACK_NOTIFICATION_ID_1 = 1;
    public static final int STACK_NOTIFICATION_ID_2 = 2;
    public static final int STACK_NOTIFICATION_ID_3 = 3;
    public static final int STACK_NOTIFICATION_ID_4 = 4;

}


text:
proto.seek = function (position, callback) {
	position = this.toValue(position);
	if (callback !== undefined) {
		var oldPos = this.view.tell();
		this.view.seek(position);
		var result = callback.call(this);
		this.view.seek(oldPos);
		return result;
	} else {
		return this.view.seek(position);
	}
};

proto.tell = function () {
	return this.view.tell();
};

proto.skip = function (offset, callback) {
	return this.seek(this.tell() + this.toValue(offset), callback);
};

proto.slice = function (start, end, forceCopy) {
	return new jBinary(this.view.slice(start, end, forceCopy), this.typeSet);
};


text:
from uw_sws.dao import SWS_DAO
from userservice.user import UserService

def get_netid_of_current_user():
    return UserService().get_user()

def is_using_file_dao():
    return SWS_DAO().get_implementation().is_mock()


text:
UIView-Overlay
===============

Plain and simple UIView category that adds overlay layer with specific color the the sublayers of the UIView.

##Requirements

* Xcode 5 (or higher)
* Apple LLVM compiler
* ARC
* iOS 6.1 (or higher)

##Installation

Recommended way to install AGToggleFieldSetView is via [CocoaPods](http://cocoapods.org/). Add the following line to your Podfile:

```ruby
pod 'UIView-Overlay'
```

##Usage

Just call methods methods to add or remove the overlay

```objc
[view ag_addOverlayWithColor: [[UIColor blackColor] colorWithAlphaComponent: 0.3]];
[view ag_removeOverlay];
```


text:
import { getColors } from '../../util/color';

/**
 * Paint polylines on the current image.
 * @memberof Image
 * @instance
 * @param {Array<Array<Array<number>>>} polylines - Array of array of [x,y] points
 * @param {object} [options]
 * @param {Array<number>|string}     [options.color] - Array of 3 elements (R, G, B) or a valid css color.
 * @param {Array<Array<number>>|Array<string>} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask
 * @param {boolean}             [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined
 * @param {boolean}             [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined
 * @param {object} [options.shape] - Definition of the shape, see Shape contructor.
 * @return {this} The original painted image
 */
export default function paintPolylines(polylines, options = {}) {
  let optionsCopy = Object.assign({}, options);

  this.checkProcessable('paintPolylines', {
    bitDepth: [8, 16],
  });

  let colors = getColors(
    Object.assign({}, options, { numberColors: polylines.length }),
  );

  for (let i = 0; i < polylines.length; i++) {
    optionsCopy.color = colors[i % colors.length];
    this.paintPolyline(polylines[i], optionsCopy);
  }

  return this;
}


text:
using System;
using System.Windows.Forms;
using FakeItEasy;
using NUnit.Framework;
using ShortcutRunner.ConfigurationParsing;
using ShortcutRunner.HotkeyRegistration;
using ShortcutRunner.ShortcutManagement;

namespace ShortcutRunner.Tests.ShortcutManagement
{
    class ShortcutManagerTests
    {
        [Test]
        public void Can_Initialize_Shortcuts()
        {
            // Arrange

            var sut = SutFactory.Create<ShortcutManager>();

            var firstLine = new ConfigurationLine
            {
                Shortcut = new ShortcutDescription(ModifierKeys.Alt, Keys.Z),
                Command = "first command"
            };

            var secondLine = new ConfigurationLine
            {
                Shortcut = new ShortcutDescription(ModifierKeys.Alt, Keys.Y),
                Command = "second command"
            };

            A.CallTo(() => sut.ConfigurationManager.ReadConfigurationFile())
                .Returns(new[] { firstLine, secondLine });

            var firstAction = A.Fake<Action>();
            var secondAction = A.Fake<Action>();

            A.CallTo(() => sut.CommandActionProvider.CreateCommandAction(firstLine.Command))
                .Returns(firstAction);

            A.CallTo(() => sut.CommandActionProvider.CreateCommandAction(secondLine.Command))
                .Returns(secondAction);

            // Act

            sut.Initialize();

            // Assert

            A.CallTo(() => sut.ShortcutController.RegisterShortcutAction(firstLine.Shortcut, firstAction))
                .MustHaveHappened();

            A.CallTo(() => sut.ShortcutController.RegisterShortcutAction(secondLine.Shortcut, secondAction))
                .MustHaveHappened();
        }
    }
}


text:
module example {

import clientViewportRect = phosphor.utility.clientViewportRect;

import BoxPanel = phosphor.widgets.BoxPanel;
import Direction = phosphor.widgets.Direction;
import Widget = phosphor.widgets.Widget;

function createContent(name: string): Widget {
  var widget = new Widget();
  widget.addClass('content');
  widget.addClass(name);
  return widget;
}

function main(): void {
  var red = createContent('red');
  var green = createContent('green');
  var blue = createContent('blue');
  var yellow = createContent('yellow');

  var panel = new BoxPanel();
  panel.addWidget(red, 1);
  panel.addWidget(green, 2);
  panel.addWidget(blue, 3);
  panel.addWidget(yellow, 1);

  panel.attach(document.getElementById('main'));

  var refresh = () => {
    if (clientViewportRect().width > 600) {
      panel.direction = Direction.LeftToRight;
    } else {
      panel.direction = Direction.TopToBottom;
    }
    panel.fit();
  };

  refresh();
  window.onresize = refresh;
}

window.onload = main;

} // module example


text:
package com.twitter.finagle.mux.exp.pushsession

import com.twitter.finagle.mux.{Handshake, Request, Response}
import com.twitter.finagle.mux.Handshake.{CanTinitMsg, Headers, TinitTag}
import com.twitter.finagle.{Mux, Service, Status}
import com.twitter.finagle.mux.transport.Message
import com.twitter.finagle.exp.pushsession.{PushSession, RefPushSession}
import com.twitter.io.{Buf, ByteReader}
import com.twitter.logging.{Level, Logger}
import com.twitter.util._
import scala.util.control.NonFatal

/**
 * Session which negotiates Mux features
 *
 * Instances of the `MuxServerNegotiator` assume ownership of the provided `Service` and
 * `PushChannelHandle`. Upon successful completion of the negotiation process ownership
 * of these is transferred to the session generated by the `negotiate` function.
 *
 * Thread safety considerations
 * - `receive` is only intended to be called from within the serial executor associated with
 *   the provided `PushChannelHandle`.
 * - `negotiation` will be called from within the `serialExecutor`
 * - `close` and `status` are safe to call from any thread.
 */
private[finagle] class MuxServerNegotiator private(
  handle: MuxChannelHandle,
  service: Service[Request, Response],
  makeLocalHeaders: Headers => Headers,
  negotiate: (Service[Request, Response], Option[Headers]) => PushSession[ByteReader, Buf],
  timer: Timer
) extends PushSession[ByteReader, Buf](handle) {
  import MuxServerNegotiator.log

  private[this] type Phase = Message => Unit

  private[this] val sessionP = Promise[PushSession[ByteReader, Buf]]
  private[this] var handshakePhase: Phase = checkRerrPhase

  @volatile
  private[this] var refSession: RefPushSession[ByteReader, Buf] = null

  // We need to be able to set the `refSession` after construction since
  // the `RefPushSession` needs a reference to `this` during its construction,
  // but `this` needs to be able to replace itself in the `RefPushSession`.
  private def setRefSession(ref: RefPushSession[ByteReader, Buf]): Unit = {
    refSession = ref
  }

  def onClose: Future[Unit] = handle.onClose

  handle.onClose.ensure {
    // If we have already completed negotiation, no need to close ourselves
    if (!sessionP.isDefined) close()
  }

  def close(deadline: Time): Future[Unit] = {
    // We want to proxy close calls to the underlying session, provided it resolves in time.
    // This facilitates draining behavior.
    sessionP.by(deadline)(timer).transform {
      case Return(session) => session.close(deadline)
      case Throw(_) => Closable.all(handle, service).close()
    }
  }

  def status: Status = handle.status

  def receive(message: ByteReader): Unit = {
    try {
      val msg = Message.decode(message)
      handshakePhase(msg)
    } catch {
      case NonFatal(t) =>
        close()
        throw t
    } finally message.close()
  }

  private[this] def checkRerrPhase: Phase = {
    case Message.Rerr(Handshake.TinitTag, Handshake.CanTinitMsg) =>
      if (log.isLoggable(Level.DEBUG)) {
        log.debug(s"Received Rerr prelude to Tinit. $remoteAddressString")
      }
      // Prepare to receive the Tinit and send the Rerr reply
      handshakePhase = getInitPhase
      handle.sendAndForget(Message.encode(Message.Rerr(TinitTag, CanTinitMsg)))

    case message => // No negotiation: just init a basic session
      if (log.isLoggable(Level.DEBUG)) {
        log.debug(s"Rerr prelude not detected (received ${message.getClass.getSimpleName}. " +
          s"Skipping Init phase. $remoteAddressString")
      }
      noInit(message)
  }

  private[this] def getInitPhase: Phase = {
    case Message.Tinit(tag, Mux.LatestVersion, headers) =>
      try {
        val localHeaders = makeLocalHeaders(headers)
        // We need to enqueue the message *now* so that it makes it down the pipeline before
        // we potentially install the Netty TLS ChannelHandler. If we use the standard
        // `sendAndForget` we bounce the send through the serial executor. If we try to execute
        // the pipeline changes via the continuation provided to `send`, we are not guaranteed
        // that it will happen before handling inbound bytes.
        handle.sendNowAndForget(Message.encode(Message.Rinit(tag, Mux.LatestVersion, localHeaders)))

        // pipeline changes for Opp-TLS
        val session = negotiate(service, Some(headers))
        negotiationSuccess(session)
      } catch {
        case NonFatal(t) => negotiationFailure(tag, t)
      }

    case Message.Tinit(tag, v, _) =>
      val ex = new IllegalStateException(s"Unsupported Mux version: $v")
      negotiationFailure(tag, ex)

    case message =>
      log.warning("Received Rerr init probe but didn't receive a follow up " +
        s"Tinit (received a ${message.getClass.getSimpleName}). $remoteAddressString")
      noInit(message)
  }

  // helper for logging purposes
  private[this] def remoteAddressString: String = s"remote: ${handle.remoteAddress}"

  private[this] def noInit(message: Message): Unit = {
    try {
      val session = negotiate(service, None)
      // Register the new session and then give it the message
      negotiationSuccess(session)
      session.receive(ByteReader(Message.encode(message)))
    } catch {
      case NonFatal(t) => negotiationFailure(message.tag, t)
    }
  }

  private[this] def negotiationSuccess(session: PushSession[ByteReader, Buf]): Unit = {
    // Upon success, we need to
    // 1. redirect events to the new session
    // 2. satisfy the promise which will trigger any pending `close` calls that occurred
    //    before negotiation completed.
    // The order of these events is not strictly important but its generally a good idea to
    // reshape our pipeline before triggering potentially arbitrary events via satisfying a
    // promise.
    refSession.updateRef(session)
    sessionP.setValue(session)
    handshakePhase = { m: Message =>
      // Should never get here
      val msg = "After negotiation success, more messages were sent to the " +
        s"negotiating session: ${m.getClass.getSimpleName}. $remoteAddressString"
      val ex = new IllegalStateException(msg)
      log.error(ex, msg)
      handle.close()
    }
  }

  private[this] def negotiationFailure(tag: Int, t: Throwable): Unit = {
    // Negotiation failed, so we need to cleanup and shutdown.
    log.warning(t, s"Negotiation failed. Closing session. $remoteAddressString")

    // This is not necessarily unexpected if the peer thinks the session is now open
    handshakePhase = { msg: Message =>
      if (log.isLoggable(Level.DEBUG)) {
        log.debug(t, s"Session negotiation failed. Swallowing message " +
          s"(${msg.getClass.getSimpleName}) that raced shutdown. $remoteAddressString")
      }
    }

    handle.send(Message.encode((Message.Rerr(tag, t.getMessage)))) { _ =>
      close().ensure {
        sessionP.setException(t)
      }
    }
  }
}

private object MuxServerNegotiator {
  private val log = Logger.get

  def apply(
    handle: MuxChannelHandle,
    service: Service[Request, Response],
    makeLocalHeaders: Headers => Headers,
    negotiate: (Service[Request, Response], Option[Headers]) => PushSession[ByteReader, Buf],
    timer: Timer
  ): PushSession[ByteReader, Buf] = {
    val negotiatingSession = new MuxServerNegotiator(handle, service, makeLocalHeaders, negotiate, timer)
    val ref = new RefPushSession[ByteReader, Buf](handle, negotiatingSession)
    negotiatingSession.setRefSession(ref)
    ref
  }
}


text: UsersXP = new Mongo.Collection('usersXP');


text:
<?php

namespace Zephir\Operators\Other;

use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\Exception\CompilerException;
use Zephir\Expression;
use Zephir\Operators\BaseOperator;

/**
 * Require.
 *
 * Includes a plain PHP file
 */
class RequireOperator extends BaseOperator
{
    /**
     * @param array              $expression
     * @param CompilationContext $compilationContext
     *
     * @throws CompilerException
     *
     * @return CompiledExpression
     */
    public function compile(array $expression, CompilationContext $compilationContext)
    {
        $expr = new Expression($expression['left']);
        $expr->setReadOnly(true);
        $expr->setExpectReturn(true);

        $exprPath = $expr->compile($compilationContext);
        if ('variable' == $exprPath->getType()) {
            $exprVariable = $compilationContext->symbolTable->getVariableForRead($exprPath->getCode(), $compilationContext, $expression);
            $exprVar = $compilationContext->backend->getVariableCode($exprVariable);
            if ('variable' == $exprVariable->getType()) {
                if ($exprVariable->hasDifferentDynamicType(['undefined', 'string'])) {
                    $compilationContext->logger->warning(
                        'Possible attempt to use invalid type as path in "require" operator',
                        ['non-valid-require', $expression]
                    );
                }
            }
        } else {
            $exprVar = $compilationContext->symbolTable->getTempVariableForWrite('variable', $compilationContext, $expression);
            $compilationContext->backend->assignString($exprVar, $exprPath->getCode(), $compilationContext);
            $exprVar = $compilationContext->backend->getVariableCode($exprVar);
        }

        $symbolVariable = false;
        if ($this->isExpecting()) {
            $symbolVariable = $compilationContext->symbolTable->getTempVariableForObserveOrNullify('variable', $compilationContext, $expression);
        }

        $compilationContext->headersManager->add('kernel/memory');
        $compilationContext->headersManager->add('kernel/require');

        $codePrinter = $compilationContext->codePrinter;

        if ($symbolVariable) {
            $codePrinter->output('ZEPHIR_OBSERVE_OR_NULLIFY_PPZV(&'.$symbolVariable->getName().');');
            $symbol = $compilationContext->backend->getVariableCodePointer($symbolVariable);
            $codePrinter->output('if (zephir_require_zval_ret('.$symbol.', '.$exprVar.') == FAILURE) {');
        } else {
            $codePrinter->output('if (zephir_require_zval('.$exprVar.') == FAILURE) {');
        }
        $codePrinter->output("\t".'RETURN_MM_NULL();');
        $codePrinter->output('}');

        if ($symbolVariable) {
            return new CompiledExpression('variable', $symbolVariable->getName(), $expression);
        }

        return new CompiledExpression('null', null, $expression);
    }
}


text:
var webpack = require('webpack');
var generateConfig = require("./webpack.config.base");
var exec = require("child_process").execSync;
var path = require("path");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
global.WEBPACK_ENV = "production";

c = function() {
    var conf = generateConfig();

    conf
        .module
        .loaders
        .push({
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract('style', 'css-loader!sass-loader')
        });

    conf.devtool = 'source-map';

    conf
        .plugins
        .push(new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production'),
            'process.env.REVISION': JSON.stringify(
                exec('git log --pretty=format:"%h%n%ad%n%f" -1').toString()),
        }));

    conf
        .plugins
        .push(new webpack.optimize.UglifyJsPlugin({
            compressor: { warnings: false },
        }));

    conf
        .plugins
        .push(new ExtractTextPlugin("app-resources/styles.css"));
    return conf;
}

module.exports = c();


text:
package com.cuitrip.app;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.lab.utils.LogHelper;
import com.lab.utils.imageupload.CacheDirManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by baziii on 15/7/28.
 */
public class PersonalDescSaver {
    public static final String TAG = "PersonalDescSaver";

    public static void saveAll(final List<Bitmap> bitmapList, final String content) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserConfig.getInstance().setPersonalDesc(content);
                if (bitmapList != null) {
                    for (Bitmap bitmap : bitmapList) {
                        try {
                            save(bitmap);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }

    public static Bitmap getBitmap(String name) {
        return BitmapFactory.decodeFile(CacheDirManager.getInstance().picDir() + "/" + name);
    }

    public static void clean() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                UserConfig.getInstance().setPersonalDesc("");
                CacheDirManager.clearDir(CacheDirManager.getInstance().picDir()
                );
            }
        }).start();
    }

    private static void save(Bitmap bitmap) throws IOException {
        File var6 = new File(CacheDirManager.getInstance().picDir(), String.valueOf(bitmap.hashCode()));
        FileOutputStream var7 = new FileOutputStream(var6);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, var7);
        var7.flush();
        var7.close();
        LogHelper.e(TAG, "save " + var6.getAbsolutePath());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="@dimen/card_margin_bottom"
    app:cardCornerRadius="2dp"
    app:cardPreventCornerOverlap="false">

    <RelativeLayout
        android:id="@+id/pull_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/pull_title"
            android:layout_width="250dp"
            android:paddingTop="@dimen/card_title_top_padding"
            android:paddingBottom="@dimen/card_title_bottom_padding"
            android:paddingLeft="@dimen/card_title_left_right_padding"
            android:paddingRight="@dimen/card_title_left_right_padding"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="@string/pull_title_mock"
            android:textSize="24sp" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/pull_body"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:layout_below="@id/pull_title"
            android:paddingBottom="@dimen/card_subtext_bottom_padding"
            android:paddingLeft="@dimen/card_subtext_left_right_padding"
            android:paddingRight="@dimen/card_subtext_left_right_padding"
            android:text="@string/pull_body_mock"
            android:ellipsize="end"
            android:maxLines="5"
            android:textSize="14sp" />

        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/pull_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/pull_body"
            android:drawableLeft="@drawable/ic_date_range_white_24dp"
            android:gravity="center_vertical"
            android:padding="@dimen/card_action_padding"
            android:text="@string/pull_created_date_mock"
            android:textColor="@color/pull_date_color"
            android:textSize="20sp" />

        <LinearLayout
            android:id="@+id/pull_user_container"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:paddingRight="@dimen/card_image_subtitle_container_right_padding"
            android:orientation="vertical">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/pull_user_img"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_account_circle_white_24dp"
                app:civ_border_color="#FFFF"
                app:civ_border_width="2dp" />

            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/pull_username"
                android:layout_width="70dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:gravity="center"
                android:text="@string/repository_owner_mock"
                android:textSize="15sp"
                android:textStyle="bold" />
        </LinearLayout>

    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
<?php

namespace AppBundle\Form;

use AppBundle\Entity\Matxura;
use AppBundle\Form\MatxuraType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class MaileguakHasiType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('bezeroa', EntityType::class, array(
                'class' => 'AppBundle:Bezeroa',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('b')
                        ->where('b.alokatua <> 1 or b.alokatua is NULL')
                        ->orderBy('b.izena', 'ASC');
                },
                'required' => true,
                'placeholder' => 'Aukeratu Bezeroa'
            ))
            ->add('guneahasi',null, array('label' => 'form.name','required' => true, 'placeholder' => 'Aukeratu gunea'))

            ->add('bizikleta', EntityType::class, array(
                    'class' => 'AppBundle:Bizikleta',
                    'query_builder' => function (EntityRepository $er) {
                        return $er->createQueryBuilder('b')
                            ->where('b.alokatua <> 1 or b.alokatua is NULL')
                            ->orderBy('b.kodea', 'ASC');
                    },
                    'required' => true,
                    'placeholder' => 'Aukeratu Bizikleta'
            ))
            ->add('fetxa_hasi',DatetimeType::class, array('widget' => 'single_text'))

            ->add('ibilbidea',null, array('label' => 'form.name','required' => true, 'placeholder' => 'Aukeratu ibilbidea'))
            ->add('eguraldia',null, array('label' => 'form.name','required' => true, 'placeholder' => 'Aukeratu Eguraldia'))

        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Maileguak'
        ));
    }
}


text:
{% if jekyll.environment == "development" %}
  <script src="{{"/assets/vendor/jquery/jquery.min.js" | relative_url }}"></script>
  <script src="{{"/assets/vendor/bootstrap/js/bootstrap.bundle.min.js" | relative_url }}"></script>
  <script src="{{"/assets/vendor/scripts.js" | relative_url }}"></script>
  <script src="{{"/assets/vendor/prism/js/prism.js" | relative_url }}"></script>
  {% endif %}

  {% if jekyll.environment == "production" %}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>
  <script src="{{"/assets/vendor/kjanshair/js/kjanshair.min.js" | relative_url }}"></script>
  {% endif %}

  <script src="{{"/assets/main.min.js" | relative_url }}"></script>


text:
<?php

class CTabView extends CDiv {

	protected $id = 'tabs';
	protected $tabs = array();
	protected $headers = array();
	protected $selectedTab = null;

	/**
	 * Disabled tabs IDs, tab option
	 *
	 * @var array
	 */
	protected $disabledTabs = array();

	public function __construct($data = array()) {
		if (isset($data['id'])) {
			$this->id = $data['id'];
		}
		if (isset($data['selected'])) {
			$this->setSelected($data['selected']);
		}
		if (isset($data['disabled'])) {
			$this->setDisabled($data['disabled']);
		}
		parent::__construct();
		$this->attr('id', zbx_formatDomId($this->id));
		$this->attr('class', 'tabs');
	}

	public function setSelected($selected) {
		$this->selectedTab = $selected;
	}

	/**
	 * Disable tabs
	 *
	 * @param array		$disabled	disabled tabs IDs (first tab - 0, second - 1...)
	 *
	 * @return void
	 */
	public function setDisabled($disabled) {
		$this->disabledTabs = $disabled;
	}

	public function addTab($id, $header, $body) {
		$this->headers[$id] = $header;
		$this->tabs[$id] = new CDiv($body);
		$this->tabs[$id]->attr('id', zbx_formatDomId($id));
	}

	public function toString($destroy = true) {
		if (count($this->tabs) == 1) {
			$this->setAttribute('class', 'min-width ui-tabs ui-widget ui-widget-content ui-corner-all widget');

			$header = reset($this->headers);
			$header = new CDiv($header);
			$header->addClass('ui-corner-all ui-widget-header header');
			$header->setAttribute('id', 'tab_'.key($this->headers));
			$this->addItem($header);

			$tab = reset($this->tabs);
			$tab->addClass('ui-tabs ui-tabs-panel ui-widget ui-widget-content ui-corner-all widget');
			$this->addItem($tab);
		}
		else {
			$headersList = new CList();

			foreach ($this->headers as $id => $header) {
				$tabLink = new CLink($header, '#'.$id, null, null, false);
				$tabLink->setAttribute('id', 'tab_'.$id);
				$headersList->addItem($tabLink);
			}

			$this->addItem($headersList);
			$this->addItem($this->tabs);

			if ($this->selectedTab === null) {
				$activeTab = get_cookie('tab', 0);
				$createEvent = '';
			}
			else {
				$activeTab = $this->selectedTab;
				$createEvent = 'create: function() { jQuery.cookie("tab", '.$this->selectedTab.'); },';
			}

			$disabledTabs = ($this->disabledTabs === null) ? '' : 'disabled: '.CJs::encodeJson($this->disabledTabs).',';

			zbx_add_post_js('
				jQuery("#'.$this->id.'").tabs({
					'.$createEvent.'
					'.$disabledTabs.'
					active: '.$activeTab.',
					activate: function(event, ui) {
						jQuery.cookie("tab", ui.newTab.index().toString());
					}
				})
				.css("visibility", "visible");'
			);
		}

		return parent::toString($destroy);
	}
}


text:
using HockeyApp.Repositories.Contracts.Base;
using HockeyApp.Models.Games.Matches;

namespace HockeyApp.Repositories.Contracts
{
    public interface IMatchRepository : IRepository<long, Match>
    {
    }
}


text:
using static System.Math;

namespace Colourful;

/// <summary>
/// Euclidean distance between two color vectors.
/// </summary>
public sealed class EuclideanDistanceColorDifference<TColor> : IColorDifference<TColor>
    where TColor : IColorSpace, IColorVector
{
    /// <summary>
    /// Computes distance between two color vectors as euclidean distance.
    /// </summary>
    public double ComputeDifference(in TColor x, in TColor y)
    {
        var distanceSquared = 0d;
        var vectorSize = Min(x.Vector.Length, y.Vector.Length);

        for (var i = 0; i < vectorSize; i++)
        {
            var xi = x.Vector[i];
            var yi = y.Vector[i];

            var xyiDiff = xi - yi;
            distanceSquared += xyiDiff * xyiDiff;
        }

        var distance = Sqrt(distanceSquared);
        return distance;
    }
}


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="thin.blog.ibts.Lister">

    <LinearLayout 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:orientation="vertical">

        <TextView
            android:id="@+id/title_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="List"
            android:textColor="@color/colorPrimary" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/main_list_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp" />

        <TextView
            android:id="@+id/details_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="Details"
            android:textColor="@color/colorPrimary" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/detail_list_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp" />

    </LinearLayout>
</ScrollView>


text:
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;

using NUnit.Framework;

using Google.Apis.Discovery;
using Google.Apis.Testing;
using Google.Apis.Tools.CodeGen.Decorator;
using Google.Apis.Tools.CodeGen.Decorator.ResourceDecorator;

namespace Google.Apis.Tools.CodeGen.Tests.Decorator
{
    ///  Tests the DecoratorUtil class.
    [TestFixture]
    public class DecoratorUtilTest
    {
        ///
        /// Tests edge cases for the AddAutoProperty method.
        ///
        [Test]
        public void CreateAutoPropertyEdgeCaseTest()
        {
            const string name = "TestProperty";
            const string comment = "Comment";
            CodeTypeReference type = new CodeTypeReference(typeof(object));
            string[] usedWords = new string[] { };

            Assert.Throws<ArgumentNullException>(
                () => DecoratorUtil.CreateAutoProperty(null, comment, type, usedWords, false));
            Assert.Throws<ArgumentNullException>(
                () => DecoratorUtil.CreateAutoProperty(name, comment, null, usedWords, false));
            Assert.Throws<ArgumentNullException>(
                () => DecoratorUtil.CreateAutoProperty(name, comment, type, null, false));
            Assert.DoesNotThrow(() => DecoratorUtil.CreateAutoProperty(name, null, type, usedWords, false));
        }

        ///
        /// Tests the AddAutoProperty method.
        ///
        [Test]
        public void CreateAutoPropertyTest()
        {
            const string name = "TestProperty";
            const string comment = "Comment";
            CodeTypeReference type = new CodeTypeReference(typeof(int));
            string[] usedWords = new string[] { };

            CodeTypeMemberCollection col = DecoratorUtil.CreateAutoProperty(name, comment, type, usedWords, false);

            Assert.That(col.Count, Is.EqualTo(2));
            Assert.That(col[1], Is.InstanceOf<CodeMemberProperty>());
            Assert.That(col[1].Attributes, Is.EqualTo(MemberAttributes.Public));
            Assert.That(col[0], Is.InstanceOf<CodeMemberField>());

            var property = col[1] as CodeMemberProperty;
            Assert.IsNotNull(property);
            Assert.That(property.Name, Is.EqualTo(name));
            Assert.That(property.Type.BaseType, Is.EqualTo(typeof(int).FullName));

            // Backening field is tested in its own unit case.
        }

        ///
        /// Tests edge cases for the CreateBackingfield method.
        ///
        [Test]
        public void CreateBackingFieldEdgeCaseTest()
        {
            const string name = "TestProperty";
            CodeTypeReference type = new CodeTypeReference(typeof(object));
            string[] usedWords = new string[] { };

            Assert.Throws<ArgumentNullException>(() => DecoratorUtil.CreateBackingField(null, type, usedWords));
            Assert.Throws<ArgumentNullException>(() => DecoratorUtil.CreateBackingField(name, null, usedWords));
            Assert.Throws<ArgumentNullException>(() => DecoratorUtil.CreateBackingField(name, type, null));
        }

        ///
        /// Tests the generation of backing fields.
        ///
        [Test]
        public void CreateBackingFieldTest()
        {
            const string name = "TestProperty";
            CodeTypeReference type = new CodeTypeReference(typeof(bool));
            string[] usedWords = new string[] { };

            CodeMemberField field = DecoratorUtil.CreateBackingField(name, type, usedWords);
            Assert.IsNotNull(field);
            Assert.That(field.Name, Is.EqualTo("_TestProperty"));
            Assert.That(field.Type.BaseType, Is.EqualTo(typeof(bool).FullName));
            Assert.That(field.Attributes, Is.EqualTo(MemberAttributes.Private));
        }

        ///
        /// Tests the creation of a simple comment.
        ///
        [Test]
        public void CreateSummaryCommentTest()
        {
            string aShortDescription = "A Short description for test";
            var result = DecoratorUtil.CreateSummaryComment(aShortDescription);
            Assert.IsNotNull(result);
            Assert.AreEqual(1, result.Count);
            Assert.IsNotNull(result[0].Comment);
            Assert.AreEqual(true, result[0].Comment.DocComment);
            Assert.AreEqual("" + aShortDescription + "", result[0].Comment.Text);
        }
        ///
        /// Checks if empty comments can be created.
        ///
        [Test]
        public void CreateSummaryCommentEmptyCommentTest()
        {
            // Test an empty comment.
            var result = DecoratorUtil.CreateSummaryComment("");
            Assert.IsNotNull(result);
            Assert.IsEmpty(result);

            // Test a null comment.
            result = DecoratorUtil.CreateSummaryComment(null);
            Assert.IsNotNull(result);
            Assert.IsEmpty(result);
        }

        ///
        /// Checks if xml escapes are done on non-compilant xml strings.
        ///
        [Test]
        public void CreateSummaryCommentXmlEscapeTest()
        {
            string aShortDescription = "A 'Short\" <description> <for/> test & fun";
            var result = DecoratorUtil.CreateSummaryComment(aShortDescription);
            string desiredComment =
                "A 'Short" <description> <for/> test & fun";
            Assert.AreEqual(desiredComment, result[0].Comment.Text);
        }

        ///
        /// Tests the AddMembersToClass method.
        ///
        [Test]
        public void AddMembersToClassTest()
        {
            var decl = new CodeTypeDeclaration();
            var memberA = new CodeTypeMember() { Name = "MemberA" };
            var memberB = new CodeTypeMember() { Name = "MemberB" };
            var memberC = new CodeTypeMember() { Name = "MemberA" };

            // Test parameter validation
            Assert.Throws<ArgumentNullException>(
                () => DecoratorUtil.AddMembersToClass(null, new CodeTypeMemberCollection()));
            Assert.Throws<ArgumentNullException>(() => DecoratorUtil.AddMembersToClass(decl, null));

            // Add a single element.
            DecoratorUtil.AddMembersToClass(decl, new CodeTypeMemberCollection(new[] { memberA }));
            Assert.AreEqual(1, decl.Members.Count);

            // Confirm that this element is skipped when adding it twice.
            DecoratorUtil.AddMembersToClass(decl, new CodeTypeMemberCollection(new[] { memberA }));
            Assert.AreEqual(1, decl.Members.Count);

            // Add the remaining elements
            DecoratorUtil.AddMembersToClass(decl, new CodeTypeMemberCollection(new[] { memberA, memberB, memberC }));
            Assert.AreEqual(2, decl.Members.Count);
        }

        ///
        /// Tests the GetEnumerablePairs method..
        ///
        [Test]
        public void GetEnumerablePairsTest()
        {
            string[] keys = new[] { "a", "b", "c" };
            string[] values = new[] { "1", "2", "3" };
            string[] invalidSized = new[] { "1", "2", "3", "x", "y" };

            // Test parameter validation.
            Assert.Throws<ArgumentNullException>(
                () => DecoratorUtil.GetEnumerablePairs((string[])null, values).First());
            Assert.DoesNotThrow(() => DecoratorUtil.GetEnumerablePairs(keys, (string[])null).First());

            Assert.Throws<ArgumentException>(() => DecoratorUtil.GetEnumerablePairs(keys, invalidSized).First());
            Assert.Throws<ArgumentException>(() => DecoratorUtil.GetEnumerablePairs(invalidSized, values).First());

            // Test simple operation.
            IEnumerable<KeyValuePair<string, string>> joined = DecoratorUtil.GetEnumerablePairs(keys, values);
            Assert.AreEqual(3, joined.Count());

            foreach (KeyValuePair<string, string> pair in joined)
            {
                Assert.AreEqual(pair.Key[0] - 'a', pair.Value[0] - '1');
            }
        }

        ///
        /// Tests the FindFittingEnumeration method.
        ///
        [Test]
        public void FindFittingEnumerationTest()
        {
            CodeTypeDeclaration decl = new CodeTypeDeclaration();
            IEnumerable<string> enumValues = new[] { "foo", "bar", "42" };
            IEnumerable<string> enumValues2 = new[] { "foo", "bar", "cake" };
            IEnumerable<string> enumValues3 = new[] { "foo", "bar" };

            // Test parameter validation.
            Assert.Throws<ArgumentNullException>(() => DecoratorUtil.FindFittingEnumeration(decl, null, null));
            Assert.Throws<ArgumentNullException>(() => DecoratorUtil.FindFittingEnumeration(null, enumValues, null));

            // Test with empty class.
            Assert.IsNull(DecoratorUtil.FindFittingEnumeration(decl, enumValues, null));

            // Add an enum, and check whether it can be found.
            CodeTypeDeclaration testEnum = EnumResourceDecorator.GenerateEnum(
                decl, "SomeName", "SomeDescription", enumValues, null);
            decl.Members.Add(testEnum);
            Assert.AreEqual(testEnum.Name, DecoratorUtil.FindFittingEnumeration(decl, enumValues, null).BaseType);

            // Confirm that the other values are not found.
            Assert.IsNull(DecoratorUtil.FindFittingEnumeration(decl, enumValues2, null));
            Assert.IsNull(DecoratorUtil.FindFittingEnumeration(decl, enumValues3, null));

            // Check that the code also works with two enumerations
            CodeTypeDeclaration testEnum3 = EnumResourceDecorator.GenerateEnum(
                decl, "SomeOtherName", "SomeDescription", enumValues3, null);
            decl.Members.Add(testEnum3);

            Assert.AreEqual(testEnum.Name, DecoratorUtil.FindFittingEnumeration(decl, enumValues, null).BaseType);
            Assert.AreEqual(testEnum3.Name, DecoratorUtil.FindFittingEnumeration(decl, enumValues3, null).BaseType);
            Assert.IsNull(DecoratorUtil.FindFittingEnumeration(decl, enumValues2, null));
        }

        ///
        /// Test the IsFittingEnum method
        ///
        [Test]
        public void IsFittingEnumTest()
        {
            var decl = new CodeTypeDeclaration();
            IEnumerable<string> enumValues = new[] { "foo", "bar", "42" };
            IEnumerable<string> enumValues2 = new[] { "foo", "bar", "cake" };
            IEnumerable<string> enumValues3 = new[] { "foo", "bar" };

            // Add an enum, and check whether it can be found.
            CodeTypeDeclaration testEnum = EnumResourceDecorator.GenerateEnum(
                decl, "SomeName", "SomeDescription", enumValues, null);
            decl.Members.Add(testEnum);
            Assert.IsTrue(DecoratorUtil.IsFittingEnum(testEnum, enumValues, null));
            Assert.IsFalse(DecoratorUtil.IsFittingEnum(testEnum, enumValues2, null));
            Assert.IsFalse(DecoratorUtil.IsFittingEnum(testEnum, enumValues3, null));
            Assert.IsFalse(DecoratorUtil.IsFittingEnum(testEnum, Enumerable.Empty<string>(), null));
        }

        ///
        /// Test the IsFittingEnum method with enum comments
        ///
        [Test]
        public void IsFittingEnumCommectTest()
        {
            var decl = new CodeTypeDeclaration();
            IEnumerable<string> enumValues = new[] { "foo", "bar", "42" };
            IEnumerable<string> enumCommentsA = new[] { "fish", "dolphins", "mice" };
            IEnumerable<string> enumCommentsB = new[] { "fishy", "dolphiny", "micy" };
            IEnumerable<string> enumCommentsC = null;

            // Add an enum, and check whether it can be found.
            CodeTypeDeclaration testEnum = EnumResourceDecorator.GenerateEnum(
                decl, "SomeName", "SomeDescription", enumValues, enumCommentsA);
            decl.Members.Add(testEnum);
            Assert.IsTrue(DecoratorUtil.IsFittingEnum(testEnum, enumValues, enumCommentsA));
            Assert.IsFalse(DecoratorUtil.IsFittingEnum(testEnum, enumValues, enumCommentsB));
            Assert.IsFalse(DecoratorUtil.IsFittingEnum(testEnum, enumValues, enumCommentsC));
        }

        ///
        /// Tests initialize parameters with null dictionary
        ///
        [Test]
        public void CreateInitParameters_NullDictionary()
        {
            CodeMemberMethod method = new CodeMemberMethod();
            DecoratorUtil.AddInitializeParameters(method, "par", null);

            Assert.AreEqual(2, method.Statements.Count); // new and assignment
            Assert.That(method.Statements[0], Is.InstanceOf<CodeVariableDeclarationStatement>());
            Assert.That(method.Statements[1], Is.InstanceOf<CodeAssignStatement>());
        }

        ///
        /// Tests initialize parameters with null dictionary
        ///
        [Test]
        public void CreateInitParameters_EmptyDictionary()
        {
            CodeMemberMethod method = new CodeMemberMethod();
            DecoratorUtil.AddInitializeParameters(method, "par", new Dictionary<string, IDiscoveryParameter> { });

            Assert.AreEqual(2, method.Statements.Count); // new and assignment
            Assert.That(method.Statements[0], Is.InstanceOf<CodeVariableDeclarationStatement>());
            Assert.That(method.Statements[1], Is.InstanceOf<CodeAssignStatement>());
        }

        ///
        /// Tests the new init parameters with empty parameters
        ///
        [Test]
        public void CreateInitParameters_WithParameters()
        {
            CodeMemberMethod method = new CodeMemberMethod();

            var parameters = new Dictionary<string, IDiscoveryParameter>();
            parameters["param1"] = new MockParameter
            {
                Name = "param1",
                DefaultValue = "default",
                IsRequired = true,
                Pattern = "pattern",
                ParameterType = "type",
                EnumValues = new[] { "1", "2" }
            };
            DecoratorUtil.AddInitializeParameters(method, "par", parameters);

            Assert.AreEqual(3, method.Statements.Count); // new, assignment and add parameter on dictionary methods
            Assert.That(method.Statements[0], Is.InstanceOf<CodeVariableDeclarationStatement>());

            // parameters.Add(param1, ...)
            Assert.That(method.Statements[1], Is.InstanceOf<CodeExpressionStatement>());
            CodeExpressionStatement exp = method.Statements[1] as CodeExpressionStatement;
            Assert.That(exp.Expression, Is.InstanceOf<CodeMethodInvokeExpression>());
            CodeMethodInvokeExpression addMethod = exp.Expression as CodeMethodInvokeExpression;
            Assert.AreEqual("Add", addMethod.Method.MethodName);
            Assert.AreEqual(2, addMethod.Parameters.Count);

            // parameters = param1, CreateRuntimeParameter(...)
            Assert.That(addMethod.Parameters[0], Is.InstanceOf<CodePrimitiveExpression>());
            var nameExp = addMethod.Parameters[0] as CodePrimitiveExpression;
            Assert.AreEqual("param1", nameExp.Value);
            Assert.That(addMethod.Parameters[1], Is.InstanceOf<CodeMethodInvokeExpression>());
            var createParameterExp = addMethod.Parameters[1] as CodeMethodInvokeExpression;
            Assert.AreEqual("CreateRuntimeParameter", createParameterExp.Method.MethodName);
            Assert.AreEqual(6, createParameterExp.Parameters.Count);

            // name
            Assert.That(createParameterExp.Parameters[0], Is.InstanceOf<CodePrimitiveExpression>());
            Assert.AreEqual("param1", (createParameterExp.Parameters[0] as CodePrimitiveExpression).Value);
            // is required
            Assert.That(createParameterExp.Parameters[1], Is.InstanceOf<CodePrimitiveExpression>());
            Assert.AreEqual(true, (createParameterExp.Parameters[1] as CodePrimitiveExpression).Value);
            // parameter type
            Assert.That(createParameterExp.Parameters[2], Is.InstanceOf<CodePrimitiveExpression>());
            Assert.AreEqual("type", (createParameterExp.Parameters[2] as CodePrimitiveExpression).Value);
            // default value
            Assert.That(createParameterExp.Parameters[3], Is.InstanceOf<CodePrimitiveExpression>());
            Assert.AreEqual("default", (createParameterExp.Parameters[3] as CodePrimitiveExpression).Value);
            // pattern
            Assert.That(createParameterExp.Parameters[4], Is.InstanceOf<CodePrimitiveExpression>());
            Assert.AreEqual("pattern", (createParameterExp.Parameters[4] as CodePrimitiveExpression).Value);
            // enum values
            Assert.That(createParameterExp.Parameters[5], Is.InstanceOf<CodeArrayCreateExpression>());
            Assert.AreEqual(2, (createParameterExp.Parameters[5] as CodeArrayCreateExpression).Initializers.Count);

            Assert.That(method.Statements[2], Is.InstanceOf<CodeAssignStatement>());
        }
    }
}


text:
class ComponentMaterial;
class GameObject;

class ModuleSceneIntro : public Module
{
public:
	ModuleSceneIntro(Application* app, bool start_enabled = true);
	~ModuleSceneIntro();

	bool Start();
	update_status Update(float dt);
	bool CleanUp();

	void Save(JSON_file& config);
	void Load(JSON_file& config);

	void DrawScene();
	void AddRootObject(GameObject* game_obj);		// utility to add objects to both root_objects and all_objects vector
	GameObject* GetSelectedObj();
public:

	std::vector<GameObject*> all_game_objects;
	std::vector<GameObject*> root_game_objects;		// for recursive functions
	std::string selected_game_obj_uid;

	std::vector<ComponentMaterial*> materials;

	// config saved variables
	std::string name = "main_scene.json";

};


text:
describe("RAML.Inspector.ParameterizedHeader", function() {
  var name, definition, parameterizedHeader;

  beforeEach(function() {
    name = "X-Custom-{*}";
    definition = { type: 'string' };

    parameterizedHeader = RAML.Inspector.ParameterizedHeader.fromRAML(name, definition);
  });

  describe("creating a header", function() {
    var header;

    describe("by default", function() {
      beforeEach(function() {
        header = parameterizedHeader.create("test");
      });

      it("returns a new header definition", function() {
        expect(header.displayName).toEqual('X-Custom-test');
        expect(header.type).toEqual(definition.type);
      });
    });

    describe("with an empty string", function() {
      it("throws", function() {
        expect(function() {
          parameterizedHeader.create('');
        }).toThrow();
      });
    });
  });
});


text:
package im.AfriChat.runtime.generic.mvvm;

import java.util.ArrayList;

public class AndroidListUpdate<T> {

    private ArrayList<T> list;
    private ArrayList<ChangeDescription<T>> changes;
    private boolean isLoadMore;

    public AndroidListUpdate(ArrayList<T> list, ArrayList<ChangeDescription<T>> changes, boolean isLoadMore) {
        this.list = new ArrayList<T>(list);
        this.changes = changes;
        this.isLoadMore = isLoadMore;
    }

    public int getSize() {
        return list.size();
    }

    public T getItem(int index) {
        return list.get(index);
    }

    public boolean isLoadMore() {
        return isLoadMore;
    }

    public ChangeDescription<T> next() {
        if (changes.size() == 0) {
            return null;
        }
        ChangeDescription<T> res = changes.remove(0);
        switch (res.getOperationType()) {
            case ADD:
                int addIndex = res.getIndex();
                for (T itm : res.getItems()) {
                    list.add(addIndex++, itm);
                }
                break;
            case UPDATE:
                int updateIndex = res.getIndex();
                for (T itm : res.getItems()) {
                    int index = updateIndex++;
                    list.remove(index);
                    list.add(index, itm);
                }
                break;
            case MOVE:
                T itm = list.remove(res.getIndex());
                list.add(res.getDestIndex(), itm);
                break;
            case REMOVE:
                int removeIndex = res.getIndex();
                for (int i = 0; i < res.getLength(); i++) {
                    list.remove(removeIndex);
                }
                break;
        }
        return res;
    }
}


text:
__author__ = 'kat4ma'

def greeting(msg):

	print(msg)


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>fn_linespecs</title><meta name="generator" content="MATLAB 8.5"><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/"><meta name="DC.date" content="2017-01-07"><meta name="DC.source" content="help_fn_linespecs.m">

fn_linespecs

Contents

Syntax

Description

Source

Syntax

lineoptions = fn_linespecs(line options as in plot)
lineoptions = fn_linespecs({line options as in plot})

Description

If necessary, converts the first argument into the accurate set of line
properties {Propertyname1,Value1,...} according to the same syntax as
the plot command.
This can be used to set line properties more easily.
ex: opt=fn_linespecs('r:','linewidth',2);
    line([0 1],[0 1],opt{:})

         b     blue          .     point              -     solid
         g     green         o     circle             :     dotted
         r     red           x     x-mark             -.    dashdot
         c     cyan          +     plus               --    dashed
         m     magenta       *     star             (none)  no line
         y     yellow        s     square
         k     black         d     diamond
         w     white         v     triangle (down)
                             ^     triangle (up)
                             <     triangle (left)
                             >     triangle (right)
                             p     pentagram
                             h     hexagram

Source

Thomas Deneux

Copyright 2004-2017

Published with MATLAB® R2015a


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Web;

namespace wojilu.cms.Controller.Admin {

    public class SecurityController : ControllerBase {

        public override void CheckPermission() {

            // 你也可以跳转到登录页面
            string url = to( new LoginController().Login ) + "?returnUrl=" + ctx.url.PathAndQuery;
            if (ctx.web.UserIsLogin == false) echoRedirect( "非法访问,请先登录。", url );
        }
    }

}


text:
exports.trailpack = require('./trailpack')
exports.proxyRouter = require('./proxyRouter')


text:
/*
(Phone key pads) The international standard letter/number mapping found on the
telephone is shown below:
Write a program that prompts the user to enter a letter and displays its corresponding
number.
*/
import java.util.Scanner;

public class Exercise_04_15 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		// Prompt the user to enter a letter
		System.out.print("Enter a letter: ");
		String s = input.nextLine();
		char ch = s.charAt(0);
		ch = Character.toUpperCase(ch);

		// Display its corresponding number
		int number = 0;
		if (Character.isLetter(ch))
		{
			if (ch >= 'W')
				number = 9;
			else if (ch >= 'T')
				number = 8;
			else if (ch >= 'P')
				number = 7;
			else if (ch >= 'M')
				number = 6;
			else if (ch >= 'J')
				number = 5;
			else if (ch >= 'G')
				number = 4;
			else if (ch >= 'D')
				number = 3;
			else if (ch >= 'A')
				number = 2;
			System.out.println("The corresponding number is " + number);
		}
		else
			System.out.println(ch + " is an invalid input");
	}
}