<commit_before>(function($){
    var methods = {
      init : function(options){
        var DBTABLE = $(this)[0].DBTABLE;
        var DBCOLUMNS = $(this)[0].DBCOLUMNS;
        methods.db_setup(DBTABLE, DBCOLUMNS);
      },//end init

      db_open : function(){
        //these vars should have been set on some global var
        //var DATABASE = '';
        //var DBVERSION = '';
        //var DBDESCRIPTION = '';
        //var DBSIZE = '';
        if(window.openDatabase){
          db = openDatabase(DATABASE, DBVERSION, DBDESCRIPTION, DBSIZE);
          return true;
        }else{
          return false;
        }
      },//end db_open

      db_setup : function(DBTABLE, DBCOLUMNS){
        if(methods.db_open()){
          DBCOLUMNS = DBCOLUMNS + ', local_storage_id';
          db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + DBTABLE + ' (' + DBCOLUMNS + ')');
            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + DBTABLE + '_AUDIT (' + DBCOLUMNS + ', api_url)');
          });
        }else{
          //methods.get_records( url );
        }
      },//end db_setup

      find : function( id, url, findClientHandle){
        if(window.openDatabase){
          var DBTABLE = $(this)[0].DBTABLE;
          //get results localy
          db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM '+ DBTABLE +' WHERE local_storage_id = ?', [id], function (tx, results) {
              data = [];
              var len = results.rows.length, i;
              for (i = 0; i < len; i++) {
                data.push({DBTABLE:{'name': results.rows.item(i).name}});
                //alert(results.rows.item(i).name);
              }
              findClientHandle(data);
            });
          });
        }else{
          //get results from api
          function returnHandler(data){
            findClientHandle(data);
          }
          $.getJSON(url + '?auth_token=' + AUTH_TOKEN +'&callback=?', returnHandler);
        }
      },//end find

      all : function( url, cb ){
        if(window.openDatabase){
          var DBTABLE = $(this)[0].DBTABLE;
          //get results localy
          db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM '+ DBTABLE, [], function (tx, results) {
              data = [];
              var len = results.rows.length, i;
              for (i = 0; i < len; i++) {
                $.each(results.rows.item(i), function(key, value){
                  data.push({key: value});
                });
                //data.push({DBTABLE:{'name': results.rows.item(i).name, 'local_storage_id': results.rows.item(i).local_storage_id}});
              }
              debugger
              cb(data);
            });
          });
        }else{
          //get results from api
          function returnHandler(data){
            cb(data);
          }
          $.getJSON(url + '?auth_token=' + AUTH_TOKEN +'&callback=?', returnHandler);
        }
      },//end get

      create : function( data, url, cb ){
        var DBTABLE = $(this)[0].DBTABLE;
        var IS_SYNCABLE = $(this)[0].IS_SYNCABLE;

        methods.auto_increment_key(DBTABLE); //sets the last_local_id
        db.transaction(postit, error, success);

        //openDatabase callbacks
        function postit(jdb){
          var keys = ''; //add local_id as a default to all tables
          var values = '';

          for(var item in data) {
              keys = keys + "'" + item + "', ";
              values = values + "'" + data[item] + "', ";
          }

          keys = 'id, ' + keys + ' local_storage_id';
          values = 'null, ' + values + ' ' + last_local_id;
          alert(values);

          jdb.executeSql('INSERT INTO ' + DBTABLE + '  (' + keys + ') VALUES (' + values + ')');
          jdb.executeSql('INSERT INTO ' + DBTABLE + '_AUDIT  (' + keys + ', api_url) VALUES (' + values + ', "' + url + '")');
        }
        function error(jdb, err){
          alert("CREATE: Error processing SQL: " + jdb.message);
        }
        function success(jdb){
          //if this model is_syncable and API is online, trigger sync method
          if(IS_SYNCABLE){
            methods.sync(DBTABLE, url, function(syncHandle){
              alert(syncHandle);
              cb(syncHandle);
            });
          }
          //should catch an else here if model is not syncable... not sure yet
        }

      },//end create

      update : function(id, url, updateHandle){
        var DBTABLE = $(this)[0].DBTABLE;
        var IS_SYNCABLE = $(this)[0].IS_SYNCABLE;

        db.transaction(postit, error, success);

        //openDatabase callbacks
        function postit(jdb){
          var sql_data = '';
          for(var item in data) {
              sql_data = sql_data + item + "='" + data[item] + "', ";
          }

          //jdb.executeSql('UPDATE ' + DBTABLE + ' SET ' + sql_data + ' WHERE local_storage_id=' + id+ ');
          jdb.executeSql('INSERT INTO ' + DBTABLE + '_AUDIT  (' + keys + ', api_url) VALUES (' + values + ', "' + url + '")');

        }
        function error(jdb, err){
          alert("UPDATE: Error processing SQL: " + jdb.message);
        }
        function success(jdb){
          //if this model is_syncable and API is online, trigger sync method
          if(IS_SYNCABLE){
            methods.sync(DBTABLE, url, function(syncHandle){
              alert(syncHandle);
              cb(syncHandle);
            });
          }
          //should catch an else here if model is not syncable... not sure yet
        }
      },//end update

      sync : function(DBTABLE, url, syncHandle){
        //need to get the lastID at some point
        //methods.find_last_id(DBTABLE, function(lastIdHandle){
        //});
        //loop through the audit table and send one post at a time
        function dataHandler(transaction, results)
        {
          // Handle the results
          for (var i=0; i<results.rows.length; i++) {
            // Each row is a standard JavaScript array indexed by
            // column names.
            var row = results.rows.item(i);
            methods.send_request(DBTABLE, row, function(sendRequestHandle){
              syncHandle(sendRequestHandle);
            });
          }
        }
        function errorHandler(transaction, error)
        {
            // error.message is a human-readable string.
            // error.code is a numeric error code
            alert('Oops.  Error was '+error.message+' (Code '+error.code+')');

            // Handle errors here
            var we_think_this_error_is_fatal = true;
            if (we_think_this_error_is_fatal) return true;
            return false;
        }
        db.transaction(
          function (transaction) {
            transaction.executeSql("SELECT * FROM " + DBTABLE + "_AUDIT;",
                [], // array of values for the ? placeholders
                dataHandler, errorHandler);
          }
        );
      },//end sync

      auto_increment_key : function(DBTABLE){
        function dataHandler(transaction, results)
        {
            // Handle the results
            for (var i=0; i<results.rows.length; i++) {
                // Each row is a standard JavaScript array indexed by
                // column names.
                var row = results.rows.item(i);
                last_local_id = row['last_local_id'] + 1;
            }
        }
        function errorHandler(transaction, error)
        {
            // error.message is a human-readable string.
            // error.code is a numeric error code
            alert('Oops.  Error was '+error.message+' (Code '+error.code+')');

            // Handle errors here
            var we_think_this_error_is_fatal = true;
            if (we_think_this_error_is_fatal) return true;
            return false;
        }
        db.transaction(
            function (transaction) {
                transaction.executeSql("SELECT MAX(local_storage_id) AS last_local_id FROM " + DBTABLE,
                    [], // array of values for the ? placeholders
                    dataHandler, errorHandler);
            }
        );

      },//end auto_increment_key

      find_last_id : function(DBTABLE){
        //get the last id so it can be used as a marker during sync
        function dataHandler(transaction, results)
        {
            // Handle the results
            for (var i=0; i<results.rows.length; i++) {
                // Each row is a standard JavaScript array indexed by
                // column names.
                var row = results.rows.item(i);
                last_id = row['last_id'] + 1;
            }
        }
        function errorHandler(transaction, error)
        {
            // error.message is a human-readable string.
            // error.code is a numeric error code
            alert('Oops.  Error was '+error.message+' (Code '+error.code+')');

            // Handle errors here
            var we_think_this_error_is_fatal = true;
            if (we_think_this_error_is_fatal) return true;
            return false;
        }
        db.transaction(
            function (transaction) {
                transaction.executeSql("SELECT MAX(id) AS last_id FROM " + DBTABLE,
                    [], // array of values for the ? placeholders
                    dataHandler, errorHandler);
            }
        );

      },//end find_last_id

      destroy : function(options){
      },//end destroy

      send_request : function(DBTABLE, row, sendRequestHandle){
        var params = '';
        for(var item in row) {
          //need to filter out local_storage_id
          if(item != 'local_storage_id' || 'api_url'){
            //this part is a bit hardwired for rails params
            //for example post[subject]
            //just so i can use params[:post] in my rails app
            params = params + '&' + DBTABLE + '[' + item + ']=' + row[item];
          }
        }
        var data = encodeURI(params);

        $.ajax({
            url : url + '?auth_token=' + AUTH_TOKEN + data,
            method : 'GET',
            dataType : 'jsonp',
            error: function(request, textStatus, error) {
                if (request.status == 401) {
                    ShowLoginUI(function() {
                        data = self.Get(url);
                    });
                }
                alert('error: ' + request);
            },
            success: function(res){
              //some error catch here if the data from

              //if there is local storage then save it, if not just return the response
              if(window.openDatabase){
                methods.merge(res, row['local_storage_id'], function(mergeHandle){
                  sendRequestHandle(mergeHandle);
                });
                //methods.merge(res, row['local_storage_id']);
              }else{
                alert('return stuff here: ' + res);
                sendRequestHandle(res);
              }
            }
          });
      },//end send_request

      merge : function(res, local_storage_id, mergeHandle){
        //update the table with the ID from the server
        //update the database
        db.transaction(
          function (transaction) {
            transaction.executeSql("UPDATE " + DBTABLE + " set id=? where local_storage_id=?;", [ res.a.id, local_storage_id ]); // array of values for the ? placeholders
          }
        );
        //purge the audit table
        methods.destroy_audit(local_storage_id, function(destroyAuditHandle){
          mergeHandle(destroyAuditHandle);
        });
        //mergeHandle('got to merge');
      },//end merge

    destroy_audit : function(local_storage_id, destroyAuditHandle){
        //removes the record from the audit table only
        db.transaction(
          function (transaction) {
           transaction.executeSql("DELETE FROM " + DBTABLE + "_AUDIT where local_storage_id=?;", [ local_storage_id ]); // array of values for the ? placeholders
          }
        );
      destroyAuditHandle('all done');
    }//end destroy_audit

    };

  $.fn.jsActiveModel = function( method, options ) {
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jsActiveModel' );
    }

  };
})(jQuery);
<commit_msg>fixed key values for lists<commit_after>(function($){
    var methods = {
      init : function(options){
        var DBTABLE = $(this)[0].DBTABLE;
        var DBCOLUMNS = $(this)[0].DBCOLUMNS;
        methods.db_setup(DBTABLE, DBCOLUMNS);
      },//end init

      db_open : function(){
        //these vars should have been set on some global var
        //var DATABASE = '';
        //var DBVERSION = '';
        //var DBDESCRIPTION = '';
        //var DBSIZE = '';
        if(window.openDatabase){
          db = openDatabase(DATABASE, DBVERSION, DBDESCRIPTION, DBSIZE);
          return true;
        }else{
          return false;
        }
      },//end db_open

      db_setup : function(DBTABLE, DBCOLUMNS){
        if(methods.db_open()){
          DBCOLUMNS = DBCOLUMNS + ', local_storage_id';
          db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + DBTABLE + ' (' + DBCOLUMNS + ')');
            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + DBTABLE + '_AUDIT (' + DBCOLUMNS + ', api_url)');
          });
        }else{
          //methods.get_records( url );
        }
      },//end db_setup

      find : function( id, url, findHandle){
        if(window.openDatabase){
          var DBTABLE = $(this)[0].DBTABLE;
          //get results localy
          db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM '+ DBTABLE +' WHERE local_storage_id = ?', [id], function (tx, results) {
              data = [];
              var len = results.rows.length, i;
              for (i = 0; i < len; i++) {
                data.push({DBTABLE:{'name': results.rows.item(i).name}});
                //alert(results.rows.item(i).name);
              }
              findHandle(data);
            });
          });
        }else{
          //get results from api
          function returnHandler(data){
            findHandle(data);
          }
          $.getJSON(url + '?auth_token=' + AUTH_TOKEN +'&callback=?', returnHandler);
        }
      },//end find

      all : function( url, allHandle ){
        if(window.openDatabase){
          var DBTABLE = $(this)[0].DBTABLE;
          //get results localy
          db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM '+ DBTABLE, [], function (tx, results) {
              data = []
              var len = results.rows.length, i;
              for (i = 0; i < len; i++) {
                data.push({jsmodel: i});
                $.each(results.rows.item(i), function(key, value){
                  data[i][key] = value;
                });
              }
              allHandle(data);
            });
          });
        }else{
          //get results from api
          function returnHandler(data){
            allHandle(data);
          }
          $.getJSON(url + '?auth_token=' + AUTH_TOKEN +'&callback=?', returnHandler);
        }
      },//end get

      create : function( data, url, createHandle ){
        var DBTABLE = $(this)[0].DBTABLE;
        var IS_SYNCABLE = $(this)[0].IS_SYNCABLE;

        methods.auto_increment_key(DBTABLE); //sets the last_local_id
        db.transaction(postit, error, success);

        //openDatabase callbacks
        function postit(jdb){
          var keys = ''; //add local_id as a default to all tables
          var values = '';

          for(var item in data) {
              keys = keys + "'" + item + "', ";
              values = values + "'" + data[item] + "', ";
          }

          keys = 'id, ' + keys + ' local_storage_id';
          values = 'null, ' + values + ' ' + last_local_id;
          alert(values);

          jdb.executeSql('INSERT INTO ' + DBTABLE + '  (' + keys + ') VALUES (' + values + ')');
          jdb.executeSql('INSERT INTO ' + DBTABLE + '_AUDIT  (' + keys + ', api_url) VALUES (' + values + ', "' + url + '")');
        }
        function error(jdb, err){
          alert("CREATE: Error processing SQL: " + jdb.message);
        }
        function success(jdb){
          //if this model is_syncable and API is online, trigger sync method
          if(IS_SYNCABLE){
            methods.sync(DBTABLE, url, function(syncHandle){
              alert(syncHandle);
              createHandle(syncHandle);
            });
          }
          //should catch an else here if model is not syncable... not sure yet
        }

      },//end create

      update : function(id, url, updateHandle){
        var DBTABLE = $(this)[0].DBTABLE;
        var IS_SYNCABLE = $(this)[0].IS_SYNCABLE;

        db.transaction(postit, error, success);

        //openDatabase callbacks
        function postit(jdb){
          var sql_data = '';
          for(var item in data) {
              sql_data = sql_data + item + "='" + data[item] + "', ";
          }

          //jdb.executeSql('UPDATE ' + DBTABLE + ' SET ' + sql_data + ' WHERE local_storage_id=' + id+ ');
          jdb.executeSql('INSERT INTO ' + DBTABLE + '_AUDIT  (' + keys + ', api_url) VALUES (' + values + ', "' + url + '")');

        }
        function error(jdb, err){
          alert("UPDATE: Error processing SQL: " + jdb.message);
        }
        function success(jdb){
          //if this model is_syncable and API is online, trigger sync method
          if(IS_SYNCABLE){
            methods.sync(DBTABLE, url, function(syncHandle){
              alert(syncHandle);
              cb(syncHandle);
            });
          }
          //should catch an else here if model is not syncable... not sure yet
        }
      },//end update

      sync : function(DBTABLE, url, syncHandle){
        //need to get the lastID at some point
        //methods.find_last_id(DBTABLE, function(lastIdHandle){
        //});
        //loop through the audit table and send one post at a time
        function dataHandler(transaction, results)
        {
          // Handle the results
          for (var i=0; i<results.rows.length; i++) {
            // Each row is a standard JavaScript array indexed by
            // column names.
            var row = results.rows.item(i);
            methods.send_request(DBTABLE, row, function(sendRequestHandle){
              syncHandle(sendRequestHandle);
            });
          }
        }
        function errorHandler(transaction, error)
        {
            // error.message is a human-readable string.
            // error.code is a numeric error code
            alert('Oops.  Error was '+error.message+' (Code '+error.code+')');

            // Handle errors here
            var we_think_this_error_is_fatal = true;
            if (we_think_this_error_is_fatal) return true;
            return false;
        }
        db.transaction(
          function (transaction) {
            transaction.executeSql("SELECT * FROM " + DBTABLE + "_AUDIT;",
                [], // array of values for the ? placeholders
                dataHandler, errorHandler);
          }
        );
      },//end sync

      auto_increment_key : function(DBTABLE){
        function dataHandler(transaction, results)
        {
            // Handle the results
            for (var i=0; i<results.rows.length; i++) {
                // Each row is a standard JavaScript array indexed by
                // column names.
                var row = results.rows.item(i);
                last_local_id = row['last_local_id'] + 1;
            }
        }
        function errorHandler(transaction, error)
        {
            // error.message is a human-readable string.
            // error.code is a numeric error code
            alert('Oops.  Error was '+error.message+' (Code '+error.code+')');

            // Handle errors here
            var we_think_this_error_is_fatal = true;
            if (we_think_this_error_is_fatal) return true;
            return false;
        }
        db.transaction(
            function (transaction) {
                transaction.executeSql("SELECT MAX(local_storage_id) AS last_local_id FROM " + DBTABLE,
                    [], // array of values for the ? placeholders
                    dataHandler, errorHandler);
            }
        );

      },//end auto_increment_key

      find_last_id : function(DBTABLE){
        //get the last id so it can be used as a marker during sync
        function dataHandler(transaction, results)
        {
            // Handle the results
            for (var i=0; i<results.rows.length; i++) {
                // Each row is a standard JavaScript array indexed by
                // column names.
                var row = results.rows.item(i);
                last_id = row['last_id'] + 1;
            }
        }
        function errorHandler(transaction, error)
        {
            // error.message is a human-readable string.
            // error.code is a numeric error code
            alert('Oops.  Error was '+error.message+' (Code '+error.code+')');

            // Handle errors here
            var we_think_this_error_is_fatal = true;
            if (we_think_this_error_is_fatal) return true;
            return false;
        }
        db.transaction(
            function (transaction) {
                transaction.executeSql("SELECT MAX(id) AS last_id FROM " + DBTABLE,
                    [], // array of values for the ? placeholders
                    dataHandler, errorHandler);
            }
        );

      },//end find_last_id

      destroy : function(options){
      },//end destroy

      send_request : function(DBTABLE, row, sendRequestHandle){
        var params = '';
        for(var item in row) {
          //need to filter out local_storage_id
          if(item != 'local_storage_id' || 'api_url'){
            //this part is a bit hardwired for rails params
            //for example post[subject]
            //just so i can use params[:post] in my rails app
            params = params + '&' + DBTABLE + '[' + item + ']=' + row[item];
          }
        }
        var data = encodeURI(params);

        $.ajax({
            url : url + '?auth_token=' + AUTH_TOKEN + data,
            method : 'GET',
            dataType : 'jsonp',
            error: function(request, textStatus, error) {
                if (request.status == 401) {
                    ShowLoginUI(function() {
                        data = self.Get(url);
                    });
                }
                alert('error: ' + request);
            },
            success: function(res){
              //some error catch here if the data from

              //if there is local storage then save it, if not just return the response
              if(window.openDatabase){
                methods.merge(res, row['local_storage_id'], function(mergeHandle){
                  sendRequestHandle(mergeHandle);
                });
                //methods.merge(res, row['local_storage_id']);
              }else{
                alert('return stuff here: ' + res);
                sendRequestHandle(res);
              }
            }
          });
      },//end send_request

      merge : function(res, local_storage_id, mergeHandle){
        //update the table with the ID from the server
        //update the database
        db.transaction(
          function (transaction) {
            transaction.executeSql("UPDATE " + DBTABLE + " set id=? where local_storage_id=?;", [ res.a.id, local_storage_id ]); // array of values for the ? placeholders
          }
        );
        //purge the audit table
        methods.destroy_audit(local_storage_id, function(destroyAuditHandle){
          mergeHandle(destroyAuditHandle);
        });
        //mergeHandle('got to merge');
      },//end merge

    destroy_audit : function(local_storage_id, destroyAuditHandle){
        //removes the record from the audit table only
        db.transaction(
          function (transaction) {
           transaction.executeSql("DELETE FROM " + DBTABLE + "_AUDIT where local_storage_id=?;", [ local_storage_id ]); // array of values for the ? placeholders
          }
        );
      destroyAuditHandle('all done');
    }//end destroy_audit

    };

  $.fn.jsActiveModel = function( method, options ) {
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jsActiveModel' );
    }

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


<commit_before>'use strict';
/*jshint bitwise: false*/

import Promise from 'es6-promises';

class BleCastBl {
  parse(manufacturerData) {
    let lx = 256 * manufacturerData[5] + manufacturerData[4];
    return {
      type: 'lx',
      unit: 'lx',
      val: lx
    };
  }
}

class BleCastTm {
  parse(manufacturerData) {
    let tempC = manufacturerData[4] - ((manufacturerData[4] & 0x80) << 1);
    tempC += ((manufacturerData[5] & 0x80) >> 7) * 0.5;
    return {
      type: 'te',
      unit: 'C',
      val: tempC
    };
  }
}

const PERIPHERALS = {
  BLECAST_BL: new BleCastBl(),
  BLECAST_TM: new BleCastTm()
};

class Peripherals {
  lookup(rawid) {
    return new Promise((resolve, reject) => {
      if (!rawid) {
        reject('Unknown peripheral: local name is empty');
      }
      let identifier = rawid.replace(new RegExp('\0', 'g'), ''); // in case of a NULL terminator is included
      let p = PERIPHERALS[identifier];
      if (!p) {
        reject(`Unknown peripheral: [${identifier}]`);
      } else {
        resolve(p);
      }
    });
  }
}

export default new Peripherals();
<commit_msg>Remove unused module<commit_after><|endoftext|>


<commit_before>module.exports = {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Moved Temporarily',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    308: 'Permanent Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Time-out',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Request Entity Too Large',
    414: 'Request-URI Too Large',
    415: 'Unsupported Media Type',
    416: 'Requested Range Not Satisfiable',
    417: 'Expectation Failed',
    418: 'I\'m a teapot',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    425: 'Unordered Collection',
    426: 'Upgrade Required',
    428: 'Precondition Required',
    429: 'Too Many Requests',
    431: 'Request Header Fields Too Large',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Time-out',
    505: 'HTTP Version Not Supported',
    506: 'Variant Also Negotiates',
    507: 'Insufficient Storage',
    509: 'Bandwidth Limit Exceeded',
    510: 'Not Extended',
    511: 'Network Authentication Required'
};
<commit_msg>Add node comment to status-messages.js<commit_after>// This status message map is taken from the node.js source code.  The original
// copyright notice for lib/_http_server.js is reproduced below.
//
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

module.exports = {
    100: "Continue",
    101: "Switching Protocols",
    102: "Processing",
    200: "OK",
    201: "Created",
    202: "Accepted",
    203: "Non-Authoritative Information",
    204: "No Content",
    205: "Reset Content",
    206: "Partial Content",
    207: "Multi-Status",
    300: "Multiple Choices",
    301: "Moved Permanently",
    302: "Moved Temporarily",
    303: "See Other",
    304: "Not Modified",
    305: "Use Proxy",
    307: "Temporary Redirect",
    308: "Permanent Redirect",
    400: "Bad Request",
    401: "Unauthorized",
    402: "Payment Required",
    403: "Forbidden",
    404: "Not Found",
    405: "Method Not Allowed",
    406: "Not Acceptable",
    407: "Proxy Authentication Required",
    408: "Request Time-out",
    409: "Conflict",
    410: "Gone",
    411: "Length Required",
    412: "Precondition Failed",
    413: "Request Entity Too Large",
    414: "Request-URI Too Large",
    415: "Unsupported Media Type",
    416: "Requested Range Not Satisfiable",
    417: "Expectation Failed",
    418: "I\"m a teapot",
    422: "Unprocessable Entity",
    423: "Locked",
    424: "Failed Dependency",
    425: "Unordered Collection",
    426: "Upgrade Required",
    428: "Precondition Required",
    429: "Too Many Requests",
    431: "Request Header Fields Too Large",
    500: "Internal Server Error",
    501: "Not Implemented",
    502: "Bad Gateway",
    503: "Service Unavailable",
    504: "Gateway Time-out",
    505: "HTTP Version Not Supported",
    506: "Variant Also Negotiates",
    507: "Insufficient Storage",
    509: "Bandwidth Limit Exceeded",
    510: "Not Extended",
    511: "Network Authentication Required"
};
<|endoftext|>


<commit_before>'use strict';
/**
 * Macros to help translate item pages
 */

(function(utils) {

const macros = utils.macros;

macros["pagine strumenti"] = function(str) {
    return macros.langtable(
        macros.tasche(
        macros.itemtemplates(
        macros.iteminfobox(
    str))));
}

const ordinals = {
    I: '1', II: '2', III: '3', IV: '4', V: '5', VI: '6',
    VII: '7', VIII: '8', IX: '9',
};

macros.tasche = function(str) {
    return str
        .replace(/key items/gi, "Strumenti base")
        .replace(/items/gi, "Strumenti")
        .replace(/z-crystals/gi, "Cristalli Z")
        .replace(/ingredients/gi, "Ingredienti")
        .replace(/treasures/gi, "Tesori")
}

macros.iteminfobox = function(str) {
    // Identify the template. Better to be precise because on Bulba is made of
    // several non-nested subtemplates call
    const begin = str.indexOf("{{ItemInfobox/head");
    const end = str.indexOf("|}", begin);
    let templ = str.substring(begin, end);
    // templ doesn't contain the closing "|}"
    templ = templ
        .replace("{{ItemInfobox/head", "{{ItemInfobox")
        .replace(/\|name=([^|]+)\|/, "|name=\n|engname=$1|engtans=\n|")
        .replace(/\|art=([^|]+)/, "")
        .replace(/\|sprite2=([^|]+)/, "")
        .replace(/\|jtrans=([^|]+)\|/, "|jrom=\n|jtrans=$1|")
        .replace(/\|gen=([IVX]+)\n?(\||})/, function(_, genord, closing) { return "|gen=" + ordinals[genord] + "\n" + closing; })
        .replace(/\|colorscheme=[^|}]+\n?(\||})/, "$1")
        .replace(/\|fling=[a-zA-Z]+\n?(\||})/, "$1")
        // bag rows
        .replace(/{{ItemInfobox\/BagRow(?:Bottom)?\|([IVX]+)\|([a-zA-Zé0-9- ]+)(?:\|[^}]*)?}}/g, function(_, genord, pocket) {
            return "|bag" + ordinals[genord] + "=" + macros.tasche(pocket);
        })
        // fling
        .replace(/{{ItemInfobox\/Fling\|(\d+)\|colorscheme=[^}]*}}/, "|fling=$1")
        // Remove the }} closing the ItemInfobox/head
        .replace("}}\n", "");

    return str.substring(0, begin) + templ + "}}" + str.substring(end + 2);
};

macros.itemtemplates = function(str) {
    str = str
    // ItemPrice
        .replace(/N\/A/g, "-")
        .replace(/{{ItemPrice\|/g, "{{ItemPrice/Row|")
        .replace(/\|{{PDollar}}([\d,.]+)(\||})/g, "|$1$2")
        // twice because the pipes around may be shared
        .replace(/\|{{PDollar}}([\d,.]+)(\||})/g, "|$1$2")
        // digit separator from English , to Italian .
        .replace(/(\d),(\d)/g, "$1.$2")
    // ItemDescription
        .replace(/{{movedesc\|/g, "{{ItemDescription/head|")
        .replace(/{{movedescentry\|/g, "{{ItemDescription/row|");
    // ItemAvailability
    // Identify bounds and only work withing them
    const begin = str.indexOf("{{ItemAvailability/head");
    const end = str.indexOf("|}", begin);
    let templ = str.substring(begin, end);
    let newtempl = templ.split("\n")[0] + "\n";
    // Each row should be transformed in one template call
    for (const row of templ.split("|-").slice(1)) {
        let cells = ("\n" + row).split("\n|").slice(1)
                        .map(s => s.trim() === "" ? "-" : s.trim());
        console.assert(cells.length == 3);
        // Update first cell
        // cells[0] = cells[0].replace(/^\s*{{gameabbrev(?:\d|ss)\|(\w+)}}/, (_, g) => macros.giochi(g));
        // Generic replacements for other cells
        // Old-school for loop because JS doesn't support me on this
        for (let i = 1; i < cells.length; ++i) {
            cells[i] = cells[i]
                .replace(/^''\[\[Trade\]\]''$/g, "[[Scambio]]")
                .replace(/\[\[Cram\-o\-matic\]\]/g, "[[CramoBot]]");
        }

        newtempl += "{{ItemAvailability/row|" + cells.join("|") + "}}\n";
    }
    newtempl += "{{ItemAvailability/footer}}\n";
    str = str.substring(0, begin) + newtempl + str.substring(end + 2).replace(/^\s*\|}/, "");

    // Replacing gameabbrev templates with only Italian abbrevs
    str = str
        .replace(/{{gameabbrev(?:\d|ss)\|(\w+)}}/g, (_, g) => macros.giochi(g));
    str = macros.tasche(str);

    return str;
}

// macros.colori = function(str) {
// 	str = str.replace(/color buio/gi, 'color dark');
// 	var matches = /\{\{([\s\w]+) color\s?[dark|light]?\}\}/gi.exec(str);
// 	str = str.replace(/\{\{([\s\w]+) color\s?((dark|light))?\}\}/gi,
// 		'{{#invoke: colore | $1 | $2 }}')
// 		.replace(/(\{\{#invoke: colore \| .+? )\|\s*\}\}/gi, '$1| normale }}');
// 	if (matches && matches.length)
// 		for (var k = 1; k < matches.length; ++k)
// 			str = str.replace(matches[k], matches[k].replace(/\s/g, '_'));
// 	return str;
// };

// macros['nature'] = function(str) {
// 	return str.replace(/Hardy/g, 'Ardita')
// 		.replace(/Lonely/g, 'Schiva')
// 		.replace(/Brave/g, 'Audace')
// 		.replace(/Adamant/g, 'Decisa')
// 		.replace(/Naughty/g, 'Birbona')
// 		.replace(/Decisa Orb/g, 'Adamant Orb')
// 		.replace(/Fiacca Incense/g, 'Lax Incense')
// 		.replace(/Calma Mind/g, 'Calm Mind')
// };

if (utils.updateMenu) { utils.updateMenu() } ;
}(utils || { macros: {} }));<commit_msg>Implementing required featuers in macro for item pages<commit_after>'use strict';
/**
 * Macros to help translate item pages
 */

/**
 * Taken a template that on Bulba is table, closed by |}, replaces header, adds
 * footer and apply a function to content.
 *
 * Named args because they are many optional.
 *
 * @param {string} str the string to work on
 * @param {object} args named arguments
 * @param {string} args.template name of the template to replace. Equivalent to
 *                setting args.head = <args.template>/head, args.foot_replace =
 *                {{<args.template>/footer}}, and not setting args.head_replace
 * @param {string} args.head header of the template to look for
 * @param {string} args.head_reaplace a string to replace args.head with. If
 *                  not given, the head is left untouched
 * @param {string} args.foot_replace the footer to add
 * @param {number} args.closing_num the number of closing |} to expect
 * @param {boolean} args.global whether to replace all occurences of the
 *                      template or not
 * @param {function} args.transl_content a function that translate the content
 *                      of the template
 * @returns {string} the modified string
 */
function tabular_template(str, args) {
    args.head = args.head || ("{{" + args.template + "/head");
    args.head_replace = args.head_replace || args.head;
    args.foot_replace = args.foot_replace || ("{{" + args.template + "/footer}}");
    args.closing_num = args.closing_num || 1;
    args.global = args.global || false;
    args.transl_content = args.transl_content || (s => s);

    const begin = str.indexOf(args.head);
    if (begin == -1) {
        return str;
    }
    const firstend = str.indexOf("|}", begin);
    let _end = firstend;
    for (let _ = 1; _ < args.closing_num; ++_) {
        _end = str.indexOf("|}", _end + 2);
    }
    const end = _end;
    const templ = args.transl_content(str.substring(begin + args.head.length, firstend));

    // Iterate if needed because of global
    const head = str.substring(0, begin) + args.head_replace + templ + args.foot_replace;
    const tail = str.substring(end + 2);
    return head + (args.global ? tabular_template(tail, args) : tail);
};

/**
 * Translate section names
 * @param {string} str the string to work on
 */
function sezioni(str) {
    return str
        .replace(/==In the core series games==/, "==Nella serie principale==")
        // .replace(/==In the core series giochi==/, "==Nella serie principale==")
        .replace(/===Price===/g, "===Prezzo===")
        .replace(/===Effect===/g, "===Effetti===")
        .replace(/====Held item====/g, "====Strumento tenuto====")
        .replace(/===Description===/g, "===Descrizione===")
        .replace(/===Acquisition===/g, "===Ottenimento===")
        .replace(/==In spin-off games==/g, "==Negli spin-off==")
        .replace(/===Pokémon Mystery Dungeon series===/g, "===Serie Pokémon Mystery Dungeon===")
        .replace(/===Appearance===/g, "===Aspetto===")
        .replace(/==In the GCC==/g, "==Nel GCC==")
        .replace(/==Trivia==/g, "==Curiosità==")
        .replace(/==In other languages==/g, "==In altre lingue==");
}

(function(utils) {

const macros = utils.macros;

macros["pagine strumenti"] = function(str) {
    return macros.langtable(
        macros.tasche(
        sezioni(
        itemtemplates(
    str))));
}

const ordinals = {
    I: '1', II: '2', III: '3', IV: '4', V: '5', VI: '6',
    VII: '7', VIII: '8', IX: '9',
};

function itemtemplates(str) {
    // ItemInfobox
    str = tabular_template(str, {
        head: "{{ItemInfobox/head",
        head_replace: "{{ItemInfobox",
        foot_replace: "}}",
        transl_content: function(content) {
            // Find name in the interwiki
            const name = (/\[\[it:([^\]]*)\]\]/).exec(str)[1];
            return content
                .replace(/\|name=([^|]+)\|/, "|name=" + name + "\n|engname=$1|engtrans=\n|")
                .replace(/\|art=([^|]+)/, "")
                .replace(/\|sprite2=([^|]+)/, "")
                .replace(/\|jtrans=([^|]+)\|/, "|jrom=\n|jtrans=$1|")
                .replace(/\|gen=([IVX]+)\n?(\||})/, function(_, genord, closing) { return "|gen=" + ordinals[genord] + "\n" + closing; })
                .replace(/\|colorscheme=[^|}]+\n?(\||})/, "$1")
                .replace(/\|fling=[a-zA-Z]+\n?(\||})/, "$1")
                // bag rows
                .replace(/{{ItemInfobox\/BagRow(?:Bottom)?\|([IVX]+)\|([a-zA-Zé0-9- ]+)(?:\|[^}]*)?}}/g, function(_, genord, pocket) {
                    return "|bag" + ordinals[genord] + "=" + macros.tasche(pocket);
                })
                // fling
                .replace(/{{ItemInfobox\/Fling\|(\d+)\|colorscheme=[^}]*}}/, "|fling=$1")
                // Remove the }} closing the ItemInfobox/head
                .replace("}}\n", "");
        },
    });
    // ItemPrice
    str = tabular_template(str, {
        template: "ItemPrice",
        closing_num: 2,
        global: true,
        transl_content: function(content) {
            return content
                .replace(/N\/A/g, "-")
                // .replace(/\b({{ItemPrice\|\b.*?)\|}\s*\|}/, "$1{{ItemPrice/footer}}")
                .replace(/{{ItemPrice\|/g, "{{ItemPrice/Row|")
                .replace(/\|{{PDollar}}([\d,.]+)(\||})/g, "|$1$2")
                // twice because the pipes around may be shared
                .replace(/\|{{PDollar}}([\d,.]+)(\||})/g, "|$1$2")
                // digit separator from English , to Italian .
                .replace(/(\d),(\d)/g, "$1.$2");
        },
    })
    // ItemDescription
    str = tabular_template(str, {
        head: "{{movedesc|",
        head_replace: "{{ItemDescription/head|",
        foot_replace: "{{ItemDescription/footer}}",
        closing_num: 2,
        global: true,
        transl_content: function(content) {
            return content
                .replace(/{{movedescentry\|/g, "{{ItemDescription/row|");
        },
    });
    // ItemAvailability
    str = tabular_template(str, {
        template: "ItemAvailability",
        closing_num: 2,
        global: true,
        transl_content: function(content) {
            let newtempl = content.split("\n")[0] + "\n";
            // Each row should be transformed in one template call
            for (const row of content.split("|-").slice(1)) {
                let cells = ("\n" + row).split("\n|").slice(1)
                                .map(s => s.trim() === "" ? "-" : s.trim());
                console.assert(cells.length == 3);
                // Update first cell
                // Actually only bothers with IoA because other are taken care
                // of by the generic gameabbr replacement
                cells[0] = cells[0].replace(/'''{{color2\|\s*{{[^}]*}}\s*\|\s*The Isle of Armor\s*\|\s*IoA\s*}}'''/, "IA");
                // Generic replacements for other cells
                // Old-school for loop because JS doesn't support me on this
                for (let i = 1; i < cells.length; ++i) {
                    cells[i] = cells[i]
                        .replace(/^''\[\[Trade\]\]''$/g, "[[Scambio]]")
                        .replace(/\[\[Cram\-o\-matic\]\]/g, "[[CramoBot]]");
                }

                newtempl += "{{ItemAvailability/row|" + cells.join("|") + "}}\n";
            }
            return newtempl;
        },
    });
    // Replacing gameabbrev templates with only Italian abbrevs
    str = str
        .replace(/{{gameabbrev(?:\d|ss)\|(\w+)}}/g, (_, g) => macros.giochi(g));
    str = macros.tasche(str);

    return str;
}

macros.tasche = function(str) {
    return str
        .replace(/key items/gi, "Strumenti base")
        .replace(/other items/gi, "Strumenti")
        .replace(/items/gi, "Strumenti")
        .replace(/z-crystals/gi, "Cristalli Z")
        .replace(/ingredients/gi, "Ingredienti")
        .replace(/treasures/gi, "Tesori")
}

if (utils.updateMenu) { utils.updateMenu() } ;
}(utils || { macros: {} }));<|endoftext|>


<commit_before>
/* medea - an Open Source, WebGL-based 3d engine for next-generation browser games.
 * (or alternatively, for clumsy and mostly useless tech demos written solely for fun)
 *
 * medea is (c) 2011, Alexander C. Gessler
 * licensed under the terms and conditions of a 3 clause BSD license.
 */

medea._addMod('shader',['filesystem'],function(undefined) {
	"use strict";
	var medea = this, gl = medea.gl;

	medea.SHADER_TYPE_PIXEL = gl.FRAGMENT_SHADER;
	medea.SHADER_TYPE_VERTEX = gl.VERTEX_SHADER;

	medea._initMod('filesystem');

	// cache for compiled shader objects.
	var sh_cache = {
	};

	medea.Shader = medea.Resource.extend( {

		init : function(src, defines, callback) {

			this.type = src.split('.').pop() == 'ps' ? medea.SHADER_TYPE_PIXEL : medea.SHADER_TYPE_VERTEX;
			this.shader = 0;
			this.defines = defines ? medea.Merge(defines,{}) : {};

			// trigger deferred loading
			this._super(src, callback);
		},

		OnDelayedInit : function(data) {

// #ifdef DEBUG
			medea.DebugAssert(typeof data === "string","got unexpected argument, perhaps the source for the shader was not a single resource?");
// #endif

			var c = this._GetCacheName();
			var s = sh_cache[c];
			if(s !== undefined) {
				this.shader = s;
				this._super();
				return;
			}

			s = this.shader = sh_cache[c] = gl.createShader(this.type);

			var gen_source = this._PrependDefines(data);
			gl.shaderSource(s,gen_source);

			gl.compileShader(s);
			if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
				medea.NotifyFatal("failure compiling shader " +  this.src + ", error log: " + gl.getShaderInfoLog(s));
				return;
			}

			// mark this resource as complete
			this._super();

			medea.LogDebug("successfully compiled shader " + this.src);
		},

		GetGlShader : function(gl) {
			return this.shader;
		},

		_PrependDefines : function(data) {
			var d = this.defines;

			var o = '';
			for(var k in d) {
				o += '#define ' + k + ' ' + (d[k] || '') + '\n';
			}
			if (o === '') {
				return data;
			}
			return	'/* !begin medea-generated head! */\n' + o +
					'/* !end medea-generated head! */\n' + data;
		},

		_GetCacheName : function() {
			var o = this.src;

			if (this.defines) {
				var d = this.defines;
				o += '#';
				for(var k in d) {
					o += k+'='+(d[k] || '');
				}
			}

			return o;
		},
	});

	medea.CreateShader = function(res, defines, callback) {
		return new medea.Shader(res, defines, callback);
	}
});
<commit_msg>- shader: keep source code and preprocessed code and expose them via GetSourceCode/GetPreProcessedSourceCode. No   actual preprocessing is done, however - for this I need an implementation of the C preprocessor in JS.<commit_after>
/* medea - an Open Source, WebGL-based 3d engine for next-generation browser games.
 * (or alternatively, for clumsy and mostly useless tech demos written solely for fun)
 *
 * medea is (c) 2011, Alexander C. Gessler
 * licensed under the terms and conditions of a 3 clause BSD license.
 */

medea._addMod('shader',['filesystem'],function(undefined) {
	"use strict";
	var medea = this, gl = medea.gl;

	medea.SHADER_TYPE_PIXEL = gl.FRAGMENT_SHADER;
	medea.SHADER_TYPE_VERTEX = gl.VERTEX_SHADER;

	medea._initMod('filesystem');

	// cache for compiled shader objects.
	var sh_cache = {
	};

	medea.Shader = medea.Resource.extend( {

		init : function(src, defines, callback) {

			this.type = src.split('.').pop() == 'ps' ? medea.SHADER_TYPE_PIXEL : medea.SHADER_TYPE_VERTEX;
			this.shader = 0;
			this.defines = defines ? medea.Merge(defines,{}) : {};

			// trigger deferred loading
			this._super(src, callback);
		},

		OnDelayedInit : function(data) {

// #ifdef DEBUG
			medea.DebugAssert(typeof data === "string","got unexpected argument, perhaps the source for the shader was not a single resource?");
// #endif
			this.source = data;

			var c = this._GetCacheName();
			var s = sh_cache[c];
			if(s !== undefined) {
				this.gen_source = s.gen_source;
				this.shader = s.shader;
				this._super();
				return;
			}

			s = this.shader = gl.createShader(this.type);
			this.gen_source = this._PrependDefines(data);

			// XXX run preprocessor manually so we have access to the
			// final, preprocessed shader.

			// create a new cache entry for this shader
			sh_cache[c] = {
				shader : this.shader,
				source : this.source,
				gen_source : this.gen_source
			};

			// compile the preprocessed shader
			gl.shaderSource(s,this.gen_source);
			gl.compileShader(s);

			if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
				medea.NotifyFatal("failure compiling shader " +  this.src + ", error log: " + gl.getShaderInfoLog(s));
				return;
			}

			// mark this resource as complete
			this._super();

			medea.LogDebug("successfully compiled shader " + this.src);
		},

		GetSourceCode : function() {
			return this.source;
		},

		GetPreProcessedSourceCode : function() {
		// XXX this is not the preprocessed source code ..
			return this.gen_source;
		},

		GetGlShader : function(gl) {
			return this.shader;
		},

		_PrependDefines : function(data) {
			var d = this.defines;

			var o = '';
			for(var k in d) {
				o += '#define ' + k + ' ' + (d[k] || '') + '\n';
			}
			if (o === '') {
				return data;
			}
			return	'/* !begin medea-generated head! */\n' + o +
					'/* !end medea-generated head! */\n' + data;
		},

		_GetCacheName : function() {
			var o = this.src;

			if (this.defines) {
				var d = this.defines;
				o += '#';
				for(var k in d) {
					o += k+'='+(d[k] || '');
				}
			}

			return o;
		},
	});

	medea.CreateShader = function(res, defines, callback) {
		return new medea.Shader(res, defines, callback);
	}
});
<|endoftext|>


<commit_before>
/**
 * 查詢 www.moedict.tw
 * 成功查詢的頁面：https://www.moedict.tw/%E5%8B%BE%E8%90%8C
 * http://localhost:3000/moedict/勾萌
 *
 * 成功查詢的頁面：https://www.moedict.tw/%E5%AE%8B
 * http://localhost:3000/moedict/宋
 *
 * 失敗查詢的頁面：https://www.moedict.tw/%E4%B8%8D%E8%90%8C
 * http://localhost:3000/moedict/不萌
 *
 */

CONFIG.module_alias["dict.tw"] = "dict.tw";
launch_proxy["dict.tw"] = function (_output, _query, _mode) {

var _options = {
    module: "dict.tw",
    query: _query,

    // 正式查詢
    url: "http://dict.tw/dict/" + encodeURI(_query),

    encoding: "utf8",

    // --------------------------------------------------
    /**
     * 沒找到資料的選擇器
     */
    //content_not_found_selector: "body",
    content_not_found_string: '',

    /**
     * 取出指定元素的HTML程式碼
     */
    //html_selector: ".db_info .def",

    /**
     * 取出指定元素的純文字
     * 取出音節(斷句)
     */
    //text_selector: ".syllable:first-of-type",

    /**
     * 指定處理元素的方法
     */
    process: function (_content) {
        try {
            //抓音節.syllable
            var _s = $(_content).find(".syllable");
            var _syllable =_s[0].text;

            //抓解釋.def
            //var _second = _content.lastIndexOf("
", _content.lastIndexOf("
"));
            var _content_hearder = '</form>';
            var _content_footer = '
';

            //var _content = _content.slice(_content_hearder + _content_footer.length, _content.lastIndexOf(_content_footer));
            var _content = _content.slice(_content.lastIndexOf(_content_hearder) + _content_hearder.length, _content.lastIndexOf(_content_footer));
            console.log("---------------------------------");
            console.log(_content);

            var _d = $(_content).find(".def");
            console.log("---------------------------------");
            console.log(_d);
            console.log(_d.length);

            var _header = '
  '
            var _footer = '
'
           // _d = _d.slice(_d.lastIndexOf(_header) + _header.length, _d.lastIndexOf(_footer));

            //var _d = $(_content).find(".db_info").find(".def");

            _content =_syllable + "def:" + _content;
        }
         catch (e) {
             console.log(e)
         }
        return _content;
    },

    // ------------------------

    /**
     * 指定use_agnet (可省略)
     */
    //user_agent: "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10",

    /**
     * 指定來源網頁 referer (可省略)
     */
    //referer: "https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5",

    // ------------------------
    /**
     * 參考來源網頁的名稱
     */
    //referer_name: "dict.tw線上字典",

    /**
     * 參考來源網頁
     */
    //referer_source: "https://zh.wikipedia.org/w/index.php?title=" + encodeURI(_query) + "&oldformat=true"
};

web_crawler(_output, _options, _mode);

//_res.send(_query);
// ----------------------------------------

};  // launch_proxy = function (_output, _query) {
<commit_msg>Update dict.tw.js<commit_after>
/**
 * 查詢 www.moedict.tw
 * 成功查詢的頁面：https://www.moedict.tw/%E5%8B%BE%E8%90%8C
 * http://localhost:3000/moedict/勾萌
 *
 * 成功查詢的頁面：https://www.moedict.tw/%E5%AE%8B
 * http://localhost:3000/moedict/宋
 *
 * 失敗查詢的頁面：https://www.moedict.tw/%E4%B8%8D%E8%90%8C
 * http://localhost:3000/moedict/不萌
 *
 */

CONFIG.module_alias["dict.tw"] = "dict.tw";
launch_proxy["dict.tw"] = function (_output, _query, _mode) {

var _options = {
    module: "dict.tw",
    query: _query,

    // 正式查詢
    url: "http://dict.tw/dict/" + encodeURI(_query),

    encoding: "utf8",

    // --------------------------------------------------
    /**
     * 沒找到資料的選擇器
     */
    //content_not_found_selector: "body",
    content_not_found_string: '',

    /**
     * 取出指定元素的HTML程式碼
     */
    //html_selector: ".db_info .def",

    /**
     * 取出指定元素的純文字
     * 取出音節(斷句)
     */
    //text_selector: ".syllable:first-of-type",

    /**
     * 指定處理元素的方法
     */
    process: function (_content) {
        try {
            //抓音節.syllable
            var _s = $(_content).find(".syllable");
            var _syllable =_s[0].text;

            //抓解釋.def
            //var _second = _content.lastIndexOf("
", _content.lastIndexOf("
"));
            var _content_hearder = '</form>';
            var _content_footer = '
';

            var _content = _content.slice(_content.lastIndexOf(_content_hearder) + _content_hearder.length, _content.lastIndexOf(_content_footer));
            console.log("---------------------------------");
            console.log(_content);

            var _d = _content.find(".def");
            console.log("---------------------------------");
            console.log(_d);
            console.log(_d.length);

            var _header = '
  '
            var _footer = '
'
           // _d = _d.slice(_d.lastIndexOf(_header) + _header.length, _d.lastIndexOf(_footer));

            //var _d = $(_content).find(".db_info").find(".def");

            _content =_syllable + "def:" + _content;
        }
         catch (e) {
             console.log(e)
         }
        return _content;
    },

    // ------------------------

    /**
     * 指定use_agnet (可省略)
     */
    //user_agent: "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10",

    /**
     * 指定來源網頁 referer (可省略)
     */
    //referer: "https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5",

    // ------------------------
    /**
     * 參考來源網頁的名稱
     */
    //referer_name: "dict.tw線上字典",

    /**
     * 參考來源網頁
     */
    //referer_source: "https://zh.wikipedia.org/w/index.php?title=" + encodeURI(_query) + "&oldformat=true"
};

web_crawler(_output, _options, _mode);

//_res.send(_query);
// ----------------------------------------

};  // launch_proxy = function (_output, _query) {
<|endoftext|>


<commit_before>const rawRender = require('../raw_render')

module.exports = function yields (hexo, args) {
  // {% requirements parent cy.clearCookies %}
  // {% requirements blurability .blur %}
  // {% requirements focusability .blur %}
  // {% requirements checkability .click %}
  // {% requirements dom .click %}
  // {% requirements dom .children %}

  const type = args[0]
  const cmd = `<code>${args[1]}()</code>`

  /* eslint-disable commas */
  const waitAssertions = `${cmd} will automatically wait for assertions you've chained to pass`

  /* eslint-disable commas */
  const retryAssertions = `${cmd} will automatically {% url "retry" retry-ability %} until assertions you've chained all pass`

  /* eslint-disable quotes */
  const exist = `${cmd} will automatically {% url "retry" retry-ability %} until the element(s) {% url 'exist in the DOM' introduction-to-cypress#Default-Assertions %}`

  /* eslint-disable quotes */
  const actionable = `${cmd} will automatically wait for the element to reach an {% url 'actionable state' interacting-with-elements %}`

  const render = (str) => {
    return rawRender.call(this, hexo, str)
  }

  const none = () => {
    return `

${cmd} cannot have any assertions chained.

`
  }

  const wait = () => {
    return `

${waitAssertions}.

`
  }

  const retry = () => {
    return `

${retryAssertions}.

`
  }

  const once = () => {
    return `

${cmd} will only run assertions you've chained once, and will not {% url "retry" retry-ability %}.

`
  }

  const utility = () => {
    return `

${cmd} is a utility command.

${cmd} will not run assertions. Assertions will pass through as if this command did not exist.

`
  }

  const its = () => {
    return `

${cmd} will automatically {% url "retry" retry-ability %} itself until the property exists on the subject.

${retryAssertions}.

`
  }

  const existence = () => {
    return render(`

${exist}.

${retryAssertions}.

`)
  }

  const actions = () => {
    return render(`

${actionable}.

${waitAssertions}.

`)
  }

  switch (type) {
    case 'none':
      return none()
    case 'once':
      return once()
    case 'wait':
      return wait()
    case 'retry':
      return retry()
    case 'utility':
      return utility()
    case 'its':
      return its()
    case 'existence':
      return existence()
    case 'actions':
      return actions()
    default:
      // error when an invalid usage option was provided
      throw new Error(`{% assertions %} tag helper was provided an invalid option: ${type}`)
  }
}
<commit_msg>call render in assertion tags (#1642)<commit_after>const rawRender = require('../raw_render')

module.exports = function yields (hexo, args) {
  // {% requirements parent cy.clearCookies %}
  // {% requirements blurability .blur %}
  // {% requirements focusability .blur %}
  // {% requirements checkability .click %}
  // {% requirements dom .click %}
  // {% requirements dom .children %}

  const type = args[0]
  const cmd = `<code>${args[1]}()</code>`

  /* eslint-disable commas */
  const waitAssertions = `${cmd} will automatically wait for assertions you've chained to pass`

  /* eslint-disable commas */
  const retryAssertions = `${cmd} will automatically {% url "retry" retry-ability %} until assertions you've chained all pass`

  /* eslint-disable quotes */
  const exist = `${cmd} will automatically {% url "retry" retry-ability %} until the element(s) {% url 'exist in the DOM' introduction-to-cypress#Default-Assertions %}`

  /* eslint-disable quotes */
  const actionable = `${cmd} will automatically wait for the element to reach an {% url 'actionable state' interacting-with-elements %}`

  const render = (str) => {
    return rawRender.call(this, hexo, str)
  }

  const none = () => {
    return `

${cmd} cannot have any assertions chained.

`
  }

  const wait = () => {
    return `

${waitAssertions}.

`
  }

  const retry = () => {
    return render(`

${retryAssertions}.

`)
  }

  const once = () => {
    return render(`

${cmd} will only run assertions you've chained once, and will not {% url "retry" retry-ability %}.

`)
  }

  const utility = () => {
    return `

${cmd} is a utility command.

${cmd} will not run assertions. Assertions will pass through as if this command did not exist.

`
  }

  const its = () => {
    return render(`

${cmd} will automatically {% url "retry" retry-ability %} itself until the property exists on the subject.

${retryAssertions}.

`)
  }

  const existence = () => {
    return render(`

${exist}.

${retryAssertions}.

`)
  }

  const actions = () => {
    return render(`

${actionable}.

${waitAssertions}.

`)
  }

  switch (type) {
    case 'none':
      return none()
    case 'once':
      return once()
    case 'wait':
      return wait()
    case 'retry':
      return retry()
    case 'utility':
      return utility()
    case 'its':
      return its()
    case 'existence':
      return existence()
    case 'actions':
      return actions()
    default:
      // error when an invalid usage option was provided
      throw new Error(`{% assertions %} tag helper was provided an invalid option: ${type}`)
  }
}
<|endoftext|>


<commit_before>(function () {
    mailcheckService.$inject = [];
    function mailcheckService() {
        var Mailcheck = {
            domainThreshold: 2,
            secondLevelThreshold: 2,
            topLevelThreshold: 2,

            defaultDomains: ['msn.com', 'bellsouth.net',
                'telus.net', 'comcast.net', 'optusnet.com.au',
                'earthlink.net', 'qq.com', 'sky.com', 'icloud.com',
                'mac.com', 'sympatico.ca', 'googlemail.com',
                'att.net', 'xtra.co.nz', 'web.de',
                'cox.net', 'gmail.com', 'ymail.com',
                'aim.com', 'rogers.com', 'verizon.net',
                'rocketmail.com', 'google.com', 'optonline.net',
                'sbcglobal.net', 'aol.com', 'me.com', 'btinternet.com',
                'charter.net', 'shaw.ca'],

            defaultSecondLevelDomains: ["yahoo", "hotmail", "mail", "live", "outlook", "gmx"],

            defaultTopLevelDomains: ["com", "com.au", "com.tw", "ca", "co.nz", "co.uk", "de",
                "fr", "it", "ru", "net", "org", "edu", "gov", "jp", "nl", "kr", "se", "eu",
                "ie", "co.il", "us", "at", "be", "dk", "hk", "es", "gr", "ch", "no", "cz",
                "in", "net", "net.au", "info", "biz", "mil", "co.jp", "sg", "hu", "uk"],

            run: function (opts) {
                opts.domains = opts.domains || Mailcheck.defaultDomains;
                opts.secondLevelDomains = opts.secondLevelDomains || Mailcheck.defaultSecondLevelDomains;
                opts.topLevelDomains = opts.topLevelDomains || Mailcheck.defaultTopLevelDomains;
                opts.distanceFunction = opts.distanceFunction || Mailcheck.sift4Distance;

                var defaultCallback = function (result) { return result; };
                var suggestedCallback = opts.suggested || defaultCallback;
                var emptyCallback = opts.empty || defaultCallback;

                var result = Mailcheck.suggest(Mailcheck.encodeEmail(opts.email), opts.domains, opts.secondLevelDomains, opts.topLevelDomains, opts.distanceFunction);

                // return result ? suggestedCallback(result) : emptyCallback();
                return result;
            },

            suggest: function (email, domains, secondLevelDomains, topLevelDomains, distanceFunction) {
                email = email.toLowerCase();

                var emailParts = this.splitEmail(email);

                if (secondLevelDomains && topLevelDomains) {
                    // If the email is a valid 2nd-level + top-level, do not suggest anything.
                    if (secondLevelDomains.indexOf(emailParts.secondLevelDomain) !== -1 && topLevelDomains.indexOf(emailParts.topLevelDomain) !== -1) {
                        return false;
                    }
                }

                var closestDomain = this.findClosestDomain(emailParts.domain, domains, distanceFunction, this.domainThreshold);

                if (closestDomain) {
                    if (closestDomain == emailParts.domain) {
                        // The email address exactly matches one of the supplied domains; do not return a suggestion.
                        return false;
                    } else {
                        // The email address closely matches one of the supplied domains; return a suggestion
                        return { address: emailParts.address, domain: closestDomain, full: emailParts.address + "@" + closestDomain };
                    }
                }

                // The email address does not closely match one of the supplied domains
                var closestSecondLevelDomain = this.findClosestDomain(emailParts.secondLevelDomain, secondLevelDomains, distanceFunction, this.secondLevelThreshold);
                var closestTopLevelDomain = this.findClosestDomain(emailParts.topLevelDomain, topLevelDomains, distanceFunction, this.topLevelThreshold);

                if (emailParts.domain) {
                    closestDomain = emailParts.domain;
                    var rtrn = false;

                    if (closestSecondLevelDomain && closestSecondLevelDomain != emailParts.secondLevelDomain) {
                        // The email address may have a mispelled second-level domain; return a suggestion
                        closestDomain = closestDomain.replace(emailParts.secondLevelDomain, closestSecondLevelDomain);
                        rtrn = true;
                    }

                    if (closestTopLevelDomain && closestTopLevelDomain != emailParts.topLevelDomain && emailParts.secondLevelDomain !== '') {
                        // The email address may have a mispelled top-level domain; return a suggestion
                        closestDomain = closestDomain.replace(new RegExp(emailParts.topLevelDomain + "$"), closestTopLevelDomain);
                        rtrn = true;
                    }

                    if (rtrn) {
                        return { address: emailParts.address, domain: closestDomain, full: emailParts.address + "@" + closestDomain };
                    }
                }

                /* The email address exactly matches one of the supplied domains, does not closely
                 * match any domain and does not appear to simply have a mispelled top-level domain,
                 * or is an invalid email address; do not return a suggestion.
                 */
                return false;
            },

            findClosestDomain: function (domain, domains, distanceFunction, threshold) {
                threshold = threshold || this.topLevelThreshold;
                var dist;
                var minDist = Infinity;
                var closestDomain = null;

                if (!domain || !domains) {
                    return false;
                }
                if (!distanceFunction) {
                    distanceFunction = this.sift4Distance;
                }

                for (var i = 0; i < domains.length; i++) {
                    if (domain === domains[i]) {
                        return domain;
                    }
                    dist = distanceFunction(domain, domains[i]);
                    if (dist < minDist) {
                        minDist = dist;
                        closestDomain = domains[i];
                    }
                }

                if (minDist <= threshold && closestDomain !== null) {
                    return closestDomain;
                } else {
                    return false;
                }
            },

            sift4Distance: function (s1, s2, maxOffset) {
                // sift4: https://siderite.blogspot.com/2014/11/super-fast-and-accurate-string-distance.html
                if (maxOffset === undefined) {
                    maxOffset = 5; //default
                }

                if (!s1 || !s1.length) {
                    if (!s2) {
                        return 0;
                    }
                    return s2.length;
                }

                if (!s2 || !s2.length) {
                    return s1.length;
                }

                var l1 = s1.length;
                var l2 = s2.length;

                var c1 = 0;  //cursor for string 1
                var c2 = 0;  //cursor for string 2
                var lcss = 0;  //largest common subsequence
                var local_cs = 0; //local common substring
                var trans = 0;  //number of transpositions ('ab' vs 'ba')
                var offset_arr = [];  //offset pair array, for computing the transpositions

                while ((c1 < l1) && (c2 < l2)) {
                    if (s1.charAt(c1) == s2.charAt(c2)) {
                        local_cs++;
                        var isTrans = false;
                        //see if current match is a transposition
                        var i = 0;
                        while (i < offset_arr.length) {
                            var ofs = offset_arr[i];
                            if (c1 <= ofs.c1 || c2 <= ofs.c2) {
                                // when two matches cross, the one considered a transposition is the one with the largest difference in offsets
                                isTrans = Math.abs(c2 - c1) >= Math.abs(ofs.c2 - ofs.c1);
                                if (isTrans) {
                                    trans++;
                                } else {
                                    if (!ofs.trans) {
                                        ofs.trans = true;
                                        trans++;
                                    }
                                }
                                break;
                            } else {
                                if (c1 > ofs.c2 && c2 > ofs.c1) {
                                    offset_arr.splice(i, 1);
                                } else {
                                    i++;
                                }
                            }
                        }
                        offset_arr.push({
                            c1: c1,
                            c2: c2,
                            trans: isTrans
                        });
                    } else {
                        lcss += local_cs;
                        local_cs = 0;
                        if (c1 != c2) {
                            c1 = c2 = Math.min(c1, c2);  //using min allows the computation of transpositions
                        }
                        //if matching characters are found, remove 1 from both cursors (they get incremented at the end of the loop)
                        //so that we can have only one code block handling matches
                        for (var j = 0; j < maxOffset && (c1 + j < l1 || c2 + j < l2); j++) {
                            if ((c1 + j < l1) && (s1.charAt(c1 + j) == s2.charAt(c2))) {
                                c1 += j - 1;
                                c2--;
                                break;
                            }
                            if ((c2 + j < l2) && (s1.charAt(c1) == s2.charAt(c2 + j))) {
                                c1--;
                                c2 += j - 1;
                                break;
                            }
                        }
                    }
                    c1++;
                    c2++;
                    // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly
                    if ((c1 >= l1) || (c2 >= l2)) {
                        lcss += local_cs;
                        local_cs = 0;
                        c1 = c2 = Math.min(c1, c2);
                    }
                }
                lcss += local_cs;
                return Math.round(Math.max(l1, l2) - lcss + trans); //add the cost of transpositions to the final result
            },

            splitEmail: function (email) {
                email = email !== null ? (email.replace(/^\s*/, '').replace(/\s*$/, '')) : null; // trim() not exist in old IE!
                var parts = email.split('@');

                if (parts.length < 2) {
                    return false;
                }

                for (var i = 0; i < parts.length; i++) {
                    if (parts[i] === '') {
                        return false;
                    }
                }

                var domain = parts.pop();
                var domainParts = domain.split('.');
                var sld = '';
                var tld = '';

                if (domainParts.length === 0) {
                    // The address does not have a top-level domain
                    return false;
                } else if (domainParts.length == 1) {
                    // The address has only a top-level domain (valid under RFC)
                    tld = domainParts[0];
                } else {
                    // The address has a domain and a top-level domain
                    sld = domainParts[0];
                    for (var j = 1; j < domainParts.length; j++) {
                        tld += domainParts[j] + '.';
                    }
                    tld = tld.substring(0, tld.length - 1);
                }

                return {
                    topLevelDomain: tld,
                    secondLevelDomain: sld,
                    domain: domain,
                    address: parts.join('@')
                };
            },

            // Encode the email address to prevent XSS but leave in valid
            // characters, following this official spec:
            // http://en.wikipedia.org/wiki/Email_address#Syntax
            encodeEmail: function (email) {
                var result = encodeURI(email);
                result = result.replace('%20', ' ').replace('%25', '%').replace('%5E', '^')
                    .replace('%60', '`').replace('%7B', '{').replace('%7C', '|')
                    .replace('%7D', '}');
                return result;
            }
        };
        return Mailcheck;
    }

    angular
        .module('myApp')
        .factory('mailcheckService', mailcheckService);

} ());<commit_msg>changed mailcheck factory name<commit_after>(function () {
    mailcheckFactory.$inject = [];
    function mailcheckFactory() {
        var Mailcheck = {
            domainThreshold: 2,
            secondLevelThreshold: 2,
            topLevelThreshold: 2,

            defaultDomains: ['msn.com', 'bellsouth.net',
                'telus.net', 'comcast.net', 'optusnet.com.au',
                'earthlink.net', 'qq.com', 'sky.com', 'icloud.com',
                'mac.com', 'sympatico.ca', 'googlemail.com',
                'att.net', 'xtra.co.nz', 'web.de',
                'cox.net', 'gmail.com', 'ymail.com',
                'aim.com', 'rogers.com', 'verizon.net',
                'rocketmail.com', 'google.com', 'optonline.net',
                'sbcglobal.net', 'aol.com', 'me.com', 'btinternet.com',
                'charter.net', 'shaw.ca'],

            defaultSecondLevelDomains: ["yahoo", "hotmail", "mail", "live", "outlook", "gmx"],

            defaultTopLevelDomains: ["com", "com.au", "com.tw", "ca", "co.nz", "co.uk", "de",
                "fr", "it", "ru", "net", "org", "edu", "gov", "jp", "nl", "kr", "se", "eu",
                "ie", "co.il", "us", "at", "be", "dk", "hk", "es", "gr", "ch", "no", "cz",
                "in", "net", "net.au", "info", "biz", "mil", "co.jp", "sg", "hu", "uk"],

            run: function (opts) {
                opts.domains = opts.domains || Mailcheck.defaultDomains;
                opts.secondLevelDomains = opts.secondLevelDomains || Mailcheck.defaultSecondLevelDomains;
                opts.topLevelDomains = opts.topLevelDomains || Mailcheck.defaultTopLevelDomains;
                opts.distanceFunction = opts.distanceFunction || Mailcheck.sift4Distance;

                var defaultCallback = function (result) { return result; };
                var suggestedCallback = opts.suggested || defaultCallback;
                var emptyCallback = opts.empty || defaultCallback;

                var result = Mailcheck.suggest(Mailcheck.encodeEmail(opts.email), opts.domains, opts.secondLevelDomains, opts.topLevelDomains, opts.distanceFunction);

                // return result ? suggestedCallback(result) : emptyCallback();
                return result;
            },

            suggest: function (email, domains, secondLevelDomains, topLevelDomains, distanceFunction) {
                email = email.toLowerCase();

                var emailParts = this.splitEmail(email);

                if (secondLevelDomains && topLevelDomains) {
                    // If the email is a valid 2nd-level + top-level, do not suggest anything.
                    if (secondLevelDomains.indexOf(emailParts.secondLevelDomain) !== -1 && topLevelDomains.indexOf(emailParts.topLevelDomain) !== -1) {
                        return false;
                    }
                }

                var closestDomain = this.findClosestDomain(emailParts.domain, domains, distanceFunction, this.domainThreshold);

                if (closestDomain) {
                    if (closestDomain == emailParts.domain) {
                        // The email address exactly matches one of the supplied domains; do not return a suggestion.
                        return false;
                    } else {
                        // The email address closely matches one of the supplied domains; return a suggestion
                        return { address: emailParts.address, domain: closestDomain, full: emailParts.address + "@" + closestDomain };
                    }
                }

                // The email address does not closely match one of the supplied domains
                var closestSecondLevelDomain = this.findClosestDomain(emailParts.secondLevelDomain, secondLevelDomains, distanceFunction, this.secondLevelThreshold);
                var closestTopLevelDomain = this.findClosestDomain(emailParts.topLevelDomain, topLevelDomains, distanceFunction, this.topLevelThreshold);

                if (emailParts.domain) {
                    closestDomain = emailParts.domain;
                    var rtrn = false;

                    if (closestSecondLevelDomain && closestSecondLevelDomain != emailParts.secondLevelDomain) {
                        // The email address may have a mispelled second-level domain; return a suggestion
                        closestDomain = closestDomain.replace(emailParts.secondLevelDomain, closestSecondLevelDomain);
                        rtrn = true;
                    }

                    if (closestTopLevelDomain && closestTopLevelDomain != emailParts.topLevelDomain && emailParts.secondLevelDomain !== '') {
                        // The email address may have a mispelled top-level domain; return a suggestion
                        closestDomain = closestDomain.replace(new RegExp(emailParts.topLevelDomain + "$"), closestTopLevelDomain);
                        rtrn = true;
                    }

                    if (rtrn) {
                        return { address: emailParts.address, domain: closestDomain, full: emailParts.address + "@" + closestDomain };
                    }
                }

                /* The email address exactly matches one of the supplied domains, does not closely
                 * match any domain and does not appear to simply have a mispelled top-level domain,
                 * or is an invalid email address; do not return a suggestion.
                 */
                return false;
            },

            findClosestDomain: function (domain, domains, distanceFunction, threshold) {
                threshold = threshold || this.topLevelThreshold;
                var dist;
                var minDist = Infinity;
                var closestDomain = null;

                if (!domain || !domains) {
                    return false;
                }
                if (!distanceFunction) {
                    distanceFunction = this.sift4Distance;
                }

                for (var i = 0; i < domains.length; i++) {
                    if (domain === domains[i]) {
                        return domain;
                    }
                    dist = distanceFunction(domain, domains[i]);
                    if (dist < minDist) {
                        minDist = dist;
                        closestDomain = domains[i];
                    }
                }

                if (minDist <= threshold && closestDomain !== null) {
                    return closestDomain;
                } else {
                    return false;
                }
            },

            sift4Distance: function (s1, s2, maxOffset) {
                // sift4: https://siderite.blogspot.com/2014/11/super-fast-and-accurate-string-distance.html
                if (maxOffset === undefined) {
                    maxOffset = 5; //default
                }

                if (!s1 || !s1.length) {
                    if (!s2) {
                        return 0;
                    }
                    return s2.length;
                }

                if (!s2 || !s2.length) {
                    return s1.length;
                }

                var l1 = s1.length;
                var l2 = s2.length;

                var c1 = 0;  //cursor for string 1
                var c2 = 0;  //cursor for string 2
                var lcss = 0;  //largest common subsequence
                var local_cs = 0; //local common substring
                var trans = 0;  //number of transpositions ('ab' vs 'ba')
                var offset_arr = [];  //offset pair array, for computing the transpositions

                while ((c1 < l1) && (c2 < l2)) {
                    if (s1.charAt(c1) == s2.charAt(c2)) {
                        local_cs++;
                        var isTrans = false;
                        //see if current match is a transposition
                        var i = 0;
                        while (i < offset_arr.length) {
                            var ofs = offset_arr[i];
                            if (c1 <= ofs.c1 || c2 <= ofs.c2) {
                                // when two matches cross, the one considered a transposition is the one with the largest difference in offsets
                                isTrans = Math.abs(c2 - c1) >= Math.abs(ofs.c2 - ofs.c1);
                                if (isTrans) {
                                    trans++;
                                } else {
                                    if (!ofs.trans) {
                                        ofs.trans = true;
                                        trans++;
                                    }
                                }
                                break;
                            } else {
                                if (c1 > ofs.c2 && c2 > ofs.c1) {
                                    offset_arr.splice(i, 1);
                                } else {
                                    i++;
                                }
                            }
                        }
                        offset_arr.push({
                            c1: c1,
                            c2: c2,
                            trans: isTrans
                        });
                    } else {
                        lcss += local_cs;
                        local_cs = 0;
                        if (c1 != c2) {
                            c1 = c2 = Math.min(c1, c2);  //using min allows the computation of transpositions
                        }
                        //if matching characters are found, remove 1 from both cursors (they get incremented at the end of the loop)
                        //so that we can have only one code block handling matches
                        for (var j = 0; j < maxOffset && (c1 + j < l1 || c2 + j < l2); j++) {
                            if ((c1 + j < l1) && (s1.charAt(c1 + j) == s2.charAt(c2))) {
                                c1 += j - 1;
                                c2--;
                                break;
                            }
                            if ((c2 + j < l2) && (s1.charAt(c1) == s2.charAt(c2 + j))) {
                                c1--;
                                c2 += j - 1;
                                break;
                            }
                        }
                    }
                    c1++;
                    c2++;
                    // this covers the case where the last match is on the last token in list, so that it can compute transpositions correctly
                    if ((c1 >= l1) || (c2 >= l2)) {
                        lcss += local_cs;
                        local_cs = 0;
                        c1 = c2 = Math.min(c1, c2);
                    }
                }
                lcss += local_cs;
                return Math.round(Math.max(l1, l2) - lcss + trans); //add the cost of transpositions to the final result
            },

            splitEmail: function (email) {
                email = email !== null ? (email.replace(/^\s*/, '').replace(/\s*$/, '')) : null; // trim() not exist in old IE!
                var parts = email.split('@');

                if (parts.length < 2) {
                    return false;
                }

                for (var i = 0; i < parts.length; i++) {
                    if (parts[i] === '') {
                        return false;
                    }
                }

                var domain = parts.pop();
                var domainParts = domain.split('.');
                var sld = '';
                var tld = '';

                if (domainParts.length === 0) {
                    // The address does not have a top-level domain
                    return false;
                } else if (domainParts.length == 1) {
                    // The address has only a top-level domain (valid under RFC)
                    tld = domainParts[0];
                } else {
                    // The address has a domain and a top-level domain
                    sld = domainParts[0];
                    for (var j = 1; j < domainParts.length; j++) {
                        tld += domainParts[j] + '.';
                    }
                    tld = tld.substring(0, tld.length - 1);
                }

                return {
                    topLevelDomain: tld,
                    secondLevelDomain: sld,
                    domain: domain,
                    address: parts.join('@')
                };
            },

            // Encode the email address to prevent XSS but leave in valid
            // characters, following this official spec:
            // http://en.wikipedia.org/wiki/Email_address#Syntax
            encodeEmail: function (email) {
                var result = encodeURI(email);
                result = result.replace('%20', ' ').replace('%25', '%').replace('%5E', '^')
                    .replace('%60', '`').replace('%7B', '{').replace('%7C', '|')
                    .replace('%7D', '}');
                return result;
            }
        };
        return Mailcheck;
    }

    angular
        .module('myApp')
        .factory('mailcheckFactory', mailcheckFactory);

} ());<|endoftext|>


<commit_before>/**
 *
 */
define(function (require, exports, module) {

    var zhCN = require('datatableZh');
    var editorCN = require('i18n');
    exports.index = function ($, tableId) {
        var editor = new $.fn.dataTable.Editor({
            ajax: {
                create: {
                    type: 'POST',
                    url: '/customer/stock',
                    data: {_token: $('meta[name="_token"]').attr('content')},
                },
                edit: {
                    type: 'PUT',
                    url: '/customer/stock/_id_',
                    data: {_token: $('meta[name="_token"]').attr('content')},
                },
                remove: {
                    type: 'DELETE',
                    url: '/customer/stock/_id_',
                    data: {_token: $('meta[name="_token"]').attr('content')},
                }
            },
            i18n: editorCN,
            table: "#" + tableId,
            idSrc: 'id',
            fields: [
                {'label': 'fbase_eqty', 'name': 'fbase_eqty',},
                {'label': 'fcreate_date', 'name': 'fcreate_date',},
                {'label': 'fcreator_id', 'name': 'fcreator_id',},
                {'label': 'fdocument_status', 'name': 'fdocument_status',},
                {'label': 'feqty', 'name': 'feqty',},
                {'label': 'fhqty', 'name': 'fhqty',},
                {'label': 'flog_id', 'name': 'flog_id',},
                {'label': 'fmaterial_id', 'name': 'fmaterial_id',},
                {'label': 'fmodify_date', 'name': 'fmodify_date',},
                {'label': 'fmodify_id', 'name': 'fmodify_id',},
                {'label': 'fold_eqty', 'name': 'fold_eqty',},
                {'label': 'fsale_hqty', 'name': 'fsale_hqty',},
                {'label': 'fstore_id', 'name': 'fstore_id',},
                {'label': 'ftime', 'name': 'ftime',},
            ]
        });

        var table = $("#" + tableId).DataTable({
            dom: "lBfrtip",
            language: zhCN,
            processing: true,
            serverSide: true,
            select: true,
            paging: true,
            rowId: "id",
            ajax: '/customer/stock/pagination',
            columns: [
                {'data': 'id'},
                {
                    'data': 'fstore_id',
                    render: function (data, type, full) {
                        if (full.store != null)
                            return full.store.fnumber
                        else
                            return "";
                    }
                },
                {
                    'data': 'femp_id',
                    render: function (data, type, full) {
                        if (full.store != null)
                            return full.store.ffullname
                        else
                            return "";
                    }
                },
                {'data': 'ftime'},
                {
                    'data': 'fstore_id',
                    render: function (data, type, full) {
                        if (full.store.employee != null)
                            return full.store.employee.fnumber
                        else
                            return "";
                    }
                },
                {
                    'data': 'flog_id',
                    render: function (data, type, full) {
                        if (full.store.employee != null)
                            return full.store.employee.fname
                        else
                            return "";
                    }
                },
                {
                    'data': 'fmaterial_id',
                    render: function (data, type, full) {
                        if (full.material != null)
                            return full.material.fnumber
                        else
                            return "";
                    }
                },
                {
                    'data': 'fcreator_id',
                    render: function (data, type, full) {
                        if (full.material != null)
                            return full.material.fname
                        else
                            return "";
                    }
                },
                {
                    'data': 'fmodify_id',
                    render: function (data, type, full) {
                        if (full.material != null)
                            return full.material.fspecification
                        else
                            return "";
                    }
                },
                {'data': 'fhqty'},
                {'data': 'feqty'},
                {'data': 'fsale_hqty'},
                {
                    "data": "fdocument_status",
                    render: function ( data, type, full ) {
                        return document_status(data);
                    }
                },
            ],
            columnDefs: [
                {
                    "targets": [0],
                    "visible": false
                }
            ],
            buttons: [
                // { text: '新增', action: function () { }  },
                // { text: '编辑', className: 'edit', enabled: false },
                // { text: '删除', className: 'delete', enabled: false },
                // {extend: "create", text: '新增', editor: editor},
                // {extend: "edit", text: '编辑', editor: editor},
                {extend: "remove", text: '删除', editor: editor},
                {extend: 'excel', text: '导出Excel'},
                {extend: 'print', text: '打印'},
                {extend: 'colvis', text: '列显示'},
                { text: '审核',className: 'check', enabled: false },
                { text: '反审核',className: 'uncheck', enabled: false },
            ]
        });

        table.on( 'select', rowSelect).on( 'deselect', rowSelect);

        function rowSelect() {
            checkEditEnabble(table,['.edit','.check','.buttons-remove'],['.uncheck']);
        }

        //审核
        $(".check").on('click',function () {
            dataCheck(table,'/customer/stock/check');
        })

        $(".uncheck").on('click',function () {
            dataCheck(table,'/customer/stock/uncheck');
        })

    }

});<commit_msg>bug fix<commit_after>/**
 *
 */
define(function (require, exports, module) {

    var zhCN = require('datatableZh');
    var editorCN = require('i18n');
    exports.index = function ($, tableId) {
        var editor = new $.fn.dataTable.Editor({
            ajax: {
                create: {
                    type: 'POST',
                    url: '/customer/stock',
                    data: {_token: $('meta[name="_token"]').attr('content')},
                },
                edit: {
                    type: 'PUT',
                    url: '/customer/stock/_id_',
                    data: {_token: $('meta[name="_token"]').attr('content')},
                },
                remove: {
                    type: 'DELETE',
                    url: '/customer/stock/_id_',
                    data: {_token: $('meta[name="_token"]').attr('content')},
                }
            },
            i18n: editorCN,
            table: "#" + tableId,
            idSrc: 'id',
            fields: [
                {'label': 'fbase_eqty', 'name': 'fbase_eqty',},
                {'label': 'fcreate_date', 'name': 'fcreate_date',},
                {'label': 'fcreator_id', 'name': 'fcreator_id',},
                {'label': 'fdocument_status', 'name': 'fdocument_status',},
                {'label': 'feqty', 'name': 'feqty',},
                {'label': 'fhqty', 'name': 'fhqty',},
                {'label': 'flog_id', 'name': 'flog_id',},
                {'label': 'fmaterial_id', 'name': 'fmaterial_id',},
                {'label': 'fmodify_date', 'name': 'fmodify_date',},
                {'label': 'fmodify_id', 'name': 'fmodify_id',},
                {'label': 'fold_eqty', 'name': 'fold_eqty',},
                {'label': 'fsale_hqty', 'name': 'fsale_hqty',},
                {'label': 'fstore_id', 'name': 'fstore_id',},
                {'label': 'ftime', 'name': 'ftime',},
            ]
        });

        var table = $("#" + tableId).DataTable({
            dom: "lBfrtip",
            language: zhCN,
            processing: true,
            serverSide: true,
            select: true,
            paging: true,
            rowId: "id",
            ajax: '/customer/stock/pagination',
            columns: [
                {'data': 'id'},
                {
                    'data': 'fstore_id',
                    render: function (data, type, full) {
                        if (full.store != null)
                            return full.store.fnumber
                        else
                            return "";
                    }
                },
                {
                    'data': 'femp_id',
                    render: function (data, type, full) {
                        if (full.store != null)
                            return full.store.ffullname
                        else
                            return "";
                    }
                },
                {'data': 'ftime'},
                {
                    'data': 'fstore_id',
                    render: function (data, type, full) {
                        if (full.store.employee != null)
                            return full.store.employee.fnumber
                        else
                            return "";
                    }
                },
                {
                    'data': 'flog_id',
                    render: function (data, type, full) {
                        if (full.store.employee != null)
                            return full.store.employee.fname
                        else
                            return "";
                    }
                },
                {
                    'data': 'fmaterial_id',
                    render: function (data, type, full) {
                        if (full.material != null)
                            return full.material.fnumber
                        else
                            return "";
                    }
                },
                {
                    'data': 'fcreator_id',
                    render: function (data, type, full) {
                        if (full.material != null)
                            return full.material.fname
                        else
                            return "";
                    }
                },
                {
                    'data': 'fmodify_id',
                    render: function (data, type, full) {
                        if (full.material != null)
                            return full.material.fspecification
                        else
                            return "";
                    }
                },
                {'data': 'fhqty'},
                {'data': 'feqty'},
                {'data': 'fsale_hqty'},
                {
                    "data": "fdocument_status",
                    render: function ( data, type, full ) {
                        return document_status(data);
                    }
                },
            ],
            columnDefs: [
                {
                    "targets": [0],
                    "visible": false
                }
            ],
            buttons: [
                // { text: '新增', action: function () { }  },
                // { text: '编辑', className: 'edit', enabled: false },
                // { text: '删除', className: 'delete', enabled: false },
                // {extend: "create", text: '新增', editor: editor},
                // {extend: "edit", text: '编辑', editor: editor},
                {extend: "remove", text: '删除', editor: editor},
                {extend: 'excel', text: '导出Excel'},
                {extend: 'print', text: '打印'},
                {extend: 'colvis', text: '列显示'},
                { text: '审核',className: 'check', enabled: false },
                { text: '反审核',className: 'uncheck', enabled: false },
            ],
            order: [[ 3, 'desc' ]]
        });

        table.on( 'select', rowSelect).on( 'deselect', rowSelect);

        function rowSelect() {
            checkEditEnabble(table,['.edit','.check','.buttons-remove'],['.uncheck']);
        }

        //审核
        $(".check").on('click',function () {
            dataCheck(table,'/customer/stock/check');
        })

        $(".uncheck").on('click',function () {
            dataCheck(table,'/customer/stock/uncheck');
        })

    }

});<|endoftext|>