<commit_before>function activateGoggles() {
  (function($){
      if (window.goggled) { return; }
      window.goggled = true;

      function bind(bindee, action) {
        return function() {
          return action.apply(bindee, Array.prototype.slice.call(arguments));
        };
      }

      // SHAPES
      function Shape(t, r,g,b,a) {
        // Each shape looks like this:
        // {p: [ [x,y], [x,y], [x,y], ...], points
        //  t: 5                            thickness
        //  r: 250, g: 200, b: 125, a: 0.5  color
        // }
        // give it a position, thickness, and rgba colors
        this.t = t;
        this.r=r;
        this.g=g;
        this.b=b;
        this.a=a;
        this.p = [];
      }
      Shape.prototype.appendPoint = function(point) {
        // Append a point to this shape.
        this.p.push(
          [Math.round(point[0]*10)/10, Math.round(point[1]*10)/10]
        );
      };
      Shape.prototype.drawLast = function(ctx) {
        // Given a canvas, draw the last line of the shape
        if (this.p.length >= 2) {
          var a = this.p[this.p.length-2],
              b = this.p[this.p.length-1];
          // draws part of the shape
          ctx.strokeStyle = "rgba("+this.r+","+this.g+","+this.b+","+this.a+")";
          ctx.lineWidth = this.t;
          ctx.lineCap = "round";
          ctx.beginPath();
          ctx.moveTo.apply(ctx, a);
          ctx.lineTo.apply(ctx, b);
          ctx.stroke();
        }
      };
      Shape.prototype.draw = function(ctx) {
        // Draw a given shape if it is in view.
//      if ((p.x + shape.s) > 0 &&
//          (p.y + shape.s) > 0 &&
//          (p.x - shape.s) < canvas.width &&
//          (p.y - shape.s) < canvas.height) {
          ctx.strokeStyle = "rgba("+this.r+","+this.g+","+this.b+","+this.a+")";
          ctx.lineWidth = this.t;
          ctx.lineCap = "round";
          ctx.beginPath();
          ctx.moveTo.apply(ctx, this.p[0]);
          for (var i=0,l=this.p.length; i<l; i++) {
            ctx.lineTo.apply(ctx, this.p[i]);
          }
          ctx.stroke();
//       }
      };

      // GOGGLES
      function Goggles() {
        // Here is our goggles object.

        this.canvas = $("<canvas>").css({
          position: "fixed",
          "z-index": "100000",
          top: "0",
          left: "0"
        }).appendTo(document.body)[0];

        this.ctx = this.canvas.getContext('2d');

        this.shapes = [];
        // the list of shapes to draw.
        this.curshape = null;

        // Events
        this.canvas.onmousedown = bind(this, function(ev) {
          this.curshape = new Shape(5, 0,0,0,1);
        });
        this.canvas.onmouseup = bind(this, function(ev) {
          this.shapes.push(this.curshape);
          this.curshape = null;
        });
        this.canvas.onmousemove = bind(this, function(ev) {
          if (this.curshape) {
            this.curshape.appendPoint(
              this.untransform(this.pointsFromEv(ev)));
            this.curshape.drawLast(this.ctx);
          }
        });

        // Window resize and scroll handlers
        this.resizeTimer = null;
        window.onresize = bind(this, function() {
          // Resize later
          clearTimeout(this.resizeTimer);
          this.resizeTimer = setTimeout(bind(this, this.resizeCanvas), 100);
        });
        window.onscroll = bind(this, this.redraw);
        this.resizeCanvas();
      }

      // Point transformation functions
      // Establish a new coordinate system. (0, 0) is at the top MIDDLE of
      // the page, +x is right and -x is left.
      // This accomodates pages that have fixed-width or centered layouts.
      // todo: actually I would really like this to be relative to either
      // the left of the content or the middle of the page.
      Goggles.prototype.transform = function(p) {
        // Given an absolute point in our new coordinate system, return the
        // point's position on the screen
        return [
          p[0]-window.scrollX + (this.canvas.width/2),
          p[1]-window.scrollY
        ];
      };
      Goggles.prototype.untransform = function(p) {
        // Given an point wrt the screen, return the point's absolute position
        // wrt our coordinate system
        return [
          p[0]+window.scrollX - (this.canvas.width/2),
          p[1]+window.scrollY
        ];
      };

      // Drawing functions

      Goggles.prototype.redraw = function() {
        // Redraw entire canvas
        var ctx = this.ctx;
        // clear
        this.resetCanvasXform();

        for (var i=0,l=this.shapes.length; i<l; i++) {
          this.shapes[i].draw(ctx);
        }

      };

      // Event handling
      Goggles.prototype.pointsFromEv = function(ev) {
        if ('clientX' in ev) { // Firefox
          return [ev.clientX, ev.clientY];
        } else if ('offsetX' in ev) { // Opera
          return [ev.offsetX, ev.offsetY];
        }
      };

      //////// INIT
      Goggles.prototype.resetCanvasXform = function() {
        this.ctx.setTransform(1,0,
                              0,1,  0, 0);
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.setTransform(1,0,
                              0,1,
          this.canvas.width/2-window.scrollX,
          -window.scrollY);
      };
      Goggles.prototype.resizeCanvas = function() {
        // Fix the canvas when resized
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        this.redraw();
      };

      window.goggles = new Goggles();

  })(jQuery);
}

if (typeof jQuery == 'undefined') {
  var jQ = document.createElement('script');
  jQ.type = 'text/javascript';
  jQ.onload=activateGoggles;
  jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
  document.body.appendChild(jQ);
} else {
  activateGoggles();
}
<commit_msg>stoppable goggles<commit_after>function activateGoggles() {
  (function($){
      if (window.goggles) { window.goggles.stop(function(){window.goggles = null;}); }

      function bind(bindee, action) {
        return function() {
          return action.apply(bindee, Array.prototype.slice.call(arguments));
        };
      }

      // SHAPES
      function Shape(t, r,g,b,a) {
        // Each shape looks like this:
        // {p: [ [x,y], [x,y], [x,y], ...], points
        //  t: 5                            thickness
        //  r: 250, g: 200, b: 125, a: 0.5  color
        // }
        // give it a position, thickness, and rgba colors
        this.t = t;
        this.r=r;
        this.g=g;
        this.b=b;
        this.a=a;
        this.p = [];
      }
      Shape.prototype.appendPoint = function(point) {
        // Append a point to this shape.
        this.p.push(
          [Math.round(point[0]*10)/10, Math.round(point[1]*10)/10]
        );
      };
      Shape.prototype.drawLast = function(ctx) {
        // Given a canvas, draw the last line of the shape
        if (this.p.length >= 2) {
          var a = this.p[this.p.length-2],
              b = this.p[this.p.length-1];
          // draws part of the shape
          ctx.strokeStyle = "rgba("+this.r+","+this.g+","+this.b+","+this.a+")";
          ctx.lineWidth = this.t;
          ctx.lineCap = "round";
          ctx.beginPath();
          ctx.moveTo.apply(ctx, a);
          ctx.lineTo.apply(ctx, b);
          ctx.stroke();
        }
      };
      Shape.prototype.draw = function(ctx) {
        // Draw a given shape if it is in view.
//      if ((p.x + shape.s) > 0 &&
//          (p.y + shape.s) > 0 &&
//          (p.x - shape.s) < canvas.width &&
//          (p.y - shape.s) < canvas.height) {
          ctx.strokeStyle = "rgba("+this.r+","+this.g+","+this.b+","+this.a+")";
          ctx.lineWidth = this.t;
          ctx.lineCap = "round";
          ctx.beginPath();
          ctx.moveTo.apply(ctx, this.p[0]);
          for (var i=0,l=this.p.length; i<l; i++) {
            ctx.lineTo.apply(ctx, this.p[i]);
          }
          ctx.stroke();
//       }
      };

      // GOGGLES
      function Goggles() {
        // Here is our goggles object.

        this.canvas = $("<canvas>").css({
          position: "fixed",
          "z-index": "100000",
          top: "0",
          left: "0"
        }).appendTo(document.body)[0];

        this.ctx = this.canvas.getContext('2d');

        this.shapes = [];
        // the list of shapes to draw.
        this.curshape = null;

        // Events
        this.canvas.onmousedown = bind(this, function(ev) {
          this.curshape = new Shape(5, 0,0,0,1);
        });
        this.canvas.onmouseup = bind(this, function(ev) {
          this.shapes.push(this.curshape);
          this.curshape = null;
        });
        this.canvas.onmousemove = bind(this, function(ev) {
          if (this.curshape) {
            this.curshape.appendPoint(
              this.untransform(this.pointsFromEv(ev)));
            this.curshape.drawLast(this.ctx);
          }
        });

        // Window resize and scroll handlers
        this.resizeTimer = null;
        window.onresize = bind(this, function() {
          // Resize later
          clearTimeout(this.resizeTimer);
          this.resizeTimer = setTimeout(bind(this, this.resizeCanvas), 100);
        });
        window.onscroll = bind(this, this.redraw);
        this.resizeCanvas();
      }
      Goggles.prototype.stop = function(cb) {
        // Destroy a goggles object with optional callback
        window.onresize = null;
        window.onscroll = null;
        clearTimeout(this.resizeTimer);
        $(this.canvas).fadeOut('medium', function(){
            $(this.canvas).remove();
            cb();
          });
      };
      // Point transformation functions
      // Establish a new coordinate system. (0, 0) is at the top MIDDLE of
      // the page, +x is right and -x is left.
      // This accomodates pages that have fixed-width or centered layouts.
      // todo: actually I would really like this to be relative to either
      // the left of the content or the middle of the page.
      Goggles.prototype.transform = function(p) {
        // Given an absolute point in our new coordinate system, return the
        // point's position on the screen
        return [
          p[0]-window.scrollX + (this.canvas.width/2),
          p[1]-window.scrollY
        ];
      };
      Goggles.prototype.untransform = function(p) {
        // Given an point wrt the screen, return the point's absolute position
        // wrt our coordinate system
        return [
          p[0]+window.scrollX - (this.canvas.width/2),
          p[1]+window.scrollY
        ];
      };

      // Drawing functions
      Goggles.prototype.redraw = function() {
        // Redraw entire canvas
        var ctx = this.ctx;
        // clear
        this.resetCanvasXform();

        for (var i=0,l=this.shapes.length; i<l; i++) {
          this.shapes[i].draw(ctx);
        }

      };

      // Event handling
      Goggles.prototype.pointsFromEv = function(ev) {
        if ('clientX' in ev) { // Firefox
          return [ev.clientX, ev.clientY];
        } else if ('offsetX' in ev) { // Opera
          return [ev.offsetX, ev.offsetY];
        }
      };

      //////// INIT
      Goggles.prototype.resetCanvasXform = function() {
        this.ctx.setTransform(1,0,
                              0,1,  0, 0);
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.setTransform(1,0,
                              0,1,
          this.canvas.width/2-window.scrollX,
          -window.scrollY);
      };
      Goggles.prototype.resizeCanvas = function() {
        // Fix the canvas when resized
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        this.redraw();
      };

      window.goggles = new Goggles();

  })(jQuery);
}

if (typeof jQuery == 'undefined') {
  var jQ = document.createElement('script');
  jQ.type = 'text/javascript';
  jQ.onload=activateGoggles;
  jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
  document.body.appendChild(jQ);
} else {
  activateGoggles();
}
<|endoftext|>


<commit_before>const Path = require('path');
const Lab = require('lab');
const Sinon = require('sinon');
const MainCtrl = require(Path.join(process.cwd(), 'lib/modules/authorization/controllers/web/admin/main'));
const UserService = require(Path.join(process.cwd(), 'lib/modules/authorization/services/user'));
const RoleService = require(Path.join(process.cwd(), 'lib/modules/authorization/services/role'));
const ResourceService = require(Path.join(process.cwd(), 'lib/modules/authorization/services/resource'));

const { beforeEach, describe, expect, it } = exports.lab = Lab.script();

describe('Web Controller: main', () => {

    let requestStub;

    beforeEach(() => {

        requestStub = { log: Sinon.stub(), params: {} };
    });

    it('gets the main admin page', async (flags) => {

        // setup
        const stubView = Sinon.stub().withArgs('pages/admin', Sinon.match.object);
        const fakeToolkit = { view: stubView };
        const count = { users: 2, roles: 3, resources: 4 };
        const countUsersStub = Sinon.stub(UserService, 'count').resolves(count.users);
        const countRolesStub = Sinon.stub(RoleService, 'count').resolves(count.roles);
        const countResourcesStub = Sinon.stub(ResourceService, 'count').resolves(count.resources);
        flags.onCleanup = function() {
            countUsersStub.restore();
            countRolesStub.restore();
            countResourcesStub.restore();
        };

        // exercise
        await MainCtrl.getMain(requestStub, fakeToolkit);

        // validate
        expect(requestStub.log.calledOnce).to.be.true();
        expect(countUsersStub.calledOnce).to.be.true();
        expect(countRolesStub.calledOnce).to.be.true();
        expect(countResourcesStub.calledOnce).to.be.true();
        expect(fakeToolkit.view.calledOnce).to.be.true();
        expect(stubView.getCall(0).args[1].getAdminPartial).to.be.a.function();
        expect(stubView.getCall(0).args[1].count).to.equals(count);
    });
});

<commit_msg>added test for admin main view controller error<commit_after>const Path = require('path');
const Lab = require('lab');
const Sinon = require('sinon');
const MainCtrl = require(Path.join(process.cwd(), 'lib/modules/authorization/controllers/web/admin/main'));
const UserService = require(Path.join(process.cwd(), 'lib/modules/authorization/services/user'));
const RoleService = require(Path.join(process.cwd(), 'lib/modules/authorization/services/role'));
const ResourceService = require(Path.join(process.cwd(), 'lib/modules/authorization/services/resource'));
const NSError = require(Path.join(process.cwd(), 'lib/errors/nserror'));

const { beforeEach, describe, expect, it } = exports.lab = Lab.script();

describe('Web Controller: main', () => {

    let requestStub;

    beforeEach(() => {

        requestStub = { log: Sinon.stub(), params: {} };
    });

    it('gets the main admin page', async (flags) => {

        // setup
        const stubView = Sinon.stub().withArgs('pages/admin', Sinon.match.object);
        const fakeToolkit = { view: stubView };
        const count = { users: 2, roles: 3, resources: 4 };
        const countUsersStub = Sinon.stub(UserService, 'count').resolves(count.users);
        const countRolesStub = Sinon.stub(RoleService, 'count').resolves(count.roles);
        const countResourcesStub = Sinon.stub(ResourceService, 'count').resolves(count.resources);
        flags.onCleanup = function() {
            countUsersStub.restore();
            countRolesStub.restore();
            countResourcesStub.restore();
        };

        // exercise
        await MainCtrl.getMain(requestStub, fakeToolkit);

        // validate
        expect(requestStub.log.calledOnce).to.be.true();
        expect(countUsersStub.calledOnce).to.be.true();
        expect(countRolesStub.calledOnce).to.be.true();
        expect(countResourcesStub.calledOnce).to.be.true();
        expect(fakeToolkit.view.calledOnce).to.be.true();
        expect(stubView.getCall(0).args[1].getAdminPartial).to.be.a.function();
        expect(stubView.getCall(0).args[1].count).to.equals(count);
    });

    it('handles errors getting the main admin page', async (flags) => {

        // setup
        const count = { users: 2, resources: 4 };
        const countUsersStub = Sinon.stub(UserService, 'count').resolves(count.users);
        const countRolesStub = Sinon.stub(RoleService, 'count').rejects(NSError.RESOURCE_NOT_FOUND());
        const countResourcesStub = Sinon.stub(ResourceService, 'count').resolves(count.resources);
        flags.onCleanup = function() {
            countUsersStub.restore();
            countRolesStub.restore();
            countResourcesStub.restore();
        };

        // exercise and validate
        await expect(MainCtrl.getMain(requestStub, { view: () => { } })).to.reject(Error, NSError.RESOURCE_NOT_FOUND().message);
    });
});

<|endoftext|>


<commit_before>var path = require('path');
var Database = require('../../database').Database;
var Domain = require('../../domain').Domain;
var Translator = require('../../batch/translator').Translator;
var Deferred = require('jsdeferred').Deferred;
var dateFormat = require('dateformat');

exports.version = path.basename(__dirname);

var XMLNS = 'http://cloudsearch.amazonaws.com/doc/2011-02-01';
var FAKE_DOMAIN_ID = '00000000000000000000000000';

function createCommonErrorResponse(errorCode, message) {
  return '<?xml version="1.0"?>\n' +
         '<Response>' +
           '<Errors>' +
             '<Error>' + errorCode +'' +
                     '<Message>' + message + '</Message></Error>' +
             '</Errors>' +
           '<RequestID></RequestID>' +
         '</Response>';
}

var handlers = Object.create(null);

function getBaseDomain(domain) {
  return domain.replace(/^cloudsearch\./, '');
}

function createDomainStatus(options) {
  return '<DomainStatus>' +
           '<Created>' + (options.created || 'false') + '</Created>' +
           '<Deleted>' + (options.deleted || 'false') + '</Deleted>' +
           '<DocService>' +
             '<Endpoint>' + (options.documentsEndpoint || '') + '</Endpoint>' +
           '</DocService>' +
           '<DomainId>' + options.domainId + '/' + options.domainName +
             '</DomainId>' +
           '<DomainName>' + options.domainName + '</DomainName>' +
           '<NumSearchableDocs>' + (options.searchableDocumentsCount || 0) +
             '</NumSearchableDocs>' +
           '<RequiresIndexDocuments>' +
             (options.requiresIndexDocuments || 'false') +
             '</RequiresIndexDocuments>' +
           '<SearchInstanceCount>' + (options.searchInstanceCount || 0) +
             '</SearchInstanceCount>' +
           '<SearchPartitionCount>' + (options.searchPartitionCount || 0) +
             '</SearchPartitionCount>' +
           '<SearchService>' +
             '<Endpoint>' + (options.searchEndpoint || '') + '</Endpoint>' +
           '</SearchService>' +
         '</DomainStatus>';
}

function createCreateDomainResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<CreateDomainResponse xmlns="' + XMLNS + '">' +
           '<CreateDomainResult>' +
             createDomainStatus(options) +
           '</CreateDomainResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</CreateDomainResponse>';
}

handlers.CreateDomain = function(database, request, response) {
  var domain = new Domain(request);
  var options = {
        name: domain.tableName,
        flags: Database.TABLE_HASH_KEY,
        key_type: Database.ShortText
      };
  database.commandDeferred('table_create', options)
    .next(function(data) {
      var termsOptions = {
            name: domain.termsTableName,
            flags: Database.TABLE_PAT_KEY + '|' + Database.KEY_NORMALIZE,
            key_type: Database.ShortText,
            default_tokenizer: Database.TokenBigram
          };
      return database.commandDeferred('table_create', termsOptions);
    })
    .next(function(data) {
      var host = getBaseDomain(request.headers.host);
      host = host ? '.' + host : '';
      response.contentType('application/xml');
      response.send(createCreateDomainResponse({
        domainName: domain.name,
        domainId: FAKE_DOMAIN_ID,
        searchEndpoint: 'search-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
        documentsEndpoint: 'doc-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
        created: true,
        searchableDocumentsCount: 0,
        searchInstanceCount: 0,
        searchPartitionCount: 0,
        requiresIndexDocuments: false
      }));
    })
    .error(function(error) {
      var body = createCommonErrorResponse('InternalFailure', error.message);
      response.contentType('application/xml');
      return response.send(body, 400);
    });
};

function createDeleteDomainResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<DeleteDomainResponse xmlns="' + XMLNS + '">' +
           '<DeleteDomainResult>' +
             createDomainStatus(options) +
           '</DeleteDomainResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</DeleteDomainResponse>';
}

handlers.DeleteDomain = function(database, request, response) {
  var domain = new Domain(request);
  try {
    database.commandSync('table_remove', {
      name: domain.tableName
    });
    database.commandSync('table_remove', {
      name: domain.termsTableName
    });
    var host = getBaseDomain(request.headers.host);
    host = host ? '.' + host : '';
    response.contentType('application/xml');
    response.send(createDeleteDomainResponse({
      domainName: domain.name,
      domainId: FAKE_DOMAIN_ID,
      searchEndpoint: 'search-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
      documentsEndpoint: 'doc-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
      deleted: true,
      searchableDocumentsCount: 0,
      searchInstanceCount: 0,
      searchPartitionCount: 0,
      requiresIndexDocuments: false
    }));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexFieldOptionStatus(options) {
  switch (options.fieldType) {
    case 'text':
      return '<TextOptions>' +
               '<DefaultValue/>' +
               '<FacetEnabled>' + (options.facetEnabled || false) +
                 '</FacetEnabled>' +
               '<ResultEnabled>' + (options.resultEnabled || false) +
                 '</ResultEnabled>' +
             '</TextOptions>';
    case 'uint':
      return '<UIntOptions>' +
               '<DefaultValue/>' +
             '</UIntOptions>';
  }
}

function createIndexFieldStatus(options) {
  return '<IndexField>' +
           '<Options>' +
             '<IndexFieldName>' + options.fieldName + '</IndexFieldName>' +
             '<IndexFieldType>' + options.fieldType + '</IndexFieldType>' +
             createIndexFieldOptionStatus(options) +
           '</Options>' +
           '<Status>' +
             '<CreationDate>' + dateFormat(options.createdAt,
                                           'isoUtcDateTime') +
               '</CreationDate>' +
             '<State>' + options.state + '</State>' +
             '<UpdateDate>' + dateFormat(options.updatedAt, 'isoUtcDateTime') +
               '</UpdateDate>' +
             '<UpdateVersion>' + (options.updateVersion || 0) +
               '</UpdateVersion>' +
           '</Status>' +
         '</IndexField>';
}

function createDefineIndexFieldResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<DefineIndexFieldResponse xmlns="' + XMLNS + '">' +
           '<DefineIndexFieldResult>' +
             createIndexFieldStatus(options) +
           '</DefineIndexFieldResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</DefineIndexFieldResponse>';
}

handlers.DefineIndexField = function(database, request, response) {
  var domain = new Domain(request);

  var fieldName = request.query['IndexField.IndexFieldName'] || '';
  var fieldType = request.query['IndexField.IndexFieldType'] || 'text';
  var field = domain.getIndexField(fieldName);

  var createdAt = new Date();
  var columnType = Translator.translateIndexFieldType(fieldType);
  try {
    database.commandSync('column_create', {
      table: domain.tableName,
      name: field.columnName,
      flags: Database.COLUMN_SCALAR,
      type: columnType
    });

    if (fieldType == 'text') {
      database.commandSync('column_create', {
        table: domain.termsTableName,
        name: field.indexColumnName,
        flags: Database.INDEX_COLUMN_DEFAULT_FLAGS,
        type: domain.tableName,
        source: field.columnName
      });
    } else if (fieldType == 'uint') {
      var alterTableName = domain.getAlterTableName(field.columnName);
      database.commandSync('table_create', {
        name: alterTableName,
        flags: Database.TABLE_HASH_KEY,
        key_type: columnType
      });
      database.commandSync('column_create', {
        table: alterTableName,
        name: field.indexColumnName,
        flags: Database.INDEX_COLUMN_DEFAULT_FLAGS,
        type: domain.tableName,
        source: field.columnName
      });
    }

    response.contentType('application/xml');
    response.send(createDefineIndexFieldResponse({
      fieldName: fieldName,
      fieldType: fieldType,
      facetEnabled: false,
      resultEnabled: true,
      state: 'RequiresIndexDocuments',
      createdAt: createdAt,
      updatedAt: createdAt
    }));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createDeleteIndexFieldResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<DeleteIndexFieldResponse xmlns="' + XMLNS + '">' +
           '<DeleteIndexFieldResult/>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</DeleteIndexFieldResponse>';
}

handlers.DeleteIndexField = function(database, request, response) {
  var domain = new Domain(request);

  var fieldName = request.query['IndexFieldName'] || '';
  var field = domain.getIndexField(fieldName);

  try {
    database.commandSync('column_remove', {
      table: domain.tableName,
      name: field.columnName
    });

    if (fieldType == 'uint') {
      var alterTableName = domain.getAlterTableName(field.columnName);
      database.commandSync('table_remove', {
        name: alterTableName
      });
    }

    response.contentType('application/xml');
    response.send(createDeleteIndexFieldResponse({}));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexDocumentsResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<IndexDocumentsResponse xmlns="' + XMLNS + '">' +
           '<IndexDocumentsResult>' +
             '<FieldNames>' +
               options.fieldNames.map(function(fieldName) {
                 return '<member>' + fieldName + '</member>';
               }).join('') +
             '</FieldNames>' +
           '</IndexDocumentsResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</IndexDocumentsResponse>';
}

handlers.IndexDocuments = function(database, request, response) {
  var domain = new Domain(request);
  var indexColumns = database.columnListSync(domain.termsTableName);
  indexColumns = indexColumns.filter(function(column) {
                   return column.flags.indexOf(Database.COLUMN_INDEX) > -1;
                 });
  try {
    indexColumns.forEach(function(column) {
      database.commandSync('column_remove', {
        table: domain.termsTableName,
        name: column.name
      });
      database.commandSync('column_create', {
        table: domain.termsTableName,
        name: column.name,
        flags: Database.INDEX_COLUMN_DEFAULT_FLAGS,
        type: column.range,
        source: column.source[0].replace(column.range + '.', '')
      });
    });
    response.contentType('application/xml');
    response.send(createIndexDocumentsResponse({
      // FieldNames must be field names, not column names.
      // However, original field names are completely lost after
      // they are created via the API...
      fieldNames: indexColumns.map(function(column) {
        return column.source[0].replace(column.range + '.', '');
      })
    }));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

exports.createHandler = function(database) {
  return function(request, response, next) {
    var message, body;

    // GCS specific behaviour: fallback to other handlers for the endpoint
    // if no action is given.
    var action = request.query.Action || '';
    if (!action)
      return next();

    var version = request.query.Version;
    if (!version) {
      message = 'An input parameter "Version" that is mandatory for ' +
                'processing the request is not supplied.';
      body = createCommonErrorResponse('MissingParameter', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (version != exports.version) {
      message = 'A bad or out-of-range value "' + version + '" was supplied ' +
                'for the "Version" input parameter.';
      body = createCommonErrorResponse('InvalidParameterValue', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (!(action in handlers)) {
      message = 'The action ' + action + ' is not valid for this web service.';
      body = createCommonErrorResponse('InvalidAction', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    var handler = handlers[action];
    handler(database, request, response);
  };
};
<commit_msg>Detect index field type from the column type<commit_after>var path = require('path');
var Database = require('../../database').Database;
var Domain = require('../../domain').Domain;
var Translator = require('../../batch/translator').Translator;
var Deferred = require('jsdeferred').Deferred;
var dateFormat = require('dateformat');

exports.version = path.basename(__dirname);

var XMLNS = 'http://cloudsearch.amazonaws.com/doc/2011-02-01';
var FAKE_DOMAIN_ID = '00000000000000000000000000';

function createCommonErrorResponse(errorCode, message) {
  return '<?xml version="1.0"?>\n' +
         '<Response>' +
           '<Errors>' +
             '<Error>' + errorCode +'' +
                     '<Message>' + message + '</Message></Error>' +
             '</Errors>' +
           '<RequestID></RequestID>' +
         '</Response>';
}

var handlers = Object.create(null);

function getBaseDomain(domain) {
  return domain.replace(/^cloudsearch\./, '');
}

function createDomainStatus(options) {
  return '<DomainStatus>' +
           '<Created>' + (options.created || 'false') + '</Created>' +
           '<Deleted>' + (options.deleted || 'false') + '</Deleted>' +
           '<DocService>' +
             '<Endpoint>' + (options.documentsEndpoint || '') + '</Endpoint>' +
           '</DocService>' +
           '<DomainId>' + options.domainId + '/' + options.domainName +
             '</DomainId>' +
           '<DomainName>' + options.domainName + '</DomainName>' +
           '<NumSearchableDocs>' + (options.searchableDocumentsCount || 0) +
             '</NumSearchableDocs>' +
           '<RequiresIndexDocuments>' +
             (options.requiresIndexDocuments || 'false') +
             '</RequiresIndexDocuments>' +
           '<SearchInstanceCount>' + (options.searchInstanceCount || 0) +
             '</SearchInstanceCount>' +
           '<SearchPartitionCount>' + (options.searchPartitionCount || 0) +
             '</SearchPartitionCount>' +
           '<SearchService>' +
             '<Endpoint>' + (options.searchEndpoint || '') + '</Endpoint>' +
           '</SearchService>' +
         '</DomainStatus>';
}

function createCreateDomainResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<CreateDomainResponse xmlns="' + XMLNS + '">' +
           '<CreateDomainResult>' +
             createDomainStatus(options) +
           '</CreateDomainResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</CreateDomainResponse>';
}

handlers.CreateDomain = function(database, request, response) {
  var domain = new Domain(request);
  var options = {
        name: domain.tableName,
        flags: Database.TABLE_HASH_KEY,
        key_type: Database.ShortText
      };
  database.commandDeferred('table_create', options)
    .next(function(data) {
      var termsOptions = {
            name: domain.termsTableName,
            flags: Database.TABLE_PAT_KEY + '|' + Database.KEY_NORMALIZE,
            key_type: Database.ShortText,
            default_tokenizer: Database.TokenBigram
          };
      return database.commandDeferred('table_create', termsOptions);
    })
    .next(function(data) {
      var host = getBaseDomain(request.headers.host);
      host = host ? '.' + host : '';
      response.contentType('application/xml');
      response.send(createCreateDomainResponse({
        domainName: domain.name,
        domainId: FAKE_DOMAIN_ID,
        searchEndpoint: 'search-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
        documentsEndpoint: 'doc-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
        created: true,
        searchableDocumentsCount: 0,
        searchInstanceCount: 0,
        searchPartitionCount: 0,
        requiresIndexDocuments: false
      }));
    })
    .error(function(error) {
      var body = createCommonErrorResponse('InternalFailure', error.message);
      response.contentType('application/xml');
      return response.send(body, 400);
    });
};

function createDeleteDomainResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<DeleteDomainResponse xmlns="' + XMLNS + '">' +
           '<DeleteDomainResult>' +
             createDomainStatus(options) +
           '</DeleteDomainResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</DeleteDomainResponse>';
}

handlers.DeleteDomain = function(database, request, response) {
  var domain = new Domain(request);
  try {
    database.commandSync('table_remove', {
      name: domain.tableName
    });
    database.commandSync('table_remove', {
      name: domain.termsTableName
    });
    var host = getBaseDomain(request.headers.host);
    host = host ? '.' + host : '';
    response.contentType('application/xml');
    response.send(createDeleteDomainResponse({
      domainName: domain.name,
      domainId: FAKE_DOMAIN_ID,
      searchEndpoint: 'search-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
      documentsEndpoint: 'doc-' + domain.name + '-' + FAKE_DOMAIN_ID + host,
      deleted: true,
      searchableDocumentsCount: 0,
      searchInstanceCount: 0,
      searchPartitionCount: 0,
      requiresIndexDocuments: false
    }));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexFieldOptionStatus(options) {
  switch (options.fieldType) {
    case 'text':
      return '<TextOptions>' +
               '<DefaultValue/>' +
               '<FacetEnabled>' + (options.facetEnabled || false) +
                 '</FacetEnabled>' +
               '<ResultEnabled>' + (options.resultEnabled || false) +
                 '</ResultEnabled>' +
             '</TextOptions>';
    case 'uint':
      return '<UIntOptions>' +
               '<DefaultValue/>' +
             '</UIntOptions>';
  }
}

function createIndexFieldStatus(options) {
  return '<IndexField>' +
           '<Options>' +
             '<IndexFieldName>' + options.fieldName + '</IndexFieldName>' +
             '<IndexFieldType>' + options.fieldType + '</IndexFieldType>' +
             createIndexFieldOptionStatus(options) +
           '</Options>' +
           '<Status>' +
             '<CreationDate>' + dateFormat(options.createdAt,
                                           'isoUtcDateTime') +
               '</CreationDate>' +
             '<State>' + options.state + '</State>' +
             '<UpdateDate>' + dateFormat(options.updatedAt, 'isoUtcDateTime') +
               '</UpdateDate>' +
             '<UpdateVersion>' + (options.updateVersion || 0) +
               '</UpdateVersion>' +
           '</Status>' +
         '</IndexField>';
}

function createDefineIndexFieldResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<DefineIndexFieldResponse xmlns="' + XMLNS + '">' +
           '<DefineIndexFieldResult>' +
             createIndexFieldStatus(options) +
           '</DefineIndexFieldResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</DefineIndexFieldResponse>';
}

handlers.DefineIndexField = function(database, request, response) {
  var domain = new Domain(request);

  var fieldName = request.query['IndexField.IndexFieldName'] || '';
  var fieldType = request.query['IndexField.IndexFieldType'] || 'text';
  var field = domain.getIndexField(fieldName);

  var createdAt = new Date();
  var columnType = Translator.translateIndexFieldType(fieldType);
  try {
    database.commandSync('column_create', {
      table: domain.tableName,
      name: field.columnName,
      flags: Database.COLUMN_SCALAR,
      type: columnType
    });

    if (fieldType == 'text') {
      database.commandSync('column_create', {
        table: domain.termsTableName,
        name: field.indexColumnName,
        flags: Database.INDEX_COLUMN_DEFAULT_FLAGS,
        type: domain.tableName,
        source: field.columnName
      });
    } else if (fieldType == 'uint') {
      var alterTableName = domain.getAlterTableName(field.columnName);
      database.commandSync('table_create', {
        name: alterTableName,
        flags: Database.TABLE_HASH_KEY,
        key_type: columnType
      });
      database.commandSync('column_create', {
        table: alterTableName,
        name: field.indexColumnName,
        flags: Database.INDEX_COLUMN_DEFAULT_FLAGS,
        type: domain.tableName,
        source: field.columnName
      });
    }

    response.contentType('application/xml');
    response.send(createDefineIndexFieldResponse({
      fieldName: fieldName,
      fieldType: fieldType,
      facetEnabled: false,
      resultEnabled: true,
      state: 'RequiresIndexDocuments',
      createdAt: createdAt,
      updatedAt: createdAt
    }));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createDeleteIndexFieldResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<DeleteIndexFieldResponse xmlns="' + XMLNS + '">' +
           '<DeleteIndexFieldResult/>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</DeleteIndexFieldResponse>';
}

handlers.DeleteIndexField = function(database, request, response) {
  var domain = new Domain(request);

  var fieldName = request.query['IndexFieldName'] || '';
  var field = domain.getIndexField(fieldName);

  var column = database.columnListSync(domain.tableName)
                 .filter(function(column) {
                   return column.name == field.columnName;
                 })[0];

  try {
    database.commandSync('column_remove', {
      table: domain.tableName,
      name: field.columnName
    });

    if (column.type == Translator.translateIndexFieldType('uint')) {
      var alterTableName = domain.getAlterTableName(field.columnName);
      database.commandSync('table_remove', {
        name: alterTableName
      });
    }

    response.contentType('application/xml');
    response.send(createDeleteIndexFieldResponse({}));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

function createIndexDocumentsResponse(options) {
  return '<?xml version="1.0"?>\n' +
         '<IndexDocumentsResponse xmlns="' + XMLNS + '">' +
           '<IndexDocumentsResult>' +
             '<FieldNames>' +
               options.fieldNames.map(function(fieldName) {
                 return '<member>' + fieldName + '</member>';
               }).join('') +
             '</FieldNames>' +
           '</IndexDocumentsResult>' +
           '<ResponseMetadata>' +
             '<RequestId>' + (options.requestId || '') + '</RequestId>' +
           '</ResponseMetadata>' +
         '</IndexDocumentsResponse>';
}

handlers.IndexDocuments = function(database, request, response) {
  var domain = new Domain(request);
  var indexColumns = database.columnListSync(domain.termsTableName);
  indexColumns = indexColumns.filter(function(column) {
                   return column.flags.indexOf(Database.COLUMN_INDEX) > -1;
                 });
  try {
    indexColumns.forEach(function(column) {
      database.commandSync('column_remove', {
        table: domain.termsTableName,
        name: column.name
      });
      database.commandSync('column_create', {
        table: domain.termsTableName,
        name: column.name,
        flags: Database.INDEX_COLUMN_DEFAULT_FLAGS,
        type: column.range,
        source: column.source[0].replace(column.range + '.', '')
      });
    });
    response.contentType('application/xml');
    response.send(createIndexDocumentsResponse({
      // FieldNames must be field names, not column names.
      // However, original field names are completely lost after
      // they are created via the API...
      fieldNames: indexColumns.map(function(column) {
        return column.source[0].replace(column.range + '.', '');
      })
    }));
  } catch(error) {
    var body = createCommonErrorResponse('InternalFailure', error.message);
    response.contentType('application/xml');
    response.send(body, 400);
  }
};

exports.createHandler = function(database) {
  return function(request, response, next) {
    var message, body;

    // GCS specific behaviour: fallback to other handlers for the endpoint
    // if no action is given.
    var action = request.query.Action || '';
    if (!action)
      return next();

    var version = request.query.Version;
    if (!version) {
      message = 'An input parameter "Version" that is mandatory for ' +
                'processing the request is not supplied.';
      body = createCommonErrorResponse('MissingParameter', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (version != exports.version) {
      message = 'A bad or out-of-range value "' + version + '" was supplied ' +
                'for the "Version" input parameter.';
      body = createCommonErrorResponse('InvalidParameterValue', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    if (!(action in handlers)) {
      message = 'The action ' + action + ' is not valid for this web service.';
      body = createCommonErrorResponse('InvalidAction', message);
      response.contentType('application/xml');
      return response.send(body, 400);
    }

    var handler = handlers[action];
    handler(database, request, response);
  };
};
<|endoftext|>


<commit_before>/**
 * 2017-09-22 Tong Yuehong
 */

/*
function anmial(){
}
anmial.prototype.species = 'mammal';

function cat(name){
    anmial.apply(this,arguments);
    this.name = name;
}

var c = new cat('a');
console.log(c);

cat.species = 'bird';
console.log(anmial.prototype.species);
*/

console.log('*******************black****************************');// 不够完善，例子如下
function animal(){

}
function cat(){

}
function dog(){

}
cat.prototype = animal.prototype;
cat.prototype.constructor = cat;
dog.prototype = animal.prototype;
dog.prototype.constructor = dog;
cat.prototype.food = 'milk';
var m = new dog();
console.log(m.food);

console.log('************************(2)直接继承 prototype***************************');
function Animal() {
    this.species = 'animal';
}
function Cat(name,color) {
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
}
var k = new Cat('k','yello');
console.log(k);

console.log('************************(3)prototype 模式***************************');
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

console.log('************************(4)利用空对象***************************');
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

console.log('************************(5)拷贝继承***************************');
function extend2(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
      c[i] = p[i];
    }
    c.uber = p;
  }
console.log('****************************object方法********************************');
function object(o) {
    function F() {}

    F.prototype = o;
    return new F();
  }

console.log('******************浅拷贝******************');// 拷贝了p的内容，指针指向地址与p指向地址为同一个内存小格
function extendCopy(p) {
    var c = {};

    for (var i in p) {
      c[i] = p[i];
    }

    c.uber = p;
    return c;
}

console.log('*******************深拷贝*********************');//拷贝时拷贝了内容，同时指向了一个新的内存小格，互不影响
function deepCopy(p, c) {
    var c = c || {};

    for (var i in p) {
      if (typeof p[i] === 'object') {
        c[i] = (p[i].constructor === Array) ? [] : {};
        deepCopy(p[i], c[i]);
      } else {
        c[i] = p[i];
      }
    }
    return c;
  }
<commit_msg>_.lodash练习<commit_after>/**
 * 2017-09-22 Tong Yuehong
 */

/*
function anmial(){
}
anmial.prototype.species = 'mammal';

function cat(name){
    anmial.apply(this,arguments);
    this.name = name;
}

var c = new cat('a');
console.log(c);

cat.species = 'bird';
console.log(anmial.prototype.species);
*/

console.log('*******************black****************************');// 不够完善，例子如下
function animal(){

}
function cat(){

}
function dog(){

}
cat.prototype = animal.prototype;
cat.prototype.constructor = cat;
dog.prototype = animal.prototype;
dog.prototype.constructor = dog;
cat.prototype.food = 'milk';
var m = new dog();
console.log(m.food);

console.log('************************(2)直接继承 prototype***************************');
function Animal() {
    this.species = 'animal';
}
function Cat(name,color) {
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
}
var k = new Cat('k','yello');
console.log(k);

console.log('************************(3)prototype 模式***************************');
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;

console.log('************************(4)利用空对象***************************');
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

console.log('************************(5)拷贝继承***************************');
function extend2(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
      c[i] = p[i];
    }
    c.uber = p;
}

console.log('****************************object方法********************************');
function object(o) {
    function F() {}

    F.prototype = o;
    return new F();
  }

console.log('******************浅拷贝******************');// 拷贝了p的内容，指针指向地址与p指向地址为同一个内存小格
function extendCopy(p) {
    var c = {};

    for (var i in p) {
      c[i] = p[i];
    }

    c.uber = p;
    return c;
}

console.log('*******************深拷贝*********************');//拷贝时拷贝了内容，同时指向了一个新的内存小格，互不影响
function deepCopy(p, c) {
    var c = c || {};

    for (var i in p) {
      if (typeof p[i] === 'object') {
        c[i] = (p[i].constructor === Array) ? [] : {};
        deepCopy(p[i], c[i]);
      } else {
        c[i] = p[i];
      }
    }
    return c;
  }
<|endoftext|>


<commit_before>var app = angular.module('myApp', ['angularMoment']);
		// http://stackoverflow.com/questions/20858395/how-to-use-ng-repeat-with-filter-and-index
		app.filter('_customFilterByPosition', function() {
			return function (arr, targetIndexes) {
				return arr.filter(function(arrItem, arrPosIndex) {
					_targetIndexesArray = targetIndexes.split(',');
					for (var i = 0; i < _targetIndexesArray.length; i++) {
						var starshipUrl = arrItem.url;
						var starshipId = starshipUrl.match(/\/([^\/]+)\/?$/)[1];
						if(_targetIndexesArray[i]===starshipId) {
							//console.log(arrPosIndex, starshipId)
							return true;
						}
					}
					//console.log(div);
					//return arrPosIndex % div === (val || 0);
					return false;
				});
			};
		});
		app.service('_customRestService', [
			'$http', '$q',
			function($http, $q) {
				var _this = this;
				this.fetch = function (targetedRestUrl, callDepth) {
					var _deferred = $q.defer();

					if(callDepth===undefined) callDepth = 0;

					console.log(targetedRestUrl);
					$http.get(targetedRestUrl)
						.then(function(response) {
							var _resultsArray = response.data.results;
							//var _next = response.data.next.replace("http", "https");

							console.log(callDepth, _resultsArray.length, response.data);
							// if(_next!==null) {
							// 	callDepth++;
							// 	console.log(_next, callDepth);
							// 	_this.fetch(_next, callDepth).then(function(returnedResultArray) {
							// 		_resultsArray = _resultsArray.concat(returnedResultArray);
							// 		_deferred.resolve(_resultsArray);
							// 	});
							// }
							// else {
							// 	_deferred.resolve(_resultsArray);
							// }
							_deferred.resolve(_resultsArray);
		        });

						return _deferred.promise;
				}
			}
		]);
		// =========================================
		app.controller('myCtrl', function($scope, $http, $filter, _customRestService) {
			_customRestService
				.fetch('https://swapi.co/api/starships/')
				.then(function(returnedResultArray) {
					//$scope.starships = $filter('filter')(returnedResultArray, {crew: '5'})[0];
					// for (var i = 0; i < returnedResultArray.length; i++) {
					// 	returnedResultArray[i].crewAsInt = parseInt(returnedResultArray[i].crew);
					// 	returnedResultArray[i].crewAsIntHidden = parseInt(returnedResultArray[i].crew);
					// }
					$scope.starships = returnedResultArray;
					$scope.isJsonReady = true;
				});

			$scope.starships = [];
			$scope.firstName= "Wei Khong";
			$scope.lastName= "Teh";
			$scope.isJsonReady = false;
			$scope.orderByFunction = function(starship) {
				return parseInt(starship.crew);
			};
		});<commit_msg>- Fixed HTTPS error (5)<commit_after>var app = angular.module('myApp', ['angularMoment']);
		// http://stackoverflow.com/questions/20858395/how-to-use-ng-repeat-with-filter-and-index
		app.filter('_customFilterByPosition', function() {
			return function (arr, targetIndexes) {
				return arr.filter(function(arrItem, arrPosIndex) {
					_targetIndexesArray = targetIndexes.split(',');
					for (var i = 0; i < _targetIndexesArray.length; i++) {
						var starshipUrl = arrItem.url;
						var starshipId = starshipUrl.match(/\/([^\/]+)\/?$/)[1];
						if(_targetIndexesArray[i]===starshipId) {
							//console.log(arrPosIndex, starshipId)
							return true;
						}
					}
					//console.log(div);
					//return arrPosIndex % div === (val || 0);
					return false;
				});
			};
		});
		app.service('_customRestService', [
			'$http', '$q',
			function($http, $q) {
				var _this = this;
				this.fetch = function (targetedRestUrl, callDepth) {
					var _deferred = $q.defer();

					if(callDepth===undefined) callDepth = 0;

					$http.get(targetedRestUrl)
						.then(function(response) {
							var _resultsArray = response.data.results;

							//console.log(callDepth, _resultsArray.length, response.data);
							if(response.data.next!==null) {
								var _next = response.data.next.replace("http", "https");
								callDepth++;
								_this.fetch(_next, callDepth).then(function(returnedResultArray) {
									_resultsArray = _resultsArray.concat(returnedResultArray);
									_deferred.resolve(_resultsArray);
								});
							}
							else {
								_deferred.resolve(_resultsArray);
							}
		        });

						return _deferred.promise;
				}
			}
		]);
		// =========================================
		app.controller('myCtrl', function($scope, $http, $filter, _customRestService) {
			_customRestService
				.fetch('https://swapi.co/api/starships/')
				.then(function(returnedResultArray) {
					//$scope.starships = $filter('filter')(returnedResultArray, {crew: '5'})[0];
					// for (var i = 0; i < returnedResultArray.length; i++) {
					// 	returnedResultArray[i].crewAsInt = parseInt(returnedResultArray[i].crew);
					// 	returnedResultArray[i].crewAsIntHidden = parseInt(returnedResultArray[i].crew);
					// }
					$scope.starships = returnedResultArray;
					$scope.isJsonReady = true;
				});

			$scope.starships = [];
			$scope.firstName= "Wei Khong";
			$scope.lastName= "Teh";
			$scope.isJsonReady = false;
			$scope.orderByFunction = function(starship) {
				return parseInt(starship.crew);
			};
		});<|endoftext|>


<commit_before>/*
Copyright (C) 2012 Vytautas Jakutis <vytautas@jakut.is>

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.
*/
(function (name, context, definition) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = definition(name, context);
    } else if (typeof define === 'function' && typeof define.amd === 'object') {
        define(definition);
    } else {
        context[name] = definition(name, context);
    }
})('navigate', this, function (name, context) {
    var lastPath, getCurrentPath, handle, w, html5, add, navigate, regexps, handlers;
    var iframe, lastIframePath, hashToPath, lastButton;
    lastPath = null;
    w = window;
    var ie = typeof w.attachEvent !== 'undefined' && typeof w.addEventListener === 'undefined';
    var opts = {
        clickHandlingEnabled : true,
        basePath : ''
    };
    var initialized = false;
    var addEvent = w.attachEvent ? function(obj, eventType, listener) {
        obj.attachEvent('on' + eventType, listener);
    } : function(obj, eventType, listener) {
        obj.addEventListener(eventType, listener, false);
    };
    var hasAttribute = typeof w.document.body.hasAttribute === 'undefined' ? function(el, attr) {
        return el.attributes[attr].specified;
    } : function(el, attr) {
        return el.hasAttribute(attr);
    };
    html5 = 'onpopstate' in w;
    regexps = [];
    handlers = [];
    add = function(regexp, handler) {
        regexps.push(regexp);
        handlers.push(handler);
    };
    handle = function(path) {
        if(!initialized || path === lastPath) {
            return;
        }
        var handled = false;
        for(var n = regexps.length, i = 0; i < n; i += 1) {
            var args = regexps[i].exec(path);
            if(args !== null) {
                args.shift();
                handlers[i](lastPath, path, args);
                handled = true;
                break;
            }
        }
        lastPath = path;
        return handled;
    };
    hashToPath = function(path) {
        if(path.charAt(0) === '#') {
            path = path.substr(1);
        }
        if(path === '') {
            return '/';
        }
        return path;
    };
    var getHTML5Path = function() {
        var path = w.document.location.pathname + w.document.location.search;
        path = path.substr(opts.basePath.length);
        return path === '' ? '/' : path;
    };
    var getHTML4Path = function() {
        return hashToPath(w.location.hash);
    };
    if(html5) {
        getCurrentPath = getHTML5Path;
        addEvent(w, 'popstate', function() {
            handle(getCurrentPath());
        });
        navigate = function(path) {
            w.history.pushState({}, '', opts.basePath + path);
            handle(path);
        };
    } else {
        getCurrentPath = getHTML4Path;
        if('onhashchange' in w && (!w.document.documentMode || w.document.documentMode >= 8)) {
            addEvent(w, 'hashchange', function() {
                handle(getCurrentPath());
            });
            navigate = function(path) {
                w.location.hash = '#' + path;
                handle(path);
            };
        } else if(ie) {
            iframe = w.document.createElement('iframe');
            iframe.style.display = 'none';
            w.document.body.appendChild(iframe);
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.close();

            lastIframePath = null;
            w.setInterval(function() {
                var path = getCurrentPath();
                var iframePath = hashToPath(iframe.contentWindow.document.location.hash);
                if(lastPath !== path) {
                    iframe.contentWindow.document.open();
                    iframe.contentWindow.document.close();
                    iframe.contentWindow.document.location.hash = '#' + path;
                    lastIframePath = path;
                    iframePath = path;
                } else if(lastIframePath !== iframePath) {
                    path = iframePath;
                    w.location.hash = '#' + path;
                    lastIframePath = iframePath;
                }
                handle(path);
            }, 300);
            navigate = function(path) {
                w.location.hash = '#' + path;
            };
        } else {
            w.setInterval(function() {
                handle(getCurrentPath());
            }, 300);
            navigate = function(path) {
                w.location.hash = '#' + path;
            };
        }
    }
    lastButton = 0;
    addEvent(w.document, 'mousedown', function(e) {
        if(typeof w.event !== 'undefined' && typeof w.event.button !== 'undefined') {
            lastButton = w.event.button;
        }
    });
    addEvent(w.document, 'click', function(e) {
        if(!opts.clickHandlingEnabled) {
            return;
        }
        e = e || w.event;
        if(typeof e.which === 'undefined') {
            if(lastButton !== 1) {
                return;
            }
        } else {
            if(e.which !== 1) {
                return;
            }
        }
        if(e.defaultPrevented) {
            return;
        }
        var el = e.target || e.srcElement;
        while (el && el.nodeName !== 'A') {
            el = el.parentNode;
        }
        if (!el || el.nodeName !== 'A') {
            return;
        }
        if (el.hash !== '' && el.hash !== '#') {
            return;
        }
        var origin = w.location.protocol + '//' + w.location.hostname;
        if (w.location.port) {
            origin += ':' + w.location.port;
        }
        if(!hasAttribute(el, 'href')) {
            return;
        }
        var href = el.href;
        if(!(typeof el.hostname === 'string' && el.hostname === '') && href.indexOf(origin) !== 0) {
            return;
        }
        var path = el.pathname + el.search;
        if(path.charAt(0) !== '/') {
            path = '/' + path;
        }
        if(path.substr(0, opts.basePath.length) !== opts.basePath) {
            return;
        }
        if(e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
        navigate(path.substr(opts.basePath.length));
        return false;
    });

    return function(a, b) {
        if(typeof a === 'string' && typeof b === 'undefined') {
            navigate(a);
        } else if((typeof a === 'object' || typeof a === 'function') && typeof b === 'function') {
            add(a, b);
        } else if(typeof a === 'undefined' && typeof b === 'undefined') {
            if(!initialized) {
                initialized = true;
                var path;
                if(html5) {
                    path = getHTML4Path();
                    w.location.hash = '';
                    if(path === '/' || (path !== '/' && !navigate(path))) {
                        navigate(getCurrentPath());
                    }
                } else {
                    path = getHTML5Path();
                    if(path === '/') {
                        w.setTimeout(function() {
                            navigate(getCurrentPath());
                        }, 0);
                    } else {
                        w.location.href = opts.basePath + '/#' + path;
                    }
                }
            }
        } else if(typeof a === 'object' && typeof b === 'undefined') {
            for(var i in a) {
                if(a.hasOwnProperty(i)) {
                    opts[i] = a[i];
                }
            }
            if(opts.basePath.charAt(opts.basePath.length - 1) === '/') {
                opts.basePath = opts.basePath.substr(0, opts.basePath.length - 1);
            }
        } else {
            throw new Error('navigate.js: incorrect arguments: ' + a + '(' +
                typeof a + '), ' + b + ' (' + typeof b + ')');
        }
    };
});
<commit_msg>navigate(regexp, handler): return a function that removes handler<commit_after>/*
Copyright (C) 2012 Vytautas Jakutis <vytautas@jakut.is>

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.
*/
(function (name, context, definition) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = definition(name, context);
    } else if (typeof define === 'function' && typeof define.amd === 'object') {
        define(definition);
    } else {
        context[name] = definition(name, context);
    }
})('navigate', this, function (name, context) {
    var lastPath, getCurrentPath, handle, w, html5, add, navigate, regexps, handlers;
    var iframe, lastIframePath, hashToPath, lastButton;
    lastPath = null;
    w = window;
    var ie = typeof w.attachEvent !== 'undefined' && typeof w.addEventListener === 'undefined';
    var opts = {
        clickHandlingEnabled : true,
        basePath : ''
    };
    var initialized = false;
    var addEvent = w.attachEvent ? function(obj, eventType, listener) {
        obj.attachEvent('on' + eventType, listener);
    } : function(obj, eventType, listener) {
        obj.addEventListener(eventType, listener, false);
    };
    var hasAttribute = typeof w.document.body.hasAttribute === 'undefined' ? function(el, attr) {
        return el.attributes[attr].specified;
    } : function(el, attr) {
        return el.hasAttribute(attr);
    };
    html5 = 'onpopstate' in w;
    regexps = [];
    handlers = [];
    add = function(regexp, handler) {
        regexps.push(regexp);
        handlers.push(handler);
        return function() {
            for(var n = regexps.length; n > 0; ) {
                n -= 1;
                if(regexps[n] === regexp && handlers[n] === handler) {
                    regexps.splice(n, 1);
                    handlers.splice(n, 1);
                }
            }
        };
    };
    handle = function(path) {
        if(!initialized || path === lastPath) {
            return;
        }
        var handled = false;
        for(var n = regexps.length, i = 0; i < n; i += 1) {
            var args = regexps[i].exec(path);
            if(args !== null) {
                args.shift();
                handlers[i](lastPath, path, args);
                handled = true;
                break;
            }
        }
        lastPath = path;
        return handled;
    };
    hashToPath = function(path) {
        if(path.charAt(0) === '#') {
            path = path.substr(1);
        }
        if(path === '') {
            return '/';
        }
        return path;
    };
    var getHTML5Path = function() {
        var path = w.document.location.pathname + w.document.location.search;
        path = path.substr(opts.basePath.length);
        return path === '' ? '/' : path;
    };
    var getHTML4Path = function() {
        return hashToPath(w.location.hash);
    };
    if(html5) {
        getCurrentPath = getHTML5Path;
        addEvent(w, 'popstate', function() {
            handle(getCurrentPath());
        });
        navigate = function(path) {
            w.history.pushState({}, '', opts.basePath + path);
            handle(path);
        };
    } else {
        getCurrentPath = getHTML4Path;
        if('onhashchange' in w && (!w.document.documentMode || w.document.documentMode >= 8)) {
            addEvent(w, 'hashchange', function() {
                handle(getCurrentPath());
            });
            navigate = function(path) {
                w.location.hash = '#' + path;
                handle(path);
            };
        } else if(ie) {
            iframe = w.document.createElement('iframe');
            iframe.style.display = 'none';
            w.document.body.appendChild(iframe);
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.close();

            lastIframePath = null;
            w.setInterval(function() {
                var path = getCurrentPath();
                var iframePath = hashToPath(iframe.contentWindow.document.location.hash);
                if(lastPath !== path) {
                    iframe.contentWindow.document.open();
                    iframe.contentWindow.document.close();
                    iframe.contentWindow.document.location.hash = '#' + path;
                    lastIframePath = path;
                    iframePath = path;
                } else if(lastIframePath !== iframePath) {
                    path = iframePath;
                    w.location.hash = '#' + path;
                    lastIframePath = iframePath;
                }
                handle(path);
            }, 300);
            navigate = function(path) {
                w.location.hash = '#' + path;
            };
        } else {
            w.setInterval(function() {
                handle(getCurrentPath());
            }, 300);
            navigate = function(path) {
                w.location.hash = '#' + path;
            };
        }
    }
    lastButton = 0;
    addEvent(w.document, 'mousedown', function(e) {
        if(typeof w.event !== 'undefined' && typeof w.event.button !== 'undefined') {
            lastButton = w.event.button;
        }
    });
    addEvent(w.document, 'click', function(e) {
        if(!opts.clickHandlingEnabled) {
            return;
        }
        e = e || w.event;
        if(typeof e.which === 'undefined') {
            if(lastButton !== 1) {
                return;
            }
        } else {
            if(e.which !== 1) {
                return;
            }
        }
        if(e.defaultPrevented) {
            return;
        }
        var el = e.target || e.srcElement;
        while (el && el.nodeName !== 'A') {
            el = el.parentNode;
        }
        if (!el || el.nodeName !== 'A') {
            return;
        }
        if (el.hash !== '' && el.hash !== '#') {
            return;
        }
        var origin = w.location.protocol + '//' + w.location.hostname;
        if (w.location.port) {
            origin += ':' + w.location.port;
        }
        if(!hasAttribute(el, 'href')) {
            return;
        }
        var href = el.href;
        if(!(typeof el.hostname === 'string' && el.hostname === '') && href.indexOf(origin) !== 0) {
            return;
        }
        var path = el.pathname + el.search;
        if(path.charAt(0) !== '/') {
            path = '/' + path;
        }
        if(path.substr(0, opts.basePath.length) !== opts.basePath) {
            return;
        }
        if(e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
        navigate(path.substr(opts.basePath.length));
        return false;
    });

    return function(a, b) {
        if(typeof a === 'string' && typeof b === 'undefined') {
            navigate(a);
        } else if((typeof a === 'object' || typeof a === 'function') && typeof b === 'function') {
            return add(a, b);
        } else if(typeof a === 'undefined' && typeof b === 'undefined') {
            if(!initialized) {
                initialized = true;
                var path;
                if(html5) {
                    path = getHTML4Path();
                    w.location.hash = '';
                    if(path === '/' || (path !== '/' && !navigate(path))) {
                        navigate(getCurrentPath());
                    }
                } else {
                    path = getHTML5Path();
                    if(path === '/') {
                        w.setTimeout(function() {
                            navigate(getCurrentPath());
                        }, 0);
                    } else {
                        w.location.href = opts.basePath + '/#' + path;
                    }
                }
            }
        } else if(typeof a === 'object' && typeof b === 'undefined') {
            for(var i in a) {
                if(a.hasOwnProperty(i)) {
                    opts[i] = a[i];
                }
            }
            if(opts.basePath.charAt(opts.basePath.length - 1) === '/') {
                opts.basePath = opts.basePath.substr(0, opts.basePath.length - 1);
            }
        } else {
            throw new Error('navigate.js: incorrect arguments: ' + a + '(' +
                typeof a + '), ' + b + ' (' + typeof b + ')');
        }
    };
});
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';

const LOAD_STARGAZERS_SUCCESS = 'LOAD_STARGAZERS_SUCCESS';

const initialState = {
  stargazers: '506'
};

export function loadStargazers() {
  return dispatch => {
    fetch('https://api.github.com/repos/moroshko/react-autosuggest')
      .then(response => response.json())
      .then(response => {
        dispatch({
          type: LOAD_STARGAZERS_SUCCESS,
          stargazers: String(response.stargazers_count)
        });
      });
  };
}

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case LOAD_STARGAZERS_SUCCESS:
      return {
        ...state,
        stargazers: action.stargazers
      };

    default:
      return state;
  }
}
<commit_msg>Update default stargazers count<commit_after>import fetch from 'isomorphic-fetch';

const LOAD_STARGAZERS_SUCCESS = 'LOAD_STARGAZERS_SUCCESS';

const initialState = {
  stargazers: '515'
};

export function loadStargazers() {
  return dispatch => {
    fetch('https://api.github.com/repos/moroshko/react-autosuggest')
      .then(response => response.json())
      .then(response => {
        dispatch({
          type: LOAD_STARGAZERS_SUCCESS,
          stargazers: String(response.stargazers_count)
        });
      });
  };
}

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case LOAD_STARGAZERS_SUCCESS:
      return {
        ...state,
        stargazers: action.stargazers
      };

    default:
      return state;
  }
}
<|endoftext|>


<commit_before>/*
 * Boardfarm Management application
 * Copyright (c) 2016 Heiko Stuebner <heiko@sntech.de>
 *
 * License:
 *   MIT: https://opensource.org/licenses/MIT
 *   See the LICENSE file in the project's top-level directory for details.
 */

var power = require("./Power");
var ipower = require("./IPowerPort");
var exec = require('child_process').exec;

qx.Class.define("sn.boardfarm.backend.power.Ykush",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerAdapter ],

	construct : function(serial)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		console.log("Power: added Ykush hub " + serial);
		this.setAdapterIdent("ykush:"+serial);
		this.setSerial(serial);
		this.__states = { 0 : -1, 1 : -1, 2 : -1 };
		this.__ports = {};

		pwr.addAdapter(this.getAdapterIdent(), this);
	},

	events :
	{
		"adapterPowerChanged" : "qx.event.type.Data",
		"adapterPortStateChanged" : "qx.event.type.Data"
	},

	properties :
	{
		adapterIdent : {},
		serial : {}
	},

	members :
	{
		adapterReadPower : function()
		{
			/* can't read power measurements */
			this.fireDataEvent("adapterPowerChanged", 0);
		},

		__states : null,

		adapterReadState : function()
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			child = exec("ykush -s " + serial + " -g a", function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					this.__states = { 0 : -1, 1 : -1, 2 : -1 };
					return;
				}

				var data = stdout.split("\n");
				for (var i = 0; i < 3; i++) {
					var state = (data[i].indexOf(": DOWN") != -1) ? 0 : 1;
					base.__states[i] = state;
				}
			});
		},

		__ports : null,

		adapterAddPort : function(port, obj)
		{
			if (this.__ports[port])
				throw "Port "+port+" already set on "+this.getAdapterIdent();

			this.__ports[port] = obj;
		},

		adapterGetPortNum : function()
		{
			 return 3;
		},

		adapterShutdown : function()
		{
			for (var i = 0; i < this.adapterGetPortNum(); i++)
				this.adapterSetPortState(i, 0);
		},

		adapterGetPort : function(port)
		{
			if (!this.__ports[port])
				throw "Port "+port+" not set on "+this.getAdapterIdent();

			return this.__ports[port];
		},

		adapterGetPortState : function(port)
		{
			return this.__states[port];
		},

		adapterSetPortState : function(port, newState)
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			var cmd = newState ? "-u" : "-d";

			child = exec("ykush -s " + serial + " " + cmd + " " + (parseInt(port) + 1), function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					return;
				}

				base.__states[port] = newState;
				base.fireDataEvent("adapterPortStateChanged", { port : port, state : newState });
				console.log("Power: set port " + parseInt(port) + " of " + base.getAdapterIdent() + " to "+ newState);
			});
		}
	}
});

qx.Class.define("sn.boardfarm.backend.power.YkushPort",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerPort ],

	construct : function(serial, port)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		try {
			this.__adapter = pwr.getAdapter("ykush:"+serial);
		} catch(ex) {
			this.__adapter = new sn.boardfarm.backend.power.Ykush(serial);
		}

		this.setPort(port);
		this.__adapter.adapterAddPort(port, this);
	},

	properties :
	{
		port : {},
		board : {}
	},

	members :
	{
		__adapter : null,

		portGetAdapter : function()
		{
			return this.__adapter;
		},

		portGetState : function()
		{
			return this.portGetAdapter().adapterGetPortState(this.getPort());
		},

		portSetState : function(newState)
		{
			this.portGetAdapter().adapterSetPortState(this.getPort(), newState);
		}
	}
});
<commit_msg>Power: YKush: fix object reference in readstate<commit_after>/*
 * Boardfarm Management application
 * Copyright (c) 2016 Heiko Stuebner <heiko@sntech.de>
 *
 * License:
 *   MIT: https://opensource.org/licenses/MIT
 *   See the LICENSE file in the project's top-level directory for details.
 */

var power = require("./Power");
var ipower = require("./IPowerPort");
var exec = require('child_process').exec;

qx.Class.define("sn.boardfarm.backend.power.Ykush",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerAdapter ],

	construct : function(serial)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		console.log("Power: added Ykush hub " + serial);
		this.setAdapterIdent("ykush:"+serial);
		this.setSerial(serial);
		this.__states = { 0 : -1, 1 : -1, 2 : -1 };
		this.__ports = {};

		pwr.addAdapter(this.getAdapterIdent(), this);
	},

	events :
	{
		"adapterPowerChanged" : "qx.event.type.Data",
		"adapterPortStateChanged" : "qx.event.type.Data"
	},

	properties :
	{
		adapterIdent : {},
		serial : {}
	},

	members :
	{
		adapterReadPower : function()
		{
			/* can't read power measurements */
			this.fireDataEvent("adapterPowerChanged", 0);
		},

		__states : null,

		adapterReadState : function()
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			child = exec("ykush -s " + serial + " -g a", function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					base.__states = { 0 : -1, 1 : -1, 2 : -1 };
					return;
				}

				var data = stdout.split("\n");
				for (var i = 0; i < 3; i++) {
					var state = (data[i].indexOf(": DOWN") != -1) ? 0 : 1;
					base.__states[i] = state;
				}
			});
		},

		__ports : null,

		adapterAddPort : function(port, obj)
		{
			if (this.__ports[port])
				throw "Port "+port+" already set on "+this.getAdapterIdent();

			this.__ports[port] = obj;
		},

		adapterGetPortNum : function()
		{
			 return 3;
		},

		adapterShutdown : function()
		{
			for (var i = 0; i < this.adapterGetPortNum(); i++)
				this.adapterSetPortState(i, 0);
		},

		adapterGetPort : function(port)
		{
			if (!this.__ports[port])
				throw "Port "+port+" not set on "+this.getAdapterIdent();

			return this.__ports[port];
		},

		adapterGetPortState : function(port)
		{
			return this.__states[port];
		},

		adapterSetPortState : function(port, newState)
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			var cmd = newState ? "-u" : "-d";

			child = exec("ykush -s " + serial + " " + cmd + " " + (parseInt(port) + 1), function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					return;
				}

				base.__states[port] = newState;
				base.fireDataEvent("adapterPortStateChanged", { port : port, state : newState });
				console.log("Power: set port " + parseInt(port) + " of " + base.getAdapterIdent() + " to "+ newState);
			});
		}
	}
});

qx.Class.define("sn.boardfarm.backend.power.YkushPort",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerPort ],

	construct : function(serial, port)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		try {
			this.__adapter = pwr.getAdapter("ykush:"+serial);
		} catch(ex) {
			this.__adapter = new sn.boardfarm.backend.power.Ykush(serial);
		}

		this.setPort(port);
		this.__adapter.adapterAddPort(port, this);
	},

	properties :
	{
		port : {},
		board : {}
	},

	members :
	{
		__adapter : null,

		portGetAdapter : function()
		{
			return this.__adapter;
		},

		portGetState : function()
		{
			return this.portGetAdapter().adapterGetPortState(this.getPort());
		},

		portSetState : function(newState)
		{
			this.portGetAdapter().adapterSetPortState(this.getPort(), newState);
		}
	}
});
<|endoftext|>


<commit_before>'use strict';
(() => {
  module.exports = (gulp, plugins, config, taskParams) => {
    return () => {
      let spriteName = 'rocketbelt.icons';
      let enterprise = false;

      if (taskParams && taskParams.enterprise === true) {
        spriteName += '.enterprise.svg';
        enterprise = true;
      } else {
        spriteName += '.svg';
      }

      const options = {
        shape: {
          id: {
            generator: (file) => {
              return `rb-icon-${file.replace(/\.svg/, '')}`;
            }
          },
          meta: './rocketbelt/components/icons/rocketbelt.icons.meta.yaml',
          transform: [{
            svgo: {
              plugins: [
                { removeViewBox: true },
                { removeUnusedNS: true },
                { removeAttrs: { attrs: '(stroke|fill)' } }
              ]
            }
          }]
        },
        mode: {
          inline: true,
          symbol: {
            dest: './sprite',
            sprite: `../../${spriteName}`,
            prefix: '.'
          }
        }
      };

      const iconsPath = `${config.patternsPath}/components/icons`;
      const sketchFiles = enterprise ? '/**/*.sketch' : '/**/rocketbelt.icons.sketch';

      return gulp.src(iconsPath + sketchFiles)
        .pipe(plugins.sketch({
          export: 'artboards',
          formats: 'svg'
        }))
        .pipe(plugins.removeHtmlComments())
        .pipe(gulp.dest(`${iconsPath}/svg`))
        .pipe(plugins.svgSprite(options))
        .pipe(plugins.cheerio({
          xmlMode: true,
          recognizeSelfClosing: true,
          // lowerCaseAttributeNames: false,
          run: ($) => {
            $('symbol[id^=rb-icon-]').each(function elHandler() {
              const $symbol = $(this);
              // const grayMinus2 = '#4a4647';
              $symbol.css('fill', 'var(--color, inherit)');

              // The following lines are necessary because cheerio lowercases attribute names,
              // despite the value of the `lowerCaseAttributeNames` option above…
              // and `viewBox` is case-sensitive. 😿
              $symbol.attr('viewBox', $symbol.attr('viewbox'));
              $symbol.removeAttr('viewbox');
            });
          }
        }))
        .pipe(plugins.htmltidy(
          {
            inputXml: true,
            outputXml: true,
            indent: true,
            indentSpaces: 2,
            wrapAttributes: false
          }
        ))
        .pipe(gulp.dest(`${iconsPath}/svg`))
      ;
    };
  };
})();
<commit_msg>docs(Icons): Remove stale comment.<commit_after>'use strict';
(() => {
  module.exports = (gulp, plugins, config, taskParams) => {
    return () => {
      let spriteName = 'rocketbelt.icons';
      let enterprise = false;

      if (taskParams && taskParams.enterprise === true) {
        spriteName += '.enterprise.svg';
        enterprise = true;
      } else {
        spriteName += '.svg';
      }

      const options = {
        shape: {
          id: {
            generator: (file) => {
              return `rb-icon-${file.replace(/\.svg/, '')}`;
            }
          },
          meta: './rocketbelt/components/icons/rocketbelt.icons.meta.yaml',
          transform: [{
            svgo: {
              plugins: [
                { removeViewBox: true },
                { removeUnusedNS: true },
                { removeAttrs: { attrs: '(stroke|fill)' } }
              ]
            }
          }]
        },
        mode: {
          inline: true,
          symbol: {
            dest: './sprite',
            sprite: `../../${spriteName}`,
            prefix: '.'
          }
        }
      };

      const iconsPath = `${config.patternsPath}/components/icons`;
      const sketchFiles = enterprise ? '/**/*.sketch' : '/**/rocketbelt.icons.sketch';

      return gulp.src(iconsPath + sketchFiles)
        .pipe(plugins.sketch({
          export: 'artboards',
          formats: 'svg'
        }))
        .pipe(plugins.removeHtmlComments())
        .pipe(gulp.dest(`${iconsPath}/svg`))
        .pipe(plugins.svgSprite(options))
        .pipe(plugins.cheerio({
          xmlMode: true,
          recognizeSelfClosing: true,
          // lowerCaseAttributeNames: false,
          run: ($) => {
            $('symbol[id^=rb-icon-]').each(function elHandler() {
              const $symbol = $(this);
              $symbol.css('fill', 'var(--color, inherit)');

              // The following lines are necessary because cheerio lowercases attribute names,
              // despite the value of the `lowerCaseAttributeNames` option above…
              // and `viewBox` is case-sensitive. 😿
              $symbol.attr('viewBox', $symbol.attr('viewbox'));
              $symbol.removeAttr('viewbox');
            });
          }
        }))
        .pipe(plugins.htmltidy(
          {
            inputXml: true,
            outputXml: true,
            indent: true,
            indentSpaces: 2,
            wrapAttributes: false
          }
        ))
        .pipe(gulp.dest(`${iconsPath}/svg`))
      ;
    };
  };
})();
<|endoftext|>