<commit_before>var objLinkList = [
            { href: "#blogs", linkText: "Blogs" },
            { href: "#herramientas", linkText: "Herramientas" }
        ];
var objBlogs =  [
    {
        url: "https://css-tricks.com/",
        linkText: "css-tricks",
        text: "Indudablemente una de las webs número uno de consulta para un frontend. Artículos y tutoriales de calidad y un buen número de snippets."
    },
    {
        url: "https://www.smashingmagazine.com/",
        linkText: "Smashing Magazine",
        text: "Todo un referente en el mundo de la web. Código, diseño, mobile, UX ... etc. Publican libros con colecciones de sus artículos más interesantes."
    },
    {
        url: "https://www.sitepoint.com/",
        linkText: "Site Point",
        text: "Artículos meticulosos de gran calidad, podcast, libros y cursos (a veces gratis). También imprescindible."
    },
    {
        url: "https://scotch.io/",
        linkText: "Scotch.io",
        text: "Tutoriales excelentes sobre el mundo frontend y backend javascript. Disponen de cursos free y premium. ¡¡No perdérselo!!"
    },
    {
        url: "https://davidwalsh.name/",
        linkText: "David Walsh Blog",
        text: "log del gurú JavaScript David Walsh. Conviene seguirle y leer sus interesantes artículos. No solo habla de JavaScript, también aborda otras tecnologías web."
    },
    {
        url: "http://alistapart.com/articles",
        linkText: "A List Apart",
        text: "Artículos de todo lo relacionado con la web. Son artículos de una calidad tan extraordinaria que algunos son un referente."
    },
    {
        url: "https://webmasters.googleblog.com/",
        linkText: "Google Webmaster Blog",
        text: "No puede faltar el blog oficial de Google para webmasters."
    },
    {
        url: "http://lea.verou.me/",
        linkText: "Lea Verou",
        text: "La gran Lea Verou. Proyectos, charlas, artículos. Una eminencia en el CSS."
    },
    {
        url: "http://wesbos.com/blog/",
        linkText: "Web Bos",
        text: "Artículos, videos y tutoriales"
    },
    {
        url: "http://www.developerdrive.com/",
        linkText: "Developer Drive",
        text: "Artículos sobre todo tipo de tecnología de desarrollo web."
    },
    {
        url: "http://www.cssportal.com/",
        linkText: "CSS Portal",
        text: "Snippets, generadores y herramientas para desarrollar en CSS."
    },
    {
        url: "http://www.elmaquetadorweb.com/",
        linkText: "El maquetador web",
        text: "Excelente blog mantenido por Javi Luna y Pedro Marín donde nos cuentan muchos trucos en esto del CSS. Me encanta el nombre de maquetador, término en desuso hoy en día.  ;D"
    },
    {
        url: "https://toddmotto.com/",
        linkText: "Todd Motto",
        text: "Artículos y tutoriales sobre JavaScript, Angular y Typescript. Dispone de muy buenos cursos en premium."
    },
    {
        url: "http://valhead.com/blog/",
        linkText: "Val Head Blog",
        text: "Artículos y tutoriales de una especialista en animaciones CSS web."
    },
    {
        url: "https://codyhouse.co/",
        linkText: "Cody House",
        text: "Colecciones gratuitas de snippets de HTML, CSS y JavaScript. También disponen de cursos premium."
    },
    {
        url: "http://www.kylejlarson.com/blog/ ",
        linkText: "kyle J. Larson",
        text: "Buenos consejos para el diseño web."
    },
    {
        url: "http://www.naderdabit.me/#/",
        linkText: "Nader Dabit",
        text: "Tutoriales sobre ReactJS, Angular, NPM ."
    },
    {
        url: "http://mrbool.com/",
        linkText: "Mr. Bool",
        text: "Tutoriales y cursos. ES6, Node+NPM, Ionic, Angular, NoSQL."
    },
    {
        url: "http://www.marketingenredes.com/",
        linkText: "Marketing en redes",
        text: "Sin unos buenos consejos como estos de marketing digital, no somos nadie."
    }
];

var objHerramientas =  [
    {
        url: "https://github.com/",
        linkText: "github",
        text: "Web que permite tener subidos tus repositorios git y así poder trabajar de forma colaborativa. Tiene versión Premiun con muchas mejoras. Dispone de las github-pages que te permiten desplegar webs estáticas incluso en la versión gratuita."
    },
    {
        url: "https://www.gitignore.io/",
        linkText: "gitignore",
        text: "Tras git init suele ser habitual crear un gitignore para configurar qué se debe ignorar en el historial. Esta aplicación nos ayudará mucho en esa tarea. Hay que indicarle qué tecnologías estamos usando y gitignore hace el resto."
    },
    {
        url: "http://web-dev.tools/",
        linkText: "Web Dev Tools",
        text: "Tres herramientas que te permiten generar tu propio framework CSS. Son, como si se tratase de los 3 mosqueteros, Gridifier, Typographier y Modulifier. Ideales para proyectos donde quieras ir con el menor peso posible."
    },
    {
        url: "http://www.regexr.com/",
        linkText: "Regexr",
        text: "Nos permite crear y probar en tiempo real expresiones regulares. Muy útil cuando ya estamos desesperados de buscar algo en stackoverflow y no damos con ello."
    },
    {
        url: "http://pxtoem.com/",
        linkText: "pxtoem",
        text: "Conversor de pixel a em y de em a pixel. Muy útil cuando recibimos diseños gráficos hechos en pixeles."
    },
    {
        url: "http://currentmillis.com/",
        linkText: "currentmillis",
        text: "¿Problemas con UTC time, local time, Epoch, Unix timestamp? Esta web te ayudará con ello."
    },
    {
        url: "http://bradfrost.github.io/this-is-responsive/patterns.html",
        linkText: "Plantillas responsive",
        text: "Sirven como boilerplates de una página, proyecto o landing page. No hay que redescubrir la rueda todos los días."
    },
    {
        url: "https://www.w3schools.com/colors/colors_converter.asp",
        linkText: "Convertidor códigos color",
        text: "Convierte todo tipo de códigos: RGB, Hex, HSL, CMYK y por nombre."
    },
    {
        url: "http://www.colorzilla.com/gradient-editor/",
        linkText: "ColorZilla Gradient Generator",
        text: "Herramienta para generar gradientes CSS. Se incluye soporte para IE9."
    },
    {
        url: "http://jeremyckahn.github.io/stylie/",
        linkText: "Stylie",
        text: "Una forma de ajustar tus animaciones CSS de forma visual sencilla."
    },
    {
        url: "http://www.tablesgenerator.com/",
        linkText: "Table generator",
        text: "Generador de tablas LaTex, HTML, Text tables, Markdown tables."
    },
    {
        url: "http://www.cssarrowplease.com/",
        linkText: "CSS arrow please",
        text: "Puedes configurar paneles con flecha, variando el tamaño y la posición de esta. Te da el código CSS para que llevártelo."
    },
    {
        url: "https://pixlr.com/",
        linkText: "Pixlr",
        text: "Una versión light y free de Photoshop online."
    },
    {
        url: "https://icomoon.io/",
        linkText: "Icomoon",
        text: "De las mejores herramientas para generar glifos para tu proyecto. Es modo freemium. Para cuando necesites algo más personalizado de Awesomefont."
    },
    {
        url: "http://lorempixel.com/",
        linkText: "Lorempixel",
        text: "Mientras recibimos las imágenes definitivas y estamos realizando ya la demo en paralelo, esta herramienta nos coloca una imagen al azar cada vez que la llamamos. Se pueden ajustar distintos parámetros como el tamaño y el tema. Creo que el nombre de lorempixel es bastante descriptivo ;)"
    },
    {
        url: "http://www.patternify.com/",
        linkText: "Patternify",
        text: "Generador para patrones de  CSS, ideal para lo que se conoce como grecas. Nos da la imagen en código Base 64."
    },
    {
        url: "https://coolors.co/",
        linkText: "Coolors",
        text: "Generador de paletas, 5 colores. Presenta un apartado para ver cómo se distingue tu paleta con distintas discapacidades."
    }
];

var siteNavigation = new Vue({
    el: "#site-navigation",
    data: {
        linkList: objLinkList
    }
});
var blogs = new Vue({
    el: '#blogs',
    data: {
        sectionTitle: "Blogs",
        aryBlogs: objBlogs
    },
    mounted: function () {
       console.log("blogs is now rendered");
    }
});
var herramientas = new Vue({
    el: '#herramientas',
    data: {
        sectionTitle: "Herramientas",
        aryHerramientas: objHerramientas
    },
    mounted: function () {
       console.log("herramientas is now rendered");
    }
});
var footer = new Vue({
  el: '#footer',
  data: {
    copyright: 'Copyright © ' + new Date().getFullYear() + ' Aitor Alejandro Herrera. MIT License'
  }
});
<commit_msg>gravit<commit_after>var objLinkList = [
            { href: "#blogs", linkText: "Blogs" },
            { href: "#herramientas", linkText: "Herramientas" }
        ];
var objBlogs =  [
    {
        url: "https://css-tricks.com/",
        linkText: "css-tricks",
        text: "Indudablemente una de las webs número uno de consulta para un frontend. Artículos y tutoriales de calidad y un buen número de snippets."
    },
    {
        url: "https://www.smashingmagazine.com/",
        linkText: "Smashing Magazine",
        text: "Todo un referente en el mundo de la web. Código, diseño, mobile, UX ... etc. Publican libros con colecciones de sus artículos más interesantes."
    },
    {
        url: "https://www.sitepoint.com/",
        linkText: "Site Point",
        text: "Artículos meticulosos de gran calidad, podcast, libros y cursos (a veces gratis). También imprescindible."
    },
    {
        url: "https://scotch.io/",
        linkText: "Scotch.io",
        text: "Tutoriales excelentes sobre el mundo frontend y backend javascript. Disponen de cursos free y premium. ¡¡No perdérselo!!"
    },
    {
        url: "https://davidwalsh.name/",
        linkText: "David Walsh Blog",
        text: "log del gurú JavaScript David Walsh. Conviene seguirle y leer sus interesantes artículos. No solo habla de JavaScript, también aborda otras tecnologías web."
    },
    {
        url: "http://alistapart.com/articles",
        linkText: "A List Apart",
        text: "Artículos de todo lo relacionado con la web. Son artículos de una calidad tan extraordinaria que algunos son un referente."
    },
    {
        url: "https://webmasters.googleblog.com/",
        linkText: "Google Webmaster Blog",
        text: "No puede faltar el blog oficial de Google para webmasters."
    },
    {
        url: "http://lea.verou.me/",
        linkText: "Lea Verou",
        text: "La gran Lea Verou. Proyectos, charlas, artículos. Una eminencia en el CSS."
    },
    {
        url: "http://wesbos.com/blog/",
        linkText: "Web Bos",
        text: "Artículos, videos y tutoriales"
    },
    {
        url: "http://www.developerdrive.com/",
        linkText: "Developer Drive",
        text: "Artículos sobre todo tipo de tecnología de desarrollo web."
    },
    {
        url: "http://www.cssportal.com/",
        linkText: "CSS Portal",
        text: "Snippets, generadores y herramientas para desarrollar en CSS."
    },
    {
        url: "http://www.elmaquetadorweb.com/",
        linkText: "El maquetador web",
        text: "Excelente blog mantenido por Javi Luna y Pedro Marín donde nos cuentan muchos trucos en esto del CSS. Me encanta el nombre de maquetador, término en desuso hoy en día.  ;D"
    },
    {
        url: "https://toddmotto.com/",
        linkText: "Todd Motto",
        text: "Artículos y tutoriales sobre JavaScript, Angular y Typescript. Dispone de muy buenos cursos en premium."
    },
    {
        url: "http://valhead.com/blog/",
        linkText: "Val Head Blog",
        text: "Artículos y tutoriales de una especialista en animaciones CSS web."
    },
    {
        url: "https://codyhouse.co/",
        linkText: "Cody House",
        text: "Colecciones gratuitas de snippets de HTML, CSS y JavaScript. También disponen de cursos premium."
    },
    {
        url: "http://www.kylejlarson.com/blog/ ",
        linkText: "kyle J. Larson",
        text: "Buenos consejos para el diseño web."
    },
    {
        url: "http://www.naderdabit.me/#/",
        linkText: "Nader Dabit",
        text: "Tutoriales sobre ReactJS, Angular, NPM ."
    },
    {
        url: "http://mrbool.com/",
        linkText: "Mr. Bool",
        text: "Tutoriales y cursos. ES6, Node+NPM, Ionic, Angular, NoSQL."
    },
    {
        url: "http://www.marketingenredes.com/",
        linkText: "Marketing en redes",
        text: "Sin unos buenos consejos como estos de marketing digital, no somos nadie."
    }
];

var objHerramientas =  [
    {
        url: "https://github.com/",
        linkText: "github",
        text: "Web que permite tener subidos tus repositorios git y así poder trabajar de forma colaborativa. Tiene versión Premiun con muchas mejoras. Dispone de las github-pages que te permiten desplegar webs estáticas incluso en la versión gratuita."
    },
    {
        url: "https://www.gitignore.io/",
        linkText: "gitignore",
        text: "Tras git init suele ser habitual crear un gitignore para configurar qué se debe ignorar en el historial. Esta aplicación nos ayudará mucho en esa tarea. Hay que indicarle qué tecnologías estamos usando y gitignore hace el resto."
    },
    {
        url: "http://web-dev.tools/",
        linkText: "Web Dev Tools",
        text: "Tres herramientas que te permiten generar tu propio framework CSS. Son, como si se tratase de los 3 mosqueteros, Gridifier, Typographier y Modulifier. Ideales para proyectos donde quieras ir con el menor peso posible."
    },
    {
        url: "http://www.regexr.com/",
        linkText: "Regexr",
        text: "Nos permite crear y probar en tiempo real expresiones regulares. Muy útil cuando ya estamos desesperados de buscar algo en stackoverflow y no damos con ello."
    },
    {
        url: "http://pxtoem.com/",
        linkText: "pxtoem",
        text: "Conversor de pixel a em y de em a pixel. Muy útil cuando recibimos diseños gráficos hechos en pixeles."
    },
    {
        url: "http://currentmillis.com/",
        linkText: "currentmillis",
        text: "¿Problemas con UTC time, local time, Epoch, Unix timestamp? Esta web te ayudará con ello."
    },
    {
        url: "http://bradfrost.github.io/this-is-responsive/patterns.html",
        linkText: "Plantillas responsive",
        text: "Sirven como boilerplates de una página, proyecto o landing page. No hay que redescubrir la rueda todos los días."
    },
    {
        url: "https://www.w3schools.com/colors/colors_converter.asp",
        linkText: "Convertidor códigos color",
        text: "Convierte todo tipo de códigos: RGB, Hex, HSL, CMYK y por nombre."
    },
    {
        url: "http://www.colorzilla.com/gradient-editor/",
        linkText: "ColorZilla Gradient Generator",
        text: "Herramienta para generar gradientes CSS. Se incluye soporte para IE9."
    },
    {
        url: "http://jeremyckahn.github.io/stylie/",
        linkText: "Stylie",
        text: "Una forma de ajustar tus animaciones CSS de forma visual sencilla."
    },
    {
        url: "http://www.tablesgenerator.com/",
        linkText: "Table generator",
        text: "Generador de tablas LaTex, HTML, Text tables, Markdown tables."
    },
    {
        url: "http://www.cssarrowplease.com/",
        linkText: "CSS arrow please",
        text: "Puedes configurar paneles con flecha, variando el tamaño y la posición de esta. Te da el código CSS para que llevártelo."
    },
    {
        url: "https://pixlr.com/",
        linkText: "Pixlr",
        text: "Una versión light y free de Photoshop online."
    },
    {
        url: "https://icomoon.io/",
        linkText: "Icomoon",
        text: "De las mejores herramientas para generar glifos para tu proyecto. Es modo freemium. Para cuando necesites algo más personalizado de Awesomefont."
    },
    {
        url: "http://lorempixel.com/",
        linkText: "Lorempixel",
        text: "Mientras recibimos las imágenes definitivas y estamos realizando ya la demo en paralelo, esta herramienta nos coloca una imagen al azar cada vez que la llamamos. Se pueden ajustar distintos parámetros como el tamaño y el tema. Creo que el nombre de lorempixel es bastante descriptivo ;)"
    },
    {
        url: "http://www.patternify.com/",
        linkText: "Patternify",
        text: "Generador para patrones de  CSS, ideal para lo que se conoce como grecas. Nos da la imagen en código Base 64."
    },
    {
        url: "https://coolors.co/",
        linkText: "Coolors",
        text: "Generador de paletas, 5 colores. Presenta un apartado para ver cómo se distingue tu paleta con distintas discapacidades."
    },
    {
        url: "https://gravit.io",
        linkText: "Gravit.io",
        text: "Herramienta de diseño gráfico. Una especie de Sketch online y gratuito."
    }
];

var siteNavigation = new Vue({
    el: "#site-navigation",
    data: {
        linkList: objLinkList
    }
});
var blogs = new Vue({
    el: '#blogs',
    data: {
        sectionTitle: "Blogs",
        aryBlogs: objBlogs
    },
    mounted: function () {
       console.log("blogs is now rendered");
    }
});
var herramientas = new Vue({
    el: '#herramientas',
    data: {
        sectionTitle: "Herramientas",
        aryHerramientas: objHerramientas
    },
    mounted: function () {
       console.log("herramientas is now rendered");
    }
});
var footer = new Vue({
  el: '#footer',
  data: {
    copyright: 'Copyright © ' + new Date().getFullYear() + ' Aitor Alejandro Herrera. MIT License'
  }
});
<|endoftext|>


<commit_before>(function (angular) {
  'use strict';

  var intakeApp = angular.module('intakeApp', ['LocalStorageModule']);

  if (!String.prototype.contains) {
    String.prototype.contains = function () {
      return String.prototype.indexOf.apply(this, arguments) !== -1;
    };
  }

  if (!String.prototype.slugify) {
    String.prototype.slugify = function () {
      return this.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
    };
  }

  intakeApp.factory('dataService', function (localStorageService) {
    var client = localStorageService.get('client') || {};
    return {
      getClient: function () {
        return client;
      },
      setClient: function (value) {
        client = value;
      }
    };
  });

  intakeApp.directive('import', function (dataService, localStorageService) {
    return {
      restrict: 'E',
      template: 'Import: <input type="file" name="import">',
      link: function (scope, elem) {
        elem.bind('change', function (e) {
          var file = e.target.files[0];
          var reader = new FileReader();

          reader.onloadend = function (evt) {
            var importData = JSON.parse(evt.target.result);

            localStorageService.add('client', importData.client);
            location.reload(true);
          };

          reader.readAsText(file);
        });
      }
    };
  });

  intakeApp.controller('IntakeHeader', function ($scope, dataService) {
    $scope.client = dataService.getClient();
    console.log();

    $scope.IntakeDownload = function () {
      var bundle = document.createElement('a');
      var prepare = {'client': $scope.client};
      bundle.href = window.URL.createObjectURL(new Blob([JSON.stringify(prepare)], { type: 'text/plain'}));
      bundle.download = $scope.client.name.slugify() + '--intake.txt';

      document.body.appendChild(bundle);
      bundle.click();
      document.body.removeChild(bundle);
    };
  });

  intakeApp.controller('IntakeClientName', function ($scope, dataService, localStorageService) {
    $scope.client = dataService.getClient();

    // Save Client info when client.name changes
    $scope.$watch('client.name', function () {
      localStorageService.add('client', $scope.client);
    });
  });

  intakeApp.filter('schemaTypeFilter', function () {
    return function (input, filterKey) {
      var filteredInput = {};

      if (filterKey === undefined) {
        return input;
      }

      var searchKeys = filterKey;
      if (typeof(searchKeys) === 'object') {
        searchKeys = Object.keys(searchKeys);
      }

      angular.forEach(input, function (value, key) {
        if (typeof(searchKeys) === 'string') {
          if (value.label && value.label.toLowerCase().contains(filterKey.toLowerCase())) {
            filteredInput[key] = value;
          }
        }
      });
      return filteredInput;
    };
  });

  intakeApp.controller('IntakeContentModelCtrl', function ($scope, $http, localStorageService) {

    function setScope(schema) {
      $scope.dataTypes = schema.datatypes;
      $scope.properties = schema.properties;
      $scope.types = schema.types;
    }

    var schema = localStorageService.get('schema');
    if (!schema) {
      $http.get('data/all.json').success(function (schema) {
        localStorageService.add('schema', schema);
        setScope(schema);
      });
    }
    else {
      setScope(schema);
    }
  });

})(window.angular);
<commit_msg>Custom Intake File Extension!<commit_after>(function (angular) {
  'use strict';

  var intakeApp = angular.module('intakeApp', ['LocalStorageModule']);

  if (!String.prototype.contains) {
    String.prototype.contains = function () {
      return String.prototype.indexOf.apply(this, arguments) !== -1;
    };
  }

  if (!String.prototype.slugify) {
    String.prototype.slugify = function () {
      return this.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
    };
  }

  intakeApp.factory('dataService', function (localStorageService) {
    var client = localStorageService.get('client') || {};
    return {
      getClient: function () {
        return client;
      },
      setClient: function (value) {
        client = value;
      }
    };
  });

  intakeApp.directive('import', function (dataService, localStorageService) {
    return {
      restrict: 'E',
      template: 'Import: <input type="file" name="import">',
      link: function (scope, elem) {
        elem.bind('change', function (e) {
          var file = e.target.files[0];
          var reader = new FileReader();

          reader.onloadend = function (evt) {
            var importData = JSON.parse(evt.target.result);

            localStorageService.add('client', importData.client);
            location.reload(true);
          };

          reader.readAsText(file);
        });
      }
    };
  });

  intakeApp.controller('IntakeHeader', function ($scope, dataService) {
    $scope.client = dataService.getClient();
    console.log();

    $scope.IntakeDownload = function () {
      var bundle = document.createElement('a');
      var prepare = {'client': $scope.client};
      bundle.href = window.URL.createObjectURL(new Blob([JSON.stringify(prepare)], { type: 'text/plain'}));
      bundle.download = $scope.client.name.slugify() + '.intake';

      document.body.appendChild(bundle);
      bundle.click();
      document.body.removeChild(bundle);
    };
  });

  intakeApp.controller('IntakeClientName', function ($scope, dataService, localStorageService) {
    $scope.client = dataService.getClient();

    // Save Client info when client.name changes
    $scope.$watch('client.name', function () {
      localStorageService.add('client', $scope.client);
    });
  });

  intakeApp.filter('schemaTypeFilter', function () {
    return function (input, filterKey) {
      var filteredInput = {};

      if (filterKey === undefined) {
        return input;
      }

      var searchKeys = filterKey;
      if (typeof(searchKeys) === 'object') {
        searchKeys = Object.keys(searchKeys);
      }

      angular.forEach(input, function (value, key) {
        if (typeof(searchKeys) === 'string') {
          if (value.label && value.label.toLowerCase().contains(filterKey.toLowerCase())) {
            filteredInput[key] = value;
          }
        }
      });
      return filteredInput;
    };
  });

  intakeApp.controller('IntakeContentModelCtrl', function ($scope, $http, localStorageService) {

    function setScope(schema) {
      $scope.dataTypes = schema.datatypes;
      $scope.properties = schema.properties;
      $scope.types = schema.types;
    }

    var schema = localStorageService.get('schema');
    if (!schema) {
      $http.get('data/all.json').success(function (schema) {
        localStorageService.add('schema', schema);
        setScope(schema);
      });
    }
    else {
      setScope(schema);
    }
  });

})(window.angular);
<|endoftext|>


<commit_before>const Sign = {
  POWER: '^',
  ADDITION: '+',
  SUBTRACTION: '-',
  DIVISION: '/',
  MULTIPLICATION: '*',
}

Array.prototype.isEmpty = function() {
  return this.length === 0
}

Array.prototype.top = function() {
  return this[this.length - 1]
}

function Infix2Postifx(exp) {
  this.exp = exp
  this.result = ''
}

Infix2Postifx.prototype.hasGreaterPriority = function(oprtr1, oprtr2) {
  return this.getPriority(oprtr1) >= this.getPriority(oprtr2)
}

Infix2Postifx.prototype.getPriority = function(oprtr) {
  switch (oprtr) {
    case Sign.POWER:
      return 4
    case Sign.MULTIPLICATION:
    case Sign.DIVISION:
      return 3
    case Sign.SUBTRACTION:
    case Sign.ADDITION:
      return 2
    default:
      return -1
  }
}

Infix2Postifx.prototype.isOperand = function(item) {
  return /\d/.test(item)
}

Infix2Postifx.prototype.isOperator = function(item) {
  switch (item) {
    case Sign.ADDITION:
    case Sign.SUBTRACTION:
    case Sign.MULTIPLICATION:
    case Sign.DIVISION:
    case Sign.POWER:
      return true
    default:
      return false
  }
}

Infix2Postifx.prototype.isOpeningParentheses = function(item) {
  return item == '('
}

Infix2Postifx.prototype.isClosingParentheses = function(item) {
  return item == ')'
}

Infix2Postifx.prototype.toPostfix = function() {
  let stack = []
  const arr = this.exp
  const len = arr.length

  for (let i = 0; i < len; i++) {
    const item = arr[i]
    const left = arr[i - 1]

    if (this.isOperand(item)) {
      this.result += item + ' '
    } else if (this.isOperator(item)) {
      while (
        !stack.isEmpty() &&
        this.hasGreaterPriority(stack.top(), item) &&
        !this.isOpeningParentheses(stack.top())
      ) {
        this.result += stack.pop() + ' '
      }

      stack.push(item)
    } else if (this.isOpeningParentheses(item)) {
      stack.push(item)
    } else if (this.isClosingParentheses(item)) {
      while (!stack.isEmpty() && !this.isOpeningParentheses(stack.top())) {
        this.result += stack.pop() + ' '
      }

      stack.pop()
    }
  } // End of for loop

  while (!stack.isEmpty()) {
    this.result += stack.pop() + ' '
  }

  return this.result
}

function CalculatePostfix(postFix) {
  this.postFix = postFix.split(' ')
  this.result = ''
}

CalculatePostfix.prototype.calculate = function() {
  let stack = []
  let _flag = false
  const len = this.postFix.length

  for (let i = 0; i < len; i++) {
    const item = this.postFix[i]
    const next = this.postFix[i + 1]

    if (this.isOperator(item)) {
      while (!stack.isEmpty()) {
        if (stack.length !== 1) {
          const operand1 = stack.pop()
          const operand2 = stack.pop()

          if (item == Sign.POWER) {
            let tmp = this.solvePower(operand2, operand1)

            if (operand1 < 0) tmp = 1 / tmp

            this.result = tmp
          } else {
            this.result = eval(`${operand2} ${item} ${operand1}`)
          }
        } else {
          if (item === Sign.SUBTRACTION && /\d/.test(next)) _flag = true

          if (item === Sign.SUBTRACTION) {
            const operand = stack.pop()
            this.result = eval(`${item}(${operand})`)
          }
        }

        stack.push(this.result)

        break
      }
    } else {
      stack.push(item)
    }
  }

  return _flag ? this.result * -1 : this.result
}

CalculatePostfix.prototype.isOperator = Infix2Postifx.prototype.isOperator

CalculatePostfix.prototype.solvePower = function(base, exp) {
  let result = 1
  exp = Math.abs(exp)

  if (exp == 0) {
    return result
  } else if (exp & 1) {
    return (result = base * this.solvePower(base, exp - 1))
  } else {
    const tmp = this.solvePower(base, exp / 2)
    return (result = tmp * tmp)
  }
}
<commit_msg>not being used<commit_after>const Sign = {
  POWER: '^',
  ADDITION: '+',
  SUBTRACTION: '-',
  DIVISION: '/',
  MULTIPLICATION: '*',
}

Array.prototype.isEmpty = function() {
  return this.length === 0
}

Array.prototype.top = function() {
  return this[this.length - 1]
}

function Infix2Postifx(exp) {
  this.exp = exp
  this.result = ''
}

Infix2Postifx.prototype.hasGreaterPriority = function(oprtr1, oprtr2) {
  return this.getPriority(oprtr1) >= this.getPriority(oprtr2)
}

Infix2Postifx.prototype.getPriority = function(oprtr) {
  switch (oprtr) {
    case Sign.POWER:
      return 4
    case Sign.MULTIPLICATION:
    case Sign.DIVISION:
      return 3
    case Sign.SUBTRACTION:
    case Sign.ADDITION:
      return 2
    default:
      return -1
  }
}

Infix2Postifx.prototype.isOperand = function(item) {
  return /\d/.test(item)
}

Infix2Postifx.prototype.isOperator = function(item) {
  switch (item) {
    case Sign.ADDITION:
    case Sign.SUBTRACTION:
    case Sign.MULTIPLICATION:
    case Sign.DIVISION:
    case Sign.POWER:
      return true
    default:
      return false
  }
}

Infix2Postifx.prototype.isOpeningParentheses = function(item) {
  return item == '('
}

Infix2Postifx.prototype.isClosingParentheses = function(item) {
  return item == ')'
}

Infix2Postifx.prototype.toPostfix = function() {
  let stack = []
  const arr = this.exp
  const len = arr.length

  for (let i = 0; i < len; i++) {
    const item = arr[i]

    if (this.isOperand(item)) {
      this.result += item + ' '
    } else if (this.isOperator(item)) {
      while (
        !stack.isEmpty() &&
        this.hasGreaterPriority(stack.top(), item) &&
        !this.isOpeningParentheses(stack.top())
      ) {
        this.result += stack.pop() + ' '
      }

      stack.push(item)
    } else if (this.isOpeningParentheses(item)) {
      stack.push(item)
    } else if (this.isClosingParentheses(item)) {
      while (!stack.isEmpty() && !this.isOpeningParentheses(stack.top())) {
        this.result += stack.pop() + ' '
      }

      stack.pop()
    }
  } // End of for loop

  while (!stack.isEmpty()) {
    this.result += stack.pop() + ' '
  }

  return this.result
}

function CalculatePostfix(postFix) {
  this.postFix = postFix.split(' ')
  this.result = ''
}

CalculatePostfix.prototype.calculate = function() {
  let stack = []
  let _flag = false
  const len = this.postFix.length

  for (let i = 0; i < len; i++) {
    const item = this.postFix[i]
    const next = this.postFix[i + 1]

    if (this.isOperator(item)) {
      while (!stack.isEmpty()) {
        if (stack.length !== 1) {
          const operand1 = stack.pop()
          const operand2 = stack.pop()

          if (item == Sign.POWER) {
            let tmp = this.solvePower(operand2, operand1)

            if (operand1 < 0) tmp = 1 / tmp

            this.result = tmp
          } else {
            this.result = eval(`${operand2} ${item} ${operand1}`)
          }
        } else {
          if (item === Sign.SUBTRACTION && /\d/.test(next)) _flag = true

          if (item === Sign.SUBTRACTION) {
            const operand = stack.pop()
            this.result = eval(`${item}(${operand})`)
          }
        }

        stack.push(this.result)

        break
      }
    } else {
      stack.push(item)
    }
  }

  return _flag ? this.result * -1 : this.result
}

CalculatePostfix.prototype.isOperator = Infix2Postifx.prototype.isOperator

CalculatePostfix.prototype.solvePower = function(base, exp) {
  let result = 1
  exp = Math.abs(exp)

  if (exp == 0) {
    return result
  } else if (exp & 1) {
    return (result = base * this.solvePower(base, exp - 1))
  } else {
    const tmp = this.solvePower(base, exp / 2)
    return (result = tmp * tmp)
  }
}
<|endoftext|>


<commit_before>angular.module('martina', ['ui.router', 'controllers', 'services'])

.config(function ($stateProvider, $urlRouterProvider) {

  $stateProvider

  .state('gallery', {
    url: '/gallery',
    views: {
      'nav': {
        templateUrl: 'partials/nav.html',
        controller: 'NavCtrl'
      },
      'content': {
        templateUrl: 'partials/gallery.html',
        controller: 'GalleryCtrl',
        resolve: {
          json: ["$http", function ($http) {
            return $http({url: "data/gallery.json"}).success(function (data) {
              return data
            })
          }]
        }
      }
    }
  })

  .state('about', {
    url: '/about',
    views: {
      'nav': {
        templateUrl: 'partials/nav.html',
        controller: 'NavCtrl'
      },
      'content': {
        templateUrl: 'partials/about.html',
        controller: 'AboutCtrl',
      }
    }
  })

  .state('contact', {
    url: '/contact',
    views: {
      'nav': {
        templateUrl: 'partials/nav.html',
        controller: 'NavCtrl'
      },
      'content': {
        templateUrl: 'partials/contact.html',
        controller: 'ContactCtrl'
      }
    }
  })

  $urlRouterProvider.otherwise('/gallery')

});
<commit_msg>Added json data resolve to about pages<commit_after>angular.module('martina', ['ui.router', 'controllers', 'services'])

.config(function ($stateProvider, $urlRouterProvider) {

  $stateProvider

  .state('gallery', {
    url: '/gallery',
    views: {
      'nav': {
        templateUrl: 'partials/nav.html',
        controller: 'NavCtrl'
      },
      'content': {
        templateUrl: 'partials/gallery.html',
        controller: 'GalleryCtrl',
        resolve: {
          json: ["$http", function ($http) {
            return $http({url: "data/gallery.json"}).success(function (data) {
              return data
            })
          }]
        }
      }
    }
  })

  .state('about', {
    url: '/about',
    views: {
      'nav': {
        templateUrl: 'partials/nav.html',
        controller: 'NavCtrl'
      },
      'content': {
        templateUrl: 'partials/about.html',
        controller: 'AboutCtrl',
        resolve: {
          json: ["$http", function ($http) {
            return $http({url: "data/about.json"}).success(function (data) {
              return data
            })
          }]
        }
      }
    }
  })

  .state('contact', {
    url: '/contact',
    views: {
      'nav': {
        templateUrl: 'partials/nav.html',
        controller: 'NavCtrl'
      },
      'content': {
        templateUrl: 'partials/contact.html',
        controller: 'ContactCtrl'
      }
    }
  })

  $urlRouterProvider.otherwise('/gallery')

});
<|endoftext|>


<commit_before>const debug = require("debug")("contract:contract"); // eslint-disable-line no-unused-vars
let Web3 = require("web3");
const webUtils = require("web3-utils");
const execute = require("./execute");
const {
  bootstrap,
  constructorMethods,
  properties
} = require("./contract/index");

// For browserified version. If browserify gave us an empty version,
// look for the one provided by the user.
if (typeof Web3 === "object" && Object.keys(Web3).length === 0) {
  Web3 = global.Web3;
}

(function(module) {
  // Accepts a contract object created with web3.eth.Contract or an address.
  function Contract(contract) {
    var instance = this;
    var constructor = instance.constructor;

    // Disambiguate between .at() and .new()
    if (typeof contract === "string") {
      var web3Instance = new constructor.web3.eth.Contract(constructor.abi);
      web3Instance.options.address = contract;
      contract = web3Instance;
    }

    // Core:
    instance.methods = {};
    instance.abi = constructor.abi;
    instance.address = contract.options.address;
    instance.transactionHash = contract.transactionHash;
    instance.contract = contract;

    // User defined methods, overloaded methods, events
    instance.abi.forEach(function(item) {
      switch (item.type) {
        case "function":
          var isConstant =
            ["pure", "view"].includes(item.stateMutability) || item.constant; // new form // deprecated case

          var signature = webUtils._jsonInterfaceMethodToString(item);

          var method = function(constant, web3Method) {
            var fn;

            constant
              ? (fn = execute.call.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ))
              : (fn = execute.send.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ));

            fn.call = execute.call.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.sendTransaction = execute.send.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.estimateGas = execute.estimate.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.request = execute.request.call(
              constructor,
              web3Method,
              item,
              instance.address
            );

            return fn;
          };

          // Only define methods once. Any overloaded methods will have all their
          // accessors available by ABI signature available on the `methods` key below.
          if (instance[item.name] === undefined) {
            instance[item.name] = method(
              isConstant,
              contract.methods[item.name]
            );
          }

          // Overloaded methods should be invoked via the .methods property
          instance.methods[signature] = method(
            isConstant,
            contract.methods[signature]
          );
          break;

        case "event":
          instance[item.name] = execute.event.call(
            constructor,
            contract.events[item.name]
          );
          break;
      }
    });

    // sendTransaction / send
    instance.sendTransaction = execute.send.call(
      constructor,
      null,
      null,
      instance.address
    );

    // Prefer user defined `send`
    if (!instance.send) {
      instance.send = (value, txParams = {}) => {
        const packet = Object.assign({ value: value }, txParams);
        return instance.sendTransaction(packet);
      };
    }

    // Other events
    instance.allEvents = execute.allEvents.call(constructor, contract);
    instance.getPastEvents = execute.getPastEvents.call(constructor, contract);
  }

  Contract._constructorMethods = constructorMethods(Contract);

  // Getter functions are scoped to Contract object.
  Contract._properties = properties;

  bootstrap(Contract);
  module.exports = Contract;

  return Contract;
})(module || {});
<commit_msg>rm old web3 Contract at/deployed logic (contract/lib/contract)<commit_after>const debug = require("debug")("contract:contract"); // eslint-disable-line no-unused-vars
let Web3 = require("web3");
const webUtils = require("web3-utils");
const execute = require("./execute");
const {
  bootstrap,
  constructorMethods,
  properties
} = require("./contract/index");

// For browserified version. If browserify gave us an empty version,
// look for the one provided by the user.
if (typeof Web3 === "object" && Object.keys(Web3).length === 0) {
  Web3 = global.Web3;
}

(function(module) {
  // Accepts a contract object created with web3.eth.Contract or an address.
  function Contract(contract) {
    var instance = this;
    var constructor = instance.constructor;

    // Core:
    instance.methods = {};
    instance.abi = constructor.abi;
    instance.address = contract.options.address;
    instance.transactionHash = contract.transactionHash;
    instance.contract = contract;

    // User defined methods, overloaded methods, events
    instance.abi.forEach(function(item) {
      switch (item.type) {
        case "function":
          var isConstant =
            ["pure", "view"].includes(item.stateMutability) || item.constant; // new form // deprecated case

          var signature = webUtils._jsonInterfaceMethodToString(item);

          var method = function(constant, web3Method) {
            var fn;

            constant
              ? (fn = execute.call.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ))
              : (fn = execute.send.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ));

            fn.call = execute.call.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.sendTransaction = execute.send.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.estimateGas = execute.estimate.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.request = execute.request.call(
              constructor,
              web3Method,
              item,
              instance.address
            );

            return fn;
          };

          // Only define methods once. Any overloaded methods will have all their
          // accessors available by ABI signature available on the `methods` key below.
          if (instance[item.name] === undefined) {
            instance[item.name] = method(
              isConstant,
              contract.methods[item.name]
            );
          }

          // Overloaded methods should be invoked via the .methods property
          instance.methods[signature] = method(
            isConstant,
            contract.methods[signature]
          );
          break;

        case "event":
          instance[item.name] = execute.event.call(
            constructor,
            contract.events[item.name]
          );
          break;
      }
    });

    // sendTransaction / send
    instance.sendTransaction = execute.send.call(
      constructor,
      null,
      null,
      instance.address
    );

    // Prefer user defined `send`
    if (!instance.send) {
      instance.send = (value, txParams = {}) => {
        const packet = Object.assign({ value: value }, txParams);
        return instance.sendTransaction(packet);
      };
    }

    // Other events
    instance.allEvents = execute.allEvents.call(constructor, contract);
    instance.getPastEvents = execute.getPastEvents.call(constructor, contract);
  }

  Contract._constructorMethods = constructorMethods(Contract);

  // Getter functions are scoped to Contract object.
  Contract._properties = properties;

  bootstrap(Contract);
  module.exports = Contract;

  return Contract;
})(module || {});
<|endoftext|>


<commit_before>/*
 * jQuery File Upload Plugin Angular JS Example 1.2.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2013, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* jshint nomen:false */
/* global window, angular */

(function () {
    'use strict';

    var isOnGitHub = window.location.hostname === 'blueimp.github.io',
        url = isOnGitHub ? '//jquery-file-upload.appspot.com/' : 'server/php/';

    angular.module('demo', [
        'blueimp.fileupload'
    ])
        .config([
            '$httpProvider', 'fileUploadProvider',
            function ($httpProvider, fileUploadProvider) {
                delete $httpProvider.defaults.headers.common['X-Requested-With'];
                fileUploadProvider.defaults.redirect = window.location.href.replace(
                    /\/[^\/]*$/,
                    '/cors/result.html?%s'
                );
                if (isOnGitHub) {
                    // Demo settings:
                    angular.extend(fileUploadProvider.defaults, {
                        // Enable image resizing, except for Android and Opera,
                        // which actually support image resizing, but fail to
                        // send Blob objects via XHR requests:
                        disableImageResize: /Android(?!.*Chrome)|Opera/
                            .test(window.navigator.userAgent),
                        maxFileSize: 5000000,
                        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
                    });
                }
            }
        ])

        .controller('DemoFileUploadController', [
            '$scope', '$http', '$filter', '$window',
            function ($scope, $http) {
                $scope.options = {
                    url: url
                };
                if (!isOnGitHub) {
                    $scope.loadingFiles = true;
                    $http.get(url)
                        .then(
                            function (response) {
                                $scope.loadingFiles = false;
                                $scope.queue = response.data.files || [];
                            },
                            function () {
                                $scope.loadingFiles = false;
                            }
                        );
                }
            }
        ])

        .controller('FileDestroyController', [
            '$scope', '$http',
            function ($scope, $http) {
                var file = $scope.file,
                    state;
                if (file.url) {
                    file.$state = function () {
                        return state;
                    };
                    file.$destroy = function () {
                        state = 'pending';
                        return $http({
                            url: file.deleteUrl,
                            method: file.deleteType
                        }).then(
                            function () {
                                state = 'resolved';
                                $scope.clear(file);
                            },
                            function () {
                                state = 'rejected';
                            }
                        );
                    };
                } else if (!file.$cancel && !file._index) {
                    file.$cancel = function () {
                        $scope.clear(file);
                    };
                }
            }
        ]);

}());
<commit_msg>emoved more unused JS<commit_after><|endoftext|>


<commit_before>import uri from './uri';
import DEFAULT_ADDONS from './addons/defaults';
import Response from './response';

function createURIs(routes, addons, parentData) {
  return routes.map(route => {
    // register the route with each addon
    const registerData = {};
    addons.forEach(addon => {
      const { name, register } = addon;
      registerData[name] = register(route, parentData[name]);
    });

    // the children need to be uris
    const children = route.children
      ? createURIs(route.children, addons, registerData)
      : [];

    // finally, create the uri
    return uri({ ...route, children });
  });
}

function createConfig(history, routes, addons = DEFAULT_ADDONS) {
  // the current uris to match against
  let uris = [];
  // the addons being used
  const globals = {};

  const setup = routes => {
    if (!Array.isArray(routes)) {
      routes = [routes];
    }

    const registerFunctions = [];
    // clear out the existing addons
    for (let key in globals) {
      delete globals[key];
    }
    // create the new addons
    addons.forEach(addonFactory => {
      const addon = addonFactory();
      globals[addon.name] = addon.get;
      registerFunctions.push(addon);
    });

    uris = createURIs(routes, registerFunctions, {});
  };

  let currentUpdate;

  /*
   * Build a Response object by iterating over the uris
   */
  const respond = () => {
    const { pathname, key } = history.location;
    currentUpdate = key;
    const resp = new Response(history.location);
    uris.some(uri => uri.match(pathname, resp));
    return resp;
  };

  /*
   * The response should not be emitted until any preload/load promises
   * have resolved.
   */
  const runURILoadFunctions = resp => {
    if (!resp.uri) {
      resp.setStatus(404);
      return Promise.resolve(resp);
    }
    const { preload, load } = resp.uri;
    return Promise.all([
      preload ? preload() : null,
      load ? load(resp) : null
    ]).then(
      () => {
        resp.call();
        return resp;
      },
      err => {
        // not sure what to do here yet
        return Promise.reject(err);
      }
    );
  };

  let lastUpdate;
  const prepareResponse = () => {
    const response = respond();
    return runURILoadFunctions(response).then(resp => {
      // save this for quick ref
      lastUpdate = resp.asObject();
      return lastUpdate;
    });
  };

  const subscribers = [];
  const subscribe = fn => {
    if (typeof fn !== 'function') {
      throw new Error('The argument passed to subscribe must be a function');
    }

    if (lastUpdate) {
      fn(lastUpdate);
    }

    const newLength = subscribers.push(fn);
    return () => {
      subscribers[newLength - 1] = null;
    };
  };

  const emit = response => {
    // don't emit old responses
    if (response.location.key !== currentUpdate) {
      return;
    }
    subscribers.forEach(fn => {
      if (fn != null) {
        fn(response);
      }
    });
  };

  setup(routes);
  const unlisten = history.listen(() => {
    prepareResponse().then(resp => {
      emit(resp);
    });
  });

  return {
    ready: () => {
      return lastUpdate ? Promise.resolve(lastUpdate) : prepareResponse()
    },
    refresh: setup,
    subscribe,
    addons: globals,
    history
  };
}

export default createConfig;
<commit_msg>Add a TODO note<commit_after>import uri from './uri';
import DEFAULT_ADDONS from './addons/defaults';
import Response from './response';

function createURIs(routes, addons, parentData) {
  return routes.map(route => {
    // register the route with each addon
    const registerData = {};
    addons.forEach(addon => {
      const { name, register } = addon;
      registerData[name] = register(route, parentData[name]);
    });

    // the children need to be uris
    const children = route.children
      ? createURIs(route.children, addons, registerData)
      : [];

    // finally, create the uri
    return uri({ ...route, children });
  });
}

function createConfig(history, routes, addons = DEFAULT_ADDONS) {
  // the current uris to match against
  let uris = [];
  // the addons being used
  const globals = {};

  const setup = routes => {
    if (!Array.isArray(routes)) {
      routes = [routes];
    }

    const registerFunctions = [];
    // clear out the existing addons
    for (let key in globals) {
      delete globals[key];
    }
    // create the new addons
    addons.forEach(addonFactory => {
      const addon = addonFactory();
      globals[addon.name] = addon.get;
      registerFunctions.push(addon);
    });

    uris = createURIs(routes, registerFunctions, {});
  };

  let currentUpdate;

  /*
   * Build a Response object by iterating over the uris
   */
  const respond = () => {
    const { pathname, key } = history.location;
    currentUpdate = key;
    const resp = new Response(history.location);
    uris.some(uri => uri.match(pathname, resp));
    return resp;
  };

  /*
   * The response should not be emitted until any preload/load promises
   * have resolved.
   */
  const runURILoadFunctions = resp => {
    if (!resp.uri) {
      resp.setStatus(404);
      return Promise.resolve(resp);
    }
    const { preload, load } = resp.uri;
    return Promise.all([
      preload ? preload() : null,
      load ? load(resp) : null
    ]).then(
      () => {
        resp.call();
        return resp;
      },
      err => {
        // not sure what to do here yet
        return Promise.reject(err);
      }
    );
  };

  let lastUpdate;
  const prepareResponse = () => {
    const response = respond();
    return runURILoadFunctions(response).then(resp => {
      // save this for quick ref
      lastUpdate = resp.asObject();
      return lastUpdate;
    });
  };

  const subscribers = [];
  const subscribe = fn => {
    if (typeof fn !== 'function') {
      throw new Error('The argument passed to subscribe must be a function');
    }

    if (lastUpdate) {
      fn(lastUpdate);
    }

    const newLength = subscribers.push(fn);
    return () => {
      subscribers[newLength - 1] = null;
    };
  };

  const emit = response => {
    // don't emit old responses
    // TODO: need to figure out a better solution for this because hash history
    // does not add a location.key (because it can have no state).
    if (response.location.key !== currentUpdate) {
      return;
    }
    subscribers.forEach(fn => {
      if (fn != null) {
        fn(response);
      }
    });
  };

  setup(routes);
  const unlisten = history.listen(() => {
    prepareResponse().then(resp => {
      emit(resp);
    });
  });

  return {
    ready: () => {
      return lastUpdate ? Promise.resolve(lastUpdate) : prepareResponse()
    },
    refresh: setup,
    subscribe,
    addons: globals,
    history
  };
}

export default createConfig;
<|endoftext|>


<commit_before>(function($)
{
  var router = new $.mobile.Router( [
   {"#page-authorize": {handler: "pageAuthorize",
         events: "s", // do when we show the page
         argsre: true
       } },

        {"#home": {handler: "home",
          events: "s", // do when we show the page
          argsre: true
        } },

        {"#listing": {handler: "listing",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#registering-ruleset": {handler: "registeringRuleset",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#confirming-deletion": {handler: "confirmingDeletion",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#updating-url": {handler: "updatingUrl",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#page-picologging": {handler: "picologging",
          events: "s", // do when we show the page
          argsre: true
        } }
        ],
        {
          pageAuthorize: function(type, match, ui, page) {
            console.log("manage fuse: authorize page");
            $.mobile.loading("hide");
          },

          home: function(type, match, ui, page) {
            console.log("home Handler");
          },

          listing: function(type, match, ui, page) {
            console.log("listing Handler");

              Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
              console.log(rids_json);

              //this is for a table
              /*
              var len = rids_json.length;
              var txt = "";
              if(len > 0){
                for(var i=0;i<len;i++){
                    txt += "
"+rids_json[i].rid+"	"+rids_json[i].uri+"	button
";

                  }
                if(txt !== ""){
                        $("#ruleset-list").html(txt);
                        $("#ruleset-list").listview('refresh');
                  }
                else{
                    $("#ruleset-list").html("
 NONE 	 NONE 	");
                    $("#ruleset-list").listview('refresh');
                }
              } */

              //trying for a list

              console.log("attempting rough listview");

             $.each(rids_json, function(key, value){
               $.each(value, function(key, value){
                  console.log(key, value);
                 });
              });

              var keys = rids_json.sort(sortBy("rid_index"));
              console.log("keys: " + keys);
              $.each(rids_json, paint_item);
            //  $.each(keys, paint_item);

              console.log("refreshing manage-list listview.")

              $('#manage-list').listview('refresh');
                });

          // document.getElementById("List-Rulesets").innerHTML = obj;

            /*var frm = "#ruleset-form";
            $(frm)[0].reset();
            var owner_eci = CloudOS.defaultECI; //from pageUpdateProfile

              $("#RID", frm).val(ruleset_obj.rid);
              $("#source-URL", frm).val(ruleset_obj.uri);*/

          },
          registeringRuleset: function(type, match, ui, page) {
            console.log("registering Ruleset Handler");
          },
          confirmingDeletion: function(type, match, ui, page) {
            console.log("confirming Deletion Handler");
          },
          updatingUrl: function(type, match, ui, page) {
            console.log("updating Url Handler");
          },
          picologging: function(type, match, ui, page) {
            console.log("pico logging page");
            $.mobile.loading("hide");
          }
        },
      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });
      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
        list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

    function onPageLoad() {// Document.Ready
    	console.log("document ready");
	CloudOS.retrieveSession();
	// only put static stuff here...
	plant_authorize_button();

	$('.logout').off("tap").on("tap", function(event)
	   {
	       CloudOS.removeSession(true); // true for hard reset (log out of login server too)
	       $.mobile.changePage('#page-authorize', {
		   transition: 'slide'
	       }); // this will go to the authorization page.
	   });

	console.log("Choose page to show");

	try {
	    var authd = CloudOS.authenticatedSession();
	    if(authd) {
		console.log("Authorized");
		document.location.hash = "#home";
	    } else {
		console.log("Asking for authorization");
		document.location.hash = "#page-authorize";
	    }
	} catch (exception) {

	} finally {
	    $.mobile.initializePage();
	    $.mobile.loading("hide");
	}

    };

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    $(document).bind("mobileinit", onMobileInit);
    $(document).ready(onPageLoad);
  })(jQuery);

    function sortBy(prop){
              return function(a,b){
            if( a[prop]  b[prop] ){
                return -1;
            }
            return 0;
              };
          };
    function paint_item(id, rids) {//(key,value)

          /*if (typeof vehicle === "undefined") {
        return;
          }*/
          var status = "no status"; // place holder for description
         console.log("in paint_item");
         console.log(id, rids);
         console.log("rid: "+ rids.rid);

        $("#manage-list li:nth-child(1)" ).after( //was #manage-fleet prior
            snippets.list_rulesets_template(
              {"rid": rids.rid,
               "uri": rids.uri,
               "description": status
              }));
    };

<commit_msg>paint<commit_after>(function($)
{
  var router = new $.mobile.Router( [
   {"#page-authorize": {handler: "pageAuthorize",
         events: "s", // do when we show the page
         argsre: true
       } },

        {"#home": {handler: "home",
          events: "s", // do when we show the page
          argsre: true
        } },

        {"#listing": {handler: "listing",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#registering-ruleset": {handler: "registeringRuleset",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#confirming-deletion": {handler: "confirmingDeletion",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#updating-url": {handler: "updatingUrl",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#page-picologging": {handler: "picologging",
          events: "s", // do when we show the page
          argsre: true
        } }
        ],
        {
          pageAuthorize: function(type, match, ui, page) {
            console.log("manage fuse: authorize page");
            $.mobile.loading("hide");
          },

          home: function(type, match, ui, page) {
            console.log("home Handler");
          },

          listing: function(type, match, ui, page) {
            console.log("listing Handler");

              Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
              console.log(rids_json);

              //this is for a table
              /*
              var len = rids_json.length;
              var txt = "";
              if(len > 0){
                for(var i=0;i<len;i++){
                    txt += "
"+rids_json[i].rid+"	"+rids_json[i].uri+"	button
";

                  }
                if(txt !== ""){
                        $("#ruleset-list").html(txt);
                        $("#ruleset-list").listview('refresh');
                  }
                else{
                    $("#ruleset-list").html("
 NONE 	 NONE 	");
                    $("#ruleset-list").listview('refresh');
                }
              } */

              //trying for a list

              console.log("attempting rough listview");

             $.each(rids_json, function(key, value){
               $.each(value, function(key, value){
                  console.log(key, value);
                 });
              });

              var keys = rids_json.sort(sortBy("rid_index"));
              console.log("keys: " + keys);
              $.each(rids_json, paint_item);
            //  $.each(keys, paint_item);

              console.log("refreshing manage-list listview.")

              $('#manage-list').listview('refresh');
                });

          // document.getElementById("List-Rulesets").innerHTML = obj;

            /*var frm = "#ruleset-form";
            $(frm)[0].reset();
            var owner_eci = CloudOS.defaultECI; //from pageUpdateProfile

              $("#RID", frm).val(ruleset_obj.rid);
              $("#source-URL", frm).val(ruleset_obj.uri);*/

          },
          registeringRuleset: function(type, match, ui, page) {
            console.log("registering Ruleset Handler");
          },
          confirmingDeletion: function(type, match, ui, page) {
            console.log("confirming Deletion Handler");
          },
          updatingUrl: function(type, match, ui, page) {
            console.log("updating Url Handler");
          },
          picologging: function(type, match, ui, page) {
            console.log("pico logging page");
            $.mobile.loading("hide");
          }
        },
      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });
      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
        list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

    function onPageLoad() {// Document.Ready
    	console.log("document ready");
	CloudOS.retrieveSession();
	// only put static stuff here...
	plant_authorize_button();

	$('.logout').off("tap").on("tap", function(event)
	   {
	       CloudOS.removeSession(true); // true for hard reset (log out of login server too)
	       $.mobile.changePage('#page-authorize', {
		   transition: 'slide'
	       }); // this will go to the authorization page.
	   });

	console.log("Choose page to show");

	try {
	    var authd = CloudOS.authenticatedSession();
	    if(authd) {
		console.log("Authorized");
		document.location.hash = "#home";
	    } else {
		console.log("Asking for authorization");
		document.location.hash = "#page-authorize";
	    }
	} catch (exception) {

	} finally {
	    $.mobile.initializePage();
	    $.mobile.loading("hide");
	}

    };

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    $(document).bind("mobileinit", onMobileInit);
    $(document).ready(onPageLoad);
  })(jQuery);

    function sortBy(prop){
              return function(a,b){
            if( a[prop]  b[prop] ){
                return -1;
            }
            return 0;
              };
          };
    function paint_item(id, rids) {//(key,value)

          /*if (typeof vehicle === "undefined") {
        return;
          }*/
          var status = "no status"; // place holder for description
         console.log("in paint_item");
         console.log(id, rids);
         console.log("rid: "+ rids["rid"]);

        $("#manage-list li:nth-child(1)" ).after( //was #manage-fleet prior
            snippets.list_rulesets_template(
              {"rid": rids.rid,
               "uri": rids.uri,
               "description": status
              }));
    };

<|endoftext|>


<commit_before>var clearPage = function(){
	$('body').html('')
}

var reloadPage =  function(){
	clearPage();
	$('body').append(sessionStorage.getItem('page-content'))
}

var savePage = function(){
	currentContent = $('body').html();
	sessionStorage.setItem('page-content', currentContent)
}

var loadBasicButtons = function(){
	$('body').prepend('<button class="back-button">back</button>')
	$('body').append('<button class="logout-button">logout</button>')
}

var logout = function(){
	location.replace(sessionStorage.getItem('login-screen'))
}

$(document).ready(function(){
	baseURL = 'https://skate-life-backend.herokuapp.com/'
	var loginScreen = $('body').html();

	sessionStorage.setItem('login-screen', location.pathname)

	// login and show skateparks
	$('.login-button').on('click', function(){
		var path = baseURL + 'api/skateparks'

		$.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})

		.done(function(response){
			clearPage();
			loadBasicButtons();

			var $skateparkList = $('
')
				.addClass('skateparks');

			var $userButton = $('<button>')
				.text('Show Users')
				.addClass('users-button');

			$('body').append($skateparkList, $userButton);

			// appends all skateparks
			$.each(response, function(index, park) {
				index = index + 1

				var $skateparkLink = $('
').append(
					$('').addClass('skatepark-link')
						.attr('href', baseURL + 'api/skateparks/' + park.id)
						.text(park.name));

				$('.skateparks').append($skateparkLink);

				savePage();
			});

		})

		.fail("nope")
	});

	// show an individual skatepark may need to abstract
	$('body').on('click', '.skatepark-link', function(e){
		e.preventDefault();
		console.log(e.target.href)
		var path = e.target.href
		var request =  $.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})
		request.done(function(response){
			console.log("yup")
			clearPage();
			loadBasicButtons();
			$('body').append('

')
			if(response.address === null){
				response.address = 'no address'
			}
			$('.skatepark-page').append('
'+response.name+'

'+response.address+'
')
			// fav_count
			$('.skatepark-page').append('

')
			$('.skatepark-page').append('<form class="message-form"><input type="text" id="nameInput" placeholder="Name" /><input type="text" id="messageInput" placeholder="Message..."/><input type="submit" value="Post"/></form>')
		})
		request.fail(function(response){
			console.log("nope")
		})
	})

	//show users
	$('body').on('click', '.users-button', function(e){
		e.preventDefault();
		var path = baseURL + 'api/users'
		var request = $.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})
		request.done(function(response){
			console.log("show me da skaters")
			clearPage();
			loadBasicButtons();
			$('body').append('

')
			$.each(response, function(index, skater){
				index = index + 1
			$('.skaters').append('
' +index + ":" + skater.name+'
');

			})
		})
		request.fail(function(response){
			console.log("showin you da haters")
		})
	})

	//show individual user and his favorites
	$('body').on('click', '.skater-link', function(e){
		e.preventDefault();
		var path = e.target.href
		var request = $.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})
		request.done(function(response){
			console.log("sup " + response.user.name)
			clearPage();
			loadBasicButtons();
			$('body').append('
'+response.user.name+'
')
			$('body').append('

')
			$.each(response.skateparks, function(index, skatepark){
				index = index + 1
				$('.user-favorites').append('
' +skatepark.name+'
')

			})
		})
		request.fail(function(response){
			console.log('failure @ life')
		})
	})

	// back button functionality -- consider refactoring or abstracting functionality
	$('body').on('click', '.back-button', function(e){
		e.preventDefault();
		// $('body').html('')
		// $('body').append(sessionStorage.getItem('page-content'))
		reloadPage();
	})

	// logout button
	$('body').on('click', '.logout-button', function(e){
		e.preventDefault();
		logout();
	})

})<commit_msg>Refactor skatepark show page and message box<commit_after>var clearPage = function(){
	$('body').html('');
}

var reloadPage =  function(){
	clearPage();
	$('body').append(sessionStorage.getItem('page-content'));
}

var savePage = function(){
	currentContent = $('body').html();
	sessionStorage.setItem('page-content', currentContent);
}

var loadBasicButtons = function(){
	$('body').prepend('<button class="back-button">back</button>');
	$('body').append('<button class="logout-button">logout</button>');
}

var logout = function(){
	location.replace(sessionStorage.getItem('login-screen'));
}

$(document).ready(function(){
	baseURL = 'https://skate-life-backend.herokuapp.com/';
	var loginScreen = $('body').html();

	sessionStorage.setItem('login-screen', location.pathname);

	// login and show skateparks
	$('.login-button').on('click', function(){
		var path = baseURL + 'api/skateparks';

		$.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})

		.done(function(response){
			clearPage();
			loadBasicButtons();

			var $skateparkList = $('
')
				.addClass('skateparks');

			var $userButton = $('<button>')
				.text('Show Users')
				.addClass('users-button');

			$('body').append($skateparkList, $userButton);

			// appends all skateparks
			$.each(response, function(index, park) {
				index = index + 1

				var $skateparkLink = $('
').append(
					$('').addClass('skatepark-link')
						.attr('href', baseURL + 'api/skateparks/' + park.id)
						.text(park.name));

				$('.skateparks').append($skateparkLink);

				savePage();
			});

		})

		.fail(function(response) {
			console.log(response);
		});
	});

	// show an individual skatepark may need to abstract
	$('body').on('click', '.skatepark-link', function(event){
		event.preventDefault();
		var path = event.target.href

		$.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})

		.done(function(response){
			clearPage();
			loadBasicButtons();

			if(response.address === null){ response.address = 'no address' }

			$('body').append(
				$('
').addClass('skatepark-page'));

			$('.skatepark-page').append(
				$('
').text(response.name),
				$('
').text(response.address),
				$('
').addClass('messages'),
				$('<form>').addClass('message-form')
					.append(
						$('<input>')
							.attr('type', 'text')
							.attr('id', 'nameInput')
							.attr('placeholder', 'Name'),
						$('<input>')
							.attr('type', 'text')
							.attr('id', 'messageInput')
							.attr('placeholder', 'Message'),
						$('<input>')
							.attr('type', 'submit')
							.val('Post')
						));

		})

		.fail(function(response){
			console.log(response);
		})
	})

	//show users
	$('body').on('click', '.users-button', function(event){
		event.preventDefault();
		var path = baseURL + 'api/users'
		var request = $.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})
		request.done(function(response){
			console.log("show me da skaters")
			clearPage();
			loadBasicButtons();
			$('body').append('

')
			$.each(response, function(index, skater){
				index = index + 1
			$('.skaters').append('
' +index + ":" + skater.name+'
');

			})
		})
		request.fail(function(response){
			console.log("showin you da haters")
		})
	})

	//show individual user and his favorites
	$('body').on('click', '.skater-link', function(event){
		event.preventDefault();
		var path = event.target.href
		var request = $.ajax({
			url: path,
			method: 'get',
			dataType: 'json'
		})
		request.done(function(response){
			console.log("sup " + response.user.name)
			clearPage();
			loadBasicButtons();
			$('body').append('
'+response.user.name+'
')
			$('body').append('

')
			$.each(response.skateparks, function(index, skatepark){
				index = index + 1
				$('.user-favorites').append('
' +skatepark.name+'
')

			})
		})
		request.fail(function(response){
			console.log('failure @ life')
		})
	})

	// back button functionality -- consider refactoring or abstracting functionality
	$('body').on('click', '.back-button', function(event){
		event.preventDefault();
		// $('body').html('')
		// $('body').append(sessionStorage.getItem('page-content'))
		reloadPage();
	})

	// logout button
	$('body').on('click', '.logout-button', function(event){
		event.preventDefault();
		logout();
	})

})<|endoftext|>


<commit_before>"use strict";

var fs = require("fs");
var path = require("path");

$(function() {

  var DB_FILENAME = "db.json";

  $("#reload-project").click(function() {
    //load_project();
  });

  // Load last project path
  (function() {
    var project_dir = window.localStorage.getItem("project_dir") || "";
    $("#project-path").val(project_dir);
  })();
  var project_dir = $("#project-path").val();

//  // Save for next time using.
//  window.localStorage.setItem("project_dir", project_dir);

  //load_project();

  var model = new SubprojectListModel(project_dir, DB_FILENAME);
  model.load();

  var view = new SubprojectListView(model, {
    "list": $(".sub-project-list"),
    "reload-button": $("reload-project")
  });
  view.show();
});

/**
 * SubprojectListModel
 * @class SubprojectListModel
 */
function SubprojectListModel(project_dir, db_filename) {
  /**
   * _project_dir
   * @property _project_dir
   * @private
   */
  this._project_dir = project_dir;
  this._db_filename = db_filename;
  this._items = [];

  /**
   * JSON database store project information.
   * @property _db
   * @private
   */
  this._db = {};

  this._load_db();
}

SubprojectListModel.prototype = {
  /**
   * getItems
   * @method getItems
   */
  "getItems": function() {
    return [].concat(this._items);
  },

  /**
   * Read project dir and store all sub dir.
   * @method load
   */
  "load": function() {
    try {
      var stats = fs.statSync(this._project_dir);
    } catch(e) {
      alert("Dir not exist");
      console.log(e);
      return;
    }

    if (!stats.isDirectory()) {
      alert("not a dir");
      return;
    }

    // List files/dirs in current dir.
    var _this = this;
    $.each.call(this, fs.readdirSync(this._project_dir), function(key, path) {
      var abs_path = _this._project_dir + "/" + path;
      if (!fs.lstatSync(abs_path).isDirectory()) {
        console.log("Ignore path: " + path);
        return;
      }
      _this._items.push({
        "dir_name": path,
        "sub_project_name": _this._get_sub_project_name(path)
      });
    });

    return this._items;
  },

  /**
   * Load database when exists.
   * @method _load_db
   * @private
   */
  "_load_db": function() {
    var db_file = path.join(this._project_dir, this._db_filename);
    if (!fs.existsSync(db_file)) {
      console.log(DB_FILENAME + " not exist: " + db_file);
      return;
    } else {
      this._db = JSON.parse(fs.readFileSync(db_file, "utf8"));
    }
  },

  /**
   * Get project name from database
   */
  "_get_sub_project_name": function(path) {
    var ret = "";
    $.each(this._db.sub_projects, function(k, v) {
      if (v.dir_name == path) {
        ret = v.sub_project_name;
      }
    });
    return ret;
  }
};

/**
 * Sub projects list
 * @class SubprojectListView
 */
function SubprojectListView(model, elements) {
  this._model = model;
  this._elements = elements;
}

SubprojectListView.prototype = {
  /**
   * Show view
   * @method show
   */
  "show": function() {
    this.rebuildList();
  },

  /**
   * Rebuild sub project list
   * @method rebuildList
   */
  "rebuildList": function() {
    var list, items;

    // Clear list.
    list = this._elements.list;
    list.html("");

    items = this._model.getItems();
    $.each(items, function(key, value){
      $(".sub-project-list").append(
        '
' + value.dir_name + '
' +
        '项目名称: ' +
        '<input placeholder="请输入项目名称" value="' + value.sub_project_name + '" />'
      );
    });
  }
};<commit_msg>add event support<commit_after>"use strict";

var fs = require("fs");
var path = require("path");

$(function() {

  var DB_FILENAME = "db.json";

  $("#reload-project").click(function() {
    //load_project();
  });

  // Load last project path
  (function() {
    var project_dir = window.localStorage.getItem("project_dir") || "";
    $("#project-path").val(project_dir);
  })();
  var project_dir = $("#project-path").val();

//  // Save for next time using.
//  window.localStorage.setItem("project_dir", project_dir);

  //load_project();

  var model = new SubprojectListModel(project_dir, DB_FILENAME);
  var view = new SubprojectListView(model, {
    "list": $(".sub-project-list"),
    "reload-button": $("#reload-project")
  });
  var controller = new SubProjectListController(model, view);
  view.show();
});

/**
 * event
 * @class Event
 */
function Event(sender) {
  /**
   * Who (whick view) send this event.
   */
  this._sender = sender;
  this._listeners = [];
}

Event.prototype = {
  "attach": function(listener) {
    this._listeners.push(listener);
  },
  "notify": function(args) {
    var index;
    for (index = 0; index < this._listeners.length; index += 1) {
      this._listeners[index](this.sender, args);
    }
  }
};

/**
 * SubprojectListModel
 * @class SubprojectListModel
 */
function SubprojectListModel(project_dir, db_filename) {
  /**
   * _project_dir
   * @property _project_dir
   * @private
   */
  this._project_dir = project_dir;
  this._db_filename = db_filename;
  this._items = [];

  /**
   * JSON database store project information.
   * @property _db
   * @private
   */
  this._db = {};

  this._load_db();
  this._load_fs();
}

SubprojectListModel.prototype = {
  /**
   * getItems
   * @method getItems
   */
  "getItems": function() {
    return [].concat(this._items);
  },

  /**
   * Read project dir and store all sub dir.
   * @method load
   */
  "_load_fs": function() {
    try {
      var stats = fs.statSync(this._project_dir);
    } catch(e) {
      alert("Dir not exist");
      console.log(e);
      return;
    }

    if (!stats.isDirectory()) {
      alert("not a dir");
      return;
    }

    // List files/dirs in current dir.
    var _this = this;
    $.each.call(this, fs.readdirSync(this._project_dir), function(key, path) {
      var abs_path = _this._project_dir + "/" + path;
      if (!fs.lstatSync(abs_path).isDirectory()) {
        console.log("Ignore path: " + path);
        return;
      }
      _this._items.push({
        "dir_name": path,
        "sub_project_name": _this._get_sub_project_name(path)
      });
    });

    return this._items;
  },

  /**
   * Load database when exists.
   * @method _load_db
   * @private
   */
  "_load_db": function() {
    var db_file = path.join(this._project_dir, this._db_filename);
    if (!fs.existsSync(db_file)) {
      console.log(DB_FILENAME + " not exist: " + db_file);
      return;
    } else {
      this._db = JSON.parse(fs.readFileSync(db_file, "utf8"));
    }
  },

  /**
   * Get project name from database
   */
  "_get_sub_project_name": function(path) {
    var ret = "";
    $.each(this._db.sub_projects, function(k, v) {
      if (v.dir_name == path) {
        ret = v.sub_project_name;
      }
    });
    return ret;
  }
};

/**
 * Sub projects list
 * @class SubprojectListView
 */
function SubprojectListView(model, elements) {
  this._model = model;
  this._elements = elements;

  this.reloadButtonClicked = new Event(this);

  var _this = this;

  this._elements["reload-button"].click(function() {
    _this.rebuildList();
  });
}

SubprojectListView.prototype = {
  /**
   * Show view
   * @method show
   */
  "show": function() {
    this.rebuildList();
  },

  /**
   * Rebuild sub project list
   * @method rebuildList
   */
  "rebuildList": function() {
    console.log("Reload data from model.");
    var list, items;

    // Clear list.
    list = this._elements.list;
    list.html("");

    items = this._model.getItems();
    $.each(items, function(key, value){
      $(".sub-project-list").append(
        '
' + value.dir_name + '
' +
        '项目名称: ' +
        '<input placeholder="请输入项目名称" value="' + value.sub_project_name + '" />'
      );
    });
  }
};

/**
 * SubProjectListController
 * @class SubProjectListController
 */
function SubProjectListController(model, view) {
  this._model = model;
  this._view = view;
}

SubProjectListController.prototype = {

};<|endoftext|>


<commit_before>$.getJSON("logic.json", function(logic){

	//globals
	var oldpop;

	//survey sortable
	$(".panel-group").sortable({
		handle: ".panel-heading",
		update: writexml
	});

	//create new surveys
	$("#new_survey_button").click(function(e){
		e.preventDefault();
		this.blur();
		var el = $("#surveytemplate .survey_content").clone();
		var id = el.children(".panel-collapse").uniqueId()[0].id;
		el.find("h4.panel-title a").attr("href", "#" + id);
		el.find(".list-group").sortable({
			update: writexml
		});
		el.find(".dropdown-menu a").click(function(e){
			e.preventDefault();
			var prompt_type = $(this).data("type");
			add_prompt(prompt_type, el)
		});
		el.find(".delete_survey_button").click(function(e){
			e.preventDefault();
			el.hide('slow', function(){
				el.remove()
			});
		});
		$("#surveygroup").append(el);
		$("#surveygroup").find(".collapse").collapse('hide');
		el.find(".collapse").collapse('show');

		//update view
		el.find(".survey_id_field").on("keyup", function(){
			el.find("h4.panel-title a").text("Survey: " + $(this).val())
		})

		//update xml
		el.find("input,textarea").change(writexml).keyup(writexml);
		writexml();
	});

	//create new prompt
	function add_prompt(prompt_type, el){
		el.find(".survey_prompt_list").append(function(){
			var a = $(Mustache.render(templates.promptlink, {
				prompt_type:prompt_type
			})).data("prompt_type", prompt_type);
			var content = popover_content(prompt_type, a);
			a.popover({
				html: true,
				//placement: "top",
				trigger: "click",
				title : prompt_type + " prompt",
				content: content
			}).click(function(e){
				e.preventDefault();
			}).on("show.bs.popover", function(){
				if(oldpop && oldpop != a){
					oldpop.popover("hide");
					oldpop = null;
				}
			}).hover(function(){
				if(oldpop != a){
					a.popover("show");
					oldpop = a;
				}
			}, function(){})
			return a;
		})
		writexml();
	}

	//initiate the prompt popover
	function popover_content(prompt_type, a){
		var templates = window.templates;
		var fields = logic.prompttypes[prompt_type];
		var el = $("#prompttemplate").children().clone();
		var form = el.find("form");

		// Other fields get dynamically
		$.each(fields, function(index, fieldname){
			var field = logic.fields[fieldname];
			var output = Mustache.render(templates[field.type], {
				field : fieldname,
				label : field.label || toTitleCase(fieldname),
				placeholder : field.placeholder || "Please enter " + fieldname.toLowerCase()
			});
			var input = form.append(output).find("input");

			//update view
			if(fieldname == "id"){
				var prompttext = a.find(".prompt_id_text");
				input.on("keyup", function(){
					prompttext.text(input.val() || "[new]")
				})
			}
		});

		el.find(".delete_prompt_button").click(function(){
			a.popover('hide');
			a.remove();
		});

		el.find(".choice_values").tagit().on('afterTagAdded', writexml).on('afterTagRemoved', writexml);
		el.find("input,textarea").change(writexml).keyup(writexml);

		return el;
	}

	/* Convert Form to XML. Should rewrite this in proper MVC */
	function form2xml(){
		var xml = $("<root/>")
		var campaign = $("<campaign/>").appendTo(xml);
		var surveys = $("<surveys/>").appendTo(campaign);

		$("#surveygroup .survey_form").each(function(){

			/* create node */
			var form = $(this);
			var survey = $("<survey/>").appendTo(surveys);

			/* survey fields */
			$("<id/>").text(form.find(".survey_id_field").val()).appendTo(survey);
			$("<title/>").text(form.find(".survey_title_field").val()).appendTo(survey);
			$("<description/>").text(form.find(".survey_description_field").val()).appendTo(survey);
			$("<submitText/>").text(form.find(".survey_submit_field").val()).appendTo(survey);
			$("<anytime/>").text(form.find(".survey_anytime_field").is(":checked")).appendTo(survey);

			/* find prompts */
			var contents = $("<contentList/>").appendTo(survey)
			form.find(".survey_prompt_list .prompt_link").each(function(){

				var prompt_link = $(this);
				var prompt_type = prompt_link.data("prompt_type");

				if(prompt_type == "message"){
					var prompt = $("<message/>").appendTo(contents)
				} else {
					var prompt = $("<prompt/>").appendTo(contents)
					$("<promptType>").text(prompt_link.data("prompt_type")).appendTo(prompt)
				}

				var popover = prompt_link.data("bs.popover").$tip;
				var fields = $(popover).find(".prompt_field")
				var properties = {};

				fields.each(function(){
					var field = $(this);
					var name = field.data("field")
					var value = getFieldValue(field)

					//some fields have to be put in the xml as 'properties'
					if(logic.fields[name].property){
						if(field.is("ol")){
							$.each(field.tagit("assignedTags"), function(i, val){
								//we start counting from 1 because that is how OL are displayed
								properties[i + 1] = val
							});
						} else {
							properties[name] = value;
						}
					} else {
						$("<"+name+"/>").text(value).appendTo(prompt)
					}

					//ohmage apparently has no default for this
					if(name == "skippable" && value == true){
						$("<skipLabel/>").text("Skip").appendTo(prompt)
					}
				})

				//append properties
				if(Object.keys(properties).length){
					var props = $("<properties>").appendTo(prompt)
					$.each(properties, function(key, val){
						var prop = $("<property>").appendTo(props)
						$("<key/>").text(key).appendTo(prop)
						$("<label/>").text(val).appendTo(prop)
					})
				}
			})
		});
		return xml
	}

	//debug
	function writexml(){
		var xmltext = '<?xml version="1.0" encoding="UTF-8"?>\n' + form2xml().html()
		$("code").text(vkbeautify.xml(xmltext))
	}

	//init page
	writexml();

}).fail(function(){
	alert("Downloading logic.json failed.")
});

function getFieldValue(el){
	if(el.is("input[type=checkbox]")){
		return el.is(':checked')
	} else if(el.is("ol")){
		return "Not implemented yet..."
	}
	return el.val();
}

$(document).keydown(function(e){
	//escape button
	if(e.which == 27){
		$(".list-group-item").popover('hide');
	}
});

function toTitleCase(str){
	return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
<commit_msg>clean urns<commit_after>$.getJSON("logic.json", function(logic){

	//globals
	var oldpop;

	//survey sortable
	$(".panel-group").sortable({
		handle: ".panel-heading",
		update: writexml
	});

	//create new surveys
	$("#new_survey_button").click(function(e){
		e.preventDefault();
		this.blur();
		var el = $("#surveytemplate .survey_content").clone();
		var id = el.children(".panel-collapse").uniqueId()[0].id;
		el.find("h4.panel-title a").attr("href", "#" + id);
		el.find(".list-group").sortable({
			update: writexml
		});
		el.find(".dropdown-menu a").click(function(e){
			e.preventDefault();
			var prompt_type = $(this).data("type");
			add_prompt(prompt_type, el)
		});
		el.find(".delete_survey_button").click(function(e){
			e.preventDefault();
			el.hide('slow', function(){
				el.remove()
			});
		});
		$("#surveygroup").append(el);
		$("#surveygroup").find(".collapse").collapse('hide');
		el.find(".collapse").collapse('show');

		//update view
		el.find(".survey_id_field").on("keyup", function(){
			var urn = urnify($(this).val())
			$(this).val(urn)
			el.find("h4.panel-title a").text("Survey: " + urn)
		})

		//update xml
		el.find("input,textarea").change(writexml).keyup(writexml);
		writexml();
	});

	//create new prompt
	function add_prompt(prompt_type, el){
		el.find(".survey_prompt_list").append(function(){
			var a = $(Mustache.render(templates.promptlink, {
				prompt_type:prompt_type
			})).data("prompt_type", prompt_type);
			var content = popover_content(prompt_type, a);
			a.popover({
				html: true,
				//placement: "top",
				trigger: "click",
				title : prompt_type + " prompt",
				content: content
			}).click(function(e){
				e.preventDefault();
			}).on("show.bs.popover", function(){
				if(oldpop && oldpop != a){
					oldpop.popover("hide");
					oldpop = null;
				}
			}).hover(function(){
				if(oldpop != a){
					a.popover("show");
					oldpop = a;
				}
			}, function(){})
			return a;
		})
		writexml();
	}

	//initiate the prompt popover
	function popover_content(prompt_type, a){
		var templates = window.templates;
		var fields = logic.prompttypes[prompt_type];
		var el = $("#prompttemplate").children().clone();
		var form = el.find("form");

		// Other fields get dynamically
		$.each(fields, function(index, fieldname){
			var field = logic.fields[fieldname];
			var output = Mustache.render(templates[field.type], {
				field : fieldname,
				label : field.label || toTitleCase(fieldname),
				placeholder : field.placeholder || "Please enter " + fieldname.toLowerCase()
			});
			var input = form.append(output).find("input");

			//update view
			if(fieldname == "id"){
				var prompttext = a.find(".prompt_id_text");
				input.on("keyup", function(){
					var urn = urnify($(this).val())
					$(this).val(urn)
					prompttext.text(urn|| "[new]")
				})
			}
		});

		el.find(".delete_prompt_button").click(function(){
			a.popover('hide');
			a.remove();
		});

		el.find(".choice_values").tagit().on('afterTagAdded', writexml).on('afterTagRemoved', writexml);
		el.find("input,textarea").change(writexml).keyup(writexml);

		return el;
	}

	/* Convert Form to XML. Should rewrite this in proper MVC */
	function form2xml(){
		var xml = $("<root/>")
		var campaign = $("<campaign/>").appendTo(xml);
		var surveys = $("<surveys/>").appendTo(campaign);

		$("#surveygroup .survey_form").each(function(){

			/* create node */
			var form = $(this);
			var survey = $("<survey/>").appendTo(surveys);

			/* survey fields */
			$("<id/>").text(form.find(".survey_id_field").val()).appendTo(survey);
			$("<title/>").text(form.find(".survey_title_field").val()).appendTo(survey);
			$("<description/>").text(form.find(".survey_description_field").val()).appendTo(survey);
			$("<submitText/>").text(form.find(".survey_submit_field").val()).appendTo(survey);
			$("<anytime/>").text(form.find(".survey_anytime_field").is(":checked")).appendTo(survey);

			/* find prompts */
			var contents = $("<contentList/>").appendTo(survey)
			form.find(".survey_prompt_list .prompt_link").each(function(){

				var prompt_link = $(this);
				var prompt_type = prompt_link.data("prompt_type");

				if(prompt_type == "message"){
					var prompt = $("<message/>").appendTo(contents)
				} else {
					var prompt = $("<prompt/>").appendTo(contents)
					$("<promptType>").text(prompt_link.data("prompt_type")).appendTo(prompt)
				}

				var popover = prompt_link.data("bs.popover").$tip;
				var fields = $(popover).find(".prompt_field")
				var properties = {};

				fields.each(function(){
					var field = $(this);
					var name = field.data("field")
					var value = getFieldValue(field)

					//some fields have to be put in the xml as 'properties'
					if(logic.fields[name].property){
						if(field.is("ol")){
							$.each(field.tagit("assignedTags"), function(i, val){
								//we start counting from 1 because that is how OL are displayed
								properties[i + 1] = val
							});
						} else {
							properties[name] = value;
						}
					} else {
						$("<"+name+"/>").text(value).appendTo(prompt)
					}

					//ohmage apparently has no default for this
					if(name == "skippable" && value == true){
						$("<skipLabel/>").text("Skip").appendTo(prompt)
					}
				})

				//append properties
				if(Object.keys(properties).length){
					var props = $("<properties>").appendTo(prompt)
					$.each(properties, function(key, val){
						var prop = $("<property>").appendTo(props)
						$("<key/>").text(key).appendTo(prop)
						$("<label/>").text(val).appendTo(prop)
					})
				}
			})
		});
		return xml
	}

	//debug
	function writexml(){
		var xmltext = '<?xml version="1.0" encoding="UTF-8"?>\n' + form2xml().html()
		$("code").text(vkbeautify.xml(xmltext))
	}

	//init page
	writexml();

}).fail(function(){
	alert("Downloading logic.json failed.")
});

function getFieldValue(el){
	if(el.is("input[type=checkbox]")){
		return el.is(':checked')
	} else if(el.is("ol")){
		return "Not implemented yet..."
	}
	return el.val();
}

$(document).keydown(function(e){
	//escape button
	if(e.which == 27){
		$(".list-group-item").popover('hide');
	}
});

function toTitleCase(str){
	return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function urnify(str){
	return str.replace(/[^a-z0-9]/gi,'').substr(0, 20)
}<|endoftext|>


<commit_before>//destructured assignment

var [d, m, y] = [15, 7, 2015]

[m, y] = [y, m]

console.log(m, y)

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

// let [a, b, c] = [1, 2, 3]
// console.log(a, b, c)
//
// [b, c] = [c, b]
// console.log(a, b, c)
<commit_msg>Fixed issue that was caused by lack of required semi-colon.<commit_after>//destructured assignment

var [d, m, y] = [15, 7, 2015]

;[m, y] = [y, m]

console.log(m, y)
<|endoftext|>