text:
package com.intellij.openapi.vcs.changes;

import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import com.intellij.util.ThreeState;
import com.intellij.util.continuation.ContinuationPause;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.File;
import java.util.Collection;
import java.util.List;

/**
 * @author max
 */
public abstract class ChangeListManager implements ChangeListModification {
  public static ChangeListManager getInstance(Project project) {
    return PeriodicalTasksCloser.getInstance().safeGetComponent(project, ChangeListManager.class);
  }

  public abstract void scheduleUpdate();
  public abstract void scheduleUpdate(boolean updateUnversionedFiles);
  public abstract void invokeAfterUpdate(final Runnable afterUpdate, final InvokeAfterUpdateMode mode, final String title,
                                         final ModalityState state);
  public abstract void invokeAfterUpdate(final Runnable afterUpdate, final InvokeAfterUpdateMode mode, final String title,
                                         final Consumer<VcsDirtyScopeManager> dirtyScopeManager,
                                         final ModalityState state);
  @TestOnly
  public abstract boolean ensureUpToDate(boolean canBeCanceled);

  public abstract int getChangeListsNumber();
  public abstract List<LocalChangeList> getChangeListsCopy();
  @NotNull
  public abstract List<LocalChangeList> getChangeLists();

  public abstract List<File> getAffectedPaths();
  @NotNull
  public abstract List<VirtualFile> getAffectedFiles();
  public abstract boolean isFileAffected(final VirtualFile file);

  /**
   * @return all changes in all changelists.
   */
  @NotNull
  public abstract Collection<Change> getAllChanges();

  @Nullable
  public abstract LocalChangeList findChangeList(final String name);
  @Nullable
  public abstract LocalChangeList getChangeList(String id);
//  public abstract LocalChangeList addChangeList(@NotNull String name, final String comment);
//  public abstract void setDefaultChangeList(@NotNull LocalChangeList list);

  /**
   * Returns currently active changelist
   * @return active changelist
   */
  public abstract LocalChangeList getDefaultChangeList();

  public abstract boolean isDefaultChangeList(ChangeList list);

  @Nullable
  public abstract LocalChangeList getChangeList(@NotNull Change change);

  @Nullable
  public abstract String getChangeListNameIfOnlyOne(Change[] changes);

  @NotNull
  public abstract Runnable prepareForChangeDeletion(final Collection<Change> changes);

  @Nullable
  public abstract Change getChange(@NotNull VirtualFile file);

  @Nullable
  public abstract LocalChangeList getChangeList(@NotNull VirtualFile file);

  @Nullable
  public abstract Change getChange(FilePath file);

  public abstract boolean isUnversioned(VirtualFile file);

  @NotNull
  public abstract FileStatus getStatus(VirtualFile file);

  @NotNull
  public abstract Collection<Change> getChangesIn(VirtualFile dir);

  @NotNull
  public abstract Collection<Change> getChangesIn(FilePath path);

//  public abstract void removeChangeList(final LocalChangeList list);

//  public abstract void moveChangesTo(final LocalChangeList list, final Change[] changes);

  public abstract void addChangeListListener(ChangeListListener listener);
  public abstract void removeChangeListListener(ChangeListListener listener);

  public abstract void registerCommitExecutor(CommitExecutor executor);

  public abstract void commitChanges(LocalChangeList changeList, List<Change> changes);

  public abstract void commitChangesSynchronously(LocalChangeList changeList, List<Change> changes);

  /**
   * @return if commit successful
   */
  public abstract boolean commitChangesSynchronouslyWithResult(LocalChangeList changeList, List<Change> changes);

  public abstract void reopenFiles(List<FilePath> paths);

  public abstract List<CommitExecutor> getRegisteredExecutors();

  public abstract void addFilesToIgnore(final IgnoredFileBean... ignoredFiles);
  public abstract void addDirectoryToIgnoreImplicitly(@NotNull String path);
  public abstract void setFilesToIgnore(final IgnoredFileBean... ignoredFiles);
  public abstract IgnoredFileBean[] getFilesToIgnore();
  public abstract boolean isIgnoredFile(@NotNull VirtualFile file);

  @Nullable
  public abstract String getSwitchedBranch(VirtualFile file);
  public abstract String getDefaultListName();
  public abstract void freeze(final ContinuationPause context, String reason);
  public abstract void letGo();
  public abstract String isFreezed();
  public abstract boolean isFreezedWithNotification(@Nullable String modalTitle);

  public static boolean isFileChanged(final Project project, final VirtualFile vf) {
    FileStatus status = getInstance(project).getStatus(vf);
    if (FileStatus.NOT_CHANGED.equals(status) || FileStatus.UNKNOWN.equals(status) || FileStatus.IGNORED.equals(status)) {
      return false;
    }
    return true;
  }

  public abstract List<VirtualFile> getModifiedWithoutEditing();

  @NotNull
  public abstract ThreeState haveChangesUnder(@NotNull VirtualFile vf);
}


text:
namespace System.Drawing.Imaging
{
    public sealed class FrameDimension
    {
        // Frame dimension GUIDs, from sdkinc\imgguids.h
        private static FrameDimension s_time = new FrameDimension(new Guid("{6aedbd6d-3fb5-418a-83a6-7f45229dc872}"));
        private static FrameDimension s_resolution = new FrameDimension(new Guid("{84236f7b-3bd3-428f-8dab-4ea1439ca315}"));
        private static FrameDimension s_page = new FrameDimension(new Guid("{7462dc86-6180-4c7e-8e3f-ee7333a7a483}"));

        private Guid _guid;

        /// <summary>
        /// Initializes a new instance of the <see cref='FrameDimension'/> class with the specified GUID.
        /// </summary>
        public FrameDimension(Guid guid)
        {
            _guid = guid;
        }

        /// <summary>
        /// Specifies a global unique identifier (GUID) that represents this <see cref='FrameDimension'/>.
        /// </summary>
        public Guid Guid
        {
            get { return _guid; }
        }

        /// <summary>
        /// The time dimension.
        /// </summary>
        public static FrameDimension Time
        {
            get { return s_time; }
        }

        /// <summary>
        /// The resolution dimension.
        /// </summary>
        public static FrameDimension Resolution
        {
            get { return s_resolution; }
        }

        /// <summary>
        /// The page dimension.
        /// </summary>
        public static FrameDimension Page
        {
            get { return s_page; }
        }
        /// <summary>
        /// Returns a value indicating whether the specified object is an <see cref='FrameDimension'/> equivalent to
        /// this <see cref='FrameDimension'/>.
        /// </summary>
        public override bool Equals(object o)
        {
            FrameDimension format = o as FrameDimension;
            if (format == null)
                return false;
            return _guid == format._guid;
        }

        public override int GetHashCode()
        {
            return _guid.GetHashCode();
        }

        /// <summary>
        /// Converts this <see cref='FrameDimension'/> to a human-readable string.
        /// </summary>
        public override string ToString()
        {
            if (this == s_time) return "Time";
            if (this == s_resolution) return "Resolution";
            if (this == s_page) return "Page";
            return "[FrameDimension: " + _guid + "]";
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var settings = require('../../settings.js');
var randomHex = require('random-hex');
const discord = require ('discord.js');
const yt = require('ytdl-core');

exports.run = (client, msg) => {
		var randomID = settings.getRandomInt(1, 32);
		var totalPhrases = 16;
				if (!msg.member.voiceChannel) {
					msg.reply(`Please be in a voice channel first!`);
				} else {
					var streamURL;
					if (msg.content.startsWith('!anythinggoes')){
							streamURL = '8VcjbO9OJCs';
							msg.reply('Anything goes. [1/'+totalPhrases+']');

					} else if (msg.content.startsWith('!livemore')){
							streamURL = '4Ni5QCpSkyk';
							msg.reply('Just Live More. [2/'+totalPhrases+']');

					} else if (msg.content.startsWith('!journey')){
							streamURL = 'PQoE_PEoFvM';
							msg.reply('You should take a Journey through the Decade. [3/'+totalPhrases+']');

					} else if (msg.content.startsWith('!allyouneed')){
							streamURL = 'AB1d0cnjOzM';
							msg.reply('All you need is Drive. [4/'+totalPhrases+']');

					} else if (msg.content.startsWith('!kita')){
							streamURL = 'GqKsFfxV0sE';
							msg.reply('UCHU KITAAAAAAAAAAA!\n....\nsorry...it\'s just...space is awesome...[5/'+totalPhrases+']');

					} else if (msg.content.startsWith('!firedup')){
							streamURL = '1Hqc_AMorug';
							msg.reply('Try getting fired up! [6/'+totalPhrases+']');

					} else if (msg.content.startsWith('!nobodysperfect')){
							streamURL = '8sGp16E6ySs';
							msg.reply('Nobody\'s Perfect. [7/'+totalPhrases+']');

					} else if (msg.content.startsWith('!castoff')){
							streamURL = 'ONZzHkT1nWA';
							msg.reply('I think it\'s time you CAST OFF that mask of yours. [8/'+totalPhrases+']');

					} else if (msg.content.startsWith('!gottabelive')){
							streamURL = 'gBTZxHnvcu4';
							msg.reply('You gotta belive. [9/'+totalPhrases+']');

					} else if (msg.content.startsWith('!excited')){
							streamURL = 'gBTZxHnvcu4';
							msg.reply('Get EXCITE...ed. [10/'+totalPhrases+']');

					} else if (msg.content.startsWith('!nofear')){
							streamURL = 'v0j46L2HE8A';
							msg.reply('No fear, no pain. [11/'+totalPhrases+']');

					} else if (msg.content.startsWith('!morphintime')){
							streamURL = '9wBid6HlGL8';
							msg.reply('It\'s morphin\' time. [12/'+totalPhrases+']');

					} else if (msg.content.startsWith('!breakthechain')){
							streamURL = 'mqdS8Ocqhik';
							msg.reply('Break the chain. [13/'+totalPhrases+']');

					} else if (msg.content.startsWith('!thereforweare')){
							streamURL = 'GX8HVXzV1E0';
							msg.reply('We think therefore we are. [14/'+totalPhrases+']');

					} else if (msg.content.startsWith('!mask')){
							streamURL = '0PAJPKYgd8A';
							msg.reply('Who needs a mask? [15/'+totalPhrases+']');

					} else if (msg.content.startsWith('!itsshowtime')){
							streamURL = '99Y8iXO-FhI';
							msg.reply('Life is showtime [16/'+totalPhrases+']');

					} else {
						if ((randomID == 1) || (randomID == 32)){
								streamURL = '8VcjbO9OJCs';
								msg.reply('Anything goes. [1/'+totalPhrases+']');

						} else if ((randomID == 3) || (randomID == 30)){
								streamURL = '4Ni5QCpSkyk';
								msg.reply('Just Live More. [2/'+totalPhrases+']');

						} else if ((randomID == 5) || (randomID == 28)){
								streamURL = 'PQoE_PEoFvM';
								msg.reply('You should take a Journey through the Decade. [3/'+totalPhrases+']');

						} else if ((randomID == 7) || (randomID == 26)){
								streamURL = 'AB1d0cnjOzM';
								msg.reply('All you need is Drive. [4/'+totalPhrases+']');

						} else if ((randomID == 9) || (randomID == 24)){
								streamURL = 'GqKsFfxV0sE';
								msg.reply('UCHU KITAAAAAAAAAAA!\n....\nsorry...it\'s just...space is awesome...[5/'+totalPhrases+']');

						} else if ((randomID == 11) || (randomID == 22)){
								streamURL = '1Hqc_AMorug';
								msg.reply('Try getting fired up! [6/'+totalPhrases+']');

						} else if ((randomID == 13) || (randomID == 20)){
								streamURL = '8sGp16E6ySs';
								msg.reply('Nobody\'s Perfect. [7/'+totalPhrases+']');

						} else if ((randomID == 15) || (randomID == 18)){
								streamURL = 'ONZzHkT1nWA';
								msg.reply('I think it\'s time you CAST OFF that mask of yours. [8/'+totalPhrases+']');

						} else if ((randomID == 17) || (randomID == 16)){
								streamURL = 'gBTZxHnvcu4';
								msg.reply('You gotta belive. [9/'+totalPhrases+']');

						} else if ((randomID == 19) || (randomID == 14)){
								streamURL = 'gBTZxHnvcu4';
								msg.reply('Get EXCITE...ed. [10/'+totalPhrases+']');

						} else if ((randomID == 21) || (randomID == 12)){
								streamURL = 'v0j46L2HE8A';
								msg.reply('No fear, no pain. [11/'+totalPhrases+']');

						} else if ((randomID == 23) || (randomID == 10)){
								streamURL = '9wBid6HlGL8';
								msg.reply('It\'s morphin\' time. [12/'+totalPhrases+']');

						} else if ((randomID == 25) || (randomID == 8)){
								streamURL = 'mqdS8Ocqhik';
								msg.reply('Break the chain. [13/'+totalPhrases+']');

						} else if ((randomID == 27) || (randomID == 6)){
								streamURL = 'GX8HVXzV1E0';
								msg.reply('We think therefore we are. [14/'+totalPhrases+']');

						} else if ((randomID == 29) || (randomID == 4)){
								streamURL = '0PAJPKYgd8A';
								msg.reply('Who needs a mask? [15/'+totalPhrases+']');

						} else if ((randomID == 31) || (randomID == 2)){
								streamURL = '99Y8iXO-FhI';
								msg.reply('Life is showtime [16/'+totalPhrases+']');
						}//end if random number
					}//end if one of the direct calls
					settings.voiceChannel = msg.member.voiceChannel;
					streamURL = "https://www.youtube.com/watch?v="+streamURL
					PlayAudio(streamURL, settings.voiceChannel);
					settings.array.push(streamURL);
					msg.reply(streamURL);
				};//if (!msg.member.voiceChannel)
};//run

exports.conf = {
  enabled: true,
  runIn: ["text"],
  aliases: ['anythinggoes', 'livemore', 'journey', 'allyouneed',
  'firedup', 'kita', 'nobodysperfect', 'castoff', 'gottabelive',
  'excited', 'nofear', 'morphintime', 'breakthechain', 'thereforweare',
  'mask', 'itsshowtime'],
  permLevel: 0,
  botPerms: [],
  requiredFuncs: []
};

exports.help = {
  name: "advice",
  description: "",
  usage: "",
  usageDelim: ""
//  extendedHelp: "";
};

function PlayAudio(tubelink, voice) {
    if (settings.botTalking == 0){
		  settings.botTalking = 1;
		voice.join()
		.then(connnection => {
			let stream = yt(tubelink, {audioonly: true});
			const dispatcher = connnection.playStream(stream);
			dispatcher.on('end', () => {
			settings.botTalking = 0;
			settings.array.splice(0, 1);
			});//dispatcher
		});//then connection
	}//if
}//function


text:
namespace MailChimp.Api.Net.Enum
{
  public enum TargetTypes
  {
    reports,
    templates,
    campaigns,
    conversations,
    automations,
    lists,
    campaign_folders,
    batches,
    template_folders
  }
}


text:
#ifndef itkVotingBinaryHoleFillingImageFilter_h
#define itkVotingBinaryHoleFillingImageFilter_h

#include "itkVotingBinaryImageFilter.h"
#include "itkArray.h"

namespace itk
{
/** \class VotingBinaryHoleFillingImageFilter
 * \brief Fills in holes and cavities by applying a voting operation on each pixel.
 *
 *
 * \sa Image
 * \sa VotingBinaryImageFilter
 * \sa VotingBinaryIterativeHoleFillingImageFilter
 * \sa Neighborhood
 * \sa NeighborhoodOperator
 * \sa NeighborhoodIterator
 *
 * \ingroup IntensityImageFilters
 * \ingroup ITKLabelVoting
 */
template< typename TInputImage, typename TOutputImage >
class ITK_TEMPLATE_EXPORT VotingBinaryHoleFillingImageFilter:
  public VotingBinaryImageFilter< TInputImage, TOutputImage >
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(VotingBinaryHoleFillingImageFilter);

  /** Extract dimension from input and output image. */
  static constexpr unsigned int InputImageDimension = TInputImage::ImageDimension;
  static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension;

  /** Convenient type alias for simplifying declarations. */
  using InputImageType = TInputImage;
  using OutputImageType = TOutputImage;

  /** Standard class type aliases. */
  using Self = VotingBinaryHoleFillingImageFilter;
  using Superclass = VotingBinaryImageFilter< InputImageType, OutputImageType >;
  using Pointer = SmartPointer< Self >;
  using ConstPointer = SmartPointer< const Self >;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(VotingBinaryHoleFillingImageFilter, VotingBinaryImageFilter);

  /** Image type alias support */
  using InputPixelType = typename InputImageType::PixelType;
  using OutputPixelType = typename OutputImageType::PixelType;

  using InputImageRegionType = typename InputImageType::RegionType;
  using OutputImageRegionType = typename OutputImageType::RegionType;

  using InputSizeType = typename InputImageType::SizeType;
  using SizeValueType = typename InputImageType::SizeValueType;

  /** Majority threshold. It is the number of pixels over 50% that will decide
   * whether an OFF pixel will become ON or not. For example, if the
   * neighborhood of a pixel has 124 pixels (excluding itself), the 50% will be
   * 62, and if you set upd a Majority threshold of 5, that means that the
   * filter will require 67 or more neighbor pixels to be ON in order to switch
   * the current OFF pixel to ON. The default value is 1. */
  itkGetConstReferenceMacro(MajorityThreshold, unsigned int);
  itkSetMacro(MajorityThreshold, unsigned int);

  /** Returns the number of pixels that changed when the filter was executed. */
  itkGetConstReferenceMacro(NumberOfPixelsChanged, SizeValueType);

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
  itkConceptMacro( IntConvertibleToInputCheck,
                   ( Concept::Convertible< int, InputPixelType > ) );
  itkConceptMacro( UnsignedIntConvertibleToInputCheck,
                   ( Concept::Convertible< unsigned int, InputPixelType > ) );
  // End concept checking
#endif

protected:
  VotingBinaryHoleFillingImageFilter();
  ~VotingBinaryHoleFillingImageFilter() override = default;
  void PrintSelf(std::ostream & os, Indent indent) const override;

  /** Make protected the methods SetBirthThreshold() and
   * SetSurvivalThreshold() so users of this filter do not have access to
   * them. */
  void SetBirthThreshold(const unsigned int value) override
  { this->Superclass::SetBirthThreshold(value);  }
  void SetSurvivalThreshold(const unsigned int value) override
  { this->Superclass::SetSurvivalThreshold(value);  }

  /** VotingBinaryHoleFillingImageFilter can be implemented as a multithreaded filter.
   * Therefore, this implementation provides a ThreadedGenerateData()
   * routine which is called for each processing thread. The output
   * image data is allocated automatically by the superclass prior to
   * calling ThreadedGenerateData().  ThreadedGenerateData can only
   * write to the portion of the output image specified by the
   * parameter "outputRegionForThread"
   *
   * \sa ImageToImageFilter::ThreadedGenerateData(),
   *     ImageToImageFilter::GenerateData() */
  void ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread,
                            ThreadIdType threadId) override;

  void DynamicThreadedGenerateData( const OutputImageRegionType & ) override
  {
    itkExceptionMacro("This class requires threadId so it must use classic multi-threading model");
  }

  /** Methods to be called before and after the invokation of
   * ThreadedGenerateData(). */
  void BeforeThreadedGenerateData() override;

  void AfterThreadedGenerateData() override;

private:
  unsigned int m_MajorityThreshold;

  SizeValueType m_NumberOfPixelsChanged;

  // Auxiliary array for multi-threading
  Array< SizeValueType > m_Count;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkVotingBinaryHoleFillingImageFilter.hxx"
#endif

#endif


text:
package com.asha.nightowllib.handler;

import android.view.View;

import com.asha.nightowllib.handler.ISkinHandler;
import com.asha.nightowllib.handler.annotations.OwlHandle;

import java.util.HashMap;

import static com.asha.nightowllib.NightOwlUtil.newInstanceSafely;

/**
 * Created by hzqiujiadi on 15/11/8.
 * hzqiujiadi ashqalcn@gmail.com
 */
public class OwlHandlerManager {
    private static HashMap<Class,ISkinHandler> sHandlers = new HashMap<>();
    private static HashMap<Class,Class<? extends ISkinHandler>> sHandlerTable = new HashMap<>();

    // TODO: 15/11/5 impl it later.
    private static Class<ISkinHandler> generateHandler() {
        return null;
    }

    public static void registerView(Class<? extends View> clz){
        sHandlerTable.put(clz, generateHandler());
    }

    public static void registerHandler(Class key, Class<? extends ISkinHandler> clz){
        sHandlerTable.put(key,clz);
    }

    public static void registerHandler(Class<? extends ISkinHandler> clz){
        OwlHandle owlHandle = clz.getAnnotation(OwlHandle.class);
        if ( owlHandle != null ){
            Class<? extends View>[] keys = owlHandle.value();
            for ( Class<? extends View> key : keys )
                registerHandler(key,clz);
        }
    }

    public static ISkinHandler queryHandler(Class clz) {
        Class<? extends ISkinHandler> handlerClz = sHandlerTable.get(clz);
        // if handlerClz == null
        // look for superclass's handlerClz
        // it will be end when meet View.class
        while( handlerClz == null ){
            clz = clz.getSuperclass();
            handlerClz = sHandlerTable.get(clz);
        }
        // query handler now
        ISkinHandler skinHandler = sHandlers.get(handlerClz);
        if ( skinHandler == null ) {
            skinHandler = newInstanceSafely(handlerClz);
            sHandlers.put(handlerClz, skinHandler);
        }
        return skinHandler;
    }

}


text:
<?php

declare(strict_types=1);

namespace VonageTest\Application;

use DateTime;
use Exception;
use Laminas\Diactoros\Request;
use Laminas\Diactoros\Response;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Vonage\Application\Application;
use Vonage\Application\Client as ApplicationClient;
use Vonage\Application\Filter;
use Vonage\Application\MessagesConfig;
use Vonage\Application\RtcConfig;
use Vonage\Application\VoiceConfig;
use Vonage\Client;
use Vonage\Client\APIResource;
use Vonage\Client\Exception\Exception as ClientException;
use Vonage\Client\Exception\Server as ServerException;
use Vonage\Entity\Filter\EmptyFilter;
use VonageTest\Psr7AssertionTrait;

use function fopen;
use function is_null;
use function json_decode;
use function substr;

class ClientTest extends TestCase
{
    use Psr7AssertionTrait;

    protected $vonageClient;

    /**
     * @var APIResource
     */
    protected $apiClient;

    /**
     * @var ApplicationClient
     */
    protected $applicationClient;

    public function setUp(): void
    {
        $this->vonageClient = $this->prophesize(Client::class);
        $this->vonageClient->getApiUrl()->willReturn('http://api.nexmo.com');

        $this->applicationClient = new ApplicationClient();
        /** @noinspection PhpParamsInspection */
        $this->applicationClient->setClient($this->vonageClient->reveal());
    }

    public function testSizeException(): void
    {
        $this->expectException('RuntimeException');
        $this->applicationClient->getSize();
    }

    /**
     * @throws ClientException
     * @throws ClientExceptionInterface
     * @throws Client\Exception\Request
     * @throws ServerException
     */
    public function testSetFilter(): void
    {
        $filter = new Filter(new DateTime('yesterday'), new DateTime('tomorrow'));

        $this->vonageClient->send(Argument::that(function (RequestInterface $request) use ($filter) {
            $this->assertEquals('/v2/applications', $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('GET', $request->getMethod());

            foreach ($filter->getQuery() as $key => $value) {
                $this->assertRequestQueryContains($key, $value, $request);
            }

            return true;
        }))->shouldBeCalledTimes(1)->willReturn($this->getResponse('list'));

        $this->assertInstanceOf(EmptyFilter::class, $this->applicationClient->getFilter());
        $this->assertSame($this->applicationClient, $this->applicationClient->setFilter($filter));
        $this->assertSame($filter, $this->applicationClient->getFilter());

        $this->applicationClient->rewind();
    }

    /**
     * @throws ClientExceptionInterface
     * @throws Client\Exception\Request
     * @throws ClientException
     * @throws ServerException
     */
    public function testSetPage(): void
    {
        $this->vonageClient->send(Argument::that(function (RequestInterface $request) {
            $this->assertEquals('/v2/applications', $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('GET', $request->getMethod());
            $this->assertRequestQueryContains('page_index', '1', $request);
            return true;
        }))->shouldBeCalledTimes(1)->willReturn($this->getResponse('list'));

        $this->assertSame($this->applicationClient, $this->applicationClient->setPage(1));
        $this->assertEquals(1, $this->applicationClient->getPage());

        $this->applicationClient->rewind();
    }

    /**
     * @throws ClientExceptionInterface
     * @throws Client\Exception\Request
     * @throws ClientException
     * @throws ServerException
     */
    public function testSetSize(): void
    {
        $this->vonageClient->send(Argument::that(function (RequestInterface $request) {
            $this->assertEquals('/v2/applications', $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('GET', $request->getMethod());
            $this->assertRequestQueryContains('page_size', '5', $request);
            return true;
        }))->shouldBeCalledTimes(1)->willReturn($this->getResponse('list'));

        $this->assertSame($this->applicationClient, $this->applicationClient->setSize(5));
        $this->assertEquals(5, $this->applicationClient->getSize());

        $this->applicationClient->rewind();
    }

    /**
     * @throws ClientExceptionInterface
     * @throws Client\Exception\Request
     * @throws ClientException
     * @throws ServerException
     */
    public function testIterationProperties(): void
    {
        $this->vonageClient->send(Argument::type(RequestInterface::class))
            ->shouldBeCalledTimes(1)
            ->willReturn($this->getResponse('list'));

        $this->assertEquals(7, $this->applicationClient->count());
        $this->assertCount(7, $this->applicationClient);
        $this->assertEquals(2, $this->applicationClient->getPage());
        $this->assertEquals(3, $this->applicationClient->getSize());
    }

    public function testIteratePages(): void
    {
        $page = $this->getResponse('list');
        $last = $this->getResponse('last');

        $this->vonageClient->send(Argument::that(function (RequestInterface $request) {
            //a bit hacky here
            static $last;
            if (is_null($last)) { //first call
                $last = $request;
            }

            $this->assertEquals('/v2/applications', $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('GET', $request->getMethod());

            if ($last !== $request) { //second call
                $this->assertRequestQueryContains('page_size', '3', $request);
                $this->assertRequestQueryContains('page_index', '3', $request);
            }

            return true;
        }))->shouldBeCalledTimes(2)->willReturn($page, $last);

        foreach ($this->applicationClient as $id => $application) {
            $this->assertInstanceOf(Application::class, $application);
            $this->assertSame($application->getId(), $id);
        }
    }

    public function testCanIterateClient(): void
    {
        $this->vonageClient->send(Argument::that(function (RequestInterface $request) {
            $this->assertEquals('/v2/applications', $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('GET', $request->getMethod());
            return true;
        }))->shouldBeCalledTimes(1)->willReturn($this->getResponse('list'));

        $this->assertInstanceOf('Iterator', $this->applicationClient);

        $application = $id = null;

        /** @noinspection LoopWhichDoesNotLoopInspection */
        foreach ($this->applicationClient as $id => $application) {
            break;
        }

        $this->assertTrue(isset($application));
        $this->assertInstanceOf(Application::class, $application);
        $this->assertSame($application->getId(), $id);
    }

    /**
     * @dataProvider getApplication
     *
     * @param $payload
     * @param $id
     *
     * @throws ClientExceptionInterface
     * @throws ClientException
     * @throws Exception
     */
    public function testGetApplication($payload, $id): void
    {
        $this->vonageClient->send(Argument::that(function (RequestInterface $request) use ($id) {
            $this->assertEquals('/v2/applications/' . $id, $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('GET', $request->getMethod());
            return true;
        }))->willReturn($this->getResponse());

        $application = @$this->applicationClient->get($payload);
        $expectedData = json_decode($this->getResponse()->getBody()->getContents(), true);

        $this->assertInstanceOf(Application::class, $application);
        $this->assertSame($expectedData['id'], $application->getId());
        $this->assertSame($expectedData['name'], $application->getName());
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['answer_url']['address'],
            $application->getVoiceConfig()->getWebhook('answer_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['answer_url']['http_method'],
            $application->getVoiceConfig()->getWebhook('answer_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['event_url']['address'],
            $application->getVoiceConfig()->getWebhook('event_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['event_url']['http_method'],
            $application->getVoiceConfig()->getWebhook('event_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['inbound_url']['address'],
            $application->getMessagesConfig()->getWebhook('inbound_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['inbound_url']['http_method'],
            $application->getMessagesConfig()->getWebhook('inbound_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['status_url']['address'],
            $application->getMessagesConfig()->getWebhook('status_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['status_url']['http_method'],
            $application->getMessagesConfig()->getWebhook('status_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['rtc']['webhooks']['event_url']['address'],
            $application->getRtcConfig()->getWebhook('event_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['rtc']['webhooks']['event_url']['address'],
            $application->getRtcConfig()->getWebhook('event_url')->getUrl()
        );

        self::markTestIncomplete('Remove error suppression when object passing has been removed');
    }

    public function getApplication(): array
    {
        return [
            ['78d335fa323d01149c3dd6f0d48968cf', '78d335fa323d01149c3dd6f0d48968cf'],
            [new Application('78d335fa323d01149c3dd6f0d48968cf'), '78d335fa323d01149c3dd6f0d48968cf']
        ];
    }

    /**
     * @dataProvider updateApplication
     *
     * @param $payload
     * @param $method
     * @param $id
     * @param $expectedId
     */
    public function testUpdateApplication($payload, $method, $id, $expectedId): void
    {
        $this->vonageClient->send(Argument::that(function (RequestInterface $request) use ($expectedId) {
            $this->assertEquals('/v2/applications/' . $expectedId, $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('PUT', $request->getMethod());

            $this->assertRequestJsonBodyContains('name', 'My Application', $request);

            // And check all other capabilities
            $capabilities = [
                'voice' => [
                    'webhooks' => [
                        'answer_url' => [
                            'address' => 'https://example.com/webhooks/answer',
                            'http_method' => null

                        ],
                        'event_url' => [
                            'address' => 'https://example.com/webhooks/event',
                            'http_method' => null
                        ]
                    ]
                ],
                'rtc' => [
                    'webhooks' => [
                        'event_url' => [
                            'address' => 'https://example.com/webhooks/event',
                            'http_method' => null
                        ]
                    ]
                ],
            ];
            $this->assertRequestJsonBodyContains('capabilities', $capabilities, $request);

            return true;
        }))->willReturn($this->getResponse());

        if ($id) {
            $application = @$this->applicationClient->$method($payload, $id);
        } else {
            $application = @$this->applicationClient->$method($payload);
        }

        $expectedData = json_decode($this->getResponse()->getBody()->getContents(), true);

        $this->assertInstanceOf(Application::class, $application);
        $this->assertSame($expectedData['id'], $application->getId());
        $this->assertSame($expectedData['name'], $application->getName());
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['answer_url']['address'],
            $application->getVoiceConfig()->getWebhook('answer_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['answer_url']['http_method'],
            $application->getVoiceConfig()->getWebhook('answer_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['event_url']['address'],
            $application->getVoiceConfig()->getWebhook('event_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['event_url']['http_method'],
            $application->getVoiceConfig()->getWebhook('event_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['inbound_url']['address'],
            $application->getMessagesConfig()->getWebhook('inbound_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['inbound_url']['http_method'],
            $application->getMessagesConfig()->getWebhook('inbound_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['status_url']['address'],
            $application->getMessagesConfig()->getWebhook('status_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['status_url']['http_method'],
            $application->getMessagesConfig()->getWebhook('status_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['rtc']['webhooks']['event_url']['address'],
            $application->getRtcConfig()->getWebhook('event_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['rtc']['webhooks']['event_url']['address'],
            $application->getRtcConfig()->getWebhook('event_url')->getUrl()
        );

        @self::markTestIncomplete("Remove error suppression when object passing has been removed");
        @self::markTestIncomplete(
            "Rework this whole test, because it uses stock responses it's impossible to test in its current form"
        );
    }

    /**
     * @throws Exception
     *
     * @return array[]
     */
    public function updateApplication(): array
    {
        $id = '1a20a124-1775-412b-b623-e6985f4aace0';
        $copy = '1a20a124-1775-412b-4444-e6985f4aace0';
        $existing = new Application($id);
        $existing->setName('My Application');
        @$existing->getVoiceConfig()->setWebhook(VoiceConfig::ANSWER, 'https://example.com/webhooks/answer');
        @$existing->getVoiceConfig()->setWebhook(VoiceConfig::EVENT, 'https://example.com/webhooks/event');
        @$existing->getRtcConfig()->setWebhook(RtcConfig::EVENT, 'https://example.com/webhooks/event');

        $new = new Application();
        $new->setName('My Application');
        @$new->getVoiceConfig()->setWebhook(VoiceConfig::ANSWER, 'https://example.com/webhooks/answer');
        @$new->getVoiceConfig()->setWebhook(VoiceConfig::EVENT, 'https://example.com/webhooks/event');
        @$new->getRtcConfig()->setWebhook(RtcConfig::EVENT, 'https://example.com/webhooks/event');

        $raw = [
            'name' => 'My Application',
            'answer_url' => 'https://example.com/webhooks/answer',
            'event_url' => 'https://example.com/webhooks/event'
        ];

        return [
            //can send an application to update it
            [clone $existing, 'update', null, $id],
            //can send raw array and id
            [$raw, 'update', $id, $id],
            //one application overwrites another if id provided
            [clone $existing, 'update', $copy, $copy],
        ];
    }

    /**
     * @dataProvider deleteApplication
     *
     * @param $payload
     * @param $id
     *
     * @throws ClientExceptionInterface
     * @throws ClientException
     */
    public function testDeleteApplication($payload, $id): void
    {
        $this->vonageClient->send(Argument::that(function (Request $request) use ($id) {
            $this->assertEquals('/v2/applications/' . $id, $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('DELETE', $request->getMethod());
            return true;
        }))->willReturn(new Response('php://memory', 204));

        $this->assertTrue(@$this->applicationClient->delete($payload));
    }

    public function deleteApplication(): array
    {
        return [
            [new Application('abcd1234'), 'abcd1234'],
            ['abcd1234', 'abcd1234'],
        ];
    }

    /**
     * @dataProvider exceptions
     *
     * @param $method
     * @param $response
     * @param $code
     */
    public function testThrowsException($method, $response, $code): void
    {
        $response = $this->getResponse($response, $code);
        $this->vonageClient->send(Argument::type(RequestInterface::class))->willReturn($response);
        $application = new Application('78d335fa323d01149c3dd6f0d48968cf');

        try {
            @$this->applicationClient->$method($application);

            self::fail('did not throw exception');
        } catch (ClientException $e) {
            $response->getBody()->rewind();
            $data = json_decode($response->getBody()->getContents(), true);
            $class = substr((string)$code, 0, 1);

            $msg = $data['title'];
            if ($data['detail']) {
                $msg .= ': ' . $data['detail'] . '. See ' . $data['type'] . ' for more information';
            }

            switch ($class) {
                case '4':
                    $this->assertInstanceOf(Client\Exception\Request::class, $e);
                    $this->assertEquals($msg, $e->getMessage());
                    $this->assertEquals($code, $e->getCode());
                    break;
                case '5':
                    $this->assertInstanceOf(ServerException::class, $e);
                    $this->assertEquals($msg, $e->getMessage());
                    $this->assertEquals($code, $e->getCode());
                    break;
                default:
                    $this->assertInstanceOf(ClientException::class, $e);
                    $this->assertEquals('Unexpected HTTP Status Code', $e->getMessage());
                    break;
            }
        }

        self::markTestIncomplete('Break this test up, it is doing way too much');
    }

    /**
     * @return string[]
     */
    public function exceptions(): array
    {
        //todo: add server error
        return [
            //post / create are aliases
            ['update', 'bad', 400],
            ['update', 'unauthorized', 401],
            ['create', 'bad', 400],
            ['create', 'unauthorized', 401],
            ['delete', 'bad', 400],
            ['delete', 'unauthorized', 401],
        ];
    }

    /**
     * @dataProvider createApplication
     *
     * @param $payload
     * @param $method
     */
    public function testCreateApplication($payload, $method): void
    {
        $this->vonageClient->send(Argument::that(function (Request $request) {
            $this->assertEquals('/v2/applications', $request->getUri()->getPath());
            $this->assertEquals('api.nexmo.com', $request->getUri()->getHost());
            $this->assertEquals('POST', $request->getMethod());

            $this->assertRequestJsonBodyContains('name', 'My Application', $request);

            // Check for VBC as an object explicitly
            $request->getBody()->rewind();
            $this->assertStringContainsString('"vbc":{}', $request->getBody()->getContents());

            // And check all other capabilities
            $capabilities = [
                'voice' => [
                    'webhooks' => [
                        'answer_url' => [
                            'address' => 'https://example.com/webhooks/answer',
                            'http_method' => 'GET'

                        ],
                        'event_url' => [
                            'address' => 'https://example.com/webhooks/event',
                            'http_method' => 'POST'
                        ]
                    ]
                ],
                'messages' => [
                    'webhooks' => [
                        'inbound_url' => [
                            'address' => 'https://example.com/webhooks/inbound',
                            'http_method' => 'POST'

                        ],
                        'status_url' => [
                            'address' => 'https://example.com/webhooks/status',
                            'http_method' => 'POST'
                        ]
                    ]
                ],
                'rtc' => [
                    'webhooks' => [
                        'event_url' => [
                            'address' => 'https://example.com/webhooks/event',
                            'http_method' => 'POST',
                        ],
                    ]
                ],
                'vbc' => []
            ];
            $this->assertRequestJsonBodyContains('capabilities', $capabilities, $request);

            // And the public key
            $keys = [
                'public_key' => "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCA\nKOxjsU4pf/sMFi9N0jqcSLcjx" .
                    "u33G\nd/vynKnlw9SENi+UZR44GdjGdmfm1\ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3\n0kYWekeIZawIwe/g9faFgkev+1xs" .
                    "O\nOUNhPx2LhuLmgwWSRS4L5W851Xe3f\nUQIDAQAB\n-----END PUBLIC KEY-----\n",
            ];
            $this->assertRequestJsonBodyContains('keys', $keys, $request);
            return true;
        }))->willReturn($this->getResponse('success', 201));

        $application = @$this->applicationClient->$method($payload);

        $expectedData = json_decode($this->getResponse()->getBody()->getContents(), true);
        $this->assertInstanceOf(Application::class, $application);
        $this->assertSame($expectedData['id'], $application->getId());
        $this->assertSame($expectedData['name'], $application->getName());
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['answer_url']['address'],
            $application->getVoiceConfig()->getWebhook('answer_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['answer_url']['http_method'],
            $application->getVoiceConfig()->getWebhook('answer_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['event_url']['address'],
            $application->getVoiceConfig()->getWebhook('event_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['voice']['webhooks']['event_url']['http_method'],
            $application->getVoiceConfig()->getWebhook('event_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['inbound_url']['address'],
            $application->getMessagesConfig()->getWebhook('inbound_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['inbound_url']['http_method'],
            $application->getMessagesConfig()->getWebhook('inbound_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['status_url']['address'],
            $application->getMessagesConfig()->getWebhook('status_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['messages']['webhooks']['status_url']['http_method'],
            $application->getMessagesConfig()->getWebhook('status_url')->getMethod()
        );
        $this->assertSame(
            $expectedData['capabilities']['rtc']['webhooks']['event_url']['address'],
            $application->getRtcConfig()->getWebhook('event_url')->getUrl()
        );
        $this->assertSame(
            $expectedData['capabilities']['rtc']['webhooks']['event_url']['address'],
            $application->getRtcConfig()->getWebhook('event_url')->getUrl()
        );
    }

    /**
     * @throws Exception
     *
     * @return array[]
     */
    public function createApplication(): array
    {
        $application = new Application();
        $application->setName('My Application');
        @$application->getVoiceConfig()->setWebhook(VoiceConfig::ANSWER, 'https://example.com/webhooks/answer', 'GET');
        @$application->getVoiceConfig()->setWebhook(VoiceConfig::EVENT, 'https://example.com/webhooks/event', 'POST');
        @$application->getMessagesConfig()->setWebhook(
            MessagesConfig::STATUS,
            'https://example.com/webhooks/status',
            'POST'
        );
        @$application->getMessagesConfig()->setWebhook(
            MessagesConfig::INBOUND,
            'https://example.com/webhooks/inbound',
            'POST'
        );
        @$application->getRtcConfig()->setWebhook(RtcConfig::EVENT, 'https://example.com/webhooks/event', 'POST');
        $application->setPublicKey("-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCA\nKOxjsU4pf/sMFi9N0jqcSL" .
            "cjxu33G\nd/vynKnlw9SENi+UZR44GdjGdmfm1\ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3\n0kYWekeIZawIwe/g9faFgkev+1xsO\nOU" .
            "NhPx2LhuLmgwWSRS4L5W851Xe3f\nUQIDAQAB\n-----END PUBLIC KEY-----\n");
        $application->getVbcConfig()->enable();

        $rawV1 = [
            'name' => 'My Application',
            'answer_url' => 'https://example.com/webhooks/answer',
            'answer_method' => 'GET',
            'event_url' => 'https://example.com/webhooks/event',
            'event_method' => 'POST',
            'status_url' => 'https://example.com/webhooks/status',
            'status_method' => 'POST',
            'inbound_url' => 'https://example.com/webhooks/inbound',
            'inbound_method' => 'POST',
            'vbc' => true,
            'public_key' => "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCA\nKOxjsU4pf/sMFi9N0jqcSLcjxu33G" .
                "\nd/vynKnlw9SENi+UZR44GdjGdmfm1\ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3\n0kYWekeIZawIwe/g9faFgkev+1xsO\nOUNhP" .
                "x2LhuLmgwWSRS4L5W851Xe3f\nUQIDAQAB\n-----END PUBLIC KEY-----\n"
        ];

        $rawV2 = [
            'name' => 'My Application',
            'keys' => [
                'public_key' => "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCA\nKOxjsU4pf/sMFi9N0jqcSLcjx" .
                    "u33G\nd/vynKnlw9SENi+UZR44GdjGdmfm1\ntL1eA7IBh2HNnkYXnAwYzKJoa4eO3\n0kYWekeIZawIwe/g9faFgkev+1xs" .
                    "O\nOUNhPx2LhuLmgwWSRS4L5W851Xe3f\nUQIDAQAB\n-----END PUBLIC KEY-----\n"
            ],
            'capabilities' => [
                'voice' => [
                    'webhooks' => [
                        'answer_url' => [
                            'address' => 'https://example.com/webhooks/answer',
                            'http_method' => 'GET',
                        ],
                        'event_url' => [
                            'address' => 'https://example.com/webhooks/event',
                            'http_method' => 'POST',
                        ],
                    ]
                ],
                'messages' => [
                    'webhooks' => [
                        'inbound_url' => [
                            'address' => 'https://example.com/webhooks/inbound',
                            'http_method' => 'POST'

                        ],
                        'status_url' => [
                            'address' => 'https://example.com/webhooks/status',
                            'http_method' => 'POST'
                        ]
                    ]
                ],
                'rtc' => [
                    'webhooks' => [
                        'event_url' => [
                            'address' => 'https://example.com/webhooks/event',
                            'http_method' => 'POST',
                        ],
                    ]
                ],
                'vbc' => []
            ]
        ];

        return [
            'createApplication' => [clone $application, 'create'],
            'postApplication' => [clone $application, 'post'],
            'createRawV1' => [$rawV1, 'create'],
            'postRawV1' => [$rawV1, 'post'],
            'createRawV2' => [$rawV2, 'create'],
            'postRawV2' => [$rawV2, 'post'],
        ];
    }

    /**
     * Get the API response we'd expect for a call to the API.
     */
    protected function getResponse(string $type = 'success', int $status = 200): Response
    {
        return new Response(fopen(__DIR__ . '/responses/' . $type . '.json', 'rb'), $status);
    }
}


text:
package org.gradle.api.internal.file.collections;

import groovy.lang.Closure;
import org.gradle.api.file.FileVisitDetails;
import org.gradle.api.file.FileVisitor;
import org.gradle.api.file.RelativePath;
import org.gradle.api.internal.file.AbstractFileTreeElement;
import org.gradle.internal.Factory;
import org.gradle.internal.nativeplatform.filesystem.Chmod;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A {@link MinimalFileTree} which is composed using a mapping from relative path to file source.
 */
public class MapFileTree implements MinimalFileTree, FileSystemMirroringFileTree {
    private final Map<RelativePath, Closure> elements = new LinkedHashMap<RelativePath, Closure>();
    private final Factory<File> tmpDirSource;
    private final Chmod chmod;

    public MapFileTree(final File tmpDir, Chmod chmod) {
        this(new Factory<File>() { public File create() { return tmpDir; }}, chmod);
    }

    public MapFileTree(Factory<File> tmpDirSource, Chmod chmod) {
        this.tmpDirSource = tmpDirSource;
        this.chmod = chmod;
    }

    private File getTmpDir() {
        return tmpDirSource.create();
    }

    public String getDisplayName() {
        return "file tree";
    }

    public DirectoryFileTree getMirror() {
        return new DirectoryFileTree(getTmpDir());
    }

    public void visit(FileVisitor visitor) {
        AtomicBoolean stopFlag = new AtomicBoolean();
        Visit visit = new Visit(visitor, stopFlag);
        for (Map.Entry<RelativePath, Closure> entry : elements.entrySet()) {
            if (stopFlag.get()) {
                break;
            }
            RelativePath path = entry.getKey();
            Closure generator = entry.getValue();
            visit.visit(path, generator);
        }
    }

    /**
     * Adds an element to this tree. The given closure is passed an OutputStream which it can use to write the content
     * of the element to.
     */
    public void add(String path, Closure contentClosure) {
        elements.put(RelativePath.parse(true, path), contentClosure);
    }

    private class Visit {
        private final Set<RelativePath> visitedDirs = new LinkedHashSet<RelativePath>();
        private final FileVisitor visitor;
        private final AtomicBoolean stopFlag;

        public Visit(FileVisitor visitor, AtomicBoolean stopFlag) {
            this.visitor = visitor;
            this.stopFlag = stopFlag;
        }

        private void visitDirs(RelativePath path, FileVisitor visitor) {
            if (path == null || path.getParent() == null || !visitedDirs.add(path)) {
                return;
            }

            visitDirs(path.getParent(), visitor);
            visitor.visitDir(new FileVisitDetailsImpl(path, null, stopFlag, chmod));
        }

        public void visit(RelativePath path, Closure generator) {
            visitDirs(path.getParent(), visitor);
            visitor.visitFile(new FileVisitDetailsImpl(path, generator, stopFlag, chmod));
        }
    }

    private class FileVisitDetailsImpl extends AbstractFileTreeElement implements FileVisitDetails {
        private final RelativePath path;
        private final Closure generator;
        private final long lastModified;
        private final AtomicBoolean stopFlag;
        private File file;

        public FileVisitDetailsImpl(RelativePath path, Closure generator, AtomicBoolean stopFlag, Chmod chmod) {
            super(chmod);
            this.path = path;
            this.generator = generator;
            this.stopFlag = stopFlag;
            // round to nearest second
            lastModified = System.currentTimeMillis() / 1000 * 1000;
        }

        public String getDisplayName() {
            return path.toString();
        }

        public void stopVisiting() {
            stopFlag.set(true);
        }

        public File getFile() {
            if (file == null) {
                file = path.getFile(getTmpDir());
                copyTo(file);
            }
            return file;
        }

        public boolean isDirectory() {
            return !path.isFile();
        }

        public long getLastModified() {
            return lastModified;
        }

        public long getSize() {
            return getFile().length();
        }

        public void copyTo(OutputStream outstr) {
            generator.call(outstr);
        }

        public InputStream open() {
            throw new UnsupportedOperationException();
        }

        public RelativePath getRelativePath() {
            return path;
        }
    }
}


text:
<?php

namespace Phlexible\Bundle\MediaManagerBundle\Search;

use Phlexible\Bundle\SearchBundle\Search\SearchResult;
use Phlexible\Bundle\SearchBundle\SearchProvider\SearchProviderInterface;
use Phlexible\Bundle\UserBundle\Model\UserManagerInterface;
use Phlexible\Component\MediaManager\Volume\ExtendedFileInterface;
use Phlexible\Component\Volume\VolumeManager;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * File search.
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class FileSearch implements SearchProviderInterface
{
    /**
     * @var VolumeManager
     */
    private $volumeManager;

    /**
     * @var UserManagerInterface
     */
    private $userManager;

    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    /**
     * @var RouterInterface
     */
    private $router;

    /**
     * @param VolumeManager                 $volumeManager
     * @param UserManagerInterface          $userManager
     * @param AuthorizationCheckerInterface $authorizationChecker
     * @param RouterInterface               $router
     */
    public function __construct(
        VolumeManager $volumeManager,
        UserManagerInterface $userManager,
        AuthorizationCheckerInterface $authorizationChecker,
        RouterInterface $router
    ) {
        $this->volumeManager = $volumeManager;
        $this->userManager = $userManager;
        $this->authorizationChecker = $authorizationChecker;
        $this->router = $router;
    }

    /**
     * {@inheritdoc}
     */
    public function getRole()
    {
        return 'ROLE_MEDIA';
    }

    /**
     * {@inheritdoc}
     */
    public function getSearchKey()
    {
        return 'mm';
    }

    /**
     * {@inheritdoc}
     */
    public function search($query)
    {
        $files = [];
        foreach ($this->volumeManager->all() as $volume) {
            $foundFiles = $volume->search($query);
            if ($foundFiles) {
                $files += $foundFiles;
            }
        }

        $folders = [];

        $results = [];
        foreach ($files as $file) {
            /* @var $file ExtendedFileInterface */

            if (empty($folders[$file->getFolderId()])) {
                $folders[$file->getFolderId()] = $file->getVolume()->findFolder($file->getFolderId());
            }

            if (!$this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN') && !$this->authorizationChecker->isGranted('FILE_READ', $folders[$file->getFolderId()])) {
                continue;
            }

            $folderPath = $folders[$file->getFolderId()]->getIdPath();

            $createUserName = 'Unknown User';
            try {
                $createUser = $this->userManager->find($file->getCreateUserId());
                if ($createUser) {
                    $createUserName = $createUser->getDisplayName();
                }
            } catch (\Exception $e) {
            }

            $results[] = new SearchResult(
                $file->getId(),
                $file->getName(),
                $createUserName,
                $file->getCreatedAt(),
                $this->router->generate('mediamanager_media', array('file_id' => $file->getId(), 'file_version' => $file->getVersion(), 'template_key' => '_mm_small')),
                'Mediamanager File Search',
                [
                    'handler' => 'media',
                    'parameters' => [
                        'start_file_id' => $file->getId(),
                        'start_folder_path' => '/'.implode('/', $folderPath),
                    ],
                ]
            );
        }

        return $results;
    }
}


text:
"""
    flask.ext.cache
    ~~~~~~~~~~~~~~

    Adds cache support to your application.

    :copyright: (c) 2010 by Thadeus Burgess.
    :license: BSD, see LICENSE for more details
"""

__version__ = '0.13'
__versionfull__ = __version__

import base64
import functools
import hashlib
import inspect
import logging
import string
import uuid
import warnings

from werkzeug import import_string
from flask import request, current_app

from ._compat import PY2

logger = logging.getLogger(__name__)

TEMPLATE_FRAGMENT_KEY_TEMPLATE = '_template_fragment_cache_%s%s'

# Used to remove control characters and whitespace from cache keys.
valid_chars = set(string.ascii_letters + string.digits + '_.')
delchars = ''.join(c for c in map(chr, range(256)) if c not in valid_chars)
if PY2:
    null_control = (None, delchars)
else:
    null_control = (dict((k,None) for k in delchars),)

def function_namespace(f, args=None):
    """
    Attempts to returns unique namespace for function
    """
    m_args = inspect.getargspec(f)[0]
    instance_token = None

    instance_self = getattr(f, '__self__', None)

    if instance_self \
    and not inspect.isclass(instance_self):
        instance_token = repr(f.__self__)
    elif m_args \
    and m_args[0] == 'self' \
    and args:
        instance_token = repr(args[0])

    module = f.__module__

    if hasattr(f, '__qualname__'):
        name = f.__qualname__
    else:
        klass = getattr(f, '__self__', None)

        if klass \
        and not inspect.isclass(klass):
            klass = klass.__class__

        if not klass:
            klass = getattr(f, 'im_class', None)

        if not klass:
            if m_args and args:
                if m_args[0] == 'self':
                    klass = args[0].__class__
                elif m_args[0] == 'cls':
                    klass = args[0]

        if klass:
            name = klass.__name__ + '.' + f.__name__
        else:
            name = f.__name__

    ns = '.'.join((module, name))
    ns = ns.translate(*null_control)

    if instance_token:
        ins = '.'.join((module, name, instance_token))
        ins = ins.translate(*null_control)
    else:
        ins = None

    return ns, ins

def make_template_fragment_key(fragment_name, vary_on=[]):
    """
    Make a cache key for a specific fragment name
    """
    if vary_on:
        fragment_name = "%s_" % fragment_name
    return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on))

#: Cache Object
################

class Cache(object):
    """
    This class is used to control the cache objects.
    """

    def __init__(self, app=None, with_jinja2_ext=True, config=None):
        if not (config is None or isinstance(config, dict)):
            raise ValueError("`config` must be an instance of dict or None")

        self.with_jinja2_ext = with_jinja2_ext
        self.config = config

        self.app = app
        if app is not None:
            self.init_app(app, config)

    def init_app(self, app, config=None):
        "This is used to initialize cache with your app object"
        if not (config is None or isinstance(config, dict)):
            raise ValueError("`config` must be an instance of dict or None")

        #: Ref PR #44.
        #: Do not set self.app in the case a single instance of the Cache
        #: object is being used for multiple app instances.
        #: Example use case would be Cache shipped as part of a blueprint
        #: or utility library.

        base_config = app.config.copy()
        if self.config:
            base_config.update(self.config)
        if config:
            base_config.update(config)
        config = base_config

        config.setdefault('CACHE_DEFAULT_TIMEOUT', 300)
        config.setdefault('CACHE_THRESHOLD', 500)
        config.setdefault('CACHE_KEY_PREFIX', 'flask_cache_')
        config.setdefault('CACHE_MEMCACHED_SERVERS', None)
        config.setdefault('CACHE_DIR', None)
        config.setdefault('CACHE_OPTIONS', None)
        config.setdefault('CACHE_ARGS', [])
        config.setdefault('CACHE_TYPE', 'null')
        config.setdefault('CACHE_NO_NULL_WARNING', False)

        if config['CACHE_TYPE'] == 'null' and not config['CACHE_NO_NULL_WARNING']:
            warnings.warn("Flask-Cache: CACHE_TYPE is set to null, "
                          "caching is effectively disabled.")

        if self.with_jinja2_ext:
            from .jinja2ext import CacheExtension, JINJA_CACHE_ATTR_NAME

            setattr(app.jinja_env, JINJA_CACHE_ATTR_NAME, self)
            app.jinja_env.add_extension(CacheExtension)

        self._set_cache(app, config)

    def _set_cache(self, app, config):
        import_me = config['CACHE_TYPE']
        if '.' not in import_me:
            from . import backends

            try:
                cache_obj = getattr(backends, import_me)
            except AttributeError:
                raise ImportError("%s is not a valid FlaskCache backend" % (
                                  import_me))
        else:
            cache_obj = import_string(import_me)

        cache_args = config['CACHE_ARGS'][:]
        cache_options = {'default_timeout': config['CACHE_DEFAULT_TIMEOUT']}

        if config['CACHE_OPTIONS']:
            cache_options.update(config['CACHE_OPTIONS'])

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions.setdefault('cache', {})
        app.extensions['cache'][self] = cache_obj(
                app, config, cache_args, cache_options)

    @property
    def cache(self):
        app = self.app or current_app
        return app.extensions['cache'][self]

    def get(self, *args, **kwargs):
        "Proxy function for internal cache object."
        return self.cache.get(*args, **kwargs)

    def set(self, *args, **kwargs):
        "Proxy function for internal cache object."
        self.cache.set(*args, **kwargs)

    def add(self, *args, **kwargs):
        "Proxy function for internal cache object."
        self.cache.add(*args, **kwargs)

    def delete(self, *args, **kwargs):
        "Proxy function for internal cache object."
        self.cache.delete(*args, **kwargs)

    def delete_many(self, *args, **kwargs):
        "Proxy function for internal cache object."
        self.cache.delete_many(*args, **kwargs)

    def clear(self):
        "Proxy function for internal cache object."
        self.cache.clear()

    def get_many(self, *args, **kwargs):
        "Proxy function for internal cache object."
        return self.cache.get_many(*args, **kwargs)

    def set_many(self, *args, **kwargs):
        "Proxy function for internal cache object."
        self.cache.set_many(*args, **kwargs)

    def cached(self, timeout=None, key_prefix='view/%s', unless=None):
        """
        Decorator. Use this to cache a function. By default the cache key
        is `view/request.path`. You are able to use this decorator with any
        function by changing the `key_prefix`. If the token `%s` is located
        within the `key_prefix` then it will replace that with `request.path`

        Example::

            # An example view function
            @cache.cached(timeout=50)
            def big_foo():
                return big_bar_calc()

            # An example misc function to cache.
            @cache.cached(key_prefix='MyCachedList')
            def get_list():
                return [random.randrange(0, 1) for i in range(50000)]

            my_list = get_list()

        .. note::

            You MUST have a request context to actually called any functions
            that are cached.

        .. versionadded:: 0.4
            The returned decorated function now has three function attributes
            assigned to it. These attributes are readable/writable.

                **uncached**
                    The original undecorated function

                **cache_timeout**
                    The cache timeout value for this function. For a custom value
                    to take affect, this must be set before the function is called.

                **make_cache_key**
                    A function used in generating the cache_key used.

        :param timeout: Default None. If set to an integer, will cache for that
                        amount of time. Unit of time is in seconds.
        :param key_prefix: Default 'view/%(request.path)s'. Beginning key to .
                           use for the cache key.

                           .. versionadded:: 0.3.4
                               Can optionally be a callable which takes no arguments
                               but returns a string that will be used as the cache_key.

        :param unless: Default None. Cache will *always* execute the caching
                       facilities unless this callable is true.
                       This will bypass the caching entirely.
        """

        def decorator(f):
            @functools.wraps(f)
            def decorated_function(*args, **kwargs):
                #: Bypass the cache entirely.
                if callable(unless) and unless() is True:
                    return f(*args, **kwargs)

                try:
                    cache_key = decorated_function.make_cache_key(*args, **kwargs)
                    rv = self.cache.get(cache_key)
                except Exception:
                    if current_app.debug:
                        raise
                    logger.exception("Exception possibly due to cache backend.")
                    return f(*args, **kwargs)

                if rv is None:
                    rv = f(*args, **kwargs)
                    try:
                        self.cache.set(cache_key, rv,
                                   timeout=decorated_function.cache_timeout)
                    except Exception:
                        if current_app.debug:
                            raise
                        logger.exception("Exception possibly due to cache backend.")
                        return f(*args, **kwargs)
                return rv

            def make_cache_key(*args, **kwargs):
                if callable(key_prefix):
                    cache_key = key_prefix()
                elif '%s' in key_prefix:
                    cache_key = key_prefix % request.path
                else:
                    cache_key = key_prefix

                return cache_key

            decorated_function.uncached = f
            decorated_function.cache_timeout = timeout
            decorated_function.make_cache_key = make_cache_key

            return decorated_function
        return decorator

    def _memvname(self, funcname):
        return funcname + '_memver'

    def _memoize_make_version_hash(self):
        return base64.b64encode(uuid.uuid4().bytes)[:6].decode('utf-8')

    def _memoize_version(self, f, args=None,
                         reset=False, delete=False, timeout=None):
        """
        Updates the hash version associated with a memoized function or method.
        """
        fname, instance_fname = function_namespace(f, args=args)
        version_key = self._memvname(fname)
        fetch_keys = [version_key]

        if instance_fname:
            instance_version_key = self._memvname(instance_fname)
            fetch_keys.append(instance_version_key)

        # Only delete the per-instance version key or per-function version
        # key but not both.
        if delete:
            self.cache.delete_many(fetch_keys[-1])
            return fname, None

        version_data_list = list(self.cache.get_many(*fetch_keys))
        dirty = False

        if version_data_list[0] is None:
            version_data_list[0] = self._memoize_make_version_hash()
            dirty = True

        if instance_fname and version_data_list[1] is None:
            version_data_list[1] = self._memoize_make_version_hash()
            dirty = True

        # Only reset the per-instance version or the per-function version
        # but not both.
        if reset:
            fetch_keys = fetch_keys[-1:]
            version_data_list = [self._memoize_make_version_hash()]
            dirty = True

        if dirty:
            self.cache.set_many(dict(zip(fetch_keys, version_data_list)),
                                timeout=timeout)

        return fname, ''.join(version_data_list)

    def _memoize_make_cache_key(self, make_name=None, timeout=None):
        """
        Function used to create the cache_key for memoized functions.
        """
        def make_cache_key(f, *args, **kwargs):
            _timeout = getattr(timeout, 'cache_timeout', timeout)
            fname, version_data = self._memoize_version(f, args=args,
                                                        timeout=_timeout)

            #: this should have to be after version_data, so that it
            #: does not break the delete_memoized functionality.
            if callable(make_name):
                altfname = make_name(fname)
            else:
                altfname = fname

            if callable(f):
                keyargs, keykwargs = self._memoize_kwargs_to_args(f,
                                                                 *args,
                                                                 **kwargs)
            else:
                keyargs, keykwargs = args, kwargs

            try:
                updated = "{0}{1}{2}".format(altfname, keyargs, keykwargs)
            except AttributeError:
                updated = "%s%s%s" % (altfname, keyargs, keykwargs)

            cache_key = hashlib.md5()
            cache_key.update(updated.encode('utf-8'))
            cache_key = base64.b64encode(cache_key.digest())[:16]
            cache_key = cache_key.decode('utf-8')
            cache_key += version_data

            return cache_key
        return make_cache_key

    def _memoize_kwargs_to_args(self, f, *args, **kwargs):
        #: Inspect the arguments to the function
        #: This allows the memoization to be the same
        #: whether the function was called with
        #: 1, b=2 is equivilant to a=1, b=2, etc.
        new_args = []
        arg_num = 0
        argspec = inspect.getargspec(f)

        args_len = len(argspec.args)
        for i in range(args_len):
            if i == 0 and argspec.args[i] in ('self', 'cls'):
                #: use the repr of the class instance
                #: this supports instance methods for
                #: the memoized functions, giving more
                #: flexibility to developers
                arg = repr(args[0])
                arg_num += 1
            elif argspec.args[i] in kwargs:
                arg = kwargs[argspec.args[i]]
            elif arg_num < len(args):
                arg = args[arg_num]
                arg_num += 1
            elif abs(i-args_len) <= len(argspec.defaults):
                arg = argspec.defaults[i-args_len]
                arg_num += 1
            else:
                arg = None
                arg_num += 1

            #: Attempt to convert all arguments to a
            #: hash/id or a representation?
            #: Not sure if this is necessary, since
            #: using objects as keys gets tricky quickly.
            # if hasattr(arg, '__class__'):
            #     try:
            #         arg = hash(arg)
            #     except:
            #         arg = repr(arg)

            #: Or what about a special __cacherepr__ function
            #: on an object, this allows objects to act normal
            #: upon inspection, yet they can define a representation
            #: that can be used to make the object unique in the
            #: cache key. Given that a case comes across that
            #: an object "must" be used as a cache key
            # if hasattr(arg, '__cacherepr__'):
            #     arg = arg.__cacherepr__

            new_args.append(arg)

        return tuple(new_args), {}

    def memoize(self, timeout=None, make_name=None, unless=None):
        """
        Use this to cache the result of a function, taking its arguments into
        account in the cache key.

        Information on
        `Memoization <http://en.wikipedia.org/wiki/Memoization>`_.

        Example::

            @cache.memoize(timeout=50)
            def big_foo(a, b):
                return a + b + random.randrange(0, 1000)

        .. code-block:: pycon

            >>> big_foo(5, 2)
            753
            >>> big_foo(5, 3)
            234
            >>> big_foo(5, 2)
            753

        .. versionadded:: 0.4
            The returned decorated function now has three function attributes
            assigned to it.

                **uncached**
                    The original undecorated function. readable only

                **cache_timeout**
                    The cache timeout value for this function. For a custom value
                    to take affect, this must be set before the function is called.

                    readable and writable

                **make_cache_key**
                    A function used in generating the cache_key used.

                    readable and writable

        :param timeout: Default None. If set to an integer, will cache for that
                        amount of time. Unit of time is in seconds.
        :param make_name: Default None. If set this is a function that accepts
                          a single argument, the function name, and returns a
                          new string to be used as the function name. If not set
                          then the function name is used.
        :param unless: Default None. Cache will *always* execute the caching
                       facilities unelss this callable is true.
                       This will bypass the caching entirely.

        .. versionadded:: 0.5
            params ``make_name``, ``unless``
        """

        def memoize(f):
            @functools.wraps(f)
            def decorated_function(*args, **kwargs):
                #: bypass cache
                if callable(unless) and unless() is True:
                    return f(*args, **kwargs)

                try:
                    cache_key = decorated_function.make_cache_key(f, *args, **kwargs)
                    rv = self.cache.get(cache_key)
                except Exception:
                    if current_app.debug:
                        raise
                    logger.exception("Exception possibly due to cache backend.")
                    return f(*args, **kwargs)

                if rv is None:
                    rv = f(*args, **kwargs)
                    try:
                        self.cache.set(cache_key, rv,
                                   timeout=decorated_function.cache_timeout)
                    except Exception:
                        if current_app.debug:
                            raise
                        logger.exception("Exception possibly due to cache backend.")
                return rv

            decorated_function.uncached = f
            decorated_function.cache_timeout = timeout
            decorated_function.make_cache_key = self._memoize_make_cache_key(
                                                make_name, decorated_function)
            decorated_function.delete_memoized = lambda: self.delete_memoized(f)

            return decorated_function
        return memoize

    def delete_memoized(self, f, *args, **kwargs):
        """
        Deletes the specified functions caches, based by given parameters.
        If parameters are given, only the functions that were memoized with them
        will be erased. Otherwise all versions of the caches will be forgotten.

        Example::

            @cache.memoize(50)
            def random_func():
                return random.randrange(1, 50)

            @cache.memoize()
            def param_func(a, b):
                return a+b+random.randrange(1, 50)

        .. code-block:: pycon

            >>> random_func()
            43
            >>> random_func()
            43
            >>> cache.delete_memoized('random_func')
            >>> random_func()
            16
            >>> param_func(1, 2)
            32
            >>> param_func(1, 2)
            32
            >>> param_func(2, 2)
            47
            >>> cache.delete_memoized('param_func', 1, 2)
            >>> param_func(1, 2)
            13
            >>> param_func(2, 2)
            47

        Delete memoized is also smart about instance methods vs class methods.

        When passing a instancemethod, it will only clear the cache related
        to that instance of that object. (object uniqueness can be overridden
            by defining the __repr__ method, such as user id).

        When passing a classmethod, it will clear all caches related across
        all instances of that class.

        Example::

            class Adder(object):
                @cache.memoize()
                def add(self, b):
                    return b + random.random()

        .. code-block:: pycon

            >>> adder1 = Adder()
            >>> adder2 = Adder()
            >>> adder1.add(3)
            3.23214234
            >>> adder2.add(3)
            3.60898509
            >>> cache.delete_memoized(adder.add)
            >>> adder1.add(3)
            3.01348673
            >>> adder2.add(3)
            3.60898509
            >>> cache.delete_memoized(Adder.add)
            >>> adder1.add(3)
            3.53235667
            >>> adder2.add(3)
            3.72341788

        :param fname: Name of the memoized function, or a reference to the function.
        :param \*args: A list of positional parameters used with memoized function.
        :param \**kwargs: A dict of named parameters used with memoized function.

        .. note::

            Flask-Cache uses inspect to order kwargs into positional args when
            the function is memoized. If you pass a function reference into ``fname``
            instead of the function name, Flask-Cache will be able to place
            the args/kwargs in the proper order, and delete the positional cache.

            However, if ``delete_memoized`` is just called with the name of the
            function, be sure to pass in potential arguments in the same order
            as defined in your function as args only, otherwise Flask-Cache
            will not be able to compute the same cache key.

        .. note::

            Flask-Cache maintains an internal random version hash for the function.
            Using delete_memoized will only swap out the version hash, causing
            the memoize function to recompute results and put them into another key.

            This leaves any computed caches for this memoized function within the
            caching backend.

            It is recommended to use a very high timeout with memoize if using
            this function, so that when the version has is swapped, the old cached
            results would eventually be reclaimed by the caching backend.
        """
        if not callable(f):
            raise DeprecationWarning("Deleting messages by relative name is no longer"
                          " reliable, please switch to a function reference")

        try:
            if not args and not kwargs:
                self._memoize_version(f, reset=True)
            else:
                cache_key = f.make_cache_key(f.uncached, *args, **kwargs)
                self.cache.delete(cache_key)
        except Exception:
            if current_app.debug:
                raise
            logger.exception("Exception possibly due to cache backend.")

    def delete_memoized_verhash(self, f, *args):
        """
        Delete the version hash associated with the function.

        ..warning::

            Performing this operation could leave keys behind that have
            been created with this version hash. It is up to the application
            to make sure that all keys that may have been created with this
            version hash at least have timeouts so they will not sit orphaned
            in the cache backend.
        """
        if not callable(f):
            raise DeprecationWarning("Deleting messages by relative name is no longer"
                          " reliable, please use a function reference")

        try:
            self._memoize_version(f, delete=True)
        except Exception:
            if current_app.debug:
                raise
            logger.exception("Exception possibly due to cache backend.")


text:
<<<<<<< HEAD
<<<<<<< HEAD
"""Memory watchdog: periodically read the memory usage of the main test process
and print it out, until terminated."""
# stdin should refer to the process' /proc/<PID>/statm: we don't pass the
# process' PID to avoid a race condition in case of - unlikely - PID recycling.
# If the process crashes, reading from the /proc entry will fail with ESRCH.

import os
import sys
import time

try:
    page_size = os.sysconf('SC_PAGESIZE')
except (ValueError, AttributeError):
    try:
        page_size = os.sysconf('SC_PAGE_SIZE')
    except (ValueError, AttributeError):
        page_size = 4096

while True:
    sys.stdin.seek(0)
    statm = sys.stdin.read()
    data = int(statm.split()[5])
    sys.stdout.write(" ... process data size: {data:.1f}G\n"
                     .format(data=data * page_size / (1024 ** 3)))
    sys.stdout.flush()
    time.sleep(1)
=======
"""Memory watchdog: periodically read the memory usage of the main test process
and print it out, until terminated."""
# stdin should refer to the process' /proc/<PID>/statm: we don't pass the
# process' PID to avoid a race condition in case of - unlikely - PID recycling.
# If the process crashes, reading from the /proc entry will fail with ESRCH.

import os
import sys
import time

try:
    page_size = os.sysconf('SC_PAGESIZE')
except (ValueError, AttributeError):
    try:
        page_size = os.sysconf('SC_PAGE_SIZE')
    except (ValueError, AttributeError):
        page_size = 4096

while True:
    sys.stdin.seek(0)
    statm = sys.stdin.read()
    data = int(statm.split()[5])
    sys.stdout.write(" ... process data size: {data:.1f}G\n"
                     .format(data=data * page_size / (1024 ** 3)))
    sys.stdout.flush()
    time.sleep(1)
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
"""Memory watchdog: periodically read the memory usage of the main test process
and print it out, until terminated."""
# stdin should refer to the process' /proc/<PID>/statm: we don't pass the
# process' PID to avoid a race condition in case of - unlikely - PID recycling.
# If the process crashes, reading from the /proc entry will fail with ESRCH.

import os
import sys
import time

try:
    page_size = os.sysconf('SC_PAGESIZE')
except (ValueError, AttributeError):
    try:
        page_size = os.sysconf('SC_PAGE_SIZE')
    except (ValueError, AttributeError):
        page_size = 4096

while True:
    sys.stdin.seek(0)
    statm = sys.stdin.read()
    data = int(statm.split()[5])
    sys.stdout.write(" ... process data size: {data:.1f}G\n"
                     .format(data=data * page_size / (1024 ** 3)))
    sys.stdout.flush()
    time.sleep(1)
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
package org.perfidix.result;

import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;

/**
 * The result container contains more results. It is by definition recursive, so
 * it can handle as much diversity as possible
 *
 * @param <ResultType>
 *            the type of the children.
 * @author Alexander Onea, neue Couch
 * @author Sebastian Graf, University of Konstanz
 */
public abstract class AbstractResultContainer<ResultType extends AbstractResult>
		extends AbstractResult {

	/**
	 * Map of all elements with the Mapping Method/Class -> ResultType.
	 */
	transient final Map<Object, ResultType> elements;

	/**
	 * Constructor.
	 *
	 * @param paramElem
	 *            related element
	 */
	AbstractResultContainer(final Object paramElem) {
		super(paramElem);
		elements = new Hashtable<Object, ResultType>();
	}

	/**
	 * Getting all elements which are included in this result. That means:
	 * {@link BenchmarkResult} contains {@link ClassResult}; {@link ClassResult}
	 * contains {@link MethodResult};
	 *
	 * @return a {@link Collection} of the included results.
	 */
	public final Collection<ResultType> getIncludedResults() {
		return elements.values();
	}

	/**
	 * Getting the results for one object.
	 *
	 * @param obj
	 *            the object, can be a Class or a Method
	 * @return the result for this object
	 */
	public final ResultType getResultForObject(final Object obj) {
		return elements.get(obj);
	}

}


text:
package com.linchaolong.apktoolplus.module.jiagu;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Tooltip;
import javafx.scene.text.Text;
import com.linchaolong.apktoolplus.core.Callback;
import com.linchaolong.apktoolplus.utils.FileHelper;

import java.io.File;

/**
 * Created by linchaolong on 2015/11/27.
 */
public class ApkItemView {

    public static final String TAG = ApkItemView.class.getSimpleName();

    @FXML
    Label label;
    @FXML
    ProgressBar progressBar;
    @FXML
    Button btnRemove;
    @FXML
    Button btnOpenDir;
    @FXML
    Text textState;

    private File apk;
    private Parent node;

    private int FINISHED = 1;
    private int WAITING = 2;
    private int ENCRYPTING = 3;
    private int SIGNING = 4;
    private int state = WAITING;

    public ApkItemView(File apk, Parent node) {
        this.apk = apk;
        this.node = node;
    }

    public File getApk() {
        return apk;
    }
    public Parent getNode() {
        return node;
    }

    public boolean isFinished() {
        return state == FINISHED;
    }

    public void setFinished() {
        state = FINISHED;
        Platform.runLater(() -> {
            textState.setText("加固完成");
            btnRemove.setVisible(true);
            textState.getStyleClass().removeAll();
            textState.getStyleClass().add("text_apk_state_finished");
            if(onFinish != null){
                onFinish.callback(null);
            }
        });
    }

    private Callback onFinish;
    public void setOnFinish(Callback callback){
        onFinish = callback;
    }

    public boolean isWaiting() {
        return state == WAITING;
    }

    public void setWaiting() {
        state = WAITING;
        Platform.runLater(() -> {
            textState.setText("等待中");
            btnRemove.setVisible(true);
            textState.getStyleClass().removeAll();
            textState.getStyleClass().add("text_apk_state_waiting");
        });
    }

    public boolean isEncrypting() {
        return state == ENCRYPTING;
    }

    public void setEncrypting() {
        state = ENCRYPTING;
        Platform.runLater(() -> {
            textState.setText("正在加固..");
            btnRemove.setVisible(false);
            textState.getStyleClass().removeAll();
            textState.getStyleClass().add("text_apk_state_encrypting");
        });
    }

    public void setSigning() {
        if(state == FINISHED){
            return;
        }
        state = SIGNING;
        Platform.runLater(() -> {
            textState.setText("正在签名..");
            btnRemove.setVisible(false);
            textState.getStyleClass().removeAll();
            textState.getStyleClass().add("text_apk_state_encrypting");
        });
    }

    public void initialize() {
        label.setText(apk.getName());
        progressBar.setProgress(0);
        btnRemove.setTooltip(new Tooltip(apk.getAbsolutePath()));
        btnOpenDir.setTooltip(new Tooltip(apk.getParent()));
        btnOpenDir.setOnAction(event -> FileHelper.showInExplorer(apk));
        setWaiting();
    }

}


text:
export interface IUser {
  id?: number;
  name?: string;
  email: string;
  password: string;
  connected?: boolean;
  isAdmin?: boolean;
}

export class User implements IUser{
  constructor(
    public email: string,
    public password: string,
  ) {  }
}


text:
body,html{position:relative;margin:0;padding:0;min-height:100%;}
body{}
body{font-family:Arial,sans-serif;font-size:1rem;line-height:1.4;margin:0;position:relative;background:#fff;}
.clearContent{clear:both;}
.navbar{min-height:55px;color:#333;background-color:white;}
.hidden{display:none;}
.navbar.navbar-fixed-top{position:fixed;top:0;left:0;width:100%;}
.navbar.mainNav{border-bottom:1px solid red;margin-bottom:3px;z-index:10;}
div.logo{display:inline-block;margin-left:25px;}
.navbar .logo img{display:inline-block;max-height:65px;border:0;}
.navbar .right-tools{float:right;margin-right:20px;}
.navbar .centerText{display:inline-block;width:70%;text-align:center;margin-top:15px;margin-left:auto;margin-right:auto;vertical-align:top;}
.navbar .centerText .title{font-size:1.5rem;font-weight:bold;}
button.icon-button{border:0;margin:5px 0;padding:0;background-color:transparent;cursor:pointer;}
img.adMenuIcon{width:50px;height:50px;}
.footer{min-height:45px;padding:10px;margin-top:10px;padding-top:10px;background-color:white;width:100%;}
.footer-fixed-bottom{position:fixed;bottom:0;}
body>.content-wrap{margin-top:72px;margin-bottom:100px;}
.content-wrap{width:1080px;margin:0 auto;}
.hero-module-full{clear:both;width:100%;min-height:405px;}
.yellow-box{background-color:yellow;}
.red-box{background-color:rgba(255,128,128,0.5);}
.blue-box{background-color:rgba(128,128,255,0.5);}
.gray-box{background-color:rgba(0,0,0,0.2);}
.section-header{font-size:1.2rem;font-weight:bold;margin:0 3 22 5;border-bottom:1px solid #333;}
.ad-unit{background-image:url(./ads/ad_bg.png);position:relative;overflow:hidden;}
.ad-unit iframe{overflow:hidden;}
.adunit-billboard{margin:0 auto;width:970px;height:250px;}
.adunit-medrect{margin:0;width:340px;height:340px;}
.adControlDialog{position:fixed;z-index:20;width:400px;min-height:450px;top:25px;right:70px;border:3px solid #ddd;border-radius:5px;background-color:white;box-shadow:4px 4px 3px #888;padding:10px;}
.adControlDialog .heading{font-size:1.1em;font-weight:bold;padding-bottom:3px;border-bottom:1px solid #ccc;}
.controls ul.adList{list-style:none;margin:10px 0;padding:0;}
.controls ul.adList li{margin-bottom:10px;}
.controls ul.adList input[type=checkbox]{margin-right:10px;}
.card-full-width{clear:both;position:relative;}
.hero-module-full .main-content{width:720px;float:left;min-height:405px;overflow:hidden;position:relative;}
.main-content .teaser{position:absolute;bottom:0;left:0;width:100%;color:white;min-height:180px;padding:10px 25px;background-color:rgba(128,128,128,0.5);}
.teaser .header{font-size:1.4rem;text-shadow:1px 1px 3px #000;}
.teaser .clippedText{max-width:95%;overflow:hidden;text-overflow:ellipsis;}
.hero-image-large{width:100%;}
.hero-image-small{display:none;}
.hero-module-full .sidebar{width:345px;float:right;padding-left:15px;background:white;}
ul.sidelinks{list-style:none;margin:0;padding:0;}
ul.sidelinks li{padding:10px 10px 8px 10px;border-bottom:1px solid #88F;}
@media (min-width:1321px){body{min-width:1320px;}
.content-wrap{width:1320px;}}
@media (max-width:1079px){.content-wrap{width:100%;}
.adunit-billboard{width:582px;height:150px;}
.hero-image-large{display:none;}
.hero-image-small{width:100%;height:auto;display:block;}
.hero-module-full .main-content{width:100%;}
.hero-module-full .sidebar{width:100%;clear:both;float:none;}
.hero-module-full .sidebar section{padding-left:15px;}}


text:
require 'ios-box/config'
require 'ios-box/iosbox'

require 'rake/tasklib'
require 'rubygems'
require 'yaml'
require 'grit'
require 'plist'
require 'pbxproject'

module Ios
  module Box
    class Tasks < ::Rake::TaskLib
      def initialize(namespace = :iosbox, &block)
      end

    private
      def require_xcode
        raise "This task must be run in XCode Environment" unless ENV['XCODE_VERSION_ACTUAL']
      end
    end
  end
end


text:
'------------------------------------------------------------------------------
' <auto-generated>
'     Dieser Code wurde von einem Tool generiert.
'     Laufzeitversion:4.0.30319.42000
'
'     Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
'     der Code erneut generiert wird.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On

Namespace My

    'HINWEIS: Diese Datei wird automatisch generiert und darf nicht direkt bearbeitet werden. Wenn Sie Änderungen vornehmen möchten,
    ' oder bei in dieser Datei auftretenden Buildfehlern wechseln Sie zum Projekt-Designer.
    ' (Wechseln Sie dazu zu den Projekteigenschaften, oder doppelklicken Sie auf den Knoten "Mein Projekt" im
    ' Projektmappen-Explorer). Nehmen Sie auf der Registerkarte "Anwendung" entsprechende Änderungen vor.
    '
    Partial Friend Class MyApplication

        <Global.System.Diagnostics.DebuggerStepThroughAttribute()>  _
        Public Sub New()
            MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
            Me.IsSingleInstance = true
            Me.EnableVisualStyles = true
            Me.SaveMySettingsOnExit = true
            Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
        End Sub

        <Global.System.Diagnostics.DebuggerStepThroughAttribute()>  _
        Protected Overrides Sub OnCreateMainForm()
            Me.MainForm = Global.Landsknecht_GreenScreen.frmMain
        End Sub
    End Class
End Namespace