<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */
goog.require('devtools.InspectorController');

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  devtools.InspectorController.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('copyNode');
  this.installInspectorControllerDelegate_('deleteCookie');
  this.installInspectorControllerDelegate_('disableResourceTracking');
  this.installInspectorControllerDelegate_('disableTimeline');
  this.installInspectorControllerDelegate_('enableResourceTracking');
  this.installInspectorControllerDelegate_('enableTimeline');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('getCookies');
  this.installInspectorControllerDelegate_('getDatabaseTableNames');
  this.installInspectorControllerDelegate_('getDOMStorageEntries');
  this.installInspectorControllerDelegate_('getEventListenersForNode');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('releaseWrapperObjectGroup');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('setDOMStorageItem');
  this.installInspectorControllerDelegate_('setSetting');
  this.installInspectorControllerDelegate_('setTextNodeValue');
  this.installInspectorControllerDelegate_('setting');
  this.installInspectorControllerDelegate_('startTimelineProfiler');
  this.installInspectorControllerDelegate_('stopTimelineProfiler');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
};
goog.inherits(devtools.InspectorControllerImpl,
    devtools.InspectorController);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return DevToolsHost.hiddenPanels();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  devtools.InspectorController.prototype.toggleNodeSearch.call(this);
  this.callInspectorController_.call(this, 'toggleNodeSearch');
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.localizedStringsURL =
    function(opt_prefix) {
  // l10n is turned off in test mode because delayed loading of strings
  // causes test failures.
  if (false) {
    var locale = DevToolsHost.getApplicationLocale();
    locale = locale.replace('_', '-');
    return 'l10n/localizedStrings_' + locale + '.js';
  } else {
    return undefined;
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }

  // Temporary fix for http://crbug/23260.
  var mimeType = resource.mimeType;
  if (!mimeType && resource.url) {
    if (resource.url.search('\.js$') != -1) {
      mimeType = 'application/x-javascript';
    } else if (resource.url.search('\.html$') != -1) {
      mimeType = 'text/html';
    }
  }

  DevToolsHost.addResourceSourceToFrame(identifier, mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.updateBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().updateBreakpoint(
      sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfileHeaders = function(callId) {
  WebInspector.didGetProfileHeaders(callId, []);
};

/**
 * Emulate WebKit InspectorController behavior. It stores profiles on renderer side,
 * and is able to retrieve them by uid using 'getProfile'.
 */
devtools.InspectorControllerImpl.prototype.addFullProfile = function(profile) {
  WebInspector.__fullProfiles = WebInspector.__fullProfiles || {};
  WebInspector.__fullProfiles[profile.uid] = profile;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfile = function(callId, uid) {
  if (WebInspector.__fullProfiles && (uid in WebInspector.__fullProfiles)) {
    WebInspector.didGetProfile(callId, WebInspector.__fullProfiles[uid]);
  }
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.takeHeapSnapshot = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_SNAPSHOT
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_STATS
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_JS_CONSTRUCTORS);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.dispatchOnInjectedScript = function(
    callId, methodName, argsString, async) {
  var callback = function(result, isException) {
    WebInspector.didDispatchOnInjectedScript(callId, result, isException);
  };
  RemoteToolsAgent.DispatchOnInjectedScript(
      WebInspector.Callback.wrap(callback),
      async ? methodName + "_async" : methodName,
      argsString);
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments, 1);
  RemoteToolsAgent.DispatchOnInspectorController(
      WebInspector.Callback.wrap(function(){}),
      methodName,
      JSON.stringify(args));
};

InspectorController = new devtools.InspectorControllerImpl();
<commit_msg>Focus DevTools window on inspected node selection with magnifier<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */
goog.require('devtools.InspectorController');

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  devtools.InspectorController.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('copyNode');
  this.installInspectorControllerDelegate_('deleteCookie');
  this.installInspectorControllerDelegate_('disableResourceTracking');
  this.installInspectorControllerDelegate_('disableTimeline');
  this.installInspectorControllerDelegate_('enableResourceTracking');
  this.installInspectorControllerDelegate_('enableTimeline');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('getCookies');
  this.installInspectorControllerDelegate_('getDatabaseTableNames');
  this.installInspectorControllerDelegate_('getDOMStorageEntries');
  this.installInspectorControllerDelegate_('getEventListenersForNode');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('releaseWrapperObjectGroup');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('setDOMStorageItem');
  this.installInspectorControllerDelegate_('setSetting');
  this.installInspectorControllerDelegate_('setTextNodeValue');
  this.installInspectorControllerDelegate_('setting');
  this.installInspectorControllerDelegate_('startTimelineProfiler');
  this.installInspectorControllerDelegate_('stopTimelineProfiler');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
};
goog.inherits(devtools.InspectorControllerImpl,
    devtools.InspectorController);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return DevToolsHost.hiddenPanels();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  devtools.InspectorController.prototype.toggleNodeSearch.call(this);
  this.callInspectorController_.call(this, 'toggleNodeSearch');
  if (!this.searchingForNode()) {
    // This is called from ElementsPanel treeOutline's focusNodeChanged().
    DevToolsHost.activateWindow();
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.localizedStringsURL =
    function(opt_prefix) {
  // l10n is turned off in test mode because delayed loading of strings
  // causes test failures.
  if (false) {
    var locale = DevToolsHost.getApplicationLocale();
    locale = locale.replace('_', '-');
    return 'l10n/localizedStrings_' + locale + '.js';
  } else {
    return undefined;
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }

  // Temporary fix for http://crbug/23260.
  var mimeType = resource.mimeType;
  if (!mimeType && resource.url) {
    if (resource.url.search('\.js$') != -1) {
      mimeType = 'application/x-javascript';
    } else if (resource.url.search('\.html$') != -1) {
      mimeType = 'text/html';
    }
  }

  DevToolsHost.addResourceSourceToFrame(identifier, mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.updateBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().updateBreakpoint(
      sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfileHeaders = function(callId) {
  WebInspector.didGetProfileHeaders(callId, []);
};

/**
 * Emulate WebKit InspectorController behavior. It stores profiles on renderer side,
 * and is able to retrieve them by uid using 'getProfile'.
 */
devtools.InspectorControllerImpl.prototype.addFullProfile = function(profile) {
  WebInspector.__fullProfiles = WebInspector.__fullProfiles || {};
  WebInspector.__fullProfiles[profile.uid] = profile;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfile = function(callId, uid) {
  if (WebInspector.__fullProfiles && (uid in WebInspector.__fullProfiles)) {
    WebInspector.didGetProfile(callId, WebInspector.__fullProfiles[uid]);
  }
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.takeHeapSnapshot = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_SNAPSHOT
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_STATS
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_JS_CONSTRUCTORS);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.dispatchOnInjectedScript = function(
    callId, methodName, argsString, async) {
  var callback = function(result, isException) {
    WebInspector.didDispatchOnInjectedScript(callId, result, isException);
  };
  RemoteToolsAgent.DispatchOnInjectedScript(
      WebInspector.Callback.wrap(callback),
      async ? methodName + "_async" : methodName,
      argsString);
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments, 1);
  RemoteToolsAgent.DispatchOnInspectorController(
      WebInspector.Callback.wrap(function(){}),
      methodName,
      JSON.stringify(args));
};

InspectorController = new devtools.InspectorControllerImpl();
<|endoftext|>


<commit_before>w.optly.mrkt.utils.trimMixpanelCookie = function trimMixpanelCookie(){
  //method to check for and unregister any archived experiments previously registered as super properties.
  //First, get a list of all active and paused experiments (should not include archived or deleted experiments)
  var allExperiments = w['optimizely'].data.experiments,
    allExperimentNames = [],
    cookieIsDefined;

  $.each(allExperiments, function(id, exp) {
    allExperimentNames.push(exp.name);
  });

  //Next, check the Mixpanel cookie for any Experiment super properties not in the list of active and paused experiments and unregister them if found
  if(typeof w.mixpanel === 'object' && w.mixpanel !== undefined) {
    cookieIsDefined = typeof (w.mixpanel.cookie && w.mixpanel.cookie.props) === 'object';

    //iterate over mixpanel cookie props object
    if(cookieIsDefined) {
      $.each(w.mixpanel.cookie.props, function(propKey, prop) {
        var propStr;
        if ( /Experiment\:/.test( propKey ) ) {
          propStr = propKey.substr( propKey.indexOf(':')  + 1 );

          if ( allExperimentNames.indexOf( propStr ) === -1) {
            mixpanel.unregister(propKey);
          }
        }
      });
    }
  }

};

<commit_msg>add fallback for optimizely array in mixpanel function<commit_after>w.optly.mrkt.utils.trimMixpanelCookie = function trimMixpanelCookie(){
  //method to check for and unregister any archived experiments previously registered as super properties.
  //First, get a list of all active and paused experiments (should not include archived or deleted experiments)
  var allExperiments = w['optimizely'].data.experiments || [],
    allExperimentNames = [],
    cookieIsDefined;

  $.each(allExperiments, function(id, exp) {
    allExperimentNames.push(exp.name);
  });

  //Next, check the Mixpanel cookie for any Experiment super properties not in the list of active and paused experiments and unregister them if found
  if(typeof w.mixpanel === 'object' && w.mixpanel !== undefined) {
    cookieIsDefined = typeof (w.mixpanel.cookie && w.mixpanel.cookie.props) === 'object';

    //iterate over mixpanel cookie props object
    if(cookieIsDefined) {
      $.each(w.mixpanel.cookie.props, function(propKey, prop) {
        var propStr;
        if ( /Experiment\:/.test( propKey ) ) {
          propStr = propKey.substr( propKey.indexOf(':')  + 1 );

          if ( allExperimentNames.indexOf( propStr ) === -1) {
            mixpanel.unregister(propKey);
          }
        }
      });
    }
  }

};

<|endoftext|>


<commit_before>var Backbone = require("lib").Backbone;
var _ = require("lib")._;

var UserModel = Backbone.Model.extend({

    defaults: {
        isAnonymous: true
    },

    url: function() {
        return "/api/v1/user/"
    },

    isAuthenticated: function() {
        return !this.attributes.isAnonymous;
    },

    logout: function() {
        this.url = "/api/v1/user/logout/";
        return this.save();
    }
});

var StreamSaveModel = Backbone.Model.extend({

    MAX_REQUESTS_PER_SECOND: 1,

    initialize: function() {

        //this._triggerIsSavedChanged = _.debounce(this._triggerIsSavedChanged, 1000, {immedate: false});

        this._lastRequestId = 0;
        this._lastSavedRequestId = 0;
        this._isSaved = true;

        this._saveImpl = _.throttle(this._saveImpl, 1000 / this.MAX_REQUESTS_PER_SECOND);
    },

    save: function() {

        if(this.isSaved()) {
            console.info("saving", this._lastRequestId);
            this._lastRequestId += 1;
            this._saveImpl();
        }
        else {
            console.info("inc requestId, don't save now");
            this._lastRequestId += 1;
        }
        this._updateIsSaved();

    },

    _saveImpl: function() {

        var requestId = this._lastRequestId;
        var self = this;
        var callback = function() {
            console.info("Saved: ", requestId);
            self._lastSavedRequestId = requestId;
            self._updateIsSaved();
            if(!self.isSaved()) {
                console.info("saving ", self._lastRequestId);
                self._saveImpl();
            }
        };
        Backbone.Model.prototype.save.apply(this, arguments).then(callback);
    },

    isSaved: function() {
        return this._lastSavedRequestId == this._lastRequestId;
    },

    _updateIsSaved: function() {
        var previousStatus, currentStatus;
        previousStatus = this._isSaved;
        currentStatus = this.isSaved();
        this._isSaved = currentStatus;

        if(previousStatus !== currentStatus) {
            this._triggerIsSavedChanged();
        }
    },

    _triggerIsSavedChanged: function() {
        console.info("isSaved changed", this._isSaved);
        this.trigger("change:isSaved", this._isSaved);
    }
});

MAX_RETRIES = 2;
BACKOFF_PER_RETRY = 2000;

var originalFetch = Backbone.Model.prototype.fetch;

fetchWithRetries = function() {
    var self = this;

    if(_.isUndefined(self._retries)) {
        self._retries = 0;
        self._fetchPromise = $.Deferred();
    }

    var onError = function(model, response) {
        self._retries += 1;
        if(self._retries > MAX_RETRIES || response.status === 404) {
            var promise = self._fetchPromise;
            delete self._retries;
            delete self._fetchPromise;
            promise.reject();
            return;
        }

        //todo -> implement clearTimeout during cleanup
        setTimeout(function() {
            fetchWithRetries.call(self);
        }, self._retries * 1000);
    }
    var onSuccess = function() {
        var promise = self._fetchPromise;
        delete self._retries;
        delete self._fetchPromise;
        promise.resolve();

    }

    // Usually, I don't pass any arguments to fetch,
    // so as of now, I'm ignoring original arguments
    // todo -> Fix it.
    originalFetch.call(this, {
        success: onSuccess,
        error: onError
    });
    return self._fetchPromise;
}

Backbone.Model.prototype.fetch = Backbone.Collection.prototype.fetch = fetchWithRetries;

module.exports = {
    UserModel: UserModel,
    StreamSaveModel: StreamSaveModel
};<commit_msg>Client Retry GET Requests: Override Model.fetch and Collection.fetch separately.<commit_after>var Backbone = require("lib").Backbone;
var _ = require("lib")._;

var UserModel = Backbone.Model.extend({

    defaults: {
        isAnonymous: true
    },

    url: function() {
        return "/api/v1/user/"
    },

    isAuthenticated: function() {
        return !this.attributes.isAnonymous;
    },

    logout: function() {
        this.url = "/api/v1/user/logout/";
        return this.save();
    }
});

var StreamSaveModel = Backbone.Model.extend({

    MAX_REQUESTS_PER_SECOND: 1,

    initialize: function() {

        //this._triggerIsSavedChanged = _.debounce(this._triggerIsSavedChanged, 1000, {immedate: false});

        this._lastRequestId = 0;
        this._lastSavedRequestId = 0;
        this._isSaved = true;

        this._saveImpl = _.throttle(this._saveImpl, 1000 / this.MAX_REQUESTS_PER_SECOND);
    },

    save: function() {

        if(this.isSaved()) {
            console.info("saving", this._lastRequestId);
            this._lastRequestId += 1;
            this._saveImpl();
        }
        else {
            console.info("inc requestId, don't save now");
            this._lastRequestId += 1;
        }
        this._updateIsSaved();

    },

    _saveImpl: function() {

        var requestId = this._lastRequestId;
        var self = this;
        var callback = function() {
            console.info("Saved: ", requestId);
            self._lastSavedRequestId = requestId;
            self._updateIsSaved();
            if(!self.isSaved()) {
                console.info("saving ", self._lastRequestId);
                self._saveImpl();
            }
        };
        Backbone.Model.prototype.save.apply(this, arguments).then(callback);
    },

    isSaved: function() {
        return this._lastSavedRequestId == this._lastRequestId;
    },

    _updateIsSaved: function() {
        var previousStatus, currentStatus;
        previousStatus = this._isSaved;
        currentStatus = this.isSaved();
        this._isSaved = currentStatus;

        if(previousStatus !== currentStatus) {
            this._triggerIsSavedChanged();
        }
    },

    _triggerIsSavedChanged: function() {
        console.info("isSaved changed", this._isSaved);
        this.trigger("change:isSaved", this._isSaved);
    }
});

MAX_RETRIES = 2;
BACKOFF_PER_RETRY = 2000;

fetchWithRetries = function(originalFetchFn) {
    return function() {
        var self = this;

        if(_.isUndefined(self._retries)) {
            self._retries = 0;
            self._fetchPromise = $.Deferred();
        }

        var onError = function(model, response) {
            self._retries += 1;
            if(self._retries > MAX_RETRIES || response.status === 404) {
                var promise = self._fetchPromise;
                delete self._retries;
                delete self._fetchPromise;
                promise.reject();
                return;
            }

            //todo -> implement clearTimeout during cleanup
            setTimeout(function() {
                fetchWithRetries.call(self);
            }, self._retries * 1000);
        }
        var onSuccess = function() {
            var promise = self._fetchPromise;
            delete self._retries;
            delete self._fetchPromise;
            promise.resolve();

        }

        // Usually, I don't pass any arguments to fetch,
        // so as of now, I'm ignoring original arguments
        // todo -> Fix it.
        originalFetchFn.call(this, {
            success: onSuccess,
            error: onError
        });
        return self._fetchPromise;
    }
}

var modelFetchFn = Backbone.Model.prototype.fetch;
var collectionFetchFn = Backbone.Collection.prototype.fetch;

Backbone.Model.prototype.fetch = fetchWithRetries(modelFetchFn)
Backbone.Collection.prototype.fetch = fetchWithRetries(collectionFetchFn);

module.exports = {
    UserModel: UserModel,
    StreamSaveModel: StreamSaveModel
};<|endoftext|>


<commit_before>//
//   Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

/* globals URI, moment, emojify */

import Ember from 'ember';

export default Ember.Object.extend({
    store: null,

    gid: 0,
    body: null,
    cat: null,
    ts: null,
    userId: null,
    window: null,
    hideImages: false,

    mentionedRegEx: Ember.computed.alias('window.userNickHighlightRegex'),

    ircMotd: false,

    nick: Ember.computed('userId', 'window', function() {
        return this.get('store.users').getNick(this.get('userId'), this.get('window.network'));
    }),

    decoratedCat: Ember.computed('cat', 'nick', 'body', 'mentionedRegEx', function() {
        let cat = this.get('cat');
        let body = this.get('body');
        let userId = this.get('userId');
        let mentionedRegEx = this.get('mentionedRegEx');

        // TBD: Network === flowdock check is missing
        if (this.get('body').indexOf('Show in Flowdock:') > -1) {
            return 'flowdock-ignore';
        } else if (mentionedRegEx && mentionedRegEx.test(body) && cat === 'msg') {
            return 'mention';
        } else if (userId == this.get('store.userId')) {
            return 'mymsg';
        }

        return this.get('nick') === 'Flowdock' ? 'flowdock' : cat;
    }),

    decoratedTs: Ember.computed('ts', function() {
        return moment.unix(this.get('ts')).format('HH:mm');
    }),

    channelAction: Ember.computed('cat', function() {
        let category = this.get('cat');
        let nick = this.get('nick');
        let groupName = this.get('window.name');
        let body = this.get('body');

        switch (category) {
            case 'join':
                return `${nick} has joined ${groupName}.`;
            case 'part':
                return `${nick} has left ${groupName}. ${body}`;
            case 'quit':
                return `${nick} has quit irc. Reason: ${body}`;
            case 'kick':
                return `${nick} was kicked from ${groupName}. Reason: ${body}`;
        }
    }),

    bodyParts: Ember.computed('body', function() {
        let body = this.get('body');
        let cat = this.get('cat');

        let parts = [];

        body = this._escapeHTMLStartTag(body);

        if (cat === 'msg') {
            ({ body, parts } = this._parseLinks(body));

            body = marked(body);
            body = this._parseCustomFormatting(body, cat);
        }

        body = this._parseWhiteSpace(body);

        parts.push({ type: 'text', text: body });

        return Ember.A(parts.map(item => Ember.Object.create(item)));
    }),

    hasMedia: Ember.computed('bodyParts', function() {
        return !this.get('bodyParts').isEvery('type', 'text');
    }),

    hasImages: Ember.computed('bodyParts', function() {
        return this.get('bodyParts').isAny('type', 'image');
    }),

    hasYoutubeVideo: Ember.computed('bodyParts', function() {
        return this.get('bodyParts').isAny('type', 'youtubelink');
    }),

    videoId: Ember.computed('bodyParts', function() {
        let video = this.get('bodyParts').findBy('type', 'youtubelink');

        if (video) {
            let urlObj = new URI(video.url);
            // Format is https://www.youtube.com/watch?v=0P7O69GuCII or https://youtu.be/0P7O69GuCII
            return urlObj.search(true).v || urlObj.pathname().substring(1).split('/')[0];
        } else {
            return null;
        }
    }),

    images: Ember.computed('bodyParts', function() {
        return this.get('bodyParts').filterBy('type', 'image');
    }),

    _parseLinks(text) {
        let imgSuffixes = [ 'png', 'jpg', 'jpeg', 'gif' ];
        let media = [];

        text = URI.withinString(text, (url, start, end, source) => {
            let urlObj = new URI(url);
            let visibleLink;
            let type = 'generic';
            let domain = urlObj.domain();

            if (imgSuffixes.indexOf(urlObj.suffix().toLowerCase()) !== -1) {
                visibleLink = urlObj.filename();
                type = 'image';
            } else if ((domain === 'youtube.com' && urlObj.search(true).v) ||
                domain === 'youtu.be') {
                visibleLink = urlObj.toString();
                type = 'youtubelink';
            } else {
                visibleLink = urlObj.readable();
            }

            if (urlObj.protocol() === '') {
                urlObj.protocol('http');
            }

            if (type === 'image' || type === 'youtubelink') {
                media.push({
                    type: type,
                    url: urlObj.toString()
                });
            }

            return this._renderLink(urlObj.normalize().toString(), visibleLink);
        });

        return { body: text, parts: media };
    },

    _parseWhiteSpace(text) {
        return text.replace(/  /g, '  '); // Preserve whitespace.
    },

    _parseCustomFormatting(text, cat) {
        let network = this.get('network');

        if (network === 'Flowdock') {
            text = text.replace(/^\[(.*?)\] << (.*)/,
                (match, p1, p2) => `[${p1.substring(0, 9)}] ${p2}`);
        }

        // Find @ character 1) after space, 2) in the beginning of string, 3) after HTML tag (>)
        text = text.replace(/(^| |>)(@\S+)(?=( |$))/g,
            (match, p1, p2) => this._renderMention(p1, p2));

        text = text.replace(/:(.+?):/g, (match, p1) => {
            if (!emojify.emojiNames.includes(p1)) {
                return match;
            } else {
                return this._renderEmoji(match, `/app/assets/images/emoji/${p1}.png`);
            }
        });

        let keywords = text.match(/<(p|br)>/g);

        // Assumes that marked is used which inserts at least one
,
, or

        let multiLine = !keywords || keywords.length > 1;

        if (!multiLine) {
            text = text.replace(/(\s*
|<\/p>\s*)/g, '');
        }

        return text;
    },

    _renderLink(url, label) {
        return `<a href="${url}" target="_blank">${label}</a>`;
    },

    _renderEmoji(name, src) {
        return `<img align="absmiddle" alt="${name}" class="emoji" src="${src}"/>`;
    },

    _renderMention(beforeCharacter, nick) {
        return `${beforeCharacter}<span class="nick-mention">${nick}</span>`;
    },

    _escapeHTMLStartTag(text) {
        return text.replace(/<]/g, '<');
    }
});
<commit_msg>Fix my message detection logic<commit_after>//
//   Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

/* globals URI, moment, emojify */

import Ember from 'ember';

export default Ember.Object.extend({
    store: null,

    gid: 0,
    body: null,
    cat: null,
    ts: null,
    userId: null,
    window: null,
    hideImages: false,

    mentionedRegEx: Ember.computed.alias('window.userNickHighlightRegex'),

    ircMotd: false,

    nick: Ember.computed('userId', 'window', function() {
        return this.get('store.users').getNick(this.get('userId'), this.get('window.network'));
    }),

    decoratedCat: Ember.computed('cat', 'nick', 'body', 'mentionedRegEx', function() {
        let cat = this.get('cat');
        let body = this.get('body');
        let userId = this.get('userId');
        let mentionedRegEx = this.get('mentionedRegEx');

        // TBD: Network === flowdock check is missing
        if (this.get('body').indexOf('Show in Flowdock:') > -1) {
            return 'flowdock-ignore';
        } else if (mentionedRegEx && mentionedRegEx.test(body) && cat === 'msg') {
            return 'mention';
        } else if (userId == this.get('store.userId') && cat === 'msg') {
            return 'mymsg';
        }

        return this.get('nick') === 'Flowdock' ? 'flowdock' : cat;
    }),

    decoratedTs: Ember.computed('ts', function() {
        return moment.unix(this.get('ts')).format('HH:mm');
    }),

    channelAction: Ember.computed('cat', function() {
        let category = this.get('cat');
        let nick = this.get('nick');
        let groupName = this.get('window.name');
        let body = this.get('body');

        switch (category) {
            case 'join':
                return `${nick} has joined ${groupName}.`;
            case 'part':
                return `${nick} has left ${groupName}. ${body}`;
            case 'quit':
                return `${nick} has quit irc. Reason: ${body}`;
            case 'kick':
                return `${nick} was kicked from ${groupName}. Reason: ${body}`;
        }
    }),

    bodyParts: Ember.computed('body', function() {
        let body = this.get('body');
        let cat = this.get('cat');

        let parts = [];

        body = this._escapeHTMLStartTag(body);

        if (cat === 'msg') {
            ({ body, parts } = this._parseLinks(body));

            body = marked(body);
            body = this._parseCustomFormatting(body, cat);
        }

        body = this._parseWhiteSpace(body);

        parts.push({ type: 'text', text: body });

        return Ember.A(parts.map(item => Ember.Object.create(item)));
    }),

    hasMedia: Ember.computed('bodyParts', function() {
        return !this.get('bodyParts').isEvery('type', 'text');
    }),

    hasImages: Ember.computed('bodyParts', function() {
        return this.get('bodyParts').isAny('type', 'image');
    }),

    hasYoutubeVideo: Ember.computed('bodyParts', function() {
        return this.get('bodyParts').isAny('type', 'youtubelink');
    }),

    videoId: Ember.computed('bodyParts', function() {
        let video = this.get('bodyParts').findBy('type', 'youtubelink');

        if (video) {
            let urlObj = new URI(video.url);
            // Format is https://www.youtube.com/watch?v=0P7O69GuCII or https://youtu.be/0P7O69GuCII
            return urlObj.search(true).v || urlObj.pathname().substring(1).split('/')[0];
        } else {
            return null;
        }
    }),

    images: Ember.computed('bodyParts', function() {
        return this.get('bodyParts').filterBy('type', 'image');
    }),

    _parseLinks(text) {
        let imgSuffixes = [ 'png', 'jpg', 'jpeg', 'gif' ];
        let media = [];

        text = URI.withinString(text, (url, start, end, source) => {
            let urlObj = new URI(url);
            let visibleLink;
            let type = 'generic';
            let domain = urlObj.domain();

            if (imgSuffixes.indexOf(urlObj.suffix().toLowerCase()) !== -1) {
                visibleLink = urlObj.filename();
                type = 'image';
            } else if ((domain === 'youtube.com' && urlObj.search(true).v) ||
                domain === 'youtu.be') {
                visibleLink = urlObj.toString();
                type = 'youtubelink';
            } else {
                visibleLink = urlObj.readable();
            }

            if (urlObj.protocol() === '') {
                urlObj.protocol('http');
            }

            if (type === 'image' || type === 'youtubelink') {
                media.push({
                    type: type,
                    url: urlObj.toString()
                });
            }

            return this._renderLink(urlObj.normalize().toString(), visibleLink);
        });

        return { body: text, parts: media };
    },

    _parseWhiteSpace(text) {
        return text.replace(/  /g, '  '); // Preserve whitespace.
    },

    _parseCustomFormatting(text, cat) {
        let network = this.get('network');

        if (network === 'Flowdock') {
            text = text.replace(/^\[(.*?)\] << (.*)/,
                (match, p1, p2) => `[${p1.substring(0, 9)}] ${p2}`);
        }

        // Find @ character 1) after space, 2) in the beginning of string, 3) after HTML tag (>)
        text = text.replace(/(^| |>)(@\S+)(?=( |$))/g,
            (match, p1, p2) => this._renderMention(p1, p2));

        text = text.replace(/:(.+?):/g, (match, p1) => {
            if (!emojify.emojiNames.includes(p1)) {
                return match;
            } else {
                return this._renderEmoji(match, `/app/assets/images/emoji/${p1}.png`);
            }
        });

        let keywords = text.match(/<(p|br)>/g);

        // Assumes that marked is used which inserts at least one
,
, or

        let multiLine = !keywords || keywords.length > 1;

        if (!multiLine) {
            text = text.replace(/(\s*
|<\/p>\s*)/g, '');
        }

        return text;
    },

    _renderLink(url, label) {
        return `<a href="${url}" target="_blank">${label}</a>`;
    },

    _renderEmoji(name, src) {
        return `<img align="absmiddle" alt="${name}" class="emoji" src="${src}"/>`;
    },

    _renderMention(beforeCharacter, nick) {
        return `${beforeCharacter}<span class="nick-mention">${nick}</span>`;
    },

    _escapeHTMLStartTag(text) {
        return text.replace(/<]/g, '<');
    }
});
<|endoftext|>


<commit_before>exports.run = (client, message) => {
  const config = require("../../settings.json");

  const embed = new client.methods.Embed()
     .setColor("#37FDFC")
     .setTimestamp()
     .setTitle("About Margarine")
     .setDescription(`I am a lovely and helpful bot (*Sometimes.*). Doing ${config.prefix}help is great for finding ways I can assist you. I was written in Komada, a Discord.js framework.\n
     \n**Name Origin:** Butterstroke#7150's typical nickname is Butter. As in the stuff that you put on toast. My name comes from the artificial butter *(Butterstroke#7150 tends to call it 'Fake Butter')* you can buy in stores called, Margarine.\n
     \n**Creation:** I was created on ${client.user.createdAt.toLocaleString()} by Butterstroke#7150. My current version is ${config.version} as of ${config.updateDate}.\n
     \n**More Info:** To find out more about what improvements ${config.version} is going to contain, please visit this link: https://github.com/Butterstroke/MargarineBot/projects/1. Any issues, complaints, improvements, or bugs should be reported using the report command!`)
     .setThumbnail(client.user.avatarURL);
  return message.channel.send({embed});
};

exports.conf = {
    enabled: true,
    runIn: ["text", "dm"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "about",
    description: "General information about Margarine.",
    usage: "",
};
<commit_msg>Update about.js<commit_after>exports.run = async (client, message) => {
  const config = require("../../settings.json");

  const embed = new client.methods.Embed()
     .setColor("#37FDFC")
     .setTimestamp()
     .setTitle("About Margarine")
     .setDescription(`I am a lovely and helpful bot (*Sometimes.*). Doing ${config.prefix}help is great for finding ways I can assist you. I was written in Komada, a Discord.js framework.\n
     \n**Name Origin:** Butterstroke#7150's typical nickname is Butter. As in the stuff that you put on toast. My name comes from the artificial butter *(Butterstroke#7150 tends to call it 'Fake Butter')* you can buy in stores called, Margarine.\n
     \n**Creation:** I was created on ${client.user.createdAt.toLocaleString()} by Butterstroke#7150. My current version is ${config.version} as of ${config.updateDate}.\n
     \nAny issues, complaints, improvements, or bugs should be reported using the report command!`)
     .setThumbnail(client.user.avatarURL());
  return message.channel.send({embed});
};

exports.conf = {
    enabled: true,
    runIn: ["text", "dm"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "about",
    description: "General information about Margarine.",
    usage: "",
};
<|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'react-router';

const LoggedOutView = props => {
  if (!props.currentUser) {
    return (

          <Link to="/" className="nav-link">
            Home
          </Link>

          <Link to="login" className="nav-link">
            Sign in
          </Link>

        <Link to="register" className="nav-link">
          Sign up
        </Link>

    );
  }
  return null;
}

const LoggedInView = props => {
  if (props.currentUser) {
    return (

          <Link to="/" className="nav-link">
            Home
          </Link>

          <Link to="animalform" className="nav-link">
             New Animal
          </Link>

          <Link to="animals" className="nav-link">
             Animals
          </Link>

          <Link
            to="settings"
            className="nav-link">
            {props.currentUser.firstName}
          </Link>

    );
  }

  return null;
};

class Header extends React.Component {
  render() {

    return(

         <Link to="/" className="navbar-brand">

         </Link>

         <LoggedOutView currentUser={this.props.currentUser} />

         <LoggedInView currentUser={this.props.currentUser} />

    )
  }
}

export default Header
<commit_msg>deleted misc header<commit_after><|endoftext|>


<commit_before>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var asyncLoading = getQueryVariable("async") === "true";
var simpleMode = getQueryVariable("simpleMode") === "true";
var pauseExecution = getQueryVariable("paused") === "true";
var remoteFile = getQueryVariable("rfile");
var yt = getQueryVariable('yt');

var swfController = new SWFController(fps, pauseExecution);

var libraryAbcs;
var libraryScripts;
function grabAbc(abcName) {
  var entry = libraryScripts[abcName];
  if (entry) {
    var offset = entry.offset;
    var length = entry.length;
    return new AbcFile(new Uint8Array(libraryAbcs, offset, length), abcName);
  }
  return null
}

function findDefiningAbc(mn) {
  if (!avm2.builtinsLoaded) {
    return null;
  }
  var name;
  for (var i = 0; i < mn.namespaces.length; i++) {
    var name = mn.namespaces[i].originalURI + ":" + mn.name;
    var abcName = playerGlobalNames[name];
    if (abcName) {
      break;
    }
  }
  if (abcName) {
    return grabAbc(abcName);
  }
  return null;
}

/** Global sanityTests array, sanity tests add themselves to this */
var sanityTests = [];

// avm2 must be global.
var avm2;
function createAVM2(builtinPath, libraryPath, avm1Path, sysMode, appMode, next) {
  function loadAVM1(next) {
    new BinaryFileReader(avm1Path).readAll(null, function (buffer) {
      avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), "avm1.abc"));
      next();
    });
  }

  assert (builtinPath);
  new BinaryFileReader(builtinPath).readAll(null, function (buffer) {
    avm2 = new AVM2(sysMode, appMode, findDefiningAbc, avm1Path && loadAVM1);
    console.time("Execute builtin.abc");
    avm2.loadedAbcs = {};
    // Avoid loading more Abcs while the builtins are loaded
    avm2.builtinsLoaded = false;
    avm2.systemDomain.onMessage.register('classCreated', Stubs.onClassCreated);
    avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), "builtin.abc"));
    avm2.builtinsLoaded = true;
    console.timeEnd("Execute builtin.abc");

    new BinaryFileReader(libraryPath).readAll(null, function (buffer) {
      // If library is shell.abc, then just go ahead and run it now since
      // it's not worth doing it lazily given that it is so small.
      if (libraryPath === shellAbcPath) {
        avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), libraryPath));
      } else {
        libraryAbcs = buffer;
      }
      next(avm2);
    });
  });
}

var avm2Root = "../../src/avm2/";
var builtinPath = avm2Root + "generated/builtin/builtin.abc";
var shellAbcPath = avm2Root + "generated/shell/shell.abc";
var avm1Path = avm2Root + "generated/avm1lib/avm1lib.abc";
var playerGlobalAbcPath = "../../src/flash/playerglobal.abc";

function parseQueryString(qs) {
  if (!qs)
    return {};

  if (qs.charAt(0) == '?')
    qs = qs.slice(1);

  var values = qs.split('&');
  var obj = {};
  for (var i = 0; i < values.length; i++) {
    var kv = values[i].split('=');
    var key = kv[0], value = kv[1];
    obj[decodeURIComponent(key)] = decodeURIComponent(value);
  }

  return obj;
}

/**
 * You can also specify a remote file as a query string parameters, ?rfile=... to load it automatically
 * when the page loads.
 */
if (remoteFile) {
  document.getElementById('openFile').setAttribute('hidden', true);
  executeFile(remoteFile, null, parseQueryString(window.location.search));
}

if (yt) {
  var xhr = new XMLHttpRequest({mozSystem: true});
  xhr.open('GET', 'http://www.youtube.com/watch?v=' + yt, true);
  xhr.onload = function (e) {
    var config = JSON.parse(/ytplayer\.config\s*=\s*(.+?);<\/script/.exec(xhr.responseText)[1]);
    // HACK removing FLVs from the fmt_list
    config.args.fmt_list = config.args.fmt_list.split(',').filter(function (s) {
      var fid = s.split('/')[0];
      return fid !== '5' && fid !== '34' && fid !== '35'; // more?
    }).join(',');

    var swf = config.url;

    document.getElementById('openFile').setAttribute('hidden', true);
    executeFile(swf, null, config.args);
  };
  xhr.send(null);
}

if (simpleMode) {
  document.body.setAttribute('class', 'simple');
}

function showMessage(msg) {
  document.getElementById('message').textContent = "(" + msg + ")";
}

function executeFile(file, buffer, movieParams) {
  // All execution paths must now load AVM2.
  if (!state.appCompiler) {
    showMessage("Running in the Interpreter");
  }
  var sysMode = state.sysCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;
  var appMode = state.appCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;

  var url = document.createElement('a');
  url.href = file;
  url.search = '';
  url.hash = '';
  var filename = url.href.replace(/\?#$/, ""); // ??? Chrome adds ?# at the end
  if (filename.endsWith(".abc")) {
    libraryScripts = {};
    createAVM2(builtinPath, shellAbcPath, null, sysMode, appMode, function (avm2) {
      function runAbc(file, buffer) {
        avm2.applicationDomain.executeAbc(new AbcFile(new Uint8Array(buffer), file));
        // TODO terminate avm2 instance?;
      }
      if (!buffer) {
        new BinaryFileReader(file).readAll(null, function(buffer) {
          runAbc(file, buffer);
        });
      } else {
        runAbc(file, buffer);
      }
    });
  } else if (filename.endsWith(".swf")) {
    libraryScripts = playerGlobalScripts;
    createAVM2(builtinPath, playerGlobalAbcPath, avm1Path, sysMode, appMode, function (avm2) {
      function runSWF(file, buffer) {
        var swfURL = FileLoadingService.resolveUrl(file);
        var loaderURL = getQueryVariable("loaderURL") || swfURL;
        SWF.embed(buffer || file, document, document.getElementById('stage'), {
          onComplete: swfController.completeCallback.bind(swfController),
          onBeforeFrame: swfController.beforeFrameCallback.bind(swfController),
          onAfterFrame: swfController.afterFrameCallback.bind(swfController),
          onStageInitialized: swfController.stageInitializedCallback.bind(swfController),
          url: swfURL,
          loaderURL: loaderURL,
          movieParams: movieParams || {},
        });
      }
      if (!buffer && asyncLoading) {
        FileLoadingService.setBaseUrl(file);
        runSWF(file);
      } else if (!buffer) {
        FileLoadingService.setBaseUrl(file);
        new BinaryFileReader(file).readAll(null, function(buffer, error) {
          if (!buffer) {
            throw "Unable to open the file " + file + ": " + error;
          }
          runSWF(file, buffer);
        });
      } else {
        runSWF(file, buffer);
      }
    });
  } else if (filename.endsWith(".js") || filename.endsWith("/")) {
    libraryScripts = playerGlobalScripts;
    createAVM2(builtinPath, playerGlobalAbcPath, null, sysMode, appMode, function (avm2) {
      if (file.endsWith("/")) {
        readDirectoryListing(file, function (files) {
          function loadNextScript(done) {
            if (!files.length) {
              done();
              return;
            }
            var sanityTest = files.pop();
            console.info("Loading Sanity Test: " + sanityTest);
            loadScript(sanityTest, function () {
              loadNextScript(done);
            });
          }
          loadNextScript(function whenAllScriptsAreLoaded() {
            console.info("Executing Sanity Test");
            sanityTests.forEach(function (test) {
              test(console, avm2);
            });
          });
        });
      } else {
        loadScript(file, function () {
          sanityTests.forEach(function (test) {
            test(console, avm2);
          });
        });
      }
    });
  }
}

(function setStageSize() {
  var stageSize = getQueryVariable("size");
  if (stageSize && /^\d+x\d+$/.test(stageSize)) {
    var dims = stageSize.split('x');
    var stage = document.getElementById('stage');
    stage.style.width = dims[0] + "px";
    stage.style.height = dims[1] + "px";
  }
})();

var TelemetryService = {
  reportTelemetry: function (data) { }
};

var FileLoadingService = {
  createSession: function () {
    return {
      open: function (request) {
        if (request.url.indexOf('http://s.youtube.com/stream_204') === 0) {
          // No reason to send error report yet, let's keep it this way for now.
          // 204 means no response, so no data will be expected.
          console.error('YT_CALLBACK: ' + request.url);
          this.onopen && this.onopen();
          this.onclose && this.onclose();
          return;
        }

        var self = this;
        var path = FileLoadingService.resolveUrl(request.url);
        console.log('FileLoadingService: loading ' + path + ", data: " + request.data);
        new BinaryFileReader(path, request.method, request.mimeType, request.data).readAsync(
          function (data, progress) {
            self.onprogress(data, {bytesLoaded: progress.loaded, bytesTotal: progress.total});
          },
          function (e) { self.onerror(e); },
          self.onopen,
          self.onclose,
          self.onhttpstatus);
      }
    };
  },
  setBaseUrl: function (url) {
    var a = document.createElement('a');
    a.href = url || '#';
    a.setAttribute('style', 'display: none;');
    document.body.appendChild(a);
    FileLoadingService.baseUrl = a.href;
    document.body.removeChild(a);
  },
  resolveUrl: function (url) {
    if (url.indexOf('://') >= 0) {
      return url;
    }

    var base = FileLoadingService.baseUrl || '';
    base = base.lastIndexOf('/') >= 0 ? base.substring(0, base.lastIndexOf('/') + 1) : '';
    if (url.indexOf('/') === 0) {
      var m = /^[^:]+:\/\/[^\/]+/.exec(base);
      if (m) base = m[0];
    }
    return base + url;
  }
};

// toggle button states in button bars
Array.prototype.forEach.call(document.querySelectorAll(".toolbarButtonBar > .toolbarButton"), function (element) {
  element.addEventListener("click", function (event) {
    Array.prototype.forEach.call(event.target.parentElement.children, function (button) {
      if (button == event.target) {
        button.classList.add("pressedState");
      } else {
        button.classList.remove("pressedState");
      }
    });
  });
});

// toggle info panels (debug info, display list)
var panelToggleButtonSelector = "#debugInfoToolbar > .toolbarButtonBar > .toolbarButton";
function panelToggleButtonClickHandler(event) {
  Array.prototype.forEach.call(document.querySelectorAll(panelToggleButtonSelector), function (element) {
    var panelId = element.dataset.panelid;
    var panel = document.getElementById(panelId);
    if (event.target == element) {
      panel.classList.add("active");
    } else {
      panel.classList.remove("active");
    }
  });
  switch (event.target.dataset.panelid) {
    case "displayListContainer":
      if (swfController.isPlaying()) {
        swfController.pause(function() {
          updateDisplayListTree();
        });
      } else {
        updateDisplayListTree();
      }
      document.getElementById("ctrlLogToConsole").classList.remove("active");
      break;
    default:
      document.getElementById("ctrlLogToConsole").classList.add("active");
      break;
  }
}
Array.prototype.forEach.call(document.querySelectorAll(panelToggleButtonSelector), function (element) {
  element.addEventListener("click", panelToggleButtonClickHandler);
});

swfController.onStateChange = function onStateChange(newState, oldState) {
  if (oldState === swfController.STATE_INIT) {
    initUI();
  }
  var pauseButton = document.getElementById("pauseButton");
  var stepButton = document.getElementById("stepButton");
  switch (newState) {
    case swfController.STATE_PLAYING:
      pauseButton.classList.remove("icon-play");
      pauseButton.classList.add("icon-pause");
      stepButton.classList.add("disabled");
      break;
    case swfController.STATE_PAUSED:
      pauseButton.classList.add("icon-play");
      pauseButton.classList.remove("icon-pause");
      stepButton.classList.remove("disabled");
      updateDisplayListTree();
      break;
  }
}

function initUI() {
  document.querySelector("#debugInfoToolbar > .toolbarButtonBar").classList.add("active");
  document.getElementById("ctrlLogToConsole").classList.add("active");
  document.getElementById("muteButton").classList.add("active");
  document.getElementById("pauseButton").classList.add("active");
  document.getElementById("stepButton").classList.add("active");

  avm2.systemDomain.getClass("flash.media.SoundMixer").native.static._setMasterVolume(state.mute ? 0 : 1);

  document.getElementById("pauseButton").addEventListener("click", function (event) {
    swfController.togglePause();
  });
  document.getElementById("stepButton").addEventListener("click", function (event) {
    if (swfController.isPaused()) {
      swfController.play(1);
    }
  });
}

function updateDisplayListTree() {
  var displayList = new DisplayListTree();
  displayList.update(swfController.stage, document.getElementById("displayListContainer"));
}
<commit_msg>Make inspector.html?rfile= work in Chrome again<commit_after>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var asyncLoading = getQueryVariable("async") === "true";
var simpleMode = getQueryVariable("simpleMode") === "true";
var pauseExecution = getQueryVariable("paused") === "true";
var remoteFile = getQueryVariable("rfile");
var yt = getQueryVariable('yt');

var swfController = new SWFController(fps, pauseExecution);

var libraryAbcs;
var libraryScripts;
function grabAbc(abcName) {
  var entry = libraryScripts[abcName];
  if (entry) {
    var offset = entry.offset;
    var length = entry.length;
    return new AbcFile(new Uint8Array(libraryAbcs, offset, length), abcName);
  }
  return null
}

function findDefiningAbc(mn) {
  if (!avm2.builtinsLoaded) {
    return null;
  }
  var name;
  for (var i = 0; i < mn.namespaces.length; i++) {
    var name = mn.namespaces[i].originalURI + ":" + mn.name;
    var abcName = playerGlobalNames[name];
    if (abcName) {
      break;
    }
  }
  if (abcName) {
    return grabAbc(abcName);
  }
  return null;
}

/** Global sanityTests array, sanity tests add themselves to this */
var sanityTests = [];

// avm2 must be global.
var avm2;
function createAVM2(builtinPath, libraryPath, avm1Path, sysMode, appMode, next) {
  function loadAVM1(next) {
    new BinaryFileReader(avm1Path).readAll(null, function (buffer) {
      avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), "avm1.abc"));
      next();
    });
  }

  assert (builtinPath);
  new BinaryFileReader(builtinPath).readAll(null, function (buffer) {
    avm2 = new AVM2(sysMode, appMode, findDefiningAbc, avm1Path && loadAVM1);
    console.time("Execute builtin.abc");
    avm2.loadedAbcs = {};
    // Avoid loading more Abcs while the builtins are loaded
    avm2.builtinsLoaded = false;
    avm2.systemDomain.onMessage.register('classCreated', Stubs.onClassCreated);
    avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), "builtin.abc"));
    avm2.builtinsLoaded = true;
    console.timeEnd("Execute builtin.abc");

    new BinaryFileReader(libraryPath).readAll(null, function (buffer) {
      // If library is shell.abc, then just go ahead and run it now since
      // it's not worth doing it lazily given that it is so small.
      if (libraryPath === shellAbcPath) {
        avm2.systemDomain.executeAbc(new AbcFile(new Uint8Array(buffer), libraryPath));
      } else {
        libraryAbcs = buffer;
      }
      next(avm2);
    });
  });
}

var avm2Root = "../../src/avm2/";
var builtinPath = avm2Root + "generated/builtin/builtin.abc";
var shellAbcPath = avm2Root + "generated/shell/shell.abc";
var avm1Path = avm2Root + "generated/avm1lib/avm1lib.abc";
var playerGlobalAbcPath = "../../src/flash/playerglobal.abc";

function parseQueryString(qs) {
  if (!qs)
    return {};

  if (qs.charAt(0) == '?')
    qs = qs.slice(1);

  var values = qs.split('&');
  var obj = {};
  for (var i = 0; i < values.length; i++) {
    var kv = values[i].split('=');
    var key = kv[0], value = kv[1];
    obj[decodeURIComponent(key)] = decodeURIComponent(value);
  }

  return obj;
}

/**
 * You can also specify a remote file as a query string parameters, ?rfile=... to load it automatically
 * when the page loads.
 */
if (remoteFile) {
  document.getElementById('openFile').setAttribute('hidden', true);
  executeFile(remoteFile, null, parseQueryString(window.location.search));
}

if (yt) {
  var xhr = new XMLHttpRequest({mozSystem: true});
  xhr.open('GET', 'http://www.youtube.com/watch?v=' + yt, true);
  xhr.onload = function (e) {
    var config = JSON.parse(/ytplayer\.config\s*=\s*(.+?);<\/script/.exec(xhr.responseText)[1]);
    // HACK removing FLVs from the fmt_list
    config.args.fmt_list = config.args.fmt_list.split(',').filter(function (s) {
      var fid = s.split('/')[0];
      return fid !== '5' && fid !== '34' && fid !== '35'; // more?
    }).join(',');

    var swf = config.url;

    document.getElementById('openFile').setAttribute('hidden', true);
    executeFile(swf, null, config.args);
  };
  xhr.send(null);
}

if (simpleMode) {
  document.body.setAttribute('class', 'simple');
}

function showMessage(msg) {
  document.getElementById('message').textContent = "(" + msg + ")";
}

function executeFile(file, buffer, movieParams) {
  // All execution paths must now load AVM2.
  if (!state.appCompiler) {
    showMessage("Running in the Interpreter");
  }
  var sysMode = state.sysCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;
  var appMode = state.appCompiler ? EXECUTION_MODE.COMPILE : EXECUTION_MODE.INTERPRET;

  var filename = file.split('?')[0].split('#')[0];
  if (filename.endsWith(".abc")) {
    libraryScripts = {};
    createAVM2(builtinPath, shellAbcPath, null, sysMode, appMode, function (avm2) {
      function runAbc(file, buffer) {
        avm2.applicationDomain.executeAbc(new AbcFile(new Uint8Array(buffer), file));
        // TODO terminate avm2 instance?;
      }
      if (!buffer) {
        new BinaryFileReader(file).readAll(null, function(buffer) {
          runAbc(file, buffer);
        });
      } else {
        runAbc(file, buffer);
      }
    });
  } else if (filename.endsWith(".swf")) {
    libraryScripts = playerGlobalScripts;
    createAVM2(builtinPath, playerGlobalAbcPath, avm1Path, sysMode, appMode, function (avm2) {
      function runSWF(file, buffer) {
        var swfURL = FileLoadingService.resolveUrl(file);
        var loaderURL = getQueryVariable("loaderURL") || swfURL;
        SWF.embed(buffer || file, document, document.getElementById('stage'), {
          onComplete: swfController.completeCallback.bind(swfController),
          onBeforeFrame: swfController.beforeFrameCallback.bind(swfController),
          onAfterFrame: swfController.afterFrameCallback.bind(swfController),
          onStageInitialized: swfController.stageInitializedCallback.bind(swfController),
          url: swfURL,
          loaderURL: loaderURL,
          movieParams: movieParams || {},
        });
      }
      if (!buffer && asyncLoading) {
        FileLoadingService.setBaseUrl(file);
        runSWF(file);
      } else if (!buffer) {
        FileLoadingService.setBaseUrl(file);
        new BinaryFileReader(file).readAll(null, function(buffer, error) {
          if (!buffer) {
            throw "Unable to open the file " + file + ": " + error;
          }
          runSWF(file, buffer);
        });
      } else {
        runSWF(file, buffer);
      }
    });
  } else if (filename.endsWith(".js") || filename.endsWith("/")) {
    libraryScripts = playerGlobalScripts;
    createAVM2(builtinPath, playerGlobalAbcPath, null, sysMode, appMode, function (avm2) {
      if (file.endsWith("/")) {
        readDirectoryListing(file, function (files) {
          function loadNextScript(done) {
            if (!files.length) {
              done();
              return;
            }
            var sanityTest = files.pop();
            console.info("Loading Sanity Test: " + sanityTest);
            loadScript(sanityTest, function () {
              loadNextScript(done);
            });
          }
          loadNextScript(function whenAllScriptsAreLoaded() {
            console.info("Executing Sanity Test");
            sanityTests.forEach(function (test) {
              test(console, avm2);
            });
          });
        });
      } else {
        loadScript(file, function () {
          sanityTests.forEach(function (test) {
            test(console, avm2);
          });
        });
      }
    });
  }
}

(function setStageSize() {
  var stageSize = getQueryVariable("size");
  if (stageSize && /^\d+x\d+$/.test(stageSize)) {
    var dims = stageSize.split('x');
    var stage = document.getElementById('stage');
    stage.style.width = dims[0] + "px";
    stage.style.height = dims[1] + "px";
  }
})();

var TelemetryService = {
  reportTelemetry: function (data) { }
};

var FileLoadingService = {
  createSession: function () {
    return {
      open: function (request) {
        if (request.url.indexOf('http://s.youtube.com/stream_204') === 0) {
          // No reason to send error report yet, let's keep it this way for now.
          // 204 means no response, so no data will be expected.
          console.error('YT_CALLBACK: ' + request.url);
          this.onopen && this.onopen();
          this.onclose && this.onclose();
          return;
        }

        var self = this;
        var path = FileLoadingService.resolveUrl(request.url);
        console.log('FileLoadingService: loading ' + path + ", data: " + request.data);
        new BinaryFileReader(path, request.method, request.mimeType, request.data).readAsync(
          function (data, progress) {
            self.onprogress(data, {bytesLoaded: progress.loaded, bytesTotal: progress.total});
          },
          function (e) { self.onerror(e); },
          self.onopen,
          self.onclose,
          self.onhttpstatus);
      }
    };
  },
  setBaseUrl: function (url) {
    var a = document.createElement('a');
    a.href = url || '#';
    a.setAttribute('style', 'display: none;');
    document.body.appendChild(a);
    FileLoadingService.baseUrl = a.href;
    document.body.removeChild(a);
  },
  resolveUrl: function (url) {
    if (url.indexOf('://') >= 0) {
      return url;
    }

    var base = FileLoadingService.baseUrl || '';
    base = base.lastIndexOf('/') >= 0 ? base.substring(0, base.lastIndexOf('/') + 1) : '';
    if (url.indexOf('/') === 0) {
      var m = /^[^:]+:\/\/[^\/]+/.exec(base);
      if (m) base = m[0];
    }
    return base + url;
  }
};

// toggle button states in button bars
Array.prototype.forEach.call(document.querySelectorAll(".toolbarButtonBar > .toolbarButton"), function (element) {
  element.addEventListener("click", function (event) {
    Array.prototype.forEach.call(event.target.parentElement.children, function (button) {
      if (button == event.target) {
        button.classList.add("pressedState");
      } else {
        button.classList.remove("pressedState");
      }
    });
  });
});

// toggle info panels (debug info, display list)
var panelToggleButtonSelector = "#debugInfoToolbar > .toolbarButtonBar > .toolbarButton";
function panelToggleButtonClickHandler(event) {
  Array.prototype.forEach.call(document.querySelectorAll(panelToggleButtonSelector), function (element) {
    var panelId = element.dataset.panelid;
    var panel = document.getElementById(panelId);
    if (event.target == element) {
      panel.classList.add("active");
    } else {
      panel.classList.remove("active");
    }
  });
  switch (event.target.dataset.panelid) {
    case "displayListContainer":
      if (swfController.isPlaying()) {
        swfController.pause(function() {
          updateDisplayListTree();
        });
      } else {
        updateDisplayListTree();
      }
      document.getElementById("ctrlLogToConsole").classList.remove("active");
      break;
    default:
      document.getElementById("ctrlLogToConsole").classList.add("active");
      break;
  }
}
Array.prototype.forEach.call(document.querySelectorAll(panelToggleButtonSelector), function (element) {
  element.addEventListener("click", panelToggleButtonClickHandler);
});

swfController.onStateChange = function onStateChange(newState, oldState) {
  if (oldState === swfController.STATE_INIT) {
    initUI();
  }
  var pauseButton = document.getElementById("pauseButton");
  var stepButton = document.getElementById("stepButton");
  switch (newState) {
    case swfController.STATE_PLAYING:
      pauseButton.classList.remove("icon-play");
      pauseButton.classList.add("icon-pause");
      stepButton.classList.add("disabled");
      break;
    case swfController.STATE_PAUSED:
      pauseButton.classList.add("icon-play");
      pauseButton.classList.remove("icon-pause");
      stepButton.classList.remove("disabled");
      updateDisplayListTree();
      break;
  }
}

function initUI() {
  document.querySelector("#debugInfoToolbar > .toolbarButtonBar").classList.add("active");
  document.getElementById("ctrlLogToConsole").classList.add("active");
  document.getElementById("muteButton").classList.add("active");
  document.getElementById("pauseButton").classList.add("active");
  document.getElementById("stepButton").classList.add("active");

  avm2.systemDomain.getClass("flash.media.SoundMixer").native.static._setMasterVolume(state.mute ? 0 : 1);

  document.getElementById("pauseButton").addEventListener("click", function (event) {
    swfController.togglePause();
  });
  document.getElementById("stepButton").addEventListener("click", function (event) {
    if (swfController.isPaused()) {
      swfController.play(1);
    }
  });
}

function updateDisplayListTree() {
  var displayList = new DisplayListTree();
  displayList.update(swfController.stage, document.getElementById("displayListContainer"));
}
<|endoftext|>


<commit_before>const commando = require('discord.js-commando');
const reddit = require('redwrap');

class RedditCommand extends commando.Command{
  constructor(client){
    super(client, {
      name: 'reddit',
      group: 'random',
      memberName: 'reddit',
      description: 'Finds a random post from a given subreddit'
    });

  }

  async run(message, args){
    try{
      var args = message.content.split(" ");
      if(args.length >= 2){
        var subreddit = args[1];
        this.findPost(subreddit).then(function(pasta){
          if(pasta){
            message.channel.send(pasta);
          }else{
            message.channel.send("Post not found");
          }
        }, function(err){
          message.channel.send(err);
        });
      }else{
        message.channel.send("You must include a subreddit");
      }
    }catch(err){console.log(err);}

  }

  loadPosts(subreddit){
    var arr = [];
    return new Promise(function(resolve, reject){
      reddit.r(subreddit, function(err, data, res){
        if(err) console.log(err);
        if(!data.data || !data.data.children || data.data.children.length == 0){
          reject("Does this subreddit exist?");
        }else{
          for(var i = 0; i < data.data.children.length; i++){
            var child = data.data.children[i];
            var post = child.data.selftext;
            if(!post) post = "";
            arr.push("**" +child.data.title + "**\n" + post.substring(0,1800) + "\n" + child.data.url + "\n");

          }

          if(arr.length == 0){
            reject("No text posts found");
          }else{
            resolve(arr);
          }
        }
      });
    });
  }

  findPost(subreddit){
    return new Promise(function(resolve, reject){
      this.loadPosts(subreddit).then(function(posts){
        // console.log(posts.length);
        resolve(posts[Math.floor(random(posts.length))]);
      }, function(err){
        // console.log(err);
        reject(err);
      });
    }.bind(this));
  }

}

function random(min,max){
  if(arguments.length == 1){
    max = min;
    min = 0;
  }
  return (Math.random() * (max-min) + min);
}

module.exports = RedditCommand;
<commit_msg>Remove console log statements<commit_after>const commando = require('discord.js-commando');
const reddit = require('redwrap');

class RedditCommand extends commando.Command{
  constructor(client){
    super(client, {
      name: 'reddit',
      group: 'random',
      memberName: 'reddit',
      description: 'Finds a random post from a given subreddit'
    });

  }

  async run(message, args){
    try{
      var args = message.content.split(" ");
      if(args.length >= 2){
        var subreddit = args[1];
        this.findPost(subreddit).then(function(pasta){
          message.channel.send(pasta);
        }, function(err){
          message.channel.send(err);
        });
      }else{
        message.channel.send("You must include a subreddit");
      }
    }catch(err){console.log(err);}

  }

  loadPosts(subreddit){
    var arr = [];
    return new Promise(function(resolve, reject){
      reddit.r(subreddit, function(err, data, res){
        if(err) console.log(err);
        if(!data.data || !data.data.children || data.data.children.length == 0){
          reject("Does this subreddit exist?");
        }else{
          for(var i = 0; i < data.data.children.length; i++){
            var child = data.data.children[i];
            var post = child.data.selftext;
            if(!post) post = "";
            arr.push("**" +child.data.title + "**\n" + post.substring(0,1800) + "\n" + child.data.url + "\n");

          }
          resolve(arr);
        }
      });
    });
  }

  findPost(subreddit){
    return new Promise(function(resolve, reject){
      this.loadPosts(subreddit).then(function(posts){
        resolve(posts[Math.floor(random(posts.length))]);
      }, function(err){
        reject(err);
      });
    }.bind(this));
  }

}

function random(min,max){
  if(arguments.length == 1){
    max = min;
    min = 0;
  }
  return (Math.random() * (max-min) + min);
}

module.exports = RedditCommand;
<|endoftext|>


<commit_before>import Axios from 'axios';
import Qs from 'qs';
import config from '../config';
import Debug from 'debug';

let debug = new Debug("rest");

function baseUrl( url ) {
    var fullUrl = config.apiUrl +  url;
    return fullUrl;
}

export default function(options = {}){
  let _jwtSelector;

  function ajax( url, method, data, params ) {
      debug("ajax url: %s, method: %s, options %s, params: ", url, method, JSON.stringify(options), params);
      let headers = {
          'Content-Type': 'application/json'
      }

      if(_jwtSelector){
          let jwt = _jwtSelector();
          if(jwt){
              headers.Authorization = 'Bearer ' + jwt;
          }
      }

      return Axios({
          method: method,
          url: baseUrl(url),
          params: params,
          data: data,
          withCredentials: true,
          headers: headers,
          timeout: 2e3,
          paramsSerializer: function(params) {
              return Qs.stringify(params, {arrayFormat: 'brackets'});
          }
      }).then(res => {
          return res.data;
      }).catch(error => {
          debug("ajax error: ", error);
          throw error
      });
  }

  return {
    setJwtSelector(jwtSelector){
        _jwtSelector = jwtSelector
    },
    get( url, options = {} ) {
        return ajax( url, 'GET', null, options );
    },
    post( url, options = {} ) {
        return ajax( url, 'POST', options );
    },
    put( url, options = {} ) {
        return ajax( url, 'PUT', options );
    },
    del( url, options = {} ) {
        return ajax( url, 'DELETE', options );
    },
    patch( url, options = {} ) {
       return ajax( url, 'PATCH', options );
    }
  }
}
<commit_msg>increase http timeout to 30 sec<commit_after>import Axios from 'axios';
import Qs from 'qs';
import config from '../config';
import Debug from 'debug';

let debug = new Debug("rest");

function baseUrl( url ) {
    var fullUrl = config.apiUrl +  url;
    return fullUrl;
}

export default function(options = {}){
  let _jwtSelector;

  function ajax( url, method, data, params ) {
      debug("ajax url: %s, method: %s, options %s, params: ", url, method, JSON.stringify(options), params);
      let headers = {
          'Content-Type': 'application/json'
      }

      if(_jwtSelector){
          let jwt = _jwtSelector();
          if(jwt){
              headers.Authorization = 'Bearer ' + jwt;
          }
      }

      return Axios({
          method: method,
          url: baseUrl(url),
          params: params,
          data: data,
          withCredentials: true,
          headers: headers,
          timeout: 30e3,
          paramsSerializer: function(params) {
              return Qs.stringify(params, {arrayFormat: 'brackets'});
          }
      }).then(res => {
          return res.data;
      }).catch(error => {
          debug("ajax error: ", error);
          throw error
      });
  }

  return {
    setJwtSelector(jwtSelector){
        _jwtSelector = jwtSelector
    },
    get( url, options = {} ) {
        return ajax( url, 'GET', null, options );
    },
    post( url, options = {} ) {
        return ajax( url, 'POST', options );
    },
    put( url, options = {} ) {
        return ajax( url, 'PUT', options );
    },
    del( url, options = {} ) {
        return ajax( url, 'DELETE', options );
    },
    patch( url, options = {} ) {
       return ajax( url, 'PATCH', options );
    }
  }
}
<|endoftext|>


<commit_before>import React, {Component} from 'react'

import GraphiQL from 'graphiql'
import 'graphiql/graphiql.css'

import Breadcrumbs from 'components/Breadcrumbs'

export default class extends Component {
	static pageProps = {
		useNavigation: false,
		fluidContainer: true,
	}

	fetch(params) {
		return fetch('/graphql', {
			credentials: 'same-origin',
			method: 'POST',
			headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
			body: JSON.stringify(params),
		}).then(response => response.json())
	}

	render() {
		return

			<Breadcrumbs items={[['Run GraphQL queries', '/graphiql']]} />
			<GraphiQL fetcher={this.fetch} />

	}
}
<commit_msg>Move graphiql to a separate bundle to save 150kb<commit_after>import React, {Component} from 'react'

import Breadcrumbs from 'components/Breadcrumbs'

var GraphiQL = null

export default class extends Component {
	static pageProps = {
		useNavigation: false,
		fluidContainer: true,
	}

	componentDidMount() {
		if (GraphiQL)
			return

		require.ensure([], () => {
			GraphiQL = require('graphiql')
			require('graphiql/graphiql.css')
			this.forceUpdate()
		})
	}

	fetch(params) {
		return fetch('/graphql', {
			credentials: 'same-origin',
			method: 'POST',
			headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
			body: JSON.stringify(params),
		}).then(response => response.json())
	}

	render() {
		return

			<Breadcrumbs items={[['Run GraphQL queries', '/graphiql']]} />
			{GraphiQL ? <GraphiQL fetcher={this.fetch} /> : "Loading..."}

	}
}
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';

import BroadcastReducer from './reducer_broadcast';

const rootReducer = combineReducers({
  state: (state = {}) => state,
  broadcasts: BroadcastReducer
});

export default rootReducer;
<commit_msg>Mount BroadcastReducer to 'form' instead of 'broadcast' per redux-form error message.<commit_after>import { combineReducers } from 'redux';

import BroadcastReducer from './reducer_broadcast';

const rootReducer = combineReducers({
  state: (state = {}) => state,
  // broadcasts: BroadcastReducer
  form: BroadcastReducer
});

export default rootReducer;
<|endoftext|>


<commit_before>import UploadActions from '../actions/UploadActions'
import UploadFile from '../UploadFile'
import alt from '../alt'
import peer from '../peer'
import socket from '../socket'

export default alt.createStore(class UploadStore {

  constructor() {
    this.bindActions(UploadActions)

    this.status = 'ready'
    this.token = null
    this.file = null
    this.peerProgress = {}
  }

  onUploadFile(file) {
    if (this.status !== 'ready') return
    this.status = 'processing'
    this.file = new UploadFile(file)

    socket.emit('upload', {
      name: this.file.name,
      size: this.file.size,
      type: this.file.type
    }, (token) => {
      this.setState({
        status: 'uploading',
        token: token
      })
    })
  }

  onSendToDownloader(peerID) {
    if (this.status !== 'uploading') return

    let conn = peer.connect(peerID, {
      reliable: true
    })

    let totalChunks = this.file.countChunks()
    let i = 0

    let sendNextChunk = () => {
      if (i === totalChunks) return
      let packet = this.file.getChunk(i)
      conn.send(packet)
      i++
      this.peerProgress[peerID] = i/totalChunks
    }

    conn.on('open', () => {
      sendNextChunk()
      this.setState({ peerProgress: this.peerProgress })
    })

    conn.on('data', (data) => {
      if (data === 'more') sendNextChunk()
      this.setState({ peerProgress: this.peerProgress })
    })

    conn.on('close', () => {
      this.setState({ peerProgress: this.peerProgress })
    })
  }

}, 'UploadStore')
<commit_msg>Store failed connections in peerProgress too.<commit_after>import UploadActions from '../actions/UploadActions'
import UploadFile from '../UploadFile'
import alt from '../alt'
import peer from '../peer'
import socket from '../socket'

export default alt.createStore(class UploadStore {

  constructor() {
    this.bindActions(UploadActions)

    this.status = 'ready'
    this.token = null
    this.file = null
    this.peerProgress = {}
  }

  onUploadFile(file) {
    if (this.status !== 'ready') return
    this.status = 'processing'
    this.file = new UploadFile(file)

    socket.emit('upload', {
      name: this.file.name,
      size: this.file.size,
      type: this.file.type
    }, (token) => {
      this.setState({
        status: 'uploading',
        token: token
      })
    })
  }

  onSendToDownloader(peerID) {
    if (this.status !== 'uploading') return

    let conn = peer.connect(peerID, {
      reliable: true
    })

    let totalChunks = this.file.countChunks()
    let i = 0

    let sendNextChunk = () => {
      if (i === totalChunks) return
      let packet = this.file.getChunk(i)
      conn.send(packet)
      i++
      this.peerProgress[peerID] = i/totalChunks
    }

    conn.on('open', () => {
      sendNextChunk()
      this.setState({ peerProgress: this.peerProgress })
    })

    conn.on('data', (data) => {
      if (data === 'more') sendNextChunk()
      this.setState({ peerProgress: this.peerProgress })
    })

    conn.on('close', () => {
      if (this.peerProgress[peerID] < 1) {
        this.peerProgress[peerID] = -1
      }
      this.setState({ peerProgress: this.peerProgress })
    })
  }

}, 'UploadStore')
<|endoftext|>


<commit_before>var util = require('util');
var _ = require('underscore');
var Promise = require('bluebird');
var Exceptions = require('../exceptions');
var EventEmitter = require('events').EventEmitter;

function FeedBase(session) {
    this.session = session;
    this.allResults=[];
    this.cursor = null;
    this.moreAvailable = null;
    this.iteration = 0;
    // Pause multiplier.
    this.parseErrorsMultiplier = 0;
}
util.inherits(FeedBase, EventEmitter);

FeedBase.prototype.all = function (parameters) {
    var that = this;
    parameters = _.isObject(parameters) ? parameters : {};
    _.defaults(parameters, { delay: 1500 , every: 200, pause: 30000, maxErrors : 9, limit: this.limit });
    // every N requests we take a pause
    var delay = this.iteration === 0 ? 0 : this.iteration%parameters.every !== 0 ? parameters.delay : parameters.pause;
    return Promise.delay(delay)
        .then(this.get.bind(this))
        .then(function (results) {
            // reset pause multiplier when we can execute requests again
            that.parseErrorsMultiplier = 0;
            return results;
        })
        // If ParseError, we assume that this is 403 forbidden HTML page, caused by "Too many requests". Just take a pause and retry.
        .catch(Exceptions.ParseError, function () {
            // Every consecutive ParseError makes delay befor new request longer. Otherwise we will never reach the end.
            that.parseErrorsMultiplier++;
            // When delay time is beyond reasonable, throw exception.
            if(that.parseErrorsMultiplier > parameters.maxErrors)
                throw new Exceptions.RequestsLimitError;
            return Promise.resolve([]).delay(parameters.pause * that.parseErrorsMultiplier)
        })
        .then(function (response) {
            var results = response.map(that.map);
            if(_.isFunction(that.reduce))
                that.allResults = that.reduce(that.allResults, results);
            that._handleInfinityListBug(response, results);

            that.emit('data', results);
            var exceedLimit = false;

            if ( (parameters.limit && that.allResults.length > parameters.limit) || that._stopAll === true)
                exceedLimit = true;

            if (that.isMoreAvailable() && !exceedLimit) {
                that.iteration++;
                return that.all(parameters);
            } else {
                that.iteration = 0;
                that.emit('end', that.allResults);
                return that.allResults;
            }
        })

};
/* This function is designed for response realtime processing when .all method is in progress.
* This is useful when you are collecting real large amount of data, and you have not so much RAM.
* The return of this function will be saved in RAM  instead of original response.
* For example, if you need only ids, you can redefine this method in your feed instance like this
* const feed = new AccountFollowingFeed();
* feed.map = follower => follower.id;
* feed.all();
* */
FeedBase.prototype.map = function (item) {
  return item;
}
/* User can redefine this method too. For example, if user dont need to reduce responses at all, it
 * can be defined as false, or as empty function. Just for example - you need to calculate followers amount:
  const feed = new Client.Feed.AccountFollowers(session, '1571836453')
  feed.allResults = 0; // Initial value. Empty array by default.
  feed.reduce = (accumulator, chunk) => accumulator + chunk.length; // accumulator is feed.allResults
  feed.on('data', results => console.log(feed.allResults)) // here will be total amount of collected items every request.
  console.log( await feed.all() ) // here will be total amount of collected items in the end.
 * */
FeedBase.prototype.reduce = function (accumulator, response) {
    return accumulator.concat(response);
}
/* Instagram backend has a bug. Sometimes it response with next_max_id cursor, but actually there is no next subjects to
* request. And when we trying to get next data, we got the same as previous. And so on to infinity.
* to prevent such behaviour, we assume that every element in this.allResults must be unique.
* And if it is not - we stop collecting.
* To see this bug try to collect AccountFollowingFeed of id 1571836453 */

FeedBase.prototype._handleInfinityListBug = function(response, results){
    var that = this;
    /* For RAM economy we can store only 2 last results, not all. So every 2 iterations we release memory  */
    if(this.iteration % 2 === 0){
      this.allResultsMap = {};
      this._allResultsLentgh = 0;
    }
    this._allResultsLentgh += response.length;

    response.forEach( function (result) {
        that.allResultsMap[result.id] = undefined;
    });

    if (_.keys(this.allResultsMap).length !== this._allResultsLentgh)
      this.stop();
};

// Stops collecting results with .all() method. Will wait unfinished request.
FeedBase.prototype.stop = function () {
    this._stopAll = true;
};

FeedBase.prototype.setCursor = function (cursor) {
    this.cursor = cursor;
};

FeedBase.prototype.getCursor = function () {
    return this.cursor;
};

FeedBase.prototype.isMoreAvailable = function() {
    return !!this.moreAvailable;
};

FeedBase.prototype.allSafe = function (parameters, timeout) {
    var that = this;
    return this.all(parameters).timeout(timeout || this.timeout)
        .catch(Promise.TimeoutError, function (reason) {
            that.stop();
            throw reason;
        })
};

module.exports = FeedBase;
<commit_msg>Store its own total collected number, do not rely on allResults array, because it may not store values.<commit_after>var util = require('util');
var _ = require('underscore');
var Promise = require('bluebird');
var Exceptions = require('../exceptions');
var EventEmitter = require('events').EventEmitter;

function FeedBase(session) {
    this.session = session;
    this.allResults=[];
    this.totalCollected = 0;
    this.cursor = null;
    this.moreAvailable = null;
    this.iteration = 0;
    // Pause multiplier.
    this.parseErrorsMultiplier = 0;
}
util.inherits(FeedBase, EventEmitter);

FeedBase.prototype.all = function (parameters) {
    var that = this;
    parameters = _.isObject(parameters) ? parameters : {};
    _.defaults(parameters, { delay: 1500 , every: 200, pause: 30000, maxErrors : 9, limit: this.limit });
    // every N requests we take a pause
    var delay = this.iteration === 0 ? 0 : this.iteration%parameters.every !== 0 ? parameters.delay : parameters.pause;
    return Promise.delay(delay)
        .then(this.get.bind(this))
        .then(function (results) {
            // reset pause multiplier when we can execute requests again
            that.parseErrorsMultiplier = 0;
            return results;
        })
        // If ParseError, we assume that this is 403 forbidden HTML page, caused by "Too many requests". Just take a pause and retry.
        .catch(Exceptions.ParseError, function () {
            // Every consecutive ParseError makes delay befor new request longer. Otherwise we will never reach the end.
            that.parseErrorsMultiplier++;
            // When delay time is beyond reasonable, throw exception.
            if(that.parseErrorsMultiplier > parameters.maxErrors)
                throw new Exceptions.RequestsLimitError;
            return Promise.resolve([]).delay(parameters.pause * that.parseErrorsMultiplier)
        })
        .then(function (response) {
            var results = response.map(that.map);
            if(_.isFunction(that.reduce))
                that.allResults = that.reduce(that.allResults, results);
            that.totalCollected += response.length;

            that._handleInfinityListBug(response, results);

            that.emit('data', results);
            var exceedLimit = false;

            if ( (parameters.limit && that.totalCollected > parameters.limit) || that._stopAll === true)
                exceedLimit = true;

            if (that.isMoreAvailable() && !exceedLimit) {
                that.iteration++;
                return that.all(parameters);
            } else {
                that.iteration = 0;
                that.emit('end', that.allResults);
                return that.allResults;
            }
        })

};
/* This function is designed for response realtime processing when .all method is in progress.
* This is useful when you are collecting real large amount of data, and you have not so much RAM.
* The return of this function will be saved in RAM  instead of original response.
* For example, if you need only ids, you can redefine this method in your feed instance like this
* const feed = new AccountFollowingFeed();
* feed.map = follower => follower.id;
* feed.all();
* */
FeedBase.prototype.map = function (item) {
  return item;
}
/* User can redefine this method too. For example, if user dont need to reduce responses at all, it
 * can be defined as false, or as empty function. Just for example - you need to calculate followers amount:
  const feed = new Client.Feed.AccountFollowers(session, '1571836453')
  feed.allResults = 0; // Initial value. Empty array by default.
  feed.reduce = (accumulator, chunk) => accumulator + chunk.length; // accumulator is feed.allResults
  feed.on('data', results => console.log(feed.allResults)) // here will be total amount of collected items every request.
  console.log( await feed.all() ) // here will be total amount of collected items in the end.
 * */
FeedBase.prototype.reduce = function (accumulator, response) {
    return accumulator.concat(response);
}
/* Instagram backend has a bug. Sometimes it response with next_max_id cursor, but actually there is no next subjects to
* request. And when we trying to get next data, we got the same as previous. And so on to infinity.
* to prevent such behaviour, we assume that every element in this.allResults must be unique.
* And if it is not - we stop collecting.
* To see this bug try to collect AccountFollowingFeed of id 1571836453 */

FeedBase.prototype._handleInfinityListBug = function(response, results){
    var that = this;
    /* For RAM economy we can store only 2 last results, not all. So every 2 iterations we release memory  */
    if(this.iteration % 2 === 0){
      this.allResultsMap = {};
      this._allResultsLentgh = 0;
    }
    this._allResultsLentgh += response.length;

    response.forEach( function (result) {
        that.allResultsMap[result.id] = undefined;
    });

    if (_.keys(this.allResultsMap).length !== this._allResultsLentgh)
      this.stop();
};

// Stops collecting results with .all() method. Will wait unfinished request.
FeedBase.prototype.stop = function () {
    this._stopAll = true;
};

FeedBase.prototype.setCursor = function (cursor) {
    this.cursor = cursor;
};

FeedBase.prototype.getCursor = function () {
    return this.cursor;
};

FeedBase.prototype.isMoreAvailable = function() {
    return !!this.moreAvailable;
};

FeedBase.prototype.allSafe = function (parameters, timeout) {
    var that = this;
    return this.all(parameters).timeout(timeout || this.timeout)
        .catch(Promise.TimeoutError, function (reason) {
            that.stop();
            throw reason;
        })
};

module.exports = FeedBase;
<|endoftext|>