text:
//-----------------------------------------------------------------------
// <copyright file="Helios.Concurrency.DedicatedThreadPool.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace Helios.Concurrency
{
    ///
    /// The type of threads to use - either foreground or background threads.
    ///
    internal enum ThreadType
    {
        Foreground,
        Background
    }

    ///
    /// Provides settings for a dedicated thread pool
    ///
    internal class DedicatedThreadPoolSettings
    {
        ///
        /// Background threads are the default thread type
        ///
        public const ThreadType DefaultThreadType = ThreadType.Background;

        public DedicatedThreadPoolSettings(int numThreads,
                                           string name = null,
                                           TimeSpan? deadlockTimeout = null,
                                           ApartmentState apartmentState = ApartmentState.Unknown,
                                           Action<Exception> exceptionHandler = null,
                                           int threadMaxStackSize = 0)
            : this(numThreads, DefaultThreadType, name, deadlockTimeout, apartmentState, exceptionHandler, threadMaxStackSize)
        { }

        ///
        /// Initializes a new instance of the <see cref="DedicatedThreadPoolSettings"/> class.
        ///
        /// <exception cref="ArgumentOutOfRangeException">
        /// This exception is thrown if the given <paramref name="deadlockTimeout"/> is set to less than 1ms.
        /// It can also be thrown if the given <paramref name="numThreads"/> is set to less than one.
        /// </exception>
        public DedicatedThreadPoolSettings(int numThreads,
                                           ThreadType threadType,
                                           string name = null,
                                           TimeSpan? deadlockTimeout = null,
                                           ApartmentState apartmentState = ApartmentState.Unknown,
                                           Action<Exception> exceptionHandler = null,
                                           int threadMaxStackSize = 0)
        {
            Name = name ?? ("DedicatedThreadPool-" + Guid.NewGuid());
            ThreadType = threadType;
            NumThreads = numThreads;
            DeadlockTimeout = deadlockTimeout;
            ApartmentState = apartmentState;
            ExceptionHandler = exceptionHandler ?? (ex => { });
            ThreadMaxStackSize = threadMaxStackSize;

            if (deadlockTimeout.HasValue && deadlockTimeout.Value.TotalMilliseconds <= 0)
                throw new ArgumentOutOfRangeException(nameof(deadlockTimeout), $"deadlockTimeout must be null or at least 1ms. Was {deadlockTimeout}.");
            if (numThreads <= 0)
                throw new ArgumentOutOfRangeException(nameof(numThreads), $"numThreads must be at least 1. Was {numThreads}");
        }

        ///
        /// The total number of threads to run in this thread pool.
        ///
        public int NumThreads { get; private set; }

        ///
        /// The type of threads to run in this thread pool.
        ///
        public ThreadType ThreadType { get; private set; }

        ///
        /// Apartment state for threads to run in this thread pool
        ///
        public ApartmentState ApartmentState { get; private set; }

        ///
        /// Interval to check for thread deadlocks.
        ///
        /// If a thread takes longer than <see cref="DeadlockTimeout"/> it will be aborted
        /// and replaced.
        ///
        public TimeSpan? DeadlockTimeout { get; private set; }

        public string Name { get; private set; }

        public Action<Exception> ExceptionHandler { get; private set; }

        ///
        /// Gets the thread stack size, 0 represents the default stack size.
        ///
        public int ThreadMaxStackSize { get; private set; }
    }

    ///
    /// TaskScheduler for working with a <see cref="DedicatedThreadPool"/> instance
    ///
    internal class DedicatedThreadPoolTaskScheduler : TaskScheduler
    {
        // Indicates whether the current thread is processing work items.
        [ThreadStatic]
        private static bool _currentThreadIsRunningTasks;

        ///
        /// Number of tasks currently running
        ///
        private volatile int _parallelWorkers = 0;

        private readonly LinkedList<Task> _tasks = new LinkedList<Task>();

        private readonly DedicatedThreadPool _pool;

        public DedicatedThreadPoolTaskScheduler(DedicatedThreadPool pool)
        {
            _pool = pool;
        }

        protected override void QueueTask(Task task)
        {
            lock (_tasks)
            {
                _tasks.AddLast(task);
            }

            EnsureWorkerRequested();
        }

        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            //current thread isn't running any tasks, can't execute inline
            if (!_currentThreadIsRunningTasks) return false;

            //remove the task from the queue if it was previously added
            if (taskWasPreviouslyQueued)
                if (TryDequeue(task))
                    return TryExecuteTask(task);
                else
                    return false;
            return TryExecuteTask(task);
        }

        protected override bool TryDequeue(Task task)
        {
            lock (_tasks) return _tasks.Remove(task);
        }

        ///
        /// Level of concurrency is directly equal to the number of threads
        /// in the <see cref="DedicatedThreadPool"/>.
        ///
        public override int MaximumConcurrencyLevel
        {
            get { return _pool.Settings.NumThreads; }
        }

        ///
        /// <exception cref="NotSupportedException">
        /// This exception is thrown if can't ensure a thread-safe return of the list of tasks.
        /// </exception>
        protected override IEnumerable<Task> GetScheduledTasks()
        {
            var lockTaken = false;
            try
            {
                Monitor.TryEnter(_tasks, ref lockTaken);

                //should this be immutable?
                if (lockTaken) return _tasks;
                else throw new NotSupportedException();
            }
            finally
            {
                if (lockTaken) Monitor.Exit(_tasks);
            }
        }

        private void EnsureWorkerRequested()
        {
            var count = _parallelWorkers;
            while (count < _pool.Settings.NumThreads)
            {
                var prev = Interlocked.CompareExchange(ref _parallelWorkers, count + 1, count);
                if (prev == count)
                {
                    RequestWorker();
                    break;
                }
                count = prev;
            }
        }

        private void ReleaseWorker()
        {
            var count = _parallelWorkers;
            while (count > 0)
            {
                var prev = Interlocked.CompareExchange(ref _parallelWorkers, count - 1, count);
                if (prev == count)
                {
                    break;
                }
                count = prev;
            }
        }

        private void RequestWorker()
        {
            _pool.QueueUserWorkItem(() =>
            {
                // this thread is now available for inlining
                _currentThreadIsRunningTasks = true;
                try
                {
                    // Process all available items in the queue.
                    while (true)
                    {
                        Task item;
                        lock (_tasks)
                        {
                            // done processing
                            if (_tasks.Count == 0)
                            {
                                ReleaseWorker();
                                break;
                            }

                            // Get the next item from the queue
                            item = _tasks.First.Value;
                            _tasks.RemoveFirst();
                        }

                        // Execute the task we pulled out of the queue
                        TryExecuteTask(item);
                    }
                }
                // We're done processing items on the current thread
                finally { _currentThreadIsRunningTasks = false; }
            });
        }
    }

    ///
    /// An instanced, dedicated thread pool.
    ///
    internal sealed class DedicatedThreadPool : IDisposable
    {
        public DedicatedThreadPool(DedicatedThreadPoolSettings settings)
        {
            _workQueue = new ThreadPoolWorkQueue();
            Settings = settings;
            _workers = Enumerable.Range(1, settings.NumThreads).Select(workerId => new PoolWorker(this, workerId)).ToArray();

            // Note:
            // The DedicatedThreadPoolSupervisor was removed because aborting thread could lead to unexpected behavior
            // If a new implementation is done, it should spawn a new thread when a worker is not making progress and
            // try to keep {settings.NumThreads} active threads.
        }

        public DedicatedThreadPoolSettings Settings { get; private set; }

        private readonly ThreadPoolWorkQueue _workQueue;
        private readonly PoolWorker[] _workers;

        ///
        /// <exception cref="ArgumentNullException">
        /// This exception is thrown if the given <paramref name="work"/> item is undefined.
        /// </exception>
        public bool QueueUserWorkItem(Action work)
        {
            if (work == null)
                throw new ArgumentNullException(nameof(work), "Work item cannot be null.");

            return _workQueue.TryAdd(work);
        }

        public void Dispose()
        {
            _workQueue.CompleteAdding();
        }

        public void WaitForThreadsExit()
        {
            WaitForThreadsExit(Timeout.InfiniteTimeSpan);
        }

        public void WaitForThreadsExit(TimeSpan timeout)
        {
            Task.WaitAll(_workers.Select(worker => worker.ThreadExit).ToArray(), timeout);
        }

        #region Pool worker implementation

        private class PoolWorker
        {
            private readonly DedicatedThreadPool _pool;

            private readonly TaskCompletionSource<object> _threadExit;

            public Task ThreadExit
            {
                get { return _threadExit.Task; }
            }

            public PoolWorker(DedicatedThreadPool pool, int workerId)
            {
                _pool = pool;
                _threadExit = new TaskCompletionSource<object>();

                var thread = new Thread(RunThread, pool.Settings.ThreadMaxStackSize);

                thread.IsBackground = pool.Settings.ThreadType == ThreadType.Background;

                if (pool.Settings.Name != null)
                    thread.Name = string.Format("{0}_{1}", pool.Settings.Name, workerId);

                if (pool.Settings.ApartmentState != ApartmentState.Unknown)
                    thread.SetApartmentState(pool.Settings.ApartmentState);

                thread.Start();
            }

            private void RunThread()
            {
                try
                {
                    foreach (var action in _pool._workQueue.GetConsumingEnumerable())
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception ex)
                        {
                            _pool.Settings.ExceptionHandler(ex);
                        }
                    }
                }
                finally
                {
                    _threadExit.TrySetResult(null);
                }
            }
        }

        #endregion

        #region WorkQueue implementation

        private class ThreadPoolWorkQueue
        {
            private static readonly int ProcessorCount = Environment.ProcessorCount;
            private const int CompletedState = 1;

            private readonly ConcurrentQueue<Action> _queue = new ConcurrentQueue<Action>();
            private readonly UnfairSemaphore _semaphore = new UnfairSemaphore();
            private int _outstandingRequests;
            private int _isAddingCompleted;

            public bool IsAddingCompleted
            {
                get { return Volatile.Read(ref _isAddingCompleted) == CompletedState; }
            }

            public bool TryAdd(Action work)
            {
                // If TryAdd returns true, it's garanteed the work item will be executed.
                // If it returns false, it's also garanteed the work item won't be executed.

                if (IsAddingCompleted)
                    return false;

                _queue.Enqueue(work);
                EnsureThreadRequested();

                return true;
            }

            public IEnumerable<Action> GetConsumingEnumerable()
            {
                while (true)
                {
                    Action work;
                    if (_queue.TryDequeue(out work))
                    {
                        yield return work;
                    }
                    else if (IsAddingCompleted)
                    {
                        while (_queue.TryDequeue(out work))
                            yield return work;

                        break;
                    }
                    else
                    {
                        _semaphore.Wait();
                        MarkThreadRequestSatisfied();
                    }
                }
            }

            public void CompleteAdding()
            {
                int previousCompleted = Interlocked.Exchange(ref _isAddingCompleted, CompletedState);

                if (previousCompleted == CompletedState)
                    return;

                // When CompleteAdding() is called, we fill up the _outstandingRequests and the semaphore
                // This will ensure that all threads will unblock and try to execute the remaining item in
                // the queue. When IsAddingCompleted is set, all threads will exit once the queue is empty.

                while (true)
                {
                    int count = Volatile.Read(ref _outstandingRequests);
                    int countToRelease = UnfairSemaphore.MaxWorker - count;

                    int prev = Interlocked.CompareExchange(ref _outstandingRequests, UnfairSemaphore.MaxWorker, count);

                    if (prev == count)
                    {
                        _semaphore.Release((short)countToRelease);
                        break;
                    }
                }
            }

            private void EnsureThreadRequested()
            {
                // There is a double counter here (_outstandingRequest and _semaphore)
                // Unfair semaphore does not support value bigger than short.MaxValue,
                // tring to Release more than short.MaxValue could fail miserably.

                // The _outstandingRequest counter ensure that we only request a
                // maximum of {ProcessorCount} to the semaphore.

                // It's also more efficient to have two counter, _outstandingRequests is
                // more lightweight than the semaphore.

                // This trick is borrowed from the .Net ThreadPool
                // https://github.com/dotnet/coreclr/blob/bc146608854d1db9cdbcc0b08029a87754e12b49/src/mscorlib/src/System/Threading/ThreadPool.cs#L568

                int count = Volatile.Read(ref _outstandingRequests);
                while (count < ProcessorCount)
                {
                    int prev = Interlocked.CompareExchange(ref _outstandingRequests, count + 1, count);
                    if (prev == count)
                    {
                        _semaphore.Release();
                        break;
                    }
                    count = prev;
                }
            }

            private void MarkThreadRequestSatisfied()
            {
                int count = Volatile.Read(ref _outstandingRequests);
                while (count > 0)
                {
                    int prev = Interlocked.CompareExchange(ref _outstandingRequests, count - 1, count);
                    if (prev == count)
                    {
                        break;
                    }
                    count = prev;
                }
            }
        }

        #endregion

        #region UnfairSemaphore implementation

        // This class has been translated from:
        // https://github.com/dotnet/coreclr/blob/97433b9d153843492008652ff6b7c3bf4d9ff31c/src/vm/win32threadpool.h#L124

        // UnfairSemaphore is a more scalable semaphore than Semaphore.  It prefers to release threads that have more recently begun waiting,
        // to preserve locality.  Additionally, very recently-waiting threads can be released without an addition kernel transition to unblock
        // them, which reduces latency.
        //
        // UnfairSemaphore is only appropriate in scenarios where the order of unblocking threads is not important, and where threads frequently
        // need to be woken.

        [StructLayout(LayoutKind.Sequential)]
        private sealed class UnfairSemaphore
        {
            public const int MaxWorker = 0x7FFF;

            // We track everything we care about in a single 64-bit struct to allow us to
            // do CompareExchanges on this for atomic updates.
            [StructLayout(LayoutKind.Explicit)]
            private struct SemaphoreState
            {
                //how many threads are currently spin-waiting for this semaphore?
                [FieldOffset(0)]
                public short Spinners;

                //how much of the semaphore's count is availble to spinners?
                [FieldOffset(2)]
                public short CountForSpinners;

                //how many threads are blocked in the OS waiting for this semaphore?
                [FieldOffset(4)]
                public short Waiters;

                //how much count is available to waiters?
                [FieldOffset(6)]
                public short CountForWaiters;

                [FieldOffset(0)]
                public long RawData;
            }

            [StructLayout(LayoutKind.Explicit, Size = 64)]
            private struct CacheLinePadding
            { }

            private readonly Semaphore m_semaphore;

            // padding to ensure we get our own cache line
#pragma warning disable 169
            private readonly CacheLinePadding m_padding1;
            private SemaphoreState m_state;
            private readonly CacheLinePadding m_padding2;
#pragma warning restore 169

            public UnfairSemaphore()
            {
                m_semaphore = new Semaphore(0, short.MaxValue);
            }

            public bool Wait()
            {
                return Wait(Timeout.InfiniteTimeSpan);
            }

            public bool Wait(TimeSpan timeout)
            {
                while (true)
                {
                    SemaphoreState currentCounts = GetCurrentState();
                    SemaphoreState newCounts = currentCounts;

                    // First, just try to grab some count.
                    if (currentCounts.CountForSpinners > 0)
                    {
                        --newCounts.CountForSpinners;
                        if (TryUpdateState(newCounts, currentCounts))
                            return true;
                    }
                    else
                    {
                        // No count available, become a spinner
                        ++newCounts.Spinners;
                        if (TryUpdateState(newCounts, currentCounts))
                            break;
                    }
                }

                //
                // Now we're a spinner.
                //
                int numSpins = 0;
                const int spinLimitPerProcessor = 50;
                while (true)
                {
                    SemaphoreState currentCounts = GetCurrentState();
                    SemaphoreState newCounts = currentCounts;

                    if (currentCounts.CountForSpinners > 0)
                    {
                        --newCounts.CountForSpinners;
                        --newCounts.Spinners;
                        if (TryUpdateState(newCounts, currentCounts))
                            return true;
                    }
                    else
                    {
                        double spinnersPerProcessor = (double)currentCounts.Spinners / Environment.ProcessorCount;
                        int spinLimit = (int)((spinLimitPerProcessor / spinnersPerProcessor) + 0.5);
                        if (numSpins >= spinLimit)
                        {
                            --newCounts.Spinners;
                            ++newCounts.Waiters;
                            if (TryUpdateState(newCounts, currentCounts))
                                break;
                        }
                        else
                        {
                            //
                            // We yield to other threads using Thread.Sleep(0) rather than the more traditional Thread.Yield().
                            // This is because Thread.Yield() does not yield to threads currently scheduled to run on other
                            // processors.  On a 4-core machine, for example, this means that Thread.Yield() is only ~25% likely
                            // to yield to the correct thread in some scenarios.
                            // Thread.Sleep(0) has the disadvantage of not yielding to lower-priority threads.  However, this is ok because
                            // once we've called this a few times we'll become a "waiter" and wait on the Semaphore, and that will
                            // yield to anything that is runnable.
                            //
                            Thread.Sleep(0);
                            numSpins++;
                        }
                    }
                }

                //
                // Now we're a waiter
                //
                bool waitSucceeded = m_semaphore.WaitOne(timeout);

                while (true)
                {
                    SemaphoreState currentCounts = GetCurrentState();
                    SemaphoreState newCounts = currentCounts;

                    --newCounts.Waiters;

                    if (waitSucceeded)
                        --newCounts.CountForWaiters;

                    if (TryUpdateState(newCounts, currentCounts))
                        return waitSucceeded;
                }
            }

            public void Release()
            {
                Release(1);
            }

            public void Release(short count)
            {
                while (true)
                {
                    SemaphoreState currentState = GetCurrentState();
                    SemaphoreState newState = currentState;

                    short remainingCount = count;

                    // First, prefer to release existing spinners,
                    // because a) they're hot, and b) we don't need a kernel
                    // transition to release them.
                    short spinnersToRelease = Math.Max((short)0, Math.Min(remainingCount, (short)(currentState.Spinners - currentState.CountForSpinners)));
                    newState.CountForSpinners += spinnersToRelease;
                    remainingCount -= spinnersToRelease;

                    // Next, prefer to release existing waiters
                    short waitersToRelease = Math.Max((short)0, Math.Min(remainingCount, (short)(currentState.Waiters - currentState.CountForWaiters)));
                    newState.CountForWaiters += waitersToRelease;
                    remainingCount -= waitersToRelease;

                    // Finally, release any future spinners that might come our way
                    newState.CountForSpinners += remainingCount;

                    // Try to commit the transaction
                    if (TryUpdateState(newState, currentState))
                    {
                        // Now we need to release the waiters we promised to release
                        if (waitersToRelease > 0)
                            m_semaphore.Release(waitersToRelease);

                        break;
                    }
                }
            }

            private bool TryUpdateState(SemaphoreState newState, SemaphoreState currentState)
            {
                if (Interlocked.CompareExchange(ref m_state.RawData, newState.RawData, currentState.RawData) == currentState.RawData)
                {
                    Debug.Assert(newState.CountForSpinners <= MaxWorker, "CountForSpinners is greater than MaxWorker");
                    Debug.Assert(newState.CountForSpinners >= 0, "CountForSpinners is lower than zero");
                    Debug.Assert(newState.Spinners <= MaxWorker, "Spinners is greater than MaxWorker");
                    Debug.Assert(newState.Spinners >= 0, "Spinners is lower than zero");
                    Debug.Assert(newState.CountForWaiters <= MaxWorker, "CountForWaiters is greater than MaxWorker");
                    Debug.Assert(newState.CountForWaiters >= 0, "CountForWaiters is lower than zero");
                    Debug.Assert(newState.Waiters <= MaxWorker, "Waiters is greater than MaxWorker");
                    Debug.Assert(newState.Waiters >= 0, "Waiters is lower than zero");
                    Debug.Assert(newState.CountForSpinners + newState.CountForWaiters <= MaxWorker, "CountForSpinners + CountForWaiters is greater than MaxWorker");

                    return true;
                }

                return false;
            }

            private SemaphoreState GetCurrentState()
            {
                // Volatile.Read of a long can get a partial read in x86 but the invalid
                // state will be detected in TryUpdateState with the CompareExchange.

                SemaphoreState state = new SemaphoreState();
                state.RawData = Volatile.Read(ref m_state.RawData);
                return state;
            }
        }

        #endregion
    }
}


text:
function disableable($parse) {

    return {
        restrict: 'C',
        priority: 1000000,
        require: '?ngClick',
        link: function (scope, elem, attrs, ngClick) {
            if (attrs.disable){
                var disable = $parse(attrs.disable);

                elem.bind('click', function (e) {
                    if (disable(scope)){
                        console.log("preventDefault");
                        e.preventDefault();
                        //e.stopImmediatePropagation();
                        return false;
                    }

                    return true;
                });

                scope.$watch(disable, function (val) {
                    if (val){
                        elem.addClass('disabled');
                        elem.css('cursor', 'default');
                        elem.prop('disabled', true);
                    }
                    else {
                        elem.removeClass('disabled');
                        elem.css('cursor', 'pointer');
                        elem.prop('disabled', false);
                    }
                });
            }
        }
    };
}

disableable.$inject = ["$parse"];

export default {
    name: 'disableable',
    fn: disableable
};

redpajama_set_name: RedPajamaGithub


text:
package org.interledger.cryptoconditions.encoding;

import java.io.IOException;
import java.io.Writer;
import java.util.EnumSet;

import org.interledger.cryptoconditions.Condition;
import org.interledger.cryptoconditions.ConditionType;
import org.interledger.cryptoconditions.FeatureSuite;

public class ConditionWriter extends Writer {

    private static final char[] HEADER = new char[]{'c', 'c'};
    private static final char[] VERSION = new char[]{'0', '1'};
    private static final char DELIMITER = ':';

    private Writer writer;

    public ConditionWriter(Writer innerWriter) {
        this.writer = innerWriter;
    }

    /**
     * Write the condition to the underlying writer using String encoding
     *
     * @param condition
     * @throws IOException
     */
    public void writeCondition(Condition condition) throws IOException {
        writeHeader();
        writeDelimiter();
        writeVersion();
        writeDelimiter();
        writeConditionType(condition.getType());
        writeDelimiter();
        writeFeatures(condition.getFeatures());
        writeDelimiter();
        writeFingerprint(condition.getFingerprint());
        writeDelimiter();
        writeMaxFulfillmentLength(condition.getMaxFulfillmentLength());

    }

    protected void writeDelimiter()
            throws IOException {
        writer.write(DELIMITER);
    }

    protected void writeHeader()
            throws IOException {
        writer.write(HEADER);
    }

    protected void writeVersion()
            throws IOException {
        writer.write(VERSION);
    }

    protected void writeConditionType(ConditionType type)
            throws IOException {
        writer.write(Integer.toString(type.getTypeCode(), 16));
    }

    protected void writeFeatures(EnumSet<FeatureSuite> features)
            throws IOException {

        //TODO - This is easy to read but could probably be optimized
        int encoded_bitmask = 0;
        for (FeatureSuite featureSuite : features) {
            encoded_bitmask += featureSuite.toInt();
        }

        writer.write(Integer.toString(encoded_bitmask, 16));
    }

    protected void writeFingerprint(byte[] fingerprint)
            throws IOException {

        writer.write(Base64Url.encode(fingerprint));
    }

    protected void writeMaxFulfillmentLength(int maxFulfillmentLength)
            throws IOException {

        writer.write(Integer.toString(maxFulfillmentLength));
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(cbuf, off, len);
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        try {
            writer.flush();
            writer.close();
        } catch(Exception e) {
            // TODO: Improvement. Inject Logger.
            System.out.println("WARN: Couldn't properly close the stream due to "+
                e.toString()+", Some data could have not been flushed to disk");
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Chapper.Model;
using AppNetDotNet.Model;
using AppNetDotNet.ApiCalls;
using System.ComponentModel;

namespace Chapper.Controls
{
    /// <summary>
    /// Interaction logic for ItemBox.xaml
    /// </summary>
    public partial class ItemBox : UserControl
    {

        public ItemBox()
        {
            InitializeComponent();
        }

        private void Grid_MouseEnter_1(object sender, MouseEventArgs e)
        {
            stackpanel_itemButtons.Visibility = System.Windows.Visibility.Visible;
        }

        private void grid_main_MouseLeave_1(object sender, MouseEventArgs e)
        {
            stackpanel_itemButtons.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void button_reply_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                if (item.isRepost)
                {
                    item = new Item(item.apnPost.repost_of);
                }
                if (item != null)
                {
                    AppController.Current.composeReplyTo(item);
                }
            }

        }

        private void button_starItem_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                if (!item.isRepost)
                {
                    Tuple<Post, ApiCallResponse> response;
                    if (item.isStarred)
                    {
                        response = Posts.unstar(AppController.Current.account.accessToken, item.id);
                    }
                    else
                    {
                        response = Posts.star(AppController.Current.account.accessToken, item.id);
                    }
                    if (response.Item2.success)
                    {
                        item.isStarred = !item.isStarred;
                    }
                }
                else
                {
                    Tuple<Post, ApiCallResponse> response;
                    if (item.isStarred)
                    {
                        response = Posts.unstar(AppController.Current.account.accessToken, item.apnPost.repost_of.id);
                    }
                    else
                    {
                        response = Posts.star(AppController.Current.account.accessToken, item.apnPost.repost_of.id);
                    }
                    if (response.Item2.success)
                    {
                        item.isStarred = !item.isStarred;
                    }
                }
            }
        }

        private void button_repost_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                if (!item.isRepost)
                {
                    Tuple<Post, ApiCallResponse> response;
                    if (item.isOwnRepost)
                    {
                        response = Posts.unrepost(AppController.Current.account.accessToken, item.id);
                    }
                    else
                    {
                        response = Posts.repost(AppController.Current.account.accessToken, item.id);
                    }
                    if (response.Item2.success)
                    {
                        item.isOwnRepost = !item.isOwnRepost;
                    }
                }
                else
                {
                    Tuple<Post, ApiCallResponse> response;
                    if (item.isOwnRepost)
                    {
                        response = Posts.unrepost(AppController.Current.account.accessToken, item.apnPost.repost_of.id);
                    }
                    else
                    {
                        response = Posts.repost(AppController.Current.account.accessToken, item.apnPost.repost_of.id);
                    }
                    if (response.Item2.success)
                    {
                        item.isOwnRepost = !item.isOwnRepost;
                    }
                }
            }
        }

        private void button_sendMessage_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppController.Current.composeMessageTo(item);
            }
        }

        private void hyperlink_source_Click_1(object sender, RoutedEventArgs e)
        {
            Hyperlink link = sender as Hyperlink;
            if (link != null)
            {
                try
                {
                    System.Diagnostics.Process.Start(link.NavigateUri.AbsoluteUri);
                }
                catch
                {

                }
            }
        }

        private void buttonAuthor_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppController.Current.showUserInfo(item.user);
            }
        }

        private void buttonAuthorRepost_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                if (item.isRepost && item.apnPost != null)
                {
                    AppController.Current.showUserInfo(item.apnPost.repost_of.user);
                }
            }
        }

        private void button_embeddedImage_Click_1(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            if (button != null)
            {
                try
                {
                    string url = button.CommandParameter as string;
                    System.Diagnostics.Process.Start(url);
                }
                catch { }
            }
        }

        private void button_conversation_Click_1(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                Conversation conversation = new Conversation(item);
                AppController.Current.addNewChapperCollection(conversation, true);
            }
        }

        private void button_quote_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                string quoteText = string.Format("RP @{0}: \"{1}\"", item.user.username, item.text);
                AppController.Current.setPostComposeText(quoteText);
            }
        }

        private void context_click_mute_repost_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppNetDotNet.ApiCalls.Users.mute(AppController.Current.account.accessToken, item.inReplyToPost.user.id);
            }
        }

        private void context_click_block_repost_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppNetDotNet.ApiCalls.Users.block(AppController.Current.account.accessToken, item.inReplyToPost.user.id);
            }
        }

        private void context_click_mute_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppNetDotNet.ApiCalls.Users.mute(AppController.Current.account.accessToken, item.user.id);
            }
        }

        private void context_click_block_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppNetDotNet.ApiCalls.Users.block(AppController.Current.account.accessToken, item.user.id);
            }
        }

        private void context_click_mute_receiver_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppNetDotNet.ApiCalls.Users.mute(AppController.Current.account.accessToken, item.messageReceiver.id);
            }
        }

        private void context_click_block_receiver_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppNetDotNet.ApiCalls.Users.block(AppController.Current.account.accessToken, item.messageReceiver.id);
            }
        }

        private void buttonMessageReceiver_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                AppController.Current.showUserInfo(item.messageReceiver);
            }
        }

        private void button_delete_Click(object sender, RoutedEventArgs e)
        {
            Item item = this.DataContext as Item;
            if (item != null)
            {
                if (item.apnMessage != null)
                {
                    Messages.delete(AppController.Current.account.accessToken, item.apnMessage.channel_id, item.apnMessage.id);
                    try
                    {
                        if (AppController.Current.account.privateMessages.Contains(item))
                        {
                            AppController.Current.account.privateMessages.Remove(item);
                        }
                        else
                        {
                            IChapperCollection collection = AppController.Current.account.allNonPrivateMessagesChannels.Where(i => i.id == item.apnMessage.channel_id).First();
                            if (collection != null)
                            {
                                collection.items.Remove(item);
                            }
                        }
                    }
                    catch { }
                }
                else if (item.apnPost != null)
                {
                    Posts.delete(AppController.Current.account.accessToken, item.apnPost.id);
                    try
                    {
                        if (AppController.Current.account.myStream.Contains(item))
                        {
                            AppController.Current.account.myStream.Remove(item);
                        }
                        if (AppController.Current.account.mentions.Contains(item))
                        {
                            AppController.Current.account.mentions.Remove(item);
                        }
                    }
                    catch { }
                }
            }
        }
    }
}


text:
require "thrift"

$: << File.expand_path(File.dirname(__FILE__))

require "storm_types"
require "storm_constants"
require "nimbus"
require "distributed_r_p_c"


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Coelomycetous Anamorphs with Appendage-bearing Conidia (Ontario) 139 (1993)

#### Original name
Pestalotia laurina Mont.

### Remarks
null


text:
#ifdef WIN32
#include <WinSock2.h>
#endif

#include "netutil.h"
#include "../headers/commonstruct.h"

string GetIpString(uint32 ip)
{
	char pszPeerIP[MAX_IP_LEN] = "";
	struct in_addr addPeerIP;
	addPeerIP.s_addr = ip;
	strcpy(pszPeerIP, inet_ntoa(addPeerIP));
	string ipString(pszPeerIP);

	return ipString;
}


text:
<Alloy>
	<View id="containerview" width="Ti.UI.FILL">
		<View id="leftMenu">
			<TableView id="leftTableView" />
		</View>
		<View id="rightMenu">
			<TableView id="rightTableView" />
		</View>
		<View id="movableview">
			<View id="shadowview" backgroundColor="#46a346">
				<View id="navview">
					<Button id="leftButton" />

					<Button id="bellButton" />

					<Button id="refreshButton" onClick="RefreshFeed" color="white" width="Ti.UI.SIZE">refresh</Button>
				</View>
				<View id="contentview" />
			</View>
		</View>
	</View>
</Alloy>


text:
Permisos para Editar Campo

Esta página te permite editar un conjunto existente de permisos del tipo
columna-usuario.
<include cpriv.es>

Tras editar, haz click en el botón <tt>Salvar</tt> para que los cambios
tengan efecto inmediato. También puedes hacer click en <tt>Borrar</tt> para
borrar los permisos de MySQL.


text:
class test_generate_key_derivation : public single_tx_test_base
{
public:
  static const size_t loop_count = 1000;

  bool test()
  {
    Crypto::KeyDerivation recv_derivation;
    Crypto::generate_key_derivation(m_tx_pub_key, m_bob.getAccountKeys().viewSecretKey, recv_derivation);
    return true;
  }
};


text:
<?
defined('C5_EXECUTE') or die("Access Denied.");
//$replaceOnUnload = 1;
$bt->inc('editor_init.php');
?>

<div style="text-align: center" id="ccm-editor-pane">
<textarea id="ccm-content-<?=$b->getBlockID()?>-<?=$a->getAreaID()?>" class="advancedEditor ccm-advanced-editor" name="content" style="width: 580px; height: 380px"><?=Loader::helper('text')->specialchars($controller->getContentEditMode())?></textarea>
</div>


text:
package org.testng.v6;

/**
 * Encapsulates a group that can have an after operation.
 */
public class RunGroup {
  public final static int XML_TEST = 1;
  public final static int CLASS = 2;
  public final static int GROUP = 3;

  private int m_type;
  private String m_name;
  private int m_id = 0;

  public RunGroup(int type, String name, int id) {
    m_type = type;
    m_name = name;
    m_id = id;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    try {
      RunGroup that = (RunGroup) obj;
      return that.getType() == getType() && that.getName().equals(getName());
    }
    catch(ClassCastException ex) {
      return false;
    }
  }

  @Override
  public int hashCode() {
    return m_name.hashCode() ^ m_type;
  }

  public int getType() {
    return m_type;
  }

  public void setType(int type) {
    m_type = type;
  }

  public String getName() {
    return m_name;
  }

  public void setName(String name) {
    m_name = name;
  }

  public int getId() {
    return m_id;
  }

  public void setId(int id) {
    m_id = id;
  }

  public String toString() {
    String type = "";
    if (m_type == CLASS) type = "class:";
    else if (m_type == XML_TEST) type = "<test>:";
    else if (m_type == GROUP) type = "group:";

//        return "(RunGroup:" + m_id + ")";
    return "(RunGroup:" + m_id + " " + type + "\"" + m_name
      + "\")";
  }

}


text:
use super::*;
use crate::config::Config;
use crate::rustfmt_diff::{make_diff, print_diff};

pub(crate) struct DiffEmitter {
    config: Config,
}

impl DiffEmitter {
    pub(crate) fn new(config: Config) -> Self {
        Self { config }
    }
}

impl Emitter for DiffEmitter {
    fn emit_formatted_file(
        &mut self,
        output: &mut dyn Write,
        FormattedFile {
            filename,
            original_text,
            formatted_text,
        }: FormattedFile<'_>,
    ) -> Result<EmitterResult, io::Error> {
        const CONTEXT_SIZE: usize = 3;
        let mismatch = make_diff(original_text, formatted_text, CONTEXT_SIZE);
        let has_diff = !mismatch.is_empty();

        if has_diff {
            if self.config.print_misformatted_file_names() {
                writeln!(output, "{}", ensure_real_path(filename).display())?;
            } else {
                print_diff(
                    mismatch,
                    |line_num| format!("Diff in {} at line {}:", filename, line_num),
                    &self.config,
                );
            }
        } else if original_text != formatted_text {
            // This occurs when the only difference between the original and formatted values
            // is the newline style. This happens because The make_diff function compares the
            // original and formatted values line by line, independent of line endings.
            let file_path = ensure_real_path(filename);
            writeln!(output, "Incorrect newline style in {}", file_path.display())?;
            return Ok(EmitterResult { has_diff: true });
        }

        Ok(EmitterResult { has_diff })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::FileName;
    use std::path::PathBuf;

    #[test]
    fn does_not_print_when_no_files_reformatted() {
        let mut writer = Vec::new();
        let config = Config::default();
        let mut emitter = DiffEmitter::new(config);
        let result = emitter
            .emit_formatted_file(
                &mut writer,
                FormattedFile {
                    filename: &FileName::Real(PathBuf::from("src/lib.rs")),
                    original_text: "fn empty() {}\n",
                    formatted_text: "fn empty() {}\n",
                },
            )
            .unwrap();
        assert_eq!(result.has_diff, false);
        assert_eq!(writer.len(), 0);
    }

    #[test]
    fn prints_file_names_when_config_is_enabled() {
        let bin_file = "src/bin.rs";
        let bin_original = "fn main() {\nprintln!(\"Hello, world!\");\n}";
        let bin_formatted = "fn main() {\n    println!(\"Hello, world!\");\n}";
        let lib_file = "src/lib.rs";
        let lib_original = "fn greet() {\nprintln!(\"Greetings!\");\n}";
        let lib_formatted = "fn greet() {\n    println!(\"Greetings!\");\n}";

        let mut writer = Vec::new();
        let mut config = Config::default();
        config.set().print_misformatted_file_names(true);
        let mut emitter = DiffEmitter::new(config);
        let _ = emitter
            .emit_formatted_file(
                &mut writer,
                FormattedFile {
                    filename: &FileName::Real(PathBuf::from(bin_file)),
                    original_text: bin_original,
                    formatted_text: bin_formatted,
                },
            )
            .unwrap();
        let _ = emitter
            .emit_formatted_file(
                &mut writer,
                FormattedFile {
                    filename: &FileName::Real(PathBuf::from(lib_file)),
                    original_text: lib_original,
                    formatted_text: lib_formatted,
                },
            )
            .unwrap();

        assert_eq!(
            String::from_utf8(writer).unwrap(),
            format!("{}\n{}\n", bin_file, lib_file),
        )
    }

    #[test]
    fn prints_newline_message_with_only_newline_style_diff() {
        let mut writer = Vec::new();
        let config = Config::default();
        let mut emitter = DiffEmitter::new(config);
        let _ = emitter
            .emit_formatted_file(
                &mut writer,
                FormattedFile {
                    filename: &FileName::Real(PathBuf::from("src/lib.rs")),
                    original_text: "fn empty() {}\n",
                    formatted_text: "fn empty() {}\r\n",
                },
            )
            .unwrap();
        assert_eq!(
            String::from_utf8(writer).unwrap(),
            String::from("Incorrect newline style in src/lib.rs\n")
        );
    }
}


text:
/**
 *
 */
package kodkod.examples.tptp;

import static kodkod.ast.Expression.UNIV;

import java.util.ArrayList;
import java.util.List;

import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.Relation;
import kodkod.ast.Variable;
import kodkod.engine.Solution;
import kodkod.engine.Solver;
import kodkod.engine.satlab.SATFactory;
import kodkod.instance.Bounds;
import kodkod.instance.TupleFactory;
import kodkod.instance.Universe;

/**
 * A KK encoding of SET948+1.p from http://www.cs.miami.edu/~tptp/
 * @author Emina Torlak
 */
public final class SET948 {

	private final Relation empty;
	private final Relation subset, in, disjoint, union;
	private final Relation intersect2, union2;

	/**
	 * Constructs a new instance of SET948.
	 */
	public SET948() {
		empty = Relation.unary("empty");
		subset = Relation.binary("subset");
		in = Relation.binary("in");
		disjoint = Relation.binary("disjoint");
		union = Relation.binary("union");
		intersect2 = Relation.ternary("set_intersection2");
		union2 = Relation.ternary("set_union2");
	}

	/**
	 * Returns set_intersection2[A][B]
	 * @return set_intersection2[A][B]
	 */
	final Expression set_intersection2(Expression a, Expression b) {
		return b.join(a.join(intersect2));
	}
	/**
	 * Returns set_union2[A][B]
	 * @return set_union2[A][B]
	 */
	final Expression set_union2(Expression a, Expression b) {
		return b.join(a.join(union2));
	}

	/**
	 * Returns union[a]
	 * @return union[a]
	 */
	final Expression union(Expression a) {
		return a.join(union);
	}

	/**
	 * Returns a in empty
	 * @return a in empty
	 */
	final Formula empty(Expression a) {
		return a.in(empty);
	}

	/**
	 * Returns a->b in subset.
	 * @return a->b in subset.
	 */
	final Formula subset(Expression a, Expression b) {
		return a.product(b).in(subset);
	}

	/**
	 * Returns a->b in in.
	 * @return a->b in in
	 */
	final Formula in(Expression a, Expression b) {
		return a.product(b).in(in);
	}

	/**
	 * Returns a->b in disjoint.
	 * @return a->b in disjoint
	 */
	final Formula disjoint(Expression a, Expression b) {
		return a.product(b).in(disjoint);
	}

	/**
	 * Returns the declarations.
	 * @return declarations
	 */
	public final Formula decls() {
		final Formula f0 = union.function(UNIV, UNIV);
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		final Formula f1 = set_intersection2(a, b).one();
		final Formula f2 = set_union2(a, b).one();
		return f0.and(f1.and(f2).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV))));
	}

	/**
	 * Returns antisymmetry_r2_hidden axiom.
	 * @return antisymmetry_r2_hidden
	 */
	public final Formula antisymmetry_r2_hidden() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return in(a,b).implies(in(b,a).not()).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns commutativity_k2_xboole_0 axiom.
	 * @return commutativity_k2_xboole_0
	 */
	public final Formula commutativity_k2_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return set_union2(a, b).eq(set_union2(b, a)).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns d10_xboole_0 axiom.
	 * @return d10_xboole_0
	 */
	public final Formula d10_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return a.eq(b).iff(subset(a,b).and(subset(b,a))).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns d2_xboole_0 axiom.
	 * @return d2_xboole_0
	 */
	public final Formula d2_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		final Variable c = Variable.unary("C");
		return c.eq(set_union2(a, b)).iff(in.join(c).eq(in.join(a).union(in.join(b)))).
			forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)).and(c.oneOf(UNIV)));
	}

	/**
	 * Returns d3_tarski axiom.
	 * @return d3_tarski
	 */
	public final Formula d3_tarski() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return subset(a,b).iff(in.join(a).in(in.join(b))).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns d3_xboole_0 axiom.
	 * @return d3_xboole_0
	 */
	public final Formula d3_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		final Variable c = Variable.unary("C");
		return c.eq(set_intersection2(a, b)).iff(in.join(c).eq(in.join(a).intersection(in.join(b)))).
			forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)).and(c.oneOf(UNIV)));
	}

	/**
	 * Returns d4_tarski axiom.
	 * @return d4_tarski
	 */
	public final Formula d4_tarski() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return b.eq(union(a)).iff(in.join(b).eq(in.join(in.join(a)))).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns fc2_xboole_0 axiom.
	 * @return fc2_xboole_0
	 */
	public final Formula fc2_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return empty(a).not().implies(empty(set_union2(a, b)).not()).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns fc3_xboole_0 axiom.
	 * @return fc3_xboole_0
	 */
	public final Formula fc3_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return empty(a).not().implies(empty(set_union2(b, a)).not()).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns idempotence_k2_xboole_0 axiom.
	 * @return idempotence_k2_xboole_0
	 */
	public final Formula idempotence_k2_xboole_0() {
		final Variable a = Variable.unary("A");
		return set_union2(a, a).eq(a).forAll(a.oneOf(UNIV));
	}

	/**
	 * Returns idempotence_k3_xboole_0 axiom.
	 * @return idempotence_k3_xboole_0
	 */
	public final Formula idempotence_k3_xboole_0() {
		final Variable a = Variable.unary("A");
		return set_intersection2(a, a).eq(a).forAll(a.oneOf(UNIV));
	}

	/**
	 * Returns rc1_xboole_0 axiom.
	 * @return rc1_xboole_0
	 */
	public final Formula rc1_xboole_0() {
		return empty.some();
	}

	/**
	 * Returns rc2_xboole_0 axiom.
	 * @return rc2_xboole_0
	 */
	public final Formula rc2_xboole_0() {
		return UNIV.difference(empty).some();
	}

	/**
	 * Returns reflexivity_r1_tarski axiom.
	 * @return reflexivity_r1_tarski
	 */
	public final Formula reflexivity_r1_tarski() {
		final Variable a = Variable.unary("A");
		return subset(a,a).forAll(a.oneOf(UNIV));
	}

	/**
	 * Returns symmetry_r1_xboole_0 axiom.
	 * @return symmetry_r1_xboole_0
	 */
	public final Formula symmetry_r1_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return disjoint(a, b).implies(disjoint(b, a)).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns t4_xboole_0 axiom.
	 * @return t4_xboole_0
	 */
	public final Formula t4_xboole_0() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return disjoint(a, b).not().implies(set_intersection2(a, b).some()).
			and(disjoint(a, b).implies(set_intersection2(a, b).no())).
			forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns t97_zfmisc_1 axiom.
	 * @return t97_zfmisc_1
	 */
	public final Formula t97_zfmisc_1() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		return subset(union(set_intersection2(a, b)), set_intersection2(union(a), union(b))).
			forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}
	/**
	 * Returns the conjunction of all  axioms.
	 * @return conjunction of all  axioms.
	 */
	public final Formula axioms() {
		return decls().and(antisymmetry_r2_hidden()).and(commutativity_k2_xboole_0()).
		and(d10_xboole_0()).and(d2_xboole_0()).and(d3_tarski()).and(d3_xboole_0()).
		and(d4_tarski()).and(fc2_xboole_0()).and(fc3_xboole_0()).and(idempotence_k2_xboole_0()).
		and(idempotence_k3_xboole_0()).and(rc1_xboole_0()).and(rc2_xboole_0()).
		and(reflexivity_r1_tarski()).and(symmetry_r1_xboole_0()).and(t4_xboole_0()).
		and(t97_zfmisc_1());
	}

	/**
	 * Returns t101_zfmisc_1 conjecture.
	 * @return t101_zfmisc_1
	 */
	public final Formula t101_zfmisc_1() {
		final Variable a = Variable.unary("A");
		final Variable b = Variable.unary("B");
		final Variable c = Variable.unary("C");
		final Variable d = Variable.unary("D");
		final Formula f0 = in(c.union(d), set_union2(a, b)).implies(c.eq(d).or(disjoint(c, c))).
			forAll(c.oneOf(UNIV).and(d.oneOf(UNIV)));
		final Formula f1 = union(set_intersection2(a, b)).eq(set_intersection2(union(a), union(b)));
		return f0.implies(f1).forAll(a.oneOf(UNIV).and(b.oneOf(UNIV)));
	}

	/**
	 * Returns the conjunction of the axioms and the negation of the hypothesis.
	 * @return axioms() && !t101_zfmisc_1()
	 */
	public final Formula checkT101_zfmisc_1() {
		return axioms().and(t101_zfmisc_1().not());
	}

	/**
	 * Returns bounds for the given scope.
	 * @return bounds for the given scope.
	 */
	public final Bounds bounds(int n) {
		assert n > 0;
		final List<String> atoms = new ArrayList<String>(n);
		for(int i = 0; i < n; i++)
			atoms.add("a"+i);
		final Universe u = new Universe(atoms);
		final Bounds b = new Bounds(u);
		final TupleFactory f = u.factory();
		b.bound(empty, f.allOf(1));
		b.bound(subset, f.allOf(2));
		b.bound(in, f.allOf(2));
		b.bound(disjoint, f.allOf(2));
		b.bound(union, f.allOf(2));
		b.bound(intersect2, f.allOf(3));
		b.bound(union2, f.allOf(3));
		return b;
	}

	private static void usage() {
		System.out.println("java examples.tptp.SET948 [univ size]");
		System.exit(1);
	}

	/**
	 * Usage: java examples.tptp.SET948 [univ size]
	 */
	public static void main(String[] args) {
		if (args.length < 1)
			usage();

		try {
			final int n = Integer.parseInt(args[0]);
			if (n < 1)
				usage();
			final SET948 model = new SET948();
			final Solver solver = new Solver();
			solver.options().setSolver(SATFactory.MiniSat);
//			solver.options().setSymmetryBreaking(n*n);
//			solver.options().setFlatten(false);
			final Formula f = model.checkT101_zfmisc_1();
			final Bounds b = model.bounds(n);
			System.out.println(f);
			final Solution sol = solver.solve(f, b);
			System.out.println(sol);
		} catch (NumberFormatException nfe) {
			usage();
		}
	}
}


text:
layout: default
title: "Manufacturing And Trade"

---

{% include interests/manufacturing-and-trade.md %}

### Who is interested in Manufacturing And Trade?

* [Ian Austin]({{ site.baseurl }}/members/ian-austin.html)


text:
package play.routing;

import play.ApplicationLoader;
import play.BuiltInComponentsFromContext;

/**
 * RoutingDsl components from the built in components.
 *
 * @see play.BuiltInComponentsFromContext
 * @see play.routing.RoutingDslComponents
 */
public abstract class RoutingDslComponentsFromContext extends BuiltInComponentsFromContext
    implements RoutingDslComponents {
  public RoutingDslComponentsFromContext(ApplicationLoader.Context context) {
    super(context);
  }
}


text:
package org.locationtech.geomesa.hbase.index

import org.apache.hadoop.hbase.client._
import org.locationtech.geomesa.hbase.data._
import org.locationtech.geomesa.index.index.{AttributeDateIndex, AttributeIndex}

case object HBaseAttributeIndex
    extends HBaseFeatureIndex with AttributeIndex[HBaseDataStore, HBaseFeature, Mutation, Query] {
  override val version: Int = 2
}

case object HBaseAttributeDateIndex
    extends HBaseFeatureIndex with AttributeDateIndex[HBaseDataStore, HBaseFeature, Mutation, Query] {
  override val version: Int = 1
}


text:
package org.apache.beam.runners.dataflow.util;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpStatusCodes;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.LowLevelHttpRequest;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.testing.http.HttpTesting;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.services.dataflow.model.DataflowPackage;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.io.LineReader;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.beam.runners.dataflow.util.PackageUtil.PackageAttributes;
import org.apache.beam.sdk.options.GcsOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.ExpectedLogs;
import org.apache.beam.sdk.testing.FastNanoClockAndSleeper;
import org.apache.beam.sdk.testing.RegexMatcher;
import org.apache.beam.sdk.util.GcsUtil;
import org.apache.beam.sdk.util.IOChannelUtils;
import org.apache.beam.sdk.util.gcsfs.GcsPath;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/** Tests for PackageUtil. */
@RunWith(JUnit4.class)
public class PackageUtilTest {
  @Rule public ExpectedLogs logged = ExpectedLogs.none(PackageUtil.class);
  @Rule
  public TemporaryFolder tmpFolder = new TemporaryFolder();

  @Rule
  public FastNanoClockAndSleeper fastNanoClockAndSleeper = new FastNanoClockAndSleeper();

  @Mock
  GcsUtil mockGcsUtil;

  // 128 bits, base64 encoded is 171 bits, rounds to 22 bytes
  private static final String HASH_PATTERN = "[a-zA-Z0-9+-]{22}";

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    GcsOptions pipelineOptions = PipelineOptionsFactory.as(GcsOptions.class);
    pipelineOptions.setGcsUtil(mockGcsUtil);

    IOChannelUtils.registerIOFactoriesAllowOverride(pipelineOptions);
  }

  private File makeFileWithContents(String name, String contents) throws Exception {
    File tmpFile = tmpFolder.newFile(name);
    Files.write(contents, tmpFile, StandardCharsets.UTF_8);
    tmpFile.setLastModified(0);  // required for determinism with directories
    return tmpFile;
  }

  static final String STAGING_PATH = GcsPath.fromComponents("somebucket", "base/path").toString();
  private static PackageAttributes makePackageAttributes(File file, String overridePackageName) {
    return PackageUtil.createPackageAttributes(file, STAGING_PATH, overridePackageName);
  }

  @Test
  public void testFileWithExtensionPackageNamingAndSize() throws Exception {
    String contents = "This is a test!";
    File tmpFile = makeFileWithContents("file.txt", contents);
    PackageAttributes attr = makePackageAttributes(tmpFile, null);
    DataflowPackage target = attr.getDataflowPackage();

    assertThat(target.getName(), RegexMatcher.matches("file-" + HASH_PATTERN + ".txt"));
    assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName()));
    assertThat(attr.getSize(), equalTo((long) contents.length()));
  }

  @Test
  public void testPackageNamingWithFileNoExtension() throws Exception {
    File tmpFile = makeFileWithContents("file", "This is a test!");
    DataflowPackage target = makePackageAttributes(tmpFile, null).getDataflowPackage();

    assertThat(target.getName(), RegexMatcher.matches("file-" + HASH_PATTERN));
    assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName()));
  }

  @Test
  public void testPackageNamingWithDirectory() throws Exception {
    File tmpDirectory = tmpFolder.newFolder("folder");
    DataflowPackage target = makePackageAttributes(tmpDirectory, null).getDataflowPackage();

    assertThat(target.getName(), RegexMatcher.matches("folder-" + HASH_PATTERN + ".jar"));
    assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName()));
  }

  @Test
  public void testPackageNamingWithFilesHavingSameContentsAndSameNames() throws Exception {
    File tmpDirectory1 = tmpFolder.newFolder("folder1", "folderA");
    makeFileWithContents("folder1/folderA/sameName", "This is a test!");
    DataflowPackage target1 = makePackageAttributes(tmpDirectory1, null).getDataflowPackage();

    File tmpDirectory2 = tmpFolder.newFolder("folder2", "folderA");
    makeFileWithContents("folder2/folderA/sameName", "This is a test!");
    DataflowPackage target2 = makePackageAttributes(tmpDirectory2, null).getDataflowPackage();

    assertEquals(target1.getName(), target2.getName());
    assertEquals(target1.getLocation(), target2.getLocation());
  }

  @Test
  public void testPackageNamingWithFilesHavingSameContentsButDifferentNames() throws Exception {
    File tmpDirectory1 = tmpFolder.newFolder("folder1", "folderA");
    makeFileWithContents("folder1/folderA/uniqueName1", "This is a test!");
    DataflowPackage target1 = makePackageAttributes(tmpDirectory1, null).getDataflowPackage();

    File tmpDirectory2 = tmpFolder.newFolder("folder2", "folderA");
    makeFileWithContents("folder2/folderA/uniqueName2", "This is a test!");
    DataflowPackage target2 = makePackageAttributes(tmpDirectory2, null).getDataflowPackage();

    assertNotEquals(target1.getName(), target2.getName());
    assertNotEquals(target1.getLocation(), target2.getLocation());
  }

  @Test
  public void testPackageNamingWithDirectoriesHavingSameContentsButDifferentNames()
      throws Exception {
    File tmpDirectory1 = tmpFolder.newFolder("folder1", "folderA");
    tmpFolder.newFolder("folder1", "folderA", "uniqueName1");
    DataflowPackage target1 = makePackageAttributes(tmpDirectory1, null).getDataflowPackage();

    File tmpDirectory2 = tmpFolder.newFolder("folder2", "folderA");
    tmpFolder.newFolder("folder2", "folderA", "uniqueName2");
    DataflowPackage target2 = makePackageAttributes(tmpDirectory2, null).getDataflowPackage();

    assertNotEquals(target1.getName(), target2.getName());
    assertNotEquals(target1.getLocation(), target2.getLocation());
  }

  @Test
  public void testPackageUploadWithLargeClasspathLogsWarning() throws Exception {
    File tmpFile = makeFileWithContents("file.txt", "This is a test!");
    // all files will be present and cached so no upload needed.
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(tmpFile.length());

    List<String> classpathElements = Lists.newLinkedList();
    for (int i = 0; i < 1005; ++i) {
      String eltName = "element" + i;
      classpathElements.add(eltName + '=' + tmpFile.getAbsolutePath());
    }

    PackageUtil.stageClasspathElements(classpathElements, STAGING_PATH, mockGcsUtil);

    logged.verifyWarn("Your classpath contains 1005 elements, which Google Cloud Dataflow");
  }

  @Test
  public void testPackageUploadWithFileSucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    String contents = "This is a test!";
    File tmpFile = makeFileWithContents("file.txt", contents);
    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    List<DataflowPackage> targets = PackageUtil.stageClasspathElements(
        ImmutableList.of(tmpFile.getAbsolutePath()), STAGING_PATH, mockGcsUtil);
    DataflowPackage target = Iterables.getOnlyElement(targets);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    assertThat(target.getName(), RegexMatcher.matches("file-" + HASH_PATTERN + ".txt"));
    assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName()));
    assertThat(new LineReader(Channels.newReader(pipe.source(), "UTF-8")).readLine(),
        equalTo(contents));
  }

  @Test
  public void testStagingPreservesClasspath() throws Exception {
    File smallFile = makeFileWithContents("small.txt", "small");
    File largeFile = makeFileWithContents("large.txt", "large contents");
    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString()))
        .thenAnswer(new Answer<SinkChannel>() {
          @Override
          public SinkChannel answer(InvocationOnMock invocation) throws Throwable {
            return Pipe.open().sink();
          }
        });

    List<DataflowPackage> targets = PackageUtil.stageClasspathElements(
        ImmutableList.of(smallFile.getAbsolutePath(), largeFile.getAbsolutePath()),
        STAGING_PATH, mockGcsUtil);
    // Verify that the packages are returned small, then large, matching input order even though
    // the large file would be uploaded first.
    assertThat(targets.get(0).getName(), startsWith("small"));
    assertThat(targets.get(1).getName(), startsWith("large"));
  }

  @Test
  public void testPackageUploadWithDirectorySucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpDirectory = tmpFolder.newFolder("folder");
    tmpFolder.newFolder("folder", "empty_directory");
    tmpFolder.newFolder("folder", "directory");
    makeFileWithContents("folder/file.txt", "This is a test!");
    makeFileWithContents("folder/directory/file.txt", "This is also a test!");

    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    PackageUtil.stageClasspathElements(
        ImmutableList.of(tmpDirectory.getAbsolutePath()), STAGING_PATH, mockGcsUtil);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    ZipInputStream inputStream = new ZipInputStream(Channels.newInputStream(pipe.source()));
    List<String> zipEntryNames = new ArrayList<>();
    for (ZipEntry entry = inputStream.getNextEntry(); entry != null;
        entry = inputStream.getNextEntry()) {
      zipEntryNames.add(entry.getName());
    }

    assertThat(zipEntryNames,
        containsInAnyOrder("directory/file.txt", "empty_directory/", "file.txt"));
  }

  @Test
  public void testPackageUploadWithEmptyDirectorySucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpDirectory = tmpFolder.newFolder("folder");

    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    List<DataflowPackage> targets = PackageUtil.stageClasspathElements(
        ImmutableList.of(tmpDirectory.getAbsolutePath()), STAGING_PATH, mockGcsUtil);
    DataflowPackage target = Iterables.getOnlyElement(targets);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    assertThat(target.getName(), RegexMatcher.matches("folder-" + HASH_PATTERN + ".jar"));
    assertThat(target.getLocation(), equalTo(STAGING_PATH + '/' + target.getName()));
    assertNull(new ZipInputStream(Channels.newInputStream(pipe.source())).getNextEntry());
  }

  @Test(expected = RuntimeException.class)
  public void testPackageUploadFailsWhenIOExceptionThrown() throws Exception {
    File tmpFile = makeFileWithContents("file.txt", "This is a test!");
    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString()))
        .thenThrow(new IOException("Fake Exception: Upload error"));

    try {
      PackageUtil.stageClasspathElements(
          ImmutableList.of(tmpFile.getAbsolutePath()),
          STAGING_PATH, fastNanoClockAndSleeper, MoreExecutors.newDirectExecutorService(),
          mockGcsUtil);
    } finally {
      verify(mockGcsUtil).fileSize(any(GcsPath.class));
      verify(mockGcsUtil, times(5)).create(any(GcsPath.class), anyString());
      verifyNoMoreInteractions(mockGcsUtil);
    }
  }

  @Test
  public void testPackageUploadFailsWithPermissionsErrorGivesDetailedMessage() throws Exception {
    File tmpFile = makeFileWithContents("file.txt", "This is a test!");
    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString()))
        .thenThrow(new IOException("Failed to write to GCS path " + STAGING_PATH,
            googleJsonResponseException(
                HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Permission denied", "Test message")));

    try {
      PackageUtil.stageClasspathElements(
          ImmutableList.of(tmpFile.getAbsolutePath()),
          STAGING_PATH, fastNanoClockAndSleeper, MoreExecutors.newDirectExecutorService(),
          mockGcsUtil);
      fail("Expected RuntimeException");
    } catch (RuntimeException e) {
      assertThat("Expected RuntimeException wrapping IOException.",
          e.getCause(), instanceOf(RuntimeException.class));
      assertThat("Expected IOException containing detailed message.",
          e.getCause().getCause(), instanceOf(IOException.class));
      assertThat(e.getCause().getCause().getMessage(),
          Matchers.allOf(
              Matchers.containsString("Uploaded failed due to permissions error"),
              Matchers.containsString(
                  "Stale credentials can be resolved by executing 'gcloud auth application-default "
                      + "login'")));
    } finally {
      verify(mockGcsUtil).fileSize(any(GcsPath.class));
      verify(mockGcsUtil).create(any(GcsPath.class), anyString());
      verifyNoMoreInteractions(mockGcsUtil);
    }
  }

  @Test
  public void testPackageUploadEventuallySucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpFile = makeFileWithContents("file.txt", "This is a test!");
    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString()))
        .thenThrow(new IOException("Fake Exception: 410 Gone")) // First attempt fails
        .thenReturn(pipe.sink());                               // second attempt succeeds

    try {
      PackageUtil.stageClasspathElements(
          ImmutableList.of(tmpFile.getAbsolutePath()), STAGING_PATH, fastNanoClockAndSleeper,
          MoreExecutors.newDirectExecutorService(), mockGcsUtil);
    } finally {
      verify(mockGcsUtil).fileSize(any(GcsPath.class));
      verify(mockGcsUtil, times(2)).create(any(GcsPath.class), anyString());
      verifyNoMoreInteractions(mockGcsUtil);
    }
  }

  @Test
  public void testPackageUploadIsSkippedWhenFileAlreadyExists() throws Exception {
    File tmpFile = makeFileWithContents("file.txt", "This is a test!");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(tmpFile.length());

    PackageUtil.stageClasspathElements(
        ImmutableList.of(tmpFile.getAbsolutePath()), STAGING_PATH, mockGcsUtil);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verifyNoMoreInteractions(mockGcsUtil);
  }

  @Test
  public void testPackageUploadIsNotSkippedWhenSizesAreDifferent() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpDirectory = tmpFolder.newFolder("folder");
    tmpFolder.newFolder("folder", "empty_directory");
    tmpFolder.newFolder("folder", "directory");
    makeFileWithContents("folder/file.txt", "This is a test!");
    makeFileWithContents("folder/directory/file.txt", "This is also a test!");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(Long.MAX_VALUE);
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    PackageUtil.stageClasspathElements(
        ImmutableList.of(tmpDirectory.getAbsolutePath()), STAGING_PATH, mockGcsUtil);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);
  }

  @Test
  public void testPackageUploadWithExplicitPackageName() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpFile = makeFileWithContents("file.txt", "This is a test!");
    final String overriddenName = "alias.txt";

    when(mockGcsUtil.fileSize(any(GcsPath.class)))
        .thenThrow(new FileNotFoundException("some/path"));
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    List<DataflowPackage> targets = PackageUtil.stageClasspathElements(
        ImmutableList.of(overriddenName + "=" + tmpFile.getAbsolutePath()), STAGING_PATH,
        mockGcsUtil);
    DataflowPackage target = Iterables.getOnlyElement(targets);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    assertThat(target.getName(), equalTo(overriddenName));
    assertThat(target.getLocation(),
        RegexMatcher.matches(STAGING_PATH + "/file-" + HASH_PATTERN + ".txt"));
  }

  @Test
  public void testPackageUploadIsSkippedWithNonExistentResource() throws Exception {
    String nonExistentFile =
        IOChannelUtils.resolve(tmpFolder.getRoot().getPath(), "non-existent-file");
    assertEquals(Collections.EMPTY_LIST, PackageUtil.stageClasspathElements(
        ImmutableList.of(nonExistentFile), STAGING_PATH, mockGcsUtil));
  }

  /**
   * Builds a fake GoogleJsonResponseException for testing API error handling.
   */
  private static GoogleJsonResponseException googleJsonResponseException(
      final int status, final String reason, final String message) throws IOException {
    final JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport = new MockHttpTransport() {
      @Override
      public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setReason(reason);
        errorInfo.setMessage(message);
        errorInfo.setFactory(jsonFactory);
        GenericJson error = new GenericJson();
        error.set("code", status);
        error.set("errors", Arrays.asList(errorInfo));
        error.setFactory(jsonFactory);
        GenericJson errorResponse = new GenericJson();
        errorResponse.set("error", error);
        errorResponse.setFactory(jsonFactory);
        return new MockLowLevelHttpRequest().setResponse(
            new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString())
            .setContentType(Json.MEDIA_TYPE).setStatusCode(status));
        }
    };
    HttpRequest request =
        transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    return GoogleJsonResponseException.from(jsonFactory, response);
  }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis
{
    internal struct SymbolKeyResolution
    {
        private readonly ISymbol _symbol;
        private readonly ImmutableArray<ISymbol> _candidateSymbols;
        private readonly CandidateReason _candidateReason;

        internal SymbolKeyResolution(ISymbol symbol) : this()
        {
            _symbol = symbol;
            _candidateSymbols = ImmutableArray<ISymbol>.Empty;
            _candidateReason = CandidateReason.None;
        }

        internal SymbolKeyResolution(ImmutableArray<ISymbol> candidateSymbols, CandidateReason candidateReason)
        {
            _symbol = null;
            _candidateSymbols = candidateSymbols;
            _candidateReason = candidateReason;
        }

        public ISymbol Symbol => _symbol;

        public ImmutableArray<ISymbol> CandidateSymbols
        {
            get { return _candidateSymbols.NullToEmpty(); }
        }

        public CandidateReason CandidateReason => _candidateReason;
    }
}


text:
require 'helper'

class TestAssertions < Test::Unit::TestCase
  def setup
    @assertable = Object.new
    @assertable.send(:extend, Test::Right::Assertions)
  end

  def test_assert
    assert_raises Test::Right::AssertionFailedError do
      x = Object.new
      x.send(:extend, Test::Right::Assertions)
      x.assert(0.1) {
        false
      }
    end

    assert_nothing_raised do
      x = Object.new
      x.send(:extend, Test::Right::Assertions)
      x.assert {
        true
      }
    end

    assert_raises ArgumentError do
      @assertable.assert true
    end
  end

  def test_ignores_missing_widget
    raised = false
    @assertable.assert {
      if raised
        true
      else
        raised = true
        raise Test::Right::WidgetNotPresentError
      end
    }
  end

  def test_spinassert
    assert_nothing_raised do
      x = Object.new
      y = false
      x.send(:extend, Test::Right::Assertions)
      t = Thread.new do
        sleep(1)
        y = true
      end
      x.assert {
        y
      }
    end

    assert_raises Test::Right::AssertionFailedError do
      x = Object.new
      y = false
      x.send(:extend, Test::Right::Assertions)
      x.assert(1) {
        y
      }
    end
  end

  def test_assert_equal
    assert_nothing_raised do
      @assertable.assert_equal 1, 1
    end
    assert_raises Test::Right::AssertionFailedError do
      @assertable.assert_equal 1, 2
    end
  end

  def test_assert_equal_on_value
    x = 1
    v = Test::Right::Value.new do
      x
    end

    Thread.new do
      sleep 0.5
      x = 2
    end

    assert_nothing_raised do
      @assertable.assert_equal 1, v
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US" />
  <App xmlns="" ProductID="{040f345e-8b65-4e4e-a962-fbc5d72041f7}" Title="Toolbox.WinPhone" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="Toolbox.WinPhone author" Description="Sample description" Publisher="Toolbox.WinPhone" PublisherID="{8f272097-0e40-4762-84da-73bd2dd9c893}">
    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="PhoneApp1Token" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
          <Title>Toolbox.WinPhone</Title>
          <BackContent></BackContent>
          <BackBackgroundImageURI></BackBackgroundImageURI>
          <BackTitle></BackTitle>
          <DeviceLockImageURI></DeviceLockImageURI>
          <HasLarge></HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
  </App>
</Deployment>
<!-- WPSDK Version 8.0.9900 -->


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 3856 $ -->
<!-- EN-Revision: 3827 Maintainer: takagi Status: ready -->
<!-- CREDITS: mat-sh,daichi,joe -->
     <sect1 id="variable.trusted.dir">
      <title>$trusted_dir</title>
      <para>
  <parameter>$trusted_dir</parameter> は、
  セキュリティが有効な場合にのみ使用します。これは、
  信用がおけると考えられる全ディレクトリパスの配列です。
  信用がおけるディレクトリには、テンプレートから
  <link linkend="language.function.include.php"><varname>{include_php}</varname></link>
  によって直接実行される PHP スクリプトを置きます。
      </para>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->