text:
using System.Collections.Generic;
using System.Linq;
using CSharpFunctionalExtensions;
using Moq;
using NBitcoin;
using Stratis.Bitcoin.Features.SmartContracts.Models;
using Stratis.Bitcoin.Features.SmartContracts.Wallet;
using Stratis.Bitcoin.Features.Wallet;
using Stratis.Bitcoin.Features.Wallet.Interfaces;
using Stratis.Bitcoin.Features.Wallet.Models;
using Stratis.SmartContracts.CLR;
using Stratis.SmartContracts.CLR.Serialization;
using Stratis.SmartContracts.Core.State;
using Stratis.SmartContracts.Networks;
using Stratis.SmartContracts.RuntimeObserver;
using Xunit;

namespace Stratis.Bitcoin.Features.SmartContracts.Tests
{
    public class SmartContractTransactionServiceTests
    {
        private readonly Network network;
        private readonly Mock<IWalletManager> walletManager = new Mock<IWalletManager>();
        private readonly Mock<IWalletTransactionHandler> walletTransactionHandler;
        private readonly Mock<IMethodParameterStringSerializer> stringSerializer;
        private readonly Mock<ICallDataSerializer> callDataSerializer;
        private readonly Mock<IAddressGenerator> addressGenerator;
        private readonly Mock<IStateRepositoryRoot> stateRepository;

        public SmartContractTransactionServiceTests()
        {
            this.network = new SmartContractsRegTest();
            this.walletManager = new Mock<IWalletManager>();
            this.walletTransactionHandler = new Mock<IWalletTransactionHandler>();
            this.stringSerializer = new Mock<IMethodParameterStringSerializer>();
            this.callDataSerializer = new Mock<ICallDataSerializer>();
            this.addressGenerator = new Mock<IAddressGenerator>();
            this.stateRepository = new Mock<IStateRepositoryRoot>();
        }

        [Fact]
        public void CanChooseInputsForCall()
        {
            const int utxoIndex = 0;
            uint256 utxoId = uint256.Zero;
            uint256 utxoIdUnused = uint256.One;
            string senderAddress = uint160.Zero.ToBase58Address(this.network);
            string contractAddress = uint160.One.ToBase58Address(this.network);

            var request = new BuildCallContractTransactionRequest
            {
                Amount = "0",
                AccountName = "account 0",
                ContractAddress = contractAddress,
                FeeAmount = "0.01",
                GasLimit = 100_000,
                GasPrice = 100,
                MethodName = "TestMethod",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
                Outpoints = new List<OutpointRequest>
                {
                    new OutpointRequest
                    {
                        Index = utxoIndex,
                        TransactionId = utxoId.ToString()
                    },
                }
            };

            this.walletManager.Setup(x => x.GetAddressBalance(request.Sender))
                .Returns(new AddressBalance
                {
                    Address = senderAddress,
                    AmountConfirmed = new Money(100, MoneyUnit.BTC)
                });

            this.walletManager.Setup(x => x.GetSpendableTransactionsInWallet(It.IsAny<string>(), 0))
                .Returns(new List<UnspentOutputReference>
                {
                    new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoId,
                            Index = utxoIndex,
                        }
                    }, new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoIdUnused,
                            Index = utxoIndex,
                        }
                    }
                });

            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>
                                    {
                                        new HdAddress
                                        {
                                            Address = senderAddress
                                        }
                                    },
                                    Name = request.AccountName
                                }
                            }
                        }
                    }
                });

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            BuildCallContractTransactionResponse result = service.BuildCallTx(request);

            this.walletTransactionHandler.Verify(x=>x.BuildTransaction(It.Is<TransactionBuildContext>(y =>y.SelectedInputs.Count == 1)));
        }

        [Fact]
        public void ChoosingInvalidInputFails()
        {
            const int utxoIndex = 0;
            uint256 utxoId = uint256.Zero;
            uint256 utxoIdUnused = uint256.One;
            string senderAddress = uint160.Zero.ToBase58Address(this.network);
            string contractAddress = uint160.One.ToBase58Address(this.network);

            var request = new BuildCallContractTransactionRequest
            {
                Amount = "0",
                AccountName = "account 0",
                ContractAddress = contractAddress,
                FeeAmount = "0.01",
                GasLimit = 100_000,
                GasPrice = 100,
                MethodName = "TestMethod",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
                Outpoints = new List<OutpointRequest>
                {
                    new OutpointRequest
                    {
                        Index = utxoIndex,
                        TransactionId = new uint256(64).ToString() // A tx we don't have.
                    },
                }
            };

            this.walletManager.Setup(x => x.GetAddressBalance(request.Sender))
                .Returns(new AddressBalance
                {
                    Address = senderAddress,
                    AmountConfirmed = new Money(100, MoneyUnit.BTC)
                });

            this.walletManager.Setup(x => x.GetSpendableTransactionsInWallet(It.IsAny<string>(), 0))
                .Returns(new List<UnspentOutputReference>
                {
                    new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoId,
                            Index = utxoIndex,
                        }
                    }, new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoIdUnused,
                            Index = utxoIndex,
                        }
                    }
                });

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            BuildCallContractTransactionResponse result = service.BuildCallTx(request);
            Assert.False(result.Success);
            Assert.StartsWith("Invalid list of request outpoints", result.Message);
        }

        [Fact]
        public void CanChooseInputsForCreate()
        {
            const int utxoIndex = 0;
            uint256 utxoId = uint256.Zero;
            uint256 utxoIdUnused = uint256.One;
            string senderAddress = uint160.Zero.ToBase58Address(this.network);
            string contractAddress = uint160.One.ToBase58Address(this.network);

            var request = new BuildCreateContractTransactionRequest
            {
                Amount = "0",
                AccountName = "account 0",
                ContractCode = "AB1234",
                FeeAmount = "0.01",
                GasLimit = 100_000,
                GasPrice = 100,
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
                Outpoints = new List<OutpointRequest>
                {
                    new OutpointRequest
                    {
                        Index = utxoIndex,
                        TransactionId = utxoId.ToString()
                    },
                }
            };

            this.walletManager.Setup(x => x.GetAddressBalance(request.Sender))
                .Returns(new AddressBalance
                {
                    Address = senderAddress,
                    AmountConfirmed = new Money(100, MoneyUnit.BTC)
                });

            this.walletManager.Setup(x => x.GetSpendableTransactionsInWallet(It.IsAny<string>(), 0))
                .Returns(new List<UnspentOutputReference>
                {
                    new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoId,
                            Index = utxoIndex,
                        }
                    }, new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoIdUnused,
                            Index = utxoIndex,
                        }
                    }
                });

            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>
                                    {
                                        new HdAddress
                                        {
                                            Address = senderAddress
                                        }
                                    },
                                    Name = request.AccountName
                                }
                            }
                        }
                    }
                });

            this.callDataSerializer.Setup(x => x.Deserialize(It.IsAny<byte[]>()))
                .Returns(Result.Ok(new ContractTxData(1, 100, (Gas) 100_000, new byte[0])));

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            BuildCreateContractTransactionResponse result = service.BuildCreateTx(request);

            this.walletTransactionHandler.Verify(x => x.BuildTransaction(It.Is<TransactionBuildContext>(y => y.SelectedInputs.Count == 1)));
        }

        [Fact]
        public void BuildTransferContext_SenderNotInWallet_Fails()
        {
            string senderAddress = uint160.Zero.ToBase58Address(this.network);

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            var request = new BuildContractTransactionRequest
            {
                AccountName = "account 0",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
            };

            // Create a wallet but without the sender address
            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>(),
                                    Name = request.AccountName
                                }
                            }
                        }
                    }
                });

            BuildContractTransactionResult result = service.BuildTx(request);

            Assert.Equal(SmartContractTransactionService.SenderNotInWalletError, result.Error);
            Assert.NotNull(result.Message);
            Assert.Null(result.Response);
        }

        [Fact]
        public void BuildTransferContext_AccountNotInWallet_Fails()
        {
            string senderAddress = uint160.Zero.ToBase58Address(this.network);

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            var request = new BuildContractTransactionRequest
            {
                AccountName = "account 0",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
            };

            // Create a wallet but without the correct account name
            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>(),
                                    Name = "account 1"
                                }
                            }
                        }
                    }
                });

            BuildContractTransactionResult result = service.BuildTx(request);

            Assert.Equal(SmartContractTransactionService.AccountNotInWalletError, result.Error);
            Assert.NotNull(result.Message);
            Assert.Null(result.Response);
        }

        [Fact]
        public void BuildTransferContext_SenderHasNoBalance_Fails()
        {
            string senderAddress = uint160.Zero.ToBase58Address(this.network);

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            var request = new BuildContractTransactionRequest
            {
                AccountName = "account 0",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
            };

            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>
                                    {
                                        new HdAddress
                                        {
                                            Address = senderAddress
                                        }
                                    },
                                    Name = request.AccountName,
                                }
                            }
                        }
                    }
                });

            this.walletManager.Setup(x => x.GetAddressBalance(request.Sender))
                .Returns(new AddressBalance { Address = request.Sender, AmountConfirmed = 0, AmountUnconfirmed = 0 });

            BuildContractTransactionResult result = service.BuildTx(request);

            Assert.Equal(SmartContractTransactionService.InsufficientBalanceError, result.Error);
            Assert.NotNull(result.Message);
            Assert.Null(result.Response);
        }

        [Fact]
        public void BuildTransferContext_RecipientIsKnownContract_Fails()
        {
            const int utxoIndex = 0;
            uint256 utxoId = uint256.Zero;
            uint256 utxoIdUnused = uint256.One;
            string senderAddress = uint160.Zero.ToBase58Address(this.network);
            string recipientAddress = uint160.One.ToBase58Address(this.network);

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            var request = new BuildContractTransactionRequest
            {
                AccountName = "account 0",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
                Recipients = new List<RecipientModel>
                {
                    new RecipientModel { Amount = "1", DestinationAddress = recipientAddress}
                }
            };

            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>
                                    {
                                        new HdAddress
                                        {
                                            Address = senderAddress
                                        }
                                    },
                                    Name = request.AccountName,
                                }
                            }
                        }
                    }
                });

            this.walletManager.Setup(x => x.GetAddressBalance(request.Sender))
                .Returns(new AddressBalance { Address = request.Sender, AmountConfirmed = 10, AmountUnconfirmed = 0 });

            this.walletManager.Setup(x => x.GetSpendableTransactionsInWallet(It.IsAny<string>(), 0))
                .Returns(new List<UnspentOutputReference>
                {
                    new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoId,
                            Index = utxoIndex,
                        }
                    }, new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoIdUnused,
                            Index = utxoIndex,
                        }
                    }
                });

            this.stateRepository.Setup(s => s.IsExist(It.IsAny<uint160>())).Returns(true);

            BuildContractTransactionResult result = service.BuildTx(request);

            Assert.Equal(SmartContractTransactionService.TransferFundsToContractError, result.Error);
            Assert.NotNull(result.Message);
            Assert.Null(result.Response);
        }

        [Fact]
        public void BuildTransferContextCorrectly()
        {
            const int utxoIndex = 0;
            uint256 utxoId = uint256.Zero;
            uint256 utxoIdUnused = uint256.One;
            string senderAddress = uint160.Zero.ToBase58Address(this.network);
            string recipientAddress = uint160.One.ToBase58Address(this.network);
            string changeAddress = new uint160(2).ToBase58Address(this.network);

            var amount = 1234.567M;

            var request = new BuildContractTransactionRequest
            {
                AccountName = "account 0",
                FeeAmount = "0.01",
                WalletName = "wallet",
                Password = "password",
                Sender = senderAddress,
                ShuffleOutputs = true,
                AllowUnconfirmed = true,
                ChangeAddress = changeAddress,
                Recipients = new List<RecipientModel>
                {
                    new RecipientModel { Amount = amount.ToString(), DestinationAddress = recipientAddress}
                }
            };

            SmartContractTransactionService service = new SmartContractTransactionService(
                this.network,
                this.walletManager.Object,
                this.walletTransactionHandler.Object,
                this.stringSerializer.Object,
                this.callDataSerializer.Object,
                this.addressGenerator.Object,
                this.stateRepository.Object);

            var senderHdAddress = new HdAddress { Address = senderAddress };

            this.walletManager.Setup(x => x.GetWallet(request.WalletName))
                .Returns(new Features.Wallet.Wallet
                {
                    AccountsRoot = new List<AccountRoot>
                    {
                        new AccountRoot
                        {
                            Accounts = new List<HdAccount>
                            {
                                new HdAccount
                                {
                                    ExternalAddresses = new List<HdAddress>
                                    {
                                        senderHdAddress
                                    },
                                    Name = request.AccountName,
                                }
                            }
                        }
                    }
                });

            this.walletManager.Setup(x => x.GetAddressBalance(request.Sender))
                .Returns(new AddressBalance { Address = request.Sender, AmountConfirmed = Money.FromUnit(amount, MoneyUnit.BTC), AmountUnconfirmed = 0 });

            var outputs = new List<UnspentOutputReference>
                {
                    new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoId,
                            Index = utxoIndex,
                        }
                    }, new UnspentOutputReference
                    {
                        Address = new HdAddress
                        {
                            Address = senderAddress
                        },
                        Transaction = new TransactionData
                        {
                            Id = utxoIdUnused,
                            Index = utxoIndex,
                        }
                    }
                };

            this.walletManager.Setup(x => x.GetSpendableTransactionsInWallet(It.IsAny<string>(), 0)).Returns(outputs);

            this.walletTransactionHandler.Setup(x => x.BuildTransaction(It.IsAny<TransactionBuildContext>()))
                .Returns(new Transaction());

            BuildContractTransactionResult result = service.BuildTx(request);

            // Check that the transaction builder is invoked, and that we:
            // - Ignore shuffleOutputs,
            // - Set inputs from sender
            // - Set recipients,
            // - Set change to sender
            this.walletTransactionHandler.Verify(w => w.BuildTransaction(It.Is<TransactionBuildContext>(context =>
                context.AllowOtherInputs == false &&
                context.Shuffle == false &&
                context.SelectedInputs.All(i => outputs.Select(o => o.Transaction.Id).Contains(i.Hash)) &&
                context.Recipients.Single().Amount == Money.FromUnit(amount, MoneyUnit.BTC) &&
                context.ChangeAddress == senderHdAddress
            )));
        }
    }
}


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
require 'capybara/rspec'
require 'pry'

Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each {|f| require f}

ActiveRecord::Migrator.migrations_paths.tap do |paths|
  paths << File.expand_path('../../spec/dummy/db/migrate', __FILE__)
  paths << File.expand_path('../../db/migrate', __FILE__)
end

RSpec.configure do |config|

  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.include FactoryGirl::Syntax::Methods

end

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.azure.management.network.v2020_05_01;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for IpsecEncryption.
 */
public final class IpsecEncryption extends ExpandableStringEnum<IpsecEncryption> {
    /** Static value None for IpsecEncryption. */
    public static final IpsecEncryption NONE = fromString("None");

    /** Static value DES for IpsecEncryption. */
    public static final IpsecEncryption DES = fromString("DES");

    /** Static value DES3 for IpsecEncryption. */
    public static final IpsecEncryption DES3 = fromString("DES3");

    /** Static value AES128 for IpsecEncryption. */
    public static final IpsecEncryption AES128 = fromString("AES128");

    /** Static value AES192 for IpsecEncryption. */
    public static final IpsecEncryption AES192 = fromString("AES192");

    /** Static value AES256 for IpsecEncryption. */
    public static final IpsecEncryption AES256 = fromString("AES256");

    /** Static value GCMAES128 for IpsecEncryption. */
    public static final IpsecEncryption GCMAES128 = fromString("GCMAES128");

    /** Static value GCMAES192 for IpsecEncryption. */
    public static final IpsecEncryption GCMAES192 = fromString("GCMAES192");

    /** Static value GCMAES256 for IpsecEncryption. */
    public static final IpsecEncryption GCMAES256 = fromString("GCMAES256");

    /**
     * Creates or finds a IpsecEncryption from its string representation.
     * @param name a name to look for
     * @return the corresponding IpsecEncryption
     */
    @JsonCreator
    public static IpsecEncryption fromString(String name) {
        return fromString(name, IpsecEncryption.class);
    }

    /**
     * @return known IpsecEncryption values
     */
    public static Collection<IpsecEncryption> values() {
        return values(IpsecEncryption.class);
    }
}


text:
module Ricer::Plugin::Radio::Model
  class AlbumSong < ActiveRecord::Base

    self.table_name = 'radio_album_songs'

    def self.upgrade_1
      m = ActiveRecord::Migration.new
      m.create_table table_name do |t|
      end
    end

  end
end


text:
import controller from './clipboard.controller';
import template from './clipboard.html';

export default {
  template,
  controller,
  bindings: {
    name: '@?',
    id: '@?',
    model: '=',
  },
};


text:
typedef enum : NSUInteger {
    NoDeal = 0,
    ResultNotification
} XWEnumOtherRequestDeal;

@interface XWModelOtherRequestDeal : XWBaseModel

@property(assign,nonatomic)XWEnumOtherRequestDeal otherReq;

@property(strong,nonatomic)NSObject *obj;

@end


text:
<?php

namespace app\modules\portalprofessor\models;

use Yii;

/**
 * This is the model class for table "acdcurriculum".
 *
 * @property string $username
 * @property string $datetime
 * @property string $ipaddress
 * @property integer $curriculumid
 * @property string $courseid
 * @property integer $courseversion
 * @property integer $turnid
 * @property integer $unitid
 * @property string $curricularcomponentid
 * @property integer $curricularcomponentversion
 * @property integer $curricularcomponenttypeid
 * @property integer $semester
 * @property boolean $showinscholarshipdescription
 * @property integer $curricularcomponentgroupdocumentendcourseid
 * @property integer $curricularcomponentgroupelectiveid
 * @property integer $curriculumtypeid
 * @property string $enddate
 * @property boolean $showinbulletin
 * @property integer $sectorid
 * @property integer $centerid
 *
 * @property Acdcomplementaryactivities[] $acdcomplementaryactivities
 * @property Acdcomplementaryactivitiescategoryrules[] $acdcomplementaryactivitiescategoryrules
 * @property Acdcomplementaryenroll[] $acdcomplementaryenrolls
 * @property Acdcondition[] $acdconditions
 * @property Acdcondition[] $acdconditions0
 * @property Acdcurricularcomponentunblock[] $acdcurricularcomponentunblocks
 * @property Acdcenter $center
 * @property Acdcourseoccurrence $course
 * @property Acdcurricularcomponent $curricularcomponent
 * @property Acdcurricularcomponentgroup $curricularcomponentgroupdocumentendcourse
 * @property Acdcurricularcomponentgroup $curricularcomponentgroupelective
 * @property Acdcurricularcomponenttype $curricularcomponenttype
 * @property Acdcurriculumtype $curriculumtype
 * @property Bassector $sector
 * @property Acdcurriculumconcurrence[] $acdcurriculumconcurrences
 * @property Acdcurriculumconcurrence[] $acdcurriculumconcurrences0
 * @property Acdcurriculumlink[] $acdcurriculumlinks
 * @property Acdcurriculumlink[] $acdcurriculumlinks0
 * @property Acdenroll[] $acdenrolls
 * @property Acdexploitation[] $acdexploitations
 * @property Acdgroup[] $acdgroups
 */
class Acdcurriculum extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'acdcurriculum';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['datetime', 'enddate'], 'safe'],
            [['ipaddress'], 'string'],
            [['courseid', 'courseversion', 'turnid', 'unitid', 'curricularcomponentid', 'curricularcomponentversion', 'curricularcomponenttypeid', 'semester', 'curricularcomponentgroupdocumentendcourseid', 'curriculumtypeid'], 'required'],
            [['courseversion', 'turnid', 'unitid', 'curricularcomponentversion', 'curricularcomponenttypeid', 'semester', 'curricularcomponentgroupdocumentendcourseid', 'curricularcomponentgroupelectiveid', 'curriculumtypeid', 'sectorid', 'centerid'], 'integer'],
            [['showinscholarshipdescription', 'showinbulletin'], 'boolean'],
            [['username'], 'string', 'max' => 20],
            [['courseid', 'curricularcomponentid'], 'string', 'max' => 10],
            [['courseid', 'courseversion', 'turnid', 'unitid', 'curricularcomponentid', 'curricularcomponentversion'], 'unique', 'targetAttribute' => ['courseid', 'courseversion', 'turnid', 'unitid', 'curricularcomponentid', 'curricularcomponentversion'], 'message' => 'The combination of Courseid, Courseversion, Turnid, Unitid, Curricularcomponentid and Curricularcomponentversion has already been taken.']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => 'Username',
            'datetime' => 'Datetime',
            'ipaddress' => 'Ipaddress',
            'curriculumid' => 'Curriculumid',
            'courseid' => 'Courseid',
            'courseversion' => 'Courseversion',
            'turnid' => 'Turnid',
            'unitid' => 'Unitid',
            'curricularcomponentid' => 'Curricularcomponentid',
            'curricularcomponentversion' => 'Curricularcomponentversion',
            'curricularcomponenttypeid' => 'Curricularcomponenttypeid',
            'semester' => 'Semester',
            'showinscholarshipdescription' => 'Showinscholarshipdescription',
            'curricularcomponentgroupdocumentendcourseid' => 'Curricularcomponentgroupdocumentendcourseid',
            'curricularcomponentgroupelectiveid' => 'Curricularcomponentgroupelectiveid',
            'curriculumtypeid' => 'Curriculumtypeid',
            'enddate' => 'Enddate',
            'showinbulletin' => 'Showinbulletin',
            'sectorid' => 'Sectorid',
            'centerid' => 'Centerid',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcomplementaryactivities()
    {
        return $this->hasMany(Acdcomplementaryactivities::className(), ['curriculumidold' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcomplementaryactivitiescategoryrules()
    {
        return $this->hasMany(Acdcomplementaryactivitiescategoryrules::className(), ['curriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcomplementaryenrolls()
    {
        return $this->hasMany(Acdcomplementaryenroll::className(), ['curriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdconditions()
    {
        return $this->hasMany(Acdcondition::className(), ['curriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdconditions0()
    {
        return $this->hasMany(Acdcondition::className(), ['conditioncurriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcurricularcomponentunblocks()
    {
        return $this->hasMany(Acdcurricularcomponentunblock::className(), ['curriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCenter()
    {
        return $this->hasOne(Acdcenter::className(), ['centerid' => 'centerid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCourse()
    {
        return $this->hasOne(Acdcourseoccurrence::className(), ['courseid' => 'courseid', 'courseversion' => 'courseversion', 'turnid' => 'turnid', 'unitid' => 'unitid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCurricularcomponent()
    {
        return $this->hasOne(Acdcurricularcomponent::className(), ['curricularcomponentid' => 'curricularcomponentid', 'curricularcomponentversion' => 'curricularcomponentversion']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCurricularcomponentgroupdocumentendcourse()
    {
        return $this->hasOne(Acdcurricularcomponentgroup::className(), ['curricularcomponentgroupid' => 'curricularcomponentgroupdocumentendcourseid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCurricularcomponentgroupelective()
    {
        return $this->hasOne(Acdcurricularcomponentgroup::className(), ['curricularcomponentgroupid' => 'curricularcomponentgroupelectiveid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCurricularcomponenttype()
    {
        return $this->hasOne(Acdcurricularcomponenttype::className(), ['curricularcomponenttypeid' => 'curricularcomponenttypeid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCurriculumtype()
    {
        return $this->hasOne(Acdcurriculumtype::className(), ['curriculumtypeid' => 'curriculumtypeid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSector()
    {
        return $this->hasOne(Bassector::className(), ['sectorid' => 'sectorid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcurriculumconcurrences()
    {
        return $this->hasMany(Acdcurriculumconcurrence::className(), ['curriculumoutid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcurriculumconcurrences0()
    {
        return $this->hasMany(Acdcurriculumconcurrence::className(), ['curriculuminid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcurriculumlinks()
    {
        return $this->hasMany(Acdcurriculumlink::className(), ['curriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdcurriculumlinks0()
    {
        return $this->hasMany(Acdcurriculumlink::className(), ['curriculumlinkid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdenrolls()
    {
        return $this->hasMany(Acdenroll::className(), ['curriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdexploitations()
    {
        return $this->hasMany(Acdexploitation::className(), ['electivecurriculumid' => 'curriculumid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAcdgroups()
    {
        return $this->hasMany(Acdgroup::className(), ['curriculumid' => 'curriculumid']);
    }
}


text:
@class JavaLangThrowable;

@interface ComGoogleCommonUtilConcurrentUncheckedTimeoutException : JavaLangRuntimeException

#pragma mark Public

- (instancetype)init;

- (instancetype)initWithNSString:(NSString *)message;

- (instancetype)initWithNSString:(NSString *)message
           withJavaLangThrowable:(JavaLangThrowable *)cause;

- (instancetype)initWithJavaLangThrowable:(JavaLangThrowable *)cause;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoogleCommonUtilConcurrentUncheckedTimeoutException)

FOUNDATION_EXPORT void ComGoogleCommonUtilConcurrentUncheckedTimeoutException_init(ComGoogleCommonUtilConcurrentUncheckedTimeoutException *self);

FOUNDATION_EXPORT ComGoogleCommonUtilConcurrentUncheckedTimeoutException *new_ComGoogleCommonUtilConcurrentUncheckedTimeoutException_init() NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void ComGoogleCommonUtilConcurrentUncheckedTimeoutException_initWithNSString_(ComGoogleCommonUtilConcurrentUncheckedTimeoutException *self, NSString *message);

FOUNDATION_EXPORT ComGoogleCommonUtilConcurrentUncheckedTimeoutException *new_ComGoogleCommonUtilConcurrentUncheckedTimeoutException_initWithNSString_(NSString *message) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void ComGoogleCommonUtilConcurrentUncheckedTimeoutException_initWithJavaLangThrowable_(ComGoogleCommonUtilConcurrentUncheckedTimeoutException *self, JavaLangThrowable *cause);

FOUNDATION_EXPORT ComGoogleCommonUtilConcurrentUncheckedTimeoutException *new_ComGoogleCommonUtilConcurrentUncheckedTimeoutException_initWithJavaLangThrowable_(JavaLangThrowable *cause) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT void ComGoogleCommonUtilConcurrentUncheckedTimeoutException_initWithNSString_withJavaLangThrowable_(ComGoogleCommonUtilConcurrentUncheckedTimeoutException *self, NSString *message, JavaLangThrowable *cause);

FOUNDATION_EXPORT ComGoogleCommonUtilConcurrentUncheckedTimeoutException *new_ComGoogleCommonUtilConcurrentUncheckedTimeoutException_initWithNSString_withJavaLangThrowable_(NSString *message, JavaLangThrowable *cause) NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonUtilConcurrentUncheckedTimeoutException)

#endif

#pragma pop_macro("ComGoogleCommonUtilConcurrentUncheckedTimeoutException_INCLUDE_ALL")


text:
class KWApi < Sinatra::Base
  set :github_secret_token, ENV['GITHUB_SECRET']

  post '/github/webhooks/kw-api/update/?' do
    request.body.rewind
    payload_body = request.body.read
    verify_signature(payload_body)
    puts 'I got some JSON!'
    `./reload.sh`
  end

  def verify_signature(payload_body)
    signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'),
                                                  settings.github_secret_token,
                                                  payload_body)
    return halt 500, "Signatures didn't match!" unless
    Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE'])
  end
end


text:
import {Directive, EventEmitter, ElementRef, Renderer, HostListener, Input, Output} from '@angular/core';

// import {setProperty} from 'angular2/ts/src/core/forms/directives/shared';
function setProperty(renderer:Renderer, elementRef:ElementRef, propName:string, propValue:any):void {
  renderer.setElementProperty(elementRef, propName, propValue);
}

@Directive({selector: '[ngTableFiltering]'})
export class NgTableFilteringDirective {
  @Input() public ngTableFiltering:any = {
    filterString: '',
    columnName: 'name'
  };

  @Output() public tableChanged:EventEmitter<any> = new EventEmitter();

  @Input()
  public get config():any {
    return this.ngTableFiltering;
  }

  public set config(value:any) {
    this.ngTableFiltering = value;
  }

  private element:ElementRef;
  private renderer:Renderer;

  @HostListener('input', ['$event.target.value'])
  public onChangeFilter(event:any):void {
    this.ngTableFiltering.filterString = event;
    this.tableChanged.emit({filtering: this.ngTableFiltering});
  }

  public constructor(element:ElementRef, renderer:Renderer) {
    this.element = element;
    this.renderer = renderer;
    // Set default value for filter
    setProperty(this.renderer, this.element, 'value', this.ngTableFiltering.filterString);
  }
}


text:
import Input, { InputProps } from 'antd/lib/input';
import React, { Ref } from 'react';
import { FieldProps, connectField, filterDOMProps } from 'uniforms';

import wrapField from './wrapField';

export type TextFieldProps = FieldProps<
  string,
  Omit<InputProps, 'onReset'>,
  { inputRef?: Ref<Input> }
>;

function Text(props: TextFieldProps) {
  return wrapField(
    props,
    <Input
      disabled={props.disabled}
      name={props.name}
      onChange={event => props.onChange(event.target.value)}
      placeholder={props.placeholder}
      readOnly={props.readOnly}
      ref={props.inputRef}
      type={props.type ?? 'text'}
      value={props.value ?? ''}
      {...filterDOMProps(props)}
    />,
  );
}

export default connectField<TextFieldProps>(Text, { kind: 'leaf' });


text:
@class IDEBatchFindResultGroup;

@protocol IDEBatchFindResultGroupDelegate <NSObject>
- (void)finishedSymbolQueryForResultsGroupNavItem:(IDEBatchFindResultGroup *)arg1;
@end


text:
package org.camunda.bpm.engine.test.api.authorization.history;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.camunda.bpm.engine.FormService;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.history.HistoricDetail;
import org.camunda.bpm.engine.history.UserOperationLogEntry;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

/**
 * Tests the operationId field in historic tables, which helps to correlate records from different tables.
 *
 * @author Svetlana Dorokhova
 *
 */
@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_FULL)
public class UserOperationIdTest {

  @Rule
  public ProcessEngineRule engineRule = new ProvidedProcessEngineRule();

  @Rule
  public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);

  protected static final String PROCESS_KEY = "oneTaskProcess";
  protected String deploymentId;

  protected RuntimeService runtimeService;
  protected RepositoryService repositoryService;
  protected HistoryService historyService;
  protected TaskService taskService;
  protected FormService formService;
  protected IdentityService identityService;

  @Before
  public void init() {
    runtimeService = engineRule.getRuntimeService();
    repositoryService = engineRule.getRepositoryService();
    historyService = engineRule.getHistoryService();
    taskService = engineRule.getTaskService();
    formService = engineRule.getFormService();
    identityService = engineRule.getIdentityService();
  }

  @Test
  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testResolveTaskOperationId() {
    // given
    identityService.setAuthenticatedUserId("demo");
    runtimeService.startProcessInstanceByKey(PROCESS_KEY);
    String taskId = taskService.createTaskQuery().singleResult().getId();

    // when
    taskService.resolveTask(taskId, getVariables());

    //then
    List<UserOperationLogEntry> userOperationLogEntries = historyService.createUserOperationLogQuery()
        .operationType(UserOperationLogEntry.OPERATION_TYPE_RESOLVE)
        .taskId(taskId)
        .list();
    List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().list();
    verifySameOperationId(userOperationLogEntries, historicDetails);
  }

  @Test
  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSubmitTaskFormOperationId() {
    // given
    identityService.setAuthenticatedUserId("demo");
    runtimeService.startProcessInstanceByKey(PROCESS_KEY);
    String taskId = taskService.createTaskQuery().singleResult().getId();

    // when
    formService.submitTaskForm(taskId, getVariables());

    //then
    List<UserOperationLogEntry> userOperationLogEntries = historyService.createUserOperationLogQuery()
        .operationType(UserOperationLogEntry.OPERATION_TYPE_COMPLETE)
        .taskId(taskId)
        .list();
    List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().list();
    verifySameOperationId(userOperationLogEntries, historicDetails);
  }

  @Test
  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetTaskVariablesOperationId() {
    // given
    identityService.setAuthenticatedUserId("demo");
    runtimeService.startProcessInstanceByKey(PROCESS_KEY);
    String taskId = taskService.createTaskQuery().singleResult().getId();

    // when
    taskService.setVariables(taskId, getVariables());

    //then
    List<UserOperationLogEntry> userOperationLogEntries = historyService.createUserOperationLogQuery()
        .operationType(UserOperationLogEntry.OPERATION_TYPE_SET_VARIABLE)
        .taskId(taskId)
        .list();
    List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().list();
    verifySameOperationId(userOperationLogEntries, historicDetails);
  }

  @Test
  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testWithoutAuthentication() {
    // given
    runtimeService.startProcessInstanceByKey(PROCESS_KEY);
    String taskId = taskService.createTaskQuery().singleResult().getId();

    // when
    taskService.resolveTask(taskId, getVariables());

    //then
    List<UserOperationLogEntry> userOperationLogEntries = historyService.createUserOperationLogQuery()
        .taskId(taskId)
        .list();
    assertEquals(0, userOperationLogEntries.size());
    List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().list();
    assertTrue(historicDetails.size() > 0);
    //history detail records must have null userOperationId as user operation log was not created
    for (HistoricDetail historicDetail: historicDetails) {
      assertNull(historicDetail.getUserOperationId());
    }
  }

  @Test
  public void testSetTaskVariablesInServiceTask() {
    // given
    BpmnModelInstance bpmnModelInstance = Bpmn.createExecutableProcess(PROCESS_KEY)
        .startEvent()
        .userTask()
        .serviceTask()
          .camundaExpression("${execution.setVariable('foo', 'bar')}")
        .endEvent()
        .done();
    testRule.deploy(bpmnModelInstance);

    identityService.setAuthenticatedUserId("demo");
    runtimeService.startProcessInstanceByKey(PROCESS_KEY);
    Task task = taskService.createTaskQuery().singleResult();

    // when
    taskService.complete(task.getId());

    //then
    HistoricDetail historicDetail = historyService.createHistoricDetailQuery().singleResult();
    // no user operation log id is set for this update, as it is not written as part of the user operation
    assertNull(historicDetail.getUserOperationId());
  }

  @Test
  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testStartProcessOperationId() {
    // given
    identityService.setAuthenticatedUserId("demo");

    // when
    ProcessInstance pi = runtimeService.startProcessInstanceByKey(PROCESS_KEY, getVariables());

    //then
    List<UserOperationLogEntry> userOperationLogEntries = historyService.createUserOperationLogQuery()
        .operationType(UserOperationLogEntry.OPERATION_TYPE_CREATE)
        .processInstanceId(pi.getId())
        .list();
    List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().list();

    assertFalse(userOperationLogEntries.isEmpty());
    assertFalse(historicDetails.isEmpty());
    verifySameOperationId(userOperationLogEntries, historicDetails);
  }

  @Test
  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testStartProcessAtActivityOperationId() {
    // given
    identityService.setAuthenticatedUserId("demo");

    // when
    ProcessInstance pi = runtimeService.createProcessInstanceByKey(PROCESS_KEY)
            .startBeforeActivity("theTask")
            .setVariables(getVariables())
            .execute();

    //then
    List<UserOperationLogEntry> userOperationLogEntries = historyService.createUserOperationLogQuery()
        .operationType(UserOperationLogEntry.OPERATION_TYPE_CREATE)
        .processInstanceId(pi.getId())
        .list();
    List<HistoricDetail> historicDetails = historyService.createHistoricDetailQuery().list();

    assertFalse(userOperationLogEntries.isEmpty());
    assertFalse(historicDetails.isEmpty());
    verifySameOperationId(userOperationLogEntries, historicDetails);
  }

  private void verifySameOperationId(List<UserOperationLogEntry> userOperationLogEntries, List<HistoricDetail> historicDetails) {
    assertTrue("Operation log entry must exist", userOperationLogEntries.size() > 0);
    String operationId = userOperationLogEntries.get(0).getOperationId();
    assertNotNull(operationId);
    assertTrue("Some historic details are expected to be present", historicDetails.size() > 0);
    for (UserOperationLogEntry userOperationLogEntry: userOperationLogEntries) {
      assertEquals("OperationIds must be the same", operationId, userOperationLogEntry.getOperationId());
    }
    for (HistoricDetail historicDetail : historicDetails) {
      assertEquals("OperationIds must be the same", operationId, historicDetail.getUserOperationId());
    }
  }

  protected VariableMap getVariables() {
    return Variables.createVariables()
        .putValue("aVariableName", "aVariableValue")
        .putValue("anotherVariableName", "anotherVariableValue");
  }

}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

using System;

public enum _StartingState{
	Default,
	Locked,
	Unlocked,
}

public enum _PerkTypeTB{
	BonusHP,
	BonusAP,
	BonusHPRegen,
	BonusAPRegen,
	BonusMoveRange,
	BonusAttackRange,

	BonusDamage,
	BonusDamageMin,
	BonusDamageMax,

	BonusRangeDamage,
	BonusRangeDamageMin,
	BonusRangeDamageMax,

	BonusMeleeDamage,
	BonusMeleeDamageMin,
	BonusMeleeDamageMax,

	BonusCounterModifier,

	BonusHitRange,
	BonusHitMelee,

	BonusCritRange,
	BonusCritMelee,

	BonusMove,
	BonusAttack,
	BonusCounter,

	BonusDodge,
	BonusCritImmune,
	BonusDamageReduc,

	APAttackReduc,
	APMoveReduc,
}

[System.Serializable]
public class EffectValue{
	public float value=0;
	public float mod=0;
}

[System.Serializable]
public class UnitStatModifier{
	public UnitTB unit;

	public List<EffectValue> stats=new List<EffectValue>();

	public UnitStatModifier(){
		unit=null;

		int enumLength = Enum.GetValues(typeof(_PerkTypeTB)).Length;
		for(int i=0; i<enumLength; i++){
			stats.Add(new EffectValue());
		}
	}
	public UnitStatModifier(UnitTB unitTB){
		unit=unitTB;

		int enumLength = Enum.GetValues(typeof(_PerkTypeTB)).Length;
		for(int i=0; i<enumLength; i++){
			stats.Add(new EffectValue());
		}
	}
}

[System.Serializable]
public class PerkEffectTB{
	//public
	public _PerkTypeTB type;
	public float value=1;
	public bool isModifier=false;

	public PerkEffectTB Clone(){
		PerkEffectTB effect=new PerkEffectTB();
		effect.type=type;
		effect.value=value;
		effect.isModifier=isModifier;
		return effect;
	}
}

[System.Serializable]
public class PerkTB{
	public int ID=-1;
	public string name="";
	public string desp="";

	public Texture icon;
	public Texture iconUnavailable;
	public Texture iconUnlocked;

	//[HideInInspector]
	public string iconName="";
	public string iconUnavailableName="";
	public string iconUnlockedName="";

	public int cost=0;
	public int pointReq=0;

	public List<PerkEffectTB> effects=new List<PerkEffectTB>();

	public List<int> prereq=new List<int>();
	public List<int> reqby=new List<int>();

	public bool applyToAllUnit=true;
	public List<UnitTB> unitPrefab=new List<UnitTB>();
	public List<int> unitPrefabID=new List<int>();

	public bool unlocked=false;

	public bool availableInScene=true;
	public _StartingState startingState=_StartingState.Default;

	public PerkTB Clone(){
		PerkTB perk=new PerkTB();

		perk.ID=ID;
		perk.name=name;
		perk.desp=desp;
		perk.icon=icon;
		perk.iconUnavailable=iconUnavailable;
		perk.iconUnlocked=iconUnlocked;
		//perk.type=type;

		perk.iconName=iconName;
		perk.iconUnavailableName=iconUnavailableName;
		perk.iconUnlockedName=iconUnlockedName;

		perk.cost=cost;

		//perk.effects=effects;
		for(int i=0; i<effects.Count; i++){
			perk.effects.Add(effects[i].Clone());
		}

		perk.prereq=prereq;
		perk.reqby=reqby;
		perk.applyToAllUnit=applyToAllUnit;
		perk.unitPrefab=unitPrefab;

		perk.unlocked=unlocked;

		perk.availableInScene=availableInScene;
		perk.startingState=startingState;

		return perk;
	}

	public int IsAvailable(){
		if(!PerkManagerTB.UsePersistentData()){
			if(PerkManagerTB.GetPoint()<cost){
				return 1;
				//return "insufficient point to unlock perk";
				//return false;
			}
		}
		else{
			if(GlobalStatsTB.GetPlayerPoint()<cost){
				return 1;
				//return "insufficient player point to unlock perk";
				//return false;
			}
		}

		if(PerkManagerTB.GetPerkPoint()<pointReq){
			return 2;
			//return  "insufficient perk point to unlock perk";
			//return false;
		}

		for(int i=0; i<prereq.Count; i++){
			if(!PerkManagerTB.GetPerk(prereq[i]).unlocked){
				return 3;
				//return "pre-req perk needed to unlock perk";
				//return false;
			}
		}

		//return true;
		//return "";
		return 0;
	}

}

public class PerkManagerTB : MonoBehaviour {

	public delegate void PerkUnlockHandler(PerkTB perk);
	public static event PerkUnlockHandler onPerkUnlockE;

	public List<PerkTB> localPerkList=new List<PerkTB>();

	public static List<PerkTB> perkList=new List<PerkTB>();

	public static UnitStatModifier globalUnitStats=new UnitStatModifier();

	public static List<UnitStatModifier> unitStats=new List<UnitStatModifier>();
	public static List<UnitTB> unitList=new List<UnitTB>();

	//recording how many perk has been unlocked
	public static int perkPoint=0;
	public static int GetPerkPoint(){
		return perkPoint;
	}

	//local point to unlock perk if persistant data is not used
	public int point=0;
	public static int GetPoint(){
		if(instance==null) return 0;
		return instance.point;
	}

	public bool dontDestroyOnLoad=true;
	public bool usePersistentData=false;
	public static bool UsePersistentData(){
		if(instance==null) return false;
		return instance.usePersistentData;
	}

	public static PerkManagerTB instance;

	void Awake(){
		if(instance!=null) Destroy(gameObject);

		if(dontDestroyOnLoad){
			GameObject.DontDestroyOnLoad(gameObject);
		}

		instance=this;

		LoadPerk();
		LoadUnit();

		//if(!GlobalStatsTB.loaded){
		//	perkPoint=startingPerkPoint;
		//}

		//ResetPerk();
	}

	/*
	void OnGUI(){

		int startX=10;
		int startY=10;

		GUI.Label(new Rect(startX, startY, 150, 25), "perk point: "+perkPoint);
		startY+=30;

		for(int i=0; i<perkList.Count; i++){
			PerkTB perk=perkList[i];
			if(perk.unlocked){
				GUI.Label(new Rect(startX, startY, 100, 25), perk.name);
			}
			else{
				if(perk.IsAvailable()){
					if(GUI.Button(new Rect(startX, startY, 100, 25), perk.name)){
						UnlockPerk(perk);
					}
				}
				else{
					GUI.Box(new Rect(startX, startY, 100, 25), perk.name);
				}
			}
			startY+=30;
		}

		if(GUI.Button(new Rect(startX, startY+30, 100, 25), "reset all")){
			ResetPerk();
		}
	}
	*/

	public static void LoadPerk(){
		GameObject obj=Resources.Load("PrefabList/PerkTBListPrefab", typeof(GameObject)) as GameObject;
		if(obj==null){
			Debug.Log("load perk fail, make sure the resource file exists");
			return;
		}

		PerkTBListPrefab prefab=obj.GetComponent<PerkTBListPrefab>();
		perkList=prefab.perkTBList;

		if(!instance.usePersistentData){
			for(int i=0; i<perkList.Count; i++){
				perkList[i]=perkList[i].Clone();
			}
		}

		//check local perk, synchronice the list, set the lock/unlock list
		for(int i=0; i<perkList.Count; i++){
			PerkTB perk=perkList[i];
			for(int j=0; j<instance.localPerkList.Count; j++){
				PerkTB localPerk=instance.localPerkList[j];
				if(perk.ID==localPerk.ID){
					if(!localPerk.availableInScene){
						perkList.RemoveAt(i);
						i-=1;
					}
					else{
						if(localPerk.startingState==_StartingState.Locked){
							perk.unlocked=false;
						}
						else if(localPerk.startingState==_StartingState.Unlocked){
							perk.unlocked=true;
						}
						else if(localPerk.startingState==_StartingState.Default){

						}
					}
					break;
				}
			}
		}

		//re-'unlocked' unlocked perk, to register the perk point and etc.
		for(int i=0; i<perkList.Count; i++){
			if(perkList[i].unlocked) {
				UnlockPerk(perkList[i], false);
			}
		}
	}

	public static void LoadUnit(){
		GameObject obj=Resources.Load("PrefabList/UnitListPrefab", typeof(GameObject)) as GameObject;
		if(obj==null){
			Debug.Log("load unit fail, make sure the resource file exists");
			return;
		}

		UnitListPrefab prefab=obj.GetComponent<UnitListPrefab>();
		unitList=prefab.unitList;

		for(int i=0; i<unitList.Count; i++){
			unitStats.Add(new UnitStatModifier(unitList[i]));
		}

		globalUnitStats=new UnitStatModifier(null);
	}

	public static void SavePerk(){
		GameObject obj=Resources.Load("PrefabList/PerkTBListPrefab", typeof(GameObject)) as GameObject;
		if(obj==null){
			Debug.Log("load perk fail, make sure the resource file exists");
			return;
		}

		PerkTBListPrefab prefab=obj.GetComponent<PerkTBListPrefab>();
		prefab.perkTBList=perkList;
	}

	public static void ResetPerk(){
		for(int i=0; i<perkList.Count; i++){
			perkList[i].unlocked=false;
		}
	}

	public static PerkTB GetPerk(int ID){
		for (int i=0; i<perkList.Count; i++){
			if(perkList[i].ID==ID){
				return perkList[i].Clone();
			}
		}
		return null;
	}

	public static List<PerkTB> GetAllPerks(){
		return perkList;
	}

	public static bool UnlockPerk(int ID){
		return UnlockPerk(perkList[ID], true);
	}
	public static bool UnlockPerk(int ID, bool flag){
		return UnlockPerk(perkList[ID], flag);
	}
	public static bool UnlockPerk(PerkTB perk){
		return UnlockPerk(perk, true);
	}
	public static bool UnlockPerk(PerkTB perk, bool flag){
		if(perk.unlocked){
			Debug.Log("attemp to unlock unlocked perk");
			return false;
		}

		perk.unlocked=true;

		perkPoint+=1;

		if(flag){
			if(!instance.usePersistentData) instance.point-=perk.cost;
			else GlobalStatsTB.GainPlayerPoint(-perk.cost);
		}

		if(perk.applyToAllUnit){
			for(int i=0; i<perk.effects.Count; i++){
				PerkEffectTB effect=perk.effects[i];

				int effectID=(int)effect.type;

				if(effect.isModifier) globalUnitStats.stats[effectID].mod+=effect.value;
				else globalUnitStats.stats[effectID].value+=effect.value;
			}
		}
		else{
			for(int i=0; i<unitStats.Count; i++){
				if(perk.unitPrefab.Contains(unitStats[i].unit)){

					perk.unitPrefabID.Add(unitStats[i].unit.prefabID);

					for(int j=0; j<perk.effects.Count; j++){
						PerkEffectTB effect=perk.effects[j];

						int effectID=(int)effect.type;

						if(effect.isModifier) unitStats[i].stats[effectID].mod+=effect.value;
						else unitStats[i].stats[effectID].value+=effect.value;
					}

					break;
				}
			}
		}

		if(onPerkUnlockE!=null) onPerkUnlockE(perk);

		return true;
	}

	public static UnitStatModifier GetSpecificUnitStat(int prefabID){
		for(int i=0; i<unitStats.Count; i++){
			if(unitStats[i].unit.prefabID==prefabID){
				//Debug.Log(unitStats[i].unit.unitName+"    "+prefabID);
				return unitStats[i];
			}
		}
		Debug.Log("error, no unit prefab found");
		return null;
	}

	//******************************************************************************************************************************
	//get specific stats bonus

	public static int GetPerkHPBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusHP;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.HP*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.HP*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkAPBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusAP;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.AP*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.AP*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkHPRegenBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusHPRegen;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=(.5f*(uStats.unit.HPGainMin+uStats.unit.HPGainMax))*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=(.5f*(uStats.unit.HPGainMin+uStats.unit.HPGainMax))*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkAPRegenBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusAPRegen;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=(.5f*(uStats.unit.APGainMin+uStats.unit.APGainMax))*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=(.5f*(uStats.unit.APGainMin+uStats.unit.APGainMax))*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkMoveRangeBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusMoveRange;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.movementRange*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.movementRange*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkAttackRangeBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusAttackRange;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.attackRangeMax*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.attackRangeMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkRangeDamageBonus(int prefabID, int dmg){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamage;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		statID=(int)_PerkTypeTB.BonusRangeDamage;
		uStats=GetSpecificUnitStat(prefabID);
		total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkMeleeDamageBonus(int prefabID, int dmg){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamage;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		statID=(int)_PerkTypeTB.BonusMeleeDamage;
		uStats=GetSpecificUnitStat(prefabID);
		total+=dmg*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=dmg*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkMinRangeDamageBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamageMin;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.rangeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.rangeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		statID=(int)_PerkTypeTB.BonusRangeDamageMin;
		uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.rangeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.rangeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkMaxRangeDamageBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamageMax;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.rangeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.rangeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		statID=(int)_PerkTypeTB.BonusRangeDamageMax;
		uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.rangeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.rangeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkMinMeleeDamageBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamageMin;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.meleeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.meleeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		statID=(int)_PerkTypeTB.BonusMeleeDamageMin;
		uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.meleeDamageMin*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.meleeDamageMin*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static int GetPerkMaxMeleeDamageBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamageMax;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.meleeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.meleeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		statID=(int)_PerkTypeTB.BonusMeleeDamageMax;
		uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.meleeDamageMax*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.meleeDamageMax*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static float GetPerkCounterModifierBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusCounterModifier;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.counterDmgModifier*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.counterDmgModifier*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}

	public static float GetPerkRangeAttackBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusHitRange;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.attRange*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.attRange*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}

	public static float GetPerkMeleeAttackBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusHitMelee;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.attMelee*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.attMelee*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}

	public static float GetPerkRangeCriticalBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusCritRange;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.criticalRange*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.criticalRange*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}

	public static float GetPerkMeleeCriticalBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusCritMelee;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.criticalMelee*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.criticalMelee*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}

	public static int GetPerkMoveCountBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusMove;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.movePerTurn*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.movePerTurn*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}
	public static int GetPerkAttackCountBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusAttack;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.attackPerTurn*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.attackPerTurn*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}
	public static int GetPerkCounterCountBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusCounter;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.counterPerTurn*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.counterPerTurn*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

	public static float GetPerkDefendBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDodge;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.defend*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.defend*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}
	public static float GetPerkCritImmuneBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusCritImmune;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.critDef*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.critDef*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}
	public static float GetPerkDamageReductionBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.BonusDamageReduc;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total+=uStats.unit.damageReduc*uStats.stats[statID].mod+uStats.stats[statID].value;
		total+=uStats.unit.damageReduc*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return total;
	}

	public static int GetPerkAttackAPReductionBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.APAttackReduc;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total-=uStats.unit.APCostAttack*uStats.stats[statID].mod+uStats.stats[statID].value;
		total-=uStats.unit.APCostAttack*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}
	public static int GetPerkMoveAPReductionBonus(int prefabID){
		float total=0;	int statID=(int)_PerkTypeTB.APMoveReduc;

		UnitStatModifier uStats=GetSpecificUnitStat(prefabID);
		total-=uStats.unit.APCostMove*uStats.stats[statID].mod+uStats.stats[statID].value;
		total-=uStats.unit.APCostMove*globalUnitStats.stats[statID].mod+globalUnitStats.stats[statID].value;

		return (int)total;
	}

}


text:
package com.liulishuo.filedownloader.notification;

import android.app.NotificationManager;
import android.content.Context;

import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.util.FileDownloadHelper;

/**
 * An atom notification item which identify with a downloading task, they have the same downloading
 * Id.
 *
 * @see FileDownloadNotificationHelper
 * @see FileDownloadNotificationListener
 */
@SuppressWarnings("WeakerAccess")
public abstract class BaseNotificationItem {

    private int id, sofar, total;
    private String title, desc;

    private int status = FileDownloadStatus.INVALID_STATUS;
    private int lastStatus = FileDownloadStatus.INVALID_STATUS;

    public BaseNotificationItem(final int id, final String title, final String desc) {
        this.id = id;

        this.title = title;
        this.desc = desc;
    }

    public void show(boolean isShowProgress) {
        show(isChanged(), getStatus(), isShowProgress);
    }

    /**
     * @param isShowProgress Whether there is a need to show the progress schedule changes
     */
    public abstract void show(boolean statusChanged, int status, boolean isShowProgress);

    public void update(final int sofar, final int total) {
        this.sofar = sofar;
        this.total = total;
        show(true);
    }

    public void updateStatus(final int status) {
        this.status = status;
    }

    public void cancel() {
        getManager().cancel(id);
    }

    private NotificationManager manager;

    protected NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) FileDownloadHelper.getAppContext().
                    getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return manager;
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getSofar() {
        return sofar;
    }

    public void setSofar(int sofar) {
        this.sofar = sofar;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public int getStatus() {
        this.lastStatus = status;
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public int getLastStatus() {
        return lastStatus;
    }

    public boolean isChanged() {
        return this.lastStatus != status;
    }
}


text:
<?php

$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */

$installer->startSetup();

$installer->getConnection()->dropKey($this->getTable('cms/page'), 'identifier');

$installer->run("ALTER TABLE `{$this->getTable('cms/page')}` ADD KEY `identifier` (`identifier`)");

$installer->getConnection()->dropColumn($this->getTable('cms/page'), 'store_id');

$installer->getConnection()->dropColumn($this->getTable('cms/block'), 'store_id');

$installer->endSetup();


text:
package org.apache.cordova;

import android.app.Activity;
import android.content.Intent;

import org.apache.cordova.CordovaPlugin;

import java.util.concurrent.ExecutorService;

/**
 * The Activity interface that is implemented by CordovaActivity.
 * It is used to isolate plugin development, and remove dependency on entire Cordova library.
 */
public interface CordovaInterface {

    /**
     * Launch an activity for which you would like a result when it finished. When this activity exits,
     * your onActivityResult() method will be called.
     *
     * @param command     The command object
     * @param intent      The intent to start
     * @param requestCode   The request code that is passed to callback to identify the activity
     */
    void startActivityForResult(CordovaPlugin command, Intent intent, int requestCode);

    /**
     * Set the plugin to be called when a sub-activity exits.
     *
     * @param plugin      The plugin on which onActivityResult is to be called
     */
    void setActivityResultCallback(CordovaPlugin plugin);

    /**
     * Get the Android activity.
     *
     * @return the Activity
     */
    Activity getActivity();

    /**
     * Called when a message is sent to plugin.
     *
     * @param id            The message id
     * @param data          The message data
     * @return              Object or null
     */
    Object onMessage(String id, Object data);

    /**
     * Returns a shared thread pool that can be used for background tasks.
     */
    ExecutorService getThreadPool();
}


text:
Contact Author

    <form method="post" action="">
        Regarding

        <select id="subject" name="subject">
            <option>Feedback</option>
            <option>Consultation Request</option>
            <option>Bug Report</option>
            <option>Feature Request</option>
        </select>

        Message
<textarea id="comments" style="width:400px; height:100px"
                                                            name="comments"></textarea>
        <input type="submit" class="submitbutton" value="Send Email" name="subscribe">
    </form>

Rate this plugin, please.

Say hello to me on Twitter, or LinkedIn.


text:
const { expect } = require('chai');
const request = require('supertest');

const api = require('../../../');
const { cleanDatabase, createPosts } = require('../../helpers');

describe('GET /api/posts when posts exist', async () => {
  before(async () => {
    await createPosts();
  });

  after(async () => {
    await cleanDatabase();
  });

  it('Successfully retrieves multiple blog posts in the correct order', async () => {
    const res = await request(api)
      .get('/api/posts');

    expect(res.status).to.equal(200);
    expect(res.headers['content-type']).to.equal('application/json; charset=utf-8');
    expect(res.body[0].categories).to.equal('0');
    expect(res.body[0].title).to.equal('0');
    expect(res.body[1].categories).to.equal('1');
    expect(res.body[1].title).to.equal('1');
  });
});

describe('GET /api/posts when no posts exist', async () => {
  it('Successfully retrieves multiple blog posts in the correct order', async () => {
    const res = await request(api)
      .get('/api/posts');

    expect(res.status).to.equal(200);
    expect(res.headers['content-type']).to.equal('application/json; charset=utf-8');
    expect(Array.isArray(res.body));
    expect(res.body.length).to.equal(0);
  });
});


text:
#include "core/fetch/CSSStyleSheetResource.h"

#include "core/css/StyleSheetContents.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/StyleSheetResourceClient.h"
#include "platform/SharedBuffer.h"
#include "wtf/CurrentTime.h"

namespace blink {

PassRefPtrWillBeRawPtr<CSSStyleSheetResource> CSSStyleSheetResource::fetch(FetchRequest& request, ResourceFetcher* fetcher)
{
    ASSERT(request.resourceRequest().frameType() == WebURLRequest::FrameTypeNone);
    request.mutableResourceRequest().setRequestContext(WebURLRequest::RequestContextStyle);
    return toCSSStyleSheetResource(fetcher->requestResource(request, CSSStyleSheetResourceFactory()));
}

PassRefPtrWillBeRawPtr<CSSStyleSheetResource> CSSStyleSheetResource::createForTest(const ResourceRequest& request, const String& charset)
{
    return adoptRefWillBeNoop(new CSSStyleSheetResource(request, charset));
}

CSSStyleSheetResource::CSSStyleSheetResource(const ResourceRequest& resourceRequest, const String& charset)
    : StyleSheetResource(resourceRequest, CSSStyleSheet, "text/css", charset)
{
    DEFINE_STATIC_LOCAL(const AtomicString, acceptCSS, ("text/css,*/*;q=0.1", AtomicString::ConstructFromLiteral));

    // Prefer text/css but accept any type (dell.com serves a stylesheet
    // as text/html; see <http://bugs.webkit.org/show_bug.cgi?id=11451>).
    setAccept(acceptCSS);
}

CSSStyleSheetResource::~CSSStyleSheetResource()
{
    // Make sure dispose() was cllaed before destruction.
    ASSERT(!m_parsedStyleSheetCache);
}

void CSSStyleSheetResource::removedFromMemoryCache()
{
    if (m_parsedStyleSheetCache)
        m_parsedStyleSheetCache->removedFromMemoryCache();
    m_parsedStyleSheetCache.clear();
    Resource::removedFromMemoryCache();
}

DEFINE_TRACE(CSSStyleSheetResource)
{
    visitor->trace(m_parsedStyleSheetCache);
    StyleSheetResource::trace(visitor);
}

void CSSStyleSheetResource::didAddClient(ResourceClient* c)
{
    ASSERT(StyleSheetResourceClient::isExpectedType(c));
    // Resource::didAddClient() must be before setCSSStyleSheet(),
    // because setCSSStyleSheet() may cause scripts to be executed, which could destroy 'c' if it is an instance of HTMLLinkElement.
    // see the comment of HTMLLinkElement::setCSSStyleSheet.
    Resource::didAddClient(c);

    if (!isLoading())
        static_cast<StyleSheetResourceClient*>(c)->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), encoding(), this);
}

const String CSSStyleSheetResource::sheetText(MIMETypeCheck mimeTypeCheck) const
{
    ASSERT(!isPurgeable());

    if (!m_data || m_data->isEmpty() || !canUseSheet(mimeTypeCheck))
        return String();

    if (!m_decodedSheetText.isNull())
        return m_decodedSheetText;

    // Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory
    return decodedText();
}

void CSSStyleSheetResource::checkNotify()
{
    // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
    if (m_data)
        m_decodedSheetText = decodedText();

    ResourceClientWalker<StyleSheetResourceClient> w(m_clients);
    while (StyleSheetResourceClient* c = w.next())
        c->setCSSStyleSheet(m_resourceRequest.url(), m_response.url(), encoding(), this);
    // Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.
    m_decodedSheetText = String();
}

bool CSSStyleSheetResource::isSafeToUnlock() const
{
    return m_data->hasOneRef();
}

void CSSStyleSheetResource::destroyDecodedDataIfPossible()
{
    if (!m_parsedStyleSheetCache)
        return;

    m_parsedStyleSheetCache->removedFromMemoryCache();
    m_parsedStyleSheetCache.clear();

    setDecodedSize(0);
}

bool CSSStyleSheetResource::canUseSheet(MIMETypeCheck mimeTypeCheck) const
{
    if (errorOccurred())
        return false;

    // This check exactly matches Firefox. Note that we grab the Content-Type
    // header directly because we want to see what the value is BEFORE content
    // sniffing. Firefox does this by setting a "type hint" on the channel.
    // This implementation should be observationally equivalent.
    //
    // This code defaults to allowing the stylesheet for non-HTTP protocols so
    // folks can use standards mode for local HTML documents.
    if (mimeTypeCheck == MIMETypeCheck::Lax)
        return true;
    AtomicString contentType = httpContentType();
    return contentType.isEmpty() || equalIgnoringCase(contentType, "text/css") || equalIgnoringCase(contentType, "application/x-unknown-content-type");
}

PassRefPtrWillBeRawPtr<StyleSheetContents> CSSStyleSheetResource::restoreParsedStyleSheet(const CSSParserContext& context)
{
    if (!m_parsedStyleSheetCache)
        return nullptr;
    if (m_parsedStyleSheetCache->hasFailedOrCanceledSubresources()) {
        m_parsedStyleSheetCache->removedFromMemoryCache();
        m_parsedStyleSheetCache.clear();
        return nullptr;
    }

    ASSERT(m_parsedStyleSheetCache->isCacheable());
    ASSERT(m_parsedStyleSheetCache->isInMemoryCache());

    // Contexts must be identical so we know we would get the same exact result if we parsed again.
    if (m_parsedStyleSheetCache->parserContext() != context)
        return nullptr;

    didAccessDecodedData();

    return m_parsedStyleSheetCache;
}

void CSSStyleSheetResource::saveParsedStyleSheet(PassRefPtrWillBeRawPtr<StyleSheetContents> sheet)
{
    ASSERT(sheet && sheet->isCacheable());

    if (m_parsedStyleSheetCache)
        m_parsedStyleSheetCache->removedFromMemoryCache();
    m_parsedStyleSheetCache = sheet;
    m_parsedStyleSheetCache->addedToMemoryCache();

    setDecodedSize(m_parsedStyleSheetCache->estimatedSizeInBytes());
}

} // namespace blink


text:
package org.knowm.xchange.kucoin;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import si.mazi.rescu.HttpStatusExceptionSupport;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"code", "msg", "success", "timestamp"})
public class KucoinException extends HttpStatusExceptionSupport {

  private static final long serialVersionUID = 1L;

  @JsonProperty("code")
  private String code;
  @JsonProperty("msg")
  private String msg;
  @JsonProperty("success")
  private boolean success;
  @JsonProperty("timestamp")
  private long timestamp;
  @JsonIgnore
  private Map<String, Object> additionalProperties = new HashMap<String, Object>();

  @Override
  public String getMessage() {
    return String.format("%s - %s (HTTP status code: %d)", code, msg, getHttpStatusCode());
  }

  @JsonProperty("code")
  public String getCode() {
    return code;
  }

  @JsonProperty("code")
  public void setCode(String code) {
    this.code = code;
  }

  @JsonProperty("msg")
  public String getMsg() {
    return msg;
  }

  @JsonProperty("msg")
  public void setMsg(String msg) {
    this.msg = msg;
  }

  @JsonProperty("success")
  public boolean isSuccess() {
    return success;
  }

  @JsonProperty("success")
  public void setSuccess(boolean success) {
    this.success = success;
  }

  @JsonProperty("timestamp")
  public long getTimestamp() {
    return timestamp;
  }

  @JsonProperty("timestamp")
  public void setTimestamp(long timestamp) {
    this.timestamp = timestamp;
  }

  @JsonAnyGetter
  public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
  }

  @JsonAnySetter
  public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
  }
}


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
if (ENABLE_AREA_LAYOUTS == false) {
	die(t('Area layouts have been disabled.'));
}
global $c;
?>

	<input id="ccm_delete_layout_cvalID" name="ccm_delete_layout_cvalID" type="hidden" value="1" />

	<?php  if($_REQUEST['hasBlocks']){ ?>

<?php echo t("What would you like to do with this layout's blocks?") ?>

		<input name="ccm_delete_layout_mode" type="radio" value="0" checked="checked" /> <?php echo t("Move them to the parent area below")?>

		<input name="ccm_delete_layout_mode" type="radio" value="1" /> <?php echo t("Delete them")?>

			<?php echo t('Cancel')?>

			<?php echo t('Remove Layout') ?>

	<?php  }else{ ?>

<?php echo t("Are you sure you want to delete this layout section?") ?>

			<?php echo t('Cancel')?>

			<?php echo t('Remove Layout') ?>

	<?php  } ?>


text:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Controls;
using Jcq.Core;
using Jcq.IcqProtocol.Contracts;
using Jcq.Ux.ViewModel.Contracts;

namespace Jcq.Ux.ViewModel
{
    public class SearchWindowViewModel : ViewModelBase
    {
        public SearchWindowViewModel()
        {
            var sv = ApplicationService.Current.Context.GetService<ISearchService>();

            sv.SearchResult += OnSearchResult;
        }

        public Collection<ContactViewModel> SearchResult { get; private set; }

        private void OnSearchResult(object sender, SearchResultEventArgs e)
        {
            try
            {
                SearchResult =
                    new Collection<ContactViewModel>(
                        (from x in e.Contacts select ContactViewModelCache.GetViewModel(x)).ToList());

                OnPropertyChanged("SearchResult");
            }
            catch (Exception ex)
            {
                Kernel.Exceptions.PublishException(ex);
            }
        }

        public void Search(string uinQuery)
        {
            var sv = ApplicationService.Current.Context.GetService<ISearchService>();

            sv.SearchByUin(uinQuery);
        }

        public void BuildContactContextMenu(ContextMenu menu, ContactViewModel contact)
        {
            var sv = ApplicationService.Current.Context.GetService<IContactContextMenuService>();
            menu.Items.Clear();

            foreach (MenuItem x in sv.GetMenuItems(contact))
            {
                menu.Items.Add(x);
            }
        }
    }
}


text:
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Quasar.Samples {

    public partial class MainPage : System.Windows.Controls.UserControl {

        internal System.Windows.Controls.Grid LayoutRoot;

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri("/Quasar.Samples;component/MainPage.xaml", System.UriKind.Relative));
            this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
        }
    }
}