<commit_before>mol.modules.map.dashboard = function(mol) {

    mol.map.dashboard = {};

    mol.map.dashboard.DashboardEngine = mol.mvp.Engine.extend(
        {
            init: function(proxy, bus) {
                this.proxy = proxy;
                this.bus = bus;
                this.summary_sql = '' +
                    'SELECT DISTINCT * ' +
                    'FROM get_dashboard_summary()';
                this.dashboard_sql = '' +
                    'SELECT DISTINCT * ' +
                    'FROM dash_cache ' +
                    'ORDER BY dataset_title asc';
                this.summary = null;
                this.types = {};
                this.sources = {};

            },
            start: function() {
                this.initDialog();
            },

            addEventHandlers: function() {
                var self = this;

                /**
                 * Callback that toggles the dashboard display visibility.
                 *
                 * @param event mol.bus.Event
                 */
                this.bus.addHandler(
                    'taxonomy-dashboard-toggle',
                    function(event) {
                        var params = null,
                            e = null;
                        if (event.state === undefined) {
                            if(self.display.dialog('isOpen')) {
                                self.display.dialog('close');
                            } else {
                                self.display.dialog('open');
                            }
                        } else {
                            self.display.dialog(event.state);
                        }
                    }
                );

                _.each(
                    this.display.datasets,
                    function(dataset) {
                        var provider = $(dataset).data('provider'),
                            type = $(dataset).data('type_id'),
                            dataset_id = $(dataset).data('dataset_id'),
                            dataset_title = $(dataset).data('dataset_title'),
                            type_title = $(dataset).data('type');

                        $(dataset).find('.table').click (
                            function(event) {
                                self.bus.fireEvent(
                                    new mol.bus.Event(
                                        'metadata-toggle',
                                        {params:
                                            {dataset_id: dataset_id,
                                             title: dataset_title}}
                                     )
                                 );
                            }
                        );
                        $(dataset).find('.type').click (
                                function(event) {
                                    self.bus.fireEvent(
                                        new mol.bus.Event(
                                            'metadata-toggle',
                                            {params:{type: type, title: type_title}}));
                                }
                         );
                    }
                );
            },

            /**
             * Fires the 'add-map-control' event. The mol.map.MapEngine handles
             * this event and adds the display to the map.
             */
            initDialog: function() {
                var self = this;

                $.getJSON(
                    mol.services.cartodb.sqlApi.jsonp_url.format(this.dashboard_sql),
                    function(response) {
                        self.display = new mol.map.dashboard.DashboardDisplay(
                            response.rows, self.summary
                        );
                        self.display.dialog(
                            {
                                autoOpen: false,
                                width: 946,
                                height: 600,
                                minHeight: 300,
                                stack: true,
                                dialogClass: "mol-Dashboard",
                                title: 'Dashboard - ' +
                                'Statistics for Data Served by the Map of Life',
                                open: function(event, ui) {
                                     $(".mol-Dashboard-TableWindow")
                                        .height(
                                            $(".mol-Dashboard").height()-95);

                                     //need this to force zebra on the table
                                     self.display.dashtable
                                        .trigger("update", true);
                                }
                            }
                        );

                        $(".mol-Dashboard").parent().bind("resize", function() {
                            $(".mol-Dashboard-TableWindow")
                                .height($(".mol-Dashboard").height()-95);
                        });
                        self.addEventHandlers();
                    }
                );

                $.getJSON(
                    mol.services.cartodb.sqlApi.jsonp_url.format(this.summary_sql),
                    function(response) {
                        self.summary = response.rows[0];
                        if(self.display) {
                            self.display.fillSummary(self.summary);
                        }
                    }
                );
            }
        }
    );

    mol.map.dashboard.DashboardDisplay = mol.mvp.View.extend(
        {
            init: function(rows, summary) {
                var html = '' +
                    '
' +
                    '
' +
                    '
' +
                    '      ' +
                             'Data sources:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Datasets:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Species names in source data:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Accepted species names:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Total records:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '          Dataset	' +
                    '          Type	' +
                    '          Source	' +
                    '          Taxon	' +
                    '          Species Names	' +
                    '          Records	' +
                    '          % Match	' +
                    '
' +
                    '
' +
                    '

' +
                    '
' +
                    '
' +
                    '
' +
                    '
  ',
                    self = this;

                this._super(html);
                _.each(
                    rows,
                    function(row) {
                        self.fillRow(row);
                    }
                )

                this.dashtable = $(this).find('.dashtable');
                this.dashtable.tablesorter({
                    sortList: [[0,0]],
                    widthFixed: true,
                    theme: "blue",
                    widgets: ["filter","zebra"]
                });
                this.datasets = $(this).find('.dataset');

                this.dashtable.find("tr.master")
                    .click(function() {
                        $(this).parent().find('tr').each(
                            function(index, elem) {
                                $(elem).find('td').each(
                                    function(index, el) {
                                        if($(el).hasClass('selectedDashRow')) {
                                            $(el).removeClass('selectedDashRow');
                                        }
                                    }
                                )
                            }
                        )

                        $(this).find('td').each(
                            function(index, elem) {
                                $(elem).addClass('selectedDashRow');
                            }
                        )
                    }
                );

                if(summary!=null) {
                    self.fillSummary(summary);
                }
            },

            fillRow:  function(row) {
                var self = this;

                $(this).find('.tablebody').append(
                    new mol.map.dashboard.DashboardRowDisplay(row));
            },

            fillSummary: function(summary) {
                var self = this;
                _.each(
                    _.keys(summary),
                    function(stat){
                        $(self).find('.{0}'.format(stat)).text(summary[stat]);
                    }
                )
            }
        }
    );

    mol.map.dashboard.DashboardRowDisplay = mol.mvp.View.extend(
        {
            init: function(row) {
                var html = '' +
                    '
' +
                        '{8}	' +
                        '{1}	' +
                        '{3}	' +
                        '{5}	' +
                        '{6}	' +
                        '{7}	' +
                        '{9}	' +
                    '
',
                    self = this;

                self._super(
                    html.format(
                        row.type_id,
                        row.type,
                        row.dataset_id,
                        row.provider,
                        row.classes.split(',').join(' '),
                        row.classes.split(',').join(', '),
                        this.format(row.species_count),
                        this.format(row.feature_count),
                        row.dataset_title,
                        row.pct_in_tax
                    )
                );
                //store some data in each dataset/row
                 _.each(
                     _.keys(row),
                     function(key) {
                        $(self).data(key, row[key]);
                     }
                );
            },

            format: function(number, comma, period) {
                var reg = /(\d+)(\d{3})/;
                var split = number.toString().split('.');
                var numeric = split[0];
                var decimal;

                comma = comma || ',';
                period = period || '.';
                decimal = split.length > 1 ? period + split[1] : '';

                while (reg.test(numeric)) {
                  numeric = numeric.replace(reg, '$1' + comma + '$2');
                }

                return numeric + decimal;
            }
         }
    );

};<commit_msg>Moving dashboard menu button to its module.<commit_after>mol.modules.map.dashboard = function(mol) {

    mol.map.dashboard = {};

    mol.map.dashboard.DashboardEngine = mol.mvp.Engine.extend(
        {
            init: function(proxy, bus) {
                this.proxy = proxy;
                this.bus = bus;
                this.summary_sql = '' +
                    'SELECT DISTINCT * ' +
                    'FROM get_dashboard_summary()';
                this.dashboard_sql = '' +
                    'SELECT DISTINCT * ' +
                    'FROM dash_cache ' +
                    'ORDER BY dataset_title asc';
                this.summary = null;
                this.types = {};
                this.sources = {};

            },

            start: function() {
                this.initDialog();
                this.addDashboardMenuButton();
            },

            addDashboardMenuButton : function() {
               var html = '' +
                    '
' +
                        'Dashboard' +
                    '
',
                    params = {
                        button: html
                    },
                    event = new mol.bus.Event('add-dashboard-toggle-button', params);

               this.bus.fireEvent(event);
            },

            addEventHandlers: function() {
                var self = this;

                /**
                 * Callback that toggles the dashboard display visibility.
                 *
                 * @param event mol.bus.Event
                 */
                this.bus.addHandler(
                    'taxonomy-dashboard-toggle',
                    function(event) {
                        var params = null,
                            e = null;
                        if (event.state === undefined) {
                            if(self.display.dialog('isOpen')) {
                                self.display.dialog('close');
                            } else {
                                self.display.dialog('open');
                            }
                        } else {
                            self.display.dialog(event.state);
                        }
                    }
                );

                _.each(
                    this.display.datasets,
                    function(dataset) {
                        var provider = $(dataset).data('provider'),
                            type = $(dataset).data('type_id'),
                            dataset_id = $(dataset).data('dataset_id'),
                            dataset_title = $(dataset).data('dataset_title'),
                            type_title = $(dataset).data('type');

                        $(dataset).find('.table').click (
                            function(event) {
                                self.bus.fireEvent(
                                    new mol.bus.Event(
                                        'metadata-toggle',
                                        {params:
                                            {dataset_id: dataset_id,
                                             title: dataset_title}}
                                     )
                                 );
                            }
                        );
                        $(dataset).find('.type').click (
                                function(event) {
                                    self.bus.fireEvent(
                                        new mol.bus.Event(
                                            'metadata-toggle',
                                            {params:{type: type, title: type_title}}));
                                }
                         );
                    }
                );
            },

            /**
             * Fires the 'add-map-control' event. The mol.map.MapEngine handles
             * this event and adds the display to the map.
             */
            initDialog: function() {
                var self = this;

                $.getJSON(
                    mol.services.cartodb.sqlApi.jsonp_url.format(this.dashboard_sql),
                    function(response) {
                        self.display = new mol.map.dashboard.DashboardDisplay(
                            response.rows, self.summary
                        );
                        self.display.dialog(
                            {
                                autoOpen: false,
                                width: 946,
                                height: 600,
                                minHeight: 300,
                                stack: true,
                                dialogClass: "mol-Dashboard",
                                title: 'Dashboard - ' +
                                'Statistics for Data Served by the Map of Life',
                                open: function(event, ui) {
                                     $(".mol-Dashboard-TableWindow")
                                        .height(
                                            $(".mol-Dashboard").height()-95);

                                     //need this to force zebra on the table
                                     self.display.dashtable
                                        .trigger("update", true);
                                }
                            }
                        );

                        $(".mol-Dashboard").parent().bind("resize", function() {
                            $(".mol-Dashboard-TableWindow")
                                .height($(".mol-Dashboard").height()-95);
                        });
                        self.addEventHandlers();
                    }
                );

                $.getJSON(
                    mol.services.cartodb.sqlApi.jsonp_url.format(this.summary_sql),
                    function(response) {
                        self.summary = response.rows[0];
                        if(self.display) {
                            self.display.fillSummary(self.summary);
                        }
                    }
                );
            }
        }
    );

    mol.map.dashboard.DashboardDisplay = mol.mvp.View.extend(
        {
            init: function(rows, summary) {
                var html = '' +
                    '
' +
                    '
' +
                    '
' +
                    '      ' +
                             'Data sources:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Datasets:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Species names in source data:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Accepted species names:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '      ' +
                             'Total records:' +
                    '      ' +
                    '      ' +
                    '      ' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '
' +
                    '          Dataset	' +
                    '          Type	' +
                    '          Source	' +
                    '          Taxon	' +
                    '          Species Names	' +
                    '          Records	' +
                    '          % Match	' +
                    '
' +
                    '
' +
                    '

' +
                    '
' +
                    '
' +
                    '
' +
                    '
  ',
                    self = this;

                this._super(html);
                _.each(
                    rows,
                    function(row) {
                        self.fillRow(row);
                    }
                )

                this.dashtable = $(this).find('.dashtable');
                this.dashtable.tablesorter({
                    sortList: [[0,0]],
                    widthFixed: true,
                    theme: "blue",
                    widgets: ["filter","zebra"]
                });
                this.datasets = $(this).find('.dataset');

                this.dashtable.find("tr.master")
                    .click(function() {
                        $(this).parent().find('tr').each(
                            function(index, elem) {
                                $(elem).find('td').each(
                                    function(index, el) {
                                        if($(el).hasClass('selectedDashRow')) {
                                            $(el).removeClass('selectedDashRow');
                                        }
                                    }
                                )
                            }
                        )

                        $(this).find('td').each(
                            function(index, elem) {
                                $(elem).addClass('selectedDashRow');
                            }
                        )
                    }
                );

                if(summary!=null) {
                    self.fillSummary(summary);
                }
            },

            fillRow:  function(row) {
                var self = this;

                $(this).find('.tablebody').append(
                    new mol.map.dashboard.DashboardRowDisplay(row));
            },

            fillSummary: function(summary) {
                var self = this;
                _.each(
                    _.keys(summary),
                    function(stat){
                        $(self).find('.{0}'.format(stat)).text(summary[stat]);
                    }
                )
            }
        }
    );

    mol.map.dashboard.DashboardRowDisplay = mol.mvp.View.extend(
        {
            init: function(row) {
                var html = '' +
                    '
' +
                        '{8}	' +
                        '{1}	' +
                        '{3}	' +
                        '{5}	' +
                        '{6}	' +
                        '{7}	' +
                        '{9}	' +
                    '
',
                    self = this;

                self._super(
                    html.format(
                        row.type_id,
                        row.type,
                        row.dataset_id,
                        row.provider,
                        row.classes.split(',').join(' '),
                        row.classes.split(',').join(', '),
                        this.format(row.species_count),
                        this.format(row.feature_count),
                        row.dataset_title,
                        row.pct_in_tax
                    )
                );
                //store some data in each dataset/row
                 _.each(
                     _.keys(row),
                     function(key) {
                        $(self).data(key, row[key]);
                     }
                );
            },

            format: function(number, comma, period) {
                var reg = /(\d+)(\d{3})/;
                var split = number.toString().split('.');
                var numeric = split[0];
                var decimal;

                comma = comma || ',';
                period = period || '.';
                decimal = split.length > 1 ? period + split[1] : '';

                while (reg.test(numeric)) {
                  numeric = numeric.replace(reg, '$1' + comma + '$2');
                }

                return numeric + decimal;
            }
         }
    );

};<|endoftext|>


<commit_before>(function(window) {
    var app = angular.module("xMobileNgTable",[]);
    angular.module("xMobileNgTable").run(function ($templateCache) {
   // The templateCache would be created automatically with GRUNT tool.
   $templateCache.put("view/MobileNgTable_Template.html", '

 				 			{{header.displayName}}

 			<input data-role="none" ng-show=commandColumnSelect ng-model=row[select] type="checkbox" data-ng-click="rowSelectClick($event,row)" />
{{::row[field.field] | mobileNgTableFilter:field.filter}}
	 			 View {{row[Visualizavel]}}	 			 Edit {{row[Editavel]}}	 			 Delete {{row[Deletavel]}}

«

‹

 <input data-role="none" ng-model="pager.startPage" style="width: 40px; text-align: right;" type="text" value="{{pager.startPage}}"/>  de   {{ functionTotal(pager.total, pager.limitPerPage) }}

›

»

Reload

 Exibindo   {{pager.startPage}}  -  {{ functionLimitPerPage(pager.total, pager.limitPerPage) }}   de   {{pager.total}}

');
});

app.directive('mobileNgTable', function($filter) {
    return {
        restrict: 'E',
        scope: {
            loadRepeat: '=loadRepeat'
        },
        templateUrl: "view/MobileNgTable_Template.html",
        replace: true,
        link : function(scope, element, attrs) {
            var option = scope.loadRepeat;
            scope.class = option.class;
            scope.columnDefs = option.columnDefs;
            scope.$parent.$watch(option.search, function (newSearch) { scope.search = newSearch; }, true);

            scope.rowClick = option.rowClick;

            scope.rowSelectClick = option.rowSelectClick;
            scope.commandColumnSelect = false;
            scope.select = option.select;
            if (scope.rowSelectClick && scope.select != null) {
                scope.commandColumnSelect = true;
            }

            scope.rowDeleteClick = option.rowDeleteClick;
            scope.commandColumnDelete = false;
            scope.deletable = option.deletable;
            if (scope.rowDeleteClick && scope.deletable != null) {
                scope.commandColumnDelete = true;
            }

            scope.rowEditClick = option.rowEditClick;
            scope.commandColumnEdit = false;
            scope.editable = option.editable;
            if (scope.rowEditClick && scope.editable != null) {
                scope.commandColumnEdit = true;
            }

            scope.rowViewClick = option.rowViewClick;
            scope.commandColumnView = false;
            scope.visualisable = option.visualisable;
            if (scope.rowViewClick && scope.visualisable != null) {
                scope.commandColumnView = true;
            }

            scope.itemOnLongPress = option.itemOnLongPress;
            scope.itemOnTouchEnd = option.itemOnTouchEnd;

            scope.pager = option.pager;
            scope.pager.type = option.pager.type;

            if(scope.pager.type == 'local') {
                scope.pagerReloadClick = function (e, pager) {
                    scope.$parent.$watch(option.data, function (newdata) {
                        var begin = ((pager.startPage - 1) * pager.limitPerPage);
                        var end = begin + pager.limitPerPage;
                        scope.data = newdata.slice(begin, end);
                        scope.pager.StartInterval = begin + 1;
                        scope.pager.EndInterval  = (end > newdata.length ? newdata.length : end);
                        scope.pager.total = newdata.length;
                    }, true);
                }
                scope.pagerReloadClick(null, scope.pager);
            } else {
                scope.$parent.$watch(option.data, function (newdata) { scope.data = newdata; }, true);
                scope.pagerReloadClick = function (e, pager)
                {
                    option.pagerReloadClick(e, pager);
                    var begin = ((parseInt(pager.startPage) - 1) * parseInt(pager.limitPerPage));
                    var end = begin + parseInt(pager.limitPerPage);
                    scope.pager.StartInterval = begin + 1;
                    scope.pager.EndInterval = (end > parseInt(scope.pager.total) ? parseInt(scope.pager.total) : end);
                }
                scope.pagerReloadClick(null, scope.pager);
            }

            scope.pagerFirstClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if (parseInt(pager.startPage) != parseInt(1)) {
                        pager.startPage = 1;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            };
            scope.pagerPreviousClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if ((parseInt(pager.startPage) > parseInt(1))) {
                        pager.startPage = pager.startPage - 1;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            };
            scope.pagerNextClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if ((parseInt(pager.startPage) < parseInt(pager.totalPages))) {
                        pager.startPage = pager.startPage + 1;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            }
            scope.pagerLastClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if ((parseInt(pager.startPage) != parseInt(pager.totalPages))) {
                        pager.startPage = pager.totalPages;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            };
            scope.functionTotal = function (total, limitPerPage) {
                scope.pager.totalPages = Math.round((total % limitPerPage > 0 ? parseInt(total / limitPerPage) + 1 : (total / limitPerPage)));
                return scope.pager.totalPages;
            };
            scope.tableLoading = true;
            scope.endRepeat = function () {
                scope.tableLoading = false;
            };
        }
    };
});

app.filter('mobileNgTableFilter', function($filter) {
    return function(value, filterData) {
        if(filterData){
            var filter = filterData.trim().split(":");
            var filterName = filter[0];
            var expression = filter[1];
            return $filter(filterName)(value,expression);
        }else{
            return value;
        }
    };
});

//Add this directive where you keep your directives
app.directive('onLongPress', function ($timeout,$parse) {
    return {
        restrict: 'A',
        link: function ($scope, $elm, $attrs) {
            var onLongPress = $attrs.onLongPress;
            var invokerOnLongPress = $parse(onLongPress);

            var onTouchEnd = $attrs.onTouchEnd;
            var invokerOnTouchEnd = $parse(onTouchEnd);

            $elm.bind('touchstart', function (evt) {
                // Locally scoped variable that will keep track of the long press
                $scope.longPress = true;

                // We'll set a timeout for 600 ms for a long press
                $timeout(function () {
                    if ($scope.longPress) {
                        // If the touchend event hasn't fired,
                        // apply the function given in on the element's on-long-press attribute
                        $scope.$apply(function () {
                            // Invoke the handler on the scope,
                            // mapping the jQuery event to the
                            // $event object.
                            invokerOnLongPress(
                               $scope
                               ,{
                                 $event: evt
                               }
                            );
                        });
                    }
                }, 600);
            });

            $elm.bind('touchend', function (evt) {
                // Prevent the onLongPress event from firing
                $scope.longPress = false;
                // If there is an on-touch-end function attached to this element, apply it
                if ($attrs.onTouchEnd) {
                    $scope.$apply(function () {
                        // Invoke the handler on the scope,
                        // mapping the jQuery event to the
                        // $event object.
                        invokerOnTouchEnd(
                           $scope
                           ,{
                             $event: evt
                           }
                        );
                    });
                }
            });
        }
    };
});

app.directive('ngCell', function($compile) {
    var ngCell = {
        scope: false,
        compile: function() {
            return {
                pre: function($scope, iElement) {
                    if($scope.field.cellTemplate){
                        // Step 1: parse HTML into DOM element
                        var template = angular.element($scope.field.cellTemplate);

                        // Step 2: compile the template
                        var linkFn = $compile(template);

                        // Step 3: link the compiled template with the scope.
                        //linkFn($scope);

                        iElement.empty();
                        iElement.append(linkFn($scope));
                    }
                }
            };
        }
    };
    return ngCell;
});
<commit_msg>Fix BUG to Directive<commit_after>var app = angular.module("xMobileNgTable");

angular.module("xMobileNgTable").run(function ($templateCache) {
   // The templateCache would be created automatically with GRUNT tool.
    $templateCache.put("view/MobileNgTable_Template.html", '

             	             {{header.displayName}}

Carregando...

             <input data-role="none" ng-show=commandColumnSelect ng-model=row[select] type="checkbox" data-ng-click="rowSelectClick($event,row)" />
{{::row[field.field] | mobileNgTableFilter:field.filter}}
	              View {{row[Visualizavel]}}	              Edit {{row[Editavel]}}	              Delete {{row[Deletavel]}}

«

‹

 <input data-role="none" ng-model="pager.startPage" style="width: 40px; text-align: right;" type="text" value="{{pager.startPage}}"/>  de   {{ functionTotal(pager.total, pager.limitPerPage) }}

›

»

                             <select data-role="page-size" class="input-sm" ng-model=pager.limitPerPage ng-change="pagerReloadClick($event, pager)" >                                 <option data-ng-repeat="size in pager.sizes" ng-selected="size == pager.limitPerPage" value="{{size}}">{{size}}</option>                             </select>

Reload

                     Exibindo   {{pager.StartInterval | number}}  -  {{pager.EndInterval | number}}   de   {{pager.total}}

');
});

app.directive('mobileNgTable', function($filter) {
    return {
        restrict: 'E',
        scope: {
            loadRepeat: '=loadRepeat'
        },
        templateUrl: "view/MobileNgTable_Template.html",
        replace: true,
        link : function(scope, element, attrs) {
            var option = scope.loadRepeat;
            scope.class = option.class;
            scope.columnDefs = option.columnDefs;
            scope.$parent.$watch(option.search, function (newSearch) { scope.search = newSearch; }, true);

            scope.rowClick = option.rowClick;

            scope.rowSelectClick = option.rowSelectClick;
            scope.commandColumnSelect = false;
            scope.select = option.select;
            if (scope.rowSelectClick && scope.select != null) {
                scope.commandColumnSelect = true;
            }

            scope.rowDeleteClick = option.rowDeleteClick;
            scope.commandColumnDelete = false;
            scope.deletable = option.deletable;
            if (scope.rowDeleteClick && scope.deletable != null) {
                scope.commandColumnDelete = true;
            }

            scope.rowEditClick = option.rowEditClick;
            scope.commandColumnEdit = false;
            scope.editable = option.editable;
            if (scope.rowEditClick && scope.editable != null) {
                scope.commandColumnEdit = true;
            }

            scope.rowViewClick = option.rowViewClick;
            scope.commandColumnView = false;
            scope.visualisable = option.visualisable;
            if (scope.rowViewClick && scope.visualisable != null) {
                scope.commandColumnView = true;
            }

            scope.itemOnLongPress = option.itemOnLongPress;
            scope.itemOnTouchEnd = option.itemOnTouchEnd;

            scope.pager = option.pager;
            scope.pager.type = option.pager.type;

            if(scope.pager.type == 'local') {
                scope.pagerReloadClick = function (e, pager) {
                    scope.$parent.$watch(option.data, function (newdata) {
                        var begin = ((pager.startPage - 1) * pager.limitPerPage);
                        var end = begin + pager.limitPerPage;
                        scope.data = newdata.slice(begin, end);
                        scope.pager.StartInterval = begin + 1;
                        scope.pager.EndInterval  = (end > newdata.length ? newdata.length : end);
                        scope.pager.total = newdata.length;
                    }, true);
                }
                scope.pagerReloadClick(null, scope.pager);
            } else {
                scope.$parent.$watch(option.data, function (newdata) { scope.data = newdata; }, true);
                scope.pagerReloadClick = function (e, pager)
                {
                    option.pagerReloadClick(e, pager);
                    var begin = ((parseInt(pager.startPage) - 1) * parseInt(pager.limitPerPage));
                    var end = begin + parseInt(pager.limitPerPage);
                    scope.pager.StartInterval = begin + 1;
                    scope.pager.EndInterval = (end > parseInt(scope.pager.total) ? parseInt(scope.pager.total) : end);
                }
                scope.pagerReloadClick(null, scope.pager);
            }

            scope.pagerFirstClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if (parseInt(pager.startPage) != parseInt(1)) {
                        pager.startPage = 1;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            };
            scope.pagerPreviousClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if ((parseInt(pager.startPage) > parseInt(1))) {
                        pager.startPage = pager.startPage - 1;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            };
            scope.pagerNextClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if ((parseInt(pager.startPage) < parseInt(pager.totalPages))) {
                        pager.startPage = pager.startPage + 1;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            }
            scope.pagerLastClick = function (e, pager) {
                if (scope.pagerReloadClick) {
                    if ((parseInt(pager.startPage) != parseInt(pager.totalPages))) {
                        pager.startPage = pager.totalPages;
                        scope.pagerReloadClick(e, pager);
                    }
                }
            };
            scope.functionTotal = function (total, limitPerPage) {
                scope.pager.totalPages = Math.round((total % limitPerPage > 0 ? parseInt(total / limitPerPage) + 1 : (total / limitPerPage)));
                return scope.pager.totalPages;
            };
            scope.tableLoading = true;
            scope.endRepeat = function () {
                scope.tableLoading = false;
            };
        }
    };
});

app.filter('mobileNgTableFilter', function($filter) {
    return function(value, filterData) {
        if(filterData){
            var filter = filterData.trim().split(":");
            var filterName = filter[0];
            var expression = filter[1];
            return $filter(filterName)(value,expression);
        }else{
            return value;
        }
    };
});

//Add this directive where you keep your directives
app.directive('onLongPress', function ($timeout,$parse) {
    return {
        restrict: 'A',
        link: function ($scope, $elm, $attrs) {
            var onLongPress = $attrs.onLongPress;
            var invokerOnLongPress = $parse(onLongPress);

            var onTouchEnd = $attrs.onTouchEnd;
            var invokerOnTouchEnd = $parse(onTouchEnd);

            $elm.bind('touchstart', function (evt) {
                // Locally scoped variable that will keep track of the long press
                $scope.longPress = true;

                // We'll set a timeout for 600 ms for a long press
                $timeout(function () {
                    if ($scope.longPress) {
                        // If the touchend event hasn't fired,
                        // apply the function given in on the element's on-long-press attribute
                        $scope.$apply(function () {
                            // Invoke the handler on the scope,
                            // mapping the jQuery event to the
                            // $event object.
                            invokerOnLongPress(
                               $scope
                               ,{
                                 $event: evt
                               }
                            );
                        });
                    }
                }, 600);
            });

            $elm.bind('touchend', function (evt) {
                // Prevent the onLongPress event from firing
                $scope.longPress = false;
                // If there is an on-touch-end function attached to this element, apply it
                if ($attrs.onTouchEnd) {
                    $scope.$apply(function () {
                        // Invoke the handler on the scope,
                        // mapping the jQuery event to the
                        // $event object.
                        invokerOnTouchEnd(
                           $scope
                           ,{
                             $event: evt
                           }
                        );
                    });
                }
            });
        }
    };
});

app.directive('ngCell', function($compile) {
    var ngCell = {
        scope: false,
        compile: function() {
            return {
                pre: function($scope, iElement) {
                    if($scope.field.cellTemplate){
                        // Step 1: parse HTML into DOM element
                        var template = angular.element($scope.field.cellTemplate);

                        // Step 2: compile the template
                        var linkFn = $compile(template);

                        // Step 3: link the compiled template with the scope.
                        //linkFn($scope);

                        iElement.empty();
                        iElement.append(linkFn($scope));
                    }
                }
            };
        }
    };
    return ngCell;
});
<|endoftext|>


<commit_before>// Load modules

var Stream = require('stream');
var Fs = require('fs');
var Zlib = require('zlib');
var Crypto = require('crypto');
var Qs = require('qs');
var Nipple = require('nipple');
var Multiparty = require('multiparty');
var Boom = require('boom');
var Utils = require('./utils');

// Declare internals

var internals = {};

// Read and parse body

exports.read = function (request, next) {

    if (request.method === 'get' || request.method === 'head') {            // When route.method is '*'
        return next();
    }

    // Fail action

    var failActionNext = function (err) {

        if (!err) {
            return next();
        }

        // failAction: 'error', 'log', 'ignore'

        var failAction = request.route.payload.failAction;
        if (failAction !== 'ignore') {
            request.log(['hapi', 'payload', 'error'], err);
        }

        if (failAction === 'error') {
            return next(err);
        }

        return next();
    };

    // Content size

    var req = request.raw.req;
    var contentLength = req.headers['content-length'];
    if (contentLength &&
        parseInt(contentLength, 10) > request.route.payload.maxBytes) {

        return next(Boom.badRequest('Payload content length greater than maximum allowed: ' + request.route.payload.maxBytes));
    }

    // Content type

    var contentType = request.route.payload.override || (req.headers && req.headers['content-type']) || 'application/json';     //  Defaults to 'application/json'
    var mime = contentType.split(';')[0].trim().toLowerCase();
    request.mime = mime;

    if (request.route.payload.allow &&
        request.route.payload.allow.indexOf(mime) === -1) {

        return failActionNext(Boom.unsupportedMediaType());
    }

    // Parse: true

    if (request.route.payload.parse === true) {
        return internals.parse(request, failActionNext);
    }

    // Parse: false, 'gunzip'

    return internals.raw(request, next);
};

internals.parse = function (request, next, failActionNext) {

    var output = request.route.payload.output;      // Output: 'data', 'stream', 'file'
    var source = request.raw.req;

    // Content-encoding

    var contentEncoding = source.headers['content-encoding'];
    if (contentEncoding === 'gzip' || contentEncoding === 'deflate') {
        var decoder = (contentEncoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate());
        next = Utils.once(next);                                                                     // Modify next() for async events
        decoder.once('error', function (err) {

            return next(Boom.badRequest('Invalid compressed payload'));
        });

        source = source.pipe(decoder);
    }

    // Tap request

    var tap = request._tap();
    if (tap) {
        source = source.pipe(tap);
    }

    // Multipart

    if (request.mime === 'multipart/form-data') {
        return internals.multipart(request, source, next);
    }

    // Output: 'stream'

    if (output === 'stream') {
        request.payload = source;
        return next();
    }

    // Output: 'file'

    if (output === 'file') {
        internals.writeFile(source, request.route.payload.uploads, function (err, path, bytes) {

            if (err) {
                return next(err);
            }

            request.payload = { path: path, bytes: bytes };
            return next();
        });

        return;
    }

    // Output: 'data'

    return internals.buffer(request, source, function (err, payload) {

        if (err) {
            return next(err);
        }

        request.payload = {};

        if (!payload.length) {
            return next();
        }

        internals.object(payload, request.mime, function (err, result) {

            if (err) {
                return next(err);
            }

            request.payload = result;
            return next();
        });
    });
};

internals.raw = function (request, next) {

    var output = request.route.payload.output;      // Output: 'data', 'stream', 'file'
    var source = request.raw.req;

    // Content-encoding

    if (request.route.payload.parse === 'gunzip') {
        var contentEncoding = source.headers['content-encoding'];
        if (contentEncoding === 'gzip' || contentEncoding === 'deflate') {
            var decoder = (contentEncoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate());
            next = Utils.once(next);                                                                     // Modify next() for async events
            decoder.once('error', function (err) {

                return next(Boom.badRequest('Invalid compressed payload'));
            });

            source = source.pipe(decoder);
        }
    }

    // Setup source

    var tap = request._tap();
    if (tap) {
        source = source.pipe(tap);
    }

    // Output: 'stream'

    if (output === 'stream') {
        request.payload = source;
        return next();
    }

    // Output: 'file'

    if (output === 'file') {
        internals.writeFile(source, request.route.payload.uploads, function (err, path, bytes) {

            if (err) {
                return next(err);
            }

            request.payload = { path: path, bytes: bytes };
            return next();
        });

        return;
    }

    // Output: 'data'

    return internals.buffer(request, source, function (err, payload) {

        if (err) {
            return next(err);
        }

        request.payload = payload;
        return next();
    });
};

internals.buffer = function (request, source, next) {

    var parseOptions = {
        timeout: request.server.settings.timeout.client,
        maxBytes: request.route.payload.maxBytes
    };

    Nipple.read(source, parseOptions, next);
};

internals.object = function (payload, mime, next) {

    // Binary

    if (mime === 'application/octet-stream') {
        return next(null, payload);
    }

    // Text

    if (mime.match(/^text\/.+$/)) {
        return next(null, payload.toString('utf8'));
    }

    // JSON

    if (mime === 'application/json') {
        return internals.jsonParse(payload, next);                      // Isolate try...catch for V8 optimization
    }

    // Form-encoded

    if (mime === 'application/x-www-form-urlencoded') {
        return next(null, Qs.parse(payload.toString('utf8')));
    }

    return next(Boom.unsupportedMediaType());
};

internals.jsonParse = function (payload, next) {

    try {
        return next(null, JSON.parse(payload.toString('utf8')));
    }
    catch (err) {
        return next(Boom.badRequest('Invalid request payload JSON format'));
    }
};

internals.multipart = function (request, source, next) {

    var options = request.route.payload;
    next = Utils.once(next);                                            // Modify next() for async events

    var form = new Multiparty.Form({
        maxFields: Infinity,
        maxFieldsSize: Infinity,
        uploadDir: options.uploads
    });

    form.once('error', function (err) {

        return next(Boom.badRequest('Invalid multipart payload format'));
    });

    var arrayFields = false;
    var finalize = function (data) {

        if (arrayFields) {
            data = Qs.parse(data);
        }

        request.payload = data;
        return next();
    };

    var data = {};
    var set = function (name, value) {

        arrayFields = arrayFields || (name.indexOf('[') !== -1);

        if (!data.hasOwnProperty(name)) {
            data[name] = value;
        }
        else if (Array.isArray(data[name])) {
            data[name].push(value);
        }
        else {
            data[name] = [data[name], value];
        }
    };

    var pendingFiles = {};
    var nextId = 0;
    var closed = false;

    form.on('part', function (part) {

        if (!part.filename) {
            return;
        }

        if (options.output === 'file') {                                                // Output: 'file'
            var id = nextId++;
            pendingFiles[id] = true;
            internals.writeFile(part, options.uploads, function (err, path, bytes) {

                delete pendingFiles[id];

                if (err) {
                    return next(err);
                }

                var item = {
                    filename: part.filename,
                    path: path,
                    headers: part.headers,
                    bytes: bytes
                };

                set(part.name, item);

                if (closed) {
                    return finalize(data);
                }
            });
        }
        else {                                                                          // Output: 'data'
            Nipple.read(part, {}, function (err, payload) {

                // err handled by form.once('error')

                if (options.output === 'stream') {                                      // Output: 'stream'
                    return set(part.name, Nipple.toReadableStream(payload));
                }

                var contentType = (part.headers && part.headers['content-type']) || '';
                var mime = contentType.split(';')[0].trim().toLowerCase();

                if (!mime) {
                    return set(part.name, payload);
                }

                if (!payload.length) {
                    return set(part.name, {});
                }

                internals.object(payload, mime, function (err, result) {

                    return set(part.name, err ? payload : result);
                });
            });
        }
    });

    form.on('field', function (name, value) {

        set(name, value);
    });

    form.once('close', function () {

        form.removeAllListeners();
        if (Object.keys(pendingFiles).length) {
            closed = true;
            return;
        }

        return finalize(data);
    });

    source.headers = source.headers || request.headers;
    form.parse(source);
};

internals.writeFile = function (stream, dest, callback) {

    var path = Utils.uniqueFilename(dest);
    var file = Fs.createWriteStream(path, { flags: 'wx' });
    var counter = new internals.Counter();

    var finalize = Utils.once(function (err) {

        file.removeAllListeners();

        if (!err) {
            return callback(null, path, counter.bytes);
        }

        file.destroy();
        Fs.unlink(path, function (fsErr) {      // Ignore unlink errors

            return callback(err);
        });
    });

    file.once('close', finalize);
    file.once('error', finalize);

    stream.pipe(counter).pipe(file);
};

internals.Counter = function () {

    Stream.Transform.call(this);
    this.bytes = 0;
}

Utils.inherits(internals.Counter, Stream.Transform);

internals.Counter.prototype._transform = function (chunk, encoding, next) {

    this.bytes += chunk.length;
    next(null, chunk);
};
<commit_msg>Fix multipart multiple large files. Closes #1532<commit_after>// Load modules

var Stream = require('stream');
var Fs = require('fs');
var Zlib = require('zlib');
var Crypto = require('crypto');
var Qs = require('qs');
var Nipple = require('nipple');
var Multiparty = require('multiparty');
var Boom = require('boom');
var Utils = require('./utils');

// Declare internals

var internals = {};

// Read and parse body

exports.read = function (request, next) {

    if (request.method === 'get' || request.method === 'head') {            // When route.method is '*'
        return next();
    }

    // Fail action

    var failActionNext = function (err) {

        if (!err) {
            return next();
        }

        // failAction: 'error', 'log', 'ignore'

        var failAction = request.route.payload.failAction;
        if (failAction !== 'ignore') {
            request.log(['hapi', 'payload', 'error'], err);
        }

        if (failAction === 'error') {
            return next(err);
        }

        return next();
    };

    // Content size

    var req = request.raw.req;
    var contentLength = req.headers['content-length'];
    if (contentLength &&
        parseInt(contentLength, 10) > request.route.payload.maxBytes) {

        return next(Boom.badRequest('Payload content length greater than maximum allowed: ' + request.route.payload.maxBytes));
    }

    // Content type

    var contentType = request.route.payload.override || req.headers['content-type'] || 'application/json';      //  Defaults to 'application/json'
    var mime = contentType.split(';')[0].trim().toLowerCase();
    request.mime = mime;

    if (request.route.payload.allow &&
        request.route.payload.allow.indexOf(mime) === -1) {

        return failActionNext(Boom.unsupportedMediaType());
    }

    // Parse: true

    if (request.route.payload.parse === true) {
        return internals.parse(request, failActionNext);
    }

    // Parse: false, 'gunzip'

    return internals.raw(request, next);
};

internals.parse = function (request, next, failActionNext) {

    var output = request.route.payload.output;      // Output: 'data', 'stream', 'file'
    var source = request.raw.req;

    // Content-encoding

    var contentEncoding = source.headers['content-encoding'];
    if (contentEncoding === 'gzip' || contentEncoding === 'deflate') {
        var decoder = (contentEncoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate());
        next = Utils.once(next);                                                                     // Modify next() for async events
        decoder.once('error', function (err) {

            return next(Boom.badRequest('Invalid compressed payload'));
        });

        source = source.pipe(decoder);
    }

    // Tap request

    var tap = request._tap();
    if (tap) {
        source = source.pipe(tap);
    }

    // Multipart

    if (request.mime === 'multipart/form-data') {
        return internals.multipart(request, source, next);
    }

    // Output: 'stream'

    if (output === 'stream') {
        request.payload = source;
        return next();
    }

    // Output: 'file'

    if (output === 'file') {
        internals.writeFile(source, request.route.payload.uploads, function (err, path, bytes) {

            if (err) {
                return next(err);
            }

            request.payload = { path: path, bytes: bytes };
            return next();
        });

        return;
    }

    // Output: 'data'

    return internals.buffer(request, source, function (err, payload) {

        if (err) {
            return next(err);
        }

        request.payload = {};

        if (!payload.length) {
            return next();
        }

        internals.object(payload, request.mime, function (err, result) {

            if (err) {
                return next(err);
            }

            request.payload = result;
            return next();
        });
    });
};

internals.raw = function (request, next) {

    var output = request.route.payload.output;      // Output: 'data', 'stream', 'file'
    var source = request.raw.req;

    // Content-encoding

    if (request.route.payload.parse === 'gunzip') {
        var contentEncoding = source.headers['content-encoding'];
        if (contentEncoding === 'gzip' || contentEncoding === 'deflate') {
            var decoder = (contentEncoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate());
            next = Utils.once(next);                                                                     // Modify next() for async events
            decoder.once('error', function (err) {

                return next(Boom.badRequest('Invalid compressed payload'));
            });

            source = source.pipe(decoder);
        }
    }

    // Setup source

    var tap = request._tap();
    if (tap) {
        source = source.pipe(tap);
    }

    // Output: 'stream'

    if (output === 'stream') {
        request.payload = source;
        return next();
    }

    // Output: 'file'

    if (output === 'file') {
        internals.writeFile(source, request.route.payload.uploads, function (err, path, bytes) {

            if (err) {
                return next(err);
            }

            request.payload = { path: path, bytes: bytes };
            return next();
        });

        return;
    }

    // Output: 'data'

    return internals.buffer(request, source, function (err, payload) {

        if (err) {
            return next(err);
        }

        request.payload = payload;
        return next();
    });
};

internals.buffer = function (request, source, next) {

    var parseOptions = {
        timeout: request.server.settings.timeout.client,
        maxBytes: request.route.payload.maxBytes
    };

    Nipple.read(source, parseOptions, next);
};

internals.object = function (payload, mime, next) {

    // Binary

    if (mime === 'application/octet-stream') {
        return next(null, payload);
    }

    // Text

    if (mime.match(/^text\/.+$/)) {
        return next(null, payload.toString('utf8'));
    }

    // JSON

    if (mime === 'application/json') {
        return internals.jsonParse(payload, next);                      // Isolate try...catch for V8 optimization
    }

    // Form-encoded

    if (mime === 'application/x-www-form-urlencoded') {
        return next(null, Qs.parse(payload.toString('utf8')));
    }

    return next(Boom.unsupportedMediaType());
};

internals.jsonParse = function (payload, next) {

    try {
        return next(null, JSON.parse(payload.toString('utf8')));
    }
    catch (err) {
        return next(Boom.badRequest('Invalid request payload JSON format'));
    }
};

internals.multipart = function (request, source, next) {

    var options = request.route.payload;
    next = Utils.once(next);                                            // Modify next() for async events

    var form = new Multiparty.Form({
        maxFields: Infinity,
        maxFieldsSize: Infinity,
        uploadDir: options.uploads
    });

    form.once('error', function (err) {

        return next(Boom.badRequest('Invalid multipart payload format'));
    });

    var arrayFields = false;
    var finalize = function (data) {

        form.removeAllListeners();

        if (arrayFields) {
            data = Qs.parse(data);
        }

        request.payload = data;
        return next();
    };

    var data = {};
    var set = function (name, value) {

        arrayFields = arrayFields || (name.indexOf('[') !== -1);

        if (!data.hasOwnProperty(name)) {
            data[name] = value;
        }
        else if (Array.isArray(data[name])) {
            data[name].push(value);
        }
        else {
            data[name] = [data[name], value];
        }
    };

    var pendingFiles = {};
    var nextId = 0;
    var closed = false;

    form.on('part', function (part) {

        if (!part.filename) {
            return;
        }

        if (options.output === 'file') {                                                // Output: 'file'
            var id = nextId++;
            pendingFiles[id] = true;
            internals.writeFile(part, options.uploads, function (err, path, bytes) {

                delete pendingFiles[id];

                if (err) {
                    return next(err);
                }

                var item = {
                    filename: part.filename,
                    path: path,
                    headers: part.headers,
                    bytes: bytes
                };

                set(part.name, item);

                if (closed &&
                    !Object.keys(pendingFiles).length) {

                    return finalize(data);
                }
            });
        }
        else {                                                                          // Output: 'data'
            Nipple.read(part, {}, function (err, payload) {

                // err handled by form.once('error')

                if (options.output === 'stream') {                                      // Output: 'stream'
                    return set(part.name, Nipple.toReadableStream(payload));
                }

                var contentType = (part.headers && part.headers['content-type']) || '';
                var mime = contentType.split(';')[0].trim().toLowerCase();

                if (!mime) {
                    return set(part.name, payload);
                }

                if (!payload.length) {
                    return set(part.name, {});
                }

                internals.object(payload, mime, function (err, result) {

                    return set(part.name, err ? payload : result);
                });
            });
        }
    });

    form.on('field', function (name, value) {

        set(name, value);
    });

    form.once('close', function () {

        if (Object.keys(pendingFiles).length) {
            closed = true;
            return;
        }

        return finalize(data);
    });

    source.headers = source.headers || request.headers;
    form.parse(source);
};

internals.writeFile = function (stream, dest, callback) {

    var path = Utils.uniqueFilename(dest);
    var file = Fs.createWriteStream(path, { flags: 'wx' });
    var counter = new internals.Counter();

    var finalize = Utils.once(function (err) {

        file.removeAllListeners();

        if (!err) {
            return callback(null, path, counter.bytes);
        }

        file.destroy();
        Fs.unlink(path, function (fsErr) {      // Ignore unlink errors

            return callback(err);
        });
    });

    file.once('close', finalize);
    file.once('error', finalize);

    stream.pipe(counter).pipe(file);
};

internals.Counter = function () {

    Stream.Transform.call(this);
    this.bytes = 0;
}

Utils.inherits(internals.Counter, Stream.Transform);

internals.Counter.prototype._transform = function (chunk, encoding, next) {

    this.bytes += chunk.length;
    next(null, chunk);
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var result = require('./result');
var orm = require('orm');
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
//Todo
var source_url = {check: '', review: ''};
var target_url = {check: '', review: ''};

//根据ID获取医生信息
router.get('/info', function (req, res, next) {
    var doctor_id = req.param('doctor_id');
    req.models.doctor.get(doctor_id, function (err, item) {
        if (err || !item) {
            res.json(result(false, err.msg, {}));
        } else {
            res.json(result(true, '', item));
        }
    });
});

//获取出院的病人
router.get('/out_sicks', function (req, res, next) {
    var doctor_id = req.param('doctor_id');
    if (!doctor_id) {
        res.json(result(false, 'no doctor_id', {}));
        return;
    }
    req.models.sick.find({
        doctor_id: doctor_id,
        out_day: orm.lte(new Date())
    }, function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', data));
        }
    });
});

//获取该医生所有的病人
router.get('/sicks', function (req, res, next) {
    var doctor_id = req.param('doctor_id');
    if (!doctor_id) {
        res.json(result(false, 'no doctor_id', {}));
        return;
    }
    req.models.sick.find({doctor_id: doctor_id}, function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', data));
        }
    });
});

//查房
router.post('/check', function (req, res, next) {
    //生成multiparty对象，并配置下载目标路径
    var form = new multiparty.Form({uploadDir: './public/images/'});
    //下载后处理
    form.parse(req, function (err, fields, files) {
        var filesTmp = JSON.stringify(files, null, 2);
        var sick_id, doctor_id, description, title;
        try {
            sick_id = fields['sick_id'];
            doctor_id = fields['doctor_id'];
            title = fields['title'];
            description = fields['description'];
        } catch (e) {
            console.error(e);
            err = e;
        }
        if (err) {
            console.log('parse image error: ' + err);
            res.redirect(source_url.check + "?err=1");
        } else {
            console.log('parse files: ' + filesTmp);
            var pic = [];
            for(var key in files) {
                for (var file in files[key]) {
                    pic.push(file.path);
                }
            }

            req.models.sickcheck.create({
                title: title,
                sick_id: sick_id, doctor_id: doctor_id, day: new Date(), description: JSON.parse(description), pics: pic
            }, function (err, item) {
                if (err) {
                    console.error(err);
                    res.redirect(source_url.check + "?err=1");
                } else {
                    res.redirect(target_url.check);
                }
            });

        }
    });
});

//随访
router.post('/out_check', function (req, res, next) {
    //生成multiparty对象，并配置下载目标路径
    var form = new multiparty.Form({uploadDir: './public/images/'});
    //下载后处理
    form.parse(req, function (err, fields, files) {
        var filesTmp = JSON.stringify(files, null, 2);
        var sick_id, doctor_id, description, title;
        try {
            sick_id = fields['sick_id'];
            doctor_id = fields['doctor_id'];
            title = fields['title'];
            description = fields['description'];
        } catch (e) {
            console.error(e);
            err = e;
        }
        if (err) {
            console.log('parse image error: ' + err);
            res.redirect(source_url.review + "?err=1");
        } else {
            console.log('parse files: ' + filesTmp);
            var pic = [];
            for (var i = 0; i < files.inputFile.length; i++) {
                pic[i] = files.file[i].path;
            }

            req.models.sickreview.create({
                title: title,
                sick_id: sick_id, doctor_id: doctor_id, day: new Date(), description: JSON.parse(description), pics: pic
            }, function (err, item) {
                if (err) {
                    console.error(err);
                    res.redirect(source_url.review + "?err=1");
                } else {
                    res.redirect(target_url.review);
                }
            });

        }
    });

});

module.exports = router;
<commit_msg>update check logic<commit_after>var express = require('express');
var router = express.Router();
var result = require('./result');
var orm = require('orm');
var multiparty = require('multiparty');
var util = require('util');
var fs = require('fs');
//Todo
var source_url = {check: '', review: ''};
var target_url = {check: '', review: ''};

//根据ID获取医生信息
router.get('/info', function (req, res, next) {
    var doctor_id = req.param('doctor_id');
    req.models.doctor.get(doctor_id, function (err, item) {
        if (err || !item) {
            res.json(result(false, err.msg, {}));
        } else {
            res.json(result(true, '', item));
        }
    });
});

//获取出院的病人
router.get('/out_sicks', function (req, res, next) {
    var doctor_id = req.param('doctor_id');
    if (!doctor_id) {
        res.json(result(false, 'no doctor_id', {}));
        return;
    }
    req.models.sick.find({
        doctor_id: doctor_id,
        out_day: orm.lte(new Date())
    }, function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', data));
        }
    });
});

//获取该医生所有的病人
router.get('/sicks', function (req, res, next) {
    var doctor_id = req.param('doctor_id');
    if (!doctor_id) {
        res.json(result(false, 'no doctor_id', {}));
        return;
    }
    req.models.sick.find({doctor_id: doctor_id}, function (err, data) {
        if (err || !data) {
            console.error(err);
            res.json(result(false, '', {}));
        } else {
            res.json(result(true, '', data));
        }
    });
});

//查房
router.post('/check', function (req, res, next) {

        var sick_id, doctor_id, description, title, pic;
        try {
            sick_id = req.param('sick_id');
            doctor_id = req.param('doctor_id');
            title = req.param('title');
            description = req.param('description');
            pic = req.param('pics');
        } catch (e) {
            console.error(e);
            err = e;
        }
        if (err) {
            console.log('parse image error: ' + err);
            res.redirect(source_url.check + "?err=1");
        } else {
            console.log('parse files: ' + filesTmp);

            req.models.sickcheck.create({
                title: title,
                sick_id: sick_id, doctor_id: doctor_id, day: new Date(), description: description, pics: pic
            }, function (err, item) {
                if (err) {
                    console.error(err);
                    res.redirect(source_url.check + "?err=1");
                } else {
                    res.redirect(target_url.check);
                }
            });

        }

});

//随访
router.post('/out_check', function (req, res, next) {
    //生成multiparty对象，并配置下载目标路径
    var form = new multiparty.Form({uploadDir: './public/images/'});
    //下载后处理
    form.parse(req, function (err, fields, files) {
        var filesTmp = JSON.stringify(files, null, 2);
        var sick_id, doctor_id, description, title;
        try {
            sick_id = fields['sick_id'];
            doctor_id = fields['doctor_id'];
            title = fields['title'];
            description = fields['description'];
        } catch (e) {
            console.error(e);
            err = e;
        }
        if (err) {
            console.log('parse image error: ' + err);
            res.redirect(source_url.review + "?err=1");
        } else {
            console.log('parse files: ' + filesTmp);
            var pic = [];
            for (var i = 0; i < files.inputFile.length; i++) {
                pic[i] = files.file[i].path;
            }

            req.models.sickreview.create({
                title: title,
                sick_id: sick_id, doctor_id: doctor_id, day: new Date(), description: JSON.parse(description), pics: pic
            }, function (err, item) {
                if (err) {
                    console.error(err);
                    res.redirect(source_url.review + "?err=1");
                } else {
                    res.redirect(target_url.review);
                }
            });

        }
    });

});

router.get("/checkList", function(req, res, next){
    var sick_id = req.param("sick_id");
    var doctor_id = req.param("doctor_id");
    var query = {};
    if (sick_id) {
        query.sick_id = sick_id;
    }
    if (doctor_id) {
        query.doctor_id = doctor_id;
    }
    req.models.sickcheck.find(query, function(err, data) {
        if (err) {
            res.json(result(false,"get sickcheck err", err));
        } else {
            res.json(result(true,'',data));
        }
    });
});

module.exports = router;
<|endoftext|>


<commit_before>angular.module('youtube-embed', ['ng'])
.service('$youtube', ['$window', '$rootScope', function ($window, $rootScope) {
    // adapted from http://stackoverflow.com/a/5831191/1614967
    var youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
    var timeRegexp = /t=(\d+)[ms]?(\d+)?s?/;

    function contains (str, substr) {
        return (str.indexOf(substr) > -1);
    }

    var service = {
        // Frame is ready
        ready: false,

        // Element id for player
        playerId: null,

        // Player currently in use
        player: null,

        // Current video id
        videoId: null,

        // Size
        playerHeight: '390',
        playerWidth: '640',

        currentState: null,

        setURL: function (url) {
            service.videoId = service.getIdFromURL(url);
        },

        getIdFromURL: function (url) {
            var id = url.replace(youtubeRegexp, '$1');

            if (contains(id, ';')) {
                var pieces = id.split(';');

                if (contains(pieces[1], '%')) {
                    // links like this:
                    // "http://www.youtube.com/attribution_link?a=pxa6goHqzaA&u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare"
                    // have the real query string URI encoded behind a ';'.
                    // at this point, `id is 'pxa6goHqzaA;u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare'
                    var uriComponent = decodeURIComponent(id.split(';')[1]);
                    id = ('http://youtube.com' + uriComponent)
                            .replace(youtubeRegexp, '$1');
                } else {
                    // https://www.youtube.com/watch?v=VbNF9X1waSc&feature=youtu.be
                    // `id` looks like 'VbNF9X1waSc;feature=youtu.be' currently.
                    // strip the ';feature=youtu.be'
                    id = pieces[0]
                }
            } else if (contains(id, '#')) {
                // id might look like '93LvTKF_jW0#t=1'
                // and we want '93LvTKF_jW0'
                id = id.split('#')[0];
            }

            return id;
        },

        getTimeFromURL: function (url) {
            url || (url = '');

            // t=4m20s
            // returns ['t=4m20s', '4', '20']
            // t=46s
            // returns ['t=46s', '46']
            // t=46
            // returns ['t=46', '46']
            var times = url.match(timeRegexp);

            if (!times) {
                // zero seconds
                return 0;
            }

            // assume the first
            var full = times[0],
                minutes = times[1],
                seconds = times[2];

            // t=4m20s
            if (typeof seconds !== 'undefined') {
                seconds = parseInt(seconds, 10);
                minutes = parseInt(minutes, 10);

            // t=4m
            } else if (contains(full, 'm')) {
                minutes = parseInt(minutes, 10);
                seconds = 0;

            // t=4s
            // t=4
            } else {
                seconds = parseInt(minutes, 10);
                minutes = 0;
            }

            // in seconds
            return seconds + (minutes * 60);
        },

        createPlayer: function (playerVars) {
            return new YT.Player(this.playerId, {
                height: this.playerHeight,
                width: this.playerWidth,
                videoId: this.videoId,
                playerVars: playerVars,
                events: {
                    onReady: onPlayerReady,
                    onStateChange: onPlayerStateChange
                }
            });
        },

        loadPlayer: function (playerVars) {
            if (this.ready && this.playerId && this.videoId) {
                if (this.player && typeof this.player.destroy === 'function') {
                    this.player.destroy();
                }

                this.player = this.createPlayer(playerVars);
            }
        }
    };

    // YT calls callbacks outside of digest cycle
    function applyBroadcast (event) {
        $rootScope.$apply(function () {
            $rootScope.$broadcast(event);
        });
    }

    // from YT.PlayerState
    var stateNames = {
        0: 'ended',
        1: 'playing',
        2: 'paused',
        3: 'buffering',
        5: 'queued'
    };

    var eventPrefix = 'youtube.player.';

    function onPlayerReady (event) {
        applyBroadcast(eventPrefix + 'ready');
    }

    function onPlayerStateChange (event) {
        var state = stateNames[event.data];
        if (typeof state !== 'undefined') {
            applyBroadcast(eventPrefix + state);
        }
        service.currentState = state;
    }

    // Inject YouTube's iFrame API
    (function () {
        var tag = document.createElement('script');
        tag.src = "//www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }());

    // Youtube callback when API is ready
    $window.onYouTubeIframeAPIReady = function () {
        $rootScope.$apply(function () {
            service.ready = true;
        });
    };

    return service;
}])
.directive('youtubeVideo', ['$youtube', function ($youtube) {
    return {
        restrict: 'EA',
        scope: {
            videoId: '=',
            videoUrl: '=',
            playerVars: '='
        },
        link: function (scope, element, attrs) {
            // Attach to element
            $youtube.playerId = element[0].id;

            var stopWatchingReady = scope.$watch(
                function () {
                    return $youtube.ready
                        // Wait until one of them is defined...
                        && (typeof scope.videoUrl !== 'undefined'
                        ||  typeof scope.videoId !== 'undefined');
                },
                function (ready) {
                    if (ready) {
                        stopWatchingReady();

                        // use URL if you've got it
                        if (typeof scope.videoUrl !== 'undefined') {
                            scope.$watch('videoUrl', function (url) {
                                $youtube.setURL(url);
                                $youtube.loadPlayer(scope.playerVars);
                            });

                        // otherwise, watch the id
                        } else {
                            scope.$watch('videoId', function (id) {
                                $youtube.videoId = id;
                                $youtube.loadPlayer(scope.playerVars);
                            });
                        }
                    }
            });
        }
    };
}]);
<commit_msg>Add player height and width args.<commit_after>angular.module('youtube-embed', ['ng'])
.service('$youtube', ['$window', '$rootScope', function ($window, $rootScope) {
    // adapted from http://stackoverflow.com/a/5831191/1614967
    var youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig;
    var timeRegexp = /t=(\d+)[ms]?(\d+)?s?/;

    function contains (str, substr) {
        return (str.indexOf(substr) > -1);
    }

    var service = {
        // Frame is ready
        ready: false,

        // Element id for player
        playerId: null,

        // Player currently in use
        player: null,

        // Current video id
        videoId: null,

        // Size
        playerHeight: null,
        playerWidth: null,

        currentState: null,

        setURL: function (url) {
            service.videoId = service.getIdFromURL(url);
        },

        getIdFromURL: function (url) {
            var id = url.replace(youtubeRegexp, '$1');

            if (contains(id, ';')) {
                var pieces = id.split(';');

                if (contains(pieces[1], '%')) {
                    // links like this:
                    // "http://www.youtube.com/attribution_link?a=pxa6goHqzaA&u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare"
                    // have the real query string URI encoded behind a ';'.
                    // at this point, `id is 'pxa6goHqzaA;u=%2Fwatch%3Fv%3DdPdgx30w9sU%26feature%3Dshare'
                    var uriComponent = decodeURIComponent(id.split(';')[1]);
                    id = ('http://youtube.com' + uriComponent)
                            .replace(youtubeRegexp, '$1');
                } else {
                    // https://www.youtube.com/watch?v=VbNF9X1waSc&feature=youtu.be
                    // `id` looks like 'VbNF9X1waSc;feature=youtu.be' currently.
                    // strip the ';feature=youtu.be'
                    id = pieces[0]
                }
            } else if (contains(id, '#')) {
                // id might look like '93LvTKF_jW0#t=1'
                // and we want '93LvTKF_jW0'
                id = id.split('#')[0];
            }

            return id;
        },

        getTimeFromURL: function (url) {
            url || (url = '');

            // t=4m20s
            // returns ['t=4m20s', '4', '20']
            // t=46s
            // returns ['t=46s', '46']
            // t=46
            // returns ['t=46', '46']
            var times = url.match(timeRegexp);

            if (!times) {
                // zero seconds
                return 0;
            }

            // assume the first
            var full = times[0],
                minutes = times[1],
                seconds = times[2];

            // t=4m20s
            if (typeof seconds !== 'undefined') {
                seconds = parseInt(seconds, 10);
                minutes = parseInt(minutes, 10);

            // t=4m
            } else if (contains(full, 'm')) {
                minutes = parseInt(minutes, 10);
                seconds = 0;

            // t=4s
            // t=4
            } else {
                seconds = parseInt(minutes, 10);
                minutes = 0;
            }

            // in seconds
            return seconds + (minutes * 60);
        },

        createPlayer: function (playerVars) {
            return new YT.Player(this.playerId, {
                height: this.playerHeight,
                width: this.playerWidth,
                videoId: this.videoId,
                playerVars: playerVars,
                events: {
                    onReady: onPlayerReady,
                    onStateChange: onPlayerStateChange
                }
            });
        },

        loadPlayer: function (playerVars) {
            if (this.ready && this.playerId && this.videoId) {
                if (this.player && typeof this.player.destroy === 'function') {
                    this.player.destroy();
                }

                this.player = this.createPlayer(playerVars);
            }
        }
    };

    // YT calls callbacks outside of digest cycle
    function applyBroadcast (event) {
        $rootScope.$apply(function () {
            $rootScope.$broadcast(event);
        });
    }

    // from YT.PlayerState
    var stateNames = {
        0: 'ended',
        1: 'playing',
        2: 'paused',
        3: 'buffering',
        5: 'queued'
    };

    var eventPrefix = 'youtube.player.';

    function onPlayerReady (event) {
        applyBroadcast(eventPrefix + 'ready');
    }

    function onPlayerStateChange (event) {
        var state = stateNames[event.data];
        if (typeof state !== 'undefined') {
            applyBroadcast(eventPrefix + state);
        }
        service.currentState = state;
    }

    // Inject YouTube's iFrame API
    (function () {
        var tag = document.createElement('script');
        tag.src = "//www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }());

    // Youtube callback when API is ready
    $window.onYouTubeIframeAPIReady = function () {
        $rootScope.$apply(function () {
            service.ready = true;
        });
    };

    return service;
}])
.directive('youtubeVideo', ['$youtube', function ($youtube) {
    return {
        restrict: 'EA',
        scope: {
            videoId: '=',
            videoUrl: '=',
            playerVars: '=',
            playerHeight: '=',
            playerWidth: '='
        },
        link: function (scope, element, attrs) {
            // Attach to element
            $youtube.playerId = element[0].id;
            $youtube.playerHeight = scope.playerHeight || 390;
            $youtube.playerWidth = scope.playerWidth || 640;

            var stopWatchingReady = scope.$watch(
                function () {
                    return $youtube.ready
                        // Wait until one of them is defined...
                        && (typeof scope.videoUrl !== 'undefined'
                        ||  typeof scope.videoId !== 'undefined');
                },
                function (ready) {
                    if (ready) {
                        stopWatchingReady();

                        // use URL if you've got it
                        if (typeof scope.videoUrl !== 'undefined') {
                            scope.$watch('videoUrl', function (url) {
                                $youtube.setURL(url);
                                $youtube.loadPlayer(scope.playerVars);
                            });

                        // otherwise, watch the id
                        } else {
                            scope.$watch('videoId', function (id) {
                                $youtube.videoId = id;
                                $youtube.loadPlayer(scope.playerVars);
                            });
                        }
                    }
            });
        }
    };
}]);
<|endoftext|>


<commit_before>const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const merge = require('lodash/merge');

const defaultOptions = {
  logo: './src/favicon.png',
  emitStats: true,
  statsFilename: '.iconstats.json',
  persistentCache: true,
  inject: false,

  appName: null,
  appDescription: null,
  developerName: null,
  developerURL: null,
  dir: 'auto',
  lang: 'en-US',
  background: '#fff',
  theme_color: '#fff',
  display: 'standalone',
  orientation: 'any',
  start_url: '/?homescreen=1',
  version: '1.0',

  icons: {
    android: true,
    appleIcon: true,
    appleStartup: true,
    coast: false,
    favicons: true,
    firefox: true,
    opengraph: false,
    twitter: false,
    yandex: false,
    windows: false,
  },
};

function isHtmlStage(stage) {
  return stage === 'develop-html' || stage === 'build-html';
}

function getOptions(options) {
  let finalOptions = {};
  merge(finalOptions, defaultOptions, options);
  return finalOptions;
}

// Gatsby v1
module.exports.modifyWebpackConfig = ({ config, stage }, options) => {
  if (isHtmlStage(stage)) {
    config.plugin(`Favicon`, FaviconsWebpackPlugin, [getOptions(options)]):
  }
};

// Gatsby v2
module.exports.onCreateWebpackConfig = ({ actions, stage }, options) => {
  if (isHtmlStage(stage)) {
    actions.setWebpackConfig({
      plugins: [
        new FaviconsWebpackPlugin(getOptions(options)),
      ],
    });
  }
};
<commit_msg>Fixes syntax error<commit_after>const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const merge = require('lodash/merge');

const defaultOptions = {
  logo: './src/favicon.png',
  emitStats: true,
  statsFilename: '.iconstats.json',
  persistentCache: true,
  inject: false,

  appName: null,
  appDescription: null,
  developerName: null,
  developerURL: null,
  dir: 'auto',
  lang: 'en-US',
  background: '#fff',
  theme_color: '#fff',
  display: 'standalone',
  orientation: 'any',
  start_url: '/?homescreen=1',
  version: '1.0',

  icons: {
    android: true,
    appleIcon: true,
    appleStartup: true,
    coast: false,
    favicons: true,
    firefox: true,
    opengraph: false,
    twitter: false,
    yandex: false,
    windows: false,
  },
};

function isHtmlStage(stage) {
  return stage === 'develop-html' || stage === 'build-html';
}

function getOptions(options) {
  let finalOptions = {};
  merge(finalOptions, defaultOptions, options);
  return finalOptions;
}

// Gatsby v1
module.exports.modifyWebpackConfig = ({ config, stage }, options) => {
  if (isHtmlStage(stage)) {
    config.plugin(`Favicon`, FaviconsWebpackPlugin, [getOptions(options)]);
  }
};

// Gatsby v2
module.exports.onCreateWebpackConfig = ({ actions, stage }, options) => {
  if (isHtmlStage(stage)) {
    actions.setWebpackConfig({
      plugins: [
        new FaviconsWebpackPlugin(getOptions(options)),
      ],
    });
  }
};
<|endoftext|>