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

couchTests.replication = function(debug) {
  if (debug) debugger;
  var host = CouchDB.host;
  var dbPairs = [
    {source:"test_suite_db_a",
      target:"test_suite_db_b"},
    {source:"test_suite_db_a",
      target:"http://" + host + "/test_suite_db_b"},
    {source:"http://" + host + "/test_suite_db_a",
      target:"test_suite_db_b"},
    {source:"http://" + host + "/test_suite_db_a",
      target:"http://" + host + "/test_suite_db_b"}
  ]
  var dbA = new CouchDB("test_suite_db_a");
  var dbB = new CouchDB("test_suite_db_b");
  var numDocs = 10;
  var xhr;
  for (var testPair = 0; testPair < dbPairs.length; testPair++) {
    var A = dbPairs[testPair].source
    var B = dbPairs[testPair].target

    dbA.deleteDb();
    dbA.createDb();
    dbB.deleteDb();
    dbB.createDb();

    var repTests = {
      // copy and paste and put your code in. delete unused steps.
      test_template: new function () {
        this.init = function(dbA, dbB) {
          // before anything has happened
        }
        this.afterAB1 = function(dbA, dbB) {
          // called after replicating src=A  tgt=B first time.
        };
        this.afterBA1 = function(dbA, dbB) {
          // called after replicating src=B  tgt=A first time.
        };
        this.afterAB2 = function(dbA, dbB) {
          // called after replicating src=A  tgt=B second time.
        };
        this.afterBA2 = function(dbA, dbB) {
          // etc...
        };
      },

      simple_test: new function () {
        this.init = function(dbA, dbB) {
          var docs = makeDocs(0, numDocs);
          dbA.bulkSave(docs);
        };

        this.afterAB1 = function(dbA, dbB) {
          for (var j = 0; j < numDocs; j++) {
            var docA = dbA.open("" + j);
            var docB = dbB.open("" + j);
            T(docA._rev == docB._rev);
          }
        };
      },

     deletes_test: new function () {
        this.init = function(dbA, dbB) {
          T(dbA.save({_id:"foo1",value:"a"}).ok);
        };

        this.afterAB1 = function(dbA, dbB) {
          var docA = dbA.open("foo1");
          var docB = dbB.open("foo1");
          T(docA._rev == docB._rev);

          dbA.deleteDoc(docA);
        };

        this.afterAB2 = function(dbA, dbB) {
          T(dbA.open("foo1") == null);
          T(dbB.open("foo1") == null);
        };
      },

      slashes_in_ids_test: new function () {
        // make sure docs with slashes in id replicate properly
        this.init = function(dbA, dbB) {
          dbA.save({ _id:"abc/def", val:"one" });
        };

        this.afterAB1 = function(dbA, dbB) {
          var docA = dbA.open("abc/def");
          var docB = dbB.open("abc/def");
          T(docA._rev == docB._rev);
        };
      },

      design_docs_test: new function() {
        // make sure design docs replicate properly
        this.init = function(dbA, dbB) {
          dbA.save({ _id:"_design/test" });
        };

        this.afterAB1 = function() {
          var docA = dbA.open("_design/test");
          var docB = dbB.open("_design/test");
          T(docA._rev == docB._rev);
        };
      },

      attachments_test: new function () {
        // Test attachments
        this.init = function(dbA, dbB) {
          dbA.save({
            _id:"bin_doc",
            _attachments:{
              "foo.txt": {
                "type":"base64",
                "data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
              }
            }
          });
        };

        this.afterAB1 = function(dbA, dbB) {
          var xhr = CouchDB.request("GET", "/test_suite_db_a/bin_doc/foo.txt");
          T(xhr.responseText == "This is a base64 encoded text")

          xhr = CouchDB.request("GET", "/test_suite_db_b/bin_doc/foo.txt");
          T(xhr.responseText == "This is a base64 encoded text")
        };
      },

      conflicts_test: new function () {
        // test conflicts
        this.init = function(dbA, dbB) {
          dbA.save({_id:"foo",value:"a"});
          dbB.save({_id:"foo",value:"b"});
        };

        this.afterBA1 = function(dbA, dbB) {
          var docA = dbA.open("foo", {conflicts: true});
          var docB = dbB.open("foo", {conflicts: true});

          // make sure the same rev is in each db
          T(docA._rev === docB._rev);

          // make sure the conflicts are the same in each db
          T(docA._conflicts[0] === docB._conflicts[0]);

          // delete a conflict.
          dbA.deleteDoc({_id:"foo", _rev:docA._conflicts[0]});
        };

        this.afterBA2 = function(dbA, dbB) {
          // open documents and include the conflict meta data
          var docA = dbA.open("foo", {conflicts: true});
          var docB = dbB.open("foo", {conflicts: true});

          // We should have no conflicts this time
          T(docA._conflicts === undefined)
          T(docB._conflicts === undefined);
        };
      }
    };

    var test;
    for(test in repTests) {
      if(repTests[test].init) {
        repTests[test].init(dbA, dbB);
      }
    }

    var result = CouchDB.replicate(A, B);

    var seqA = result.source_last_seq;
    T(0 == result.history[0].start_last_seq);
    T(result.history[1] === undefined)

    for(test in repTests) {
      if(repTests[test].afterAB1) repTests[test].afterAB1(dbA, dbB);
    }

    result = CouchDB.replicate(B, A);

    var seqB = result.source_last_seq;
    T(0 == result.history[0].start_last_seq);
    T(result.history[1] === undefined)

    for(test in repTests) {
      if(repTests[test].afterBA1) repTests[test].afterBA1(dbA, dbB);
    }

    var result2 = CouchDB.replicate(A, B);

    // each successful replication produces a new session id
    T(result2.session_id != result.session_id);

    T(seqA < result2.source_last_seq);
    T(seqA == result2.history[0].start_last_seq);
    T(result2.history[1].end_last_seq == seqA)

    seqA = result2.source_last_seq;

    for(test in repTests) {
      if(repTests[test].afterAB2) repTests[test].afterAB2(dbA, dbB);
    }

    result = CouchDB.replicate(B, A)

    T(seqB < result.source_last_seq);
    T(seqB == result.history[0].start_last_seq);
    T(result.history[1].end_last_seq == seqB)

    seqB = result.source_last_seq;

    for(test in repTests) {
      if(repTests[test].afterBA2) repTests[test].afterBA2(dbA, dbB);
    }

    // do an replication where nothing has changed
    result2 = CouchDB.replicate(B, A);
    T(result2.no_changes == true);
    T(result2.session_id == result.session_id);
  }
};
<commit_msg>error message on invalid rev format. another replication test.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.replication = function(debug) {
  if (debug) debugger;
  var host = CouchDB.host;
  var dbPairs = [
    {source:"test_suite_db_a",
      target:"test_suite_db_b"},
    {source:"test_suite_db_a",
      target:"http://" + host + "/test_suite_db_b"},
    {source:"http://" + host + "/test_suite_db_a",
      target:"test_suite_db_b"},
    {source:"http://" + host + "/test_suite_db_a",
      target:"http://" + host + "/test_suite_db_b"}
  ]
  var dbA = new CouchDB("test_suite_db_a");
  var dbB = new CouchDB("test_suite_db_b");
  var numDocs = 10;
  var xhr;
  for (var testPair = 0; testPair < dbPairs.length; testPair++) {
    var A = dbPairs[testPair].source
    var B = dbPairs[testPair].target

    dbA.deleteDb();
    dbA.createDb();
    dbB.deleteDb();
    dbB.createDb();

    var repTests = {
      // copy and paste and put your code in. delete unused steps.
      test_template: new function () {
        this.init = function(dbA, dbB) {
          // before anything has happened
        }
        this.afterAB1 = function(dbA, dbB) {
          // called after replicating src=A  tgt=B first time.
        };
        this.afterBA1 = function(dbA, dbB) {
          // called after replicating src=B  tgt=A first time.
        };
        this.afterAB2 = function(dbA, dbB) {
          // called after replicating src=A  tgt=B second time.
        };
        this.afterBA2 = function(dbA, dbB) {
          // etc...
        };
      },

      simple_test: new function () {
        this.init = function(dbA, dbB) {
          var docs = makeDocs(0, numDocs);
          dbA.bulkSave(docs);
        };

        this.afterAB1 = function(dbA, dbB) {
          for (var j = 0; j < numDocs; j++) {
            var docA = dbA.open("" + j);
            var docB = dbB.open("" + j);
            T(docA._rev == docB._rev);
          }
        };
      },

     deletes_test: new function () {
        // make sure deletes are replicated
        this.init = function(dbA, dbB) {
          T(dbA.save({_id:"foo1",value:"a"}).ok);
        };

        this.afterAB1 = function(dbA, dbB) {
          var docA = dbA.open("foo1");
          var docB = dbB.open("foo1");
          T(docA._rev == docB._rev);

          dbA.deleteDoc(docA);
        };

        this.afterAB2 = function(dbA, dbB) {
          T(dbA.open("foo1") == null);
          T(dbB.open("foo1") == null);
        };
      },

      deleted_test : new function() {
        // docs created and deleted on a single node are also replicated
        this.init = function(dbA, dbB) {
          T(dbA.save({_id:"del1",value:"a"}).ok);
          var docA = dbA.open("del1");
          dbA.deleteDoc(docA);
        };

        this.afterAB1 = function(dbA, dbB) {
          var rows = dbB.allDocsBySeq().rows;
          var rowCnt = 0;
          for (var i=0; i < rows.length; i++) {
            if (rows[i].id == "del1") {
              rowCnt += 1;
              T(rows[i].value.deleted == true);
            }
          };
          T(rowCnt == 1);
        };
      },

      slashes_in_ids_test: new function () {
        // make sure docs with slashes in id replicate properly
        this.init = function(dbA, dbB) {
          dbA.save({ _id:"abc/def", val:"one" });
        };

        this.afterAB1 = function(dbA, dbB) {
          var docA = dbA.open("abc/def");
          var docB = dbB.open("abc/def");
          T(docA._rev == docB._rev);
        };
      },

      design_docs_test: new function() {
        // make sure design docs replicate properly
        this.init = function(dbA, dbB) {
          dbA.save({ _id:"_design/test" });
        };

        this.afterAB1 = function() {
          var docA = dbA.open("_design/test");
          var docB = dbB.open("_design/test");
          T(docA._rev == docB._rev);
        };
      },

      attachments_test: new function () {
        // Test attachments
        this.init = function(dbA, dbB) {
          dbA.save({
            _id:"bin_doc",
            _attachments:{
              "foo.txt": {
                "type":"base64",
                "data": "VGhpcyBpcyBhIGJhc2U2NCBlbmNvZGVkIHRleHQ="
              }
            }
          });
        };

        this.afterAB1 = function(dbA, dbB) {
          var xhr = CouchDB.request("GET", "/test_suite_db_a/bin_doc/foo.txt");
          T(xhr.responseText == "This is a base64 encoded text")

          xhr = CouchDB.request("GET", "/test_suite_db_b/bin_doc/foo.txt");
          T(xhr.responseText == "This is a base64 encoded text")
        };
      },

      conflicts_test: new function () {
        // test conflicts
        this.init = function(dbA, dbB) {
          dbA.save({_id:"foo",value:"a"});
          dbB.save({_id:"foo",value:"b"});
        };

        this.afterBA1 = function(dbA, dbB) {
          var docA = dbA.open("foo", {conflicts: true});
          var docB = dbB.open("foo", {conflicts: true});

          // make sure the same rev is in each db
          T(docA._rev === docB._rev);

          // make sure the conflicts are the same in each db
          T(docA._conflicts[0] === docB._conflicts[0]);

          // delete a conflict.
          dbA.deleteDoc({_id:"foo", _rev:docA._conflicts[0]});
        };

        this.afterBA2 = function(dbA, dbB) {
          // open documents and include the conflict meta data
          var docA = dbA.open("foo", {conflicts: true});
          var docB = dbB.open("foo", {conflicts: true});

          // We should have no conflicts this time
          T(docA._conflicts === undefined)
          T(docB._conflicts === undefined);
        };
      }
    };

    var test;
    for(test in repTests) {
      if(repTests[test].init) {
        repTests[test].init(dbA, dbB);
      }
    }

    var result = CouchDB.replicate(A, B);

    var seqA = result.source_last_seq;
    T(0 == result.history[0].start_last_seq);
    T(result.history[1] === undefined)

    for(test in repTests) {
      if(repTests[test].afterAB1) repTests[test].afterAB1(dbA, dbB);
    }

    result = CouchDB.replicate(B, A);

    var seqB = result.source_last_seq;
    T(0 == result.history[0].start_last_seq);
    T(result.history[1] === undefined)

    for(test in repTests) {
      if(repTests[test].afterBA1) repTests[test].afterBA1(dbA, dbB);
    }

    var result2 = CouchDB.replicate(A, B);

    // each successful replication produces a new session id
    T(result2.session_id != result.session_id);

    T(seqA < result2.source_last_seq);
    T(seqA == result2.history[0].start_last_seq);
    T(result2.history[1].end_last_seq == seqA)

    seqA = result2.source_last_seq;

    for(test in repTests) {
      if(repTests[test].afterAB2) repTests[test].afterAB2(dbA, dbB);
    }

    result = CouchDB.replicate(B, A)

    T(seqB < result.source_last_seq);
    T(seqB == result.history[0].start_last_seq);
    T(result.history[1].end_last_seq == seqB)

    seqB = result.source_last_seq;

    for(test in repTests) {
      if(repTests[test].afterBA2) repTests[test].afterBA2(dbA, dbB);
    }

    // do an replication where nothing has changed
    result2 = CouchDB.replicate(B, A);
    T(result2.no_changes == true);
    T(result2.session_id == result.session_id);
  }
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  addNewReview: false,
  actions: {
    reviewFormShow() {
      this.set('addNewReview', true);
    },
    saveReview() {
      var params = {
        profile: this.get('profile'),
        author: this.get('author'),
        content: this.get('content'),
        rating: this.get('rating'),
        answer: this.get('answer'),
        image: this.get('image'),
        message: this.get('message')
      };
      this.set('addNewReview', false);
      this.sendAction('saveReview', params);
    }
  }
});
<commit_msg>commenting on new-review.js<commit_after>import Ember from 'ember';

//exporting behavior of adding new reviews and saving them
export default Ember.Component.extend({
  addNewReview: false,
  actions: {
    reviewFormShow() {
      this.set('addNewReview', true);
    },
    saveReview() {
      var params = {
        profile: this.get('profile'),
        author: this.get('author'),
        content: this.get('content'),
        rating: this.get('rating'),
        answer: this.get('answer'),
        image: this.get('image'),
        message: this.get('message')
      };
      this.set('addNewReview', false);
      this.sendAction('saveReview', params);
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

/* Services */

angular.module('glark.services', [])
    .factory('ace', function () {
        return ace.edit('editor');
    })

    .factory('EditSession', function () {
        return ace.require("ace/edit_session").EditSession;
    })

    .factory('editor', function (EditSession, ace) {
        ace.setTheme("ace/theme/twilight");

        return {
            focus: function () {
                setTimeout(function () {
                    ace.focus();
                }, 0);
            },

            setSession: function (session) {
                session.setFoldStyle('markbegin');

                ace.setSession(session);
                ace.setReadOnly(false);
            },

            clearSession: function () {
                ace.setSession(new EditSession(''));
                ace.setReadOnly(true);
            },

            goToLine: function (lineNumber) {
                ace.gotoLine(lineNumber);
            },

            find: function (value) {
                return ace.find(value);
            },

            findNext: function () {
                return ace.findNext();
            },

            findPrevious: function () {
                return ace.findPrevious();
            }
        };
    })

    .factory('File', function (EditSession) {
        var readAndSetFileContent = function (file, fileEntry) {
            var reader = new FileReader();
            reader.onload = function (event) {
                file.session.setValue(event.target.result, -1);
            };
            reader.readAsText(fileEntry);
        };

        return function (fileEntry) {
            this.fileEntry = fileEntry;
            this.name = fileEntry.name;
            this.session = new EditSession('');

            // TODO: Should be changed.
            this.session.setMode("ace/mode/javascript");

            readAndSetFileContent(this, fileEntry);
        };
    })

    .factory('workspace', function ($rootScope) {
        return {
            files: [],
            activeFile: null,

            addFile: function (file) {
                this.files.push(file);
            },

            getFileCount: function () {
                return this.files.length;
            },

            setActiveFile: function (file) {
                this.activeFile = file;
            },

            getActiveFile: function () {
                return this.activeFile;
            }
        };
    });
<commit_msg>Create filesystem services.<commit_after>'use strict';

/* Services */

angular.module('glark.services', [])
    .factory('ace', function () {
        return ace.edit('editor');
    })

    .factory('EditSession', function () {
        return ace.require("ace/edit_session").EditSession;
    })

    .factory('editor', function (EditSession, ace) {
        ace.setTheme("ace/theme/twilight");

        return {
            focus: function () {
                setTimeout(function () {
                    ace.focus();
                }, 0);
            },

            setSession: function (session) {
                session.setFoldStyle('markbegin');

                ace.setSession(session);
                ace.setReadOnly(false);
            },

            clearSession: function () {
                ace.setSession(new EditSession(''));
                ace.setReadOnly(true);
            },

            goToLine: function (lineNumber) {
                ace.gotoLine(lineNumber);
            },

            find: function (value) {
                return ace.find(value);
            },

            findNext: function () {
                return ace.findNext();
            },

            findPrevious: function () {
                return ace.findPrevious();
            }
        };
    })

    .factory('filesystem', function ($q, $rootScope) {
        return {
            getFileContent: function (fileEntry) {
                var defered = $q.defer();
                var reader = new FileReader();
                reader.onload = function (event) {
                    defered.resolve(event.target.result);
                    $rootScope.$digest();
                };
                reader.readAsText(fileEntry);
                return defered.promise;
            }
        };
    })

    .factory('File', function (filesystem, EditSession) {

        return function (fileEntry) {
            var file = this;

            file.fileEntry = fileEntry;
            file.name = fileEntry.name;
            file.session = new EditSession('');

            // TODO: Should be changed.
            file.session.setMode("ace/mode/javascript");

            var promise = filesystem.getFileContent(fileEntry);
            promise.then(function (content) {
                file.session.setValue(content, -1);
            });
        };
    })

    .factory('workspace', function ($rootScope) {
        return {
            files: [],
            activeFile: null,

            addFile: function (file) {
                this.files.push(file);
            },

            getFileCount: function () {
                return this.files.length;
            },

            setActiveFile: function (file) {
                this.activeFile = file;
            },

            getActiveFile: function () {
                return this.activeFile;
            }
        };
    });
<|endoftext|>


<commit_before>/*
 *
 * Home
 *
 */

import React from 'react';
import Helmet from 'react-helmet';
import Button from 'react-bootstrap/lib/Button';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Menu from 'material-ui/svg-icons/navigation/Menu';
import {Link} from 'react-router';

export default class Home extends React.PureComponent {
  render() {
    const bannerStyle={
      display:"flex",
      width:"100%",
      height:"300px",
      marginTop:"70px",
      background:"url(http://www.adirectory.us/pix/tax-preparation-400.jpg)",
      backgroundSize:"cover",

    }
    const logoStyle={
      width:"350px",
      height:"100px",
      marginTop:"20px",
      background:"url(http://easiertaxes.com/wp-content/uploads/2013/07/taxslayer-logo-large.png)",
      backgroundSize:"cover",

    }
    const linkStyle={
      textDecoration:"0",
      display:"flex",
      flexDirection:"column",
      padding:"15px",
      alignSelf:"center",
      color:"#000000"

    }

    const navBar={
      display:"flex",
      flexDirection:"row",
      width:"100%",
      justifyContent:"space-between",
      position:"fixed",
      top:"0",
      background:"white"
    }
    const boxTwo={
      display:"flex"

    }
    const boxThree={
      display:"flex"

    }
    const boxFour={
      display:"flex"

    }
    const imgContainer={
      display:"flex",
      flexDirection:"column",
      border:"1px #ccc solid",
      padding:"10px"

    }

    const heading={
      display:"flex",
      width:"100px",
      height:"100px",
      backgound:"ffffff"

    }
    const boxSix={
      display:"flex"

    }
    const boxSeven={
      display:"flex"

    }
    const boxEight={
      display:"flex"

    }
    const parStyle={
      display:"flex",
      width:"100px",
      height:"100px"

    }
    const boxNine={
      display:"flex",
      width:"100px",
      height:"100px"

    }
    const boxTen={
      display:"flex"

    }

    return (

        <Helmet title="Home" meta={[ { name: 'description', content: 'Description of Home' }]}/>

              <Link to="/" style={linkStyle}>Products</Link>
              <Link to="/" style={linkStyle}>Refund Calculator</Link>
              <Link to="/" style={linkStyle}>About</Link>
              <Link to="/" style={linkStyle}>Support</Link>
              <Menu/>

          <banner style={bannerStyle}>

          </banner>

Basic

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Classic

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Professional

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

    );
  }
}
<commit_msg>commit3<commit_after>/*
 *
 * Home
 *
 */

import React from 'react';
import Helmet from 'react-helmet';
import Button from 'react-bootstrap/lib/Button';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Menu from 'material-ui/svg-icons/navigation/Menu';
import {Link} from 'react-router';

export default class Home extends React.PureComponent {
  render() {
    const bannerStyle={
      display:"flex",
      width:"100%",
      height:"300px",
      marginTop:"70px",
      background:"url(http://www.adirectory.us/pix/tax-preparation-400.jpg)",
      backgroundSize:"cover",

    }
    const logoStyle={
      width:"350px",
      height:"100px",
      marginTop:"20px",
      background:"url(http://easiertaxes.com/wp-content/uploads/2013/07/taxslayer-logo-large.png)",
      backgroundSize:"cover",

    }
    const linkStyle={
      textDecoration:"0",
      display:"flex",
      flexDirection:"column",
      padding:"15px",
      alignSelf:"center",
      color:"#000000"

    }

    const navBar={
      display:"flex",
      flexDirection:"row",
      width:"100%",
      justifyContent:"space-between",
      position:"fixed",
      top:"0",
      background:"white"
    }
    const boxTwo={
      display:"flex"

    }
    const boxThree={
      display:"flex"

    }
    const boxFour={
      display:"flex"

    }
    const boxOne={
      display:"flex",
      flexDirection:"column",
      width:"300px",
      height:"300px",
      background:"#000000",
      marginTop:"50px"
    }
    const mainStyle={
    display:"flex",
    flexDirection:"row",
    justifyContent:"space-around"
    }

    const heading={
      display:"flex",
      fontSize:"15px",
      justifyContent:"center",
      color:"#ffffff",
      fontFamily:"Roboto, sans serif",
      padding:"10px",
      marginTop:"20px"
    }
    const container2={
      display:"flex",
      fontSize:"10px",
      justifyContent:"center",
      color:"#ffffff",
      fontFamily:"Roboto, sans serif",

    }
    const boxSix={
      display:"flex",
      flexDirection:"column",
      width:"300px",
      height:"300px",
      background:"#000000",
      marginTop:"50px"

    }
    const boxSeven={
      display:"flex",
      flexDirection:"column",
      width:"300px",
      height:"300px",
      background:"#000000",
      marginTop:"50px"

    }
    const boxEight={
      display:"flex"

    }
    const parStyle={
      display:"flex",

    }
    const parStyle1={
      display:"flex",
      fontSize:"15px",
      justifyContent:"center",
      color:"#ffffff",
      fontFamily:"Roboto, sans serif",
      padding:"10px",
      marginTop:"20px"

    }
    const boxNine={
      display:"flex",
      width:"100px",
      height:"100px"

    }
    const boxTen={
      display:"flex"

    }
    const footerStyle={
      width:"100%",
      height:"50px",
      background:"#000000",
      bottom:"auto"

    }

    return (

        <Helmet title="Home" meta={[ { name: 'description', content: 'Description of Home' }]}/>

              <Link to="/" style={linkStyle}>Products</Link>
              <Link to="/" style={linkStyle}>Refund Calculator</Link>
              <Link to="/" style={linkStyle}>About</Link>
              <Link to="/" style={linkStyle}>Support</Link>
              <Menu/>

          <banner style={bannerStyle}>

          </banner>

PREMIUM

LIVE CHAT SUPPORT

CLASSIC

ALL MAJOR FORMS

PROFESSIONAL

BEST FOR SELF EMPLOYED

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var d3 = require('d3');
var queries = require('../../helpers/queries');
var utils = require('../../helpers/utils');

exports.getData = {
	plugins: {
        'crumb': {
            skip: true
        }
    },
    handler: function(request, reply) {

        var sequelize = request.server.plugins.sequelize.db.sequelize;

        var userId = request.auth.credentials.id;

        var queryString = queries.cards(userId);

        // API CODE
		sequelize.query(queryString, {
		        type: sequelize.QueryTypes.SELECT
		    }).then(function(rows) {

	            var overviewResponse = utils.flatten(rows[0]);

	            var cardsResponse = utils.flatten(rows[1]);

	            var blockResponse = utils.flatten(rows[2]);

	            var panchayatResponse = utils.flatten(rows[3]);

	            var notificationsResponse = utils.flatten(rows[4]);

	            // Parse the overview response
	           	var current_total = overviewResponse[0].current_total;
	            var delayed_total = overviewResponse[0].delayed_total;
	            var days_to_payment = overviewResponse[0].time_to_payment;
	            var total_transactions = overviewResponse[0].total_transactions;
	            console.log(days_to_payment)
	            // Nest the cards response and include the overview stats
	            var cards = d3.nest()
	                .key(function(d) {
	                    return d.staff_id;
	                })
	                .rollup(function(v) {
	                    return {
	                        'name': v[0].name,
	                        'designation': v[0].task_assign,
	                        'mobile':v[0].mobile_no,
	                        'block_name':v[0].block_name,
		        			'current_total':v[0].current_total,
		        			'delayed_total':v[0].delayed_total,
	                        'delayed_musters': v.filter(function(d) { return d.type==='delayed_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date,
	                                	'days_pending':d.days_pending
	                            	}
	                            ];
	                        }),
	                       	'current_musters': v.filter(function(d) { return d.type==='current_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date
	                            	}
	                            ];
	                        })
	                    };
	                })
	                .entries(cardsResponse)
	                .map(function(d) {
	                    return d.values;
	                });

	            // Nest the block response
	            var blockPerformance = d3.nest()
	                .key(function(d) {
	                    return d.block_code;
	                })
	                .rollup(function(v) {
	                    return {
	                        'block_code': v[0].block_code,
	                        'block_name': v[0].block_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(blockResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

	            // Nest the panchayat response
	            var panchayatPerformance = d3.nest()
	                .key(function(d) {
	                    return d.panchayat_code;
	                })
	                .rollup(function(v) {
	                    return {
	                    	'block_code': v[0].block_code,
	                        'panchayat_code': v[0].panchayat_code,
	                        'panchayat_name': v[0].panchayat_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(panchayatResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

            	var headers = ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'];

	            var data = {
		        	'overview': {
		        		'current_total':current_total,
		        		'delayed_total':delayed_total,
		        		'days_to_payment':days_to_payment,
		        		'total_transactions':total_transactions,
		        		'cards_total': cards.length
		        	},
		        	'cards': cards,
		        	'block_performance': blockPerformance,
		        	'panchayat_performance': panchayatPerformance,
		        	'notifications': notificationsResponse,
		        	'config': {
		        		'headers': headers,
		        		labels: [
		        			'Date',
		        		    'Muster roll closure to muster roll entry',
		        		    'Muster roll entry to wage list generation',
		        		    'Wage list generation to wage list signing',
		        		    'Wage list signing to FTO generation',
		        		    'FTO generation to first signature',
		        		    'First signature to second signature',
		        		    'Second signature to processed by bank',
		        		    'Total Transactions'
		        		],
		        	}
		        };

	            reply(data);
		    });
    }
};
<commit_msg>Adding staff_id to cards API<commit_after>'use strict';

var d3 = require('d3');
var queries = require('../../helpers/queries');
var utils = require('../../helpers/utils');

exports.getData = {
	plugins: {
        'crumb': {
            skip: true
        }
    },
    handler: function(request, reply) {

        var sequelize = request.server.plugins.sequelize.db.sequelize;

        var userId = request.auth.credentials.id;

        var queryString = queries.cards(userId);

        // API CODE
		sequelize.query(queryString, {
		        type: sequelize.QueryTypes.SELECT
		    }).then(function(rows) {

	            var overviewResponse = utils.flatten(rows[0]);

	            var cardsResponse = utils.flatten(rows[1]);

	            var blockResponse = utils.flatten(rows[2]);

	            var panchayatResponse = utils.flatten(rows[3]);

	            var notificationsResponse = utils.flatten(rows[4]);

	            // Parse the overview response
	           	var current_total = overviewResponse[0].current_total;
	            var delayed_total = overviewResponse[0].delayed_total;
	            var days_to_payment = overviewResponse[0].time_to_payment;
	            var total_transactions = overviewResponse[0].total_transactions;
	            console.log(days_to_payment)
	            // Nest the cards response and include the overview stats
	            var cards = d3.nest()
	                .key(function(d) {
	                    return d.staff_id;
	                })
	                .rollup(function(v) {
	                    return {
	                        'name': v[0].name,
	                        'staff_id': v[0].staff_id,
	                        'designation': v[0].task_assign,
	                        'mobile':v[0].mobile_no,
	                        'block_name':v[0].block_name,
		        			'current_total':v[0].current_total,
		        			'delayed_total':v[0].delayed_total,
	                        'delayed_musters': v.filter(function(d) { return d.type==='delayed_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date,
	                                	'days_pending':d.days_pending
	                            	}
	                            ];
	                        }),
	                       	'current_musters': v.filter(function(d) { return d.type==='current_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date
	                            	}
	                            ];
	                        })
	                    };
	                })
	                .entries(cardsResponse)
	                .map(function(d) {
	                    return d.values;
	                });

	            // Nest the block response
	            var blockPerformance = d3.nest()
	                .key(function(d) {
	                    return d.block_code;
	                })
	                .rollup(function(v) {
	                    return {
	                        'block_code': v[0].block_code,
	                        'block_name': v[0].block_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(blockResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

	            // Nest the panchayat response
	            var panchayatPerformance = d3.nest()
	                .key(function(d) {
	                    return d.panchayat_code;
	                })
	                .rollup(function(v) {
	                    return {
	                    	'block_code': v[0].block_code,
	                        'panchayat_code': v[0].panchayat_code,
	                        'panchayat_name': v[0].panchayat_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(panchayatResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

            	var headers = ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'];

	            var data = {
		        	'overview': {
		        		'current_total':current_total,
		        		'delayed_total':delayed_total,
		        		'days_to_payment':days_to_payment,
		        		'total_transactions':total_transactions,
		        		'cards_total': cards.length
		        	},
		        	'cards': cards,
		        	'block_performance': blockPerformance,
		        	'panchayat_performance': panchayatPerformance,
		        	'notifications': notificationsResponse,
		        	'config': {
		        		'headers': headers,
		        		labels: [
		        			'Date',
		        		    'Muster roll closure to muster roll entry',
		        		    'Muster roll entry to wage list generation',
		        		    'Wage list generation to wage list signing',
		        		    'Wage list signing to FTO generation',
		        		    'FTO generation to first signature',
		        		    'First signature to second signature',
		        		    'Second signature to processed by bank',
		        		    'Total Transactions'
		        		],
		        	}
		        };
		        console.log(cards)
	            reply(data);
		    });
    }
};
<|endoftext|>


<commit_before>var args = arguments[0] || {};

var data = new Date();
var anno = data.getFullYear();

var utenti = Alloy.Collections.instance("utente");
utenti.fetch({query: 'select * from utente where anno = '+anno });

if(utenti.length>0){
	var buttons = new Array();
	for (var i = 0; i < utenti.length; i++) {
		var relatore = utenti.at(i).get("relatore");
		relatore = relatore.replace("|", "\n");
		relatore = relatore.replace("&", " ");
		relatore = relatore.replace("_", " ");
		buttons[i] = Titanium.UI.createButton({title: relatore});
		buttons[i].addEventListener('click', function(e) {
	       alert(e.source.title);
	    });
	    this.addClass(buttons[i],"button");

		$.programmaContent.add(buttons[i]);
	}
}
else{
	$.textLabel.text="Nessun evento disponibile!";
}

<commit_msg>creata funzione replace<commit_after>var args = arguments[0] || {};

function replace(str){
	str = str.replace(/\|/g, "\n");
	str = str.replace(/&/g, " ");
	str = str.replace(/_/g, " ");
	str = str.replace(/<br>/g, "\n");
	str = str.replace(/<p>/g, "");
	str = str.replace(/<\/p>/g, "");
	return str;
}

var data = new Date();
var anno = data.getFullYear();

var utenti = Alloy.Collections.instance("utente");
utenti.fetch({query: 'select * from utente where anno = '+anno });

if(utenti.length>0){
	var buttons = new Array();
	for (var i = 0; i < utenti.length; i++) {
		var relatore = utenti.at(i).get("relatore");
		var id = utenti.at(i).get("id");
		relatore = replace(relatore);
		buttons[i] = Titanium.UI.createButton({title: relatore, titleid:id});
		buttons[i].addEventListener('click', function(e) {
			Ti.App.fireEvent("changeView", {
				row : {
					customView: "",
					className: "evento",
					idRelatore: e.source.titleid
				}
			});
	    });
	    this.addClass(buttons[i],"button");

		$.programmaContent.add(buttons[i]);
	}
}
else{
	$.textLabel.text="Nessun evento disponibile!";
}

<|endoftext|>


<commit_before>import { loop, isLoop, getEffect, getModel } from './loop';
import { batch, none } from './effects';

function optimizeBatch(effects) {
  switch(effects.length) {
    case 0:
      return none();
    case 1:
      return effects[0];
    default:
      return batch(effects);
  }
}

export function combineReducers(reducerMap) {
  return function finalReducer(state = {}, action) {
    let hasChanged = false;
    let effects = [];
    let model = {};

    const reducerMapKeys = Object.keys(reducerMap);
    for (let i = 0; i < reducerMapKeys.length; i++) {
      const key = reducerMapKeys[i];
      const reducer = reducerMap[key];

      const previousStateForKey = state[key];
      let nextStateForKey = reducer(previousStateForKey, action);

      if (isLoop(nextStateForKey)) {
        effects.push(getEffect(nextStateForKey));
        nextStateForKey = getModel(nextStateForKey);
      }

      model[key] = nextStateForKey;
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
    });

    return loop(
      hasChanged ? model : state,
      optimizeBatch(effects)
    );
  };
}
<commit_msg>Fix syntax error<commit_after>import { loop, isLoop, getEffect, getModel } from './loop';
import { batch, none } from './effects';

function optimizeBatch(effects) {
  switch(effects.length) {
    case 0:
      return none();
    case 1:
      return effects[0];
    default:
      return batch(effects);
  }
}

export function combineReducers(reducerMap) {
  return function finalReducer(state = {}, action) {
    let hasChanged = false;
    let effects = [];
    let model = {};

    const reducerMapKeys = Object.keys(reducerMap);
    for (let i = 0; i < reducerMapKeys.length; i++) {
      const key = reducerMapKeys[i];
      const reducer = reducerMap[key];

      const previousStateForKey = state[key];
      let nextStateForKey = reducer(previousStateForKey, action);

      if (isLoop(nextStateForKey)) {
        effects.push(getEffect(nextStateForKey));
        nextStateForKey = getModel(nextStateForKey);
      }

      model[key] = nextStateForKey;
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
    }

    return loop(
      hasChanged ? model : state,
      optimizeBatch(effects)
    );
  };
}
<|endoftext|>


<commit_before>/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

import {
  GraphQLInputObjectType,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLString
} from 'graphql';

import type {
  GraphQLFieldConfig,
  InputObjectFieldConfigMap,
  GraphQLFieldConfigMap,
  GraphQLResolveInfo
} from 'graphql';

type mutationFn = (object: Object, info: GraphQLResolveInfo) => Object |
                  (object: Object, info: GraphQLResolveInfo) => Promise<Object>;

/**
 * A description of a mutation consumable by mutationWithClientMutationId
 * to create a GraphQLFieldConfig for that mutation.
 *
 * The inputFields and outputFields should not include `clientMutationId`,
 * as this will be provided automatically.
 *
 * An input object will be created containing the input fields, and an
 * object will be created containing the output fields.
 *
 * mutateAndGetPayload will receieve an Object with a key for each
 * input field, and it should return an Object with a key for each
 * output field. It may return synchronously, or return a Promise.
 */
type MutationConfig = {
  name: string,
  inputFields: InputObjectFieldConfigMap,
  outputFields: GraphQLFieldConfigMap,
  mutateAndGetPayload: mutationFn,
}

/**
 * Returns a GraphQLFieldConfig for the mutation described by the
 * provided MutationConfig.
 */
export function mutationWithClientMutationId(
  config: MutationConfig
): GraphQLFieldConfig {
  var {name, inputFields, outputFields, mutateAndGetPayload} = config;
  var augmentedInputFields = {
    ...inputFields,
    clientMutationId: {
      type: new GraphQLNonNull(GraphQLString)
    }
  };
  var augmentedOutputFields = {
    ...outputFields,
    clientMutationId: {
      type: new GraphQLNonNull(GraphQLString)
    }
  };

  var outputType = new GraphQLObjectType({
    name: name + 'Payload',
    fields: augmentedOutputFields
  });

  var inputType = new GraphQLInputObjectType({
    name: name + 'Input',
    fields: augmentedInputFields
  });

  return {
    type: outputType,
    args: {
      input: {type: new GraphQLNonNull(inputType)}
    },
    resolve: (_, {input}, info) => {
      return Promise.resolve(mutateAndGetPayload(input, info)).then(payload => {
        payload.clientMutationId = input.clientMutationId;
        return payload;
      });
    }
  };
}
<commit_msg>Use renamed type<commit_after>/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

import {
  GraphQLInputObjectType,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLString
} from 'graphql';

import type {
  GraphQLFieldConfig,
  InputObjectConfigFieldMap,
  GraphQLFieldConfigMap,
  GraphQLResolveInfo
} from 'graphql';

type mutationFn = (object: Object, info: GraphQLResolveInfo) => Object |
                  (object: Object, info: GraphQLResolveInfo) => Promise<Object>;

/**
 * A description of a mutation consumable by mutationWithClientMutationId
 * to create a GraphQLFieldConfig for that mutation.
 *
 * The inputFields and outputFields should not include `clientMutationId`,
 * as this will be provided automatically.
 *
 * An input object will be created containing the input fields, and an
 * object will be created containing the output fields.
 *
 * mutateAndGetPayload will receieve an Object with a key for each
 * input field, and it should return an Object with a key for each
 * output field. It may return synchronously, or return a Promise.
 */
type MutationConfig = {
  name: string,
  inputFields: InputObjectConfigFieldMap,
  outputFields: GraphQLFieldConfigMap,
  mutateAndGetPayload: mutationFn,
}

/**
 * Returns a GraphQLFieldConfig for the mutation described by the
 * provided MutationConfig.
 */
export function mutationWithClientMutationId(
  config: MutationConfig
): GraphQLFieldConfig {
  var {name, inputFields, outputFields, mutateAndGetPayload} = config;
  var augmentedInputFields = {
    ...inputFields,
    clientMutationId: {
      type: new GraphQLNonNull(GraphQLString)
    }
  };
  var augmentedOutputFields = {
    ...outputFields,
    clientMutationId: {
      type: new GraphQLNonNull(GraphQLString)
    }
  };

  var outputType = new GraphQLObjectType({
    name: name + 'Payload',
    fields: augmentedOutputFields
  });

  var inputType = new GraphQLInputObjectType({
    name: name + 'Input',
    fields: augmentedInputFields
  });

  return {
    type: outputType,
    args: {
      input: {type: new GraphQLNonNull(inputType)}
    },
    resolve: (_, {input}, info) => {
      return Promise.resolve(mutateAndGetPayload(input, info)).then(payload => {
        payload.clientMutationId = input.clientMutationId;
        return payload;
      });
    }
  };
}
<|endoftext|>


<commit_before>var utility = require('./utility');
var async = require('async');
var db = require('./db');
var logger = utility.logger;
var fs = require('fs');
var moment = require('moment');
var getData = utility.getData;
var request = require('request');
var operations = require('./operations');
var insertPlayer = operations.insertPlayer;
var insertMatch = operations.insertMatch;
var spawn = require('child_process').spawn;
var replay_dir = process.env.REPLAY_DIR || "./replays/";
var domain = require('domain');
var queueReq = operations.queueReq;
var JSONStream = require('JSONStream');
var constants = require('./constants.json');
var mode = utility.mode;

function processParse(job, cb) {
    var t1 = new Date();
    var attempts = job.toJSON().attempts.remaining;
    var noRetry = attempts <= 1;
    async.waterfall([
        async.apply(checkLocal, job),
        getReplayUrl,
        streamReplay,
    ], function(err) {
        var match_id = job.data.payload.match_id;
        logger.info("[PARSER] match_id %s, parse time: %s, error: %s", match_id, (new Date() - t1) / 1000, err);
        if (err === "replay expired" || (err && noRetry)) {
            logger.info("match_id %s, error %s, not retrying", match_id, err);
            return db.matches.update({
                match_id: match_id,
                parse_status: 0
            }, {
                $set: {
                    parse_status: 1
                }
            }, function(err2) {
                //nullify error if replay expired
                err = err === "replay expired" ? null : err;
                cb(err || err2);
            });
        }
        else if (err) {
            logger.info("match_id %s, error %s, attempts %s", match_id, err, attempts);
            return cb(err);
        }
        else {
            return cb(err, job.data.payload);
        }
    });
}

function checkLocal(job, cb) {
    var match_id = job.data.payload.match_id;
    var fileName = job.data.fileName || replay_dir + match_id + ".dem";
    if (fs.existsSync(fileName)) {
        logger.info("[PARSER] %s, found local replay", match_id);
        job.data.fileName = fileName;
        job.update();
    }
    cb(null, job);
}

function getReplayUrl(job, cb) {
    if (job.data.url || job.data.fileName) {
        logger.info("has url or fileName");
        return cb(null, job);
    }
    var match = job.data.payload;
    if (match.start_time > moment().subtract(7, 'days').format('X')) {
        getData("http://retriever?match_id=" + job.data.payload.match_id, function(err, body) {
            if (err || !body || !body.match) {
                return cb("invalid body or error");
            }
            var url = "http://replay" + body.match.cluster + ".valve.net/570/" + match.match_id + "_" + body.match.replaySalt + ".dem.bz2";
            job.data.url = url;
            job.data.payload.url = url;
            job.update();
            return cb(null, job);
        });
    }
    /*
    else if (process.env.AWS_S3_BUCKET) {
        getS3Url(match.match_id, function(err, url) {
            if (!url) {
                return cb("replay expired");
            }
            job.data.url = url;
            job.update();
            return cb(err, job);
        });
    }
    */
    else {
        cb("replay expired");
    }
}

function streamReplay(job, cb) {
    //var fileName = replay_dir + match_id + ".dem";
    //var archiveName = fileName + ".bz2";
    var match_id = job.data.payload.match_id;
    logger.info("[PARSER] streaming from %s", job.data.url || job.data.fileName);
    var d = domain.create();
    var bz;
    var parser;
    var error;
    var inStream;
    var exited;

    function exit(err) {
        if (!exited) {
            exited = true;
            cb(error || err.message || err);
        }
    }
    d.on('error', exit);
    d.run(function() {
        parser = runParser(function(err, output) {
            if (err) {
                return exit(err);
            }
            match_id = match_id || output.match_id;
            job.data.payload.match_id = match_id;
            job.data.payload.parsed_data = output;
            job.data.payload.parse_status = 2;
            job.update();
            db.matches.find({
                match_id: match_id
            }, function(err, docs) {
                if (err) {
                    return cb(err);
                }
                else if (docs.length) {
                    db.matches.update({
                        match_id: match_id
                    }, {
                        $set: job.data.payload,
                    }, function(err) {
                        return cb(err);
                    });
                }
                else {
                    console.log("parsed match not in db");
                    queueReq("api_details", job.data.payload, function(err, apijob) {
                        if (err) {
                            return cb(err);
                        }
                        apijob.on('complete', function() {
                            return cb();
                        });
                    });
                }
            });
        });
        if (job.data.fileName) {
            inStream = fs.createReadStream(job.data.fileName);
            inStream.pipe(parser.stdin);
        }
        else {
            bz = spawn("bunzip2");
            bz.stdout.pipe(parser.stdin);
            inStream = request.get({
                url: job.data.url,
                encoding: null,
                timeout: 30000
            });
            inStream.on('response', function(response) {
                if (response.statusCode !== 200) {
                    error = "download error";
                }
            }).pipe(bz.stdin);
        }
    });
}

function runParser(cb) {
    //todo choose a parser to stream from
    //todo set version based on parser?
    //todo handle parser errors
    var parser_file = "parser/target/stats-0.1.0.jar";
    var entries = [];
    var parsed_data = {
        "version": constants.parser_version,
        "game_zero": 0,
        "game_end": 0,
        "match_id": 0,
        "players": Array.apply(null, new Array(10)).map(function() {
            return {
                "stuns": -1,
                "lane": -1,
                "pos": [],
                "obs": [],
                "sen": [],
                "gold": [],
                "lh": [],
                "xp": [],
                "hero_log": [],
                "item_log": [],
                "kill_log": [],
                "buyback_log": [],
                "gold_reasons": {},
                "xp_reasons": {},
                "kills": {},
                "item_uses": {},
                "ability_uses": {},
                "hero_hits": {},
                "damage": {},
                "damage_taken": {},
                "runes": {},
                "runes_bottled": {},
                "killed_by": {}
            };
        }),
        "times": []
    };
    var name_to_slot = {};
    var hero_to_slot = {};
    var types = {
        "times": setData,
        "match_id": setData,
        "game_zero": setData,
        "game_end": setData,
        "hero_log": function(e) {
            //get hero by id
            var h = constants.heroes[e.key];
            hero_to_slot[h ? h.name : e.key] = e.slot;
            //add to player's hero list
            getSlot(e);
        },
        "name": function(e) {
            name_to_slot[e.key] = e.slot;
        },
        "gold_reasons": getSlot,
        "xp_reasons": getSlot,
        "item_log": getSlot,
        "item_uses": getSlot,
        "ability_uses": getSlot,
        "kills": getSlot,
        "damage": getSlot,
        "runes": getSlot,
        "runes_bottled": getSlot,
        "stuns": getSlot,
        "buyback_log": getSlot,
        "chat": getChatSlot,
        "lh": interval,
        "gold": interval,
        "xp": interval,
        "pos": translate,
        "obs": translate,
        "sen": translate,
        "hero_hits": getSlot,
        "kill_log": getSlot,
        "damage_taken": getSlotReverse,
        "killed_by": getSlotReverse
    };

    function preprocess(e) {
        (types[e.type]) ? types[e.type](e): console.log(e);
    }

    function setData(e) {
        var t = parsed_data[e.type];
        if (t.constructor === Array) {
            t.push(e.value);
        }
        else {
            parsed_data[e.type] = e.value;
        }
    }

    function translate(e) {
        //transform to 0-127 range from 64-191, y=0 at top left from bottom left
        e.key = JSON.parse(e.key);
        e.key = [e.key[0] - 64, 127 - (e.key[1] - 64)];
        e.position = true;
        entries.push(e);
    }

    function interval(e) {
        e.interval = true;
        entries.push(e);
    }

    function assocName(name) {
        //given a name (npc_dota_visage_familiar...), tries to convert to the associated hero's name
        if (!name) {
            return;
        }
        else if (name in hero_to_slot) {
            return name;
        }
        else if (name.indexOf("illusion_") === 0) {
            var s = name.slice("illusion_".length);
            return s;
        }
        else if (name.indexOf("npc_dota_") === 0) {
            //split by _
            var split = name.split("_");
            //get the third element
            var identifiers = [split[2], split[2] + "_" + split[3]];
            identifiers.forEach(function(id) {
                //append to npc_dota_hero_, see if matches
                var attempt = "npc_dota_hero_" + id;
                if (attempt in hero_to_slot) {
                    return attempt;
                }
            });
        }
    }

    function getSlot(e) {
        //on a reversed field, key should be merged since the unit was damaged/killed by the key or a minion
        //otherwise, unit should be merged since the damage/kill was done by the unit or a minion
        e.reverse ? e.key = assocName(e.key) : e.unit = assocName(e.unit);
        //use slot, then map value (could be undefined)
        e.slot = ("slot" in e) ? e.slot : hero_to_slot[e.unit];
        entries.push(e);
    }

    function getSlotReverse(e) {
        e.reverse = true;
        getSlot(e);
    }

    function getChatSlot(e) {
        e.slot = name_to_slot[e.unit];
        entries.push(e);
    }

    function processEntry(e) {
        e.time -= parsed_data.game_zero;
        if (typeof e.slot === "undefined") {
            //console.log(e);
            return;
        }
        var t = parsed_data.players[e.slot][e.type];
        if (t.constructor === Array) {
            e = (e.interval) ? e.value : {
                time: e.time,
                key: e.key
            };
            t.push(e);
        }
        else if (typeof t === "object") {
            e.value = e.value || 1;
            t[e.key] ? t[e.key] += e.value : t[e.key] = e.value;
        }
        else {
            parsed_data.players[e.slot][e.type] = e.value || Number(e.key);
        }
    }
    var parser = spawn("java", ["-jar",
        parser_file
    ], {
        stdio: ['pipe', 'pipe', 'ignore'], //don't handle stderr
        encoding: 'utf8'
    });
    var stream = JSONStream.parse();
    parser.stdout.pipe(stream);
    stream.on('root', preprocess);
    parser.on('exit', function(code) {
        if (code) {
            return cb(code);
        }
        entries.forEach(processEntry);
        var keys = Object.keys(types).filter(function(k) {
            return types[k] === translate;
        });
        parsed_data.players.forEach(function(p) {
            var lanes = [];
            keys.forEach(function(key) {
                var h = {};
                p[key].forEach(function(e) {
                    var x = e.key[0];
                    var y = e.key[1];
                    if (!h[x]) {
                        h[x] = {};
                    }
                    if (!h[x][y]) {
                        h[x][y] = 0;
                    }
                    h[x][y] += 1;
                    if (e.time <= 600 && key === "pos") {
                        lanes.push(constants.lanes[e.key[1]][e.key[0]]);
                    }
                });
                /*
                for (var x in h) {
                    for (var y in h[x]) {
                        if (h[x][y]) {
                            //points.push({x: x,y: y,value: map[y][x]});
                            //super hacker bit packing!
                            points.push((Number(x) << 24) + (Number(y) << 16) + h[x][y]);
                        }
                    }
                }
                p[key] = points;
                */
                p[key] = h;
            });
            p.lane = mode(lanes);
        });
        fs.writeFile("output2.json", JSON.stringify(parsed_data), function() {});
        cb(code, parsed_data);
    });
    return parser;
}

function processApi(job, cb) {
    //process an api request
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            //encountered non-retryable error, pass back to kue as the result
            //cb with err causes kue to retry
            return cb(null, {
                error: err
            });
        }
        else if (data.response) {
            logger.info("summaries response");
            async.mapSeries(data.response.players, insertPlayer, function(err) {
                cb(err, job.data.payload);
            });
        }
        else if (payload.match_id) {
            logger.info("details response");
            var match = data.result;
            //join payload with match
            for (var prop in payload) {
                match[prop] = (prop in match) ? match[prop] : payload[prop];
            }
            insertMatch(match, function(err) {
                cb(err, job.data.payload);
            });
        }
        else {
            return cb("unknown response");
        }
    });
}

function processMmr(job, cb) {
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            logger.info(err);
            //don't retry processmmr attempts, data will likely be out of date anyway
            return cb(null, err);
        }
        logger.info("mmr response");
        if (data.soloCompetitiveRank || data.competitiveRank) {
            db.ratings.insert({
                match_id: payload.match_id,
                account_id: payload.account_id,
                soloCompetitiveRank: data.soloCompetitiveRank,
                competitiveRank: data.competitiveRank,
                time: new Date()
            }, function(err) {
                cb(err);
            });
        }
        else {
            cb(null);
        }
    });
}
module.exports = {
    processParse: processParse,
    processApi: processApi,
    processMmr: processMmr
};
<commit_msg>moved todos<commit_after>var utility = require('./utility');
var async = require('async');
var db = require('./db');
var logger = utility.logger;
var fs = require('fs');
var moment = require('moment');
var getData = utility.getData;
var request = require('request');
var operations = require('./operations');
var insertPlayer = operations.insertPlayer;
var insertMatch = operations.insertMatch;
var spawn = require('child_process').spawn;
var replay_dir = process.env.REPLAY_DIR || "./replays/";
var domain = require('domain');
var queueReq = operations.queueReq;
var JSONStream = require('JSONStream');
var constants = require('./constants.json');
var mode = utility.mode;

function processParse(job, cb) {
    var t1 = new Date();
    var attempts = job.toJSON().attempts.remaining;
    var noRetry = attempts <= 1;
    async.waterfall([
        async.apply(checkLocal, job),
        getReplayUrl,
        streamReplay,
    ], function(err) {
        var match_id = job.data.payload.match_id;
        logger.info("[PARSER] match_id %s, parse time: %s, error: %s", match_id, (new Date() - t1) / 1000, err);
        if (err === "replay expired" || (err && noRetry)) {
            logger.info("match_id %s, error %s, not retrying", match_id, err);
            return db.matches.update({
                match_id: match_id,
                parse_status: 0
            }, {
                $set: {
                    parse_status: 1
                }
            }, function(err2) {
                //nullify error if replay expired
                err = err === "replay expired" ? null : err;
                cb(err || err2);
            });
        }
        else if (err) {
            logger.info("match_id %s, error %s, attempts %s", match_id, err, attempts);
            return cb(err);
        }
        else {
            return cb(err, job.data.payload);
        }
    });
}

function checkLocal(job, cb) {
    var match_id = job.data.payload.match_id;
    var fileName = job.data.fileName || replay_dir + match_id + ".dem";
    if (fs.existsSync(fileName)) {
        logger.info("[PARSER] %s, found local replay", match_id);
        job.data.fileName = fileName;
        job.update();
    }
    cb(null, job);
}

function getReplayUrl(job, cb) {
    if (job.data.url || job.data.fileName) {
        logger.info("has url or fileName");
        return cb(null, job);
    }
    var match = job.data.payload;
    if (match.start_time > moment().subtract(7, 'days').format('X')) {
        getData("http://retriever?match_id=" + job.data.payload.match_id, function(err, body) {
            if (err || !body || !body.match) {
                return cb("invalid body or error");
            }
            var url = "http://replay" + body.match.cluster + ".valve.net/570/" + match.match_id + "_" + body.match.replaySalt + ".dem.bz2";
            job.data.url = url;
            job.data.payload.url = url;
            job.update();
            return cb(null, job);
        });
    }
    /*
    else if (process.env.AWS_S3_BUCKET) {
        getS3Url(match.match_id, function(err, url) {
            if (!url) {
                return cb("replay expired");
            }
            job.data.url = url;
            job.update();
            return cb(err, job);
        });
    }
    */
    else {
        cb("replay expired");
    }
}

function streamReplay(job, cb) {
    //var fileName = replay_dir + match_id + ".dem";
    //var archiveName = fileName + ".bz2";
    var match_id = job.data.payload.match_id;
    logger.info("[PARSER] streaming from %s", job.data.url || job.data.fileName);
    var d = domain.create();
    var bz;
    var parser;
    var error;
    var inStream;
    var exited;

    function exit(err) {
        if (!exited) {
            exited = true;
            cb(error || err.message || err);
        }
    }
    d.on('error', exit);
    d.run(function() {
        parser = runParser(function(err, output) {
            if (err) {
                return exit(err);
            }
            match_id = match_id || output.match_id;
            job.data.payload.match_id = match_id;
            job.data.payload.parsed_data = output;
            job.data.payload.parse_status = 2;
            job.update();
            db.matches.find({
                match_id: match_id
            }, function(err, docs) {
                if (err) {
                    return cb(err);
                }
                else if (docs.length) {
                    db.matches.update({
                        match_id: match_id
                    }, {
                        $set: job.data.payload,
                    }, function(err) {
                        return cb(err);
                    });
                }
                else {
                    console.log("parsed match not in db");
                    queueReq("api_details", job.data.payload, function(err, apijob) {
                        if (err) {
                            return cb(err);
                        }
                        apijob.on('complete', function() {
                            return cb();
                        });
                    });
                }
            });
        });
        if (job.data.fileName) {
            inStream = fs.createReadStream(job.data.fileName);
            inStream.pipe(parser.stdin);
        }
        else {
            bz = spawn("bunzip2");
            bz.stdout.pipe(parser.stdin);
            inStream = request.get({
                url: job.data.url,
                encoding: null,
                timeout: 30000
            });
            inStream.on('response', function(response) {
                if (response.statusCode !== 200) {
                    error = "download error";
                }
            }).pipe(bz.stdin);
        }
    });
}

function runParser(cb) {
    var entries = [];
    var parsed_data = {
        "version": constants.parser_version,
        "game_zero": 0,
        "game_end": 0,
        "match_id": 0,
        "players": Array.apply(null, new Array(10)).map(function() {
            return {
                "stuns": -1,
                "lane": -1,
                "pos": [],
                "obs": [],
                "sen": [],
                "gold": [],
                "lh": [],
                "xp": [],
                "hero_log": [],
                "item_log": [],
                "kill_log": [],
                "buyback_log": [],
                "gold_reasons": {},
                "xp_reasons": {},
                "kills": {},
                "item_uses": {},
                "ability_uses": {},
                "hero_hits": {},
                "damage": {},
                "damage_taken": {},
                "runes": {},
                "runes_bottled": {},
                "killed_by": {}
            };
        }),
        "times": []
    };
    var name_to_slot = {};
    var hero_to_slot = {};
    var types = {
        "times": setData,
        "match_id": setData,
        "game_zero": setData,
        "game_end": setData,
        "hero_log": function(e) {
            //get hero by id
            var h = constants.heroes[e.key];
            hero_to_slot[h ? h.name : e.key] = e.slot;
            //add to player's hero list
            getSlot(e);
        },
        "name": function(e) {
            name_to_slot[e.key] = e.slot;
        },
        "gold_reasons": getSlot,
        "xp_reasons": getSlot,
        "item_log": getSlot,
        "item_uses": getSlot,
        "ability_uses": getSlot,
        "kills": getSlot,
        "damage": getSlot,
        "runes": getSlot,
        "runes_bottled": getSlot,
        "stuns": getSlot,
        "buyback_log": getSlot,
        "chat": getChatSlot,
        "lh": interval,
        "gold": interval,
        "xp": interval,
        "pos": translate,
        "obs": translate,
        "sen": translate,
        "hero_hits": getSlot,
        "kill_log": getSlot,
        "damage_taken": getSlotReverse,
        "killed_by": getSlotReverse
    };

    function preprocess(e) {
        (types[e.type]) ? types[e.type](e): console.log(e);
    }

    function setData(e) {
        var t = parsed_data[e.type];
        if (t.constructor === Array) {
            t.push(e.value);
        }
        else {
            parsed_data[e.type] = e.value;
        }
    }

    function translate(e) {
        //transform to 0-127 range from 64-191, y=0 at top left from bottom left
        e.key = JSON.parse(e.key);
        e.key = [e.key[0] - 64, 127 - (e.key[1] - 64)];
        e.position = true;
        entries.push(e);
    }

    function interval(e) {
        e.interval = true;
        entries.push(e);
    }

    function assocName(name) {
        //given a name (npc_dota_visage_familiar...), tries to convert to the associated hero's name
        if (!name) {
            return;
        }
        else if (name in hero_to_slot) {
            return name;
        }
        else if (name.indexOf("illusion_") === 0) {
            var s = name.slice("illusion_".length);
            return s;
        }
        else if (name.indexOf("npc_dota_") === 0) {
            //split by _
            var split = name.split("_");
            //get the third element
            var identifiers = [split[2], split[2] + "_" + split[3]];
            identifiers.forEach(function(id) {
                //append to npc_dota_hero_, see if matches
                var attempt = "npc_dota_hero_" + id;
                if (attempt in hero_to_slot) {
                    return attempt;
                }
            });
        }
    }

    function getSlot(e) {
        //on a reversed field, key should be merged since the unit was damaged/killed by the key or a minion
        //otherwise, unit should be merged since the damage/kill was done by the unit or a minion
        e.reverse ? e.key = assocName(e.key) : e.unit = assocName(e.unit);
        //use slot, then map value (could be undefined)
        e.slot = ("slot" in e) ? e.slot : hero_to_slot[e.unit];
        entries.push(e);
    }

    function getSlotReverse(e) {
        e.reverse = true;
        getSlot(e);
    }

    function getChatSlot(e) {
        e.slot = name_to_slot[e.unit];
        entries.push(e);
    }

    function processEntry(e) {
            e.time -= parsed_data.game_zero;
            if (typeof e.slot === "undefined") {
                //console.log(e);
                return;
            }
            var t = parsed_data.players[e.slot][e.type];
            if (t.constructor === Array) {
                e = (e.interval) ? e.value : {
                    time: e.time,
                    key: e.key
                };
                t.push(e);
            }
            else if (typeof t === "object") {
                e.value = e.value || 1;
                t[e.key] ? t[e.key] += e.value : t[e.key] = e.value;
            }
            else {
                parsed_data.players[e.slot][e.type] = e.value || Number(e.key);
            }
        }
        //todo choose a parser to stream from
        //parse locally if upload
    var parser_file = "parser/target/stats-0.1.0.jar";
    var parser = spawn("java", ["-jar",
        parser_file
    ], {
        stdio: ['pipe', 'pipe', 'ignore'], //don't handle stderr
        encoding: 'utf8'
    });
    var stream = JSONStream.parse();
    parser.stdout.pipe(stream);
    stream.on('root', preprocess);
    parser.on('exit', function(code) {
        if (code) {
            return cb(code);
        }
        entries.forEach(processEntry);
        var keys = Object.keys(types).filter(function(k) {
            return types[k] === translate;
        });
        parsed_data.players.forEach(function(p) {
            var lanes = [];
            keys.forEach(function(key) {
                var h = {};
                p[key].forEach(function(e) {
                    var x = e.key[0];
                    var y = e.key[1];
                    if (!h[x]) {
                        h[x] = {};
                    }
                    if (!h[x][y]) {
                        h[x][y] = 0;
                    }
                    h[x][y] += 1;
                    if (e.time <= 600 && key === "pos") {
                        lanes.push(constants.lanes[e.key[1]][e.key[0]]);
                    }
                });
                p[key] = h;
            });
            p.lane = mode(lanes);
        });
        cb(code, parsed_data);
    });
    return parser;
}

function processApi(job, cb) {
    //process an api request
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            //encountered non-retryable error, pass back to kue as the result
            //cb with err causes kue to retry
            return cb(null, {
                error: err
            });
        }
        else if (data.response) {
            logger.info("summaries response");
            async.mapSeries(data.response.players, insertPlayer, function(err) {
                cb(err, job.data.payload);
            });
        }
        else if (payload.match_id) {
            logger.info("details response");
            var match = data.result;
            //join payload with match
            for (var prop in payload) {
                match[prop] = (prop in match) ? match[prop] : payload[prop];
            }
            insertMatch(match, function(err) {
                cb(err, job.data.payload);
            });
        }
        else {
            return cb("unknown response");
        }
    });
}

function processMmr(job, cb) {
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            logger.info(err);
            //don't retry processmmr attempts, data will likely be out of date anyway
            return cb(null, err);
        }
        logger.info("mmr response");
        if (data.soloCompetitiveRank || data.competitiveRank) {
            db.ratings.insert({
                match_id: payload.match_id,
                account_id: payload.account_id,
                soloCompetitiveRank: data.soloCompetitiveRank,
                competitiveRank: data.competitiveRank,
                time: new Date()
            }, function(err) {
                cb(err);
            });
        }
        else {
            cb(null);
        }
    });
}
module.exports = {
    processParse: processParse,
    processApi: processApi,
    processMmr: processMmr
};
<|endoftext|>


<commit_before>//* Parameters *//

//determines how radically wireV glitches
var glitchyness = 60;

//determines how radically glitched the final wireV will be once it stops glitching
var finalGlitchyness = 25;

//determines how often wireV blinks when not glitching (between 0 and 1, the higher, the more likely)
var blinkyness = 0.02;

// ** ///

//references to html elements
var canvas = document.getElementById('userCanvas');
var ctx = canvas.getContext('2d');

//will hold WireV objects
var logo1;
var logo2;
var logo3;

//determines whether or not to render the third WireV
var renderThird = false;

//determines whether or not WireV is glitching
var isGlitching = false;

//animation setup
function setup() {

	//assign WireV objects
	logo1 = new WireV(200, 200, 85, 100, glitchyness, finalGlitchyness);
	logo2 = new WireV(200, 200, 85, 100, glitchyness, finalGlitchyness);
	logo3 = new WireV(200, 200, 85, 100, glitchyness, finalGlitchyness);

	logo1.setWire();
	logo2.setWire();
	logo3.setWire();

	//call draw function to start animation loop
	window.requestAnimationFrame(draw);
}

//animation loop
function draw() {

	//clear canvas for next frame
	ctx.clearRect(0, 0, canvas.width, canvas.height);

	//if glitching, reset shape, glitch it, and draw it
	//rest it once more for a more stable glitching (in case glitching is about to end and we want the final WireV to be a bit more tamed)
	//randomly decide if third WireV will be visible
	if (isGlitching) {
		logo1.setWire();
		logo2.setWire();
		logo3.setWire();

		logo1.glitchWire();
		logo2.glitchWire();
		logo3.glitchWire();

		logo1.drawWire();
		logo2.drawWire();
		logo3.drawWire();

		logo1.setWire();
		logo2.setWire();
		logo3.setWire();

		logo1.stableGlitchWire();
		logo2.stableGlitchWire();
		logo3.stableGlitchWire();

		if (getRandomFloat(0, 1) > 0.5) renderThird = true;
		else renderThird = false;

		//stop glitching after 400 millis
		setTimeout(function() {
			isGlitching = false;
			console.log("STOP");
		}, 400);

		//if not glitching, then render WireVs according to blinkyness
	} else {
		if (getRandomFloat(0, 1) > blinkyness) logo1.drawWire();
		if (getRandomFloat(0, 1) > blinkyness) logo2.drawWire();
		if (renderThird && getRandomFloat(0, 1) > blinkyness) logo3.drawWire();
	}

	//loop animation
	window.requestAnimationFrame(draw);
}

//determines when wireV glitches
setInterval(function() {
	isGlitching = true
	console.log("GLITCH");
}, 7000);

//on page load, call setup to start animation
window.addEventListener("DOMContentLoaded", function () {
	setup();
});<commit_msg>commenting fixes<commit_after>//* Parameters *//

//determines how radically wireV glitches
var glitchyness = 60;

//determines how radically glitched the final wireV will be once it stops glitching
var finalGlitchyness = 25;

//determines how often wireV blinks when not glitching (between 0 and 1, the higher, the more likely)
var blinkyness = 0.02;

// ** ///

//references to html elements
var canvas = document.getElementById('userCanvas');
var ctx = canvas.getContext('2d');

//will hold WireV objects
var logo1;
var logo2;
var logo3;

//determines whether or not to render the third WireV
var renderThird = false;

//determines whether or not WireV is glitching
var isGlitching = false;

//animation setup
function setup() {

	//assign WireV objects
	logo1 = new WireV(200, 200, 85, 100, glitchyness, finalGlitchyness);
	logo2 = new WireV(200, 200, 85, 100, glitchyness, finalGlitchyness);
	logo3 = new WireV(200, 200, 85, 100, glitchyness, finalGlitchyness);

	logo1.setWire();
	logo2.setWire();
	logo3.setWire();

	//call draw function to start animation loop
	window.requestAnimationFrame(draw);
}

//animation loop
function draw() {

	//clear canvas for next frame
	ctx.clearRect(0, 0, canvas.width, canvas.height);

	//if glitching, reset shape, glitch it, and draw it
	//rest it once more for a more stable glitching (in case glitching is about to end and we want the final WireV to be a bit more tamed)
	//randomly decide if third WireV will be visible
	if (isGlitching) {
		logo1.setWire();
		logo2.setWire();
		logo3.setWire();

		logo1.glitchWire();
		logo2.glitchWire();
		logo3.glitchWire();

		logo1.drawWire();
		logo2.drawWire();
		logo3.drawWire();

		logo1.setWire();
		logo2.setWire();
		logo3.setWire();

		logo1.stableGlitchWire();
		logo2.stableGlitchWire();
		logo3.stableGlitchWire();

		if (getRandomFloat(0, 1) > 0.5) renderThird = true;
		else renderThird = false;

		//stop glitching after 400 millis
		setTimeout(function() {
			isGlitching = false;
		}, 400);

		//if not glitching, then render WireVs according to blinkyness
	} else {
		if (getRandomFloat(0, 1) > blinkyness) logo1.drawWire();
		if (getRandomFloat(0, 1) > blinkyness) logo2.drawWire();
		if (renderThird && getRandomFloat(0, 1) > blinkyness) logo3.drawWire();
	}

	//loop animation
	window.requestAnimationFrame(draw);
}

//triggerswireV glitches
setInterval(function() {
	isGlitching = true
}, 7000);

//on page load, call setup to start animation
window.addEventListener("DOMContentLoaded", function () {
	setup();
});
<|endoftext|>


<commit_before>/**
 * @file pirateSpeak command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const dictionary = require('../../data/piratePhrases.json');

exports.run = (Bastion, message, args) => {
  if (args.length < 1) {
    return message.channel.send({
      embed: {
        color: Bastion.colors.yellow,
        title: 'Usage',
        description: `\`${Bastion.config.prefix}${this.help.usage}\``
      }
    }).catch(e => {
      Bastion.log.error(e.stack);
    });
  }

  message.channel.send({
    embed: {
      color: Bastion.colors.blue,
      title: 'Pirate Speak:',
      description: translate(args.join(' '))
    }
  }).catch(e => {
    Bastion.log.error(e.stack);
  });
};

exports.config = {
  aliases: [ 'pirate' ],
  enabled: true
};

exports.help = {
  name: 'piratespeak',
  description: 'Convert\'s the given text to pirate speak.',
  botPermission: '',
  userPermission: '',
  usage: 'pirateSpeak <text>',
  example: [ 'pirateSpeak You can always trust the untrustworthy because you can always trust that they will be untrustworthy. Its the trustworthy you can’t trust.' ]
};

/**
 * Translates a string to pirate speak.
 * @function translate
 * @param {string} text The string to be translated to pirate speak.
 * @returns {string} The translated pirate speak string.
*/
function translate(text) {
  let translatedText = '';
  // Loop through the text, one character at a time.
  let word = '';
  for (let i = 0; i < text.length; i += 1) {
    let character = text[i];
    // If the character is a letter, then we are in the middle of a word, so we should accumulate the letter into the word variable.
    if (isLetter(character)) {
      word += character;
    }
    // If the character is not a letter, then we hit the end of a word, so we should translate the current word and add it to the translation.
    else {
      if (word !== '') {
        // If we've just finished a word, translate it
        let pirateWord = translateWord(word);
        translatedText += pirateWord;
        word = '';
      }
      translatedText += character; // Add the non-letter character
    }
  }
  // If we ended the loop before translating a word, then translate the final word and add it to the translation.
  if (word !== '') translatedText += translateWord(word);
  return translatedText;
}

/**
 * Checks if a character is a letter.
 * @function isLetter
 * @param {string} character The character to check.
 * @returns {boolean} If the character is a letter or not.
*/
function isLetter(character) {
  if (character.search(/[a-zA-Z'-]/) === -1) return false;
  return true;
}

/**
 * Translates a word to pirate speak word.
 * @function translateWord
 * @param {string} word The word to be translated to pirate speak.
 * @returns {function} applyCase
*/
function translateWord(word) {
  let pirateWord = dictionary[word.toLowerCase()];
  if (pirateWord === undefined) return word;
  return applyCase(word, pirateWord);
}

/**
 * Apply the case of the original word to the pirate speak word.
 * @function applyCase
 * @param {string} wordA The original word to be translated.
 * @param {string} wordB The translated pirate speak word.
 * @returns {string} The translated pirate speak word with the applied casing.
*/
function applyCase(wordA, wordB) {
  if (wordA.length === 1 && wordB.length !== 1) return wordB;
  if (wordA === wordA.toUpperCase()) return wordB.toUpperCase();
  if (wordA === wordA.toLowerCase()) return wordB.toLowerCase();

  let firstChar = wordA.slice(0, 1);
  let otherChars = wordA.slice(1);
  if (firstChar === firstChar.toUpperCase() && otherChars === otherChars.toLowerCase()) {
    return wordB.slice(0, 1).toUpperCase() + wordB.slice(1).toLowerCase();
  }

  return wordB;
}
<commit_msg>Fixed a character in pirateSpeak command<commit_after>/**
 * @file pirateSpeak command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const dictionary = require('../../data/piratePhrases.json');

exports.run = (Bastion, message, args) => {
  if (args.length < 1) {
    return message.channel.send({
      embed: {
        color: Bastion.colors.yellow,
        title: 'Usage',
        description: `\`${Bastion.config.prefix}${this.help.usage}\``
      }
    }).catch(e => {
      Bastion.log.error(e.stack);
    });
  }

  message.channel.send({
    embed: {
      color: Bastion.colors.blue,
      title: 'Pirate Speak:',
      description: translate(args.join(' '))
    }
  }).catch(e => {
    Bastion.log.error(e.stack);
  });
};

exports.config = {
  aliases: [ 'pirate' ],
  enabled: true
};

exports.help = {
  name: 'piratespeak',
  description: 'Convert\'s the given text to pirate speak.',
  botPermission: '',
  userPermission: '',
  usage: 'pirateSpeak <text>',
  example: [ 'pirateSpeak You can always trust the untrustworthy because you can always trust that they will be untrustworthy. Its the trustworthy you can\'t trust.' ]
};

/**
 * Translates a string to pirate speak.
 * @function translate
 * @param {string} text The string to be translated to pirate speak.
 * @returns {string} The translated pirate speak string.
*/
function translate(text) {
  let translatedText = '';
  // Loop through the text, one character at a time.
  let word = '';
  for (let i = 0; i < text.length; i += 1) {
    let character = text[i];
    // If the character is a letter, then we are in the middle of a word, so we should accumulate the letter into the word variable.
    if (isLetter(character)) {
      word += character;
    }
    // If the character is not a letter, then we hit the end of a word, so we should translate the current word and add it to the translation.
    else {
      if (word !== '') {
        // If we've just finished a word, translate it
        let pirateWord = translateWord(word);
        translatedText += pirateWord;
        word = '';
      }
      translatedText += character; // Add the non-letter character
    }
  }
  // If we ended the loop before translating a word, then translate the final word and add it to the translation.
  if (word !== '') translatedText += translateWord(word);
  return translatedText;
}

/**
 * Checks if a character is a letter.
 * @function isLetter
 * @param {string} character The character to check.
 * @returns {boolean} If the character is a letter or not.
*/
function isLetter(character) {
  if (character.search(/[a-zA-Z'-]/) === -1) return false;
  return true;
}

/**
 * Translates a word to pirate speak word.
 * @function translateWord
 * @param {string} word The word to be translated to pirate speak.
 * @returns {function} applyCase
*/
function translateWord(word) {
  let pirateWord = dictionary[word.toLowerCase()];
  if (pirateWord === undefined) return word;
  return applyCase(word, pirateWord);
}

/**
 * Apply the case of the original word to the pirate speak word.
 * @function applyCase
 * @param {string} wordA The original word to be translated.
 * @param {string} wordB The translated pirate speak word.
 * @returns {string} The translated pirate speak word with the applied casing.
*/
function applyCase(wordA, wordB) {
  if (wordA.length === 1 && wordB.length !== 1) return wordB;
  if (wordA === wordA.toUpperCase()) return wordB.toUpperCase();
  if (wordA === wordA.toLowerCase()) return wordB.toLowerCase();

  let firstChar = wordA.slice(0, 1);
  let otherChars = wordA.slice(1);
  if (firstChar === firstChar.toUpperCase() && otherChars === otherChars.toLowerCase()) {
    return wordB.slice(0, 1).toUpperCase() + wordB.slice(1).toLowerCase();
  }

  return wordB;
}
<|endoftext|>