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

    var app = angular.module('search.service.find', []);
    app.factory('searchService', ['$http', '$rootScope', '$q', function($http, $rootScope, $q){
        $rootScope.lastResult = $rootScope.lastResult || { agent:null, space:null, event:null };
        var activeRequests = 0,
            canceler = null,
            lastEmitedResult = 'null',
            lastEmitedCountResult = 'null',
            lastQueries = {enabledEntities: null, space: null, agent: null, event: null, project: null, listedEntity: null, list:null, page: null};

        $rootScope.spinnerCount = $rootScope.spinnerCount || 0;

        $rootScope.$on('searchDataChange', search);
        $rootScope.$on('resultPagination', search);

        $rootScope.searchArgs = {
            list: {},
            map: {}
        };

        function search (ev, data){

            var results = {},
                numRequests = 0,
                numSuccessRequests = 0,
                numCountRequests = 0,
                numCountSuccessRequests = 0,
                countResults = {},
                paginating = ev.name === 'resultPagination';

            if(!paginating){
                $rootScope.resetPagination();
            }

            var activeEntity = data.global.filterEntity;
            if(data.global.viewMode === 'map'){
                var compareEnabledEntities = angular.equals(lastQueries.enabledEntities, data.global.enabled);

                var entityQueryData = data2searchData(activeEntity, data[activeEntity]);
                if(!angular.equals(entityQueryData, lastQueries[activeEntity]) || !compareEnabledEntities){
                    lastQueries[activeEntity] = angular.copy(entityQueryData);
                    callApi(activeEntity, entityQueryData);
                }else{
                    results[activeEntity] = $rootScope.lastResult[activeEntity];
                }

                lastQueries.enabledEntities = angular.copy(data.global.enabled);
            }else{

                var listQueryData = data2searchData(activeEntity, data[activeEntity]);

                if(activeEntity !== lastQueries.listedEntity)
                    $rootScope.pagination[activeEntity] = 1;

                var isDiff = (paginating && $rootScope.pagination[activeEntity] !== lastQueries.page) || (!angular.equals(listQueryData, lastQueries.list) || lastQueries.listedEntity !== activeEntity);

                if( isDiff ){
                    $rootScope.isPaginating = true;
                    lastQueries.listedEntity = activeEntity;
                    lastQueries.list = angular.copy(listQueryData);
                    callApi(activeEntity, angular.copy(listQueryData));
                }else{
                    $rootScope.isPaginating = false;
                }
            }

            endCountRequest();
            endRequest();

            function callApi(entity, sData){
                var requestEntity = entity,
                    requestAction = 'find';

                if(entity === 'event'){
                    if(data.global.viewMode === 'list'){
                        requestAction = 'findByLocation';
                    }else{
                        requestEntity = 'space' ;
                        requestAction = 'findByEvents';
                    }

                }

                $rootScope.searchArgs[data.global.viewMode][entity] = sData;

                //Counting XX events in YY spaces (events in map mode)
                if(requestEntity === 'space' && requestAction === 'findByEvents'){

                   var otherRequestEntity = 'event';
                   var otherRequestAction = 'findByLocation';

                   numCountRequests++;
                   activeRequests++;
                   $rootScope.spinnerCount++;

                   countResults['event'] = {};

                   apiCount(otherRequestEntity, sData, otherRequestAction).success(function(rs){
                       numCountSuccessRequests++;
                       activeRequests--;
                       $rootScope.spinnerCount--;

                       countResults['event'].events = rs;
                       endCountRequest();
                   });

                }

                numRequests++;
                activeRequests++;
                $rootScope.spinnerCount++;

                apiFind(requestEntity, sData, $rootScope.pagination[entity], requestAction).success(function(rs,status,header){
                    var metadata = JSON.parse(header('API-Metadata'));
                    numSuccessRequests++;
                    activeRequests--;
                    $rootScope.spinnerCount--;

                    results[entity] = rs;

                    endRequest();

                    if(requestEntity === 'space' && requestAction === 'findByEvents')
                        countResults[entity].spaces = metadata.count;
                    else
                        countResults[entity] = metadata.count;
                    numCountSuccessRequests++;
                    numCountRequests++;
                    endCountRequest();
                });

            }

            function countAndRemoveResultsNotInMap(entity, results){
                results[entity].forEach(function(item, index) {
                    if (!item.location || (item.location.latitude == 0 && item.location.longitude == 0)) {
                        $rootScope.resultsNotInMap[entity]++;
                    }
                });
            }

            function endRequest(){
                if(numRequests > 0 && numSuccessRequests === numRequests && lastEmitedResult !== JSON.stringify(results)){
                    if(data.global.viewMode === 'map') {
                        $rootScope.resultsNotInMap = {agent: 0, space: 0, event: 0};
                        if(results.agent) {
                            countAndRemoveResultsNotInMap('agent', results);
                        }
                        if(results.space) {
                            countAndRemoveResultsNotInMap('space', results);
                        }
                        if(results.event) {
                            countAndRemoveResultsNotInMap('event', results);
                        }
                    }

                    lastEmitedResult = JSON.stringify(results);
                    results.paginating = paginating;
                    $rootScope.lastResult = results;
                    $rootScope.$emit('searchResultsReady', results);
                }
            }

            function endCountRequest(){
                if(numCountRequests > 0 && numCountSuccessRequests === numCountRequests && lastEmitedCountResult !== JSON.stringify(countResults)){
                    $rootScope.$emit('searchCountResultsReady', countResults);
                }
            }

            function data2searchData(entity, entityData){
                var searchData = {};

                if(entityData.keyword){
                    searchData['@keyword'] = entityData.keyword.replace(/ /g,'%25');
                }

                for (var search_filter in entityData.filters){

                    if(entityData.from)
                        searchData['@from'] = moment(entityData.from).format('YYYY-MM-DD');
                    if(entityData.to)
                        searchData['@to'] = moment(entityData.to).format('YYYY-MM-DD');

                    if(entityData.ropen){
                        var today = moment().format('YYYY-MM-DD');
                        searchData.registrationFrom = 'LTE(' + today + ')';
                        searchData.registrationTo   = 'GTE(' + today + ')';
                    }

                    if(entityData.filters[search_filter]){
                        var filter = MapasCulturais.filters[entity].filter(function(f){
                            return f.filter.param === search_filter;
                        })[0];
                        if (entityData.filters[search_filter].length){
                            if (filter.type === 'term'){
                                var search_value = entityData.filters[search_filter].map(function(e){
                                    return MapasCulturais.taxonomyTerms[filter.filter.param][e] || e;
                                })
;                                searchData['term:'+ filter.prefix + filter.filter.param] = filter.filter.value.replace(/\{val\}/g, search_value.join(','));
                            } else
                                searchData[filter.prefix + filter.filter.param] = filter.filter.value.replace(/\{val\}/g, entityData.filters[search_filter].join(','));
                        } else if (!filter.isArray) {
                            searchData[filter.prefix + filter.filter.param] = filter.filter.value;
                        }
                    }
                }

                if(data.global.locationFilters.enabled !== null){
                    var type = data.global.locationFilters.enabled;
                    var center = data.global.locationFilters[type].center;
                    var radius = data.global.locationFilters[type].radius;
                    searchData._geoLocation = 'GEONEAR(' + center.lng + ',' + center.lat + ',' + radius + ')';
                }
                return searchData;
            }

            function apiFind(entity, searchData, page, action) {

                if(MapasCulturais.searchFilters && MapasCulturais.searchFilters[entity]){
                    angular.extend(searchData, MapasCulturais.searchFilters[entity]);
                }

                var selectData = 'id,singleUrl,name,type,shortDescription,terms';
                var apiExportURL = MapasCulturais.baseURL + 'api/';
                var exportEntity = entity;
                if(entity === 'space'){
                    if(action === 'find') {
                        selectData += ',endereco,acessibilidade';
                    }else{
                    	exportEntity = 'event';
                        selectData += ',classificacaoEtaria,project.name,project.singleUrl,occurrences';
                        apiExportURL += 'event/findByLocation/?';
                    }
                }else if (entity === 'project'){
                    selectData += ',registrationFrom,registrationTo';
                }else if(entity === 'event'){
                    selectData += ',classificacaoEtaria,project.name,project.singleUrl,occurrences';
                }

                if(data.global.viewMode === 'list'){
                    searchData['@select'] = selectData;
                    searchData['@files'] = '(avatar.avatarMedium):url';
                    if(page) {
                        searchData['@page'] = page;
                        searchData['@limit'] = '10';
                    }
                }else{
                    searchData['@select'] = 'id,name,location';
                }

                action = action || 'find';
                searchData['@order'] = 'name ASC';
                delete searchData['@count'];

                var querystring = '';
                var Description = MapasCulturais.EntitiesDescription[exportEntity];
                Object.keys(Description).forEach(function(prop) {
                	if (!Description[prop].isEntityRelation && (MapasCulturais.allowedFields || (!MapasCulturais.allowedFields && !Description[prop].private))) {
                		if (Description[prop]['@select']) {
                			prop = Description[prop]['@select'];
                		}
                		selectData += "," + prop;
                	}
                })

                var queryString_apiExport = '@select='+selectData;

                //removes type column from event export
                if(apiExportURL.indexOf('event/findByLocation') !== -1)
                    queryString_apiExport = queryString_apiExport.replace(',type','');
                else
                    apiExportURL += entity + '/' + action + '/?';

                for(var att in searchData) {
                    querystring += "&"+att+"="+searchData[att];
                    if(att != '@select' && att!='@page' && att!='@limit')
                        queryString_apiExport += "&"+att+"="+searchData[att];
                }

                $rootScope.apiURL = apiExportURL+queryString_apiExport;

                return $http({method: 'GET', cache:true, url:MapasCulturais.baseURL + 'api/' + entity + '/' + action + '/?'+querystring , data:searchData});
            }

            function apiCount(entity, searchData, action) {

                action = action || 'find';
                var querystring = "";

                for(var att in searchData) {
                    querystring += "&"+att+"="+searchData[att];
                }
                return $http({method: 'GET', cache:true, url: MapasCulturais.baseURL + 'api/'+entity+'/' + action + '/?@count=1&'+querystring, data:searchData});
            }
        }

        return 'done';
    }]);

})(angular);

<commit_msg>Fix search of text-field type<commit_after>(function(angular) {
    "use strict";

    var app = angular.module('search.service.find', []);
    app.factory('searchService', ['$http', '$rootScope', '$q', function($http, $rootScope, $q){
        $rootScope.lastResult = $rootScope.lastResult || { agent:null, space:null, event:null };
        var activeRequests = 0,
            canceler = null,
            lastEmitedResult = 'null',
            lastEmitedCountResult = 'null',
            lastQueries = {enabledEntities: null, space: null, agent: null, event: null, project: null, listedEntity: null, list:null, page: null};

        $rootScope.spinnerCount = $rootScope.spinnerCount || 0;

        $rootScope.$on('searchDataChange', search);
        $rootScope.$on('resultPagination', search);

        $rootScope.searchArgs = {
            list: {},
            map: {}
        };

        function search (ev, data){

            var results = {},
                numRequests = 0,
                numSuccessRequests = 0,
                numCountRequests = 0,
                numCountSuccessRequests = 0,
                countResults = {},
                paginating = ev.name === 'resultPagination';

            if(!paginating){
                $rootScope.resetPagination();
            }

            var activeEntity = data.global.filterEntity;
            if(data.global.viewMode === 'map'){
                var compareEnabledEntities = angular.equals(lastQueries.enabledEntities, data.global.enabled);

                var entityQueryData = data2searchData(activeEntity, data[activeEntity]);
                if(!angular.equals(entityQueryData, lastQueries[activeEntity]) || !compareEnabledEntities){
                    lastQueries[activeEntity] = angular.copy(entityQueryData);
                    callApi(activeEntity, entityQueryData);
                }else{
                    results[activeEntity] = $rootScope.lastResult[activeEntity];
                }

                lastQueries.enabledEntities = angular.copy(data.global.enabled);
            }else{

                var listQueryData = data2searchData(activeEntity, data[activeEntity]);

                if(activeEntity !== lastQueries.listedEntity)
                    $rootScope.pagination[activeEntity] = 1;

                var isDiff = (paginating && $rootScope.pagination[activeEntity] !== lastQueries.page) || (!angular.equals(listQueryData, lastQueries.list) || lastQueries.listedEntity !== activeEntity);

                if( isDiff ){
                    $rootScope.isPaginating = true;
                    lastQueries.listedEntity = activeEntity;
                    lastQueries.list = angular.copy(listQueryData);
                    callApi(activeEntity, angular.copy(listQueryData));
                }else{
                    $rootScope.isPaginating = false;
                }
            }

            endCountRequest();
            endRequest();

            function callApi(entity, sData){
                var requestEntity = entity,
                    requestAction = 'find';

                if(entity === 'event'){
                    if(data.global.viewMode === 'list'){
                        requestAction = 'findByLocation';
                    }else{
                        requestEntity = 'space' ;
                        requestAction = 'findByEvents';
                    }

                }

                $rootScope.searchArgs[data.global.viewMode][entity] = sData;

                //Counting XX events in YY spaces (events in map mode)
                if(requestEntity === 'space' && requestAction === 'findByEvents'){

                   var otherRequestEntity = 'event';
                   var otherRequestAction = 'findByLocation';

                   numCountRequests++;
                   activeRequests++;
                   $rootScope.spinnerCount++;

                   countResults['event'] = {};

                   apiCount(otherRequestEntity, sData, otherRequestAction).success(function(rs){
                       numCountSuccessRequests++;
                       activeRequests--;
                       $rootScope.spinnerCount--;

                       countResults['event'].events = rs;
                       endCountRequest();
                   });

                }

                numRequests++;
                activeRequests++;
                $rootScope.spinnerCount++;

                apiFind(requestEntity, sData, $rootScope.pagination[entity], requestAction).success(function(rs,status,header){
                    var metadata = JSON.parse(header('API-Metadata'));
                    numSuccessRequests++;
                    activeRequests--;
                    $rootScope.spinnerCount--;

                    results[entity] = rs;

                    endRequest();

                    if(requestEntity === 'space' && requestAction === 'findByEvents')
                        countResults[entity].spaces = metadata.count;
                    else
                        countResults[entity] = metadata.count;
                    numCountSuccessRequests++;
                    numCountRequests++;
                    endCountRequest();
                });

            }

            function countAndRemoveResultsNotInMap(entity, results){
                results[entity].forEach(function(item, index) {
                    if (!item.location || (item.location.latitude == 0 && item.location.longitude == 0)) {
                        $rootScope.resultsNotInMap[entity]++;
                    }
                });
            }

            function endRequest(){
                if(numRequests > 0 && numSuccessRequests === numRequests && lastEmitedResult !== JSON.stringify(results)){
                    if(data.global.viewMode === 'map') {
                        $rootScope.resultsNotInMap = {agent: 0, space: 0, event: 0};
                        if(results.agent) {
                            countAndRemoveResultsNotInMap('agent', results);
                        }
                        if(results.space) {
                            countAndRemoveResultsNotInMap('space', results);
                        }
                        if(results.event) {
                            countAndRemoveResultsNotInMap('event', results);
                        }
                    }

                    lastEmitedResult = JSON.stringify(results);
                    results.paginating = paginating;
                    $rootScope.lastResult = results;
                    $rootScope.$emit('searchResultsReady', results);
                }
            }

            function endCountRequest(){
                if(numCountRequests > 0 && numCountSuccessRequests === numCountRequests && lastEmitedCountResult !== JSON.stringify(countResults)){
                    $rootScope.$emit('searchCountResultsReady', countResults);
                }
            }

            function data2searchData(entity, entityData){
                var searchData = {};

                if(entityData.keyword){
                    searchData['@keyword'] = entityData.keyword.replace(/ /g,'%25');
                }

                for (var search_filter in entityData.filters){

                    if(entityData.from)
                        searchData['@from'] = moment(entityData.from).format('YYYY-MM-DD');
                    if(entityData.to)
                        searchData['@to'] = moment(entityData.to).format('YYYY-MM-DD');

                    if(entityData.ropen){
                        var today = moment().format('YYYY-MM-DD');
                        searchData.registrationFrom = 'LTE(' + today + ')';
                        searchData.registrationTo   = 'GTE(' + today + ')';
                    }

                    if(entityData.filters[search_filter]){
                        var filter = MapasCulturais.filters[entity].filter(function(f){
                            return f.filter.param === search_filter;
                        })[0];
                        if (!filter.isArray) {
                            searchData[filter.prefix + filter.filter.param] = filter.filter.value;
                        } else if (entityData.filters[search_filter].length){
                            if (filter.type === 'term'){
                                var search_value = entityData.filters[search_filter].map(function(e){
                                    return MapasCulturais.taxonomyTerms[filter.filter.param][e] || e;
                                })
;                                searchData['term:'+ filter.prefix + filter.filter.param] = filter.filter.value.replace(/\{val\}/g, search_value.join(','));
                            } else
                                searchData[filter.prefix + filter.filter.param] = filter.filter.value.replace(/\{val\}/g, entityData.filters[search_filter].join(','));
                        }
                    }
                }

                if(data.global.locationFilters.enabled !== null){
                    var type = data.global.locationFilters.enabled;
                    var center = data.global.locationFilters[type].center;
                    var radius = data.global.locationFilters[type].radius;
                    searchData._geoLocation = 'GEONEAR(' + center.lng + ',' + center.lat + ',' + radius + ')';
                }
                return searchData;
            }

            function apiFind(entity, searchData, page, action) {

                if(MapasCulturais.searchFilters && MapasCulturais.searchFilters[entity]){
                    angular.extend(searchData, MapasCulturais.searchFilters[entity]);
                }

                var selectData = 'id,singleUrl,name,type,shortDescription,terms';
                var apiExportURL = MapasCulturais.baseURL + 'api/';
                var exportEntity = entity;
                if(entity === 'space'){
                    if(action === 'find') {
                        selectData += ',endereco,acessibilidade';
                    }else{
                    	exportEntity = 'event';
                        selectData += ',classificacaoEtaria,project.name,project.singleUrl,occurrences';
                        apiExportURL += 'event/findByLocation/?';
                    }
                }else if (entity === 'project'){
                    selectData += ',registrationFrom,registrationTo';
                }else if(entity === 'event'){
                    selectData += ',classificacaoEtaria,project.name,project.singleUrl,occurrences';
                }

                if(data.global.viewMode === 'list'){
                    searchData['@select'] = selectData;
                    searchData['@files'] = '(avatar.avatarMedium):url';
                    if(page) {
                        searchData['@page'] = page;
                        searchData['@limit'] = '10';
                    }
                }else{
                    searchData['@select'] = 'id,name,location';
                }

                action = action || 'find';
                searchData['@order'] = 'name ASC';
                delete searchData['@count'];

                var querystring = '';
                var Description = MapasCulturais.EntitiesDescription[exportEntity];
                Object.keys(Description).forEach(function(prop) {
                	if (!Description[prop].isEntityRelation && (MapasCulturais.allowedFields || (!MapasCulturais.allowedFields && !Description[prop].private))) {
                		if (Description[prop]['@select']) {
                			prop = Description[prop]['@select'];
                		}
                		selectData += "," + prop;
                	}
                })

                var queryString_apiExport = '@select='+selectData;

                //removes type column from event export
                if(apiExportURL.indexOf('event/findByLocation') !== -1)
                    queryString_apiExport = queryString_apiExport.replace(',type','');
                else
                    apiExportURL += entity + '/' + action + '/?';

                for(var att in searchData) {
                    querystring += "&"+att+"="+searchData[att];
                    if(att != '@select' && att!='@page' && att!='@limit')
                        queryString_apiExport += "&"+att+"="+searchData[att];
                }

                $rootScope.apiURL = apiExportURL+queryString_apiExport;

                return $http({method: 'GET', cache:true, url:MapasCulturais.baseURL + 'api/' + entity + '/' + action + '/?'+querystring , data:searchData});
            }

            function apiCount(entity, searchData, action) {

                action = action || 'find';
                var querystring = "";

                for(var att in searchData) {
                    querystring += "&"+att+"="+searchData[att];
                }
                return $http({method: 'GET', cache:true, url: MapasCulturais.baseURL + 'api/'+entity+'/' + action + '/?@count=1&'+querystring, data:searchData});
            }
        }

        return 'done';
    }]);

})(angular);

<|endoftext|>


<commit_before>/*global ODSA, setPointerL */
//"use strict";
$(document).ready(function () {
//  var av = new JSAV(av_name);
    $(".avcontainer").on("jsav-message" ,  function() {
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset" , MathJax.Hub]);
    });
    $(".avcontainer").on("jsav-updatecounter" ,  function(){
      // invoke MathJax to do conversion again
     MathJax.Hub.Queue(["Typeset" , MathJax.Hub]); });

    var av = new JSAV($('.avcontainer'));

  var label1, label2 , label3, label4, label5, label6,label7,label8,label9;
  //slide2
  var y = 0;
  av.umsg("

Boelan Expressions");
  av.umsg("

Boolean variables : x1 , x2 , "
  +"x3 ...",{preserve:true});
  av.umsg("

Boolean operators: AND (+) , OR (.), NOT (^)",
  {preserve:true});
  av.umsg("

Boolean expressions/Propositional logic formula :"+
  "x1 + x2 . x3 ",{preserve:true});
  av.displayInit();
//slide 3
  av.step();
  av.umsg("CNF");
  av.umsg("

A literal is either a boolean variable (x) or "
  +"its negation (^x) ",{preserve:true});

  av.umsg("

For e.g. : a , ^b , ^g , c , ^c , ^e ... ",{preserve:true});

  av.umsg("

A clause is disjunction (OR) of literals i.e. of "
  +"the form  l1 + l2 + l3 + ... +"+
  "ln for some literal li",{preserve:true});

  av.umsg("

For e.g. :&nbsp&nbsp&nbsp&nbsp (a + ^b) , &nbsp&nbsp&nbsp"
  +"&nbsp ^g , &nbsp&nbsp&nbsp&nbsp (c + ^f + ^e + h), &nbsp&nbsp&nbsp&nbsp "
  +"... ",{preserve:true});

  av.umsg("

A Conjunctive normal form (CNF) is a conjunction "
  +"(AND) of clauses.",{preserve:true});

  av.umsg("

For e.g.: &nbsp&nbsp&nbsp&nbsp^x1 . ("+
  "x1 + x2) . (x3 + x4 + "+
  "^x5)",{preserve:true});

  av.umsg("

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp(x1 + "
  +"x3) . (^x3 + x2 + ^x5) . "+
  "(x1 + x2 + ^x3) . (x3 + "+
  "x4 + ^x2) . (^x4 + ^x1 + "+
  "^x5) . (x1 + x3 + x5)",{preserve:true});

 //slide 4

  av.step();
  av.umsg("Satisfiability");
  y=0;

  label1 = av.label("A formula is said to be satisfiable if it can be made TRUE by some assignment of variables.",{top: y,left:50}).css({"text-align": "center"});
  label1.show();
  y = y+ 50;
  label2 = av.label("For e.g. (x1 + x2 . x3) is TRUE for x1=TRUE , x2=TRUE, x3=TRUE , hence satisfiable.",{top: y,left:50}).css({"text-align": "center"});
  label2.show();
  y = y+ 50;
  label3 = av.label("(x1 . ^x1) is  always FALSE, hence not satisfiable.",{top: y,left:50}).css({"text-align": "center"});
  label3.show();

  // slide 4
  av.step();
  av.umsg("SAT");
  y=0;
  label1.hide();
  label2.hide();
  label3.hide();

  label1 = av.label("The Boolean satisfiability problem (SAT) is, given a formula, to check whether it is satisfiable.",{top: y,left:50}).css({"text-align": "center"});
  label1.show();

//slide 6 : Is the following formula satisfiable ?
  av.step();
  av.umsg("Example of SAT");
  label1.hide();
  label2.hide();

  y = 0;

  label1 = av.label("P = ($x_1$ + $x_2$).($x_2$ + ^$x_3$ + $x_4$).($x_1$ + ^$x_2$ + $x_3$ + $x_4$).(^$x_1$ + $x_3$)",{top: y-30,left:0}).css({"text-align": "center"});

  label1.show();
  label2 = av.label("Truth Table for P",{top: y+20,left:150}).css({"text-align": "center"});
  label2.show();
  var matdata=[["x1","x2","x3","x4","P"],
               ["0","0","0","0","0"],
               ["0","0","0","1","0"],
               ["0","0","1","0","0"],
               ["0","0","1","1","0"],
               ["0","1","0","0","0"],
               ["0","1","0","1","1"],
               ["0","1","1","0","1"],
               ["0","1","1","1","1"]];
  var matdata1=[["x1","x2","x3","x4","P"],
                ["1","0","0","0","0"],
                ["1","0","0","1","0"],
                ["1","0","1","0","0"],
                ["1","0","1","1","1"],
                ["1","1","0","0","0"],
                ["1","1","0","1","0"],
                ["1","1","1","0","1"],
                ["1","1","1","1","1"]];

  var mat1 = new av.ds.matrix(matdata,{style:"table",left:50,top:y+50});
  var mat2= new av.ds.matrix(matdata1,{style:"table",left:250,top:y+50});

  for(var j=0; j<5 ; j++)
      mat1.css(0,j,{"background-color":"Tan",opacity:0.5});
  for(var j=0; j<5 ; j++)
      mat2.css(0,j,{"background-color":"Tan",opacity:0.5});

  av.step();
  for (var i=1; i< 9; i++){
	if (matdata[i][4] == 0){
		for(var j=0; j<5 ; j++)
			mat1.css(i,j,{"background-color":"#CC3333"});
	}
	else{
		for(var j=0; j<5 ; j++)
			mat1.css(i,j,{"background-color":"#669966"});
	}

	if (matdata1[i][4] == 0){
		for(var j=0; j<8 ; j++)
			mat2.css(i,j,{"background-color":"#CC3333"});
	}
	else{
		for(var j=0; j<8 ; j++)
			mat2.css(i,j,{"background-color":"#669966"});
	}

  }
  mat1.show();
  mat2.show();

    av.step();
    label4 = av.label("There exists assignments that makes the formula true "+
    "(The green rows)",{top:y+120,left:550})
    av.step();

  label3 = av.label("P is satisfiable",{top: y+175,left:550}).css({"text-align": "center", "font-size": "20px"});
  label3.show();

//slide 8
  av.step();
  mat1.hide();
  mat2.hide();
  label1.hide();
  label2.hide();
  label3.hide();
  label4.hide();

  av.umsg("Example of SAT");
  y = 0;

  label1 = av.label("P = ($x_1$ + $x_2$).($x_2$ + ^$x_3$ + $x_4$).($x_3$ + ^$x_4$).($x_1$ + ^$x_1$).($x_1$ + ^$x_2$ + $x_3$ + $x_4$)",{top: y-30,left:0}).css({"text-align": "center"});

  label1.show();
  label2 = av.label("Truth Table for P",{top: y+20,left:150}).css({"text-align": "center"});
  label2.show();

   var matdata2=[["x1","x2","x3","x4","P"],
                 ["0","0","0","0","0"],
                 ["0","0","0","1","0"],
                 ["0","0","1","0","0"],
                 ["0","0","1","1","0"],
                 ["0","1","0","0","0"],
                 ["0","1","0","1","0"],
                 ["0","1","1","0","0"],
                 ["0","1","1","1","0"]];
   var matdata3=[["x1","x2","x3","x4","P"],
                 ["1","0","0","0","0"],
                 ["1","0","0","1","0"],
                 ["1","0","1","0","0"],
                 ["1","0","1","1","0"],
                 ["1","1","0","0","0"],
                 ["1","1","0","1","0"],
                 ["1","1","1","0","0"],
                 ["1","1","1","1","0"]];

   var mat3 = new av.ds.matrix(matdata2,{style:"table",left:50,top:y+50});
   var mat4= new av.ds.matrix(matdata3,{style:"table",left:250,top:y+50});
  for(var j=0; j<5 ; j++)
      mat3.css(0,j,{"background-color":"Tan",opacity:0.5});
  for(var j=0; j<5 ; j++)
      mat4.css(0,j,{"background-color":"Tan",opacity:0.5});

  av.step();
  for ( var k=1; k< 9; k++){
	for(var l=0; l<5 ; l++){
		mat3.css(k,l,{"background-color":"#CC3333"});
		mat4.css(k,l,{"background-color":"#CC3333"});
	}

  }
  mat3.show();
  mat4.show();
//slide 9
    av.step();
    label4 = av.label("There does not exist any assignment that makes the formula true "+
    "(No green rows)",{top:y+120,left:550})
    av.step();

  label3 = av.label("P is non satisfiable",{top: y+175,left:550}).css({"text-align": "center", "font-size": "20px"});
  label3.show();

  av.step();
  mat3.hide();
  mat4.hide();
  label1.hide();
  label2.hide();
  label3.hide();
  label4.hide();
  av.umsg("Insights");
  av.umsg("

Size of the truth table is 2n where n is the "
  +"number of boolean variables involved ",{preserve:true});
  av.umsg("

Hence the problem gets exponentially harder as number of variables"
  +" increase ",{preserve:true});

  av.recorded();
});
<commit_msg>submitting sat to illustrate the display problems wit latex symbols in tables and umsg.<commit_after>/*global ODSA, setPointerL */
//"use strict";
$(document).ready(function () {
//  var av = new JSAV(av_name);
    $(".avcontainer").on("jsav-message" ,  function() {
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset" , MathJax.Hub]);
    });
    $(".avcontainer").on("jsav-updatecounter" ,  function(){
      // invoke MathJax to do conversion again
     MathJax.Hub.Queue(["Typeset" , MathJax.Hub]); });

    var av = new JSAV($('.avcontainer'));

  var label1, label2 , label3, label4, label5, label6,label7,label8,label9;
  //slide2
  var y = 0;
  av.umsg("

Boelan Expressions");
  av.umsg("

Boolean variables : x1 , x2 , "
  +"x3 ...",{preserve:true});
  av.umsg("

Boolean operators: AND (+) , OR (.), NOT (^)",
  {preserve:true});
  av.umsg("

Boolean expressions/Propositional logic formula :"+
  "x1 + x2 . x3 ",{preserve:true});
  av.displayInit();
//slide 3
  av.step();
  av.umsg("CNF");
  av.umsg("

A literal is either a boolean variable (x) or "
  +"its negation (^x) ",{preserve:true});

  av.umsg("

For e.g. : a , ^b , ^g , c , ^c , ^e ... ",{preserve:true});

  av.umsg("

A clause is disjunction (OR) of literals i.e. of "
  +"the form  l1 + l2 + l3 + ... +"+
  "ln for some literal li",{preserve:true});

  av.umsg("

For e.g. :&nbsp&nbsp&nbsp&nbsp (a + ^b) , &nbsp&nbsp&nbsp"
  +"&nbsp ^g , &nbsp&nbsp&nbsp&nbsp (c + ^f + ^e + h), &nbsp&nbsp&nbsp&nbsp "
  +"... ",{preserve:true});

  av.umsg("

A Conjunctive normal form (CNF) is a conjunction "
  +"(AND) of clauses.",{preserve:true});

  av.umsg("

For e.g.: &nbsp&nbsp&nbsp&nbsp^x1 . ("+
  "x1 + x2) . (x3 + x4 + "+
  "^x5)",{preserve:true});

  av.umsg("

&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp(x1 + "
  +"x3) . (^x3 + x2 + ^x5) . "+
  "(x1 + x2 + ^x3) . (x3 + "+
  "x4 + ^x2) . (^x4 + ^x1 + "+
  "^x5) . (x1 + x3 + x5)",{preserve:true});

 //slide 4

  av.step();
  av.umsg("Satisfiability");
  y=0;

  label1 = av.label("A formula is said to be satisfiable if it can be made TRUE by some assignment of variables.",{top: y,left:50}).css({"text-align": "center"});
  label1.show();
  y = y+ 50;
  label2 = av.label("For e.g. (x1 + x2 . x3) is TRUE for x1=TRUE , x2=TRUE, x3=TRUE , hence satisfiable.",{top: y,left:50}).css({"text-align": "center"});
  label2.show();
  y = y+ 50;
  label3 = av.label("(x1 . ^x1) is  always FALSE, hence not satisfiable.",{top: y,left:50}).css({"text-align": "center"});
  label3.show();

  // slide 4
  av.step();
  av.umsg("SAT");
  y=0;
  label1.hide();
  label2.hide();
  label3.hide();

  label1 = av.label("The Boolean satisfiability problem (SAT) is, given a formula, to check whether it is satisfiable.",{top: y,left:50}).css({"text-align": "center"});
  label1.show();

//slide 5 : Is the following formula satisfiable ?
  av.step();
  av.umsg("Example of SAT");
  label1.hide();
  label2.hide();

  y = 0;

//  label1 = av.label("P = ($x_1$ + $x_2$).($x_2$ + ^$x_3$ + $x_4$).($x_1$ + ^$x_2$ + $x_3$ + $x_4$).(^$x_1$ + $x_3$)",{top: y-30,left:0}).css({"text-align": "center"});
 av.umsg("

P = $(x_1 + x_2).(x_2 + \\overline{x_3} + x_4).(x_1 + \\overline{x_2} + x_3 + x_4).(\\overline{x_1} + x_3)$ is the expression.",{preserve:true});

//  label1.show();
  label2 = av.label("Truth Table for P",{top: y+20,left:150}).css({"text-align": "center"});
  label2.show();
  var matdata=[["$x_1$","$x_2$","$x_3$","$x_4$","P"],
               ["F","F","F","F","F"],
               ["F","F","F","T","F"],
               ["F","F","T","F","F"],
               ["F","F","T","T","F"],
               ["F","T","F","F","F"],
               ["F","T","F","T","T"],
               ["F","T","T","F","T"],
               ["F","T","T","T","T"]];
  var matdata1=[["x1","x2","x3","x4","P"],
                ["T","F","F","F","F"],
                ["T","F","F","T","F"],
                ["T","F","T","F","F"],
                ["T","F","T","T","T"],
                ["T","T","F","F","F"],
                ["T","T","F","T","F"],
                ["T","T","T","F","T"],
                ["T","T","T","T","T"]];

  var mat1 = new av.ds.matrix(matdata,{style:"table",left:50,top:y+50});
  var mat2= new av.ds.matrix(matdata1,{style:"table",left:250,top:y+50});

  for(var j=0; j<5 ; j++)
      mat1.css(0,j,{"background-color":"Tan",opacity:0.5});
  for(var j=0; j<5 ; j++)
      mat2.css(0,j,{"background-color":"Tan",opacity:0.5});

  av.step();
  for (var i=1; i< 9; i++){
	if (matdata[i][4] == "F"){
		for(var j=0; j<5 ; j++)
			mat1.css(i,j,{"background-color":"#CC3333"});
	}
	else{
		for(var j=0; j<5 ; j++)
			mat1.css(i,j,{"background-color":"#669966"});
	}

	if (matdata1[i][4] == "F"){
		for(var j=0; j<8 ; j++)
			mat2.css(i,j,{"background-color":"#CC3333"});
	}
	else{
		for(var j=0; j<8 ; j++)
			mat2.css(i,j,{"background-color":"#669966"});
	}

  }
  mat1.show();
  mat2.show();

    av.step();
    label4 = av.label("There exists assignments that makes the formula true "+
    "(The green rows)",{top:y+120,left:550})
    av.step();

  label3 = av.label("P is satisfiable",{top: y+175,left:550}).css({"text-align": "center", "font-size": "20px"});
  label3.show();

//slide 8
  av.step();
  mat1.hide();
  mat2.hide();
//  label1.hide();
  label2.hide();
  label3.hide();
  label4.hide();

  av.umsg("Example of SAT");
  y = 0;

  label1 = av.label("P = ($x_1$ + $x_2$).($x_2$ + ^$x_3$ + $x_4$).($x_3$ + ^$x_4$).($x_1$ + ^$x_1$).($x_1$ + ^$x_2$ + $x_3$ + $x_4$)",{top: y-30,left:0}).css({"text-align": "center"});

  label1.show();
  label2 = av.label("Truth Table for P",{top: y+20,left:150}).css({"text-align": "center"});
  label2.show();

   var matdata2=[["x1","x2","x3","x4","P"],
                 ["F","F","F","F","F"],
                 ["F","F","F","T","F"],
                 ["F","F","T","F","F"],
                 ["F","F","T","T","F"],
                 ["F","T","F","F","F"],
                 ["F","T","F","T","F"],
                 ["F","T","T","F","F"],
                 ["F","T","T","T","F"]];
   var matdata3=[["x1","x2","x3","x4","P"],
                 ["T","F","F","F","F"],
                 ["T","F","F","T","F"],
                 ["T","F","T","F","F"],
                 ["T","F","T","T","F"],
                 ["T","T","F","F","F"],
                 ["T","T","F","T","F"],
                 ["T","T","T","F","F"],
                 ["T","T","T","T","F"]];

   var mat3 = new av.ds.matrix(matdata2,{style:"table",left:50,top:y+50});
   var mat4= new av.ds.matrix(matdata3,{style:"table",left:250,top:y+50});
  for(var j=0; j<5 ; j++)
      mat3.css(0,j,{"background-color":"Tan",opacity:0.5});
  for(var j=0; j<5 ; j++)
      mat4.css(0,j,{"background-color":"Tan",opacity:0.5});

  av.step();
  for ( var k=1; k< 9; k++){
	for(var l=0; l<5 ; l++){
		mat3.css(k,l,{"background-color":"#CC3333"});
		mat4.css(k,l,{"background-color":"#CC3333"});
	}

  }
  mat3.show();
  mat4.show();
//slide 9
    av.step();
    label4 = av.label("There does not exist any assignment that makes the formula true "+
    "(No green rows)",{top:y+120,left:550})
    av.step();

  label3 = av.label("P is non satisfiable",{top: y+175,left:550}).css({"text-align": "center", "font-size": "20px"});
  label3.show();

  av.step();
  mat3.hide();
  mat4.hide();
  label1.hide();
  label2.hide();
  label3.hide();
  label4.hide();
  av.umsg("Insights");
  av.umsg("

Size of the truth table is 2n where n is the "
  +"number of boolean variables involved ",{preserve:true});
  av.umsg("

Hence the problem gets exponentially harder as number of variables"
  +" increase ",{preserve:true});

  av.recorded();
});
<|endoftext|>


<commit_before>var MarketContract = artifacts.require("MarketContract");
var CollateralToken = artifacts.require("CollateralToken");
var OrderLib = artifacts.require("OrderLib");

// basic tests for interacting with market contract.
contract('MarketContract', function(accounts) {

    // test setup of token for collateral
    var initBalance;
    var collateralToken;
    var balancePerAcct;
    it("Initial supply should be 1e+22", async function() {
        collateralToken = await CollateralToken.deployed();
        initBalance = await collateralToken.INITIAL_SUPPLY.call().valueOf();
        assert.equal(initBalance, 1e+22, "Initial balance not as expected");
    });

    it("Main account should have entire balance", async function() {
        let mainAcctBalance = await collateralToken.balanceOf.call(accounts[0]).valueOf();
        assert.equal(mainAcctBalance.toNumber(), initBalance.toNumber(), "Entire coin balance should be in primary account");
    });

    it("Main account should be able to transfer balance", async function() {
        var balanceToTransfer = initBalance / 2;
        balancePerAcct = balanceToTransfer;
        await collateralToken.transfer(accounts[1], balanceToTransfer, {from: accounts[0]});
        let secondAcctBalance = await collateralToken.balanceOf.call(accounts[1]).valueOf();
        assert.equal(secondAcctBalance.toNumber(), balanceToTransfer, "Transfer didn't register correctly");
    });

    // now we have two accounts with equal balances, begin testing market contract functionality
    var marketContract;
    it("Both accounts should be able to deposit to main contract", async function() {
        marketContract = await MarketContract.deployed();
        var amountToDeposit = 5000000;
        // create approval for main contract to move tokens!
        await collateralToken.approve(marketContract.address, amountToDeposit, {from: accounts[0]})
        await collateralToken.approve(marketContract.address, amountToDeposit, {from: accounts[1]})
        // move tokens to the MarketContract
        await marketContract.depositTokensForTrading(amountToDeposit, {from: accounts[0]})
        await marketContract.depositTokensForTrading(amountToDeposit, {from: accounts[1]})
        // ensure balances are now inside the contract.
        let tradingBalanceAcctOne = await marketContract.getUserAccountBalance.call(accounts[0]);
        let tradingBalanceAcctTwo = await marketContract.getUserAccountBalance.call(accounts[1]);
        assert.equal(tradingBalanceAcctOne, amountToDeposit, "Balance doesn't equal tokens deposited");
        assert.equal(tradingBalanceAcctTwo, amountToDeposit, "Balance doesn't equal tokens deposited");
    });

    it("Both accounts should be able to withdraw from main contract", async function() {
        var amountToWithdraw = 2500000;
        // move tokens to the MarketContract
        await marketContract.withdrawTokens(amountToWithdraw, {from: accounts[0]})
        await marketContract.withdrawTokens(amountToWithdraw, {from: accounts[1]})
        // ensure balances are now correct inside the contract.
        let tradingBalanceAcctOne = await marketContract.getUserAccountBalance.call(accounts[0]);
        let tradingBalanceAcctTwo = await marketContract.getUserAccountBalance.call(accounts[1]);
        assert.equal(tradingBalanceAcctOne, amountToWithdraw, "Balance doesn't equal tokens deposited - withdraw");
        assert.equal(tradingBalanceAcctTwo, amountToWithdraw, "Balance doesn't equal tokens deposited - withdraw");
        // ensure balances are now correct inside the arbitrary token
        var expectedTokenBalances = balancePerAcct - tradingBalanceAcctOne;
        let secondAcctTokenBalance = await collateralToken.balanceOf.call(accounts[1]).valueOf();
        assert.equal(secondAcctTokenBalance, expectedTokenBalances, "Token didn't get transferred back to user");
    });

//     it("Order signed correctly", async function() {
//            let orderLib = await OrderLib.deployed();
//            var timeStamp = ((new Date()).getTime() / 1000) + 60*5; // order expires 5 minute from now.
//            var orderAddresses = [accounts[0], accounts[1], accounts[2]];
//            var unsignedOrderValues = [0, 0, 33025, timeStamp, 0];
//            var orderQty = 5;   // user is attempting to buy 5
//            var orderHash = await orderLib.createOrderHash.call(
//                MarketContract.address,
//                orderAddresses,
//                unsignedOrderValues,
//                orderQty
//            );
//            var orderSignature = web3.eth.sign(accounts[0], orderHash);
//            var r = orderSignature.substring(0, 64)
//            var s = orderSignature.substring(64, 128)
//            var v = parseInt(orderSignature.substring(128, 130));
//            console.log(r);
//            console.log(s);
//            console.log(v);
//            console.log(await orderLib.isValidSignature.call(accounts[0], orderHash, v,r,s))
//    });
});
<commit_msg>signing test working<commit_after>var MarketContract = artifacts.require("MarketContract");
var CollateralToken = artifacts.require("CollateralToken");
var OrderLib = artifacts.require("OrderLib");

// basic tests for interacting with market contract.
contract('MarketContract', function(accounts) {

    // test setup of token for collateral
    var initBalance;
    var collateralToken;
    var balancePerAcct;
    it("Initial supply should be 1e+22", async function() {
        collateralToken = await CollateralToken.deployed();
        initBalance = await collateralToken.INITIAL_SUPPLY.call().valueOf();
        assert.equal(initBalance, 1e+22, "Initial balance not as expected");
    });

    it("Main account should have entire balance", async function() {
        let mainAcctBalance = await collateralToken.balanceOf.call(accounts[0]).valueOf();
        assert.equal(mainAcctBalance.toNumber(), initBalance.toNumber(), "Entire coin balance should be in primary account");
    });

    it("Main account should be able to transfer balance", async function() {
        var balanceToTransfer = initBalance / 2;
        balancePerAcct = balanceToTransfer;
        await collateralToken.transfer(accounts[1], balanceToTransfer, {from: accounts[0]});
        let secondAcctBalance = await collateralToken.balanceOf.call(accounts[1]).valueOf();
        assert.equal(secondAcctBalance.toNumber(), balanceToTransfer, "Transfer didn't register correctly");
    });

    // now we have two accounts with equal balances, begin testing market contract functionality
    var marketContract;
    it("Both accounts should be able to deposit to main contract", async function() {
        marketContract = await MarketContract.deployed();
        var amountToDeposit = 5000000;
        // create approval for main contract to move tokens!
        await collateralToken.approve(marketContract.address, amountToDeposit, {from: accounts[0]})
        await collateralToken.approve(marketContract.address, amountToDeposit, {from: accounts[1]})
        // move tokens to the MarketContract
        await marketContract.depositTokensForTrading(amountToDeposit, {from: accounts[0]})
        await marketContract.depositTokensForTrading(amountToDeposit, {from: accounts[1]})
        // ensure balances are now inside the contract.
        let tradingBalanceAcctOne = await marketContract.getUserAccountBalance.call(accounts[0]);
        let tradingBalanceAcctTwo = await marketContract.getUserAccountBalance.call(accounts[1]);
        assert.equal(tradingBalanceAcctOne, amountToDeposit, "Balance doesn't equal tokens deposited");
        assert.equal(tradingBalanceAcctTwo, amountToDeposit, "Balance doesn't equal tokens deposited");
    });

    it("Both accounts should be able to withdraw from main contract", async function() {
        var amountToWithdraw = 2500000;
        // move tokens to the MarketContract
        await marketContract.withdrawTokens(amountToWithdraw, {from: accounts[0]})
        await marketContract.withdrawTokens(amountToWithdraw, {from: accounts[1]})
        // ensure balances are now correct inside the contract.
        let tradingBalanceAcctOne = await marketContract.getUserAccountBalance.call(accounts[0]);
        let tradingBalanceAcctTwo = await marketContract.getUserAccountBalance.call(accounts[1]);
        assert.equal(tradingBalanceAcctOne, amountToWithdraw, "Balance doesn't equal tokens deposited - withdraw");
        assert.equal(tradingBalanceAcctTwo, amountToWithdraw, "Balance doesn't equal tokens deposited - withdraw");
        // ensure balances are now correct inside the arbitrary token
        var expectedTokenBalances = balancePerAcct - tradingBalanceAcctOne;
        let secondAcctTokenBalance = await collateralToken.balanceOf.call(accounts[1]).valueOf();
        assert.equal(secondAcctTokenBalance, expectedTokenBalances, "Token didn't get transferred back to user");
    });

    var orderLib;
    it("Orders are signed correctly", async function() {
        orderLib = await OrderLib.deployed();
        var timeStamp = ((new Date()).getTime() / 1000) + 60*5; // order expires 5 minute from now.
        var orderAddresses = [accounts[0], accounts[1], accounts[2]];
        var unsignedOrderValues = [0, 0, 33025, timeStamp, 0];
        var orderQty = 5;   // user is attempting to buy 5
        var orderHash = await orderLib.createOrderHash.call(
            MarketContract.address,
            orderAddresses,
            unsignedOrderValues,
            orderQty
        );
        var orderSignature = await web3.eth.sign(accounts[0], orderHash);
        var r = orderSignature.slice(0, 66);
        var s = `0x${orderSignature.slice(66, 130)}`;
        var v = web3.toDecimal(`0x${orderSignature.slice(130, 132)}`);
        if (v !== 27 && v !== 28) v += 27;
        assert.isTrue(await orderLib.isValidSignature.call(accounts[0], orderHash, v,r,s), "Order hash doesn't match signer");
        assert.isTrue(!await orderLib.isValidSignature.call(accounts[1], orderHash, v,r,s), "Order has matches a non signer");
    });
});<|endoftext|>


<commit_before>var body = document.body.textContent.split('\n');
var newBody = '';
var newLine = '';
var splitter = '';
var lines = body.length;
var tableStarted = false;
var table = '';

for (i = 0; i < lines; i++) {

	if (tableStarted && body[i].indexOf('|') == -1) {
		table = '
' + table + '
';
		tableStarted = false;
		newBody = newBody.concat(table);
		table = '';
	};

    if(body[i].indexOf('Feature:') > -1){

        //Format the Feature Line
        newLine = body[i];

        newLine = newLine.replace('Feature:', '
Feature:').concat('

');

        newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Scenario:') > -1) {

        //Format the Scenario Line
        newLine = body[i];

        newLine = newLine.replace('Scenario:', 'Scenario:').concat('
');

        newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Scenario Outline:') > -1) {

    	//Format the Scenario Line
    	newLine = body[i];

    	newLine = newLine.replace('Scenario Outline:', 'Scenario Outline:').concat('
');

    	newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Scenarios:') > -1) {

    	//Format the Scenario Line
    	newLine = body[i];

    	newLine = newLine.replace('Scenarios:', 'Scenarios:').concat('
');

    	newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Given ') > -1) {

        //Format the Given Line
        newLine = body[i];

        newLine = newLine.replace('Given ','Given ').concat('
');

        newBody = newBody.concat(newLine);

    } else if(body[i].indexOf('When ') > -1){

        //Format the When Line
        newLine = body[i];

        newLine = newLine.replace('When ','When ').concat('
');

        newBody = newBody.concat(newLine);

    } else if(body[i].indexOf('Then ') > -1){

        //Format the Then Line
        newLine = body[i];

        newLine = newLine.replace('Then ','Then ').concat('
');

        newBody = newBody.concat(newLine);

    } else if(body[i].indexOf('And ') > -1){

        //Format the Then Line
        newLine = body[i];

        newLine = newLine.replace('And ','And ').concat('
');

        newBody = newBody.concat(newLine);
    } else if (body[i].indexOf('#') > -1 && (body[i].indexOf('|') == -1 || body[i].indexOf('#') < body[i].indexOf('|'))) {

    	//Format the Comment Line
    	newLine = body[i];
    	newLine = '' + htmlEscape(newLine) + '

';
    	newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('@') > -1) {

    	//Format the Comment Line
    	newLine = body[i];
    	newLine = '' + newLine + '
';
    	newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('|') > -1 && body[i].lastIndexOf('|') > -1) {

    	//Format the Table Line
	    var textStart = body[i].indexOf('|');
	    var textEnd = body[i].lastIndexOf('|');
	    var splittedLine = body[i].substring(textStart + 1, textEnd).trim().split('|');
	    var openTd = ''
	    if (!tableStarted)
	    	openTd = ''
	    table = table + '
';
	    tableStarted = true;

    	for (j = 0; j < splittedLine.length; j++)
		{
    		table = table + '|	' + openTd + splittedLine[j].trim() + '	';
    	};

    	table = table.substring(0, table.lastIndexOf('	')) + '	|
';
    } else {
    	newBody = newBody.concat(body[i] + '
');
    }
}

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
}

document.body.innerHTML = newBody;
<commit_msg>Fix defects<commit_after>var body = document.body.textContent.split('\n');
var newBody = '';
var newLine = '';
var splitter = '';
var lines = body.length;
var tableStarted = false;
var table = '';
var tableRegEx = /^\s*\|.*\|\s*$/im;

for (i = 0; i < lines; i++) {

    if(body[i].indexOf('Feature:') > -1){

        //Format the Feature Line
        newLine = body[i];

        newLine = newLine.replace('Feature:', '
Feature:').concat('

');

        newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Scenario:') > -1) {

        //Format the Scenario Line
        newLine = body[i];

        newLine = newLine.replace('Scenario:', 'Scenario:').concat('
');

        newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Scenario Outline:') > -1) {

    	//Format the Scenario Line
    	newLine = body[i];

    	newLine = newLine.replace('Scenario Outline:', 'Scenario Outline:').concat('
');

    	newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Scenarios:') > -1) {

    	//Format the Scenario Line
    	newLine = body[i];

    	newLine = newLine.replace('Scenarios:', 'Scenarios:').concat('
');

    	newBody = newBody.concat(newLine);

    } else if (body[i].indexOf('Given ') > -1) {

        //Format the Given Line
        newLine = body[i];

        newLine = newLine.replace('Given ','Given ').concat('
');

        newBody = newBody.concat(newLine);

    } else if(body[i].indexOf('When ') > -1){

        //Format the When Line
        newLine = body[i];

        newLine = newLine.replace('When ','When ').concat('
');

        newBody = newBody.concat(newLine);

    } else if(body[i].indexOf('Then ') > -1){

        //Format the Then Line
        newLine = body[i];

        newLine = newLine.replace('Then ','Then ').concat('
');

        newBody = newBody.concat(newLine);

    } else if(body[i].indexOf('And ') > -1){

        //Format the Then Line
        newLine = body[i];

        newLine = newLine.replace('And ','And ').concat('
');

        newBody = newBody.concat(newLine);
    } else if (body[i].match(/^\s*#.*/i)) {

    	//Format the Comment Line
    	newLine = body[i];
    	newLine = '' + htmlEscape(newLine) + '

';
    	newBody = newBody.concat(newLine);

    } else if (body[i].match(/^@.*/i)) {

        newBody = newBody.concat(body[i].replace(/^@.*/i, '' + body[i] + '
'));

    } else if (body[i].match(tableRegEx)) {
        //(body[i].indexOf('|') > -1 && body[i].lastIndexOf('|') > -1) {

    	//Format the Table Line
	    var textStart = body[i].indexOf('|');
	    var textEnd = body[i].lastIndexOf('|');
	    var splittedLine = body[i].substring(textStart + 1, textEnd).trim().split('|');
	    var openTd = ''
	    if (!tableStarted)
	    	openTd = ''
	    table = table + '
';
	    tableStarted = true;

    	for (j = 0; j < splittedLine.length; j++)
		{
    	    table = table + '|	' + openTd + htmlEscape(splittedLine[j].trim()) + '	';
    	};

        table = table.substring(0, table.lastIndexOf('	')) + '	|
';

    } else {
        newBody = newBody.concat(body[i] + '
');
    }

    if (tableStarted && body.length <= i + 1){
        finishTable();
    }else if (tableStarted && !body[i + 1].match(tableRegEx)) {
        finishTable();
    }
}

function finishTable() {
    table = '
' + table + '
';
    tableStarted = false;
    newBody = newBody.concat(table);
    table = '';
}

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
}

document.body.innerHTML = newBody;
<|endoftext|>


<commit_before>var body = document.body.textContent.split('\n');
var newBody = '';
var newLine = '';
var splitter = '';
var lines = body.length;
var tableStarted = false;
var table = '';
var tableRegEx = /^\s*\|.*\|\s*$/im;

for (i = 0; i < lines; i++) {

    if (body[i].match(/^\s*#.*/i)) {

        //Format the Comment Line
        newLine = body[i];
        newLine = '' + htmlEscape(newLine) + '

';
        newBody = newBody.concat(newLine);
    } else if(body[i].indexOf('Feature:') > -1){
        //Format the Feature Line
        formatLine(body[i], 'Feature:', 'feature', true);
    } else if (body[i].indexOf('Scenario:') > -1) {
        //Format the Scenario Line
        formatLine(body[i], 'Scenario:', 'scenario', false);
    } else if (body[i].indexOf('Scenario Outline:') > -1) {
        //Format the Scenario Line
        formatLine(body[i], 'Scenario Outline:', 'scenario', false);
    } else if (body[i].indexOf('Scenarios:') > -1) {
        //Format the Scenarios Line
        formatLine(body[i], 'Scenarios:', 'scenario', false);
    } else if (body[i].indexOf('Given ') > -1) {
        //Format the Given Line
        formatLine(body[i], 'Given ', 'example', false);
    } else if(body[i].indexOf('When ') > -1){
        //Format the When Line
        formatLine(body[i], 'When ', 'example', false);
    } else if(body[i].indexOf('Then ') > -1){
        //Format the Then Line
        formatLine(body[i], 'Then ', 'example', false);
    } else if(body[i].indexOf('And ') > -1){
        //Format the Then Line
        formatLine(body[i], 'And ', 'example', false);
    } else if (body[i].match(/^@.*/i)) {
        newBody = newBody.concat(body[i].replace(/^@.*/i, '' + body[i] + '
'));
    } else if (body[i].match(tableRegEx)) {
    	//Format the Table Line
	    var textStart = body[i].indexOf('|');
	    var textEnd = body[i].lastIndexOf('|');
	    var splittedLine = body[i].substring(textStart + 1, textEnd).trim().split('|');
	    var openTd = ''
	    if (!tableStarted)
	    	openTd = ''
	    table = table + '
';
	    tableStarted = true;

    	for (j = 0; j < splittedLine.length; j++)
		{
    	    table = table + '|	' + openTd + htmlEscape(splittedLine[j].trim()) + '	';
    	};

        table = table.substring(0, table.lastIndexOf('	')) + '	|
';
    } else {
        newBody = newBody.concat(body[i] + '
');
    }

    if (tableStarted && body.length <= i + 1){
        finishTable();
    }else if (tableStarted && !body[i + 1].match(tableRegEx)) {
        finishTable();
    }
}

function formatLine(line, strWord, strClass, useH1) {
    var textStart = line.indexOf(strWord) + strWord.length;
    var text = line.substring(textStart);

    if (useH1)
        newLine = '
' + strWord + '' + formatReplaceTag(htmlEscape(text)) + '

';
    else
        newLine = '' + strWord + '' + formatReplaceTag(htmlEscape(text)) + '
';

    newBody = newBody.concat(newLine);
}

function formatReplaceTag(line) {
    if (line.match(/&lt.*&gt/i)) {
        line = line.replace('<', '<');
        line = line.replace('>', '>');
    }
    return line;
}

function finishTable() {
    table = '
' + table + '
';
    tableStarted = false;
    newBody = newBody.concat(table);
    table = '';
}

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
}

document.body.innerHTML = newBody;
<commit_msg>Fix for inline variables<commit_after>var body = document.body.textContent.split('\n');
var newBody = '';
var newLine = '';
var splitter = '';
var lines = body.length;
var tableStarted = false;
var table = '';
var tableRegEx = /^\s*\|.*\|\s*$/im;

for (i = 0; i < lines; i++)
{
    if (body[i].match(/^\s*#.*/i))
    {
        //Format the Comment Line
        newLine = body[i];
        newLine = '' + htmlEscape(newLine) + '

';
        newBody = newBody.concat(newLine);
    }
    else if (body[i].indexOf('Feature:') > -1)
    {
        //Format the Feature Line
        formatLine(body[i], 'Feature:', 'feature', true);
    }
    else if (body[i].indexOf('Scenario:') > -1)
    {
        //Format the Scenario Line
        formatLine(body[i], 'Scenario:', 'scenario', false);
    }
    else if (body[i].indexOf('Scenario Outline:') > -1)
    {
        //Format the Scenario Outline Line
        formatLine(body[i], 'Scenario Outline:', 'scenario', false);
    }
    else if (body[i].indexOf('Scenarios:') > -1)
    {
        //Format the Scenarios Line
        formatLine(body[i], 'Scenarios:', 'scenario', false);
    }
    else if (body[i].indexOf('Given ') > -1)
    {
        //Format the Given Line
        formatLine(body[i], 'Given ', 'example', false);
    }
    else if (body[i].indexOf('When ') > -1)
    {
        //Format the When Line
        formatLine(body[i], 'When ', 'example', false);
    }
    else if (body[i].indexOf('Then ') > -1)
    {
        //Format the Then Line
        formatLine(body[i], 'Then ', 'example', false);
    }
    else if (body[i].indexOf('And ') > -1)
    {
        //Format the Then Line
        formatLine(body[i], 'And ', 'example', false);
    }
    else if (body[i].match(/^@.*/i))
    {
        newBody = newBody.concat(body[i].replace(/^@.*/i, '' + body[i] + '
'));
    }
    else if (body[i].match(tableRegEx))
    {
    	//Format the Table Line
	    var textStart = body[i].indexOf('|');
	    var textEnd = body[i].lastIndexOf('|');
	    var splittedLine = body[i].substring(textStart + 1, textEnd).trim().split('|');
	    var openTd = ''
	    if (!tableStarted)
	    	openTd = ''
	    table = table + '
';
	    tableStarted = true;

    	for (j = 0; j < splittedLine.length; j++)
		{
    	    table = table + '|	' + openTd + htmlEscape(splittedLine[j].trim()) + '	';
    	};

        table = table.substring(0, table.lastIndexOf('	')) + '	|
';
    }
    else
    {
        newBody = newBody.concat(body[i] + '
');
    }

    if (tableStarted && body.length <= i + 1){
        finishTable();
    }else if (tableStarted && !body[i + 1].match(tableRegEx)) {
        finishTable();
    }
}

function formatLine(line, strWord, strClass, useH1) {
    var textStart = line.indexOf(strWord) + strWord.length;
    var text = line.substring(textStart);

    newLine = '' + strWord + '' + formatReplaceTag(htmlEscape(text)) + '
';
    if (useH1)
        newLine = '
' + newLine.replace('
', '

');

    newBody = newBody.concat(newLine);
}

function formatReplaceTag(line) {
    if (line.match(/&lt.*&gt/i)) {
        line = line.replace('<', '<');
        line = line.replace('>', '>');
    }
    return line;
}

function finishTable() {
    table = '
' + table + '
';
    tableStarted = false;
    newBody = newBody.concat(table);
    table = '';
}

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
}

document.body.innerHTML = newBody;
<|endoftext|>


<commit_before>BEST.scene('super.demo.day:hello-famous', 'HEAD', {
    behaviors: {
        '#hello-famous': {
            'align': [0.5, 0.5],
            'mount-point': [0.5, 0.5],
            'style': {
                'color': 'white',
                'background': 'linear-gradient(to right, #00B9D7, #82CDB9)',
                'font-family': 'Lato',
                'font-size': '60px',
                'text-align': 'center',
                'line-height': window.innerHeight + 'px'
            }
        }
    },
    events: {},
    states: {},
    tree: 'hello-famous.html'
});
<commit_msg>demos: use famous.org colors<commit_after>BEST.scene('super.demo.day:hello-famous', 'HEAD', {
    behaviors: {
        '#hello-famous': {
            'align': [0.5, 0.5],
            'mount-point': [0.5, 0.5],
            'style': {
                'color': 'white',
                'background': 'linear-gradient(to right, #00B9D7, #9783F2)',
                'font-family': 'Lato',
                'font-size': '60px',
                'text-align': 'center',
                'line-height': window.innerHeight + 'px'
            }
        }
    },
    events: {},
    states: {},
    tree: 'hello-famous.html'
});
<|endoftext|>


<commit_before>import Hook from '../../util/hook'
import dns from 'native-dns'

import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import resolver from "../cronjob/resolver";
import schema from "../cronjob/schema";

console.log('create dns server')
const server = dns.createServer()

let database = null
let hosts = {}

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolverGen(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schemaGen)
})

// Hook when db is ready
Hook.on('appready', ({db}) => {
    database = db
    readHosts(db)
})

// Hook when the type CronJob has changed
Hook.on('typeUpdated_DnsHost', ({result}) => {
    if (result.name) {
        hosts[result.name] = {...hosts[result.name], ...result}
    }
})

server.on('request', (req, res) => {

    let hostname = req.question[0].name

    if (database != null) {

        if (hosts[hostname] === undefined) {
            hosts[hostname] = {block:false}
            database.collection('DnsHost').insertOne({
                name: hostname
            })
        }
    }

    let block = hosts[hostname].block === true

    if( !block ){
        //check subdomains
        const pos = hostname.indexOf('.')
        while(pos>=0){
            hostname = hostname.substring(pos+1)
            if(hosts[hostname] && hosts[hostname].block === true && hosts[hostname].subdomains === true){
                block = true
                break
            }
        }
    }

    if(block){
        console.log(`block host ${hostname}`)
        res.answer.push(dns.A({
            name: hostname,
            address: '0.0.0.0',
            ttl: 1,
        }))
        res.send()
    }else {

        console.log(`resolve host ${hostname}`)
        const dnsRequest = dns.Request({
            question: req.question[0],
            server: {address: '8.8.8.8', port: 53, type: 'udp'},
            timeout: 1000
        })

        dnsRequest.on('timeout', () => {
            console.log('Timeout in making request')
        })

        dnsRequest.on('message', (err, answer) => {
            answer.answer.forEach((a) => {
                res.answer.push(a)
            })
        })

        dnsRequest.on('end', () => {
            res.send()
        })

        dnsRequest.send()
    }
})

server.on('error', (err, buff, req, res) => {
    console.log(err.stack)
})

server.on('listening', ()=> {
    console.log('dns listening')
})

server.on('listening', ()=> {
    console.log('dns close')
})

server.serve(53)

const readHosts = async (db) => {
    (await db.collection('DnsHost').find().forEach(o => {
        hosts[o.name] = o
    }))
}
<commit_msg>Small improvements<commit_after>import Hook from '../../util/hook'
import dns from 'native-dns'

import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import resolver from "../cronjob/resolver";
import schema from "../cronjob/schema";

console.log('create dns server')
const server = dns.createServer()

let database = null
let hosts = {}

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolverGen(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schemaGen)
})

// Hook when db is ready
Hook.on('appready', ({db}) => {
    database = db
    readHosts(db)
})

// Hook when the type CronJob has changed
Hook.on('typeUpdated_DnsHost', ({result}) => {
    if (result.name) {
        hosts[result.name] = {...hosts[result.name], ...result}
    }
})

server.on('request', (req, res) => {

    let hostname = req.question[0].name

    if (database != null) {

        if (hosts[hostname] === undefined) {
            hosts[hostname] = {block:false}
            database.collection('DnsHost').insertOne({
                name: hostname
            })
        }
    }

    let block = hosts[hostname].block === true

    if( !block ){
        //check subdomains
        let pos = hostname.indexOf('.')
        while(pos>=0){
            hostname = hostname.substring(pos+1)
            if(hosts[hostname] && hosts[hostname].block === true && hosts[hostname].subdomains === true){
                block = true
                break
            }
            pos = hostname.indexOf('.')
        }
    }

    if(block){
        console.log(`block host ${hostname}`)
        res.answer.push(dns.A({
            name: hostname,
            address: '0.0.0.0',
            ttl: 1,
        }))
        res.send()
    }else {

        console.log(`resolve host ${hostname}`)
        const dnsRequest = dns.Request({
            question: req.question[0],
            server: {address: '8.8.8.8', port: 53, type: 'udp'},
            timeout: 1000
        })

        dnsRequest.on('timeout', () => {
            console.log('Timeout in making request')
        })

        dnsRequest.on('message', (err, answer) => {
            answer.answer.forEach((a) => {
                res.answer.push(a)
            })
        })

        dnsRequest.on('end', () => {
            res.send()
        })

        dnsRequest.send()
    }
})

server.on('error', (err, buff, req, res) => {
    console.log(err.stack)
})

server.on('listening', ()=> {
    console.log('dns listening')
})

server.on('listening', ()=> {
    console.log('dns close')
})

server.serve(53)

const readHosts = async (db) => {
    (await db.collection('DnsHost').find().forEach(o => {
        hosts[o.name] = o
    }))
}
<|endoftext|>


<commit_before>(function(){function l(){function n(a){return a?"object"===typeof a||"function"===typeof a:!1}var p=null;var g=function(a,b){function f(){}if(!n(a)||!n(b))throw new TypeError("Cannot create proxy with a non-object as target or handler");p=function(){f=function(a){throw new TypeError("Cannot perform '"+a+"' on a proxy that has been revoked");}};var e=b;b={get:null,set:null,apply:null,construct:null};for(var k in e){if(!(k in b))throw new TypeError("Proxy polyfill does not support trap '"+k+"'");b[k]=e[k]}"function"===
typeof e&&(b.apply=e.apply.bind(e));var c=this,g=!1,q=!1;"function"===typeof a?(c=function(){var h=this&&this.constructor===c,d=Array.prototype.slice.call(arguments);f(h?"construct":"apply");return h&&b.construct?b.construct.call(this,a,d):!h&&b.apply?b.apply(a,this,d):h?(d.unshift(a),new (a.bind.apply(a,d))):a.apply(this,d)},g=!0):a instanceof Array&&(c=[],q=!0);var r=b.get?function(a){f("get");return b.get(this,a,c)}:function(a){f("get");return this[a]},v=b.set?function(a,d){f("set");b.set(this,
a,d,c)}:function(a,b){f("set");this[a]=b},t={};Object.getOwnPropertyNames(a).forEach(function(b){if(!((g||q)&&b in c)){var d={enumerable:!!Object.getOwnPropertyDescriptor(a,b).enumerable,get:r.bind(a,b),set:v.bind(a,b)};Object.defineProperty(c,b,d);t[b]=!0}});e=!0;Object.setPrototypeOf?Object.setPrototypeOf(c,Object.getPrototypeOf(a)):c.__proto__?c.__proto__=a.__proto__:e=!1;if(b.get||!e)for(var m in a)t[m]||Object.defineProperty(c,m,{get:r.bind(a,m)});Object.seal(a);Object.seal(c);return c};g.revocable=
function(a,b){return{proxy:new g(a,b),revoke:p}};return g};var u="undefined"!==typeof process&&"[object process]"==={}.toString.call(process)||"undefined"!==typeof navigator&&"ReactNative"===navigator.product?global:self;u.Proxy||(u.Proxy=l(),u.Proxy.revocable=u.Proxy.revocable);})()
<commit_msg>bugfix<commit_after><|endoftext|>


<commit_before>/** 	Global js file for myGroceryBank application
 ** 	@author touzbi
 **/

$(document).ready(function() {

		var

		// JQuery elements
		$addItemBtn = $('#addItemBtn'),
		$itemName = $('#itemName'),
		$itemPrice = $('#itemPrice'),
		$messageLabel = $('#messageLabel'),
		$totalCount = $('#total'),
		$items = $('#items');

		// REST resources
		itemResourceURL = '/items';

		// Add an item to the system
		var addItem = function() {
			var itemName = $itemName.val();
			var itemPrice = $itemPrice.val();
			var item = { name: itemName, price: itemPrice };

			$.post(itemResourceURL, item).done(function(){
				$messageLabel.html('Item ' + itemName +' created');

				//Update item list at success
				getAllItems();
			});

		};

		// Get all registered items
		var getAllItems = function(){
			$.get(itemResourceURL, function(items) {

				var itemName, itemPrice, totalCount = 0,

				// Open table
					itemListContent = '

';

				// Data row
				$.each(items, function(i,item){
					itemName = item.name != null ? item.name : '_';
					itemPrice = item.price != null ? item.price : 0;
					itemListContent += '
' + itemName + '	' + itemPrice + '
';

					totalCount += itemPrice;
				})

				// Update total count
				$totalCount.html(totalCount);

				// Close table
				itemListContent += '

'

				// Render items
				$items.html(itemListContent);
			});
		}

		$addItemBtn.click(function() {
			addItem();
		});

		// Get all items at startup
		getAllItems();
	});<commit_msg>Refactoring<commit_after>/** 	Global js file for myGroceryBank application
 ** 	@author touzbi
 **/

$(document).ready(function() {

		var

		// JQuery elements
		$addItemBtn = $('#addItemBtn'),
		$itemName = $('#itemName'),
		$itemPrice = $('#itemPrice'),
		$messageLabel = $('#messageLabel'),
		$totalCount = $('#total'),
		$items = $('#items');

		// REST resources
		itemResourceURL = '/items';

		// Add an item to the system
		var addItem = function() {
			var itemName = $itemName.val();
			var itemPrice = $itemPrice.val();
			var item = { name: itemName, price: itemPrice };

			$.post(itemResourceURL, item).done(function(){
				$messageLabel.html('Item ' + itemName +' created');

				//Update item list after creating the item
				getAllItems();
			});

		};

		// Get all registered items
		var getAllItems = function(){
			$.get(itemResourceURL, function(items) {

				var itemName, itemPrice, totalCount = 0,

				// Open table
					itemListContent = '

';

				// Data row
				$.each(items, function(i,item){
					itemName = item.name != null ? item.name : '_';
					itemPrice = item.price != null ? item.price : 0;
					itemListContent += '
' + itemName + '	' + itemPrice + '
';

					totalCount += itemPrice;
				})

				// Update total count
				$totalCount.html(totalCount);

				// Close table
				itemListContent += '

'

				// Render items
				$items.html(itemListContent);
			});
		}

		$addItemBtn.click(function() {
			addItem();
		});

		// Get all items at startup
		getAllItems();
	});<|endoftext|>


<commit_before>var lats=[];
    var longs=[];
    var map;
    var markers=[];

    $(document).ready(function(){
      var arr = [];
      var arrSec = [];
      console.log('jquery is ready');

      $.ajax({
        url:'/data',
        type:'get',
        success:function(data){
          // console.dir(data);
          // console.dir(data[0]['primary_type']);
          fillCrimeSelector('#type','primary_type',data);
          console.log($('option:selected').val());
          for(var crime in data){
              // if($('option:selected').val()=='all'){
              //   addMarker(data[crime]);
              // }
             if(data[crime].primary_type==$('option:selected').val()){
              //  console.log(data[crime]);
               addMarker(data[crime]);
              //  console.log(markers);
            };//end of if statment
          }//end of for in loop

/////////////////////////change event listener
          $('#type').change(function(){
            // console.log($('option:selected').val());
            // console.log('yay!');
            $('#description').empty();
            removeMarkers(markers);
            redrawMap();
            console.log($('#type'));
            getIUCR($('#type').val());
          });//option:selected .change event listener
//////////////////////////////////////////////////////
          $('#description').change(function(){
            removeMarkers(markers);
            redrawMap();
            console.log('yoyoyoyoyo');

          });

        },
        error:function(err){
          console.log(err);
        }
      });//end of ajax call
    });//end of document.ready

///////////function definitions//////////////////////

function addMarker (data){
  var marker = new google.maps.Marker({
    position: {lat:parseFloat(data.latitude),lng:parseFloat(data.longitude)},
    map: map,
    icon:'http://megaicons.net/static/img/icons_sizes/15/534/32/map-marker-ball-left-pink-icon.png',
    title: data.primary_type+' ---- '+data.description+' ---- '+data.date,
    animation:google.maps.Animation.DROP
  });// end of marker constructor
  markers.push(marker);
}

function removeMarkers(arr){
  for(var i in arr){
    arr[i].setMap(null);
  }
}
function redrawMap(){
  var arr=[];
  var arrDes=[];
  $.ajax({
    url:'/data',
    type:'get',
    success:function(data){
      // console.dir(data);
      for(var crime in data){
        if(arr.indexOf(data[crime].primary_type) == -1){
          arr.push(data[crime].primary_type);
        }//end of if statment

        //comparing value from first dropdown to looped
         if(data[crime].primary_type==$('#type option:selected').val() && $('#description option:selected').val()=='All Subtypes'){
          //  console.log(data[crime]);
           addMarker(data[crime]);
          //  console.log(markers);
        }//end of if statment

        if(data[crime].primary_type==$('#type option:selected').val() && $('#description option:selected').val()==data[crime].description){
          addMarker(data[crime]);
        }//end of if statment

      }//end of for-loop
    },
    error:function(err){
      console.log(err);
    }
  });//end of $.ajax

}//end of draw map function

function initMap() {
  var myLatLng = {lat: 41.845652363, lng: -87.636561415};

   map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: myLatLng
  });
}//end of initMap function

function fillCrimeSelector(id,field,data){
  var arr=[];
  var desc=[];
  for(var crime in data){
    // console.dir(data[crime][field]);
    if(arr.indexOf(data[crime][field]) == -1){
      arr.push(data[crime][field]);
      // console.log('new type!', data[crime][field]);
        $(id).append('<option id="'+data[crime][field]+'"  value="'+data[crime][field]+'">'+data[crime][field]+'</option>');

    }//end of if statment

  }//end of for-in loop

}//end of fillSelector function

// $.post('/api',{name:'Terry'}, function(data){
//   console.log(data);
// });

// getIUCR('ROBBERY');

function getIUCR(crime){
  $.ajax({
    url:'https://data.cityofchicago.org/resource/c7ck-438e.json',
    type:'get',
    success:function(data){
      var arr=[];
      console.log(data);
      for(var x in data){
        if(data[x].primary_description==crime){
          console.log(data[x]);
          arr.push(data[x].secondary_description);
        }
      }
      console.log('arr: ',arr);
      $('#description').append('<option id="All Subtypes" value="All Subtypes">ALL SUBTYPES</option>');
      for(var i in arr){
        $('#description').append('<option class="poop" id="'+arr[i]+'" value="'+arr[i]+'">'+arr[i]+'</option>');
      }

    },
    error:function(err){
      console.log(err);
    }
  });
}//end getIUCR function
<commit_msg>trying to merge.<commit_after>var lats=[];
var longs=[];
var map;
var markers=[];

$(document).ready(function(){
  var arr = [];

  console.log('jquery is ready');

  $.ajax({
    url:'/data',
    type:'get',
    success:function(data){

      var date = new Date;
      $('#endDate').val(parseDateString(date))

      console.dir(data);
      var thing = data[0].date
      console.log(thing);
      // console.dir(data[0]['primary_type']);

      fillCrimeSelector('#type','primary_type',data);
      console.log($('option:selected').val());
      for(var crime in data){
          // if($('option:selected').val()=='all'){
          //   addMarker(data[crime]);
          // }
         if(data[crime].primary_type==$('option:selected').val()){
          //  console.log(data[crime]);
           addMarker(data[crime]);
          //  console.log(markers);
        };//end of if statment
      }//end of for in loop

/////////////////////////change event listener

      $('#type').change(function(){
        // console.log($('option:selected').val());
        // console.log('yay!');
        $('#description').empty();
        removeMarkers(markers);
        redrawMap();
        console.log($('#type'));
        getIUCR($('#type').val());
      });//option:selected .change event listener

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

      $('#description').change(function(){
        removeMarkers(markers);
        redrawMap();
        console.log('yoyoyoyoyo');

      });//end of #description event listener

      $('#startDate').change(function(){
        console.log('hello world!');
        removeMarkers(markers);
        redrawMap();
      });

      $('#endDate').change(function(){
        console.log('end world!');
        removeMarkers(markers);
        redrawMap();
      });

    },
    error:function(err){
      console.log(err);
    }
  });//end of ajax call
});//end of document.ready

///////////function definitions//////////////////////

function addMarker (data){
var marker = new google.maps.Marker({
position: {lat:parseFloat(data.latitude),lng:parseFloat(data.longitude)},
map: map,
icon:'http://megaicons.net/static/img/icons_sizes/15/534/32/map-marker-ball-left-pink-icon.png',
title: data.primary_type+' ---- '+data.description+' ---- '+data.date,
animation:google.maps.Animation.DROP
});// end of marker constructor
markers.push(marker);
}

function removeMarkers(arr){
for(var i in arr){
arr[i].setMap(null);
}
}
function redrawMap(){
var arr=[];
var arrDes=[];
$.ajax({
url:'/data',
type:'get',
success:function(data){
  // console.dir(data);
  for(var crime in data){
    if(arr.indexOf(data[crime].primary_type) == -1){
      arr.push(data[crime].primary_type);
    }//end of if statment

    //comparing value from first dropdown to looped
     if(data[crime].primary_type==$('#type option:selected').val() && $('#description option:selected').val()=='All Subtypes') {
       if(isDateInRange(Date.parse(data[crime].date),Date.parse($('#startDate').val()),Date.parse($('#endDate').val()))){
      //  console.log(data[crime]);
       addMarker(data[crime]);
     }
      //  console.log(markers);
    }//end of if statment

    if(data[crime].primary_type==$('#type option:selected').val() && $('#description option:selected').val()==data[crime].description && isDateInRange(Date.parse(data[crime].date),Date.parse($('#startDate').val()),Date.parse($('#endDate').val()))){
      addMarker(data[crime]);
    }//end of if statment

  }//end of for-loop
},
error:function(err){
  console.log(err);
}
});//end of $.ajax

}//end of draw map function

function initMap() {
//chicago coordinates to center the map
var myLatLng = {lat: 41.845652363, lng: -87.636561415};

map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: myLatLng
});
}//end of initMap function

function fillCrimeSelector(id,field,data){
var arr=[];
var desc=[];
for(var crime in data){
// console.dir(data[crime][field]);
if(arr.indexOf(data[crime][field]) == -1){
  arr.push(data[crime][field]);
  // console.log('new type!', data[crime][field]);
    $(id).append('<option id="'+data[crime][field]+'"  value="'+data[crime][field]+'">'+data[crime][field]+'</option>');

}//end of if statment

}//end of for-in loop

}//end of fillSelector function

function getIUCR(crime){
$.ajax({
url:'https://data.cityofchicago.org/resource/c7ck-438e.json',
type:'get',
success:function(data){
  var arr=[];
  console.log(data);
  for(var x in data){
    if(data[x].primary_description==crime){
      console.log(data[x]);
      arr.push(data[x].secondary_description);
    }
  }
  console.log('arr: ',arr);
  $('#description').append('<option id="All Subtypes" value="All Subtypes">ALL SUBTYPES</option>');
  for(var i in arr){
    $('#description').append('<option class="poop" id="'+arr[i]+'" value="'+arr[i]+'">'+arr[i]+'</option>');
  }

},
error:function(err){
  console.log(err);
}
});
}//end getIUCR function

function parseDateString(date){
date=date.toString();
var arr=date.split(' ');
return arr[3]+'-'+getNumberMonthFromName(arr[1])+'-'+arr[2];
}

function getNumberMonthFromName(str){
if(str=='Jan'){
return '01'
}
if(str == 'Feb'){
return '02'
}
if(str == 'Mar'){
return '03'
}
if(str == 'Apr'){
return '04'
}
if(str == 'May'){
return '05'
}
if(str == 'Jun'){
return '06'
}
if(str == 'Jul'){
return '07'
}
if(str == 'Aug'){
return '08'
}
if(str == 'Sep'){
return '09'
}
if(str == 'Oct'){
return '10'
}
if(str == 'Nov'){
return '11'
}
if(str == 'Dec'){
return '12'
}
}

//takes in a UTC dates in miliseconds and returns true/false if is within those ranges
function isDateInRange(testDate,startDate,endDate){
if ( startDate <= testDate && testDate <= endDate ) {
  console.log('date is in range');
  return true;
} else {
  console.log('date is not in range');
  return false;
}
}
<|endoftext|>