<commit_before>import { createEntryFacade } from "@buttercup/facades";
import * as Buttercup from "../../shared/library/buttercup.js";
import { dispatch, getState } from "../redux/index.js";
import log from "../../shared/library/log.js";
import {
    addArchiveByRequest,
    addNewEntry,
    archiveToObjectGroupsOnly,
    generateEntryPath,
    getArchive,
    getMatchingEntriesForSearchTerm,
    getMatchingEntriesForURL,
    getNameForSource,
    getUnlockedSourcesCount,
    lockSource,
    lockSources,
    openCredentialsPageForEntry,
    removeSource,
    sendCredentialsToTab,
    unlockSource
} from "./archives.js";
import { setEntrySearchResults, setSourcesCount } from "../../shared/actions/searching.js";
import { setCurrentArchiveId } from "../../shared/actions/archives.js";
import { setConfig } from "../../shared/actions/app.js";
import { clearLastLogin, getLastLogin, saveLastLogin } from "./lastLogin.js";
import { lastPassword } from "./lastGeneratedPassword.js";
import { createNewTab, getCurrentTab, sendTabMessage } from "../../shared/library/extension.js";
import { getCurrentArchive } from "../../shared/selectors/archives.js";

const { ENTRY_URL_TYPE_GENERAL, ENTRY_URL_TYPE_ICON, ENTRY_URL_TYPE_LOGIN, getEntryURLs } = Buttercup.tools.entry;

const LAST_LOGIN_MAX_AGE = 0.5 * 60 * 1000; // 30 seconds

function clearSearchResults() {
    return getUnlockedSourcesCount().then(unlockedSources => {
        dispatch(setEntrySearchResults([]));
        dispatch(setSourcesCount(unlockedSources));
    });
}

function handleMessage(request, sender, sendResponse) {
    switch (request.type) {
        case "add-archive": {
            const { payload } = request;
            addArchiveByRequest(payload)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            // Async
            return true;
        }
        case "add-new-entry": {
            const { payload } = request;
            const { username, password, url, title, sourceID, groupID } = payload;
            addNewEntry(sourceID, groupID, title, username, password, url)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "clear-search":
            clearSearchResults();
            return false;
        case "clear-used-credentials":
            clearLastLogin();
            return false;
        case "get-groups-tree": {
            const { sourceID } = request;
            getArchive(sourceID)
                .then(archive => {
                    const obj = archiveToObjectGroupsOnly(archive);
                    sendResponse({ ok: true, groups: obj.groups });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "get-used-credentials": {
            const force = !!request.force;
            const currentID = sender.tab.id;
            const lastLogin = getLastLogin();
            if (lastLogin && (lastLogin.tabID === currentID || force)) {
                const now = new Date();
                const lastLoginAge = now - lastLogin.timestamp;
                if (lastLoginAge <= LAST_LOGIN_MAX_AGE || force) {
                    sendResponse({ ok: true, credentials: lastLogin });
                } else {
                    clearLastLogin();
                    sendResponse({ ok: true, credentials: null });
                }
            } else {
                sendResponse({ ok: true, credentials: null });
            }
            return false;
        }
        case "lock-all-archives": {
            lockSources()
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "lock-archive": {
            const { sourceID } = request;
            lockSource(sourceID)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "open-credentials-url": {
            const { sourceID, entryID } = request;
            openCredentialsPageForEntry(sourceID, entryID);
            return false;
        }
        case "open-tab": {
            const { url } = request;
            log.info(`Will open new tab by request: ${url}`);
            createNewTab(url);
            return false;
        }
        case "remove-archive": {
            const { sourceID } = request;
            removeSource(sourceID)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "save-used-credentials": {
            const { credentials } = request;
            const { url, username } = credentials;
            getMatchingEntriesForURL(url)
                .then(entries => entries.filter(entryResult => entryResult.entry.getProperty("username") === username))
                .then(entries => {
                    if (entries.length > 0) {
                        log.info("Provided login details already exist for URL that was requested to be saved.");
                        log.info(`Will not save login credentials from tab: ${sender.tab.id}`);
                    } else {
                        // No existing entries, ok to save
                        log.info(`Saved login credentials from tab: ${sender.tab.id}`);
                        saveLastLogin({
                            ...credentials,
                            tabID: sender.tab.id
                        });
                    }
                });
            return false;
        }
        case "search-entries-for-term": {
            const { term } = request;
            Promise.all([getMatchingEntriesForSearchTerm(term), getUnlockedSourcesCount()])
                .then(processSearchResults)
                .catch(err => {
                    console.error(err);
                });
            return false;
        }
        case "search-entries-for-url": {
            const { url } = request;
            Promise.all([getMatchingEntriesForURL(url), getUnlockedSourcesCount()])
                .then(processSearchResults)
                .catch(err => {
                    console.error(err);
                });
            return false;
        }
        case "send-credentials-to-current-tab": {
            const { sourceID, entryID, signIn } = request;
            sendCredentialsToTab(sourceID, entryID, signIn)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "set-generated-password": {
            const { password } = request;
            getCurrentTab().then(tab => {
                sendTabMessage(tab.id, {
                    type: "set-generated-password",
                    password
                });
            });
            lastPassword.value = password;
            return false;
        }
        case "unlock-archive": {
            const { sourceID, masterPassword } = request;
            unlockSource(sourceID, masterPassword)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "set-current-vault-context": {
            dispatch(setCurrentArchiveId(request.vaultId));
            return;
        }
        case "set-config": {
            dispatch(
                setConfig({
                    key: request.key,
                    value: request.value
                })
            );
        }
        default:
            // Do nothing
            break;
    }
}

function processSearchResults([entries, sources]) {
    const currentArchive = getCurrentArchive(getState());
    return Promise.all(
        entries
            .filter(entry => {
                if (currentArchive) {
                    return currentArchive.id === entry.sourceID;
                }
                return true;
            })
            .map(info =>
                getNameForSource(info.sourceID).then(name => ({
                    ...info,
                    sourceName: name
                }))
            )
    ).then(entries => {
        dispatch(
            setEntrySearchResults(
                entries.map(({ entry, sourceID, sourceName }) => {
                    const facade = createEntryFacade(entry);
                    return {
                        title: entry.getProperty("title"),
                        id: entry.id,
                        entryPath: generateEntryPath(entry),
                        sourceID,
                        sourceName,
                        facade,
                        url: getEntryURLs(entry.getProperty(), ENTRY_URL_TYPE_LOGIN)
                    };
                })
            )
        );
        dispatch(setSourcesCount(sources));
    });
}

export function startMessageListener() {
    chrome.runtime.onMessage.addListener(handleMessage);
}
<commit_msg>Return correct url value<commit_after>import { createEntryFacade } from "@buttercup/facades";
import * as Buttercup from "../../shared/library/buttercup.js";
import { dispatch, getState } from "../redux/index.js";
import log from "../../shared/library/log.js";
import {
    addArchiveByRequest,
    addNewEntry,
    archiveToObjectGroupsOnly,
    generateEntryPath,
    getArchive,
    getMatchingEntriesForSearchTerm,
    getMatchingEntriesForURL,
    getNameForSource,
    getUnlockedSourcesCount,
    lockSource,
    lockSources,
    openCredentialsPageForEntry,
    removeSource,
    sendCredentialsToTab,
    unlockSource
} from "./archives.js";
import { setEntrySearchResults, setSourcesCount } from "../../shared/actions/searching.js";
import { setCurrentArchiveId } from "../../shared/actions/archives.js";
import { setConfig } from "../../shared/actions/app.js";
import { clearLastLogin, getLastLogin, saveLastLogin } from "./lastLogin.js";
import { lastPassword } from "./lastGeneratedPassword.js";
import { createNewTab, getCurrentTab, sendTabMessage } from "../../shared/library/extension.js";
import { getCurrentArchive } from "../../shared/selectors/archives.js";

const { ENTRY_URL_TYPE_GENERAL, ENTRY_URL_TYPE_ICON, ENTRY_URL_TYPE_LOGIN, getEntryURLs } = Buttercup.tools.entry;

const LAST_LOGIN_MAX_AGE = 0.5 * 60 * 1000; // 30 seconds

function clearSearchResults() {
    return getUnlockedSourcesCount().then(unlockedSources => {
        dispatch(setEntrySearchResults([]));
        dispatch(setSourcesCount(unlockedSources));
    });
}

function handleMessage(request, sender, sendResponse) {
    switch (request.type) {
        case "add-archive": {
            const { payload } = request;
            addArchiveByRequest(payload)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            // Async
            return true;
        }
        case "add-new-entry": {
            const { payload } = request;
            const { username, password, url, title, sourceID, groupID } = payload;
            addNewEntry(sourceID, groupID, title, username, password, url)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "clear-search":
            clearSearchResults();
            return false;
        case "clear-used-credentials":
            clearLastLogin();
            return false;
        case "get-groups-tree": {
            const { sourceID } = request;
            getArchive(sourceID)
                .then(archive => {
                    const obj = archiveToObjectGroupsOnly(archive);
                    sendResponse({ ok: true, groups: obj.groups });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "get-used-credentials": {
            const force = !!request.force;
            const currentID = sender.tab.id;
            const lastLogin = getLastLogin();
            if (lastLogin && (lastLogin.tabID === currentID || force)) {
                const now = new Date();
                const lastLoginAge = now - lastLogin.timestamp;
                if (lastLoginAge <= LAST_LOGIN_MAX_AGE || force) {
                    sendResponse({ ok: true, credentials: lastLogin });
                } else {
                    clearLastLogin();
                    sendResponse({ ok: true, credentials: null });
                }
            } else {
                sendResponse({ ok: true, credentials: null });
            }
            return false;
        }
        case "lock-all-archives": {
            lockSources()
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "lock-archive": {
            const { sourceID } = request;
            lockSource(sourceID)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "open-credentials-url": {
            const { sourceID, entryID } = request;
            openCredentialsPageForEntry(sourceID, entryID);
            return false;
        }
        case "open-tab": {
            const { url } = request;
            log.info(`Will open new tab by request: ${url}`);
            createNewTab(url);
            return false;
        }
        case "remove-archive": {
            const { sourceID } = request;
            removeSource(sourceID)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "save-used-credentials": {
            const { credentials } = request;
            const { url, username } = credentials;
            getMatchingEntriesForURL(url)
                .then(entries => entries.filter(entryResult => entryResult.entry.getProperty("username") === username))
                .then(entries => {
                    if (entries.length > 0) {
                        log.info("Provided login details already exist for URL that was requested to be saved.");
                        log.info(`Will not save login credentials from tab: ${sender.tab.id}`);
                    } else {
                        // No existing entries, ok to save
                        log.info(`Saved login credentials from tab: ${sender.tab.id}`);
                        saveLastLogin({
                            ...credentials,
                            tabID: sender.tab.id
                        });
                    }
                });
            return false;
        }
        case "search-entries-for-term": {
            const { term } = request;
            Promise.all([getMatchingEntriesForSearchTerm(term), getUnlockedSourcesCount()])
                .then(processSearchResults)
                .catch(err => {
                    console.error(err);
                });
            return false;
        }
        case "search-entries-for-url": {
            const { url } = request;
            Promise.all([getMatchingEntriesForURL(url), getUnlockedSourcesCount()])
                .then(processSearchResults)
                .catch(err => {
                    console.error(err);
                });
            return false;
        }
        case "send-credentials-to-current-tab": {
            const { sourceID, entryID, signIn } = request;
            sendCredentialsToTab(sourceID, entryID, signIn)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "set-generated-password": {
            const { password } = request;
            getCurrentTab().then(tab => {
                sendTabMessage(tab.id, {
                    type: "set-generated-password",
                    password
                });
            });
            lastPassword.value = password;
            return false;
        }
        case "unlock-archive": {
            const { sourceID, masterPassword } = request;
            unlockSource(sourceID, masterPassword)
                .then(() => {
                    sendResponse({ ok: true });
                })
                .catch(err => {
                    sendResponse({ ok: false, error: err.message });
                    console.error(err);
                });
            return true;
        }
        case "set-current-vault-context": {
            dispatch(setCurrentArchiveId(request.vaultId));
            return;
        }
        case "set-config": {
            dispatch(
                setConfig({
                    key: request.key,
                    value: request.value
                })
            );
        }
        default:
            // Do nothing
            break;
    }
}

function processSearchResults([entries, sources]) {
    const currentArchive = getCurrentArchive(getState());
    return Promise.all(
        entries
            .filter(entry => {
                if (currentArchive) {
                    return currentArchive.id === entry.sourceID;
                }
                return true;
            })
            .map(info =>
                getNameForSource(info.sourceID).then(name => ({
                    ...info,
                    sourceName: name
                }))
            )
    ).then(entries => {
        dispatch(
            setEntrySearchResults(
                entries.map(({ entry, sourceID, sourceName }) => {
                    const facade = createEntryFacade(entry);
                    const urls = getEntryURLs(entry.getProperty(), ENTRY_URL_TYPE_LOGIN);
                    return {
                        title: entry.getProperty("title"),
                        id: entry.id,
                        entryPath: generateEntryPath(entry),
                        sourceID,
                        sourceName,
                        facade,
                        url: urls[0] || null,
                        urls
                    };
                })
            )
        );
        dispatch(setSourcesCount(sources));
    });
}

export function startMessageListener() {
    chrome.runtime.onMessage.addListener(handleMessage);
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        VK Code
// @namespace   vkcode
// @description VK Code Highlighter
// @author      Queyenth
// @include     *vk.com/*
// @version     1
// @grant       none
// ==/UserScript==

// Replace 12 with any size you want
var FONT_SIZE = 'font-size: 12px';
// Replace monospace with your favourite font
var FONT_FAMILY = 'font-family: consolas';

// Available themes: default, solarized_dark, solarized_light, github,
// railscasts, monokai_sublime, mono-blue, tomorrow, color-brewer, zenburn
var THEME = 'mono-blue';
var TAB_TO_SPACE = 2;

// Creating a new stylesheet
var sheet = (function() {
  var style = document.createElement("style");
  // WebKit hack
  style.appendChild(document.createTextNode(""));
  document.head.appendChild(style);

  return style.sheet;
})();

function loadScript(scriptSrc, callback) {
  var head = document.getElementsByTagName("head")[0];
  var js = document.createElement("script");
  js.type = "text/javascript";
  js.src = scriptSrc;

  js.onreadystatechange = callback;
  js.onload = callback;

  head.appendChild(js);
}

function loadCss(cssHref) {
  var head = document.getElementsByTagName("head")[0];
  var cssElement = document.createElement("link");
  cssElement.rel = "stylesheet";
  cssElement.href = cssHref;
  head.appendChild(cssElement);
}

function addCSSRule(sheet, selector, rules, index) {
  if ("insertRule" in sheet) {
    sheet.insertRule(selector + "{" + rules + "}", index);
  }
  else if ("addRule" in sheet) {
    sheet.addRule(selector, rules, index);
  }
}

function initCssRules() {
  addCSSRule(sheet, 'pre', FONT_FAMILY);
  addCSSRule(sheet, 'pre code', FONT_FAMILY);
  addCSSRule(sheet, 'pre', FONT_SIZE);
  addCSSRule(sheet, 'pre', 'margin: 0;');
  addCSSRule(sheet, '.hljs', 'padding: 1em !important;');
}

function highlightBlock(block) {
  if ($(block).html().indexOf("<code>
") > -1) {
    console.log(block);
    $(block).html($(block).html().replace("<code>
", "
").replace("</code>", "
"));
    hljs.highlightBlock($(block).children('pre').children('code')[0]);
  }
}

function getImFromTr(trblock) {
  return $(trblock).children('.im_log_body').children('.wrapped').children('.im_msg_text')[0];
}

function IMMutationObserver() {
  var observer = new MutationObserver(
    function(mutations) {
      mutations.forEach(function(mutation) {
        for (var i = 0; i < mutation.addedNodes.length; i++) {
          highlightBlock(getImFromTr(mutation.addedNodes[i]));
        }
      });
    }
  );
  observer.observe($('.im_log_t tbody:visible')[0], {childList: true});
  return observer;
}

function highlightAllBlocksOnPage() {
  $('.im_msg_text').each(function(i, block) {
    highlightBlock(block);
  });
}

function highlight() {
  var observer = IMMutationObserver();
  hljs.configure({useBR: true, tabReplace: '  '});
  console.log($('.im_log_t tbody:visible')[0]);
  highlightAllBlocksOnPage();
  $(".im_tab, .im_tab_selected").on("click", function() {
    window.setTimeout(function() {
      highlightAllBlocksOnPage();
      observer.disconnect();
      observer = IMMutationObserver();
    }, 500);
    //window.setTimeout(observer.observe($('.im_log_t tbody:visible')[0], {childList: true}), 500);
  });
}

var jqueryloaded = function() {
  $(document).ready(function() {
    loadCss("https://highlightjs.org/static/styles/"+THEME+".css");
    initCssRules();
    loadScript("https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/highlight.min.js", highlight);
  });
}

loadScript("https://code.jquery.com/jquery-2.1.4.min.js", jqueryloaded);
<commit_msg>Refactor a bit and fixed #4<commit_after>// ==UserScript==
// @name        VK Code
// @namespace   vkcode
// @description VK Code Highlighter
// @author      Queyenth
// @include     *vk.com/im*
// @version     1
// @grant       none
// ==/UserScript==

// Replace 12 with any size you want
var FONT_SIZE = 'font-size: 10px';
// Replace monospace with your favourite font
var FONT_FAMILY = "font-family: 'monaco for powerline'";
//
var TAB_TO_SPACE = "  ";

// List of all themes: https://github.com/queyenth/vkcode/tree/gh-pages/highlight.js/styles
var THEME = 'mono-blue';

// Creating a new stylesheet
var sheet = (function() {
  var style = document.createElement("style");
  // WebKit hack
  style.appendChild(document.createTextNode(""));
  document.head.appendChild(style);

  return style.sheet;
})();

function loadScript(scriptSrc, callback) {
  var head = document.getElementsByTagName("head")[0];
  var js = document.createElement("script");
  js.type = "text/javascript";
  js.src = scriptSrc;

  js.onreadystatechange = callback;
  js.onload = callback;

  head.appendChild(js);
}

function loadCss(cssHref) {
  var head = document.getElementsByTagName("head")[0];
  var cssElement = document.createElement("link");
  cssElement.rel = "stylesheet";
  cssElement.href = cssHref;
  head.appendChild(cssElement);
}

function addCSSRule(sheet, selector, rules, index) {
  if ("insertRule" in sheet) {
    sheet.insertRule(selector + "{" + rules + "}", index);
  }
  else if ("addRule" in sheet) {
    sheet.addRule(selector, rules, index);
  }
}

function initCssRules() {
  addCSSRule(sheet, 'pre', FONT_FAMILY);
  addCSSRule(sheet, 'pre code', FONT_FAMILY);
  addCSSRule(sheet, 'pre', FONT_SIZE);
  addCSSRule(sheet, 'pre', 'margin: 0;');
  addCSSRule(sheet, '.hljs', 'padding: 1em !important;');
}

function parseMessage(block) {
  if ($(block).html().indexOf("</code>") === -1) $(block).html($(block).html() + "
");
  $(block).html($(block).html().replace("<code>
", "
").replace("</code>", "
"));
  $(block).html($(block).html().replace(/\\t( )*/g, TAB_TO_SPACE));
  // TODO: replace all smiles, and remove all links, << >> etc
}

function highlightBlock(block) {
  if ($(block).html().indexOf("<code>
") > -1) {
    parseMessage(block);
    hljs.highlightBlock($(block).children('pre').children('code')[0]);
    hljs.lineNumbersBlock($(block).children('pre').children('code')[0]);
  }
}

function getImFromTr(trblock) {
  return $(trblock).find('.im_msg_text');
}

function IMMutationObserver() {
  var observer = new MutationObserver(
    function(mutations) {
      mutations.forEach(function(mutation) {
        for (var i = 0; i < mutation.addedNodes.length; i++) {
          var msg = getImFromTr(mutation.addedNodes[i]);
          msg.each(function(i, block) {
            highlightBlock(block);
          });
        }
      });
    }
  );
  observer.observe($('.im_log_t tbody:visible')[0], {childList: true});
  return observer;
}

function highlightAllBlocksOnPage() {
  $('.im_msg_text').each(function(i, block) {
    highlightBlock(block);
  });
}

loadScript("https://code.jquery.com/jquery-2.1.4.min.js", function() {
  $(document).ready(function() {
    loadCss("https://queyenth.github.io/vkcode/highlight.js/styles/"+THEME+".css");
    initCssRules();
    loadScript("https://queyenth.github.io/vkcode/highlight.js/highlight.pack.js", function() {
      loadScript("https://queyenth.github.io/vkcode/highlight.js/highlightjs-line-numbers.min.js", function() {
        var observer = IMMutationObserver();
        hljs.configure({useBR: true, tabReplace: '  '});
        highlightAllBlocksOnPage();
        window.setTimeout(function() {
          $("#im_dialogs").on("click", ".dialogs_row", function() {
            console.log("pressed chat!");
          });
        }, 500);
        $(".im_tab, .im_tab_selected").on("click", function() {
          console.log("pressed chat!");
          window.setTimeout(function() {
            highlightAllBlocksOnPage();
            observer.disconnect();
            observer = IMMutationObserver();
          }, 500);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////
// NR.DOM = > jquery--$
//////////////////////////////////////////////////////////////////

var

UglifyJS = require('uglify-js'),

log =  require('../neuron/log'),
neuronDom =  require('../neuron/neuron-dom'),

map_1 = {
  get : "eq",
  match : "is",
  el : "get",
  all : "find",
  count : "length",
  one : "find",
  forEach : "forEach"
},

map_2 = {
  prev:'prev',
  prevAll:'prevAll',
  next:'next',
  nextAll:'nextAll',
  children:'children',
  parent:'parent',
  parents:'parents'
},

handler = {
    before: function(node,descend){

        //判断为.()类型的
        if(node.CTOR === UglifyJS.AST_Call){
            var _expression;
            var dotAST = node.expression || "";
            var _property = dotAST.property || "";

            //判断为$("")类型的
            if(dotAST && (map_1[_property] || map_2[_property])){

                 if(dotAST.expression.CTOR === UglifyJS.AST_SymbolRef && _property ==="all"){

                      _expression = new UglifyJS.AST_Call({
                            expression : new UglifyJS.AST_SymbolRef({
                                name:"$"
                             }),
                            args : node.args
                        });

                      descend(_expression,this);

                      return _expression;
                 }

                 if(!neuronDom.is(dotAST)){
                      //log(dotAST);
                  }
                // $.forEach = > 不变
                if(_property === "forEach"){
                    descend(dotAST,this);
                    return node;
                }else{

                    //$.count() = >$.length
                    if(_property === "count"){

                           _expression = new UglifyJS.AST_Dot({
                                         expression : dotAST.expression,
                                         property : "length"
                          });

                           descend(_expression,this);

                           return _expression;
                    }

                    if(map_2[_property] || _property === "one" || _property === "all"){
                         _expression = new UglifyJS.AST_Call({

                            expression: new UglifyJS.AST_Dot({
                                            expression : dotAST.expression,
                                            property : "eq"
                            }),

                            args : [
                                    new UglifyJS.AST_Number({
                                          value : 0
                                    })
                            ]
                          });
                    }else{
                        _expression = dotAST.expression;
                    }

                    if(map_1[_property]){
                        _expression = new UglifyJS.AST_Call({

                                              expression : new UglifyJS.AST_Dot({
                                                  expression : _expression,
                                                  property : map_1[_property]

                                               }),
                                              args : node.args
                                      })
                    }

                    if(_property === "one"){
                        _expression = new UglifyJS.AST_Call({

                            expression: new UglifyJS.AST_Dot({
                                            expression : _expression,
                                            property : "eq"
                                         }),

                            args : [
                                    new UglifyJS.AST_Number({
                                          value : 0
                                    })
                            ]
                          });
                    }
                    descend(_expression,this);
                    return _expression;

                }

            }
        }
    },
            //var expression = node.expression;

            //处理$("") = > $("").eq(0)

            // if(expression && expression.CTOR === UglifyJS.AST_SymbolRef && expression.name === "$"){

                // return  new UglifyJS.AST_Call({

            //                 expression: new UglifyJS.AST_Dot({
            //                                  expression : node,
            //                                  property : "eq"
            //                              }),

            //                 args : [
            //                         new UglifyJS.AST_Number({
            //                               value : 0
            //                         })
            //                 ]
            //             });
           //}

    after: function(node){

    },

    setup: function(){

    },

    tearDown: function(){
        neuronDom.clear_cache();
    }
};

module.exports = handler;<commit_msg>lib/transformer/dom.js:alter<commit_after>//////////////////////////////////////////////////////////////////
// NR.DOM = > jquery--$
//////////////////////////////////////////////////////////////////

var

UglifyJS = require('uglify-js'),

log =  require('../neuron/log'),
neuronDom =  require('../neuron/neuron-dom'),

//流水线处理

//$().方法 => $().eq(0).方法
map_1 = {
  prev:true,
  prevAll:true,
  next:true,
  nextAll:true,
  children:true,
  parent:true,
  parents:true,
  one:true,
  all:true
},

//$().方法=>方法名要变
map_2 = {
  get : "eq",
  match : "is",
  el : "get",
  all : "find",
  one : "find",
  child : "children"
},

//$().方法 => $().方法.eq(0)
map_3 = {
  one :true,
  child:true
},
//特殊处理
map_4 = {
    forEach:true,
    count : "length"
},

handler = {
    before: function(node,descend){

        //判断为.()类型的
        if(node.CTOR === UglifyJS.AST_Call){
            var _expression;
            var dotAST = node.expression || "";
            var _property = dotAST.property || "";

            //判断为.方法()类型的，入口
            if(dotAST && (map_1[_property] || map_2[_property] || map_4[_property] || map_4[_property])){

                //处理$.all() =>$()
                 if(dotAST.expression.CTOR === UglifyJS.AST_SymbolRef && _property ==="all"){

                      _expression = new UglifyJS.AST_Call({
                            expression : new UglifyJS.AST_SymbolRef({
                                name:"$"
                             }),
                            args : node.args
                        });

                      descend(_expression,this);

                      return _expression;
                 }
                 //处理.el(0) =>[0]
                 if(_property === "el" && node.args.length ===1 && node.args[0].CTOR === UglifyJS.AST_Number && node.args[0].value ===0){
                      descend(node,this);
                      return new UglifyJS.AST_Sub({
                          expression:dotAST.expression,
                          property:new UglifyJS.AST_Number({
                              value : 0
                          })
                      })
                 }

                 //打点
                 if(!neuronDom.is(dotAST)){
                     // log(dotAST);
                  }

                // $.forEach = > 不变
                if(_property === "forEach"){
                   // _expression = dotAST.expression;
                    descend(node,this);
                    return node;
                }else{

                    //$.count() = >$.length
                    if(_property === "count"){

                           _expression = new UglifyJS.AST_Dot({
                                         expression : dotAST.expression,
                                         property : "length"
                          });

                           descend(_expression,this);

                           return _expression;
                    }

                    //流水线处理

                    if(map_1[_property]){

                         _expression = new UglifyJS.AST_Call({

                            expression: new UglifyJS.AST_Dot({
                                            expression : dotAST.expression,
                                            property : "eq"
                            }),

                            args : [
                                    new UglifyJS.AST_Number({
                                          value : 0
                                    })
                            ]
                          });

                    }else{
                        _expression = dotAST.expression;
                    }

                    _expression = new UglifyJS.AST_Call({

                                      expression : new UglifyJS.AST_Dot({
                                          expression : _expression,
                                          property : map_2[_property] || _property
                                       }),
                                      args : node.args
                                  })

                    if(map_3[_property]){
                        _expression = new UglifyJS.AST_Call({

                            expression: new UglifyJS.AST_Dot({
                                            expression : _expression,
                                            property : "eq"
                                         }),

                            args : [
                                    new UglifyJS.AST_Number({
                                          value : 0
                                    })
                            ]
                          });
                    }

                    descend(_expression,this);

                    return _expression;

                }

            }
        }
    },
            //var expression = node.expression;

            //处理$("") = > $("").eq(0)

            // if(expression && expression.CTOR === UglifyJS.AST_SymbolRef && expression.name === "$"){

                // return  new UglifyJS.AST_Call({

            //                 expression: new UglifyJS.AST_Dot({
            //                                  expression : node,
            //                                  property : "eq"
            //                              }),

            //                 args : [
            //                         new UglifyJS.AST_Number({
            //                               value : 0
            //                         })
            //                 ]
            //             });
           //}

    after: function(node){

    },

    setup: function(){

    },

    tearDown: function(){
        neuronDom.clear_cache();
        _expression = "";
    }
};

module.exports = handler;<|endoftext|>


<commit_before>/*
    Copyright 2008, 2009, 2010 Boris ARZUR

    This file is part of Kemuri.

    Kemuri is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Kemuri is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public
    License along with Kemuri. If not, see http://www.gnu.org/licenses.
*/

var do_move = true;
function voyage_focus_input( event ) {
    voyage_placeholder.style.opacity = "1.0";
    do_move = false;
    if( typeof( rad_bar_placeholder ) != "undefined" )
        rad_bar_placeholder.style.opacity = "0.0";
    document.getElementById( 'voyage_btns' ).style.display = "inline";
};

function voyage_blur_input( event ) {
    voyage_placeholder.style.opacity = "0.3";
    do_move = true;
    if( typeof( rad_bar_placeholder ) != "undefined" )
        rad_bar_placeholder.style.opacity = "1.0";
    document.getElementById( 'voyage_btns' ).style.display = "hidden";
};

function voyage_create_option( nani ) {
    var option = document.createElement( 'option' );
    option.setAttribute( 'value', nani );
    option.appendChild( document.createTextNode( nani ) );
    return option;
};

function voyage_update_options() {
    var dokomade = document.getElementById( 'dokomade' ).value;
    if( dokomade.size != 0) {
        var select = document.createElement( 'select' );
        select.setAttribute( 'id', 'douyatte' );
        var direct_commit = true;

        if( dokomade.match(/^\d-\d+-\d+$/) || dokomade.match(/^\d+$/) )
            select.appendChild( voyage_create_option( '/sk/' ) );
        else if( dokomade.match(/^\d-\d+-\d+\+\d-\d+-\d+$/) )
            select.appendChild( voyage_create_option( '/biskip/' ) );
        else if( dokomade.match(/^\d+-\d+$/) || dokomade.match(/^\d-\d+-\d+-\d-\d+-\d+$/) )
            select.appendChild( voyage_create_option( '/sk/' ) );
        else if( dokomade.match(/^rad$/) || dokomade.match(/^his$/) )
            select.appendChild( voyage_create_option( '/' ) );
    	else if( dokomade.match(/^[\u4E00-\u9FAF]$/) ) {
            select.appendChild( voyage_create_option( '/yad/' ) );
            select.appendChild( voyage_create_option( '/kan/' ) );
            direct_commit = false;
    	}
        else if( dokomade.match(/^[\u4E00-\u9FAF]+$/) || dokomade.match(/^[\u3040-\u3096]+$/) )
            select.appendChild( voyage_create_option( '/yad/' ) );
    	else select.appendChild( voyage_create_option( '/yad/' ) );

        select.firstChild.setAttribute( 'selected', 'selected' );
        select.setAttribute( 'onchange', 'javascript:voyage_shuppatsu()' );
        voyage_placeholder.appendChild( select );

        if( direct_commit )
            voyage_shuppatsu();
    	else {
            var go_btn = document.createElement( 'input' );
            go_btn.setAttribute( 'type', 'button' );
            go_btn.setAttribute( 'value', '出発' );
            go_btn.setAttribute( 'onclick', 'javascript:voyage_shuppatsu()' );
            voyage_placeholder.appendChild( go_btn );
            voyage_scroll_offset = 70;
            voyage_scroll_hdl( null );
    	}
   } else {
        voyage_blur_input( null );
   }
};

function voyage_shuppatsu() {
    var dokomade = document.getElementById( 'dokomade' ).value;
    var douyatte = document.getElementById( 'douyatte' );
    var path = douyatte.options[douyatte.selectedIndex].value;
    window.location = path + dokomade;
};

function voyage_scroll_hdl(event) {
  if( do_move ) {
    voyage_placeholder.style.top = window.innerHeight - voyage_scroll_offset + window.scrollY;
  }
};

var voyage_scroll_offset = 40;
var voyage_placeholder = document.getElementById( 'voyage' );
document.addEventListener( "scroll", voyage_scroll_hdl, false );
voyage_placeholder.addEventListener( "change", voyage_update_options, false );
voyage_placeholder.addEventListener( "focus", voyage_focus_input, true );
voyage_placeholder.addEventListener( "blur", voyage_blur_input, true );

voyage_placeholder.style.left = 220;
<commit_msg>visual enhancement<commit_after>/*
    Copyright 2008, 2009, 2010 Boris ARZUR

    This file is part of Kemuri.

    Kemuri is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Kemuri is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public
    License along with Kemuri. If not, see http://www.gnu.org/licenses.
*/

var do_move = true;
function voyage_focus_input( event ) {
    voyage_placeholder.style.opacity = "1.0";
    do_move = false;
    if( typeof( rad_bar_placeholder ) != "undefined" )
        rad_bar_placeholder.style.opacity = "0.0";
    document.getElementById( 'voyage_btns' ).style.display = "inline";
};

function voyage_blur_input( event ) {
    voyage_placeholder.style.opacity = "0.3";
    do_move = true;
    if( typeof( rad_bar_placeholder ) != "undefined" )
        rad_bar_placeholder.style.opacity = "1.0";
    document.getElementById( 'voyage_btns' ).style.display = "hidden";
};

function voyage_create_option( nani ) {
    var option = document.createElement( 'option' );
    option.setAttribute( 'value', nani );
    option.appendChild( document.createTextNode( nani ) );
    return option;
};

function voyage_update_options() {
    var dokomade = document.getElementById( 'dokomade' ).value;
    if( dokomade.size != 0) {
        voyage_placeholder.appendChild( document.createElement( 'br' ) );

        var select = document.createElement( 'select' );
        select.setAttribute( 'id', 'douyatte' );
        var direct_commit = true;

        if( dokomade.match(/^\d-\d+-\d+$/) || dokomade.match(/^\d+$/) )
            select.appendChild( voyage_create_option( '/sk/' ) );
        else if( dokomade.match(/^\d-\d+-\d+\+\d-\d+-\d+$/) )
            select.appendChild( voyage_create_option( '/biskip/' ) );
        else if( dokomade.match(/^\d+-\d+$/) || dokomade.match(/^\d-\d+-\d+-\d-\d+-\d+$/) )
            select.appendChild( voyage_create_option( '/sk/' ) );
        else if( dokomade.match(/^rad$/) || dokomade.match(/^his$/) )
            select.appendChild( voyage_create_option( '/' ) );
    	else if( dokomade.match(/^[\u4E00-\u9FAF]$/) ) {
            select.appendChild( voyage_create_option( '/yad/' ) );
            select.appendChild( voyage_create_option( '/kan/' ) );
            direct_commit = false;
    	}
        else if( dokomade.match(/^[\u4E00-\u9FAF]+$/) || dokomade.match(/^[\u3040-\u3096]+$/) )
            select.appendChild( voyage_create_option( '/yad/' ) );
    	else select.appendChild( voyage_create_option( '/yad/' ) );

        select.firstChild.setAttribute( 'selected', 'selected' );
        select.setAttribute( 'onchange', 'javascript:voyage_shuppatsu()' );
        voyage_placeholder.appendChild( select );

        if( direct_commit )
            voyage_shuppatsu();
    	else {
            var go_btn = document.createElement( 'input' );
            go_btn.setAttribute( 'type', 'button' );
            go_btn.setAttribute( 'value', '出発' );
            go_btn.setAttribute( 'onclick', 'javascript:voyage_shuppatsu()' );
            voyage_placeholder.appendChild( go_btn );
            voyage_scroll_offset = 70;
            voyage_scroll_hdl( null );
    	}
   } else {
        voyage_blur_input( null );
   }
};

function voyage_shuppatsu() {
    var dokomade = document.getElementById( 'dokomade' ).value;
    var douyatte = document.getElementById( 'douyatte' );
    var path = douyatte.options[douyatte.selectedIndex].value;
    window.location = path + dokomade;
};

function voyage_scroll_hdl(event) {
  if( do_move ) {
    voyage_placeholder.style.top = window.innerHeight - voyage_scroll_offset + window.scrollY;
  }
};

var voyage_scroll_offset = 40;
var voyage_placeholder = document.getElementById( 'voyage' );
document.addEventListener( "scroll", voyage_scroll_hdl, false );
voyage_placeholder.addEventListener( "change", voyage_update_options, false );
voyage_placeholder.addEventListener( "focus", voyage_focus_input, true );
voyage_placeholder.addEventListener( "blur", voyage_blur_input, true );

voyage_placeholder.style.left = 220;
<|endoftext|>


<commit_before>import React from "react"

import Layout from "../Layout"
import Anchor from "../Anchor"
import Heading from "../Heading"
import Newsletter from "./Newsletter"

const callToActionStyle = {
  padding: 25,
  display: "flex",
  flexDirection: "row",
  alignItems: "center",
  justifyContent: "space-around"
}

export default function LandingPage () {
  return <Layout subtitle="Welcome to Polish">

        <Heading kind="page" subtitle="Welcome to Polish">
          Lacqueristas
        </Heading>

        <Newsletter />

        <Anchor kind="primary" href="/sign-up">
          Join us
        </Anchor>

        <Anchor kind="normal" href="/sign-in">Login</Anchor>

  </Layout>
}
<commit_msg>We don't really want to show it right now<commit_after>import React from "react"

import Layout from "../Layout"
import Anchor from "../Anchor"
import Heading from "../Heading"
import Newsletter from "./Newsletter"

const callToActionStyle = {
  padding: 25,
  display: "none",
  flexDirection: "row",
  alignItems: "center",
  justifyContent: "space-around"
}

export default function LandingPage () {
  return <Layout subtitle="Welcome to Polish">

        <Heading kind="page" subtitle="Welcome to Polish">
          Lacqueristas
        </Heading>

        <Newsletter />

        <Anchor kind="primary" href="/sign-up">
          Join us
        </Anchor>

        <Anchor kind="normal" href="/sign-in">Login</Anchor>

  </Layout>
}
<|endoftext|>


<commit_before>import React, { Suspense } from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router';
import Loading from 'components/Loading';
import Button from 'components/Button';
import Icon from 'components/Icon';
import ErrorBoundary from 'components/Wrappers/ErrorBoundary';
import Featured from './Featured';
import Notification from 'components/Notification';
import { NavLink } from 'react-router-dom';
import { css } from 'emotion';
import { Color, mobileMaxWidth } from 'constants/css';
import { connect } from 'react-redux';
import {
  openAddPlaylistModal,
  openAddVideoModal
} from 'redux/actions/VideoActions';
const WorkMenuItems = React.lazy(() => import('./WorkMenuItems'));
const Videos = React.lazy(() => import('./Videos'));
const Links = React.lazy(() => import('./Links'));

WorkSection.propTypes = {
  location: PropTypes.object.isRequired,
  mobileNavbarShown: PropTypes.bool.isRequired,
  openAddVideoModal: PropTypes.func.isRequired,
  openAddPlaylistModal: PropTypes.func.isRequired,
  userId: PropTypes.number
};

function WorkSection({
  location,
  mobileNavbarShown,
  openAddPlaylistModal,
  openAddVideoModal,
  userId
}) {
  return (
    <ErrorBoundary>

          <Suspense fallback={<Loading />}>
            <WorkMenuItems
              className={css`
                top: CALC(50vh - 11rem);
                height: auto;
                width: 19rem;
                display: flex;
                position: fixed;
                justify-content: center;
                flex-direction: column;
                font-size: 2rem;
                font-family: sans-serif, Arial, Helvetica;
                > a {
                  padding: 1.5rem;
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                  text-align: center;
                  width: 100%;
                  justify-content: center;
                  color: ${Color.gray()};
                  text-decoration: none;
                }
                > a:hover {
                  font-weight: bold;
                  color: ${Color.black()};
                }
                > a.active {
                  font-weight: bold;
                  color: ${Color.black()};
                  background: #fff;
                }
                @media (max-width: ${mobileMaxWidth}) {
                  display: none;
                }
              `}
            />
          </Suspense>

            <Suspense fallback={<Loading />}>
              <Switch>
                <Route path="/videos" component={Videos} />
                <Route path="/links" component={Links} />
                <Route path="/xp" component={Featured} />
              </Switch>
            </Suspense>

          <Notification
            className={css`
              width: 31rem;
              overflow-y: scroll;
              -webkit-overflow-scrolling: touch;
              right: 1rem;
              top: 5rem;
              bottom: 0;
              position: absolute;
              @media (max-width: ${mobileMaxWidth}) {
                display: none;
              }
            `}
            location={location.pathname.substring(1)}
          >
            {location.pathname === '/videos' && userId && (
              <>
                <Button
                  skeuomorphic
                  color="darkerGray"
                  style={{
                    fontSize: '2rem',
                    width: '99%',
                    marginTop: '0.1rem',
                    marginBottom: '1rem'
                  }}
                  onClick={openAddVideoModal}
                >
                  + Add Video
                </Button>
                <Button
                  skeuomorphic
                  color="darkerGray"
                  style={{
                    fontSize: '2rem',
                    width: '99%',
                    marginBottom: '1rem'
                  }}
                  onClick={openAddPlaylistModal}
                >
                  + Add Playlist
                </Button>
              </>
            )}
          </Notification>

 a {
              color: ${Color.gray()};
              &:hover {
                color: ${Color.gray()};
              }
            }
            > a.active {
              color: ${Color.black()};
              &:hover {
                color: ${Color.black()};
              }
            }
            @media (max-width: ${mobileMaxWidth}) {
              display: flex;
              z-index: 5;
              position: fixed;
              bottom: 9rem;
              justify-content: space-around;
              align-items: center;
              font-size: 3rem;
              width: 100%;
              height: 5rem;
              background: #fff;
            }
          `}
        >
          <NavLink to="/xp" activeClassName="active">
            <Icon icon="bolt" />
          </NavLink>
          <NavLink to="/videos" activeClassName="active">
            <Icon icon="film" />
          </NavLink>
          <NavLink to="/links" activeClassName="active">
            <Icon icon="book" />
          </NavLink>

    </ErrorBoundary>
  );
}

export default connect(
  state => ({
    userId: state.UserReducer.userId,
    mobileNavbarShown: state.ViewReducer.mobileNavbarShown
  }),
  { openAddPlaylistModal, openAddVideoModal }
)(WorkSection);
<commit_msg>reduce unnecessary lazy load<commit_after>import React, { Suspense } from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router';
import Loading from 'components/Loading';
import Button from 'components/Button';
import Icon from 'components/Icon';
import ErrorBoundary from 'components/Wrappers/ErrorBoundary';
import Featured from './Featured';
import Notification from 'components/Notification';
import WorkMenuItems from './WorkMenuItems';
import { NavLink } from 'react-router-dom';
import { css } from 'emotion';
import { Color, mobileMaxWidth } from 'constants/css';
import { connect } from 'react-redux';
import {
  openAddPlaylistModal,
  openAddVideoModal
} from 'redux/actions/VideoActions';
const Videos = React.lazy(() => import('./Videos'));
const Links = React.lazy(() => import('./Links'));

WorkSection.propTypes = {
  location: PropTypes.object.isRequired,
  mobileNavbarShown: PropTypes.bool.isRequired,
  openAddVideoModal: PropTypes.func.isRequired,
  openAddPlaylistModal: PropTypes.func.isRequired,
  userId: PropTypes.number
};

function WorkSection({
  location,
  mobileNavbarShown,
  openAddPlaylistModal,
  openAddVideoModal,
  userId
}) {
  return (
    <ErrorBoundary>

          <WorkMenuItems
            className={css`
              top: CALC(50vh - 11rem);
              height: auto;
              width: 19rem;
              display: flex;
              position: fixed;
              justify-content: center;
              flex-direction: column;
              font-size: 2rem;
              font-family: sans-serif, Arial, Helvetica;
              > a {
                padding: 1.5rem;
                cursor: pointer;
                display: flex;
                align-items: center;
                text-align: center;
                width: 100%;
                justify-content: center;
                color: ${Color.gray()};
                text-decoration: none;
              }
              > a:hover {
                font-weight: bold;
                color: ${Color.black()};
              }
              > a.active {
                font-weight: bold;
                color: ${Color.black()};
                background: #fff;
              }
              @media (max-width: ${mobileMaxWidth}) {
                display: none;
              }
            `}
          />

            <Suspense fallback={<Loading />}>
              <Switch>
                <Route path="/videos" component={Videos} />
                <Route path="/links" component={Links} />
                <Route path="/xp" component={Featured} />
              </Switch>
            </Suspense>

          <Notification
            className={css`
              width: 31rem;
              overflow-y: scroll;
              -webkit-overflow-scrolling: touch;
              right: 1rem;
              top: 5rem;
              bottom: 0;
              position: absolute;
              @media (max-width: ${mobileMaxWidth}) {
                display: none;
              }
            `}
            location={location.pathname.substring(1)}
          >
            {location.pathname === '/videos' && userId && (
              <>
                <Button
                  skeuomorphic
                  color="darkerGray"
                  style={{
                    fontSize: '2rem',
                    width: '99%',
                    marginTop: '0.1rem',
                    marginBottom: '1rem'
                  }}
                  onClick={openAddVideoModal}
                >
                  + Add Video
                </Button>
                <Button
                  skeuomorphic
                  color="darkerGray"
                  style={{
                    fontSize: '2rem',
                    width: '99%',
                    marginBottom: '1rem'
                  }}
                  onClick={openAddPlaylistModal}
                >
                  + Add Playlist
                </Button>
              </>
            )}
          </Notification>

 a {
              color: ${Color.gray()};
              &:hover {
                color: ${Color.gray()};
              }
            }
            > a.active {
              color: ${Color.black()};
              &:hover {
                color: ${Color.black()};
              }
            }
            @media (max-width: ${mobileMaxWidth}) {
              display: flex;
              z-index: 5;
              position: fixed;
              bottom: 9rem;
              justify-content: space-around;
              align-items: center;
              font-size: 3rem;
              width: 100%;
              height: 5rem;
              background: #fff;
            }
          `}
        >
          <NavLink to="/xp" activeClassName="active">
            <Icon icon="bolt" />
          </NavLink>
          <NavLink to="/videos" activeClassName="active">
            <Icon icon="film" />
          </NavLink>
          <NavLink to="/links" activeClassName="active">
            <Icon icon="book" />
          </NavLink>

    </ErrorBoundary>
  );
}

export default connect(
  state => ({
    userId: state.UserReducer.userId,
    mobileNavbarShown: state.ViewReducer.mobileNavbarShown
  }),
  { openAddPlaylistModal, openAddVideoModal }
)(WorkSection);
<|endoftext|>


<commit_before>function (c, a) {
    var _ = (e, p) => {
            e.forEach(p)
        }, // loop utility method
        r = a.t.call({}), // first call to get method names
        k = /d with ([a-z]+):/.exec(r)[1], // extract command key
        j = /y with [a-z]+:"([a-z]+)"/.exec(r)[1], // extract special command
        o = / "([a-z_]*)"/g, // extract commands
        n = a.c, // list of commands
        p = /y ([a-zA-Z_]*) an/, // password regex
        v, // password
        x = [], // project names
        b = [], // results
        q = {},
        z = [/ject ([a-za-z_.]*) /, /e for ([a-z_0-9.]+)\. /, /on ([a-z()0-9_]+) pr/] // project name patterns
    /*
    while(c = o.exec(r)) {
    	n.push(c[1])
    }
    */
    _(n, c => { // for each command
        q[k] = c
        r = a.t.call(q) // run the script

        if ((typeof r)[0] != "s") // if we get an array parse the individual items for projects
            _(r, q => {
                _(z, z => {
                    o = z.exec(q)
                    if (o) x.push(o[1])
                })
            })
        else { // if we get a single item parse it for passwords
            o = p.exec(r)
            if (o) v = o[1]
        }
    })

    _(x, h => { // for each project
        p = {
            project: h,
            password: v,
            pass: v,
            p: v
        }
        p[k] = j
        r = a.t.call(p) // call the script to get the npc locs
        b.push(r)
        /*
        _(r, g => { // for each npc loc push it in the results array
        	b.push(g)
        })
        */
    })

    return n
}<commit_msg>rework harvest to account for game changes<commit_after>function (c, a)
{
	var _ = (c, p) => { c.forEach(p) }, // loop utility method
        u = a.t.call(),
		r = a.t.call({}), // first call to get method names
        d = /y with ([a-z]+):"([a-z]+)"/.exec(r),
		k = d[1], // extract command key
		j = d[2], // extract special command
        o = /([a-z_]*) \|/g,
		n = [o.exec(u)[1],o.exec(u)[1]], // list of commands
		p = /y ([a-zA-Z_]*) an/, // password regex
		v, // password
		x = [], // project names
		b = [], // results
		q = {},
		z = [/ject ([a-zA-Z_.]*) /, /e for ([a-z_0-9.]+)\. /, /on ([a-z()0-9_]+) pr/] // project name patterns

	_(n, c => { // for each command
		q[k] = c
		r = a.t.call(q) // run the script

		if((typeof r)[0]!="s") // if we get an array parse the individual items for projects
			_(r, q => {
				_(z, z => {
					o = z.exec(q)
					if(o) x.push(o[1])
				})
			})
		else { // if we get a single item parse it for passwords
			o = p.exec(r)
			if(o) v = o[1]
		}
	})

	_(x, h => { // for each project
		p = {project: h, password: v, pass: v, p: v}
		p[k] = j
		r = a.t.call(p) // call the script to get the npc locs
        if((typeof r)[0]!="s")
            b.push(r)
        /*
		_(r, g => { // for each npc loc push it in the results array
			b.push(g)
		})
        */
	})

	return b
}<|endoftext|>


<commit_before>/* global ares */
enyo.kind({
	name: "Ares.ErrorPopup",
	kind: "onyx.Popup",
	modal: true,
	centered: true,
	floating: true,
	autoDismiss: false,
	published: {
		title: $L("Error"),
		errorMsg: $L("unknown error"),
		actionMsg: undefined,
		detailsHtml: "",
		detailsText: "",
		callback: null,
		okButton: $L("Close")
	},
	classes: "ares-classic-popup",
	components: [
	    {tag: "div", name: "title", classes: "title"},
			{classes:"ares-error-popup", fit: true, components: [
				{name: "msg"},
				{name: "action", showing: false},
				{classes: "ares-error-details", components: [
					{classes: "button", components: [
						{tag: "label", classes:" label", name: "detailsBtn", content: $L("Details"), ontap: "toggleDetails", showing: false},
						{name: "detailsArrow", classes: "optionDownArrow", ontap: "toggleDetails", showing: false},
						{name: "detailsDrw", kind: "onyx.Drawer", open: false, showing: false, classes: "ares-error-drawer", components: [
							{name: "detailsText", kind: "onyx.TextArea", disabled: true, fit: true, classes: "ares-error-text"},
							{name: "detailsHtml", allowHtml: true, fit: true}
						]}
					]}
				]}
			]},
			{kind: "onyx.Toolbar", name: "bottomToolbar",  classes: "bottom-toolbar", components: [
				{name: "okButton", kind: "onyx.Button", ontap: "hideErrorPopup"}
			]}
	],
	create: function() {
		ares.setupTraceLogger(this);
		this.inherited(arguments);
		this.titleChanged();
		this.errorMsgChanged();
		this.detailsHtmlChanged();
		this.detailsTextChanged();
		this.okButtonChanged();
	},
	titleChanged: function (oldVal) {
		this.trace(oldVal, "->", this.title);
		this.$.title.setContent(this.title);
	},
	errorMsgChanged: function (oldVal) {
		this.trace(oldVal, "->", this.errorMsg);
		this.$.msg.setContent(this.errorMsg);
	},
	detailsTextChanged: function() {
		this.updateDetailsDrw();
	},
	detailsHtmlChanged: function() {
		this.updateDetailsDrw();
	},
	actionMsgChanged: function() {
		if (this.actionMsg) {
			this.$.action.setContent(this.actionMsg);
			this.$.action.setShowing(true);
		} else {
			this.$.action.setShowing(false);
		}
	},
	updateDetailsDrw: function() {
		if (this.detailsText || this.detailsHtml) {
			this.$.detailsBtn.show();
			this.$.detailsArrow.show();
			this.$.detailsDrw.show();
			this.$.detailsDrw.setOpen(true);
			if (this.detailsHtml) {
				this.$.detailsHtml.setContent(this.detailsHtml);
				this.$.detailsHtml.show();
				this.$.detailsText.hide();
			} else {
				this.$.detailsText.setValue(this.detailsText);
				this.$.detailsText.show();
				this.$.detailsHtml.hide();
			}
		} else {
			this.$.detailsBtn.hide();
			this.$.detailsArrow.hide();
			this.$.detailsDrw.hide();
			this.$.detailsText.setValue("");
			this.$.detailsHtml.setContent("");
		}
	},
	okButtonChanged: function(oldVal) {
		this.trace(oldVal, "->", this.okButton);
		this.$.okButton.setContent(this.okButton);
	},
	toggleDetails: function() {
		this.$.detailsDrw.setOpen(!this.$.detailsDrw.open);
	},
	hideErrorPopup: function() {
		this.reset();
		this.hide();
		if (this.callback) {
			var cb = this.callback;
			this.callback = null;
			try {
				cb();
			} catch(error) {
				var errMsg = "An unexpected exception occured in callback:" + ( typeof error === 'object' ? error.message : error );
				var errStack = typeof error === 'object' ? error.stack : '' ;
				this.error(errMsg, errStack );
				this.raise({msg: errMsg, err: {stack: errStack}});
			}
		}
	},
	raise: function(evt) {
		var msg, err, text, html;

		if (evt.callback) {
			if (this.callback) {
				this.error("Previous callback was not fired ! Bug?");
			}
			this.callback = evt.callback;
		}
		if (typeof evt === 'object') {
			if (evt instanceof Error) {
				err = evt;
				msg = err.toString();
			} else {
				err = evt.err;
				msg = evt.msg || (err && err.toString());

				if(evt.title !== undefined) {
					this.$.title.setContent(evt.title);
				}
			}
		} else {
			msg = evt.toString();
		}
		text = err && (err.text || err.stack);
		html = err && err.html;
		text = !html && text;
		this.setErrorMsg(msg);
		this.setDetailsHtml(html);
		this.setDetailsText(text);
		this.setActionMsg(evt.action);
		this.show();
	},
	reset: function() {
		this.set("title", $L("error"));
		this.set("errorMsg", $L("unknown error"));
		this.set("actionMsg", undefined);
		this.set("detailsHtml", "");
		this.set("detailsTxt", "");
		this.set("okButton", $L("Close"));
	}
});
<commit_msg>ENYO-3182: Better manage auto-dismiss of Ares.ErrorPopup<commit_after>/* global ares */
enyo.kind({
	name: "Ares.ErrorPopup",
	kind: "onyx.Popup",
	modal: true,
	centered: true,
	floating: true,
	autoDismiss: true,
	published: {
		title: $L("Error"),
		errorMsg: $L("unknown error"),
		actionMsg: undefined,
		detailsHtml: "",
		detailsText: "",
		callback: null,
		okButton: $L("Close")
	},
	classes: "ares-classic-popup",
	components: [
	    {tag: "div", name: "title", classes: "title"},
			{classes:"ares-error-popup", fit: true, components: [
				{name: "msg"},
				{name: "action", showing: false},
				{classes: "ares-error-details", components: [
					{classes: "button", components: [
						{tag: "label", classes:" label", name: "detailsBtn", content: $L("Details"), ontap: "toggleDetails", showing: false},
						{name: "detailsArrow", classes: "optionDownArrow", ontap: "toggleDetails", showing: false},
						{name: "detailsDrw", kind: "onyx.Drawer", open: false, showing: false, classes: "ares-error-drawer", components: [
							{name: "detailsText", kind: "onyx.TextArea", disabled: true, fit: true, classes: "ares-error-text"},
							{name: "detailsHtml", allowHtml: true, fit: true}
						]}
					]}
				]}
			]},
			{kind: "onyx.Toolbar", name: "bottomToolbar",  classes: "bottom-toolbar", components: [
				{name: "okButton", kind: "onyx.Button", ontap: "hideErrorPopup"}
			]}
	],
	create: function() {
		ares.setupTraceLogger(this);
		this.inherited(arguments);
		this.titleChanged();
		this.errorMsgChanged();
		this.detailsHtmlChanged();
		this.detailsTextChanged();
		this.okButtonChanged();
	},
	titleChanged: function (oldVal) {
		this.trace(oldVal, "->", this.title);
		this.$.title.setContent(this.title);
	},
	errorMsgChanged: function (oldVal) {
		this.trace(oldVal, "->", this.errorMsg);
		this.$.msg.setContent(this.errorMsg);
	},
	detailsTextChanged: function() {
		this.updateDetailsDrw();
	},
	detailsHtmlChanged: function() {
		this.updateDetailsDrw();
	},
	actionMsgChanged: function() {
		if (this.actionMsg) {
			this.$.action.setContent(this.actionMsg);
			this.$.action.setShowing(true);
		} else {
			this.$.action.setShowing(false);
		}
	},
	updateDetailsDrw: function() {
		if (this.detailsText || this.detailsHtml) {
			this.$.detailsBtn.show();
			this.$.detailsArrow.show();
			this.$.detailsDrw.show();
			this.$.detailsDrw.setOpen(true);
			if (this.detailsHtml) {
				this.$.detailsHtml.setContent(this.detailsHtml);
				this.$.detailsHtml.show();
				this.$.detailsText.hide();
			} else {
				this.$.detailsText.setValue(this.detailsText);
				this.$.detailsText.show();
				this.$.detailsHtml.hide();
			}
		} else {
			this.$.detailsBtn.hide();
			this.$.detailsArrow.hide();
			this.$.detailsDrw.hide();
			this.$.detailsText.setValue("");
			this.$.detailsHtml.setContent("");
		}
	},
	okButtonChanged: function(oldVal) {
		this.trace(oldVal, "->", this.okButton);
		this.$.okButton.setContent(this.okButton);
	},
	toggleDetails: function() {
		this.$.detailsDrw.setOpen(!this.$.detailsDrw.open);
	},
	hideErrorPopup: function() {
		this.reset();
		this.hide();
		if (this.callback) {
			var cb = this.callback;
			this.callback = null;
			try {
				cb();
			} catch(error) {
				var errMsg = "An unexpected exception occured in callback:" + ( typeof error === 'object' ? error.message : error );
				var errStack = typeof error === 'object' ? error.stack : '' ;
				this.error(errMsg, errStack );
				this.raise({msg: errMsg, err: {stack: errStack}});
			}
		}
	},
	raise: function(evt) {
		var msg, err, text, html;

		if (evt.callback) {
			if (this.callback) {
				this.error("Previous callback was not fired ! Bug?");
			}
			this.callback = evt.callback;
			this.setAutoDismiss(false);
		} else {
			this.setAutoDismiss(true);
		}

		if (typeof evt === 'object') {
			if (evt instanceof Error) {
				err = evt;
				msg = err.toString();
			} else {
				err = evt.err;
				msg = evt.msg || (err && err.toString());

				if(evt.title !== undefined) {
					this.$.title.setContent(evt.title);
				}
			}
		} else {
			msg = evt.toString();
		}
		text = err && (err.text || err.stack);
		html = err && err.html;
		text = !html && text;
		this.setErrorMsg(msg);
		this.setDetailsHtml(html);
		this.setDetailsText(text);
		this.setActionMsg(evt.action);
		this.show();
	},
	reset: function() {
		this.set("title", $L("error"));
		this.set("errorMsg", $L("unknown error"));
		this.set("actionMsg", undefined);
		this.set("detailsHtml", "");
		this.set("detailsTxt", "");
		this.set("okButton", $L("Close"));
	}
});
<|endoftext|>


<commit_before>"use strict";

const path = require("path");
const Conf = require("./conf");
const defaults = require("./defaults");
const toNerfDart = require("./nerf-dart");

module.exports = npmConf;
module.exports.Conf = Conf;
module.exports.defaults = Object.assign({}, defaults.defaults);
module.exports.toNerfDart = toNerfDart;

// https://github.com/npm/npm/blob/latest/lib/config/core.js#L101-L200
function npmConf(opts) {
  const conf = new Conf(Object.assign({}, defaults.defaults));

  // prevent keys with undefined values from obscuring defaults
  const cleanOpts = opts
    ? Object.keys(opts).reduce((acc, key) => {
        if (opts && opts[key] !== undefined) {
          // eslint-disable-next-line no-param-reassign
          acc[key] = opts[key];
        }

        return acc;
      }, {})
    : {};

  conf.add(cleanOpts, "cli");
  conf.addEnv();
  conf.loadPrefix();

  const projectConf = path.resolve(conf.localPrefix, ".npmrc");
  const userConf = conf.get("userconfig");

  if (!conf.get("global") && projectConf !== userConf) {
    conf.addFile(projectConf, "project");
  } else {
    conf.add({}, "project");
  }

  conf.addFile(conf.get("userconfig"), "user");

  if (conf.get("prefix")) {
    const etc = path.resolve(conf.get("prefix"), "etc");
    conf.root.globalconfig = path.resolve(etc, "npmrc");
    conf.root.globalignorefile = path.resolve(etc, "npmignore");
  }

  conf.addFile(conf.get("globalconfig"), "global");
  conf.loadUser();

  const caFile = conf.get("cafile");

  if (caFile) {
    conf.loadCAFile(caFile);
  }

  return conf;
}
<commit_msg>refactor(npm-conf): remove redundant check, add istanbul comments<commit_after>"use strict";

const path = require("path");
const Conf = require("./conf");
const defaults = require("./defaults");
const toNerfDart = require("./nerf-dart");

module.exports = npmConf;
module.exports.Conf = Conf;
module.exports.defaults = Object.assign({}, defaults.defaults);
module.exports.toNerfDart = toNerfDart;

// https://github.com/npm/npm/blob/latest/lib/config/core.js#L101-L200
function npmConf(opts) {
  const conf = new Conf(Object.assign({}, defaults.defaults));

  // prevent keys with undefined values from obscuring defaults
  const cleanOpts = opts
    ? Object.keys(opts).reduce((acc, key) => {
        if (opts[key] !== undefined) {
          // eslint-disable-next-line no-param-reassign
          acc[key] = opts[key];
        }

        return acc;
      }, {})
    : {};

  conf.add(cleanOpts, "cli");
  conf.addEnv();
  conf.loadPrefix();

  const projectConf = path.resolve(conf.localPrefix, ".npmrc");
  const userConf = conf.get("userconfig");

  /* istanbul ignore else */
  if (!conf.get("global") && projectConf !== userConf) {
    conf.addFile(projectConf, "project");
  } else {
    conf.add({}, "project");
  }

  conf.addFile(conf.get("userconfig"), "user");

  /* istanbul ignore else */
  if (conf.get("prefix")) {
    const etc = path.resolve(conf.get("prefix"), "etc");
    conf.root.globalconfig = path.resolve(etc, "npmrc");
    conf.root.globalignorefile = path.resolve(etc, "npmignore");
  }

  conf.addFile(conf.get("globalconfig"), "global");
  conf.loadUser();

  const caFile = conf.get("cafile");

  /* istanbul ignore if */
  if (caFile) {
    conf.loadCAFile(caFile);
  }

  return conf;
}
<|endoftext|>


<commit_before>const winston = require('winston');

const isProductionMode = process.env.NODE_ENV === 'production';
let format;

if (isProductionMode) {
	format = winston.format.combine(
		winston.format.colorize(),
		winston.format.simple(),
	);
} else {
	format = winston.format.simple();
}

const logger = winston.createLogger({
	transports: [
		new winston.transports.Console({
			format,
		}),
	],
});

module.exports = logger;
<commit_msg>invert condition<commit_after>const winston = require('winston');

const isProductionMode = process.env.NODE_ENV === 'production';
let format;

if (!isProductionMode) {
	format = winston.format.combine(
		winston.format.colorize(),
		winston.format.simple(),
	);
} else {
	format = winston.format.simple();
}

const logger = winston.createLogger({
	transports: [
		new winston.transports.Console({
			format,
		}),
	],
});

module.exports = logger;
<|endoftext|>


<commit_before><commit_msg>flanker_single_task_network - changed condition to flanker_condition to match other flanker tasks data output<commit_after><|endoftext|>


<commit_before>var DisneyRequest = require("./disneyRequest");
var moment = require("moment-timezone");

/** Class to hold park-specific API calls for ease of access
 * Setup with a park ID and a DisneyRequest object
 * eg. new DisneyPark("80007944", new DisneyRequest());
 */
function DisneyPark(options, DRequest)
{

    var config = {
        wdw_park_id: null,
        // default timezone (Florida time)
        timezone: "America/New_York",
        // time format to return dates in (see momentjs doc http://momentjs.com/docs/#/displaying/format/)
        //  default is ISO8601 format YYYY-MM-DDTHH:mm:ssZ
        timeFormat: "YYYY-MM-DDTHH:mm:ssZ",
        // format for printing days
        dateFormat: "YYYY-MM-DD"
    };

    this.TakeOptions = function(options)
    {
        // overwrite config with supplied options if they exist
        if (options)
        {
            for(var key in options)
            {
                config[key] = options[key];
            }
        }
    };
    this.TakeOptions(options);

    /** ===== Exports ===== */

    /** Get park waiting times for rides */
    this.GetWaitTimes = function(include_entertainment)
    {
        // callback is the last argument sent to the function
        var cb = arguments[ arguments.length - 1 ];

        // include_entertainment defaults to false
        if (typeof include_entertainment == "function") include_entertainment = false;

        // fetch wait times from the API
        DRequest.GetPage(config.wdw_park_id, "theme-park", "wait-times", function(err, data) {
            if (err) return cb(err);

            // build ride array
            var rides = [];
            for(var i=0; i<data.entries.length; i++)
            {
                var ride = data.entries[i];

                if (ride.id && ride.name && ride.type && ride.type == "Attraction")
                {
                    // skip non attraction rides if we've not been told to include them
                    if (!include_entertainment)
                    {
                        if (ride.type != "Attraction") continue;
                    }

                    var obj = {
                        id: ride.id,
                        name: ride.name
                    };

                    // try to find wait time value
                    if (ride.waitTime && ride.waitTime && ride.waitTime.postedWaitMinutes)
                    {
                        // report the posted wait time if present
                        obj.waitTime = ride.waitTIme.postedWaitMinutes;
                    }
                    else
                    {
                        // zero if we cannot find a wait time
                        obj.waitTime = 0;
                    }

                    // work out if the ride is active
                    obj.active = (ride.waitTime && ride.waitTime.status == "Operating") ? true : false;

                    // work out if we have fastpass
                    obj.fastPass = (ride.waitTime.fastPass && ride.waitTime.fastPass.available);

                    // add to our return rides array
                    rides.push(obj);
                }
            }

            // return rides
            cb(null, rides);
        });
    };

    /** Get park opening hours */
    this.GetSchedule = function(cb)
    {
        // TODO - format this data nicely
        DRequest.GetPage(config.wdw_park_id, "schedule", function(err, data) {
            if (err) return cb(err);

            var times = [];
            // parse data into a nice format
            for(var i=0; i<data.schedules.length; i++)
            {
                var o = {
                    // format date as well as times
                    date: moment(data.schedules[i].date).format(config.dateFormat),
                    // format time to the timezone properly using momentjs
                    openingTime: ParseTime(data.schedules[i].date + data.schedules[i].startTime),
                    // add an extra day if the closing time is past midnight
                    closingTime: ParseTime(data.schedules[i].date + data.schedules[i].endTime, (data.schedules[i].endTime[0] == "0") ? 1 : 0),
                    // type, can be "Operating", "Extra Magic Hours" or "Special Ticketed Event"
                    //  consider only using "Operating" or have special UI to handle any type of park hours
                    type: data.schedules[i].type
                };

                times.push(o);
            }

            return cb(null, times);
        });
    };

    // format of wdw API times
    var wdwTimeFormat = "YYYY-MM-DDHH:mm";
    function ParseTime(time, add_days)
    {
        var parsedTime = moment.tz(time, wdwTimeFormat, config.timezone);

        if (add_days)
        {
            parsedTime.add(add_days, "days");
        }

        return parsedTime.format(config.timeFormat);
    }

    /** ===== Variables ===== */

    // make sure we have a request object if it wasn't supplied
    if (!DRequest) DRequest = new DisneyRequest();
}

// export this module
module.exports = DisneyPark;
<commit_msg>FIS Tyop no waititmes<commit_after>var DisneyRequest = require("./disneyRequest");
var moment = require("moment-timezone");

/** Class to hold park-specific API calls for ease of access
 * Setup with a park ID and a DisneyRequest object
 * eg. new DisneyPark("80007944", new DisneyRequest());
 */
function DisneyPark(options, DRequest)
{

    var config = {
        wdw_park_id: null,
        // default timezone (Florida time)
        timezone: "America/New_York",
        // time format to return dates in (see momentjs doc http://momentjs.com/docs/#/displaying/format/)
        //  default is ISO8601 format YYYY-MM-DDTHH:mm:ssZ
        timeFormat: "YYYY-MM-DDTHH:mm:ssZ",
        // format for printing days
        dateFormat: "YYYY-MM-DD"
    };

    this.TakeOptions = function(options)
    {
        // overwrite config with supplied options if they exist
        if (options)
        {
            for(var key in options)
            {
                config[key] = options[key];
            }
        }
    };
    this.TakeOptions(options);

    /** ===== Exports ===== */

    /** Get park waiting times for rides */
    this.GetWaitTimes = function(include_entertainment)
    {
        // callback is the last argument sent to the function
        var cb = arguments[ arguments.length - 1 ];

        // include_entertainment defaults to false
        if (typeof include_entertainment == "function") include_entertainment = false;

        // fetch wait times from the API
        DRequest.GetPage(config.wdw_park_id, "theme-park", "wait-times", function(err, data) {
            if (err) return cb(err);

            // build ride array
            var rides = [];
            for(var i=0; i<data.entries.length; i++)
            {
                var ride = data.entries[i];

                if (ride.id && ride.name && ride.type && ride.type == "Attraction")
                {
                    // skip non attraction rides if we've not been told to include them
                    if (!include_entertainment)
                    {
                        if (ride.type != "Attraction") continue;
                    }

                    var obj = {
                        id: ride.id,
                        name: ride.name
                    };

                    // try to find wait time value
                    if (ride.waitTime && ride.waitTime && ride.waitTime.postedWaitMinutes)
                    {
                        // report the posted wait time if present
                        obj.waitTime = ride.waitTime.postedWaitMinutes;
                    }
                    else
                    {
                        // zero if we cannot find a wait time
                        obj.waitTime = 0;
                    }

                    // work out if the ride is active
                    obj.active = (ride.waitTime && ride.waitTime.status == "Operating") ? true : false;

                    // work out if we have fastpass
                    obj.fastPass = (ride.waitTime.fastPass && ride.waitTime.fastPass.available);

                    // add to our return rides array
                    rides.push(obj);
                }
            }

            // return rides
            cb(null, rides);
        });
    };

    /** Get park opening hours */
    this.GetSchedule = function(cb)
    {
        // TODO - format this data nicely
        DRequest.GetPage(config.wdw_park_id, "schedule", function(err, data) {
            if (err) return cb(err);

            var times = [];
            // parse data into a nice format
            for(var i=0; i<data.schedules.length; i++)
            {
                var o = {
                    // format date as well as times
                    date: moment(data.schedules[i].date).format(config.dateFormat),
                    // format time to the timezone properly using momentjs
                    openingTime: ParseTime(data.schedules[i].date + data.schedules[i].startTime),
                    // add an extra day if the closing time is past midnight
                    closingTime: ParseTime(data.schedules[i].date + data.schedules[i].endTime, (data.schedules[i].endTime[0] == "0") ? 1 : 0),
                    // type, can be "Operating", "Extra Magic Hours" or "Special Ticketed Event"
                    //  consider only using "Operating" or have special UI to handle any type of park hours
                    type: data.schedules[i].type
                };

                times.push(o);
            }

            return cb(null, times);
        });
    };

    // format of wdw API times
    var wdwTimeFormat = "YYYY-MM-DDHH:mm";
    function ParseTime(time, add_days)
    {
        var parsedTime = moment.tz(time, wdwTimeFormat, config.timezone);

        if (add_days)
        {
            parsedTime.add(add_days, "days");
        }

        return parsedTime.format(config.timeFormat);
    }

    /** ===== Variables ===== */

    // make sure we have a request object if it wasn't supplied
    if (!DRequest) DRequest = new DisneyRequest();
}

// export this module
module.exports = DisneyPark;
<|endoftext|>