text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonLib;
using System.IO;
using System.Threading;

namespace FileManager
{
    /// <summary>
    /// this class is used to manage the filebuffer including replacement policy
    /// it's also designed in singleton model
    /// </summary>
    public class FileBuffer
    {
        //I use the way like paging to manage the FileBuffer
        int pageSize;//size of each page
        int totalPage;//the max num of page
        int bufferSize;//the size of FileBuffer
        int currentPageNum;//the offset of pages which has been used
        int totalFreeSpace;//to recorde the size of free space in the buffer
        byte[] memoryBuffer;
        bool isRun = false;

        Stack<int> freePageStack;//the page which has been
        Dictionary<string, string> urlToPageDic;//used to store the pageNums of the file in the buffer
        LinkedList<string> LruList;//to relize LRU
        Dictionary<string, long> fileLengthDictionary;//store the length of the file store in the buffer

        private static FileBuffer localFileBuffer = new FileBuffer();
        private object LockSSConflict = new object();  //used to avoid save & save conflict;
        private object LockRDConflict = new object();  //used to avoid read & delete conflict
        private ReaderWriterLock RWLock = new ReaderWriterLock();
        /// <summary>
        /// return buffer usage percent
        /// </summary>
        public int BufferUsage
        {
            get
            {
                if (bufferSize != 0)
                {
                    return 100 * (bufferSize - totalFreeSpace) / bufferSize;
                }
                else
                {
                    return 0;
                }
            }
        }
        private FileBuffer()
        {
            pageSize = Properties.FileManagerSettings.Default.PageSize;
            totalPage = Properties.FileManagerSettings.Default.MaxPageNum;
            bufferSize = pageSize * totalPage;
            totalFreeSpace = bufferSize;
            memoryBuffer = new Byte[bufferSize];
            currentPageNum = 0;
            freePageStack = new Stack<int>();
            urlToPageDic = new Dictionary<string, string>();
            LruList = new LinkedList<string>();
            fileLengthDictionary = new Dictionary<string, long>();
        }
        /// <summary>
        /// when you want to use this service,you need to call the Run() function
        /// </summary>
        public void Run()
        {
            if (!isRun)
            {
                //run fileWatcher
                totalPage = Properties.FileManagerSettings.Default.MaxPageNum;
                bufferSize = pageSize * totalPage;
                totalFreeSpace = bufferSize;
                memoryBuffer = new Byte[bufferSize];
                FileWatcher.getInstance().Run();
                FileSystem.GetInstance().ResetSeverDirectory();
                Logger log = new Logger("AppLogger");
                log.Info("FileBuffer Module started");
                isRun = true;
            }
            else
            {
                Logger log = new Logger("AppLogger");
                log.Info("FileBuffer has already started");
            }
        }
        /// <summary>
        /// when stop this service we need to clear the buffer for fear of files changing
        /// which will cause the different bettween local file and file buffer
        /// it's definitely dangerous
        /// </summary>
        public void Stop()
        {
            if (isRun)
            {
                isRun = false;
                FileWatcher.getInstance().Stop();
                Logger log = new Logger("AppLogger");
                log.Info("FileBuffer Module stopped");
                clear();
            }
            else
            {
                Logger log = new Logger("AppLogger");
                log.Info("FileBuffer is not running.It can't be stopped");
            }
        }
        /// <summary>
        /// clear all the data in buffer
        /// </summary>
        private void clear()
        {
            totalFreeSpace = bufferSize;
            currentPageNum = 0;
            freePageStack.Clear();
            urlToPageDic.Clear();
            LruList.Clear();
            fileLengthDictionary.Clear();
        }

        public static FileBuffer GetInstance()
        {
            return localFileBuffer;
        }

        /// <summary>
        /// when a new file is read from local file system, the function will be called to store it in the buffer
        /// </summary>
        /// <returns></returns>
        private bool SaveFile(Byte[] fileByteStream, string url)
        {
            Logger log = new Logger("AppLogger");
            long fileLength = fileByteStream.Length;
            if (totalFreeSpace < fileLength)
            {
                if (fileLength > bufferSize)
                {
                    log.Warn("File: " + url + " is too big to store in buffer!");
                    return false;
                }
                while (totalFreeSpace < fileLength)
                {
                    if (!ReleaseFileLRU(fileLength)) // while there is no file to realse ,return false
                    {
                        return false;
                    }
                }
                SaveFile(fileByteStream, url);//when there are enough buffer space after delete
            }
            else
            {
                long fileOffset = 0;
                lock (LockSSConflict) // used to avoid the conflic of saving the same
                {
                    if (fileLengthDictionary.ContainsKey(url) || totalFreeSpace < fileLength)//avoid the error causing by other saving action
                    {
                        return false;
                    }
                    LruList.AddFirst(url);
                    string urlPages = "";
                    int pageNum = 0;
                    while (fileOffset < fileLength)
                    {
                        if (freePageStack.Count > 0)//while there is page while has been released
                        {
                            pageNum = freePageStack.Pop();
                            if (fileLength - fileOffset < pageSize)
                            {
                                System.Buffer.BlockCopy(fileByteStream, (Int32)fileOffset,
                                    memoryBuffer, pageNum * pageSize, (int)(fileLength - fileOffset));
                                fileOffset = fileLength;
                            }
                            else
                            {
                                System.Buffer.BlockCopy(fileByteStream, (Int32)fileOffset, memoryBuffer, pageNum * pageSize, pageSize);
                                fileOffset += pageSize;
                            }
                        }
                        else
                        {
                            pageNum = currentPageNum++;
                            if (fileLength - fileOffset < pageSize)
                            {
                                System.Buffer.BlockCopy(fileByteStream, (Int32)fileOffset,
                                    memoryBuffer, pageNum * pageSize, (int)(fileLength - fileOffset));
                                fileOffset = fileLength;
                            }
                            else
                            {
                                System.Buffer.BlockCopy(fileByteStream, (Int32)fileOffset, memoryBuffer, pageNum * pageSize, pageSize);
                                fileOffset += pageSize;
                            }
                        }
                        if (urlPages != "")
                        {
                            urlPages += ",";
                        }
                        urlPages += Convert.ToString(pageNum);
                        totalFreeSpace -= pageSize;
                    }
                    urlToPageDic.Add(url, urlPages);//added to the dictionnary which is used as a page table
                    fileLengthDictionary.Add(url, fileLength);//add to the dictionnary when it has been saved in the memory
                    log.Debug("Add file: " + url + " in buffer");
                }
            }
            return true;
        }

        /// <summary>
        /// used to release files in the buffer to get more free space
        /// the strategy now is  LRU
        /// </summary>
        /// <returns></returns>
        private bool ReleaseFileLRU(long fileLength)
        {
            if (LruList.Count != 0)
            {
                string url = LruList.Last.Value;
                return RemoveFileInBuffer(url, fileLength);
            }
            else
            {
                Logger log = new Logger("AppLogger");
                log.Error("There is no file to release");
                return false;
            }
        }
        /// <summary>
        /// used to remove the files in the buffer
        /// </summary>
        /// <param name="url"></param>
        /// <returns>when the file is not stored in the buffer,return false</returns>
        private bool RemoveFileInBuffer(string url)
        {
            Logger log = new Logger("AppLogger");
            log.Debug("File changed, remove file data in buffer: " + url);
            // lock (LockRDConflict)//avoid the conflict when read the file which has been deleted
            RWLock.AcquireWriterLock(FileManager.Properties.FileManagerSettings.Default.LockTimeOut);
            try
            {
                if (!LruList.Remove(url))//when the url is not in the LruList
                {
                    return false;
                }
                string pageString = urlToPageDic[url];
                urlToPageDic.Remove(url);
                fileLengthDictionary.Remove(url);
                string[] pageNumStr = pageString.Split(',');
                int pageNumInt = 0;
                for (int i = 0; i < pageNumStr.Length; ++i)
                {
                    pageNumInt = Convert.ToInt32(pageNumStr[i]);
                    freePageStack.Push(pageNumInt);//release the buffer
                    totalFreeSpace += pageSize; //get the new size of FreeSpace
                }
            }
            finally
            {
                RWLock.ReleaseWriterLock();
            }
            return true;
        }
        /// <summary>
        /// used to avoid too much delete caused by multithreading
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileLength"></param>
        /// <returns></returns>
        private bool RemoveFileInBuffer(string url, long fileLength)
        {
            // lock (LockRDConflict)//avoid the conflict when read the file which has been deleted
            RWLock.AcquireWriterLock(FileManager.Properties.FileManagerSettings.Default.LockTimeOut);
            try
            {
                if (totalFreeSpace > fileLength | !LruList.Remove(url))//when the url is not in the LruList
                {
                    return false;
                }
                string pageString = urlToPageDic[url];
                urlToPageDic.Remove(url);
                fileLengthDictionary.Remove(url);
                string[] pageNumStr = pageString.Split(',');
                int pageNumInt = 0;
                for (int i = 0; i < pageNumStr.Length; ++i)
                {
                    pageNumInt = Convert.ToInt32(pageNumStr[i]);
                    freePageStack.Push(pageNumInt);//release the buffer
                    totalFreeSpace += pageSize; //get the new size of FreeSpace
                }
            }
            finally
            {
                RWLock.ReleaseWriterLock();
            }

            return true;
        }

        /// <summary>
        /// read file from the buffer & local file system
        /// if the file is read success ,statusCode will reutrn 200
        /// else return 404
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Byte[] readFile(string url, ref int statusCode)
        {
            if (!isRun)
            {
                Logger log = new Logger("AppLogger");
                log.Error("please run the filebuffer before reading file");
                return null;
            }
            if (!isUrlEffective(url))
            {
                statusCode = 404;
                return null;
            }
            if (fileLengthDictionary.ContainsKey(url))//if the file was exsited in filebuffer
            {
                RWLock.AcquireReaderLock(FileManager.Properties.FileManagerSettings.Default.LockTimeOut);
                try
                //lock (LockRDConflict)
                {
                    if (!fileLengthDictionary.ContainsKey(url))//when the delete part has delete the file in the buffer,
                    //due to  the wait the last contain is not effective now,we need to make sure if the file exist or not again
                    {
                        Byte[] readBuffer = FileSystem.GetInstance().readFile(url);
                        SaveFile(readBuffer, url);//save the file to fileBuffer in memory
                        statusCode = 200;
                        return readBuffer;
                    }
                    long fileLength = fileLengthDictionary[url];
                    Byte[] fileByteStream = new Byte[fileLength];
                    string pageString = urlToPageDic[url];
                    string[] pageNumStr = pageString.Split(',');
                    int pageNumInt = 0;
                    int fileOffset = 0;
                    for (int i = 0; i < pageNumStr.Length; ++i)
                    {
                        pageNumInt = Convert.ToInt32(pageNumStr[i]);
                        if (fileLength - fileOffset >= pageSize)
                        {
                            System.Buffer.BlockCopy(memoryBuffer, pageNumInt * pageSize, fileByteStream, (int)fileOffset, pageSize);
                        }
                        else
                        {
                            System.Buffer.BlockCopy(memoryBuffer, pageNumInt * pageSize, fileByteStream, (int)fileOffset, (int)(fileLength - fileOffset));
                        }
                        fileOffset += pageSize;
                    }
                    //to realize LRU,the file which was read need to be put into the head of the list
                    LinkedListNode<string> readNode = LruList.Find(url);
                    if (readNode != null)
                    {
                        LruList.Remove(url);
                        LruList.AddFirst(readNode);
                    }
                    statusCode = 200;
                    return fileByteStream;
                }
                finally
                {
                    RWLock.ReleaseReaderLock();
                }
            }
            else //when the file is not in fileBuffer,read the file from local fileSystem
            {
                Byte[] readBuffer = FileSystem.GetInstance().readFile(url);
                if (readBuffer.Length != 0) //in test,we find that some file's lengths could be zero
                {
                    SaveFile(readBuffer, url);//save the file to fileBuffer in memory
                }
                statusCode = 200;
                return readBuffer;
            }
        }

        private bool isUrlEffective(string url)
        {
            if (url.Contains(".."))
            {
                return false;
            }
            string path = FileSystem.GetInstance().ServerDiretory + url;
            return File.Exists(path);
        }
        /// <summary>
        /// used by FileWatcher when there was file deleted
        /// </summary>
        /// <param name="url"></param>
        internal void OnFileChanged(string url)
        {
            if (urlToPageDic.ContainsKey(url))
            {
                RemoveFileInBuffer(url);
            }
        }

        internal void OnFileOrDirectoryDeleted(string url)
        {
            if (urlToPageDic.ContainsKey(url))//when a file was deleted
            {
                RemoveFileInBuffer(url);
                return;
            }
            else
            {
                //when a directory was deleted or the file deleted was not included in the buffer
                string[] keys = new string[urlToPageDic.Count];
                urlToPageDic.Keys.CopyTo(keys, 0);
                foreach (string key in keys)
                {
                    //when the forward component was same with url ,it was in the directory
                    if (key.Substring(0, url.Length) == url)
                    {
                        RemoveFileInBuffer(key);
                    }
                }

            }

        }

    }
}


text: Rails.application.config.session_store :cookie_store, key: '_Brisk_Mornings_session'

redpajama_set_name: RedPajamaGithub


text:
namespace System.Security.Authentication.ExtendedProtection
{

    public enum TokenBindingType
    {
        Provided = 0,
        Referred = 1
    };

    public class TokenBinding
    {
        internal TokenBinding(TokenBindingType bindingType, byte[] rawData)
        {
            BindingType = bindingType;
            _rawTokenBindingId = rawData;
        }

        private byte[] _rawTokenBindingId = null;

        public byte[] GetRawTokenBindingId()
        {
            return (_rawTokenBindingId != null) ? (byte[])_rawTokenBindingId.Clone() : null;
        }

        public TokenBindingType BindingType
        {
            get;
            private set;
        }
    }
}


text:
'use strict';
/* global postMessage: true */
/* global importScripts: true */
/* global onmessage: true */

var msgId = 0, msgCallbacks = {};
var pendingMessages = [];

var msgCount = 0;
var servers = null;

var consoleLike = {
    log: function (msg) {
        //'use strict';
        postMessage({type: 'log', message: '## cc worker [' + msgCount + '] ' + msg});
    },
    warn: function (msg) {
        //'use strict';
        postMessage({type: 'warn', message: '## cc worker [' + msgCount + '] ' + msg});
    },
    error: function (msg) {
        //'use strict';
        postMessage({type: 'error', message: '## cc worker [' + msgCount + '] ' + msg});
    }
};

importScripts('../lib/require.js');

function send(data, c) {
    //'use strict';

    if (c) {
        data.id = ++msgId;
        msgCallbacks[msgId] = c;
    }
    postMessage(data);
}

function initServers(/*webidaHost, webidaLibPath, otherLibPath*/) {
    if (servers) {
        consoleLike.error('unexpected: servers are already set');
        return;
    }

    require.config({
        baseUrl: '..',
        paths: {
            // 'other-lib': '//library3.' + webidaHost,
            'other-lib': '../../../../../external/src',
            // 'webida-lib': '//library.' + webidaHost + '/webida',
            'webida-lib': '../../../../../common/src/webida',
            text: 'lib/text',
            tern: 'lib/ternjs',
            acorn: 'lib/acorn'
        }
    });

    require(['content-assist/file-server',
             'content-assist/js-hint-server',
             'content-assist/css-hint-server',
             'content-assist/html-hint-server'],
    function (fileServer, jsserver, cssserver, htmlserver) {
        //'use strict';

        function getRemoteFile(filepath, c) {
            //'use strict';

            send({type: 'getRemoteFile', filepath: filepath}, function (data) {
                c(data.error, data.text);
            });
        }

        fileServer.init(getRemoteFile);

        servers = {};
        servers.js = jsserver;
        servers.css = cssserver;
        servers.html = htmlserver;

        consoleLike.log('servers set in CA worker');
    });
}

function handleMessage(message) {
    //'use strict';

    ++msgCount;

    consoleLike.log('handleMessage(' + message.type + ', ' + message.filepath + ')');
    var server = servers[message.mode];

    if (!server && message.type !== 'callback') {
        consoleLike.warn('unknown mode : ' + message.mode);
    }
    switch (message.type) {
    case 'start':
        server.startServer(message.server);
        send({type: 'callback', id: message.id});
        break;
    case 'stop':
        server.stopServer(message.server);
        send({type: 'callback', id: message.id});
        break;
    case 'addFile':
        server.addFile(message.server, message.filepath, message.text);
        break;
    case 'delFile':
        server.delFile(message.server, message.filepath);
        break;
    case 'getFile':
        server.getFile(message.filepath, function (error, data) {
            send({type: 'callback', error: error, data: data, id: message.id});
        });
        break;
    case 'request':
        server.request(message.server, message.body, function (error, data) {
            send({type: 'callback', error: error && error.message, data: data, id: message.id});
        });
        break;
    case 'callback':
        if (message.id && msgCallbacks[message.id]) {
            msgCallbacks[message.id](message);
            delete msgCallbacks[message.id];
        }
        break;
    default:
        consoleLike.error('unknown message type : ' + message.type);
    }
}

var intervalForPendings;

function handlePendings() {
    //'use strict';

    if (servers && intervalForPendings) {
        clearInterval(intervalForPendings);
        intervalForPendings = undefined;
        if (pendingMessages.length > 0) {
            for (var i = 0; i < pendingMessages.length; i++) {
                handleMessage(pendingMessages[i]);
            }
            pendingMessages = [];
        }
    }
}

onmessage = function (e) {
    //'use strict';

    if (e.data.type === 'informHost') {
        initServers(e.data.webidaHost, e.data.webidaLibPath, e.data.otherLibPath);
    } else {
        if (!servers) {
            consoleLike.log('pendingMessages.push(' + e.data.type + ', ' + e.data.server + ')');
            pendingMessages.push(e.data);
            if (!intervalForPendings) {
                intervalForPendings = setInterval(handlePendings, 300);
            }
        } else {
            handlePendings();
            handleMessage(e.data);
        }
    }
};


text:
package org.spacehq.bukkitutils.music;

import org.bukkit.Note;

public interface Track {
	public static final NoteData PAUSE_NOTE = new NoteData(new Note(0), 0);

	public Instrument getInstrument();

	public NoteData nextNote();
}


text:
@import TMTumblrSDK;

@interface TMRequestFactoryTests : XCTestCase

@end

@implementation TMRequestFactoryTests

- (void)testPOSTRequestMethodIsAPOSTRequest {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory POSTRequestWithPath:@"/" JSONParameters:@{}];

    XCTAssert(request.method == TMHTTPRequestMethodPOST);
}

- (void)testPermalinkFactoryMethod {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] init];

    id <TMRequest> request = [requestFactory permalinkRequestWithBlogName:@"pearapps" postID:@"ken"];

    XCTAssertEqualObjects(@"https://api.tumblr.com/v2/blog/pearapps.tumblr.com/posts/ken/permalink", request.URL.absoluteString);
}

- (void)testPermalinkFactoryMethodUUID {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] init];

    id <TMRequest> request = [requestFactory permalinkRequestWithBlogUUID:@"sdihoadspfhdsoiao" postID:@"ken"];

    XCTAssertEqualObjects(@"https://api.tumblr.com/v2/blog/sdihoadspfhdsoiao/posts/ken/permalink", request.URL.absoluteString);

}
- (void)testURLEncodingSimplePath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", @"simpleString"] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/simpleString"]);
}

- (void)testURLEncodingQuestionCharacterInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"didithappen?")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/didithappen%3F"]);
}

- (void)testURLEncodingSpaceCharactersInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"hat cat in ")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/hat%20cat%20in%20"]);
}

- (void)testURLEncodingHashCharactersInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"maybeATag#tag")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/maybeATag%23tag"]);
}

- (void)testURLEncodingPlusCharactersInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"who+why")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/who%2Bwhy"]);
}

- (void)testURLEncodingEqualCharactersInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"hat=cat")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/hat%3Dcat"]);
}

- (void)testURLEncodingForwardSlashCharactersInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"hat/cat")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/hat%2Fcat"]);
}

- (void)testURLEncodingBackwardSlashCharactersInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"hat\\cat")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/hat%5Ccat"]);
}

- (void)testURLEncodingAllSpecialCharactersInPathInLastPositionInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@", TMURLEncode(@"ij#ij+ij/ij/ij+=?\\")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/ij%23ij%2Bij%2Fij%2Fij%2B%3D%3F%5C"]);
}

- (void)testURLEncodingAllSpecialCharactersInPathInMiddlePositionInPath {
    TMRequestFactory *requestFactory = [[TMRequestFactory alloc] initWithBaseURLDeterminer:[[TMBasicBaseURLDeterminer alloc] init]];

    id <TMRequest> request = [requestFactory requestWithPath:[NSString stringWithFormat:@"samplePathComponent1/samplePathComponent2/%@/samplePathComponent3", TMURLEncode(@"ij#ij+ij/ij/ij+=?\\")] method:TMHTTPRequestMethodGET queryParameters:nil];

    XCTAssert([request.URL.absoluteString isEqualToString:@"https://api.tumblr.com/v2/samplePathComponent1/samplePathComponent2/ij%23ij%2Bij%2Fij%2Fij%2B%3D%3F%5C/samplePathComponent3"]);
}

@end


text:
"""A better I2C class for bulk write operations"""

import machine

from mplibs.helpers import chunk

class I2C(machine.I2C):
    def writeto_mem(self, addr, pos, data, chunksize=8):
        chunks = map(bytearray, chunk(data, chunksize))
        current_pos = pos
        for chk in chunks:
            super().writeto_mem(addr, current_pos, chk)
            current_pos += 8


text:
[![Platform](https://img.shields.io/cocoapods/p/Bond.svg?style=flat)](http://cocoadocs.org/docsets/Bond/)
[![CI Status](https://travis-ci.org/ReactiveKit/Bond.svg?branch=master)](https://travis-ci.org/ReactiveKit/Bond)
[![Join Us on Gitter](https://img.shields.io/badge/GITTER-join%20chat-blue.svg)](https://gitter.im/ReactiveKit/General)
[![Twitter](https://img.shields.io/badge/twitter-@srdanrasic-red.svg?style=flat)](https://twitter.com/srdanrasic)

Bond is a Swift binding framework that takes binding concepts to a whole new level. It's simple, powerful, type-safe and multi-paradigm - just like Swift.

Bond is built on top of ReactiveKit and bridges the gap between the reactive and imperative paradigms. You can use it as a standalone framework to simplify your state changes with bindings and reactive data sources, but you can also use it with ReactiveKit to complement your reactive data flows with bindings and reactive delegates and data sources.

### Note: Xcode 9 support

Version 6.3 introduces Xcode 9 support. One of the required changes to support Xcode 9, i.e. Swift 3.2 or 4, was to drop `Collection` conformance from `ObservableArray`, `Observable2DArray`, `ObservableSet` and `ObservableDictionary` types. This is unfortunate, but not problematic as the types expose underlaying collection.

For example, if you were doing

```swift
for element in observableArray { .. }
```

now you need to do

```swift
for element in observableArray.array { .. }
```

Respective underlaying collections for other types are `Observable2DArray.sections`, `ObservableSet.set` and `ObservableDictionary.dictionary`.

Note: Since version 6.4, ReactiveKit is using Swift 4 syntax that compiles under Xcode 9. If you are still using Xcode 8, please do not update to v6.4 and stay on the latest v6.3.x version!

## What can it do?

Let's say you would like to act on a text change event of a `UITextField`. Well, you could setup 'target-action' mechanism between your object and go through all that target-action selector registration pain, or you could simply use Bond and do this:

```swift
textField.reactive.text.observeNext { text in
  print(text)
}
```

Now, instead of printing what the user has typed, you can _bind_ it to a `UILabel`:

```swift
textField.reactive.text.bind(to: label.reactive.text)
```

Because binding to a label text property is so common, you can even do:

```swift
textField.reactive.text.bind(to: label)
```

That one line establishes a binding between text field's text property and label's text property. In effect, whenever user makes a change to the text field, that change will be automatically propagated to the label.

More often than not, direct binding is not enough. Usually you need to transform input is some way, like prepending a greeting to a name. As Bond is backed by ReactiveKit it has full confidence in functional paradigm.

```swift
textField.reactive.text
  .map { "Hi " + $0 }
  .bind(to: label)
```

Whenever a change occurs in the text field, new value will be transformed by the closure and propagated to the label.

Notice how we've used `reactive.text` property of the UITextField. It's an observable representation of the `text` property provided by Bond framework. There are many other extensions like that one for various UIKit components. They are all placed within `.reactive` proxy. Just start typing `.reactive.` any UIKit object and you'll get the list of available extensions.

For example, to observe button events do:

```swift
button.reactive.controlEvents(.touchUpInside)
  .observeNext { e in
    print("Button tapped.")
  }
```

Handling `touchUpInside` event is used so frequently that Bond comes with the extension just for that event:

```swift
button.reactive.tap
  .observeNext {
    print("Button tapped.")
  }
```

You can use any ReactiveKit operators to transform or combine signals. Following snippet depicts how values of two text fields can be reduced to a boolean value and applied to button's enabled property.

```swift
combineLatest(emailField.reactive.text, passField.reactive.text) { email, pass in
    return email.length > 0 && pass.length > 0
  }
  .bind(to: button.reactive.enabled)
```

Whenever user types something into any of these text fields, expression will be evaluated and button state updated.

Bond's power is not, however, in coupling various UI components, but in the binding of a Model (or a ViewModel) to a View and vice-versa. It's great for MVVM paradigm. Here is how one could bind user's number of followers property of the model to the label.

```swift
viewModel.numberOfFollowers
  .map { "\($0)" }
  .bind(to: label)
```

Point here is not in the simplicity of a value assignment to the text property of a label, but in the creation of a binding which automatically updates label text property whenever number of followers change.

Bond also supports two way bindings. Here is an example of how you could keep username text field and username property of your view model in sync (whenever any of them change, other one will be updated too):

```swift
viewModel.username
  .bidirectionalBind(to: usernameTextField.reactive.text)
```

Bond is also great for observing various different events and asynchronous tasks. For example, you could observe a notification just like this:

```swift
NotificationCenter.default.reactive.notification("MyNotification")
  .observeNext { notification in
    print("Got \(notification)")
  }
  .dispose(in: bag)
```

Let me give you one last example. Say you have an array of repositories you would like to display in a collection view. For each repository you have a name and its owner's profile photo. Of course, photo is not immediately available as it has to be downloaded, but once you get it, you want it to appear in collection view's cell. Additionally, when user does 'pull down to refresh' and your array gets new repositories, you want those in collection view too.

So how do you proceed? Well, instead of implementing a data source object, observing photo downloads with KVO and manually updating the collection view with new items, with Bond you can do all that in just few lines:

```swift
repositories.bind(to: collectionView) { array, indexPath, collectionView in
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! RepositoryCell
  let repository = array[indexPath.item]

  repository.name
    .bind(to: cell.nameLabel)
    .dispose(in: cell.onReuseBag)

  repository.photo
    .bind(to: cell.avatarImageView)
    .dispose(in: cell.onReuseBag)

  return cell
}
```

Yes, that's right!

## Observable

Observable wraps mutable state into an object that enables observation of that state. Whenever the state changes, an observer can be notified.

To create the observable, just initialize it with the initial value.

```swift
let name = Observable("Jim")
```

> `nil` is valid value for observables that wrap optional type.

Observables are signals just like signals of `Signal` type from ReactiveKit framework. To learn more about signals, consult [ReactiveKit documentation](https://github.com/ReactiveKit/ReactiveKit). Observables can be transformed into another signals, observed and bound in the same manner as signals can be.

For example, you can register an observer with `observe` or `observeNext` methods.

```swift
name.observeNext { value in
  print("Hi \(value)!")
}
```

> When you register an observer, it will be immediately invoked with the current value of the observable so that snippet will print "Hi Jim!".

To change value of the observable afterwards, just set the `value` property.

```swift
name.value = "Jim Kirk" // Prints: Hi Jim Kirk!
```

Observables, like signals, can be bound to views:

```swift
name.bind(to: nameLabel)
```

> Observable is just a typealias for ReactiveKit `Property` type. You can use that name if it suits you better.

## Bindings

Binding is a connection between a signal or observable that produces events and a bond that observers events and performs certain actions (e.g. updates UI).

The producing side of bindings are signals that are defined in ReactiveKit framework on top of which Bond is built. To learn more about signals, consult [ReactiveKit documentation](https://github.com/ReactiveKit/ReactiveKit).

The consuming side of bindings is represented by the `Bond` type. It's a simple struct that performs an action on a given target whenever the bound signal fires an event.

```swift
public struct Bond<Element>: BindableProtocol {
  public init<Target: Deallocatable>(target: Target, context: ExecutionContext, setter: @escaping (Target, Element) -> Void)
}
```

The only requirement is that the target must be "deallocatable", in other words that it provides a signal of its own deallocation.

```swift
public protocol Deallocatable: class {
  var deallocated: Signal<Void, NoError> { get }
}
```

All NSObject subclasses conform to that protocol out of the box. Let's see how we could implement a Bond for text property of a label. It's recommended to implement reactive extensions on `ReactiveExtensions` proxy protocol. That way you encapsulate extensions within the `.reactive` property.

```swift
extension ReactiveExtensions where Base: UILabel {
  var myTextBond: Bond<String?> {
    return bond { label, text in
      label.text = text
    }
  }
}
```

That's it! To bind any string signal, just use `bind(to:)` method on that bond.

```swift
let name: Signal<String, NoError> = ...
name.bind(to: nameLabel.reactive.myTextBond)
```

> Bonds will automatically ensure that the target object is updated on the main thread (queue). That means that the signal can generate events on a background thread without you worrying how the UI will be updated - it will always happen on the main thread.

Note that you can bind only __non-failable__ signals, i.e. signals with `NoError` error type. Only those kind of signals are safe to represent the data that UI displays.

Bindings will automatically dispose themselves (i.e. cancel source signals) when the binding target gets deallocated. For example, if we do

```swift
blurredImage().bind(to: imageView)
```

then the image processing will be automatically cancelled when the image view gets deallocated. Isn't that cool!

### Inline Bindings

Most of the time you should be able to replace an observation with a binding. Consider the following example. Say we have a signal of users

```swift
let presentUserProfile: Signal<User, NoError> = ...
```

and we would like to present a profile screen when a user is sent on the signal. Usually we would do something like:

```swift
presentUserProfile.observeOn(.main).observeNext { [weak self] user in
  let profileViewController = ProfileViewController(user: user)
  self?.present(profileViewController, animated: true)
}.dispose(in: bag)
```

But that's ugly! We have to dispatch everything to the main queue, be cautious not to create a retain cycle and ensure that the disposable we get from the observation is handled.

Thankfully Bond provides a better way. We can create inline binding instead of the observation. Just do the following

```swift
presentUserProfile.bind(to: self) { me, user in
  let profileViewController = ProfileViewController(user: user)
  me.present(profileViewController, animated: true)
}
```

and stop worrying about threading, retain cycles and disposing  because bindings take care of all that automatically. Just bind a signal to the target responsible for performing side effects (in our example, to the object responsible for presenting a profile view controller). The closure you provide will be called whenever the signal emits an event with both the target and the sent element as arguments.

## Reactive Delegates

Bond provides NSObject extensions that makes it easy to convert delegate pattern into signals.

First make an extension on ReactiveExtensions (where `Base` is defined as your type - `UITableView` in the following example), that provides a reactive delegate proxy:

```swift
extension ReactiveExtensions where Base: UITableView {
  public var delegate: ProtocolProxy {
    return base.protocolProxy(for: UITableViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
  }
}
```

> Note: `reactive.delegate` is already provided by Bond. This is an example of the implementation.

You can then convert methods of that protocol into signals:

```swift
extension UITableView {
  var selectedRow: Signal<Int, NoError> {
    return reactive.delegate.signal(for: #selector(UITableViewDelegate.tableView(_:didSelectRowAtIndexPath:))) { (subject: SafePublishSubject<Int>, _: UITableView, indexPath: IndexPath) in
      subject.next(indexPath.row)
    }
  }
}
```

Method `signal(for:)` takes two parameters: a selector to convert to a signal and a mapping closure that maps selector method arguments into a signal.

Now you can do:

```swift
tableView.selectedRow.observeNext { row in
  print("Tapped row at index \(row).")
}.dispose(in: bag)
```

**Note:** Protocol proxy takes up delegate slot of the object so if you also need to implement delegate methods manually, don't set `tableView.delegate = x`, rather set `tableView.reactive.delegate.forwardTo = x`.

Protocol methods that return values are usually used to query data. Such methods can be set up to be fed from a property type. For example:

```swift
let numberOfItems = Property(12)

tableView.reactive.dataSource.feed(
  property: numberOfItems,
  to: #selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:)),
  map: { (value: Int, _: UITableView, _: Int) -> Int in value }
)
```

Method `feed` takes three parameters: a property to feed from, a selector, and a mapping closure that maps from the property value and selector method arguments to the selector method return value.

You should not set more that one feed property per selector.

Note that in the mapping closures of both `signal(for:)` and `feed` methods you must be explicit about argument and return types.

## Reactive Data Sources

Bond provides a way to make reactive data sources and allows such sources to be easily bound to table or collection views.

Any signal that emits elements of the following type can be bound to a table or collection view

```swift
public struct DataSourceEvent<DataSource: DataSourceProtocol>: DataSourceEventProtocol {
  public let kind: DataSourceEventKind
  public let dataSource: DataSource
}
```

where the data source is any object conforming to `DataSource` protocol

```swift
public protocol DataSourceProtocol {
  func numberOfSections() -> Int
  func numberOfItems(inSection section: Int) -> Int
}
```

and kind is a case of the enumeration `DataSourceEventKind`:

```swift
public enum DataSourceEventKind {
  case reload

  case insertRows([IndexPath])
  case deleteRows([IndexPath])
  case reloadRows([IndexPath])
  case moveRow(IndexPath, IndexPath)

  case insertSections(IndexSet)
  case deleteSections(IndexSet)
  case reloadSections(IndexSet)
  case moveSection(Int, Int)

  case beginUpdates
  case endUpdates
}
```

If you have a signal that emits an array of elements you can bind it to a table view.

```swift
let places = SafeSignal.just(["London", "Berlin", "Copenhagen"])

places.bind(to: tableView) { places, indexPath, tableView in
  let cell = tableView.dequeueCell(withIdentifier: "Cell", for: indexPath) as! PlaceCell
  cell.place = places[indexPath.row]
  return cell
}
```

Whenever the signal emits new array, it will be mapped to a `.reload` event and cause the table view to update. To get fine-grained changes, you should use better data source.

### ObservableArray / MutableObservableArray

When working with arrays, it's usually not enough to know only that the array has changed, but how exactly did it change. New elements could have been inserted into the array and old ones deleted or updated. Bond provides mechanisms for observing such fine-grained changes.

Creating a Signal/Observable/Property of arrays enables observation of the change of the array as whole, but to observe fine-grained changes Bond provides you with the `ObservableArray` type. Just like the Observable, it is a type conforming to SignalProtocol, but instead of sending events that match the wrapped value type, it sends events of the `ObservableArrayChange` type that actually conforms to `DataSourceEventProtocol`. Such event contains both the array itself (the data source) and the change that was just applied to the array (like element insertion or deletion).

To create observable array, just initialize it with the initial array.

```swift
let names = MutableObservableArray(["Steve", "Tim"])
```

When observing observable array, events you receive will contain detailed description of changes that happened.

```swift
names.observeNext { e in
  print("array: \(e.source), change: \(e.change)")
}
```

You work with the observable array like you'd work with the array it encapsulates.

```swift
names.append("John") // prints: array ["Steve", "Tim", "John"], change: .inserts([2])
names.removeLast()   // prints: array ["Steve", "Tim"], change: .deletes([2])
names[1] = "Mark"    // prints: array ["Steve", "Mark"], change: .updates([1])
```

Observable array can be mapped or filtered. For example, if we map our array

```
names.map { $0.characters.count }.observeNext { e in
  print("array: \(e.source), change: \(e.change)")
}
```

then modifying it

```swift
names.append("Tony") // prints: array [5, 3, 4], change: .inserts([2])
```

gives us fine-grained notification of mapped array changes.

Mapping and filtering arrays operates on an array signal. To get the result back as an observable array, just bind it to an instance of ObservableArray.

```swift
let nameLengths = MutableObservableArray<Int>()
names.map { $0.characters.count }.bind(to: nameLengths)
```

Such features enable us to build powerful UI bindings. Observable array can be bound to `UITableView` or `UICollectionView`. Just provide a closure that creates cells to the `bind(to:)` method.

```swift
let posts: ObservableArray <[Post]> = ...

posts.bind(to: tableView) { posts, indexPath, tableView in
  let cell = tableView.dequeueCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
  cell.post = posts[indexPath.row]
  return cell
}
```

Subsequent changes done to the `posts` array will then be automatically reflected in the table view.

#### Array diff

When you need to replace an array with another array, but need an event that contains fine-grained changes (for example to update table/collection view with nice animations), you can use method `replace(with:performDiff:)`. Let's say you have

```swift
let numbers: MutableObservableArray([1, 2, 3])
```

and you do

```swift
numbers.replace(with: [0, 1, 3, 4], performDiff: true)
```

then the row at index path 1 would be deleted and new rows would be inserted at index paths 0 and 3. The view would automatically animate only the changes from the *merge*. Helpful, isn't it.

### Observable2DArray / MutableObservable2DArray

Array is often not enough. Usually our data is grouped into sections. To enable such use case, Bond provides two-dimensional arrays that can be observed and bound to table or collection views.

Let's explain this type by example. First we'll need some sections. A section represents a group of items. Those items, i.e. section can have a metadata associated with it. In iOS it's useful to display section header and footer titles to the user so let's define that as our metadata:

```swift
typealias SectionMetadata = (header: String, footer: String)
```
> If you need only, for example, header title, then you don't need to define separate type. Just use `String` instead of `SectionMetadata` in examples that follow.

Now that we have defined our metadata type, we can create a section:

```swift
let cities = Observable2DArraySection<SectionMetadata, String>(
  metadata: (header: "Cities", footer: "That's it"),
  items: ["Paris", "Berlin"]
)
```

Section is defined with `Observable2DArraySection` type. It's generic over its metadata type and type of the items it can contain. To create a section we passed section metadata and section items.

We can now create an observable 2D array. Let's create mutable variant so we can later modify it.

```swift
let array = MutableObservable2DArray([cities])
```

You just pass it an array of sections. Such array can be bound to a table or collection view. You can bind it the same way as you would bind `ObservableArray`. However, if you want to display header and/or footer titles, you'll need to define `TableViewBond` object.

```swift
struct MyBond: TableViewBond {

  func cellForRow(at indexPath: IndexPath, tableView: UITableView, dataSource: Observable2DArray<SectionMetadata, String>) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel?.text = array[indexPath]
    return cell
  }

  func titleForHeader(in section: Int, dataSource: Observable2DArray<SectionMetadata, String>) -> String? {
    return dataSource[section].metadata.header
  }

  func titleForFooter(in section: Int, dataSource: Observable2DArray<SectionMetadata, String>) -> String? {
    return dataSource[section].metadata.footer
  }
}
```

Only the method `cellForRow:at:tableView:` is required. Other two are optional and are used when we want to show header and/or footer titles.

Method `cellForRow:at:tableView:` describes how cells are instantiated (dequeued) and filled with data. Method `titleForHeader/Footer` just reads section metadata from the data source object and returns it.

> If you don't need to display header and/or footer titles, you don't need to create `TableViewBond` type. Just bind `Observable2DArray` as you would bind `ObservableArray` as described in the previous section of this document.

Now that we have a table view bond type, you can bind our array to the table view:

```swift
array.bind(to: tableView, using: MyBond())
```

We just pass it an instance of table view bond type.

And that's it. If you run that code you'll see a table view with one section that has header and footer and two items.

If you now modify the array like

```swift
array.appendItem("Copenhagen", toSection: 0)
```

the new item will automatically be inserted and animated into the table view.

You can also, for example; add another section:

```swift
let countries = Observable2DArraySection<SectionMetadata, String>(metadata: ("Countries", "No more..."), items: ["France", "Croatia"])
array.appendSection(countries)
```

There are many other methods. Just look at the code reference or source.

## Requirements

* iOS 8.0+ / macOS 10.9+ / tvOS 9.0+
* Xcode 9

## Communication

* If you'd like to ask a general question, use Stack Overflow.
* If you'd like to ask a quick question or chat about the project, try [Gitter](https://gitter.im/ReactiveKit/General).
* If you found a bug, open an issue.
* If you have a feature request, open an issue.
* If you want to contribute, submit a pull request (include unit tests).

## Installation

### Carthage

1. Add the following to your *Cartfile*:
  <br> `github "ReactiveKit/Bond"`
2. Run `carthage update`
3. Add the framework as described in [Carthage Readme](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)

### CocoaPods

1. Add the following to your *Podfile*:
  <br> `pod 'Bond'`
2. Run `pod install`.

## <a name="migration"></a>Migration

### Migration from v5.x to v6.x

* Extensions are moved into `reactive` proxy. Replace occurrences of `bnd_` with `reactive.`. For example `label.bnd_text` becomes `label.reactive.text`. The simplest way is to do _Search and Replace_ in Xcode across the project.
* `Bond<Target, Element>` becomes `Bond<Element>`.
* `DynamicSubject<Target, Element>` becomes `DynamicSubject<Element>`.
* `disposeIn()` is deprecated in favour of `dispose(in:)`.

### Migration from v4.x to v5.x

There are some big changes in Bond v5! Bond is now backed by ReactiveKit framework. All reactive types have been moved down to ReactiveKit. Bond builds its infrastructure on top of ReactiveKit types, primarily on top of `Signal` that serves the purpose of `EventProducer`.

Bindings have been improved and simplified. It gives them better performances and additional uses. ObservableArray has been reimplemented and significantly simplified and optimised. New features are introduced: reactive delegates and reactive data sources.

What that means for you? Well, nothing has changed conceptually so your migration should be easy. Following is a list of changes:

* `EventProducer` is removed. Use Signal from ReactiveKit for reactive programming.
* Operator `deliverOn` is renamed to `observeOn`.
* Method `bindTo` is renamed to `bind(to:)`.
* Method `observe` is renamed to `observeNext`.
* `ObservableArray` is reimplemented. Mapping and filtering it is not supported any more.
* `ObservableArray` is now immutable. Use `MutableObservableArray` instead.
* Table view and collection view binding closure now has the data source as first argument and the index path as second argument.
* KVO can now be established using the methods `keyPath(:ofType:)` / `keyPath(:ofExpectedType:)` on any NSObject subclass.
* `Queue` is removed. Use `DispatchQueue` instead.

## License

The MIT License (MIT)

Copyright (c) 2015-2017 Srdan Rasic (@srdanrasic)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
from pingdomexport import checks
from pingdomexport import configuration

class TestPicker:
    def test_get_strategy_all(self):
        picker = checks.Picker(
            configuration.Checks('all', []),
            {"checks": [{"id":1}, {"id":2}]}
        )
        assert picker.filter() == [{'id': 1}, {'id': 2}]

    def test_get_strategy_include(self):
        picker = checks.Picker(
            configuration.Checks('include', [2]),
            {"checks": [{"id":1}, {"id":2}]}
        )
        assert picker.filter() == [{'id': 2}]

    def test_get_strategy_include_none(self):
        picker = checks.Picker(
            configuration.Checks('include', [3]),
            {"checks": [{"id":1}, {"id":2}]}
        )
        assert picker.filter() == []

    def test_get_strategy_exclude(self):
        picker = checks.Picker(
            configuration.Checks('exclude', [2]),
            {"checks": [{"id":1}, {"id":2}]}
        )
        assert picker.filter() == [{'id': 1}]

    def test_get_strategy_exclude_none(self):
        picker = checks.Picker(
            configuration.Checks('exclude', [5]),
            {"checks": [{"id":1}, {"id":2}]}
        )
        assert picker.filter() == [{'id': 1}, {'id': 2}]

    def test_get_strategy_exclude_all(self):
        picker = checks.Picker(
            configuration.Checks('exclude', [1, 2]),
            {"checks": [{"id":1}, {"id":2}]}
        )
        assert picker.filter() == []


text:
//
//package views.html
//
//import forms.ScenarioForm
//import models.CalculationType
//import play.api.data.Form
//import play.api.data.Forms.{mapping, optional, text}
//import play.twirl.api.Html
//import utils.GmpViewSpec
//import views.OldViewHelpers
//
//class ScenarioSpec extends GmpViewSpec{
//  lazy val gmpMain = app.injector.instanceOf[gmp_main_old]
//  lazy val viewHelpers = app.injector.instanceOf[OldViewHelpers]
//
//  override def view: Html = new views.html.scenario(gmpMain, viewHelpers)(scenarioForm)
// // private val pensionDetailsForm: Form[models.CalculationType] = ScenarioForm.scenarioForm
//
//  val scenarioForm = Form(
//    mapping(
//      "calcType" -> optional(text).verifying(messages("gmp.error.scenario.mandatory"), {x => {x.isDefined && x.get.matches("[0-4]{1}")}})
//    )(CalculationType.apply)(CalculationType.unapply)
//  )
//
//  "Scenario page" must {
//    behave like pageWithTitle(messages("gmp.scenarios.title"))
//    behave like pageWithHeader(messages("gmp.scenarios.title"))
//    behave like pageWithBackLink
//
//    "have correct input labels" in {
//      doc must haveInputLabelWithText("calcType-payableage", "GMP payable age")
//      doc must haveInputLabelWithText("calcType-spa", "State Pension age")
//      doc must haveInputLabelWithText("calcType-survivor", "Survivor")
//      doc must haveInputLabelWithText("calcType-leaving", "Leaving")
//      doc must haveInputLabelWithText("calcType-specificdate", "GMP value on a specific date")
//      doc must haveLegendWithText(messages("gmp.scenarios.title"))
//    }
//
//    "have a continue button" in {
//      doc must haveSubmitButton(messages("gmp.continue.button"))
//    }
//  }
//
//}


text:
#include "third_party/blink/renderer/modules/filesystem/file_writer.h"

#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/renderer/core/events/progress_event.h"
#include "third_party/blink/renderer/core/fileapi/blob.h"
#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/modules/filesystem/file_system_dispatcher.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"

namespace blink {

static const int kMaxRecursionDepth = 3;
static const base::TimeDelta kProgressNotificationInterval =
    base::Milliseconds(50);
static constexpr uint64_t kMaxTruncateLength =
    std::numeric_limits<uint64_t>::max();

FileWriter::FileWriter(ExecutionContext* context)
    : ExecutionContextLifecycleObserver(context),
      ready_state_(kInit),
      operation_in_progress_(kOperationNone),
      queued_operation_(kOperationNone),
      bytes_written_(0),
      bytes_to_write_(0),
      truncate_length_(kMaxTruncateLength),
      num_aborts_(0),
      recursion_depth_(0),
      request_id_(0) {}

FileWriter::~FileWriter() {
  DCHECK(!recursion_depth_);
}

const AtomicString& FileWriter::InterfaceName() const {
  return event_target_names::kFileWriter;
}

void FileWriter::ContextDestroyed() {
  Dispose();
}

bool FileWriter::HasPendingActivity() const {
  return operation_in_progress_ != kOperationNone ||
         queued_operation_ != kOperationNone || ready_state_ == kWriting;
}

void FileWriter::write(Blob* data, ExceptionState& exception_state) {
  if (!GetExecutionContext())
    return;
  DCHECK(data);
  DCHECK_EQ(truncate_length_, kMaxTruncateLength);
  if (ready_state_ == kWriting) {
    SetError(FileErrorCode::kInvalidStateErr, exception_state);
    return;
  }
  if (recursion_depth_ > kMaxRecursionDepth) {
    SetError(FileErrorCode::kSecurityErr, exception_state);
    return;
  }

  blob_being_written_ = data;
  ready_state_ = kWriting;
  bytes_written_ = 0;
  bytes_to_write_ = data->size();
  DCHECK_EQ(queued_operation_, kOperationNone);
  if (operation_in_progress_ != kOperationNone) {
    // We must be waiting for an abort to complete, since m_readyState wasn't
    // kWriting.
    DCHECK_EQ(operation_in_progress_, kOperationAbort);
    queued_operation_ = kOperationWrite;
  } else
    DoOperation(kOperationWrite);

  FireEvent(event_type_names::kWritestart);
}

void FileWriter::seek(int64_t position, ExceptionState& exception_state) {
  if (!GetExecutionContext())
    return;
  if (ready_state_ == kWriting) {
    SetError(FileErrorCode::kInvalidStateErr, exception_state);
    return;
  }

  DCHECK_EQ(truncate_length_, kMaxTruncateLength);
  DCHECK_EQ(queued_operation_, kOperationNone);
  SeekInternal(position);
}

void FileWriter::truncate(int64_t position, ExceptionState& exception_state) {
  if (!GetExecutionContext())
    return;
  DCHECK_EQ(truncate_length_, kMaxTruncateLength);
  if (ready_state_ == kWriting || position < 0) {
    SetError(FileErrorCode::kInvalidStateErr, exception_state);
    return;
  }
  if (recursion_depth_ > kMaxRecursionDepth) {
    SetError(FileErrorCode::kSecurityErr, exception_state);
    return;
  }

  ready_state_ = kWriting;
  bytes_written_ = 0;
  bytes_to_write_ = 0;
  truncate_length_ = position;
  DCHECK_EQ(queued_operation_, kOperationNone);
  if (operation_in_progress_ != kOperationNone) {
    // We must be waiting for an abort to complete, since m_readyState wasn't
    // kWriting.
    DCHECK_EQ(operation_in_progress_, kOperationAbort);
    queued_operation_ = kOperationTruncate;
  } else
    DoOperation(kOperationTruncate);
  FireEvent(event_type_names::kWritestart);
}

void FileWriter::abort(ExceptionState& exception_state) {
  if (!GetExecutionContext())
    return;
  if (ready_state_ != kWriting)
    return;
  ++num_aborts_;

  DoOperation(kOperationAbort);
  SignalCompletion(base::File::FILE_ERROR_ABORT);
}

void FileWriter::DidWriteImpl(int64_t bytes, bool complete) {
  if (operation_in_progress_ == kOperationAbort) {
    CompleteAbort();
    return;
  }
  DCHECK_EQ(kWriting, ready_state_);
  DCHECK_EQ(kMaxTruncateLength, truncate_length_);
  DCHECK_EQ(kOperationWrite, operation_in_progress_);
  DCHECK(!bytes_to_write_ || bytes + bytes_written_ > 0);
  DCHECK(bytes + bytes_written_ <= bytes_to_write_);
  bytes_written_ += bytes;
  DCHECK((bytes_written_ == bytes_to_write_) || !complete);
  SetPosition(position() + bytes);
  if (position() > length())
    SetLength(position());
  if (complete) {
    blob_being_written_.Clear();
    operation_in_progress_ = kOperationNone;
  }

  uint64_t num_aborts = num_aborts_;
  // We could get an abort in the handler for this event. If we do, it's
  // already handled the cleanup and signalCompletion call.
  base::TimeTicks now = base::TimeTicks::Now();
  if (complete || !last_progress_notification_time_.is_null() ||
      (now - last_progress_notification_time_ >
       kProgressNotificationInterval)) {
    last_progress_notification_time_ = now;
    FireEvent(event_type_names::kProgress);
  }

  if (complete) {
    if (num_aborts == num_aborts_)
      SignalCompletion(base::File::FILE_OK);
  }
}

void FileWriter::DidTruncateImpl() {
  if (operation_in_progress_ == kOperationAbort) {
    CompleteAbort();
    return;
  }
  DCHECK_EQ(operation_in_progress_, kOperationTruncate);
  DCHECK_NE(truncate_length_, kMaxTruncateLength);
  SetLength(truncate_length_);
  if (position() > length())
    SetPosition(length());
  operation_in_progress_ = kOperationNone;
  SignalCompletion(base::File::FILE_OK);
}

void FileWriter::DidFailImpl(base::File::Error error) {
  DCHECK_NE(kOperationNone, operation_in_progress_);
  DCHECK_NE(base::File::FILE_OK, error);
  if (operation_in_progress_ == kOperationAbort) {
    CompleteAbort();
    return;
  }
  DCHECK_EQ(kOperationNone, queued_operation_);
  DCHECK_EQ(kWriting, ready_state_);
  blob_being_written_.Clear();
  operation_in_progress_ = kOperationNone;
  SignalCompletion(error);
}

void FileWriter::DoTruncate(const KURL& path, int64_t offset) {
  FileSystemDispatcher::From(GetExecutionContext())
      .Truncate(path, offset, &request_id_,
                WTF::Bind(&FileWriter::DidFinish, WrapWeakPersistent(this)));
}

void FileWriter::DoWrite(const KURL& path,
                         const String& blob_id,
                         int64_t offset) {
  FileSystemDispatcher::From(GetExecutionContext())
      .Write(
          path, blob_id, offset, &request_id_,
          WTF::BindRepeating(&FileWriter::DidWrite, WrapWeakPersistent(this)),
          WTF::Bind(&FileWriter::DidFinish, WrapWeakPersistent(this)));
}

void FileWriter::DoCancel() {
  FileSystemDispatcher::From(GetExecutionContext())
      .Cancel(request_id_,
              WTF::Bind(&FileWriter::DidFinish, WrapWeakPersistent(this)));
}

void FileWriter::CompleteAbort() {
  DCHECK_EQ(operation_in_progress_, kOperationAbort);
  operation_in_progress_ = kOperationNone;
  Operation operation = queued_operation_;
  queued_operation_ = kOperationNone;
  DoOperation(operation);
}

void FileWriter::DoOperation(Operation operation) {
  async_task_context_.Schedule(GetExecutionContext(), "FileWriter");
  switch (operation) {
    case kOperationWrite:
      DCHECK_EQ(kOperationNone, operation_in_progress_);
      DCHECK_EQ(kMaxTruncateLength, truncate_length_);
      DCHECK(blob_being_written_.Get());
      DCHECK_EQ(kWriting, ready_state_);
      Write(position(), blob_being_written_->Uuid());
      break;
    case kOperationTruncate:
      DCHECK_EQ(kOperationNone, operation_in_progress_);
      DCHECK_NE(truncate_length_, kMaxTruncateLength);
      DCHECK_EQ(kWriting, ready_state_);
      Truncate(truncate_length_);
      break;
    case kOperationNone:
      DCHECK_EQ(kOperationNone, operation_in_progress_);
      DCHECK_EQ(kMaxTruncateLength, truncate_length_);
      DCHECK(!blob_being_written_.Get());
      DCHECK_EQ(kDone, ready_state_);
      break;
    case kOperationAbort:
      if (operation_in_progress_ == kOperationWrite ||
          operation_in_progress_ == kOperationTruncate)
        Cancel();
      else if (operation_in_progress_ != kOperationAbort)
        operation = kOperationNone;
      queued_operation_ = kOperationNone;
      blob_being_written_.Clear();
      truncate_length_ = kMaxTruncateLength;
      break;
  }
  DCHECK_EQ(queued_operation_, kOperationNone);
  operation_in_progress_ = operation;
}

void FileWriter::SignalCompletion(base::File::Error error) {
  ready_state_ = kDone;
  truncate_length_ = kMaxTruncateLength;
  if (error != base::File::FILE_OK) {
    error_ = file_error::CreateDOMException(error);
    if (base::File::FILE_ERROR_ABORT == error)
      FireEvent(event_type_names::kAbort);
    else
      FireEvent(event_type_names::kError);
  } else {
    FireEvent(event_type_names::kWrite);
  }
  FireEvent(event_type_names::kWriteend);

  async_task_context_.Cancel();
}

void FileWriter::FireEvent(const AtomicString& type) {
  probe::AsyncTask async_task(GetExecutionContext(), &async_task_context_);
  ++recursion_depth_;
  DispatchEvent(
      *ProgressEvent::Create(type, true, bytes_written_, bytes_to_write_));
  DCHECK_GT(recursion_depth_, 0);
  --recursion_depth_;
}

void FileWriter::SetError(FileErrorCode error_code,
                          ExceptionState& exception_state) {
  DCHECK_NE(error_code, FileErrorCode::kOK);
  file_error::ThrowDOMException(exception_state, error_code);
  error_ = file_error::CreateDOMException(error_code);
}

void FileWriter::Dispose() {
  // Make sure we've actually got something to stop, and haven't already called
  // abort().
  if (ready_state_ == kWriting) {
    DoOperation(kOperationAbort);
    ready_state_ = kDone;
  }
  // Prevents any queued operations from running after abort completes.
  queued_operation_ = kOperationNone;
}

void FileWriter::Trace(Visitor* visitor) const {
  visitor->Trace(error_);
  visitor->Trace(blob_being_written_);
  EventTargetWithInlineData::Trace(visitor);
  FileWriterBase::Trace(visitor);
  ExecutionContextLifecycleObserver::Trace(visitor);
}

}  // namespace blink


text:
MODx.Component = function(config) {
    config = config || {};
    MODx.Component.superclass.constructor.call(this,config);
    this.config = config;

    this._loadForm();
    if (this.config.tabs) {
        this._loadTabs();
    }
    this._loadComponents();
    this._loadActionButtons();
    MODx.activePage = this;
};
Ext.extend(MODx.Component,Ext.Component,{
    fields: {}
    ,form: null
    ,action: false

    ,_loadForm: function() {
        if (!this.config.form) { return false; }
        this.form = new Ext.form.BasicForm(Ext.get(this.config.form),{ errorReader : MODx.util.JSONReader });

        if (this.config.fields) {
            for (var i in this.config.fields) {
                if (this.config.fields.hasOwnProperty(i)) {
                    var f = this.config.fields[i];
                    if (f.xtype) {
                        f = Ext.ComponentMgr.create(f);
                    }
                    this.fields[i] = f;
                    this.form.add(f);
                }
            }
        }
        return this.form.render();
    }

    ,_loadActionButtons: function() {
        if (!this.config.buttons) { return false; }

        this.ab = MODx.load({
            xtype: 'modx-actionbuttons'
            ,form: this.form || null
            ,formpanel: this.config.formpanel || null
            ,actions: this.config.actions || null
            ,items: this.config.buttons || []
        });
        return this.ab;
    }

    ,_loadTabs: function() {
        if (!this.config.tabs) { return false; }
        var o = this.config.tabOptions || {};
        Ext.applyIf(o,{
            xtype: 'modx-tabs'
            ,renderTo: this.config.tabs_div || 'tabs_div'
            ,items: this.config.tabs
        });
        return MODx.load(o);
    }

    ,_loadComponents: function() {
        if (!this.config.components) { return false; }
        var l = this.config.components.length;

        var cp = Ext.getCmp('modx-content');
        for (var i=0;i<l;i=i+1) {
            var a = MODx.load(this.config.components[i]);
            if (cp) {
                cp.add(a);
            }
        }
        if (cp) {
            cp.doLayout();
        }
        return true;
    }

    ,submitForm: function(listeners,options,otherParams) {
        listeners = listeners || {};
        otherParams = otherParams || {};
        if (!this.config.formpanel || !this.config.action) { return false; }
        f = Ext.getCmp(this.config.formpanel);
        if (!f) { return false; }

        for (var i in listeners) {
            if (typeof listeners[i] == 'function') {
                f.on(i,listeners[i],this);
            } else if (listeners[i] && typeof listeners[i] == 'object' && listeners[i].fn) {
                f.on(i,listeners[i].fn,listeners[i].scope || this);
            }
        }

        Ext.apply(f.baseParams,{
            'action':this.config.action
        });
        Ext.apply(f.baseParams,otherParams);
        options = options || {};
        options.headers = {
            'Powered-By': 'MODx'
            ,'modAuth': MODx.siteId
        };
        f.submit(options);
        return true;
    }
});
Ext.reg('modx-component',MODx.Component);

MODx.toolbar.ActionButtons = function(config) {
    config = config || {};
    Ext.applyIf(config,{
        actions: { 'close': 'welcome' }
        ,formpanel: false
        ,id: 'modx-action-buttons'
        ,params: {}
        ,items: []
        ,renderTo: Ext.get('modx-action-buttons-container') ? 'modx-action-buttons-container' : 'modx-container'
    });
    if (config.formpanel) {
        this.setupDirtyButtons(config.formpanel);
    }
    this.checkDirtyBtns = [];
    MODx.toolbar.ActionButtons.superclass.constructor.call(this,config);
    this.config = config;
};
Ext.extend(MODx.toolbar.ActionButtons,Ext.Toolbar,{
    id: ''
    ,buttons: []
    ,options: { a_close: 'welcome' }

    ,add: function() {
        var a = arguments, l = a.length;
        for(var i = 0; i < l; i++) {
            var el = a[i];
            var ex = ['-','->','<-','',' '];
            if (ex.indexOf(el) != -1 || (el.xtype && el.xtype == 'switch')) {
                MODx.toolbar.ActionButtons.superclass.add.call(this,el);
                continue;
            }

            var id = el.id || Ext.id();
            Ext.applyIf(el,{
                xtype: 'button'
                ,cls: (el.icon ? 'x-btn-icon bmenu' : 'x-btn-text bmenu')
                ,scope: this
                ,disabled: el.checkDirty ? true : false
                ,listeners: {}
                ,id: id
            });
            if (el.button) {
                MODx.toolbar.ActionButtons.superclass.add.call(this,el);
            }

            if (el.handler === null && el.menu === null) {
                el.handler = this.checkConfirm;
            } else if (el.confirm && el.handler) {
                el.handler = function() {
                    Ext.Msg.confirm(_('warning'),el.confirm,function(e) {
                      if (e === 'yes') { Ext.callback(el.handler,this); }
                    },el.scope || this);
                };
            } else if (el.handler) {} else { el.handler = this.handleClick; }

            /* if javascript is specified, run it when button is click, before this.checkConfirm is run */
            if (el.javascript) {
                el.listeners['click'] = {fn:this.evalJS,scope:this};
            }

            /* if checkDirty, disable until field change */
            if (el.xtype == 'button') {
                el.listeners['render'] = {fn:function(btn) {
                    if (el.checkDirty && btn) {
                        this.checkDirtyBtns.push(btn);
                    }
                },scope:this}
            }

            if (el.keys) {
                el.keyMap = new Ext.KeyMap(Ext.get(document));
                for (var j = 0; j < el.keys.length; j++) {
                    var key = el.keys[j];
                    Ext.applyIf(key,{
                        scope: this
                        ,stopEvent: true
                        ,fn: function(e) {
                            var b = Ext.getCmp(id);
                            if (b) this.checkConfirm(b,e);
                        }
                    });
                    el.keyMap.addBinding(key);
                }
                el.listeners['destroy'] = {fn:function(btn) {
                    btn.keyMap.disable();
                },scope:this}
            }

            /* add button to toolbar */
            MODx.toolbar.ActionButtons.superclass.add.call(this,el);
        }
    }

    ,evalJS: function(itm,e) {
        if (!eval(itm.javascript)) {
            e.stopEvent();
            e.preventDefault();
        }
    }

    ,checkConfirm: function(itm,e) {
        if (itm.confirm !== null && itm.confirm !== undefined) {
            this.confirm(itm,function() {
                this.handleClick(itm,e);
            },this);
        } else { this.handleClick(itm,e); }
        return false;
    }

    ,confirm: function(itm,callback,scope) {
        /* if no message go ahead and redirect...we dont like blank questions */
        if (itm.confirm === null) { return true; }

        Ext.Msg.confirm('',itm.confirm,function(e) {
            /* if the user is okay with the action */
            if (e === 'yes') {
                if (callback === null) { return true; }
                if (typeof(callback) === 'function') { /* if callback is a function, run it, and pass Button */
                    Ext.callback(callback,scope || this,[itm]);
                } else { location.href = callback; }
            }
            return true;
        },this);
        return true;
    }

    ,reloadPage: function() {
        location.href = location.href;
    }

    ,handleClick: function(itm,e) {
        var o = this.config;
        if (o.formpanel === false || o.formpanel === undefined || o.formpanel === null) return false;

        if (itm.method === 'remote') { /* if using connectors */
            MODx.util.Progress.reset();
            o.form = Ext.getCmp(o.formpanel);
            if (!o.form) return false;

            var f = o.form.getForm ? o.form.getForm() : o.form;
            var isv = true;
            if (f.items && f.items.items) {
                for (var fld in f.items.items) {
                    if (f.items.items[fld] && f.items.items[fld].validate) {
                        var fisv = f.items.items[fld].validate();
                        if (!fisv) {
                            f.items.items[fld].markInvalid();
                            isv = false;
                        }
                    }
                }
            }

            if (isv) {
                Ext.applyIf(o.params,{
                    action: itm.process
                });

                Ext.apply(f.baseParams,o.params);

                o.form.on('success',function(r) {
                    if (o.form.clearDirty) o.form.clearDirty();
                    /* allow for success messages */
                    MODx.msg.status({
                        title: _('success')
                        ,message: r.result.message || _('save_successful')
                        ,dontHide: r.result.message != '' ? true : false
                    });

                    if (itm.redirect != false) {
                        var redirect = this.redirect;

                        if (typeof itm.redirect == 'function') {
                            redirect = itm.redirect;
                        }

                        Ext.callback(redirect,this,[o,itm,r.result],1000);
                    }

                    this.resetDirtyButtons(r.result);
                },this);
                o.form.submit({
                    headers: {
                        'Powered-By': 'MODx'
                        ,'modAuth': MODx.siteId
                    }
                });
            } else {
                Ext.Msg.alert(_('error'),_('correct_errors'));
            }
        } else {
            // if just doing a URL redirect
            var params = itm.params || {};
            Ext.applyIf(params, o.baseParams || {});
            MODx.loadPage('?' + Ext.urlEncode(params));
        }
        return false;
    }

    ,resetDirtyButtons: function(r) {
        for (var i=0;i<this.checkDirtyBtns.length;i=i+1) {
            var btn = this.checkDirtyBtns[i];
            btn.setDisabled(true);
        }
    }

    ,redirect: function(o,itm,res) {
        o = this.config;
        itm.params = itm.params || {};
        Ext.applyIf(itm.params,o.baseParams);
        var url;

        var process = itm.process.substr(itm.process.lastIndexOf('/') + 1);
        if ((process === 'create' || process === 'duplicate' || itm.reload) && res.object.id) {
            itm.params.id = res.object.id;
            if (MODx.request.parent) { itm.params.parent = MODx.request.parent; }
            if (MODx.request.context_key) { itm.params.context_key = MODx.request.context_key; }
            url = Ext.urlEncode(itm.params);
            var action;
            if (o.actions && o.actions.edit) {
                // If an edit action is given, use it (BC)
                action = o.actions.edit;
            } else {
                // Else assume we want the 'update' controller
                action = itm.process.replace('create', 'update');
            }
            MODx.loadPage(action, url);

        } else if (process === 'delete') {
            itm.params.a = o.actions.cancel;
            url = Ext.urlEncode(itm.params);
            MODx.loadPage('?'+url);
        }
    }

    ,refreshTreeNode: function(tree,node,self) {
        var t = parent.Ext.getCmp(tree);
        t.refreshNode(node,self || false);
        return false;
    }

    ,setupDirtyButtons: function(f) {
        var fp = Ext.getCmp(f);
        if (fp) {
            fp.on('fieldChange',function(o) {
               for (var i=0;i<this.checkDirtyBtns.length;i=i+1) {
                    var btn = this.checkDirtyBtns[i];
                    btn.setDisabled(false);
               }
            },this);
        }
    }
});
Ext.reg('modx-actionbuttons',MODx.toolbar.ActionButtons);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.gradoop</groupId>
    <artifactId>magimport-parse</artifactId>
    <version>0.2-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.gradoop</groupId>
        <artifactId>magimport-parent</artifactId>
        <version>0.2-SNAPSHOT</version>
    </parent>
    <developers>
        <developer>
            <id>p-f</id>
            <name>Philip Fritzsche</name>
            <email>philipfritzsche@ymail.com</email>
            <roles>
                <role>Maintainer</role>
            </roles>
        </developer>
        <developer>
            <id>traderjoe95</id>
            <name>Johannes Leupold</name>
            <email>johannes.leupold@studserv.uni-leipzig.de</email>
            <roles>
                <role>Developer</role>
            </roles>
        </developer>
        <developer>
            <id>timo95</id>
            <name>Timo Adameit</name>
            <email>timo@timo-adameit.de</email>
            <roles>
                <role>Developer</role>
            </roles>
        </developer>
    </developers>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <!--archive>
                        <manifest>
                            <mainClass>one.p_f.testing.magimport.ImportMain</mainClass>
                        </manifest>
                    </archive-->
                </configuration>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <configuration>
                    <configLocation>config/sun_checks.xml</configLocation>
                </configuration>
            </plugin>
        </plugins>
    </reporting>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <netbeans.hint.license>apache20</netbeans.hint.license>
    </properties>
</project>


text:
package org.moparscape.elysium.world;

/**
 * Created by IntelliJ IDEA.
 *
 * @author lothy
 */
public class Point {

    protected final short x;

    protected final short y;

    public Point(int x, int y) {
        if (x < 0 || x > World.MAX_WIDTH) {
            throw new IllegalArgumentException("Invalid x ordinate: " + x);
        }

        if (y < 0 || y > World.MAX_HEIGHT) {
            throw new IllegalArgumentException("Invalid y ordinate: " + y);
        }

        this.x = (short) x;
        this.y = (short) y;
    }

    public final int getX() {
        return x;
    }

    public final int getY() {
        return y;
    }

    @Override
    public int hashCode() {
        return (x << 16) | y;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (o == null || !(o instanceof Point)) {
            return false;
        }

        Point p = (Point) o;
        return this.x == p.x && this.y == p.y;
    }

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }

    public boolean withinRange(Point target, int radius) {
        int xDiff = Math.abs(this.x - target.x);
        int yDiff = Math.abs(this.y - target.y);
        return xDiff <= radius && yDiff <= radius;
    }
}