<commit_before>var SoundManager = require('./SoundManager');
var scheduler, audioContext, server, manager;

beforeEach(function(){
  scheduler = {
    observe: function(){}
  }
});

describe('SoundManager', function(){
  describe('SoundManager()', function(){
    it('should set audio context');
    it('should set server');
    it('shold set sounds to empty obj');
  });

  describe('playSound', function(){
    it.only('should play the sound with given handle at spec time',
      function(){
        var returnObj = {
          start: sinon.spy(),
          connect: sinon.spy()
        };

        var audioContext = {
          createBufferSource: function(){
            return returnObj;
          },
          destination: 'acd'
        };

        manager = new SoundManager(audioContext, scheduler, server);
        manager.sounds['testSound'] = {buffer:{duration: 3}};

        manager.playSound('testSound', 3);

        returnObj.start.calledWith(3).should.be.true;
        returnObj.connect.calledWith(audioContext.destination)
            .should.be.true;

      }
    );

    it('should return duration on playSound', function(){
      var audioContext = {
        createBufferSource: function(){
          return {
            connect: function(){},
            start: function(){},
          };
        },
        destination: 'audio context destination'
      };
      manager = new SoundManager(audioContext, scheduler, server);
      manager.sounds['testSound'] = {buffer:{duration: 3}};

      manager.playSound('testSound')
        .should.equal(3);
    });

    it('should set time of zero if no other value provided', function(){
      var returnObj = {
        start: sinon.spy(),
        connect: function(){}
      };

      var audioContext = {
        createBufferSource: function(){
          return returnObj;
        }
      };

      manager = new SoundManager(audioContext, scheduler, server);
      manager.sounds['testSound'] = {buffer:{duration: 3}};

      manager.playSound('testSound');

      returnObj.start.calledWith(0).should.be.true;

    });

    it('should play no sound if handle does not exist', function(){
      var returnObj = {
        start: sinon.spy(),
        connect: function(){}
      };

      var audioContext = {
        createBufferSource: function(){
          return returnObj;
        }
      };

      manager = new SoundManager(audioContext, scheduler, server);
      manager.playSound('testSound');

      returnObj.start.called.should.be.false;

    });

    it('should play sound from file info if given', function(){
      var returnObj = {
        start: sinon.spy(),
        connect: sinon.spy()
      };

      var audioContext = {
        createBufferSource: function(){
          return returnObj;
        },
        destination: 'acd'
      };

      manager = new SoundManager(audioContext, scheduler, server);
      manager.sounds['testSound'] = {buffer:{duration: 3}};

      manager.playSound({handle: 'testSound'});

      returnObj.start.calledWith(0).should.be.true;
      returnObj.connect.calledWith(audioContext.destination)
          .should.be.true;
    });

    it('should warn when no matching sound', function(){
      var spy = sinon.spy(console, 'warn');
      manager = new SoundManager(audioContext, scheduler, server);
      manager.playSound('testSound');

      spy.calledWith(
        'ClipConductor.SoundManager: cannot find sound: testSound'
      ).should.be.true;

    });

  });

  describe('loadFile',function(){
    var fileInfo, audioContext, server, manager;

    beforeEach(function(){
      fileInfo = {
        filename: 'test.mp3',
        handle: 'test'
      };

      audioContext = {
        decodeAudioData: function(data, cb){
          cb();
        },
        createBufferSource: function(){
          return {
            connect: function(destination){
            }
          }
        },
        destination: 'audio context destination'
      };

      server = {
        loadFile: function(fn){
          return new Promise(function(resolve){
            resolve('audio data');
          });
        }
      };
    });

    it('should call server.loadfile with fn', function(){
      var spy = sinon.spy();

      server.loadFile = function(fn){
        spy(fn);
        return new Promise(function(){});
      };

      manager = SoundManager.new(audioContext, scheduler, server);
      manager.loadFile(fileInfo);

      spy.calledWith(fileInfo.filename).should.be.true;
    });

    it('should call context.decodeAudioData', function(){
      audioContext.decodeAudioData = sinon.spy();

      server.loadFile = function(fn){
        return new Promise(function(resolve){
          resolve('audio data');
        });
      };

      manager = SoundManager.new(audioContext, scheduler, server);
      return manager.loadFile(fileInfo).then(function(){
        audioContext.decodeAudioData.calledWith('audio data')
          .should.be.true;
      });
    });

    it('should create and connect buffer stored on this.sounds',
      function(){
        var spy = sinon.spy();

        audioContext.decodeAudioData = function(data, cb){
          cb('the buffer');
        }

        manager = SoundManager.new(audioContext, scheduler, server);

        return manager.loadFile(fileInfo).then(function(){
          manager.sounds[fileInfo.handle]
            .should.equal('the buffer');
        });
      }
    );

    it('should call done callback on success', function(){
      var spy = sinon.spy();
      manager = SoundManager.new(audioContext, scheduler, server);

      return manager.loadFile(fileInfo, spy).then(function(){
        spy.called.should.be.true;
      });

    });

    it('should call error callback on encoding error', function(){
      var spy = sinon.spy();

      audioContext.decodeAudioData = function(data, succ, er){
        er();
      };
      manager = SoundManager.new(audioContext, scheduler, server);

      return manager.loadFile(fileInfo, null, spy).then(function(){
        spy.called.should.be.true;
      });
    });

    it('should call error callback on network error', function(){
      var spy = sinon.spy();

      server.loadFile = function(fn){
        return new Promise(function(resolve, reject){
          reject();
        });
      };

      manager = SoundManager.new(audioContext, scheduler, server);

      return manager.loadFile(fileInfo, null, spy).then(function(){
        spy.called.should.be.true;
      });

    });

  });
});
<commit_msg>Added rudimentary tests to SoundManagar<commit_after>var SoundManager = require('./SoundManager');
var scheduler, audioContext, server, manager;

beforeEach(function(){
  scheduler = {
    observe: function(){}
  }
});

describe('SoundManager', function(){
  describe('SoundManager()', function(){
    it('should set audio context and server', function(){
      var ac = {};
      var server = {};
      manager = new SoundManager(ac, server);
      manager.audioContext.should.equal(ac);
      manager.server.should.equal(server);
    });
    it('shold set sounds to empty obj', function(){
      manager.sounds.should.deep.equal({});
    });
  });

  describe('playSound', function(){
    it('should play the sound with given handle at spec time',
      function(){
        var returnObj = {
          start: sinon.spy(),
          connect: sinon.spy()
        };

        var audioContext = {
          createBufferSource: function(){
            return returnObj;
          },
          destination: 'acd'
        };

        manager = new SoundManager(audioContext, scheduler, server);
        manager.sounds['testSound'] = {buffer:{duration: 3}};

        manager.playSound('testSound', 3);

        returnObj.start.calledWith(3).should.be.true;
        returnObj.connect.calledWith(audioContext.destination)
            .should.be.true;

      }
    );

    it('should return duration on playSound', function(){
      var audioContext = {
        createBufferSource: function(){
          return {
            connect: function(){},
            start: function(){},
          };
        },
        destination: 'audio context destination'
      };
      manager = new SoundManager(audioContext, scheduler, server);
      manager.sounds['testSound'] = {buffer:{duration: 3}};

      manager.playSound('testSound')
        .should.equal(3);
    });

    it('should set time of zero if no other value provided', function(){
      var returnObj = {
        start: sinon.spy(),
        connect: function(){}
      };

      var audioContext = {
        createBufferSource: function(){
          return returnObj;
        }
      };

      manager = new SoundManager(audioContext, scheduler, server);
      manager.sounds['testSound'] = {buffer:{duration: 3}};

      manager.playSound('testSound');

      returnObj.start.calledWith(0).should.be.true;

    });

    it('should play no sound if handle does not exist', function(){
      var returnObj = {
        start: sinon.spy(),
        connect: function(){}
      };

      var audioContext = {
        createBufferSource: function(){
          return returnObj;
        }
      };

      manager = new SoundManager(audioContext, scheduler, server);
      manager.playSound('testSound');

      returnObj.start.called.should.be.false;

    });

    it('should play sound from file info if given', function(){
      var returnObj = {
        start: sinon.spy(),
        connect: sinon.spy()
      };

      var audioContext = {
        createBufferSource: function(){
          return returnObj;
        },
        destination: 'acd'
      };

      manager = new SoundManager(audioContext, scheduler, server);
      manager.sounds['testSound'] = {buffer:{duration: 3}};

      manager.playSound({handle: 'testSound'});

      returnObj.start.calledWith(0).should.be.true;
      returnObj.connect.calledWith(audioContext.destination)
          .should.be.true;
    });

    it('should warn when no matching sound', function(){
      var spy = sinon.spy(console, 'warn');
      manager = new SoundManager(audioContext, scheduler, server);
      manager.playSound('testSound');

      spy.calledWith(
        'ClipConductor.SoundManager: cannot find sound: testSound'
      ).should.be.true;

    });

  });

  describe('loadFile',function(){
    var fileInfo, audioContext, server, manager;

    beforeEach(function(){
      fileInfo = {
        filename: 'test.mp3',
        handle: 'test'
      };

      audioContext = {
        decodeAudioData: function(data, cb){
          cb();
        },
        createBufferSource: function(){
          return {
            connect: function(destination){
            }
          }
        },
        destination: 'audio context destination'
      };

      server = {
        loadFile: function(fn){
          return new Promise(function(resolve){
            resolve('audio data');
          });
        }
      };
    });

    it('should call server.loadfile with fn', function(){
      var spy = sinon.spy();

      server.loadFile = function(fn){
        spy(fn);
        return new Promise(function(){});
      };

      manager = new SoundManager(audioContext, server);
      manager.loadFile(fileInfo);

      spy.calledWith(fileInfo.filename).should.be.true;
    });

    it('should call context.decodeAudioData', function(){
      audioContext.decodeAudioData = sinon.spy();

      server.loadFile = function(fn){
        return new Promise(function(resolve){
          resolve('audio data');
        });
      };

      manager = new SoundManager(audioContext, server);
      return manager.loadFile(fileInfo).then(function(){
        audioContext.decodeAudioData.calledWith('audio data')
          .should.be.true;
      });
    });

    it('should store buffer on this.sounds',
      function(){
        var spy = sinon.spy();

        audioContext.decodeAudioData = function(data, cb){
          cb('the buffer');
        }

        manager = new SoundManager(audioContext, server);

        return manager.loadFile(fileInfo).then(function(){
          manager.sounds[fileInfo.handle]
            .should.deep.equal({
              buffer: 'the buffer',
              info: fileInfo
            });
        });
      }
    );

    it('should call done callback on success', function(){
      var spy = sinon.spy();
      manager = new SoundManager(audioContext, server);

      return manager.loadFile(fileInfo, spy).then(function(){
        spy.called.should.be.true;
      });

    });

    it('should call error callback on encoding error', function(){
      var spy = sinon.spy();

      audioContext.decodeAudioData = function(data, succ, er){
        er();
      };
      manager = new SoundManager(audioContext, server);

      return manager.loadFile(fileInfo, null, spy).then(function(){
        spy.called.should.be.true;
      });
    });

    it('should call error callback on network error', function(){
      var spy = sinon.spy();

      server.loadFile = function(fn){
        return new Promise(function(resolve, reject){
          reject();
        });
      };

      manager = new SoundManager(audioContext, server);

      return manager.loadFile(fileInfo, null, spy).then(function(){
        spy.called.should.be.true;
      });

    });

    it('should raise error if fileInfo does not contain handle');
    it('should raise error if fileInfo does not contain filename');
  });
});
<|endoftext|>


<commit_before>module.exports = {
  books: [
    {
      "title": "Quick Guide for Firefox OS Development",
      "author": "Andre Alves Garzia",
      "twitter": "soapdog",
      "status": "published",
      "url": "https://leanpub.com/quickguidefirefoxosdevelopment/",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/quickguidefirefoxosdevelopment/large?1401145962",
      "price": "FREE",
      "license": "Creative Commons",
      "description": "Learn how easy and quick it is to develop applications for Firefox OS, the new mobile operating system by Mozilla. Empowered by this books practical approach you will learn thru examples how to develop apps from the beginning all the way to the distribution in the Firefox Markeplace.",
      "translations": [
        {
          "language": "Portuguese",
          "url": "https://leanpub.com/guiarapidofirefoxos/",
          "title": "Guia Rápido de Desenvolvimento para Firefox OS"
        }
      ]
    },
    {
      "title": "Beginning Firefox OS HTML5 Game Programming",
      "author": "Bob Thulfram",
      "twitter": "thulfram",
      "status": "published",
      "url": "http://www.amazon.com/gp/product/B00IZUYIGO/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=B00IZUYIGO&linkCode=as2&tag=andregacom02-20&linkId=4E2H6GAKNOAY2OXM",
      "cover": "http://i.imgur.com/kheFiy0.png",
      "price": "$5.21",
      "license": "Commercial",
      "description": "In this book three standard game technologies are examined, compared, and contrasted: CSS Sprites, Canvas, and SVG (Scalable Vector Graphics). You will see examples using each of the three to move graphics, detect collisions, and more. Variations within Canvas and SVG are explored as well. You'll also see examples for phone-specific technologies such as Touch, Vibration, Device Orientation, and Screen Orientation. You'll also be shown how to upgrade your Firefox OS phone, how to use the Simulator if you don't have a phone, and how to use the App Manager to put your apps on phones.

This book assumes you know the basics of HTML5, CSS, and JavaScript, and that you are interested in making games. Concepts and code are explained carefully along the way and newer options like CSS Sprites and SVG are covered extensively, as well as current JavaScript and HTML5 tips and tricks. In fact, except for the phone-specific chapters, you can use these techniques to make HTML5 games for other platforms. All the code is straight HTML5, CSS, SVG, and JavaScript with no libraries, no jQuery, nothing but pure code. The focus is 100% on Firefox OS games and I hope you will be inspired to create games for this fast-growing platform.

The book is written in an informal, friendly style that invites the reader to come along and explore the fun that is Firefox OS! There isn't just one way to write a game, there are a great many, and it is hoped that this book can inform and inspire you to make your own games."
    },
    {
      "title": "Beyond Web and Firefox OS - GAIA FROM ABOVE",
      "author": "看見Gaia",
      "twitter": "#",
      "status": "Published",
      "url": "https://leanpub.com/gaiafromabove",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/gaiafromabove/large?1402367604",
      "price": "$4.99 - $14.99",
      "license": "Commercial",
      "description": "The book is provide an overview of the javascript written OS: FirefoxOS front end - gaia. We'd like to document and findout how mozilla and the community design and achieve this ongoing great goal. And try to learn things from their design decisions. The book help developers understand how B2G and Gaia fit together. And shows how the system startup and the app launching process.",
    },
    {
      "title": "Building Games for Firefox OS",
      "author": "Andre Alves Garzia",
      "twitter": "soapdog",
      "status": "Unpublished",
      "url": "https://leanpub.com/buildinggamesforfirefoxos/",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/buildinggamesforfirefoxos/large?1403752894",
      "price": "FREE",
      "license": "Creative Commons",
      "description": "Join us in the quest for building games for Firefox OS, the new mobile operating system by Mozilla. Empowered by this books practical approach you will learn thru examples how to develop a full game from the beginning all the way to the distribution in the Firefox Markeplace.",
    },
    {
      "title": "Build HTML5 Games for Firefox OS",
      "author": "Andrzej Mazur",
      "twitter": "end3r",
      "status": "Unpublished",
      "url": "http://firefoxos.enclavegames.com/",
      "cover": "http://firefoxos.enclavegames.com/img/html5games-firefoxos-ebook.png",
      "price": "Unknown",
      "license": "Unknown",
      "description": "I'm passionate about making HTML5 games, you can tell by looking at my various private projects with the 'games' keyword inside: Enclave Games, js13kGames, Gamedev.js Weekly, HTML5 Gamedev Starter. Then there's also Firefox OS - I've created some games for the platform and wrote a few articles. I've run through the whole process of preparing your game for the Firefox OS platform, testing the game on the actual device and pushing it to the Firefox Marketplace. So, why not write a book about it? It's just another side project, so I have no idea when it will be finished, if ever. You can wish me luck using the social buttons above or send me a donation, if I ever create a proper button.",
    }
  ]
};
<commit_msg>Add Firefox OS in Action<commit_after>module.exports = {
  books: [
    {
      "title": "Quick Guide for Firefox OS Development",
      "author": "Andre Alves Garzia",
      "twitter": "soapdog",
      "status": "published",
      "url": "https://leanpub.com/quickguidefirefoxosdevelopment/",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/quickguidefirefoxosdevelopment/large?1401145962",
      "price": "FREE",
      "license": "Creative Commons",
      "description": "Learn how easy and quick it is to develop applications for Firefox OS, the new mobile operating system by Mozilla. Empowered by this books practical approach you will learn thru examples how to develop apps from the beginning all the way to the distribution in the Firefox Markeplace.",
      "translations": [
        {
          "language": "Portuguese",
          "url": "https://leanpub.com/guiarapidofirefoxos/",
          "title": "Guia Rápido de Desenvolvimento para Firefox OS"
        }
      ]
    },
    {
      "title": "Beginning Firefox OS HTML5 Game Programming",
      "author": "Bob Thulfram",
      "twitter": "thulfram",
      "status": "published",
      "url": "http://www.amazon.com/gp/product/B00IZUYIGO/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=B00IZUYIGO&linkCode=as2&tag=andregacom02-20&linkId=4E2H6GAKNOAY2OXM",
      "cover": "http://i.imgur.com/kheFiy0.png",
      "price": "$5.21",
      "license": "Commercial",
      "description": "In this book three standard game technologies are examined, compared, and contrasted: CSS Sprites, Canvas, and SVG (Scalable Vector Graphics). You will see examples using each of the three to move graphics, detect collisions, and more. Variations within Canvas and SVG are explored as well. You'll also see examples for phone-specific technologies such as Touch, Vibration, Device Orientation, and Screen Orientation. You'll also be shown how to upgrade your Firefox OS phone, how to use the Simulator if you don't have a phone, and how to use the App Manager to put your apps on phones.

This book assumes you know the basics of HTML5, CSS, and JavaScript, and that you are interested in making games. Concepts and code are explained carefully along the way and newer options like CSS Sprites and SVG are covered extensively, as well as current JavaScript and HTML5 tips and tricks. In fact, except for the phone-specific chapters, you can use these techniques to make HTML5 games for other platforms. All the code is straight HTML5, CSS, SVG, and JavaScript with no libraries, no jQuery, nothing but pure code. The focus is 100% on Firefox OS games and I hope you will be inspired to create games for this fast-growing platform.

The book is written in an informal, friendly style that invites the reader to come along and explore the fun that is Firefox OS! There isn't just one way to write a game, there are a great many, and it is hoped that this book can inform and inspire you to make your own games."
    },
    {
      "title": "Beyond Web and Firefox OS - GAIA FROM ABOVE",
      "author": "看見Gaia",
      "twitter": "#",
      "status": "Published",
      "url": "https://leanpub.com/gaiafromabove",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/gaiafromabove/large?1402367604",
      "price": "$4.99 - $14.99",
      "license": "Commercial",
      "description": "The book is provide an overview of the javascript written OS: FirefoxOS front end - gaia. We'd like to document and findout how mozilla and the community design and achieve this ongoing great goal. And try to learn things from their design decisions. The book help developers understand how B2G and Gaia fit together. And shows how the system startup and the app launching process.",
    },
    {
      "title": "Firefox OS in Action",
      "author": "Jan Jongboom",
      "twitter": "janjongboom",
      "status": "Published",
      "url": "https://leanpub.com/firefoxosinaction",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/firefoxosinaction/hero?1427198916",
      "price": "FREE",
      "license": "Commercial"
    },
    {
      "title": "Building Games for Firefox OS",
      "author": "Andre Alves Garzia",
      "twitter": "soapdog",
      "status": "Unpublished",
      "url": "https://leanpub.com/buildinggamesforfirefoxos/",
      "cover": "https://s3.amazonaws.com/titlepages.leanpub.com/buildinggamesforfirefoxos/large?1403752894",
      "price": "FREE",
      "license": "Creative Commons",
      "description": "Join us in the quest for building games for Firefox OS, the new mobile operating system by Mozilla. Empowered by this books practical approach you will learn thru examples how to develop a full game from the beginning all the way to the distribution in the Firefox Markeplace.",
    },
    {
      "title": "Build HTML5 Games for Firefox OS",
      "author": "Andrzej Mazur",
      "twitter": "end3r",
      "status": "Unpublished",
      "url": "http://firefoxos.enclavegames.com/",
      "cover": "http://firefoxos.enclavegames.com/img/html5games-firefoxos-ebook.png",
      "price": "Unknown",
      "license": "Unknown",
      "description": "I'm passionate about making HTML5 games, you can tell by looking at my various private projects with the 'games' keyword inside: Enclave Games, js13kGames, Gamedev.js Weekly, HTML5 Gamedev Starter. Then there's also Firefox OS - I've created some games for the platform and wrote a few articles. I've run through the whole process of preparing your game for the Firefox OS platform, testing the game on the actual device and pushing it to the Firefox Marketplace. So, why not write a book about it? It's just another side project, so I have no idea when it will be finished, if ever. You can wish me luck using the social buttons above or send me a donation, if I ever create a proper button.",
    }
  ]
};
<|endoftext|>


<commit_before>// title      : X1
// author     : Gino Tubaro
// license    : MIT License
// description: Conector inferior x1 (bottom)
// file       : xbottom.jscad

// Curvatura dada por elipsoide

//

function getParameterDefinitions() {
  return [
    { name: 'x', type: 'float', initial: 80, caption: "x:" },
    { name: 'y', type: 'float', initial: 30, caption: "y:" },
    { name: 'z', type: 'float', initial: 8, caption: "z:" },
    ];
}
 var r = [], y = [], t = [];
 var result,xbottom,cono, ext, int, pata;

function main() {
var ancho = 40;
var alt = 6;
  var arco =
        union(
          conectores(),
          ext(ancho,alt)
            //int(ancho-3).translate([0, 0, 1.5])
          );
return  arco;
}

  function ext(dist,alt) {

  	var cag = CAG.fromPoints([
  		[-1, -1, 0],
  		[1, -1, 0],
  		[1, 1, 0]
  	]).expand(1, CSG.defaultResolution2D);

  	var flatBottom = CSG.Polygon.createFromPoints(
  		cag.getOutlinePaths()[0].points
  	);
   height=dist*2;
   var t = 0;
   var x1 =0;
   var x2 =0;

    var thing = flatBottom.solidFromSlices({
  	numslices: height
  	,callback: function() {

      //dista=2*Math.abs(Math.pow((1-(Math.pow(k,2)/(Math.pow(dist/2,2)))),2));
      //dista=Math.abs(1*Math.sqrt((Math.pow(dist,2)-(Math.pow(k,2)/9))));
      var vals = calculate(0,dist,alt,0);
      //console.log("Val0"+vals[0]+"Val1"+vals[1]+"Val2"+vals[2]);
      var x =  (vals[0]*Math.pow(t,2)) + (vals[1]*t) + vals[2];

      var valsy = calculate(0,dist,2,5);

      var y =  (valsy[0]*Math.pow(t,2)) + (valsy[1]*t) + valsy[2];

      if (x>=0) {
        x1=x;
        console.log("x1 es" + x1);
      }else{
        x2=x;
        console.log("x2 es" + x2);
      }
    //  var x = -0.16*Math.pow(t,2)+dist/2;
    //  var y = 0.16*Math.pow(t,2)-dist/2;

      var coef = t;

  		if (coef < 0.01) coef = 0.01;//los poligonos no deben colapsar

      var h = height+t*5;

      var o = new Array();
  o.push(
    circle({r: y, center: true}).scale([0.4,1,1]).translate([x1,0,0])
  //  circle({r: 1, center: true}).translate([x2,0,0])
         );

  cag =  hull(o); //.expand(1,CSG.defaultResolution2D)

var all = CSG.Polygon.createFromPoints(
  cag.getOutlinePaths()[0].points
).translate([0, 0, t]);

   t=t+0.5;
  		return all;
  	}
    });

     return thing;

}

function calculate(x1,x2,y,yaux)
{
    sgnb=" +"; sgnc=" +";
    a = x1; //x1
    a=a*a;
    b = x1; //x1
    c = 1;
    d = yaux; //y1

    e = ((x1+x2)/2);//x2
    e=e*e;
    f = ((x1+x2)/2); //x2
    g = 1;
    h = y; //y2

    i = x2; //x3
    i=i*i;
    j = x2; //x3
    k = 1;
    l = yaux; //y3

<!--EVALUATING THE DELTA DETERMINANT -->
delta = (a*f*k)+(b*g*i)+(c*e*j)-(c*f*i)-(a*g*j)-(b*e*k);
//document.output.x.value = delta;

<!--EVALUATING THE X NUMERATOR & ANSWER -->
xnum = eval((d*f*k)+(b*g*l)+(c*h*j)-(c*f*l)-(d*g*j)-(b*h*k));
xans =eval(xnum/delta);

<!--EVALUATING THE Y NUMERATOR & ANSWER -->
ynum = eval((a*h*k)+(d*g*i)+(c*e*l)-(c*h*i)-(a*g*l)-(d*e*k));
yans =eval(ynum/delta);

<!--EVALUATING THE Z NUMERATOR & ANSWER -->
znum = eval((a*f*l)+(b*h*i)+(d*e*j)-(d*f*i)-(a*h*j)-(b*e*l));
zans =eval(znum/delta);
if (yans<0) {sgnb=" "};
if (zans<0) {sgnc=" "};
xans = xans;
yans = sgnb + yans;
var spacer="          ";
var sgnb=" +";
var sgnc=" +";
var suprscrpt="²";
return [xans,yans,zans];
}
function conectores() {
    return cube({size: [10, 9.8, 1], center: [true, true, false]}).translate([-5, 0, 0]);
}
<commit_msg>Delimitacion de los bordes<commit_after>// title      : X1
// author     : Gino Tubaro
// license    : MIT License
// description: Conector inferior x1 (bottom)
// file       : xbottom.jscad

// Curvatura dada por elipsoide

include('lodash.js');

include("node_modules/jscad-utils/jscad-utils.jscad");
include("node_modules/jscad-utils/jscad-utils-color.jscad");

include('node_modules/jscad-utils/jscad-utils-parts.jscad');
include('node_modules/jscad-utils/jscad-boxes.jscad');

function getParameterDefinitions() {
  return [
    { name: 'x', type: 'float', initial: 80, caption: "x:" },
    { name: 'y', type: 'float', initial: 30, caption: "y:" },
    { name: 'z', type: 'float', initial: 8, caption: "z:" },
    ];
}
 var r = [], y = [], t = [];
 var result,xbottom,cono, ext, int, pata;

function main() {
    util.init(CSG);
var ancho = 40;
var alt = 7;
var array = conectores(ancho);
  var arco =
        union(
          array[0],
          array[1],
          ext(ancho,alt)
            //int(ancho-3).translate([0, 0, 1.5])
          );
return  arco
      .fillet(0.5,'z-')
      .fillet(0.5,'z+');
}

  function ext(dist,alt) {

  	var cag = CAG.fromPoints([
  		[-1, -1, 0],
  		[1, -1, 0],
  		[1, 1, 0]
  	]).expand(1, CSG.defaultResolution2D);

  	var flatBottom = CSG.Polygon.createFromPoints(
  		cag.getOutlinePaths()[0].points
  	);
   height=dist*2;
   var t = 0;
   var x1 =0;
   var x2 =0;

    var thing = flatBottom.solidFromSlices({
  	numslices: height
  	,callback: function() {

      //dista=2*Math.abs(Math.pow((1-(Math.pow(k,2)/(Math.pow(dist/2,2)))),2));
      //dista=Math.abs(1*Math.sqrt((Math.pow(dist,2)-(Math.pow(k,2)/9))));
      var vals = calculate(0,dist,alt,0);
      //console.log("Val0"+vals[0]+"Val1"+vals[1]+"Val2"+vals[2]);
      var x =  (vals[0]*Math.pow(t,2)) + (vals[1]*t) + vals[2];

      var valsy = calculate(0,dist,2,5);

      var y =  (valsy[0]*Math.pow(t,2)) + (valsy[1]*t) + valsy[2];

      if (x>=0) {
        x1=x;
        console.log("x1 es" + x1);
      }else{
        x2=x;
        console.log("x2 es" + x2);
      }
    //  var x = -0.16*Math.pow(t,2)+dist/2;
    //  var y = 0.16*Math.pow(t,2)-dist/2;

      var coef = t;

  		if (coef < 0.01) coef = 0.01;//los poligonos no deben colapsar

      var h = height+t*5;

      var o = new Array();
    o.push(
    circle({r: y, center: true}).scale([0.5,1,1]).translate([x1,0,0])
  //  circle({r: 1, center: true}).translate([x2,0,0])
         );

  cag =  hull(o); //.expand(1,CSG.defaultResolution2D)

var all = CSG.Polygon.createFromPoints(
  cag.getOutlinePaths()[0].points
).translate([0, 0, t]);

   t=t+0.5;
  		return all;
  	}
    });

     return thing;

}

function calculate(x1,x2,y,yaux)
{
    sgnb=" +"; sgnc=" +";
    a = x1; //x1
    a=a*a;
    b = x1; //x1
    c = 1;
    d = yaux; //y1

    e = ((x1+x2)/2);//x2
    e=e*e;
    f = ((x1+x2)/2); //x2
    g = 1;
    h = y; //y2

    i = x2; //x3
    i=i*i;
    j = x2; //x3
    k = 1;
    l = yaux; //y3

<!--EVALUATING THE DELTA DETERMINANT -->
delta = (a*f*k)+(b*g*i)+(c*e*j)-(c*f*i)-(a*g*j)-(b*e*k);
//document.output.x.value = delta;

<!--EVALUATING THE X NUMERATOR & ANSWER -->
xnum = eval((d*f*k)+(b*g*l)+(c*h*j)-(c*f*l)-(d*g*j)-(b*h*k));
xans =eval(xnum/delta);

<!--EVALUATING THE Y NUMERATOR & ANSWER -->
ynum = eval((a*h*k)+(d*g*i)+(c*e*l)-(c*h*i)-(a*g*l)-(d*e*k));
yans =eval(ynum/delta);

<!--EVALUATING THE Z NUMERATOR & ANSWER -->
znum = eval((a*f*l)+(b*h*i)+(d*e*j)-(d*f*i)-(a*h*j)-(b*e*l));
zans =eval(znum/delta);
if (yans<0) {sgnb=" "};
if (zans<0) {sgnc=" "};
xans = xans;
yans = sgnb + yans;

return [xans,yans,zans];
}

function conectores(alto) {

  var bajo = hull(
      square({size: [4,9.5], center: true}),
      circle(1).translate([-2,5,0]),
      circle(1).translate([-2,-6.5,0])
    );
  bajo= linear_extrude({ height: 1}, bajo).translate([-1.5, 0, alto-1.5]);

  var superior = hull(
      square({size: [4,9.5], center: true}),
      circle(1).translate([-2,5,0]),
      circle(1).translate([-2,-6.5,0])
    );
  superior= linear_extrude({ height: 1}, superior).translate([-1.5, 0, 0]);

    return [bajo,superior];
}
<|endoftext|>


<commit_before>import React from 'react'
import NotificationItem from 'app/components/notifications/item'
import {i18n} from 'app/utils/i18n'

function NotificationsMenu(props){
  const unread=props.unread || []
  return (

        {(unread).slice(0,5).map((p) => (
          <NotificationItem key={p.id} notification={p} now={props.open_time}/>
        ))}
        {unread.length > 5 ? (

          {i18n("And {n} more...", {n: unread.length - 5})}

        ) : null}

          {i18n("View all")}

  )
}

export default NotificationsMenu
<commit_msg>Fix #112. Improved no messages dropdown.<commit_after>import React from 'react'
import NotificationItem from 'app/components/notifications/item'
import {i18n} from 'app/utils/i18n'

function NotificationsMenu(props){
  const unread=props.unread || []
  return (

        {(unread).slice(0,5).map((p) => (
          <NotificationItem key={p.id} notification={p} now={props.open_time}/>
        ))}
        {unread.length > 5 ? (

          {i18n("And {n} more...", {n: unread.length - 5})}

        ) : null}
        {unread.length == 0 ? (

            {i18n("No new messages.")}

        ) : null}

          {i18n("View all")}

  )
}

export default NotificationsMenu
<|endoftext|>


<commit_before>import THREE from 'three'

export function getEntryExitThickness(entryInteresect, normalType){
  let normal  = entryInteresect.face.normal.clone()
  switch(normalType)
  {
    case "face":
    break
    case "x":
      normal = new THREE.Vector3(1,0,0)
    break
    case "y":
      normal = new THREE.Vector3(0,1,0)
    break
    case "z":
      normal = new THREE.Vector3(0,0,1)
    break
  }

  let object = entryInteresect.object
  if( !object ) return undefined

  let entryPoint = entryInteresect.point.clone()
  let flippedNormal = normal.clone().negate()
  let offsetPoint = entryPoint.clone().add( flippedNormal.clone().multiplyScalar(10000))

  //get escape entryPoint
  let raycaster  = new THREE.Raycaster(offsetPoint, normal.clone().normalize())
  let intersects = raycaster.intersectObjects([object], true)

  let exitPoint = null
  let minDist   = Infinity

  intersects.map(function(entry){
      let curPt = entry.point
      let curLn = curPt.clone().sub( entryPoint ).length()

      if( curLn < minDist )
      {
        exitPoint = curPt
        minDist = curLn
      }
    })

  //FIXME: todo or not ??
  object.worldToLocal( entryPoint )
  object.worldToLocal( exitPoint )

  //compute actual thickness
  let endToStart = exitPoint.clone().sub( entryPoint )
  let thickness = endToStart.length()

  return {object, entryPoint, exitPoint, thickness}
}

export function getObjectPointNormal(pickingInfos){
  let point = pickingInfos.point//closest point
  let object= pickingInfos.object//closest point
  let face  = pickingInfos.face//closes face
  let normal= face.normal

  //set point coordinates to be local , not global
  //FIXME: are we sure about this?
  object.worldToLocal( point )

  return {object, point, normal}
}

export function getDistanceFromStartEnd(start, end){
  let endToStart = end.clone().sub( start )
  let distance = endToStart.length()
  return distance
}

//compute center , dia/radius from three 3d points
export function computeCenterDiaNormalFromThreePoints(pointA,pointB,pointC){

  let plane = new THREE.Plane().setFromCoplanarPoints( pointA, pointB, pointC )
  let center = new THREE.Vector3()

  //see http://en.wikipedia.org/wiki/Circumscribed_circle
  // triangle "edges"
  let t = pointA.clone().sub( pointB )
  let u = pointB.clone().sub( pointC )
  let v = pointC.clone().sub( pointA )
  let m = pointA.clone().sub( pointC )
  let x = pointB.clone().sub( pointA )
  let z = pointC.clone().sub( pointB )

  let foo = t.clone().cross( u ).length()
  let bar = 2 * foo
  let baz = foo * foo
  let buu = 2 * baz

  let radius = ( t.length()*u.length()*v.length() )/ bar

  let alpha = ( u.lengthSq() * t.clone().dot( m ) ) / buu
  let beta  = ( m.lengthSq() * x.clone().dot( u ) ) / buu
  let gamma = ( t.lengthSq() * v.clone().dot( z ) ) / buu

  center = pointA.clone().multiplyScalar( alpha ).add(
   pointB.clone().multiplyScalar( beta ) ) .add(
   pointC.clone().multiplyScalar( gamma ) )

  let diameter = radius * 2
  let normal   = plane.normal

  return {center,diameter,normal}
}

<commit_msg>- added correct default for some utils<commit_after>import THREE from 'three'

export function getEntryExitThickness(entryInteresect, normalType="face"){
  let normal  = entryInteresect.face.normal.clone()
  switch(normalType)
  {
    case "face":
    break
    case "x":
      normal = new THREE.Vector3(1,0,0)
    break
    case "y":
      normal = new THREE.Vector3(0,1,0)
    break
    case "z":
      normal = new THREE.Vector3(0,0,1)
    break
  }

  let object = entryInteresect.object
  if( !object ) return undefined

  let entryPoint = entryInteresect.point.clone()
  let flippedNormal = normal.clone().negate()
  let offsetPoint = entryPoint.clone().add( flippedNormal.clone().multiplyScalar(10000))

  //get escape entryPoint
  let raycaster  = new THREE.Raycaster(offsetPoint, normal.clone().normalize())
  let intersects = raycaster.intersectObjects([object], true)

  let exitPoint = null
  let minDist   = Infinity

  intersects.map(function(entry){
      let curPt = entry.point
      let curLn = curPt.clone().sub( entryPoint ).length()

      if( curLn < minDist )
      {
        exitPoint = curPt
        minDist = curLn
      }
    })

  //FIXME: todo or not ??
  object.worldToLocal( entryPoint )

  object.worldToLocal( exitPoint )

  //compute actual thickness
  let endToStart = exitPoint.clone().sub( entryPoint )
  let thickness = endToStart.length()

  return {object, entryPoint, exitPoint, thickness}
}

export function getObjectPointNormal(pickingInfos){
  let point = pickingInfos.point//closest point
  let object= pickingInfos.object//closest point
  let face  = pickingInfos.face//closest face
  let normal= face.normal

  //set point coordinates to be local , not global
  //FIXME: are we sure about this?
  object.worldToLocal( point )

  return {object, point, normal}
}

export function getDistanceFromStartEnd(start, end){
  let endToStart = end.clone().sub( start )
  let distance = endToStart.length()
  return distance
}

//compute center , dia/radius from three 3d points
export function computeCenterDiaNormalFromThreePoints(pointA,pointB,pointC){

  let plane = new THREE.Plane().setFromCoplanarPoints( pointA, pointB, pointC )
  let center = new THREE.Vector3()

  //see http://en.wikipedia.org/wiki/Circumscribed_circle
  // triangle "edges"
  let t = pointA.clone().sub( pointB )
  let u = pointB.clone().sub( pointC )
  let v = pointC.clone().sub( pointA )
  let m = pointA.clone().sub( pointC )
  let x = pointB.clone().sub( pointA )
  let z = pointC.clone().sub( pointB )

  let foo = t.clone().cross( u ).length()
  let bar = 2 * foo
  let baz = foo * foo
  let buu = 2 * baz

  let radius = ( t.length()*u.length()*v.length() )/ bar

  let alpha = ( u.lengthSq() * t.clone().dot( m ) ) / buu
  let beta  = ( m.lengthSq() * x.clone().dot( u ) ) / buu
  let gamma = ( t.lengthSq() * v.clone().dot( z ) ) / buu

  center = pointA.clone().multiplyScalar( alpha ).add(
   pointB.clone().multiplyScalar( beta ) ) .add(
   pointC.clone().multiplyScalar( gamma ) )

  let diameter = radius * 2
  let normal   = plane.normal

  return {center,diameter,normal}
}

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { debounce } from './utils'

export default function SpeechRecognition(options) {
  const SpeechRecognitionInner = function (WrappedComponent) {
    const BrowserSpeechRecognition =
      typeof window !== 'undefined' &&
      (window.SpeechRecognition ||
        window.webkitSpeechRecognition ||
        window.mozSpeechRecognition ||
        window.msSpeechRecognition ||
        window.oSpeechRecognition)
    const recognition = BrowserSpeechRecognition
      ? new BrowserSpeechRecognition()
      : null
    const browserSupportsSpeechRecognition = recognition !== null
    const isAndroid = /(android)/i.test(navigator.userAgent)
    let listening
    if (
      !browserSupportsSpeechRecognition ||
      (options && options.autoStart === false)
    ) {
      listening = false
    } else {
      recognition.start()
      listening = true
    }
    let pauseAfterDisconnect = false
    let interimTranscript = ''
    let finalTranscript = ''

    return class SpeechRecognitionContainer extends Component {
      constructor(props) {
        super(props)

        if (browserSupportsSpeechRecognition) {
          recognition.continuous = options.continuous !== false
          recognition.interimResults = true
          recognition.onresult = this.updateTranscript.bind(this)
          recognition.onend = this.onRecognitionDisconnect.bind(this)
        }

        if (isAndroid) {
          this.updateFinalTranscript = debounce(this.updateFinalTranscript.bind(this), 250, true)
        }

        this.state = {
          interimTranscript,
          finalTranscript,
          listening
        }
      }

      disconnect = disconnectType => {
        if (recognition) {
          switch (disconnectType) {
            case 'ABORT':
              pauseAfterDisconnect = true
              recognition.abort()
              break
            case 'RESET':
              pauseAfterDisconnect = false
              recognition.abort()
              break
            case 'STOP':
            default:
              pauseAfterDisconnect = true
              recognition.stop()
          }
        }
      }

      onRecognitionDisconnect() {
        listening = false
        if (pauseAfterDisconnect) {
          this.setState({ listening })
        } else if (recognition) {
          if (recognition.continuous) {
            this.startListening()
          } else {
            this.setState({ listening })
          }
        }
        pauseAfterDisconnect = false
      }

      updateTranscript(event) {
        interimTranscript = ''
        for (let i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal && (!isAndroid || event.results[i][0].confidence > 0)) {
            this.updateFinalTranscript(event.results[i][0].transcript)
          } else {
            interimTranscript = this.concatTranscripts(
              interimTranscript,
              event.results[i][0].transcript
            )
          }
        }
        this.setState({ finalTranscript, interimTranscript })
      }

      updateFinalTranscript(newFinalTranscript) {
        finalTranscript = this.concatTranscripts(
          finalTranscript,
          newFinalTranscript
        )
      }

      concatTranscripts(...transcriptParts) {
        return transcriptParts.map(t => t.trim()).join(' ').trim()
      }

      resetTranscript = () => {
        interimTranscript = ''
        finalTranscript = ''
        this.disconnect('RESET')
        this.setState({ interimTranscript, finalTranscript })
      }

      startListening = () => {
        if (recognition && !listening) {
          if (!recognition.continuous) {
            this.resetTranscript()
          }
          try {
            recognition.start()
          } catch (DOMException) {
            // Tried to start recognition after it has already started - safe to swallow this error
          }
          listening = true
          this.setState({ listening })
        }
      }

      abortListening = () => {
        listening = false
        this.setState({ listening })
        this.disconnect('ABORT')
      }

      stopListening = () => {
        listening = false
        this.setState({ listening })
        this.disconnect('STOP')
      }

      render() {
        const transcript = this.concatTranscripts(
          finalTranscript,
          interimTranscript
        )

        return (
          <WrappedComponent
            resetTranscript={this.resetTranscript}
            startListening={this.startListening}
            abortListening={this.abortListening}
            stopListening={this.stopListening}
            transcript={transcript}
            recognition={recognition}
            browserSupportsSpeechRecognition={browserSupportsSpeechRecognition}
            {...this.state}
            {...this.props} />
        )
      }
    }
  }

  if (typeof options === 'function') {
    return SpeechRecognitionInner(options)
  } else {
    return SpeechRecognitionInner
  }
}
<commit_msg>Remove use of class properties<commit_after>import React, { Component } from 'react'
import { debounce } from './utils'

export default function SpeechRecognition(options) {
  const SpeechRecognitionInner = function (WrappedComponent) {
    const BrowserSpeechRecognition =
      typeof window !== 'undefined' &&
      (window.SpeechRecognition ||
        window.webkitSpeechRecognition ||
        window.mozSpeechRecognition ||
        window.msSpeechRecognition ||
        window.oSpeechRecognition)
    const recognition = BrowserSpeechRecognition
      ? new BrowserSpeechRecognition()
      : null
    const browserSupportsSpeechRecognition = recognition !== null
    const isAndroid = /(android)/i.test(navigator.userAgent)
    let listening
    if (
      !browserSupportsSpeechRecognition ||
      (options && options.autoStart === false)
    ) {
      listening = false
    } else {
      recognition.start()
      listening = true
    }
    let pauseAfterDisconnect = false
    let interimTranscript = ''
    let finalTranscript = ''

    return class SpeechRecognitionContainer extends Component {
      constructor(props) {
        super(props)

        if (browserSupportsSpeechRecognition) {
          recognition.continuous = options.continuous !== false
          recognition.interimResults = true
          recognition.onresult = this.updateTranscript.bind(this)
          recognition.onend = this.onRecognitionDisconnect.bind(this)
        }

        this.disconnect = this.disconnect.bind(this)
        this.resetTranscript = this.resetTranscript.bind(this)
        this.startListening = this.startListening.bind(this)
        this.abortListening = this.abortListening.bind(this)
        this.stopListening = this.stopListening.bind(this)

        if (isAndroid) {
          this.updateFinalTranscript = debounce(this.updateFinalTranscript.bind(this), 250, true)
        }

        this.state = {
          interimTranscript,
          finalTranscript,
          listening
        }
      }

      disconnect(disconnectType) {
        if (recognition) {
          switch (disconnectType) {
            case 'ABORT':
              pauseAfterDisconnect = true
              recognition.abort()
              break
            case 'RESET':
              pauseAfterDisconnect = false
              recognition.abort()
              break
            case 'STOP':
            default:
              pauseAfterDisconnect = true
              recognition.stop()
          }
        }
      }

      onRecognitionDisconnect() {
        listening = false
        if (pauseAfterDisconnect) {
          this.setState({ listening })
        } else if (recognition) {
          if (recognition.continuous) {
            this.startListening()
          } else {
            this.setState({ listening })
          }
        }
        pauseAfterDisconnect = false
      }

      updateTranscript(event) {
        interimTranscript = ''
        for (let i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal && (!isAndroid || event.results[i][0].confidence > 0)) {
            this.updateFinalTranscript(event.results[i][0].transcript)
          } else {
            interimTranscript = this.concatTranscripts(
              interimTranscript,
              event.results[i][0].transcript
            )
          }
        }
        this.setState({ finalTranscript, interimTranscript })
      }

      updateFinalTranscript(newFinalTranscript) {
        finalTranscript = this.concatTranscripts(
          finalTranscript,
          newFinalTranscript
        )
      }

      concatTranscripts(...transcriptParts) {
        return transcriptParts.map(t => t.trim()).join(' ').trim()
      }

      resetTranscript() {
        interimTranscript = ''
        finalTranscript = ''
        this.disconnect('RESET')
        this.setState({ interimTranscript, finalTranscript })
      }

      startListening() {
        if (recognition && !listening) {
          if (!recognition.continuous) {
            this.resetTranscript()
          }
          try {
            recognition.start()
          } catch (DOMException) {
            // Tried to start recognition after it has already started - safe to swallow this error
          }
          listening = true
          this.setState({ listening })
        }
      }

      abortListening() {
        listening = false
        this.setState({ listening })
        this.disconnect('ABORT')
      }

      stopListening() {
        listening = false
        this.setState({ listening })
        this.disconnect('STOP')
      }

      render() {
        const transcript = this.concatTranscripts(
          finalTranscript,
          interimTranscript
        )

        return (
          <WrappedComponent
            resetTranscript={this.resetTranscript}
            startListening={this.startListening}
            abortListening={this.abortListening}
            stopListening={this.stopListening}
            transcript={transcript}
            recognition={recognition}
            browserSupportsSpeechRecognition={browserSupportsSpeechRecognition}
            {...this.state}
            {...this.props} />
        )
      }
    }
  }

  if (typeof options === 'function') {
    return SpeechRecognitionInner(options)
  } else {
    return SpeechRecognitionInner
  }
}
<|endoftext|>


<commit_before>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    $(document).ready(function(){

        //console.log(imageSrc);

        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#pdf').click(function () {
        var imageSrc = $('#image').attr('src');

        console.log(imageSrc);
        var doc = new jsPDF();

        var imgData = 'data:image/jpeg;base64,/imageSrc';
        console.log(imgData);
        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");
        doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
        // doc.fromHTML($('#content-box').html(), 15, 15, {
        //     'width': 170,'elementHandlers': specialElementHandlers
        // });
        doc.save('sample-file.pdf');
    });
});

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });  <commit_msg>added files<commit_after>// $(function() {
//     $("#print").on('click', function() {
//        // console.log("asdfasdfasd asdfasdf asdasdf");
//         $.print("#content-box");
//     });

    $(document).ready(function(){

        //console.log(imageSrc);

        var doc = new jsPDF();

        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#pdf').click(function () {
        var imageSrc = $('#image').attr('src');

        console.log(imageSrc);
        var doc = new jsPDF();

        var imgData = 'data:image/jpeg;base64,/'+imageSrc;
        console.log(imgData);
        doc.setFontSize(40);
        doc.text(35, 25, "Octonyan loves jsPDF");
        doc.addImage(imgData, 'JPEG', 15, 40, 180, 180);
        // doc.fromHTML($('#content-box').html(), 15, 15, {
        //     'width': 170,'elementHandlers': specialElementHandlers
        // });
        doc.save('sample-file.pdf');
    });
});

      $(function() {
    $("#message").on('click', function() {
        alert("asdfasdf");
       // $.message("#formdata");
    });
     });  <|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const assign = require('lodash.assign')
const makeTemplate = require('./make-template.js')
const defaultDirectives = require('./default-directives.js')

module.exports = function (settings) {
  settings = settings || {}
  settings.cacheDirectory = path.join(process.cwd(), settings.cacheDirectory || './.atlatl-cache/')
  settings.runtimePath = settings.runtimePath || 'atlatl/code/runtime.js'

  var directives = assign({}, defaultDirectives, settings.directives || {})
  var promises = {}

  return function (file) {
    var directory = path.dirname(file)

    function load (file) {
      var _file = path.join(directory, file)

      if (!promises[_file]) {
        promises[_file] = new Promise(function (resolve, reject) {
          fs.readFile(_file, { encoding: 'utf-8' }, function (err, result) {
            if (err) throw err

            makeTemplate(result, load, directives, settings.runtimePath, function (err, result) {
              if (err) throw err

              var cacheFile = path.join(settings.cacheDirectory, file + '.js')

              mkdirp(path.dirname(cacheFile), function (err) {
                if (err) throw err

                fs.writeFile(cacheFile, result, function (err) {
                  if (err) throw err

                  resolve(cacheFile)
                })
              })
            })
          })
        })
      }

      return promises[_file].then(function (path) {
        delete require.cache[path]

        var Template = require(path)

        return Promise.resolve(function (content) {
          return (new Template()).render(content)
        })
      })
    }

    return load(path.basename(file))
  }
}
<commit_msg>Trim the read file<commit_after>'use strict'

const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const assign = require('lodash.assign')
const makeTemplate = require('./make-template.js')
const defaultDirectives = require('./default-directives.js')

module.exports = function (settings) {
  settings = settings || {}
  settings.cacheDirectory = path.join(process.cwd(), settings.cacheDirectory || './.atlatl-cache/')
  settings.runtimePath = settings.runtimePath || 'atlatl/code/runtime.js'

  var directives = assign({}, defaultDirectives, settings.directives || {})
  var promises = {}

  return function (file) {
    var directory = path.dirname(file)

    function load (file) {
      var _file = path.join(directory, file)

      if (!promises[_file]) {
        promises[_file] = new Promise(function (resolve, reject) {
          fs.readFile(_file, { encoding: 'utf-8' }, function (err, result) {
            if (err) throw err

            makeTemplate(result.trim(), load, directives, settings.runtimePath, function (err, result) {
              if (err) throw err

              var cacheFile = path.join(settings.cacheDirectory, file + '.js')

              mkdirp(path.dirname(cacheFile), function (err) {
                if (err) throw err

                fs.writeFile(cacheFile, result, function (err) {
                  if (err) throw err

                  resolve(cacheFile)
                })
              })
            })
          })
        })
      }

      return promises[_file].then(function (path) {
        delete require.cache[path]

        var Template = require(path)

        return Promise.resolve(function (content) {
          return (new Template()).render(content)
        })
      })
    }

    return load(path.basename(file))
  }
}
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = mongoose.Schema.ObjectId,
    _ = require('lodash'),
    base = require('./baseContentModel');

var properties = _.extend({
    name: {type: String, required: true},
    type: {type: String, required: true}, // Activity, Exhibit, Tour, Program/Festival
    description: String,
    visibility: String, //Private/Public
    setupDateTime: Date,
    startDateTime: Date,
    endDateTime: Date,
    cleanupDateTime: Date,
    isReccuring: Boolean,
    isAllDayEvent: Boolean,
    anticipatedAttendance: Number,
    location: String,
    geoLocation: {type: [Number], index: '2d'},
    media: [{type: ObjectId, ref: 'Media'}],
    coverPhoto: {type: ObjectId, ref: 'Media'},
    organizer: {
        name: String,
        email: {
            type: String,
            match: [/.+\@.+\..+/, 'Please enter a valid email']
        },
        phone: String
    },
    tourpointId: String //Entangled
}, base.properties);

var EventSchema = new Schema(properties, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

EventSchema.pre('save', function(next) {
    base.preSave(this);
    next();
});

EventSchema.virtual('coords').get(function(){
    if(this.geoLocation && this.geoLocation.length == 2){
        return {
            latitude: this.geoLocation[0],
            longitude: this.geoLocation[1]
        };
    }
    return {};

});

EventSchema.virtual('permissions')
    .set(function(permissions) {
        this._permissions = permissions;
    })
    .get(function() {
        return this._permissions;
    });

//Each model must define its set of assignable permissions.
//All models inherit basic CRUD permissions
EventSchema.statics = base.permissions;

//Programatically create field permissions
EventSchema.statics.fieldPermissions = function(){
    return base.fieldPermissions(this);
}

//Specifies which permissions are granted to a user over the documents they create
EventSchema.statics.permissionsGrantedOnCreation = function(){
    return base.permissionsGrantedOnCreation(this);
};

//Specifies which permissions are granted to a user on creation
EventSchema.statics.permissionsGrantedOnUserCreation = function(){
    return base.permissionsGrantedOnUserCreation(this);
};

EventSchema.statics.permissionsGrantedToAnon = function(){
    var fieldPermissions = this.fieldPermissions();
    var readPermission = this.readPermission();
    var readListPermission = this.readListPermission();

    return [
        readPermission,
        readListPermission,
        fieldPermissions['name'][readPermission],
        fieldPermissions['type'][readPermission],
        fieldPermissions['description'][readPermission],
        fieldPermissions['visibility'][readPermission],
        fieldPermissions['startDateTime'][readPermission],
        fieldPermissions['endDateTime'][readPermission],
        fieldPermissions['isReccuring'][readPermission],
        fieldPermissions['location'][readPermission],
        fieldPermissions['geoLocation'][readPermission],
        fieldPermissions['media'][readPermission],
        fieldPermissions['coverPhoto'][readPermission],
        fieldPermissions['isAllDayEvent'][readPermission],
        fieldPermissions['tourpointId'][readPermission],
        fieldPermissions['organizer'][readPermission]
    ].concat(base.permissionsGrantedToAnon(this));
};

EventSchema.statics.load = function(id, callback){
    this.findOne({
        _id: id
    })
    .populate('media', 'slug id')
    .populate('coverPhoto', 'slug id')
    .exec(callback);
};

mongoose.model('Event', EventSchema);
<commit_msg>Fixed 500 server error caused by getting fieldPermissions for nested object on Event model.<commit_after>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = mongoose.Schema.ObjectId,
    _ = require('lodash'),
    base = require('./baseContentModel');

var properties = _.extend({
    name: {type: String, required: true},
    type: {type: String, required: true}, // Activity, Exhibit, Tour, Program/Festival
    description: String,
    visibility: String, //Private/Public
    setupDateTime: Date,
    startDateTime: Date,
    endDateTime: Date,
    cleanupDateTime: Date,
    isReccuring: Boolean,
    isAllDayEvent: Boolean,
    anticipatedAttendance: Number,
    location: String,
    geoLocation: {type: [Number], index: '2d'},
    media: [{type: ObjectId, ref: 'Media'}],
    coverPhoto: {type: ObjectId, ref: 'Media'},
    organizer: {
        name: String,
        email: {
            type: String,
            match: [/.+\@.+\..+/, 'Please enter a valid email']
        },
        phone: String
    },
    tourpointId: String //Entangled
}, base.properties);

var EventSchema = new Schema(properties, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

EventSchema.pre('save', function(next) {
    base.preSave(this);
    next();
});

EventSchema.virtual('coords').get(function(){
    if(this.geoLocation && this.geoLocation.length == 2){
        return {
            latitude: this.geoLocation[0],
            longitude: this.geoLocation[1]
        };
    }
    return {};

});

EventSchema.virtual('permissions')
    .set(function(permissions) {
        this._permissions = permissions;
    })
    .get(function() {
        return this._permissions;
    });

//Each model must define its set of assignable permissions.
//All models inherit basic CRUD permissions
EventSchema.statics = base.permissions;

//Programatically create field permissions
EventSchema.statics.fieldPermissions = function(){
    return base.fieldPermissions(this);
}

//Specifies which permissions are granted to a user over the documents they create
EventSchema.statics.permissionsGrantedOnCreation = function(){
    return base.permissionsGrantedOnCreation(this);
};

//Specifies which permissions are granted to a user on creation
EventSchema.statics.permissionsGrantedOnUserCreation = function(){
    return base.permissionsGrantedOnUserCreation(this);
};

EventSchema.statics.permissionsGrantedToAnon = function(){
    var fieldPermissions = this.fieldPermissions();
    var readPermission = this.readPermission();
    var readListPermission = this.readListPermission();

    return [
        readPermission,
        readListPermission,
        fieldPermissions['name'][readPermission],
        fieldPermissions['type'][readPermission],
        fieldPermissions['description'][readPermission],
        fieldPermissions['visibility'][readPermission],
        fieldPermissions['startDateTime'][readPermission],
        fieldPermissions['endDateTime'][readPermission],
        fieldPermissions['isReccuring'][readPermission],
        fieldPermissions['location'][readPermission],
        fieldPermissions['geoLocation'][readPermission],
        fieldPermissions['media'][readPermission],
        fieldPermissions['coverPhoto'][readPermission],
        fieldPermissions['isAllDayEvent'][readPermission],
        fieldPermissions['tourpointId'][readPermission],
        fieldPermissions['organizer.name'][readPermission],
        fieldPermissions['organizer.email'][readPermission],
        fieldPermissions['organizer.phone'][readPermission]
    ].concat(base.permissionsGrantedToAnon(this));
};

EventSchema.statics.load = function(id, callback){
    this.findOne({
        _id: id
    })
    .populate('media', 'slug id')
    .populate('coverPhoto', 'slug id')
    .exec(callback);
};

mongoose.model('Event', EventSchema);
<|endoftext|>


<commit_before>'use strict';

/* global document */

function renderHistory(history) {
    var template = document.getElementById('history-template').innerHTML;
    var display = Mustache.render(template, history);
    document.getElementById('historyTable').innerHTML = display;

    if(index === 0) {
        $prevHistory.style.display = 'none';
    } else {
        $prevHistory.style.display = 'inline';
    }

    if (index === batchHistory.length - perPage) {
        $nextHistory.style.display = 'none';
    } else {
        $nextHistory.style.display = 'inline';
    }
}

function loadHistory(e) {
    if (e) {
        e.preventDefault();
    }

    reqwest({
        url: 'api/history',
        method: 'get',
        headers: {
            'Authorization': 'Bearer '+sessionStorage.getItem('token')
        }
    })
    .then(function (resp) {
        batchHistory = resp.history;
        index = 0;
        perPage = 10;

        historyData.history = batchHistory.slice(index, perPage);
        renderHistory(historyData);
    })
    .fail(function (err, msg) {
        if(JSON.parse(err.response).error == 'disconnected') document.location.href = './';
    });

}

function changePin(e) {
    if (e) {
        e.preventDefault();
    }

    reqwest({
        url: 'api/pin',
        method: 'put',
        headers: {
            'Authorization': 'Bearer '+sessionStorage.getItem('token')
        },
        data: { oldPin: $pin.elements['oldPin'].value, newPin: $pin.elements['newPin'].value, checkPin: $pin.elements['checkPin'].value }
    })
    .then(function (resp) {
        if(resp.success == 'changePin') {
            showModal('Changement de PIN', 'Le code PIN a bien été modifié !');

            var $inputs = [].slice.call(document.getElementsByTagName('input'));
            $inputs.forEach(function ($input) {
                $input.value = '';
            });
        }
    })
    .fail(function (err, msg) {
        var error = JSON.parse(err.response);
        switch(error.error) {
            case 'wrongPin':
                showModal('Erreur', 'Le PIN actuel n\'est pas le bon');
                break;
            case 'formatPin':
                showModal('Erreur', 'Le format du nouveau PIN n\'est pas bon (4 caractères, uniquement des chiffres)');
                break;
            case 'checkFailed':
                showModal('Erreur', 'Les deux PIN ne correspondent pas');
                break;
            default:
                showModal('Erreur', 'Une erreur a eu lieu');
                break;
        }
    });

}

function transfer(e) {
    e.preventDefault();

    var isFirstStep = $transferCancel.nextElementSibling.childNodes[0].nodeValue.indexOf('Suivant') === 0;

    if (!isFirstStep) {
        reqwest({
            url: 'api/transfer',
            method: 'post',
            headers: {
                'Authorization': 'Bearer '+sessionStorage.getItem('token')
            },
            data: {
                userId: $transferTo.value,
                amount: $transferAmount.value,
                pin: $transferPIN.value
            }
        })
        .then(function (resp) {

        })
        .fail(function (err, msg) {
            var error = JSON.parse(err.response);
            switch(error.error) {
                case 'bearer':
                    showModal('Erreur', 'Utilisateur introuvable');
                    break;
                default:
                    showModal('Erreur', 'Une erreur a eu lieu');
                    break;
            }
        });
        return;
    }

    $transferCancel.style.display = 'inline-block';
    $transferTo.setAttribute('disabled', '');
    $transferPIN.setAttribute('disabled', '');
    $transferAmount.setAttribute('disabled', '');
    // next button (suivant) children.
    // First one is text node (suivant >), second one is ripple effect
    $transferCancel.nextElementSibling.childNodes[0].nodeValue = 'Envoyer à ' + 'Lucas Lonk';
    return;
    reqwest({
        url: 'api/getEtuName?cardId=' + $transferTo.value,
        method: 'get',
        headers: {
            'Authorization': 'Bearer '+sessionStorage.getItem('token')
        }
    })
    .then(function (resp) {
        $transferCancel.style.display = 'inline-block';
        $transferTo.setAttribute('disabled', '');
        $transferPIN.setAttribute('disabled', '');
        $transferAmount.setAttribute('disabled', '');
        // next button (suivant) children.
        // First one is text node (suivant >), second one is ripple effect
        $transferCancel.nextElementSibling.childNodes[0].nodeValue = 'Envoyer à ' + resp;
    })
    .fail(function (err, msg) {
        var error = JSON.parse(err.response);
        switch(error.error) {
            case 'wrongPin':
                showModal('Erreur', 'Le PIN actuel n\'est pas le bon');
                break;
            case 'card':
                showModal('Erreur', 'Spécifiez un utilisateur');
                break;
            case 'user':
                showModal('Erreur', 'Utilisateur introuvable');
                break;
            default:
                showModal('Erreur', 'Une erreur a eu lieu');
                break;
        }
    });
}

function cancelTransfer(e) {
    e.preventDefault();

    $transferCancel.style.display = 'none';
    $transferTo.removeAttribute('disabled');
    $transferPIN.removeAttribute('disabled');
    $transferAmount.removeAttribute('disabled');
    $transferTo.value = '';
    $transferTo.focus();
    $transferCancel.nextElementSibling.childNodes[0].nodeValue = 'Suivant ›';
}

var $links = [].slice.call(document.getElementsByClassName('mdl-navigation__link'));

$links.forEach(function ($link) {
    $link.addEventListener('click', function (e) {
        e.preventDefault();

        var $page       = document.getElementById($link.getAttribute('data-target'));
        var $active     = document.getElementsByClassName('page-visible')[0];
        var $activeLink = document.getElementsByClassName('navigation-active')[0];

        if ($page === $active) {
            return;
        }

        $active.className = 'page-content';
        $page.className  += ' page-visible';

        $activeLink.className = 'mdl-navigation__link';
        $link.className      += ' navigation-active';

        return false;
    }, false);
});

// Set required after Material loads to prevent automatic error input
var $input = document.querySelector('#page-1 .mdl-textfield__input');
setTimeout(function () {
    $input.setAttribute('required', '');
}, 100);

var $history = document.getElementById('history');
var $pin = document.getElementById('pin');
var $transferPIN = document.getElementById('transferPIN');
var $transferTo = document.getElementById('transferTo');
var $transferAmount = document.getElementById('transferAmount');
var $transfer = document.getElementById('transfer');
var $transferCancel = document.getElementById('cancelTransfer');
var $prevHistory = document.getElementById('prevHistory');
var $nextHistory = document.getElementById('nextHistory');

var batchHistory = [];
var index = 0;
var perPage = 10;

var historyData = {
    type: function() {
        if(this.credit) return 'Rechargement';
        return 'Achat';
    },
    priceEuro: function() {
        if(this.credit) return this.credit/100;
        return this.price/100;
    },
    performer: function() {
        if(this.credit) return 'Opérateur ' + this.Operator.firstname + ' ' + this.Operator.lastname;
        return  'Vendeur ' + this.Seller.firstname + ' ' + this.Seller.lastname;
    },
    object: function() {
        if(this.credit) return this.ReloadType.name;
        return this.Article.name;
    },
    formatDate: function() {
        var date = new Date(this.date);
        return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth()+1)).slice(-2) + '/' + date.getFullYear();
    }
};

$history.addEventListener('click', loadHistory, false);

$pin.addEventListener('submit', changePin, false);

$transfer.addEventListener('submit', transfer, false);
$transferCancel.addEventListener('click', cancelTransfer, false);

$prevHistory.addEventListener('click', function (e){
    e.preventDefault();

    index -= perPage;
    index = Math.max(0, index);

    historyData.history = batchHistory.slice(index, index + perPage);
    renderHistory(historyData);
});

$nextHistory.addEventListener('click', function (e){
    e.preventDefault();

    index += perPage;
    index = Math.min(batchHistory.length - perPage, index);

    historyData.history = batchHistory.slice(index, index + perPage);
    renderHistory(historyData);
});

//loadHistory();
<commit_msg>Remove debug symbols<commit_after>'use strict';

/* global document */

function renderHistory(history) {
    var template = document.getElementById('history-template').innerHTML;
    var display = Mustache.render(template, history);
    document.getElementById('historyTable').innerHTML = display;

    if(index === 0) {
        $prevHistory.style.display = 'none';
    } else {
        $prevHistory.style.display = 'inline';
    }

    if (index === batchHistory.length - perPage) {
        $nextHistory.style.display = 'none';
    } else {
        $nextHistory.style.display = 'inline';
    }
}

function loadHistory(e) {
    if (e) {
        e.preventDefault();
    }

    reqwest({
        url: 'api/history',
        method: 'get',
        headers: {
            'Authorization': 'Bearer '+sessionStorage.getItem('token')
        }
    })
    .then(function (resp) {
        batchHistory = resp.history;
        index = 0;
        perPage = 10;

        historyData.history = batchHistory.slice(index, perPage);
        renderHistory(historyData);
    })
    .fail(function (err, msg) {
        if(JSON.parse(err.response).error == 'disconnected') document.location.href = './';
    });

}

function changePin(e) {
    if (e) {
        e.preventDefault();
    }

    reqwest({
        url: 'api/pin',
        method: 'put',
        headers: {
            'Authorization': 'Bearer '+sessionStorage.getItem('token')
        },
        data: { oldPin: $pin.elements['oldPin'].value, newPin: $pin.elements['newPin'].value, checkPin: $pin.elements['checkPin'].value }
    })
    .then(function (resp) {
        if(resp.success == 'changePin') {
            showModal('Changement de PIN', 'Le code PIN a bien été modifié !');

            var $inputs = [].slice.call(document.getElementsByTagName('input'));
            $inputs.forEach(function ($input) {
                $input.value = '';
            });
        }
    })
    .fail(function (err, msg) {
        var error = JSON.parse(err.response);
        switch(error.error) {
            case 'wrongPin':
                showModal('Erreur', 'Le PIN actuel n\'est pas le bon');
                break;
            case 'formatPin':
                showModal('Erreur', 'Le format du nouveau PIN n\'est pas bon (4 caractères, uniquement des chiffres)');
                break;
            case 'checkFailed':
                showModal('Erreur', 'Les deux PIN ne correspondent pas');
                break;
            default:
                showModal('Erreur', 'Une erreur a eu lieu');
                break;
        }
    });

}

function transfer(e) {
    e.preventDefault();

    var isFirstStep = $transferCancel.nextElementSibling.childNodes[0].nodeValue.indexOf('Suivant') === 0;

    if (!isFirstStep) {
        reqwest({
            url: 'api/transfer',
            method: 'post',
            headers: {
                'Authorization': 'Bearer '+sessionStorage.getItem('token')
            },
            data: {
                userId: $transferTo.value,
                amount: $transferAmount.value,
                pin: $transferPIN.value
            }
        })
        .then(function (resp) {
            showModal('Virement', 'Virement effectué');
            $transferCancel.style.display = 'none';
            $transferTo.removeAttribute('disabled');
            $transferPIN.removeAttribute('disabled');
            $transferAmount.removeAttribute('disabled');
            $transferTo.value = '';
            $transferPIN.value = '';
            $transferAmount.value = '';
            $transferCancel.nextElementSibling.childNodes[0].nodeValue = 'Suivant ›';
        })
        .fail(function (err, msg) {
            var error = JSON.parse(err.response);
            switch(error.error) {
                case 'bearer':
                    showModal('Erreur', 'Utilisateur introuvable');
                    break;
                default:
                    showModal('Erreur', 'Une erreur a eu lieu');
                    break;
            }
        });
        return;
    }

    reqwest({
        url: 'api/getEtuName?cardId=' + $transferTo.value,
        method: 'get',
        headers: {
            'Authorization': 'Bearer '+sessionStorage.getItem('token')
        }
    })
    .then(function (resp) {
        $transferCancel.style.display = 'inline-block';
        $transferTo.setAttribute('disabled', '');
        $transferPIN.setAttribute('disabled', '');
        $transferAmount.setAttribute('disabled', '');
        // next button (suivant) children.
        // First one is text node (suivant >), second one is ripple effect
        $transferCancel.nextElementSibling.childNodes[0].nodeValue = 'Envoyer à ' + resp;
    })
    .fail(function (err, msg) {
        var error = JSON.parse(err.response);
        switch(error.error) {
            case 'wrongPin':
                showModal('Erreur', 'Le PIN actuel n\'est pas le bon');
                break;
            case 'card':
                showModal('Erreur', 'Spécifiez un utilisateur');
                break;
            case 'user':
                showModal('Erreur', 'Utilisateur introuvable');
                break;
            default:
                showModal('Erreur', 'Une erreur a eu lieu');
                break;
        }
    });
}

function cancelTransfer(e) {
    e.preventDefault();

    $transferCancel.style.display = 'none';
    $transferTo.removeAttribute('disabled');
    $transferPIN.removeAttribute('disabled');
    $transferAmount.removeAttribute('disabled');
    $transferTo.value = '';
    $transferTo.focus();
    $transferCancel.nextElementSibling.childNodes[0].nodeValue = 'Suivant ›';
}

var $links = [].slice.call(document.getElementsByClassName('mdl-navigation__link'));

$links.forEach(function ($link) {
    $link.addEventListener('click', function (e) {
        e.preventDefault();

        var $page       = document.getElementById($link.getAttribute('data-target'));
        var $active     = document.getElementsByClassName('page-visible')[0];
        var $activeLink = document.getElementsByClassName('navigation-active')[0];

        if ($page === $active) {
            return;
        }

        $active.className = 'page-content';
        $page.className  += ' page-visible';

        $activeLink.className = 'mdl-navigation__link';
        $link.className      += ' navigation-active';

        return false;
    }, false);
});

// Set required after Material loads to prevent automatic error input
var $input = document.querySelector('#page-1 .mdl-textfield__input');
setTimeout(function () {
    $input.setAttribute('required', '');
}, 100);

var $history = document.getElementById('history');
var $pin = document.getElementById('pin');
var $transferPIN = document.getElementById('transferPIN');
var $transferTo = document.getElementById('transferTo');
var $transferAmount = document.getElementById('transferAmount');
var $transfer = document.getElementById('transfer');
var $transferCancel = document.getElementById('cancelTransfer');
var $prevHistory = document.getElementById('prevHistory');
var $nextHistory = document.getElementById('nextHistory');

var batchHistory = [];
var index = 0;
var perPage = 10;

var historyData = {
    type: function() {
        if(this.credit) return 'Rechargement';
        return 'Achat';
    },
    priceEuro: function() {
        if(this.credit) return this.credit/100;
        return this.price/100;
    },
    performer: function() {
        if(this.credit) return 'Opérateur ' + this.Operator.firstname + ' ' + this.Operator.lastname;
        return  'Vendeur ' + this.Seller.firstname + ' ' + this.Seller.lastname;
    },
    object: function() {
        if(this.credit) return this.ReloadType.name;
        return this.Article.name;
    },
    formatDate: function() {
        var date = new Date(this.date);
        return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth()+1)).slice(-2) + '/' + date.getFullYear();
    }
};

$history.addEventListener('click', loadHistory, false);

$pin.addEventListener('submit', changePin, false);

$transfer.addEventListener('submit', transfer, false);
$transferCancel.addEventListener('click', cancelTransfer, false);

$prevHistory.addEventListener('click', function (e){
    e.preventDefault();

    index -= perPage;
    index = Math.max(0, index);

    historyData.history = batchHistory.slice(index, index + perPage);
    renderHistory(historyData);
});

$nextHistory.addEventListener('click', function (e){
    e.preventDefault();

    index += perPage;
    index = Math.min(batchHistory.length - perPage, index);

    historyData.history = batchHistory.slice(index, index + perPage);
    renderHistory(historyData);
});

loadHistory();
<|endoftext|>


<commit_before>'use strict';

describe('test module angular-placeholder', function() {
	beforeEach(function() {
		module('ng.shims.placeholder');
	});

	describe('for an empty input field of type text using directive placeholder', function() {
		var email_field, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			email_field = angular.element('<input type="text" name="useremail" placeholder="E-Mail" ng-model="form.email" value="" />');
			$compile(email_field)(scope);
		}));

		it('should display the placeholder as input value', function() {
			expect(email_field.val()).toBe('E-Mail');
			expect(email_field.hasClass('empty')).toBe(true);
			expect(scope.form.email).toBe('');
		});

		describe('when input field gains focus', function() {
			beforeEach(function() {
				email_field.triggerHandler('focus');
			});

			afterEach(function() {
				email_field.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(email_field.val()).toBe('');
				expect(email_field.hasClass('empty')).toBe(false);
				expect(scope.form.email).toBe('');
			});

			it('should restore the placeholder and class "empty" when leaving field unchanged', function() {
				email_field.triggerHandler('blur');
				expect(email_field.val()).toBe('E-Mail');
				expect(email_field.hasClass('empty')).toBe(true);
				expect(scope.form.email).toBe('');
			});

			describe('when text is entered into the input field', function() {
				beforeEach(function() {
					email_field.val('me@example.com');
					email_field.triggerHandler('blur');
				});

				it('should remember the entered text in scope.form and remove class "empty"', function() {
					expect(email_field.val()).toBe('me@example.com');
					expect(email_field.hasClass('empty')).toBe(false);
					expect(scope.form.email).toBe('me@example.com');
				});

				it('should reset the field as "empty"', function() {
					email_field.triggerHandler('focus');
					email_field.val('');
					email_field.triggerHandler('blur');
					expect(email_field.val()).toBe('E-Mail');
					expect(email_field.hasClass('empty')).toBe(true);
					expect(scope.form.email).toBe('');
				});
			});
		});

		describe('when the value is set through the model controller', function() {
			beforeEach(function() {
				expect(email_field.val()).toBe('E-Mail');
				scope.form.email = 'john@doe.com';
				scope.$digest();
			});

			it('should display the value in the input field', function() {
				expect(email_field.val()).toBe('john@doe.com');
				expect(email_field.hasClass('empty')).toBe(false);
			});

			it('should replace an empty value in the input field by placeholder', function() {
				scope.form.email = '';
				scope.$digest();
				expect(email_field.val()).toBe('E-Mail');
				expect(email_field.hasClass('empty')).toBe(true);
			});

		});

	});

	describe('for input field of type password using directive placeholder', function() {
		var pwd_field, pwd_clone, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			pwd_field = angular.element('<input type="password" name="userpwd" placeholder="Password" ng-model="form.passwd" value="" />');
			$compile(pwd_field)(scope);
			pwd_clone = angular.element(pwd_field[0].previousElementSibling);
		}));

		it('should hide the password input, add class "empty", and show a separate placeholder text input', function() {
			expect(pwd_field.val()).toBe('');
			expect(pwd_field.attr('type')).toBe('password');
			expect(pwd_field.hasClass('ng-hide')).toBe(true);
			expect(pwd_field.hasClass('empty')).toBe(true);
			expect(pwd_clone.val()).toBe('Password');
			expect(pwd_clone.attr('type')).toBe('text');
			expect(pwd_clone.hasClass('ng-hide')).toBe(false);
			expect(pwd_clone.hasClass('empty')).toBe(true);
			expect(scope.form.passwd).toBe('');
		});

		describe('when password placeholder gains focus', function() {
			beforeEach(function() {
				pwd_clone.triggerHandler('focus');
				pwd_field.triggerHandler('focus');
			});

			afterEach(function() {
				pwd_field.triggerHandler('blur');
			});

			it('should show the password input, remove class "empty", and hide the placeholder', function() {
				expect(pwd_field.val()).toBe('');
				expect(pwd_field.hasClass('ng-hide')).toBe(false);
				expect(pwd_field.hasClass('empty')).toBe(false);
				expect(pwd_clone.val()).toBe('Password');
				expect(pwd_clone.hasClass('ng-hide')).toBe(true);
				expect(pwd_clone.hasClass('empty')).toBe(true);
				expect(scope.form.passwd).toBe('');
			});
		});
	});

	describe('for textarea using directive placeholder', function() {
		var textarea, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			textarea = angular.element('<textarea name="userprofile" placeholder="Profile" ng-model="form.profile" />');
			$compile(textarea)(scope);
		}));

		it('should display the placeholder as input value and add class "empty",', function() {
			expect(textarea.val()).toBe('Profile');
			expect(textarea.hasClass('empty')).toBe(true);
			expect(scope.form.profile).toBe('');
		});

		describe('when textarea gains focus', function() {
			beforeEach(function() {
				textarea.triggerHandler('focus');
			});

			afterEach(function() {
				textarea.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(textarea.val()).toBe('');
				expect(textarea.hasClass('empty')).toBe(false);
				expect(scope.form.profile).toBe('');
			});
		});
	});

	describe('for html5 search input using directive placeholder', function() {
		var search, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			search = angular.element('<input type="search" name="query" placeholder="Search for terms..." ng-model="form.query" />');
			$compile(search)(scope);
		}));

		it('should display the placeholder as input value and add class "empty",', function() {
			expect(search.val()).toBe('Search for terms...');
			expect(search.hasClass('empty')).toBe(true);
			expect(scope.form.query).toBe('');
		});

		describe('when input gains focus', function() {
			beforeEach(function() {
				search.triggerHandler('focus');
			});

			afterEach(function() {
				search.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(search.val()).toBe('');
				expect(search.hasClass('empty')).toBe(false);
				expect(scope.form.query).toBe('');
			});
		});
	});

	describe('for an empty input without ngModel using directive placeholder', function() {
		var elem, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			elem = angular.element('<input type="text" name="query" placeholder="no model" />');
			$compile(elem)(scope);
		}));

		it('should display the placeholder as input value and add class "empty",', function() {
			expect(elem.val()).toBe('no model');
			expect(elem.hasClass('empty')).toBe(true);
		});

		describe('when input gains focus', function() {
			beforeEach(function() {
				elem.triggerHandler('focus');
			});

			afterEach(function() {
				elem.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(elem.val()).toBe('');
				expect(elem.hasClass('empty')).toBe(false);
			});
		});
	});

	describe('for a pre-filled input without ngModel using directive placeholder', function() {
		var elem, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			elem = angular.element('<input type="text" name="query" placeholder="no model" value="existing" />');
			$compile(elem)(scope);
		}));

		it('should display the placeholder as input value and not have class "empty",', function() {
			expect(elem.val()).toBe('existing');
			expect(elem.hasClass('empty')).toBe(false);
		});

		describe('when input gains focus', function() {
			beforeEach(function() {
				elem.triggerHandler('focus');
			});

			afterEach(function() {
				elem.triggerHandler('blur');
			});

			it('should keep its value and not add class "empty"', function() {
				expect(elem.val()).toBe('existing');
				expect(elem.hasClass('empty')).toBe(false);
			});
		});
	});
});
<commit_msg>Adjust tests to account for placeholder no longer setting the model<commit_after>'use strict';

describe('test module angular-placeholder', function() {
	beforeEach(function() {
		module('ng.shims.placeholder');
	});

	describe('for an empty input field of type text using directive placeholder', function() {
		var email_field, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			scope.form = {};
			email_field = angular.element('<input type="text" name="useremail" placeholder="E-Mail" ng-model="form.email" value="" />');
			$compile(email_field)(scope);
		}));

		it('should display the placeholder as input value', function() {
			expect(email_field.val()).toBe('E-Mail');
			expect(email_field.hasClass('empty')).toBe(true);
			expect(scope.form.email).toBeUndefined();
		});

		describe('when input field gains focus', function() {
			beforeEach(function() {
				email_field.triggerHandler('focus');
			});

			afterEach(function() {
				email_field.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(email_field.val()).toBe('');
				expect(email_field.hasClass('empty')).toBe(false);
				expect(scope.form.email).toBeUndefined();
			});

			it('should restore the placeholder and class "empty" when leaving field unchanged', function() {
				email_field.triggerHandler('blur');
				expect(email_field.val()).toBe('E-Mail');
				expect(email_field.hasClass('empty')).toBe(true);
				expect(scope.form.email).toBeUndefined();
			});

			describe('when text is entered into the input field', function() {
				beforeEach(function() {
					email_field.val('me@example.com');
					email_field.triggerHandler('change'); // trigger handler from input directive
					email_field.triggerHandler('blur');
				});

				it('should remember the entered text in scope.form and remove class "empty"', function() {
					expect(email_field.val()).toBe('me@example.com');
					expect(email_field.hasClass('empty')).toBe(false);
					expect(scope.form.email).toBe('me@example.com');
				});

				it('should reset the field as "empty"', function() {
					email_field.triggerHandler('focus');
					email_field.val('');
					email_field.triggerHandler('change'); // trigger handler from input directive
					email_field.triggerHandler('blur');
					expect(email_field.val()).toBe('E-Mail');
					expect(email_field.hasClass('empty')).toBe(true);
					expect(scope.form.email).toBe('');
				});
			});
		});

		describe('when the value is set through the model controller', function() {
			beforeEach(function() {
				expect(email_field.val()).toBe('E-Mail');
				scope.form.email = 'john@doe.com';
				scope.$digest();
			});

			it('should display the value in the input field', function() {
				expect(email_field.val()).toBe('john@doe.com');
				expect(email_field.hasClass('empty')).toBe(false);
			});

			it('should replace an empty value in the input field by placeholder', function() {
				scope.form.email = '';
				scope.$digest();
				expect(email_field.val()).toBe('E-Mail');
				expect(email_field.hasClass('empty')).toBe(true);
			});

		});

	});

	describe('for input field of type password using directive placeholder', function() {
		var pwd_field, pwd_clone, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			scope.form = {};
			pwd_field = angular.element('<input type="password" name="userpwd" placeholder="Password" ng-model="form.passwd" value="" />');
			$compile(pwd_field)(scope);
			pwd_clone = angular.element(pwd_field[0].previousElementSibling);
		}));

		it('should hide the password input, add class "empty", and show a separate placeholder text input', function() {
			expect(pwd_field.val()).toBe('');
			expect(pwd_field.attr('type')).toBe('password');
			expect(pwd_field.hasClass('ng-hide')).toBe(true);
			expect(pwd_field.hasClass('empty')).toBe(true);
			expect(pwd_clone.val()).toBe('Password');
			expect(pwd_clone.attr('type')).toBe('text');
			expect(pwd_clone.hasClass('ng-hide')).toBe(false);
			expect(pwd_clone.hasClass('empty')).toBe(true);
			expect(scope.form.passwd).toBeUndefined();
		});

		describe('when password placeholder gains focus', function() {
			beforeEach(function() {
				pwd_clone.triggerHandler('focus');
				pwd_field.triggerHandler('focus');
			});

			afterEach(function() {
				pwd_field.triggerHandler('blur');
			});

			it('should show the password input, remove class "empty", and hide the placeholder', function() {
				expect(pwd_field.val()).toBe('');
				expect(pwd_field.hasClass('ng-hide')).toBe(false);
				expect(pwd_field.hasClass('empty')).toBe(false);
				expect(pwd_clone.val()).toBe('Password');
				expect(pwd_clone.hasClass('ng-hide')).toBe(true);
				expect(pwd_clone.hasClass('empty')).toBe(true);
				expect(scope.form.passwd).toBeUndefined();
			});
		});
	});

	describe('for textarea using directive placeholder', function() {
		var textarea, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			scope.form = {};
			textarea = angular.element('<textarea name="userprofile" placeholder="Profile" ng-model="form.profile" />');
			$compile(textarea)(scope);
		}));

		it('should display the placeholder as input value and add class "empty",', function() {
			expect(textarea.val()).toBe('Profile');
			expect(textarea.hasClass('empty')).toBe(true);
			expect(scope.form.profile).toBeUndefined();
		});

		describe('when textarea gains focus', function() {
			beforeEach(function() {
				textarea.triggerHandler('focus');
			});

			afterEach(function() {
				textarea.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(textarea.val()).toBe('');
				expect(textarea.hasClass('empty')).toBe(false);
				expect(scope.form.profile).toBeUndefined();
			});
		});
	});

	describe('for html5 search input using directive placeholder', function() {
		var search, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			scope.form = {};
			search = angular.element('<input type="search" name="query" placeholder="Search for terms..." ng-model="form.query" />');
			$compile(search)(scope);
		}));

		it('should display the placeholder as input value and add class "empty",', function() {
			expect(search.val()).toBe('Search for terms...');
			expect(search.hasClass('empty')).toBe(true);
			expect(scope.form.query).toBeUndefined();
		});

		describe('when input gains focus', function() {
			beforeEach(function() {
				search.triggerHandler('focus');
			});

			afterEach(function() {
				search.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(search.val()).toBe('');
				expect(search.hasClass('empty')).toBe(false);
				expect(scope.form.query).toBeUndefined();
			});
		});
	});

	describe('for an empty input without ngModel using directive placeholder', function() {
		var elem, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			elem = angular.element('<input type="text" name="query" placeholder="no model" />');
			$compile(elem)(scope);
		}));

		it('should display the placeholder as input value and add class "empty",', function() {
			expect(elem.val()).toBe('no model');
			expect(elem.hasClass('empty')).toBe(true);
		});

		describe('when input gains focus', function() {
			beforeEach(function() {
				elem.triggerHandler('focus');
			});

			afterEach(function() {
				elem.triggerHandler('blur');
			});

			it('should hide the placeholder and remove class "empty"', function() {
				expect(elem.val()).toBe('');
				expect(elem.hasClass('empty')).toBe(false);
			});
		});
	});

	describe('for a pre-filled input without ngModel using directive placeholder', function() {
		var elem, scope;

		beforeEach(inject(function($rootScope, $compile) {
			scope = $rootScope.$new();
			elem = angular.element('<input type="text" name="query" placeholder="no model" value="existing" />');
			$compile(elem)(scope);
		}));

		it('should display the placeholder as input value and not have class "empty",', function() {
			expect(elem.val()).toBe('existing');
			expect(elem.hasClass('empty')).toBe(false);
		});

		describe('when input gains focus', function() {
			beforeEach(function() {
				elem.triggerHandler('focus');
			});

			afterEach(function() {
				elem.triggerHandler('blur');
			});

			it('should keep its value and not add class "empty"', function() {
				expect(elem.val()).toBe('existing');
				expect(elem.hasClass('empty')).toBe(false);
			});
		});
	});
});
<|endoftext|>