<commit_before>{
    "genres": [

               {
               "url": "https://image.tmdb.org/t/p/w500/br4TdosVhbpFKEJrZ84OYI42JkN.jpg",
               "title":"Summer Time Is Here",
               "id":"57496ed092514134780015d4"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/ld8CzJneOCVSCq4dm6zRmQzlIZl.jpg",
               "title":"Just Survival",
               "id":"56f99a869251412fdd006c0a"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/g7y79gXw88PRl5MXD9BiJaWPA9Z.jpg",
               "title":"For A Romantic Night",
               "id":"56aa016ac3a36872e90053c7"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/9pdIEOHiAcOAHsVW0Ia7v4tOrot.jpg",
               "title":"Good Old Westerns",
               "id":"56aa0180c3a36872d800567c"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/ohKncfyZi0NLR1oyyz7ETRnxxWd.jpg",
               "title":"The James Bond - Movie Collection",
               "id":"5308b87fc3a36842010027be"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/xDEOxA01480uLTWuvQCw61VmDBt.jpg",
               "title":"The Gangster Classics",
               "id":"56d0bf859251415ad90004bc"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/to4AKd4SOyXE1YR8QZ34xSTCtjO.jpg",
               "title":"The Entire Star Wars Collection",
               "id":"56c09c7b925141398a003932"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/iqE52K9m00rq3wutzfvTcUlstaL.jpg",
               "title":"End Of The World Films",
               "id":"56f9aa5e9251414de600016e"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/ymzaJLm2EIYbG9n7snVfCnHAPQk.jpg",
               "title":"Saddest Films Of All Time",
               "id":"56f9a5dc9251414deb0000fa"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/1LrtAhWPSEetJLjblXvnaYtl7eA.jpg",
               "title":"Experience The Truth Of World War II ",
               "id":"56d0b844925141799e0040c3"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/mZcqznpPHNPHONEbiT6IGH6j4d.jpg",
               "title":"Great Movies Instructed By Steven Spielberg",
               "id":"56d5f8e592514112cd000543"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/AoYGqtWxcNmQjQIpRCMtzpFfL1T.jpg",
               "title":"The 10 Funniest Movies Of 2015",
               "id":"56d05cf39251413e5f005ce2"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/cDctk61tUeQz4LX7tTFPknI28ea.jpg",
               "title":"15 Movies Your Have To See",
               "id":"56d0bafd9251413e59006b20"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/lXOqBOcx1t5A3YhJEIfJZOkigwH.jpg",
               "title":"The 10 Most Anticipated Titles Of This Year",
               "id":"56d047339251413e6a005fed"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/dYtAyg4vD88hIfrR1VKDnVGhnE6.jpg",
               "title":"The Very Best Of Leonardo DiCaprio",
               "id":"56d05e3e9251416e3a003383"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/50xTVRANi9p423luloU4SA6QgbM.jpg",
               "title":"The Most Anticipated Movies Of 2017",
               "id":"56d0942b9251413e680069fe"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/jt2Y00h7cOWVAZLCGR444D1B6QV.jpg",
               "title":"The 88th Academy Awards (Oscars 2016)",
               "id":"569bc01dc3a36858c6000030"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/sSvgNBeBNzAuKl8U8sP50ETJPgx.jpg",
               "title":"The Top 25 Movies Of 2015",
               "id":"56d091769251413e6d0069d4"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/aY0kmLSNKFbHZyvmHqiuegVlDFW.jpg",
               "title":"The Entire DreamWorks Animation Collection",
               "id":"56d5fcf092514139320041ea"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/vXIrvKadue7GdySiVh3huoQZiMi.jpg",
               "title":"The Marvel Universe Collection",
               "id":"50941077760ee35e1500000c"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/OS88xaFcO1FwyMStmM1nFKbT7C.jpg",
               "title":"The DC Universe Collection",
               "id":"5094147819c2955e4c00006a"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/f2WtyrZeupq7hQ4SX0SXuMUbjOa.jpg",
               "title":"Movies Starring Amanda Seyfried",
               "id":"56d314eac3a3681e3c010f42"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/hQIPa1oKM6fSzyp1UBxBfVpSCj2.jpg",
               "title":"Late Valentine With Your Only One",
               "id":"56d2235e9251413e5f00afa1"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/s0ICtHdrTWYaBRJSbOgKEYrm3F4.jpg",
               "title":"For A Quiet Family Night",
               "id":"56deec15c3a36803bf002fd0"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/kFslzsvxOQgjbuDfta3kzbOWQY5.jpg",
               "title":"The Alien Story",
               "id":"56dee364c3a36803ce0031c9"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/oH39T1bwjztw6qh89pvVAJBsUUq.jpg",
               "title":"The Disney Classics",
               "id":"51224e42760ee3297424a1e0"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/lAdRfK0Clun517bq5V0meoIx7SG.jpg",
               "title":"Horror For A Spooky Night",
               "id":"54e4781b925141195300adba"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/sEgULSEnywgdSesVHFHpPAbOijl.jpg",
               "title":"The Finest Work Of Matt Damon",
               "id":"56d05f33c3a3681e3e006ae8"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/l7zANdjgTvYqwZUx76Vk0EKpCH5.jpg",
               "title":"The Pirates Of The Caribbean Collection",
               "id":"56d03aac9251416e3a002e5a"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/xu9zaAevzQ5nnrsXN6JcahLnG4i.jpg",
               "title":"The Best Of Matthew McConaughey",
               "id":"56d0614a9251413e6a006438"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/6kVVfNT0auG6fU5SFQ1zbayNWUC.jpg",
               "title":"The Greatest From Paramount Pictures",
               "id":"56def1d8925141579d001f89"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/cHy7nSitAVgvZ7qfCK4JO47t3oZ.jpg",
               "title":"The Entire Transformer Collection",
               "id":"56def7349251412eee0000ca"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/kUYha9j3oFgRdSQlROfj61ISjeO.jpg",
               "title":"Good Science Fiction Flicks",
               "id":"54408e79929fb858d1000052"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/7MGIEdu0Mokqt8i7snflYRLbooI.jpg",
               "title":"Best Picture Winners - The Academy Awards",
               "id":"509ec17b19c2950a0600050d"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/iNGNoZbDKzawUulvL6x0drHOZNI.jpg",
               "title":"The Entire Lord Of The Rings Collection",
               "id":"56d046029251416e3a002fc8"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/bIlYH4l2AyYvEysmS2AOfjO7Dn8.jpg",
               "title":"The Terminator Collection",
               "id":"54906e07c3a3686d6e002470"
               }

               ]

}<commit_msg>updated lists<commit_after>{
    "genres": [

               {
               "url": "https://image.tmdb.org/t/p/w500/atlgUPxj5PLdEUwtSm9O0Hd2Scr.jpg",
               "title":"The Most Anticipated Movies Of 2018",
               "id":"14762"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/50xTVRANi9p423luloU4SA6QgbM.jpg",
               "title":"The Best Of 2017",
               "id":"56d0942b9251413e680069fe"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/rqAHkvXldb9tHlnbQDwOzRi0yVD.jpg",
               "title":"The Marvel Universe Collection",
               "id":"50941077760ee35e1500000c"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/uyzUPJ2krcOOZERfV391lmtVQsu.jpg",
               "title":"The DC Universe Collection",
               "id":"5094147819c2955e4c00006a"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/tZjVVIYXACV4IIIhXeIM59ytqwS.jpg",
               "title":"The Entire Star Wars Collection",
               "id":"56c09c7b925141398a003932"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/br4TdosVhbpFKEJrZ84OYI42JkN.jpg",
               "title":"Summer Time Is Here",
               "id":"57496ed092514134780015d4"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/ld8CzJneOCVSCq4dm6zRmQzlIZl.jpg",
               "title":"Just Survival",
               "id":"56f99a869251412fdd006c0a"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/g7y79gXw88PRl5MXD9BiJaWPA9Z.jpg",
               "title":"For A Romantic Night",
               "id":"56aa016ac3a36872e90053c7"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/9pdIEOHiAcOAHsVW0Ia7v4tOrot.jpg",
               "title":"Good Old Westerns",
               "id":"56aa0180c3a36872d800567c"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/ohKncfyZi0NLR1oyyz7ETRnxxWd.jpg",
               "title":"The James Bond - Movie Collection",
               "id":"5308b87fc3a36842010027be"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/xDEOxA01480uLTWuvQCw61VmDBt.jpg",
               "title":"The Gangster Classics",
               "id":"56d0bf859251415ad90004bc"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/iqE52K9m00rq3wutzfvTcUlstaL.jpg",
               "title":"End Of The World Films",
               "id":"56f9aa5e9251414de600016e"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/ymzaJLm2EIYbG9n7snVfCnHAPQk.jpg",
               "title":"Saddest Films Of All Time",
               "id":"56f9a5dc9251414deb0000fa"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/1LrtAhWPSEetJLjblXvnaYtl7eA.jpg",
               "title":"Experience The Truth Of World War II ",
               "id":"56d0b844925141799e0040c3"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/mZcqznpPHNPHONEbiT6IGH6j4d.jpg",
               "title":"Great Movies Instructed By Steven Spielberg",
               "id":"56d5f8e592514112cd000543"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/AoYGqtWxcNmQjQIpRCMtzpFfL1T.jpg",
               "title":"The 10 Funniest Movies Of 2015",
               "id":"56d05cf39251413e5f005ce2"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/cDctk61tUeQz4LX7tTFPknI28ea.jpg",
               "title":"15 Movies Your Have To See",
               "id":"56d0bafd9251413e59006b20"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/lXOqBOcx1t5A3YhJEIfJZOkigwH.jpg",
               "title":"The 10 Most Anticipated Titles Of 2016",
               "id":"56d047339251413e6a005fed"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/dYtAyg4vD88hIfrR1VKDnVGhnE6.jpg",
               "title":"The Very Best Of Leonardo DiCaprio",
               "id":"56d05e3e9251416e3a003383"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/jt2Y00h7cOWVAZLCGR444D1B6QV.jpg",
               "title":"The 88th Academy Awards (Oscars 2016)",
               "id":"569bc01dc3a36858c6000030"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/sSvgNBeBNzAuKl8U8sP50ETJPgx.jpg",
               "title":"The Top 25 Movies Of 2015",
               "id":"56d091769251413e6d0069d4"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/aY0kmLSNKFbHZyvmHqiuegVlDFW.jpg",
               "title":"The Entire DreamWorks Animation Collection",
               "id":"56d5fcf092514139320041ea"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/f2WtyrZeupq7hQ4SX0SXuMUbjOa.jpg",
               "title":"Movies Starring Amanda Seyfried",
               "id":"56d314eac3a3681e3c010f42"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/hQIPa1oKM6fSzyp1UBxBfVpSCj2.jpg",
               "title":"Late Valentine With Your Only One",
               "id":"56d2235e9251413e5f00afa1"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/s0ICtHdrTWYaBRJSbOgKEYrm3F4.jpg",
               "title":"For A Quiet Family Night",
               "id":"56deec15c3a36803bf002fd0"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/kFslzsvxOQgjbuDfta3kzbOWQY5.jpg",
               "title":"The Alien Story",
               "id":"56dee364c3a36803ce0031c9"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/oH39T1bwjztw6qh89pvVAJBsUUq.jpg",
               "title":"The Disney Classics",
               "id":"51224e42760ee3297424a1e0"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/lAdRfK0Clun517bq5V0meoIx7SG.jpg",
               "title":"Horror For A Spooky Night",
               "id":"54e4781b925141195300adba"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/sEgULSEnywgdSesVHFHpPAbOijl.jpg",
               "title":"The Finest Work Of Matt Damon",
               "id":"56d05f33c3a3681e3e006ae8"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/l7zANdjgTvYqwZUx76Vk0EKpCH5.jpg",
               "title":"The Pirates Of The Caribbean Collection",
               "id":"56d03aac9251416e3a002e5a"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/xu9zaAevzQ5nnrsXN6JcahLnG4i.jpg",
               "title":"The Best Of Matthew McConaughey",
               "id":"56d0614a9251413e6a006438"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/6kVVfNT0auG6fU5SFQ1zbayNWUC.jpg",
               "title":"The Greatest From Paramount Pictures",
               "id":"56def1d8925141579d001f89"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/cHy7nSitAVgvZ7qfCK4JO47t3oZ.jpg",
               "title":"The Entire Transformer Collection",
               "id":"56def7349251412eee0000ca"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/kUYha9j3oFgRdSQlROfj61ISjeO.jpg",
               "title":"Good Science Fiction Flicks",
               "id":"54408e79929fb858d1000052"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/7MGIEdu0Mokqt8i7snflYRLbooI.jpg",
               "title":"Best Picture Winners - The Academy Awards",
               "id":"509ec17b19c2950a0600050d"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/iNGNoZbDKzawUulvL6x0drHOZNI.jpg",
               "title":"The Entire Lord Of The Rings Collection",
               "id":"56d046029251416e3a002fc8"
               },

               {
               "url": "https://image.tmdb.org/t/p/w500/bIlYH4l2AyYvEysmS2AOfjO7Dn8.jpg",
               "title":"The Terminator Collection",
               "id":"54906e07c3a3686d6e002470"
               }

               ]

}<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
  res.render('index');
});

router.get('/examples/template-data', function (req, res) {
  res.render('examples/template-data', { 'name' : 'Foo' });
});

// routes for producers/de
router.post('/producers/delete/delete-confirmation', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes');
  } else {
    res.redirect('/producers/delete/index');
  }
});

router.post('/producers/delete/delete-confirmation-single', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-single');
  }
  else {
    res.redirect('/producers/delete/index-single');
  }
});

router.post('/producers/delete/delete-confirmation-2', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-2');
  } else {
    res.redirect('/producers/delete/index-2');
  }
});

router.post('/producers/delete/delete-confirmation-3', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-3');
  } else {
    res.redirect('/producers/delete/index-3');
  }
});

router.post('/producers/delete/delete-confirmation-4', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-4');
  } else {
    res.redirect('/producers/delete/index-4');
  }
});

router.post('/producers/delete/delete-confirmation-5', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-5');
  } else {
    res.redirect('/producers/delete/index-5');
  }
});

router.post('/producers/delete/delete-confirmation-6', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-6');
  } else {
    res.redirect('/producers/delete/index-6');
  }
});

router.post('/schemes/datareturnmenu', function (req,res) {
  if (req.body['radio-inline-group']==="View data returns"){
    res.redirect('/schemes/viewreturns');
  } else {
    res.redirect('/schemes/datareturnmenu');
  }
});

router.post('/schemes/index-2', function (req,res) {
  if (req.body['radio-inline-group']==="Manage EEE/WEEE data returns"){
    res.redirect('/schemes/datareturnmenu');

  }

  else {
    res.redirect('/schemes/index-2');
  }
});

router.post('/producers/eee-data/index', function (req,res) {
  if (req.body['radio-inline-group']==="View producer information"){
    res.redirect('/producers/eee-data/find');
  } else {
    res.redirect('/producers/eee-data/index');
  }
});

/* Notice address journey */

router.post('/register/main-contact-address', function (req,res) {
    res.redirect('/register/phone-email');

});

router.post('/register/address-lookup', function (req,res) {
    res.redirect('/register/address-lookup-2');

});

router.post('/register/address-lookup-2', function (req,res) {
    res.redirect('/register/phone-email');

});

router.post('/register/phone-email', function (req,res) {
    res.redirect('/register/registered-office-check');

});

router.post('/notice-address/reg-company', function (req,res) {
    res.redirect('/notice-address/main-contact');

});

router.post('/notice-address/main-contact', function (req,res) {
    res.redirect('/notice-address/main-contact-address');

});

router.post('/notice-address/main-contact-address', function (req,res) {
    res.redirect('/notice-address/reg-office-same');

});

router.post('/notice-address/reg-office-details', function (req,res) {
    res.redirect('/notice-address/notice-address-same');

});

router.post('/notice-address/notice-address-details', function (req,res) {
    res.redirect('/notice-address/summary');

});

router.post('/notice-address/business-trading-name', function (req,res) {
    res.redirect('/notice-address/main-contact-partnership');

});

router.post('/notice-address/main-contact-partnership', function (req,res) {
    res.redirect('/notice-address/main-contact-address-partnership');

});
router.post('/notice-address/main-contact-address-partnership', function (req,res) {
    res.redirect('/notice-address/principal-place-same');

});

router.post('/notice-address/notice-address-details-principal', function (req,res) {
    res.redirect('/notice-address/summary-principal');

});

router.post('/notice-address/principal-place-details', function (req,res) {
    res.redirect('/notice-address/notice-address-same-principal');

});

router.post('/notice-address/reg-office-same', function (req,res) {
  if (req.body['SelectedValue']==="Yes"){
    res.redirect('/notice-address/notice-address-same');

  }

  else {
    res.redirect('/notice-address/reg-office-details');
  }
});

router.post('/notice-address/principal-place-same', function (req,res) {
  if (req.body['SelectedValue']==="Yes"){
    res.redirect('/notice-address/notice-address-same-principal');

  }

  else {
    res.redirect('/notice-address/principal-place-details');
  }
});

router.post('/notice-address/notice-address-same-principal', function (req,res) {
  if (req.body['SelectedValue']==="A new address"){
    res.redirect('/notice-address/notice-address-details-principal');

  }

  else {
    res.redirect('/notice-address/summary-principal');
  }
});

router.post('/notice-address/notice-address-same', function (req,res) {
  if (req.body['SelectedValue']==="A new address"){
    res.redirect('/notice-address/notice-address-details');

  }

  else {
    res.redirect('/notice-address/summary');
  }
});

module.exports = router;
<commit_msg>commit<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function (req, res) {
  res.render('index');
});

router.get('/examples/template-data', function (req, res) {
  res.render('examples/template-data', { 'name' : 'Foo' });
});

// routes for producers/de
router.post('/producers/delete/delete-confirmation', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes');
  } else {
    res.redirect('/producers/delete/index');
  }
});

router.post('/producers/delete/delete-confirmation-single', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-single');
  }
  else {
    res.redirect('/producers/delete/index-single');
  }
});

router.post('/producers/delete/delete-confirmation-2', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-2');
  } else {
    res.redirect('/producers/delete/index-2');
  }
});

router.post('/producers/delete/delete-confirmation-3', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-3');
  } else {
    res.redirect('/producers/delete/index-3');
  }
});

router.post('/producers/delete/delete-confirmation-4', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-4');
  } else {
    res.redirect('/producers/delete/index-4');
  }
});

router.post('/producers/delete/delete-confirmation-5', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-5');
  } else {
    res.redirect('/producers/delete/index-5');
  }
});

router.post('/producers/delete/delete-confirmation-6', function (req,res) {
  if (req.body['radio-inline-group']==="Yes"){
    res.redirect('/producers/delete/delete-confirmation-yes-6');
  } else {
    res.redirect('/producers/delete/index-6');
  }
});

router.post('/schemes/datareturnmenu', function (req,res) {
  if (req.body['radio-inline-group']==="View data returns"){
    res.redirect('/schemes/viewreturns');
  } else {
    res.redirect('/schemes/datareturnmenu');
  }
});

router.post('/schemes/index-2', function (req,res) {
  if (req.body['radio-inline-group']==="Manage EEE/WEEE data returns"){
    res.redirect('/schemes/datareturnmenu');

  }

  else {
    res.redirect('/schemes/index-2');
  }
});

router.post('/producers/eee-data/index', function (req,res) {
  if (req.body['radio-inline-group']==="View producer information"){
    res.redirect('/producers/eee-data/find');
  } else {
    res.redirect('/producers/eee-data/index');
  }
});

/*Address lookup feature */

router.post('/register/main-contact-address', function (req,res) {
    res.redirect('/register/phone-email');

});

router.post('/register/address-lookup', function (req,res) {
    res.redirect('/register/address-lookup-2');

});

router.post('/register/address-lookup-2', function (req,res) {
    res.redirect('/register/phone-email');

});

router.post('/register/phone-email', function (req,res) {
    res.redirect('/register/registered-office-check');

});

/* Notice address journey */

router.post('/notice-address/reg-company', function (req,res) {
    res.redirect('/notice-address/main-contact');

});

router.post('/notice-address/main-contact', function (req,res) {
    res.redirect('/notice-address/main-contact-address');

});

router.post('/notice-address/main-contact-address', function (req,res) {
    res.redirect('/notice-address/reg-office-same');

});

router.post('/notice-address/reg-office-details', function (req,res) {
    res.redirect('/notice-address/notice-address-same');

});

router.post('/notice-address/notice-address-details', function (req,res) {
    res.redirect('/notice-address/summary');

});

router.post('/notice-address/business-trading-name', function (req,res) {
    res.redirect('/notice-address/main-contact-partnership');

});

router.post('/notice-address/main-contact-partnership', function (req,res) {
    res.redirect('/notice-address/main-contact-address-partnership');

});
router.post('/notice-address/main-contact-address-partnership', function (req,res) {
    res.redirect('/notice-address/principal-place-same');

});

router.post('/notice-address/notice-address-details-principal', function (req,res) {
    res.redirect('/notice-address/summary-principal');

});

router.post('/notice-address/principal-place-details', function (req,res) {
    res.redirect('/notice-address/notice-address-same-principal');

});

router.post('/notice-address/reg-office-same', function (req,res) {
  if (req.body['SelectedValue']==="Yes"){
    res.redirect('/notice-address/notice-address-same');

  }

  else {
    res.redirect('/notice-address/reg-office-details');
  }
});

router.post('/notice-address/principal-place-same', function (req,res) {
  if (req.body['SelectedValue']==="Yes"){
    res.redirect('/notice-address/notice-address-same-principal');

  }

  else {
    res.redirect('/notice-address/principal-place-details');
  }
});

router.post('/notice-address/notice-address-same-principal', function (req,res) {
  if (req.body['SelectedValue']==="A new address"){
    res.redirect('/notice-address/notice-address-details-principal');

  }

  else {
    res.redirect('/notice-address/summary-principal');
  }
});

router.post('/notice-address/notice-address-same', function (req,res) {
  if (req.body['SelectedValue']==="A new address"){
    res.redirect('/notice-address/notice-address-details');

  }

  else {
    res.redirect('/notice-address/summary');
  }
});

module.exports = router;
<|endoftext|>


<commit_before>var https = require('https');
var url = require('url');

var server = https.createServer(function(){});

server.on('request', function(req, res) {
    res.setHeader("Access-Control-Allow-Origin", "https://semmle.com"); // OK, fixed origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', function(req, res) {
    let origin = url.parse(req.url, true).query.origin;
    res.setHeader("Access-Control-Allow-Origin", origin); // NOT OK, tainted origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // NOT OK, null origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "null"); // NOT OK, null origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', function(req, res) {
    let origin = url.parse(req.url, true).query.origin;
    res.setHeader("Access-Control-Allow-Origin", origin);  // OK, credentials are not transferred
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // OK, credentials are not transferred
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // OK, credentials are not transferred
    res.setHeader("Access-Control-Allow-Credentials", false);
});

server.on('request', (req, res) => {
    let origin = url.parse(req.url, true).query.origin;
    if (origin in o) {
        res.setHeader("Access-Control-Allow-Origin", origin); // OK, sanitized origin
        res.setHeader("Access-Control-Allow-Credentials", true);
    }
});

// syntactic header defintion
probalyAServer.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // NOT OK (but not detected)
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', (req, res) => {
    let origin = url.parse(req.url, true).query.origin;
    if (ALLOWED_ORIGINS.indexOf(origin) !== -1) {
        res.setHeader("Access-Control-Allow-Origin", origin); // OK, sanitized origin
        res.setHeader("Access-Control-Allow-Credentials", true);
    }
});

server.on('request', (req, res) => {
    let origin = url.parse(req.url, true).query.origin;
    if (ALLOWED_ORIGINS.indexOf(origin) >= 0) {
        res.setHeader("Access-Control-Allow-Origin", origin); // OK, sanitized origin
        res.setHeader("Access-Control-Allow-Credentials", true);
    }
});
<commit_msg>update inconsistency comment for CWE-346<commit_after>var https = require('https');
var url = require('url');

var server = https.createServer(function(){});

server.on('request', function(req, res) {
    res.setHeader("Access-Control-Allow-Origin", "https://semmle.com"); // OK, fixed origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', function(req, res) {
    let origin = url.parse(req.url, true).query.origin;
    res.setHeader("Access-Control-Allow-Origin", origin); // NOT OK, tainted origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // NOT OK, null origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "null"); // NOT OK, null origin
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', function(req, res) {
    let origin = url.parse(req.url, true).query.origin;
    res.setHeader("Access-Control-Allow-Origin", origin);  // OK, credentials are not transferred
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // OK, credentials are not transferred
});

server.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // OK, credentials are not transferred
    res.setHeader("Access-Control-Allow-Credentials", false);
});

server.on('request', (req, res) => {
    let origin = url.parse(req.url, true).query.origin;
    if (origin in o) {
        res.setHeader("Access-Control-Allow-Origin", origin); // OK, sanitized origin
        res.setHeader("Access-Control-Allow-Credentials", true);
    }
});

// syntactic header defintion
probalyAServer.on('request', (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", null); // NOT OK (but not detected) [INCONSISTENCY]
    res.setHeader("Access-Control-Allow-Credentials", true);
});

server.on('request', (req, res) => {
    let origin = url.parse(req.url, true).query.origin;
    if (ALLOWED_ORIGINS.indexOf(origin) !== -1) {
        res.setHeader("Access-Control-Allow-Origin", origin); // OK, sanitized origin
        res.setHeader("Access-Control-Allow-Credentials", true);
    }
});

server.on('request', (req, res) => {
    let origin = url.parse(req.url, true).query.origin;
    if (ALLOWED_ORIGINS.indexOf(origin) >= 0) {
        res.setHeader("Access-Control-Allow-Origin", origin); // OK, sanitized origin
        res.setHeader("Access-Control-Allow-Credentials", true);
    }
});
<|endoftext|>


<commit_before>app
  .controller('juxtaCtrl', function($scope, authFactory, apiFactory, firebaseFactory, $location, $routeParams, players) {
    console.log('juxtaCtrl firing')

  // ______ set variables ______
    $scope.playerList = players  // full list of nfl players
    $scope.nameX = $routeParams.paramX // player x name
    $scope.nameY = $routeParams.paramY // player y name
    $scope.week = $routeParams.week
    // $scope.uid = firebase.auth().currentUser.uid

  // _____ radar/bar chart labels _____
    $scope.barLabels = ["Projected Season Pts", "Actual Season Pts", "Projected Weekly Pts", "Actual Weekly Pts"]
    $scope.radarLabels = ["Projected Season Pts", "Actual Season Pts", "Projected Weekly Pts", "Actual Weekly Pts"]
    $scope.series = [$routeParams.paramX, $routeParams.paramY]  // setting series names for bar chart

  // _______ define functions ______
    $scope.setPlayers = function (input, output) { // find input player in playerList, set player object to output
      for (let i = 0; i < $scope.playerList.length; i++) {
        if ($scope[input] === ($scope.playerList[i].player.FirstName + " " + $scope.playerList[i].player.LastName)) {
          $scope[output] = $scope.playerList[i]
        }
      }
    }

    $scope.showProjections = function (guy, letter) {
      apiFactory.getNerdProjections()  // (week, pos)
        .then((projections) => {
          // console.log(projections)
          for (i = 0; i < projections.length; i++) {
            if (projections[i].displayName === guy) {   // find matching player
              $scope[letter] = projections[i]
              // console.log($scope[letter])

              $scope.getOpponents(projections[i].team, $scope.week)
            }
          }
        })
    }

    $scope.showRankings = function (dude, letter, pos) {
      apiFactory.getNerdRankings() // (dude, [week#])
        .then((rankings) => {
          for (j = 0; j < rankings.length; j++) {
            if (rankings[j].name === dude) {   // find matching player
              $scope[letter] = rankings[j]
              $scope[pos] = j + 1
              // console.log('position rank:', $scope[pos], 'rankings: ', $scope[letter])
            }
          }
        })
    }

    $scope.showStats = function (guy, seasonProj, season, weekProj, week) {
      apiFactory.getNflStats()
        .then((stats) => {
          for (k = 0; k < stats.length; k++) {
            if (stats[k].name === guy) {  // find matching player
              $scope[seasonProj] = stats[k].seasonProjectedPts  // assign stats to variables
              $scope[season] = stats[k].seasonPts
              $scope[weekProj] = stats[k].weekProjectedPts
              $scope[week] = stats[k].weekPts

              $scope.data = [  // inject stat variables into graph
                [$scope.seasonProjectedX, $scope.seasonPtsX, $scope.weekProjectedX, $scope.weekPtsX],
                [$scope.seasonProjectedY, $scope.seasonPtsY, $scope.weekProjectedY, $scope.weekPtsY]
              ]
            }
          }
        })
    }

    $scope.getOpponents = function (team, week) {
      apiFactory.getSchedule()
      .then(() => console.log(team, week))
    }

    $scope.postComparison = function (pick) {  // post to firebase
      var $toastContent = $('Juxtaposition saved to your profile.');  // toast
      Materialize.toast($toastContent, 4500, 'rounded');
      firebaseFactory.postComp($routeParams.paramX, $routeParams.paramY, $routeParams.week, pick, $scope.uid)
        .then(() => $location.path('/'))
    }

  // ______ run functions _______
    $scope.setPlayers('nameX', 'playerX') // define object $scope.playerX
    $scope.setPlayers('nameY', 'playerY') // define object $scope.playerY

    $scope.showProjections($routeParams.paramX, 'projectionsX');  // find playerX projections, set obj to var
    $scope.showProjections($routeParams.paramY, 'projectionsY');  // find playerY projections, set obj to var

    $scope.showRankings($routeParams.paramX, 'rankingsX', 'positionXrank')
    $scope.showRankings($routeParams.paramY, 'rankingsY', 'positionYrank')

    $scope.showStats($routeParams.paramX, 'seasonProjectedX', 'seasonPtsX', 'weekProjectedX', 'weekPtsX')
    $scope.showStats($routeParams.paramY, 'seasonProjectedY', 'seasonPtsY', 'weekProjectedY', 'weekPtsY')

  // _____ materialize stuff _____
    $('.carousel.carousel-slider').carousel({fullWidth: true});

  })
<commit_msg>setting opponent and team logo<commit_after>app
  .controller('juxtaCtrl', function($scope, authFactory, apiFactory, firebaseFactory, $location, $routeParams, players) {
    console.log('juxtaCtrl firing')

  // ______ set variables ______
    $scope.playerList = players  // full list of nfl players
    $scope.nameX = $routeParams.paramX // player x name
    $scope.nameY = $routeParams.paramY // player y name
    $scope.week = $routeParams.week
    // $scope.uid = firebase.auth().currentUser.uid

  // _____ radar/bar chart labels _____
    $scope.barLabels = ["Projected Season Pts", "Actual Season Pts", "Projected Weekly Pts", "Actual Weekly Pts"]
    $scope.radarLabels = ["Projected Season Pts", "Actual Season Pts", "Projected Weekly Pts", "Actual Weekly Pts"]
    $scope.series = [$routeParams.paramX, $routeParams.paramY]  // setting series names for bar chart

  // _______ define functions ______
    $scope.setPlayers = function (input, output) { // find input player in playerList, set player object to output
      for (let i = 0; i < $scope.playerList.length; i++) {
        if ($scope[input] === ($scope.playerList[i].player.FirstName + " " + $scope.playerList[i].player.LastName)) {
          $scope[output] = $scope.playerList[i]
        }
      }
    }

    $scope.showProjections = function (guy, letter) {
      apiFactory.getNerdProjections()  // (week, pos)
        .then((projections) => {
          // console.log(projections)
          for (i = 0; i < projections.length; i++) {
            if (projections[i].displayName === guy) {   // find matching player
              $scope[letter] = projections[i]
              // console.log($scope[letter])

              $scope.getOpponents(projections[i].team, $scope.week)
            }
          }
        })
    }

    $scope.showRankings = function (dude, letter, pos) {
      apiFactory.getNerdRankings() // (dude, [week#])
        .then((rankings) => {
          for (j = 0; j < rankings.length; j++) {
            if (rankings[j].name === dude) {   // find matching player
              $scope[letter] = rankings[j]
              $scope[pos] = j + 1
              // console.log('position rank:', $scope[pos], 'rankings: ', $scope[letter])
            }
          }
        })
    }

    $scope.showStats = function (guy, seasonProj, season, weekProj, week) {
      apiFactory.getNflStats()
        .then((stats) => {
          for (k = 0; k < stats.length; k++) {
            if (stats[k].name === guy) {  // find matching player
              $scope[seasonProj] = stats[k].seasonProjectedPts  // assign stats to variables
              $scope[season] = stats[k].seasonPts
              $scope[weekProj] = stats[k].weekProjectedPts
              $scope[week] = stats[k].weekPts

              $scope.data = [  // inject stat variables into graph
                [$scope.seasonProjectedX, $scope.seasonPtsX, $scope.weekProjectedX, $scope.weekPtsX],
                [$scope.seasonProjectedY, $scope.seasonPtsY, $scope.weekProjectedY, $scope.weekPtsY]
              ]
            }
          }
        })
    }

    $scope.getOpponents = function (team, opp) {
      apiFactory.getSchedule()
      .then((schedule) =>  {
        for (i = 0; i < schedule.length; i++) {
          if ((schedule[i].gameWeek === $scope.week) && (schedule[i].homeTeam === team)) {
            $scope[opp] = schedule[i].awayTeam  // if home team
          } else
          if ((schedule[i].gameWeek === $scope.week) && (schedule[i].awayTeam === team)) {
            $scope[opp] = schedule[i].homeTeam  // if away team
          }
        }
      })
    }

    $scope.postComparison = function (pick) {  // post to firebase
      var $toastContent = $('Juxtaposition saved to your profile.');  // toast
      Materialize.toast($toastContent, 4500, 'rounded');
      firebaseFactory.postComp($routeParams.paramX, $routeParams.paramY, $routeParams.week, pick, $scope.uid)
        .then(() => $location.path('/'))
    }

  // ______ run functions _______
    $scope.setPlayers('nameX', 'playerX') // define object $scope.playerX
    $scope.setPlayers('nameY', 'playerY') // define object $scope.playerY

    $scope.showProjections($routeParams.paramX, 'projectionsX');  // find playerX projections, set obj to var
    $scope.showProjections($routeParams.paramY, 'projectionsY');  // find playerY projections, set obj to var

    $scope.showRankings($routeParams.paramX, 'rankingsX', 'positionXrank')
    $scope.showRankings($routeParams.paramY, 'rankingsY', 'positionYrank')

    $scope.showStats($routeParams.paramX, 'seasonProjectedX', 'seasonPtsX', 'weekProjectedX', 'weekPtsX')
    $scope.showStats($routeParams.paramY, 'seasonProjectedY', 'seasonPtsY', 'weekProjectedY', 'weekPtsY')

    $scope.getOpponents($scope.playerX.team.Abbreviation, 'opponentX')  // set opponent to $scope.opponentX
    $scope.getOpponents($scope.playerY.team.Abbreviation, 'opponentY')  // set opponent to $scope.opponentY

  // _____ materialize stuff _____
    $('.carousel.carousel-slider').carousel({fullWidth: true});

  })
<|endoftext|>


<commit_before>import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';

import Module from 'Parser/Core/Module';

const debug = false;

class InnerHallation extends Module {
  manaGained = 0;

  // timestamp for power infusion if its talented & casted (to exclude mana saved):
  lastPowerInfusionCastStartTimestamp = null;

  on_initialized() {
    const selectedCombatant = this.owner.modules.combatants.selected;
    this.active = selectedCombatant.hasShoulder(ITEMS.INNER_HALLATION.id);
  }

  on_byPlayer_cast(event) {
    if (this.owner.modules.combatants.selected.hasTalent(SPELLS.POWER_INFUSION_TALENT.id) && event.ability.guid === SPELLS.POWER_INFUSION_TALENT.id) {
      this.lastPowerInfusionCastStartTimestamp = event.timestamp;
    } else if (this.owner.modules.combatants.selected.hasBuff(SPELLS.POWER_INFUSION_TALENT.id) && (event.timestamp + 20000) > this.lastPowerInfusionCastStartTimestamp) {
      const spellId = event.ability.guid;
      const manaCost = event.manaCost;
      if (!manaCost) {
        return;
      }

      const manaSaved = Math.floor(manaCost / 3);

      if (!event.isManaCostNullified) {
        this.manaGained += manaSaved;
        debug && console.log('Inner Hallation saved', manaSaved, 'mana on', SPELLS[spellId].name, ', normally costing', manaCost, event);
      } else {
        debug && console.log('Inner Hallation saved 0 mana on', SPELLS[spellId].name, 'costing', manaCost, 'since Innervate or Symbol of Hope is active (normally ', manaSaved, ' mana)', event);
      }
    }
  }
}

export default InnerHallation;
<commit_msg>inner hallation work<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import { formatThousands } from 'common/format';

import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';

const debug = false;

class InnerHallation extends Module {
  static dependencies = {
    combatants: Combatants,
  };

  manaGained = 0;

  // timestamp for power infusion if its talented & casted (to exclude mana saved):
  lastPowerInfusionCastStartTimestamp = null;

  on_initialized() {
    const selectedCombatant = this.owner.modules.combatants.selected;
    this.active = selectedCombatant.hasShoulder(ITEMS.INNER_HALLATION.id);
  }

  on_byPlayer_cast(event) {
    if (this.owner.modules.combatants.selected.hasTalent(SPELLS.POWER_INFUSION_TALENT.id) && event.ability.guid === SPELLS.POWER_INFUSION_TALENT.id) {
      this.lastPowerInfusionCastStartTimestamp = event.timestamp;
    } else if (this.owner.modules.combatants.selected.hasBuff(SPELLS.POWER_INFUSION_TALENT.id) && (event.timestamp + 20000) > this.lastPowerInfusionCastStartTimestamp) {
      const spellId = event.ability.guid;
      const manaCost = event.manaCost;
      if (!manaCost) {
        return;
      }

      const manaSaved = Math.floor(manaCost / 3);

      if (!event.isManaCostNullified) {
        this.manaGained += manaSaved;
        debug && console.log('Inner Hallation saved', manaSaved, 'mana on', SPELLS[spellId].name, ', normally costing', manaCost, event);
      } else {
        debug && console.log('Inner Hallation saved 0 mana on', SPELLS[spellId].name, 'costing', manaCost, 'since Innervate or Symbol of Hope is active (normally ', manaSaved, ' mana)', event);
      }
    }
  }

  item() {
    const manaGained = this.manaGained || 0;

    return {
      item: ITEMS.INNER_HALLATION,
      result: (
        <dfn>
          {formatThousands(manaGained)} mana saved ({formatThousands(manaGained / this.owner.fightDuration * 1000 * 5)} MP5)
        </dfn>
      ),
    };
  }
}

export default InnerHallation;
<|endoftext|>


<commit_before>let express = require('express');
let Mustache = require('mustache');
let fs = require('fs');
let app = express();

class PresentationServer {

    constructor(presentations, config) {

        config = config ? config : {};
        presentations = presentations ? presentations : [];

        this.config = Object.assign({
            resources: __dirname + '/../node_modules',
            lib: __dirname + '/../node_modules/reveal.js/lib',
            themes: __dirname + '/../node_modules/reveal.js/css/theme',
            styles: __dirname + '/../node_modules/highlight.js/src/styles'
        }, config);

        this.presentationContainer = this.loadContainer(__dirname + '/templates/presentationContainer.mustache');
        this.configurationContainer = this.loadContainer(__dirname + '/templates/configurationContainer.mustache');

        presentations.unshift({
            id: '404',
            title: 'Presentation not found',
            path: __dirname + '/static/not-found.html'
        });

        presentations.unshift({
            id: 'demo',
            title: 'Demonstration',
            path: __dirname + '/static/demo.html'
        });

        this.presentations = presentations.map(presentation => {
            try {
                presentation.slides = fs.readFileSync(presentation.path).toString();
            } catch (err) {
                throw "Unable to load presentation path -> '" + presentation.path + "'";
            }
            return presentation;
        }).map(presentations => this.buildConfig(presentations));

        this.themes = this.loadCSSResources(this.config.themes);
        this.styles = this.loadCSSResources(this.config.styles);
    }

    loadContainer(path) {
        try {
            return fs.readFileSync(path).toString();
        } catch (err) {
            throw "Unable to load container '" + path + "' -> " + err;
        }
    }

    loadCSSResources(path) {
        try {
            return fs.readdirSync(path)
                .toString()
                .split(',')
                .filter(file => file.endsWith('.css'))
                .map(file => file.replace('.css', ''));
        } catch (err) {
            throw "Unable to load resource directory '" + path + "' -> " + err;
        }
    }

    clone(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    buildConfig(config) {
        return Object.assign({
            title: 'Presentation',
            theme: 'black',
            style: 'vs2015',
            controls: false,
            loop: false
        }, config);
    }

    generateSection(presentation, config) {
        return '
' +
            '' +
            (config ?
                '
Use your left/right arrows to switch between different themes, while the up/down arrows to control the code highlight style
' +
                '
Theme: default Style: default
' +
                'Start'
                :
                '
Use your left/right arrows to switch between different presentations
' +
                'Start | ' +
                'Configure'
            ) +
            '
';
    }

    constructHomePage() {
        return this.presentations
            .filter(presentation => presentation.id != '404')
            .reduce((arr, presentation) => {
                arr.push(this.generateSection(presentation, false));
                return arr;
            }, []).join('\n');
    }

    constructConfigPage(presentation) {
        return [this.generateSection(presentation, true), this.generateSection(presentation, true)].join('\n');
    }

    getPresentation(req) {

        let findPresentation = function (id) {
            return this.presentations.find(presentation => {
                return presentation.id == id;
            });
        }.bind(this);

        let presentation = findPresentation(req.params.id);

        if (!presentation) {
            presentation = findPresentation('404');
        }

        presentation = this.clone(presentation);

        presentation.theme = req.query.theme && this.themes.indexOf(req.query.theme) > -1 ? req.query.theme : presentation.theme;
        presentation.style = req.query.style && this.styles.indexOf(req.query.style) > -1 ? req.query.style : presentation.style;
        return presentation;
    }

    start(port) {

        port = port ? port : 8080;

        Object.keys(this.config).map(resource => {
            app.use('/' + resource, express.static(this.config[resource]));
        });

        app.get('/api/themes', (req, res) => {
            res.json(this.themes);
        });

        app.get('/api/styles', (req, res) => {
            res.json(this.styles);
        });

        app.get('/api/presentations', (req, res) => {
            res.json(this.clone(this.presentations)
                .filter(presentation => presentation.id != '404')
                .map(presentation => {
                    delete presentation.slides;
                    delete presentation.path;
                    return presentation
                }));
        });

        app.get('/', (req, res) => {
            res.redirect('/presentations');
        });

        app.get('/presentations', (req, res) => {
            var presentation = this.buildConfig({
                title: 'Home',
                theme: 'night',
                slides: this.constructHomePage(),
                loop: true
            });
            var output = Mustache.render(this.presentationContainer, presentation);
            res.contentType('text/html');
            res.send(output);
        });

        app.get('/presentations/:id', (req, res) => {
            let presentation = this.getPresentation(req);
            var output = Mustache.render(this.presentationContainer, presentation);
            res.contentType('text/html');
            res.send(output);
        });

        app.get('/presentations/:id/configure', (req, res) => {
            let presentation = this.getPresentation(req);
            var content = this.buildConfig({
                id: presentation.id,
                title: 'Presentation Configuration',
                theme: 'night',
                defaultTheme: presentation.theme,
                defaultStyle: presentation.style,
                slides: this.constructConfigPage(presentation)
            });
            var output = Mustache.render(this.configurationContainer, content);
            res.contentType('text/html');
            res.send(output);
        });

        app.listen(port, (err) => {
            console.info("Presentation Server is running on port " + port);
        });

    }

}

module.exports = (presentations, config) => new PresentationServer(presentations, config);<commit_msg>now validating for duplicate presentation ids<commit_after>let express = require('express');
let Mustache = require('mustache');
let fs = require('fs');
let app = express();

class PresentationServer {

    constructor(presentations, config) {

        config = config ? config : {};
        presentations = presentations ? presentations : [];

        this.config = Object.assign({
            resources: __dirname + '/../node_modules',
            lib: __dirname + '/../node_modules/reveal.js/lib',
            themes: __dirname + '/../node_modules/reveal.js/css/theme',
            styles: __dirname + '/../node_modules/highlight.js/src/styles'
        }, config);

        this.presentationContainer = this.loadContainer(__dirname + '/templates/presentationContainer.mustache');
        this.configurationContainer = this.loadContainer(__dirname + '/templates/configurationContainer.mustache');

        presentations.unshift({
            id: '404',
            title: 'Presentation not found',
            path: __dirname + '/static/not-found.html'
        });

        presentations.unshift({
            id: 'demo',
            title: 'Demonstration',
            path: __dirname + '/static/demo.html'
        });

        presentations.forEach(function(presentation) {
            if (presentations.filter(p => p.id == presentation.id).length > 1) {
                throw "Duplicate presentation id detected, please rename '" + presentation.id + "'";
            }
        });

        this.presentations = presentations.map(presentation => {
            try {
                presentation.slides = fs.readFileSync(presentation.path).toString();
            } catch (err) {
                throw "Unable to load presentation path -> '" + presentation.path + "'";
            }
            return presentation;
        }).map(presentations => this.buildConfig(presentations));

        this.themes = this.loadCSSResources(this.config.themes);
        this.styles = this.loadCSSResources(this.config.styles);
    }

    loadContainer(path) {
        try {
            return fs.readFileSync(path).toString();
        } catch (err) {
            throw "Unable to load container '" + path + "' -> " + err;
        }
    }

    loadCSSResources(path) {
        try {
            return fs.readdirSync(path)
                .toString()
                .split(',')
                .filter(file => file.endsWith('.css'))
                .map(file => file.replace('.css', ''));
        } catch (err) {
            throw "Unable to load resource directory '" + path + "' -> " + err;
        }
    }

    clone(obj) {
        return JSON.parse(JSON.stringify(obj));
    }

    buildConfig(config) {
        return Object.assign({
            title: 'Presentation',
            theme: 'black',
            style: 'vs2015',
            controls: false,
            loop: false
        }, config);
    }

    generateSection(presentation, config) {
        return '
' +
            '' +
            (config ?
                '
Use your left/right arrows to switch between different themes, while the up/down arrows to control the code highlight style
' +
                '
Theme: default Style: default
' +
                'Start'
                :
                '
Use your left/right arrows to switch between different presentations
' +
                'Start | ' +
                'Configure'
            ) +
            '
';
    }

    constructHomePage() {
        return this.presentations
            .filter(presentation => presentation.id != '404')
            .reduce((arr, presentation) => {
                arr.push(this.generateSection(presentation, false));
                return arr;
            }, []).join('\n');
    }

    constructConfigPage(presentation) {
        return [this.generateSection(presentation, true), this.generateSection(presentation, true)].join('\n');
    }

    getPresentation(req) {

        let findPresentation = function (id) {
            return this.presentations.find(presentation => {
                return presentation.id == id;
            });
        }.bind(this);

        let presentation = findPresentation(req.params.id);

        if (!presentation) {
            presentation = findPresentation('404');
        }

        presentation = this.clone(presentation);

        presentation.theme = req.query.theme && this.themes.indexOf(req.query.theme) > -1 ? req.query.theme : presentation.theme;
        presentation.style = req.query.style && this.styles.indexOf(req.query.style) > -1 ? req.query.style : presentation.style;
        return presentation;
    }

    start(port) {

        port = port ? port : 8080;

        Object.keys(this.config).map(resource => {
            app.use('/' + resource, express.static(this.config[resource]));
        });

        app.get('/api/themes', (req, res) => {
            res.json(this.themes);
        });

        app.get('/api/styles', (req, res) => {
            res.json(this.styles);
        });

        app.get('/api/presentations', (req, res) => {
            res.json(this.clone(this.presentations)
                .filter(presentation => presentation.id != '404')
                .map(presentation => {
                    delete presentation.slides;
                    delete presentation.path;
                    return presentation
                }));
        });

        app.get('/', (req, res) => {
            res.redirect('/presentations');
        });

        app.get('/presentations', (req, res) => {
            var presentation = this.buildConfig({
                title: 'Home',
                theme: 'night',
                slides: this.constructHomePage(),
                loop: true
            });
            var output = Mustache.render(this.presentationContainer, presentation);
            res.contentType('text/html');
            res.send(output);
        });

        app.get('/presentations/:id', (req, res) => {
            let presentation = this.getPresentation(req);
            var output = Mustache.render(this.presentationContainer, presentation);
            res.contentType('text/html');
            res.send(output);
        });

        app.get('/presentations/:id/configure', (req, res) => {
            let presentation = this.getPresentation(req);
            var content = this.buildConfig({
                id: presentation.id,
                title: 'Presentation Configuration',
                theme: 'night',
                defaultTheme: presentation.theme,
                defaultStyle: presentation.style,
                slides: this.constructConfigPage(presentation)
            });
            var output = Mustache.render(this.configurationContainer, content);
            res.contentType('text/html');
            res.send(output);
        });

        app.listen(port, (err) => {
            console.info("Presentation Server is running on port " + port);
        });

    }

}

module.exports = (presentations, config) => new PresentationServer(presentations, config);<|endoftext|>


<commit_before>export default Ember.ObjectController.extend({
    noteTitle: '',
    noteContent: '',
    noteTags: '',
    actions: {
        createNote: function () {
            var note = this.store.createRecord('note', {
                title: this.get('noteTitle'),
                content: this.get('noteContent'),
                tag_list: this.get('noteTags').split(/[, ]/)
            });

            note.save().then(this.transitionToNote.bind(this))
                       .catch(this.failure.bind(this));
        }
    },
    transitionToNote: function(note) {
        this.transitionToRoute('notes.note', note);
    },
    failure: function() {}
});<commit_msg>fix(notes-new): Clear ctrl state on success<commit_after>export default Ember.ObjectController.extend({
    noteTitle: '',
    noteContent: '',
    noteTags: '',
    actions: {
        createNote: function () {
            var note = this.store.createRecord('note', {
                title: this.get('noteTitle'),
                content: this.get('noteContent'),
                tag_list: this.get('noteTags').split(/[, ]/)
            });

            note.save().then(this.transitionToNote.bind(this))
                       .catch(this.failure.bind(this));
        }
    },
    transitionToNote: function(note) {
        this.set('noteTitle', '');
        this.set('noteContent', '');
        this.set('noteTags', '');
        this.transitionToRoute('notes.note', note);
    },
    failure: function() {}
});<|endoftext|>


<commit_before>// TODO:
// - require process.env.SECRET

module.exports.server = function (options) {
    // Room server
    var http = require('http'),
        util = require('util'),
        express = require('express'),
        uuid = require('node-uuid'),
        crypto = require('crypto'),
        extend = require('deep-extend'),
        app = express(),
        host = process.env.HOST,
        port = process.env.PORT,
        webPort = process.env.WEB_PORT, // 80 or 443
        secret = process.env.SECRET,
        server, io, base;

    options = options  || {};
    base = options.base || ['.'];

    app.use(express.urlencoded());
    app.use(express.cookieParser());
    app.use(express.session({
        secret: secret
    }));
    app.use(express.compress());
    app.use(express.json());

    // TODO
    base.forEach(function (dir) {
        app.use('/scripts', express.static(dir + '/scripts'));
        app.use('/styles', express.static(dir + '/styles'));
    });

    //
    // Web server
    //

    // Handle Persona authentication
    require('express-persona')(app, {
      audience: 'http://' + host + ':' + webPort
    });

    app.get('/', function (req, res) {
        res.sendfile(__dirname + '/index.html');
    });

    app.get('/room', function (req, res) {
        var ip = req.headers['x-forwarded-for'] || req.ip,
            name = crypto.createHmac('md5', secret).update(ip).digest('hex');

        res.json({
            name: name,
            uuid: uuid.v1(),
            public_ip: ip
        });
    });

    //
    // Room server
    //
    server = http.createServer(app);
    io = require('socket.io').listen(server);

    io.sockets.on('connection', function (client) {

        // When a peer joins a room, send back list of other peers already there
        client.on('join', function (data) {
            var room = data.room,
                peer = data.peer;

            console.log('on:join', data);
            client.peer = peer;

            var clients = io.sockets.clients(room),
                peers = clients.map(function (client) {return client.peer;});

            // Send back list of other peers in the room
            client.emit('user_list', peers);

            // Join the room
            client.join(room);

            // Notify other peers that a new peer has joined the room
            client.broadcast.to(room).emit('user_added', client.peer);

            // Notify other peers when a peer leaves the room
            client.on('disconnect', function () {
                client.broadcast.to(room).emit('user_removed', client.peer);
            });

            console.log('on:join', peers);
        });

        client.on('update', function (data) {
            var room = data.room,
                peer = data.peer;

            extend(client.peer, peer);

            client.broadcast.to(room).emit('user_changed', client.peer);
        });
    });

    return server;
};

<commit_msg>tidied up server.js<commit_after>// TODO:
// - require process.env.SECRET

module.exports.server = function (options) {
    // Room server
    var http = require('http'),
        util = require('util'),
        express = require('express'),
        uuid = require('node-uuid'),
        crypto = require('crypto'),
        extend = require('deep-extend'),
        persona = require('express-persona'),
        socketIo = require('socket.io'),
        app = express(),
        host = process.env.HOST,
        port = process.env.PORT,
        webPort = process.env.WEB_PORT, // 80 or 443
        secret = process.env.SECRET,
        server, io, base;

    options = options || {};
    base = options.base || ['.'];

    app.use(express.urlencoded());
    app.use(express.cookieParser());
    app.use(express.session({ secret: secret }));
    app.use(express.compress());
    app.use(express.json());

    // TODO
    base.forEach(function (dir) {
        app.use('/scripts', express.static(dir + '/scripts'));
        app.use('/styles', express.static(dir + '/styles'));
    });

    //
    // Web server
    //

    // Handle Persona authentication
    persona(app, { audience: 'http://' + host + ':' + webPort });

    app.get('/', function (req, res) {
        res.sendfile(__dirname + '/index.html');
    });

    app.get('/room', function (req, res) {
        var ip = req.headers['x-forwarded-for'] || req.ip,
            name = crypto.createHmac('md5', secret).update(ip).digest('hex');

        res.json({ name: name, uuid: uuid.v1(), public_ip: ip });
    });

    //
    // Room server
    //
    server = http.createServer(app);
    io = socketIo.listen(server);

    io.sockets.on('connection', function (client) {

        // When a peer joins a room, send back list of other peers already there
        client.on('join', function (data) {
            var room = data.room,
                peer = data.peer;

            console.log('on:join', data);
            client.peer = peer;

            var clients = io.sockets.clients(room),
                peers = clients.map(function (client) {return client.peer;});

            // Send back list of other peers in the room
            client.emit('user_list', peers);

            // Join the room
            client.join(room);

            // Notify other peers that a new peer has joined the room
            client.broadcast.to(room).emit('user_added', client.peer);

            // Notify other peers when a peer leaves the room
            client.on('disconnect', function () {
                client.broadcast.to(room).emit('user_removed', client.peer);
            });

            console.log('on:join', peers);
        });

        client.on('update', function (data) {
            var room = data.room,
                peer = data.peer;

            extend(client.peer, peer);

            client.broadcast.to(room).emit('user_changed', client.peer);
        });
    });

    return server;
};
<|endoftext|>


<commit_before>(function(){
  angular
    .module('app')
    .factory('lineFactory',lineFactory);

  function lineFactory() {
    return {lineHolder: lineHolder,
            makeLines: makeLines
           };

    ////////////

    function lineHolder(){
      var c = document.getElementById("canvas");
      var ctx = c.getContext("2d");
      c.width = window.innerWidth;
      c.height = window.innerHeight;
      ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
      makeLines('.cm-attribute:contains(ng-controller)', '.cm-property:contains("controller")', ctx);
      makeLines('.cm-attribute:contains(ng-app)', '.cm-property:contains(module)', ctx);
      makeLines('.cm-property:contains($inject)', '.cm-property:contains(factory)', ctx);

      return 'Line Created...';
    }
  function makeLines(query1, query2, ctx) {
    var temp1 = $(query1),
        word1,
        temp2 = $(query2),
        word2;

    if(temp1[0]) {
      word1 = temp1[0].nextElementSibling;
      if(word1.className === "cm-operator") {
        word1 = word1.nextElementSibling;
      }
    } else {
      return;
    }
    if(temp2[0]) {
      word2 = temp2[0].nextElementSibling;
    }else {
      return;
    }

    if(word1.innerHTML.substring(1,word1.innerHTML.length - 1).indexOf(word2.innerHTML.substring(1,word2.innerHTML.length - 1)) != -1) {
        var x1 = $(word1).offset().left+5;
        var y1 = $(word1).offset().top +10;
        var x2 = $(word2).offset().left+5;
        var y2 = $(word2).offset().top +10;

        ctx.beginPath();
        ctx.lineWidth = 0.2;
        ctx.moveTo(x1, y1);
        ctx.quadraticCurveTo(400,400,x2,y2);
        ctx.stroke();
    }

  }
  }
}());
<commit_msg>need to change ui<commit_after>(function(){
  angular
    .module('app')
    .factory('lineFactory',lineFactory);

  function lineFactory() {
    return {lineHolder: lineHolder,
            makeLines: makeLines
           };

    ////////////

    function lineHolder(){
      var c = document.getElementById("canvas");
      var ctx = c.getContext("2d");
      c.width = window.innerWidth;
      c.height = window.innerHeight;
      ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
      makeLines('.cm-attribute:contains(ng-controller)', '.cm-property:contains("controller")', ctx);
      makeLines('.cm-attribute:contains(ng-app)', '.cm-property:contains(module)', ctx);
      makeLines('.cm-property:contains($inject)', '.cm-property:contains(factory)', ctx);

      return 'Line Created...';
    }
  function makeLines(query1, query2, ctx) {
    var temp1 = $(query1),
        word1,
        temp2 = $(query2),
        word2;

    if(temp1[0]) {
      word1 = temp1[0].nextElementSibling;
      if(word1.className === "cm-operator") {
        word1 = word1.nextElementSibling;
      }
    } else {
      return;
    }
    if(temp2[0]) {
      word2 = temp2[0].nextElementSibling;
    }else {
      return;
    }

    if(word1.innerHTML.substring(1,word1.innerHTML.length - 1).indexOf(word2.innerHTML.substring(1,word2.innerHTML.length - 1)) != -1) {
        var x1 = $(word1).offset().left+5;
        var y1 = $(word1).offset().top +10;
        var x2 = $(word2).offset().left+5;
        var y2 = $(word2).offset().top +10;

        ctx.beginPath();
        ctx.lineWidth = 0.5;
        ctx.moveTo(x1, y1);
        ctx.quadraticCurveTo(400,400,x2,y2);
        ctx.stroke();
    }

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


<commit_before>// This is really the creation of
// a new meaning proposal

import Ember from "ember";
import EmberValidations from 'ember-validations';
import ENV from '../../config/environment';

export default Ember.Controller.extend(EmberValidations.Mixin, {
  wordId: null,
  proposalId: null,
  validations: {
    "model.wordName": {
      inline: EmberValidations.validator(function() {
        var name = this.get("model.wordName");

        var _this = this;
        if(name && (name.length > 0)) {
          Ember.$.getJSON(ENV.api + "/proposals/new-word-status/" + name).then(
            function(resp) {
              _this.set("wordId", "");
              _this.set("proposalId", "");
              if(!resp.can) {
                if(resp.word_id) {
                  _this.set("wordId", resp.word_id);
                  _this.get("errors").addObject("This word already exists");
                } else if(resp.proposal_id) {
                  _this.set("proposalId", resp.proposal_id);
                  _this.get("errors").addObject("There is an open proposal for this word");
                }
              }
            }
          );
        } else {
          return "It needs the actual word! :)";
        }
      })
    },
  },
  posList: ENV.posList,

  canRemove: function() {
    return this.get("model").get("meanings").length > 1;
  }.property("model.meanings.@each"),

  actions: {
    submitProposal: function() {
      var _this = this;
      this.send("log", "propose", "new word");
      this.get("model").save().then(
        function(p) {
          _this.transitionToRoute("proposal.index", p);
        },
        function() {}
        );
    },
    addMeaning: function() {
      this.get("model").get("meanings").addObject({});
    },
    removeMeaning: function(meaning) {
      this.get("model").get("meanings").removeObject(meaning);
    }
  }

});
<commit_msg>Log line for the model in new word<commit_after>// This is really the creation of
// a new meaning proposal

import Ember from "ember";
import EmberValidations from 'ember-validations';
import ENV from '../../config/environment';

export default Ember.Controller.extend(EmberValidations.Mixin, {
  wordId: null,
  proposalId: null,
  validations: {
    "model.wordName": {
      inline: EmberValidations.validator(function() {
        var name = this.get("model.wordName");

        var _this = this;
        if(name && (name.length > 0)) {
          Ember.$.getJSON(ENV.api + "/proposals/new-word-status/" + name).then(
            function(resp) {
              _this.set("wordId", "");
              _this.set("proposalId", "");
              if(!resp.can) {
                if(resp.word_id) {
                  _this.set("wordId", resp.word_id);
                  _this.get("errors").addObject("This word already exists");
                } else if(resp.proposal_id) {
                  _this.set("proposalId", resp.proposal_id);
                  _this.get("errors").addObject("There is an open proposal for this word");
                }
              }
            }
          );
        } else {
          // console.log(this.get("model.wordName"));
          return "It needs the actual word! :)";
        }
      })
    },
  },
  posList: ENV.posList,

  canRemove: function() {
    return this.get("model").get("meanings").length > 1;
  }.property("model.meanings.@each"),

  actions: {
    submitProposal: function() {
      var _this = this;
      this.send("log", "propose", "new word");
      this.get("model").save().then(
        function(p) {
          _this.transitionToRoute("proposal.index", p);
        },
        function() {}
        );
    },
    addMeaning: function() {
      this.get("model").get("meanings").addObject({});
    },
    removeMeaning: function(meaning) {
      this.get("model").get("meanings").removeObject(meaning);
    }
  }

});
<|endoftext|>


<commit_before>import $ from 'jquery';
import React from 'react';
import PropTypes from 'prop-types';
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import Reflux from 'reflux';
import alertify from 'alertifyjs';
import classNames from 'classnames';

import bem from 'js/bem';
import stores from 'js/stores';
import mixins from 'js/mixins';
import ui from 'js/ui';
import actions from 'js/actions';
import {MODAL_TYPES} from 'js/constants'

import {t, getLangAsObject, getLangString, notify} from 'utils';

class LanguageForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      languageName: '',
      languageCode: ''
    }

    if (this.props.langString) {
      const lang = getLangAsObject(this.props.langString);
      this.state = {
        languageName: lang.name || '',
        languageCode: lang.code || ''
      }
    }
    autoBind(this);
  }
  onSubmit(evt) {
    evt.preventDefault();
    if (this.props.langIndex !== undefined) {
      this.props.addOrUpdateLanguage(this.state, this.props.langIndex);
    } else {
      this.props.addOrUpdateLanguage(this.state, -1);
    }
  }
  nameChange (e) {
    this.setState({languageName: e.target.value});
  }
  codeChange (e) {
    this.setState({languageCode: e.target.value});
  }
  render () {
    let fieldsNotEmpty = this.state.languageName.length > 0 && this.state.languageCode.length > 0;
    var btnClasses = classNames('mdl-button','mdl-js-button', 'mdl-button--raised', fieldsNotEmpty ? 'mdl-button--colored' : 'mdl-button--disabled');

    return (
      <bem.FormView__form m='add-language-fields'>
        <bem.FormView__cell>
          <bem.FormModal__item>
            {t('Language name')}
            <input type='text' value={this.state.languageName} onChange={this.nameChange} />
          </bem.FormModal__item>
        </bem.FormView__cell>
        <bem.FormView__cell m='lang-code'>
          <bem.FormModal__item>
            {t('Language code')}
            <input type='text' value={this.state.languageCode} onChange={this.codeChange} />
          </bem.FormModal__item>
        </bem.FormView__cell>
        <bem.FormView__cell>
          <button className={btnClasses} onClick={this.onSubmit} type='submit'>
            {this.props.langIndex !== undefined ? t('Update') : t('Add')}
          </button>
        </bem.FormView__cell>
      </bem.FormView__form>
      );
  }
};

export class TranslationSettings extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      translations: props.asset.content.translations || [],
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    }
    autoBind(this);
  }
  componentDidMount () {
    this.listenTo(stores.asset, this.assetStoreChange);
  }
  assetStoreChange(asset) {
    let uid = this.props.asset.uid;

    this.setState({
      translations: asset[uid].content.translations,
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    })

    stores.pageState.showModal({
      type: MODAL_TYPES.FORM_LANGUAGES,
      asset: asset[uid]
    });
  }
  showAddLanguageForm() {
    this.setState({
      showAddLanguageForm: true
    })
  }
  hideAddLanguageForm() {
    this.setState({
      showAddLanguageForm: false
    })
  }
  toggleRenameLanguageForm(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index'));
    if (this.state.renameLanguageIndex === index) {
      this.setState({
        renameLanguageIndex: -1
      });
    } else {
      this.setState({
        renameLanguageIndex: index
      });
    }
  }
  launchTranslationTableModal(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index')),
        asset = this.props.asset;
    stores.pageState.switchModal({
      type: MODAL_TYPES.FORM_TRANSLATIONS_TABLE,
      asset: asset,
      langIndex: index
    });
  }
  addOrUpdateLanguage(lang, index) {
    let content = this.props.asset.content;
    if (index > -1) {
      content.translations[index] = getLangString(lang);
    } else {
      content.translations.push(getLangString(lang));
      content = this.prepareTranslations(content);
    }

    this.updateAsset(content);
  }
  deleteLanguage(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index'));
    const content = this.deleteTranslations(this.props.asset.content, index);
    if (content) {
      content.translations.splice(index, 1);
      let dialog = alertify.dialog('confirm');
      let opts = {
        title: t('Delete language?'),
        message: t('Are you sure you want to delete this language? This action is not reversible.'),
        labels: {ok: t('Delete'), cancel: t('Cancel')},
        onok: () => {
          this.updateAsset(content);
          dialog.destroy();
        },
        oncancel: () => {dialog.destroy()}
      };
      dialog.set(opts).show();

    } else {
      notify('Error: translation index mismatch. Cannot delete language.');
    }
  }
  prepareTranslations(content) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    // append null values to translations for each survey row
    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property] && row[property].length < translationsLength) {
          row[property].push(null);
        }
      }
    }

    // append null values to translations for choices
    if (content.choices && content.choices.length) {
      for (var i = 0, len = choices.length; i < len; i++) {
        if (choices[i].label.length < translationsLength) {
          choices[i].label.push(null);
        }
      }
    }
    return content;
  }
  deleteTranslations(content, langIndex) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property]) {
          if (row[property].length === translationsLength) {
            row[property].splice(langIndex, 1);
          } else {
            console.error('Translations index mismatch');
            return false;
          }
        }
      }
    }

    for (var i = 0, len = choices.length; i < len; i++) {
      if (choices[i].label) {
        if (choices[i].label.length === translationsLength) {
          choices[i].label.splice(langIndex, 1);
        } else {
          console.error('Translations index mismatch');
          return false;
        }
      }
    }
    return content;
  }
  updateAsset (content) {
    actions.resources.updateAsset(
      this.props.asset.uid,
      {content: JSON.stringify(content)}
    );
  }
  renderEmptyMessage() {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          <bem.FormView__cell>
            {t('There is nothing to translate in this form.')}
          </bem.FormView__cell>
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  renderTranslationsSettings() {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          {(translations && translations[0] === null) ?
            <bem.FormView__cell m='translation-note'>
              {t('Here you can add one more more languages to your project, and translate the strings in each language.')}

                {t('Note: make sure your default language has a name. If it doesn\'t, you will not be able to edit your form in the form builder.')}

            </bem.FormView__cell>
            :
            <bem.FormView__cell m='label'>
              {t('Current languages')}
            </bem.FormView__cell>
          }
          {translations.map((l, i)=> {
            return (
              <React.Fragment key={`lang-${i}`}>
                <bem.FormView__cell m='translation'>
                  <bem.FormView__cell>
                    {l ? l : t('Unnamed language')}
                    {i === 0 ? ` ${t('default')}` : ''}
                  </bem.FormView__cell>
                  <bem.FormView__cell m='translation-actions'>
                    <bem.FormView__link m='rename'
                                        onClick={this.toggleRenameLanguageForm}
                                        data-index={i}
                                        data-tip={t('Edit language')}>

                    </bem.FormView__link>
                    {i > 0 &&
                      <bem.FormView__link m='translate'
                                          data-index={i}
                                          onClick={this.launchTranslationTableModal}
                                          data-tip={t('Update translations')}>

                      </bem.FormView__link>
                    }
                    {i > 0 &&
                      <bem.FormView__link m='translate'
                                          onClick={this.deleteLanguage}
                                          data-index={i}
                                          data-tip={t('Delete language')}>

                      </bem.FormView__link>
                    }
                  </bem.FormView__cell>
                </bem.FormView__cell>
                {this.state.renameLanguageIndex === i &&
                  <bem.FormView__cell m='update-language-form'>
                    <LanguageForm langString={l} langIndex={i} addOrUpdateLanguage={this.addOrUpdateLanguage}/>
                  </bem.FormView__cell>
                }
              </React.Fragment>
            );
          })}
          {!this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language'>
              <button className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
                      onClick={this.showAddLanguageForm}>
                {t('Add language')}
              </button>
            </bem.FormView__cell>
          }
          {this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language-form'>
              <bem.FormView__link m='close' onClick={this.hideAddLanguageForm}>

              </bem.FormView__link>
              <bem.FormView__cell m='label'>
                {t('Add a new language')}
              </bem.FormView__cell>
              <LanguageForm addOrUpdateLanguage={this.addOrUpdateLanguage}/>
            </bem.FormView__cell>
          }
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  render () {
    let translations = this.state.translations;
    if (translations.length === 0) {
      return this.renderEmptyMessage();
    } else {
      return this.renderTranslationsSettings();
    }
  }
};

reactMixin(TranslationSettings.prototype, Reflux.ListenerMixin);

export default TranslationSettings;
<commit_msg>pass translations variable<commit_after>import $ from 'jquery';
import React from 'react';
import PropTypes from 'prop-types';
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import Reflux from 'reflux';
import alertify from 'alertifyjs';
import classNames from 'classnames';

import bem from 'js/bem';
import stores from 'js/stores';
import mixins from 'js/mixins';
import ui from 'js/ui';
import actions from 'js/actions';
import {MODAL_TYPES} from 'js/constants'

import {t, getLangAsObject, getLangString, notify} from 'utils';

class LanguageForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      languageName: '',
      languageCode: ''
    }

    if (this.props.langString) {
      const lang = getLangAsObject(this.props.langString);
      this.state = {
        languageName: lang.name || '',
        languageCode: lang.code || ''
      }
    }
    autoBind(this);
  }
  onSubmit(evt) {
    evt.preventDefault();
    if (this.props.langIndex !== undefined) {
      this.props.addOrUpdateLanguage(this.state, this.props.langIndex);
    } else {
      this.props.addOrUpdateLanguage(this.state, -1);
    }
  }
  nameChange (e) {
    this.setState({languageName: e.target.value});
  }
  codeChange (e) {
    this.setState({languageCode: e.target.value});
  }
  render () {
    let fieldsNotEmpty = this.state.languageName.length > 0 && this.state.languageCode.length > 0;
    var btnClasses = classNames('mdl-button','mdl-js-button', 'mdl-button--raised', fieldsNotEmpty ? 'mdl-button--colored' : 'mdl-button--disabled');

    return (
      <bem.FormView__form m='add-language-fields'>
        <bem.FormView__cell>
          <bem.FormModal__item>
            {t('Language name')}
            <input type='text' value={this.state.languageName} onChange={this.nameChange} />
          </bem.FormModal__item>
        </bem.FormView__cell>
        <bem.FormView__cell m='lang-code'>
          <bem.FormModal__item>
            {t('Language code')}
            <input type='text' value={this.state.languageCode} onChange={this.codeChange} />
          </bem.FormModal__item>
        </bem.FormView__cell>
        <bem.FormView__cell>
          <button className={btnClasses} onClick={this.onSubmit} type='submit'>
            {this.props.langIndex !== undefined ? t('Update') : t('Add')}
          </button>
        </bem.FormView__cell>
      </bem.FormView__form>
      );
  }
};

export class TranslationSettings extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      translations: props.asset.content.translations || [],
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    }
    autoBind(this);
  }
  componentDidMount () {
    this.listenTo(stores.asset, this.assetStoreChange);
  }
  assetStoreChange(asset) {
    let uid = this.props.asset.uid;

    this.setState({
      translations: asset[uid].content.translations,
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    })

    stores.pageState.showModal({
      type: MODAL_TYPES.FORM_LANGUAGES,
      asset: asset[uid]
    });
  }
  showAddLanguageForm() {
    this.setState({
      showAddLanguageForm: true
    })
  }
  hideAddLanguageForm() {
    this.setState({
      showAddLanguageForm: false
    })
  }
  toggleRenameLanguageForm(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index'));
    if (this.state.renameLanguageIndex === index) {
      this.setState({
        renameLanguageIndex: -1
      });
    } else {
      this.setState({
        renameLanguageIndex: index
      });
    }
  }
  launchTranslationTableModal(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index')),
        asset = this.props.asset;
    stores.pageState.switchModal({
      type: MODAL_TYPES.FORM_TRANSLATIONS_TABLE,
      asset: asset,
      langIndex: index
    });
  }
  addOrUpdateLanguage(lang, index) {
    let content = this.props.asset.content;
    if (index > -1) {
      content.translations[index] = getLangString(lang);
    } else {
      content.translations.push(getLangString(lang));
      content = this.prepareTranslations(content);
    }

    this.updateAsset(content);
  }
  deleteLanguage(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index'));
    const content = this.deleteTranslations(this.props.asset.content, index);
    if (content) {
      content.translations.splice(index, 1);
      let dialog = alertify.dialog('confirm');
      let opts = {
        title: t('Delete language?'),
        message: t('Are you sure you want to delete this language? This action is not reversible.'),
        labels: {ok: t('Delete'), cancel: t('Cancel')},
        onok: () => {
          this.updateAsset(content);
          dialog.destroy();
        },
        oncancel: () => {dialog.destroy()}
      };
      dialog.set(opts).show();

    } else {
      notify('Error: translation index mismatch. Cannot delete language.');
    }
  }
  prepareTranslations(content) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    // append null values to translations for each survey row
    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property] && row[property].length < translationsLength) {
          row[property].push(null);
        }
      }
    }

    // append null values to translations for choices
    if (content.choices && content.choices.length) {
      for (var i = 0, len = choices.length; i < len; i++) {
        if (choices[i].label.length < translationsLength) {
          choices[i].label.push(null);
        }
      }
    }
    return content;
  }
  deleteTranslations(content, langIndex) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property]) {
          if (row[property].length === translationsLength) {
            row[property].splice(langIndex, 1);
          } else {
            console.error('Translations index mismatch');
            return false;
          }
        }
      }
    }

    for (var i = 0, len = choices.length; i < len; i++) {
      if (choices[i].label) {
        if (choices[i].label.length === translationsLength) {
          choices[i].label.splice(langIndex, 1);
        } else {
          console.error('Translations index mismatch');
          return false;
        }
      }
    }
    return content;
  }
  updateAsset (content) {
    actions.resources.updateAsset(
      this.props.asset.uid,
      {content: JSON.stringify(content)}
    );
  }
  renderEmptyMessage() {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          <bem.FormView__cell>
            {t('There is nothing to translate in this form.')}
          </bem.FormView__cell>
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  renderTranslationsSettings(translations) {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          {(translations && translations[0] === null) ?
            <bem.FormView__cell m='translation-note'>
              {t('Here you can add one more more languages to your project, and translate the strings in each language.')}

                {t('Note: make sure your default language has a name. If it doesn\'t, you will not be able to edit your form in the form builder.')}

            </bem.FormView__cell>
            :
            <bem.FormView__cell m='label'>
              {t('Current languages')}
            </bem.FormView__cell>
          }
          {translations.map((l, i)=> {
            return (
              <React.Fragment key={`lang-${i}`}>
                <bem.FormView__cell m='translation'>
                  <bem.FormView__cell>
                    {l ? l : t('Unnamed language')}
                    {i === 0 ? ` ${t('default')}` : ''}
                  </bem.FormView__cell>
                  <bem.FormView__cell m='translation-actions'>
                    <bem.FormView__link m='rename'
                                        onClick={this.toggleRenameLanguageForm}
                                        data-index={i}
                                        data-tip={t('Edit language')}>

                    </bem.FormView__link>
                    {i > 0 &&
                      <bem.FormView__link m='translate'
                                          data-index={i}
                                          onClick={this.launchTranslationTableModal}
                                          data-tip={t('Update translations')}>

                      </bem.FormView__link>
                    }
                    {i > 0 &&
                      <bem.FormView__link m='translate'
                                          onClick={this.deleteLanguage}
                                          data-index={i}
                                          data-tip={t('Delete language')}>

                      </bem.FormView__link>
                    }
                  </bem.FormView__cell>
                </bem.FormView__cell>
                {this.state.renameLanguageIndex === i &&
                  <bem.FormView__cell m='update-language-form'>
                    <LanguageForm langString={l} langIndex={i} addOrUpdateLanguage={this.addOrUpdateLanguage}/>
                  </bem.FormView__cell>
                }
              </React.Fragment>
            );
          })}
          {!this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language'>
              <button className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
                      onClick={this.showAddLanguageForm}>
                {t('Add language')}
              </button>
            </bem.FormView__cell>
          }
          {this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language-form'>
              <bem.FormView__link m='close' onClick={this.hideAddLanguageForm}>

              </bem.FormView__link>
              <bem.FormView__cell m='label'>
                {t('Add a new language')}
              </bem.FormView__cell>
              <LanguageForm addOrUpdateLanguage={this.addOrUpdateLanguage}/>
            </bem.FormView__cell>
          }
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  render () {
    let translations = this.state.translations;
    if (translations.length === 0) {
      return this.renderEmptyMessage();
    } else {
      return this.renderTranslationsSettings(translations);
    }
  }
};

reactMixin(TranslationSettings.prototype, Reflux.ListenerMixin);

export default TranslationSettings;
<|endoftext|>