text:
var myApp = angular.module('myModule', ['ngSanitize']).run([
    '$templateCache','$window',
    function ($templateCache, $window) {
        var w = angular.element($window);
        var height = w.height() - 140;
        var left = w.width() - 340;
        $templateCache.put('/tmpls/draggable-default', '

');
        $templateCache.put('/tmpls/myTemplate', '

');
        $templateCache.put('/tmpls/searchTemplate', '

EXPLORE THE DATA:

');
        $templateCache.put('/tmpls/selectTemplate', '

CHANGE VISUALIZATION:

');

        var chart = angular.element('.chart');
        chart.css("height", w.height() - 130);

        w.bind('resize', function () {
            var height = w.height() - 140;
            var left = w.width() - 340;
            var selectPanel = angular.element('.selectPanel');

            chart.css("height", w.height() - 130);
            selectPanel.css('top',height);
            selectPanel.css('left',left);
        });
    }
]).controller('dragCtrlr', [
    '$scope',
    function ($scope) {
        var obj = {
            id: null,
            content: null,
            group: null
        };
        $scope.obj = angular.copy(obj);
        $scope.$on('drag.started', function (evt, data) {
            if (angular.isDefined(data.obj))
                $scope.obj = data.obj;
        });
        $scope.$on('drag.stopped', function (evt, data) {
            $scope.obj = angular.copy(obj);
        });

        $scope.toggle = function($event, field, event) {
            $event.preventDefault();
            $event.stopPropagation();
            event[field] = !event[field];
        };
    }

]).directive('draggable', [
    '$compile',
    function ($compile, $window) {
        return {
            restrict: 'E',
            transclude: true,
            replace: true,
            scope: {},
            templateUrl: function (el, attrs) {
                return angular.isDefined(attrs.template) ? attrs.template : '/tmpls/draggable-default';
            },
            link: function (scope, el, attrs, ctrlr, transFn) {
                scope.obj = {
                    id: null,
                    content: '',
                    group: null
                };
                scope.placeholder = false;
                transFn(scope, function (clone, innerScope) {
                    var dummy = angular.element('

');
                    dummy.append($compile(clone)(innerScope));
                    scope.obj.content = dummy.html();
                    dummy = null;
                    scope.obj.content = scope.obj.content.replace(/([^<]+)<\/span>/gi, '$1');
                    scope.obj.content = scope.obj.content.replace(/\s*ng\-scope\s*/gi, '');
                    scope.obj.content = scope.obj.content.replace(/\s*class\=\"\"\s*/gi, '');
                });
                if (angular.isDefined(attrs.id))
                    scope.obj.id = attrs.id;
                if (angular.isDefined(attrs.placeholder))
                    scope.placeholder = scope.$eval(attrs.placeholder);
                var opts = angular.isDefined(attrs.options) ? scope.$eval(attrs.options) : {};
                if (angular.isDefined(attrs.group)) {
                    scope.obj.group = attrs.group;
                    opts.stack = '.' + attrs.group;
                }
                var evts = {
                    start: function (evt, ui) {
                        if (scope.placeholder)
                            ui.helper.wrap('

');
                        scope.$apply(function () {
                            scope.$emit('drag.started', { obj: scope.obj });
                        });
                    },
                    drag: function (evt) {
                        scope.$apply(function () {
                            scope.$emit('drag.dragging', { obj: scope.obj });
                        });
                    },
                    stop: function (evt, ui) {
                        if (scope.placeholder)
                            ui.helper.unwrap();
                        scope.$apply(function () {
                            scope.$emit('drag.stopped', { obj: scope.obj });
                        });
                    }
                };
                var options = $.extend({}, opts, evts);
                el.draggable(options);
            }
        };
    }
]).service('sharedProperties', function () {
        var iFilter;
        var iDisplay = "map";
        var iGroupBy = "event_type";

        return {
            getFilter: function () {
                return iFilter;
            },
            setFilter: function(value) {
                iFilter = value;
            },
            getDisplay: function () {
                return iDisplay;
            },
            setDisplay: function(value) {
                iDisplay = value;
            },
            getGroupBy: function () {
                return iGroupBy;
            },
            setGroupBy: function(value) {
                iGroupBy = value;
            },
        };
    });

myApp.directive("datepicker", function () {
  return {
    restrict: "A",
    require: "ngModel",
    link: function (scope, elem, attrs, ngModelCtrl) {
        var $startImg = angular.element('.cal_start_img');
        var $startInput = angular.element('#startInput');
        $startImg.on('click',function(){
            if($startInput.is(':focus')){
                $startInput.trigger('blur');
            } else {
                $startInput.trigger('focus');
            }
        });

       var $endImg = angular.element('.cal_end_img');
       var $endInput = angular.element('#endInput');
       $endImg.on('click',function(){
            if($endInput.is(':focus')){
                $endInput.trigger('blur');
            } else {
                $endInput.trigger('focus');
            }
       });

      /*
      var updateModel = function (dateText) {
        scope.$apply(function () {
          ngModelCtrl.$setViewValue(dateText);
        });
      };

      var options = {
        dateFormat: "mm/dd/yy",
        onSelect: function (dateText) {
          updateModel(dateText);
        }
      };

     var options = {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'M yy',
        onSelect: function (dateText) {
            updateModel(dateText);
        },
        onClose: function(dateText, inst) {
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
     };
      elem.datepicker(options);
        */
    }
  }
});

myApp.controller('searchController', function ($scope, $window, deviceRepository) {
   var mainMap = angular.element('.mainMap');
   var window = angular.element($window);
   mainMap.css("height", window.height() - 123);

   window.bind('resize', function () {
       mainMap.css("height", window.height() - 123);
    });
});
myApp.controller('deviceController', function ($scope, deviceRepository, deviceAddressRepository, earthquakeRepository, sharedProperties) {
    $scope.deviceTypeOptions = [{
        name: 'pump',
        value: 'pump'
    }, {
        name: 'infusion',
        value: 'infusion'
    },{
        name: 'implantable',
        value: 'implantable'
    },{
        name: 'system',
        value: 'system'
    },{
        name: 'glucose',
        value: 'glucose'
    },{
        name: 'monitoring',
        value: 'monitoring'
    },{
        name: 'insulin',
        value: 'insulin'
    }];

    $scope.manuLocationOptions = [{
        name: 'Juncos',
        value: 'juncos'
    }, {
        name: 'West',
        value: 'west'
    }, {
        name: 'Chester',
        value: 'chester'
    }, {
        name: 'Lake',
        value: 'lake'
    }, {
        name: 'Salt',
        value: 'salt'
    }, {
        name: 'Zug',
        value: 'zug'
    }, {
        name: 'Indianapolis',
        value: 'indianapolis'
    }];

    $scope.eventTypeOptions = [{
        name: 'malfunction',
        value: 'malfunction'
    }, {
        name: 'injury',
        value: 'injury'
    }, {
        name: 'death',
        value: 'death'
    }, {
        name: 'other',
        value: 'other'
    }, {
        name: 'provided',
        value: 'provided'
    }];

    $scope.eventLocationOptions = [{
        name: 'hospital',
        value: 'hospital'
    }, {
        name: 'other',
        value: 'other'
    }, {
        name: 'ambulatory',
        value: 'ambulatory'
    }, {
        name: 'surgical',
        value: 'surgical'
    }, {
        name: 'nursing',
        value: 'nursing'
    }];

    $scope.loadMapView = function() {
        sharedProperties.setDisplay("map");
        var map = angular.element('#map');
        var chart = angular.element('.chartWrapper');
        var pie = angular.element('#pieChart');
        var stack = angular.element('#stackDiv');

        stack.hide();
        chart.hide();
        pie.hide();
        map.show();
        $scope.applySearch();
    };

    $scope.loadStackView = function() {
        sharedProperties.setDisplay("stack");
        var stack = angular.element('#stackDiv');
        var map = angular.element('#map');
        var chart = angular.element('.chartWrapper');
        var pie = angular.element('#pieChart');

        chart.hide();
        pie.hide();
        map.hide();
        stack.show();
        $scope.applySearch();
    };

    $scope.loadGraphView = function() {
        sharedProperties.setDisplay("graph");
        var map = angular.element('#map');
        var chart = angular.element('.chartWrapper');
        var pie = angular.element('#pieChart');
        var stack = angular.element('#stackDiv');

        stack.hide();
        map.hide();
        pie.hide();
        chart.show();
        $scope.applySearch();
    };

    $scope.loadPieView = function() {
        sharedProperties.setDisplay("pie");
        var map = angular.element('#map');
        var chart = angular.element('.chartWrapper');
        var pie = angular.element('#pieChart');
        var stack = angular.element('#stackDiv');

        stack.hide();
        map.hide();
        chart.hide();
        pie.show();
        $scope.applySearch();
    };

    $scope.openStartCalendar = function() {
        var options = {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'mm/yy',
            onClose: function(dateText, inst) {
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            }
        };

      /*
        var options = {
            dateFormat: "mm/dd/yy"
        };
        */
        var elem = angular.element('#startInput');
        elem.datepicker(options);
    };

    $scope.openEndCalendar = function() {
        var options = {
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'mm/yy',
            onClose: function(dateText, inst) {
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

                $(this).datepicker('setDate', new Date(year, month, 1));
            }
        };

      /*
         var options = {
            dateFormat: "mm/dd/yy"
        };
        */
        var elem = angular.element('#endInput');
        elem.datepicker(options);
    };

    $scope.updateFilter = function () {

    };

    $scope.clearSearch = function () {
        if ($scope.filter) {
            $scope.filter.type1 = 0;
            $scope.filter.type2 = 0;
            $scope.filter.type3 = 0;
            $scope.filter.type4 = 0;
            sharedProperties.setFilter($scope.filter);
        }
        var $startInput = angular.element('#startInput');
        var $endInput = angular.element('#endInput');
        $startInput.val("");
        $endInput.val("");
    };

    $scope.getToday = function() {
        return "20150628";
    };

    $scope.applySearch = function () {
        var gotFirst = false;
        var searchString = "";
        var searchDatesOnly = "";

        if ($scope.filter) {
            sharedProperties.setFilter($scope.filter);
        }

        var filter = sharedProperties.getFilter();
        var $startInput = angular.element('#startInput');
        var $endInput = angular.element('#endInput');
        var startDate = $startInput.val();
        var endDate = $endInput.val();

        if (startDate != "" || endDate != "" || filter) {
            if (startDate != "") {
                var temp = startDate.split("/");
                startDate = temp[1] + temp[0] + "01";
            }
            if (endDate != "") {
                var temp = endDate.split("/");
                var tempDate = new Date(+temp[1], +temp[0], 0);
                endDate = tempDate.toISOString().substring(0, 10).replace("-", "").replace("-", "");
            }

            if (startDate != "" && endDate == "") {
                alert("Please select an end date");
                return;
            }

            if (endDate != "" && startDate == "") {
                alert("Please select a start date");
                return;
            }

            if (endDate != "" || startDate != "") {
                gotFirst = true;
                searchString += "date_of_event:[" + startDate + "+TO+" + endDate + "]";
                searchDatesOnly += "event_date:[" + startDate + "+TO+" + endDate + "]";
            }
            else {
                alert("Please select a date range");
                return;
            }

            if (filter) {
                if (filter.type1 && filter.type1 != "") {
                    if (gotFirst) {
                        searchString += "\+AND\+";
                    }
                    gotFirst = true;
                    searchString += "device.generic_name:" + filter.type1;
                }

                if (filter.type2 && filter.type2 != "") {
                    if (gotFirst) {
                        searchString += "\+AND\+";
                    }
                    gotFirst = true;
                    searchString += "device.generic_name:" + filter.type2;
                }

                if (filter.type3 && filter.type3 != "") {
                    if (gotFirst) {
                        searchString += "\+AND\+";
                    }
                    gotFirst = true;
                    searchString += "event_type:" + filter.type3;
                }

                if (filter.type4 && filter.type4 != "") {
                    if (gotFirst) {
                        searchString += "\+AND\+";
                    }
                    gotFirst = true;
                    searchString += "event_location:" + filter.type4;
                }
            }

            if (searchString != "" && searchDatesOnly != "") {
               if(sharedProperties.getDisplay() == "stack") {
                   d3.selectAll("#stackDiv > svg").remove();
                    var parseDate = d3.time.format("%Y%m").parse,
                        formatYear = d3.format("02d"),
                        formatDate = function(d) {
                            return (d.getMonth() + 1) + "/" + d.getFullYear();
                        };

                    var margin = {top: 10, right: 20, bottom: 20, left: 90},
                        width = 960 - margin.left - margin.right,
                        height = 500 - margin.top - margin.bottom;

                    var y0 = d3.scale.ordinal()
                        .rangeRoundBands([height, 0], .2);

                    var y1 = d3.scale.linear();

                    var x = d3.scale.ordinal()
                        .rangeRoundBands([0, width], .1, 0);

                    var xAxis = d3.svg.axis()
                        .scale(x)
                        .orient("bottom")
                        .tickFormat(formatDate);

                    var nest = d3.nest()
                        .key(function(d) { return d.group; });

                    var stack = d3.layout.stack()
                        .values(function(d) { return d.values; })
                        .x(function(d) { return d.date; })
                        .y(function(d) { return d.value; })
                        .out(function(d, y0) {
                            d.valueOffset = y0;
                        });

                    var color = d3.scale.category10();

                    var svg = d3.select("#stackDiv").append("svg")
                        .attr("width", width + margin.left + margin.right)
                        .attr("height", height + margin.top + margin.bottom)
                      .append("g")
                        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

                    deviceRepository.doSearch(searchString).
                    success(function (data) {
                        var allData = [];
                        var allDataIdx = 0;

                        if (data && data.results) {
                            var eventData = {};
                            for (var idx in data.results) {
                                var event = data.results[idx];
                                var dateGroup = event.date_of_event.substring(0,6);
                                if (!eventData[dateGroup]) {
                                    eventData[dateGroup] = 1;
                                }
                                else {
                                    eventData[dateGroup]++;
                                }
                            }

                            for (var eventDate in eventData) {
                                allData[allDataIdx] = {"group": "Device Events", "date":parseDate(eventDate), "value":+eventData[eventDate]};
                                allDataIdx++;
                            }
                        }

                        earthquakeRepository.doSearch(searchDatesOnly).
                        success(function (data) {

                            var earthquakeData = {};
                            for (var idx in data.results) {
                                var earthquake = data.results[idx];
                                var dateGroup = earthquake.event_date.substring(0,7).replace("-","");
                                if (!earthquakeData[dateGroup]) {
                                    earthquakeData[dateGroup] = 1;
                                }
                                else {
                                    earthquakeData[dateGroup]++;
                                }
                            }

                            for (var eqDate in earthquakeData) {
                                allData[allDataIdx] = {"group": "Earthquakes", "date":parseDate(eqDate), "value":+earthquakeData[eqDate]};
                                allDataIdx++;
                            }

                           /*
                            var data = [
                                {"group":"Device Events","date":"2008-01","value":"10"},
                                {"group":"Device Events","date":"2008-04","value":"8"},
                                {"group":"Device Events","date":"2008-07","value":"14"},
                                {"group":"Device Events","date":"2008-10","value":"9"},
                                {"group":"Device Events","date":"2009-01","value":"10"},
                                {"group":"Device Events","date":"2009-04","value":"8"},
                                {"group":"Device Events","date":"2009-07","value":"14"},
                                {"group":"Device Events","date":"2009-10","value":"9"},
                                {"group":"Earthquakes","date":"2008-01","value":"3"},
                                {"group":"Earthquakes","date":"2008-04","value":"3.5"},
                                {"group":"Earthquakes","date":"2008-07","value":"5"},
                                {"group":"Earthquakes","date":"2008-10","value":"11"},
                                {"group":"Earthquakes","date":"2009-01","value":"3"},
                                {"group":"Earthquakes","date":"2009-04","value":"3.5"},
                                {"group":"Earthquakes","date":"2009-07","value":"4.5"},
                                {"group":"Earthquakes","date":"2009-10","value":"10.5"},
                                {"group":"Solar Flares","date":"2008-01","value":"10"},
                                {"group":"Solar Flares","date":"2008-04","value":"8"},
                                {"group":"Solar Flares","date":"2008-07","value":"14"},
                                {"group":"Solar Flares","date":"2008-10","value":"9"},
                                {"group":"Solar Flares","date":"2009-01","value":"10"},
                                {"group":"Solar Flares","date":"2009-04","value":"8"},
                                {"group":"Solar Flares","date":"2009-07","value":"14"},
                                {"group":"Solar Flares","date":"2009-10","value":"9"}
                            ];
                            data.forEach(function(d) {
                              d.date = parseDate(d.date);
                              d.value = +d.value;
                            });
                            */

                            var dataByGroup = nest.entries(allData);

                            stack(dataByGroup);
                            x.domain(dataByGroup[0].values.map(function(d) { return d.date; }));
                            y0.domain(dataByGroup.map(function(d) { return d.key; }));
                            y1.domain([0, d3.max(allData, function(d) { return d.value; })]).range([y0.rangeBand(), 0]);

                            var group = svg.selectAll(".group")
                                .data(dataByGroup)
                              .enter().append("g")
                                .attr("class", "group")
                                .attr("transform", function(d) { return "translate(0," + y0(d.key) + ")"; });

                            group.append("text")
                                .attr("class", "group-label")
                                .attr("x", -6)
                                .attr("y", function(d) { return y1(d.values[0].value / 2); })
                                .attr("dy", ".35em")
                                .text(function(d) { return d.key; });

                            group.selectAll("rect")
                                .data(function(d) { return d.values; })
                              .enter().append("rect")
                                .style("fill", function(d) { return color(d.group); })
                                .attr("x", function(d) { return x(d.date); })
                                .attr("y", function(d) {
                                    return y1(d.value);
                                })
                                .attr("width", x.rangeBand())
                                .attr("height", function(d) { return y0.rangeBand() - y1(d.value); });

                            group.filter(function(d, i) { return !i; }).append("g")
                                .attr("class", "x axis")
                                .attr("transform", "translate(0," + y0.rangeBand() + ")")
                                .call(xAxis);

                            d3.selectAll("input").on("change", change);

                            var timeout = setTimeout(function() {
                              d3.select("input[value=\"stacked\"]").property("checked", true).each(change);
                            }, 2000);

                            function change() {
                              clearTimeout(timeout);
                              if (this.value === "multiples") transitionMultiples();
                              else transitionStacked();
                            }

                            function transitionMultiples() {
                              var t = svg.transition().duration(750),
                                  g = t.selectAll(".group").attr("transform", function(d) { return "translate(0," + y0(d.key) + ")"; });
                              g.selectAll("rect").attr("y", function(d) { return y1(d.value); });
                              g.select(".group-label").attr("y", function(d) { return y1(d.values[0].value / 2); })
                            }

                            function transitionStacked() {
                              var t = svg.transition().duration(750),
                                  g = t.selectAll(".group").attr("transform", "translate(0," + y0(y0.domain()[0]) + ")");
                              g.selectAll("rect").attr("y", function(d) {
                                  return y1(d.value + d.valueOffset);
                              });
                              g.select(".group-label").attr("y", function(d) {
                                  return y1(d.values[0].value / 2 + d.values[0].valueOffset);
                              })
                            }
                        }).
                        error(function (data) {
                            alert("An error has occurred.");
                        });
                    }).
                    error(function (data) {
                        alert("An error has occurred.");
                    });
                }
                else if(sharedProperties.getDisplay() == "pie") {
                    d3.selectAll("#pieChart > *").remove();

                    searchString += "&count=" + sharedProperties.getGroupBy();
                    deviceRepository.doSearch(searchString).
                    success(function (data) {
                        if (data && data.results) {
                            var pieResults = $scope.convertToPie(data.results);
                            var pie = new d3pie("pieChart", {
                                "size": {
                                    "canvasWidth": 500,
                                    "canvasHeight": 500,
                                    "pieOuterRadius": "90%"
                                },
                                "data": {
                                    "sortOrder": "value-desc",
                                    "content": pieResults
                                },
                                "labels": {
                                    "outer": {
                                        "pieDistance": 32
                                    },
                                    "inner": {
                                        "hideWhenLessThanPercentage": 3
                                    },
                                    "mainLabel": {
                                        "fontSize": 11
                                    },
                                    "percentage": {
                                        "color": "#ffffff",
                                        "decimalPlaces": 0
                                    },
                                    "value": {
                                        "color": "#adadad",
                                        "fontSize": 11
                                    },
                                    "lines": {
                                        "enabled": true
                                    },
                                    "truncation": {
                                        "enabled": true
                                    }
                                },
                                "effects": {
                                    "pullOutSegmentOnClick": {
                                        "effect": "linear",
                                        "speed": 400,
                                        "size": 8
                                    }
                                }
                            });
                        }
                    }).
                    error(function (data) {
                        alert("An error has occurred.");
                    });
                }
                else if(sharedProperties.getDisplay() == "graph") {
                    searchString += "&count=" + sharedProperties.getGroupBy();
                    deviceRepository.doSearch(searchString).
                    success(function (data) {
                        if (data && data.results) {

                            var width = angular.element(window)[0].innerWidth - 55,
                                barHeight = 20,
                                height = 100;

                            d3.selectAll(".chart > *").remove();

                            //if ($scope.chart.type == "Horizontal") {
                            var x = d3.scale.linear().range([0, width]);
                            var chart = d3.select(".chart").attr("width", "100%");

                            x.domain([0, d3.max(data.results, function (d) {
                                return d.count;
                            })]);

                            chart.attr("height", barHeight * data.results.length);
                            var bar = chart.selectAll("g")
                                .data(data.results)
                                .enter().append("g")
                                .attr("transform", function (d, i) {
                                return "translate(0," + i * barHeight + ")";
                            });
                            bar.append("rect")
                                .attr("width", function (d) {
                                return x(d.count);
                            }).attr("height", barHeight - 1);

                            bar.append("text").attr("x", function (d) {
                                return 1;
                            })
                            .attr("y", barHeight / 2)
                            .attr("dy", ".35em")
                            .text(function (d) {
                                return "(" + d.term.toUpperCase() + ") " + d.count;
                            });
                        }
                    }).
                    error(function (data) {
                        alert("An error has occurred.");
                    });
                }
                else {
                    deviceRepository.doSearch(searchString).
                    success(function (data) {
                        clearLayer();
                        if (searchDatesOnly != "") {
                            earthquakeRepository.doSearch(searchDatesOnly).success(function (data) {
                                if (data && data.results) {
                                    for (var idx in data.results) {
                                        loadEarthquakeResults(data.results[idx].lat, data.results[idx].lon);
                                    }
                                }
                            }).error(function (data) {
                                alert("An error has occurred.");
                            });
                        }
                        if (data && data.results) {
                            for (var idx in data.results) {
                                var device = data.results[idx];
                                if (device.manufacturer_city != "" && device.manufacturer_state != "" && device.manufacturer_country != "") {
                                    deviceAddressRepository.doAddressLookup(device.manufacturer_address_1, device.manufacturer_city, device.manufacturer_state, device.manufacturer_country).
                                    success(function (data) {
                                        if (data && data.length > 0) {
                                            loadSearchResults(data[0].lat, data[0].lon);
                                        }
                                    }).
                                    error(function (data) {
                                        alert("An error has occurred.");
                                    });
                                }
                            }
                        }
                    }).
                    error(function (data) {
                        alert("An error has occurred.");
                    });
                }
            }
        }
    };

    $scope.convertToPie = function(results) {
        var content = [];
        for (var idx in results) {
            content[idx] = {"label": results[idx].term, "value": results[idx].count};
        }
        return content;
    };

    $scope.getDeviceInfo = function () {
        deviceRepository.doSearch($scope.locationName, $scope.filter.type1).
            success(function (data) {
                if (data && data.results) {
                    var width = angular.element(window)[0].innerWidth - 55,
                        barHeight = 20,
                        height = 900;

                    d3.selectAll(".chart > *").remove();

                    //if ($scope.chart.type == "Horizontal") {
                    var x = d3.scale.linear().range([0, width]);
                    var chart = d3.select(".chart").attr("width", "100%");

                    x.domain([0, d3.max(data.results, function (d) {
                        return d.count;
                    })]);

                    chart.attr("height", barHeight * data.results.length);
                    var bar = chart.selectAll("g")
                        .data(data.results)
                        .enter().append("g")
                        .attr("transform", function (d, i) {
                        return "translate(0," + i * barHeight + ")";
                    });
                    bar.append("rect")
                        .attr("width", function (d) {
                        return x(d.count);
                    }).attr("height", barHeight - 1);

                    bar.append("text").attr("x", function (d) {
                        return 1;
                    })
                    .attr("y", barHeight / 2)
                    .attr("dy", ".35em")
                    .text(function (d) {
                        return "(" + d.term.toUpperCase() + ") " + d.count;
                    });
                }
            }).
            error(function (data) {
                alert("An error has occurred.");
            });
    };

});

myApp.factory('deviceRepository', function ($http) {
    return {
        doSearch: function (searchString) {
            var url = "http://api.fda.gov/device/event.json?search=" + searchString + "&limit=50";
            return $http.get(url, {
                params: {
                }
            });
        }
    }
});

myApp.factory('deviceAddressRepository', function ($http) {
    return {
        doAddressLookup: function (street, city, state, country) {
            var url = 'http://nominatim.openstreetmap.org/search';
            return $http.get(url, {
                params: {
                    format: "json",
                    limit: 1,
                    street: street,
                    city: city,
                    state: state,
                    country: country
                }
            });
        }
    }
});


text:
<?php

class PostsController extends BaseController{

	function show($postID){
		if($post = Post::find($postID)){
			$comments = Comment::where('postid','=',$postID)->get();
			return View::make('viewpost',['post'=>$post, 'comments'=>$comments]);
		}

		return Redirect::to('/');
	}

	function create(){
		if(Auth::check())
			return View::make('admin.admin');
		else
			return Redirect::to('/login');
	}

	function store() {
		$post = new Post;
		$post->title = Input :: get ('title');
		$post->body = Input :: get ('body');
		$post->save();

	   return Redirect::to('/');
	}

}

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <asm/tm.h>
#include <asm/cputable.h>
#include <linux/auxvec.h>
#include <sys/time.h>
#include <stdlib.h>

#include "utils.h"

extern int getppid_tm_active(void);
extern int getppid_tm_suspended(void);

unsigned retries = 0;

#define TEST_DURATION 10 /* seconds */
#define TM_RETRIES 100

long failure_code(void)
{
	return __builtin_get_texasru() >> 24;
}

bool failure_is_persistent(void)
{
	return (failure_code() & TM_CAUSE_PERSISTENT) == TM_CAUSE_PERSISTENT;
}

bool failure_is_syscall(void)
{
	return (failure_code() & TM_CAUSE_SYSCALL) == TM_CAUSE_SYSCALL;
}

pid_t getppid_tm(bool suspend)
{
	int i;
	pid_t pid;

	for (i = 0; i < TM_RETRIES; i++) {
		if (suspend)
			pid = getppid_tm_suspended();
		else
			pid = getppid_tm_active();

		if (pid >= 0)
			return pid;

		if (failure_is_persistent()) {
			if (failure_is_syscall())
				return -1;

			printf("Unexpected persistent transaction failure.\n");
			printf("TEXASR 0x%016lx, TFIAR 0x%016lx.\n",
			       __builtin_get_texasr(), __builtin_get_tfiar());
			exit(-1);
		}

		retries++;
	}

	printf("Exceeded limit of %d temporary transaction failures.\n", TM_RETRIES);
	printf("TEXASR 0x%016lx, TFIAR 0x%016lx.\n",
	       __builtin_get_texasr(), __builtin_get_tfiar());

	exit(-1);
}

static inline bool have_htm_nosc(void)
{
#ifdef PPC_FEATURE2_HTM_NOSC
	return ((long)get_auxv_entry(AT_HWCAP2) & PPC_FEATURE2_HTM_NOSC);
#else
	printf("PPC_FEATURE2_HTM_NOSC not defined, can't check AT_HWCAP2\n");
	return false;
#endif
}

int tm_syscall(void)
{
	unsigned count = 0;
	struct timeval end, now;

	SKIP_IF(!have_htm_nosc());

	setbuf(stdout, NULL);

	printf("Testing transactional syscalls for %d seconds...\n", TEST_DURATION);

	gettimeofday(&end, NULL);
	now.tv_sec = TEST_DURATION;
	now.tv_usec = 0;
	timeradd(&end, &now, &end);

	for (count = 0; timercmp(&now, &end, <); count++) {
		/*
		 * Test a syscall within a suspended transaction and verify
		 * that it succeeds.
		 */
		FAIL_IF(getppid_tm(true) == -1); /* Should succeed. */

		/*
		 * Test a syscall within an active transaction and verify that
		 * it fails with the correct failure code.
		 */
		FAIL_IF(getppid_tm(false) != -1);  /* Should fail... */
		FAIL_IF(!failure_is_persistent()); /* ...persistently... */
		FAIL_IF(!failure_is_syscall());    /* ...with code syscall. */
		gettimeofday(&now, 0);
	}

	printf("%d active and suspended transactions behaved correctly.\n", count);
	printf("(There were %d transaction retries.)\n", retries);

	return 0;
}

int main(void)
{
	return test_harness(tm_syscall, "tm_syscall");
}


text:
namespace org.apache.lucene.analysis.fi
{

	using CharArraySet = org.apache.lucene.analysis.util.CharArraySet;

	public class TestFinnishAnalyzer : BaseTokenStreamTestCase
	{
	  /// <summary>
	  /// This test fails with NPE when the
	  /// stopwords file is missing in classpath
	  /// </summary>
	  public virtual void testResourcesAvailable()
	  {
		new FinnishAnalyzer(TEST_VERSION_CURRENT);
	  }

	  /// <summary>
	  /// test stopwords and stemming </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testBasics() throws java.io.IOException
	  public virtual void testBasics()
	  {
		Analyzer a = new FinnishAnalyzer(TEST_VERSION_CURRENT);
		// stemming
		checkOneTerm(a, "edeltäjiinsä", "edeltäj");
		checkOneTerm(a, "edeltäjistään", "edeltäj");
		// stopword
		assertAnalyzesTo(a, "olla", new string[] {});
	  }

	  /// <summary>
	  /// test use of exclusion set </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testExclude() throws java.io.IOException
	  public virtual void testExclude()
	  {
		CharArraySet exclusionSet = new CharArraySet(TEST_VERSION_CURRENT, asSet("edeltäjistään"), false);
		Analyzer a = new FinnishAnalyzer(TEST_VERSION_CURRENT, FinnishAnalyzer.DefaultStopSet, exclusionSet);
		checkOneTerm(a, "edeltäjiinsä", "edeltäj");
		checkOneTerm(a, "edeltäjistään", "edeltäjistään");
	  }

	  /// <summary>
	  /// blast some random strings through the analyzer </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testRandomStrings() throws Exception
	  public virtual void testRandomStrings()
	  {
		checkRandomData(random(), new FinnishAnalyzer(TEST_VERSION_CURRENT), 1000 * RANDOM_MULTIPLIER);
	  }
	}

}


text:
![screenshot](https://raw.github.com/fang64/ansible-ioncube/master/screenshot.png)

This Ansible Galaxy role installs the [ionCube Loader][ion] on a LAMP stack. This loader is required to run some encoded PHP applications such as [Blesta][blesta] and [WHMCS][whmcs].

Since the ionCube Loader version depends on the specific PHP version installed, check the [ionCube Loader Chart][ion_support].

## Requirements

Redhat Enterprise Linux 7

CentOS 7

Ubuntu 12.04 "Precise Pangolin"

Ubuntu 14.04 "Trusty Tahr"

Ubuntu 16.04 "Xenial Xerus"

Debian 8 "Jessie"

[elementaryOS][eos] 0.2 "Luna"

## Dependencies

Ansible Galaxy [geerlingguy.apache][apache]

Ansible Galaxy [geerlingguy.php][php]

## Example Playbook

Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:

    - hosts: servers
      roles:
         - geerlingguy.apache
         - geerlingguy.php

## License

MIT

## Copyright

(c)2014 Cristian R. Arroyo

(c)2016 Roy Williams

[ion]: http://www.ioncube.com/loaders.php
[ion_support]: https://www.ioncube.com/loaders/support_comparison.php
[apache]: https://github.com/geerlingguy/ansible-role-apache
[php]: https://github.com/geerlingguy/ansible-role-php
[whmcs]: http://www.whmcs.com/
[blesta]: http://www.blesta.com/
[eos]: http://elementaryos.org


text:
import Controller from '@ember/controller';
import config from 'wholetale/config/environment';
import EventStream from 'npm:sse.js';
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import $ from 'jquery';
import { later } from '@ember/runloop';
import { getOwner } from '@ember/application';

export default Controller.extend({
  // requires the sessions controller
  session: service(),
  userAuth: service('user-auth'),
  internalState: service('internal-state'),
  notificationHandler: service('notification-handler'),
  notificationStream: service('notification-stream'),
  tokenHandler: service(),

  user: computed(function() {
    return {
      fullName: "John Winter"
    }
  }),
  gravatarUrl: "/images/avatar.png",
  currentPage: "Dashboard",
  currentIcon: "browser",
  routing: service('-routing'),
  loggedIn: false,
  staticMenu: true,
  isLoadingJobs: true,
  mobileMenuDisplay: false,

  init() {
    this._super();
    // this.set('staticMenu', this.get('internalState').getIsStaticMenu());
    this.set('staticMenu', true);
    this.get('userAuth').getCurrentUserFromServer().then(
      (user) => {
        this.set('user', user);
      },
      (error) => {
        console.log(`There was an error loading the logged user: ${error}`);
      }
    );

    // FIXME: Gross hack - guys, this is real bad...
    later(() => {
      $('#user-dropdown-menu').dropdown({ action: 'nothing' });
    }, 1500);
    // this.set('eventStream', this.getEventStream.call(this));
  },

  // getEventStream() {
  //   let token = this.get('tokenHandler').getWholeTaleAuthToken();
  //   let source = new EventStream.SSE(config.apiUrl+"/notification/stream?timeout=15000", {headers: {'Girder-Token': token}});

  //   let self = this;
  //   source.addEventListener('message', function(evt) {
  //     let payload = JSON.parse(evt.data);
  //   });

  //   source.stream();

  //   return source;
  // },

  checkMyRouteName: computed(function () {
    return this.get('routing.currentRouteName');
  }),
  currentUserName: 'Hallo!',
  actions: {

    closeModal() {
        this.set('isModalVisible', false);
      },

    toggle: function (subSidebarName) {
      $('#' + subSidebarName)
        .sidebar('setting', 'transition', 'push')
        .sidebar('toggle');
    },
    logout: function () {

      this.get('userAuth').logoutCurrentUser();
      this.set('loggedIn', false);
      // let location = this.get('router.url');
      // window.location.href = location.split('?')[0];
      this.transitionToRoute('login');
    },
    refreshJobs: function () {
      const controller = this;
      controller.set('isLoadingJobs', true);
      this.store.findAll('job', {
        reload: true,
        adapterOptions: {
          queryParams: {
            limit: "0"
          }
        }
      }).then(jobs => {
        controller.set('jobs', jobs);
        window.setTimeout(controller.set.bind(controller, 'isLoadingJobs', false), 2000);
      });
    },
    staticMenu: function () {
      this.set('staticMenu', true);
      this.get('internalState').setStaticMenu(true);
    },
    dynamicMenu: function () {
      this.set('staticMenu', false);
      this.get('internalState').setStaticMenu(false);
    },
    closeMenu: function (pageTitle, icon) {
      this.set('currentPage', pageTitle);
      this.set('currentIcon', icon);
      // $('.sidebar').sidebar("toggle");
      if ($('.ember-burger-menu')) {
        this.actions.toggleMobileMenu.call(this);
      }

      if (pageTitle === "logout") {
        this.send("logout"); // call logout above.
      }
    },
    openJobWatcher() {
      $('.message.job-watcher').removeClass('hidden');
    },
    toggleMobileMenu() {
      let displayMobileMenu = !this.get('mobileMenuDisplay');
      this.set('mobileMenuDisplay', displayMobileMenu);
    },
    toggleShowNotifications() {
      this.notificationStream.set('showNotificationStream',
        !this.notificationStream.showNotificationStream);
    },
  }

});


text:
struct SDrawMenuGlobals {
							nwol::STimer				Timer;
							nwol::SAccumulator<double>	Accumulator;
};

extern					SDrawMenuGlobals			drawMenu_globals;

#define MENU_ROFFSET 8

namespace klib
{
	static inline constexpr		bool						mouseOver											(int32_t mouseX, int32_t mouseY, int32_t offsetX, int32_t offsetY, int32_t width)																							{ return (mouseY == offsetY) && (mouseX >= offsetX) && (mouseX < offsetX+width); }

#pragma pack(push, 1)
	struct SDrawMenuState {
								char						SlowTitle[96]										= {'_',};
								uint32_t					MenuItemAccum										= 0;
								uint32_t					CurrentPage											= 0;
								int32_t						CurrentOption										= 0;
		// - Ctor
	};
#pragma pack(pop)

								void						printMultipageHelp									(char* targetASCII, uint32_t targetWidth, uint32_t targetHeight, uint32_t currentPage, uint32_t pageCount, uint32_t posXOffset);

	template <size_t _FormatLen>
	static						int32_t						drawExitOption										(char* targetASCII, uint16_t* targetAttributes, uint32_t targetWidth, uint32_t targetHeight, uint32_t posXOffset, nwol::ALIGN_SCREEN align, const char (&formatString)[_FormatLen], const std::string& exitText, bool bSelected )		{
		int32_t														offsetY												= (int32_t)targetHeight-MENU_ROFFSET-1;
		int32_t														actualOffsetX										= printfToRect(targetASCII, targetWidth, targetHeight, offsetY, posXOffset, align, formatString, "0", exitText.c_str());

		uint16_t													colorBkg											= bSelected ? COLOR_GREEN << 4 : COLOR_GREEN;
		return ::nwol::valueToRect(targetAttributes, targetWidth, targetHeight,  offsetY, actualOffsetX, nwol::SCREEN_LEFT, &colorBkg, 1, (int32_t)exitText.size()+3);
	}

	template <size_t _ArraySize, typename _ReturnType>
								_ReturnType					processInput										(const nwol::SInput& frameInput, uint32_t targetWidth, uint32_t targetHeight, SDrawMenuState& localPersistentState, bool& bResetMenuStuff, bool& bResetTitle, int32_t lineOffset, const klib::SMenuItem<_ReturnType>(&menuItems)[_ArraySize], uint32_t actualOptionCount, uint32_t pageCount, size_t itemOffset, int32_t exitOffset, int32_t numberCharsAvailable, const _ReturnType& noActionValue, const _ReturnType& exitValue, bool disableEscKeyClose, const ::nwol::glabel& exitText)	{
		bool														bMouseOverExit										= mouseOver(frameInput.Mouse.Deltas.x, frameInput.Mouse.Deltas.y, exitOffset-4, (int32_t)targetHeight-MENU_ROFFSET-1, (int32_t)exitText.size()+4);

		_ReturnType													resultVal											= noActionValue;
		if(localPersistentState.CurrentPage < (pageCount-1) && (frameInput.Keys[VK_NEXT] || frameInput.Keys[VK_RIGHT]))
			(bResetMenuStuff = true) && ++localPersistentState.CurrentPage;
		else if(localPersistentState.CurrentPage > 0 && (frameInput.Keys[VK_PRIOR] || frameInput.Keys[VK_LEFT]))
			(bResetMenuStuff = true) && --localPersistentState.CurrentPage;
		else if(frameInput.Keys[VK_DOWN])  {		// Test down and up keys.
			++localPersistentState.CurrentOption;
			bResetMenuStuff											= true;
			if( localPersistentState.CurrentOption == (int32_t)actualOptionCount ) {
				if(localPersistentState.CurrentPage < (pageCount-1) )
					(localPersistentState.CurrentOption = 0) && ++localPersistentState.CurrentPage;
				else
					localPersistentState.CurrentOption						= actualOptionCount-1;
			}
		}
		else if(frameInput.Keys[VK_UP]) {
			--localPersistentState.CurrentOption;
			bResetMenuStuff											= true;
			if( localPersistentState.CurrentOption < 0 ) {
				if(localPersistentState.CurrentPage > 0 )
					(localPersistentState.CurrentOption = 8) && --localPersistentState.CurrentPage;
				else
					localPersistentState.CurrentOption						= 0;
			}
		}
		else if(frameInput.Keys['0'] || frameInput.Keys[VK_NUMPAD0] || ((frameInput.Mouse.Buttons[4] || frameInput.Keys[VK_ESCAPE]) && !disableEscKeyClose) 	// Test exit request keys.
			|| (frameInput.Mouse.Buttons[0] && bMouseOverExit)
			)
		{
			bResetMenuStuff											= true;
			bResetTitle												= true;
			localPersistentState.CurrentPage						= 0;
			localPersistentState.CurrentOption						= 0;
			resultVal												= exitValue;
		}
		else if(frameInput.Keys[VK_RETURN] && localPersistentState.CurrentOption != -1) {	// Test execute keys.
			bResetMenuStuff											= true;
			resultVal												= menuItems[localPersistentState.CurrentOption+itemOffset].ReturnValue;
		}
		else { // look if any of the options was chose from the possible inputs
			for(uint32_t i=0, count = (uint32_t)actualOptionCount; i < count; i++) {
				int32_t														actualOffsetX										= (int32_t)(targetWidth-targetWidth/2-numberCharsAvailable/2);
				bool														bMouseOver											= ::klib::mouseOver(frameInput.Mouse.Deltas.x, frameInput.Mouse.Deltas.y, actualOffsetX-2, lineOffset+i, numberCharsAvailable + 2);
				if(frameInput.Keys['1'+i] || frameInput.Keys[VK_NUMPAD1+i] || (frameInput.Mouse.Buttons[0] && bMouseOver)) {
					bResetMenuStuff									= true;
					resultVal										= menuItems[i+itemOffset].ReturnValue;
					break;
				}
			}
		}

		return resultVal;
	}

	template <size_t _ArraySize, typename _ReturnType>
	_ReturnType												drawMenu											(char* targetASCII, uint16_t* targetAttributes, uint32_t targetWidth, uint32_t targetHeight, uint32_t optionCount, const std::string& title, const klib::SMenuItem<_ReturnType>(&menuItems)[_ArraySize], const nwol::SInput& frameInput, const _ReturnType& exitValue, const _ReturnType& noActionValue=-1, uint32_t rowWidth=20, bool disableEscKeyClose=false, const ::nwol::glabel& exitText="Exit this menu") {
		drawMenu_globals.Timer.Frame();

		optionCount												= (optionCount < _ArraySize) ? optionCount : _ArraySize; // Fix optionCount to the maximum size of the array if optionCount is higher than the allowed size.

		int32_t														lineOffset											= (int32_t)(targetHeight-MENU_ROFFSET-4-std::min((int32_t)optionCount, 9));
		const int32_t												clearOffset											= (int32_t)(targetHeight-MENU_ROFFSET-4-9);
		const int32_t												optionsOffset										= lineOffset;

		std::string													clearString											(::std::max(rowWidth, 128U), ' ');
		for(int32_t i=-2, count = (int32_t)targetHeight-clearOffset; i<count; ++i)
			::nwol::printfToRectColored(targetASCII, targetWidth, targetHeight, targetAttributes, (COLOR_BLACK<<4) | COLOR_YELLOW, clearOffset+i, 0, nwol::SCREEN_CENTER, "%s", clearString.c_str()); // clear all lines where we're going to draw

		const bool													multipage											= optionCount > 9;
		const uint32_t												pageCount											= (uint32_t)((multipage == false) ? 1 : optionCount/9 + ((optionCount%9)?1:0));

		static SDrawMenuState										localPersistentState;
		if( localPersistentState.CurrentPage >= pageCount )
			localPersistentState.CurrentPage = 0;

		// Build formatted menu title
		char														titleFormat		[]									= "-- %s --";
		char														titleFormatted	[128]								= {};
		int32_t														titleLength											= (int32_t)sprintf_s(titleFormatted, titleFormat, title.c_str());

		rowWidth												= ::std::max((uint32_t)titleLength, std::max((uint32_t)exitText.size()+3, rowWidth));
		const bool													bDonePrinting										= ::nwol::getMessageSlow(localPersistentState.SlowTitle, titleFormatted, titleLength, drawMenu_globals.Timer.LastTimeSeconds*4);
		int32_t														actualOffsetX										= ::nwol::lineToRect(targetASCII, targetWidth, targetHeight, lineOffset, 0, nwol::SCREEN_CENTER, localPersistentState.SlowTitle);		//"-- %s --", title.c_str() );	// Print menu title
		for(uint32_t i=0; i<rowWidth+1; i++)
			targetAttributes[lineOffset*targetWidth+actualOffsetX+i] = COLOR_GREEN;

		if( !bDonePrinting )
			return noActionValue;

		lineOffset												+= 2;

		// Print menu options
		uint32_t													numberCharsAvailable								= rowWidth-4;	// 4 is for "%2.2s: "
		char														formatString	[24]								= {};
		char														numberKey		[4]									= {};
		sprintf_s(formatString, "%%2.2s: %%-%u.%us", numberCharsAvailable, numberCharsAvailable);

		// Draw options
		uint32_t													actualOptionCount									= std::min(9U, (uint32_t)(optionCount-(localPersistentState.CurrentPage*9)));
		const uint32_t											itemOffset											= localPersistentState.CurrentPage*9;
		if(drawMenu_globals.Accumulator.Value < 0.575 && localPersistentState.MenuItemAccum < actualOptionCount)
			drawMenu_globals.Accumulator.Value						= 0.575;

		for(uint32_t i = 0, count = (uint32_t)actualOptionCount; i < count; ++i) {
			actualOffsetX											= (int32_t)(targetWidth-targetWidth/2-numberCharsAvailable/2);
			if(::klib::mouseOver(frameInput.Mouse.Deltas.x, frameInput.Mouse.Deltas.y, actualOffsetX-2, lineOffset+i, numberCharsAvailable + 2)) {
				localPersistentState.CurrentOption						= i;
				break;
			}
		}

		if( localPersistentState.CurrentOption >= (int32_t)actualOptionCount )
			localPersistentState.CurrentOption						= actualOptionCount-1;

		const uint32_t												posXOffset											= 0;
		for(uint32_t i = 0, count = (localPersistentState.MenuItemAccum < actualOptionCount) ? localPersistentState.MenuItemAccum : actualOptionCount; i < count; ++i) {
			::sprintf_s(numberKey, "%u", (uint32_t)(i+1));
			actualOffsetX											= ::nwol::printfToRect(targetASCII, targetWidth, targetHeight, lineOffset, posXOffset, nwol::SCREEN_CENTER, formatString, numberKey, menuItems[itemOffset+i].Text.c_str());
			if(localPersistentState.CurrentOption == (int32_t)i)
				for(uint32_t j = 0; j < rowWidth + 1; ++j)
					targetAttributes[lineOffset * targetWidth + actualOffsetX + j]	= COLOR_YELLOW << 4;
			else
				for(uint32_t j = 0; j < rowWidth + 1; ++j)
					targetAttributes[lineOffset * targetWidth + actualOffsetX + j]	= COLOR_YELLOW;

			++lineOffset;
		}

		int32_t														exitOffset											= 0;
		// Print Exit option at the end.
		if(localPersistentState.MenuItemAccum > actualOptionCount)
			exitOffset												= drawExitOption(targetASCII, targetAttributes, targetWidth, targetHeight, posXOffset, nwol::SCREEN_CENTER, formatString, exitText, localPersistentState.CurrentOption == 10);

		// Print page control help if multipage.
		if(multipage)
			printMultipageHelp(targetASCII, targetWidth, targetHeight, localPersistentState.CurrentPage, pageCount, posXOffset);

		_ReturnType													resultVal											= noActionValue;
		bool														bResetMenuStuff										= false;
		bool														bResetTitle											= false;
		if( drawMenu_globals.Accumulator.Accumulate(drawMenu_globals.Timer.LastTimeSeconds) ) {
			if(localPersistentState.MenuItemAccum <= actualOptionCount) // Don't process keys until the menu has finished displaying
				(drawMenu_globals.Accumulator.Value = 0.575) && ++localPersistentState.MenuItemAccum;
			else	// Process page change keys first.
				resultVal												= processInput(frameInput, targetWidth, targetHeight, localPersistentState, bResetMenuStuff, bResetTitle, lineOffset - (int32_t)actualOptionCount, menuItems, actualOptionCount, pageCount, itemOffset, exitOffset, numberCharsAvailable, noActionValue, exitValue, disableEscKeyClose, exitText);
		}

		if(bResetMenuStuff)
			drawMenu_globals.Accumulator.Value						= 0;

		if(bResetTitle) {
			::nwol::resetCursorString(localPersistentState.SlowTitle);
			localPersistentState.MenuItemAccum						= actualOptionCount >> 1;
		}

		return resultVal;
	}

	template <typename _tCell, size_t _ItemCount, typename _ReturnType>
	inline _ReturnType										drawMenu			(::nwol::grid_view<_tCell>& display, uint16_t* targetAttributes, uint32_t optionCount, const std::string& title, const klib::SMenuItem<_ReturnType>(&menuItems)[_ItemCount], const nwol::SInput& frameInput, _ReturnType exitValue, _ReturnType noActionValue = -1, uint32_t rowWidth=20, bool disableEscapeKey=false, const std::string& exitText="Exit this menu") {
		return drawMenu(display.begin(), targetAttributes, display.width(), display.height(), optionCount, title, menuItems, frameInput, exitValue, noActionValue, rowWidth, disableEscapeKey, exitText);
	}

	template <typename _tCell, size_t _ItemCount, typename _ReturnType>
	inline _ReturnType										drawMenu			(::nwol::grid_view<_tCell>& display, uint16_t* targetAttributes, const std::string& title, const klib::SMenuItem<_ReturnType>(&menuItems)[_ItemCount], const nwol::SInput& frameInput, _ReturnType exitValue, _ReturnType noActionValue = -1, uint32_t rowWidth=20, bool disableEscapeKey=false, const std::string& exitText="Exit this menu") {
		return drawMenu(display.begin(), targetAttributes, display.width(), display.height(), _ItemCount, title, menuItems, frameInput, exitValue, noActionValue, rowWidth, disableEscapeKey, exitText);
	}

	template <typename _ReturnType>
	struct SMenu {
		::nwol::glabel				Title;
		uint32_t					RowWidth;
		_ReturnType					ValueExit;
		bool						bDisableEscapeKey;
		::nwol::glabel				TextExit;
		SDrawMenuState				MenuState;

		constexpr					SMenu				(_ReturnType exitValue, const std::string& title, uint32_t rowWidth=24, bool disableEscapeKey=false, const ::nwol::glabel& exitText="Exit this menu")
			: Title				(title)
			, RowWidth			(rowWidth)
			, ValueExit			(exitValue)
			, bDisableEscapeKey	(disableEscapeKey)
			, TextExit			(exitText)
			, MenuState			()
		{};
	};

	template <typename _tCell, size_t _ItemCount, typename _ReturnType>
	_ReturnType drawMenu(::nwol::grid_view<_tCell>& display, uint16_t* targetAttributes, const SMenu<_ReturnType>& menuInstance, const klib::SMenuItem<_ReturnType>(&menuItems)[_ItemCount], const nwol::SInput& frameInput, _ReturnType noActionValue = -1) {
		return drawMenu(display.begin(), targetAttributes, display.width(), display.height(), (uint32_t)_ItemCount, menuInstance.Title, menuItems, frameInput, menuInstance.ValueExit, noActionValue, menuInstance.RowWidth, menuInstance.bDisableEscapeKey, menuInstance.TextExit);
	}

	template <typename _tCell, size_t _ItemCount, typename _ReturnType>
	_ReturnType drawMenu(::nwol::grid_view<_tCell>& display, uint16_t* targetAttributes, const SMenu<_ReturnType>& menuInstance, const klib::SMenuItem<_ReturnType>(&menuItems)[_ItemCount], uint32_t optionCount, const nwol::SInput& frameInput, _ReturnType noActionValue = -1) {
		return drawMenu(display.begin(), targetAttributes, display.width(), display.height(), optionCount, menuInstance.Title, menuItems, frameInput, menuInstance.ValueExit, noActionValue, menuInstance.RowWidth, menuInstance.bDisableEscapeKey, menuInstance.TextExit);
	}
} // namespace

#endif // __DRAWMENU_H__98237409236409872364987236498__


text:
/**
 *   @class Realtime.Storage.TableSnapshot Class with the definition of a table snapshot.
 *   @see TableSnapshot\tableSnapshot.js
 */
var TableSnapshot = function(args) {
	/**
	 *   @function {TableRef} ref Creates and returns the corresponding TableRef object.
	 *   @return A reference to the table.
	 *   @see TableSnapshot\ref.js
	 */
	this.ref = function() { return new TableRef(args); };

	/**
	 *   @function {String} val Returns the name of the table.
	 *   @return The attributes this snapshot refers to.
	 *   @see TableSnapshot\val.js
	 */
	this.val = function() { return args.name; };
};

module.exports = TableSnapshot;

var TableRef = require("./TableRef.js");


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__int_connect_socket_to_char_21.c
Label Definition File: CWE197_Numeric_Truncation_Error__int.label.xml
Template File: sources-sink-21.tmpl.c
*/
/*
 * @description
 * CWE: 197 Numeric Truncation Error
 * BadSource: connect_socket Read data using a connect socket (client side)
 * GoodSource: Less than CHAR_MAX
 * Sink: to_char
 *    BadSink : Convert data to a char
 * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file.
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

/* The static variable below is used to drive control flow in the source function */
static int badStatic = 0;

static int badSource(int data)
{
    if(badStatic)
    {
        {
#ifdef _WIN32
            WSADATA wsaData;
            int wsaDataInit = 0;
#endif
            int recvResult;
            struct sockaddr_in service;
            SOCKET connectSocket = INVALID_SOCKET;
            char inputBuffer[CHAR_ARRAY_SIZE];
            do
            {
#ifdef _WIN32
                if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
                {
                    break;
                }
                wsaDataInit = 1;
#endif
                /* POTENTIAL FLAW: Read data using a connect socket */
                connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                if (connectSocket == INVALID_SOCKET)
                {
                    break;
                }
                memset(&service, 0, sizeof(service));
                service.sin_family = AF_INET;
                service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
                service.sin_port = htons(TCP_PORT);
                if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
                {
                    break;
                }
                /* Abort on error or the connection was closed, make sure to recv one
                 * less char than is in the recv_buf in order to append a terminator */
                recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0);
                if (recvResult == SOCKET_ERROR || recvResult == 0)
                {
                    break;
                }
                /* NUL-terminate the string */
                inputBuffer[recvResult] = '\0';
                /* Convert to int */
                data = atoi(inputBuffer);
            }
            while (0);
            if (connectSocket != INVALID_SOCKET)
            {
                CLOSE_SOCKET(connectSocket);
            }
#ifdef _WIN32
            if (wsaDataInit)
            {
                WSACleanup();
            }
#endif
        }
    }
    return data;
}

void CWE197_Numeric_Truncation_Error__int_connect_socket_to_char_21_bad()
{
    int data;
    /* Initialize data */
    data = -1;
    badStatic = 1; /* true */
    data = badSource(data);
    {
        /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */
        char charData = (char)data;
        printHexCharLine(charData);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* The static variables below are used to drive control flow in the source functions. */
static int goodG2B1Static = 0;
static int goodG2B2Static = 0;

/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */
static int goodG2B1Source(int data)
{
    if(goodG2B1Static)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Use a positive integer less than CHAR_MAX*/
        data = CHAR_MAX-5;
    }
    return data;
}

static void goodG2B1()
{
    int data;
    /* Initialize data */
    data = -1;
    goodG2B1Static = 0; /* false */
    data = goodG2B1Source(data);
    {
        /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */
        char charData = (char)data;
        printHexCharLine(charData);
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */
static int goodG2B2Source(int data)
{
    if(goodG2B2Static)
    {
        /* FIX: Use a positive integer less than CHAR_MAX*/
        data = CHAR_MAX-5;
    }
    return data;
}

static void goodG2B2()
{
    int data;
    /* Initialize data */
    data = -1;
    goodG2B2Static = 1; /* true */
    data = goodG2B2Source(data);
    {
        /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */
        char charData = (char)data;
        printHexCharLine(charData);
    }
}

void CWE197_Numeric_Truncation_Error__int_connect_socket_to_char_21_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE197_Numeric_Truncation_Error__int_connect_socket_to_char_21_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE197_Numeric_Truncation_Error__int_connect_socket_to_char_21_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package codegen

import (
	"gate.computer/wag/internal/gen"
	"gate.computer/wag/internal/gen/operand"
	"gate.computer/wag/internal/gen/storage"
	"gate.computer/wag/internal/loader"
	"gate.computer/wag/internal/module"
	"gate.computer/wag/wa"
	"gate.computer/wag/wa/opcode"
)

func readLocalIndex(f *gen.Func, load loader.L, op opcode.Opcode) (index int, t wa.Type) {
	i := load.Varuint32()
	if i >= uint32(len(f.LocalTypes)) {
		panic(module.Errorf("%s index out of bounds: %d", op, i))
	}

	index = int(i)
	t = f.LocalTypes[index]
	return
}

func genGetLocal(f *gen.Func, load loader.L, op opcode.Opcode, info opInfo) (deadend bool) {
	index, t := readLocalIndex(f, load, op)
	r, _ := opAllocReg(f, t)
	asm.LoadStack(&f.Prog, t, r, f.LocalOffset(index))
	pushOperand(f, operand.Reg(t, r))
	return
}

func genSetLocal(f *gen.Func, load loader.L, op opcode.Opcode, info opInfo) (deadend bool) {
	index, t := readLocalIndex(f, load, op)
	value := popOperand(f, t)
	asm.StoreStack(f, f.LocalOffset(index), value)
	return
}

func genTeeLocal(f *gen.Func, load loader.L, op opcode.Opcode, info opInfo) (deadend bool) {
	index, t := readLocalIndex(f, load, op)
	value := popOperand(f, t)

	switch value.Storage {
	default:
		r, _ := opAllocReg(f, t)
		asm.Move(f, r, value)
		value.SetReg(r)
		fallthrough

	case storage.Reg:
		asm.StoreStackReg(&f.Prog, t, f.LocalOffset(index), value.Reg())

	case storage.Imm:
		asm.StoreStackImm(&f.Prog, t, f.LocalOffset(index), value.ImmValue())
	}

	pushOperand(f, value)
	return
}


text:
package api

import "github.com/starkandwayne/cf-cli/cf/models"

type FakeStackRepository struct {
	FindByNameStack models.Stack
	FindByNameName  string

	FindAllStacks []models.Stack
}

func (repo *FakeStackRepository) FindByName(name string) (stack models.Stack, apiErr error) {
	repo.FindByNameName = name
	stack = repo.FindByNameStack

	return
}

func (repo *FakeStackRepository) FindAll() (stacks []models.Stack, apiErr error) {
	stacks = repo.FindAllStacks
	return
}