<commit_before>define(['logger', 'voc', 'underscore' ], function(Logger, Voc, _){
    return {
        init : function(vie) {
            this.LOG.debug("initialize TimelineModel");
            this.vie = vie;
            this.vie.entities.on('add', this.filter, this);
        },
        LOG : Logger.get('TimelineModel'),
        /**
         * Filters entities from added entities to vie.entities
         */
        filter: function(model, collection, options) {
            if( this.vie.namespaces.curie(model.get('@type').id) === Voc.TIMELINE ) {
                if( !model.isNew()) {
                    this.fetchRange(model);
                }
                var tl = this;
                model.on('change:' + this.vie.namespaces.uri(Voc.start) + ' ' +
                         'change:' + this.vie.namespaces.uri(Voc.end),
                    function(model, value, options){
                        /* TODO performance issue:
                           this will be triggered twice because on rangechange of
                           the timeline, start and end are changed at the same time
                           */
                        tl.fetchRange(model);
                    }
                );
            }
        },
        fetchRange: function( timeline, start, end ) {
            this.LOG.debug("fetchRange:" + start + ";" + end);
            if( !start ) start = new Date(timeline.get(Voc.start));
            if( !end ) end = new Date(timeline.get(Voc.end));
            var range = end - start;
            // Fetch entities currently visible
            var forUser = timeline.get(Voc.belongsToUser);
            if( forUser.isEntity ) forUser = forUser.getSubject();
            var that = this;
            this.vie.load({
                'type' : timeline.get('predicate'), //TODO check that property
                'start' : start - range,
                'end' : end -0 + range,
                'forUser' : forUser
            }).from('sss').execute().success(
                function(entities) {
                    that.LOG.debug('success fetchRange: ', _.clone(entities), 'timeline: ', timeline);
                    that.LOG.debug('in entities', _.clone(that.vie.entities.get(entities[0]['@subject'])));
                    entities = that.vie.entities.addOrUpdate(entities, {'overrideAttributes': true});
                    that.LOG.debug('entities', _.clone(entities));
                    var current = timeline.get(Voc.hasEntity) || [];
                    if( !_.isArray(current)) current = [current];
                    var added = _.difference(entities, current);
                    added = added.map(function(e){
                        var resource = e.get(Voc.hasResource);
                        if( !resource.isEntity ) {
                            var newEntity = new that.vie.Entity;
                            newEntity.set(newEntity.idAttribute, resource );
                            that.vie.entities.addOrUpdate(newEntity);
                            newEntity.fetch();
                        }
                        return e.getSubject();
                    });
                    current = current.map(function(c){
                        return c.getSubject();
                    });
                    current = _.union(current, added);
                    that.LOG.debug('current', current);
                    timeline.set(Voc.hasEntity, current);
                }
            );
        },
        copy: function(timeline) {
            var newAttr = _.clone(timeline.attributes);
            delete newAttr[timeline.idAttribute];
            var newTimeline = new this.vie.Entity(newAttr);
            this.vie.entities.addOrUpdate(newTimeline);
            return newTimeline;
        }

    };
});
<commit_msg>removed log messages<commit_after>define(['logger', 'voc', 'underscore' ], function(Logger, Voc, _){
    return {
        init : function(vie) {
            this.LOG.debug("initialize TimelineModel");
            this.vie = vie;
            this.vie.entities.on('add', this.filter, this);
        },
        LOG : Logger.get('TimelineModel'),
        /**
         * Filters entities from added entities to vie.entities
         */
        filter: function(model, collection, options) {
            if( this.vie.namespaces.curie(model.get('@type').id) === Voc.TIMELINE ) {
                if( !model.isNew()) {
                    this.fetchRange(model);
                }
                var tl = this;
                model.on('change:' + this.vie.namespaces.uri(Voc.start) + ' ' +
                         'change:' + this.vie.namespaces.uri(Voc.end),
                    function(model, value, options){
                        /* TODO performance issue:
                           this will be triggered twice because on rangechange of
                           the timeline, start and end are changed at the same time
                           */
                        tl.fetchRange(model);
                    }
                );
            }
        },
        fetchRange: function( timeline, start, end ) {
            this.LOG.debug("fetchRange:" + start + ";" + end);
            if( !start ) start = new Date(timeline.get(Voc.start));
            if( !end ) end = new Date(timeline.get(Voc.end));
            var range = end - start;
            // Fetch entities currently visible
            var forUser = timeline.get(Voc.belongsToUser);
            if( forUser.isEntity ) forUser = forUser.getSubject();
            var that = this;
            this.vie.load({
                'type' : timeline.get('predicate'), //TODO check that property
                'start' : start - range,
                'end' : end -0 + range,
                'forUser' : forUser
            }).from('sss').execute().success(
                function(entities) {
                    that.LOG.debug('success fetchRange: ', _.clone(entities), 'timeline: ', timeline);
                    entities = that.vie.entities.addOrUpdate(entities, {'overrideAttributes': true});
                    var current = timeline.get(Voc.hasEntity) || [];
                    if( !_.isArray(current)) current = [current];
                    var added = _.difference(entities, current);
                    added = added.map(function(e){
                        var resource = e.get(Voc.hasResource);
                        if( !resource.isEntity ) {
                            var newEntity = new that.vie.Entity;
                            newEntity.set(newEntity.idAttribute, resource );
                            that.vie.entities.addOrUpdate(newEntity);
                            newEntity.fetch();
                        }
                        return e.getSubject();
                    });
                    current = current.map(function(c){
                        return c.getSubject();
                    });
                    current = _.union(current, added);
                    that.LOG.debug('current', current);
                    timeline.set(Voc.hasEntity, current);
                }
            );
        },
        copy: function(timeline) {
            var newAttr = _.clone(timeline.attributes);
            delete newAttr[timeline.idAttribute];
            var newTimeline = new this.vie.Entity(newAttr);
            this.vie.entities.addOrUpdate(newTimeline);
            return newTimeline;
        }

    };
});
<|endoftext|>


<commit_before>var workQueue = [];

function pageViewModel(gvm) {
    var self = this;

    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastIdFromDb = -1;
    gvm.lastId = -1;
    gvm.totalDocumentPercentage = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.totalDocumentPercentage = data[0].document;
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.getDocuments = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/documents', function(data) {
            data.forEach(function(entry) {
                gvm.addDocument(new Document(entry.id,entry.description,entry.amount_required,entry.weight,entry.locked));
            })
        });
    };

    gvm.addDocument = function(document) {
        gvm.documents.push(document)
    };

    gvm.removeDocument = function(document) {
        gvm.documents.remove(document);
    };

    gvm.saveDocuments = function() {
        $.ajax({
            type: "POST",
            url: "/api/project/" + gvm.projectId +  "/documenttype/add",
            data: ko.toJSON(gvm.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved documents to server");
                gvm.getDocuments();
            }
        });
    }

}

function Document(id,description,amount_required,weight,locked)
{
    return {
        id: ko.observable(id || 0),
        description: ko.observable(description || ""),
        amount_required: ko.observable(amount_required || ""),
        weight: ko.observable(weight || ""),
        locked: ko.observable(locked || false),

        removeThis: function() {
            viewModel.removeDocument(this);
        },

        toggleLock: function(data,event) {
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
            }
            this.locked = !this.locked;
        }
    }
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocuments();
}<commit_msg>Grade Documents<commit_after>var workQueue = [];

function pageViewModel(gvm) {
    var self = this;

    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastIdFromDb = -1;
    gvm.lastId = -1;
    gvm.totalDocumentPercentage = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.totalDocumentPercentage = data[0].document;
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.getDocuments = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/documents', function(data) {
            data.forEach(function(entry) {
                gvm.addDocument(new Document(entry.id,entry.description,entry.amount_required,entry.weight,entry.locked));
            })
        });
    };

    gvm.addDocument = function(document) {
        gvm.documents.push(document)
    };

    gvm.removeDocument = function(document) {
        gvm.documents.remove(document);
    };

    gvm.saveDocuments = function() {
        $.ajax({
            type: "POST",
            url: "/api/project/" + gvm.projectId +  "/documenttype/add",
            data: gvm.documents,
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved documents to server");
                gvm.getDocuments();
            }
        });
    }

}

function Document(id,description,amount_required,weight,locked)
{
    return {
        id: ko.observable(id || 0),
        description: ko.observable(description || ""),
        amount_required: ko.observable(amount_required || ""),
        weight: ko.observable(weight || ""),
        locked: ko.observable(locked || false),

        removeThis: function() {
            viewModel.removeDocument(this);
        },

        toggleLock: function(data,event) {
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
            }
            this.locked = !this.locked;
        }
    }
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocuments();
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        })
    }

    gvm.addDocumentToSubmit = function() {
        gvm.addDocument(-1, "Descrion", 1, 1);
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id != -1) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            })
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {

    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<commit_msg>completeness page<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.lastId = -1;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectCompletenessTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectCompletenessTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.documents = ko.observableArray([]);

    gvm.addDocument = function(id, description, amount_required, weight) {
        var document = {id: id, description: description, amount_required: amount_required, weight: weight};
        gvm.documents.push(document);

        $('#removebtn-' + id).bind('click', function(event, data) {
            gvm.removeDocument(id, document);
            event.stopPropagation();
        })
    }

    gvm.addDocumentToSubmit = function() {
        ++gvm.lastId;
        gvm.addDocument(gvm.lastId, "", "", "");
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(item.id, item.description, item.amount_required, item.weight);
                gvm.lastId = item.id;
            });
        });
    };

    gvm.removeDocument = function(id, document) {
        if(id != -1) {
            $.ajax({
                url: "/api/delete/document/" + id,
                type: "DELETE",
                success: function() {
                    gvm.documents.remove(document);
                }
            })
        } else {
            gvm.documents.remove(document);
        }
    };

    gvm.saveDocumentsToSubmit = function() {

    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getDocumentsToSubmit();
}<|endoftext|>


<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Allow the creation of filters for queries
 */
var Filters = Backbone.View.extend({

    events: {
        'click .add_filter': 'add_filter',
        'click  a.save' : 'save_filter',
        'click a.refresh_filters' : 'render_menu',
        'click .filter' : 'click_filter',
        'click .delete' : 'delete_filter'
    },

    filter_css: {
        'color': '#555',
        'margin-right': '5px',
        'text-decoration': 'none',
        'border': '1px solid #ccc',
        'padding': '5px',
        '-moz-border-radius': '3px',
        '-webkit-border-radius': '3px'
    },

    filters: [],
    currentFilter: null,

     filters_template: function() {
            var self = this;
            var t = "

"
                + "

"
                + "

"
                + "

"
                ;
            _.each(this.filters, function(filter) {
              t += self.filter_template(filter);
            });
            t += "
";
            return t;
    },

    filter_template: function(filter) {
          var title = "" + filter.name + ": \n "
                + "dimension:" + filter.dimension.caption + " \n(";
          var first = true;

        _.each(filter.members, function(member) {
            if (!first) {
                title += "\n, ";
            }
            first = false;
            title += member.caption;
        });
        title += ")";

          return "
" + filter.name + " (" + filter.members.length + ")
"
          + "
x
";
    },

    initialize: function(args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("filters_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render",  "show", "buildTemplate", "render", "deactivate_add_filter",
            "add_filter", "save_filter", "click_filter", "render_menu", "post_activation");

        // Add filters button
        this.add_button();
        this.workspace.toolbar.filters = this.show;

        // Listen to adjust event and rerender filters
        //this.workspace.bind('workspace:adjust', this.render);

        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide());

    },

    add_button: function() {
        var $stats_button =
            $('')
            .css({  'background-image': "url('js/saiku/plugins/filters/tag_red.png')",
                    'background-repeat':'no-repeat',
                    'background-position':'50% 50%'
                });

        var $stats_li = $('

').append($stats_button);
        $(this.workspace.toolbar.el).find("ul").append($stats_li);
    },

    show: function(event, ui) {
        var self = this;
        $(this.el).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.render_menu();
        } else {
            this.workspace.query.action.del("/filter", {
                            success: this.workspace.query.run,
                            data: this.currentFilter
            });
        }

    },

    render_menu: function() {
            this.repo = new FilterRepository({
                query: this.workspace.query.get('name')
            }).fetch({success: this.buildTemplate, data: { query : this.workspace.query.id }});

    },

    buildTemplate: function(model,response) {
        this.filters = response;
        this.render();
    },

    render: function() {
        /*
        if (! $(this.workspace.toolbar.el).find('.filters').hasClass('on')) {
            return;
        }
        */

        $(this.el).empty();

        var rendered = this.filters_template();
        var $table = $(rendered);
        $(this.el).append($table)

        if (this.currentFilter != null && this.filters.hasOwnProperty(this.currentFilter.name)) {
            //$(this.el).find('a.filter[href="#' + this.currentFilter.name + '"]').addClass('on');
            $(this.el).find('a.filter[href="#' + this.currentFilter.name + '"]').click();
        } else {
            this.currentFilter = null;
        }

    },

    deactivate_add_filter: function() {
        var self = this;
        var $addBtn = $(self.el).find('.add_filter');
        $addBtn.removeClass('on');
        $(self.el).find('.new_filter').parent().remove();
        return;
    },

    add_filter: function(event) {
        var self = this;
        var filterAction = $(event.target).attr('href').replace('#','');

        var $addBtn = $(event.target);
        if ($addBtn.hasClass('on')) {
            self.deactivate_add_filter();
            return;
        }
        $addBtn.addClass('on');
        var queryFilter = null;
        this.workspace.query.action.get("/filter", {
                            success: function(model, response) {
                                if (response != null && response.dimension != null && response.members.length > 0) {
                                    queryFilter = response;
                                } else {
                                    alert("Filter cannot be created. Dimension: " + FilterConfig.dimension + " not part of the query or no matching members found!");
                                    self.deactivate_add_filter();
                                }

                            },
                            data: {
                                dimension: FilterConfig.dimension,
                                hierarchy: FilterConfig.hierarchy,
                                level: FilterConfig.level
                            },
                            async: false
        });
        if (queryFilter != null) {
            this.currentFilter = queryFilter;
            $("
<input id='new_filter' type='text' class='new_filter'/>(" + queryFilter.members.length + ")
"
                + "

")
                                .insertAfter($(self.el).find('.filter_items .add_filter').parent());

        }

        $(self.workspace.el).find(".query_scenario, .drillthrough, .drillthrough_export").removeClass('on');
    },

    save_filter: function() {
        var self = this;
        var filtername = $(self.el).find('#new_filter').val();
        this.currentFilter.name = filtername;

        var savefilter = function(response, model) {
            self.filters[filtername] = model;
            self.deactivate_add_filter();
                $filter = $(self.filter_template(model))
                            .appendTo($(self.el).find('.filter_items ul'));
        };

// FILTER STUFF
        (new SaikuFilter({
            filtername: self.currentFilter.name,
            filter: JSON.stringify(self.currentFilter),
            queryname: self.workspace.query.id
        })).save({}, {
            success: savefilter
        });

    },

    click_filter: function(event) {
        var filterName = $(event.target).attr('href').replace('#','');
        this.currentFilter = this.filters.hasOwnProperty(filterName) ? this.filters[filterName] : null;
        var self = this;
        if ($(event.target).hasClass('on')) {
            $(event.target).removeClass('on');
            this.workspace.query.action.del("/filter", {
                            success: this.post_activation
            });
        } else {
            $(event.target).addClass('on');

            _.each(this.filters, function(filter) {
                if (filter.name == filterName) {
                    self.workspace.query.action.put("/filter", {
                          success: self.post_activation, data: {filter:JSON.stringify(filter)}});
                }
            });
        }
        $(event.target).parent().siblings().find('.on').removeClass('on');
    },

    post_activation: function(response, model) {
        var query = response.hasOwnProperty('uniqueName') ? response : model;
        this.workspace.query.parse(query);
        this.workspace.sync_query();
        this.workspace.query.run();
    },

    delete_filter: function(event) {
        var filtername = $(event.target).attr('href').replace('#','');
        var self = this;

        (new SaikuFilter({
            filtername: filtername,
            id: 'dummy'
        },{})).destroy({
            data: {filtername : filtername}
        });

        $(event.target).parent().prev().remove();
        $(event.target).parent().remove();
    }
});

/**
 * Start Plugin
 */
 Saiku.events.bind('session:new', function(session) {

        function new_workspace(args) {
            // Add stats element
            if (typeof args.workspace.filters == "undefined") {
                args.workspace.filters = new Filters({ workspace: args.workspace });
                args.workspace.bind('query:result', args.workspace.filters.deactivate_add_filter);
            }
        }

        function clear_workspace(args) {
                    if (typeof args.workspace.filters != "undefined") {
                        $(args.workspace.filters.el).hide();

                    }
        }

        // Attach stats to existing tabs
        for(var i = 0; i < Saiku.tabs._tabs.length; i++) {
            var tab = Saiku.tabs._tabs[i];
            new_workspace({
                workspace: tab.content
            });
        };

        // Attach stats to future tabs
        Saiku.session.bind("workspace:new", new_workspace);
        Saiku.session.bind("workspace:clear", clear_workspace);
    });

var SaikuFilter = Backbone.Model.extend({
    filtername: null,

    initialize: function(args, options) {
        _.extend(this.attributes, args);
        if (options != null && options.success) {
            this.parse = options.success;
        }

    },

    url: function() {
        return encodeURI(Saiku.session.username + "/filters/" + encodeURIComponent(this.get('filtername')));
    }
});

/**
 * Repository adapter
 */
var FilterRepository = Backbone.Collection.extend({
    model: SaikuFilter,

    initialize: function(args, options) {},

    url: function() {
        return encodeURI(Saiku.session.username + "/filters/");
    }
});

<commit_msg>edit and update filters<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Allow the creation of filters for queries
 */
var Filters = Backbone.View.extend({

    events: {
        'click .add_filter': 'add_filter',
        'click .edit_filter': 'add_filter',
        'click  a.save' : 'save_filter',
        'click a.refresh_filters' : 'render_menu',
        'click .filter' : 'click_filter',
        'click .delete' : 'delete_filter'
    },

    filter_css: {
        'color': '#555',
        'margin-right': '5px',
        'text-decoration': 'none',
        'border': '1px solid #ccc',
        'padding': '5px',
        '-moz-border-radius': '3px',
        '-webkit-border-radius': '3px'
    },

    filters: [],
    currentFilter: null,

     filters_template: function() {
            var self = this;
            var t = "

"
                + "

"
                + "

"
                + "

"
                ;
            _.each(this.filters, function(filter) {
              t += self.filter_template(filter);
            });
            t += "
";
            return t;
    },

    filter_template: function(filter) {
          var title = "" + filter.name + ": \n "
                + "dimension:" + filter.dimension.caption + " \n(";
          var first = true;

        _.each(filter.members, function(member) {
            if (!first) {
                title += "\n, ";
            }
            first = false;
            title += member.caption;
        });
        title += ")";

          return "
" + filter.name + " (" + filter.members.length + ")
"
          + "
x
";
    },

    initialize: function(args) {
        this.workspace = args.workspace;

        // Create a unique ID for use as the CSS selector
        this.id = _.uniqueId("filters_");
        $(this.el).attr({ id: this.id });

        // Bind table rendering to query result event
        _.bindAll(this, "render",  "show", "buildTemplate", "render", "deactivate_add_filter",
            "add_filter", "save_filter", "click_filter", "render_menu", "post_activation");

        // Add filters button
        this.add_button();
        this.workspace.toolbar.filters = this.show;

        // Listen to adjust event and rerender filters
        //this.workspace.bind('workspace:adjust', this.render);

        $(this.workspace.el).find('.workspace_results')
            .prepend($(this.el).hide());

    },

    add_button: function() {
        var $stats_button =
            $('')
            .css({  'background-image': "url('js/saiku/plugins/filters/tag_red.png')",
                    'background-repeat':'no-repeat',
                    'background-position':'50% 50%'
                });

        var $stats_li = $('

').append($stats_button);
        $(this.workspace.toolbar.el).find("ul").append($stats_li);
    },

    show: function(event, ui) {
        var self = this;
        $(this.el).toggle();
        $(event.target).toggleClass('on');

        if ($(event.target).hasClass('on')) {
            this.render_menu();
        } else {
            this.workspace.query.action.del("/filter", {
                            success: this.workspace.query.run,
                            data: this.currentFilter
            });
        }

    },

    render_menu: function() {
            this.repo = new FilterRepository({
                query: this.workspace.query.get('name')
            }).fetch({success: this.buildTemplate, data: { query : this.workspace.query.id }});

    },

    buildTemplate: function(model,response) {
        this.filters = response;
        this.render();
    },

    render: function() {
        /*
        if (! $(this.workspace.toolbar.el).find('.filters').hasClass('on')) {
            return;
        }
        */

        $(this.el).empty();

        var rendered = this.filters_template();
        var $table = $(rendered);
        $(this.el).append($table)
        this.currentFilter = null;
/*
        if (this.currentFilter != null && this.filters.hasOwnProperty(this.currentFilter.name)) {
            //$(this.el).find('a.filter[href="#' + this.currentFilter.name + '"]').addClass('on');
            $(this.el).find('a.filter[href="#' + this.currentFilter.name + '"]').click();
        } else {
            this.currentFilter = null;
        }
*/

    },

    deactivate_add_filter: function(other) {
        var self = this;
        $(self.el).find('a.add_filter, a.edit_filter').removeClass('on');
        $(self.el).find('.new_filter_input, .edit_filter_input, .new_filter').parent().remove();
        return false;
    },

    add_filter: function(event) {
        var self = this;
        var filterAction = $(event.target).attr('href').replace('#','');
        var other = filterAction == "add" ? "edit" : "add";

        this.deactivate_add_filter(other);

        var $addBtn = $(event.target);
        if ($addBtn.hasClass('on')) {
            self.deactivate_add_filter();
            return;
        }
        $addBtn.addClass('on');
        var queryFilter = null;
        this.workspace.query.action.get("/filter", {
                            success: function(model, response) {
                                if (response != null && response.dimension != null && response.members.length > 0) {
                                    queryFilter = response;
                                } else {
                                    alert("Filter cannot be created. Dimension: " + FilterConfig.dimension + " not part of the query or no matching members found!");
                                    self.deactivate_add_filter();
                                }

                            },
                            data: {
                                dimension: FilterConfig.dimension,
                                hierarchy: FilterConfig.hierarchy,
                                level: FilterConfig.level
                            },
                            async: false
        });
        if (queryFilter != null) {
            var selectedName = (this.currentFilter != null) ? this.currentFilter.name : null;

            this.currentFilter = queryFilter;

            if (filterAction == "add") {
                    $("
<input id='new_filter' type='text' class='new_filter_input'/>   (" + queryFilter.members.length + ")
"
                        + "

")
                                        .insertAfter($(self.el).find('.filter_items .add_filter').parent());

            } else {
                var edit = "
<select id='new_filter' class='edit_filter_input'>";
                _.each(self.filters, function (filter) {
                    edit += "<option value='" + safe_tags_replace(filter.name) + "'>" + safe_tags_replace(filter.name) + "</option>";
                });
                edit += "</select>   (" + queryFilter.members.length + ")
";
                $(edit + "

")
                    .insertAfter($(self.el).find('.filter_items .edit_filter').parent());

                $('#new_filter').val(selectedName);
            }
        }

        $(self.workspace.el).find(".query_scenario, .drillthrough, .drillthrough_export").removeClass('on');
    },

    save_filter: function() {
        var self = this;
        var filtername = $(self.el).find('#new_filter').val();
        this.currentFilter.name = filtername;

        var savefilter = function(response, model) {
            self.filters[filtername] = model;
            self.deactivate_add_filter();
            self.render();
        };

// FILTER STUFF
        (new SaikuFilter({
            filtername: self.currentFilter.name,
            filter: JSON.stringify(self.currentFilter),
            queryname: self.workspace.query.id
        })).save({}, {
            success: savefilter
        });

    },

    click_filter: function(event) {
        var filterName = $(event.target).attr('href').replace('#','');
        this.currentFilter = this.filters.hasOwnProperty(filterName) ? this.filters[filterName] : null;
        var self = this;
        if ($(event.target).hasClass('on')) {
            $(event.target).removeClass('on');
            this.workspace.query.action.del("/filter", {
                            success: this.post_activation
            });
        } else {
            $(event.target).addClass('on');

            _.each(this.filters, function(filter) {
                if (filter.name == filterName) {
                    self.workspace.query.action.put("/filter", {
                          success: self.post_activation, data: {filter:JSON.stringify(filter)}});
                }
            });
        }
        $(event.target).parent().siblings().find('.on').removeClass('on');
    },

    post_activation: function(response, model) {
        var query = response.hasOwnProperty('uniqueName') ? response : model;
        this.workspace.query.parse(query);
        this.workspace.sync_query();
        this.workspace.query.run();
    },

    delete_filter: function(event) {
        var filtername = $(event.target).attr('href').replace('#','');
        var self = this;

        (new SaikuFilter({
            filtername: filtername,
            id: _.uniqueId("filter_");
        },{})).destroy({
            data: {filtername : filtername}
        });

        $(event.target).parent().prev().remove();
        $(event.target).parent().remove();
    }
});

/**
 * Start Plugin
 */
 Saiku.events.bind('session:new', function(session) {

        function new_workspace(args) {
            // Add stats element
            if (typeof args.workspace.filters == "undefined") {
                args.workspace.filters = new Filters({ workspace: args.workspace });
                args.workspace.bind('query:result', args.workspace.filters.deactivate_add_filter);
            }
        }

        function clear_workspace(args) {
                    if (typeof args.workspace.filters != "undefined") {
                        $(args.workspace.filters.el).hide();

                    }
        }

        // Attach stats to existing tabs
        for(var i = 0; i < Saiku.tabs._tabs.length; i++) {
            var tab = Saiku.tabs._tabs[i];
            new_workspace({
                workspace: tab.content
            });
        };

        // Attach stats to future tabs
        Saiku.session.bind("workspace:new", new_workspace);
        Saiku.session.bind("workspace:clear", clear_workspace);
    });

var SaikuFilter = Backbone.Model.extend({
    filtername: null,

    initialize: function(args, options) {
        _.extend(this.attributes, args);
        if (options != null && options.success) {
            this.parse = options.success;
        }

    },

    url: function() {
        return encodeURI(Saiku.session.username + "/filters/" + this.get('filtername'));
    }
});

/**
 * Repository adapter
 */
var FilterRepository = Backbone.Collection.extend({
    model: SaikuFilter,

    initialize: function(args, options) {},

    url: function() {
        return encodeURI(Saiku.session.username + "/filters/");
    }
});

<|endoftext|>


<commit_before>CRM.$(function ($) {

  CRM.SecureFilesWidget.formComplete = false;

  function uploadFileWithPromise(file, key, field) {

    var dfd = $.Deferred();

    var params = {
      Key: key,
      ContentType: file.type,
      Body: file
      //todo: Add server-side Encryption Settings
    };

    if(CRM.SecureFilesWidget.useEncryption) {
      params.ServerSideEncryption = CRM.SecureFilesWidget.encryptionType;
    }

    CRM.SecureFilesWidget.Bucket.putObject(params, function (err, data) {
      if (err) {
        dfd.reject(err);
      } else {
        //Unset the file
        $(field).val("");

        //Resolve this promise
        dfd.resolve({"field": $(field).attr("name"), "name": key, "mime-type": file.type, "data": data});
      }
    });

    return dfd.promise();
  }

  $(".securefiles_upload").closest("form").submit(function(event) {
    var formObj = $(this);
    if(!CRM.SecureFilesWidget.formComplete) {
      event.preventDefault();
      if (CRM.SecureFilesWidget.useSTS) {
        //Upload the file using the JavaScript SDK
        CRM.SecureFilesWidget.promises = [];
        $(this).find(".securefiles_upload").each(function () {

          var i = 0;
          if(this.files[i]) {
            //Looks like we have something to upload
            var file = this.files[i];
            var fileTitle = CRM.SecureFilesWidget.S3Fields[$(this).attr("name")].filename || this.files[i].name;
            var objKey = CRM.SecureFilesWidget.currentContactId + '/' + fileTitle;

            CRM.SecureFilesWidget.promises.push(uploadFileWithPromise(this.files[i], objKey, this));

          }
        });

        $.when.apply($, CRM.SecureFilesWidget.promises).done(function(data) {
          CRM.SecureFilesWidget.formComplete = true;
          formObj.find(".securefiles-metadata").val(JSON.stringify(data));
          //Todo: Clear the file field so it doesn't attempt to upload
          formObj.submit();
        }).fail(function(err) {
          console.log(err);
        });

      }
    }
  });

  //Setup Creds for S3 if we need them.
  if(CRM.SecureFilesWidget.useSTS) {

    AWS.config.update({
      accessKeyId: CRM.SecureFilesWidget.Credentials.AccessKeyId,
      secretAccessKey: CRM.SecureFilesWidget.Credentials.SecretAccessKey,
      sessionToken: CRM.SecureFilesWidget.Credentials.SessionToken
    });

    AWS.config.region = CRM.SecureFilesWidget.S3Region;

    //This tells the js sdk to log debugging symbols to the console
    //AWS.config.logger = console;

    CRM.SecureFilesWidget.Bucket = new AWS.S3({
      params: {
        Bucket: CRM.SecureFilesWidget.S3Bucket
      }
    });
  }

});<commit_msg>Added server side encryption<commit_after>CRM.$(function ($) {

  CRM.SecureFilesWidget.formComplete = false;

  function uploadFileWithPromise(file, key, field) {

    var dfd = $.Deferred();

    var params = {
      Key: key,
      ContentType: file.type,
      Body: file
    };

    //server-side Encryption Settings
    if(CRM.SecureFilesWidget.useEncryption) {
      params.ServerSideEncryption = CRM.SecureFilesWidget.encryptionType;
    }

    CRM.SecureFilesWidget.Bucket.putObject(params, function (err, data) {
      if (err) {
        dfd.reject(err);
      } else {
        //Unset the file
        $(field).val("");

        //Resolve this promise
        dfd.resolve({"field": $(field).attr("name"), "name": key, "mime-type": file.type, "data": data});
      }
    });

    return dfd.promise();
  }

  $(".securefiles_upload").closest("form").submit(function(event) {
    var formObj = $(this);
    if(!CRM.SecureFilesWidget.formComplete) {
      event.preventDefault();
      if (CRM.SecureFilesWidget.useSTS) {
        //Upload the file using the JavaScript SDK
        CRM.SecureFilesWidget.promises = [];
        $(this).find(".securefiles_upload").each(function () {

          var i = 0;
          if(this.files[i]) {
            //Looks like we have something to upload
            var file = this.files[i];
            var fileTitle = CRM.SecureFilesWidget.S3Fields[$(this).attr("name")].filename || this.files[i].name;
            var objKey = CRM.SecureFilesWidget.currentContactId + '/' + fileTitle;

            CRM.SecureFilesWidget.promises.push(uploadFileWithPromise(this.files[i], objKey, this));

          }
        });

        $.when.apply($, CRM.SecureFilesWidget.promises).done(function(data) {
          CRM.SecureFilesWidget.formComplete = true;
          formObj.find(".securefiles-metadata").val(JSON.stringify(data));
          //Todo: Clear the file field so it doesn't attempt to upload
          formObj.submit();
        }).fail(function(err) {
          console.log(err);
        });

      }
    }
  });

  //Setup Creds for S3 if we need them.
  if(CRM.SecureFilesWidget.useSTS) {

    AWS.config.update({
      accessKeyId: CRM.SecureFilesWidget.Credentials.AccessKeyId,
      secretAccessKey: CRM.SecureFilesWidget.Credentials.SecretAccessKey,
      sessionToken: CRM.SecureFilesWidget.Credentials.SessionToken
    });

    AWS.config.region = CRM.SecureFilesWidget.S3Region;

    //This tells the js sdk to log debugging symbols to the console
    //AWS.config.logger = console;

    CRM.SecureFilesWidget.Bucket = new AWS.S3({
      params: {
        Bucket: CRM.SecureFilesWidget.S3Bucket
      }
    });
  }

});<|endoftext|>


<commit_before>define(
'services/booleanSearchEngine',
[
  'underscore',
  'bookmarksApp'
],
function(_, bookmarksApp) { "use strict";

/*
* Boolean search engine.
*/
var BooleanSearchEngine = function () {

	var andExpression = 'and';
    var patterns = ['tag:', 'url:', 'title:'];
	var bookmarks = {};

	// Compress some whitespaces to one. Defaults to whitespace characters.
	var clean = function(input, characters){
		if (!angular.isString(input)) return input;

        if (!characters) characters = '\\s';

        return String(input).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
    };

	// Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
    var trim = function(input, characters){
    	if (!angular.isString(input)) return input;

        if (!characters) characters = '\\s';

        return String(input).replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
    };

    // Checks if string is blank or not.
    var isBlank = function(str){
        if (str == null) str = '';
        return (/^\s*$/).test(str);
    };

    // Splits input string by words. Defaults to whitespace characters.
    var words = function(str, delimiter) {
        if (isBlank(str)) return [];
        return trim(str, delimiter).split(delimiter || /\s+/);
    };

    var evaluateExpression = function(bookmark, searchText){

        var pattern  = _.find(patterns, function(item){ return searchText.indexOf(item) == 0; });

        if(!pattern){
            var filteredValue = _.find(_.values(bookmark), function(propertyValue){
                return propertyValue.toString().indexOf(trim(searchText)) != -1;
            });
            return !_.isUndefined(filteredValue);
        }
        else{
            var patternText = trim(searchText.substring(pattern.length));
            var tag = _.find(bookmark.tag, function(item){
                return item.text.indexOf(patternText) != -1;
            });

            return !_.isUndefined(tag);
        }
    };

	this.filterBookmark = function(bookmark, searchText){
		// var search = searchText;
		var search = 'tag:  prog  and Algo';
		if(!search) return true;

		var searchWords = words(search, andExpression);
        var failureWord = _.find(searchWords, function(word){
            return !evaluateExpression(bookmark, word);
        });

        return _.isUndefined(failureWord);
	};
};

/*
* Boolean search engine factory method.
*/
var BooleanSearchEngineFactory = function() {
  return new BooleanSearchEngine();
};

bookmarksApp.factory('booleanSearchEngine', BooleanSearchEngineFactory);

});<commit_msg>code clean up<commit_after>define(
'services/booleanSearchEngine',
[
  'underscore',
  'bookmarksApp'
],
function(_, bookmarksApp) { "use strict";

/*
* Boolean search engine.
*/
var BooleanSearchEngine = function () {

	var andExpression = 'and';
    var patterns = ['tag:', 'url:', 'title:'];
	var bookmarks = {};

	// Compress some whitespaces to one. Defaults to whitespace characters.
	var clean = function(input, characters){
		if (!angular.isString(input)) return input;

        if (!characters) characters = '\\s';

        return String(input).replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), '');
    };

	// Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
    var trim = function(input, characters){
    	if (!angular.isString(input)) return input;

        if (!characters) characters = '\\s';

        return String(input).replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
    };

    // Checks if string is blank or not.
    var isBlank = function(str){
        if (str == null) str = '';
        return (/^\s*$/).test(str);
    };

    // Splits input string by words. Defaults to whitespace characters.
    var words = function(str, delimiter) {
        if (isBlank(str)) return [];
        return trim(str, delimiter).split(delimiter || /\s+/);
    };

    var evaluateExpression = function(bookmark, searchText){

        var pattern  = _.find(patterns, function(item){ return searchText.indexOf(item) == 0; });

        if(!pattern){
            var filteredValue = _.find(_.values(bookmark), function(propertyValue){
                return propertyValue.toString().indexOf(trim(searchText)) != -1;
            });
            return !_.isUndefined(filteredValue);
        }
        else{
            var patternText = trim(searchText.substring(pattern.length));
            var tag = _.find(bookmark.tag, function(item){
                return item.text.indexOf(patternText) != -1;
            });

            return !_.isUndefined(tag);
        }
    };

	this.filterBookmark = function(bookmark, searchText){
		// var search = searchText;
		var search = 'tag:  prog  and Algo';
		if(!search) return true;

        search.indexOf()
		var searchWords = words(search, andExpression);
        var failureWord = _.find(searchWords, function(word){
            return !evaluateExpression(bookmark, word);
        });

        return _.isUndefined(failureWord);
	};
};

/*
* Boolean search engine factory method.
*/
var BooleanSearchEngineFactory = function() {
    return new BooleanSearchEngine();
};

bookmarksApp.factory('booleanSearchEngine', BooleanSearchEngineFactory);

});<|endoftext|>


<commit_before>

/**
selection population upload from lists
and files. Run prediction model on uploaded selection population
and display output.

Isaak Y Tecle
iyt2@cornell.edu
*/

JSAN.use("jquery.cookie");
JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");

jQuery(document).ready( function() {
        var list = new CXGN.List();
        var listMenu = list.listSelect("prediction_genotypes");

        jQuery("#prediction_genotypes_list").append(listMenu);

    });

jQuery(document).ready( function() {
        var listId;
        jQuery("#prediction_genotypes_list_select").change(function() {

                listId = jQuery(this).find("option:selected").val();

                if(listId) {
                    jQuery("#prediction_genotypes_list_upload").click(function() {
                            //alert('get list: ' + listId);
                            loadGenotypesList(listId);
                        });
                }
            });
    });

function getGenotypesList(listId) {

    var list = new CXGN.List();
    var genotypesList;

    if (! listId == "") {
        genotypesList = list.getList(listId);
    }

    var listName = list.listNameById(listId);

    return {'name'   : listName,
            'list'   : genotypesList
            };
}

function loadGenotypesList(listId) {

    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( list.length === 0) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {

        jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
        jQuery.blockUI({message: 'Please wait..'});

        list = JSON.stringify(list);

        jQuery.ajax({
                type: 'POST',
                    dataType: 'json',
                    data: {id: listId, 'name': listName, 'list': list},
                    url: '/solgs/upload/prediction/genotypes/list',

                    success: function(response) {

                    if (response.status == 'success') {

                        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

                        if (uploadedSelPops == false) {

                            uploadedSelPops = getUserUploadedSelPop(listId);
                            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();

                        }
                        else {

                            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
                            var listIdArg = '\'' + listId +'\'';
                            var listSource = '\'from_db\'';

                            var popIdName   = {id : 'uploaded_' + listId, name: listName,};
                            popIdName       = JSON.stringify(popIdName);
                            var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

                            var addRow = '
'
                                +'' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '
';

                            var tdId = '#list_prediction_output_' + listId;
                            var addedRow = jQuery(tdId).doesExist();

                            if (addedRow == false) {
                                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);

                            }
                        }
                        jQuery.unblockUI();

                    } else {

                    alert("Error occured while uploading the list of selection genotypes.");
                    jQuery.unblockUI();
                    }

                }
            });
    }
}

jQuery.fn.doesExist = function(){
        return jQuery(this).length > 0;
 };

function getModelId () {

    var modelId;
    var modelIdExists = jQuery("#model_id").doesExist();
    var comboPopsIdExists = jQuery("#combo_pops_id").doesExist();

    if ( modelIdExists == true ) {
        modelId = jQuery("#model_id").val();
    }
    else if ( comboPopsIdExists == true ) {
        modelId = jQuery("#combo_pops_id").val();
    }

    return modelId;

}

function getTraitId () {

    var traitId;
    var traitIdExists = jQuery("#trait_id").doesExist();

    if ( traitIdExists == true ) {
        traitId = jQuery("#trait_id").val();
    }

    return traitId;

}

function getUserUploadedSelPop (listId) {
    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url         =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg   = '\'' + listId +'\'';
    var listSource  = '\'from_db\'';
    var popIdName   = {id : 'uploaded_' + listId, name: listName,};
    popIdName       = JSON.stringify(popIdName);
    var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + '' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}

function loadPredictionOutput (url, listId, listSource) {

    var traitId        = getTraitId();
    var modelId        = getModelId();

    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
    jQuery.blockUI({message: 'Please wait..'});

    jQuery.ajax({
            type: 'POST',
                url: url,
                dataType: 'json',
                data: {
                       'uploaded_prediction': 1,
                       'trait_id': traitId,
                       'model_id': modelId,
                       'prediction_id': listId,
                       'list_source': listSource,
                      },

                success: function (response) {

                if (response.status == 'success') {
                    var tdId = '#list_prediction_output_' + listId;
                    jQuery(tdId).html(response.output);

                    var popsList = listSelPopulationsUploaded();

                    jQuery("#select_a_population_div").html('');

                    selectAPopulation(modelId,  popsList);

                    jQuery.unblockUI();

                }
                else {
                    alert('Error occured calculating GEBVs for the list of selection genotypes.');
                    jQuery.unblockUI();
                }
            },
                error: function(response) {
                alert('error: ' + res.responseText);

            }
        });

}

jQuery(function () {
        var url = '/solgs/upload/prediction/genotypes/file';

        jQuery('#fileupload').fileupload({
                url: url,
                    dataType: 'json',
                    submit: function(e, data) {
                    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
                    jQuery.blockUI({message: 'Please wait..'});
                },
                    done: function (e, data) {
                    jQuery.each(data.result.files, function (index, file) {

                            getCheckValue(file.name);

                        });

                    jQuery.unblockUI();

                }
            });
    });

function getCheckValue(fileName) {

    jQuery.ajax({
            type: 'POST',
                url: '/solgs/generate/checkvalue',
                dataType: 'json',
                data: {'file_name': fileName},

                success: function (response) {

                if (response.status == 'success') {

                    var checkValue = response.check_value;
                    jQuery("#check_value").empty();
                    jQuery("#check_value").val(checkValue);

                    loadListFromFile(fileName, checkValue);

                }

            }
        });

}

function loadListFromFile(fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( ! fileName ) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {
        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

        if (uploadedSelPops == false) {

            uploadedSelPops = getUserUploadedFile(fileName, listId);
            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();
        }
        else {

            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
            var listIdArg = '\'' + listId +'\'';
            var listSource = '\'from_file \'';

            var popIdName   = {id : 'uploaded_' + listId, name: listName,};
            popIdName       = JSON.stringify(popIdName);
            var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

            var addRow = '
'
                +'' + '<data>'+ hiddenInput + '</data>'
                + listName + ''
                + '	'
                + ''
                + ''
                + '[ Predict GEBVs ]'+ ''
                + '
';

            var tdId = '#list_prediction_output_' + listId;
            var addedRow = jQuery(tdId).doesExist();

            if (addedRow == false) {
                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);
            }
        }
    }

}

function getUserUploadedFile (fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg = '\'' + listId +'\'';
    var listSource = '\'from_file \'';

    var popIdName   = {id : 'uploaded_' + listId, name: listName,};
    popIdName       = JSON.stringify(popIdName);
    var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + '' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}
<commit_msg>use getListData instead of getList<commit_after>

/**
selection population upload from lists
and files. Run prediction model on uploaded selection population
and display output.

Isaak Y Tecle
iyt2@cornell.edu
*/

JSAN.use("jquery.cookie");
JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");

jQuery(document).ready( function() {
        var list = new CXGN.List();
        var listMenu = list.listSelect("prediction_genotypes");

        jQuery("#prediction_genotypes_list").append(listMenu);

    });

jQuery(document).ready( function() {
        var listId;
        jQuery("#prediction_genotypes_list_select").change(function() {

                listId = jQuery(this).find("option:selected").val();

                if(listId) {
                    jQuery("#prediction_genotypes_list_upload").click(function() {
                            //alert('get list: ' + listId);
                            loadGenotypesList(listId);
                        });
                }
            });
    });

function getGenotypesList(listId) {

    var list = new CXGN.List();
    var genotypesList;

    if (! listId == "") {
        genotypesList = list.getListData(listId);
    }

    var listName = list.listNameById(listId);
    var listType = list.getListType(listId);

    return {'name'      : listName,
            'list'      : genotypesList.elements,
            'list_type' : listType,
            };
}

function loadGenotypesList(listId) {

    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;
    var listType       = genoList.list_type;

    alert('list type ' + listType);
    if ( list.length === 0) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {

        jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
        jQuery.blockUI({message: 'Please wait..'});

        list = JSON.stringify(list);

        jQuery.ajax({
                type: 'POST',
                    dataType: 'json',
                    data: {id: listId, 'name': listName, 'list': list},
                    url: '/solgs/upload/prediction/genotypes/list',

                    success: function(response) {

                    if (response.status == 'success') {

                        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

                        if (uploadedSelPops == false) {

                            uploadedSelPops = getUserUploadedSelPop(listId);
                            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();

                        }
                        else {

                            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
                            var listIdArg = '\'' + listId +'\'';
                            var listSource = '\'from_db\'';

                            var popIdName   = {id : 'uploaded_' + listId, name: listName,};
                            popIdName       = JSON.stringify(popIdName);
                            var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

                            var addRow = '
'
                                +'' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '
';

                            var tdId = '#list_prediction_output_' + listId;
                            var addedRow = jQuery(tdId).doesExist();

                            if (addedRow == false) {
                                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);

                            }
                        }
                        jQuery.unblockUI();

                    } else {

                        alert("Error occured while uploading the list of selection genotypes.");
                        jQuery.unblockUI();
                    }

                }
                   //  error: function(res) {
//                     alert("Error occured while uploading the list of selection genotypes.");
//                     jQuery.unblockUI();
//                 }
            });
    }
}

jQuery.fn.doesExist = function(){
        return jQuery(this).length > 0;
 };

function getModelId () {

    var modelId;
    var modelIdExists = jQuery("#model_id").doesExist();
    var comboPopsIdExists = jQuery("#combo_pops_id").doesExist();

    if ( modelIdExists == true ) {
        modelId = jQuery("#model_id").val();
    }
    else if ( comboPopsIdExists == true ) {
        modelId = jQuery("#combo_pops_id").val();
    }

    return modelId;

}

function getTraitId () {

    var traitId;
    var traitIdExists = jQuery("#trait_id").doesExist();

    if ( traitIdExists == true ) {
        traitId = jQuery("#trait_id").val();
    }

    return traitId;

}

function getUserUploadedSelPop (listId) {

    var genoList       = getGenotypesList(listId);
    var listName       = genoList.name;
    var list           = genoList.list;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url         =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg   = '\'' + listId +'\'';
    var listSource  = '\'from_db\'';
    var popIdName   = {id : 'uploaded_' + listId, name: listName,};
    popIdName       = JSON.stringify(popIdName);
    var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + '' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}

function loadPredictionOutput (url, listId, listSource) {

    var traitId        = getTraitId();
    var modelId        = getModelId();

    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
    jQuery.blockUI({message: 'Please wait..'});

    jQuery.ajax({
            type: 'POST',
                url: url,
                dataType: 'json',
                data: {
                       'uploaded_prediction': 1,
                       'trait_id': traitId,
                       'model_id': modelId,
                       'prediction_id': listId,
                       'list_source': listSource,
                      },

                success: function (response) {

                if (response.status == 'success') {
                    var tdId = '#list_prediction_output_' + listId;
                    jQuery(tdId).html(response.output);

                    var popsList = listSelPopulationsUploaded();

                    jQuery("#select_a_population_div").html('');

                    selectAPopulation(modelId,  popsList);

                    jQuery.unblockUI();

                }
                else {
                    alert('Error occured calculating GEBVs for the list of selection genotypes.');
                    jQuery.unblockUI();
                }
            },
                error: function(response) {
                alert('error: ' + res.responseText);

            }
        });

}

jQuery(function () {
        var url = '/solgs/upload/prediction/genotypes/file';

        jQuery('#fileupload').fileupload({
                url: url,
                    dataType: 'json',
                    submit: function(e, data) {
                    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
                    jQuery.blockUI({message: 'Please wait..'});
                },
                    done: function (e, data) {
                    jQuery.each(data.result.files, function (index, file) {

                            getCheckValue(file.name);

                        });

                    jQuery.unblockUI();

                }
            });
    });

function getCheckValue(fileName) {

    jQuery.ajax({
            type: 'POST',
                url: '/solgs/generate/checkvalue',
                dataType: 'json',
                data: {'file_name': fileName},

                success: function (response) {

                if (response.status == 'success') {

                    var checkValue = response.check_value;
                    jQuery("#check_value").empty();
                    jQuery("#check_value").val(checkValue);

                    loadListFromFile(fileName, checkValue);

                }

            }
        });

}

function loadListFromFile(fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    if ( ! fileName ) {
        alert('The list is empty. Please select a list with content.' );
    }
    else {
        var uploadedSelPops = jQuery("#uploaded_selection_pops_table").doesExist();

        if (uploadedSelPops == false) {

            uploadedSelPops = getUserUploadedFile(fileName, listId);
            jQuery("#uploaded_selection_populations").append(uploadedSelPops).show();
        }
        else {

            var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
            var listIdArg = '\'' + listId +'\'';
            var listSource = '\'from_file \'';

            var popIdName   = {id : 'uploaded_' + listId, name: listName,};
            popIdName       = JSON.stringify(popIdName);
            var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

            var addRow = '
'
                +'' + '<data>'+ hiddenInput + '</data>'
                + listName + ''
                + '	'
                + ''
                + ''
                + '[ Predict GEBVs ]'+ ''
                + '
';

            var tdId = '#list_prediction_output_' + listId;
            var addedRow = jQuery(tdId).doesExist();

            if (addedRow == false) {
                jQuery("#uploaded_selection_pops_table tr:last").after(addRow);
            }
        }
    }

}

function getUserUploadedFile (fileName, listId) {

    var listName       = fileName;
    var modelId        = getModelId();
    var traitId        = getTraitId();
    var selectionPopId = listId;

    var url =   '\'/solgs/model/'+ modelId + '/uploaded/prediction/'+ selectionPopId + '\'' ;
    var listIdArg = '\'' + listId +'\'';
    var listSource = '\'from_file \'';

    var popIdName   = {id : 'uploaded_' + listId, name: listName,};
    popIdName       = JSON.stringify(popIdName);
    var hiddenInput =  '<input type="hidden" value=\'' + popIdName + '\'/>';

    var uploadedSelPop ='

'
                                + 'Uploaded Selection Population	'
                                + 'Prediction output	'
                                +'
'
                                + '
'
                                + ''
                                + '' + '<data>'+ hiddenInput + '</data>'
                                + listName + ''
                                + '	'
                                + ''
                                + ''
                                + '[ Predict GEBVs ]'+ ''
                                + '

';

    return uploadedSelPop;
}
<|endoftext|>


<commit_before>import Component from '../Component';
import icon from '../helpers/icon';
import withAttr from '../utils/withAttr';
import classList from '../utils/classList';

/**
 * The `Select` component displays a <select> input, surrounded with some extra
 * elements for styling. It accepts the following attrs:
 *
 * - `options` A map of option values to labels.
 * - `onchange` A callback to run when the selected value is changed.
 * - `value` The value of the selected option.
 * - `disabled` Disabled state for the input.
 * - `wrapperAttrs` A map of attrs to be passed to the DOM element wrapping the `<select>`
 *
 * Other attributes are passed directly to the `<select>` element rendered to the DOM.
 */
export default class Select extends Component {
  view() {
    const {
      options,
      onchange,
      value,
      disabled,
      className,
      class: _class,

      // Destructure the `wrapperAttrs` object to extract the `className` for passing to `classList()`
      // `= {}` prevents errors when `wrapperAttrs` is undefined
      wrapperAttrs: { className: wrapperClassName, class: wrapperClass, ...wrapperAttrs } = {},

      ...domAttrs
    } = this.attrs;

    return (

        <select
          className={classList("Select-input FormControl", className, _class)}
          onchange={onchange ? withAttr('value', onchange.bind(this)) : undefined}
          value={value}
          disabled={disabled}
          {...domAttrs}
        >
          {Object.keys(options).map((key) => (
            <option value={key}>{options[key]}</option>
          ))}
        </select>
        {icon('fas fa-sort', { className: 'Select-caret' })}

    );
  }
}
<commit_msg>npm run format<commit_after>import Component from '../Component';
import icon from '../helpers/icon';
import withAttr from '../utils/withAttr';
import classList from '../utils/classList';

/**
 * The `Select` component displays a <select> input, surrounded with some extra
 * elements for styling. It accepts the following attrs:
 *
 * - `options` A map of option values to labels.
 * - `onchange` A callback to run when the selected value is changed.
 * - `value` The value of the selected option.
 * - `disabled` Disabled state for the input.
 * - `wrapperAttrs` A map of attrs to be passed to the DOM element wrapping the `<select>`
 *
 * Other attributes are passed directly to the `<select>` element rendered to the DOM.
 */
export default class Select extends Component {
  view() {
    const {
      options,
      onchange,
      value,
      disabled,
      className,
      class: _class,

      // Destructure the `wrapperAttrs` object to extract the `className` for passing to `classList()`
      // `= {}` prevents errors when `wrapperAttrs` is undefined
      wrapperAttrs: { className: wrapperClassName, class: wrapperClass, ...wrapperAttrs } = {},

      ...domAttrs
    } = this.attrs;

    return (

        <select
          className={classList('Select-input FormControl', className, _class)}
          onchange={onchange ? withAttr('value', onchange.bind(this)) : undefined}
          value={value}
          disabled={disabled}
          {...domAttrs}
        >
          {Object.keys(options).map((key) => (
            <option value={key}>{options[key]}</option>
          ))}
        </select>
        {icon('fas fa-sort', { className: 'Select-caret' })}

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var fs = require('fs');
var ftp = require('ftp');
var moment = require('moment');

var time = moment().format('h:mm:ss');
var newfile = 'logs/hrtrtf_'+ time + '.txt';

// fetch the latest hrtbus data
var ftp = new ftp();
ftp.on('ready', () => {
	ftp.get('Anrd/hrtrtf.txt', (err, stream) => {
		if (err) throw err;

		stream
		  .once('close',() => {ftp.end();})
		  .pipe(fs.createWriteStream(newfile));
	});
}).connect({host : '216.54.15.3'});

//read the files from the log dir
fs.readdir('logs/', (err, files) => {
	if (err) throw err;

	if (files[files.length -1] == undefined) {
		console.log("Error: No File Found");
	};

	//If only header in last sync, notify
	fs.stat('logs/' + files[files.length -1], (err,stats) => {
		//if err throw err;
		if (stats.size == 107) {
			console.log("Error: Most recent pull only returned header");
		}
	});

	//If file size hasn't for 5 consecutive  pulls, assume stale feed
	fs.readFile('logs/' + files[files.length -1],'utf8', (err, data) => {
		if (err) throw err;
		var lasttimestamp = moment(data.slice(data.length - 50,data.length -42),
															"hh:mm:ss").fromNow();
		if (lasttimestamp[0] > 10) {
			console.log("Stale Feed");
		}
	});

	// maintain a queue of 6 files
	if(files.length > 5) {
		fs.unlinkSync('logs/' + files[0]);
	};
  console.log(files);
});

<commit_msg>cleaner requirements<commit_after>'use strict';

var _ = require('lodash'),
   fs = require('fs'),
  ftp = require('ftp'),
moment = require('moment');

var time = moment().format('h:mm:ss');
var newfile = 'logs/hrtrtf_'+ time + '.txt';

// fetch the latest hrtbus data
var ftp = new ftp();
ftp.on('ready', () => {
	ftp.get('Anrd/hrtrtf.txt', (err, stream) => {
		if (err) throw err;

		stream
		  .once('close',() => {ftp.end();})
		  .pipe(fs.createWriteStream(newfile));
	});
}).connect({host : '216.54.15.3'});

//read the files from the log dir
fs.readdir('logs/', (err, files) => {
	if (err) throw err;

	if (files[files.length -1] == undefined) {
		console.log("Error: No File Found");
	};

	//If only header in last sync, notify
	fs.stat('logs/' + files[files.length -1], (err,stats) => {
		//if err throw err;
		if (stats.size == 107) {
			console.log("Error: Most recent pull only returned header");
		}
	});

	//If file size hasn't for 5 consecutive  pulls, assume stale feed
	fs.readFile('logs/' + files[files.length -1],'utf8', (err, data) => {
		if (err) throw err;
		var lasttimestamp = moment(data.slice(data.length - 50,data.length -42),
															"hh:mm:ss").fromNow();
		if (lasttimestamp[0] > 10) {
			console.log("Stale Feed");
		}
	});

	// maintain a queue of 6 files
	if(files.length > 5) {
		fs.unlinkSync('logs/' + files[0]);
	};
  console.log(files);
});<|endoftext|>


<commit_before>function humanOldness(diff){
  // diff should be a value in seconds
	var	day_diff = Math.floor(diff / 86400)
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return
	return day_diff == 0 && (
			diff < 60 && "brand new" ||
			diff < 120 && "1 minute old" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes old" ||
			diff < 7200 && "1 hour old" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours old") ||
		day_diff == 1 && "1 day old" ||
		day_diff < 7 && day_diff + " days old" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks old"
}

// http://stackoverflow.com/questions/280634
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1
}

function localSql(sql, success, error) {
  var settings = scraperwiki.readSettings()
  options = {
    url: "" + settings.source.url + "/sql/",
    type: "GET",
    dataType: "json",
    data: {
      q: sql
    }
  }
  if (success != null) {
    options.success = success
  }
  if (error != null) {
    options.error = error
  }
  return $.ajax(options)
}

function showFiles(files){
  // files should be a list of objects, containing rowids, filenames and ages:
  // [ {rowid: 2, filename: 'test.csv', age: 3600}, {…}, … ]
  var $ul = $('ul.nav')
  $('li', $ul).each(function(){
    var li = $(this)
    var id = li.attr('id')
    var found = false
    $.each(files, function(i, file){
      if('file_' + file.rowid == id){
        found = true
      }
    })
    if(!found){
      li.remove()
    }
  })
  $.each(files, function(i, file){
    var elementId = '#file_' + file.rowid
    var loading = (file.age == '' || file.age == null)
    var needToCreate = !($(elementId).length)
    var icon = file.filename.endsWith('csv') ? 'csv.png' : 'xlsx.png'

    if(needToCreate) {
      $ul.append('
 '+ file.filename +'
')
    }

    if(loading){
      var timeOrLoading = 'Creating '
      $(elementId + ' a').addClass('loading').removeAttr('href')
    } else {
      var timeOrLoading = humanOldness(file.age)
      $(elementId + ' a').removeClass('loading').attr('href', file.filename)
    }

    $(elementId + ' span.muted').html(timeOrLoading)  // update the time
  })
}

function trackProgress(){
  localSql('SELECT rowid, filename, STRFTIME("%s", "now") - STRFTIME("%s", created) AS age FROM _state ORDER BY filename ASC').done(function(files){
    showFiles(files)
  }).fail(function(x, y, z){
    if(x.responseText.match(/database file does not exist/) != null){
      regenerate()
    } else {
      scraperwiki.alert('Error contacting ScraperWiki API', x.responseText, 1)
    }
  })
}

function regenerate(){
  scraperwiki.exec('echo "started"; tool/extract.py ' + scraperwiki.readSettings().target.url + ' &> log.txt &')
}

$(function(){

  $(document).on('click', '#regenerate', regenerate)

  trackProgress()
  poll = setInterval(trackProgress, 2000)

})
<commit_msg>only update timeOrLoading if necessary<commit_after>function humanOldness(diff){
  // diff should be a value in seconds
	var	day_diff = Math.floor(diff / 86400)
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return
	return day_diff == 0 && (
			diff < 60 && "brand new" ||
			diff < 120 && "1 minute old" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes old" ||
			diff < 7200 && "1 hour old" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours old") ||
		day_diff == 1 && "1 day old" ||
		day_diff < 7 && day_diff + " days old" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks old"
}

// http://stackoverflow.com/questions/280634
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1
}

function localSql(sql, success, error) {
  var settings = scraperwiki.readSettings()
  options = {
    url: "" + settings.source.url + "/sql/",
    type: "GET",
    dataType: "json",
    data: {
      q: sql
    }
  }
  if (success != null) {
    options.success = success
  }
  if (error != null) {
    options.error = error
  }
  return $.ajax(options)
}

function showFiles(files){
  // files should be a list of objects, containing rowids, filenames and ages:
  // [ {rowid: 2, filename: 'test.csv', age: 3600}, {…}, … ]
  var $ul = $('ul.nav')
  $('li', $ul).each(function(){
    var li = $(this)
    var id = li.attr('id')
    var found = false
    $.each(files, function(i, file){
      if('file_' + file.rowid == id){
        found = true
      }
    })
    if(!found){
      li.remove()
    }
  })
  $.each(files, function(i, file){
    var elementId = '#file_' + file.rowid
    var loading = (file.age == '' || file.age == null)
    var needToCreate = !($(elementId).length)
    var icon = file.filename.endsWith('csv') ? 'csv.png' : 'xlsx.png'

    if(needToCreate) {
      $ul.append('
 '+ file.filename +'
')
    }

    if(loading){
      var timeOrLoading = 'Creating '
      $(elementId + ' a').addClass('loading').removeAttr('href')
    } else {
      var timeOrLoading = humanOldness(file.age)
      $(elementId + ' a').removeClass('loading').attr('href', file.filename)
    }

    if($(elementId + ' span.muted').html() != timeOrLoading){
      console.log($(elementId + ' span.muted').html(), timeOrLoading)
      $(elementId + ' span.muted').html(timeOrLoading)  // update the time
    }
  })
}

function trackProgress(){
  localSql('SELECT rowid, filename, STRFTIME("%s", "now") - STRFTIME("%s", created) AS age FROM _state ORDER BY filename ASC').done(function(files){
    showFiles(files)
  }).fail(function(x, y, z){
    if(x.responseText.match(/database file does not exist/) != null){
      regenerate()
    } else {
      scraperwiki.alert('Error contacting ScraperWiki API', x.responseText, 1)
    }
  })
}

function regenerate(){
  scraperwiki.exec('echo "started"; tool/extract.py ' + scraperwiki.readSettings().target.url + ' &> log.txt &')
}

$(function(){

  $(document).on('click', '#regenerate', regenerate)

  trackProgress()
  poll = setInterval(trackProgress, 2000)

})
<|endoftext|>


<commit_before>var puppy = {
  x: 40,
  y: 200,
  alive: true,
  won: false,
  canMove: true,
};

var alien = {
  x: 560,
  y: 80,
  alive: true,
};

var alien2 = {
  x: 560,
  y: 200,
  alive: true,
};

var alien3 = {
  x: 560,
  y: 320,
  alive: true,
};

document.getElementById("up").onclick = function() {move(38);};
document.getElementById("down").onclick = function() {move(40);};
document.getElementById("right").onclick = function() {move(39);};
document.getElementById("left").onclick = function() {move(37);};

var puppyImg = document.getElementById("puppy");
var alienImg = document.getElementById("alien");
var alienImg2 = document.getElementById("alien2");
var alienImg3 = document.getElementById("alien3");

var alienCount = 3;

function move(direction){
  if (puppy.canMove){
    console.log('moving');
    ai_move(alien, alienImg);
    ai_move(alien2, alienImg2);
    ai_move(alien3, alienImg3);
    if (direction.keyCode === 38 || direction === 38 || direction.keyCode === 73){ // move up
      if (puppy.y > 0){
        puppy.y = (puppy.y - 40);
        puppyImg.style.top = (puppy.y + "px");
      }
    }else if (direction.keyCode === 40 || direction === 40 || direction.keyCode === 75){ // move down
      if (puppy.y < 440){
        puppy.y = (puppy.y + 40);
        puppyImg.style.top = (puppy.y + "px");
      }
    }else if (direction.keyCode === 39 || direction == 39 || direction.keyCode === 76){ // move right
      if (puppy.x < 600){
        puppy.x = (puppy.x + 40);
        puppyImg.style.left = (puppy.x + "px");
      }

    }else if (direction.keyCode === 37 || direction == 37 || direction.keyCode === 74){ // move left
      if (puppy.x > 0){
        puppy.x = (puppy.x - 40);
        puppyImg.style.left = (puppy.x + "px");
      }
    }
    status(alien, alienImg);
    status(alien2, alienImg2);
    status(alien3, alienImg3);
    setTimeout(function(){
      puppy.canMove = true;
    }, 200)
    puppy.canMove = false;
  }
}

function ai_move(player, playerImg){
  var random = Math.floor((Math.random() * 4) + 1);
  // move up
  if (random === 1){
    if (player.y > 0){
      player.y = (player.y - 40);
      playerImg.style.top = (player.y + "px");
    }
  }else if (random === 2){
    // move down
    if (player.y < 440){
      player.y = (player.y + 40);
      playerImg.style.top = (player.y + "px");
    }
  }else if (random === 3){
    // move right
    if (player.x < 600){
      player.x = (player.x + 40);
      playerImg.style.left = (player.x + "px");
    }
 }else{
    //move left
    if (player.x > 0){
      player.x = (player.x - 40);
      playerImg.style.left = (player.x + "px");
    }
 }
}

document.onkeydown = move;
<commit_msg>Add puppy<commit_after>document.onkeydown = move;

var puppy = {
  x: 40,
  y: 200,
  alive: true,
  won: false,
  canMove: true,
};

var alien = {
  x: 560,
  y: 80,
  alive: true,
};

var alien2 = {
  x: 560,
  y: 200,
  alive: true,
};

var alien3 = {
  x: 560,
  y: 320,
  alive: true,
};

document.getElementById("up").onclick = function() {move(38);};
document.getElementById("down").onclick = function() {move(40);};
document.getElementById("right").onclick = function() {move(39);};
document.getElementById("left").onclick = function() {move(37);};

var puppyImg = document.getElementById("puppy");
var alienImg = document.getElementById("alien");
var alienImg2 = document.getElementById("alien2");
var alienImg3 = document.getElementById("alien3");

var alienCount = 3;

function move(direction){
  if (puppy.canMove){
    console.log('moving');
    ai_move(alien, alienImg);
    ai_move(alien2, alienImg2);
    ai_move(alien3, alienImg3);
    if (direction.keyCode === 38 || direction === 38 || direction.keyCode === 73){ // move up
      if (puppy.y > 0){
        puppy.y = (puppy.y - 40);
        puppyImg.style.top = (puppy.y + "px");
      }
    }else if (direction.keyCode === 40 || direction === 40 || direction.keyCode === 75){ // move down
      if (puppy.y < 440){
        puppy.y = (puppy.y + 40);
        puppyImg.style.top = (puppy.y + "px");
      }
    }else if (direction.keyCode === 39 || direction == 39 || direction.keyCode === 76){ // move right
      if (puppy.x < 600){
        puppy.x = (puppy.x + 40);
        puppyImg.style.left = (puppy.x + "px");
      }

    }else if (direction.keyCode === 37 || direction == 37 || direction.keyCode === 74){ // move left
      if (puppy.x > 0){
        puppy.x = (puppy.x - 40);
        puppyImg.style.left = (puppy.x + "px");
      }
    }
    status(alien, alienImg);
    status(alien2, alienImg2);
    status(alien3, alienImg3);
    setTimeout(function(){
      puppy.canMove = true;
    }, 200)
    puppy.canMove = false;
  }
}

function ai_move(player, playerImg){
  var random = Math.floor((Math.random() * 4) + 1);
  // move up
  if (random === 1){
    if (player.y > 0){
      player.y = (player.y - 40);
      playerImg.style.top = (player.y + "px");
    }
  }else if (random === 2){
    // move down
    if (player.y < 440){
      player.y = (player.y + 40);
      playerImg.style.top = (player.y + "px");
    }
  }else if (random === 3){
    // move right
    if (player.x < 600){
      player.x = (player.x + 40);
      playerImg.style.left = (player.x + "px");
    }
 }else{
    //move left
    if (player.x > 0){
      player.x = (player.x - 40);
      playerImg.style.left = (player.x + "px");
    }
 }
}
<|endoftext|>


<commit_before>
var StandardTheme = Theme.extend({

	classes: {
		widget: 'fc-unthemed',
		widgetHeader: 'fc-widget-header',
		widgetContent: 'fc-widget-content',

		buttonGroup: 'fc-button-group',
		button: 'fc-button',
		cornerLeft: 'fc-corner-left',
		cornerRight: 'fc-corner-right',
		stateDefault: 'fc-state-default',
		stateActive: 'fc-state-active',
		stateDisabled: 'fc-state-disabled',
		stateHover: 'fc-state-hover',
		stateDown: 'fc-state-down',

		popoverHeader: 'fc-widget-header',
		popoverContent: 'fc-widget-content',

		// day grid
		headerRow: 'fc-widget-header',
		dayRow: 'fc-widget-content',

		// list view
		listView: 'fc-widget-content'
	},

	baseIconClass: 'fc-icon',
	iconClasses: {
		close: 'fc-icon-x',
		prev: 'fc-icon-left-single-arrow',
		next: 'fc-icon-right-single-arrow',
		prevYear: 'fc-icon-left-double-arrow',
		nextYear: 'fc-icon-right-double-arrow'
	},

	iconOverrideOption: 'buttonIcons',
	iconOverrideCustomButtonOption: 'icon',
	iconOverridePrefix: 'fc-icon-'

});
<commit_msg>"standard" theme in registry<commit_after>
var StandardTheme = Theme.extend({

	classes: {
		widget: 'fc-unthemed',
		widgetHeader: 'fc-widget-header',
		widgetContent: 'fc-widget-content',

		buttonGroup: 'fc-button-group',
		button: 'fc-button',
		cornerLeft: 'fc-corner-left',
		cornerRight: 'fc-corner-right',
		stateDefault: 'fc-state-default',
		stateActive: 'fc-state-active',
		stateDisabled: 'fc-state-disabled',
		stateHover: 'fc-state-hover',
		stateDown: 'fc-state-down',

		popoverHeader: 'fc-widget-header',
		popoverContent: 'fc-widget-content',

		// day grid
		headerRow: 'fc-widget-header',
		dayRow: 'fc-widget-content',

		// list view
		listView: 'fc-widget-content'
	},

	baseIconClass: 'fc-icon',
	iconClasses: {
		close: 'fc-icon-x',
		prev: 'fc-icon-left-single-arrow',
		next: 'fc-icon-right-single-arrow',
		prevYear: 'fc-icon-left-double-arrow',
		nextYear: 'fc-icon-right-double-arrow'
	},

	iconOverrideOption: 'buttonIcons',
	iconOverrideCustomButtonOption: 'icon',
	iconOverridePrefix: 'fc-icon-'

});

ThemeRegistry.register('standard', StandardTheme);
<|endoftext|>