<commit_before>
//Adds new Cross Spectrum Tab Panel
function addXsTabPanel(navBarList, panelContainer, plotConfigs, projectConfigs, id, navItemClass){
  return new XSTabPanel(!isNull(id) ? id : "Tab_" + tabPanels.length,
                        "TabPanelTemplate",
                        !isNull(navItemClass) ? navItemClass : "NavItem_" + tabPanels.length,
                        theService, navBarList, panelContainer, plotConfigs, projectConfigs);
}

//Subscribes the load workspace XSTabPanel function
tabPanelsLoadFns["XSTabPanel"] = function (tabConfig) {
  //Creates new CrossSpectra Tab Panel
  return addXsTabPanel($("#navbar").find("ul").first(),
                      $(".daveContainer"),
                      tabConfig.plotConfigs,
                      [],
                      tabConfig.id,
                      tabConfig.navItemClass);
}

//Cross Spectrum Tab Panel
function XSTabPanel (id, classSelector, navItemClass, service, navBarList, panelContainer, plotConfigs, projectConfigs) {

  var currentObj = this;
  tabPanels.push(this); // Insert on tabPanels here for preparing access to getTabForSelector from plots

  WfTabPanel.call(this, id, classSelector, navItemClass, service, navBarList, panelContainer);

  //XSTabPanel METHODS:
  this.getPageName = function () {
    return "CrossSpectraPage";
  }

  this.getXSDataFromServer = function (paramsData) {

    log("XSTabPanel getXSDataFromServer...");

    if (!isNull(currentObj.currentRequest) && !isNull(currentObj.currentRequest.abort)) {
      currentObj.currentRequest.abort();
    }

    currentObj.outputPanel.setPlotsReadyState(false);

    currentObj.currentRequest = currentObj.service.request_cross_spectrum(paramsData, function( jsdata ) {

      if (!isNull(jsdata.abort)){
        log("Current request aborted, XSTabPanel: " + currentObj.id);
        if (jsdata.statusText == "error"){
          //If abort cause is because python server died
          currentObj.outputPanel.setPlotsReadyState(true);
        }
        return; //Comes from request abort call.
      }

      log("XSData received!, XSTabPanel: " + currentObj.id);
      data = JSON.parse(jsdata);

      if (isNull(data)) {
        log("onPlotDataReceived wrong data!, XSTabPanel: " + currentObj.id);
        currentObj.outputPanel.setPlotsReadyState(true);
        return;

      } else if (!isNull(data.error)) {
        currentObj.xsPlot.showWarn(data.error);
        log("onPlotDataReceived data error: " + data.error + ", XSTabPanel: " + currentObj.id);
        currentObj.outputPanel.setPlotsReadyState(true);
        return;

      } else {

        //Prepares Cross Spectrum Plot data and sends it to xsPlot
        var xsPlot = currentObj.outputPanel.plots[currentObj.xsPlotIdx];
        if (xsPlot.isVisible) {
          //PDSPlot Params req: freq, power, duration, warnmsg
          //Clones array data for allowing changes on data withot affecting othe plotsdata
          xsPlot.setData($.extend(true, [], [ data[0], data[1], data[4], data[5] ]));
        }

        //Prepares TimeLag Plot data and sends it to timeLagPlot
        var timeLagPlot = currentObj.outputPanel.plots[currentObj.timeLagPlotIdx];
        if (timeLagPlot.isVisible) {
          //Lightcurve Params req: freq, time_lag, error_values, gti_start, gti_stop
          timeLagPlot.setData($.extend(true, [], [ data[0],
                                                  { values: (data[2].values.length > 0) ? data[2].values[0] : [] },
                                                  { values: (data[2].values.length > 1) ? data[2].values[1] : [] },
                                                  [], [] ]));
        }

        //Prepares Coherence Plot data and sends it to coherencePlot
        var coherencePlot = currentObj.outputPanel.plots[currentObj.coherencePlotIdx];
        if (coherencePlot.isVisible) {
          //ColorLc Params req: freq, color_A, color_B, gti_start, gti_stop
          coherencePlot.setData($.extend(true, [], [ data[0],
                                                    { values: (data[3].values.length > 0) ? data[3].values[0] : [] },
                                                    { values: (data[3].values.length > 1) ? data[3].values[1] : [] },
                                                    [], [] ]));
        }

      }
    });

  };

  this.getConfig = function () {
    return { type: "XSTabPanel",
             id: this.id,
             navItemClass: this.navItemClass,
             plotConfigs: this.plotConfigs,
             projectConfig: this.projectConfig.getConfig(),
             outputPanelConfig: this.outputPanel.getConfig(),
             plotDefaultConfig: this.plotDefaultConfig
           };
  }

  this.setConfig = function (tabConfig, callback) {
    log("setConfig for tab " + this.id);

    if (!isNull(tabConfig.plotDefaultConfig)){
      this.plotDefaultConfig = $.extend(true, {}, tabConfig.plotDefaultConfig);
    }
    this.projectConfig = $.extend( this.projectConfig, tabConfig.projectConfig );
    this.createPlots();
    this.outputPanel.setConfig(tabConfig.outputPanelConfig);

    callback();
  }

  this.createPlots = function () {
    if (this.plotConfigs.length == 2) {

      //Adds Cross Spectrum Plot to outputPanel
      var xsPlot = new PDSPlot(
                                this.id + "_xs_" + (new Date()).getTime(),
                                {
                                  filename1: this.plotConfigs[0].filename,
                                  bck_filename1: this.plotConfigs[0].bck_filename,
                                  gti_filename1: this.plotConfigs[0].gti_filename,
                                  filters1: this.plotConfigs[0].filters,
                                  axis1: this.plotConfigs[0].axis,
                                  dt1: this.plotConfigs[0].dt,

                                  filename2: this.plotConfigs[1].filename,
                                  bck_filename2: this.plotConfigs[1].bck_filename,
                                  gti_filename2: this.plotConfigs[1].gti_filename,
                                  filters2: this.plotConfigs[1].filters,
                                  axis2: this.plotConfigs[1].axis,
                                  dt2: this.plotConfigs[1].dt,

                                  styles: { type: "ligthcurve",
                                            labels: ["Frequency (Hz)", "Power"],
                                            title: "Cross Spectrum" }
                                },
                                this.getXSDataFromServer, //Only XSpectra plot triggers receive new data from server
                                this.outputPanel.onFiltersChangedFromPlot,
                                this.outputPanel.onPlotReady,
                                null,
                                "fullWidth",
                                false,
                                this.projectConfig
                              );
      this.xsPlotIdx = this.outputPanel.plots.length;
      this.addPlot(xsPlot, false);

      //Adds TimeLag Plot to outputPanel
      var timeLagPlot = new TimingPlot(
                                this.id + "_timelag_" + (new Date()).getTime(),
                                {
                                  styles: { type: "ligthcurve",
                                            labels: ["Frequency (Hz)", "Time(s)"],
                                            title: "Frequency Lag" }
                                },
                                null,
                                this.outputPanel.onFiltersChangedFromPlot,
                                this.outputPanel.onPlotReady,
                                null,
                                "",
                                false
                              );
      this.timeLagPlotIdx = this.outputPanel.plots.length;
      this.addPlot(timeLagPlot, false);

      //Adds Coherence Plot to outputPanel
      var coherencePlot = new TimingPlot(
                                this.id + "_coherence_" + (new Date()).getTime(),
                                {
                                  styles: { type: "ligthcurve",
                                            labels: ["Frequency (Hz)", "Coherence"],
                                            title: "Coherence" },
                                },
                                null,
                                this.outputPanel.onFiltersChangedFromPlot,
                                this.outputPanel.onPlotReady,
                                null,
                                "",
                                false
                              );
      this.coherencePlotIdx = this.outputPanel.plots.length;
      this.addPlot(coherencePlot, false);

      //Request plot data after all plots were added
      xsPlot.onDatasetValuesChanged(this.outputPanel.getFilters());
    }
  }

  //Set the selected plot configs
  this.plotConfigs = plotConfigs;
  this.xsPlotIdx = -1;
  this.timeLagPlotIdx = -1;
  this.coherencePlotIdx = -1;

  this.setTitle("XSpectrum");

  //Preapares XS toolpanel data
  this.wfSelector.find(".loadBtn").html('Analyze');
  this.prepareTabButton(this.wfSelector.find(".styleBtn"));
  this.wfSelector.find(".styleBtn").show();
  this.toolPanel.styleContainer.removeClass("hidden");
  this.toolPanel.clearFileSelectors();
  for (i in this.plotConfigs){
    var plotConfig = this.plotConfigs[i];
    var label = isNull(plotConfig.styles.title) ? "File " + i + ":" : plotConfig.styles.title;
    this.toolPanel.addSelectedFile(label, getFilename(plotConfig.filename));
  }

  if (projectConfigs.length > 0){
    this.projectConfig.updateFromProjectConfigs(projectConfigs);
    this.createPlots();
  }

  log("XSTabPanel ready! id: " + this.id);
  return this;
}
<commit_msg>DAVE-346: Tab name XSpectrum -> Spectral Timing<commit_after>
//Adds new Cross Spectrum Tab Panel
function addXsTabPanel(navBarList, panelContainer, plotConfigs, projectConfigs, id, navItemClass){
  return new XSTabPanel(!isNull(id) ? id : "Tab_" + tabPanels.length,
                        "TabPanelTemplate",
                        !isNull(navItemClass) ? navItemClass : "NavItem_" + tabPanels.length,
                        theService, navBarList, panelContainer, plotConfigs, projectConfigs);
}

//Subscribes the load workspace XSTabPanel function
tabPanelsLoadFns["XSTabPanel"] = function (tabConfig) {
  //Creates new CrossSpectra Tab Panel
  return addXsTabPanel($("#navbar").find("ul").first(),
                      $(".daveContainer"),
                      tabConfig.plotConfigs,
                      [],
                      tabConfig.id,
                      tabConfig.navItemClass);
}

//Cross Spectrum Tab Panel
function XSTabPanel (id, classSelector, navItemClass, service, navBarList, panelContainer, plotConfigs, projectConfigs) {

  var currentObj = this;
  tabPanels.push(this); // Insert on tabPanels here for preparing access to getTabForSelector from plots

  WfTabPanel.call(this, id, classSelector, navItemClass, service, navBarList, panelContainer);

  //XSTabPanel METHODS:
  this.getPageName = function () {
    return "CrossSpectraPage";
  }

  this.getXSDataFromServer = function (paramsData) {

    log("XSTabPanel getXSDataFromServer...");

    if (!isNull(currentObj.currentRequest) && !isNull(currentObj.currentRequest.abort)) {
      currentObj.currentRequest.abort();
    }

    currentObj.outputPanel.setPlotsReadyState(false);

    currentObj.currentRequest = currentObj.service.request_cross_spectrum(paramsData, function( jsdata ) {

      if (!isNull(jsdata.abort)){
        log("Current request aborted, XSTabPanel: " + currentObj.id);
        if (jsdata.statusText == "error"){
          //If abort cause is because python server died
          currentObj.outputPanel.setPlotsReadyState(true);
        }
        return; //Comes from request abort call.
      }

      log("XSData received!, XSTabPanel: " + currentObj.id);
      data = JSON.parse(jsdata);

      if (isNull(data)) {
        log("onPlotDataReceived wrong data!, XSTabPanel: " + currentObj.id);
        currentObj.outputPanel.setPlotsReadyState(true);
        return;

      } else if (!isNull(data.error)) {
        currentObj.xsPlot.showWarn(data.error);
        log("onPlotDataReceived data error: " + data.error + ", XSTabPanel: " + currentObj.id);
        currentObj.outputPanel.setPlotsReadyState(true);
        return;

      } else {

        //Prepares Cross Spectrum Plot data and sends it to xsPlot
        var xsPlot = currentObj.outputPanel.plots[currentObj.xsPlotIdx];
        if (xsPlot.isVisible) {
          //PDSPlot Params req: freq, power, duration, warnmsg
          //Clones array data for allowing changes on data withot affecting othe plotsdata
          xsPlot.setData($.extend(true, [], [ data[0], data[1], data[4], data[5] ]));
        }

        //Prepares TimeLag Plot data and sends it to timeLagPlot
        var timeLagPlot = currentObj.outputPanel.plots[currentObj.timeLagPlotIdx];
        if (timeLagPlot.isVisible) {
          //Lightcurve Params req: freq, time_lag, error_values, gti_start, gti_stop
          timeLagPlot.setData($.extend(true, [], [ data[0],
                                                  { values: (data[2].values.length > 0) ? data[2].values[0] : [] },
                                                  { values: (data[2].values.length > 1) ? data[2].values[1] : [] },
                                                  [], [] ]));
        }

        //Prepares Coherence Plot data and sends it to coherencePlot
        var coherencePlot = currentObj.outputPanel.plots[currentObj.coherencePlotIdx];
        if (coherencePlot.isVisible) {
          //ColorLc Params req: freq, color_A, color_B, gti_start, gti_stop
          coherencePlot.setData($.extend(true, [], [ data[0],
                                                    { values: (data[3].values.length > 0) ? data[3].values[0] : [] },
                                                    { values: (data[3].values.length > 1) ? data[3].values[1] : [] },
                                                    [], [] ]));
        }

      }
    });

  };

  this.getConfig = function () {
    return { type: "XSTabPanel",
             id: this.id,
             navItemClass: this.navItemClass,
             plotConfigs: this.plotConfigs,
             projectConfig: this.projectConfig.getConfig(),
             outputPanelConfig: this.outputPanel.getConfig(),
             plotDefaultConfig: this.plotDefaultConfig
           };
  }

  this.setConfig = function (tabConfig, callback) {
    log("setConfig for tab " + this.id);

    if (!isNull(tabConfig.plotDefaultConfig)){
      this.plotDefaultConfig = $.extend(true, {}, tabConfig.plotDefaultConfig);
    }
    this.projectConfig = $.extend( this.projectConfig, tabConfig.projectConfig );
    this.createPlots();
    this.outputPanel.setConfig(tabConfig.outputPanelConfig);

    callback();
  }

  this.createPlots = function () {
    if (this.plotConfigs.length == 2) {

      //Adds Cross Spectrum Plot to outputPanel
      var xsPlot = new PDSPlot(
                                this.id + "_xs_" + (new Date()).getTime(),
                                {
                                  filename1: this.plotConfigs[0].filename,
                                  bck_filename1: this.plotConfigs[0].bck_filename,
                                  gti_filename1: this.plotConfigs[0].gti_filename,
                                  filters1: this.plotConfigs[0].filters,
                                  axis1: this.plotConfigs[0].axis,
                                  dt1: this.plotConfigs[0].dt,

                                  filename2: this.plotConfigs[1].filename,
                                  bck_filename2: this.plotConfigs[1].bck_filename,
                                  gti_filename2: this.plotConfigs[1].gti_filename,
                                  filters2: this.plotConfigs[1].filters,
                                  axis2: this.plotConfigs[1].axis,
                                  dt2: this.plotConfigs[1].dt,

                                  styles: { type: "ligthcurve",
                                            labels: ["Frequency (Hz)", "Power"],
                                            title: "Cross Spectrum" }
                                },
                                this.getXSDataFromServer, //Only XSpectra plot triggers receive new data from server
                                this.outputPanel.onFiltersChangedFromPlot,
                                this.outputPanel.onPlotReady,
                                null,
                                "fullWidth",
                                false,
                                this.projectConfig
                              );
      this.xsPlotIdx = this.outputPanel.plots.length;
      this.addPlot(xsPlot, false);

      //Adds TimeLag Plot to outputPanel
      var timeLagPlot = new TimingPlot(
                                this.id + "_timelag_" + (new Date()).getTime(),
                                {
                                  styles: { type: "ligthcurve",
                                            labels: ["Frequency (Hz)", "Time(s)"],
                                            title: "Frequency Lag" }
                                },
                                null,
                                this.outputPanel.onFiltersChangedFromPlot,
                                this.outputPanel.onPlotReady,
                                null,
                                "",
                                false
                              );
      this.timeLagPlotIdx = this.outputPanel.plots.length;
      this.addPlot(timeLagPlot, false);

      //Adds Coherence Plot to outputPanel
      var coherencePlot = new TimingPlot(
                                this.id + "_coherence_" + (new Date()).getTime(),
                                {
                                  styles: { type: "ligthcurve",
                                            labels: ["Frequency (Hz)", "Coherence"],
                                            title: "Coherence" },
                                },
                                null,
                                this.outputPanel.onFiltersChangedFromPlot,
                                this.outputPanel.onPlotReady,
                                null,
                                "",
                                false
                              );
      this.coherencePlotIdx = this.outputPanel.plots.length;
      this.addPlot(coherencePlot, false);

      //Request plot data after all plots were added
      xsPlot.onDatasetValuesChanged(this.outputPanel.getFilters());
    }
  }

  //Set the selected plot configs
  this.plotConfigs = plotConfigs;
  this.xsPlotIdx = -1;
  this.timeLagPlotIdx = -1;
  this.coherencePlotIdx = -1;

  this.setTitle("Spectral Timing");

  //Preapares XS toolpanel data
  this.wfSelector.find(".loadBtn").html('Analyze');
  this.prepareTabButton(this.wfSelector.find(".styleBtn"));
  this.wfSelector.find(".styleBtn").show();
  this.toolPanel.styleContainer.removeClass("hidden");
  this.toolPanel.clearFileSelectors();
  for (i in this.plotConfigs){
    var plotConfig = this.plotConfigs[i];
    var label = isNull(plotConfig.styles.title) ? "File " + i + ":" : plotConfig.styles.title;
    this.toolPanel.addSelectedFile(label, getFilename(plotConfig.filename));
  }

  if (projectConfigs.length > 0){
    this.projectConfig.updateFromProjectConfigs(projectConfigs);
    this.createPlots();
  }

  log("XSTabPanel ready! id: " + this.id);
  return this;
}
<|endoftext|>


<commit_before>const { Extractor } = require('./../utils')

const pikabu = new Extractor((url) => url.startsWith('http://pikabu.ru'))

pikabu.title(($) => $('.page-story .story .story__main .story__header.first_story .story__header-title a.story__title-link').text())
pikabu.authorName(($) => $('.page-story .story .story__main .story__header.first_story .story__header-additional .story__header-additional-wrapper a.story__author').text())
pikabu.authorUrl(($, url) => $('.page-story .story .story__main .story__header.first_story .story__header-additional .story__header-additional-wrapper a.story__author').attr('href'))
pikabu.content(($) => $('.page-story .story .story__main .b-story__content.b-story-blocks .b-story-block'))

module.exports = pikabu
<commit_msg>LICENSE <commit_after>const { Extractor } = require ( './../utils' )
const
pikabu = new Extractor ((url)  =>  url.startsWith  ('http://pikabu.ru'
 ))
      pikabu.title (($) => $('.page-story .story .story__main .story__header.first_story .story__header-title a.story__title-link').text())
pikabu.authorName(($) => $('.page-story .story .story__main .story__header.first_story .story__header-additional .story__header-additional-             wrapper a.story__author').text ())
pikabu.authorUrl (($, url) => $('.page-story.story .story__main .story__header.first_story .story__header-additional .story__header-additional-wrapper a.story__author').attr( 'href' ))
pikabu.content (($) => $('.page-story .story .story__main .b-story__content.b-story-blocks .b-story-block' ))

module.exports = pikabu

<|endoftext|>


<commit_before>// Copyright (c) 2012 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.

// Custom binding for the fileManagerPrivate API.

// Bindings
var binding = require('binding').Binding.create('fileManagerPrivate');
var eventBindings = require('event_bindings');

// Natives
var fileManagerPrivateNatives = requireNative('file_manager_private');
var fileBrowserHandlerNatives = requireNative('file_browser_handler');

// Internals
var fileManagerPrivateInternal =
    require('binding').Binding.create('fileManagerPrivateInternal').generate();

// Shorthands
var GetFileSystem = fileManagerPrivateNatives.GetFileSystem;
var GetExternalFileEntry = fileBrowserHandlerNatives.GetExternalFileEntry;

binding.registerCustomHook(function(bindingsAPI) {
  var apiFunctions = bindingsAPI.apiFunctions;

  apiFunctions.setCustomCallback('searchDrive',
      function(name, request, callback, response) {
    if (response && !response.error && response.entries) {
      response.entries = response.entries.map(function(entry) {
        return GetExternalFileEntry(entry);
      });
    }

    // So |callback| doesn't break if response is not defined.
    if (!response)
      response = {};

    if (callback)
      callback(response.entries, response.nextFeed);
  });

  apiFunctions.setCustomCallback('searchDriveMetadata',
      function(name, request, callback, response) {
    if (response && !response.error) {
      for (var i = 0; i < response.length; i++) {
        response[i].entry =
            GetExternalFileEntry(response[i].entry);
      }
    }

    // So |callback| doesn't break if response is not defined.
    if (!response)
      response = {};

    if (callback)
      callback(response);
  });

  apiFunctions.setHandleRequest('resolveIsolatedEntries',
                                function(entries, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.resolveIsolatedEntries(urls, function(
        entryDescriptions) {
      callback(entryDescriptions.map(function(description) {
        return GetExternalFileEntry(description);
      }));
    });
  });

  apiFunctions.setHandleRequest('getEntryProperties',
                                function(entries, names, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.getEntryProperties(urls, names, callback);
  });

  apiFunctions.setHandleRequest('addFileWatch', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.addFileWatch(url, callback);
  });

  apiFunctions.setHandleRequest('removeFileWatch', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.removeFileWatch(url, callback);
  });

  apiFunctions.setHandleRequest('getEntryActions', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getEntryActions(url, callback);
  });

  apiFunctions.setHandleRequest('executeEntryAction', function(
        entry, actionId, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.executeEntryAction(url, actionId, callback);
  });

  apiFunctions.setHandleRequest('computeChecksum', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.computeChecksum(url, callback);
  });

  apiFunctions.setHandleRequest('getMimeType', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getMimeType(url, callback);
  });

  apiFunctions.setHandleRequest('pinDriveFile', function(entry, pin, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.pinDriveFile(url, pin, callback);
  });

  apiFunctions.setHandleRequest('executeTask',
      function(taskId, entries, callback) {
        var urls = entries.map(function(entry) {
          return fileBrowserHandlerNatives.GetEntryURL(entry);
        });
        fileManagerPrivateInternal.executeTask(taskId, urls, callback);
      });

  apiFunctions.setHandleRequest('setDefaultTask',
      function(taskId, entries, mimeTypes, callback) {
        var urls = entries.map(function(entry) {
          return fileBrowserHandlerNatives.GetEntryURL(entry);
        });
        fileManagerPrivateInternal.setDefaultTask(
            taskId, urls, mimeTypes, callback);
      });

  apiFunctions.setHandleRequest('getFileTasks', function(entries, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.getFileTasks(urls, callback);
  });

  apiFunctions.setHandleRequest('getShareUrl', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getShareUrl(url, callback);
  });

  apiFunctions.setHandleRequest('getDownloadUrl', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getDownloadUrl(url, callback);
  });

  apiFunctions.setHandleRequest('requestDriveShare', function(
        entry, shareType, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.requestDriveShare(url, shareType, callback);
  });

  apiFunctions.setHandleRequest('setEntryTag', function(
        entry, visibility, key, value, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.setEntryTag(
        url, visibility, key, value, callback);
  });

  apiFunctions.setHandleRequest('cancelFileTransfers', function(
        entries, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.cancelFileTransfers(entry);
    });
    fileManagerPrivateInternal.cancelFileTransfers(urls, callback);
  });

  apiFunctions.setHandleRequest('startCopy', function(
        entry, parentEntry, newName, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    var parentUrl = fileBrowserHandlerNatives.GetEntryURL(parentEntry);
    fileManagerPrivateInternal.startCopy(
        url, parentUrl, newName, callback);
  });

  apiFunctions.setHandleRequest('zipSelection', function(
        parentEntry, entries, destName, callback) {
    var parentUrl = fileBrowserHandlerNatives.GetEntryURL(parentEntry);
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.cancelFileTransfers(entry);
    });
    fileManagerPrivateInternal.zipSelection(
        parentUrl, urls, destName, callback);
  });

  apiFunctions.setHandleRequest('validatePathNameLength', function(
        entry, name, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.validatePathNameLength(url, name, callback);
  });
});

eventBindings.registerArgumentMassager(
    'fileManagerPrivate.onDirectoryChanged', function(args, dispatch) {
  // Convert the entry arguments into a real Entry object.
  args[0].entry = GetExternalFileEntry(args[0].entry);
  dispatch(args);
});

exports.binding = binding.generate();
<commit_msg>Fix zipping in Files app.<commit_after>// Copyright (c) 2012 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.

// Custom binding for the fileManagerPrivate API.

// Bindings
var binding = require('binding').Binding.create('fileManagerPrivate');
var eventBindings = require('event_bindings');

// Natives
var fileManagerPrivateNatives = requireNative('file_manager_private');
var fileBrowserHandlerNatives = requireNative('file_browser_handler');

// Internals
var fileManagerPrivateInternal =
    require('binding').Binding.create('fileManagerPrivateInternal').generate();

// Shorthands
var GetFileSystem = fileManagerPrivateNatives.GetFileSystem;
var GetExternalFileEntry = fileBrowserHandlerNatives.GetExternalFileEntry;

binding.registerCustomHook(function(bindingsAPI) {
  var apiFunctions = bindingsAPI.apiFunctions;

  apiFunctions.setCustomCallback('searchDrive',
      function(name, request, callback, response) {
    if (response && !response.error && response.entries) {
      response.entries = response.entries.map(function(entry) {
        return GetExternalFileEntry(entry);
      });
    }

    // So |callback| doesn't break if response is not defined.
    if (!response)
      response = {};

    if (callback)
      callback(response.entries, response.nextFeed);
  });

  apiFunctions.setCustomCallback('searchDriveMetadata',
      function(name, request, callback, response) {
    if (response && !response.error) {
      for (var i = 0; i < response.length; i++) {
        response[i].entry =
            GetExternalFileEntry(response[i].entry);
      }
    }

    // So |callback| doesn't break if response is not defined.
    if (!response)
      response = {};

    if (callback)
      callback(response);
  });

  apiFunctions.setHandleRequest('resolveIsolatedEntries',
                                function(entries, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.resolveIsolatedEntries(urls, function(
        entryDescriptions) {
      callback(entryDescriptions.map(function(description) {
        return GetExternalFileEntry(description);
      }));
    });
  });

  apiFunctions.setHandleRequest('getEntryProperties',
                                function(entries, names, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.getEntryProperties(urls, names, callback);
  });

  apiFunctions.setHandleRequest('addFileWatch', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.addFileWatch(url, callback);
  });

  apiFunctions.setHandleRequest('removeFileWatch', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.removeFileWatch(url, callback);
  });

  apiFunctions.setHandleRequest('getEntryActions', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getEntryActions(url, callback);
  });

  apiFunctions.setHandleRequest('executeEntryAction', function(
        entry, actionId, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.executeEntryAction(url, actionId, callback);
  });

  apiFunctions.setHandleRequest('computeChecksum', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.computeChecksum(url, callback);
  });

  apiFunctions.setHandleRequest('getMimeType', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getMimeType(url, callback);
  });

  apiFunctions.setHandleRequest('pinDriveFile', function(entry, pin, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.pinDriveFile(url, pin, callback);
  });

  apiFunctions.setHandleRequest('executeTask',
      function(taskId, entries, callback) {
        var urls = entries.map(function(entry) {
          return fileBrowserHandlerNatives.GetEntryURL(entry);
        });
        fileManagerPrivateInternal.executeTask(taskId, urls, callback);
      });

  apiFunctions.setHandleRequest('setDefaultTask',
      function(taskId, entries, mimeTypes, callback) {
        var urls = entries.map(function(entry) {
          return fileBrowserHandlerNatives.GetEntryURL(entry);
        });
        fileManagerPrivateInternal.setDefaultTask(
            taskId, urls, mimeTypes, callback);
      });

  apiFunctions.setHandleRequest('getFileTasks', function(entries, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.getFileTasks(urls, callback);
  });

  apiFunctions.setHandleRequest('getShareUrl', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getShareUrl(url, callback);
  });

  apiFunctions.setHandleRequest('getDownloadUrl', function(entry, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.getDownloadUrl(url, callback);
  });

  apiFunctions.setHandleRequest('requestDriveShare', function(
        entry, shareType, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.requestDriveShare(url, shareType, callback);
  });

  apiFunctions.setHandleRequest('setEntryTag', function(
        entry, visibility, key, value, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.setEntryTag(
        url, visibility, key, value, callback);
  });

  apiFunctions.setHandleRequest('cancelFileTransfers', function(
        entries, callback) {
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.cancelFileTransfers(urls, callback);
  });

  apiFunctions.setHandleRequest('startCopy', function(
        entry, parentEntry, newName, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    var parentUrl = fileBrowserHandlerNatives.GetEntryURL(parentEntry);
    fileManagerPrivateInternal.startCopy(
        url, parentUrl, newName, callback);
  });

  apiFunctions.setHandleRequest('zipSelection', function(
        parentEntry, entries, destName, callback) {
    var parentUrl = fileBrowserHandlerNatives.GetEntryURL(parentEntry);
    var urls = entries.map(function(entry) {
      return fileBrowserHandlerNatives.GetEntryURL(entry);
    });
    fileManagerPrivateInternal.zipSelection(
        parentUrl, urls, destName, callback);
  });

  apiFunctions.setHandleRequest('validatePathNameLength', function(
        entry, name, callback) {
    var url = fileBrowserHandlerNatives.GetEntryURL(entry);
    fileManagerPrivateInternal.validatePathNameLength(url, name, callback);
  });
});

eventBindings.registerArgumentMassager(
    'fileManagerPrivate.onDirectoryChanged', function(args, dispatch) {
  // Convert the entry arguments into a real Entry object.
  args[0].entry = GetExternalFileEntry(args[0].entry);
  dispatch(args);
});

exports.binding = binding.generate();
<|endoftext|>


<commit_before>function staticPageEditor(collectionId, data) {

  var newLinks = [], newFiles = [];
  var setActiveTab, getActiveTab;
  var renameUri = false;
  var timeoutId;
  $(".edit-accordion").on('accordionactivate', function (event, ui) {
    setActiveTab = $(".edit-accordion").accordion("option", "active");
    if (setActiveTab !== false) {
      Florence.globalVars.activeTab = setActiveTab;
    }
  });

  getActiveTab = Florence.globalVars.activeTab;
  accordion(getActiveTab);

  $("#metadata-ad").remove();
  $("#metadata-f").remove();
  $("#metadata-md").remove();
  $("#metadata-q").remove();
  $("#contact-p").remove();
  $("#natStat").remove();
  $("#survey-p").remove();
  $("#frequency-p").remove();
  $("#compilation-p").remove();
  $("#geoCoverage-p").remove();
  $("#sampleSize-p").remove();
  $(".lastRevised-p").remove();
  $(".release-date").remove();
  $("#reference-p").remove();

  // Metadata edition and saving
  $("#title").on('input', function () {
    renameUri = true;
    $(this).textareaAutoSize();
    data.description.title = $(this).val();
  });
  $("#summary").on('input', function () {
    $(this).textareaAutoSize();
    data.description.summary = $(this).val();
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      autoSaveMetadata(collectionId, data);
    }, 3000);
  });
  $("#keywordsTag").tagit({
    availableTags: data.description.keywords,
    singleField: true,
    allowSpaces: true,
    singleFieldNode: $('#keywords')
  });
  $('#keywords').on('change', function () {
    data.description.keywords = $('#keywords').val().split(',');
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      autoSaveMetadata(collectionId, data);
    }, 3000);
  });
  $("#metaDescription").on('input', function () {
    $(this).textareaAutoSize();
    data.description.metaDescription = $(this).val();
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      autoSaveMetadata(collectionId, data);
    }, 3000);
  });

  // Save
  var editNav = $('.edit-nav');
  editNav.off(); // remove any existing event handlers.

  editNav.on('click', '.btn-edit-save', function () {
    save(updateContent);
  });

  // completed to review
  editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
    save(saveAndCompleteContent);
  });

  // reviewed to approve
  editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
    save(saveAndReviewContent);
  });

  function save(onSave) {
    // Sections
    data.markdown = [$('#content-markdown').val()];
    // Files are uploaded. Save metadata
    var orderFile = $("#sortable-file").sortable('toArray');
    $(orderFile).each(function (indexF, nameF) {
      var title = $('#file-title_' + nameF).val();
      var file = data.downloads[parseInt(nameF)].file;
      newFiles[indexF] = {title: title, file: file};
    });
    data.downloads = newFiles;
    // External links
    var orderLink = $("#sortable-link").sortable('toArray');
    $(orderLink).each(function (indexL, nameL) {
      var displayText = $('#link-markdown_' + nameL).val();
      var link = $('#link-uri_' + nameL).val();
      newLinks[indexL] = {uri: link, title: displayText};
    });
    data.links = newLinks;

    checkRenameUri(collectionId, data, renameUri, onSave);
  }
}

<commit_msg>Add date field<commit_after>function staticPageEditor(collectionId, data) {

  var newLinks = [], newFiles = [];
  var setActiveTab, getActiveTab;
  var renameUri = false;
  var timeoutId;
  $(".edit-accordion").on('accordionactivate', function (event, ui) {
    setActiveTab = $(".edit-accordion").accordion("option", "active");
    if (setActiveTab !== false) {
      Florence.globalVars.activeTab = setActiveTab;
    }
  });

  getActiveTab = Florence.globalVars.activeTab;
  accordion(getActiveTab);

  $("#metadata-ad").remove();
  $("#metadata-f").remove();
  $("#metadata-md").remove();
  $("#metadata-q").remove();
  $("#contact-p").remove();
  $("#natStat").remove();
  $("#survey-p").remove();
  $("#frequency-p").remove();
  $("#compilation-p").remove();
  $("#geoCoverage-p").remove();
  $("#sampleSize-p").remove();
  $(".lastRevised-p").remove();
  $("#reference-p").remove();

  // Metadata edition and saving
  $("#title").on('input', function () {
    renameUri = true;
    $(this).textareaAutoSize();
    data.description.title = $(this).val();
  });
  $("#summary").on('input', function () {
    $(this).textareaAutoSize();
    data.description.summary = $(this).val();
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      autoSaveMetadata(collectionId, data);
    }, 3000);
  });
  if (!data.description.releaseDate) {
    $('#releaseDate').datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.releaseDate = new Date($(this).datepicker({dateFormat: 'dd MM yy'})[0].value).toISOString();
      clearTimeout(timeoutId);
      timeoutId = setTimeout(function () {
        autoSaveMetadata(collectionId, data);
      }, 3000);
    });
  } else {
    dateTmp = data.description.releaseDate;
    var dateTmpFormatted = $.datepicker.formatDate('dd MM yy', new Date(dateTmp));
    $('#releaseDate').val(dateTmpFormatted).datepicker({dateFormat: 'dd MM yy'}).on('change', function () {
      data.description.releaseDate = new Date($('#releaseDate').datepicker('getDate')).toISOString();
      clearTimeout(timeoutId);
      timeoutId = setTimeout(function () {
        autoSaveMetadata(collectionId, data);
      }, 3000);
    });
  }
  $("#keywordsTag").tagit({
    availableTags: data.description.keywords,
    singleField: true,
    allowSpaces: true,
    singleFieldNode: $('#keywords')
  });
  $('#keywords').on('change', function () {
    data.description.keywords = $('#keywords').val().split(',');
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      autoSaveMetadata(collectionId, data);
    }, 3000);
  });
  $("#metaDescription").on('input', function () {
    $(this).textareaAutoSize();
    data.description.metaDescription = $(this).val();
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function () {
      autoSaveMetadata(collectionId, data);
    }, 3000);
  });

  // Save
  var editNav = $('.edit-nav');
  editNav.off(); // remove any existing event handlers.

  editNav.on('click', '.btn-edit-save', function () {
    save(updateContent);
  });

  // completed to review
  editNav.on('click', '.btn-edit-save-and-submit-for-review', function () {
    save(saveAndCompleteContent);
  });

  // reviewed to approve
  editNav.on('click', '.btn-edit-save-and-submit-for-approval', function () {
    save(saveAndReviewContent);
  });

  function save(onSave) {
    // Sections
    data.markdown = [$('#content-markdown').val()];
    // Files are uploaded. Save metadata
    var orderFile = $("#sortable-file").sortable('toArray');
    $(orderFile).each(function (indexF, nameF) {
      var title = $('#file-title_' + nameF).val();
      var file = data.downloads[parseInt(nameF)].file;
      newFiles[indexF] = {title: title, file: file};
    });
    data.downloads = newFiles;
    // External links
    var orderLink = $("#sortable-link").sortable('toArray');
    $(orderLink).each(function (indexL, nameL) {
      var displayText = $('#link-markdown_' + nameL).val();
      var link = $('#link-uri_' + nameL).val();
      newLinks[indexL] = {uri: link, title: displayText};
    });
    data.links = newLinks;

    checkRenameUri(collectionId, data, renameUri, onSave);
  }
}

<|endoftext|>


<commit_before>/* global Vulcan */
import { Posts } from '../../lib/collections/posts';
import Users from 'meteor/vulcan:users';
import { createDummyMessage, createDummyConversation, createDummyPost, createDummyComment } from '../../testing/utils.js';
import { performSubscriptionAction } from '../../lib/subscriptions/mutations.js';
import moment from 'moment';

Vulcan.populateNotifications = async ({username,
  messageNotifications = 3,
  postNotifications = 3,
  commentNotifications = 3,
  replyNotifications = 3 }) =>
{
  const user = Users.findOne({username});
  const randomUser = Users.findOne({_id: {$ne: user._id}});
  if (messageNotifications > 0) {
    //eslint-disable-next-line no-console
    console.log("generating new messages...")
    const conversation = await createDummyConversation(randomUser, {participantIds: [randomUser._id, user._id]});
    _.times(messageNotifications, () => createDummyMessage(randomUser, {conversationId: conversation._id}))
  }
  if (postNotifications > 0) {
    //eslint-disable-next-line no-console
    console.log("generating new posts...")
    try {
      performSubscriptionAction('subscribe', Users, randomUser._id, user)
    } catch(err) {
      //eslint-disable-next-line no-console
      console.log("User already subscribed, continuing");
    }
    _.times(postNotifications, () => createDummyPost(randomUser))
  }
  if (commentNotifications > 0) {
    const post = Posts.findOne(); // Grab random post
    //eslint-disable-next-line no-console
    console.log("generating new comments...")
    try {
      performSubscriptionAction('subscribe', Posts, post._id, user)
    } catch(err) {
      //eslint-disable-next-line no-console
      console.log("User already subscribed, continuing");
    }
    _.times(commentNotifications, () => createDummyComment(randomUser, {postId: post._id}));

  }
  if (replyNotifications > 0) {
    const post = Posts.findOne();
    //eslint-disable-next-line no-console
    console.log("generating new replies...")
    try {
      performSubscriptionAction('subscribe', Users, randomUser._id, user);
    } catch(err) {
      //eslint-disable-next-line no-console
      console.log("User already subscribed, continuing");
    }
    const comment = createDummyComment(user, {postId: post._id});
    _.times(replyNotifications, () => createDummyComment(randomUser, {postId: post._id, parentCommentId: comment._id}));
  }
}

let loremIpsumTokens = [ "lorem", "ipsum", "dolor", "sit", "amet",
  "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor",
  "incididunt", "ut", "labore", "et" ];

function getLoremIpsumToken() {
  let index = Math.floor(Math.random() * loremIpsumTokens.length);
  return loremIpsumTokens[index];
}

// Generate a given number of characters of lorem ipsum.
function makeLoremIpsum(length) {
  let result = [];
  let lengthSoFar = 0;

  result.push("Lorem ");
  lengthSoFar = "Lorem ".length;

  while(lengthSoFar < length) {
    let token = getLoremIpsumToken()+" ";
    lengthSoFar += token.length;
    result.push(token)
  }

  return result.join("").substr(0,length);
}

// Create a given number of paragraphs of a given length (in characters)
// of lorem ipsum, formatted like:
//
Lorem ipsum dolor sit ame

// This is strictly for making big/slow posts for test purposes.
function makeLoremIpsumBody(numParagraphs, paragraphLength) {
  let result = [];

  for(var ii=0; ii<numParagraphs; ii++) {
    result.push('
');
    result.push(makeLoremIpsum(paragraphLength));
    result.push('
');
  }
  return result.join("");
}

function makeStyledBody() {
  let result = [];

  result.push('
Post Title
')

  result.push('
Test Link ');
  result.push(makeLoremIpsum(500));
  result.push('
');
  result.push('
');
  result.push(makeLoremIpsum(200));
  result.push('
');

  result.push('

Option 1

Option 2

Option 3

');

  result.push('
');
  result.push(makeLoremIpsum(200));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(300));
  result.push('
');
  result.push('
');
  result.push(makeLoremIpsum(100));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(100));
  result.push('
');

  result.push('
');
  result.push(makeLoremIpsum(250));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(300));
  result.push('
');

  result.push('
');
  result.push(makeLoremIpsum(250));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(100));
  result.push('
');

  result.push('
Post Title
')
  result.push('
');
  result.push(makeLoremIpsum(200));
  result.push('
');

  return result.join("");
}

Vulcan.createStyledPost = async () => {
  const user = Users.findOne();
  // Create a post

  const post = await createDummyPost(user, {
    title: "Styled Post",
    slug: "styled-post",
    body: makeStyledBody(),
    af: true,
    frontpageDate: new Date(),
  })

  await createDummyComment(user, {
    postId: post._id,
    body: makeStyledBody()
  })
}

// Create a set of bulky test posts, used for checking for load time
// problems. This is meant to be invoked from 'meteor shell'. It is
// slow.

Vulcan.createTestPostSet = async () =>
{
  //eslint-disable-next-line no-console
  console.log("Creating a set of bulky posts to test for load-time problems. This may take awhile...");
  await Vulcan.createStyledPost()

  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 100 flat comments",
    numRootComments: 100
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 1000 flat comments",
    numRootComments: 1000
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 50-deep comments",
    numRootComments: 1,
    commentDepth: 50
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 1000-deep comments",
    numRootComments: 1,
    commentDepth: 1000
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 500-paragraph long post body",
    postParagraphCount: 500,
    numRootComments: 1,
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 500-paragraph long comment body",
    commentParagraphCount: 500,
    numRootComments: 1,
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 100kb-long single paragraph body",
    postParagraphCount: 1,
    postParagraphLength: 100000,
    numRootComments: 1,
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 100kb-long single comment body",
    commentParagraphCount: 1,
    commentParagraphLength: 100000,
    numRootComments: 1,
  });
  //eslint-disable-next-line no-console
  console.log("Finished creating bulky test posts.");
}

// Create a single test post, which is bulky in one or more of a
// number of different ways, controlled by arguments. Used for testing
// for loading time problems. Vulcan.createTestPostSet() will invoke
// this in different ways with pretty good coverage of the problems
// it's capable uncovering.
Vulcan.createBulkyTestPost = async ({
  username = null,
  postTitle = "Test Post With Many Comments",
  postParagraphCount = 3,
  postParagraphLength = 1000,
  commentParagraphCount = 2,
  commentParagraphLength = 800,
  numRootComments = 100,
  commentDepth = 1,
  backDate = null}) =>
{
  var user;
  if(username)
    user = Users.findOne({username});
  else
    user = Users.findOne();

  // Create a post
  const body = "
This is a programmatically generated test post.
" +
    makeLoremIpsumBody(postParagraphCount, postParagraphLength);

  let dummyPostFields = {
    title: postTitle,
    body: body
  };
  if (backDate) {
    dummyPostFields.createdAt = backDate;
    dummyPostFields.postedAt = backDate;
  }
  const post = await createDummyPost(user, dummyPostFields)

  // Create some comments
  for(var ii=0; ii<numRootComments; ii++)
  {
    //eslint-disable-next-line no-await-in-loop
    var rootComment = await createDummyComment(user, {
      postId: post._id,
      body: makeLoremIpsumBody(commentParagraphCount, commentParagraphLength)
    })

    // If commentDepth>1, create a series of replies-to-replies under the top-level replies
    var parentCommentId = rootComment._id
    for(var jj=0; jj<commentDepth-1; jj++) {
      var childComment = await createDummyComment(user, {
        postId: post._id,
        parentCommentId: parentCommentId,
        body: makeLoremIpsumBody(commentParagraphCount, commentParagraphLength)
      });
      parentCommentId = childComment._id
    }
  }
}

// Create a set of test posts that are back-dated, one per hour for the past
// ten days. Primarily for testing time-zone handling on /daily.
Vulcan.createBackdatedPosts = async () =>
{
  //eslint-disable-next-line no-console
  console.log("Creating back-dated test post set");

  for(let i=0; i<24*10; i++) {
    const backdateTime = moment().subtract(i, 'hours').toDate();
    await Vulcan.createBulkyTestPost({
      postTitle: "Test post backdated by "+i+" hours",
      numRootComments: 0,
      backDate: backdateTime,
    });
  }

  //eslint-disable-next-line no-console
  console.log("Done");
}<commit_msg>Update auto posts script<commit_after>/* global Vulcan */
import { Posts } from '../../lib/collections/posts';
import Users from 'meteor/vulcan:users';
import { createDummyMessage, createDummyConversation, createDummyPost, createDummyComment } from '../../testing/utils.js';
import { performSubscriptionAction } from '../../lib/subscriptions/mutations.js';
import moment from 'moment';

Vulcan.populateNotifications = async ({username,
  messageNotifications = 3,
  postNotifications = 3,
  commentNotifications = 3,
  replyNotifications = 3 }) =>
{
  const user = Users.findOne({username});
  const randomUser = Users.findOne({_id: {$ne: user._id}});
  if (messageNotifications > 0) {
    //eslint-disable-next-line no-console
    console.log("generating new messages...")
    const conversation = await createDummyConversation(randomUser, {participantIds: [randomUser._id, user._id]});
    _.times(messageNotifications, () => createDummyMessage(randomUser, {conversationId: conversation._id}))
  }
  if (postNotifications > 0) {
    //eslint-disable-next-line no-console
    console.log("generating new posts...")
    try {
      performSubscriptionAction('subscribe', Users, randomUser._id, user)
    } catch(err) {
      //eslint-disable-next-line no-console
      console.log("User already subscribed, continuing");
    }
    _.times(postNotifications, () => createDummyPost(randomUser))
  }
  if (commentNotifications > 0) {
    const post = Posts.findOne(); // Grab random post
    //eslint-disable-next-line no-console
    console.log("generating new comments...")
    try {
      performSubscriptionAction('subscribe', Posts, post._id, user)
    } catch(err) {
      //eslint-disable-next-line no-console
      console.log("User already subscribed, continuing");
    }
    _.times(commentNotifications, () => createDummyComment(randomUser, {postId: post._id}));

  }
  if (replyNotifications > 0) {
    const post = Posts.findOne();
    //eslint-disable-next-line no-console
    console.log("generating new replies...")
    try {
      performSubscriptionAction('subscribe', Users, randomUser._id, user);
    } catch(err) {
      //eslint-disable-next-line no-console
      console.log("User already subscribed, continuing");
    }
    const comment = createDummyComment(user, {postId: post._id});
    _.times(replyNotifications, () => createDummyComment(randomUser, {postId: post._id, parentCommentId: comment._id}));
  }
}

let loremIpsumTokens = [ "lorem", "ipsum", "dolor", "sit", "amet",
  "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor",
  "incididunt", "ut", "labore", "et" ];

function getLoremIpsumToken() {
  let index = Math.floor(Math.random() * loremIpsumTokens.length);
  return loremIpsumTokens[index];
}

// Generate a given number of characters of lorem ipsum.
function makeLoremIpsum(length) {
  let result = [];
  let lengthSoFar = 0;

  result.push("Lorem ");
  lengthSoFar = "Lorem ".length;

  while(lengthSoFar < length) {
    let token = getLoremIpsumToken()+" ";
    lengthSoFar += token.length;
    result.push(token)
  }

  return result.join("").substr(0,length);
}

// Create a given number of paragraphs of a given length (in characters)
// of lorem ipsum, formatted like:
//
Lorem ipsum dolor sit ame

// This is strictly for making big/slow posts for test purposes.
function makeLoremIpsumBody(numParagraphs, paragraphLength) {
  let result = [];

  for(var ii=0; ii<numParagraphs; ii++) {
    result.push('
');
    result.push(makeLoremIpsum(paragraphLength));
    result.push('
');
  }
  return result.join("");
}

function makeStyledBody() {
  let result = [];

  result.push('
Post Title
')

  result.push('
Test Link ');
  result.push(makeLoremIpsum(500));
  result.push('
');
  result.push('
');
  result.push(makeLoremIpsum(200));
  result.push('
');

  result.push('

Option 1

Option 2

Option 3

');

  result.push('
');
  result.push(makeLoremIpsum(200));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(300));
  result.push('
');
  result.push('
');
  result.push(makeLoremIpsum(100));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(100));
  result.push('
');

  result.push('
');
  result.push(makeLoremIpsum(250));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(300));
  result.push('
');

  result.push('
');
  result.push(makeLoremIpsum(250));
  result.push('
');

  result.push('
Test Link ');
  result.push(makeLoremIpsum(100));
  result.push('
');

  result.push('
Post Title
')
  result.push('
');
  result.push(makeLoremIpsum(200));
  result.push('
');

  return result.join("");
}

Vulcan.createStyledPost = async () => {
  const user = Users.findOne();
  // Create a post

  const post = await createDummyPost(user, {
    title: "Styled Post",
    slug: "styled-post",
    htmlBody: makeStyledBody(),
    frontpageDate: new Date(),
    curatedDate: new Date(),
  })

  await createDummyComment(user, {
    postId: post._id,
    htmlBody: makeStyledBody()
  })
}

Vulcan.createStyledAFPost = async () => {
  const user = Users.findOne();
  // Create a post

  const post = await createDummyPost(user, {
    title: "Styled Post",
    slug: "styled-post",
    htmlBody: makeStyledBody(),
    af: true,
    frontpageDate: new Date(),
    curateDate: new Date(),
  })

  await createDummyComment(user, {
    postId: post._id,
    htmlBody: makeStyledBody()
  })
}

Vulcan.createStyledQuestion = async () => {
  const user = Users.findOne();
  // Create a post

  const post = await createDummyPost(user, {
    title: "Styled Post",
    slug: "styled-post",
    htmlBody: makeStyledBody(),
    question: true,
    frontpageDate: new Date(),
    curatedDate: new Date(),
  })

  await createDummyComment(user, {
    postId: post._id,
    htmlBody: makeStyledBody()
  })
}

// Create a set of bulky test posts, used for checking for load time
// problems. This is meant to be invoked from 'meteor shell'. It is
// slow.

Vulcan.createTestPostSet = async () =>
{
  //eslint-disable-next-line no-console
  console.log("Creating a set of bulky posts to test for load-time problems. This may take awhile...");

  await Vulcan.createStyledPost()
  await Vulcan.createStyledAFPost()
  await Vulcan.createStyledQuestion()

  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 100 flat comments",
    numRootComments: 100
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 1000 flat comments",
    numRootComments: 1000
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 50-deep comments",
    numRootComments: 1,
    commentDepth: 50
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with 1000-deep comments",
    numRootComments: 1,
    commentDepth: 1000
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 500-paragraph long post body",
    postParagraphCount: 500,
    numRootComments: 1,
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 500-paragraph long comment body",
    commentParagraphCount: 500,
    numRootComments: 1,
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 100kb-long single paragraph body",
    postParagraphCount: 1,
    postParagraphLength: 100000,
    numRootComments: 1,
  });
  await Vulcan.createBulkyTestPost({
    postTitle: "Test post with a 100kb-long single comment body",
    commentParagraphCount: 1,
    commentParagraphLength: 100000,
    numRootComments: 1,
  });
  //eslint-disable-next-line no-console
  console.log("Finished creating bulky test posts.");
}

// Create a single test post, which is bulky in one or more of a
// number of different ways, controlled by arguments. Used for testing
// for loading time problems. Vulcan.createTestPostSet() will invoke
// this in different ways with pretty good coverage of the problems
// it's capable uncovering.
Vulcan.createBulkyTestPost = async ({
  username = null,
  postTitle = "Test Post With Many Comments",
  postParagraphCount = 3,
  postParagraphLength = 1000,
  commentParagraphCount = 2,
  commentParagraphLength = 800,
  numRootComments = 100,
  commentDepth = 1,
  backDate = null}) =>
{
  var user;
  if(username)
    user = Users.findOne({username});
  else
    user = Users.findOne();

  // Create a post
  const body = "
This is a programmatically generated test post.
" +
    makeLoremIpsumBody(postParagraphCount, postParagraphLength);

  let dummyPostFields = {
    title: postTitle,
    htmlBody: body
  };
  if (backDate) {
    dummyPostFields.createdAt = backDate;
    dummyPostFields.postedAt = backDate;
  }
  const post = await createDummyPost(user, dummyPostFields)

  // Create some comments
  for(var ii=0; ii<numRootComments; ii++)
  {
    //eslint-disable-next-line no-await-in-loop
    var rootComment = await createDummyComment(user, {
      postId: post._id,
      htmlBody: makeLoremIpsumBody(commentParagraphCount, commentParagraphLength)
    })

    // If commentDepth>1, create a series of replies-to-replies under the top-level replies
    var parentCommentId = rootComment._id
    for(var jj=0; jj<commentDepth-1; jj++) {
      var childComment = await createDummyComment(user, {
        postId: post._id,
        parentCommentId: parentCommentId,
        htmlBody: makeLoremIpsumBody(commentParagraphCount, commentParagraphLength)
      });
      parentCommentId = childComment._id
    }
  }
}

// Create a set of test posts that are back-dated, one per hour for the past
// ten days. Primarily for testing time-zone handling on /daily.
Vulcan.createBackdatedPosts = async () =>
{
  //eslint-disable-next-line no-console
  console.log("Creating back-dated test post set");

  for(let i=0; i<24*10; i++) {
    const backdateTime = moment().subtract(i, 'hours').toDate();
    await Vulcan.createBulkyTestPost({
      postTitle: "Test post backdated by "+i+" hours",
      numRootComments: 0,
      backDate: backdateTime,
    });
  }

  //eslint-disable-next-line no-console
  console.log("Done");
}
<|endoftext|>


<commit_before>import {
  getRealPath
} from '../util'

import {
  publish
} from '../../bridge'

let uploadTaskId = 0
const uploadTasks = {}

const publishStateChange = (res) => {
  publish('onUploadTaskStateChange', res)
}

const createUploadTaskById = function (uploadTaskId, {
  url,
  filePath,
  name,
  files,
  header,
  formData
} = {}) {
  const uploader = plus.uploader.createUpload(url, {
    timeout: __uniConfig.networkTimeout.uploadFile ? __uniConfig.networkTimeout.uploadFile / 1000 : 120,
    // 需要与其它平台上的表现保持一致，不走重试的逻辑。
    retry: 0,
    retryInterval: 0
  }, (upload, statusCode) => {
    if (statusCode) {
      publishStateChange({
        uploadTaskId,
        state: 'success',
        data: upload.responseText,
        statusCode
      })
    } else {
      publishStateChange({
        uploadTaskId,
        state: 'fail',
        data: '',
        statusCode
      })
    }
    delete uploadTasks[uploadTaskId]
  })

  for (const name in header) {
    if (header.hasOwnProperty(name)) {
      uploader.setRequestHeader(name, header[name])
    }
  }
  for (const name in formData) {
    if (formData.hasOwnProperty(name)) {
      uploader.addData(name, formData[name])
    }
  }
  if (files && files.length) {
    files.forEach(file => {
      uploader.addFile(getRealPath(file.uri), {
        key: file.name || 'file'
      })
    })
  } else {
    uploader.addFile(getRealPath(filePath), {
      key: name
    })
  }
  uploader.addEventListener('statechanged', (upload, status) => {
    if (upload.uploadedSize && upload.totalSize) {
      publishStateChange({
        uploadTaskId,
        state: 'progressUpdate',
        progress: parseInt(upload.uploadedSize / upload.totalSize * 100),
        totalBytesSent: upload.uploadedSize,
        totalBytesExpectedToSend: upload.totalSize
      })
    }
  })
  uploadTasks[uploadTaskId] = uploader
  uploader.start()
  return {
    uploadTaskId,
    errMsg: 'createUploadTask:ok'
  }
}

export function operateUploadTask ({
  uploadTaskId,
  operationType
} = {}) {
  const uploadTask = uploadTasks[uploadTaskId]
  if (uploadTask && operationType === 'abort') {
    delete uploadTasks[uploadTaskId]
    uploadTask.abort()
    publishStateChange({
      uploadTaskId,
      state: 'fail',
      errMsg: 'abort'
    })
    return {
      errMsg: 'operateUploadTask:ok'
    }
  }
  return {
    errMsg: 'operateUploadTask:fail'
  }
}

export function createUploadTask (args) {
  return createUploadTaskById(++uploadTaskId, args)
}
<commit_msg>fix: app-v3 formData 支持非 String 类型<commit_after>import {
  getRealPath
} from '../util'

import {
  publish
} from '../../bridge'

let uploadTaskId = 0
const uploadTasks = {}

const publishStateChange = (res) => {
  publish('onUploadTaskStateChange', res)
}

const createUploadTaskById = function (uploadTaskId, {
  url,
  filePath,
  name,
  files,
  header,
  formData
} = {}) {
  const uploader = plus.uploader.createUpload(url, {
    timeout: __uniConfig.networkTimeout.uploadFile ? __uniConfig.networkTimeout.uploadFile / 1000 : 120,
    // 需要与其它平台上的表现保持一致，不走重试的逻辑。
    retry: 0,
    retryInterval: 0
  }, (upload, statusCode) => {
    if (statusCode) {
      publishStateChange({
        uploadTaskId,
        state: 'success',
        data: upload.responseText,
        statusCode
      })
    } else {
      publishStateChange({
        uploadTaskId,
        state: 'fail',
        data: '',
        statusCode
      })
    }
    delete uploadTasks[uploadTaskId]
  })

  for (const name in header) {
    if (header.hasOwnProperty(name)) {
      uploader.setRequestHeader(name, header[name])
    }
  }
  for (const name in formData) {
    if (formData.hasOwnProperty(name)) {
      uploader.addData(name, String(formData[name]))
    }
  }
  if (files && files.length) {
    files.forEach(file => {
      uploader.addFile(getRealPath(file.uri), {
        key: file.name || 'file'
      })
    })
  } else {
    uploader.addFile(getRealPath(filePath), {
      key: name
    })
  }
  uploader.addEventListener('statechanged', (upload, status) => {
    if (upload.uploadedSize && upload.totalSize) {
      publishStateChange({
        uploadTaskId,
        state: 'progressUpdate',
        progress: parseInt(upload.uploadedSize / upload.totalSize * 100),
        totalBytesSent: upload.uploadedSize,
        totalBytesExpectedToSend: upload.totalSize
      })
    }
  })
  uploadTasks[uploadTaskId] = uploader
  uploader.start()
  return {
    uploadTaskId,
    errMsg: 'createUploadTask:ok'
  }
}

export function operateUploadTask ({
  uploadTaskId,
  operationType
} = {}) {
  const uploadTask = uploadTasks[uploadTaskId]
  if (uploadTask && operationType === 'abort') {
    delete uploadTasks[uploadTaskId]
    uploadTask.abort()
    publishStateChange({
      uploadTaskId,
      state: 'fail',
      errMsg: 'abort'
    })
    return {
      errMsg: 'operateUploadTask:ok'
    }
  }
  return {
    errMsg: 'operateUploadTask:fail'
  }
}

export function createUploadTask (args) {
  return createUploadTaskById(++uploadTaskId, args)
}
<|endoftext|>


<commit_before>import SHARED_CONFIG from '../shared-config/shared-config';
import verblijfsobject from './adressen-verblijfsobject';

export default function fetchByUri(uri) {
  return fetch(uri)
    .then((response) => response.json())
    .then((result) => ({
      ...result,
      label: result._display,
      isNevenadres: !result.hoofdadres
    }))
    .then((result) => (
      result.verblijfsobject ?
        verblijfsobject(result.verblijfsobject)
          .then((vboResult) => ({
            ...vboResult,
            label: result.label,
            isNevenadres: result.isNevenadres
          })) :
        result
    ));
}

export function fetchByPandId(pandId) {
  const searchParams = {
    pand: pandId
  };

  const queryString = Object.keys(searchParams)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(searchParams[key])}`)
    .join('&');

  return fetch(`${SHARED_CONFIG.API_ROOT}bag/nummeraanduiding/?${queryString}`)
    .then((response) => response.json())
    .then((data) => data.results);
}

export function fetchByLigplaatsId(ligplaatsId) {
  const searchParams = {
    ligplaats: ligplaatsId
  };

  const queryString = Object.keys(searchParams)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(searchParams[key])}`)
    .join('&');

  return fetch(`${SHARED_CONFIG.API_ROOT}bag/nummeraanduiding/?${queryString}`)
    .then((response) => response.json())
    .then((data) => data.results
      .map((result) => ({
        ...result,
        id: result.landelijk_id
      }))
    );
}

export function fetchHoofdadresByLigplaatsId(ligplaatsId) {
  return fetchByLigplaatsId(ligplaatsId)
    .then((results) => results.find((result) => result.hoofdadres));
}

export function fetchByStandplaatsId(standplaatsId) {
  const searchParams = {
    standplaats: standplaatsId
  };

  const queryString = Object.keys(searchParams)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(searchParams[key])}`)
    .join('&');

  return fetch(`${SHARED_CONFIG.API_ROOT}bag/nummeraanduiding/?${queryString}`)
    .then((response) => response.json())
    .then((data) => data.results
      .map((result) => ({
        ...result,
        id: result.landelijk_id
      }))
    );
}

export function fetchHoofdadresByStandplaatsId(standplaatsId) {
  return fetchByStandplaatsId(standplaatsId)
    .then((results) => results.find((result) => result.hoofdadres));
}
<commit_msg>add location for nummeraanduiding results when _geometrie field is available<commit_after>import SHARED_CONFIG from '../shared-config/shared-config';
import verblijfsobject from './adressen-verblijfsobject';

import getCenter from '../geo-json/geo-json';
import { rdToWgs84 } from '../coordinate-reference-system/crs-converter';

export default function fetchByUri(uri) {
  return fetch(uri)
    .then((response) => response.json())
    .then((result) => ({
      ...result,
      label: result._display,
      isNevenadres: !result.hoofdadres
    }))
    .then((result) => (
      result.verblijfsobject ?
        verblijfsobject(result.verblijfsobject)
          .then((vboResult) => ({
            ...vboResult,
            label: result.label,
            isNevenadres: result.isNevenadres
          })) :
        result
    ))
    .then((result) => {
      const geometryCenter = result._geometrie && getCenter(result._geometrie);
      const wgs84Center = geometryCenter && rdToWgs84(geometryCenter);

      return {
        ...result,
        location: result.location || wgs84Center
      };
    })
}

export function fetchByPandId(pandId) {
  const searchParams = {
    pand: pandId
  };

  const queryString = Object.keys(searchParams)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(searchParams[key])}`)
    .join('&');

  return fetch(`${SHARED_CONFIG.API_ROOT}bag/nummeraanduiding/?${queryString}`)
    .then((response) => response.json())
    .then((data) => data.results);
}

export function fetchByLigplaatsId(ligplaatsId) {
  const searchParams = {
    ligplaats: ligplaatsId
  };

  const queryString = Object.keys(searchParams)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(searchParams[key])}`)
    .join('&');

  return fetch(`${SHARED_CONFIG.API_ROOT}bag/nummeraanduiding/?${queryString}`)
    .then((response) => response.json())
    .then((data) => data.results
      .map((result) => ({
        ...result,
        id: result.landelijk_id
      }))
    );
}

export function fetchHoofdadresByLigplaatsId(ligplaatsId) {
  return fetchByLigplaatsId(ligplaatsId)
    .then((results) => results.find((result) => result.hoofdadres));
}

export function fetchByStandplaatsId(standplaatsId) {
  const searchParams = {
    standplaats: standplaatsId
  };

  const queryString = Object.keys(searchParams)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(searchParams[key])}`)
    .join('&');

  return fetch(`${SHARED_CONFIG.API_ROOT}bag/nummeraanduiding/?${queryString}`)
    .then((response) => response.json())
    .then((data) => data.results
      .map((result) => ({
        ...result,
        id: result.landelijk_id
      }))
    );
}

export function fetchHoofdadresByStandplaatsId(standplaatsId) {
  return fetchByStandplaatsId(standplaatsId)
    .then((results) => results.find((result) => result.hoofdadres));
}
<|endoftext|>


<commit_before>/*
 * karma.conf.js and karma.es5.conf.js optionally load this
 */

var CUSTOM_LAUNCHERS = {
  'SL_Chrome': {
    base: 'SauceLabs',
    browserName: 'chrome',
    version: '35'
  }
};

module.exports = function(options) {
  options.sauceLabs = {
    testName: 'AngularJS Batarang Unit Tests',
    startConnect: true
  };
  options.customLaunchers = CUSTOM_LAUNCHERS;
  options.browsers = Object.keys(CUSTOM_LAUNCHERS);
  options.reporters = ['dots', 'saucelabs'];
};
<commit_msg>chore(sauce): increase timeout<commit_after>/*
 * karma.conf.js and karma.es5.conf.js optionally load this
 */

var CUSTOM_LAUNCHERS = {
  'SL_Chrome': {
    base: 'SauceLabs',
    browserName: 'chrome',
    version: '35'
  }
};

module.exports = function(options) {
  options.sauceLabs = {
    testName: 'AngularJS Batarang Unit Tests',
    startConnect: true
  };
  options.captureTimeout = 100000;
  options.customLaunchers = CUSTOM_LAUNCHERS;
  options.browsers = Object.keys(CUSTOM_LAUNCHERS);
  options.reporters = ['dots', 'saucelabs'];
};
<|endoftext|>