<commit_before>/*
 * grunt-crafter-deploy
 * https://github.com/asotog/grunt-crafter-deploy
 *
 * Copyright (c) 2014 asotog
 * Licensed under the MIT license.
 */

'use strict';

var http = require('http');
var FormData = require('form-data');
var fs = require('fs');

module.exports = function (grunt) {

    grunt.registerMultiTask('crafter_deploy', 'Crafter Studio deployer for assets such as images, js or css', function () {
        /* **************************** */
        /* GLOBALS */
        /* **************************** */
        var self = this;

        var alfrescoTicket = '';

        var filesNumber = 0; /* number of files to be uploaded */
        var filesUploaded = 0 /* files uploaded */

        var baseUrl = '';
        // Merge task-specific and/or target-specific options with these defaults.
        var taskOptions = this.options({
            protocol: 'http',
            host: '',
            port: null,
            site: '',
            username: '',
            password: '',
            loginPath: '/alfresco/service/api/login', /* login service path */
            uploadFilePath: '/alfresco/s/cstudio/wcm/content/upload-content-asset' /* upload service path */
        });

        /* **************************** */
        /* METHODS */
        /* **************************** */

        /* executes a GET request */
        var execGetRequest = function (options, responseCallback) {
            var callback = function (response) {
                var str = '';

                response.on('data', function (chunk) {
                    str += chunk;
                });

                response.on('end', function () {
                    responseCallback(str);
                });
            }

            http.request(options, callback).end();
        };

        /* uploads a file to the server */
        var uploadFile = function (source, destination) {
            var form = new FormData();
            form.append('site', taskOptions.site);
            form.append('path', destination);
            form.append('file', fs.createReadStream(source));

            form.submit({
                host: taskOptions.host,
                port: taskOptions.port,
                path: taskOptions.uploadFilePath + '?alf_ticket=' + alfrescoTicket,
                auth: taskOptions.username + ':' + taskOptions.password
            }, function (err, res) {
                filesUploaded += 1;
                grunt.log.writeln('File deployed -> ' + source);
                res.resume();
                /* if all files were uploaded */
                if (filesUploaded == filesNumber) {
                    done();
                }
            });

        };

        /* Reads files that are going to be deployed */
        var processFiles = function () {
            filesNumber = 0;
            filesUploaded = 0;

            self.files.forEach(function (f) {
                var dest = f.dest;
                var src = f.src.filter(function (filepath) {
                    if (!grunt.file.exists(filepath)) {
                        //grunt.log.writeln('Source file "' + filepath + '" not found.');
                        return false;
                    } else {
                        return true;
                    }
                });

                filesNumber += src.length;

                for (var i = 0; i < src.length; i++) {
                    grunt.log.writeln('Uploading: "' + src[i] + '" to "' + baseUrl + dest + '"');
                    uploadFile(src[i], dest);
                }
            });

        }

        /* **************************** */
        /* BODY */
        /* **************************** */

        if (taskOptions.host != '') {
            baseUrl = taskOptions.protocol + '://' + taskOptions.host + (taskOptions.port ? (':' + taskOptions.port) : '');
            grunt.log.writeln('== Connecting to "' + baseUrl + '", Site = "' + taskOptions.site + '"');
            grunt.log.writeln('== Using credentials: user=' + taskOptions.username + ', password=****');

            var done = this.async();

            var options = {
                host: taskOptions.host,
                port: taskOptions.port,
                path: taskOptions.loginPath + '?u=' + taskOptions.username + '&pw=' + taskOptions.password
            };

            /* exec request to retrieve ticket */
            execGetRequest(options, function (response) {
                alfrescoTicket = response.match(/<ticket[^>]*>(.*?)<\/ticket>/)[1];
                processFiles();
            });

        } else {
            grunt.log.writeln('Host not specified, please set it from options');
        }

    });

};<commit_msg>log commented<commit_after>/*
 * grunt-crafter-deploy
 * https://github.com/asotog/grunt-crafter-deploy
 *
 * Copyright (c) 2014 asotog
 * Licensed under the MIT license.
 */

'use strict';

var http = require('http');
var FormData = require('form-data');
var fs = require('fs');

module.exports = function (grunt) {

    grunt.registerMultiTask('crafter_deploy', 'Crafter Studio deployer for assets such as images, js or css', function () {
        /* **************************** */
        /* GLOBALS */
        /* **************************** */
        var self = this;

        var alfrescoTicket = '';

        var filesNumber = 0; /* number of files to be uploaded */
        var filesUploaded = 0 /* files uploaded */

        var baseUrl = '';
        // Merge task-specific and/or target-specific options with these defaults.
        var taskOptions = this.options({
            protocol: 'http',
            host: '',
            port: null,
            site: '',
            username: '',
            password: '',
            loginPath: '/alfresco/service/api/login', /* login service path */
            uploadFilePath: '/alfresco/s/cstudio/wcm/content/upload-content-asset' /* upload service path */
        });

        /* **************************** */
        /* METHODS */
        /* **************************** */

        /* executes a GET request */
        var execGetRequest = function (options, responseCallback) {
            var callback = function (response) {
                var str = '';

                response.on('data', function (chunk) {
                    str += chunk;
                });

                response.on('end', function () {
                    responseCallback(str);
                });
            }

            http.request(options, callback).end();
        };

        /* uploads a file to the server */
        var uploadFile = function (source, destination) {
            var form = new FormData();
            form.append('site', taskOptions.site);
            form.append('path', destination);
            form.append('file', fs.createReadStream(source));

            form.submit({
                host: taskOptions.host,
                port: taskOptions.port,
                path: taskOptions.uploadFilePath + '?alf_ticket=' + alfrescoTicket,
                auth: taskOptions.username + ':' + taskOptions.password
            }, function (err, res) {
                filesUploaded += 1;
                grunt.log.writeln('File deployed -> ' + source);
                res.resume();
                /* if all files were uploaded */
                if (filesUploaded == filesNumber) {
                    done();
                }
            });

        };

        /* Reads files that are going to be deployed */
        var processFiles = function () {
            filesNumber = 0;
            filesUploaded = 0;

            self.files.forEach(function (f) {
                var dest = f.dest;
                var src = f.src.filter(function (filepath) {
                    if (!grunt.file.exists(filepath)) {
                        grunt.log.writeln('Source file "' + filepath + '" not found.');
                        return false;
                    } else {
                        return true;
                    }
                });

                filesNumber += src.length;

                for (var i = 0; i < src.length; i++) {
                    //grunt.log.writeln('Uploading: "' + src[i] + '" to "' + baseUrl + dest + '"');
                    uploadFile(src[i], dest);
                }
            });

        }

        /* **************************** */
        /* BODY */
        /* **************************** */

        if (taskOptions.host != '') {
            baseUrl = taskOptions.protocol + '://' + taskOptions.host + (taskOptions.port ? (':' + taskOptions.port) : '');
            grunt.log.writeln('== Connecting to "' + baseUrl + '", Site = "' + taskOptions.site + '"');
            grunt.log.writeln('== Using credentials: user=' + taskOptions.username + ', password=****');

            var done = this.async();

            var options = {
                host: taskOptions.host,
                port: taskOptions.port,
                path: taskOptions.loginPath + '?u=' + taskOptions.username + '&pw=' + taskOptions.password
            };

            /* exec request to retrieve ticket */
            execGetRequest(options, function (response) {
                alfrescoTicket = response.match(/<ticket[^>]*>(.*?)<\/ticket>/)[1];
                processFiles();
            });

        } else {
            grunt.log.writeln('Host not specified, please set it from options');
        }

    });

};<|endoftext|>


<commit_before>/*********************************************************************
*  #### Twitter Post Fetcher v14.0 ####
*  Coded by Jason Mayes 2015. A present to all the developers out there.
*  www.jasonmayes.com
*  Please keep this disclaimer with my code if you use it. Thanks. :-)
*  Got feedback or questions, ask here:
*  http://www.jasonmayes.com/projects/twitterApi/
*  Github: https://github.com/jasonmayes/Twitter-Post-Fetcher
*  Updates will be posted to this site.
*********************************************************************/
(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals.
    factory();
  }
}(this, function() {
  var domNode = '';
  var maxTweets = 20;
  var parseLinks = true;
  var queue = [];
  var inProgress = false;
  var printTime = true;
  var printUser = true;
  var formatterFunction = null;
  var supportsClassName = true;
  var showRts = true;
  var customCallbackFunction = null;
  var showInteractionLinks = true;
  var showImages = false;
  var targetBlank = true;
  var lang = 'en';
  var permalinks = true;
  var dataOnly = false;
  var script = null;
  var scriptAdded = false;

  function handleTweets(tweets){
    if (customCallbackFunction === null) {
      var x = tweets.length;
      var n = 0;
      var element = document.getElementById(domNode);
      var html = '
';
      while(n < x) {
        html += '
' + tweets[n] + '
';
        n++;
      }
      html += '
';
      element.innerHTML = html;
    } else {
      customCallbackFunction(tweets);
    }
  }

  function strip(data) {
    return data.replace(/]*>(.*?)<\/b>/gi, function(a,s){return s;})
        .replace(/class="(?!(tco-hidden|tco-display|tco-ellipsis))+.*?"|data-query-source=".*?"|dir=".*?"|rel=".*?"/gi,
        '');
  }

  function targetLinksToNewWindow(el) {
    var links = el.getElementsByTagName('a');
    for (var i = links.length - 1; i >= 0; i--) {
      links[i].setAttribute('target', '_blank');
    }
  }

  function getElementsByClassName (node, classname) {
    var a = [];
    var regex = new RegExp('(^| )' + classname + '( |$)');
    var elems = node.getElementsByTagName('*');
    for (var i = 0, j = elems.length; i < j; i++) {
        if(regex.test(elems[i].className)){
          a.push(elems[i]);
        }
    }
    return a;
  }

  function extractImageUrl(image_data) {
    if (image_data !== undefined) {
      var data_src = image_data.innerHTML
          .match(/data-srcset="([A-z0-9%_\.-]+)/i)[0];
      return decodeURIComponent(data_src).split('"')[1];
    }
  }

  var twitterFetcher = {
    fetch: function(config) {
      if (config.maxTweets === undefined) {
        config.maxTweets = 20;
      }
      if (config.enableLinks === undefined) {
        config.enableLinks = true;
      }
      if (config.showUser === undefined) {
        config.showUser = true;
      }
      if (config.showTime === undefined) {
        config.showTime = true;
      }
      if (config.dateFunction === undefined) {
        config.dateFunction = 'default';
      }
      if (config.showRetweet === undefined) {
        config.showRetweet = true;
      }
      if (config.customCallback === undefined) {
        config.customCallback = null;
      }
      if (config.showInteraction === undefined) {
        config.showInteraction = true;
      }
      if (config.showImages === undefined) {
        config.showImages = false;
      }
      if (config.linksInNewWindow === undefined) {
        config.linksInNewWindow = true;
      }
      if (config.showPermalinks === undefined) {
        config.showPermalinks = true;
      }
      if (config.dataOnly === undefined) {
        config.dataOnly = false;
      }

      if (inProgress) {
        queue.push(config);
      } else {
        inProgress = true;

        domNode = config.domId;
        maxTweets = config.maxTweets;
        parseLinks = config.enableLinks;
        printUser = config.showUser;
        printTime = config.showTime;
        showRts = config.showRetweet;
        formatterFunction = config.dateFunction;
        customCallbackFunction = config.customCallback;
        showInteractionLinks = config.showInteraction;
        showImages = config.showImages;
        targetBlank = config.linksInNewWindow;
        permalinks = config.showPermalinks;
        dataOnly = config.dataOnly;

        var head = document.getElementsByTagName('head')[0];
        if (script !== null) {
          head.removeChild(script);
        }
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://cdn.syndication.twimg.com/widgets/timelines/' +
            config.id + '?&lang=' + (config.lang || lang) +
            '&callback=twitterFetcher.callback&' +
            'suppress_response_codes=true&rnd=' + Math.random();
        head.appendChild(script);
      }
    },
    callback: function(data) {
      var div = document.createElement('div');
      div.innerHTML = data.body;
      if (typeof(div.getElementsByClassName) === 'undefined') {
         supportsClassName = false;
      }

      function swapDataSrc(element) {
        var avatarImg = element.getElementsByTagName('img')[0];
        avatarImg.src = avatarImg.getAttribute('data-src-2x');
        return element;
      };

      var tweets = [];
      var authors = [];
      var times = [];
      var images = [];
      var rts = [];
      var tids = [];
      var permalinksURL = [];
      var x = 0;

      if (supportsClassName) {
        var tmp = div.getElementsByClassName('tweet');
        while (x < tmp.length) {
          if (tmp[x].getElementsByClassName('retweet-credit').length > 0) {
            rts.push(true);
          } else {
            rts.push(false);
          }
          if (!rts[x] || rts[x] && showRts) {
            tweets.push(tmp[x].getElementsByClassName('e-entry-title')[0]);
            tids.push(tmp[x].getAttribute('data-tweet-id'));
            authors.push(swapDataSrc(tmp[x]
                .getElementsByClassName('p-author')[0]));
            times.push(tmp[x].getElementsByClassName('dt-updated')[0]);
            permalinksURL.push(tmp[x].getElementsByClassName('permalink')[0]);
            if (tmp[x].getElementsByClassName('inline-media')[0] !==
                undefined) {
              images.push(tmp[x].getElementsByClassName('inline-media')[0]);
            } else {
              images.push(undefined);
            }
          }
          x++;
        }
      } else {
        var tmp = getElementsByClassName(div, 'tweet');
        while (x < tmp.length) {
          tweets.push(getElementsByClassName(tmp[x], 'e-entry-title')[0]);
          tids.push(tmp[x].getAttribute('data-tweet-id'));
          authors.push(swapDataSrc(getElementsByClassName(tmp[x],
              'p-author')[0]));
          times.push(getElementsByClassName(tmp[x], 'dt-updated')[0]);
          permalinksURL.push(getElementsByClassName(tmp[x], 'permalink')[0]);
          if (getElementsByClassName(tmp[x], 'inline-media')[0] !== undefined) {
            images.push(getElementsByClassName(tmp[x], 'inline-media')[0]);
          } else {
            images.push(undefined);
          }

          if (getElementsByClassName(tmp[x], 'retweet-credit').length > 0) {
            rts.push(true);
          } else {
            rts.push(false);
          }
          x++;
        }
      }

      if (tweets.length > maxTweets) {
        tweets.splice(maxTweets, (tweets.length - maxTweets));
        authors.splice(maxTweets, (authors.length - maxTweets));
        times.splice(maxTweets, (times.length - maxTweets));
        rts.splice(maxTweets, (rts.length - maxTweets));
        images.splice(maxTweets, (images.length - maxTweets));
        permalinksURL.splice(maxTweets, (permalinksURL.length - maxTweets));
      }

      var arrayTweets = [];
      var x = tweets.length;
      var n = 0;
      if (dataOnly) {
        while (n < x) {
          arrayTweets.push({
            tweet: tweets[n].innerHTML,
            author: authors[n].innerHTML,
            time: times[n].innerText,
            image: extractImageUrl(images[n]),
            rt: rts[n],
            tid: tids[n],
            permalinkURL: permalinksURL[n].href
          });
          n++;
        }
      } else {
        while (n < x) {
          if (typeof(formatterFunction) !== 'string') {
            var datetimeText = times[n].getAttribute('datetime');
            var newDate = new Date(times[n].getAttribute('datetime')
                .replace(/-/g,'/').replace('T', ' ').split('+')[0]);
            var dateString = formatterFunction(newDate, datetimeText);
            times[n].setAttribute('aria-label', dateString);

            if (tweets[n].innerText) {
              // IE hack.
              if (supportsClassName) {
                times[n].innerText = dateString;
              } else {
                var h = document.createElement('p');
                var t = document.createTextNode(dateString);
                h.appendChild(t);
                h.setAttribute('aria-label', dateString);
                times[n] = h;
              }
            } else {
              times[n].textContent = dateString;
            }
          }
          var op = '';
          if (parseLinks) {
            if (targetBlank) {
              targetLinksToNewWindow(tweets[n]);
              if (printUser) {
                targetLinksToNewWindow(authors[n]);
              }
            }
            if (printUser) {
              op += '
' + strip(authors[n].innerHTML) +
                  '
';
            }
            op += '
' + strip(tweets[n].innerHTML) + '
';
            if (printTime) {
              if (permalinks) {
                op += '
' + times[n].getAttribute('aria-label') + '
';
              } else {
                op += '
' +
                    times[n].getAttribute('aria-label') + '
';
              }
            }
          } else {
            if (tweets[n].innerText) {
              if (printUser) {
                op += '
' + authors[n].innerText + '
';
              }
              op += '
' +  tweets[n].innerText + '
';
              if (printTime) {
                op += '
' + times[n].innerText + '
';
              }

            } else {
              if (printUser) {
                op += '
' + authors[n].textContent + '
';
              }
              op += '
' +  tweets[n].textContent + '
';
              if (printTime) {
                op += '
' + times[n].textContent + '
';
              }
            }
          }
          if (showInteractionLinks) {
            op += '
' : '>') +
                'Reply' : '>') + 'Retweet' +
                '' : '>') + 'Favorite
';
          }

          if (showImages && images[n] !== undefined) {
            op += '
' +
                '' + '
';
          }

          arrayTweets.push(op);
          n++;
        }
      }

      handleTweets(arrayTweets);
      inProgress = false;

      if (queue.length > 0) {
        twitterFetcher.fetch(queue[0]);
        queue.splice(0,1);
      }
    }
  };

  // It must be a global variable because it will be called by JSONP.
  window.twitterFetcher = twitterFetcher;
  return twitterFetcher;
}));
<commit_msg>Fix twitter feed<commit_after>/*********************************************************************
*  #### Twitter Post Fetcher v16.0.1 ####
*  Coded by Jason Mayes 2015. A present to all the developers out there.
*  www.jasonmayes.com
*  Please keep this disclaimer with my code if you use it. Thanks. :-)
*  Got feedback or questions, ask here:
*  http://www.jasonmayes.com/projects/twitterApi/
*  Github: https://github.com/jasonmayes/Twitter-Post-Fetcher
*  Updates will be posted to this site.
*********************************************************************/
(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    // Browser globals.
    factory();
  }
}(this, function() {
  var domNode = '';
  var maxTweets = 20;
  var parseLinks = true;
  var queue = [];
  var inProgress = false;
  var printTime = true;
  var printUser = true;
  var formatterFunction = null;
  var supportsClassName = true;
  var showRts = true;
  var customCallbackFunction = null;
  var showInteractionLinks = true;
  var showImages = false;
  var targetBlank = true;
  var lang = 'en';
  var permalinks = true;
  var dataOnly = false;
  var script = null;
  var scriptAdded = false;

  function handleTweets(tweets){
    if (customCallbackFunction === null) {
      var x = tweets.length;
      var n = 0;
      var element = document.getElementById(domNode);
      var html = '
';
      while(n < x) {
        html += '
' + tweets[n] + '
';
        n++;
      }
      html += '
';
      element.innerHTML = html;
    } else {
      customCallbackFunction(tweets);
    }
  }

  function strip(data) {
    return data.replace(/]*>(.*?)<\/b>/gi, function(a,s){return s;})
        .replace(/class="(?!(tco-hidden|tco-display|tco-ellipsis))+.*?"|data-query-source=".*?"|dir=".*?"|rel=".*?"/gi,
        '');
  }

  function targetLinksToNewWindow(el) {
    var links = el.getElementsByTagName('a');
    for (var i = links.length - 1; i >= 0; i--) {
      links[i].setAttribute('target', '_blank');
    }
  }

  function getElementsByClassName (node, classname) {
    var a = [];
    var regex = new RegExp('(^| )' + classname + '( |$)');
    var elems = node.getElementsByTagName('*');
    for (var i = 0, j = elems.length; i < j; i++) {
        if(regex.test(elems[i].className)){
          a.push(elems[i]);
        }
    }
    return a;
  }

  function extractImageUrl(image_data) {
    if (image_data !== undefined && image_data.innerHTML.indexOf('data-srcset') >= 0) {
      var data_src = image_data.innerHTML
          .match(/data-srcset="([A-z0-9%_\.-]+)/i)[0];
      return decodeURIComponent(data_src).split('"')[1];
    }
  }

  var twitterFetcher = {
    fetch: function(config) {
      if (config.maxTweets === undefined) {
        config.maxTweets = 20;
      }
      if (config.enableLinks === undefined) {
        config.enableLinks = true;
      }
      if (config.showUser === undefined) {
        config.showUser = true;
      }
      if (config.showTime === undefined) {
        config.showTime = true;
      }
      if (config.dateFunction === undefined) {
        config.dateFunction = 'default';
      }
      if (config.showRetweet === undefined) {
        config.showRetweet = true;
      }
      if (config.customCallback === undefined) {
        config.customCallback = null;
      }
      if (config.showInteraction === undefined) {
        config.showInteraction = true;
      }
      if (config.showImages === undefined) {
        config.showImages = false;
      }
      if (config.linksInNewWindow === undefined) {
        config.linksInNewWindow = true;
      }
      if (config.showPermalinks === undefined) {
        config.showPermalinks = true;
      }
      if (config.dataOnly === undefined) {
        config.dataOnly = false;
      }

      if (inProgress) {
        queue.push(config);
      } else {
        inProgress = true;

        domNode = config.domId;
        maxTweets = config.maxTweets;
        parseLinks = config.enableLinks;
        printUser = config.showUser;
        printTime = config.showTime;
        showRts = config.showRetweet;
        formatterFunction = config.dateFunction;
        customCallbackFunction = config.customCallback;
        showInteractionLinks = config.showInteraction;
        showImages = config.showImages;
        targetBlank = config.linksInNewWindow;
        permalinks = config.showPermalinks;
        dataOnly = config.dataOnly;

        var head = document.getElementsByTagName('head')[0];
        if (script !== null) {
          head.removeChild(script);
        }
        script = document.createElement('script');
        script.type = 'text/javascript';
        if (config.list !== undefined) {
          script.src = 'https://syndication.twitter.com/timeline/list?' +
              'callback=twitterFetcher.callback&dnt=false&list_slug=' +
              config.list.listSlug + '&screen_name=' + config.list.screenName +
              '&suppress_response_codes=true&lang=' + (config.lang || lang) +
              '&rnd=' + Math.random();
        } else if (config.profile !== undefined) {
          script.src = 'https://syndication.twitter.com/timeline/profile?' +
              'callback=twitterFetcher.callback&dnt=false' +
              '&screen_name=' + config.profile.screenName +
              '&suppress_response_codes=true&lang=' + (config.lang || lang) +
              '&rnd=' + Math.random();
        } else if (config.likes !== undefined) {
          script.src = 'https://syndication.twitter.com/timeline/likes?' +
              'callback=twitterFetcher.callback&dnt=false' +
              '&screen_name=' + config.likes.screenName +
              '&suppress_response_codes=true&lang=' + (config.lang || lang) +
              '&rnd=' + Math.random();
        } else {
          script.src = 'https://cdn.syndication.twimg.com/widgets/timelines/' +
              config.id + '?&lang=' + (config.lang || lang) +
              '&callback=twitterFetcher.callback&' +
              'suppress_response_codes=true&rnd=' + Math.random();
        }
        head.appendChild(script);
      }
    },
    callback: function(data) {
      var div = document.createElement('div');
      div.innerHTML = data.body;
      if (typeof(div.getElementsByClassName) === 'undefined') {
         supportsClassName = false;
      }

      function swapDataSrc(element) {
        var avatarImg = element.getElementsByTagName('img')[0];
        avatarImg.src = avatarImg.getAttribute('data-src-2x');
        return element;
      };

      var tweets = [];
      var authors = [];
      var times = [];
      var images = [];
      var rts = [];
      var tids = [];
      var permalinksURL = [];
      var x = 0;

      if (supportsClassName) {
        var tmp = div.getElementsByClassName('timeline-Tweet');
        while (x < tmp.length) {
          if (tmp[x].getElementsByClassName('timeline-Tweet-retweetCredit').length > 0) {
            rts.push(true);
          } else {
            rts.push(false);
          }
          if (!rts[x] || rts[x] && showRts) {
            tweets.push(tmp[x].getElementsByClassName('timeline-Tweet-text')[0]);
            tids.push(tmp[x].getAttribute('data-tweet-id'));
            authors.push(swapDataSrc(tmp[x]
                .getElementsByClassName('timeline-Tweet-author')[0]));
            times.push(tmp[x].getElementsByClassName('dt-updated')[0]);
            permalinksURL.push(tmp[x].getElementsByClassName('timeline-Tweet-timestamp')[0]);
            if (tmp[x].getElementsByClassName('timeline-Tweet-media')[0] !==
                undefined) {
              images.push(tmp[x].getElementsByClassName('timeline-Tweet-media')[0]);
            } else {
              images.push(undefined);
            }
          }
          x++;
        }
      } else {
        var tmp = getElementsByClassName(div, 'timeline-Tweet');
        while (x < tmp.length) {
          if (getElementsByClassName(tmp[x], 'timeline-Tweet-retweetCredit').length > 0) {
            rts.push(true);
          } else {
            rts.push(false);
          }
          if (!rts[x] || rts[x] && showRts) {
            tweets.push(getElementsByClassName(tmp[x], 'timeline-Tweet-text')[0]);
            tids.push(tmp[x].getAttribute('data-tweet-id'));
            authors.push(swapDataSrc(getElementsByClassName(tmp[x],
                'timeline-Tweet-author')[0]));
            times.push(getElementsByClassName(tmp[x], 'dt-updated')[0]);
            permalinksURL.push(getElementsByClassName(tmp[x], 'timeline-Tweet-timestamp')[0]);
            if (getElementsByClassName(tmp[x], 'timeline-Tweet-media')[0] !== undefined) {
              images.push(getElementsByClassName(tmp[x], 'timeline-Tweet-media')[0]);
            } else {
              images.push(undefined);
            }
          }
          x++;
        }
      }

      if (tweets.length > maxTweets) {
        tweets.splice(maxTweets, (tweets.length - maxTweets));
        authors.splice(maxTweets, (authors.length - maxTweets));
        times.splice(maxTweets, (times.length - maxTweets));
        rts.splice(maxTweets, (rts.length - maxTweets));
        images.splice(maxTweets, (images.length - maxTweets));
        permalinksURL.splice(maxTweets, (permalinksURL.length - maxTweets));
      }

      var arrayTweets = [];
      var x = tweets.length;
      var n = 0;
      if (dataOnly) {
        while (n < x) {
          arrayTweets.push({
            tweet: tweets[n].innerHTML,
            author: authors[n].innerHTML,
            time: times[n].textContent,
            image: extractImageUrl(images[n]),
            rt: rts[n],
            tid: tids[n],
            permalinkURL: (permalinksURL[n] === undefined) ?
                '' : permalinksURL[n].href
          });
          n++;
        }
      } else {
        while (n < x) {
          if (typeof(formatterFunction) !== 'string') {
            var datetimeText = times[n].getAttribute('datetime');
            var newDate = new Date(times[n].getAttribute('datetime')
                .replace(/-/g,'/').replace('T', ' ').split('+')[0]);
            var dateString = formatterFunction(newDate, datetimeText);
            times[n].setAttribute('aria-label', dateString);

            if (tweets[n].textContent) {
              // IE hack.
              if (supportsClassName) {
                times[n].textContent = dateString;
              } else {
                var h = document.createElement('p');
                var t = document.createTextNode(dateString);
                h.appendChild(t);
                h.setAttribute('aria-label', dateString);
                times[n] = h;
              }
            } else {
              times[n].textContent = dateString;
            }
          }
          var op = '';
          if (parseLinks) {
            if (targetBlank) {
              targetLinksToNewWindow(tweets[n]);
              if (printUser) {
                targetLinksToNewWindow(authors[n]);
              }
            }
            if (printUser) {
              op += '
' + strip(authors[n].innerHTML) +
                  '
';
            }
            op += '
' + strip(tweets[n].innerHTML) + '
';
            if (printTime) {
              if (permalinks) {
                op += '
' + times[n].getAttribute('aria-label') + '
';
              } else {
                op += '
' +
                    times[n].getAttribute('aria-label') + '
';
              }
            }
          } else {
            if (tweets[n].textContent) {
              if (printUser) {
                op += '
' + authors[n].textContent + '
';
              }
              op += '
' +  tweets[n].textContent + '
';
              if (printTime) {
                op += '
' + times[n].textContent + '
';
              }

            } else {
              if (printUser) {
                op += '
' + authors[n].textContent + '
';
              }
              op += '
' +  tweets[n].textContent + '
';
              if (printTime) {
                op += '
' + times[n].textContent + '
';
              }
            }
          }
          if (showInteractionLinks) {
            op += '
' : '>') +
                'Reply' : '>') + 'Retweet' +
                '' : '>') + 'Favorite
';
          }

          if (showImages && images[n] !== undefined) {
            op += '
' +
                '' + '
';
          }

          arrayTweets.push(op);
          n++;
        }
      }

      handleTweets(arrayTweets);
      inProgress = false;

      if (queue.length > 0) {
        twitterFetcher.fetch(queue[0]);
        queue.splice(0,1);
      }
    }
  };

  // It must be a global variable because it will be called by JSONP.
  window.twitterFetcher = twitterFetcher;
  return twitterFetcher;
}));
<|endoftext|>


<commit_before>'use strict';

/*
 * Defining the Package
 */
var Module = require('meanio').Module;

var Result = new Module('result');

/*
 * All MEAN packages require registration
 * Dependency injection is used to define required modules
 */
Result.register(function(app, auth, database) {

  //We enable routing. By default the Package Object is passed to the routes
  Result.routes(app, auth, database);

  //We are adding a link to the main menu for all authenticated users
  Result.menus.add({
    title: 'Resultat erfassen',
    link: 'result enter-result',
    roles: ['resultAdmin'],
    menu: 'main'
  });

  Result.menus.add({
    title: 'Start- und Ranglisten',
    link: 'result lists',
    roles: ['resultAdmin'],
    menu: 'main'
  });

  Result.aggregateAsset('css','result.css');

  /**
    //Uncomment to use. Requires meanio@0.3.7 or above
    // Save settings with callback
    // Use this for saving data from administration pages
    Result.settings({
        'someSetting': 'some value'
    }, function(err, settings) {
        //you now have the settings object
    });

    // Another save settings example this time with no callback
    // This writes over the last settings.
    Result.settings({
        'anotherSettings': 'some value'
    });

    // Get settings. Retrieves latest saved settigns
    Result.settings(function(err, settings) {
        //you now have the settings object
    });
    */

  return Result;
});
<commit_msg>fix menu link select-lists<commit_after>'use strict';

/*
 * Defining the Package
 */
var Module = require('meanio').Module;

var Result = new Module('result');

/*
 * All MEAN packages require registration
 * Dependency injection is used to define required modules
 */
Result.register(function(app, auth, database) {

  //We enable routing. By default the Package Object is passed to the routes
  Result.routes(app, auth, database);

  //We are adding a link to the main menu for all authenticated users
  Result.menus.add({
    title: 'Resultat erfassen',
    link: 'result enter-result',
    roles: ['resultAdmin'],
    menu: 'main'
  });

  Result.menus.add({
    title: 'Start- und Ranglisten',
    link: 'result select-lists',
    roles: ['resultAdmin'],
    menu: 'main'
  });

  Result.aggregateAsset('css','result.css');

  /**
    //Uncomment to use. Requires meanio@0.3.7 or above
    // Save settings with callback
    // Use this for saving data from administration pages
    Result.settings({
        'someSetting': 'some value'
    }, function(err, settings) {
        //you now have the settings object
    });

    // Another save settings example this time with no callback
    // This writes over the last settings.
    Result.settings({
        'anotherSettings': 'some value'
    });

    // Get settings. Retrieves latest saved settigns
    Result.settings(function(err, settings) {
        //you now have the settings object
    });
    */

  return Result;
});
<|endoftext|>


<commit_before>import {Slice, Fragment} from "../model"

import {Transform} from "./transform"
import {Step, StepResult} from "./step"
import {PosMap} from "./map"

// !! **`split`**
//   : Split a block node at `pos`. The parameter, if given, may be
//     `{type, ?attrs}` object giving the node type and optionally the
//     attributes of the node created to hold the content after the
//     split.

Step.define("split", {
  apply(doc, step) {
    let $pos = doc.resolve(step.from), parent = $pos.parent
    let cut = [parent.copy(), step.param ? step.param.type.create(step.attrs) : parent.copy()]
    return StepResult.fromReplace(doc, $pos.pos, $pos.pos, new Slice(Fragment.fromArray(cut), 1, 1))
  },
  posMap(step) {
    return new PosMap([step.from, 0, 2])
  },
  invert(step) {
    return new Step("join", step.from, step.from + 2)
  },
  paramToJSON(param) {
    return param && {type: param.type.name, attrs: param.attrs}
  },
  paramFromJSON(schema, json) {
    return json && {type: schema.nodeType(json.type), attrs: json.attrs}
  }
})

// :: (number, ?number, ?NodeType, ?Object) → Transform
// Split the node at the given position, and optionally, if `depth` is
// greater than one, any number of nodes above that. By default, the part
// split off will inherit the node type of the original node. This can
// be changed by passing `typeAfter` and `attrsAfter`.
Transform.prototype.split = function(pos, depth = 1, typeAfter, attrsAfter) {
  for (let i = 0; i < depth; i++)
    this.step("split", pos + i, pos + i,
              i == 0 && typeAfter ? {type: typeAfter, attrs: attrsAfter} : null)
  return this
}

// :: (number, ?number) → Transform
// Split at the given position, up to the given depth, if that
// position isn't already at the start or end of its parent node.
Transform.prototype.splitIfNeeded = function(pos, depth = 1) {
  let $pos = this.doc.resolve(pos), before = true
  for (let i = 0; i < depth; i++) {
    let d = $pos.depth - i, point = i == 0 ? $pos.pos : before ? $pos.before(d + 1) : $pos.after(d + 1)
    if (point == $pos.start(d)) before = true
    else if (point == $pos.end(d)) before = false
    else return this.split(point, depth - i)
  }
  return this
}
<commit_msg>Fix passing of attributes to node type after split<commit_after>import {Slice, Fragment} from "../model"

import {Transform} from "./transform"
import {Step, StepResult} from "./step"
import {PosMap} from "./map"

// !! **`split`**
//   : Split a block node at `pos`. The parameter, if given, may be
//     `{type, ?attrs}` object giving the node type and optionally the
//     attributes of the node created to hold the content after the
//     split.

Step.define("split", {
  apply(doc, step) {
    let $pos = doc.resolve(step.from), parent = $pos.parent
    let cut = [parent.copy(), step.param ? step.param.type.create(step.param.attrs) : parent.copy()]
    return StepResult.fromReplace(doc, $pos.pos, $pos.pos, new Slice(Fragment.fromArray(cut), 1, 1))
  },
  posMap(step) {
    return new PosMap([step.from, 0, 2])
  },
  invert(step) {
    return new Step("join", step.from, step.from + 2)
  },
  paramToJSON(param) {
    return param && {type: param.type.name, attrs: param.attrs}
  },
  paramFromJSON(schema, json) {
    return json && {type: schema.nodeType(json.type), attrs: json.attrs}
  }
})

// :: (number, ?number, ?NodeType, ?Object) → Transform
// Split the node at the given position, and optionally, if `depth` is
// greater than one, any number of nodes above that. By default, the part
// split off will inherit the node type of the original node. This can
// be changed by passing `typeAfter` and `attrsAfter`.
Transform.prototype.split = function(pos, depth = 1, typeAfter, attrsAfter) {
  for (let i = 0; i < depth; i++)
    this.step("split", pos + i, pos + i,
              i == 0 && typeAfter ? {type: typeAfter, attrs: attrsAfter} : null)
  return this
}

// :: (number, ?number) → Transform
// Split at the given position, up to the given depth, if that
// position isn't already at the start or end of its parent node.
Transform.prototype.splitIfNeeded = function(pos, depth = 1) {
  let $pos = this.doc.resolve(pos), before = true
  for (let i = 0; i < depth; i++) {
    let d = $pos.depth - i, point = i == 0 ? $pos.pos : before ? $pos.before(d + 1) : $pos.after(d + 1)
    if (point == $pos.start(d)) before = true
    else if (point == $pos.end(d)) before = false
    else return this.split(point, depth - i)
  }
  return this
}
<|endoftext|>


<commit_before>var utils = require('./utils')

module.exports = function split (utxos, outputs, feeRate) {
  if (!isFinite(utils.uintOrNaN(feeRate))) return {}

  var bytesAccum = utils.transactionBytes(utxos, outputs)
  var fee = feeRate * bytesAccum
  if (outputs.length === 0) return { fee: fee }

  var inAccum = utils.sumOrNaN(utxos)
  var outAccum = utils.sumForgiving(outputs)
  var remaining = inAccum - outAccum - fee
  if (!isFinite(remaining) || remaining <= 0) return { fee: fee }

  var splitOutputsCount = outputs.reduce(function (a, x) {
    return a + !x.value
  }, 0)
  var splitValue = (remaining / splitOutputsCount) >>> 0

  // ensure every output is either user defined, or over the threshold
  if (!outputs.every(function (x) {
    return x.value !== undefined || (splitValue > utils.dustThreshold(x, feeRate))
  })) return { fee: fee }

  // assign splitValue to outputs not user defined
  outputs = outputs.map(function (x) {
    if (x.value !== undefined) return x

    // not user defined, but still copy over any non-value fields
    var y = {
      value: splitValue
    }

    for (var k in x) y[k] = x[k]
    return y
  })

  return utils.finalize(utxos, outputs, feeRate)
}
<commit_msg>split: avoid undefined value overwrite<commit_after>var utils = require('./utils')

module.exports = function split (utxos, outputs, feeRate) {
  if (!isFinite(utils.uintOrNaN(feeRate))) return {}

  var bytesAccum = utils.transactionBytes(utxos, outputs)
  var fee = feeRate * bytesAccum
  if (outputs.length === 0) return { fee: fee }

  var inAccum = utils.sumOrNaN(utxos)
  var outAccum = utils.sumForgiving(outputs)
  var remaining = inAccum - outAccum - fee
  if (!isFinite(remaining) || remaining <= 0) return { fee: fee }

  var splitOutputsCount = outputs.reduce(function (a, x) {
    return a + !x.value
  }, 0)
  var splitValue = (remaining / splitOutputsCount) >>> 0

  // ensure every output is either user defined, or over the threshold
  if (!outputs.every(function (x) {
    return x.value !== undefined || (splitValue > utils.dustThreshold(x, feeRate))
  })) return { fee: fee }

  // assign splitValue to outputs not user defined
  outputs = outputs.map(function (x) {
    if (x.value !== undefined) return x

    // not user defined, but still copy over any non-value fields
    var y = {}
    for (var k in x) y[k] = x[k]
    y.value = splitValue
    return y
  })

  return utils.finalize(utxos, outputs, feeRate)
}
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');

var resolveBabel = function(name) {
  return path.join(__dirname, '..', 'node_modules', name)
}

var babelPlugins = [
  resolveBabel('babel-plugin-transform-object-rest-spread'),
  resolveBabel('babel-plugin-transform-decorators-legacy')
];

var babelPresets = [
  resolveBabel('babel-preset-es2015'),
  resolveBabel('babel-preset-stage-0'),
  resolveBabel('babel-preset-react')
];

module.exports = {
  bail: true,
  devtool: 'source-map',
  entry: {
    app: path.resolve(__dirname, '../src/web/index.jsx')
  },
  output: {
    path: path.resolve(__dirname, '../lib/web/js'),
    publicPath: '/js/',
    filename: '[name].dll.bundle.js'
  },
  resolve: {
    root: [path.join(__dirname, '..', 'node_modules')],
    extensions: ['', '.js', '.jsx', '.css'],
    alias: {
      '~': path.resolve(__dirname, '../src/web')
    }
  },
  resolveLoader: {
    root: path.join(__dirname, '..', 'node_modules')
  },
  plugins: [
    // new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DllReferencePlugin({
      context: path.join(__dirname, '..'),
      manifest: require(path.join(__dirname, '../lib/web/js', 'vendor-manifest.json'))
    }),
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../src/web/index.html'),
        to: path.resolve(__dirname, '../lib/web/index.html')
      },
      {
        from: path.resolve(__dirname, '../src/web/img'),
        to: path.resolve(__dirname, '../lib/web/img')
      }
    ])
  ],
  module: {
    loaders: [{
        test: /\.jsx?$/,
        exclude: /botskin\/node_modules/,
        loader: 'babel-loader',
        query: {
          presets: babelPresets,
          plugins: babelPlugins,
          compact: false
        }
        },
      {
        test: /\.scss$/,
        loaders: ['style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]', 'sass']
        },
      {
        test: /\.css$/,
        loaders: ['style', 'css']
        },
      {
        test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
        loader: 'file?name=../fonts/[name].[ext]'
        },
      {
        test: /\.json$/,
        loader: "json-loader"
        }]
  }
}
<commit_msg>Fixed babel packing<commit_after>var webpack = require('webpack');
var path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');

var resolveBabel = function(name) {
  return path.join(__dirname, '..', 'node_modules', name)
}

var babelPlugins = [
  resolveBabel('babel-plugin-transform-object-rest-spread'),
  resolveBabel('babel-plugin-transform-decorators-legacy')
];

var babelPresets = [
  resolveBabel('babel-preset-es2015'),
  resolveBabel('babel-preset-stage-0'),
  resolveBabel('babel-preset-react')
];

module.exports = {
  bail: true,
  devtool: 'source-map',
  entry: {
    app: path.resolve(__dirname, '../src/web/index.jsx')
  },
  output: {
    path: path.resolve(__dirname, '../lib/web/js'),
    publicPath: '/js/',
    filename: '[name].dll.bundle.js'
  },
  resolve: {
    root: [path.join(__dirname, '..', 'node_modules')],
    extensions: ['', '.js', '.jsx', '.css'],
    alias: {
      '~': path.resolve(__dirname, '../src/web')
    }
  },
  resolveLoader: {
    root: path.join(__dirname, '..', 'node_modules')
  },
  plugins: [
    // new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DllReferencePlugin({
      context: path.join(__dirname, '..'),
      manifest: require(path.join(__dirname, '../lib/web/js', 'vendor-manifest.json'))
    }),
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../src/web/index.html'),
        to: path.resolve(__dirname, '../lib/web/index.html')
      },
      {
        from: path.resolve(__dirname, '../src/web/img'),
        to: path.resolve(__dirname, '../lib/web/img')
      }
    ])
  ],
  module: {
    loaders: [{
        test: /\.jsx?$/,
        exclude: /botskin\/node_modules/,
        loader: 'babel-loader',
        query: {
          presets: babelPresets,
          plugins: babelPlugins,
          compact: false,
          babelrc: false
        }
        },
      {
        test: /\.scss$/,
        loaders: ['style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]', 'sass']
        },
      {
        test: /\.css$/,
        loaders: ['style', 'css']
        },
      {
        test: /\.woff|\.woff2|\.svg|.eot|\.ttf/,
        loader: 'file?name=../fonts/[name].[ext]'
        },
      {
        test: /\.json$/,
        loader: "json-loader"
        }]
  }
}
<|endoftext|>


<commit_before>Spore = function(x,y,size){
	this.x = x || floor(random(mapSize/cellSize))*cellSize+cellSize/2
	this.y = y || floor(random(mapSize/cellSize))*cellSize+cellSize/2
	this.speed = cellSpeed
	this.vel = {x:random(-1,1),y:random(-1,1)}
	this.food = 100; //saturation
	this.size = size || sporeSize
	this.life = 100;
	this.tileArea = 0;
	this.facing = PI/2+Math.atan2(this.vel.y, this.vel.x);
	this.tFacing = PI/2+Math.atan2(this.vel.y, this.vel.x);
  this.alive = true;
	this.target = {x:this.x,y:this.y}
}
Spore.prototype.draw = function(){
  push()
  translate(this.x,this.y)
  rotate(this.facing)
	fill(255,55+this.life*2,55+this.life*2,155+this.food)
	ellipse(0,0,this.size*0.9,this.size)
	fill(0,0,255,155+this.food)
	ellipse(0,-this.size/5,this.size/2,this.size/3)
	pop()
}
Spore.prototype.checkMove = function(){
  if(this.x < this.size/2)
    this.x = this.size/2
  else if(this.x > mapSize - this.size/2)
    this.x = mapSize - this.size/2
  if(this.y < this.size/2)
    this.y = this.size/2
  else if(this.y > mapSize - this.size/2)
    this.y = mapSize - this.size/2
}
Spore.prototype.checkCollision = function(){
  for(var i = 0; i < spores.length; i++){
    if(i != spores.indexOf(this) && this.tileArea == spores[i].tileArea && this.chckCol(spores[i])){
					return spores[i];
    }
  }
  for(i = 0; i < corpses.length; i++){
    if(this.tileArea == corpses[i].tileArea && this.chckCol(corpses[i])){
      return corpses[i]
    }
  }
  return false;
}
Spore.prototype.update = function(){
  this.tileArea = this.chckArea();
  var index = floor(this.y/cellSize)*(mapSize/cellSize)+floor(this.x/cellSize)
  //////Food
  this.food-= 0.5;
  if(tiles[index].food < 0){
      this.food+= tiles[index].food
      if(this.food < 0)
       this.food = 0;
  }
  else if(this.food < 100){
    var sp = this.checkCollision()
    if( sp && random() > 0.5){ //bite target
      this.bite(sp)
    }
    else
      this.eatGrass(tiles[index])
  }

  /////life
    this.checkLife()
  //////move
  if(this.rotate()){ //finished rotation
    if(random() < 0.03){
      this.changeDirection()
    }else
      this.move(index);
  }
  return(this.life > 0) //alive
}
Spore.prototype.bite = function(target){
  if(target.alive){
    target.life-=5;
    this.food+=5;
  } else{
    target.life-=2;
    this.food+=2;
  }
}
Spore.prototype.eatGrass = function(tile){
  this.food+= 1
  tile.food-= 1;
}
Spore.prototype.checkLife = function(){
  if(this.food > 60 && this.life < 100){
    this.life+=0.1
    if(this.food > 90){
      this.life+=0.4
      this.food--;
    }
  }
  else if(this.food === 0){
    this.life--;
  }
}
Spore.prototype.move = function(index){
  var dx = this.vel.x
  var dy = this.vel.y

  dx *= this.speed
  dy *= this.speed

  if(!tiles[index].land){
    dx *= 0.6
    dy *= 0.6
  }
  if(this.food < 30){
    dx *= 0.8
    dy *= 0.8
  }

  this.x += dx
  this.y += dy
  this.checkMove();
}
Spore.prototype.rotate = function(){
  if(this.facing == this.tFacing)
    return true
  if(0.4 >  abs(this.facing - this.tFacing)){
    this.facing = this.tFacing
  }else if(this.facing < this.tFacing)
    this.facing += 0.3
  else
    this.facing -= 0.3
  return false;
}
Spore.prototype.chckArea = function(){
	this.tileArea = 0;
	var indx = floor(this.y/cellSize)*(mapSize/cellSize)+floor(this.x/cellSize)
	if(indx%cellNum > floor(cellNum/2)) // 0 1 // 0 0 // areas
		this.tileArea++;			   // 0 1 // 2 2 // 0-3
	if(indx > floor(cellNum*(cellNum/2)))
		this.tileArea+=2;
}
Spore.prototype.chckCol = function(spore){
	if(Math.pow((spore.x-this.x),2) + Math.pow((this.y-spore.y),2) <= Math.pow((this.size/2+spore.size/2),2)){
		return true;
	}
}
Spore.prototype.changeDirection = function(){
  this.vel.x = random(-1,1)
  this.vel.y = random(-1,1)
  this.tFacing = PI/2+Math.atan2(this.vel.y, this.vel.x)
}<commit_msg>spore bitting only when facing enemy<commit_after>Spore = function(x,y,size){
	this.x = x || floor(random(mapSize/cellSize))*cellSize+cellSize/2
	this.y = y || floor(random(mapSize/cellSize))*cellSize+cellSize/2
	this.speed = cellSpeed
	this.vel = {x:random(-1,1),y:random(-1,1)}
	this.food = 100; //saturation
	this.size = size || sporeSize
	this.life = 100;
	this.tileArea = 0;
	this.facing = PI/2+Math.atan2(this.vel.y, this.vel.x);
	this.tFacing = PI/2+Math.atan2(this.vel.y, this.vel.x);
  this.alive = true;
	this.target = {x:this.x,y:this.y}
}
Spore.prototype.draw = function(){
  push()
  translate(this.x,this.y)
  rotate(this.facing)
	fill(255,55+this.life*2,55+this.life*2,155+this.food)
	ellipse(0,0,this.size*0.9,this.size)
	fill(0,0,255,155+this.food)
	ellipse(0,-this.size/5,this.size/2,this.size/3)
	pop()
}
Spore.prototype.checkMove = function(){
  if(this.x < this.size/2)
    this.x = this.size/2
  else if(this.x > mapSize - this.size/2)
    this.x = mapSize - this.size/2
  if(this.y < this.size/2)
    this.y = this.size/2
  else if(this.y > mapSize - this.size/2)
    this.y = mapSize - this.size/2
}
Spore.prototype.checkCollision = function(){
  for(var i = 0; i < spores.length; i++){
    if(i != spores.indexOf(this) && this.tileArea == spores[i].tileArea && this.chckCol(spores[i])){
					return spores[i];
    }
  }
  for(i = 0; i < corpses.length; i++){
    if(this.tileArea == corpses[i].tileArea && this.chckCol(corpses[i])){
      return corpses[i]
    }
  }
  return false;
}
Spore.prototype.update = function(){
  this.tileArea = this.chckArea();
  var index = floor(this.y/cellSize)*(mapSize/cellSize)+floor(this.x/cellSize)
  //////Food
  this.food-= 0.25;
  if(tiles[index].food < 0){
      this.food+= tiles[index].food
      if(this.food < 0)
       this.food = 0;
  }
  else if(tiles[index].food > 1 && this.food < 100)
    this.eatGrass(tiles[index])

  var sp = this.checkCollision()
  if( sp && this.isFacing(sp) && random() < 0.4 ){
    this.bite(sp)
  }

  /////life
    this.checkLife()
  //////move
  if(this.rotate()){ //finished rotation
    if(random() < 0.03){
      this.changeDirection()
    }else
      this.move(index);
  }
  return(this.life > 0) //alive
}
Spore.prototype.isFacing = function(spore){
  var angle = PI/2 + Math.atan2(spore.y - this.y, spore.x - this.x);
  if(0.4 > abs(this.facing - angle)){
    return true;
  }else
    return false;
}
Spore.prototype.bite = function(target){
  if(target.alive){
    target.life-=5;
    this.food+=5;
  } else{
    target.life-=2;
    this.food+=2;
  }
}
Spore.prototype.eatGrass = function(tile){
  this.food+= 1
  tile.food-= 1;
}
Spore.prototype.checkLife = function(){
  if(this.food > 60 && this.life < 100){
    this.life+=0.1
    if(this.food > 90){
      this.life+=0.4
      this.food--;
    }
  }
  else if(this.food === 0){
    this.life--;
  }
}
Spore.prototype.move = function(index){
  var dx = this.vel.x
  var dy = this.vel.y

  dx *= this.speed
  dy *= this.speed

  if(!tiles[index].land){
    dx *= 0.6
    dy *= 0.6
  }
  if(this.food < 30){
    dx *= 0.8
    dy *= 0.8
  }

  this.x += dx
  this.y += dy
  this.checkMove();
}
Spore.prototype.rotate = function(){
  if(this.facing == this.tFacing)
    return true
  if(0.4 > abs(this.facing - this.tFacing)){
    this.facing = this.tFacing
  }else if(this.facing < this.tFacing)
    this.facing += 0.3
  else
    this.facing -= 0.3
  return false;
}
Spore.prototype.chckArea = function(){
	this.tileArea = 0;
	var indx = floor(this.y/cellSize)*(mapSize/cellSize)+floor(this.x/cellSize)
	if(indx%cellNum > floor(cellNum/2)) // 0 1 // 0 0 // areas
		this.tileArea++;			   // 0 1 // 2 2 // 0-3
	if(indx > floor(cellNum*(cellNum/2)))
		this.tileArea+=2;
}
Spore.prototype.chckCol = function(spore){
	if(Math.pow((spore.x-this.x),2) + Math.pow((this.y-spore.y),2) <= Math.pow((this.size/2+spore.size/2),2)){
		return true;
	}
}
Spore.prototype.changeDirection = function(){
  this.vel.x = random(-1,1)
  this.vel.y = random(-1,1)
  this.tFacing = PI/2+Math.atan2(this.vel.y, this.vel.x)
}<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const colog = require('colog');
const app = require('commander');

/**
 * Import the connection module.
 * This import implicitly validates the connection
 * configuration and throws an exception if there is
 * an error.
 */
const {config} = require('./connection');
const {core} = require('./commands/core');
// TO DO: custom object should have its own method of
// selecting a command name from configuration and returning a function
// to register the command.  this will also have to validate
// the custom configuration.
const custom = require('./custom');
const commandName = process.argv[2];
if (config.isValid) {
	if (!commandName) {
		// TO DO: show description and list of commands
	} else if (core.hasOwnProperty(commandName)) {
		core[commandName](app, config);
	} else if (custom.hasOwnProperty(commandName)) {
		custom[commandName](app, config);
	} else {
		colog.error(`${commandName} is not a valid command name`);
	}

	app.parse(process.argv);
}
<commit_msg>modify entry point file to reflect updated changes to custom and core command configuration setups<commit_after>#!/usr/bin/env node
'use strict';

const colog = require('colog');
const app = require('commander');

const core = require('./commands/core');
/**
 * Loading the connection and custom modules parses the
 * settings files and implicitly validates settings and configuration.
 * `isValid` properties store the result of the validations.
 */
const connection = require('./connection');
const custom = require('./custom');
/**
 * Commander normally handles parsing of argv,
 * but we want to configure the commander object at runtime..
 */
const commandName = process.argv[2];

if (connection.isValid && custom.isValid) {
	if (!commandName) {
		// TO DO: show description and list of commands
	} else if (core.commands.hasOwnProperty(commandName)) {
		core.commands[commandName](app, connection);
	} else if (custom.commands.hasOwnProperty(commandName)) {
		custom.commands[commandName](app, connection);
	} else {
		colog.error(`${commandName} is not a valid command name`);
	}

	app.parse(process.argv);
}
<|endoftext|>


<commit_before>const DEBUG = false;
class Debug {
    constructor() {
        this.debugPar = document.getElementById("debug");
        this.debugPar.style.display = DEBUG ? "" : "none";
        if (DEBUG) this.show();
        else this.hide();
    }
    clear() {
        if (!DEBUG) return;
        this.debugPar.innerHTML = "";
    }
    append(...html) {
        if (!DEBUG) return;
        this.debugPar.innerHTML += html.join(" ");
    }
    appendLine(...html) {
        if (!DEBUG) return;
        this.debugPar.innerHTML += "
" + html.join(" ");;
    }
    show() {
        this.debugPar.style.display = "";
    }
    hide() {
        this.debugPar.style.display = "none";
    }
}
var debug = new Debug();
class Zoom {
    constructor() {}
    reset() {
        this.zoomUpperLimit = document.getElementById("zoomUpperLimit").innerText === "true";
        this.marginPixels = 20;
        this.img = document.getElementById("image");
        this.naturalWidth = this.img.naturalWidth;
        this.naturalHeight = this.img.naturalHeight;
        this.zoom = (window.innerWidth - this.marginPixels) / this.naturalWidth * 100;
        if (this.zoom > 100) this.zoom = 100;
        this.img.style.width = "";
        this.img.style.maxWidth = "";
        document.body.style.width = "";
        if (document.body.offsetHeight < window.innerHeight) document.body.style.height = window.innerHeight - this.marginPixels + "px";
        debug.clear();
        debug.append(`
            initial zoom:${this.zoom}

            image naturalWidth:${this.naturalWidth}

            image width:${this.img.width}

            window width:${window.innerWidth}

            window height:${window.innerHeight}

            body width:${document.body.offsetWidth}

            body height:${document.body.offsetHeight}

            scroll Width:${window.innerWidth - document.body.clientWidth}

        `);
    }
    setZoom(zoom) {
        debug.appendLine("org: ", this.zoom);
        let winWidth = window.innerWidth;
        let contentWidth = winWidth - this.marginPixels
        let minWidth = contentWidth < this.naturalWidth ? contentWidth : this.naturalWidth;
        let minZoom = parseInt(minWidth / this.naturalWidth * 100);
        const maxZoom = 100;

        if (this.zoomUpperLimit && zoom > maxZoom) zoom = maxZoom;
        if (zoom < minZoom || (minZoom == maxZoom && this.zoomUpperLimit)) {
            zoom = minZoom;
            this.img.style.width = "";
            this.img.style.maxWidth = "";
            document.body.style.width = "";
            zoom = minZoom;
        } else {
            let imgWidth = parseInt(this.naturalWidth * zoom / 100);
            this.img.style.width = imgWidth + 'px';
            let body = document.body;
            let bodyWidth = imgWidth + this.marginPixels < winWidth ? winWidth : imgWidth + this.marginPixels;
            body.style.width = bodyWidth + 'px'
            if (body.offsetHeight < window.innerHeight) body.style.height = window.innerHeight - this.marginPixels + "px";
        }
        this.zoom = zoom;
        debug.appendLine("cur: ", this.zoom);
    }
    setScroll(left, top) {
        document.body.scrollLeft = left;
        document.body.scrollTop = top;
    }
    add() {
        this.reset();
        document.body.addEventListener("mousewheel", () => {
            let mouseAt = this.getMousePointer();
            if (this.zoomUpperLimit) {
                this.setZoom(this.zoom + event.wheelDelta / 12);
            } else {
                // zoom level increase / decrease by 30% for each wheel scroll
                this.setZoom(this.zoom * (event.wheelDelta / 600 + 1));
            }
            this.followMousePointer(mouseAt);
            saveStatus();
            return false;
        });
        window.onresize = () => {
            let winWidth = window.innerWidth;
            let contentWidth = winWidth - this.marginPixels
            let minWidth = contentWidth < this.naturalWidth ? contentWidth : this.naturalWidth;
            let minZoom = parseInt(minWidth / this.naturalWidth * 100);

            if (this.img.style.width == "") {
                // console.log("update zoom value due to resize");
                this.zoom = minZoom;
            } else if (this.zoom < minZoom) {
                // console.log("change zoom to fit");
                this.zoom = minZoom;
                this.img.style.width = "";
                this.img.style.maxWidth = "";
                document.body.style.width = "";
            }
        };
        window.onmousewheel = function () {
            return false
        };
    }
    followMousePointer(mouseAt) {
        let e = event || window.event;
        let imgWidth = parseInt(this.naturalWidth * this.zoom / 100);
        let imgHeight = parseInt(this.naturalHeight * this.zoom / 100);
        document.body.scrollLeft += parseInt(imgWidth * mouseAt.imageX + this.marginPixels / 2) - mouseAt.x;
        document.body.scrollTop += parseInt(imgHeight * mouseAt.imageY + this.marginPixels / 2) - mouseAt.y;
    }
    getMousePointer() {
        let imgWidth = parseInt(this.naturalWidth * this.zoom / 100);
        let imgHeight = parseInt(this.naturalHeight * this.zoom / 100);
        let e = event || window.event;
        let mouseAt = {
            x: e.clientX + document.body.scrollLeft,
            y: e.clientY + document.body.scrollTop,
            imageX: (e.clientX + document.body.scrollLeft - this.marginPixels / 2) / imgWidth,
            imageY: (e.clientY + document.body.scrollTop - this.marginPixels / 2) / imgHeight,
        }
        return mouseAt;
    }
}
class Switcher {
    constructor() {
        this.current = 0;
        this.images = [];
        this.image = document.getElementById("image");
        this.pInfo = document.getElementById("pageInfo");
        this.pInfoTpl = this.pInfo.innerText;
        for (let e of document.getElementById("images").getElementsByTagName("img")) {
            this.images.push(e.src);
        }
    }
    add() {
        if (this.images.length <= 1) {
            document.getElementById("placeholder").style.display = "none";
            document.getElementById("controls").style.display = "none";
            return;
        }
        document.getElementById("btnNext").addEventListener("click", () => {
            if (this.current == this.images.length) return;
            this.moveTo(++this.current);
            saveStatus();
        });
        document.getElementById("btnPrev").addEventListener("click", () => {
            if (this.current == 1) return;
            this.moveTo(--this.current);
            saveStatus();
        });

        this.moveTo(1);
        document.getElementById("images").remove();
        // console.log(this.images.length);
    }
    moveTo(page) {
        if (page < 1 || page > this.images.length) return;
        this.image.src = this.images[page - 1];
        this.pInfo.innerText = String.format(this.pInfoTpl, page, this.images.length);
        this.current = page;
        zoomer.reset();
    }
}
String.format = function format() {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}
let zoomer;
let switcher;
let sendStatus;

function saveStatus() {
    if (sendStatus) {
        let status = JSON.stringify({
            page: switcher.current,
            zoom: zoomer.zoom,
            x: document.body.scrollLeft,
            y: document.body.scrollTop
        });
        // console.log("save status: " + status);
        sendStatus.attributes["href"].value = 'command:plantuml.previewStatus?' + encodeURIComponent(status);
        sendStatus.click();
    }
}
window.addEventListener("load", () => {
    sendStatus = document.getElementById("sendStatus");
    zoomer = new Zoom();
    switcher = new Switcher();
    switcher.add();
    zoomer.add();
    let jsonStatus = document.getElementById("status").innerHTML;
    if (jsonStatus) {
        let status = JSON.parse(jsonStatus);
        if (status) {
            switcher.moveTo(status.page);
            zoomer.setZoom(status.zoom);
            zoomer.setScroll(status.x, status.y);
        }
    }
    if (!document.getElementById("errtxt").innerText.trim())
        document.getElementById("error-warning").style.display = "none";

});
window.addEventListener("mouseup", () => saveStatus());<commit_msg>optimized preview for touchpad<commit_after>const DEBUG = false;
class Debug {
    constructor() {
        this.debugPar = document.getElementById("debug");
        this.debugPar.style.display = DEBUG ? "" : "none";
        if (DEBUG) this.show();
        else this.hide();
    }
    clear() {
        if (!DEBUG) return;
        this.debugPar.innerHTML = "";
    }
    append(...html) {
        if (!DEBUG) return;
        this.debugPar.innerHTML += html.join(" ");
    }
    appendLine(...html) {
        if (!DEBUG) return;
        this.debugPar.innerHTML += "
" + html.join(" ");;
    }
    show() {
        this.debugPar.style.display = "";
    }
    hide() {
        this.debugPar.style.display = "none";
    }
}
var debug = new Debug();
class Zoom {
    constructor() {}
    reset() {
        this.zoomUpperLimit = document.getElementById("zoomUpperLimit").innerText === "true";
        this.marginPixels = 20;
        this.img = document.getElementById("image");
        this.naturalWidth = this.img.naturalWidth;
        this.naturalHeight = this.img.naturalHeight;
        this.zoom = (window.innerWidth - this.marginPixels) / this.naturalWidth * 100;
        if (this.zoom > 100) this.zoom = 100;
        this.img.style.width = "";
        this.img.style.maxWidth = "";
        document.body.style.width = "";
        if (document.body.offsetHeight < window.innerHeight) document.body.style.height = window.innerHeight - this.marginPixels + "px";
        debug.clear();
        debug.append(`
            initial zoom:${this.zoom}

            image naturalWidth:${this.naturalWidth}

            image width:${this.img.width}

            window width:${window.innerWidth}

            window height:${window.innerHeight}

            body width:${document.body.offsetWidth}

            body height:${document.body.offsetHeight}

            scroll Width:${window.innerWidth - document.body.clientWidth}

        `);
    }
    setZoom(zoom) {
        debug.appendLine("org: ", this.zoom);
        let winWidth = window.innerWidth;
        let contentWidth = winWidth - this.marginPixels
        let minWidth = contentWidth < this.naturalWidth ? contentWidth : this.naturalWidth;
        let minZoom = parseInt(minWidth / this.naturalWidth * 100);
        const maxZoom = 100;

        if (this.zoomUpperLimit && zoom > maxZoom) zoom = maxZoom;
        if (zoom < minZoom || (minZoom == maxZoom && this.zoomUpperLimit)) {
            zoom = minZoom;
            this.img.style.width = "";
            this.img.style.maxWidth = "";
            document.body.style.width = "";
            zoom = minZoom;
        } else {
            let imgWidth = parseInt(this.naturalWidth * zoom / 100);
            this.img.style.width = imgWidth + 'px';
            let body = document.body;
            let bodyWidth = imgWidth + this.marginPixels < winWidth ? winWidth : imgWidth + this.marginPixels;
            body.style.width = bodyWidth + 'px'
            if (body.offsetHeight < window.innerHeight) body.style.height = window.innerHeight - this.marginPixels + "px";
        }
        this.zoom = zoom;
        debug.appendLine("cur: ", this.zoom);
    }
    setScroll(left, top) {
        document.body.scrollLeft = left;
        document.body.scrollTop = top;
    }
    add() {
        this.reset();
        document.body.addEventListener("mousewheel", () => {
            console.log(event.ctrlKey, event.wheelDeltaX, event.wheelDeltaY);
            // scroll to zoom, or ctrl key pressed scroll
            if (false || event.ctrlKey) {
                // ctrlKey == true: pinch
                let delta = event.ctrlKey ? event.wheelDelta / 60 : event.wheelDelta / 12;
                let mouseAt = this.getMousePointer();
                if (this.zoomUpperLimit) {
                    this.setZoom(this.zoom + delta);
                } else {
                    // zoom level increase / decrease by 30% for each wheel scroll
                    this.setZoom(this.zoom * (delta / 50 + 1));
                }
                this.followMousePointer(mouseAt);
                if(event.preventDefault) event.preventDefault();
                return false;
            }
            saveStatus();
        });
        window.onresize = () => {
            let winWidth = window.innerWidth;
            let contentWidth = winWidth - this.marginPixels
            let minWidth = contentWidth < this.naturalWidth ? contentWidth : this.naturalWidth;
            let minZoom = parseInt(minWidth / this.naturalWidth * 100);

            if (this.img.style.width == "") {
                // console.log("update zoom value due to resize");
                this.zoom = minZoom;
            } else if (this.zoom < minZoom) {
                // console.log("change zoom to fit");
                this.zoom = minZoom;
                this.img.style.width = "";
                this.img.style.maxWidth = "";
                document.body.style.width = "";
            }
        };
    }
    followMousePointer(mouseAt) {
        let e = event || window.event;
        let imgWidth = parseInt(this.naturalWidth * this.zoom / 100);
        let imgHeight = parseInt(this.naturalHeight * this.zoom / 100);
        document.body.scrollLeft += parseInt(imgWidth * mouseAt.imageX + this.marginPixels / 2) - mouseAt.x;
        document.body.scrollTop += parseInt(imgHeight * mouseAt.imageY + this.marginPixels / 2) - mouseAt.y;
    }
    getMousePointer() {
        let imgWidth = parseInt(this.naturalWidth * this.zoom / 100);
        let imgHeight = parseInt(this.naturalHeight * this.zoom / 100);
        let e = event || window.event;
        let mouseAt = {
            x: e.clientX + document.body.scrollLeft,
            y: e.clientY + document.body.scrollTop,
            imageX: (e.clientX + document.body.scrollLeft - this.marginPixels / 2) / imgWidth,
            imageY: (e.clientY + document.body.scrollTop - this.marginPixels / 2) / imgHeight,
        }
        return mouseAt;
    }
}
class Switcher {
    constructor() {
        this.current = 0;
        this.images = [];
        this.image = document.getElementById("image");
        this.pInfo = document.getElementById("pageInfo");
        this.pInfoTpl = this.pInfo.innerText;
        for (let e of document.getElementById("images").getElementsByTagName("img")) {
            this.images.push(e.src);
        }
    }
    add() {
        if (this.images.length <= 1) {
            document.getElementById("placeholder").style.display = "none";
            document.getElementById("controls").style.display = "none";
            return;
        }
        document.getElementById("btnNext").addEventListener("click", () => {
            if (this.current == this.images.length) return;
            this.moveTo(++this.current);
            saveStatus();
        });
        document.getElementById("btnPrev").addEventListener("click", () => {
            if (this.current == 1) return;
            this.moveTo(--this.current);
            saveStatus();
        });

        this.moveTo(1);
        document.getElementById("images").remove();
        // console.log(this.images.length);
    }
    moveTo(page) {
        if (page < 1 || page > this.images.length) return;
        this.image.src = this.images[page - 1];
        this.pInfo.innerText = String.format(this.pInfoTpl, page, this.images.length);
        this.current = page;
        zoomer.reset();
    }
}
String.format = function format() {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}
let zoomer;
let switcher;
let sendStatus;

function saveStatus() {
    if (sendStatus) {
        let status = JSON.stringify({
            page: switcher.current,
            zoom: zoomer.zoom,
            x: document.body.scrollLeft,
            y: document.body.scrollTop
        });
        // console.log("save status: " + status);
        sendStatus.attributes["href"].value = 'command:plantuml.previewStatus?' + encodeURIComponent(status);
        sendStatus.click();
    }
}
window.addEventListener("load", () => {
    sendStatus = document.getElementById("sendStatus");
    zoomer = new Zoom();
    switcher = new Switcher();
    switcher.add();
    zoomer.add();
    let jsonStatus = document.getElementById("status").innerHTML;
    if (jsonStatus) {
        let status = {};
        try {
            status = JSON.parse(jsonStatus);
        } catch (error) {}
        status.page = status.page || 1;
        status.zoom = status.zoom || 1;
        status.x = status.x || 0;
        status.y = status.y || 0;
        switcher.moveTo(status.page);
        zoomer.setZoom(status.zoom);
        zoomer.setScroll(status.x, status.y);
    }
    if (!document.getElementById("errtxt").innerText.trim())
        document.getElementById("error-warning").style.display = "none";

});
window.addEventListener("mouseup", () => saveStatus());<|endoftext|>