text:
using Autofac;
using AutoMapper;
using Miningcore.Blockchain.Ergo.Configuration;
using Miningcore.Configuration;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Mining;
using Miningcore.Payments;
using Miningcore.Persistence;
using Miningcore.Persistence.Model;
using Miningcore.Persistence.Repositories;
using Miningcore.Time;
using Miningcore.Util;
using Block = Miningcore.Persistence.Model.Block;
using Contract = Miningcore.Contracts.Contract;
using static Miningcore.Util.ActionUtils;

namespace Miningcore.Blockchain.Ergo;

[CoinFamily(CoinFamily.Ergo)]
public class ErgoPayoutHandler : PayoutHandlerBase,
    IPayoutHandler
{
    public ErgoPayoutHandler(
        IComponentContext ctx,
        IConnectionFactory cf,
        IMapper mapper,
        IShareRepository shareRepo,
        IBlockRepository blockRepo,
        IBalanceRepository balanceRepo,
        IPaymentRepository paymentRepo,
        IMasterClock clock,
        IMessageBus messageBus) :
        base(cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, messageBus)
    {
        Contract.RequiresNonNull(ctx);
        Contract.RequiresNonNull(balanceRepo);
        Contract.RequiresNonNull(paymentRepo);

        this.ctx = ctx;
    }

    protected readonly IComponentContext ctx;
    protected ErgoClient ergoClient;
    private string network;
    private ErgoPaymentProcessingConfigExtra extraPoolPaymentProcessingConfig;

    protected override string LogCategory => "Ergo Payout Handler";

    private class PaymentException : Exception
    {
        public PaymentException(string msg) : base(msg)
        {
        }
    }

    private void ReportAndRethrowApiError(string action, Exception ex, bool rethrow = true)
    {
        var error = ex.Message;

        if(ex is ApiException<ApiError> apiException)
            error = apiException.Result.Detail ?? apiException.Result.Reason;

        logger.Warn(() => $"{action}: {error}");

        if(rethrow)
            throw ex;
    }

    private async Task UnlockWallet(CancellationToken ct)
    {
        logger.Info(() => $"[{LogCategory}] Unlocking wallet");

        var walletPassword = extraPoolPaymentProcessingConfig.WalletPassword ?? string.Empty;

        await Guard(() => ergoClient.WalletUnlockAsync(new UnlockWallet {Pass = walletPassword}, ct), ex =>
        {
            if (ex is ApiException<ApiError> apiException)
            {
                var error = apiException.Result.Detail;

                if (error != null && !error.ToLower().Contains("already unlocked"))
                    throw new PaymentException($"Failed to unlock wallet: {error}");
            }

            else
                throw ex;
        });

        logger.Info(() => $"[{LogCategory}] Wallet unlocked");
    }

    private async Task LockWallet(CancellationToken ct)
    {
        logger.Info(() => $"[{LogCategory}] Locking wallet");

        await Guard(() => ergoClient.WalletLockAsync(ct),
            ex => ReportAndRethrowApiError("Failed to lock wallet", ex));

        logger.Info(() => $"[{LogCategory}] Wallet locked");
    }

    #region IPayoutHandler

    public virtual async Task ConfigureAsync(ClusterConfig cc, PoolConfig pc, CancellationToken ct)
    {
        Contract.RequiresNonNull(pc);

        logger = LogUtil.GetPoolScopedLogger(typeof(ErgoPayoutHandler), pc);

        poolConfig = pc;
        clusterConfig = cc;
        extraPoolPaymentProcessingConfig = pc.PaymentProcessing.Extra.SafeExtensionDataAs<ErgoPaymentProcessingConfigExtra>();

        ergoClient = ErgoClientFactory.CreateClient(pc, cc, null);

        // detect chain
        var info = await ergoClient.GetNodeInfoAsync(ct);
        network = ErgoConstants.RegexChain.Match(info.Name).Groups[1].Value.ToLower();
    }

    public virtual async Task<Block[]> ClassifyBlocksAsync(IMiningPool pool, Block[] blocks, CancellationToken ct)
    {
        Contract.RequiresNonNull(poolConfig);
        Contract.RequiresNonNull(blocks);

        if(blocks.Length == 0)
            return blocks;

        var coin = poolConfig.Template.As<ErgoCoinTemplate>();
        var pageSize = 100;
        var pageCount = (int) Math.Ceiling(blocks.Length / (double) pageSize);
        var result = new List<Block>();
        var minConfirmations = extraPoolPaymentProcessingConfig?.MinimumConfirmations ?? (network == "mainnet" ? 720 : 72);
        var minerRewardsPubKey = await ergoClient.MiningReadMinerRewardPubkeyAsync(ct);
        var minerRewardsAddress = await ergoClient.MiningReadMinerRewardAddressAsync(ct);

        for(var i = 0; i < pageCount; i++)
        {
            // get a page full of blocks
            var page = blocks
                .Skip(i * pageSize)
                .Take(pageSize)
                .ToArray();

            // fetch header ids for blocks in page
            var headerBatch = page.Select(block => ergoClient.GetFullBlockAtAsync((int) block.BlockHeight, ct)).ToArray();

            await Guard(()=> Task.WhenAll(headerBatch),
                ex=> logger.Debug(ex));

            for(var j = 0; j < page.Length; j++)
            {
                var block = page[j];
                var headerTask = headerBatch[j];

                if(!headerTask.IsCompletedSuccessfully)
                {
                    if(headerTask.IsFaulted)
                        logger.Warn(()=> $"Failed to fetch block {block.BlockHeight}: {headerTask.Exception?.InnerException?.Message ?? headerTask.Exception?.Message}");
                    else
                        logger.Warn(()=> $"Failed to fetch block {block.BlockHeight}: {headerTask.Status.ToString().ToLower()}");

                    continue;
                }

                var headerIds = headerTask.Result;

                // fetch blocks
                var blockBatch = headerIds.Select(x=> ergoClient.GetFullBlockByIdAsync(x, ct)).ToArray();

                await Guard(()=> Task.WhenAll(blockBatch),
                    ex=> logger.Debug(ex));

                var blockHandled = false;
                var pkMismatchCount = 0;
                var nonceMismatchCount = 0;
                var coinbaseNonWalletTxCount = 0;

                foreach (var blockTask in blockBatch)
                {
                    if(blockHandled)
                        break;

                    if(!blockTask.IsCompletedSuccessfully)
                        continue;

                    var fullBlock = blockTask.Result;

                    // only consider blocks with pow-solution pk matching ours
                    if(fullBlock.Header.PowSolutions.Pk != minerRewardsPubKey.RewardPubkey)
                    {
                        pkMismatchCount++;
                        continue;
                    }

                    // only consider blocks with pow-solution nonce matching what we have on file
                    if(fullBlock.Header.PowSolutions.N != block.TransactionConfirmationData)
                    {
                        nonceMismatchCount++;
                        continue;
                    }

                    var coinbaseWalletTxFound = false;

                    // reset block reward
                    block.Reward = 0;

                    foreach(var blockTx in fullBlock.BlockTransactions.Transactions)
                    {
                        var walletTx = await Guard(()=> ergoClient.WalletGetTransactionAsync(blockTx.Id, ct));
                        var coinbaseOutput = walletTx?.Outputs.FirstOrDefault(x => x.Address == minerRewardsAddress.RewardAddress1);

                        if(coinbaseOutput != null)
                        {
                            coinbaseWalletTxFound = true;

                            block.ConfirmationProgress = Math.Min(1.0d, (double) walletTx.NumConfirmations / minConfirmations);
                            block.Hash = fullBlock.Header.Id;

                            var assetValue = coinbaseOutput.Assets?.FirstOrDefault()?.Amount ?? 0;
                            block.Reward += (coinbaseOutput.Value - assetValue) / ErgoConstants.SmallestUnit;

                            if(walletTx.NumConfirmations >= minConfirmations)
                            {
                                // matured and spendable coinbase transaction
                                block.Status = BlockStatus.Confirmed;
                                block.ConfirmationProgress = 1;
                            }
                        }
                    }

                    blockHandled = coinbaseWalletTxFound;

                    if(blockHandled)
                    {
                        result.Add(block);

                        if(block.Status == BlockStatus.Confirmed)
                        {
                            logger.Info(() => $"[{LogCategory}] Unlocked block {block.BlockHeight} worth {FormatAmount(block.Reward)}");

                            messageBus.NotifyBlockUnlocked(poolConfig.Id, block, coin);
                        }

                        else
                            messageBus.NotifyBlockConfirmationProgress(poolConfig.Id, block, coin);
                    }

                    else
                        coinbaseNonWalletTxCount++;
                }

                if(!blockHandled)
                {
                    string orphanReason = null;

                    if(pkMismatchCount == blockBatch.Length)
                        orphanReason = "pk mismatch";
                    else if(nonceMismatchCount == blockBatch.Length)
                        orphanReason = "nonce mismatch";
                    else if(coinbaseNonWalletTxCount == blockBatch.Length)
                        orphanReason = "no related coinbase tx found in wallet";

                    if(!string.IsNullOrEmpty(orphanReason))
                    {
                        block.Status = BlockStatus.Orphaned;
                        block.Reward = 0;
                        result.Add(block);

                        logger.Info(() => $"[{LogCategory}] Block {block.BlockHeight} classified as orphaned due to {orphanReason}");

                        messageBus.NotifyBlockUnlocked(poolConfig.Id, block, coin);
                    }
                }
            }
        }

        return result.ToArray();
    }

    public override double AdjustShareDifficulty(double difficulty)
    {
        return difficulty * ErgoConstants.ShareMultiplier;
    }

    public double AdjustBlockEffort(double effort)
    {
        return effort * ErgoConstants.ShareMultiplier;
    }

    public virtual async Task PayoutAsync(IMiningPool pool, Balance[] balances, CancellationToken ct)
    {
        Contract.RequiresNonNull(balances);

        // build args
        var amounts = balances
            .Where(x => x.Amount > 0)
            .ToDictionary(x => x.Address, x => Math.Round(x.Amount, 4));

        if(amounts.Count == 0)
            return;

        var balancesTotal = amounts.Sum(x => x.Value);

        try
        {
            logger.Info(() => $"[{LogCategory}] Paying {FormatAmount(balances.Sum(x => x.Amount))} to {balances.Length} addresses");

            // get wallet status
            var status = await ergoClient.GetWalletStatusAsync(ct);

            if(!status.IsInitialized)
                throw new PaymentException($"Wallet is not initialized");

            if(!status.IsUnlocked)
                await UnlockWallet(ct);

            // get balance
            var walletBalances = await ergoClient.WalletBalancesAsync(ct);
            var walletTotal = walletBalances.Balance / ErgoConstants.SmallestUnit;

            logger.Info(() => $"[{LogCategory}] Current wallet balance is {FormatAmount(walletTotal)}");

            // bail if balance does not satisfy payments
            if(walletTotal < balancesTotal)
            {
                logger.Warn(() => $"[{LogCategory}] Wallet balance currently short of {FormatAmount(balancesTotal - walletTotal)}. Will try again.");
                return;
            }

            // validate addresses
            logger.Info("Validating addresses ...");

            foreach(var pair in amounts)
            {
                var validity = await Guard(() => ergoClient.CheckAddressValidityAsync(pair.Key, ct));

                if(validity == null || !validity.IsValid)
                    logger.Warn(()=> $"Address {pair.Key} is not valid!");
            }

            // Create request batch
            var requests = amounts.Select(x => new PaymentRequest
            {
                Address = x.Key,
                Value = (long) (x.Value * ErgoConstants.SmallestUnit),
            }).ToArray();

            var txId = await Guard(()=> ergoClient.WalletPaymentTransactionGenerateAndSendAsync(requests, ct), ex =>
            {
                if(ex is ApiException<ApiError> apiException)
                {
                    var error = apiException.Result.Detail ?? apiException.Result.Reason;

                    if(error.Contains("reason:"))
                        error = error.Substring(error.IndexOf("reason:"));

                    throw new PaymentException($"Payment transaction failed: {error}");
                }

                else
                    throw ex;
            });

            if(string.IsNullOrEmpty(txId))
                throw new PaymentException("Payment transaction failed to return a transaction id");

            // payment successful
            logger.Info(() => $"[{LogCategory}] Payment transaction id: {txId}");

            await PersistPaymentsAsync(balances, txId);

            NotifyPayoutSuccess(poolConfig.Id, balances, new[] {txId}, null);
        }

        catch(PaymentException ex)
        {
            logger.Error(() => $"[{LogCategory}] {ex.Message}");

            NotifyPayoutFailure(poolConfig.Id, balances, ex.Message, null);
        }

        finally
        {
            await LockWallet(ct);
        }
    }

    #endregion // IPayoutHandler
}


text:
module.exports = {
  name: 'Create Animated Emoji',
  section: 'Emoji Control',
  meta: {
    version: '2.1.6',
    preciseCheck: false,
    author: 'DBM Mods',
    authorUrl: 'https://github.com/dbm-network/mods',
    downloadURL: 'https://github.com/dbm-network/mods/blob/master/actions/create_animated_emoji_MOD.js',
  },

  subtitle(data) {
    return `${data.emojiName}`;
  },

  variableStorage(data, varType) {
    if (parseInt(data.storage2, 10) !== varType) return;
    return [data.varName2, 'Animated Emoji'];
  },

  fields: ['emojiName', 'storage', 'varName', 'storage2', 'varName2'],

  html(_isEvent, data) {
    return `

  Animated Emoji Name:

  <input id="emojiName" class="round" type="text">

    Source GIF:

    <select id="storage" class="round" onchange="glob.refreshVariableList(this)">
      ${data.variables[1]}
    </select>

    Variable Name:

    <input id="varName" class="round" type="text" list="variableList">

    Store In:

    <select id="storage2" class="round" onchange="glob.onChange1(this)">
      ${data.variables[0]}
    </select>

    Variable Name:

    <input id="varName2" class="round" type="text">

`;
  },

  init() {
    const { glob, document } = this;

    glob.onChange1 = function onChange1(event) {
      const value = parseInt(event.value, 10);
      const varNameInput = document.getElementById('varNameContainer2');
      if (value === 0) {
        varNameInput.style.display = 'none';
      } else {
        varNameInput.style.display = null;
      }
    };

    glob.refreshVariableList(document.getElementById('storage'));
    glob.onChange1(document.getElementById('storage2'));
  },

  async action(cache) {
    const data = cache.actions[cache.index];
    const { server } = cache;

    if (!server?.emojis?.create) return this.callNextAction(cache);

    const type = parseInt(data.storage, 10);
    const varName = this.evalMessage(data.varName, cache);
    const gif = this.getVariable(type, varName, cache);
    const name = this.evalMessage(data.emojiName, cache);

    server.emojis
      .create(gif, name)
      .then((emoji) => {
        const varName2 = this.evalMessage(data.varName2, cache);
        const storage = parseInt(data.storage2, 10);
        this.storeValue(emoji, storage, varName2, cache);
        this.callNextAction(cache);
      })
      .catch(this.displayError.bind(this, data, cache));
  },

  mod() {},
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PhpInPractice\Matters\Projection\StateSerializer;

use Mockery as m;

/**
 * @coversDefaultClass PhpInPractice\Matters\Projection\StateSerializer\FromArray
 * @covers ::<private>
 */
class FromArrayTest extends \PHPUnit_Framework_TestCase
{
    /** @var FromArray */
    private $serializer;

    public function setUp()
    {
        $this->serializer = $serializer = new FromArray();
    }

    /**
     * @test
     * @covers ::unserialize
     */
    public function it_should_call_from_array_on_event_when_unserializing()
    {
        $expected = ['id' => 1];

        $event = $this->serializer->unserialize(FromArrayProjectionMock::class, $expected);

        $this->assertInstanceOf(FromArrayProjectionMock::class, $event);
        $this->assertSame($expected['id'], $event->id());
    }

    /**
     * @test
     * @covers ::unserialize
     * @expectedException \PhpInPractice\Matters\Projection\StateSerializer\MissingMethodException
     */
    public function it_should_throw_an_exception_if_the_from_array_method_does_not_exist()
    {
        $this->serializer->unserialize('stdClass', ['id' => 1]);
    }
}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)setUpStatusButton {
    NSStatusBarButton *statusButton = self.statusItem.button;
    NSImage *buttonImage = [NSImage imageNamed:@"Status"];
    NSImage *alterButtonImage = [NSImage imageNamed:@"StatusHighlighted"];

    statusButton.image = buttonImage;
    statusButton.alternateImage = alterButtonImage;
}

static OSStatus superHotKeyHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData) {
    NSLog(@"Event");

    return CallNextEventHandler(nextHandler, event);
}

- (void)registerHotKeys {
    EventHotKeyRef hotKeyRef;
    EventHotKeyID hotKeyID;
    EventTypeSpec eventType;
    EventHandlerUPP	handlerUPP;

    eventType.eventClass = kEventClassKeyboard;
    eventType.eventKind = kEventHotKeyPressed;

    handlerUPP = NewEventHandlerUPP(superHotKeyHandler);
    InstallApplicationEventHandler(handlerUPP, 1, &eventType, nil, nil);

    hotKeyID.signature = 'xxxx';
    hotKeyID.id = 1234;

    RegisterEventHotKey(kVK_ANSI_C, cmdKey, hotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef);
    RegisterEventHotKey(kVK_ANSI_S, cmdKey, hotKeyID, GetApplicationEventTarget(), 0, &hotKeyRef);
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    self.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:24];
    [self setUpStatusButton];

    [self registerHotKeys];
}

- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}

@end


text:
namespace QuickFAST
{
  namespace DotNet
  {
    /// @brief A .NET representation of a FAST encoded Decimal field
    public value struct DNDecimal
    {
      /// @brief the mantissa
      __int64  Mantissa;
      /// @brief the exponent (base 10)
      signed char Exponent;

      /// @brief constuct from separate mantissa and exponent
      DNDecimal(__int64 mantissa, signed char exponent):
        Mantissa(mantissa),
        Exponent(exponent)
      {
      }

      /// @brief Express the value as a double
      double ToDouble()
      {
        return (double)Mantissa * System::Math::Pow(10, Exponent);
      }

      /// @brief Express the value as a string
      virtual System::String^ ToString() override
      {
        return System::String::Format("{0}E{1}", this->Mantissa, this->Exponent);
      }

    internal:
      DNDecimal(const QuickFAST::Decimal& decimal):
        Mantissa(decimal.getMantissa()),
        Exponent(decimal.getExponent())
      {
      }
    };
  }
}


text:
package com.googlecode.totallylazy.iterators;

import java.util.Enumeration;

public final class EnumerationIterator<T> extends ReadOnlyIterator<T> {
    private final Enumeration<T> enumeration;

    public EnumerationIterator(final Enumeration<T> enumeration) {
        this.enumeration = enumeration;
    }

    public final boolean hasNext() {
        return enumeration.hasMoreElements();
    }

    public T next() {
        return enumeration.nextElement();
    }
}


text:
package help

import (
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/thought-machine/please/src/core"
)

func TestRuleArgs(t *testing.T) {
	env := getRuleArgs(core.NewDefaultBuildState())
	assert.True(t, len(env.Functions) > 20) // Don't care exactly how many there are, but it should have a fair few.
	rule := env.Functions["cc_library"]
	assert.True(t, len(rule.Args) > 5)
	assert.NotEqual(t, "", rule.Comment)
	assert.NotEqual(t, "", rule.Docstring)
	assert.Equal(t, "cc", rule.Language)
	// Some of this is getting a bit more specific than I'd like, but we have to test it on *something*,
	// and it'd not be hard to update if the rule does change.
	arg := rule.Args[0]
	assert.Equal(t, "name", arg.Name)
	assert.True(t, arg.Required)
	assert.False(t, arg.Deprecated)
	assert.Equal(t, []string{"str"}, arg.Types)
	assert.Equal(t, "Name of the rule", arg.Comment)
	arg = rule.Args[3]
	assert.Equal(t, "hdrs", arg.Name)
	assert.False(t, arg.Required)
	assert.False(t, arg.Deprecated)
	assert.Equal(t, []string{"list"}, arg.Types)
	assert.Equal(t, "Header files. These will be made available to dependent rules, so the distinction between srcs and hdrs is important.", arg.Comment)
}

func TestMultilineComment(t *testing.T) {
	env := getRuleArgs(core.NewDefaultBuildState())
	rule := env.Functions["new_http_archive"]
	assert.True(t, strings.Count(rule.Comment, "\n") > 1)
}


text:
'use strict';

module.exports = (options) => {
	const makePath = require('../makepath');

	return require('../common/restructure')(Object.assign({
		restructure: {
			src: '*.css',
			configures: makePath([options.basedir, options.projectDir], ['', 'gulp-configs'], 'restructure.config.json'),
			replaceManifest: 'assets-manifest-unreved.json',
			manifest: 'css-manifest-unreved.json'
		}
	}, options));
};


text:
#ifndef XSIMD_AVX512F_REGISTER_HPP
#define XSIMD_AVX512F_REGISTER_HPP

#include "./xsimd_generic_arch.hpp"

namespace xsimd
{

    /**
     * @ingroup arch
     *
     * AVX512F instructions
     */
    struct avx512f : generic
    {
        static constexpr bool supported() noexcept { return XSIMD_WITH_AVX512F; }
        static constexpr bool available() noexcept { return true; }
        static constexpr unsigned version() noexcept { return generic::version(3, 1, 0); }
        static constexpr std::size_t alignment() noexcept { return 64; }
        static constexpr bool requires_alignment() noexcept { return true; }
        static constexpr char const* name() noexcept { return "avx512f"; }
    };

#if XSIMD_WITH_AVX512F

    namespace types
    {
        template <class T>
        struct simd_avx512_bool_register
        {
            using register_type = typename std::conditional<
                (sizeof(T) < 4), std::conditional<(sizeof(T) == 1), __mmask64, __mmask32>,
                std::conditional<(sizeof(T) == 4), __mmask16, __mmask8>>::type::type;
            register_type data;
            simd_avx512_bool_register() = default;
            simd_avx512_bool_register(register_type r) { data = r; }
            operator register_type() const noexcept { return data; }
        };
        template <class T>
        struct get_bool_simd_register<T, avx512f>
        {
            using type = simd_avx512_bool_register<T>;
        };

        XSIMD_DECLARE_SIMD_REGISTER(bool, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(signed char, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned char, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(char, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned short, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(short, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned int, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(int, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned long int, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(long int, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(unsigned long long int, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(long long int, avx512f, __m512i);
        XSIMD_DECLARE_SIMD_REGISTER(float, avx512f, __m512);
        XSIMD_DECLARE_SIMD_REGISTER(double, avx512f, __m512d);

    }
#endif
}

#endif


text:
"""Cloudmesh install util functions.

This file contains basic utility functions that must not need any
import from cloudmesh OR any other non-standard python
modules. Everything in this file must execute on a clean python 2.7.x
environment.

"""
import platform

from string import Template
import os
import sys

def get_system():
    if is_ubuntu():
        return "ubuntu"
    elif is_centos():
        return "centos"
    elif is_osx():
        return "osx"
    else:
        return "unsupported"

def is_ubuntu():
    """test sif the platform is ubuntu"""
    (dist, version, release) = platform.dist()
    if dist == "ubuntu" and version not in ["14.04"]:
        print("ERROR: %s %s is not tested" % (dist, version))
    return dist == 'Ubuntu'

def is_centos():
    """test if the platform is centos"""
    (dist, version, release) = platform.dist()
    if dist == "centos" and version not in ["6.5"]:
        print("WARNING: %s %s is not tested" % (dist, version))
    return dist == "centos"

def is_osx():
    osx = platform.system().lower() == 'darwin'
    if osx:
        os_version = platform.mac_ver()[0]
        if os_version not in ['10.9.5',
                              '10.10',
                              '10.10.1',
                              '10.10.2',
                              '10.10.3']:
            osx = False
            print("WARNING: %s %s is not tested" % ('OSX', os_version))
    return osx


text:
layout: page
title: Frederick 30th Anniversary
date: 2016-05-24
author: Vincent Murphy
tags: weekly links, java
status: published
summary: Vestibulum in gravida nunc. Fusce felis tellus, tempus nec est.
banner: images/banner/people.jpg
booking:
  startDate: 05/18/2017
  endDate: 05/21/2017
  ctyhocn: MKCSMHX
  groupCode: F3A
published: true
---
Nunc pulvinar orci et risus rutrum, at accumsan turpis blandit. Nulla et turpis efficitur, suscipit ipsum vel, varius enim. Sed tristique sollicitudin velit congue posuere. Aliquam aliquet id est vitae tincidunt. Integer lobortis mattis est id sodales. In placerat elementum commodo. Nunc posuere efficitur dolor, sed hendrerit ante tempus sed. In pulvinar vel orci ac ultricies. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer quam quam, placerat ultrices risus rutrum, scelerisque pulvinar elit. Mauris nisl augue, maximus id lorem nec, dignissim facilisis neque. Aenean ornare ornare dictum. Praesent luctus nulla ac risus iaculis maximus. Proin id urna elementum, varius turpis sed, laoreet lacus.

* Nullam in nunc at nunc vehicula aliquet finibus ac augue
* Cras sed enim tincidunt, pulvinar arcu in, convallis risus
* Nulla molestie diam eget faucibus bibendum.

Donec luctus purus et pulvinar posuere. Duis feugiat mauris nec dapibus fermentum. Nullam neque elit, luctus cursus interdum eu, sollicitudin eget lacus. Nullam vestibulum luctus sem, sit amet mollis mi fringilla id. Mauris volutpat lacus eu gravida interdum. Nulla ultricies metus et quam tempor porttitor. Sed porttitor, eros in fermentum euismod, est libero feugiat odio, id rhoncus felis libero quis ligula.


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="bundle">
        <note>
            Frames file for 'bundle' based on sentences in wsj.  Verbnet entry
            22.3-2.
        </note>

        <roleset id="bundle.01" name="put items together   into a bundle" vncls="22.3-2">
            <roles>
                <role descr="bundler (not bungler)" n="0">
                    <vnrole vncls="22.3-2" vntheta="Agent"/>
                </role>
                <role descr="items" n="1">
                    <vnrole vncls="22.3-2" vntheta="Patient"/>
                </role>
                <role descr="bundle" n="2"/>
            </roles>

            <example name="banking services">
                <inflection aspect="ns" form="gerund" person="ns" tense="present" voice="active"/>
                <text>
                    Instead, [they]-2 are trying *trace* to build customer loyalty by
                    *trace*-2 bundling their services into packages and targeting them
                    to small segments of the population.
                </text>
                <arg n="0">*trace*-2</arg>
                <rel>bundling</rel>
                <arg n="1">their services</arg>
                <arg n="2">into packages</arg>
            </example>

            <note>
            </note>

        </roleset>

        <roleset id="bundle.02" name="dress warmly" vncls="22.3-2-1">
            <roles>
                <role descr="causal agent of dressing" n="0">
                    <vnrole vncls="22.3-2-1" vntheta="Agent"/>
                </role>
                <role descr="entity dressed" n="1">
                    <vnrole vncls="22.3-2-1" vntheta="Patient"/>
                </role>
                <role descr="clothing" n="2"/>
            </roles>

            <example name="passive">
                <inflection aspect="ns" form="participle" person="ns" tense="ns" voice="passive"/>
                <text>
                    ``Ski school is great,'' cries out [a tot]-1,*trace*-1 bundled in a snowsuit as
                    he plows down a bunny slope.
                </text>
                <rel>bundled</rel>
                <arg n="1">*trace*-1</arg>
                <arg n="2">in a snowsuit</arg>
            </example>

            <note>
                Two senses might be difficult to distinguish, except 'dressing' sense
                seems usually occur in the passive?
            </note>

        </roleset>
    </predicate>
    <predicate lemma="bundle_up">
        <roleset id="bundle.03" name="dress warmly">
            <roles>
                <role descr="causal agent of dressing" n="0"/>
                <role descr="entity dressed" n="1"/>
                <role descr="clothing" n="2"/>
            </roles>
            <example name="necessity">
                <text>
                    You have *-1 to bundle up.
                </text>
                <arg n="1">*-1 you</arg>
                <rel>bundle up</rel>
            </example>
        </roleset>
        <note>frame by Perryn</note>
    </predicate>

</frameset>


text:
import editor
from blackmamba.config import get_config_value

def get_line_count():
    text = editor.get_text()

    if text is None:
        return None

    return len(text.splitlines())

def get_line_number():
    text = editor.get_text()

    if text is None:
        return None

    return text.count('\n', 0, editor.get_selection()[0]) + 1

def get_column_index():
    text = editor.get_text()

    if text is None:
        return None

    col = 0
    index = editor.get_selection()[0]
    while index > 0:
        if text[index - 1] == '\n':
            break
        index -= 1
        col += 1

    return col

def scroll_to_line(line_number, relative=False):
    text = editor.get_text()
    if not text:
        return

    if relative:
        current_line = get_line_number()
        line_count = get_line_count()

        if current_line is None or line_count is None:
            return

        line_number = max(min(current_line + line_number, line_count), 1)

    # https://github.com/omz/Pythonista-Issues/issues/365
    start = 0
    for index, line in enumerate(text.splitlines(True)):
        if index == line_number - 1:
            editor.set_selection(start)
            return
        start += len(line)
    editor.set_selection(start)

def page_up():
    scroll_to_line(-get_config_value('general.page_line_count', 40), True)

def page_down():
    scroll_to_line(get_config_value('general.page_line_count', 40), True)


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

angular.module('zeppelinWebApp').controller('NotebookCtrl', NotebookCtrl);

NotebookCtrl.$inject = [
  '$scope',
  'ngToast',
  'rules0',
  '$rootScope'
];

function NotebookCtrl($scope, ngToast, rules0, $rootScope) {

  ngToast.dismiss();

  $scope.note = null;
  $scope.rules = rules0.$data();
  rules0.$subscribe($scope, function (rules) {
    $scope.rules = rules;
  });

  $scope.getCronOptionNameFromValue = function(value) {
    if (!value) {
      return '';
    }

    for (var o in $scope.cronOption) {
      if ($scope.cronOption[o].value === value) {
        return $scope.cronOption[o].name;
      }
    }
    return value;
  };

  /** Init the new controller */
  var initNotebook = function() {
    $scope.note = $rootScope.note;
  };

  initNotebook();

  // register mouseevent handler for focus paragraph
  document.addEventListener('click', $scope.focusParagraphOnClick);

  $scope.keyboardShortcut = function(keyEvent) {
    // handle keyevent
    if (!$scope.viewOnly && !$scope.revisionView) {
      $scope.$broadcast('keyEvent', keyEvent);
    }
  };

  // register mouseevent handler for focus paragraph
  document.addEventListener('keydown', $scope.keyboardShortcut);

  $scope.paragraphOnDoubleClick = function(paragraphId) {
    $scope.$broadcast('doubleClickParagraph', paragraphId);
  };

  $scope.isNoteRunning = function() {
    if (!$scope.note) { return false; }
    for (var i = 0; i < $scope.note.paragraphs.length; i++) {
      const status = $scope.note.paragraphs[i].status;
      if (status === 'PENDING' || status === 'RUNNING') {
        return true;
      }
    }
    return false;
  };

  $scope.cloneRule = function (rule) {
    if ($scope.note.paragraphs[0].text) {
      if (confirm("Are you sure to overwrite existing rule?")) {
        $scope.note.paragraphs[0].text = rule;
      };
    } else {
      $scope.note.paragraphs[0].text = rule;
    }
  };

  angular.element(document).click(function() {
    angular.element('.ace_autocomplete').hide();
  });

  $scope.$on('$destroy', function() {
    angular.element(window).off('beforeunload');
    // $scope.killSaveTimer();
    /*$scope.saveNote();*/

    document.removeEventListener('click', $scope.focusParagraphOnClick);
    document.removeEventListener('keydown', $scope.keyboardShortcut);
  });

  $scope.$on('$unBindKeyEvent', function() {
    document.removeEventListener('click', $scope.focusParagraphOnClick);
    document.removeEventListener('keydown', $scope.keyboardShortcut);
  });
}


text:
// Dstl (c) Crown Copyright 2017
package uk.gov.dstl.baleen.annotators.coreference.impl.enhancers;

import uk.gov.dstl.baleen.annotators.coreference.impl.data.Mention;

/** interface for enhancers which add additional information to mentions. */
@FunctionalInterface
public interface MentionEnhancer {

  /**
   * Enhance the mention.
   *
   * @param mention the mention
   */
  void enhance(Mention mention);
}


text:
package com.ylp.date.controller;

import java.util.Collection;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ylp.date.login.Login;

public class ControlUtil {
	private static final Logger logger = LoggerFactory
			.getLogger(ControlUtil.class);
	private static final int COOKIE_EXPIRETIME = 1000 * 60 * 120;
	private static final String DATE_LOGIN_USER = "DATE_LOGIN_USER";
	private static final String DATE_LOGIN = "DATE_LOGIN";

	public static final Login getLogin(HttpServletRequest req) {
		HttpSession session = req.getSession();
		Login login = (Login) session.getAttribute(DATE_LOGIN);
		if (login == null) {
			login = new Login();
			session.setAttribute(DATE_LOGIN, login);
		}
		return login;
	}

	public static final String getImgUrl(HttpServletRequest req, String userId) {
		String contextPath = req.getContextPath();
		if (!StringUtils.isNotEmpty(contextPath)) {
			contextPath = "/";
		}
		if (!StringUtils.endsWith(contextPath, "/")) {
			contextPath = contextPath + "/";
		}
		return contextPath + "user/userinfo.do?action=img&userid=" + userId;
	}

	/**
	 * 将登陆信息写入cookie
	 *
	 * @param login
	 * @param res
	 */
	public static final void addCookieForLogin(Login login,
			HttpServletResponse res) {
		if (!login.isLogined()) {
			return;
		}
		Cookie cookie = new Cookie(DATE_LOGIN_USER, login.getUser().getId());
		cookie.setMaxAge(COOKIE_EXPIRETIME);
		res.addCookie(cookie);
	}

	/**
	 *
	 * @param res
	 */
	public static final boolean checkCookie(HttpServletRequest req) {
		Login login = ControlUtil.getLogin(req);
		if (login.isLogined()) {
			return true;
		}
		Cookie[] cookies = req.getCookies();
		if (cookies == null) {
			return false;
		}
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (StringUtils.equals(DATE_LOGIN_USER, cookie.getName())) {
				String userName = cookie.getValue();
				if (!login.isLogined()) {
					try {
						return login.loginWithoutPwd(userName);
					} catch (Exception e) {
						logger.error("登陆失败", e);
						return false;
					}
				}
			}
		}
		return false;
	}

	public static void removeLoginCookie(HttpServletResponse res) {
		Cookie cookie = new Cookie(DATE_LOGIN_USER, null);
		cookie.setMaxAge(0);
		res.addCookie(cookie);
	}

	/**
	 * 获取卡片的地址链接
	 *
	 * @param req
	 * @param id
	 * @return
	 */
	public static String getCardImgUrl(HttpServletRequest req, String id) {
		String contextPath = req.getContextPath();
		if (!StringUtils.isNotEmpty(contextPath)) {
			contextPath = "/";
		}
		if (!StringUtils.endsWith(contextPath, "/")) {
			contextPath = contextPath + "/";
		}
		return contextPath + "user/userinfo.do?action=cardImg&userid=" + id;
	}
}


text:
<?php
      $this->load->view('includes/header.php');
	  $this->load->view('includes/asside.php');
?>

          <?php $this->load->view($content) ?>

<?php
      $this->load->view('includes/footer.php');
?>


text:
// i18n hot loader library

function loadLangJSON(path, langStr, objStr, callback) {
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', path + langStr + '.json', true);
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      eval(objStr + '= JSON.parse(xobj.responseText)');
      if (callback)
        callback();
    }
  };
  xobj.send(null);
}
function loadLang(path, langStr, callback) {
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/javascript");
  xobj.open('GET', path + langStr + '.js', true);
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      eval(xobj.responseText);
      if (callback)
        callback();
    }
  };
  xobj.send(null);
};
function observerHelper(obj, func) {
  var observer = new ObjectObserver(obj);
  observer.open(function() {
    func();
  });
};

// Blockly patchs

Blockly.Input.prototype.appendField = function(field, opt_name) {
  // Empty string, Null or undefined generates no field, unless field is named.
  if (!field && !opt_name) {
    return this;
  }
  // Generate a FieldLabel when given a plain text field.
  if (goog.isString(field)) {
    field = new Blockly.FieldLabel(/** @type {string} */ (field));
  }
  //-------- patched: allows using a function in field for hot translating
  if (goog.isFunction(field)) {
    var func = field;
    field = new Blockly.FieldLabel(/** @type {function} */ (func()));
    observerHelper(Blockly.Msg, function() {
      field.setText(func())
    });
  }
  //--------
  if (this.sourceBlock_.rendered) {
    field.init(this.sourceBlock_);
  }
  field.name = opt_name;

  if (field.prefixField) {
    // Add any prefix.
    this.appendField(field.prefixField);
  }
  // Add the field to the field row.
  this.fieldRow.push(field);
  if (field.suffixField) {
    // Add any suffix.
    this.appendField(field.suffixField);
  }

  if (this.sourceBlock_.rendered) {
    this.sourceBlock_.render();
    // Adding a field will cause the block to change shape.
    this.sourceBlock_.bumpNeighbours_();
  }
  return this;
};

Blockly.BlockSvg.prototype.setMutator = function(mutator) {
  if (this.mutator && this.mutator !== mutator) {
    this.mutator.dispose();
  }
  if (mutator) {
    mutator.block_ = this;
    this.mutator = mutator;
    if (this.rendered) {
      mutator.createIcon();
    }
    //-------- patched: mutator hot translation updater
    var thisBlock = this;
    observerHelper(Blockly.Msg, function() {
      if(thisBlock.mutator.isVisible()) {
        thisBlock.mutator.setVisible(false);
        thisBlock.mutator.setVisible(true);
      }
    });
    //--------
  }
};


text:
package com.ovoenergy.comms.composer
package servicetest

import cats.implicits._
import cats.effect.IO

import com.ovoenergy.comms.model._
import formats._
import email._

import Arbitraries._
class EmailServiceSpec extends ServiceSpec {

  "Composer" should {

    "process orchestrated Email message successfully" in {
      val sourceMessage: OrchestratedEmailV4 = {
        val initial = generate[OrchestratedEmailV4]
        initial.copy(
          customerProfile = generate[CustomerProfile].some,
          templateData = Map("amount"->TemplateData.fromString("10000"))
        )
      }
      positiveTest[OrchestratedEmailV4, ComposedEmailV4](sourceMessage, topics.orchestratedEmail, topics.composedEmail){ message =>

        note(s"Sent message: ${sourceMessage} Received message: ${message}")

        message.record.key() shouldBe sourceMessage.metadata.commId
        message.record.value().metadata.commId shouldBe sourceMessage.metadata.commId
        message.record.value().recipient shouldBe sourceMessage.recipientEmailAddress
      }
    }

    "send a feedback (and failed) message if the template does not exist" in {
      val sourceMessage: OrchestratedEmailV4 = {
        val initial = generate[OrchestratedEmailV4]
        initial.copy(
          customerProfile = generate[CustomerProfile].some,
          templateData = Map("amount"->TemplateData.fromString("10000"))
        )
      }
      negativeTest[OrchestratedEmailV4](sourceMessage, topics.orchestratedEmail){ (failed, feedback) =>

        note(s"Sent message: ${sourceMessage} Received messages: ${failed} ${feedback}")

        failed.record.value().metadata.commId shouldBe sourceMessage.metadata.commId
        failed.record.value().errorCode shouldBe InvalidTemplate

        feedback.record.value().commId shouldBe sourceMessage.metadata.commId
        feedback.record.value().status shouldBe FeedbackOptions.Failed
      }
    }
  }
}


text:
layout: documentation
title: Depsets
---

# Depsets

Depsets are a specialized data structure for efficiently collecting data across
a target's transitive dependencies. Since this use case concerns the [analysis
phase](concepts.md#evaluation-model), depsets are useful for authors of rules
and aspects, but probably not macros.

The main feature of depsets is that they support a time- and space-efficient
merge operation, whose cost is independent of the size of the existing contents.
Depsets also have well-defined ordering semantics.

Example uses of depsets include:

*   storing the paths of all object files for a program's libraries, which can
    then be passed to a linker action

*   for an interpreted language, storing the transitive source files that will
    be included in an executable's runfiles

<!-- [TOC] -->

## Full example

Suppose we have a hypothetical interpreted language Foo. In order to build each
`foo_binary` we need to know all the \*.foo files that it directly or indirectly
depends on.

```python
# //mypackage:BUILD

load(":foo.bzl", "foo_library", "foo_binary")

# Our hypothetical Foo compiler.
py_binary(
    name = "foocc",
    srcs = ["foocc.py"],
)

foo_library(
    name = "a",
    srcs = ["a.foo", "a_impl.foo"],
)

foo_library(
    name = "b",
    srcs = ["b.foo", "b_impl.foo"],
    deps = [":a"],
)

foo_library(
    name = "c",
    srcs = ["c.foo", "c_impl.foo"],
    deps = [":a"],
)

foo_binary(
    name = "d",
    srcs = ["d.foo"],
    deps = [":b", ":c"],
)
```

```python
# //mypackage:foocc.py

# "Foo compiler" that just concatenates its inputs to form its output.
import sys

if __name__ == "__main__":
  assert len(sys.argv) >= 1
  output = open(sys.argv[1], "wt")
  for path in sys.argv[2:]:
    input = open(path, "rt")
    output.write(input.read())
```

Here, the transitive sources of the binary `d` are all of the \*.foo files in
the `srcs` fields of `a`, `b`, `c`, and `d`. In order for the `foo_binary`
target to know about any file besides `d.foo`, the `foo_library` targets need to
pass them along in a provider. Each library receives the providers from its own
dependencies, adds its own immediate sources, and passes on a new provider with
the augmented contents. The `foo_binary` rule does the same, except that instead
of returning a provider, it uses the complete list of sources to construct a
command line for an action.

Here's a complete implementation of the `foo_library` and `foo_binary` rules.

```python
# //mypackage/foo.bzl

# A provider with one field, transitive_sources.
FooFiles = provider()

def get_transitive_srcs(srcs, deps):
  """Obtain the source files for a target and its transitive dependencies.

  Args:
    srcs: a list of source files
    deps: a list of targets that are direct dependencies
  Returns:
    a collection of the transitive sources
  """
  trans_srcs = depset()
  for dep in deps:
    trans_srcs += dep[FooFiles].transitive_sources
  trans_srcs += srcs
  return trans_srcs

def _foo_library_impl(ctx):
  trans_srcs = get_transitive_srcs(ctx.files.srcs, ctx.attr.deps)
  return [FooFiles(transitive_sources=trans_srcs)]

foo_library = rule(
    implementation = _foo_library_impl,
    attrs = {
        "srcs": attr.label_list(allow_files=True),
        "deps": attr.label_list(),
    },
)

def _foo_binary_impl(ctx):
  foocc = ctx.executable._foocc
  out = ctx.outputs.out
  trans_srcs = get_transitive_srcs(ctx.files.srcs, ctx.attr.deps)
  srcs_list = trans_srcs.to_list()
  cmd_string = (foocc.path + " " + out.path + " " +
                " ".join([src.path for src in srcs_list]))
  ctx.actions.run_shell(command=cmd_string,
                        inputs=srcs_list + [foocc],
                        outputs=[out])

foo_binary = rule(
    implementation = _foo_binary_impl,
    attrs = {
        "srcs": attr.label_list(allow_files=True),
        "deps": attr.label_list(),
        "_foocc": attr.label(default=Label("//mypackage:foocc"),
                             allow_files=True, executable=True, cfg="host")
    },
    outputs = {"out": "%{name}.out"},
)
```

You can test this by copying these files into a fresh package, renaming the
labels appropriately, creating the source \*.foo files with dummy content, and
building the `d` target.

## Description and operations

Conceptually, a depset is a directed acyclic graph (DAG) that typically looks
similar to the target graph. It is constructed from the leaves up to the root.
Each target in a dependency chain can add its own contents on top of the
previous without having to read or copy them.

Each node in the DAG holds a list of direct elements and a list of child nodes.
The contents of the depset are the transitive elements, i.e. the direct elements
of all the nodes. A new depset with direct elements but no children can be
created using the [depset](lib/globals.html#depset) constructor. Given an
existing depset, the `+` operator can be used to form a new depset that has
additional contents. Specifically, for the operation `a + b` where `a` is a
depset, the result is a copy of `a` where:

*   if `b` is a depset, then `b` is appended to `a`'s list of children; and
    otherwise,

*   if `b` is an iterable, then `b`'s elements are appended to `a`'s list of
    direct elements.

In all cases, the original depset is left unmodified because depsets are
immutable. The returned value shares most of its internal structure with the old
depset. As with other immutable types, `s += t` is shorthand for `s = s + t`.

```python
s = depset(["a", "b", "c"])
t = s
s += depset(["d", "e"])

print(s)    # depset(["d", "e", "a", "b", "c"])
print(t)    # depset(["a", "b", "c"])
```

To retrieve the contents of a depset, use the
[to_list()](lib/depset.html#to_list) method. It returns a list of all transitive
elements, not including duplicates. There is no way to directly inspect the
precise structure of the DAG, although this structure does affect the order in
which the elements are returned.

```python
s = depset(["a", "b", "c"])

print("c" in s.to_list())              # True
print(s.to_list() == ["a", "b", "c"])  # True
```

The allowed items in a depset are restricted, just as the allowed keys in
dictionaries are restricted. In particular, depset contents may not be mutable.

Depsets use reference equality: a depset is equal to itself, but unequal to any
other depset, even if they have the same contents and same internal structure.

```python
s = depset(["a", "b", "c"])
t = s
print(s == t)  # True

t = depset(["a", "b", "c"])
print(s == t)  # False

t = s
# Trivial modification that adds no elements
t += []
print(s == t)  # False

d = {}
d[s] = None
d[t] = None
print(len(d))  # 2
```

To compare depsets by their contents, convert them to sorted lists.

```python
s = depset(["a", "b", "c"])
t = depset(["c", "b", "a"])
print(sorted(s.to_list()) == sorted(t.to_list()))  # True
```

There is no ability to remove elements from a depset. If this is needed, you
must read out the entire contents of the depset, filter the elements you want to
remove, and reconstruct a new depset. This is not particularly efficient.

```python
s = depset(["a", "b", "c"])
t = depset(["b", "c"])

# Compute set difference s - t. Precompute t.to_list() so it's not done
# in a loop, and convert it to a dictionary for fast membership tests.
t_items = {e: None for e in t.to_list()}
diff_items = [x for x in s.to_list() if x not in t_items]
# Convert back to depset if it's still going to be used for merge operations.
s = depset(diff_items)
print(s)  # depset(["a"])
```

## Order

The `to_list` operation performs a traversal over the DAG. The kind of traversal
depends on the *order* that was specified at the time the depset was
constructed. It is useful for Bazel to support multiple orders because sometimes
tools care about the order of their inputs. For example, a linker action may
need to ensure that if `B` depends on `A`, then `A.o` comes before `B.o` on the
linker's command line. Other tools might have the opposite requirement.

Three traversal orders are supported: `postorder`, `preorder`, and
`topological`. The first two work exactly like [tree
traversals](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search)
except that they operate on DAGs and skip already visited nodes. The third order
works as a topological sort from root to leaves, essentially the same as
preorder except that shared children are listed only after all of their parents.
Preorder and postorder operate as left-to-right traversals, but note that within
each node direct elements have no order relative to children. For topological
order, there is no left-to-right guarantee, and even the
all-parents-before-child guarantee does not apply in the case that there are
duplicate elements in different nodes of the DAG.

```python
# This demonstrates how the + operator interacts with traversal orders.

def create(order):
  # Create s with "a" and "b" as direct elements.
  s = depset(["a", "b"], order=order)
  # Add a new child with contents "c" and "d".
  s += depset(["c", "d"], order=order)
  # Append "e" and "f" as direct elements.
  s += ["e", "f"]
  # Add a new child with contents "g" and "h"
  s += depset(["g", "h"], order=order)
  # During postorder traversal, all contents of children are emitted first,
  # then the direct contents.
  return s

print(create("postorder").to_list())  # ["c", "d", "g", "h", "a", "b", "e", "f"]
print(create("preorder").to_list())   # ["a", "b", "e", "f", "c", "d", "g", "h"]
```

```python
# This demonstrates different orders on a diamond graph.

def create(order):
  a = depset(["a"], order=order)
  b = depset(["b"], order=order)
  b += a
  c = depset(["c"], order=order)
  c += a
  d = depset(["d"], order=order)
  d = d + b + c
  return d

print(create("postorder").to_list())    # ["a", "b", "c", "d"]
print(create("preorder").to_list())     # ["d", "b", "a", "c"]
print(create("topological").to_list())  # ["d", "b", "c", "a"]
```

Due to how traversals are implemented, the order must be specified at the time
the depset is created with the constructor's `order` keyword argument. If this
argument is omitted, the depset has the special `default` order, in which case
there are no guarantees about the order of any of its elements.

For safety, depsets with different orders cannot be merged with the `+` operator
unless one of them uses the default order; the resulting depset's order is the
same as the left operand. Note that when two depsets of different order are
merged in this way, the child may appear to have had its elements rearranged
when it is traversed via the parent.

## Performance

To see the motivation for using depsets, consider what would have happened if we
had implemented `get_transitive_srcs()` without them. A naive way of writing
this function would be to collect the sources in a list.

```python
def get_transitive_srcs(srcs, deps):
  trans_srcs = []
  for dep in deps:
    trans_srcs += dep[FooFiles].transitive_sources
  trans_srcs += srcs
  return trans_srcs
```

However, this does not take into account duplicates, so the source files for `a`
will appear twice on the command line and twice in the contents of the output
file.

The next alternative is using a general set, which can be simulated by a
dictionary where the keys are the elements and all the keys map to `None`.

```python
def get_transitive_srcs(srcs, deps):
  trans_srcs = {}
  for dep in deps:
    for file in dep[FooFiles].transitive_sources:
      trans_srcs[file] = None
  for file in srcs:
    trans_srcs[file] = None
  return trans_srcs
```

This gets rid of the duplicates, but it makes the order of the command line
arguments (and therefore the contents of the files) unspecified, although still
deterministic.

Moreover, both this approach and the list-based one are asymptotically worse
than the depset-based approach. Consider the case where there is a long chain of
dependencies on Foo libraries. Processing every rule requires copying all of the
transitive sources that came before it into a new data structure. This means
that the time and space cost for analyzing an individual library or binary
target is proportional to its own height in the chain. For a chain of length n,
foolib_1 ← foolib_2 ← … ← foolib_n, the overall cost is effectively the
[triangle sum](https://en.wikipedia.org/wiki/Triangular_number) 1 + 2 + … + n,
which is O(n^2). This cost is wasteful because the library rule's behavior is
not actually affected by the transitive sources.

Generally speaking, depsets should be used whenever you are accumulating more
and more information through your transitive dependencies. This helps ensure
that your build scales well as your target graph grows deeper. The exact
advantage will depend on how deep the target graph is and how many elements per
target are added.

To actually get the performance advantage, it's important to not retrieve the
contents of the depset unnecessarily in library rules. One call to `to_list()`
at the end in a binary rule is fine, since the overall cost is just O(n). It's
when many non-terminal targets try to call `to_list()` that we start to get into
quadratic behavior.

## Upcoming changes

The API for depsets is being updated to be more consistent. Here are some recent
and/or upcoming changes.

*   The name "set" has been replaced by "depset". Do not use the `set`
    constructor in new code; it is deprecated and will be removed. The traversal
    orders have undergone a similar renaming; their old names will be removed as
    well.

*   Depset contents should be retrieved using `to_list()`, not by iterating over
    the depset itself. Direct iteration over depsets is deprecated and will be
    removed. I.e., don't use `list(...)`, `sorted(...)`, or other functions
    expecting an iterable, on depsets.

*   Depset elements currently must have the same type, e.g. all ints or all
    strings. This restriction will be lifted.

*   The `|` operator is defined for depsets as a synonym for `+`. This will be
    going away; use `+` instead.

*   (Pending approval) The `+` operator will be deprecated in favor of a new
    syntax based on function calls. This avoids confusion regarding how `+`
    treats direct elements vs children.


text:
//    boost asinh.hpp header file

//  (C) Copyright Eric Ford & Hubert Holin 2001.
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

// See http://www.boost.org for updates, documentation, and revision history.

#ifndef BOOST_ASINH_HPP
#define BOOST_ASINH_HPP

#ifdef _MSC_VER
#pragma once
#endif

#include <cmath>
#include <boost/config.hpp>
#include <boost/math/tools/precision.hpp>
#include <boost/math/special_functions/math_fwd.hpp>

// This is the inverse of the hyperbolic sine function.

namespace boost
{
    namespace math
    {
       namespace detail{
#if defined(__GNUC__) && (__GNUC__ < 3)
        // gcc 2.x ignores function scope using declarations,
        // put them in the scope of the enclosing namespace instead:

        using    ::std::abs;
        using    ::std::sqrt;
        using    ::std::log;

        using    ::std::numeric_limits;
#endif

        template<typename T>
        inline T    asinh_imp(const T x)
        {
            using    ::std::abs;
            using    ::std::sqrt;
            using    ::std::log;

            T const            one = static_cast<T>(1);
            T const            two = static_cast<T>(2);

            static T const    taylor_2_bound = sqrt(tools::epsilon<T>());
            static T const    taylor_n_bound = sqrt(taylor_2_bound);
            static T const    upper_taylor_2_bound = one/taylor_2_bound;
            static T const    upper_taylor_n_bound = one/taylor_n_bound;

            if        (x >= +taylor_n_bound)
            {
                if        (x > upper_taylor_n_bound)
                {
                    if        (x > upper_taylor_2_bound)
                    {
                        // approximation by laurent series in 1/x at 0+ order from -1 to 0
                        return( log( x * two) );
                    }
                    else
                    {
                        // approximation by laurent series in 1/x at 0+ order from -1 to 1
                        return( log( x*two + (one/(x*two)) ) );
                    }
                }
                else
                {
                    return( log( x + sqrt(x*x+one) ) );
                }
            }
            else if    (x <= -taylor_n_bound)
            {
                return(-asinh(-x));
            }
            else
            {
                // approximation by taylor series in x at 0 up to order 2
                T    result = x;

                if    (abs(x) >= taylor_2_bound)
                {
                    T    x3 = x*x*x;

                    // approximation by taylor series in x at 0 up to order 4
                    result -= x3/static_cast<T>(6);
                }

                return(result);
            }
        }
       }

        template<typename T>
        inline typename tools::promote_args<T>::type asinh(const T x)
        {
           typedef typename tools::promote_args<T>::type result_type;
           return detail::asinh_imp(
              static_cast<result_type>(x));
        }
        template<typename T, typename Policy>
        inline typename tools::promote_args<T>::type asinh(const T x, const Policy&)
        {
           typedef typename tools::promote_args<T>::type result_type;
           return detail::asinh_imp(
              static_cast<result_type>(x));
        }

    }
}

#endif /* BOOST_ASINH_HPP */


text:
<md-card class="md-whiteframe-4dp">
	<md-card-header>
		<md-card-header-text>

		</md-card-header-text>

	</md-card-header>

	<md-card-content>

	</md-card-content>

	<md-card-actions layout="row" layout-align="center center" layout-wrap>
		<md-button class="md-primary" ng-click="$ctrl.select()">Edit</md-button>
		<md-button class="md-warn" ng-click="$ctrl.delete()">Delete</md-button>
	</md-card-actions>
</md-card>


text:
require 'image_size'

module ImageInfo
  class Parser

    attr_reader :image, :data

    def initialize(image, data)
      @image = image
      @data = data
    end

    def call
      set_image_size
      set_image_type
    end

    private

    def set_image_size
      image.width  = parser.width
      image.height = parser.height
    end

    def set_image_type
      image.type = parser.format
    end

    private

    def parser
      @parser ||= ::ImageSize.new(data)
    rescue ImageSize::FormatError
      @parser ||= ::ImageInfo::NullParser.new
    end
  end
end


text:
Irreducible angular momentum and spin eigenspaces on atomic subshells
=====================================================================

Mathematica implementation of the algorithm described in the paper **Efficient algorithm for many-electron angular momentum and spin diagonalization on atomic subshells**, see Ref. 1 below.

The main code resides in the Mathematica package `irredLSbase.m`, and the computations are performed in the notebook `irredLS.nb`. This notebook requires the **FermiFab** toolbox (see Ref. 2) and stores the results in `irredLS.m`.

The files `fermi2latex.m` and `irredLSlatex.nb` generate the Latex tables of the eigenspaces in the *tables* subfolder.

License
-------
Copyright (c) 2009-2014, Christian B. Mendl
All rights reserved.
http://christian.mendl.net

This program is free software; you can redistribute it and/or
modify it under the terms of the Simplified BSD License
http://www.opensource.org/licenses/bsd-license.php

References
----------
1. Christian B. Mendl
   Efficient algorithm for many-electron angular momentum and spin diagonalization on atomic subshells
   preprint [arXiv:1409.6860](http://arxiv.org/abs/1409.6860) (2014)
2. Christian B. Mendl
   The FermiFab toolbox for fermionic many-particle quantum systems
   Comput. Phys. Commun. 182, 1327-1337 (2011), [arXiv:1103.0872](http://arxiv.org/abs/1103.0872)
   URL http://sourceforge.net/projects/fermifab


text:
using System;
using Nop.Core.Domain.Orders;

namespace Nop.Core.Domain.Customers
{
    /// <summary>
    /// Represents a reward point history entry
    /// </summary>
    public partial class RewardPointsHistory : BaseEntity
    {
        /// <summary>
        /// Gets or sets the customer identifier
        /// </summary>
        public int CustomerId { get; set; }

        /// <summary>
        /// Gets or sets the store identifier in which these reward points were awarded or redeemed
        /// </summary>
        public int StoreId { get; set; }

        /// <summary>
        /// Gets or sets the points redeemed/added
        /// </summary>
        public int Points { get; set; }

        /// <summary>
        /// Gets or sets the points balance
        /// </summary>
        public int? PointsBalance { get; set; }

        /// <summary>
        /// Gets or sets the used amount
        /// </summary>
        public decimal UsedAmount { get; set; }

        /// <summary>
        /// Gets or sets the message
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Gets or sets the date and time of instance creation
        /// </summary>
        public DateTime CreatedOnUtc { get; set; }

        /// <summary>
        /// Gets or sets the order for which points were redeemed as a payment (spent by a customer when placing this order)
        /// </summary>
        public virtual Order UsedWithOrder { get; set; }

        /// <summary>
        /// Gets or sets the customer
        /// </summary>
        public virtual Customer Customer { get; set; }
    }
}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#include "module2_constants.h"

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

module2Constants::module2Constants() {
}

#pragma GCC diagnostic pop


text:
define(['exports'], function (exports) {
  'use strict';

  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  var constants = exports.constants = {
    eventPrefix: 'k-on-',
    bindablePrefix: 'k-',
    attributePrefix: 'ak-',
    elementPrefix: 'ak-'
  };
});


text:
##
## Classe permettant de créer un contrôleur pour la vue FenetreMenu
##
class MenuControleur < Controller

	##
    ## Initialize
    ##
	def initialize
		#charge le modele utilisateur
		loadModel("Utilisateur")
		loadModel("Jeu")

		#paramètres fenêtre
		@title = "Sudoku - Menu"
		@width = 600
		@height = 550
		@resizable = false
		@position= "CENTER_ALWAYS"
	end

	##
	## Charge la dernière partie utilisateur
	##
	## @return     self
	##
	def charger
		Core::changeTo("JeuLibre", :pseudo => @content["pseudo"], :charger => true)
	end

	##
	## Permet de connaître si une partie sauvegardée existe portant le nom du pseudo
	##
	## @param 	pseudo		Le pseudo de l'utilisateur
	##
	## @return 	boolean
	##
	def partieExiste(pseudo)
		return @Utilisateur.partieUtilisateur?(pseudo)
	end

	##
    ## Méthode à définir dans tous les cas !
    ##
    ## @return 	self
    ##
	def run
		return self
	end
end


text:
require 'filter/strip_html_filter'
require 'time'

class FlowdockEvent
  class UnsupportedMessageError < StandardError; end
  class InvalidMessageError < StandardError; end

  include CommandViews

  attr_accessor :irc_connection, :channel, :user, :message
  @@registered_events = {}

  def initialize(irc_connection, target, user, message)
    @irc_connection = irc_connection
    @target = target
    @user = user
    @message = message
  end

  def self.register_event(command)
    @@registered_events[command.to_s] = self
  end

  def self.from_message(irc_connection, message)
    event_type = @@registered_events[message['event']]
    raise UnsupportedMessageError, "Event '#{message['event']}' is not supported" if event_type.nil?

    if message['flow']
      target = irc_connection.find_channel_by_id(message['flow'])
      return if target && !target.open?
    elsif message['to']
      target = irc_connection.find_user_by_id(message['to'])
    end

    user = irc_connection.find_user_by_id(message['user'] || message['user_id'])

    processed_message = MessageProcessor.new(message).perform
    event_type.new(irc_connection, target, user, processed_message)
  end

  def process
    text = self.render
    @irc_connection.send_reply(text)
  end

  def valid?
    raise NotImplementedError.new("You need to override valid?")
  end

  protected

  def channel?
    @target.is_a?(IrcChannel)
  end

  def user?
    @target.is_a?(User)
  end

  def team_inbox_event(integration, *description)
    description.collect do |str|
      "[#{integration}] #{str}"
    end.join("\n")
  end

  def thread_event(author, thread, *description)
    description.map do |str|
      "#{thread_header(thread)} #{author}: #{str}"
    end.join("\n")
  end

  def thread_header(thread)
    thread_title = thread["title"]
    if thread["source"]
      source = thread["source"]["name"]
      app = thread["source"]["application"]["name"]

      "[#{app} (#{source}): #{thread_title}]"
    else
      "[#{thread_title}]"
    end
  end

  def first_line(text)
    text.split(/(\\n|\\r|\n|\r)/)[0] # read text until the first (escaped) new line or carriage return
  end

  def strip_html(input)
    Filter::StripHTMLFilter.new(input).call
  end
end

# Load all events automatically
Dir[File.join(File.dirname(__FILE__), 'events', '*_event.rb')].each do |file|
  require file
end


text:
package org.allenai.common.cache

import java.io.File
import org.allenai.common.{ GitVersion, Version, cache }
import org.allenai.common.testkit.UnitSpec
import org.scalatest.BeforeAndAfterAll
import spray.json.DefaultJsonProtocol._
import sys.process._

case class Foo(stringVar: String, intVar: Int)

object FooJsonProtocol extends DefaultJsonProtocol {
  implicit val fooFormat = jsonFormat2(Foo)
}

class QueryCaches(redisHostname: String, redisPort: Int) {
  import FooJsonProtocol.__

  val stringQueryCache = new JsonQueryCache[String](redisHostname, redisPort, "test")
  val intQueryCache = new JsonQueryCache[Int](redisHostname, redisPort, "test")
  val seqStringQueryCache = new JsonQueryCache[Seq[String]](redisHostname, redisPort, "test")

  // It's an object I can test
  val fooQueryCache = new JsonQueryCache[Foo](redisHostname, redisPort, "test")

  val stringKey = "stringKey"
  val stringValue = "stringValue"

  val intKey = "intKey"
  val intValue = 32

  val seqStringKey = "seqStringKey"
  val seqStringValue = Seq("a string", "a second string", "third time's the charm")

  val fooKey = "fooKey"
  val fooValue = new Foo("stringerino", 42)

  def getAll(): Seq[Option[Any]] = Seq(
    stringQueryCache.get(stringKey),
    intQueryCache.get(intKey),
    seqStringQueryCache.get(seqStringKey),
    fooQueryCache.get(fooKey)
  )

  def putAll(): Unit = {
    stringQueryCache.put(stringKey, stringValue)
    intQueryCache.put(intKey, intValue)
    seqStringQueryCache.put(seqStringKey, seqStringValue)
    fooQueryCache.put(fooKey, fooValue)
  }

  def delAll(): Unit = {
    stringQueryCache.del(stringKey)
    intQueryCache.del(intKey)
    seqStringQueryCache.del(seqStringKey)
    fooQueryCache.del(fooKey)
  }

  def allThereAndEq(): Boolean = {
    stringQueryCache.get(stringKey).exists(_.equals(stringValue)) &&
      intQueryCache.get(intKey).exists(_.equals(intValue)) &&
      seqStringQueryCache.get(seqStringKey).exists(_.equals(seqStringValue)) &&
      fooQueryCache.get(fooKey).exists(_.equals(fooValue))
  }
}

class QueryCacheSpec extends UnitSpec with BeforeAndAfterAll {

  val redisHostname = "127.0.0.1"
  val redisPort = 6379
  val redisServer = "redis-server".run()
  val queryCaches = new QueryCaches(redisHostname, redisPort)

  "QueryCache" should "return None when items are not in cache" in {
    assert(queryCaches.getAll().forall(_.isEmpty))
  }

  it should "put the items in properly and let us get them back" in {
    queryCaches.putAll()
    assert(queryCaches.allThereAndEq())
  }

  it should "delete the items properly" in {
    queryCaches.delAll()
    assert(queryCaches.getAll().forall(_.isEmpty))
  }

  override def afterAll() {
    Seq("redis-cli", "FLUSHALL").!!
    Seq("redis-cli", "SHUTDOWN").!!
    // delete redis dump file if it exists
    val f = new File("./dump.rdb")
    if (f.exists) {
      f.delete()
    }
  }
}


text:
'use strict';

var RNC = require('react-native-css');
var path = require('path');

module.exports = function(grunt) {

  grunt.registerMultiTask('react_native_css', 'A wrapper for react-native-css', function() {
    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      pretty: false,
      literal: false,
    });

    var files = this.files.slice();

    function process() {
      if(files.length <= 0) {
        done();
        return;
      }

      var f = files.pop();

      if (f.src.length > 1) {
        grunt.warn(
          'Due to limitation in react-native-css, output files are limited to one source file at a time.' +
          ' Make multiple output files with one source file each.'
        );
      }

      // Check destination exists
      if (!grunt.file.exists(path.dirname(f.dest))) {
        grunt.file.mkdir(path.dirname(f.dest));
      }

      var rncss = new RNC();
      rncss.parse(f.src[0], f.dest, options.pretty, options.literal, function () {
        grunt.log.writeln('File "' + f.dest + '" created');
        process();
      });
    }

    process();

  });
};


text:
package com.mauriciotogneri.infiltration.utils;

public class Resources
{
	public static class Images
	{
		private static final String ROOT_IMAGES = "images/";

		public static class Protagonist
		{
			private static final String ROOT_PROTAGONIST = Images.ROOT_IMAGES + "protagonist/";

			public static final String CHARACTER_IDLE = Protagonist.ROOT_PROTAGONIST + "idle.png";
			public static final String CHARACTER_JUMPING = Protagonist.ROOT_PROTAGONIST + "jumping.png";
			public static final String CHARACTER_FALLING = Protagonist.ROOT_PROTAGONIST + "falling.png";
			public static final String CHARACTER_RUNNING_1 = Protagonist.ROOT_PROTAGONIST + "running_1.png";
			public static final String CHARACTER_RUNNING_2 = Protagonist.ROOT_PROTAGONIST + "running_2.png";
			public static final String CHARACTER_RUNNING_3 = Protagonist.ROOT_PROTAGONIST + "running_3.png";
			public static final String CHARACTER_RUNNING_4 = Protagonist.ROOT_PROTAGONIST + "running_4.png";
			public static final String CHARACTER_RUNNING_5 = Protagonist.ROOT_PROTAGONIST + "running_5.png";
			public static final String CHARACTER_RUNNING_6 = Protagonist.ROOT_PROTAGONIST + "running_6.png";
		}

		public static class Enemies
		{
			private static final String ROOT_ENEMIES = Images.ROOT_IMAGES + "enemies/";

			public static class Laser
			{
				private static final String ROOT_LASER = Enemies.ROOT_ENEMIES + "laser/";

				public static final String BASE = Laser.ROOT_LASER + "laser_base.png";
				public static final String BEAM = Laser.ROOT_LASER + "laser_beam.png";
			}

			public static class Turret
			{
				private static final String ROOT_TURRET = Enemies.ROOT_ENEMIES + "turret/";

				public static final String BASE = Turret.ROOT_TURRET + "turret_base.png";
				public static final String BEAM = Turret.ROOT_TURRET + "turret_beam.png";
			}
		}

		public static class Levels
		{
			private static final String ROOT_LEVELS = Images.ROOT_IMAGES + "levels/";

			public static class Buildings
			{
				private static final String ROOT_BUILDINGS = Levels.ROOT_LEVELS + "buildings/";

				public static final String BUILDING_1 = Buildings.ROOT_BUILDINGS + "building_1.png";
			}

			public static class Door
			{
				private static final String ROOT_DOOR = Levels.ROOT_LEVELS + "door/";

				public static final String DOOR_CLOSED = Door.ROOT_DOOR + "door_closed.png";
				public static final String DOOR_OPENING_1 = Door.ROOT_DOOR + "door_opening_1.png";
				public static final String DOOR_OPENING_2 = Door.ROOT_DOOR + "door_opening_2.png";
				public static final String DOOR_OPENING_3 = Door.ROOT_DOOR + "door_opening_3.png";
			}

			public static class Switch
			{
				private static final String ROOT_SWITCH = Levels.ROOT_LEVELS + "switch/";

				public static final String SWITCH_ON = Switch.ROOT_SWITCH + "switch_on.png";
				public static final String SWITCH_OFF = Switch.ROOT_SWITCH + "switch_off.png";
			}
		}

		public static class Controls
		{
			private static final String ROOT_CONTROLS = Images.ROOT_IMAGES + "controls/";

			public static final String ARROW = Controls.ROOT_CONTROLS + "arrow.png";
		}
	}

	public static class Levels
	{
		private static final String ROOT_LEVELS = "levels/";

		public static final String LEVEL_1 = Levels.ROOT_LEVELS + "level_1.txt";
	}

	public static class Audio
	{
		private static final String ROOT_AUDIO = "audio/";

		public static class Music
		{
			private static final String ROOT_MUSIC = Audio.ROOT_AUDIO + "music/";

			public static final String MUSIC = Music.ROOT_MUSIC + "music.ogg";
		}

		public static class Sound
		{
			private static final String ROOT_SOUND = Audio.ROOT_AUDIO + "sounds/";

			public static class Protagonist
			{
				private static final String ROOT_PROTAGONIST = Sound.ROOT_SOUND + "protagonist/";

				public static final String JUMP = Protagonist.ROOT_PROTAGONIST + "jump.ogg";
			}

			public static class Enemies
			{
				private static final String ROOT_ENEMIES = Sound.ROOT_SOUND + "enemies/";

				public static final String TURRET_BEAM = Enemies.ROOT_ENEMIES + "turret_beam.ogg";
				public static final String LASER_BEAM = Enemies.ROOT_ENEMIES + "laser_beam.mp3";
			}

			public static class Levels
			{
				private static final String ROOT_LEVELS = Sound.ROOT_SOUND + "levels/";

				public static final String DOOR_OPENING = Levels.ROOT_LEVELS + "door_opening.ogg";
				public static final String SWITCH_ON = Levels.ROOT_LEVELS + "switch_on.mp3";
			}
		}
	}
}


text:
angular.module('ItemCtrl', ['ItemService']).controller('ItemController', ['$scope', '$rootScope', '$location', '$routeParams', 'Item', function($scope, $rootScope, $location, $routeParams, Item) {
  $scope.text = 'Click any item to edit it';
  $scope.items = [];
  $scope.item = {};
  // Edit item view
  if ($routeParams.item_id != undefined) {
    Item.get($routeParams.item_id).then(function(resp) {
      $scope.item = resp.data;
    });
  }
  // Get all items
  Item.all().then(function(resp) {
    $scope.items = resp.data;
  });
  // Add new item to database
  $scope.createNewItem = function() {

    Item.create(this.item).then(function() {
      $scope.item = {};
      $location.path('/items');
    });
  };

  $scope.removeItem = function(item_id) {
    Item.delete(item_id).then(function() {
      $scope.item = {};
      $location.path('/items');
    });
  };

  $scope.editItem = function(item_id) {

    Item.update(item_id, $scope.item).then(function() {
      $scope.item = {};
      $location.path('/items');
    });
  };

}]);


text:
{% capture imagePath %}{{ page.date | date: "%Y-%m-%d" }}-{{ page.title | slugify }}/{{ include.name }}{% endcapture %}
{% if include.frame == false %}
  {% assign frame = false %}
{% else %}
  {% assign frame = true %}
{% endif %}

    {% if include.caption %}

{{ include.caption }}

    {% endif %}


text:
__all__ = ('Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty')

import collections
import heapq
import warnings

from . import events
from . import locks

class QueueEmpty(Exception):
    """Raised when Queue.get_nowait() is called on an empty Queue."""
    pass

class QueueFull(Exception):
    """Raised when the Queue.put_nowait() method is called on a full Queue."""
    pass

class Queue:
    """A queue, useful for coordinating producer and consumer coroutines.

    If maxsize is less than or equal to zero, the queue size is infinite. If it
    is an integer greater than 0, then "await put()" will block when the
    queue reaches maxsize, until an item is removed by get().

    Unlike the standard library Queue, you can reliably know this Queue's size
    with qsize(), since your single-threaded asyncio application won't be
    interrupted between calling qsize() and doing an operation on the Queue.
    """

    def __init__(self, maxsize=0, *, loop=None):
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
            warnings.warn("The loop argument is deprecated since Python 3.8, "
                          "and scheduled for removal in Python 3.10.",
                          DeprecationWarning, stacklevel=2)
        self._maxsize = maxsize

        # Futures.
        self._getters = collections.deque()
        # Futures.
        self._putters = collections.deque()
        self._unfinished_tasks = 0
        self._finished = locks.Event(loop=loop)
        self._finished.set()
        self._init(maxsize)

    # These three are overridable in subclasses.

    def _init(self, maxsize):
        self._queue = collections.deque()

    def _get(self):
        return self._queue.popleft()

    def _put(self, item):
        self._queue.append(item)

    # End of the overridable methods.

    def _wakeup_next(self, waiters):
        # Wake up the next waiter (if any) that isn't cancelled.
        while waiters:
            waiter = waiters.popleft()
            if not waiter.done():
                waiter.set_result(None)
                break

    def __repr__(self):
        return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'

    def __str__(self):
        return f'<{type(self).__name__} {self._format()}>'

    def _format(self):
        result = f'maxsize={self._maxsize!r}'
        if getattr(self, '_queue', None):
            result += f' _queue={list(self._queue)!r}'
        if self._getters:
            result += f' _getters[{len(self._getters)}]'
        if self._putters:
            result += f' _putters[{len(self._putters)}]'
        if self._unfinished_tasks:
            result += f' tasks={self._unfinished_tasks}'
        return result

    def qsize(self):
        """Number of items in the queue."""
        return len(self._queue)

    @property
    def maxsize(self):
        """Number of items allowed in the queue."""
        return self._maxsize

    def empty(self):
        """Return True if the queue is empty, False otherwise."""
        return not self._queue

    def full(self):
        """Return True if there are maxsize items in the queue.

        Note: if the Queue was initialized with maxsize=0 (the default),
        then full() is never True.
        """
        if self._maxsize <= 0:
            return False
        else:
            return self.qsize() >= self._maxsize

    async def put(self, item):
        """Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.
        """
        while self.full():
            putter = self._loop.create_future()
            self._putters.append(putter)
            try:
                await putter
            except:
                putter.cancel()  # Just in case putter is not done yet.
                try:
                    # Clean self._putters from canceled putters.
                    self._putters.remove(putter)
                except ValueError:
                    # The putter could be removed from self._putters by a
                    # previous get_nowait call.
                    pass
                if not self.full() and not putter.cancelled():
                    # We were woken up by get_nowait(), but can't take
                    # the call.  Wake up the next in line.
                    self._wakeup_next(self._putters)
                raise
        return self.put_nowait(item)

    def put_nowait(self, item):
        """Put an item into the queue without blocking.

        If no free slot is immediately available, raise QueueFull.
        """
        if self.full():
            raise QueueFull
        self._put(item)
        self._unfinished_tasks += 1
        self._finished.clear()
        self._wakeup_next(self._getters)

    async def get(self):
        """Remove and return an item from the queue.

        If queue is empty, wait until an item is available.
        """
        while self.empty():
            getter = self._loop.create_future()
            self._getters.append(getter)
            try:
                await getter
            except:
                getter.cancel()  # Just in case getter is not done yet.
                try:
                    # Clean self._getters from canceled getters.
                    self._getters.remove(getter)
                except ValueError:
                    # The getter could be removed from self._getters by a
                    # previous put_nowait call.
                    pass
                if not self.empty() and not getter.cancelled():
                    # We were woken up by put_nowait(), but can't take
                    # the call.  Wake up the next in line.
                    self._wakeup_next(self._getters)
                raise
        return self.get_nowait()

    def get_nowait(self):
        """Remove and return an item from the queue.

        Return an item if one is immediately available, else raise QueueEmpty.
        """
        if self.empty():
            raise QueueEmpty
        item = self._get()
        self._wakeup_next(self._putters)
        return item

    def task_done(self):
        """Indicate that a formerly enqueued task is complete.

        Used by queue consumers. For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items have
        been processed (meaning that a task_done() call was received for every
        item that had been put() into the queue).

        Raises ValueError if called more times than there were items placed in
        the queue.
        """
        if self._unfinished_tasks <= 0:
            raise ValueError('task_done() called too many times')
        self._unfinished_tasks -= 1
        if self._unfinished_tasks == 0:
            self._finished.set()

    async def join(self):
        """Block until all items in the queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer calls task_done() to
        indicate that the item was retrieved and all work on it is complete.
        When the count of unfinished tasks drops to zero, join() unblocks.
        """
        if self._unfinished_tasks > 0:
            await self._finished.wait()

class PriorityQueue(Queue):
    """A subclass of Queue; retrieves entries in priority order (lowest first).

    Entries are typically tuples of the form: (priority number, data).
    """

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item, heappush=heapq.heappush):
        heappush(self._queue, item)

    def _get(self, heappop=heapq.heappop):
        return heappop(self._queue)

class LifoQueue(Queue):
    """A subclass of Queue that retrieves most recently added entries first."""

    def _init(self, maxsize):
        self._queue = []

    def _put(self, item):
        self._queue.append(item)

    def _get(self):
        return self._queue.pop()


text:
'use strict';

var app = require('connect')();
var http = require('http');
var swaggerTools = require('swagger-tools');

var serverPort = 3000;

// swaggerRouter configuration
var options = {
  controllers: './controllers',
  useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
};

// The Swagger Resource Listing Document (require it, build it programmatically, fetch it from a URL, ...)
var apiDocJson = require('./api/api-doc.json');
// The Swagger API Declaration Documents (require them, build them programmatically, fetch them from a URL, ...)
var apiDeclarations = [
  require('./api/weather.json')
];

// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(apiDocJson, apiDeclarations, function (middleware) {
  // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
  app.use(middleware.swaggerMetadata());

  // Validate Swagger requests
  app.use(middleware.swaggerValidator());

  // Route validated requests to appropriate controller
  app.use(middleware.swaggerRouter(options));

  // Serve the Swagger documents and Swagger UI
  app.use(middleware.swaggerUi({
    '/weather': apiDeclarations[0]
  }));

  // Start the server
  http.createServer(app).listen(serverPort, function () {
    console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
  });
});


text:
"""Setup configuration for the python grr modules."""

# pylint: disable=unused-variable
# pylint: disable=g-multiple-import
# pylint: disable=g-import-not-at-top
import ConfigParser
import os
import subprocess

from setuptools import find_packages, setup, Extension
from setuptools.command.develop import develop
from setuptools.command.install import install
from setuptools.command.sdist import sdist

IGNORE_GUI_DIRS = ["node_modules", "bower_components", "tmp"]

def find_data_files(source, ignore_dirs=None):
  ignore_dirs = ignore_dirs or []
  result = []
  for directory, dirnames, files in os.walk(source):
    dirnames[:] = [d for d in dirnames if d not in ignore_dirs]

    files = [os.path.join(directory, x) for x in files]
    result.append((directory, files))

  return result

def run_make_files(make_docs=False,
                   make_ui_files=True,
                   force_compile_protos=False,
                   sync_artifacts=True):
  """Builds necessary assets from sources."""

  if force_compile_protos:
    # Clean and recompile the protobufs.
    subprocess.check_call(["python", "makefile.py", "--clean"])
  else:
    subprocess.check_call(["python", "makefile.py"])

  if sync_artifacts:
    # Sync the artifact repo with upstream for distribution.
    subprocess.check_call(["python", "makefile.py"], cwd="grr/artifacts")

  if make_docs:
    # Download the docs so they are available offline.
    subprocess.check_call(["python", "makefile.py"], cwd="docs")

  if make_ui_files:
    subprocess.check_call(["npm", "install"], cwd="grr/gui/static")
    subprocess.check_call(
        ["npm", "install", "-g", "bower", "gulp"], cwd="grr/gui/static")
    subprocess.check_call(["bower", "update"], cwd="grr/gui/static")
    subprocess.check_call(["gulp", "compile"], cwd="grr/gui/static")

def get_version():
  config = ConfigParser.SafeConfigParser()
  config.read(
      os.path.join(os.path.dirname(os.path.realpath(__file__)), "version.ini"))
  return config.get("Version", "packageversion")

class Develop(develop):

  def run(self):
    run_make_files()
    develop.run(self)

class Sdist(sdist):
  """Build sdist."""

  user_options = sdist.user_options + [
      ("no-make-docs", None, "Don't build ascii docs when building the sdist."),
      ("no-make-ui-files", None, "Don't build UI JS/CSS bundles (AdminUI "
       "won't work without them)."),
      ("no-compile-protos", None, "Don't clean protos, use existing _pb2's."),
      ("no-sync-artifacts", None,
       "Don't sync the artifact repo. This is unnecessary for "
       "clients and old client build OSes can't make the SSL connection."),
  ]

  def initialize_options(self):
    self.no_make_docs = None
    self.no_sync_artifacts = None
    self.no_make_ui_files = None
    self.no_compile_protos = None
    sdist.initialize_options(self)

  def run(self):
    run_make_files(
        make_docs=not self.no_make_docs,
        make_ui_files=not self.no_make_ui_files,
        force_compile_protos=not self.no_compile_protos,
        sync_artifacts=not self.no_sync_artifacts)
    sdist.run(self)

class Install(install):
  """Allow some installation options."""
  DEFAULT_TEMPLATE = """
# Autogenerated file. Do not edit. Written by setup.py.
CONFIG_FILE = "%(CONFIG_FILE)s"
"""

  user_options = install.user_options + [
      ("config-file=", None,
       "Specify the default location of the GRR config file."),
  ]

  def initialize_options(self):
    self.config_file = None
    install.initialize_options(self)

  def finalize_options(self):
    if (self.config_file is not None and
        not os.access(self.config_file, os.R_OK)):
      raise RuntimeError("Default config file %s is not readable." %
                         self.config_file)

    install.finalize_options(self)

  def run(self):
    # Update the defaults if needed.
    if self.config_file:
      with open("grr/defaults.py", "wb") as fd:
        fd.write(self.DEFAULT_TEMPLATE % dict(CONFIG_FILE=self.config_file))

    install.run(self)

data_files = (
    find_data_files("docs") + find_data_files("executables") +
    find_data_files("install_data") + find_data_files("scripts") +
    find_data_files("grr/artifacts") + find_data_files("grr/checks") +
    find_data_files("grr/gui/static", ignore_dirs=IGNORE_GUI_DIRS) +
    find_data_files("grr/gui/local/static",
                    ignore_dirs=IGNORE_GUI_DIRS) + ["version.ini"])

if "VIRTUAL_ENV" not in os.environ:
  print "*****************************************************"
  print "  WARNING: You are not installing in a virtual"
  print "  environment. This configuration is not supported!!!"
  print "  Expect breakage."
  print "*****************************************************"

setup_args = dict(
    name="grr-response-core",
    version=get_version(),
    description="GRR Rapid Response",
    license="Apache License, Version 2.0",
    url="https://github.com/google/grr",
    packages=find_packages(),
    zip_safe=False,
    include_package_data=True,
    ext_modules=[Extension(
        "grr._semantic",
        ["accelerated/accelerated.c"],)],
    cmdclass={
        "develop": Develop,
        "install": Install,
        "sdist": Sdist,
    },
    install_requires=[
        "cryptography==1.5.2",
        "PyYAML==3.11",
        "binplist==0.1.4",
        "ipaddr==2.1.11",
        "ipython==5.0.0",
        "pip>=8.1.1",
        "psutil==4.3.0",
        "pyaml==15.8.2",
        "pycrypto==2.6.1",
        "python-dateutil==2.5.3",
        "pytsk3==20160721",
        "pytz==2016.4",
        "requests==2.9.1",
        "protobuf==3.2.0",
        "Werkzeug==0.11.3",
        "wheel==0.29",
        "virtualenv==15.0.3",
    ],
    extras_require={
        # The following requirements are needed in Windows.
        ':sys_platform=="win32"': [
            "WMI==1.4.9",
            "pypiwin32==219",
        ],
    },

    # Data files used by GRR. Access these via the config_lib "resource" filter.
    data_files=data_files)

setup(**setup_args)


text:
<?php namespace Maatwebsite\Usher\Contracts\Shared\Embeddables;

use Carbon\Carbon;

interface Date
{

    /**
     * @param string $format
     * @return null|string
     */
    public function format($format = 'd-m-Y H:i:s');

    /**
     * @return Carbon
     */
    public function getDate();

    /**
     * @param Carbon $date
     */
    public function setDate(Carbon $date);

    /**
     * Check if date is in past
     * @return mixed
     */
    public function inPast();
}


text:
<title>
Central America's poor will suffer
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Bush signs CAFTA into law

Central America's poor will suffer

By Elizabeth Schulte | August 5, 2005 | Page 2

AFTER PASSING the House of Representatives in a narrow 217-215 vote July 28, the Central America Free Trade Agreement (CAFTA) has gone to Bush for his signature.

CAFTA will extend the Clinton administration's 1994 North American Trade Agreement to Costa Rica, El Salvador, Guatemala, Honduras, Nicaragua and the Dominican Republic.

The bill squeaked through the House with the help of 15 Democrats who defected from their party's stated opposition to CAFTA, overcoming the 27 Republicans who voted against the bill.

George W. Bush made last-minute appeals to House members, arguing that the trade deal was about national security and encouraging fledgling democracies. "We must not neglect the antidemocracy, anti-American forces that are at work in Latin America," chimed in Rep. David Dreier (R-Calif.).

Afterward, a New York Times editorial cheered Democrats who crossed the aisle to vote for the deal. "Anyone who believes, as this page does, that the benefits of free trade outweigh those of protectionism should give a pat on the back to the Democrats who chose principle over politics and defied their party's leaders to vote for the trade pact," the Times wrote.

Unions lobbied for a "no" vote on CAFTA. The sugar industry, for its part, also lobbied against it, challenging provisions that would cut subsidies to domestic growers.

Largely, though, business interests--and their mouthpieces in the Bush administration--supported CAFTA because it strengthens the U.S.'s hand economically, and gives momentum to the broader Free Trade Area of the Americas (FTAA) initiative.

In addition to eliminating barriers to trade in U.S. goods and investment, CAFTA also gives U.S. corporations the right to enforce patents and copyrights on CAFTA member countries. This means the pharmaceutical industry will have free rein to make super-profits because of protections against cheaper generic drugs--and the poor in Central America will pay the price.

U.S. agribusiness is expected to make a killing when CAFTA goes into effect, as Central America is opened to U.S. imports.

In the last hours before its passage, the Bush administration negotiated last-minute deals will lawmakers to secure their yes votes. For instance, Rep. Robert Aderholt (R-Ala.) told the Los Angeles Times that he was promised that if he voted "yes," the sock industry in his district would be protected, and he was presented with a letter signed by Commerce Secretary Carlos Gutierrez and U.S. Trade Representative Rob Portman to prove it.

But opposition to CAFTA isn't so easily bought off in Central America, where the impending trade deal has sparked big protests, delaying ratification in Costa Rica, Nicaragua, the Dominican Republic and other countries.

We have to build solidarity with our brothers and sisters in Central America--and show Washington that we won't sit down while their trade deals rob the world's poor.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
import TutorialModal from './TutorialModal'

export default TutorialModal