<commit_before>var express = require('express');
var pg = require('pg');
var db_info = require('./db_info.js')
var app = express();
var pool = new pg.Pool(db_info.config);

app.get('/', function (req, res) {
  res.jsonp('Hello World!');
});

/****************************************************
* /path     /checkout/:id/:person/:qty
* /params   id
*           person
*           qty
* /brief    Route to remove some :qty from inventory
*
* /author   Luke?
****************************************************/
app.get('/checkout/:id/:person/:qty', function(req, res) {
    transaction(req.params.id, req.params.person, -req.params.qty, errResultHandler, res);
});

/****************************************************
* /path     /checkin/:id/:person/:qty
* /params   id
*           person
*           qty
* /brief    Route to add quantity to an existing item in the inventory
*
* /author   Luke
****************************************************/
app.get('/checkin/:id/:person/:qty', function(req, res) {
    transaction(req.params.id, req.params.person, req.params.qty, errResultHandler, res);
});

/****************************************************
* /path     N/A
* /brief    Helper function for checkin route
*
* /author   Luke
****************************************************/
var transaction = function(id, person, qty, retFunc, res) {

    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }

         client.query('INSERT INTO transactions(item_id, person, qty_changed) VALUES ($1, $2, $3)', [id, person, qty], function(err, result) {
            //call `done()` to release the client back to the pool
            done();

            if(err) {
                console.error('error running query', err);
                retFunc(err, null, res);
            } else {
                retFunc(null, 'Transaction Completed Successfully', res);
            }
        });
    });
}

/****************************************************
* /path     /view
* /params   null
* /brief    Display all entries in the items table
*
* /author   <insert name>
****************************************************/
app.get('/view', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT item_id, item_name AS name, description, quantity FROM items', [], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, result.rows, res);
        });
    });
});

/****************************************************
* /path     /add/:name/:desc/:price/:thresh
* /params   name - the name of the item
*           desc - the item description
*           price - the price of the item in decimal form
*           thresh - the threshold to notify the admin if the quantity drops below
*
* /brief    Add new item api route, used to insert rows into
*
* /author   Austen & Luke
* /date     2/7/2017
****************************************************/
app.get('/add/:name/:desc/:price/:thresh', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('INSERT INTO items(item_name, description, price, threshold) VALUES ($1, $2, $3, $4)',
        [req.params.name, req.params.desc, req.params.price, req.params.thresh], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, 'Item Added Successfully', res);
        });
    });
});

/****************************************************
* /path     /tagitem/:id/:tag
* /params   :id - The id of the item to tag
*           :tag - the name of the tag to give the item
*
* /brief    Add a tag to an item given its id
*
* /author   Luke
* /date     2/7/2017
****************************************************/
app.get('/tagitem/:id/:tag', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('INSERT INTO tags VALUES ($1, $2)',
                    [req.params.tag, req.params.id], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, 'Tag Added Successfully', res);
        });
    });
});

/****************************************************
* /path     /shoppinglist
* /params   null
* /brief    Returns all items with quantity less than threshold
*
* /author   Luke
****************************************************/
app.get('/shoppinglist', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT item_name AS name, description, price FROM items WHERE quantity < threshold', [], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, result.rows, res);
        });
    });
});

/****************************************************
* /path     /stats/:id
* /params
*
*
* /brief    Route to pull satistics for an item
*           should probably be renamed to be more specific
*
* /author   Andrew McCann
* /date     2/3/2017
****************************************************/
app.get('/stats/:id', function(err, client, done) {
    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('Error fetching client from pool', err);
        }
        /*
        client.query('INSERT INTO transactions(item_id, person, qty_changed) VALUES ($1, $2, $3)', [id, person, qty], function(err, result) {
        client.query('SELECT item_name, quantity, blahbalh
        client.query('SELECT * FROM transactions WHERE item_name = id', [], function(err, result) {
            done();

            if(err)
                return console.error('Error returned from DB', err);

            res.jsonp(result.rows);
        }*/
    });
});

/****************************************************
* /path     /stats/range/:start_date/:end_date
* /params   :start_date - Beginning of time frame
*           :end_date - End of time frame
*
* /brief    Route to pull all stats from a date_range
*
* /author   Andrew McCann
* /date     2/3/2017
****************************************************/
app.get('/stats/range/:start_date/:end_date', function(err, client, done) {
    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('Error fetching client from pool', err);
        }
        /*
        client.query('SELECT * FROM transactions WHERE date <= end_date AND date >= start_date', [], function(err, result) {
            done();
            if(err) {
                return console.error('Error resulting from query', err);
            }
        } */
    });

});

/****************************************************
* /path     N/A
* /params   :err - the error that occured, null if none
*           :result - the result of the database query
                      (either the rows returned or success message)
            :res - the function to handle the responding the result
*
* /brief    Responds with a meaningful status and returns the results
*
* /author   Luke
* /date     2/7/2017
****************************************************/
var errResultHandler = function(err, result, res) {
    if (err) {
      res.status(500);
      res.jsonp('Database Error');
    } else {
      res.status(200);
      res.jsonp(result);
    }
}

app.listen(3000, function () {
  console.log('Listening on port 3000');
});
<commit_msg>Fix function comments again.<commit_after>var express = require('express');
var pg = require('pg');
var db_info = require('./db_info.js')
var app = express();
var pool = new pg.Pool(db_info.config);

app.get('/', function (req, res) {
  res.jsonp('Hello World!');
});

/****************************************************
* /path     /checkout/:id/:person/:qty
* /params   id
*           person
*           qty
* /brief    Route to remove some :qty from inventory
*
* /author   Luke?
****************************************************/
app.get('/checkout/:id/:person/:qty', function(req, res) {
    transaction(req.params.id, req.params.person, -req.params.qty, errResultHandler, res);
});

/****************************************************
* /path     /checkin/:id/:person/:qty
* /params   id
*           person
*           qty
* /brief    Route to add quantity to an existing item in the inventory
*
* /author   Luke
****************************************************/
app.get('/checkin/:id/:person/:qty', function(req, res) {
    transaction(req.params.id, req.params.person, req.params.qty, errResultHandler, res);
});

/****************************************************
* /func name  transaction
* /brief      Helper function for checkin route
*
* /author     Luke
****************************************************/
var transaction = function(id, person, qty, retFunc, res) {

    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }

         client.query('INSERT INTO transactions(item_id, person, qty_changed) VALUES ($1, $2, $3)', [id, person, qty], function(err, result) {
            //call `done()` to release the client back to the pool
            done();

            if(err) {
                console.error('error running query', err);
                retFunc(err, null, res);
            } else {
                retFunc(null, 'Transaction Completed Successfully', res);
            }
        });
    });
}

/****************************************************
* /path     /view
* /params   null
* /brief    Display all entries in the items table
*
* /author   <insert name>
****************************************************/
app.get('/view', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT item_id, item_name AS name, description, quantity FROM items', [], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, result.rows, res);
        });
    });
});

/****************************************************
* /path     /add/:name/:desc/:price/:thresh
* /params   name - the name of the item
*           desc - the item description
*           price - the price of the item in decimal form
*           thresh - the threshold to notify the admin if the quantity drops below
*
* /brief    Add new item api route, used to insert rows into
*
* /author   Austen & Luke
* /date     2/7/2017
****************************************************/
app.get('/add/:name/:desc/:price/:thresh', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('INSERT INTO items(item_name, description, price, threshold) VALUES ($1, $2, $3, $4)',
        [req.params.name, req.params.desc, req.params.price, req.params.thresh], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, 'Item Added Successfully', res);
        });
    });
});

/****************************************************
* /path     /tagitem/:id/:tag
* /params   :id - The id of the item to tag
*           :tag - the name of the tag to give the item
*
* /brief    Add a tag to an item given its id
*
* /author   Luke
* /date     2/7/2017
****************************************************/
app.get('/tagitem/:id/:tag', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('INSERT INTO tags VALUES ($1, $2)',
                    [req.params.tag, req.params.id], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, 'Tag Added Successfully', res);
        });
    });
});

/****************************************************
* /path     /shoppinglist
* /params   null
* /brief    Returns all items with quantity less than threshold
*
* /author   Luke
****************************************************/
app.get('/shoppinglist', function(req, res){
  //first query the database
  //then return the results to the user

      pool.connect(function(err, client, done) {
        if(err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT item_name AS name, description, price FROM items WHERE quantity < threshold', [], function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            errResultHandler(err, result.rows, res);
        });
    });
});

/****************************************************
* /path     /stats/:id
* /params
*
*
* /brief    Route to pull satistics for an item
*           should probably be renamed to be more specific
*
* /author   Andrew McCann
* /date     2/3/2017
****************************************************/
app.get('/stats/:id', function(err, client, done) {
    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('Error fetching client from pool', err);
        }
        /*
        client.query('INSERT INTO transactions(item_id, person, qty_changed) VALUES ($1, $2, $3)', [id, person, qty], function(err, result) {
        client.query('SELECT item_name, quantity, blahbalh
        client.query('SELECT * FROM transactions WHERE item_name = id', [], function(err, result) {
            done();

            if(err)
                return console.error('Error returned from DB', err);

            res.jsonp(result.rows);
        }*/
    });
});

/****************************************************
* /path     /stats/range/:start_date/:end_date
* /params   :start_date - Beginning of time frame
*           :end_date - End of time frame
*
* /brief    Route to pull all stats from a date_range
*
* /author   Andrew McCann
* /date     2/3/2017
****************************************************/
app.get('/stats/range/:start_date/:end_date', function(err, client, done) {
    pool.connect(function(err, client, done) {
        if(err) {
            return console.error('Error fetching client from pool', err);
        }
        /*
        client.query('SELECT * FROM transactions WHERE date <= end_date AND date >= start_date', [], function(err, result) {
            done();
            if(err) {
                return console.error('Error resulting from query', err);
            }
        } */
    });

});

/****************************************************
* /func name  errResultHandler
* /params     :err - the error that occured, null if none
*             :result - the result of the database query
                      (either the rows returned or success message)
              :res - the function to handle the responding the result
*
* /brief      Responds with a meaningful status and returns the results
*
* /author     Luke
* /date       2/7/2017
****************************************************/
var errResultHandler = function(err, result, res) {
    if (err) {
      res.status(500);
      res.jsonp('Database Error');
    } else {
      res.status(200);
      res.jsonp(result);
    }
}

app.listen(3000, function () {
  console.log('Listening on port 3000');
});
<|endoftext|>


<commit_before>import React from 'react';
import { Route } from 'react-router';

import App from './containers/app';
import Home from './containers/home';
import NoMatch from './containers/no-match';

export default (
  <Route component={App}>
    <Route path="/" component={Home} />
    <Route path="*" component={NoMatch}/>
  </Route>
);
<commit_msg>Update routes<commit_after>import React from 'react';
import { Route } from 'react-router';

import App from './containers/app';
import AuctionDetail from './containers/auction-detail';
import Auctions from './containers/auctions';
import Home from './containers/home';
import NoMatch from './containers/no-match';

export default (
  <Route component={App}>
    <Route path="/" component={Home} />
    <Route path="/auctions/:buyerId" component={Auctions} />
    <Route path="/auctions/detail/:buyerId/:auctionId" component={AuctionDetail} />
    <Route path="*" component={NoMatch}/>
  </Route>
);
<|endoftext|>


<commit_before>'use strict';

describe('basic frontend testing', function () {

  var deltaMs = 200;

  beforeEach(function () {
    browser.get('/');
  });

  it('time ago directive', function () {
    expect(element(by.css('.directive-example')).getText()).toMatch(/^(Directive Example\nYou opened this demo page )(less than|about)( a minute ago)$/);
  });

  it('time ago filter', function () {
    expect(element(by.css('.filter-example')).getText()).toMatch(/^(Filter Example\nYou opened this demo page )(less than|about)( a minute ago)$/);
  });

  it('loading time', function () {
    var testStartTime = Date.now();
    element(by.css('.loading-time')).getText().then(function (loadingTimeText) {
      var pageLoadingTimestamp = loadingTimeText.replace('Page load time: ', '');
      var pageLoadtimeMs = new Date(pageLoadingTimestamp).getTime();
      expect(Math.abs(pageLoadtimeMs - testStartTime) < deltaMs).toBe(true);
    })
  });

  it('current time is changing', function () {
    browser.sleep(1000);
    element(by.css('.current-time')).getText().then(function (pageNowTimeText) {
      var pageNowMs = parseInt(pageNowTimeText.replace('Current time: ', ''));
      expect(Math.abs(pageNowMs - Date.now()) < deltaMs).toBe(true);
    })
  });

});

<commit_msg>Updating test delta b/c my computer apparently can't handle 200ms<commit_after>'use strict';

describe('basic frontend testing', function () {

  var deltaMs = 300;

  beforeEach(function () {
    browser.get('/');
  });

  it('time ago directive', function () {
    expect(element(by.css('.directive-example')).getText()).toMatch(/^(Directive Example\nYou opened this demo page )(less than|about)( a minute ago)$/);
  });

  it('time ago filter', function () {
    expect(element(by.css('.filter-example')).getText()).toMatch(/^(Filter Example\nYou opened this demo page )(less than|about)( a minute ago)$/);
  });

  it('loading time', function () {
    var testStartTime = Date.now();
    element(by.css('.loading-time')).getText().then(function (loadingTimeText) {
      var pageLoadingTimestamp = loadingTimeText.replace('Page load time: ', '');
      var pageLoadtimeMs = new Date(pageLoadingTimestamp).getTime();
      expect(Math.abs(pageLoadtimeMs - testStartTime) < deltaMs).toBe(true);
    })
  });

  it('current time is changing', function () {
    browser.sleep(1000);
    element(by.css('.current-time')).getText().then(function (pageNowTimeText) {
      var pageNowMs = parseInt(pageNowTimeText.replace('Current time: ', ''));
      expect(Math.abs(pageNowMs - Date.now()) < deltaMs).toBe(true);
    })
  });

});

<|endoftext|>


<commit_before>var eviltransform = require('eviltransform');

function gll2ll(gll, gcj02) {
  var ll;
  if (!gll) {
    return;
  }
  ll = [gll.lng(), gll.lat()];
  if (!(gcj02 && this.isGCJ02 && this.isGCJ02(ll))) {
    return ll;
  }
  ll = eviltransform.gcj2wgs(ll[1], ll[0]);
  return [ll.lng, ll.lat];
}

function ll2gll(ll, gcj02) {
  var LatLng = gm().LatLng;
  if (!(gcj02 && this.isGCJ02(ll))) {
    return new LatLng(ll[1], ll[0]);
  }
  ll = eviltransform.wgs2gcj(ll[1], ll[0]);
  return new LatLng(ll.lat, ll.lng);
}

function bounds2gbounds(b, gcj02) {
  var LatLngBounds = gm().LatLngBounds;
  b = b.map(function (ll) {
    return ll2gll.call(this, ll, gcj02);
  }, this);
  return new LatLngBounds(b[0], b[1]);
}

function gbounds2bounds(gb, gcj02) {
  return gb && [
    gb.getSouthWest(),
    gb.getNorthEast()
  ].map(function (gll) {
    return gll2ll.call(this, gll, gcj02);
  }, this);
}

function decodePath(path) {
  return gm().geometry.encoding.decodePath(path);
}

function path2gpath(path, gcj02) {
  if (path.gmPath) {
    path = path.gmPath;
  }
  else if (Array.isArray(path)) {
    if (Array.isArray(path[0])) {
      path = path.gmPath = path.map(function (ll) {
        return ll2gll.call(this, ll, gcj02);
      }, this);
    }
  }
  else if (typeof path === 'string') {
    path = decodePath(path);
  }
  return path;
}

function gm() {
  if (!window.google || !window.google.maps) {
    throw 'Google Maps not initialized properly: call maps.init()';
  }
  return window.google.maps;
}

module.exports = {
  decodePath: decodePath,
  gll2ll: gll2ll,
  ll2gll: ll2gll,
  bounds2gbounds: bounds2gbounds,
  gbounds2bounds: gbounds2bounds,
  path2gpath: path2gpath,
  gm: gm
};<commit_msg>normalize longitude before checking if coordinates are in China<commit_after>var eviltransform = require('eviltransform');

function gll2ll(gll, gcj02) {
  var ll;
  if (!gll) {
    return;
  }
  ll = [gll.lng(), gll.lat()];
  if (ll[0] < -180) {
    ll[0] = ll[0] + 360;
  }
  else if (ll[0] > 180) {
    ll[0] = ll[0] - 360;
  }
  if (!(gcj02 && this.isGCJ02 && this.isGCJ02(ll))) {
    return ll;
  }
  ll = eviltransform.gcj2wgs(ll[1], ll[0]);
  return [ll.lng, ll.lat];
}

function ll2gll(ll, gcj02) {
  var LatLng = gm().LatLng;
  if (!(gcj02 && this.isGCJ02(ll))) {
    return new LatLng(ll[1], ll[0]);
  }
  ll = eviltransform.wgs2gcj(ll[1], ll[0]);
  return new LatLng(ll.lat, ll.lng);
}

function bounds2gbounds(b, gcj02) {
  var LatLngBounds = gm().LatLngBounds;
  b = b.map(function (ll) {
    return ll2gll.call(this, ll, gcj02);
  }, this);
  return new LatLngBounds(b[0], b[1]);
}

function gbounds2bounds(gb, gcj02) {
  return gb && [
    gb.getSouthWest(),
    gb.getNorthEast()
  ].map(function (gll) {
    return gll2ll.call(this, gll, gcj02);
  }, this);
}

function decodePath(path) {
  return gm().geometry.encoding.decodePath(path);
}

function path2gpath(path, gcj02) {
  if (path.gmPath) {
    path = path.gmPath;
  }
  else if (Array.isArray(path)) {
    if (Array.isArray(path[0])) {
      path = path.gmPath = path.map(function (ll) {
        return ll2gll.call(this, ll, gcj02);
      }, this);
    }
  }
  else if (typeof path === 'string') {
    path = decodePath(path);
  }
  return path;
}

function gm() {
  if (!window.google || !window.google.maps) {
    throw 'Google Maps not initialized properly: call maps.init()';
  }
  return window.google.maps;
}

module.exports = {
  decodePath: decodePath,
  gll2ll: gll2ll,
  ll2gll: ll2gll,
  bounds2gbounds: bounds2gbounds,
  gbounds2bounds: gbounds2bounds,
  path2gpath: path2gpath,
  gm: gm
};<|endoftext|>


<commit_before>//Swaps the default skill used when using ranged weapons.

//Find mov eax,00005209
//That's the ranged attack skill ID to change.

//Uncomment the line for the skill you want.

var pattern = scan('B8 09 52 00 00 5F');
//patch(pattern.add(1), 0x0A, 0x52); //Magnum Shot
//patch(pattern.add(1), 0x0C, 0x52); //Arrow Revolver
//patch(pattern.add(1), 0x0E, 0x52); //Support Shot
//patch(pattern.add(1), 0x0F, 0x52); //Mirage Missile
//patch(pattern.add(1), 0xFB, 0x55); //Crash Shot
//patch(pattern.add(1), 0x14, 0x52); //Spider Shot
//patch(pattern.add(1), 0x14, 0x52); //Urgent Shot
<commit_msg>Corrected urgent shot<commit_after>//Swaps the default skill used when using ranged weapons.

//Find mov eax,00005209
//That's the ranged attack skill ID to change.

//Uncomment the line for the skill you want.

var pattern = scan('B8 09 52 00 00 5F');
//patch(pattern.add(1), 0x0A, 0x52); //Magnum Shot
//patch(pattern.add(1), 0x0C, 0x52); //Arrow Revolver
//patch(pattern.add(1), 0x0E, 0x52); //Support Shot
//patch(pattern.add(1), 0x0F, 0x52); //Mirage Missile
//patch(pattern.add(1), 0xFB, 0x55); //Crash Shot
//patch(pattern.add(1), 0x14, 0x52); //Spider Shot
//patch(pattern.add(1), 0x16, 0x52); //Urgent Shot
<|endoftext|>


<commit_before>'use strict';

module.exports = function(leadAttributes) {
  return '<tns:paramsSyncLead>' +
    '<leadRecord>' +
    '<Email>' + leadAttributes.Email + '</Email>' +
    '<leadAttributeList>' +
    '<attribute>' +
    '<attrName>FirstName</attrName><attrValue>' + leadAttributes.FirstName + '</attrValue>' +
    '</attribute>' +
    '<attribute>' +
    '<attrName>LastName</attrName><attrValue>' + leadAttributes.LastName + '</attrValue>' +
    '</attribute>' +
    jobTitle(leadAttributes) + company(leadAttributes) +
    phone(leadAttributes) + leadStatus(leadAttributes) +
    leadScore(leadAttributes) + address(leadAttributes) +
    city(leadAttributes) + state(leadAttributes) +
    postCode(leadAttributes) + country(leadAttributes)+
    bestTime(leadAttributes) + leadNotes(leadAttributes) +
    optIn(leadAttributes) +
    '</leadAttributeList>' +
    '</leadRecord>' +
    '<returnLead>true</returnLead>' +
    '</tns:paramsSyncLead>';
};

function jobTitle(leadAttributes){
	if(leadAttributes.Title){
 		return '<attribute>' +
    		'<attrName>Title</attrName><attrValue>' + leadAttributes.Title + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

function company(leadAttributes){
	if(leadAttributes.Company){
    	return '<attribute>' +
    		'<attrName>Company</attrName><attrValue>' + leadAttributes.Company + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

   //MainPhone
function phone(leadAttributes){
    if(leadAttributes.Phone){
	    return'<attribute>' +
    		'<attrName>Phone</attrName><attrValue>' + leadAttributes.Phone + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

	 //LeadStatus
function leadStatus(leadAttributes){
    if(leadAttributes.LeadStatus){
		return '<attribute>' +
		    '<attrName>LeadStatus</attrName><attrValue>' + leadAttributes.LeadStatus + '</attrValue>' +
		    '</attribute>' }
    else {return '';}
};
 //LeadScore
function leadScore(leadAttributes){
    if(leadAttributes.LeadScore){
		return '<attribute>' +
    		'<attrName>LeadScore</attrName><attrValue>' + leadAttributes.LeadScore + '</attrValue>' +
    		'</attribute>'  }
    else {return '';}
};
//LeadSource
function leadSource(leadAttributes){
    if(leadAttributes.LeadSource){
		return '<attribute>' +
    		'<attrName>LeadSource</attrName><attrValue>' + leadAttributes.LeadSource + '</attrValue>' +
    		'</attribute>'  }
    else {return '';}
};
//Address
function address(leadAttributes){
    if(leadAttributes.Address){
		return '<attribute>' +
    		'<attrName>Address</attrName><attrValue>' + leadAttributes.Address + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};
//City
function city(leadAttributes){
	if(leadAttributes.City){
		return '<attribute>' +
    		'<attrName>City</attrName><attrValue>' + leadAttributes.City + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};
//State
function state(leadAttributes){
	if(leadAttributes.State){
		return '<attribute>' +
    		'<attrName>State</attrName><attrValue>' + leadAttributes.State + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};
//PostalCode
function postCode(leadAttributes){
	if(leadAttributes.PostalCode){
		return '<attribute>' +
    		'<attrName>PostalCode</attrName><attrValue>' + leadAttributes.PostalCode + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

//Country
function country(leadAttributes){
    if(leadAttributes.Country){
	    return '<attribute>' +
    		'<attrName>Country</attrName><attrValue>' + leadAttributes.Country + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

//BestTimetoContact
function bestTime(leadAttributes){
	if(leadAttributes.BestTimetoContact){
		return '<attribute>' +
    		'<attrName>BestTimetoContact</attrName><attrValue>' + leadAttributes.BestTimetoContact + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

function leadNotes(leadAttributes){
    if(leadAttributes.LeadNotes){
        return '<attribute>' +
            '<attrName>leadAdditionalNotes</attrName><attrValue>' + leadAttributes.LeadNotes + '</attrValue>' +
            '</attribute>' }
    else {return '';}
};

function optIn(leadAttributes){
    if(leadAttributes.OptIn){
        return '<attribute>' +
            '<attrName>OptIn</attrName><attrValue>' + leadAttributes.OptIn + '</attrValue>' +
            '</attribute>' }
    else {return '';}
};<commit_msg>added sourceForm<commit_after>'use strict';

module.exports = function(leadAttributes) {
  return '<tns:paramsSyncLead>' +
    '<leadRecord>' +
    '<Email>' + leadAttributes.Email + '</Email>' +
    '<leadAttributeList>' +
    '<attribute>' +
    '<attrName>FirstName</attrName><attrValue>' + leadAttributes.FirstName + '</attrValue>' +
    '</attribute>' +
    '<attribute>' +
    '<attrName>LastName</attrName><attrValue>' + leadAttributes.LastName + '</attrValue>' +
    '</attribute>' +
    jobTitle(leadAttributes) + company(leadAttributes) +
    phone(leadAttributes) + leadStatus(leadAttributes) +
    leadScore(leadAttributes) + address(leadAttributes) +
    city(leadAttributes) + state(leadAttributes) +
    postCode(leadAttributes) + country(leadAttributes)+
    bestTime(leadAttributes) + leadNotes(leadAttributes) +
    optIn(leadAttributes) + sourceForm(leadAttributes) +
    '</leadAttributeList>' +
    '</leadRecord>' +
    '<returnLead>true</returnLead>' +
    '</tns:paramsSyncLead>';
};

function jobTitle(leadAttributes){
	if(leadAttributes.Title){
 		return '<attribute>' +
    		'<attrName>Title</attrName><attrValue>' + leadAttributes.Title + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

function company(leadAttributes){
	if(leadAttributes.Company){
    	return '<attribute>' +
    		'<attrName>Company</attrName><attrValue>' + leadAttributes.Company + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

   //MainPhone
function phone(leadAttributes){
    if(leadAttributes.Phone){
	    return'<attribute>' +
    		'<attrName>Phone</attrName><attrValue>' + leadAttributes.Phone + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

	 //LeadStatus
function leadStatus(leadAttributes){
    if(leadAttributes.LeadStatus){
		return '<attribute>' +
		    '<attrName>LeadStatus</attrName><attrValue>' + leadAttributes.LeadStatus + '</attrValue>' +
		    '</attribute>' }
    else {return '';}
};
 //LeadScore
function leadScore(leadAttributes){
    if(leadAttributes.LeadScore){
		return '<attribute>' +
    		'<attrName>LeadScore</attrName><attrValue>' + leadAttributes.LeadScore + '</attrValue>' +
    		'</attribute>'  }
    else {return '';}
};
//LeadSource
function leadSource(leadAttributes){
    if(leadAttributes.LeadSource){
		return '<attribute>' +
    		'<attrName>LeadSource</attrName><attrValue>' + leadAttributes.LeadSource + '</attrValue>' +
    		'</attribute>'  }
    else {return '';}
};
//Address
function address(leadAttributes){
    if(leadAttributes.Address){
		return '<attribute>' +
    		'<attrName>Address</attrName><attrValue>' + leadAttributes.Address + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};
//City
function city(leadAttributes){
	if(leadAttributes.City){
		return '<attribute>' +
    		'<attrName>City</attrName><attrValue>' + leadAttributes.City + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};
//State
function state(leadAttributes){
	if(leadAttributes.State){
		return '<attribute>' +
    		'<attrName>State</attrName><attrValue>' + leadAttributes.State + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};
//PostalCode
function postCode(leadAttributes){
	if(leadAttributes.PostalCode){
		return '<attribute>' +
    		'<attrName>PostalCode</attrName><attrValue>' + leadAttributes.PostalCode + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

//Country
function country(leadAttributes){
    if(leadAttributes.Country){
	    return '<attribute>' +
    		'<attrName>Country</attrName><attrValue>' + leadAttributes.Country + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

//BestTimetoContact
function bestTime(leadAttributes){
	if(leadAttributes.BestTimetoContact){
		return '<attribute>' +
    		'<attrName>BestTimetoContact</attrName><attrValue>' + leadAttributes.BestTimetoContact + '</attrValue>' +
    		'</attribute>' }
    else {return '';}
};

function leadNotes(leadAttributes){
    if(leadAttributes.LeadNotes){
        return '<attribute>' +
            '<attrName>leadAdditionalNotes</attrName><attrValue>' + leadAttributes.LeadNotes + '</attrValue>' +
            '</attribute>' }
    else {return '';}
};

function optIn(leadAttributes){
    if(leadAttributes.OptIn){
        return '<attribute>' +
            '<attrName>OptIn</attrName><attrValue>' + leadAttributes.OptIn + '</attrValue>' +
            '</attribute>' }
    else {return '';}
};

function sourceForm(leadAttributes){
    if(leadAttributes.SourceForm){
        return '<attribute>' +
            '<attrName>sourceForm</attrName><attrValue>' + leadAttributes.SourceForm + '</attrValue>' +
            '</attribute>' }
    else {return '';}
}<|endoftext|>


<commit_before>var Broker = require('./broker');

exports.createBroker = function(messageListener) {
  var broker = new Broker();
  if (messageListener) { broker.on('message', messageListener); }
  return broker;
}

exports.Broker = Broker;
<commit_msg>Add documentation.<commit_after>/**
 * Module dependencies.
 */
var Broker = require('./broker');

/**
 * Create broker with optional message listener.
 *
 * @param {Function} messageListener
 * @return {Broker}
 * @api public
 */
exports.createBroker = function(messageListener) {
  var broker = new Broker();
  if (messageListener) { broker.on('message', messageListener); }
  return broker;
}

/**
 * Export constructors.
 */
exports.Broker = Broker;
<|endoftext|>


<commit_before>describe('Legend Visualization', function () {
    var $el, el;
    var instance;

    beforeEach(function () {
        $el = $('<div>');
        el = $el.get(0);
        document.body.appendChild(el);
    });

    afterEach(function () {
        document.body.removeChild(el);
    })

    function createinstance(options) {
        options = _.extend({ el: el }, options);

        instance = new Contour(options).cartesian();
        return instance;
    }

    it('should create a div with the text for each data series', function () {
        var data = [
            { name: 'name-1', data: [] },
            { name: 'name-2', data: [] }
        ];

        createinstance().nullVis(data).legend(data).render();

        var entries = $el.find('div.contour-legend .contour-legend-entry');
        expect(entries.length).toBe(2);
        expect(entries.eq(0).text()).toBe('name-1');
        expect(entries.eq(1).text()).toBe('name-2');
    });

    it('should create a svg text with the text for each data series', function () {
        var data = [
            { name: 'name-1', data: [] },
            { name: 'name-2', data: [] }
        ];

        createinstance().nullVis(data).legend(data).render();

        var entries = $el.find('g[vis-type="legend"] g.contour-legend g.contour-legend-entry');
        expect(entries.length).toBe(2);
        expect(entries.eq(0).find('text').text()).toBe('name-1');
        expect(entries.eq(1).find('text').text()).toBe('name-2');
    });

});
<commit_msg>comment on legend spec<commit_after>describe('Legend Visualization', function () {
    var $el, el;
    var instance;

    beforeEach(function () {
        $el = $('<div>');
        el = $el.get(0);
        // div must have layout in order to build svg legend
        document.body.appendChild(el);
    });

    afterEach(function () {
        document.body.removeChild(el);
    })

    function createinstance(options) {
        options = _.extend({ el: el }, options);

        instance = new Contour(options).cartesian();
        return instance;
    }

    it('should create a div with the text for each data series', function () {
        var data = [
            { name: 'name-1', data: [] },
            { name: 'name-2', data: [] }
        ];

        createinstance().nullVis(data).legend(data).render();

        var entries = $el.find('div.contour-legend .contour-legend-entry');
        expect(entries.length).toBe(2);
        expect(entries.eq(0).text()).toBe('name-1');
        expect(entries.eq(1).text()).toBe('name-2');
    });

    it('should create a svg text with the text for each data series', function () {
        var data = [
            { name: 'name-1', data: [] },
            { name: 'name-2', data: [] }
        ];

        createinstance().nullVis(data).legend(data).render();

        var entries = $el.find('g[vis-type="legend"] g.contour-legend g.contour-legend-entry');
        expect(entries.length).toBe(2);
        expect(entries.eq(0).find('text').text()).toBe('name-1');
        expect(entries.eq(1).find('text').text()).toBe('name-2');
    });

});
<|endoftext|>


<commit_before>/* jshint ignore:start */
require(["neue/validation", "validation/auth", "validation/reportback"], function(Validation, auth, reportback) {
  module("Validation");

  test("Name", function() {
    Validation.Validations.name.fn("John", function(result) {
      ok(result.message == "Hey, John!", "should greet");
    });

    Validation.Validations.name.fn("", function(result) {
      ok(result.success == false, "should require name");
    });

  });

  test("Birthdays", function() {
    var now = new Date();
    var birthday_date = (now.getMonth() + 1) + "/" + now.getDate() + "/1990";
    var user_9_years_old = Math.min(now.getMonth() + 2, 12) + "/" + now.getDate() + "/" + (now.getFullYear() - 10);
    var user_19_years_old = Math.min(now.getMonth() + 2, 12) + "/" + now.getDate() + "/" + (now.getFullYear() - 20);

    Validation.Validations.birthday.fn(birthday_date, function(result) {
      ok(result.message == "Wow, happy birthday!", "should wish me a happy birthday");
    });

    Validation.Validations.birthday.fn(user_9_years_old, function(result) {
      ok(result.message == "Wow, you're 9!", "should tell young users their age");
    });

    Validation.Validations.birthday.fn(user_19_years_old, function(result) {
      ok(result.message == "Cool, 19!", "should tell me my age");
    });

    Validation.Validations.birthday.fn("yesterday", function(result) {
      ok(result.success == false, "should reject non-formatted dates");
    });

    Validation.Validations.birthday.fn("1/15/1960", function(result) {
      ok(result.message == "Yikes, you're old!", "should tell old people that they're old");
    });

    Validation.Validations.birthday.fn("1/15/1860", function(result) {
      ok(result.message == "That doesn't seem right.", "should reject users with birthdates too far in the past");
    });

    Validation.Validations.birthday.fn("1/15/2095", function(result) {
      ok(result.message == "Are you a time traveller?", "should reject users with future birthdates");
    });

    Validation.Validations.birthday.fn("61/12/1990", function(result) {
      ok(result.success == false, "should reject users with invalid month values");
    });

    Validation.Validations.birthday.fn("12/42/1990", function(result) {
      ok(result.success == false, "should reject users with day value greater than 31");
    });

    Validation.Validations.birthday.fn("10/25/90", function(result) {
      ok(result.success == false, "should reject dates with two-digit years");
    });

  });

  test("Emails", function() {
    Validation.Validations.email.fn("my.name@gmail.com", function(result) {
      ok(result.success == true, "should accept a valid email");
    });

    Validation.Validations.email.fn("my.name.com", function(result) {
      ok(result.success == false, "should reject an invalid email");
    });

    Validation.Validations.email.fn("myname@com", function(result) {
      ok(result.success == false, "should reject an invalid email");
    });

    Validation.Validations.email.fn("myname@gmail.123", function(result) {
      ok(result.success == false, "should reject an invalid email");
    });
  });

  test("Passwords", function() {
    Validation.Validations.password.fn("12345", function(result) {
      ok(result.success == false, "should reject if too short");
    });

    Validation.Validations.password.fn("super$ecure19", function(result) {
      ok(result.success == true, "should be totally chill with a good password");
    });
  });

  test("Match", function() {
    Validation.Validations.match.fn("dog", "cat", function(result) {
      ok(result.success == false, "should reject if different strings");
    });

    Validation.Validations.match.fn("dog", "Dog", function(result) {
      ok(result.success == false, "should reject if different capitalization");
    });

    Validation.Validations.match.fn("dog", "dog ", function(result) {
      ok(result.success == false, "should reject if different spacing");
    });

    Validation.Validations.match.fn("super$ecure19", "super$ecure19", function(result) {
      ok(result.success == true, "should accept if the same");
    });
  });

  test("Phone numbers", function() {
    Validation.Validations.phone.fn("123-456-7890", function(result) {
      ok(result.success == true, "should accept 10-digit number with dashes");
    });

    Validation.Validations.phone.fn("123.456 7890", function(result) {
      ok(result.success == true, "should accept 10-digit number with dot and space");
    });

    Validation.Validations.phone.fn("1 (123) 456-7890", function(result) {
      ok(result.success == true, "should accept 11-digit US number");
    });

    Validation.Validations.phone.fn("123-555-9942", function(result) {
      ok(result.success == false, "should reject number with repeating digits");
    });

    Validation.Validations.phone.fn("1 902 #@@ 1234", function(result) {
      ok(result.success == false, "should reject number with invalid symbols");
    });

    Validation.Validations.phone.fn("999 999 9999", function(result) {
      ok(result.success == false, "should reject number with all repeating digits");
    });
  });

  test("Reportback numbers", function() {
    Validation.Validations.positiveInteger.fn("19", function(result) {
      ok(result.success == true, "should accept a valid integer");
    });

    Validation.Validations.positiveInteger.fn(" 5", function(result) {
      ok(result.success == true, "should accept a number with space in front");
    });

    Validation.Validations.positiveInteger.fn("5 ", function(result) {
      ok(result.success == true, "should accept a number with space at the end");
    });

    Validation.Validations.positiveInteger.fn("two", function(result) {
      ok(result.success == false, "should reject a number spelled out as a string");
    });

    Validation.Validations.positiveInteger.fn("4.5", function(result) {
      ok(result.success == false, "should reject a decimal number");
    });

    Validation.Validations.positiveInteger.fn("0", function(result) {
      ok(result.success == false, "should reject zero");
    });
  });

});
<commit_msg>Update tests for new :older_man: :older_woman: validation language.<commit_after>/* jshint ignore:start */
require(["neue/validation", "validation/auth", "validation/reportback"], function(Validation, auth, reportback) {
  module("Validation");

  test("Name", function() {
    Validation.Validations.name.fn("John", function(result) {
      ok(result.message == "Hey, John!", "should greet");
    });

    Validation.Validations.name.fn("", function(result) {
      ok(result.success == false, "should require name");
    });

  });

  test("Birthdays", function() {
    var now = new Date();
    var birthday_date = (now.getMonth() + 1) + "/" + now.getDate() + "/1990";
    var user_9_years_old = Math.min(now.getMonth() + 2, 12) + "/" + now.getDate() + "/" + (now.getFullYear() - 10);
    var user_19_years_old = Math.min(now.getMonth() + 2, 12) + "/" + now.getDate() + "/" + (now.getFullYear() - 20);

    Validation.Validations.birthday.fn(birthday_date, function(result) {
      ok(result.message == "Wow, happy birthday!", "should wish me a happy birthday");
    });

    Validation.Validations.birthday.fn(user_9_years_old, function(result) {
      ok(result.message == "Wow, you're 9!", "should tell young users their age");
    });

    Validation.Validations.birthday.fn(user_19_years_old, function(result) {
      ok(result.message == "Cool, 19!", "should tell me my age");
    });

    Validation.Validations.birthday.fn("yesterday", function(result) {
      ok(result.success == false, "should reject non-formatted dates");
    });

    Validation.Validations.birthday.fn("1/15/1960", function(result) {
      ok(result.message == "Got it!", "should be cordial to old people");
    });

    Validation.Validations.birthday.fn("1/15/1860", function(result) {
      ok(result.message == "That doesn't seem right.", "should reject users with birthdates too far in the past");
    });

    Validation.Validations.birthday.fn("1/15/2095", function(result) {
      ok(result.message == "Are you a time traveller?", "should reject users with future birthdates");
    });

    Validation.Validations.birthday.fn("61/12/1990", function(result) {
      ok(result.success == false, "should reject users with invalid month values");
    });

    Validation.Validations.birthday.fn("12/42/1990", function(result) {
      ok(result.success == false, "should reject users with day value greater than 31");
    });

    Validation.Validations.birthday.fn("10/25/90", function(result) {
      ok(result.success == false, "should reject dates with two-digit years");
    });

  });

  test("Emails", function() {
    Validation.Validations.email.fn("my.name@gmail.com", function(result) {
      ok(result.success == true, "should accept a valid email");
    });

    Validation.Validations.email.fn("my.name.com", function(result) {
      ok(result.success == false, "should reject an invalid email");
    });

    Validation.Validations.email.fn("myname@com", function(result) {
      ok(result.success == false, "should reject an invalid email");
    });

    Validation.Validations.email.fn("myname@gmail.123", function(result) {
      ok(result.success == false, "should reject an invalid email");
    });
  });

  test("Passwords", function() {
    Validation.Validations.password.fn("12345", function(result) {
      ok(result.success == false, "should reject if too short");
    });

    Validation.Validations.password.fn("super$ecure19", function(result) {
      ok(result.success == true, "should be totally chill with a good password");
    });
  });

  test("Match", function() {
    Validation.Validations.match.fn("dog", "cat", function(result) {
      ok(result.success == false, "should reject if different strings");
    });

    Validation.Validations.match.fn("dog", "Dog", function(result) {
      ok(result.success == false, "should reject if different capitalization");
    });

    Validation.Validations.match.fn("dog", "dog ", function(result) {
      ok(result.success == false, "should reject if different spacing");
    });

    Validation.Validations.match.fn("super$ecure19", "super$ecure19", function(result) {
      ok(result.success == true, "should accept if the same");
    });
  });

  test("Phone numbers", function() {
    Validation.Validations.phone.fn("123-456-7890", function(result) {
      ok(result.success == true, "should accept 10-digit number with dashes");
    });

    Validation.Validations.phone.fn("123.456 7890", function(result) {
      ok(result.success == true, "should accept 10-digit number with dot and space");
    });

    Validation.Validations.phone.fn("1 (123) 456-7890", function(result) {
      ok(result.success == true, "should accept 11-digit US number");
    });

    Validation.Validations.phone.fn("123-555-9942", function(result) {
      ok(result.success == false, "should reject number with repeating digits");
    });

    Validation.Validations.phone.fn("1 902 #@@ 1234", function(result) {
      ok(result.success == false, "should reject number with invalid symbols");
    });

    Validation.Validations.phone.fn("999 999 9999", function(result) {
      ok(result.success == false, "should reject number with all repeating digits");
    });
  });

  test("Reportback numbers", function() {
    Validation.Validations.positiveInteger.fn("19", function(result) {
      ok(result.success == true, "should accept a valid integer");
    });

    Validation.Validations.positiveInteger.fn(" 5", function(result) {
      ok(result.success == true, "should accept a number with space in front");
    });

    Validation.Validations.positiveInteger.fn("5 ", function(result) {
      ok(result.success == true, "should accept a number with space at the end");
    });

    Validation.Validations.positiveInteger.fn("two", function(result) {
      ok(result.success == false, "should reject a number spelled out as a string");
    });

    Validation.Validations.positiveInteger.fn("4.5", function(result) {
      ok(result.success == false, "should reject a decimal number");
    });

    Validation.Validations.positiveInteger.fn("0", function(result) {
      ok(result.success == false, "should reject zero");
    });
  });

});
<|endoftext|>


<commit_before>/*
Name:         europeana.js
Description:  Unofficial node.js module for the Europeana API
Author:       Franklin van de Meent - https://frankl.in
Source:       https://github.com/fvdm/nodejs-europeana
Feedback:     https://github.com/fvdm/nodejs-europeana/issues
License:      Public Domain / Unlicense (see UNLICENSE file)
              (https://github.com/fvdm/nodejs-europeana/raw/master/UNLICENSE)
*/

var http = require ('httpreq');

var settings = {
  apikey: null,
  timeout: 5000
};

// errors
// http://www.europeana.eu/portal/api-working-with-api.html#Error-Codes

var errors = {
  400: 'The request sent by the client was syntactically incorrect',
  401: 'Authentication credentials were missing or authentication failed.',
  404: 'The requested record was not found.',
  429: 'The request could be served because the application has reached its usage limit.',
  500: 'Internal Server Error. Something has gone wrong, please report to us.'
};

/**
 * Make and call back error
 *
 * @callback callback
 * @param message {string} - Error.message
 * @param err {mixed} - Error.error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err) {}`
 * @returns {void}
 */

function doError (message, err, res, callback) {
  var error = new Error (message);

  error.code = res.statusCode;
  error.error = err || errors [res.statusCode] || null;
  error.data = res.body;
  callback (error);
}

/**
 * Process response
 *
 * @callback callback
 * @param err {Error, null} - httpreq error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpResponse (err, res, callback) {
  var data = res && res.body;
  var html;

  // client failed
  if (err) {
    doError ('request failed', err, res, callback);
    return;
  }

  // parse response
  try {
    data = JSON.parse (data);
  } catch (reason) {
    // weird API error
    if (data.match (/
HTTP Status /)) {
      html = data.replace (/.*description<\/b> (.+)<\/u><\/p>.*/, '$1');
      doError ('API error', html, res, callback);
    } else {
      doError ('invalid response', reason, res, callback);
    }
    return;
  }

  if (data.apikey) {
    delete data.apikey;
  }

  // API error
  if (!data.success && data.error) {
    doError ('API error', data.error, res, callback);
    return;
  }

  if (res.statusCode >= 300) {
    doError ('API error', null, res, callback);
    return;
  }

  // all good
  callback (null, data);
}

/**
 * Communicate with API
 *
 * @callback callback
 * @param path {string} - Method path between `/v2/` and `.json`
 * @param fields {object} - Method parameters
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpRequest (path, fields, callback) {
  var options = {
    method: 'GET',
    url: 'https://www.europeana.eu/api/v2/' + path + '.json',
    parameters: fields,
    timeout: settings.timeout,
    headers: {
      'User-Agent': 'europeana.js'
    }
  };

  if (typeof fields === 'function') {
    callback = fields;
    options.parameters = {};
  }

  // Request

  // check API key
  if (!settings.apikey) {
    callback (new Error ('apikey missing'));
    return;
  }

  options.parameters.wskey = settings.apikey;

  function doResponse (err, res) {
    httpResponse (err, res, callback);
  }

  http.doRequest (options, doResponse);
}

/**
 * Module interface
 *
 * @param [apikey] {string} - Your Europeana API key
 * @param [timeout = 5000] {number} - Request wait timeout in ms
 * @returns httpRequest {function}
 */

function setup (apikey, timeout) {
  settings.apikey = apikey || null;
  settings.timeout = timeout || settings.timeout;
  return httpRequest;
}

module.exports = setup;
<commit_msg>Fix(error): res can be unavailable<commit_after>/*
Name:         europeana.js
Description:  Unofficial node.js module for the Europeana API
Author:       Franklin van de Meent - https://frankl.in
Source:       https://github.com/fvdm/nodejs-europeana
Feedback:     https://github.com/fvdm/nodejs-europeana/issues
License:      Public Domain / Unlicense (see UNLICENSE file)
              (https://github.com/fvdm/nodejs-europeana/raw/master/UNLICENSE)
*/

var http = require ('httpreq');

var settings = {
  apikey: null,
  timeout: 5000
};

// errors
// http://www.europeana.eu/portal/api-working-with-api.html#Error-Codes

var errors = {
  400: 'The request sent by the client was syntactically incorrect',
  401: 'Authentication credentials were missing or authentication failed.',
  404: 'The requested record was not found.',
  429: 'The request could be served because the application has reached its usage limit.',
  500: 'Internal Server Error. Something has gone wrong, please report to us.'
};

/**
 * Make and call back error
 *
 * @callback callback
 * @param message {string} - Error.message
 * @param err {mixed} - Error.error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err) {}`
 * @returns {void}
 */

function doError (message, err, res, callback) {
  var error = new Error (message);
  var code = res && res.statusCode;
  var body = res && res.body;

  error.code = code;
  error.error = err || errors [code] || null;
  error.data = body;
  callback (error);
}

/**
 * Process response
 *
 * @callback callback
 * @param err {Error, null} - httpreq error
 * @param res {object} - httpreq response details
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpResponse (err, res, callback) {
  var data = res && res.body;
  var html;

  // client failed
  if (err) {
    doError ('request failed', err, res, callback);
    return;
  }

  // parse response
  try {
    data = JSON.parse (data);
  } catch (reason) {
    // weird API error
    if (data.match (/
HTTP Status /)) {
      html = data.replace (/.*description<\/b> (.+)<\/u><\/p>.*/, '$1');
      doError ('API error', html, res, callback);
    } else {
      doError ('invalid response', reason, res, callback);
    }
    return;
  }

  if (data.apikey) {
    delete data.apikey;
  }

  // API error
  if (!data.success && data.error) {
    doError ('API error', data.error, res, callback);
    return;
  }

  if (res.statusCode >= 300) {
    doError ('API error', null, res, callback);
    return;
  }

  // all good
  callback (null, data);
}

/**
 * Communicate with API
 *
 * @callback callback
 * @param path {string} - Method path between `/v2/` and `.json`
 * @param fields {object} - Method parameters
 * @param callback {function} - `function (err, data) {}`
 * @returns {void}
 */

function httpRequest (path, fields, callback) {
  var options = {
    method: 'GET',
    url: 'https://www.europeana.eu/api/v2/' + path + '.json',
    parameters: fields,
    timeout: settings.timeout,
    headers: {
      'User-Agent': 'europeana.js'
    }
  };

  if (typeof fields === 'function') {
    callback = fields;
    options.parameters = {};
  }

  // Request

  // check API key
  if (!settings.apikey) {
    callback (new Error ('apikey missing'));
    return;
  }

  options.parameters.wskey = settings.apikey;

  function doResponse (err, res) {
    httpResponse (err, res, callback);
  }

  http.doRequest (options, doResponse);
}

/**
 * Module interface
 *
 * @param [apikey] {string} - Your Europeana API key
 * @param [timeout = 5000] {number} - Request wait timeout in ms
 * @returns httpRequest {function}
 */

function setup (apikey, timeout) {
  settings.apikey = apikey || null;
  settings.timeout = timeout || settings.timeout;
  return httpRequest;
}

module.exports = setup;
<|endoftext|>


<commit_before>import { createElement } from 'lwc';
import errRecordLog from 'c/errRecordLog';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getNavigateCalledWith } from "lightning/navigation";
import { registerSa11yMatcher } from '@sa11y/jest';

import getData from '@salesforce/apex/ERR_Log_CTRL.getData';
jest.mock(
    '@salesforce/apex/ERR_Log_CTRL.getData',
    () => {
        return {
            default: jest.fn(),
        };
    },
    { virtual: true }
);

import { registerLdsTestWireAdapter } from '@salesforce/sfdx-lwc-jest';

const getObjectInfoAdapter = registerLdsTestWireAdapter(getObjectInfo);

const mockGetObjectInfo = require('./data/getObjectInfo.json');
const mockGetData = require('./data/getData.json');
const mockGetDataErrorLogs = require('./data/getDataErrorLogs.json');

const RECORD_ID = "a0900000008MR9bQAG";

describe('c-err-record-log', () => {
    let component;

    beforeAll(() => {
        registerSa11yMatcher();
    });

    beforeEach(() => {
        component = createElement('c-err-record-log', {
            is: errRecordLog,
        });

        getObjectInfoAdapter.emit(mockGetObjectInfo);
    });

    afterEach(() => {
        clearDOM();
        jest.clearAllMocks();
    });

    /***
    * @description Verifies header is always displayed on the page
    */
    it('should display header', () => {
        document.body.appendChild(component);

        const header = component.shadowRoot.querySelector('h1');
        expect(header).not.toBeNull();
        expect(header.textContent).toBe('c.ERR_RecordLogTitle');
    });

    /***
    * @description Verifies Error Log page elements for the specified record
    */
    describe('on data load', () => {

        beforeEach(() => {
            component.recordId = RECORD_ID;
            getData.mockResolvedValue(mockGetData);

            document.body.appendChild(component);
        });

        /***
        * @description Verifies record detail page is displayed when
        * user clicks on the record name breadcrumb
        */
        it("should navigate to the record detail page", async () => {
            return global.flushPromises()
                .then(async () => {
                    const recordViewBreadcrumb = getElement(component, "breadcrumb Record View Page");
                    expect(recordViewBreadcrumb).not.toBeNull();
                    expect(recordViewBreadcrumb.label).toBe(mockGetData.recordName);

                    dispatchClickEvent(recordViewBreadcrumb);
                })
                .then(async () => {
                    const { pageReference } = getNavigateCalledWith();

                    expect(pageReference.type).toBe("standard__recordPage");
                    expect(pageReference.attributes.recordId).toBe(component.recordId);
                    expect(pageReference.attributes.actionName).toBe("view");
                });
        });

        /***
        * @description Verifies record SObject tab is displayed when
        * user clicks on the record SObject name breadcrumb
        */
        it("should navigate to the record SObject page", async () => {
            return global.flushPromises()
                .then(async () => {
                    const recordSObjectBreadcrumb = getElement(component, "breadcrumb Record SObject Page");
                    expect(recordSObjectBreadcrumb).not.toBeNull();
                    expect(recordSObjectBreadcrumb.label).toBe(mockGetData.sObjectLabelPlural);

                    dispatchClickEvent(recordSObjectBreadcrumb);
                })
                .then(async () => {
                    const { pageReference } = getNavigateCalledWith();

                    expect(pageReference.type).toBe("standard__objectPage");
                    expect(pageReference.attributes.objectApiName).toBe(mockGetData.sObjectType);
                    expect(pageReference.attributes.actionName).toBe("list");
                });
        });

        it('should display error log datatable summary', async () => {
            return global.flushPromises().then(async () => {
                const summary = getElement(component, "text Summary");

                expect(summary).not.toBeNull();
                expect(summary.textContent).toBe("c.geTextListViewItemsCount c.geTextListViewSortedBy");
            });
        });

        it('should display no item message when record has no error logs', async () => {
            return global.flushPromises().then(async () => {
                const message = getElement(component, "text No Items Message");

                expect(message).not.toBeNull();
                expect(message.value).toBe("c.commonNoItems");
            });
        });

        it("should be accessible", async () => {
            return global.flushPromises().then(async () => {
                await expect(component).toBeAccessible();
            });
        });
    });

    /***
    * @description Verifies Error Log page elements when
    * the specified record has error logs
    */
    describe('on datatable displaying error logs', () => {

        beforeEach(() => {
            component.recordId = RECORD_ID;
            getData.mockResolvedValue(mockGetDataErrorLogs);

            document.body.appendChild(component);
        });

        it('should not display no item message', async () => {
            return global.flushPromises().then(async () => {
                const message = getElement(component, "text No Items Message");

                expect(message).toBeNull();
            });
        });

        it('should display error logs', async () => {
            return global.flushPromises().then(async () => {
                const datatable = getElement(component, "datatable Logs");
                expect(datatable).not.toBeNull();

                expect(datatable.columns.length).toBe(4);
                expect(datatable.columns[0].fieldName).toBe("logURL");
                expect(datatable.columns[0].type).toBe("url");
                expect(datatable.columns[0].label).toBe(
                    mockGetObjectInfo.fields["Name"].label
                );

                expect(datatable.data.length).toBe(1);
                expect(datatable.data[0].Name).not.toBeNull();
                expect(datatable.data[0].Name).toBe(
                    mockGetDataErrorLogs.data[0].Name
                );
            });
        });

        it("should be accessible", async () => {
            return global.flushPromises().then(async () => {
                await expect(component).toBeAccessible();
            });
        });
    });

    /***
    * @description Verifies No Access illustration is displayed when
    * user has no read access on the record SObject or Error SObject
    */
    describe('on no access', () => {

        beforeEach(() => {
            component.recordId = RECORD_ID;

            let mockGetDataNoAccess = JSON.parse(JSON.stringify(mockGetData));
            mockGetDataNoAccess.hasAccess = false;

            getData.mockResolvedValue(mockGetDataNoAccess);

            document.body.appendChild(component);
        });

        it('should display No Access illustration', async () => {
            return global.flushPromises().then(async () => {
                const illustration = getElement(component, "illustration NoAccess");
                expect(illustration).not.toBeNull();

                expect(illustration.heading2).toBe('c.commonInsufficientPermissions');
                expect(illustration.message).toBe('c.addrCopyConAddBtnFls');
            });
        });

        it("should be accessible", async () => {
            return global.flushPromises().then(async () => {
                await expect(component).toBeAccessible();
            });
        });
    });

});

// Helpers
//////////////

/***
* @description Finds and returns element defined by its "data-qa-locator" on the component
*/
const getElement = (component, qaLocator) => {
    const breadcrumb = component.shadowRoot.querySelector('[data-qa-locator="' + qaLocator + '"]');

    return breadcrumb;
}

/***
* @description Mimics user clicking on the element
*/
const dispatchClickEvent = (element) => {
    element.dispatchEvent(
        new CustomEvent('click')
    );
}
<commit_msg>Clean up<commit_after>import { createElement } from 'lwc';
import errRecordLog from 'c/errRecordLog';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getNavigateCalledWith } from "lightning/navigation";
import { registerSa11yMatcher } from '@sa11y/jest';

import getData from '@salesforce/apex/ERR_Log_CTRL.getData';
jest.mock(
    '@salesforce/apex/ERR_Log_CTRL.getData',
    () => {
        return {
            default: jest.fn(),
        };
    },
    { virtual: true }
);

import { registerLdsTestWireAdapter } from '@salesforce/sfdx-lwc-jest';

const getObjectInfoAdapter = registerLdsTestWireAdapter(getObjectInfo);

const mockGetObjectInfo = require('./data/getObjectInfo.json');
const mockGetData = require('./data/getData.json');
const mockGetDataErrorLogs = require('./data/getDataErrorLogs.json');

const RECORD_ID = "a0900000008MR9bQAG";

describe('c-err-record-log', () => {
    let component;

    beforeAll(() => {
        registerSa11yMatcher();
    });

    beforeEach(() => {
        component = createElement('c-err-record-log', {
            is: errRecordLog,
        });

        getObjectInfoAdapter.emit(mockGetObjectInfo);
    });

    afterEach(() => {
        clearDOM();
        jest.clearAllMocks();
    });

    /***
    * @description Verifies header is always displayed on the page
    */
    it('should display header', () => {
        document.body.appendChild(component);

        const header = component.shadowRoot.querySelector('h1');
        expect(header).not.toBeNull();
        expect(header.textContent).toBe('c.ERR_RecordLogTitle');
    });

    /***
    * @description Verifies Error Log page elements for the specified record
    */
    describe('on data load', () => {

        beforeEach(() => {
            component.recordId = RECORD_ID;
            getData.mockResolvedValue(mockGetData);

            document.body.appendChild(component);
        });

        /***
        * @description Verifies record detail page is displayed when
        * user clicks on the record name breadcrumb
        */
        it("should navigate to the record detail page", async () => {
            return global.flushPromises()
                .then(async () => {
                    const recordViewBreadcrumb = getElement(component, "breadcrumb Record View Page");
                    expect(recordViewBreadcrumb).not.toBeNull();
                    expect(recordViewBreadcrumb.label).toBe(mockGetData.recordName);

                    dispatchClickEvent(recordViewBreadcrumb);
                })
                .then(async () => {
                    const { pageReference } = getNavigateCalledWith();

                    expect(pageReference.type).toBe("standard__recordPage");
                    expect(pageReference.attributes.recordId).toBe(component.recordId);
                    expect(pageReference.attributes.actionName).toBe("view");
                });
        });

        /***
        * @description Verifies record SObject tab is displayed when
        * user clicks on the record SObject name breadcrumb
        */
        it("should navigate to the record SObject page", async () => {
            return global.flushPromises()
                .then(async () => {
                    const recordSObjectBreadcrumb = getElement(component, "breadcrumb Record SObject Page");
                    expect(recordSObjectBreadcrumb).not.toBeNull();
                    expect(recordSObjectBreadcrumb.label).toBe(mockGetData.sObjectLabelPlural);

                    dispatchClickEvent(recordSObjectBreadcrumb);
                })
                .then(async () => {
                    const { pageReference } = getNavigateCalledWith();

                    expect(pageReference.type).toBe("standard__objectPage");
                    expect(pageReference.attributes.objectApiName).toBe(mockGetData.sObjectType);
                    expect(pageReference.attributes.actionName).toBe("list");
                });
        });

        it('should display error log datatable summary', async () => {
            return global.flushPromises().then(async () => {
                const summary = getElement(component, "text Summary");

                expect(summary).not.toBeNull();
                expect(summary.textContent).toBe("c.geTextListViewItemsCount c.geTextListViewSortedBy");
            });
        });

        it('should display no item message when record has no error logs', async () => {
            return global.flushPromises().then(async () => {
                const message = getElement(component, "text No Items Message");

                expect(message).not.toBeNull();
                expect(message.value).toBe("c.commonNoItems");
            });
        });

        it("should be accessible", async () => {
            return global.flushPromises().then(async () => {
                await expect(component).toBeAccessible();
            });
        });
    });

    /***
    * @description Verifies Error Log page elements when
    * the specified record has error logs
    */
    describe('on datatable displaying error logs', () => {

        beforeEach(() => {
            component.recordId = RECORD_ID;
            getData.mockResolvedValue(mockGetDataErrorLogs);

            document.body.appendChild(component);
        });

        it('should not display no item message', async () => {
            return global.flushPromises().then(async () => {
                const message = getElement(component, "text No Items Message");

                expect(message).toBeNull();
            });
        });

        it('should display error logs', async () => {
            return global.flushPromises().then(async () => {
                const datatable = getElement(component, "datatable Logs");
                expect(datatable).not.toBeNull();

                expect(datatable.columns.length).toBe(4);
                expect(datatable.columns[0].fieldName).toBe("logURL");
                expect(datatable.columns[0].type).toBe("url");
                expect(datatable.columns[0].label).toBe(
                    mockGetObjectInfo.fields["Name"].label
                );

                expect(datatable.data.length).toBe(1);
                expect(datatable.data[0].Name).not.toBeNull();
                expect(datatable.data[0].Name).toBe(
                    mockGetDataErrorLogs.data[0].Name
                );
            });
        });

        it("should be accessible", async () => {
            return global.flushPromises().then(async () => {
                await expect(component).toBeAccessible();
            });
        });
    });

    /***
    * @description Verifies No Access illustration is displayed when
    * user has no read access on the record SObject or Error SObject
    */
    describe('on no access', () => {

        beforeEach(() => {
            component.recordId = RECORD_ID;

            let mockGetDataNoAccess = JSON.parse(JSON.stringify(mockGetData));
            mockGetDataNoAccess.hasAccess = false;

            getData.mockResolvedValue(mockGetDataNoAccess);

            document.body.appendChild(component);
        });

        it('should display No Access illustration', async () => {
            return global.flushPromises().then(async () => {
                const illustration = getElement(component, "illustration NoAccess");
                expect(illustration).not.toBeNull();

                expect(illustration.heading2).toBe('c.commonInsufficientPermissions');
                expect(illustration.message).toBe('c.addrCopyConAddBtnFls');
            });
        });

        it("should be accessible", async () => {
            return global.flushPromises().then(async () => {
                await expect(component).toBeAccessible();
            });
        });
    });

});

// Helpers
//////////////

/***
* @description Finds and returns element defined by its "data-qa-locator" on the component
*/
const getElement = (component, qaLocator) => {
    const element = component.shadowRoot.querySelector('[data-qa-locator="' + qaLocator + '"]');

    return element;
}

/***
* @description Dispatch event when user clicks on the element
*/
const dispatchClickEvent = (element) => {
    element.dispatchEvent(
        new CustomEvent('click')
    );
}
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';

//// actions
import { toggleAddForm } from '../../actions/addForm';

//// components
import {Icon} from '../common/common';

const AddButton = ({clickHandler}) => {
  return <Icon icon='plus-square' onClick={e => {e.preventDefault(); clickHandler();  }} />
};
AddButton.defaultProps = {
  addButtonClickHandler: e => e
};

const mapStateToProps = ({ user }) => {
  return {
    user
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    addButtonClickHandler: () => {
      dispatch(toggleAddForm());
    }
  };
};

const WimfNavbar = ({ user, addButtonClickHandler }) => (
  <Navbar inverse>
    <Navbar.Header>
      <Navbar.Brand>
        What's in my Freezer?
      </Navbar.Brand>
      <Navbar.Toggle />
    </Navbar.Header>
    <Navbar.Collapse>

        <NavItem eventKey={1} href="#">
          <AddButton clickHandler={addButtonClickHandler} />
        </NavItem>
        <NavItem eventKey={2} href="/demo" target='_blank'>Demo</NavItem>
        <NavDropdown eventKey={3} title={user.name} id="basic-nav-dropdown">
          <MenuItem eventKey={3.1}>Logout</MenuItem>
          <MenuItem eventKey={3.2}>Another action</MenuItem>
          <MenuItem eventKey={3.3}>Something else here</MenuItem>
          <MenuItem divider />
          <MenuItem eventKey={3.3}>Separated link</MenuItem>
        </NavDropdown>

    </Navbar.Collapse>
  </Navbar>
);

export default connect(mapStateToProps, mapDispatchToProps)(WimfNavbar);<commit_msg>navbar: fix link<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';

//// actions
import { toggleAddForm } from '../../actions/addForm';

//// components
import {Icon} from '../common/common';

const AddButton = ({clickHandler}) => {
  return <Icon icon='plus-square' onClick={e => {e.preventDefault(); clickHandler();  }} />
};
AddButton.defaultProps = {
  addButtonClickHandler: e => e
};

const mapStateToProps = ({ user }) => {
  return {
    user
  };
}

const mapDispatchToProps = (dispatch) => {
  return {
    addButtonClickHandler: () => {
      dispatch(toggleAddForm());
    }
  };
};

const WimfNavbar = ({ user, addButtonClickHandler }) => (
  <Navbar inverse>
    <Navbar.Header>
      <Navbar.Brand>
        What's in my Freezer?
      </Navbar.Brand>
      <Navbar.Toggle />
    </Navbar.Header>
    <Navbar.Collapse>

        <NavItem eventKey={1} href="#">
          <AddButton clickHandler={addButtonClickHandler} />
        </NavItem>
        <NavItem eventKey={2} href="/demo" target='_blank'>Demo</NavItem>
        <NavDropdown eventKey={3} title={user.name} id="basic-nav-dropdown">
          <MenuItem eventKey={3.1} href='/auth/logout'>Logout</MenuItem>
          <MenuItem eventKey={3.2}>Another action</MenuItem>
          <MenuItem eventKey={3.3}>Something else here</MenuItem>
          <MenuItem divider />
          <MenuItem eventKey={3.3}>Separated link</MenuItem>
        </NavDropdown>

    </Navbar.Collapse>
  </Navbar>
);

export default connect(mapStateToProps, mapDispatchToProps)(WimfNavbar);<|endoftext|>


<commit_before>function show(request, sender, sendResponse) {
  if(!sender.tab) {
    return;
  }

  const tabId = sender.tab.id;
  chrome.pageAction.show(tabId);

  const oneDay = 3600*24*1000;
  const diff = request.oriUpdateTime - request.curUpdateTime;
  if(diff <= 0) { // up to date
    chrome.pageAction.setIcon({tabId: tabId, path: 'icons/emoji_u1f600.png'});
  } else if(diff < oneDay*45) { // warming
    chrome.pageAction.setIcon({tabId: tabId, path: 'icons/emoji_u26a0.png'});
  } else { // dangerous
    chrome.pageAction.setIcon({tabId: tabId, path: 'icons/emoji_u2620.png'});
  }

  console.log(chrome.pageAction.getPopup({tabId: tabId}));
}

chrome.runtime.onMessage.addListener(show);<commit_msg>fix typo, remove log<commit_after>function show(request, sender, sendResponse) {
  if(!sender.tab) {
    return;
  }

  const tabId = sender.tab.id;
  chrome.pageAction.show(tabId);

  const oneDay = 3600*24*1000;
  const diff = request.oriUpdateTime - request.curUpdateTime;
  if(diff <= 0) { // up to date
    chrome.pageAction.setIcon({tabId: tabId, path: 'icons/emoji_u1f600.png'});
  } else if(diff < oneDay*45) { // warning
    chrome.pageAction.setIcon({tabId: tabId, path: 'icons/emoji_u26a0.png'});
  } else { // dangerous
    chrome.pageAction.setIcon({tabId: tabId, path: 'icons/emoji_u2620.png'});
  }
}

chrome.runtime.onMessage.addListener(show);<|endoftext|>


<commit_before>import GLBoost from '../../globals';
import M_Element from '../elements/M_Element';
import Vector3 from '../../low_level/math/Vector3';
import Vector4 from '../../low_level/math/Vector4';
import Matrix44 from '../../low_level/math/Matrix44';
import M_FrustumCamera from '../elements/cameras/M_FrustumCamera';
import M_PerspectiveCamera from '../elements/cameras/M_PerspectiveCamera';

export default class EffekseerElement extends M_Element {
  constructor(glBoostContext) {
    super(glBoostContext);
    this.__effect = null;
    this.__handle = null;
    this.__speed = 1;
    this.__timer = null;
  }

  load(uri, playJustAfterLoaded = false, isLoop = false) {
    return new Promise((resolve, reject)=>{
      this.__effect = effekseer.loadEffect(uri, ()=>{
        if (playJustAfterLoaded) {
          if (isLoop) {
            this.__timer = setInterval(()=>{ this.play(); }, 500);
          } else {
            this.play();
          }
        }
        resolve(this);
      });
    })
  }

  cancelLoop() {
    clearInterval(this.__timer);
  }

  play(isLoop = false) {
    const __play = ()=>{
      // Play the loaded effect
      this.__handle = effekseer.play(this.__effect);
      this.update();
    };

    if (isLoop) {
      this.__timer = setInterval(__play, 200);
    } else {
      __play();
    }

  }

  update(camera) {
    if (this.__handle != null) {
      const m = this.worldMatrix;
      this.__handle.setLocation(m.m03, m.m13, m.m23);
      const eular = m.toEulerAngles();
      this.__handle.setRotation(eular.x, eular.y, eular.z);
      const scale = m.getScale();
      this.__handle.setScale(scale.x, scale.y, scale.z);

 //     this.__handle.setMatrix(this.worldMatrix.transpose().m);
//      this.__handle.setMatrix(this.worldMatrix.m);
      let lookAtMatrix = Matrix44.identity().m;
      let projectionMatrix = Matrix44.identity().m;
      if (camera) {
//        lookAtMatrix = camera.lookAtRHMatrix().transpose().m;
//        projectionMatrix = camera.projectionRHMatrix().transpose().m;
//        lookAtMatrix = camera.lookAtRHMatrix().m;
        projectionMatrix = camera.projectionRHMatrix().transpose().m;
//        effekseer.setCameraMatrix(lookAtMatrix);
        effekseer.setProjectionMatrix(projectionMatrix);

          effekseer.setCameraLookAt(camera.translateInner.x, camera.translateInner.y, camera.translateInner.z,
            camera.centerInner.x, camera.centerInner.y, camera.centerInner.z,
            camera.upInner.x, camera.upInner.y, camera.upInner.z);
/*
            if (camera instanceof M_FrustumCamera) {
            effekseer.setProjectionMatrix();
          } else if (camera instanceof M_PerspectiveCamera) {

          } else {

          }
          */
        }

      this.__handle.setSpeed(this.__speed);
    }
  }

  set playSpeed(val) {
    if (this.__handle) {
      this.__handle.setSpeed(val);
    }
    this.__speed = val;
  }

  get playSpeed() {
    return this.__speed;
  }

  set translate(vec) {
    if (this.__handle) {
      this.__handle.setLocation(vec.x, vec.y, vec.z);
    }
    super.translate = vec;
  }

  get translate() {
    return super.translate;
  }

  set rotate(vec) {
    if (this.__handle) {
      this.__handle.setRotation(vec.x, vec.y, vec.z);
    }
    super.rotate = vec;
  }

  get rotate() {
    return super.rotate;
  }

  set scale(vec) {
    if (this.__handle) {
      this.__handle.setScale(vec.x, vec.y, vec.z);
    }
    super.scale = vec;
  }

  get scale() {
    return super.scale;
  }

}
<commit_msg>Tweak EffekseerElement.js<commit_after>import GLBoost from '../../globals';
import M_Element from '../elements/M_Element';
import Vector3 from '../../low_level/math/Vector3';
import Vector4 from '../../low_level/math/Vector4';
import Matrix44 from '../../low_level/math/Matrix44';
import M_FrustumCamera from '../elements/cameras/M_FrustumCamera';
import M_PerspectiveCamera from '../elements/cameras/M_PerspectiveCamera';

export default class EffekseerElement extends M_Element {
  constructor(glBoostContext) {
    super(glBoostContext);
    this.__effect = null;
    this.__handle = null;
    this.__speed = 1;
    this.__timer = null;
  }

  load(uri, playJustAfterLoaded = false, isLoop = false) {
    return new Promise((resolve, reject)=>{
      this.__effect = effekseer.loadEffect(uri, ()=>{
        if (playJustAfterLoaded) {
          if (isLoop) {
            this.__timer = setInterval(()=>{ this.play(); }, 500);
          } else {
            this.play();
          }
        }
        resolve(this);
      });
    })
  }

  cancelLoop() {
    clearInterval(this.__timer);
  }

  play(isLoop = false) {
    const __play = ()=>{
      // Play the loaded effect
      this.__handle = effekseer.play(this.__effect);
      this.update();
    };

    if (isLoop) {
      this.__timer = setInterval(__play, 200);
    } else {
      __play();
    }

  }

  update(camera) {
    if (this.__handle != null) {

      // Set Model Matrix
      const scale = 0.1;
      const m = this.worldMatrix;
      this.__handle.setLocation(m.m03*scale, m.m13*scale, m.m23*scale);
      const eular = m.toEulerAngles();
      this.__handle.setRotation(eular.x, eular.y, eular.z);
      const _scale = m.getScale();
      this.__handle.setScale(_scale.x*scale, _scale.y*scale, _scale.z*scale);

 //     this.__handle.setMatrix(this.worldMatrix.transpose().m);
//      this.__handle.setMatrix(this.worldMatrix.m);

      let lookAtMatrix = Matrix44.identity().m;
      let projectionMatrix = Matrix44.identity().m;
      if (camera) {

        // Set Viewing Matrix
//        lookAtMatrix = camera.lookAtRHMatrix();
//        let viewMatrix = lookAtMatrix.multiply(camera.inverseWorldMatrixWithoutMySelf);
//        console.log(lookAtMatrix.toStringApproximately())

        effekseer.setCameraLookAt(camera.translateInner.x, camera.translateInner.y, camera.translateInner.z,
          camera.centerInner.x, camera.centerInner.y, camera.centerInner.z,
          camera.upInner.x, camera.upInner.y, camera.upInner.z);

        // Set Projection Matrix
//        projectionMatrix = camera.projectionRHMatrix().transpose().m;
//        effekseer.setProjectionMatrix(projectionMatrix);
        //effekseer.setCameraMatrix(viewMatrix.transpose().m);

          effekseer.setProjectionPerspective(camera.fovy, camera.aspect, camera.zNear, camera.zFar);

            /*
            if (camera instanceof M_FrustumCamera) {
            effekseer.setProjectionMatrix();
          } else if (camera instanceof M_PerspectiveCamera) {

          } else {

          }
          */
        }

      this.__handle.setSpeed(this.__speed);
    }
  }

  set playSpeed(val) {
    if (this.__handle) {
      this.__handle.setSpeed(val);
    }
    this.__speed = val;
  }

  get playSpeed() {
    return this.__speed;
  }

  set translate(vec) {
    if (this.__handle) {
      this.__handle.setLocation(vec.x, vec.y, vec.z);
    }
    super.translate = vec;
  }

  get translate() {
    return super.translate;
  }

  set rotate(vec) {
    if (this.__handle) {
      this.__handle.setRotation(vec.x, vec.y, vec.z);
    }
    super.rotate = vec;
  }

  get rotate() {
    return super.rotate;
  }

  set scale(vec) {
    if (this.__handle) {
      this.__handle.setScale(vec.x, vec.y, vec.z);
    }
    super.scale = vec;
  }

  get scale() {
    return super.scale;
  }

}
<|endoftext|>