<commit_before>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @implements {WebInspector.ProjectDelegate}
 * @extends {WebInspector.Object}
 * @param {WebInspector.IsolatedFileSystem} isolatedFileSystem
 * @param {WebInspector.Workspace} workspace
 */
WebInspector.FileSystemProjectDelegate = function(isolatedFileSystem, workspace)
{
    this._fileSystem = isolatedFileSystem;
    this._workspace = workspace;
}

WebInspector.FileSystemProjectDelegate._scriptExtensions = ["js", "java", "cc", "cpp", "h", "cs", "py", "php"].keySet();

WebInspector.FileSystemProjectDelegate.projectId = function(fileSystemPath)
{
    return "filesystem:" + fileSystemPath;
}

WebInspector.FileSystemProjectDelegate.prototype = {
    /**
     * @return {string}
     */
    id: function()
    {
        return WebInspector.FileSystemProjectDelegate.projectId(this._fileSystem.path());
    },

    /**
     * @return {string}
     */
    type: function()
    {
        return WebInspector.projectTypes.FileSystem;
    },

    /**
     * @return {string}
     */
    fileSystemPath: function()
    {
        return this._fileSystem.path();
    },

    /**
     * @return {string}
     */
    displayName: function()
    {
        return this._fileSystem.path().substr(this._fileSystem.path().lastIndexOf("/") + 1);
    },

    /**
     * @param {Array.<string>} path
     * @return {string}
     */
    _filePathForPath: function(path)
    {
        return "/" + path.join("/");
    },

    /**
     * @param {Array.<string>} path
     * @param {function(?string,boolean,string)} callback
     */
    requestFileContent: function(path, callback)
    {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestFileContent(filePath, innerCallback.bind(this));

        /**
         * @param {?string} content
         */
        function innerCallback(content)
        {
            var contentType = this._contentTypeForPath(path);
            callback(content, false, contentType.canonicalMimeType());
        }
    },

    /**
     * @return {boolean}
     */
    canSetFileContent: function()
    {
        return true;
    },

    /**
     * @param {Array.<string>} path
     * @param {string} newContent
     * @param {function(?string)} callback
     */
    setFileContent: function(path, newContent, callback)
    {
        var filePath = this._filePathForPath(path);
        this._fileSystem.setFileContent(filePath, newContent, callback.bind(this, ""));
    },

    /**
     * @param {Array.<string>} path
     * @param {string} query
     * @param {boolean} caseSensitive
     * @param {boolean} isRegex
     * @param {function(Array.<WebInspector.ContentProvider.SearchMatch>)} callback
     */
    searchInFileContent: function(path, query, caseSensitive, isRegex, callback)
    {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestFileContent(filePath, contentCallback.bind(this));

        /**
         * @param {?string} content
         */
        function contentCallback(content)
        {
            var result = [];
            if (content !== null)
                result = WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex);
            callback(result);
        }
    },

    /**
     * @param {Array.<string>} path
     * @return {WebInspector.ResourceType}
     */
    _contentTypeForPath: function(path)
    {
        var fileName = path[path.length - 1];
        var extensionIndex = fileName.lastIndexOf(".");
        var extension = "";
        if (extensionIndex !== -1)
            extension = fileName.substring(extensionIndex + 1);
        var contentType = WebInspector.resourceTypes.Other;
        if (WebInspector.FileSystemProjectDelegate._scriptExtensions[extension])
            return WebInspector.resourceTypes.Script;
        if (extension === "css")
            return WebInspector.resourceTypes.Stylesheet;
        if (extension === "html")
            return WebInspector.resourceTypes.Document;
        return WebInspector.resourceTypes.Other;
    },

    populate: function()
    {
        this._fileSystem.requestFilesRecursive("", fileLoaded.bind(this));

        function fileLoaded(filePath)
        {
            var path = filePath.split("/");
            path.shift();
            console.assert(path.length);
            var fullPath = this._fileSystem.path() + filePath;
            var url = this._workspace.urlForPath(fullPath);
            var contentType = this._contentTypeForPath(path);
            var fileDescriptor = new WebInspector.FileDescriptor(path, "file://" + fullPath, url, contentType, true);
            this._addFile(fileDescriptor);
        }
    },

    /**
     * @param {WebInspector.FileDescriptor} fileDescriptor
     */
    _addFile: function(fileDescriptor)
    {
        this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileAdded, fileDescriptor);
    },

    /**
     * @param {Array.<string>} path
     */
    _removeFile: function(path)
    {
        this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileRemoved, path);
    },

    reset: function()
    {
        this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.Reset, null);
    },

    __proto__: WebInspector.Object.prototype
}

/**
 * @type {?WebInspector.FileSystemProjectDelegate}
 */
WebInspector.fileSystemProjectDelegate = null;

/**
 * @constructor
 * @param {WebInspector.IsolatedFileSystemManager} isolatedFileSystemManager
 * @param {WebInspector.Workspace} workspace
 */
WebInspector.FileSystemWorkspaceProvider = function(isolatedFileSystemManager, workspace)
{
    this._isolatedFileSystemManager = isolatedFileSystemManager;
    this._workspace = workspace;
    this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemAdded, this._fileSystemAdded, this);
    this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemRemoved, this._fileSystemRemoved, this);
    this._simpleProjectDelegates = {};
}

WebInspector.FileSystemWorkspaceProvider.prototype = {
    /**
     * @param {WebInspector.Event} event
     */
    _fileSystemAdded: function(event)
    {
        var fileSystem = /** @type {WebInspector.IsolatedFileSystem} */ (event.data);
        var projectId = WebInspector.FileSystemProjectDelegate.projectId(fileSystem.path());
        var projectDelegate = new WebInspector.FileSystemProjectDelegate(fileSystem, this._workspace)
        this._simpleProjectDelegates[projectDelegate.id()] = projectDelegate;
        console.assert(!this._workspace.project(projectDelegate.id()));
        this._workspace.addProject(projectDelegate);
        projectDelegate.populate();
    },

    /**
     * @param {WebInspector.Event} event
     */
    _fileSystemRemoved: function(event)
    {
        var fileSystem = /** @type {WebInspector.IsolatedFileSystem} */ (event.data);
        var projectId = WebInspector.FileSystemProjectDelegate.projectId(fileSystem.path());
        this._workspace.removeProject(projectId);
        delete this._simpleProjectDelegates[projectId];
    },

    /**
     * @param {WebInspector.UISourceCode} uiSourceCode
     */
    fileSystemPath: function(uiSourceCode)
    {
        var projectDelegate = this._simpleProjectDelegates[uiSourceCode.project().id()];
        return projectDelegate.fileSystemPath();
    }
}

/**
 * @type {?WebInspector.FileSystemWorkspaceProvider}
 */
WebInspector.fileSystemWorkspaceProvider = null;
<commit_msg>DevTools: Highlight Sass sources loaded from the local filesystem<commit_after>/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @implements {WebInspector.ProjectDelegate}
 * @extends {WebInspector.Object}
 * @param {WebInspector.IsolatedFileSystem} isolatedFileSystem
 * @param {WebInspector.Workspace} workspace
 */
WebInspector.FileSystemProjectDelegate = function(isolatedFileSystem, workspace)
{
    this._fileSystem = isolatedFileSystem;
    this._workspace = workspace;
}

WebInspector.FileSystemProjectDelegate._scriptExtensions = ["js", "java", "cc", "cpp", "h", "cs", "py", "php"].keySet();
WebInspector.FileSystemProjectDelegate._styleSheetExtensions = ["css", "scss", "sass"].keySet();

WebInspector.FileSystemProjectDelegate.projectId = function(fileSystemPath)
{
    return "filesystem:" + fileSystemPath;
}

WebInspector.FileSystemProjectDelegate.prototype = {
    /**
     * @return {string}
     */
    id: function()
    {
        return WebInspector.FileSystemProjectDelegate.projectId(this._fileSystem.path());
    },

    /**
     * @return {string}
     */
    type: function()
    {
        return WebInspector.projectTypes.FileSystem;
    },

    /**
     * @return {string}
     */
    fileSystemPath: function()
    {
        return this._fileSystem.path();
    },

    /**
     * @return {string}
     */
    displayName: function()
    {
        return this._fileSystem.path().substr(this._fileSystem.path().lastIndexOf("/") + 1);
    },

    /**
     * @param {Array.<string>} path
     * @return {string}
     */
    _filePathForPath: function(path)
    {
        return "/" + path.join("/");
    },

    /**
     * @param {Array.<string>} path
     * @param {function(?string,boolean,string)} callback
     */
    requestFileContent: function(path, callback)
    {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestFileContent(filePath, innerCallback.bind(this));

        /**
         * @param {?string} content
         */
        function innerCallback(content)
        {
            var contentType = this._contentTypeForPath(path);
            callback(content, false, contentType.canonicalMimeType());
        }
    },

    /**
     * @return {boolean}
     */
    canSetFileContent: function()
    {
        return true;
    },

    /**
     * @param {Array.<string>} path
     * @param {string} newContent
     * @param {function(?string)} callback
     */
    setFileContent: function(path, newContent, callback)
    {
        var filePath = this._filePathForPath(path);
        this._fileSystem.setFileContent(filePath, newContent, callback.bind(this, ""));
    },

    /**
     * @param {Array.<string>} path
     * @param {string} query
     * @param {boolean} caseSensitive
     * @param {boolean} isRegex
     * @param {function(Array.<WebInspector.ContentProvider.SearchMatch>)} callback
     */
    searchInFileContent: function(path, query, caseSensitive, isRegex, callback)
    {
        var filePath = this._filePathForPath(path);
        this._fileSystem.requestFileContent(filePath, contentCallback.bind(this));

        /**
         * @param {?string} content
         */
        function contentCallback(content)
        {
            var result = [];
            if (content !== null)
                result = WebInspector.ContentProvider.performSearchInContent(content, query, caseSensitive, isRegex);
            callback(result);
        }
    },

    /**
     * @param {Array.<string>} path
     * @return {WebInspector.ResourceType}
     */
    _contentTypeForPath: function(path)
    {
        var fileName = path[path.length - 1];
        var extensionIndex = fileName.lastIndexOf(".");
        var extension = "";
        if (extensionIndex !== -1)
            extension = fileName.substring(extensionIndex + 1).toLowerCase();
        var contentType = WebInspector.resourceTypes.Other;
        if (WebInspector.FileSystemProjectDelegate._scriptExtensions[extension])
            return WebInspector.resourceTypes.Script;
        if (WebInspector.FileSystemProjectDelegate._styleSheetExtensions[extension])
            return WebInspector.resourceTypes.Stylesheet;
        if (extension === "html" || extension === "htm")
            return WebInspector.resourceTypes.Document;
        return WebInspector.resourceTypes.Other;
    },

    populate: function()
    {
        this._fileSystem.requestFilesRecursive("", fileLoaded.bind(this));

        function fileLoaded(filePath)
        {
            var path = filePath.split("/");
            path.shift();
            console.assert(path.length);
            var fullPath = this._fileSystem.path() + filePath;
            var url = this._workspace.urlForPath(fullPath);
            var contentType = this._contentTypeForPath(path);
            var fileDescriptor = new WebInspector.FileDescriptor(path, "file://" + fullPath, url, contentType, true);
            this._addFile(fileDescriptor);
        }
    },

    /**
     * @param {WebInspector.FileDescriptor} fileDescriptor
     */
    _addFile: function(fileDescriptor)
    {
        this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileAdded, fileDescriptor);
    },

    /**
     * @param {Array.<string>} path
     */
    _removeFile: function(path)
    {
        this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.FileRemoved, path);
    },

    reset: function()
    {
        this.dispatchEventToListeners(WebInspector.ProjectDelegate.Events.Reset, null);
    },

    __proto__: WebInspector.Object.prototype
}

/**
 * @type {?WebInspector.FileSystemProjectDelegate}
 */
WebInspector.fileSystemProjectDelegate = null;

/**
 * @constructor
 * @param {WebInspector.IsolatedFileSystemManager} isolatedFileSystemManager
 * @param {WebInspector.Workspace} workspace
 */
WebInspector.FileSystemWorkspaceProvider = function(isolatedFileSystemManager, workspace)
{
    this._isolatedFileSystemManager = isolatedFileSystemManager;
    this._workspace = workspace;
    this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemAdded, this._fileSystemAdded, this);
    this._isolatedFileSystemManager.addEventListener(WebInspector.IsolatedFileSystemManager.Events.FileSystemRemoved, this._fileSystemRemoved, this);
    this._simpleProjectDelegates = {};
}

WebInspector.FileSystemWorkspaceProvider.prototype = {
    /**
     * @param {WebInspector.Event} event
     */
    _fileSystemAdded: function(event)
    {
        var fileSystem = /** @type {WebInspector.IsolatedFileSystem} */ (event.data);
        var projectId = WebInspector.FileSystemProjectDelegate.projectId(fileSystem.path());
        var projectDelegate = new WebInspector.FileSystemProjectDelegate(fileSystem, this._workspace)
        this._simpleProjectDelegates[projectDelegate.id()] = projectDelegate;
        console.assert(!this._workspace.project(projectDelegate.id()));
        this._workspace.addProject(projectDelegate);
        projectDelegate.populate();
    },

    /**
     * @param {WebInspector.Event} event
     */
    _fileSystemRemoved: function(event)
    {
        var fileSystem = /** @type {WebInspector.IsolatedFileSystem} */ (event.data);
        var projectId = WebInspector.FileSystemProjectDelegate.projectId(fileSystem.path());
        this._workspace.removeProject(projectId);
        delete this._simpleProjectDelegates[projectId];
    },

    /**
     * @param {WebInspector.UISourceCode} uiSourceCode
     */
    fileSystemPath: function(uiSourceCode)
    {
        var projectDelegate = this._simpleProjectDelegates[uiSourceCode.project().id()];
        return projectDelegate.fileSystemPath();
    }
}

/**
 * @type {?WebInspector.FileSystemWorkspaceProvider}
 */
WebInspector.fileSystemWorkspaceProvider = null;
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

if (!window.InspectorFrontendHost) {

/**
 * @constructor
 * @implements {InspectorFrontendHostAPI}
 */
WebInspector.InspectorFrontendHostStub = function()
{
    this._attachedWindowHeight = 0;
    this.isStub = true;
    this._fileBuffers = {};
    WebInspector.documentCopyEventFired = this.documentCopy.bind(this);
}

WebInspector.InspectorFrontendHostStub.prototype = {
    getSelectionBackgroundColor: function()
    {
        return "#6e86ff";
    },

    getSelectionForegroundColor: function()
    {
        return "#ffffff";
    },

    platform: function()
    {
        var match = navigator.userAgent.match(/Windows NT/);
        if (match)
            return "windows";
        match = navigator.userAgent.match(/Mac OS X/);
        if (match)
            return "mac";
        return "linux";
    },

    port: function()
    {
        return "unknown";
    },

    bringToFront: function()
    {
        this._windowVisible = true;
    },

    closeWindow: function()
    {
        this._windowVisible = false;
    },

    requestSetDockSide: function(side)
    {
        InspectorFrontendAPI.setDockSide(side);
    },

    setAttachedWindowHeight: function(height)
    {
    },

    moveWindowBy: function(x, y)
    {
    },

    setInjectedScriptForOrigin: function(origin, script)
    {
    },

    loaded: function()
    {
    },

    localizedStringsURL: function()
    {
        return undefined;
    },

    inspectedURLChanged: function(url)
    {
        document.title = WebInspector.UIString(Preferences.applicationTitle, url);
    },

    documentCopy: function(event)
    {
        if (!this._textToCopy)
            return;
        event.clipboardData.setData("text", this._textToCopy);
        event.preventDefault();
        delete this._textToCopy;
    },

    copyText: function(text)
    {
        this._textToCopy = text;
        if (!document.execCommand("copy")) {
            var screen = new WebInspector.ClipboardAccessDeniedScreen();
            screen.showModal();
        }
    },

    openInNewTab: function(url)
    {
        window.open(url, "_blank");
    },

    canSave: function()
    {
        return true;
    },

    save: function(url, content, forceSaveAs)
    {
        if (this._fileBuffers[url])
            throw new Error("Concurrent file modification denied.");

        this._fileBuffers[url] = [content];
        setTimeout(WebInspector.fileManager.savedURL.bind(WebInspector.fileManager, url), 0);
    },

    append: function(url, content)
    {
        var buffer = this._fileBuffers[url];
        if (!buffer)
            throw new Error("File is not open for write yet.");

        buffer.push(content);
        setTimeout(WebInspector.fileManager.appendedToURL.bind(WebInspector.fileManager, url), 0);
    },

    close: function(url)
    {
        var content = this._fileBuffers[url];
        delete this._fileBuffers[url];

        if (!content)
            return;

        var lastSlashIndex = url.lastIndexOf("/");
        var fileNameSuffix = (lastSlashIndex === -1) ? url : url.substring(lastSlashIndex + 1);

        var blob = new Blob(content, { type: "application/octet-stream" });
        var objectUrl = window.URL.createObjectURL(blob);
        window.location = objectUrl + "#/" + fileNameSuffix;

        function cleanup()
        {
            window.URL.revokeObjectURL(objectUrl);
        }
        setTimeout(cleanup, 3000);
    },

    sendMessageToBackend: function(message)
    {
    },

    recordActionTaken: function(actionCode)
    {
    },

    recordPanelShown: function(panelCode)
    {
    },

    recordSettingChanged: function(settingCode)
    {
    },

    loadResourceSynchronously: function(url)
    {
        return loadXHR(url);
    },

    supportsFileSystems: function()
    {
        return false;
    },

    requestFileSystems: function()
    {
    },

    addFileSystem: function()
    {
    },

    removeFileSystem: function(fileSystemPath)
    {
    },

    isolatedFileSystem: function(fileSystemId, registeredName)
    {
        return null;
    },

    indexPath: function(requestId, fileSystemPath)
    {
    },

    stopIndexing: function(requestId)
    {
    },

    searchInPath: function(requestId, fileSystemPath, query)
    {
    },

    setZoomFactor: function(zoom)
    {
    },

    isUnderTest: function()
    {
        return false;
    }
}

InspectorFrontendHost = new WebInspector.InspectorFrontendHostStub();

/**
 * @constructor
 * @extends {WebInspector.HelpScreen}
 */
WebInspector.ClipboardAccessDeniedScreen = function()
{
    WebInspector.HelpScreen.call(this, WebInspector.UIString("Clipboard access is denied"));
    var platformMessage = WebInspector.UIString("You need to install a Chrome extension that grants clipboard access to Developer Tools.");
    if (platformMessage) {
        var p = this.contentElement.createChild("p");
        p.addStyleClass("help-section");
        p.textContent = platformMessage;
    }
}

WebInspector.ClipboardAccessDeniedScreen.prototype = {
    __proto__: WebInspector.HelpScreen.prototype
}

}

/**
 * @constructor
 * @extends {WebInspector.HelpScreen}
 */
WebInspector.RemoteDebuggingTerminatedScreen = function(reason)
{
    WebInspector.HelpScreen.call(this, WebInspector.UIString("Detached from the target"));
    var p = this.contentElement.createChild("p");
    p.addStyleClass("help-section");
    p.createChild("span").textContent = "Remote debugging has been terminated with reason: ";
    p.createChild("span", "error-message").textContent = reason;
    p.createChild("br");
    p.createChild("span").textContent = "Please re-attach to the new target.";
}

WebInspector.RemoteDebuggingTerminatedScreen.prototype = {
    __proto__: WebInspector.HelpScreen.prototype
}
<commit_msg>Remove unused variable in InspectorFrontendHostStub.<commit_after>/*
 * Copyright (C) 2009 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

if (!window.InspectorFrontendHost) {

/**
 * @constructor
 * @implements {InspectorFrontendHostAPI}
 */
WebInspector.InspectorFrontendHostStub = function()
{
    this.isStub = true;
    this._fileBuffers = {};
    WebInspector.documentCopyEventFired = this.documentCopy.bind(this);
}

WebInspector.InspectorFrontendHostStub.prototype = {
    getSelectionBackgroundColor: function()
    {
        return "#6e86ff";
    },

    getSelectionForegroundColor: function()
    {
        return "#ffffff";
    },

    platform: function()
    {
        var match = navigator.userAgent.match(/Windows NT/);
        if (match)
            return "windows";
        match = navigator.userAgent.match(/Mac OS X/);
        if (match)
            return "mac";
        return "linux";
    },

    port: function()
    {
        return "unknown";
    },

    bringToFront: function()
    {
        this._windowVisible = true;
    },

    closeWindow: function()
    {
        this._windowVisible = false;
    },

    requestSetDockSide: function(side)
    {
        InspectorFrontendAPI.setDockSide(side);
    },

    setAttachedWindowHeight: function(height)
    {
    },

    moveWindowBy: function(x, y)
    {
    },

    setInjectedScriptForOrigin: function(origin, script)
    {
    },

    loaded: function()
    {
    },

    localizedStringsURL: function()
    {
        return undefined;
    },

    inspectedURLChanged: function(url)
    {
        document.title = WebInspector.UIString(Preferences.applicationTitle, url);
    },

    documentCopy: function(event)
    {
        if (!this._textToCopy)
            return;
        event.clipboardData.setData("text", this._textToCopy);
        event.preventDefault();
        delete this._textToCopy;
    },

    copyText: function(text)
    {
        this._textToCopy = text;
        if (!document.execCommand("copy")) {
            var screen = new WebInspector.ClipboardAccessDeniedScreen();
            screen.showModal();
        }
    },

    openInNewTab: function(url)
    {
        window.open(url, "_blank");
    },

    canSave: function()
    {
        return true;
    },

    save: function(url, content, forceSaveAs)
    {
        if (this._fileBuffers[url])
            throw new Error("Concurrent file modification denied.");

        this._fileBuffers[url] = [content];
        setTimeout(WebInspector.fileManager.savedURL.bind(WebInspector.fileManager, url), 0);
    },

    append: function(url, content)
    {
        var buffer = this._fileBuffers[url];
        if (!buffer)
            throw new Error("File is not open for write yet.");

        buffer.push(content);
        setTimeout(WebInspector.fileManager.appendedToURL.bind(WebInspector.fileManager, url), 0);
    },

    close: function(url)
    {
        var content = this._fileBuffers[url];
        delete this._fileBuffers[url];

        if (!content)
            return;

        var lastSlashIndex = url.lastIndexOf("/");
        var fileNameSuffix = (lastSlashIndex === -1) ? url : url.substring(lastSlashIndex + 1);

        var blob = new Blob(content, { type: "application/octet-stream" });
        var objectUrl = window.URL.createObjectURL(blob);
        window.location = objectUrl + "#/" + fileNameSuffix;

        function cleanup()
        {
            window.URL.revokeObjectURL(objectUrl);
        }
        setTimeout(cleanup, 3000);
    },

    sendMessageToBackend: function(message)
    {
    },

    recordActionTaken: function(actionCode)
    {
    },

    recordPanelShown: function(panelCode)
    {
    },

    recordSettingChanged: function(settingCode)
    {
    },

    loadResourceSynchronously: function(url)
    {
        return loadXHR(url);
    },

    supportsFileSystems: function()
    {
        return false;
    },

    requestFileSystems: function()
    {
    },

    addFileSystem: function()
    {
    },

    removeFileSystem: function(fileSystemPath)
    {
    },

    isolatedFileSystem: function(fileSystemId, registeredName)
    {
        return null;
    },

    indexPath: function(requestId, fileSystemPath)
    {
    },

    stopIndexing: function(requestId)
    {
    },

    searchInPath: function(requestId, fileSystemPath, query)
    {
    },

    setZoomFactor: function(zoom)
    {
    },

    isUnderTest: function()
    {
        return false;
    }
}

InspectorFrontendHost = new WebInspector.InspectorFrontendHostStub();

/**
 * @constructor
 * @extends {WebInspector.HelpScreen}
 */
WebInspector.ClipboardAccessDeniedScreen = function()
{
    WebInspector.HelpScreen.call(this, WebInspector.UIString("Clipboard access is denied"));
    var platformMessage = WebInspector.UIString("You need to install a Chrome extension that grants clipboard access to Developer Tools.");
    if (platformMessage) {
        var p = this.contentElement.createChild("p");
        p.addStyleClass("help-section");
        p.textContent = platformMessage;
    }
}

WebInspector.ClipboardAccessDeniedScreen.prototype = {
    __proto__: WebInspector.HelpScreen.prototype
}

}

/**
 * @constructor
 * @extends {WebInspector.HelpScreen}
 */
WebInspector.RemoteDebuggingTerminatedScreen = function(reason)
{
    WebInspector.HelpScreen.call(this, WebInspector.UIString("Detached from the target"));
    var p = this.contentElement.createChild("p");
    p.addStyleClass("help-section");
    p.createChild("span").textContent = "Remote debugging has been terminated with reason: ";
    p.createChild("span", "error-message").textContent = reason;
    p.createChild("br");
    p.createChild("span").textContent = "Please re-attach to the new target.";
}

WebInspector.RemoteDebuggingTerminatedScreen.prototype = {
    __proto__: WebInspector.HelpScreen.prototype
}
<|endoftext|>


<commit_before>module.exports = function(app, helpers, agenda) {

    var badWords = ["4r5e", "5h1t", "5hit", "a55", "anal", "anus", "ar5e", "arrse", "arse", "ass", "ass-fucker", "asses", "assfucker", "assfukka", "asshole", "assholes", "asswhole", "a_s_s", "b!tch", "b00bs", "b17ch", "b1tch", "ballbag", "balls", "ballsack", "bastard", "beastial", "beastiality", "bellend", "bestial", "bestiality", "bi+ch", "biatch", "bitch", "bitcher", "bitchers", "bitches", "bitchin", "bitching", "bloody", "blow job", "blowjob", "blowjobs", "boiolas", "bollock", "bollok", "boner", "boob", "boobs", "booobs", "boooobs", "booooobs", "booooooobs", "breasts", "buceta", "bugger", "bum", "bunny fucker", "butt", "butthole", "buttmuch", "buttplug", "c0ck", "c0cksucker", "carpet muncher", "cawk", "chink", "cipa", "cl1t", "clit", "clitoris", "clits", "cnut", "cock", "cock-sucker", "cockface", "cockhead", "cockmunch", "cockmuncher", "cocks", "cocksuck", "cocksucked", "cocksucker", "cocksucking", "cocksucks", "cocksuka", "cocksukka", "cok", "cokmuncher", "coksucka", "coon", "cox", "crap", "cum", "cummer", "cumming", "cums", "cumshot", "cunilingus", "cunillingus", "cunnilingus", "cunt", "cuntlick", "cuntlicker", "cuntlicking", "cunts", "cyalis", "cyberfuc", "cyberfuck", "cyberfucked", "cyberfucker", "cyberfuckers", "cyberfucking", "d1ck", "damn", "dick", "dickhead", "dildo", "dildos", "dink", "dinks", "dirsa", "dlck", "dog-fucker", "doggin", "dogging", "donkeyribber", "doosh", "duche", "dyke", "ejaculate", "ejaculated", "ejaculates", "ejaculating", "ejaculatings", "ejaculation", "ejakulate", "f u c k", "f u c k e r", "f4nny", "fag", "fagging", "faggitt", "faggot", "faggs", "fagot", "fagots", "fags", "fanny", "fannyflaps", "fannyfucker", "fanyy", "fatass", "fcuk", "fcuker", "fcuking", "feck", "fecker", "felching", "fellate", "fellatio", "fingerfuck", "fingerfucked", "fingerfucker", "fingerfuckers", "fingerfucking", "fingerfucks", "fistfuck", "fistfucked", "fistfucker", "fistfuckers", "fistfucking", "fistfuckings", "fistfucks", "flange", "fook", "fooker", "fuck", "fucka", "fucked", "fucker", "fuckers", "fuckhead", "fuckheads", "fuckin", "fucking", "fuckings", "fuckingshitmotherfucker", "fuckme", "fucks", "fuckwhit", "fuckwit", "fudge packer", "fudgepacker", "fuk", "fuker", "fukker", "fukkin", "fuks", "fukwhit", "fukwit", "fux", "fux0r", "f_u_c_k", "gangbang", "gangbanged", "gangbangs", "gaylord", "gaysex", "goatse", "God", "god-dam", "god-damned", "goddamn", "goddamned", "hardcoresex", "hell", "heshe", "hoar", "hoare", "hoer", "homo", "hore", "horniest", "horny", "hotsex", "jack-off", "jackoff", "jap", "jerk-off", "jism", "jiz", "jizm", "jizz", "kawk", "knob", "knobead", "knobed", "knobend", "knobhead", "knobjocky", "knobjokey", "kock", "kondum", "kondums", "kum", "kummer", "kumming", "kums", "kunilingus", "l3i+ch", "l3itch", "labia", "lust", "lusting", "m0f0", "m0fo", "m45terbate", "ma5terb8", "ma5terbate", "masochist", "master-bate", "masterb8", "masterbat*", "masterbat3", "masterbate", "masterbation", "masterbations", "masturbate", "mo-fo", "mof0", "mofo", "mothafuck", "mothafucka", "mothafuckas", "mothafuckaz", "mothafucked", "mothafucker", "mothafuckers", "mothafuckin", "mothafucking", "mothafuckings", "mothafucks", "mother fucker", "motherfuck", "motherfucked", "motherfucker", "motherfuckers", "motherfuckin", "motherfucking", "motherfuckings", "motherfuckka", "motherfucks", "muff", "mutha", "muthafecker", "muthafuckker", "muther", "mutherfucker", "n1gga", "n1gger", "nazi", "nigg3r", "nigg4h", "nigga", "niggah", "niggas", "niggaz", "nigger", "niggers", "nob", "nob jokey", "nobhead", "nobjocky", "nobjokey", "numbnuts", "nutsack", "orgasim", "orgasims", "orgasm", "orgasms", "p0rn", "pawn", "pecker", "penis", "penisfucker", "phonesex", "phuck", "phuk", "phuked", "phuking", "phukked", "phukking", "phuks", "phuq", "pigfucker", "pimpis", "piss", "pissed", "pisser", "pissers", "pisses", "pissflaps", "pissin", "pissing", "pissoff", "poop", "porn", "porno", "pornography", "pornos", "prick", "pricks", "pron", "pube", "pusse", "pussi", "pussies", "pussy", "pussys", "rectum", "retard", "rimjaw", "rimming", "s hit", "s.o.b.", "sadist", "schlong", "screwing", "scroat", "scrote", "scrotum", "semen", "sex", "sh!+", "sh!t", "sh1t", "shag", "shagger", "shaggin", "shagging", "shemale", "shi+", "shit", "shitdick", "shite", "shited", "shitey", "shitfuck", "shitfull", "shithead", "shiting", "shitings", "shits", "shitted", "shitter", "shitters", "shitting", "shittings", "shitty", "skank", "slut", "sluts", "smegma", "smut", "snatch", "son-of-a-bitch", "spac", "spunk", "s_h_i_t", "t1tt1e5", "t1tties", "teets", "teez", "testical", "testicle", "tit", "titfuck", "tits", "titt", "tittie5", "tittiefucker", "titties", "tittyfuck", "tittywank", "titwank", "tosser", "turd", "tw4t", "twat", "twathead", "twatty", "twunt", "twunter", "v14gra", "v1gra", "vagina", "viagra", "vulva", "w00se", "wang", "wank", "wanker", "wanky", "whoar", "whore", "willies", "willy", "xrated", "xxx"]

    var profanityResponses = ["watch your profanity", "watch your language, asshole", "do you kiss your mother with that mouth?", "eat shit and die, you foul-mouthed whore", "grow up and stop cursing like some 5-year-old dumbass", "wow, look at this guy. think's he's cool or some shit, using words like that", "fuck you, cunt", "vulgarity isn't cool, you're a dumb piece of shit"]

    app.post('/groupme', function(req, res) {
        agenda.now('import single message', req.body)
        if(req.body.sender_type != "bot") {
            var text = req.body.text.toLowerCase()

            var profanity = []
            badWords.forEach(badWord => {
              var place = text.indexOf(badWord)
              var leftSide
              var rightSide
              if(place > -1) {
                if(place === 0 || text[place - 1] === ' ') {
                  leftSide = true
                }
                if(place + badWord.length === text.length || text[place + badWord.length + 1] === ' ') {
                  rightSide = true
                }
              }
              if(rightWord && leftWord) {
                profanity.push(badWord)
              }
            })

            if(text.indexOf('imitate') > -1) {
                var markov = 4
                if(text.indexOf('good') > -1) markov = 6
                else if(text.indexOf('really good') > -1) markov = 8
                else if(text.indexOf('bad') > -1) markov = 2
                else if(text.indexOf('really bad') > -1) markov = 1
                agenda.now('generate markov message', {markov, sender_id: req.body.sender_id});
            }
            else if (profanity.length > 0) {
                profanity.forEach(word => {
                    agenda.now('send message', word)
                })
                if(req.body.sender_id === '30010919' && Math.random() > .5) {
                    agenda.now('send message', "don't forget your manners, Ravn")
                }
                else {
                    agenda.now('send message', profanityResponses[Math.floor(Math.random()*profanityResponses.length)]);
                }
            }
            else if(req.body.sender_id === '140530527') {
                if(Math.random() > .075) {
                    agenda.now('send message', 'Fuck off, john');
                }
            }
            else if(req.body.sender_id === '19747855') {
                if(Math.random() > .075) {
                    agenda.now('send message', 'Stop shitposting, Connor');
                }
            }
            else if(req.body.sender_id === '30010919') {
                /*if(Math.random() > .075) {
                    agenda.now('send message', "don't forget your manners, Ravn")
                }*/
            }
            /*else if(req.body.text.toLowerCase().indexOf('bot') > -1) {
                agenda.now('send message', 'You called?');
            }*/
        }
    })

};
<commit_msg>Added a 5% chance to send a loving post on chat<commit_after>module.exports = function(app, helpers, agenda) {

    var badWords = ["4r5e", "5h1t", "5hit", "a55", "anal", "anus", "ar5e", "arrse", "arse", "ass", "ass-fucker", "asses", "assfucker", "assfukka", "asshole", "assholes", "asswhole", "a_s_s", "b!tch", "b00bs", "b17ch", "b1tch", "ballbag", "balls", "ballsack", "bastard", "beastial", "beastiality", "bellend", "bestial", "bestiality", "bi+ch", "biatch", "bitch", "bitcher", "bitchers", "bitches", "bitchin", "bitching", "bloody", "blow job", "blowjob", "blowjobs", "boiolas", "bollock", "bollok", "boner", "boob", "boobs", "booobs", "boooobs", "booooobs", "booooooobs", "breasts", "buceta", "bugger", "bum", "bunny fucker", "butt", "butthole", "buttmuch", "buttplug", "c0ck", "c0cksucker", "carpet muncher", "cawk", "chink", "cipa", "cl1t", "clit", "clitoris", "clits", "cnut", "cock", "cock-sucker", "cockface", "cockhead", "cockmunch", "cockmuncher", "cocks", "cocksuck", "cocksucked", "cocksucker", "cocksucking", "cocksucks", "cocksuka", "cocksukka", "cok", "cokmuncher", "coksucka", "coon", "cox", "crap", "cum", "cummer", "cumming", "cums", "cumshot", "cunilingus", "cunillingus", "cunnilingus", "cunt", "cuntlick", "cuntlicker", "cuntlicking", "cunts", "cyalis", "cyberfuc", "cyberfuck", "cyberfucked", "cyberfucker", "cyberfuckers", "cyberfucking", "d1ck", "damn", "dick", "dickhead", "dildo", "dildos", "dink", "dinks", "dirsa", "dlck", "dog-fucker", "doggin", "dogging", "donkeyribber", "doosh", "duche", "dyke", "ejaculate", "ejaculated", "ejaculates", "ejaculating", "ejaculatings", "ejaculation", "ejakulate", "f u c k", "f u c k e r", "f4nny", "fag", "fagging", "faggitt", "faggot", "faggs", "fagot", "fagots", "fags", "fanny", "fannyflaps", "fannyfucker", "fanyy", "fatass", "fcuk", "fcuker", "fcuking", "feck", "fecker", "felching", "fellate", "fellatio", "fingerfuck", "fingerfucked", "fingerfucker", "fingerfuckers", "fingerfucking", "fingerfucks", "fistfuck", "fistfucked", "fistfucker", "fistfuckers", "fistfucking", "fistfuckings", "fistfucks", "flange", "fook", "fooker", "fuck", "fucka", "fucked", "fucker", "fuckers", "fuckhead", "fuckheads", "fuckin", "fucking", "fuckings", "fuckingshitmotherfucker", "fuckme", "fucks", "fuckwhit", "fuckwit", "fudge packer", "fudgepacker", "fuk", "fuker", "fukker", "fukkin", "fuks", "fukwhit", "fukwit", "fux", "fux0r", "f_u_c_k", "gangbang", "gangbanged", "gangbangs", "gaylord", "gaysex", "goatse", "God", "god-dam", "god-damned", "goddamn", "goddamned", "hardcoresex", "hell", "heshe", "hoar", "hoare", "hoer", "homo", "hore", "horniest", "horny", "hotsex", "jack-off", "jackoff", "jap", "jerk-off", "jism", "jiz", "jizm", "jizz", "kawk", "knob", "knobead", "knobed", "knobend", "knobhead", "knobjocky", "knobjokey", "kock", "kondum", "kondums", "kum", "kummer", "kumming", "kums", "kunilingus", "l3i+ch", "l3itch", "labia", "lust", "lusting", "m0f0", "m0fo", "m45terbate", "ma5terb8", "ma5terbate", "masochist", "master-bate", "masterb8", "masterbat*", "masterbat3", "masterbate", "masterbation", "masterbations", "masturbate", "mo-fo", "mof0", "mofo", "mothafuck", "mothafucka", "mothafuckas", "mothafuckaz", "mothafucked", "mothafucker", "mothafuckers", "mothafuckin", "mothafucking", "mothafuckings", "mothafucks", "mother fucker", "motherfuck", "motherfucked", "motherfucker", "motherfuckers", "motherfuckin", "motherfucking", "motherfuckings", "motherfuckka", "motherfucks", "muff", "mutha", "muthafecker", "muthafuckker", "muther", "mutherfucker", "n1gga", "n1gger", "nazi", "nigg3r", "nigg4h", "nigga", "niggah", "niggas", "niggaz", "nigger", "niggers", "nob", "nob jokey", "nobhead", "nobjocky", "nobjokey", "numbnuts", "nutsack", "orgasim", "orgasims", "orgasm", "orgasms", "p0rn", "pawn", "pecker", "penis", "penisfucker", "phonesex", "phuck", "phuk", "phuked", "phuking", "phukked", "phukking", "phuks", "phuq", "pigfucker", "pimpis", "piss", "pissed", "pisser", "pissers", "pisses", "pissflaps", "pissin", "pissing", "pissoff", "poop", "porn", "porno", "pornography", "pornos", "prick", "pricks", "pron", "pube", "pusse", "pussi", "pussies", "pussy", "pussys", "rectum", "retard", "rimjaw", "rimming", "s hit", "s.o.b.", "sadist", "schlong", "screwing", "scroat", "scrote", "scrotum", "semen", "sex", "sh!+", "sh!t", "sh1t", "shag", "shagger", "shaggin", "shagging", "shemale", "shi+", "shit", "shitdick", "shite", "shited", "shitey", "shitfuck", "shitfull", "shithead", "shiting", "shitings", "shits", "shitted", "shitter", "shitters", "shitting", "shittings", "shitty", "skank", "slut", "sluts", "smegma", "smut", "snatch", "son-of-a-bitch", "spac", "spunk", "s_h_i_t", "t1tt1e5", "t1tties", "teets", "teez", "testical", "testicle", "tit", "titfuck", "tits", "titt", "tittie5", "tittiefucker", "titties", "tittyfuck", "tittywank", "titwank", "tosser", "turd", "tw4t", "twat", "twathead", "twatty", "twunt", "twunter", "v14gra", "v1gra", "vagina", "viagra", "vulva", "w00se", "wang", "wank", "wanker", "wanky", "whoar", "whore", "willies", "willy", "xrated", "xxx"]

    var profanityResponses = ["watch your profanity", "watch your language, asshole", "do you kiss your mother with that mouth?", "eat shit and die, you foul-mouthed whore", "grow up and stop cursing like some 5-year-old dumbass", "wow, look at this guy. think's he's cool or some shit, using words like that", "fuck you, cunt", "vulgarity isn't cool, you're a dumb piece of shit"]

    app.post('/groupme', function(req, res) {
        agenda.now('import single message', req.body)
        if(req.body.sender_type != "bot") {
            var text = req.body.text.toLowerCase()

            var profanity = []
            badWords.forEach(badWord => {
              var place = text.indexOf(badWord)
              var leftSide
              var rightSide
              if(place > -1) {
                if(place === 0 || text[place - 1] === ' ') {
                  leftSide = true
                }
                if(place + badWord.length === text.length || text[place + badWord.length + 1] === ' ') {
                  rightSide = true
                }
              }
              if(rightWord && leftWord) {
                profanity.push(badWord)
              }
            })

    app.post('/groupme', function (req, res) {
        agenda.now('import single message', req.body)
        if(req.body.sender_type != "bot") {
          if(Math.random() > .9) {
            agenda.now('send message', "i think i'm in love with you for saying that, do it again")
          }
        }
    })

            if(text.indexOf('imitate') > -1) {
                var markov = 4
                if(text.indexOf('good') > -1) markov = 6
                else if(text.indexOf('really good') > -1) markov = 8
                else if(text.indexOf('bad') > -1) markov = 2
                else if(text.indexOf('really bad') > -1) markov = 1
                agenda.now('generate markov message', {markov, sender_id: req.body.sender_id});
            }
            else if (profanity.length > 0) {
                profanity.forEach(word => {
                    agenda.now('send message', word)
                })
                if(req.body.sender_id === '30010919' && Math.random() > .5) {
                    agenda.now('send message', "don't forget your manners, Ravn")
                }
                else {
                    agenda.now('send message', profanityResponses[Math.floor(Math.random()*profanityResponses.length)]);
                }
            }
            else if(req.body.sender_id === '140530527') {
                if(Math.random() > .075) {
                    agenda.now('send message', 'Fuck off, john');
                }
            }
            else if(req.body.sender_id === '19747855') {
                if(Math.random() > .075) {
                    agenda.now('send message', 'Stop shitposting, Connor');
                }
            }
            else if(req.body.sender_id === '30010919') {
                /*if(Math.random() > .075) {
                    agenda.now('send message', "don't forget your manners, Ravn")
                }*/
            }
            /*else if(req.body.text.toLowerCase().indexOf('bot') > -1) {
                agenda.now('send message', 'You called?');
            }*/
        }
    })

};
<|endoftext|>


<commit_before>var paper = require('paper');

function createCanvas(element, options) {
  var canvas = document.createElement('canvas');
  canvas.width = options.width || 100;
  canvas.height = options.height || 100;
  canvas.style.border = "1px solid black";
  element.appendChild(canvas);
  return canvas;
}

function convertDraw(world, additional) {
  var additional = additional || {};

  var xyf = _.flatten(
    _.map( world.features, function (val, y) {
             return _.map(val, function (feat, x) {
               return { feat : feat, pos : [x, y]};
             })}
         ));

  var filterHasName = function(ar){
    return _.filter(ar, function(x){return x.feat.name;});
  };
  var blocked  = _.map(_.filter(xyf, function(x){return x.feat=='#';}), 'pos');
  var terminal = _.map(filterHasName(xyf), 'pos');

  var world2 = {
    blockedStates : blocked,
    terminals : terminal,
    xLim : world.xLim,
    yLim : world.yLim
  };

  var featureLabels = _.map( filterHasName(xyf), function (a) {
    return { point : a.pos, content : a.feat.name }
  })

  var additionalLabels = additional.labels || [];
  var labels = additionalLabels.concat(featureLabels);

  var trajectory = _.map(additional.trajectory, function(state) {
    return [state.loc, ''];
  });

  return draw(world2, _.extend(additional, {trajectory : trajectory, labels : labels}));
}

function draw(world, additional) {
  if (world.features) {
    return convertDraw(world, additional)
  }

  if (typeof(wpEditor) === 'undefined') {
    console.log("no wpEditor, not drawing");
    return;
  }

  var element = wpEditor.makeResultContainer();

  var canvas = createCanvas(element, { width : world.xLim * 100, height : world.yLim * 100});
  paper.setup(canvas);

  var color = {
    blocked : 'grey',
    terminal: new paper.Color(.7),
    agent : 'blue'
   };

  var position = function(coords) {
    return [coords[0], world.yLim - coords[1]];
  };

  var makeSquare = function(c) {
    var rect = new paper.Rectangle(([0, 0]), ([1, 1]));
    var path = new paper.Path.Rectangle(rect, .00);
    path.fillColor = c;
    path.remove();
    return path;
  };

  var label = new paper.PointText({
      fillColor : new paper.Color(.1, .8),
      fontSize : 16,
      justification : 'center'
  });

  label.scale(.02);
  var toHeat = function (v) {
    var mag = Math.min(Math.abs(v)/20,1);

    if (v > 0) {
      return new paper.Color(0, 1, 0, mag);
    } else {
      return new paper.Color(1, 0, 0, mag);
    }
  }

  var addUtilities = function (v) {
    var group = new paper.Group();

    group.addChild(new paper.Path.Rectangle(([-.5, +.5]), ([world.xLim, world.yLim])));
    var lastCoord;
    for (var i = 0; i < v.length; i++) {
      var coord = v[i][0];
      var LRUD = v[i][1];
      var LURD = [LRUD[0], LRUD[2], LRUD[1], LRUD[3]];
      if (!_.isEqual(lastCoord, coord)) {

        for (var j = 0; j < 4; j ++) {
          var tri = triangleSquare(coord, j*90, toHeat(LURD[j]), new paper.Color(.5, .4))
          group.addChild(tri);

          var l = makeLabel({
            point : [ coord[0] + .3 * Math.cos(-j * Math.PI/2 + Math.PI) ,
                      coord[1] + .3 * Math.sin(-j * Math.PI/2 + Math.PI)],
            content : LURD[j].toFixed(1), fontSize : 10
          });

          group.addChild(l);
        }
      }
      lastCoord = coord;
    }
    return group;
  };

  var triangleSquare = function(coord, orientation, color, borderColor) {
    var a = new paper.Path([[-.5, -.5], [0, 0], [-.5, +.5]]);
    var j = orientation;
    a.closed = true;
    a.fillColor = color;
    a.strokeColor = borderColor;
    a.rotate(orientation);

    var offsetx = Math.cos(-orientation/90 * Math.PI/2 + Math.PI);
    var offsety = Math.sin(-orientation/90 * Math.PI/2 + Math.PI);

    a.position = position([coord[0] + offsetx *.25, coord[1] + offsety *.25]);
    return a;
  }

  var makeLabel = function (a) {
      var copy = _.extend(label.clone(), a);
      copy.point = position(a.point);
      copy.point.y += copy.bounds.height/3.5;
      return copy;
  };

  var makeGrid = function(world) {
    var group = new paper.Group();

    for (var i = 0; i < world.xLim; i++) {
      for (var j = 0; j < world.yLim; j++) {
        var grid = new paper.Path.Rectangle(([i-.5, j+.5]), ([1, 1]));
        grid.strokeColor = new paper.Color(.5, .2);
        grid.fillColor = new paper.Color(1, 0);
        group.addChild(grid);
      }
    }
    return group;
  };

  var addShapes = function(coords, shape, group) {
    for (var i = 0; i < coords.length; i++) {
      var copy = shape.clone();
      copy.position = position(coords[i]);
      group.addChild(copy);
    }
  };

  var addAgentPath = function(trajectory, paths, group) {
    var coords = _.map(trajectory, 0);

    var agentPath = new paper.Path();
    agentPath.strokeColor = 'black';
    agentPath.strokeWidth = 2;
    agentPath.dashArray = [8,8];
    group.addChild(agentPath);

    var agent = new paper.Path.Circle(position(coords[0]), .3);
    agent.fillColor = color.agent;
    group.addChild(agent);

    var pathsGroup = new paper.Group();
    group.addChild(pathsGroup);

    var segPerSec = 3;
    var extraAtEnd = 1;
    var lastTime = 0;

    var scale, offsetx, offsety;
    var active = true;
    var offsett = 0;

    paper.view.onFrame = function (event) {
      //the first time we execute we need to find out how things have been rescaled
      if (scale === undefined) {
        scale = agent.bounds.width/2/.3;
        offsetx = agent.position.x - position(coords[0])[0] * scale;
        offsety = agent.position.y - position(coords[0])[1] * scale;
      }
      var scalePosition = function(v) {
        var x = position(v);
        return [x[0] * scale + offsetx, x[1] * scale + offsety];
      }

      if (active) {
        if (event.time - lastTime > .1) {
          offsett += event.time - lastTime;
        }
        lastTime = event.time;

        var segments = (event.time - offsett)*segPerSec;
        var frac = segments % 1;
        var idx = Math.floor(Math.min(Math.floor(segments) % (trajectory.length + extraAtEnd), trajectory.length-1));
        console.log(idx >= 0, 'idx floor in gridworld-viz')

        agentPath.remove()

        var currentLocation;
        if (idx < trajectory.length-1) {
          currentLocation = [
            (1-frac) * coords[idx][0] + frac * coords[idx+1][0],
            (1-frac) * coords[idx][1] + frac * coords[idx+1][1]
          ];
        } else {
          currentLocation = coords[idx];
        }

        var lodashTake = function(ar,n){return ar.slice(0,n);};
        var currentPath = lodashTake(coords, idx+1);
        currentPath.push(currentLocation);

        if (paths) {
          pathsGroup.remove();
          pathsGroup = addUtilities(paths[idx]);
          group.addChild(pathsGroup);
          pathsGroup.scale(scale);
          pathsGroup.translate(world.xLim/2 * scale, world.yLim/2 * scale );
          var fudgeFactor = 33;
          pathsGroup.translate(-pathsGroup.bounds.topLeft.x + fudgeFactor, -pathsGroup.bounds.topLeft.y );
          console.log()
        }

        agentPath = new paper.Path();
        agentPath.strokeColor = 'black';
        agentPath.strokeWidth = 2;
        agentPath.dashArray = [8,8];
        group.addChild(agentPath);

        agentPath.addSegments(_.map(currentPath, scalePosition));
        agent.position = scalePosition(currentLocation);
      }
    };

    paper.view.on('mousedown', function (event) {
      active = !active;
    });

  };
  var axisx = _.map(_.range(world.xLim), function (i) {
    return { point : [i, -.75], content : i };
  });

  var axisy = _.map(_.range(world.yLim), function (i) {
    return { point : [-.75, i], content : i };
  });

  var makeTerminal = function (coords) {
    var group = new paper.Group();
    var tri = undefined;
    for (var i = 0; i < 4; i++) {
      var gradient = {
        gradient: {
          stops: [['white', 0.75], [color.terminal, 1]],
          radial: false
        },
        origin: [0,0],
        destination: [ -.5, 0]
      };

      tri = triangleSquare(coords, i*90, gradient, new paper.Color(0, 0));
      group.addChild(tri);;
    }
    return group;
  };

  var group = new paper.Group();
  //draw the world
  addShapes(world.blockedStates, makeSquare(color.blocked), group);

  var f =_.map(world.terminals, makeTerminal);
  group.addChildren(f);

  group.addChild(makeGrid(world));

  group.addChildren(_.map(axisx, makeLabel));
  group.addChildren(_.map(axisy, makeLabel));

  group.addChildren(_.map(world.labels, makeLabel));

  if (world.labels) {
    group.addChildren(_.map(world.labels, makeLabel));
  }
  if (additional) { //additional items to be drawn
    if (additional.expUtilities) {
      group.addChild(addUtilities(additional.expUtilities));
    }
    if (additional.trajectory) {
      addAgentPath(additional.trajectory, additional.paths, group);
    }
    if (additional.labels) {
      group.addChildren(_.map(additional.labels, makeLabel));
    }
  }

  group.fitBounds(paper.view.bounds);
  paper.view.draw();

}

module.exports = {
  draw: draw
}
<commit_msg>rm logging<commit_after>var paper = require('paper');

function createCanvas(element, options) {
  var canvas = document.createElement('canvas');
  canvas.width = options.width || 100;
  canvas.height = options.height || 100;
  canvas.style.border = "1px solid black";
  element.appendChild(canvas);
  return canvas;
}

function convertDraw(world, additional) {
  var additional = additional || {};

  var xyf = _.flatten(
    _.map( world.features, function (val, y) {
             return _.map(val, function (feat, x) {
               return { feat : feat, pos : [x, y]};
             })}
         ));

  var filterHasName = function(ar){
    return _.filter(ar, function(x){return x.feat.name;});
  };
  var blocked  = _.map(_.filter(xyf, function(x){return x.feat=='#';}), 'pos');
  var terminal = _.map(filterHasName(xyf), 'pos');

  var world2 = {
    blockedStates : blocked,
    terminals : terminal,
    xLim : world.xLim,
    yLim : world.yLim
  };

  var featureLabels = _.map( filterHasName(xyf), function (a) {
    return { point : a.pos, content : a.feat.name }
  })

  var additionalLabels = additional.labels || [];
  var labels = additionalLabels.concat(featureLabels);

  var trajectory = _.map(additional.trajectory, function(state) {
    return [state.loc, ''];
  });

  return draw(world2, _.extend(additional, {trajectory : trajectory, labels : labels}));
}

function draw(world, additional) {
  if (world.features) {
    return convertDraw(world, additional)
  }

  if (typeof(wpEditor) === 'undefined') {
    console.log("no wpEditor, not drawing");
    return;
  }

  var element = wpEditor.makeResultContainer();

  var canvas = createCanvas(element, { width : world.xLim * 100, height : world.yLim * 100});
  paper.setup(canvas);

  var color = {
    blocked : 'grey',
    terminal: new paper.Color(.7),
    agent : 'blue'
   };

  var position = function(coords) {
    return [coords[0], world.yLim - coords[1]];
  };

  var makeSquare = function(c) {
    var rect = new paper.Rectangle(([0, 0]), ([1, 1]));
    var path = new paper.Path.Rectangle(rect, .00);
    path.fillColor = c;
    path.remove();
    return path;
  };

  var label = new paper.PointText({
      fillColor : new paper.Color(.1, .8),
      fontSize : 16,
      justification : 'center'
  });

  label.scale(.02);
  var toHeat = function (v) {
    var mag = Math.min(Math.abs(v)/20,1);

    if (v > 0) {
      return new paper.Color(0, 1, 0, mag);
    } else {
      return new paper.Color(1, 0, 0, mag);
    }
  }

  var addUtilities = function (v) {
    var group = new paper.Group();

    group.addChild(new paper.Path.Rectangle(([-.5, +.5]), ([world.xLim, world.yLim])));
    var lastCoord;
    for (var i = 0; i < v.length; i++) {
      var coord = v[i][0];
      var LRUD = v[i][1];
      var LURD = [LRUD[0], LRUD[2], LRUD[1], LRUD[3]];
      if (!_.isEqual(lastCoord, coord)) {

        for (var j = 0; j < 4; j ++) {
          var tri = triangleSquare(coord, j*90, toHeat(LURD[j]), new paper.Color(.5, .4))
          group.addChild(tri);

          var l = makeLabel({
            point : [ coord[0] + .3 * Math.cos(-j * Math.PI/2 + Math.PI) ,
                      coord[1] + .3 * Math.sin(-j * Math.PI/2 + Math.PI)],
            content : LURD[j].toFixed(1), fontSize : 10
          });

          group.addChild(l);
        }
      }
      lastCoord = coord;
    }
    return group;
  };

  var triangleSquare = function(coord, orientation, color, borderColor) {
    var a = new paper.Path([[-.5, -.5], [0, 0], [-.5, +.5]]);
    var j = orientation;
    a.closed = true;
    a.fillColor = color;
    a.strokeColor = borderColor;
    a.rotate(orientation);

    var offsetx = Math.cos(-orientation/90 * Math.PI/2 + Math.PI);
    var offsety = Math.sin(-orientation/90 * Math.PI/2 + Math.PI);

    a.position = position([coord[0] + offsetx *.25, coord[1] + offsety *.25]);
    return a;
  }

  var makeLabel = function (a) {
      var copy = _.extend(label.clone(), a);
      copy.point = position(a.point);
      copy.point.y += copy.bounds.height/3.5;
      return copy;
  };

  var makeGrid = function(world) {
    var group = new paper.Group();

    for (var i = 0; i < world.xLim; i++) {
      for (var j = 0; j < world.yLim; j++) {
        var grid = new paper.Path.Rectangle(([i-.5, j+.5]), ([1, 1]));
        grid.strokeColor = new paper.Color(.5, .2);
        grid.fillColor = new paper.Color(1, 0);
        group.addChild(grid);
      }
    }
    return group;
  };

  var addShapes = function(coords, shape, group) {
    for (var i = 0; i < coords.length; i++) {
      var copy = shape.clone();
      copy.position = position(coords[i]);
      group.addChild(copy);
    }
  };

  var addAgentPath = function(trajectory, paths, group) {
    var coords = _.map(trajectory, 0);

    var agentPath = new paper.Path();
    agentPath.strokeColor = 'black';
    agentPath.strokeWidth = 2;
    agentPath.dashArray = [8,8];
    group.addChild(agentPath);

    var agent = new paper.Path.Circle(position(coords[0]), .3);
    agent.fillColor = color.agent;
    group.addChild(agent);

    var pathsGroup = new paper.Group();
    group.addChild(pathsGroup);

    var segPerSec = 3;
    var extraAtEnd = 1;
    var lastTime = 0;

    var scale, offsetx, offsety;
    var active = true;
    var offsett = 0;

    paper.view.onFrame = function (event) {
      //the first time we execute we need to find out how things have been rescaled
      if (scale === undefined) {
        scale = agent.bounds.width/2/.3;
        offsetx = agent.position.x - position(coords[0])[0] * scale;
        offsety = agent.position.y - position(coords[0])[1] * scale;
      }
      var scalePosition = function(v) {
        var x = position(v);
        return [x[0] * scale + offsetx, x[1] * scale + offsety];
      }

      if (active) {
        if (event.time - lastTime > .1) {
          offsett += event.time - lastTime;
        }
        lastTime = event.time;

        var segments = (event.time - offsett)*segPerSec;
        var frac = segments % 1;
        var idx = Math.floor(Math.min(Math.floor(segments) % (trajectory.length + extraAtEnd), trajectory.length-1));

        agentPath.remove()

        var currentLocation;
        if (idx < trajectory.length-1) {
          currentLocation = [
            (1-frac) * coords[idx][0] + frac * coords[idx+1][0],
            (1-frac) * coords[idx][1] + frac * coords[idx+1][1]
          ];
        } else {
          currentLocation = coords[idx];
        }

        var lodashTake = function(ar,n){return ar.slice(0,n);};
        var currentPath = lodashTake(coords, idx+1);
        currentPath.push(currentLocation);

        if (paths) {
          pathsGroup.remove();
          pathsGroup = addUtilities(paths[idx]);
          group.addChild(pathsGroup);
          pathsGroup.scale(scale);
          pathsGroup.translate(world.xLim/2 * scale, world.yLim/2 * scale );
          var fudgeFactor = 33;
          pathsGroup.translate(-pathsGroup.bounds.topLeft.x + fudgeFactor, -pathsGroup.bounds.topLeft.y );
          console.log()
        }

        agentPath = new paper.Path();
        agentPath.strokeColor = 'black';
        agentPath.strokeWidth = 2;
        agentPath.dashArray = [8,8];
        group.addChild(agentPath);

        agentPath.addSegments(_.map(currentPath, scalePosition));
        agent.position = scalePosition(currentLocation);
      }
    };

    paper.view.on('mousedown', function (event) {
      active = !active;
    });

  };
  var axisx = _.map(_.range(world.xLim), function (i) {
    return { point : [i, -.75], content : i };
  });

  var axisy = _.map(_.range(world.yLim), function (i) {
    return { point : [-.75, i], content : i };
  });

  var makeTerminal = function (coords) {
    var group = new paper.Group();
    var tri = undefined;
    for (var i = 0; i < 4; i++) {
      var gradient = {
        gradient: {
          stops: [['white', 0.75], [color.terminal, 1]],
          radial: false
        },
        origin: [0,0],
        destination: [ -.5, 0]
      };

      tri = triangleSquare(coords, i*90, gradient, new paper.Color(0, 0));
      group.addChild(tri);;
    }
    return group;
  };

  var group = new paper.Group();
  //draw the world
  addShapes(world.blockedStates, makeSquare(color.blocked), group);

  var f =_.map(world.terminals, makeTerminal);
  group.addChildren(f);

  group.addChild(makeGrid(world));

  group.addChildren(_.map(axisx, makeLabel));
  group.addChildren(_.map(axisy, makeLabel));

  group.addChildren(_.map(world.labels, makeLabel));

  if (world.labels) {
    group.addChildren(_.map(world.labels, makeLabel));
  }
  if (additional) { //additional items to be drawn
    if (additional.expUtilities) {
      group.addChild(addUtilities(additional.expUtilities));
    }
    if (additional.trajectory) {
      addAgentPath(additional.trajectory, additional.paths, group);
    }
    if (additional.labels) {
      group.addChildren(_.map(additional.labels, makeLabel));
    }
  }

  group.fitBounds(paper.view.bounds);
  paper.view.draw();

}

module.exports = {
  draw: draw
}
<|endoftext|>


<commit_before>import macro                      from 'vtk.js/Sources/macro';
import vtkOpenGLRenderWindow      from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkRenderer                from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow            from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkRenderWindowInteractor  from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor';

// Load basic classes for vtk() factory
import 'vtk.js/Sources/Common/Core/Points';
import 'vtk.js/Sources/Common/Core/DataArray';
import 'vtk.js/Sources/Common/DataModel/PolyData';
import 'vtk.js/Sources/Rendering/Core/Actor';
import 'vtk.js/Sources/Rendering/Core/Mapper';

const STYLE_CONTAINER = {
  margin: '0',
  padding: '0',
  position: 'absolute',
  top: '0',
  left: '0',
  width: '100vw',
  height: '100vh',
  overflow: 'hidden',
};

const STYLE_CONTROL_PANEL = {
  position: 'absolute',
  left: '25px',
  top: '25px',
  backgroundColor: 'white',
  borderRadius: '5px',
  listStyle: 'none',
  padding: '5px 10px',
  margin: '0',
  display: 'block',
  border: 'solid 1px black',
  maxWidth: 'calc(100vw - 70px)',
  maxHeight: 'calc(100vh - 60px)',
  overflow: 'auto',
};

function applyStyle(el, style) {
  Object.keys(style).forEach((key) => {
    el.style[key] = style[key];
  });
}

function vtkFullScreenRenderWindow(publicAPI, model) {
  // Full screen DOM handler
  if (!model.rootContainer) {
    model.rootContainer = document.querySelector('body');
  }

  if (!model.container) {
    model.container = document.createElement('div');
    applyStyle(model.container, model.containerStyle || STYLE_CONTAINER);
    model.rootContainer.appendChild(model.container);
  }

  // VTK renderWindow/renderer
  model.renderWindow = vtkRenderWindow.newInstance();
  model.renderer = vtkRenderer.newInstance();
  model.renderWindow.addRenderer(model.renderer);

  // OpenGlRenderWindow
  model.openGlRenderWindow = vtkOpenGLRenderWindow.newInstance();
  model.openGlRenderWindow.setContainer(model.container);
  model.renderWindow.addView(model.openGlRenderWindow);

  // Interactor
  model.interactor = vtkRenderWindowInteractor.newInstance();
  model.interactor.setView(model.openGlRenderWindow);
  model.interactor.initialize();
  model.interactor.bindEvents(model.container);

  // Expose background
  publicAPI.setBackground = model.renderer.setBackground;

  publicAPI.removeController = () => {
    const el = model.controlContainer;
    if (el) {
      el.parentNode.removeChild(el);
    }
  };

  publicAPI.addController = (html) => {
    model.controlContainer = document.createElement('div');
    applyStyle(model.controlContainer, model.controlPanelStyle || STYLE_CONTROL_PANEL);
    model.rootContainer.appendChild(model.controlContainer);
    model.controlContainer.innerHTML = html;

    model.rootContainer.addEventListener('keypress', (e) => {
      if (String.fromCharCode(e.charCode) === 'c') {
        if (model.controlContainer.style.display === 'none') {
          model.controlContainer.style.display = 'block';
        } else {
          model.controlContainer.style.display = 'none';
        }
      }
    });
  };

  // Update BG color
  publicAPI.setBackground(...model.background);

  // Representation API
  publicAPI.addRepresentation = (representation) => {
    representation.getActors().forEach((actor) => {
      model.renderer.addActor(actor);
    });
  };
  publicAPI.removeRepresentation = (representation) => {
    representation.getActors().forEach(actor => model.renderer.removeActor(actor));
  };

  // Handle window resize
  publicAPI.resize = () => {
    const dims = model.container.getBoundingClientRect();
    model.openGlRenderWindow.setSize(dims.width, dims.height);
    if (model.resizeCallback) {
      model.resizeCallback(dims);
    }
    model.renderWindow.render();
  };

  publicAPI.setResizeCallback = (cb) => {
    model.resizeCallback = cb;
    publicAPI.resize();
  };

  if (model.listenWindowResize) {
    window.addEventListener('resize', publicAPI.resize);
  }
  publicAPI.resize();
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  background: [0.32, 0.34, 0.43],
  containerStyle: null,
  controlPanelStyle: null,
  listenWindowResize: true,
  resizeCallback: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Object methods
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, [
    'renderWindow',
    'renderer',
    'openGlRenderWindow',
    'interactor',
    'container',
    'controlContainer',
  ]);

  // Object specific methods
  vtkFullScreenRenderWindow(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(FullScreenRenderWindow): Ensure size passed to canvas are integer<commit_after>import macro                      from 'vtk.js/Sources/macro';
import vtkOpenGLRenderWindow      from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkRenderer                from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow            from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkRenderWindowInteractor  from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor';

// Load basic classes for vtk() factory
import 'vtk.js/Sources/Common/Core/Points';
import 'vtk.js/Sources/Common/Core/DataArray';
import 'vtk.js/Sources/Common/DataModel/PolyData';
import 'vtk.js/Sources/Rendering/Core/Actor';
import 'vtk.js/Sources/Rendering/Core/Mapper';

const STYLE_CONTAINER = {
  margin: '0',
  padding: '0',
  position: 'absolute',
  top: '0',
  left: '0',
  width: '100vw',
  height: '100vh',
  overflow: 'hidden',
};

const STYLE_CONTROL_PANEL = {
  position: 'absolute',
  left: '25px',
  top: '25px',
  backgroundColor: 'white',
  borderRadius: '5px',
  listStyle: 'none',
  padding: '5px 10px',
  margin: '0',
  display: 'block',
  border: 'solid 1px black',
  maxWidth: 'calc(100vw - 70px)',
  maxHeight: 'calc(100vh - 60px)',
  overflow: 'auto',
};

function applyStyle(el, style) {
  Object.keys(style).forEach((key) => {
    el.style[key] = style[key];
  });
}

function vtkFullScreenRenderWindow(publicAPI, model) {
  // Full screen DOM handler
  if (!model.rootContainer) {
    model.rootContainer = document.querySelector('body');
  }

  if (!model.container) {
    model.container = document.createElement('div');
    applyStyle(model.container, model.containerStyle || STYLE_CONTAINER);
    model.rootContainer.appendChild(model.container);
  }

  // VTK renderWindow/renderer
  model.renderWindow = vtkRenderWindow.newInstance();
  model.renderer = vtkRenderer.newInstance();
  model.renderWindow.addRenderer(model.renderer);

  // OpenGlRenderWindow
  model.openGlRenderWindow = vtkOpenGLRenderWindow.newInstance();
  model.openGlRenderWindow.setContainer(model.container);
  model.renderWindow.addView(model.openGlRenderWindow);

  // Interactor
  model.interactor = vtkRenderWindowInteractor.newInstance();
  model.interactor.setView(model.openGlRenderWindow);
  model.interactor.initialize();
  model.interactor.bindEvents(model.container);

  // Expose background
  publicAPI.setBackground = model.renderer.setBackground;

  publicAPI.removeController = () => {
    const el = model.controlContainer;
    if (el) {
      el.parentNode.removeChild(el);
    }
  };

  publicAPI.addController = (html) => {
    model.controlContainer = document.createElement('div');
    applyStyle(model.controlContainer, model.controlPanelStyle || STYLE_CONTROL_PANEL);
    model.rootContainer.appendChild(model.controlContainer);
    model.controlContainer.innerHTML = html;

    model.rootContainer.addEventListener('keypress', (e) => {
      if (String.fromCharCode(e.charCode) === 'c') {
        if (model.controlContainer.style.display === 'none') {
          model.controlContainer.style.display = 'block';
        } else {
          model.controlContainer.style.display = 'none';
        }
      }
    });
  };

  // Update BG color
  publicAPI.setBackground(...model.background);

  // Representation API
  publicAPI.addRepresentation = (representation) => {
    representation.getActors().forEach((actor) => {
      model.renderer.addActor(actor);
    });
  };
  publicAPI.removeRepresentation = (representation) => {
    representation.getActors().forEach(actor => model.renderer.removeActor(actor));
  };

  // Handle window resize
  publicAPI.resize = () => {
    const dims = model.container.getBoundingClientRect();
    model.openGlRenderWindow.setSize(Math.floor(dims.width), Math.floor(dims.height));
    if (model.resizeCallback) {
      model.resizeCallback(dims);
    }
    model.renderWindow.render();
  };

  publicAPI.setResizeCallback = (cb) => {
    model.resizeCallback = cb;
    publicAPI.resize();
  };

  if (model.listenWindowResize) {
    window.addEventListener('resize', publicAPI.resize);
  }
  publicAPI.resize();
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  background: [0.32, 0.34, 0.43],
  containerStyle: null,
  controlPanelStyle: null,
  listenWindowResize: true,
  resizeCallback: null,
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Object methods
  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, [
    'renderWindow',
    'renderer',
    'openGlRenderWindow',
    'interactor',
    'container',
    'controlContainer',
  ]);

  // Object specific methods
  vtkFullScreenRenderWindow(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>
function onDocumentReady(firebaseApp) {

  //[START fs_emulator_connect]
  // firebaseApp previously initialized using firebase.initializeApp().
  var db = firebaseApp.firestore();
  if (location.hostname === "localhost") {
    // Note that the Firebase Web SDK must connect to the WebChannel port
    db.settings({
      host: "localhost:8081",
      ssl: false
    });
  }
  // [END fs_emulator_connect]
}
<commit_msg>Stop mentioning the WebChannel port<commit_after>
function onDocumentReady(firebaseApp) {

  //[START fs_emulator_connect]
  // firebaseApp previously initialized using firebase.initializeApp().
  var db = firebaseApp.firestore();
  if (location.hostname === "localhost") {
    db.settings({
      host: "localhost:8080",
      ssl: false
    });
  }
  // [END fs_emulator_connect]
}
<|endoftext|>


<commit_before>var initialState = {
    animating: false,
    dragging: false,
    currentDirection: 0,
    currentLeft: null,
    currentSlide: 0,
    direction: 1,
    listWidth: null,
    listHeight: null,
    scrolling: false,
    // loadIndex: 0,
    slideCount: null,
    slideWidth: null,
    slideHeight: null,
    swiping: false,
    // sliding: false,
    // slideOffset: 0,
    swipeLeft: null,
    touchObject: {
      startX: 0,
      startY: 0,
      curX: 0,
      curY: 0
    },

    lazyLoadedList: [],

    // added for react
    initialized: false,
    edgeDragged: false,
    swiped: false, // used by swipeEvent. differentites between touch and swipe.
    trackStyle: {},
    trackWidth: 0

    // Removed
    // transformsEnabled: false,
    // $nextArrow: null,
    // $prevArrow: null,
    // $dots: null,
    // $list: null,
    // $slideTrack: null,
    // $slides: null,
};

module.exports = initialState;
<commit_msg>redefined initial-state with addition of autoplaying state and es6 export<commit_after>const initialState = {
  animating: false,
  autoplaying: null,
  currentDirection: 0,
  currentLeft: null,
  currentSlide: 0,
  direction: 1,
  dragging: false,
  edgeDragged: false,
  initialized: false,
  lazyLoadedList: [],
  listHeight: null,
  listWidth: null,
  scrolling: false,
  slideCount: null,
  slideHeight: null,
  slideWidth: null,
  swipeLeft: null,
  swiped: false, // used by swipeEvent. differentites between touch and swipe.
  swiping: false,
  touchObject: { startX: 0, startY: 0, curX: 0, curY: 0 },
  trackStyle: {},
  trackWidth: 0
}

export default initialState
<|endoftext|>


<commit_before>chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

		// ----------------------------------------------------------
		// This part of the script triggers when page is done loading
		console.log("Hello. This message was sent from scripts/inject.js");
		// ----------------------------------------------------------

	}
	}, 10);

	function addButtonsIfNotExist(){
		[].slice.call(document.querySelectorAll('.comment-thread-container')).forEach(function(container){
			if($(container).has('button.ba-hide-comment-button').length==0){
				var $toggle = $('<button class="ba-hide-comment-button">Toggle comment</button>')
				$(container).prepend($toggle);
			}
		});
	}
	$(document).on('click','button',function(e){
		var threadContainer = $(e.target).parent();
		var visible = !threadContainer.hasClass('ba-hidden');
		if(visible){
			$(threadContainer).addClass('ba-hidden');
		}else{
			$(threadContainer).removeClass('ba-hidden');
		}
	});
	setInterval(addButtonsIfNotExist,2000);
	console.log('bitbucket awesomizer loaded')
});
<commit_msg>reformat<commit_after>chrome.extension.sendMessage({}, function(response) {
  var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
      // This runs when page is done loading.

      // TODO Document whe the interval is cleared.
      clearInterval(readyStateCheckInterval);
    }
  }, 10);

  function addButtonsIfNotExist() {
    Array.prototype.slice.call(document.querySelectorAll('.comment-thread-container')).forEach(function(container) {
      if ($(container).has('button.ba-hide-comment-button').length == 0) {
        var $toggle = $('<button class="ba-hide-comment-button">Toggle comment</button>')
        $(container).prepend($toggle);
      }
    });
  }

  $(document).on('click', 'button', function(e) {
    var threadContainer = $(e.target).parent();
    var visible = !threadContainer.hasClass('ba-hidden');
    if (visible) {
      $(threadContainer).addClass('ba-hidden');
    } else {
      $(threadContainer).removeClass('ba-hidden');
    }
  });

  setInterval(addButtonsIfNotExist, 2000);
  console.log('bitbucket awesomizer loaded')
});
<|endoftext|>


<commit_before>chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

		// ----------------------------------------------------------
		// This part of the script triggers when page is done loading
		console.log("Hello. This message was sent from scripts/inject.js");
		// ----------------------------------------------------------

		var bar = document.createElement("div");
		bar.innerHTML = "GET BACK TO WORK!";
		bar.style.color = "white"
		bar.style.backgroundColor = "dodgerblue";
		bar.style.textAlign = "center";
		document.body.insertBefore(bar, document.body.firstChild);
		bar.style.position="fixed";
		bar.style.top ="1%";
		bar.style.left ="50%";
		bar.style.padding = "2px";
		bar.style.zIndex = "10000";
		bar.style.borderRadius = "5px";

	}
	}, 10);
});<commit_msg>now only displays message on fb<commit_after>chrome.extension.sendMessage({}, function(response) {
	var readyStateCheckInterval = setInterval(function() {
	if (document.readyState === "complete") {
		clearInterval(readyStateCheckInterval);

		// ----------------------------------------------------------
		// This part of the script triggers when page is done loading
		console.log("Hello. This message was sent from scripts/inject.js");
		// ----------------------------------------------------------
		var current = window.location.href;

		if(current.indexOf('facebook') != '-1'){
			var bar = document.createElement("div");
			bar.innerHTML = "GET BACK TO WORK!";
			bar.style.color = "white"
			bar.style.backgroundColor = "dodgerblue";
			bar.style.textAlign = "center";
			document.body.insertBefore(bar, document.body.firstChild);
			bar.style.position="fixed";
			bar.style.top ="1%";
			bar.style.left ="50%";
			bar.style.padding = "2px";
			bar.style.zIndex = "10000";
			bar.style.borderRadius = "5px";
		}
	}
	}, 10);
});<|endoftext|>


<commit_before>// @flow

import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';
import type { ThreadSettingsNavigate } from './thread-settings.react';
import type { AppState } from '../../redux/redux-setup';

import * as React from 'react';
import { View, Platform } from 'react-native';
import PropTypes from 'prop-types';

import { connect } from 'lib/utils/redux-utils';

import { MessageListRouteName } from '../../navigation/route-names';
import Button from '../../components/button.react';
import ColorSplotch from '../../components/color-splotch.react';
import ThreadIcon from '../../components/thread-icon.react';
import {
  type Colors,
  colorsPropType,
  colorsSelector,
  styleSelector,
} from '../../themes/colors';
import { SingleLine } from '../../components/single-line.react';

type Props = {|
  threadInfo: ThreadInfo,
  navigate: ThreadSettingsNavigate,
  lastListItem: boolean,
  // Redux state
  colors: Colors,
  styles: typeof styles,
|};
class ThreadSettingsChildThread extends React.PureComponent<Props> {
  static propTypes = {
    threadInfo: threadInfoPropType.isRequired,
    navigate: PropTypes.func.isRequired,
    lastListItem: PropTypes.bool.isRequired,
    colors: colorsPropType.isRequired,
    styles: PropTypes.objectOf(PropTypes.object).isRequired,
  };

  render() {
    const lastButtonStyle = this.props.lastListItem
      ? this.props.styles.lastButton
      : null;
    return (
      <View style={this.props.styles.container}>
        <Button
          onPress={this.onPress}
          style={[this.props.styles.button, lastButtonStyle]}
        >
          <View style={this.props.styles.leftSide}>
            <ColorSplotch color={this.props.threadInfo.color} />
            <SingleLine style={this.props.styles.text}>
              {this.props.threadInfo.uiName}
            </SingleLine>
          </View>
          <ThreadIcon
            threadType={this.props.threadInfo.type}
            color={this.props.colors.panelForegroundSecondaryLabel}
          />
        </Button>
      </View>
    );
  }

  onPress = () => {
    const { threadInfo, navigate } = this.props;
    navigate({
      name: MessageListRouteName,
      params: { threadInfo },
      key: `${MessageListRouteName}${threadInfo.id}`,
    });
  };
}

const styles = {
  button: {
    flex: 1,
    flexDirection: 'row',
    paddingVertical: 8,
    paddingLeft: 12,
    paddingRight: 10,
    alignItems: 'center',
    borderTopWidth: 1,
    borderColor: 'panelForegroundBorder',
  },
  container: {
    backgroundColor: 'panelForeground',
    flex: 1,
    paddingHorizontal: 12,
  },
  lastButton: {
    paddingBottom: Platform.OS === 'ios' ? 12 : 10,
    paddingTop: 8,
  },
  leftSide: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  text: {
    flex: 1,
    color: 'link',
    fontSize: 16,
    paddingLeft: 8,
  },
};
const stylesSelector = styleSelector(styles);

export default connect((state: AppState) => ({
  colors: colorsSelector(state),
  styles: stylesSelector(state),
}))(ThreadSettingsChildThread);
<commit_msg>[native] Convert ThreadSettingsChildThread to hook<commit_after>// @flow

import type { ThreadInfo } from 'lib/types/thread-types';
import type { ThreadSettingsNavigate } from './thread-settings.react';

import * as React from 'react';
import { View, Platform } from 'react-native';

import { MessageListRouteName } from '../../navigation/route-names';
import Button from '../../components/button.react';
import ColorSplotch from '../../components/color-splotch.react';
import ThreadIcon from '../../components/thread-icon.react';
import { useColors, useStyles } from '../../themes/colors';
import { SingleLine } from '../../components/single-line.react';

type Props = {|
  +threadInfo: ThreadInfo,
  +navigate: ThreadSettingsNavigate,
  +lastListItem: boolean,
|};
function ThreadSettingsChildThread(props: Props) {
  const { navigate, threadInfo } = props;
  const onPress = React.useCallback(() => {
    navigate({
      name: MessageListRouteName,
      params: { threadInfo },
      key: `${MessageListRouteName}${threadInfo.id}`,
    });
  }, [navigate, threadInfo]);

  const styles = useStyles(unboundStyles);
  const colors = useColors();

  const lastButtonStyle = props.lastListItem ? styles.lastButton : null;
  return (
    <View style={styles.container}>
      <Button onPress={onPress} style={[styles.button, lastButtonStyle]}>
        <View style={styles.leftSide}>
          <ColorSplotch color={threadInfo.color} />
          <SingleLine style={styles.text}>{threadInfo.uiName}</SingleLine>
        </View>
        <ThreadIcon
          threadType={threadInfo.type}
          color={colors.panelForegroundSecondaryLabel}
        />
      </Button>
    </View>
  );
}

const unboundStyles = {
  button: {
    flex: 1,
    flexDirection: 'row',
    paddingVertical: 8,
    paddingLeft: 12,
    paddingRight: 10,
    alignItems: 'center',
    borderTopWidth: 1,
    borderColor: 'panelForegroundBorder',
  },
  container: {
    backgroundColor: 'panelForeground',
    flex: 1,
    paddingHorizontal: 12,
  },
  lastButton: {
    paddingBottom: Platform.OS === 'ios' ? 12 : 10,
    paddingTop: 8,
  },
  leftSide: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  text: {
    flex: 1,
    color: 'link',
    fontSize: 16,
    paddingLeft: 8,
  },
};

export default ThreadSettingsChildThread;
<|endoftext|>


<commit_before>describe("views.pairingPage", function() {
  var subject;

  beforeEach(function() {
    subject = new pairmatic.views.pairingPage();
  });

  it("uses the pairingPage template when rendered", function() {
    spyOn(JST, 'client/js/templates/pairingPage.hbs').and.callReturn('<div/>');

    var renderReturnValue = subject.render();

    expect(renderReturnValue).toBe(subject);
    expect(JST['client/js/templates/pairingPage.hbs']).toHaveBeenCalled();
  });

  it("should re-render when system state is updated", function() {
    var people = pairmatic.models.people;
    spyOn(people, 'toJSON').and.callReturn({});  // spy on this because render function is private
    people.trigger('reset');
    expect(people.toJSON).toHaveBeenCalled();
  });

  it("marks avatars as draggable when rendered", function() {
    var spiedOnWrappedSelector;
    setupSpyOnJquery('.avatar', function(spiedObject) {
      spiedOnWrappedSelector = spiedObject;
      spyOn(spiedObject, 'draggable');
    });

    subject.render();

    expect(spiedOnWrappedSelector.draggable).toHaveBeenCalled();
  });

  describe("values passed to template", function() {
    var capturedTemplateArgs;

    beforeEach(function() {
      spyOn(JST, 'client/js/templates/pairingPage.hbs').and.callFake(
          function(infoHash) { capturedTemplateArgs = infoHash; } );
    });

    it("should pass right active/inactive lists to template", function() {
      var people = simplePeopleListFixture();
      pairmatic.models.people.reset(people);

      // only assert against fields we sent in....
      capturedTemplateArgs.activeUsers =
          _(capturedTemplateArgs.activeUsers  ).map(function(personHash) {
              return { active: personHash.active, name: personHash.name }; });
      capturedTemplateArgs.inactiveUsers =
          _(capturedTemplateArgs.inactiveUsers).map(function(personHash) {
              return { active: personHash.active, name: personHash.name }; });

      expect(JST['client/js/templates/pairingPage.hbs']).toHaveBeenCalled();
      expect(capturedTemplateArgs).toEqual({
	activeUsers:   [
	  { active: true,  name: 'one' },
	  { active: true,  name: 'four' }
	],
	inactiveUsers: [
	  { active: false, name: 'two' },
	  { active: false, name: 'three' }
	]
      });
    });

    it("should send email addresses as their md5 hashes", function() {
      var people = simplePeopleListFixture().slice(0,2);
      pairmatic.models.people.reset(people);

      expect(JST['client/js/templates/pairingPage.hbs']).toHaveBeenCalledWith({
	activeUsers:   [{ active: true,  name: 'one', email: hex_md5('one@example.com') }],
	inactiveUsers: [{ active: false, name: 'two', email: hex_md5('two@three.four') }]
      });
    });
  });
});
<commit_msg>refactor unit spec for pairing page view<commit_after>describe("views.pairingPage", function() {
  var subject;

  describe("when rendered", funtion() {
    beforeEach(function() {
      subject = new pairmatic.views.pairingPage();
    });

    it("uses the pairingPage template", function() {
      spyOn(JST, 'client/js/templates/pairingPage.hbs').and.callReturn('<div/>');

      var renderReturnValue = subject.render();

      expect(renderReturnValue).toBe(subject);
      expect(JST['client/js/templates/pairingPage.hbs']).toHaveBeenCalled();
    });

    it("it responds to model updates", function() {
      var people = pairmatic.models.people;
      spyOn(people, 'toJSON').and.callReturn({});  // spy on this because render function is private
      people.trigger('reset');
      expect(people.toJSON).toHaveBeenCalled();
    });

    it("it marks avatars as draggable", function() {
      var spiedOnWrappedSelector;
      setupSpyOnJquery('.avatar', function(spiedObject) {
	spiedOnWrappedSelector = spiedObject;
	spyOn(spiedObject, 'draggable');
      });

      subject.render();

      expect(spiedOnWrappedSelector.draggable).toHaveBeenCalled();
    });

    describe("values passed to template", function() {
      var capturedTemplateArgs;

      beforeEach(function() {
	spyOn(JST, 'client/js/templates/pairingPage.hbs').and.callFake(
	    function(infoHash) { capturedTemplateArgs = infoHash; } );
      });

      it("should pass right active/inactive lists to template", function() {
	var people = simplePeopleListFixture();
	pairmatic.models.people.reset(people);

	// only assert against fields we sent in....
	capturedTemplateArgs.activeUsers =
	    _(capturedTemplateArgs.activeUsers  ).map(function(personHash) {
		return { active: personHash.active, name: personHash.name }; });
	capturedTemplateArgs.inactiveUsers =
	    _(capturedTemplateArgs.inactiveUsers).map(function(personHash) {
		return { active: personHash.active, name: personHash.name }; });

	expect(JST['client/js/templates/pairingPage.hbs']).toHaveBeenCalled();
	expect(capturedTemplateArgs).toEqual({
	  activeUsers:   [
	    { active: true,  name: 'one' },
	    { active: true,  name: 'four' }
	  ],
	  inactiveUsers: [
	    { active: false, name: 'two' },
	    { active: false, name: 'three' }
	  ]
	});
      });

      it("should send email addresses as their md5 hashes", function() {
	var people = simplePeopleListFixture().slice(0,2);
	pairmatic.models.people.reset(people);

	expect(JST['client/js/templates/pairingPage.hbs']).toHaveBeenCalledWith({
	  activeUsers:   [{ active: true,  name: 'one', email: hex_md5('one@example.com') }],
	  inactiveUsers: [{ active: false, name: 'two', email: hex_md5('two@three.four') }]
	});
      });
    });
  });
});
<|endoftext|>