<commit_before>export { TensorPlaceholderSet };

import { TensorPlaceholder } from "./Block_TensorPlaceholder.js";

//!!! ...unfinished... (2022/05/30) Used by Operation.apply()
// class OperationApplyArgs {
//
// //   constructor() {
// //     this.blockInput0 =
// //     this.blockInput1 =
// //
// //     this.operationInput0 =
// //     this.operationInput1 =
// //     this.operationOutput0 =
// //     this.operationOutput1 =;
//   }
//
// }
//
//
// //!!! ...unfinished... (2022/05/30) should create objects representing this operation's output(s).
// class Operation {
//
//   constructor() {
//     this.tensorPlaceholderSet = new TensorPlaceholderSet();
//   }
//
// }

/**
 * A set of TensorPlaceholder.
 *
 * In Block.init(), it is used for tracking the current tensor placeholders. It could simply the decision of what tensor placeholders
 * should be used as the next operation's input.
 *
 * In operation (e.g. Pointwise.Base), it is used for tracking the tensor placeholders of the operation. It is used to get input tensor(s)
 * and output tensor(s) in Operation.apply().
 *
 *
 *
 * @member {Block.TensorPlaceholder} input0
 *   The TensorPlaceholder object which represents this operation's first input. It (from constructor) will be kept (not cloned)
 * directly. So caller should not modify them.
 *
 * @member {Block.TensorPlaceholder} input1
 *   The TensorOpCounter.Base object which represents this operation's second input. It could be null which means this operation
 * does not have second input tensor. It (from constructor) will be kept (not cloned) directly. So caller should not modify them.
 *
 * @param {number} inputTensorCount
 *   How many input tensor placeholders.
 *
 * @member {Block.TensorPlaceholder} output0
 *   The TensorPlaceholder object which represents this operation's first output. It is always be created by constructor.
 *
 * @member {Block.TensorPlaceholder} output1
 *   The TensorOpCounter.Base object which represents this operation's second output. It is only be created by constructor if
 * outputTensorCount (of constructor) is 2.
 *
 * @param {number} outputTensorCount
 *   How many output tensor placeholders.
 *
 */
class TensorPlaceholderSet {

  /**
   * @param {number} outputTensorCount
   *   If 1, only the this.output0 will be created. If 2, the this.output0 and this.output1 will be created.
   */
  constructor( input0, input1, outputTensorCount = 1 ) {
    this.input0 = input0;
    this.input1 = input1;

//!!! ...unfinished... (2022/05/30) Register as the input TensorPlaceholder's final user.

    this.output0 = new TensorPlaceholder();
    if ( outputTensorCount >= 2 ) {
      this.output1 = new TensorPlaceholder();
    }
  }

  get inputTensorCount() {
    if ( this.input0 )
      if ( this.input1 )
        return 2;
      else
        return 1;
    else
      if ( this.input1 )
        return 1;
      else
        return 0; // (should not happen)
  }

  get outputTensorCount() {
    if ( this.output0 )
      if ( this.output1 )
        return 2;
      else
        return 1;
    else
      if ( this.output1 )
        return 1;
      else
        return 0; // (should not happen)
  }

}
<commit_msg>Update Block_TensorPlaceholderSet.js<commit_after>export { TensorPlaceholderSet };

import { TensorPlaceholder } from "./Block_TensorPlaceholder.js";
//import { Operation } from "./Block_Operation.js";

//!!! ...unfinished... (2022/05/30) Used by Operation.apply()
// class OperationApplyArgs {
//
// //   constructor() {
// //     this.blockInput0 =
// //     this.blockInput1 =
// //
// //     this.operationInput0 =
// //     this.operationInput1 =
// //     this.operationOutput0 =
// //     this.operationOutput1 =;
//   }
//
// }
//
//
// //!!! ...unfinished... (2022/05/30) should create objects representing this operation's output(s).
// class Operation {
//
//   constructor() {
//     this.tensorPlaceholderSet = new TensorPlaceholderSet();
//   }
//
// }

/**
 * A set of TensorPlaceholder.
 *
 * In Block.init(), it is used for tracking the current tensor placeholders. It could simply the decision of what tensor placeholders
 * should be used as the next operation's input.
 *
 * In operation (e.g. Pointwise.Base), it is used for tracking the tensor placeholders of the operation. It is used to get input tensor(s)
 * and output tensor(s) in Operation.apply().
 *
 *
 *
 * @member {Block.TensorPlaceholder} input0
 *   The TensorPlaceholder object which represents this operation's first input. It (from constructor) will be kept (not cloned)
 * directly. So caller should not modify them.
 *
 * @member {Block.TensorPlaceholder} input1
 *   The TensorOpCounter.Base object which represents this operation's second input. It could be null which means this operation
 * does not have second input tensor. It (from constructor) will be kept (not cloned) directly. So caller should not modify them.
 *
 * @param {number} inputTensorCount
 *   How many input tensor placeholders.
 *
 * @member {Block.TensorPlaceholder} output0
 *   The TensorPlaceholder object which represents this operation's first output. It is always be created by constructor.
 *
 * @member {Block.TensorPlaceholder} output1
 *   The TensorOpCounter.Base object which represents this operation's second output. It is only be created by constructor if
 * outputTensorCount (of constructor) is 2.
 *
 * @param {number} outputTensorCount
 *   How many output tensor placeholders.
 *
 */
class TensorPlaceholderSet {

  /**
   * @param {number} outputTensorCount
   *   If 1, only the this.output0 will be created. If 2, the this.output0 and this.output1 will be created.
   */
  constructor( input0, input1, outputTensorCount = 1 ) {
    this.input0 = input0;
    this.input1 = input1;

//!!! ...unfinished... (2022/05/30) Register as the input TensorPlaceholder's final user.

    this.output0 = new TensorPlaceholder();
    if ( outputTensorCount >= 2 ) {
      this.output1 = new TensorPlaceholder();
    }
  }

  get inputTensorCount() {
    if ( this.input0 )
      if ( this.input1 )
        return 2;
      else
        return 1;
    else
      if ( this.input1 )
        return 1;
      else
        return 0; // (should not happen)
  }

  get outputTensorCount() {
    if ( this.output0 )
      if ( this.output1 )
        return 2;
      else
        return 1;
    else
      if ( this.output1 )
        return 1;
      else
        return 0; // (should not happen)
  }

}
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
*/

(function() {
    // special patch to correctly work on Ripple emulator (CB-9760)
    if (window.parent && !!window.parent.ripple) { // https://gist.github.com/triceam/4658021
        module.exports = window.open.bind(window); // fallback to default window.open behaviour
        return;
    }

    var exec = require('cordova/exec');
    var channel = require('cordova/channel');
    var modulemapper = require('cordova/modulemapper');
    var urlutil = require('cordova/urlutil');

    var inAppBrowserInstance = null;
    var lastUrl = '';
    var lastWindowName = '';
    var lastWindowFeatures = '';
    var hidden = false;

    var InAppBrowser = function() {

        var me = this,
            lastPollIntervalToRestore = null,
            lastPollFunctionToRestore = null;

        function clearPolling () {
            lastPollIntervalToRestore = null;
            lastPollFunctionToRestore = null;
        }

        function clearRestoring(){
            clearPolling();
        }

        this.channels = {
            'loadstart': channel.create('loadstart'),
            'loadstop' : channel.create('loadstop'),
            'loaderror' : channel.create('loaderror'),
            'hidden' : channel.create('hidden'),
            'unhidden' : channel.create('unhidden'),
            'pollresult' : channel.create('pollresult'),
            'exit' : channel.create('exit')
        }

        this._eventHandler = function(event) {
            if (event && (event.type in this.channels)) {
                this.channels[event.type].fire(event);
            }
        }

        this.close = function(eventname) {
            exec(null, null, "InAppBrowser", "close", []);
            this.stopPoll();
            if(hidden){
                this.channels['exit'].fire();
            }
        }

        this.show = function(eventname) {
            exec(null, null, "InAppBrowser", "show", []);
        }

        this.startPoll = function(pollFunction, pollInterval){
           lastPollInterval = pollInterval;
           lastPollFunction = pollFunction;
           exec(null, null, "InAppBrowser", "startPoll", [pollFunction, pollInterval])
        }

        this.stopPoll = function() {
           clearPolling();
           exec(null, null, "InAppBrowser", "stopPoll", []);
        }

        this.hide = function(releaseResources){
            if(hidden){
                return;
            }
            //TODO: Polling
            //TODO: remove handlers if releaseResources
            var exitHandlersToRestore = {},
                exitChannel = me.channels['exit'],
                exitRestoreCallBack = function(){
                    // This cleans up the current handler
                    if(exitRestoreCallBack.observer_guid){
                        me.removeEventListener('exit', exitChannel.handlers[exitRestoreCallBack.observer_guid]);
                    }

                    for(var exitCallbackObserverId in exitHandlersToRestore) {
                        var eventHandler = exitHandlersToRestore[exitCallbackObserverId];
                        me.addEventListener('exit', eventHandler);
                    }
                };

            if(exitChannel.numHandlers >0){
                for(var exitCallbackObserverId in exitChannel.handlers) {
                    var eventHandler = exitChannel.handlers[exitCallbackObserverId];
                    exitHandlersToRestore[exitCallbackObserverId] = exitChannel.handlers[exitCallbackObserverId];
                    me.removeEventListener('exit', eventHandler);
                }
                me.addEventListener('exit', exitRestoreCallBack);
            }

            // Release resources has no effect in native iOS - the IAB
            // Is fully closed & the JS pretends it isn't
            exec(null,null,"InAppBrowser", "hide", [releaseResources]);
            hidden = true;
        }

        this.unHide = function(strUrl, eventname){
            if(!hidden){
                return;
            }
            lastUrl = strUrl || lastUrl;

            //TODO: Polling
            var cb = function(eventname) {
               me._eventHandler(eventname);
            };
            exec(cb, cb, "InAppBrowser", "unHide", [lastUrl, lastWindowName, lastWindowFeatures]);
            hidden = false;
        }

        this.addEventListener = function (eventname,f) {
            if (eventname in this.channels) {
                me.channels[eventname].subscribe(f);
            }
        }

        this.removeEventListener = function (eventname, f) {
            if (eventname in this.channels) {
                this.channels[eventname].unsubscribe(f);
            }
        }

        this.executeScript = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('executeScript requires exactly one of code or file to be specified');
            }
        }

        this.insertCSS = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('insertCSS requires exactly one of code or file to be specified');
            }
        }
    }

    module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
        // Don't catch calls that write to existing frames (e.g. named iframes).
        if (window.frames && window.frames[strWindowName]) {
            var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
            return origOpenFunc.apply(window, arguments);
        }

        strUrl = urlutil.makeAbsolute(strUrl);
        inAppBrowserInstance = new InAppBrowser();

        callbacks = callbacks || {};
        for (var callbackName in callbacks) {
            inAppBrowserInstance.addEventListener(callbackName, callbacks[callbackName]);
        }

        var cb = function(eventname) {
           inAppBrowserInstance._eventHandler(eventname);
        };

        strWindowFeatures = strWindowFeatures || "";

        lastUrl = strUrl;
        lastWindowName = strWindowName;
        lastWindowFeatures = strWindowFeatures;
        exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
        return inAppBrowserInstance;
    };
})();
<commit_msg>post testing - did not reset hidden flag on close, could no longer hide<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
*/

(function() {
    // special patch to correctly work on Ripple emulator (CB-9760)
    if (window.parent && !!window.parent.ripple) { // https://gist.github.com/triceam/4658021
        module.exports = window.open.bind(window); // fallback to default window.open behaviour
        return;
    }

    var exec = require('cordova/exec');
    var channel = require('cordova/channel');
    var modulemapper = require('cordova/modulemapper');
    var urlutil = require('cordova/urlutil');

    var inAppBrowserInstance = null;
    var lastUrl = '';
    var lastWindowName = '';
    var lastWindowFeatures = '';

    var InAppBrowser = function() {
        var me = this,
            hidden = false,
            polling = false,
            lastPollIntervalToRestore = null,
            lastPollFunctionToRestore = null;

        function clearPolling () {
            lastPollIntervalToRestore = null;
            lastPollFunctionToRestore = null;
        }

        function clearRestoring(){
            clearPolling();
        }

        this.channels = {
            'loadstart': channel.create('loadstart'),
            'loadstop' : channel.create('loadstop'),
            'loaderror' : channel.create('loaderror'),
            'hidden' : channel.create('hidden'),
            'unhidden' : channel.create('unhidden'),
            'pollresult' : channel.create('pollresult'),
            'exit' : channel.create('exit')
        }

        this._eventHandler = function(event) {
            if (event && (event.type in this.channels)) {
                this.channels[event.type].fire(event);
            }
        }

        this.isHidden = function(){
            return hidden;
        }

        this.isPolling = function(){
            return polling;
        }

        this.close = function(eventname) {
            exec(null, null, "InAppBrowser", "close", []);
            this.stopPoll();
            if(hidden){
                this.channels['exit'].fire();
            }
            hidden = false;
        }

        this.show = function(eventname) {
            exec(null, null, "InAppBrowser", "show", []);
            hidden = false;
        }

        this.startPoll = function(pollFunction, pollInterval){
           lastPollInterval = pollInterval;
           lastPollFunction = pollFunction;
           exec(null, null, "InAppBrowser", "startPoll", [pollFunction, pollInterval])
           polling = true;
        }

        this.stopPoll = function() {
           clearPolling();
           exec(null, null, "InAppBrowser", "stopPoll", []);
           polling = true;
        }

        this.hide = function(releaseResources){
            if(hidden){
                return;
            }
            //TODO: Polling
            //TODO: remove handlers if releaseResources
            var exitHandlersToRestore = {},
                exitChannel = me.channels['exit'],
                exitRestoreCallBack = function(){
                    // This cleans up the current handler
                    if(exitRestoreCallBack.observer_guid){
                        me.removeEventListener('exit', exitChannel.handlers[exitRestoreCallBack.observer_guid]);
                    }

                    for(var exitCallbackObserverId in exitHandlersToRestore) {
                        var eventHandler = exitHandlersToRestore[exitCallbackObserverId];
                        me.addEventListener('exit', eventHandler);
                    }
                };

            if(exitChannel.numHandlers >0){
                for(var exitCallbackObserverId in exitChannel.handlers) {
                    var eventHandler = exitChannel.handlers[exitCallbackObserverId];
                    exitHandlersToRestore[exitCallbackObserverId] = exitChannel.handlers[exitCallbackObserverId];
                    me.removeEventListener('exit', eventHandler);
                }
                me.addEventListener('exit', exitRestoreCallBack);
            }

            // Release resources has no effect in native iOS - the IAB
            // Is fully closed & the JS pretends it isn't
            exec(null,null,"InAppBrowser", "hide", [releaseResources]);
            hidden = true;
        }

        this.unHide = function(strUrl, eventname){
            if(!hidden){
                return;
            }
            lastUrl = strUrl || lastUrl;

            //TODO: Polling
            var cb = function(eventname) {
               me._eventHandler(eventname);
            };
            exec(cb, cb, "InAppBrowser", "unHide", [lastUrl, lastWindowName, lastWindowFeatures]);
            hidden = false;
        }

        this.addEventListener = function (eventname,f) {
            if (eventname in this.channels) {
                me.channels[eventname].subscribe(f);
            }
        }

        this.removeEventListener = function (eventname, f) {
            if (eventname in this.channels) {
                this.channels[eventname].unsubscribe(f);
            }
        }

        this.executeScript = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('executeScript requires exactly one of code or file to be specified');
            }
        }

        this.insertCSS = function (injectDetails, cb) {
            if (injectDetails.code) {
                exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
            } else if (injectDetails.file) {
                exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
            } else {
                throw new Error('insertCSS requires exactly one of code or file to be specified');
            }
        }
    }

    module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
        // Don't catch calls that write to existing frames (e.g. named iframes).
        if (window.frames && window.frames[strWindowName]) {
            var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
            return origOpenFunc.apply(window, arguments);
        }

        strUrl = urlutil.makeAbsolute(strUrl);
        inAppBrowserInstance = new InAppBrowser();

        callbacks = callbacks || {};
        for (var callbackName in callbacks) {
            inAppBrowserInstance.addEventListener(callbackName, callbacks[callbackName]);
        }

        var cb = function(eventname) {
           inAppBrowserInstance._eventHandler(eventname);
        };

        strWindowFeatures = strWindowFeatures || "";

        lastUrl = strUrl;
        lastWindowName = strWindowName;
        lastWindowFeatures = strWindowFeatures;
        exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
        return inAppBrowserInstance;
    };
})();
<|endoftext|>


<commit_before>db.swiss.find({featurable:true,startsAt:{$lt:new Date(Date.now() - 1000 * 3600 * 24)},'settings.i':{$lt:3600 * 24}}).forEach(s => {
  print(`${s._id} ${s.name} round:${s.round}`);
  db.swiss.update({_id:s._id},{
    $set:{
      finishedAt: new Date(),
      'settings.n': s.round,
      canceled: new Date()
    },
    $unset:{
      nextRoundAt: 1,
      featurable: 1
    }
  });
});
<commit_msg>swiss cleanup scripts<commit_after>db.swiss.find({featurable:true,startsAt:{$lt:new Date(Date.now() - 1000 * 3600 * 24)},'settings.i':{$lt:3600 * 24}}).forEach(s => {
  print(`FINISH ${s._id} ${s.name} round:${s.round}`);
  db.swiss.update({_id:s._id},{
    $set:{
      finishedAt: new Date(),
      'settings.n': s.round,
      canceled: new Date()
    },
    $unset:{
      nextRoundAt: 1,
      featurable: 1
    }
  });
});

db.swiss.find({nbOngoing:{$ne:0}}).forEach(s => {
  const count = db.swiss_pairing.count({s:s._id,t:true});
  if (count != s.nbOngoing) {
    print(`nbOngoing ${s._id} ${s.name} ${s.nbOngoing} -> ${count}`);
    db.swiss.update({_id:s._id},{$set:{
      nbOngoing:NumberInt(count),
      nextRoundAt: new Date(Date.now() + 1000 * 30)
    }});
  }
});
<|endoftext|>


<commit_before>var key = require('../utils/nyt_api_key');
var sync = require('synchronize');
var request = require('request');
var fs = require('fs');
var path = require('path');

// The API that returns the in-email representation.
module.exports = function(req, res) {
  var term = req.query.text;
  if(term) term = term.trim();

  if (/^nytimes\.com\/\S+/.test(term)) {
    // Special-case: handle strings in the special URL form that are suggested by the /typeahead
    // API. This is how the command hint menu suggests an exact Giphy image.
    handleIdString(term, req, res);
  } else {
    // Else, if the user was typing fast and press enter before the /typeahead API can respond,
    // Mixmax will just send the text to the /resolver API (for performance). Handle that here.
    handleSearchString(term, req, res);
  }
};

function handleIdString(url, req, res) {
  var response;
  try {
    response = sync.await(request({
      url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
      qs: {
        'api-key': key,
        fq: 'web_url:("' + url + '")',
        fl: 'web_url,_id,headline,multimedia,snippet'
      },
      gzip: true,
      json: true,
      timeout: 15 * 1000
    }, sync.defer()));
  } catch (e) {
    res.status(500).send('Error');
    return;
  }

  var article = response.body.response.docs[0];
  handleArticle(article, req, res);
}

function handleSearchString(term, req, res) {
  var response;
  try {
    response = sync.await(request({
      url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
      qs: {
        'api-key': key,
        q: term,
        fl: 'web_url,_id,headline,multimedia,snippet'
      },
      gzip: true,
      json: true,
      timeout: 15 * 1000
    }, sync.defer()));
  } catch (e) {
    res.status(500).send('Error');
    return;
  }

  var article = response.body.response.docs[0];
  handleArticle(article, req, res);
}

function handleArticle(article, req, res) {
  var template = '../res/template_no_img.html';
  var hasImage = article.multimedia.length > 0;

  if(hasImage) template = '../res/template.html';

  var html = fs.readFileSync(path.join(__dirname, template)).toString();

  html = html.replace(/##LINK##/ig, article.web_url);
  html = html.replace(/##SAFE_LINK##/ig, '');
  html = html.replace(/##HEADLINE##/ig, article.headline.main);
  html = html.replace(/##SNIPPET##/ig, article.snippet);

  if(hasImage)  html = html.replace(/##IMG_SRC##/ig, article.multimedia[0].url);

  res.json({
    body: html
  });
}<commit_msg>bugfix<commit_after>var key = require('../utils/nyt_api_key');
var sync = require('synchronize');
var request = require('request');
var fs = require('fs');
var path = require('path');

// The API that returns the in-email representation.
module.exports = function(req, res) {
  var term = req.query.text;
  if(term) term = term.trim();

  if (/nytimes\.com\/\S+/.test(term)) {
    // Special-case: handle strings in the special URL form that are suggested by the /typeahead
    // API. This is how the command hint menu suggests an exact Giphy image.
    handleIdString(term, req, res);
  } else {
    // Else, if the user was typing fast and press enter before the /typeahead API can respond,
    // Mixmax will just send the text to the /resolver API (for performance). Handle that here.
    handleSearchString(term, req, res);
  }
};

function handleIdString(url, req, res) {
  var response;
  try {
    response = sync.await(request({
      url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
      qs: {
        'api-key': key,
        fq: 'web_url:("' + url + '")',
        fl: 'web_url,_id,headline,multimedia,snippet'
      },
      gzip: true,
      json: true,
      timeout: 15 * 1000
    }, sync.defer()));
  } catch (e) {
    res.status(500).send('Error');
    return;
  }

  var article = response.body.response.docs[0];
  handleArticle(article, req, res);
}

function handleSearchString(term, req, res) {
  var response;
  try {
    response = sync.await(request({
      url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
      qs: {
        'api-key': key,
        q: term,
        fl: 'web_url,_id,headline,multimedia,snippet'
      },
      gzip: true,
      json: true,
      timeout: 15 * 1000
    }, sync.defer()));
  } catch (e) {
    res.status(500).send('Error');
    return;
  }

  var article = response.body.response.docs[0];
  handleArticle(article, req, res);
}

function handleArticle(article, req, res) {
  var template = '../res/template_no_img.html';
  var hasImage = article.multimedia.length > 0;

  if(hasImage) template = '../res/template.html';

  var html = fs.readFileSync(path.join(__dirname, template)).toString();

  html = html.replace(/##LINK##/ig, article.web_url);
  html = html.replace(/##SAFE_LINK##/ig, '');
  html = html.replace(/##HEADLINE##/ig, article.headline.main);
  html = html.replace(/##SNIPPET##/ig, article.snippet);

  if(hasImage)  html = html.replace(/##IMG_SRC##/ig, article.multimedia[0].url);

  res.json({
    body: html
  });
}
<|endoftext|>


<commit_before>/* eslint-disable camelcase */
/* eslint-disable no-process-exit */
require('dotenv').config();

const csv = require('to-csv');

const emberAddons = require('./lib/ember-addons');
const createRssGenerator = require('./lib/rss');
const createS3FileUploader = require('./lib/s3');
const createDatabase = require('./lib/db');
const formatStats = require('./lib/format-stats');

function createTimer() {
  let startTime = new Date().getTime();

  return function() {
    let totalTime = (new Date().getTime() - startTime) / 1000;
    console.log('--> Duration: ' + totalTime + 's');
  };
}

const printTotalTime = createTimer();

// Init...
const db = createDatabase({
  databaseURL: process.env.DATABASE_URL
});

const rssGenerator = createRssGenerator({
  language: 'en',
  pubDate: new Date(),
  title: 'Ember Addons',
  description: 'Listing hundreds of modules that extend ember-cli.',
  feed_url: 'https://io-builtwithember-addons-data.s3.amazonaws.com/feed.xml',
  site_url: 'http://addons.builtwithember.io/'
});

const s3FileUploader = createS3FileUploader({
  key: process.env.AWS_ACCESS_KEY,
  secret: process.env.AWS_SECRET_KEY,
  bucket: process.env.AWS_BUCKET_NAME
});

// Check if we need an update
async function run() {
  console.log('--> Starting...');

  try {
    console.log('--> Getting all addons from npm...');
    let allAddons = await emberAddons.getAll();

    console.log('--> Fetching data from npm registry...');
    let addons = await emberAddons.getDetails(allAddons);

    let lastCount = await db.getLatestTotalMetric();
    if (lastCount !== allAddons.length) {
      console.log('--> Updating total metric...');
      await db.updateTotalMetric(addons.length);
    } else {
      console.log('--> Skip update total metric...');
    }

    console.log('--> Creating Feed...');
    let rssFeed = rssGenerator(addons);

    console.log('--> Creating stats.csv...');
    let rows = await db.getMetric('total');
    let stats = formatStats(rows);

    let uploadAddons = s3FileUploader({
      data: JSON.stringify(addons),
      fileName: process.env.ADDON_JSON_FILENAME,
      contentType: 'application/json'
    });
    await uploadAddons();

    let uploadFeed = s3FileUploader({
      data: rssFeed,
      fileName: process.env.FEED_FILENAME,
      contentType: 'application/rss+xml'
    });
    await uploadFeed();

    let uploadStats = s3FileUploader({
      data: csv(stats),
      fileName: process.env.STATS_FILENAME,
      contentType: 'text/csv',
      compressData: false
    });
    await uploadStats();

    let lastUpdated = s3FileUploader({
      data: JSON.stringify({ date: new Date() }),
      fileName: process.env.ADDON_LAST_UPDATED_FILENAME,
      contentType: 'application/json'
    });
    await lastUpdated();

    console.log('--> Done updating %s addons.', addons.length);
    db.close();
    printTotalTime();
    process.exit(0);
  } catch (error) {
    console.error('--> ERROR:', error);
  }
}

run();
<commit_msg>Update the the URL on xml feed<commit_after>/* eslint-disable camelcase */
/* eslint-disable no-process-exit */
require('dotenv').config();

const csv = require('to-csv');

const emberAddons = require('./lib/ember-addons');
const createRssGenerator = require('./lib/rss');
const createS3FileUploader = require('./lib/s3');
const createDatabase = require('./lib/db');
const formatStats = require('./lib/format-stats');

function createTimer() {
  let startTime = new Date().getTime();

  return function() {
    let totalTime = (new Date().getTime() - startTime) / 1000;
    console.log('--> Duration: ' + totalTime + 's');
  };
}

const printTotalTime = createTimer();

// Init...
const db = createDatabase({
  databaseURL: process.env.DATABASE_URL
});

const rssGenerator = createRssGenerator({
  language: 'en',
  pubDate: new Date(),
  title: 'Ember Addons',
  description: 'Listing hundreds of modules that extend ember-cli.',
  feed_url: 'https://io-builtwithember-addons-data.s3.amazonaws.com/feed.xml',
  site_url: 'https://www.emberaddons.com/'
});

const s3FileUploader = createS3FileUploader({
  key: process.env.AWS_ACCESS_KEY,
  secret: process.env.AWS_SECRET_KEY,
  bucket: process.env.AWS_BUCKET_NAME
});

// Check if we need an update
async function run() {
  console.log('--> Starting...');

  try {
    console.log('--> Getting all addons from npm...');
    let allAddons = await emberAddons.getAll();

    console.log('--> Fetching data from npm registry...');
    let addons = await emberAddons.getDetails(allAddons);

    let lastCount = await db.getLatestTotalMetric();
    if (lastCount !== allAddons.length) {
      console.log('--> Updating total metric...');
      await db.updateTotalMetric(addons.length);
    } else {
      console.log('--> Skip update total metric...');
    }

    console.log('--> Creating Feed...');
    let rssFeed = rssGenerator(addons);

    console.log('--> Creating stats.csv...');
    let rows = await db.getMetric('total');
    let stats = formatStats(rows);

    let uploadAddons = s3FileUploader({
      data: JSON.stringify(addons),
      fileName: process.env.ADDON_JSON_FILENAME,
      contentType: 'application/json'
    });
    await uploadAddons();

    let uploadFeed = s3FileUploader({
      data: rssFeed,
      fileName: process.env.FEED_FILENAME,
      contentType: 'application/rss+xml'
    });
    await uploadFeed();

    let uploadStats = s3FileUploader({
      data: csv(stats),
      fileName: process.env.STATS_FILENAME,
      contentType: 'text/csv',
      compressData: false
    });
    await uploadStats();

    let lastUpdated = s3FileUploader({
      data: JSON.stringify({ date: new Date() }),
      fileName: process.env.ADDON_LAST_UPDATED_FILENAME,
      contentType: 'application/json'
    });
    await lastUpdated();

    console.log('--> Done updating %s addons.', addons.length);
    db.close();
    printTotalTime();
    process.exit(0);
  } catch (error) {
    console.error('--> ERROR:', error);
  }
}

run();
<|endoftext|>


<commit_before>"use strict";

const ROUND_DURATION = 5000;
const WAIT_DURATION = 3000;

const STINGS_PER_PLAYER = 6;
const BASE_HIDE_CHANCE = 0.05;

exports.game = "bees";
exports.aliases = ["meme", "memes"];

class BeesGame extends Rooms.botGame {
    constructor(room) {
        super(room);

        this.gameId = "bees";
        this.gameName = "BEES";

        this.answerCommand = "special";
        this.state = "signups";
        this.allowJoins = true;

        this.round = 0;
        this.ranCount = 0;

        this.beesReleased = 0;

        this.sendRoom(`A new game of BEES is starting! Use \`\`${this.room.commandCharacter[0]}join\`\` to join the game.`);
    }

    onStart() {
        if (this.userList.length < 2 || this.state !== "signups") return false;
        this.state = "started";
        this.sendRoom(`Use \`\`${this.room.commandCharacter[0]}run\`\` to escape the swarm of bees.  You can choose not to run and there will be a variable chance that the bees do not notice you.`);

        this.startCount = this.userList.length;

        this.onBeforeTurn();
    }

    onBeforeTurn() {
        this.beesReleased = 0;
        this.round++;

        let pl = this.buildPlayerList();
        this.sendRoom(`Round ${this.round} | Players (${pl.count}): ${pl.players}`);
        this.timer = setTimeout(() => this.onInitTurn(), WAIT_DURATION);
    }

    onInitTurn() {
        this.beesReleased = 1;
        this.bigSwarm = Math.random() > 0.75;
        this.ranCount = 0;

        this.sendRoom(`A ${this.bigSwarm ? "big " : ""}swarm of ${["killer", "angry", "fuzzy, yellow", "bumble", "dangerous", "poisonous"][Math.floor(Math.random() * 6)]} bees has appeared!`);

        this.timer = setTimeout(() => this.onAfterTurn(), ROUND_DURATION);
    }

    onAfterTurn() {
        this.beesReleased = 0;
        let stungCount = Math.ceil(this.userList.length / 5) + (this.bigSwarm ? this.userList.length > 10 ? 2 : 1 : 0);

        // chance of successfully hiding
        let hideChance = (1 / this.userList.length) * 0.8;
        hideChance = hideChance < BASE_HIDE_CHANCE ? BASE_HIDE_CHANCE : hideChance;

        // count the number of people who got stung when hiding
        let hidStung = [];
        let hidSuccess = [];
        let usersRan = [];

        // determine those who didnt run first
        for (let u in this.users) {
            let player = this.users[u];
            let ran = player.ran + 0;
            delete player.ran;

            // for players who didnt run!
            if (!ran) {
                if (Math.random() <= hideChance) {
                    hidSuccess.push(player);
                    continue;
                }

                hidStung.push(player);
                continue;
            }

            usersRan.push({player: player, id: ran});
        }

        if (hidSuccess.length) this.sendRoom(`The bees did not notice ${hidSuccess.map(p => p.name).join(", ")}!`);

        stungCount -= hidStung.length;
        if (hidStung.length) {
            this.sendRoom(`${hidStung.map(p => p.name).join(", ")} tried to avoid the bees' attention, but they failed and got stung!`);
            hidStung.forEach(p => this.eliminate(p.userid));
        }

        usersRan = usersRan.sort((a, b) => a.id - b.id);

        if (stungCount > 0) {
            let stung = usersRan.slice(-stungCount);
            if (stung.length) {
                this.sendRoom(`${stung.map(p => p.player.name).join(", ")} ran too slowly and got stung!`);
                stung.forEach(p => this.eliminate(p.player.userid));
            }
        }

        // now parse win/game conditions
        if (this.userList.length === 0) {
            this.sendRoom("Everyone has been stung! The bees win!");
            this.onEnd();
        } else if (this.userList.length === 1) {
            this.onEnd(true);
        } else {
            this.onBeforeTurn();
        }
    }

    eliminate(userid) {
        this.userList.splice(this.userList.indexOf(userid), 1);
        delete this.users[userid];
    }

    onRun(user) {
        let player = this.users[user.userid];
        if (!player || !this.beesReleased || "ran" in player) return;

        player.ran = this.beesReleased ? ++this.ranCount : 0;
    }

    onEnd(winner) {
        if (winner) {
            this.sendRoom(`Congratulations to ${this.users[this.userList[0]].name} for outsmarting the bees and winning the game!`);

            Leaderboard.onWin("bees", this.room, this.userList[0], this.startCount);
        }
        this.destroy();
    }
}

exports.commands = {
    bees: function (target, room, user) {
        if (!room || !this.can("games")) return false;
        if (room.game) return this.send("There is already a game going on in this room! (" + room.game.gameName + ")");
        room.game = new BeesGame(room);
    },

    run: function (target, room, user) {
        if (!room || !room.game || !room.game.gameId === "bees") return false;
        room.game.onRun(user);
    },
};<commit_msg>Bees: Early run counts as hide<commit_after>"use strict";

const ROUND_DURATION = 5000;
const WAIT_DURATION = 3000;

const STINGS_PER_PLAYER = 6;
const BASE_HIDE_CHANCE = 0.05;

exports.game = "bees";
exports.aliases = ["meme", "memes"];

class BeesGame extends Rooms.botGame {
    constructor(room) {
        super(room);

        this.gameId = "bees";
        this.gameName = "BEES";

        this.answerCommand = "special";
        this.state = "signups";
        this.allowJoins = true;

        this.round = 0;
        this.ranCount = 0;

        this.beesReleased = 0;

        this.sendRoom(`A new game of BEES is starting! Use \`\`${this.room.commandCharacter[0]}join\`\` to join the game.`);
    }

    onStart() {
        if (this.userList.length < 2 || this.state !== "signups") return false;
        this.state = "started";
        this.sendRoom(`Use \`\`${this.room.commandCharacter[0]}run\`\` to escape the swarm of bees.  You can choose not to run and there will be a variable chance that the bees do not notice you.`);

        this.startCount = this.userList.length;

        this.onBeforeTurn();
    }

    onBeforeTurn() {
        this.beesReleased = 0;
        this.round++;

        let pl = this.buildPlayerList();
        this.sendRoom(`Round ${this.round} | Players (${pl.count}): ${pl.players}`);
        this.timer = setTimeout(() => this.onInitTurn(), WAIT_DURATION);
    }

    onInitTurn() {
        this.beesReleased = 1;
        this.bigSwarm = Math.random() > 0.75;
        this.ranCount = 0;

        this.sendRoom(`A ${this.bigSwarm ? "big " : ""}swarm of ${["killer", "angry", "fuzzy, yellow", "bumble", "dangerous", "poisonous"][Math.floor(Math.random() * 6)]} bees has appeared!`);

        this.timer = setTimeout(() => this.onAfterTurn(), ROUND_DURATION);
    }

    onAfterTurn() {
        this.beesReleased = 0;
        let stungCount = Math.ceil(this.userList.length / 5) + (this.bigSwarm ? this.userList.length > 10 ? 2 : 1 : 0);

        // chance of successfully hiding
        let hideChance = (1 / this.userList.length) * 0.8;
        hideChance = hideChance < BASE_HIDE_CHANCE ? BASE_HIDE_CHANCE : hideChance;

        // count the number of people who got stung when hiding
        let hidStung = [];
        let hidSuccess = [];
        let usersRan = [];

        // determine those who didnt run first
        for (let u in this.users) {
            let player = this.users[u];
            let ran = player.ran + 0;
            delete player.ran;

            // for players who didnt run!
            if (!ran) {
                if (Math.random() <= hideChance) {
                    hidSuccess.push(player);
                    continue;
                }

                hidStung.push(player);
                continue;
            }

            usersRan.push({player: player, id: ran});
        }

        if (hidSuccess.length) this.sendRoom(`The bees did not notice ${hidSuccess.map(p => p.name).join(", ")}!`);

        stungCount -= hidStung.length;
        if (hidStung.length) {
            this.sendRoom(`${hidStung.map(p => p.name).join(", ")} tried to avoid the bees' attention, but they failed and got stung!`);
            hidStung.forEach(p => this.eliminate(p.userid));
        }

        usersRan = usersRan.sort((a, b) => a.id - b.id);

        if (stungCount > 0) {
            let stung = usersRan.slice(-stungCount);
            if (stung.length) {
                this.sendRoom(`${stung.map(p => p.player.name).join(", ")} ran too slowly and got stung!`);
                stung.forEach(p => this.eliminate(p.player.userid));
            }
        }

        // now parse win/game conditions
        if (this.userList.length === 0) {
            this.sendRoom("Everyone has been stung! The bees win!");
            this.onEnd();
        } else if (this.userList.length === 1) {
            this.onEnd(true);
        } else {
            this.onBeforeTurn();
        }
    }

    eliminate(userid) {
        this.userList.splice(this.userList.indexOf(userid), 1);
        delete this.users[userid];
    }

    onRun(user) {
        let player = this.users[user.userid];
        if (!player || this.state !== "started" || "ran" in player) return;

        player.ran = this.beesReleased ? ++this.ranCount : 0;
    }

    onEnd(winner) {
        if (winner) {
            this.sendRoom(`Congratulations to ${this.users[this.userList[0]].name} for outsmarting the bees and winning the game!`);

            Leaderboard.onWin("bees", this.room, this.userList[0], this.startCount);
        }
        this.destroy();
    }
}

exports.commands = {
    bees: function (target, room, user) {
        if (!room || !this.can("games")) return false;
        if (room.game) return this.send("There is already a game going on in this room! (" + room.game.gameName + ")");
        room.game = new BeesGame(room);
    },

    run: function (target, room, user) {
        if (!room || !room.game || !room.game.gameId === "bees") return false;
        room.game.onRun(user);
    },
};<|endoftext|>


<commit_before>import API from "api"
import autobind from "autobind-decorator"
import MosaicLayout from "components/MosaicLayout"
import { GQL_REPORT_FIELDS } from "components/ReportCollection"
import _isEqual from "lodash/isEqual"
import PropTypes from "prop-types"
import React, { Component } from "react"

const d3 = require("d3")

export const propTypes = {
  queryParams: PropTypes.object,
  showLoading: PropTypes.func.isRequired,
  hideLoading: PropTypes.func.isRequired,
  style: PropTypes.object
}

export default class ReportsVisualisation extends Component {
  get chartId() {
    return this.CHART_ID
  }

  get gqlChartFields() {
    return this.GQL_CHART_FIELDS
  }

  get visualizations() {
    return this.VISUALIZATIONS
  }

  get initialLayout() {
    return this.INITIAL_LAYOUT
  }

  get description() {
    return this.DESCRIPTION
  }

  get selectedBarClass() {
    return "selected-bar"
  }

  get gqlReportFields() {
    return GQL_REPORT_FIELDS
  }

  get gqlMapFields() {
    return /* GraphQL */ `
      uuid
      intent
      location { uuid name lat lng }
    `
  }

  render() {
    return (
      <MosaicLayout
        style={this.props.style}
        visualizations={this.visualizations}
        initialNode={this.initialLayout}
        description={this.description}
      />
    )
  }

  fetchData() {
    this.setState({ isLoading: true })
    this.props.showLoading()
    Promise.all([
      // Query used by the chart
      this.fetchChartData(this.runChartQuery(this.chartQueryParams())),
      this.fetchReportData(true)
    ]).then(() => this.props.hideLoading())
  }

  fetchReportData(includeAll) {
    // Query used by the reports collection
    const queries = [
      this.runReportsQuery(this.reportsQueryParams(false), false)
    ]
    if (includeAll) {
      // Query used by the map
      queries.push(this.runReportsQuery(this.reportsQueryParams(true), true))
    }
    return Promise.all(queries).then(values => {
      const stateUpdate = {
        updateChart: false, // only update the report list
        reports: values[0].reportList
      }
      if (includeAll) {
        Object.assign(stateUpdate, {
          allReports: values[1].reportList.list
        })
      }
      this.setState(stateUpdate)
    })
  }

  chartQueryParams = () => {
    const chartQueryParams = {}
    Object.assign(chartQueryParams, this.props.queryParams)
    Object.assign(chartQueryParams, {
      pageSize: 0 // retrieve all the filtered reports
    })
    return chartQueryParams
  }

  runChartQuery = chartQueryParams => {
    return API.query(
      /* GraphQL */ `
      reportList(query:$chartQueryParams) {
        totalCount, list {
          ${this.gqlChartFields}
        }
      }`,
      { chartQueryParams },
      "($chartQueryParams: ReportSearchQueryInput)"
    )
  }

  reportsQueryParams = forMap => {
    const reportsQueryParams = {}
    Object.assign(reportsQueryParams, this.props.queryParams)
    Object.assign(reportsQueryParams, {
      pageNum: forMap ? 0 : this.state.reportsPageNum,
      pageSize: forMap ? 0 : 10
    })
    if (this.state.focusedSelection) {
      Object.assign(reportsQueryParams, this.additionalReportParams)
    }
    return reportsQueryParams
  }

  runReportsQuery = (reportsQueryParams, forMap) => {
    return API.query(
      /* GraphQL */ `
      reportList(query:$reportsQueryParams) {
        pageNum, pageSize, totalCount, list {
          ${forMap ? this.gqlMapFields : this.gqlReportFields}
        }
      }`,
      { reportsQueryParams },
      "($reportsQueryParams: ReportSearchQueryInput)"
    )
  }

  @autobind
  goToReportsPage(newPage) {
    this.setState({ updateChart: false, reportsPageNum: newPage }, () =>
      this.fetchReportData(false)
    )
  }

  @autobind
  goToSelection(item, chartId) {
    chartId = chartId || this.chartId
    this.updateHighlight(null, true, chartId)
    // Note: we set updateChart to false as we do not want to re-render the chart
    // when changing the focus.
    if (!item || item === this.state.focusedSelection) {
      this.setState(
        { updateChart: false, reportsPageNum: 0, focusedSelection: "" },
        () => this.fetchReportData(true)
      )
    } else {
      this.setState(
        { updateChart: false, reportsPageNum: 0, focusedSelection: item },
        () => this.fetchReportData(true)
      )
      this.updateHighlight(item, false, chartId)
    }
  }

  @autobind
  updateHighlight(focusedSelectionId, clear, chartId) {
    chartId = chartId || this.chartId
    if (clear) {
      // remove highlighting of the bars
      d3.selectAll("#" + chartId + " rect").classed(
        this.selectedBarClass,
        false
      )
    } else if (focusedSelectionId) {
      // highlight the bar corresponding to the selected day of the week
      d3.select("#" + chartId + " #bar_" + focusedSelectionId).classed(
        this.selectedBarClass,
        true
      )
    }
  }

  componentDidMount() {
    this.setState(
      {
        reportsPageNum: 0,
        focusedSelection: "" // reset focus when changing the queryParams
      },
      () => this.fetchData()
    )
  }

  componentDidUpdate(prevProps, prevState) {
    if (!_isEqual(prevProps.queryParams, this.props.queryParams)) {
      this.setState(
        {
          reportsPageNum: 0,
          focusedSelection: "" // reset focus when changing the queryParams
        },
        () => this.fetchData()
      )
    }
  }

  @autobind
  showPopover(graphPopover, hoveredBar) {
    this.setState({ graphPopover, hoveredBar })
  }

  @autobind
  hidePopover() {
    this.setState({ graphPopover: null, hoveredBar: null })
  }
}
<commit_msg>NCI-Agency/anet#1723: Also retrieve report state for the calendar view<commit_after>import API from "api"
import autobind from "autobind-decorator"
import MosaicLayout from "components/MosaicLayout"
import { GQL_REPORT_FIELDS } from "components/ReportCollection"
import _isEqual from "lodash/isEqual"
import PropTypes from "prop-types"
import React, { Component } from "react"

const d3 = require("d3")

export const propTypes = {
  queryParams: PropTypes.object,
  showLoading: PropTypes.func.isRequired,
  hideLoading: PropTypes.func.isRequired,
  style: PropTypes.object
}

export default class ReportsVisualisation extends Component {
  get chartId() {
    return this.CHART_ID
  }

  get gqlChartFields() {
    return this.GQL_CHART_FIELDS
  }

  get visualizations() {
    return this.VISUALIZATIONS
  }

  get initialLayout() {
    return this.INITIAL_LAYOUT
  }

  get description() {
    return this.DESCRIPTION
  }

  get selectedBarClass() {
    return "selected-bar"
  }

  get gqlReportFields() {
    return GQL_REPORT_FIELDS
  }

  get gqlMapFields() {
    return /* GraphQL */ `
      uuid
      intent
      state
      location { uuid name lat lng }
    `
  }

  render() {
    return (
      <MosaicLayout
        style={this.props.style}
        visualizations={this.visualizations}
        initialNode={this.initialLayout}
        description={this.description}
      />
    )
  }

  fetchData() {
    this.setState({ isLoading: true })
    this.props.showLoading()
    Promise.all([
      // Query used by the chart
      this.fetchChartData(this.runChartQuery(this.chartQueryParams())),
      this.fetchReportData(true)
    ]).then(() => this.props.hideLoading())
  }

  fetchReportData(includeAll) {
    // Query used by the reports collection
    const queries = [
      this.runReportsQuery(this.reportsQueryParams(false), false)
    ]
    if (includeAll) {
      // Query used by the map and calendar
      queries.push(this.runReportsQuery(this.reportsQueryParams(true), true))
    }
    return Promise.all(queries).then(values => {
      const stateUpdate = {
        updateChart: false, // only update the report list
        reports: values[0].reportList
      }
      if (includeAll) {
        Object.assign(stateUpdate, {
          allReports: values[1].reportList.list
        })
      }
      this.setState(stateUpdate)
    })
  }

  chartQueryParams = () => {
    const chartQueryParams = {}
    Object.assign(chartQueryParams, this.props.queryParams)
    Object.assign(chartQueryParams, {
      pageSize: 0 // retrieve all the filtered reports
    })
    return chartQueryParams
  }

  runChartQuery = chartQueryParams => {
    return API.query(
      /* GraphQL */ `
      reportList(query:$chartQueryParams) {
        totalCount, list {
          ${this.gqlChartFields}
        }
      }`,
      { chartQueryParams },
      "($chartQueryParams: ReportSearchQueryInput)"
    )
  }

  reportsQueryParams = forMapOrCalendar => {
    const reportsQueryParams = {}
    Object.assign(reportsQueryParams, this.props.queryParams)
    Object.assign(reportsQueryParams, {
      pageNum: forMapOrCalendar ? 0 : this.state.reportsPageNum,
      pageSize: forMapOrCalendar ? 0 : 10
    })
    if (this.state.focusedSelection) {
      Object.assign(reportsQueryParams, this.additionalReportParams)
    }
    return reportsQueryParams
  }

  runReportsQuery = (reportsQueryParams, forMapOrCalendar) => {
    return API.query(
      /* GraphQL */ `
      reportList(query:$reportsQueryParams) {
        pageNum, pageSize, totalCount, list {
          ${forMapOrCalendar ? this.gqlMapFields : this.gqlReportFields}
        }
      }`,
      { reportsQueryParams },
      "($reportsQueryParams: ReportSearchQueryInput)"
    )
  }

  @autobind
  goToReportsPage(newPage) {
    this.setState({ updateChart: false, reportsPageNum: newPage }, () =>
      this.fetchReportData(false)
    )
  }

  @autobind
  goToSelection(item, chartId) {
    chartId = chartId || this.chartId
    this.updateHighlight(null, true, chartId)
    // Note: we set updateChart to false as we do not want to re-render the chart
    // when changing the focus.
    if (!item || item === this.state.focusedSelection) {
      this.setState(
        { updateChart: false, reportsPageNum: 0, focusedSelection: "" },
        () => this.fetchReportData(true)
      )
    } else {
      this.setState(
        { updateChart: false, reportsPageNum: 0, focusedSelection: item },
        () => this.fetchReportData(true)
      )
      this.updateHighlight(item, false, chartId)
    }
  }

  @autobind
  updateHighlight(focusedSelectionId, clear, chartId) {
    chartId = chartId || this.chartId
    if (clear) {
      // remove highlighting of the bars
      d3.selectAll("#" + chartId + " rect").classed(
        this.selectedBarClass,
        false
      )
    } else if (focusedSelectionId) {
      // highlight the bar corresponding to the selected day of the week
      d3.select("#" + chartId + " #bar_" + focusedSelectionId).classed(
        this.selectedBarClass,
        true
      )
    }
  }

  componentDidMount() {
    this.setState(
      {
        reportsPageNum: 0,
        focusedSelection: "" // reset focus when changing the queryParams
      },
      () => this.fetchData()
    )
  }

  componentDidUpdate(prevProps, prevState) {
    if (!_isEqual(prevProps.queryParams, this.props.queryParams)) {
      this.setState(
        {
          reportsPageNum: 0,
          focusedSelection: "" // reset focus when changing the queryParams
        },
        () => this.fetchData()
      )
    }
  }

  @autobind
  showPopover(graphPopover, hoveredBar) {
    this.setState({ graphPopover, hoveredBar })
  }

  @autobind
  hidePopover() {
    this.setState({ graphPopover: null, hoveredBar: null })
  }
}
<|endoftext|>


<commit_before>/************************************************
 * jQuery iOS App Switcher
 *	- by Ryan Scherf
 *
 * Convert your site's links to URL
 * schemes to deeplink to iOS apps.
 ************************************************/

(function($) {
	$.fn.switcher = function(options) {

		var settings = $.extend({
			additionalSchemas : [],
			debug							: false,
			iOS								: /(iPad|iPhone|iPod)/g.test(navigator.userAgent),
			usernameFromURL 	: true, // or use data-username html attribute
    }, options);

		if(settings.iOS || settings.debug)
		{
			// Define the native apps to deeplink
			var services = [
				{
					pattern	: /(facebook)/g,
					scheme	: function(username) {

						var facebookId = "";

						if(isNaN(parseInt(username)))
						{
							$.ajax({
								url			 : "https://graph.facebook.com/" + username,
								type 		 : "get",
								dataType : "json",
								async		 : false,
							}).done(function(response) {
								facebookId = response.id;
							});
						}
						else
						{
							facebookId = username;
						}

						return "fb://profile/" + facebookId;
					}
				},
				{
					pattern : /(linkedin)/g,
					scheme  : function(username) {
						return "linkedin://profile/" + username
					}
				},
				{
					pattern	: /(instagram)/g,
					scheme	: function(username) {
						return "instagram://user?username=" + username
					}
				},
				{
					pattern	: /(quirky)/g,
					scheme	: function(username) {
						return "quirky:///" + username
					}
				},
				{
					pattern	: /(twitter)/g,
					scheme	: function(username) {
						return "twitter://user?screen_name=" + username
					}
				},
			];

			// Add on any user defined schemas
			services = services.concat(settings.additionalSchemas);

			// Iterate through the set
	    this.each(function() {

	  		var $this  = $(this),
					href  	 = $(this).attr("href");

				if(settings.usernameFromURL)
					username = href.split(".com/")[1];
				else
					username = $this.data("username");

				$(services).each(function(i) {
					if(services[i].pattern.test(href))
					{
						$this.attr("href", services[i].scheme(username));
						return false;
					}
				});
	    });

	  }

    return this;

	};
}(jQuery));
<commit_msg>Refactor to always include data-username<commit_after>/************************************************
 * jQuery iOS App Switcher
 *	- by Ryan Scherf
 *
 * Convert your site's links to URL
 * schemes to deeplink to iOS apps.
 ************************************************/

(function($) {
	$.fn.switcher = function(options) {

		var settings = $.extend({
			additionalSchemas : [],
			debug							: false,
			iOS								: /(iPad|iPhone|iPod)/g.test(navigator.userAgent)
    }, options);

		if(settings.iOS || settings.debug)
		{
			// Define the native apps to deeplink
			var services = [
				{
					pattern	: /(facebook)/g,
					scheme	: function(username) {

						var facebookId = "";

						if(isNaN(parseInt(username)))
						{
							$.ajax({
								url			 : "https://graph.facebook.com/" + username,
								type 		 : "get",
								dataType : "json",
								async		 : false,
							}).done(function(response) {
								facebookId = response.id;
							});
						}
						else
						{
							facebookId = username;
						}

						return "fb://profile/" + facebookId;
					}
				},
				{
					pattern : /(linkedin)/g,
					scheme  : function(username) {
						return "linkedin://#profile/" + username
					}
				},
				{
					pattern	: /(instagram)/g,
					scheme	: function(username) {
						return "instagram://user?username=" + username
					}
				},
				{
					pattern	: /(quirky)/g,
					scheme	: function(username) {
						return "quirky:///" + username
					}
				},
				{
					pattern	: /(twitter)/g,
					scheme	: function(username) {
						return "twitter://user?screen_name=" + username
					}
				},
			];

			// Add on any user defined schemas
			services = services.concat(settings.additionalSchemas);

			// Iterate through the set
	    this.each(function() {

	  		var $this    = $(this),
					href  	 	 = $(this).attr("href"),
					identifier = href.split(".com/");

				if(identifier.length > 1)
					username = identifier[1];
				else if($this.data("username") != "")
					username = $this.data("username");
				else
					username = "notfound";

				$(services).each(function(i) {
					if(services[i].pattern.test(href))
					{
						$this.attr("href", services[i].scheme(username));
						return false;
					}
				});
	    });

	  }

    return this;

	};
}(jQuery));
<|endoftext|>


<commit_before>'use strict';

const videoClip = require('./movie.js');
const remote = require('electron').remote;
const Menu = require('electron').remote.Menu;
const MenuItem = require('electron').remote.MenuItem;
let video;

function Init() {
  video = document.querySelector('video');
  BindEvents();
}

function BindEvents() {
  // Drag and Drop holder.
  const holder = document.getElementById('holder');
  // Placehold text in holder.
  const dragText = document.getElementById('drag-text');
  const doScale = document.querySelector('#do-scale');
  const makeBtn = document.querySelector('#make-gif');
  const resetBtn = document.querySelector('#reset');
  const gvSwitch = document.querySelector('#gif-video-switch');
  // Disable drag and drop event for document.
  document.addEventListener('dragover', Idle, false);
  document.addEventListener('drop', Idle, false);

  holder.ondragover = Idle;
  holder.ondragleave = holder.ondragend = Idle;
  holder.ondrop = LoadVideoFromDrop;

  doScale.onchange = ToggleScale;

  makeBtn.addEventListener('click', function(){videoClip.MakeGIF(UpdateGIF);});
  resetBtn.addEventListener('click', Reset);
  gvSwitch.addEventListener('click', function(){ToggleGV(event);});

  const bind = new Bind({clip: videoClip}, {
    'clip.video': 'input#video-input',
    'clip.start': {
      dom: 'input#start-input',
      callback: CalDuration,
    },
    'clip.end': {
      dom: 'input#end-input',
      callback: CalDuration,
    },
    'clip.width': 'input#width-input',
    'clip.height': 'input#height-input',
    'clip.scale': {
      dom: 'input#scale-input',
      callback: videoClip.UpdateWithScale,
    },
    'clip.fps': 'input#fps-input',
    'clip.speed': 'input#speed-input',
    'clip.mirror': 'input#do-mirror'
    });
}

function UpdateGIF(gifFile) {
  const gif = document.querySelector('#gif');
  const gv = document.querySelector('#gif-video-switch');
  gif.innerHTML = '';
  if (gv.checked) gv.click();
}

function ToggleGV(event) {
  const video = document.querySelector('video');
  const gif = document.querySelector('#gif');
  const dragText = document.getElementById('drag-text');
  if (event.target.checked) {
    video.classList.remove('hidden');
    gif.className += ' hidden';
    dragText.className += ' hidden';
  } else {
    video.className += ' hidden';
    gif.classList.remove('hidden');
    dragText.className += ' hidden';
  }
}

function ToggleScale() {
  const doScale = document.querySelector('#do-scale');
  const scaleInput = document.querySelector('input#scale-input');
  const heightInput = document.querySelector('input#height-input');
  const widthInput = document.querySelector('input#width-input');
  if (doScale.checked) {
    scaleInput.removeAttribute('disabled');
    heightInput.setAttribute('disabled', '');
    widthInput.setAttribute('disabled', '');
  } else {
    scaleInput.setAttribute('disabled', '');
    heightInput.removeAttribute('disabled');
    widthInput.removeAttribute('disabled');
  }
}

function CalDuration() {
  const duration = document.querySelector('input#duration-input');
  duration.value = videoClip.Duration();
}

function Idle(e) {
  e.preventDefault();
  return false;
}

function VideoError(msg) {
  console.log(msg);
}

function LoadVideo(videoFile) {
  videoClip.LoadVideo(videoFile);
}

function LoadVideoFromDrop(e) {
  e.preventDefault();

  const dragText = document.getElementById('drag-text');
  const file = e.dataTransfer.files[0];

  videoClip.LoadVideo(file.path);

  video.src = file.path;
  dragText.className += ' hidden';
  video.classList.remove('hidden');
  setTimeout(function() {
    if (!video.videoWidth) VideoError('Cannot play video');
  }, 200);
}

function Reset() {
  // Reset options to values of video file.
  const doScale = document.querySelector('input#do-scale');
  doScale.checked = false;
  ToggleScale();
  videoClip.Reset();
}

window.onload = Init;
<commit_msg>Create menu and handle open file in menu<commit_after>'use strict';

const videoClip = require('./movie.js');
const remote = require('electron').remote;
const dialog = remote.dialog;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
const video = document.querySelector('video');

function Init() {
  CreateMenu();
  BindEvents();
}

function CreateMenu() {
  const template = [
  {
    label: 'File',
    submenu: [
    {
        label: 'Open Video',
        accelerator: 'CmdOrCtrl+O',
        click: function(item, win) {LoadVideo();},
    }]}];

  if (process.platform == 'darwin') {
  const name = require('electron').remote.app.getName();
  template.unshift({
    label: name,
    submenu: [
      {
        label: 'About ' + name,
        role: 'about'
      },
      {
        type: 'separator'
      },
      {
        label: 'Services',
        role: 'services',
        submenu: []
      },
      {
        type: 'separator'
      },
      {
        label: 'Hide ' + name,
        accelerator: 'Command+H',
        role: 'hide'
      },
      {
        label: 'Hide Others',
        accelerator: 'Command+Alt+H',
        role: 'hideothers'
      },
      {
        label: 'Show All',
        role: 'unhide'
      },
      {
        type: 'separator'
      },
      {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function() { app.quit(); }
      },
    ]
  });
  }

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

function BindEvents() {
  // Drag and Drop holder.
  const holder = document.getElementById('holder');
  // Placehold text in holder.
  const dragText = document.getElementById('drag-text');
  const doScale = document.querySelector('#do-scale');
  const makeBtn = document.querySelector('#make-gif');
  const resetBtn = document.querySelector('#reset');
  const gvSwitch = document.querySelector('#gif-video-switch');
  // Disable drag and drop event for document.
  document.addEventListener('dragover', Idle, false);
  document.addEventListener('dragleave', Idle, false);
  document.addEventListener('dragend', Idle, false);
  document.addEventListener('drop', Idle, false);

  holder.ondragover = Idle;
  holder.ondragleave = holder.ondragend = Idle;
  holder.ondrop = LoadVideoFromDrop;

  doScale.onchange = ToggleScale;

  makeBtn.addEventListener('click', function(){videoClip.MakeGIF(UpdateGIF);});
  resetBtn.addEventListener('click', Reset);
  gvSwitch.addEventListener('click', function(){ToggleGV(event);});

  const bind = new Bind({clip: videoClip}, {
    'clip.video': 'input#video-input',
    'clip.start': {
      dom: 'input#start-input',
      callback: CalDuration,
    },
    'clip.end': {
      dom: 'input#end-input',
      callback: CalDuration,
    },
    'clip.width': 'input#width-input',
    'clip.height': 'input#height-input',
    'clip.scale': {
      dom: 'input#scale-input',
      callback: videoClip.UpdateWithScale,
    },
    'clip.fps': 'input#fps-input',
    'clip.speed': 'input#speed-input',
    'clip.mirror': 'input#do-mirror'
    });
}

function UpdateGIF(gifFile) {
  const gif = document.querySelector('#gif');
  const gv = document.querySelector('#gif-video-switch');
  gif.innerHTML = '';
  if (gv.checked) gv.click();
}

function ToggleGV(event) {
  const video = document.querySelector('video');
  const gif = document.querySelector('#gif');
  const dragText = document.getElementById('drag-text');
  if (event.target.checked) {
    video.classList.remove('hidden');
    gif.className += ' hidden';
    dragText.className += ' hidden';
  } else {
    video.className += ' hidden';
    gif.classList.remove('hidden');
    dragText.className += ' hidden';
  }
}

function ToggleScale() {
  const doScale = document.querySelector('#do-scale');
  const scaleInput = document.querySelector('input#scale-input');
  const heightInput = document.querySelector('input#height-input');
  const widthInput = document.querySelector('input#width-input');
  if (doScale.checked) {
    scaleInput.removeAttribute('disabled');
    heightInput.setAttribute('disabled', '');
    widthInput.setAttribute('disabled', '');
  } else {
    scaleInput.setAttribute('disabled', '');
    heightInput.removeAttribute('disabled');
    widthInput.removeAttribute('disabled');
  }
}

function CalDuration() {
  const duration = document.querySelector('input#duration-input');
  duration.value = videoClip.Duration();
}

function Idle(e) {
  e.preventDefault();
  return false;
}

function VideoError(msg) {
  console.log(msg);
}

function LoadVideo() {
  videoClip.OpenVideoDialog(AfterLoadingVideo);
}

function AfterLoadingVideo(videoFile){
  const dragText = document.getElementById('drag-text');
  const video = document.querySelector('video');
  video.src = videoFile;
  // Hide text if haven't.
  if (! dragText.classList.contains('hidden')) {
    dragText.className += 'hidden';
  }
  // Show video if haven't.
  if (video.classList.contains('hidden')) {
    video.classList.remove('hidden');
  }
  setTimeout(function() {
    if (!video.videoWidth) VideoError('Cannot play video');
  }, 500);
}

function LoadVideoFromDrop(e) {
  e.preventDefault();

  const dragText = document.getElementById('drag-text');
  const file = e.dataTransfer.files[0];

  videoClip.LoadVideo(file.path);

  video.src = file.path;
  dragText.className += ' hidden';
  video.classList.remove('hidden');
  setTimeout(function() {
    if (!video.videoWidth) VideoError('Cannot play video');
  }, 500);
}

function Reset() {
  // Reset options to values of video file.
  const doScale = document.querySelector('input#do-scale');
  doScale.checked = false;
  ToggleScale();
  videoClip.Reset();
}

window.onload = Init;
<|endoftext|>


<commit_before>lobby.transporter.module.create('transporter', function(thisModule) {

thisModule.addSlots(modules.transporter, function(add) {

    add.data('_directory', 'transporter');

});

thisModule.addSlots(transporter.module, function(add) {

  add.data('_directory', '', {category: ['accessing']});

  add.method('name', function () { return this._name; }, {category: ['accessing']});

  add.method('directory', function () { return this._directory; }, {category: ['accessing']});

  add.method('setDirectory', function (d) { this._directory = d; }, {category: ['accessing']});

  add.method('toString', function () { return this.name(); }, {category: ['printing']});

  add.method('objectsThatMightContainSlotsInMe', function () {
    return lobby.transporter.module.cache[this.name()];
  }, {category: ['keeping track of changes']});

  add.method('hasChangedSinceLastFileOut', function () {
    return this._hasChangedSinceLastFileOut;
  }, {category: ['keeping track of changes']});

  add.method('markAsChanged', function () {
    this._hasChangedSinceLastFileOut = true;
  }, {category: ['keeping track of changes']});

  add.method('markAsUnchanged', function () {
    this._hasChangedSinceLastFileOut = false;
  }, {category: ['keeping track of changes']});

  add.method('mirrorsInOrderForFilingOut', function (f) {
    var alreadySeen = bloodyHashTable.copyRemoveAll(); // aaa - remember that mirrors don't hash well; this'll be slow for big modules unless we fix that
    this.objectsThatMightContainSlotsInMe().each(function(obj) {
      var mir = reflect(obj);
      if (! alreadySeen.containsKey(mir)) {
        alreadySeen.put(mir, mir);
      }
    }.bind(this));
    return alreadySeen.values().sort(function(a, b) { var an = a.name(); var bn = b.name(); return an === bn ? 0 : an < bn ? -1 : 1; });
  }, {category: ['transporting']});

  add.method('fileOut', function () {
    var buffer = stringBuffer.create("lobby.transporter.module.create('").append(this.name()).append("', function(thisModule) {\n\n\n");
    this.fileOutSlots(buffer);
    buffer.append("});");

    var doc = buffer.toString();

    // aaa - hack because I haven't managed to get WebDAV working on adamspitz.com yet
    if (URL.source.hostname.include("adamspitz.com")) {
      var uploadScriptURL = "http://adamspitz.com/cgi-bin/savefile.cgi";
      new Ajax.Request(uploadScriptURL, {
        method: 'post',
        contentType: 'text/plain',
        parameters: {fileName: this.name() + ".js", fileContents: doc},
        asynchronous: true,
        onSuccess:   function(transport) { var urlToDownload = transport.responseText; window.open(urlToDownload, 'Download'); }.bind(this),
        onFailure:   function(         ) {alert("Failure. :(");}.bind(this),
        onException: function(r,      e) {alert("Exception. :(");}.bind(this),
      });
    } else {

      var baseDirURL = URL.source.getDirectory().withRelativePath("javascripts/");
      //new FileDirectory(baseDirURL.withRelativePath("javascripts/")).createDirectory(this.directory());
      var moduleDirURL = this.urlForModuleDirectory("non-core/" + this.directory());
      var url = moduleDirURL.withFilename(this.name() + ".js");
      var status = new Resource(Record.newPlainInstance({URL: url})).store(doc, true).getStatus();
      if (! status.isSuccess()) {
        throw "failed to file out " + this + ", status is " + status.code();
      }
    }
  }, {category: ['transporting']});

  add.method('fileOutSlots', function (buffer) {
    var mirs = this.mirrorsInOrderForFilingOut();
    mirs.each(function(mir) {
      buffer.append("thisModule.addSlots(").append(mir.creatorSlotChainExpression()).append(", function(add) {\n\n");
      mir.eachSlot(function(s) {
        if (s.module && s.module() === this) {
          s.fileOutTo(buffer);
        }
      }.bind(this));
      buffer.append("});\n\n\n");
    }.bind(this));
  }, {category: ['transporting']});

  add.method('urlForModuleDirectory', function (directory) {
    if (! directory) { directory = ""; }
    if (directory && directory[directory.length] !== '/') { directory += '/'; }
    var baseDirURL = URL.source.getDirectory().withRelativePath("javascripts/");
    return baseDirURL.withRelativePath(directory);
  }, {category: ['saving to WebDAV']});

  add.method('urlForCoreModulesDirectory', function () {
    return URL.source.getDirectory().withRelativePath("javascripts/fileouts/");
  }, {category: ['saving to WebDAV']});

  add.method('urlForNonCoreModulesDirectory', function () {
    return URL.source.getDirectory().withRelativePath("javascripts/non-core/");
  }, {category: ['saving to WebDAV']});

  add.method('urlForModuleName', function (name, directory) {
    var moduleDirURL = this.urlForModuleDirectory(directory);
    return moduleDirURL.withFilename(name + ".js");
  }, {category: ['saving to WebDAV']});

  add.method('fileIn', function (name) {
    var url = this.urlForModuleName(name, "non-core/");
    var code = FileDirectory.getContent(url);
    eval(code);
    var module = this.existingOneNamed(name);
    if (module) {
      if (module.postFileIn) { module.postFileIn(); }
      return module;
    } else {
      // Could just be some external Javascript library - doesn't have
      // to be one of our modules.
    }
  }, {category: ['transporting']});

  add.method('eachModule', function (f) {
    reflect(lobby.modules).eachNormalSlot(function(s) { f(s.contents().reflectee()); });
  }, {category: ['iterating']});

  add.method('existingOneNamed', function (n) {
    return lobby.modules[n];
  }, {category: ['accessing modules']});

  add.method('changedOnes', function () {
    return Object.newChildOf(enumerator, this, 'eachModule').select(function(m) { return m.hasChangedSinceLastFileOut(); });
  }, {category: ['keeping track of changes']});

});

});
<commit_msg>Oops, forgot to mark the module as unchanged after we file it out.<commit_after>lobby.transporter.module.create('transporter', function(thisModule) {

thisModule.addSlots(modules.transporter, function(add) {

    add.data('_directory', 'transporter');

});

thisModule.addSlots(transporter.module, function(add) {

  add.data('_directory', '', {category: ['accessing']});

  add.method('name', function () { return this._name; }, {category: ['accessing']});

  add.method('directory', function () { return this._directory; }, {category: ['accessing']});

  add.method('setDirectory', function (d) { this._directory = d; }, {category: ['accessing']});

  add.method('toString', function () { return this.name(); }, {category: ['printing']});

  add.method('objectsThatMightContainSlotsInMe', function () {
    return lobby.transporter.module.cache[this.name()];
  }, {category: ['keeping track of changes']});

  add.method('hasChangedSinceLastFileOut', function () {
    return this._hasChangedSinceLastFileOut;
  }, {category: ['keeping track of changes']});

  add.method('markAsChanged', function () {
    this._hasChangedSinceLastFileOut = true;
  }, {category: ['keeping track of changes']});

  add.method('markAsUnchanged', function () {
    this._hasChangedSinceLastFileOut = false;
  }, {category: ['keeping track of changes']});

  add.method('mirrorsInOrderForFilingOut', function (f) {
    var alreadySeen = bloodyHashTable.copyRemoveAll(); // aaa - remember that mirrors don't hash well; this'll be slow for big modules unless we fix that
    this.objectsThatMightContainSlotsInMe().each(function(obj) {
      var mir = reflect(obj);
      if (! alreadySeen.containsKey(mir)) {
        alreadySeen.put(mir, mir);
      }
    }.bind(this));
    return alreadySeen.values().sort(function(a, b) { var an = a.name(); var bn = b.name(); return an === bn ? 0 : an < bn ? -1 : 1; });
  }, {category: ['transporting']});

  add.method('fileOut', function () {
    var buffer = stringBuffer.create("lobby.transporter.module.create('").append(this.name()).append("', function(thisModule) {\n\n\n");
    this.fileOutSlots(buffer);
    buffer.append("});");

    var doc = buffer.toString();

    // aaa - hack because I haven't managed to get WebDAV working on adamspitz.com yet
    if (URL.source.hostname.include("adamspitz.com")) {
      var uploadScriptURL = "http://adamspitz.com/cgi-bin/savefile.cgi";
      new Ajax.Request(uploadScriptURL, {
        method: 'post',
        contentType: 'text/plain',
        parameters: {fileName: this.name() + ".js", fileContents: doc},
        asynchronous: true,
        onSuccess:   function(transport) { var urlToDownload = transport.responseText; window.open(urlToDownload, 'Download'); this.markAsUnchanged();  }.bind(this),
        onFailure:   function(         ) {alert("Failure. :(");}.bind(this),
        onException: function(r,      e) {alert("Exception. :(");}.bind(this),
      });
    } else {

      var baseDirURL = URL.source.getDirectory().withRelativePath("javascripts/");
      //new FileDirectory(baseDirURL.withRelativePath("javascripts/")).createDirectory(this.directory());
      var moduleDirURL = this.urlForModuleDirectory("non-core/" + this.directory());
      var url = moduleDirURL.withFilename(this.name() + ".js");
      var status = new Resource(Record.newPlainInstance({URL: url})).store(doc, true).getStatus();
      if (! status.isSuccess()) {
        throw "failed to file out " + this + ", status is " + status.code();
      }
      this.markAsUnchanged();
    }
  }, {category: ['transporting']});

  add.method('fileOutSlots', function (buffer) {
    var mirs = this.mirrorsInOrderForFilingOut();
    mirs.each(function(mir) {
      buffer.append("thisModule.addSlots(").append(mir.creatorSlotChainExpression()).append(", function(add) {\n\n");
      mir.eachSlot(function(s) {
        if (s.module && s.module() === this) {
          s.fileOutTo(buffer);
        }
      }.bind(this));
      buffer.append("});\n\n\n");
    }.bind(this));
  }, {category: ['transporting']});

  add.method('urlForModuleDirectory', function (directory) {
    if (! directory) { directory = ""; }
    if (directory && directory[directory.length] !== '/') { directory += '/'; }
    var baseDirURL = URL.source.getDirectory().withRelativePath("javascripts/");
    return baseDirURL.withRelativePath(directory);
  }, {category: ['saving to WebDAV']});

  add.method('urlForCoreModulesDirectory', function () {
    return URL.source.getDirectory().withRelativePath("javascripts/fileouts/");
  }, {category: ['saving to WebDAV']});

  add.method('urlForNonCoreModulesDirectory', function () {
    return URL.source.getDirectory().withRelativePath("javascripts/non-core/");
  }, {category: ['saving to WebDAV']});

  add.method('urlForModuleName', function (name, directory) {
    var moduleDirURL = this.urlForModuleDirectory(directory);
    return moduleDirURL.withFilename(name + ".js");
  }, {category: ['saving to WebDAV']});

  add.method('fileIn', function (name) {
    var url = this.urlForModuleName(name, "non-core/");
    var code = FileDirectory.getContent(url);
    eval(code);
    var module = this.existingOneNamed(name);
    if (module) {
      if (module.postFileIn) { module.postFileIn(); }
      return module;
    } else {
      // Could just be some external Javascript library - doesn't have
      // to be one of our modules.
    }
  }, {category: ['transporting']});

  add.method('eachModule', function (f) {
    reflect(lobby.modules).eachNormalSlot(function(s) { f(s.contents().reflectee()); });
  }, {category: ['iterating']});

  add.method('existingOneNamed', function (n) {
    return lobby.modules[n];
  }, {category: ['accessing modules']});

  add.method('changedOnes', function () {
    return Object.newChildOf(enumerator, this, 'eachModule').select(function(m) { return m.hasChangedSinceLastFileOut(); });
  }, {category: ['keeping track of changes']});

});

});
<|endoftext|>


<commit_before>// http://developer.appcelerator.com/question/124014/saving-xml-file-offline-for-read-later
function getData(url, f, win){

if(Ti.Platform.name === 'iPhone OS') {
    var activityStyle = Ti.UI.iPhone.ActivityIndicatorStyle.DARK;
} else {
    var activityStyle = Ti.UI.ActivityIndicatorStyle.DARK;
}
//Show the activity indicator
var activityIndicator = Ti.UI.createActivityIndicator({
    height: '100%',
    width: '100%',
    color: '#404347',
    backgroundColor: '#d8d8d8',
    font: {
        fontFamily: 'Helvetica Neue',
        fontSize: 14,
        fontWeight: 'normal'
    },
    message: 'Loading...',
    style: activityStyle,
});
win.add(activityIndicator);
activityIndicator.show();
//innitialise the array
var data = [];
//if internet connection is on - continue
if(Titanium.Network.online) {
    //open network connection
    var xhr = Ti.Network.createHTTPClient({
        cache: Ti.App.Properties.getBool('cache', false),
        timeout:5000,
    });
    xhr.open('GET', url);
    xhr.onload = function () {
        //Writing data to a file
        f.write(this.responseData);
        getXMLdata(f);
        showTable();
    };
    xhr.onerror = function (e) {
    //check response status and act aaccordingly.
    if(xhr.status != 200) {
        activityIndicator.hide();
        xhr.abort();
        alert("The service is currently unavailable. Please Try Again Later.");
        return;
    }};
    try {
        xhr.send();
    } catch(e) {
        Ti.API.info('error with xhr.send(): '+e);
        xhr.abort();
        activityIndicator.hide();
    }
}
else if(f.exists()) {
        getXMLdata(f);
        showTable();
    }
else if(!f.exists()) {
        activityIndicator.hide();
        alert('Your device is not connected to the internet.');
}

function showTable() {
    var searchBar = Titanium.UI.createSearchBar({
    barColor:'#bbb',
    tintColor :'#980012',
    height:43,
    top:0,
    });
    // create table
    var tableView = Ti.UI.createTableView({
        data: data,
        search:searchBar,
        filterAttribute:'filter',
        searchHidden:true,
        hideSearchOnSelection: true,
    });
    win.add(tableView);
    // add event handeler
    tableView.addEventListener('click', function (e) {
        /*
        var detailWin = Ti.UI.createWindow({
            //title of the label that the user selected
            title: e.row.children[0].text,
            barColor: '#650000',
            url: 'tableDetail.js',
       });
       */
           //alternative method:
           // var Window = require('windowClass');
        var detailWin = new Window (e.row.children[0].text, 'tableDetail.js');
        detailWin.desc = e.row.desc;
        tabGroup.activeTab.open(detailWin, {
            animation: true
        });
        //Hide the activity indicator when the funtion has completed
        activityIndicator.hide();
    });
    searchBar.addEventListener('change', function (e) {
        Ti.App.Properties.setString('search', searchBar.value);
    });
    win.addEventListener('focus', function(e) {
        if(searchBar.value){
        searchBar.value=Ti.App.Properties.getString('search','');
        tableView.searchHidden=false;
        }
    });
};

function getXMLdata(file) {
    if(file.exists()) {
        //read file
        var contents = f.read().text;
// Ti.API.info('contents = ' + contents);
        var doc = Ti.XML.parseString(contents);
        //var doc = this.responseXML.documentElement;
        var items = doc.getElementsByTagName('item');
        var x = 0;
        for(var i = 0; i < items.length; i++) {
            var item = items.item(i);
            var title = item.getElementsByTagName('title').item(0).text;
            var description = item.getElementsByTagName('description').item(0).text;
            var pubDate = item.getElementsByTagName('pubDate').item(0).text;
            var link = item.getElementsByTagName('link').item(0).text;
            //display content and create objects
            var row = Ti.UI.createTableViewRow({
                height: 80,
                layout: 'vertical',
                selectedBackgroundColor: '#650000',
            });
            row.filter = title; //data for search
            var labelText = title;
            var label = Ti.UI.createLabel({
                text: labelText,
                highlightedColor: '#fff',
                left: 5,
                top: 5,
                bottom: 5,
                right: 5,
            });
            //add objects
            row.add(label);
            row.desc = description;
            data[x++] = row;
        }
    }
}}
<commit_msg>fixed bug<commit_after>// http://developer.appcelerator.com/question/124014/saving-xml-file-offline-for-read-later
function getData(url, f, win){

if(Ti.Platform.name === 'iPhone OS') {
    var activityStyle = Ti.UI.iPhone.ActivityIndicatorStyle.DARK;
} else {
    var activityStyle = Ti.UI.ActivityIndicatorStyle.DARK;
}

//innitialise the array
var data = [];
//if internet connection is on - continue
if(Titanium.Network.online) {
    //Show the activity indicator
var activityIndicator = Ti.UI.createActivityIndicator({
    height: '100%',
    width: '100%',
    color: '#404347',
    backgroundColor: '#d8d8d8',
    font: {
        fontFamily: 'Helvetica Neue',
        fontSize: 14,
        fontWeight: 'normal'
    },
    message: 'Loading...',
    style: activityStyle,
});
win.add(activityIndicator);
activityIndicator.show();
    //open network connection
    var xhr = Ti.Network.createHTTPClient({
        cache: Ti.App.Properties.getBool('cache', false),
        timeout:5000,
    });
    xhr.open('GET', url);
    xhr.onload = function () {
        //Writing data to a file
        f.write(this.responseData);
        getXMLdata(f);
        showTable();
    };
    xhr.onerror = function (e) {
    //check response status and act aaccordingly.
    if(xhr.status != 200) {
        activityIndicator.hide();
        xhr.abort();
        alert("The service is currently unavailable. Please Try Again Later.");
        return;
    }};
    try {
        xhr.send();
    } catch(e) {
        Ti.API.info('error with xhr.send(): '+e);
        xhr.abort();
        activityIndicator.hide();
    }
}
else if(f.exists()) {
        getXMLdata(f);
        showTable();
    }
else if(!f.exists()) {
        activityIndicator.hide();
        alert('Your device is not connected to the internet.');
}

function showTable() {
    var searchBar = Titanium.UI.createSearchBar({
    barColor:'#bbb',
    tintColor :'#980012',
    height:43,
    top:0,
    });
    // create table
    var tableView = Ti.UI.createTableView({
        data: data,
        search:searchBar,
        filterAttribute:'filter',
        searchHidden:true,
        hideSearchOnSelection: true,
    });
    win.add(tableView);
    // add event handeler
    tableView.addEventListener('click', function (e) {
        /*
        var detailWin = Ti.UI.createWindow({
            //title of the label that the user selected
            title: e.row.children[0].text,
            barColor: '#650000',
            url: 'tableDetail.js',
       });
       */
           //alternative method:
           // var Window = require('windowClass');
        var detailWin = new Window (e.row.children[0].text, 'tableDetail.js');
        detailWin.desc = e.row.desc;
        tabGroup.activeTab.open(detailWin, {
            animation: true
        });
        //Hide the activity indicator when the funtion has completed
        activityIndicator.hide();
    });
    searchBar.addEventListener('change', function (e) {
        Ti.App.Properties.setString('search', searchBar.value);
    });
    win.addEventListener('focus', function(e) {
        if(searchBar.value){
        searchBar.value=Ti.App.Properties.getString('search','');
        tableView.searchHidden=false;
        }
    });
};

function getXMLdata(file) {
    if(file.exists()) {
        //read file
        var contents = f.read().text;
// Ti.API.info('contents = ' + contents);
        var doc = Ti.XML.parseString(contents);
        //var doc = this.responseXML.documentElement;
        var items = doc.getElementsByTagName('item');
        var x = 0;
        for(var i = 0; i < items.length; i++) {
            var item = items.item(i);
            var title = item.getElementsByTagName('title').item(0).text;
            var description = item.getElementsByTagName('description').item(0).text;
            var pubDate = item.getElementsByTagName('pubDate').item(0).text;
            var link = item.getElementsByTagName('link').item(0).text;
            //display content and create objects
            var row = Ti.UI.createTableViewRow({
                height: 80,
                layout: 'vertical',
                selectedBackgroundColor: '#650000',
            });
            row.filter = title; //data for search
            var labelText = title;
            var label = Ti.UI.createLabel({
                text: labelText,
                highlightedColor: '#fff',
                left: 5,
                top: 5,
                bottom: 5,
                right: 5,
            });
            //add objects
            row.add(label);
            row.desc = description;
            data[x++] = row;
        }
    }
}}
<|endoftext|>


<commit_before>/**
 * Policy Mappings
 * (sails.config.policies)
 *
 * Policies are simple functions which run **before** your controllers.
 * You can apply one or more policies to a given controller, or protect
 * its actions individually.
 *
 * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed
 * below by its filename, minus the extension, (e.g. "authenticated")
 *
 * For more information on how policies work, see:
 * http://sailsjs.org/#/documentation/concepts/Policies
 *
 * For more information on configuring policies, check out:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.policies.html
 *
 * Here's an example of mapping some policies to run before a controller
 * and its actions:
 *
 * ```
 * RabbitController: {
 *
 *   // Apply the `false` policy as the default for all of RabbitController's actions
 *   // (`false` prevents all access, which ensures that nothing bad happens to our rabbits)
 *   '*': false,
 *
 *   // For the action `nurture`, apply the 'isRabbitMother' policy
 *   // (this overrides `false` above)
 *   nurture  : 'isRabbitMother',

 *   // Apply the `isNiceToAnimals` AND `hasRabbitFood` policies
 *   // before letting any users feed our rabbits
 *   feed : ['isNiceToAnimals', 'hasRabbitFood']
 * }
 * ```
 */
module.exports.policies = {

  /**
   * Default policy for all controllers and actions (`true` allows publicaccess)
   */
  '*': ['authenticated', 'siteadmin'],

  CMSController: {
    'setup': 'developer',
    'infoUser': true
  },

  ConfigController: {
    'setup': 'developer',
    'find': true
  },

  ContentController: {
    'setup': 'developer',
    'find': true,
    'findAll': true,
    'findAllWithImage': true
  },

  DocsController: {
    'setup': 'developer',
    'config': true,
    'controllers': true,
    'policies': true,
    'services': true,
    'adapters': true,
    'models': true,
    'hooks': true,
    'blueprints': true,
    'responses': true,
    'views': true,
    'available': true,
    'all': true
  },

  DocumentController: {
    'setup': 'developer',
    'upload': true,
    'convert': true,
  },

  EmailController: {
    'setup': 'developer',
    'send': true,
    'contact': true,
    'application': true,
  },

  GalleryController: {
    'setup': 'developer',
    'find': true,
    'findOne': true,
  },

  LocaleController: {
    'setup': 'developer',
  },

  MagentoController: {
    'setup': 'developer',
  },

  MarkdownController: {
    'setup': 'developer',
    'find': true
  },

  MemberController: {
    'setup': 'developer',
    'find': true,
  },

  MultisiteController: {
    'find': ['authenticated', 'superadmin'],
    'findNames': ['authenticated', 'superadmin'],
    'findHosts': ['authenticated', 'superadmin'],
  },

  NavigationController: {
    'setup': 'developer',
    'find': true
  },

  SessionController: {
    'setup': 'developer',
    'create': true,
    'subscribe': true,
    'authenticated': true
  },

  SetupController: {
    '*': 'developer',
  },

  ThemeController: {
    'setup': 'developer',
    'assets': true,
    'likeAssets': true,
    'favicon': true,
    'signin': true,
    'modern': true,
    'fallback': true,
    'view': true,
    'find': ['authenticated', 'siteadmin'],
    'findByHost': ['authenticated', 'superadmin'],
    'updateOrCreate': ['authenticated', 'siteadmin'],
    'updateOrCreateByHost': ['authenticated', 'superadmin'],
    'updateOrCreateEach': ['authenticated', 'siteadmin'],
    'updateOrCreateEachByHost': ['authenticated', 'siteadmin'],
  },

  TimelineController: {
    'setup': 'developer',
    'find': true,
  },

  UserController: {
    'setup': 'developer',
    'find': true,
  },

  VWHeritageController: {
    'setup': 'developer',
    'find': true,
  }
};
<commit_msg>image upload policy<commit_after>/**
 * Policy Mappings
 * (sails.config.policies)
 *
 * Policies are simple functions which run **before** your controllers.
 * You can apply one or more policies to a given controller, or protect
 * its actions individually.
 *
 * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed
 * below by its filename, minus the extension, (e.g. "authenticated")
 *
 * For more information on how policies work, see:
 * http://sailsjs.org/#/documentation/concepts/Policies
 *
 * For more information on configuring policies, check out:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.policies.html
 *
 * Here's an example of mapping some policies to run before a controller
 * and its actions:
 *
 * ```
 * RabbitController: {
 *
 *   // Apply the `false` policy as the default for all of RabbitController's actions
 *   // (`false` prevents all access, which ensures that nothing bad happens to our rabbits)
 *   '*': false,
 *
 *   // For the action `nurture`, apply the 'isRabbitMother' policy
 *   // (this overrides `false` above)
 *   nurture  : 'isRabbitMother',

 *   // Apply the `isNiceToAnimals` AND `hasRabbitFood` policies
 *   // before letting any users feed our rabbits
 *   feed : ['isNiceToAnimals', 'hasRabbitFood']
 * }
 * ```
 */
module.exports.policies = {

  /**
   * Default policy for all controllers and actions (`true` allows publicaccess)
   */
  '*': ['authenticated', 'siteadmin'],

  CMSController: {
    'setup': 'developer',
    'infoUser': true
  },

  ConfigController: {
    'setup': 'developer',
    'find': true
  },

  ContentController: {
    'setup': 'developer',
    'find': true,
    'findAll': true,
    'findAllWithImage': true
  },

  DocsController: {
    'setup': 'developer',
    'config': true,
    'controllers': true,
    'policies': true,
    'services': true,
    'adapters': true,
    'models': true,
    'hooks': true,
    'blueprints': true,
    'responses': true,
    'views': true,
    'available': true,
    'all': true
  },

  DocumentController: {
    'setup': 'developer',
    'upload': true,
    'convert': true,
  },

  EmailController: {
    'setup': 'developer',
    'send': true,
    'contact': true,
    'application': true,
  },

  GalleryController: {
    'setup': 'developer',
    'find': true,
    'findOne': true,
    'upload': ['authenticated', 'siteadmin']
  },

  LocaleController: {
    'setup': 'developer',
  },

  MagentoController: {
    'setup': 'developer',
  },

  MarkdownController: {
    'setup': 'developer',
    'find': true
  },

  MemberController: {
    'setup': 'developer',
    'find': true,
  },

  MultisiteController: {
    'find': ['authenticated', 'superadmin'],
    'findNames': ['authenticated', 'superadmin'],
    'findHosts': ['authenticated', 'superadmin'],
  },

  NavigationController: {
    'setup': 'developer',
    'find': true
  },

  SessionController: {
    'setup': 'developer',
    'create': true,
    'subscribe': true,
    'authenticated': true
  },

  SetupController: {
    '*': 'developer',
  },

  ThemeController: {
    'setup': 'developer',
    'assets': true,
    'likeAssets': true,
    'favicon': true,
    'signin': true,
    'modern': true,
    'fallback': true,
    'view': true,
    'find': ['authenticated', 'siteadmin'],
    'findByHost': ['authenticated', 'superadmin'],
    'updateOrCreate': ['authenticated', 'siteadmin'],
    'updateOrCreateByHost': ['authenticated', 'superadmin'],
    'updateOrCreateEach': ['authenticated', 'siteadmin'],
    'updateOrCreateEachByHost': ['authenticated', 'siteadmin'],
  },

  TimelineController: {
    'setup': 'developer',
    'find': true,
  },

  UserController: {
    'setup': 'developer',
    'find': true,
  },

  VWHeritageController: {
    'setup': 'developer',
    'find': true,
  }
};
<|endoftext|>