<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
    classNames: 'graph-data',

    didInsertElement() {
        this._super(...arguments);

        Ember.$(window).on('resize.chart', () => this.rerender());
        Ember.$(document).on('googleChartsLoaded', () => this.rerender());
    },

    willDestroyElement() {
        Ember.$(window).off('resize.chart');
        Ember.$(document).off('googleChartsLoaded');
    },

    didRender() {
        this._super(...arguments);

        let data = this.get('data');

        let subarray_length = (data[1] || []).length;

        // Start at 1 to skip the date element in the 0th
        // location in the array.
        for (let k = 1; k < subarray_length; k++) {
            let on = false;

            // Start at 1 because the 0th entry in the array
            // is an array of version numbers.
            //
            // End before the last element is reached because we never
            // want to change the last element.
            for (let i = 1; i < data.length - 1; i++) {
                // k + 1 because the first entry in the array is the date
                let value = data[i][k];

                // If we are "off" and are looking at a zero
                // replace the data at this point with `null`.
                //
                // Null tells google.visualization to stop drawing
                // the line altogether.
                if (!on && value === 0) {
                    data[i][k] = null;
                }

                // If we are off and the value is not zero, we
                // need to turn back on.  (keep the value the same though)
                else if (!on && value !== 0) {
                    on = true;

                    // We previously wrote a null into data[i - 1][k + 1],
                    // so to make the graph look pretty, we'll switch it back
                    // to the zero that it was before.
                    if (i >= 2) {
                        data[i - 1][k] = 0;
                    }
                }
                // If we are on and the value is zero, turn off
                // but keep the zero in the array
                else if (on && value === 0) {
                    on = false;
                }
            }
        }

        if (!data || !window.google || !window.googleChartsLoaded) {
            this.$().hide();
            return;
        } else {
            this.$().show();
        }

        var myData = window.google.visualization.arrayToDataTable(data);

        var fmt = new window.google.visualization.DateFormat({
            pattern: 'LLL d, yyyy',
        });
        fmt.format(myData, 0);

        // use a DataView to calculate an x-day moving average
        var days = 7;
        var view = new google.visualization.DataView(myData);
        var moving_avg_func_for_col = function(col) {
            return function(dt, row) {
                // For the last rows (the *first* days, remember, the dataset is
                // backwards), we cannot calculate the avg. of previous days.
                if (row >= dt.getNumberOfRows() - days) {
                    return null;
                }

                var total = 0;
                for (var i = days; i > 0; i--) {
                    total += dt.getValue(row + i, col);
                }
                var avg = total / days;
                return {
                    v: avg,
                    f: avg.toFixed(2)
                };
            };
        };

        var columns = [0]; // 0 = datetime
        var seriesOption = {};
        // Colors by http://colorbrewer2.org/#type=diverging&scheme=RdBu&n=10
        var colors = ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#92c5de',
                      '#4393c3', '#2166ac', '#053061'];
        var [headers, ] = data;
        // Walk over the headers/colums in reverse order, as the newest version
        // is at the end, but in the UI we want it at the top of the chart legend.
        _.forEach(_.range(headers.length - 1, 0, -1), (dataCol, i) => {
            columns.push(dataCol); // add the column itself
            columns.push({ // add a 'calculated' column, the moving average
                type: 'number',
                label: `${headers[dataCol]} ${days}-day avg.`,
                calc: moving_avg_func_for_col(dataCol)
            });
            // Note: while the columns start with index 1 (because 0 is the time
            // axis), the series configuration starts with index 0.
            seriesOption[i * 2] = {
                type: 'scatter',
                color: colors[i % colors.length],
                pointSize: 3,
                pointShape: 'square'
            };
            seriesOption[i * 2 + 1] = {
                type: 'line',
                color: colors[i % colors.length],
                lineWidth: 2,
                curveType: 'function',
                visibleInLegend: false
            };
        });
        view.setColumns(columns);

        var chart = new window.google.visualization.ComboChart(this.get('element'));
        chart.draw(view, {
            chartArea: { 'left': 85, 'width': '77%', 'height': '80%' },
            hAxis: {
                minorGridlines: { count: 8 },
            },
            vAxis: {
                minorGridlines: { count: 5 },
                viewWindow: { min: 0, },
            },
            isStacked: false,
            focusTarget: 'category',
            seriesType: 'scatter',
            series: seriesOption
        });
    },
});
<commit_msg>Fix JSHint complaints.<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
    classNames: 'graph-data',

    didInsertElement() {
        this._super(...arguments);

        Ember.$(window).on('resize.chart', () => this.rerender());
        Ember.$(document).on('googleChartsLoaded', () => this.rerender());
    },

    willDestroyElement() {
        Ember.$(window).off('resize.chart');
        Ember.$(document).off('googleChartsLoaded');
    },

    didRender() {
        this._super(...arguments);

        let data = this.get('data');

        let subarray_length = (data[1] || []).length;

        // Start at 1 to skip the date element in the 0th
        // location in the array.
        for (let k = 1; k < subarray_length; k++) {
            let on = false;

            // Start at 1 because the 0th entry in the array
            // is an array of version numbers.
            //
            // End before the last element is reached because we never
            // want to change the last element.
            for (let i = 1; i < data.length - 1; i++) {
                // k + 1 because the first entry in the array is the date
                let value = data[i][k];

                // If we are "off" and are looking at a zero
                // replace the data at this point with `null`.
                //
                // Null tells google.visualization to stop drawing
                // the line altogether.
                if (!on && value === 0) {
                    data[i][k] = null;
                }

                // If we are off and the value is not zero, we
                // need to turn back on.  (keep the value the same though)
                else if (!on && value !== 0) {
                    on = true;

                    // We previously wrote a null into data[i - 1][k + 1],
                    // so to make the graph look pretty, we'll switch it back
                    // to the zero that it was before.
                    if (i >= 2) {
                        data[i - 1][k] = 0;
                    }
                }
                // If we are on and the value is zero, turn off
                // but keep the zero in the array
                else if (on && value === 0) {
                    on = false;
                }
            }
        }

        if (!data || !window.google || !window.googleChartsLoaded) {
            this.$().hide();
            return;
        } else {
            this.$().show();
        }

        var myData = window.google.visualization.arrayToDataTable(data);

        var fmt = new window.google.visualization.DateFormat({
            pattern: 'LLL d, yyyy',
        });
        fmt.format(myData, 0);

        // use a DataView to calculate an x-day moving average
        var days = 7;
        var view = new window.google.visualization.DataView(myData);
        var moving_avg_func_for_col = function(col) {
            return function(dt, row) {
                // For the last rows (the *first* days, remember, the dataset is
                // backwards), we cannot calculate the avg. of previous days.
                if (row >= dt.getNumberOfRows() - days) {
                    return null;
                }

                var total = 0;
                for (var i = days; i > 0; i--) {
                    total += dt.getValue(row + i, col);
                }
                var avg = total / days;
                return {
                    v: avg,
                    f: avg.toFixed(2)
                };
            };
        };

        var columns = [0]; // 0 = datetime
        var seriesOption = {};
        // Colors by http://colorbrewer2.org/#type=diverging&scheme=RdBu&n=10
        var colors = ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#92c5de',
                      '#4393c3', '#2166ac', '#053061'];
        var [headers, ] = data;
        // Walk over the headers/colums in reverse order, as the newest version
        // is at the end, but in the UI we want it at the top of the chart legend.

        window._.range(headers.length - 1, 0, -1).forEach((dataCol, i) => {
            columns.push(dataCol); // add the column itself
            columns.push({ // add a 'calculated' column, the moving average
                type: 'number',
                label: `${headers[dataCol]} ${days}-day avg.`,
                calc: moving_avg_func_for_col(dataCol)
            });
            // Note: while the columns start with index 1 (because 0 is the time
            // axis), the series configuration starts with index 0.
            seriesOption[i * 2] = {
                type: 'scatter',
                color: colors[i % colors.length],
                pointSize: 3,
                pointShape: 'square'
            };
            seriesOption[i * 2 + 1] = {
                type: 'line',
                color: colors[i % colors.length],
                lineWidth: 2,
                curveType: 'function',
                visibleInLegend: false
            };
        });
        view.setColumns(columns);

        var chart = new window.google.visualization.ComboChart(this.get('element'));
        chart.draw(view, {
            chartArea: { 'left': 85, 'width': '77%', 'height': '80%' },
            hAxis: {
                minorGridlines: { count: 8 },
            },
            vAxis: {
                minorGridlines: { count: 5 },
                viewWindow: { min: 0, },
            },
            isStacked: false,
            focusTarget: 'category',
            seriesType: 'scatter',
            series: seriesOption
        });
    },
});
<|endoftext|>


<commit_before>'use strict';

const React = require('react');
const PropTypes = React.PropTypes;

const ResumePropTypes = require('../../prop_types/resume');
const Datetime = require('../../utils/datetime');

const Entry = React.createClass({
    propTypes: {
        index: PropTypes.number.isRequired,
        total: PropTypes.number.isRequired,
        entry: ResumePropTypes.awards
    },

    render: function () {
        const startDate = Datetime.getDisplayFromDate(this.props.entry.startDate);
        const endDate = Datetime.getDisplayFromDate(this.props.entry.endDate);
        const index = this.props.index + 1;
        const divider = index === this.props.total ? (
) : (
);

        return (

                        {this.props.entry.title}

                        {this.props.entry.awarder}
                         •
                        {this.props.entry.summary}
                         •
                        {startDate}

                {divider}

        );
    }
});

const Awards = React.createClass({
    propTypes: {
        content: ResumePropTypes.awardsSet
    },

    render: function () {
        const numEntries = this.props.content.length;
        return (

                            Awards

                        {this.props.content.map(function (entry, index) {
                            return (
                                <Entry key={index} index={index} total={numEntries} entry={entry}/>
                            );
                        })}

        );
    }
});

module.exports = Awards;
<commit_msg>Update awards.js<commit_after>'use strict';

const React = require('react');
const PropTypes = React.PropTypes;

const ResumePropTypes = require('../../prop_types/resume');
const Datetime = require('../../utils/datetime');

const Entry = React.createClass({
    propTypes: {
        index: PropTypes.number.isRequired,
        total: PropTypes.number.isRequired,
        entry: ResumePropTypes.awards
    },

    render: function () {
        const startDate = Datetime.getDisplayFromDate(this.props.entry.startDate);
        const index = this.props.index + 1;
        const divider = index === this.props.total ? (
) : (
);

        return (

                        {this.props.entry.title}

                        {this.props.entry.awarder}
                         •
                        {this.props.entry.summary}
                         •
                        {startDate}

                {divider}

        );
    }
});

const Awards = React.createClass({
    propTypes: {
        content: ResumePropTypes.awardsSet
    },

    render: function () {
        const numEntries = this.props.content.length;
        return (

                            Awards

                        {this.props.content.map(function (entry, index) {
                            return (
                                <Entry key={index} index={index} total={numEntries} entry={entry}/>
                            );
                        })}

        );
    }
});

module.exports = Awards;
<|endoftext|>


<commit_before>
/*
 *  Card Directives  (widgets to draggable cards)
 *
 *  These can be thought of as the 'widgets' on a page.
 *  Scope comes from the controllers.
 *
*/

angular.module('card-directives', []);
angular.module('card-directives')
    .directive('genomecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "genome",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('gptype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gptype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            },
            replace: true
        };
    })
    .directive('gttype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gttype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            },
        };
    })
    .directive('gvtype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gvtype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('ggltype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "ggltype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('gtvtype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gtvtype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('genecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();

                if(scope.params.ws == "CDS" ) {
                        scope.params.ws = "KBasePublicGenomesV3";
                }

                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gene",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('memecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "meme",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('cmonkeycards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "cmonkey",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('inferelatorcards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "inferelator",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('regprecisecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "regprecise",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('makcards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "mak",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('bambicards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "bambi",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('ppid', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                $(element).KBaseCardLayoutManager({
                    template: 'ppid',
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('modelcards', function($rootScope, $location) {
        return {
            link: function(scope, element, attrs) {
                if(cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager();
                var prom = kb.req('ws', 'get_objectmeta',
                            {type:'Model', id: scope.id, workspace: scope.ws, auth: scope.USER_TOKEN});
                $.when(prom).done(function(data){
                    cardManager.addNewCard("kbaseModelMeta",
                        { title: 'Model Info',
                          data: data,
                          id: scope.id,
                          ws: scope.ws },
                        { my: "left top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                });

                var prom = kb.req('fba', 'get_models',
                            {models: [scope.id], workspaces: [scope.ws], auth: scope.USER_TOKEN});
                $.when(prom).done(function(data) {
                    cardManager.addNewCard("kbaseModelTabs",
                        { modelsData: data,
                          title: 'Model Details',
                          id: scope.id,
                          ws: scope.ws,
                          width: 700 },
                        { my: "left+400 top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                    cardManager.addNewCard("kbaseModelCore",
                        { title: 'Central Carbon Core Metabolic Pathway',
                          modelsData: data,
                          ids: [scope.id],
                          workspaces: [scope.ws],
                          width: 900 },
                        { my: "left+800 top+600",
                          at: "left bottom",
                          of: "#app"
                    });
                    events();
                });

                function events() {
                    $(document).on('rxnClick', function(e, data) {
                        var url = '/rxns/'+data.ids;
                        scope.$apply( $location.path(url) );
                    });
                    $(document).on('coreRxnClick', function(e, data) {
                        console.log(data.ids)
                        var url = '/rxns/'+data.ids.join('&');
                        scope.$apply( $location.path(url) );
                    });
                }
            }
        }

    })
    .directive('fbacards', function($rootScope, $location) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager();
                var prom = kb.req('ws', 'get_objectmeta',
                            {type:'FBA', id: scope.id, workspace: scope.ws, auth: scope.USER_TOKEN});
                $.when(prom).done(function(data){
                    cardManager.addNewCard("kbaseFbaMeta",
                        { title: 'Model Info',
                          data: data,
                          id: scope.id,
                          ws: scope.ws },
                        { my: "left top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                });

                var prom = kb.req('fba', 'get_fbas',
                            {fbas: [scope.id], workspaces: [scope.ws], auth: scope.USER_TOKEN})
                $.when(prom).done(function(fbas_data) {
                    cardManager.addNewCard("kbaseFbaTabs",
                        { title: 'FBA Details',
                          fbaData: fbas_data,
                          id: scope.id,
                          ws: scope.ws,
                          width: 700 },
                        { my: "left+400 top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                    var model_ws = fbas_data[0].model_workspace;
                    var model_id = fbas_data[0].model;

                    var prom2 = kb.req('fba', 'get_models',
                            {models: [model_id], workspaces: [model_ws], auth: scope.USER_TOKEN});
                    $.when(prom2).done(function(models_data){
                        cardManager.addNewCard("kbaseModelCore",
                            { title: 'Central Carbon Core Metabolic Pathway',
                              modelsData: models_data,
                              fbasData: fbas_data,
                              ids: [scope.id],
                              workspaces: [scope.ws],
                              width: 900 },
                            { my: "left+800 top+600",
                              at: "left bottom",
                              of: "#app"
                        });

                        events();
                    });
                });

                function events() {
                    $(document).on('rxnClick', function(e, data) {
                        var url = '/rxns/'+data.ids;
                        scope.$apply( $location.path(url) );
                    });
                    $(document).on('cpdClick', function(e, data) {
                        var url = '/cpds/'+data.ids;
                        scope.$apply( $location.path(url) );
                    });
                    $(document).on('coreRxnClick', function(e, data) {
                        console.log(data.ids)
                        var url = '/rxns/'+data.ids.join('&');
                        scope.$apply( $location.path(url) );
                    });
                }

            }
        }
    })
    .directive('speccards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "spec",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN
                });
            }
        };
    })
    .directive('wsrefcards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsref",
                    data: scope.params
                });
            }
        };
    })
    .directive('wsrefusers', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsrefusers",
                    data: scope.params
                });
            }
        };
    })
    .directive('wsobjgraphview', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsobjgraphview",
                    data: scope.params
                });
            }
        };
    })
    .directive('wsobjgraphcenteredview', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsobjgraphcenteredview",
                    data: scope.params
                });
            }
        };
    })
    .directive('treecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "tree",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('taxonomyview', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "taxonomy",
                    data: scope.params
                });
            }
        };
    })
;

<commit_msg>updated CDS gene page redirect<commit_after>
/*
 *  Card Directives  (widgets to draggable cards)
 *
 *  These can be thought of as the 'widgets' on a page.
 *  Scope comes from the controllers.
 *
*/

angular.module('card-directives', []);
angular.module('card-directives')
    .directive('genomecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "genome",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('gptype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gptype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            },
            replace: true
        };
    })
    .directive('gttype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gttype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            },
        };
    })
    .directive('gvtype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gvtype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('ggltype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "ggltype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('gtvtype', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gtvtype",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('genecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();

                if(scope.params.workspaceID == "CDS" ) {
                    scope.params.workspaceID = "KBasePublicGenomesV3";
                }
                if (!scope.params.genomeID) {
                    var temp = scope.params.featureID.split(".");
                    if (temp.length>3) {
                        scope.params.genomeID = temp[0]+"."+temp[1];
                    }
                }
		alert(JSON.stringify(scope.params));
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "gene",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('memecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "meme",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('cmonkeycards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "cmonkey",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('inferelatorcards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "inferelator",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('regprecisecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "regprecise",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('makcards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "mak",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('bambicards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "bambi",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('ppid', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                $(element).KBaseCardLayoutManager({
                    template: 'ppid',
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('modelcards', function($rootScope, $location) {
        return {
            link: function(scope, element, attrs) {
                if(cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager();
                var prom = kb.req('ws', 'get_objectmeta',
                            {type:'Model', id: scope.id, workspace: scope.ws, auth: scope.USER_TOKEN});
                $.when(prom).done(function(data){
                    cardManager.addNewCard("kbaseModelMeta",
                        { title: 'Model Info',
                          data: data,
                          id: scope.id,
                          ws: scope.ws },
                        { my: "left top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                });

                var prom = kb.req('fba', 'get_models',
                            {models: [scope.id], workspaces: [scope.ws], auth: scope.USER_TOKEN});
                $.when(prom).done(function(data) {
                    cardManager.addNewCard("kbaseModelTabs",
                        { modelsData: data,
                          title: 'Model Details',
                          id: scope.id,
                          ws: scope.ws,
                          width: 700 },
                        { my: "left+400 top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                    cardManager.addNewCard("kbaseModelCore",
                        { title: 'Central Carbon Core Metabolic Pathway',
                          modelsData: data,
                          ids: [scope.id],
                          workspaces: [scope.ws],
                          width: 900 },
                        { my: "left+800 top+600",
                          at: "left bottom",
                          of: "#app"
                    });
                    events();
                });

                function events() {
                    $(document).on('rxnClick', function(e, data) {
                        var url = '/rxns/'+data.ids;
                        scope.$apply( $location.path(url) );
                    });
                    $(document).on('coreRxnClick', function(e, data) {
                        console.log(data.ids)
                        var url = '/rxns/'+data.ids.join('&');
                        scope.$apply( $location.path(url) );
                    });
                }
            }
        }

    })
    .directive('fbacards', function($rootScope, $location) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager();
                var prom = kb.req('ws', 'get_objectmeta',
                            {type:'FBA', id: scope.id, workspace: scope.ws, auth: scope.USER_TOKEN});
                $.when(prom).done(function(data){
                    cardManager.addNewCard("kbaseFbaMeta",
                        { title: 'Model Info',
                          data: data,
                          id: scope.id,
                          ws: scope.ws },
                        { my: "left top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                });

                var prom = kb.req('fba', 'get_fbas',
                            {fbas: [scope.id], workspaces: [scope.ws], auth: scope.USER_TOKEN})
                $.when(prom).done(function(fbas_data) {
                    cardManager.addNewCard("kbaseFbaTabs",
                        { title: 'FBA Details',
                          fbaData: fbas_data,
                          id: scope.id,
                          ws: scope.ws,
                          width: 700 },
                        { my: "left+400 top+100",
                          at: "left bottom",
                          of: "#app"
                    });
                    var model_ws = fbas_data[0].model_workspace;
                    var model_id = fbas_data[0].model;

                    var prom2 = kb.req('fba', 'get_models',
                            {models: [model_id], workspaces: [model_ws], auth: scope.USER_TOKEN});
                    $.when(prom2).done(function(models_data){
                        cardManager.addNewCard("kbaseModelCore",
                            { title: 'Central Carbon Core Metabolic Pathway',
                              modelsData: models_data,
                              fbasData: fbas_data,
                              ids: [scope.id],
                              workspaces: [scope.ws],
                              width: 900 },
                            { my: "left+800 top+600",
                              at: "left bottom",
                              of: "#app"
                        });

                        events();
                    });
                });

                function events() {
                    $(document).on('rxnClick', function(e, data) {
                        var url = '/rxns/'+data.ids;
                        scope.$apply( $location.path(url) );
                    });
                    $(document).on('cpdClick', function(e, data) {
                        var url = '/cpds/'+data.ids;
                        scope.$apply( $location.path(url) );
                    });
                    $(document).on('coreRxnClick', function(e, data) {
                        console.log(data.ids)
                        var url = '/rxns/'+data.ids.join('&');
                        scope.$apply( $location.path(url) );
                    });
                }

            }
        }
    })
    .directive('speccards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "spec",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN
                });
            }
        };
    })
    .directive('wsrefcards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsref",
                    data: scope.params
                });
            }
        };
    })
    .directive('wsrefusers', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsrefusers",
                    data: scope.params
                });
            }
        };
    })
    .directive('wsobjgraphview', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsobjgraphview",
                    data: scope.params
                });
            }
        };
    })
    .directive('wsobjgraphcenteredview', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "wsobjgraphcenteredview",
                    data: scope.params
                });
            }
        };
    })
    .directive('treecards', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "tree",
                    data: scope.params,
                    auth: $rootScope.USER_TOKEN,
                    userId: $rootScope.USER_ID
                });
            }
        };
    })
    .directive('taxonomyview', function($rootScope) {
        return {
            link: function(scope, element, attrs) {
                if (cardManager) cardManager.destroy();
                cardManager = $(element).KBaseCardLayoutManager({
                    template: "taxonomy",
                    data: scope.params
                });
            }
        };
    })
;

<|endoftext|>


<commit_before>'use strict';

Module.register("Hako-ticker", {

  result: {},
  defaults: {
    updateInterval: 30000,
	  showHighLow: true,
    highLowColor: true
  },

  getStyles: function() {
    return ["Hako-ticker.css"];
  },

  start: function() {
    this.getTickers();
    this.scheduleUpdate();
  },

  getDom: function() {
    var wrapper = document.createElement("ticker");
    wrapper.className = 'medium bright';
    wrapper.className = 'ticker';

    var data = this.result.result;
    var symbolElement =  document.createElement("span");
	  var breakElement =  document.createElement("br");
    var symbol = data.pair_name;
	  //var lastPrice = data.buy_price;
	  var highPrice = data.buy_price;
	  var lowPrice = data.sell_price;

    symbolElement.innerHTML = symbol + ' $';
    wrapper.appendChild(symbolElement);
    var priceElement = document.createElement("span");
    priceElement.innerHTML = highPrice;
    wrapper.appendChild(priceElement);
	  wrapper.appendChild(breakElement);

	  if (this.config.showHighLow) {
		  var lowElement = document.createElement("span");
		  lowElement.className = 'small';
		  lowElement.innerHTML = '$' + lowPrice + '&nbsp  ';

		  var highElement = document.createElement("span");
		  highElement.className = 'small';
		  highElement.innerHTML = '$' + highPrice;

          if (this.config.highLowColor) {
              lowElement.className = 'small down';
              highElement.className = 'small up';
          }

          wrapper.appendChild(lowElement);
		  wrapper.appendChild(highElement);
    }

    return wrapper;
  },

  scheduleUpdate: function(delay) {
    var nextLoad = this.config.updateInterval;
    if (typeof delay !== "undefined" && delay >= 0) {
      nextLoad = delay;
    }

    var self = this;
    setInterval(function() {
      self.getTickers();
    }, nextLoad);
  },

  getTickers: function () {
    var url = 'https://www.coinhako.com/api/v1/wallet/supported_currencies';
	  this.sendSocketNotification('GET_DATA', url);
  },

  socketNotificationReceived: function(notification, payload, payload2) {
    if (notification === "DATA_RESULT") {
      this.result = payload;
      this.updateDom(self.config.fadeSpeed);
    }
  },

});
<commit_msg>Hako-ticker: Dynamic Pairs<commit_after>'use strict';

Module.register("1", {

  result: {},
  defaults: {
    updateInterval: 30000,
	  showHighLow: true,
    highLowColor: true
  },

  getStyles: function() {
    return ["Hako-ticker.css"];
  },

  start: function() {
    this.getTickers();
    this.scheduleUpdate();
  },

  getDom: function() {
    var wrapper = document.createElement("ticker");
    wrapper.className = 'medium bright';
    wrapper.className = 'ticker';

    var data = this.result;

    var symbolElement =  document.createElement("span");
    var breakElement =  document.createElement("br");

    for (i = 0; i < data.length; i++) {
      var symbol = data[i].pair_name;
      //var lastPrice = data.buy_price;
      var highPrice = data[i].buy_price;
      var lowPrice = data[i].sell_price;

      var priceElement = document.createElement("span");
      var lowElement = document.createElement("span");
      var highElement = document.createElement("span");

      symbolElement.innerHTML = symbol + ' $';
      wrapper.appendChild(symbolElement);
      priceElement.innerHTML = highPrice;
      wrapper.appendChild(priceElement);
      wrapper.appendChild(breakElement);
      lowElement.className = 'small';
      lowElement.innerHTML = '$' + lowPrice + '&nbsp  ';

      highElement.className = 'small';
      highElement.innerHTML = '$' + highPrice;

      lowElement.className = 'small down';
      highElement.className = 'small up';

      wrapper.appendChild(lowElement);
      wrapper.appendChild(highElement);
    }

    return wrapper;
  },

  scheduleUpdate: function(delay) {
    var nextLoad = this.config.updateInterval;
    if (typeof delay !== "undefined" && delay >= 0) {
      nextLoad = delay;
    }

    var self = this;
    setInterval(function() {
      self.getTickers();
    }, nextLoad);
  },

  getTickers: function () {
    var url = 'https://www.coinhako.com/api/v1/wallet/supported_currencies';
	  this.sendSocketNotification('GET_DATA', url);
  },

  socketNotificationReceived: function(notification, payload, payload2) {
    if (notification === "DATA_RESULT") {
      this.result = payload;
      this.updateDom(self.config.fadeSpeed);
    }
  },

});
<|endoftext|>


<commit_before>const electron = require('electron')
const ipcRenderer = electron.ipcRenderer
const userDataPath = (electron.app || electron.remote.app).getPath('userData')

const fs = require('fs')
const path = require('path')

const util = require('util')

const logFilePath = path.join(userDataPath, 'log.txt')

let debug = false

let shownError = false

function argsToString(args) {
    return Array.prototype.slice
        .apply(args)
        .map(arg => (typeof arg === 'string' ? arg : util.inspect(arg)))
        .join(' ')
}

let linesToWrite = []

function writeToFile() {
    let line = linesToWrite.shift()

    fs.appendFile(logFilePath, line, error => {
        if (error) {
            if (debug) {
                console.error("Log couldn't write to file!", error)

                if (!shownError) {
                    shownError = true

                    if (layout) {
                        layout.dialog.showError({
                            title: 'Display Whisper Error',
                            message:
                                'There was an error while trying to write to the log!',
                            detail: error.message || error.toString()
                        })
                    } else if (ipcRenderer) {
                        ipcRenderer.send('show-dialog', 'error', {
                            title: 'Display Whisper Error',
                            content:
                                'There was an error while trying to write to the log!\n' +
                                (error.message || error.toString())
                        })
                    } else if (dialog) {
                        dialog.showErrorBox(
                            'Display Whisper Error',
                            'There was an error while trying to write to the log!\n' +
                                (error.message || error.toString())
                        )
                    }
                }
            }
        }

        if (linesToWrite.length > 0) {
            writeToFile()
        }
    })
}

function addToLog(args, type = 'log') {
    linesToWrite.push(
        '[' + type.toUpperCase() + '] ' + argsToString(args) + '\n'
    )

    if (linesToWrite.length === 1) {
        writeToFile()
    }
}

Object.defineProperty(exports, 'writing', {
    get: () => {
        return linesToWrite.length > 0
    }
})

exports.log = function() {
    addToLog(arguments, 'log')

    if (debug) {
        console.log(...arguments)
    }
}

exports.info = function() {
    addToLog(arguments, 'info')

    if (debug) {
        console.info(...arguments)
    }
}

exports.warn = function() {
    addToLog(arguments, 'warn')

    if (debug) {
        console.warn(...arguments)
    }
}

exports.error = function() {
    addToLog(arguments, 'error')

    if (debug) {
        console.error(...arguments)

        if (layout) {
            //If in a window which is using the layout module, use it's error dialog method
            layout.dialog.showError({
                title: 'Display Whisper Error',
                message: argsToString(arguments)
            })
        } else if (ipcRenderer) {
            //Else if available, use ipc messaging
            ipcRenderer.send('show-dialog', 'error', {
                title: 'Display Whisper Error',
                content: argsToString(arguments)
            })
        } else if (dialog) {
            //Else if available, use base electron dialog without any inbetween
            dialog.showErrorBox(
                'Display Whisper Error',
                argsToString(arguments)
            )
        }
    }
}

Object.defineProperty(exports, 'debug', {
    get: () => {
        return debug
    },
    set: value => {
        if (value) {
            debug = true
        } else {
            debug = false
        }
    }
})

if (ipcRenderer) {
    ipcRenderer.on('setting', (event, key, value) => {
        if (key === 'debug.enable') {
            debug = value
        }
    })

    ipcRenderer.send('get-setting', 'debug.enable', false)
}
<commit_msg>Removed util dependency<commit_after>const electron = require('electron')
const ipcRenderer = electron.ipcRenderer
const userDataPath = (electron.app || electron.remote.app).getPath('userData')

const fs = require('fs')
const path = require('path')

const util = require('util')

const logFilePath = path.join(userDataPath, 'log.txt')

let debug = false

let shownError = false

function getCircularReplacer() {
    const seen = new WeakSet()

    return (key, value) => {
        if (typeof value === 'object' && value !== null) {
            if (seen.has(value)) {
                return
            }

            seen.add(value)
        }

        return value
    }
}

function argsToString(args) {
    return Array.prototype.slice
        .apply(args)
        .map(arg =>
            typeof arg === 'string'
                ? arg
                : JSON.stringify(arg, getCircularReplacer(), 2)
        )
        .join(' ')
}

let linesToWrite = []

function writeToFile() {
    let line = linesToWrite.shift()

    fs.appendFile(logFilePath, line, error => {
        if (error) {
            if (debug) {
                console.error("Log couldn't write to file!", error)

                if (!shownError) {
                    shownError = true

                    if (layout) {
                        layout.dialog.showError({
                            title: 'Display Whisper Error',
                            message:
                                'There was an error while trying to write to the log!',
                            detail: error.message || error.toString()
                        })
                    } else if (ipcRenderer) {
                        ipcRenderer.send('show-dialog', 'error', {
                            title: 'Display Whisper Error',
                            content:
                                'There was an error while trying to write to the log!\n' +
                                (error.message || error.toString())
                        })
                    } else if (dialog) {
                        dialog.showErrorBox(
                            'Display Whisper Error',
                            'There was an error while trying to write to the log!\n' +
                                (error.message || error.toString())
                        )
                    }
                }
            }
        }

        if (linesToWrite.length > 0) {
            writeToFile()
        }
    })
}

function addToLog(args, type = 'log') {
    linesToWrite.push(
        '[' + type.toUpperCase() + '] ' + argsToString(args) + '\n'
    )

    if (linesToWrite.length === 1) {
        writeToFile()
    }
}

Object.defineProperty(exports, 'writing', {
    get: () => {
        return linesToWrite.length > 0
    }
})

exports.log = function() {
    addToLog(arguments, 'log')

    if (debug) {
        console.log(...arguments)
    }
}

exports.info = function() {
    addToLog(arguments, 'info')

    if (debug) {
        console.info(...arguments)
    }
}

exports.warn = function() {
    addToLog(arguments, 'warn')

    if (debug) {
        console.warn(...arguments)
    }
}

exports.error = function() {
    addToLog(arguments, 'error')

    if (debug) {
        console.error(...arguments)

        if (layout) {
            //If in a window which is using the layout module, use it's error dialog method
            layout.dialog.showError({
                title: 'Display Whisper Error',
                message: argsToString(arguments)
            })
        } else if (ipcRenderer) {
            //Else if available, use ipc messaging
            ipcRenderer.send('show-dialog', 'error', {
                title: 'Display Whisper Error',
                content: argsToString(arguments)
            })
        } else if (dialog) {
            //Else if available, use base electron dialog without any inbetween
            dialog.showErrorBox(
                'Display Whisper Error',
                argsToString(arguments)
            )
        }
    }
}

Object.defineProperty(exports, 'debug', {
    get: () => {
        return debug
    },
    set: value => {
        if (value) {
            debug = true
        } else {
            debug = false
        }
    }
})

if (ipcRenderer) {
    ipcRenderer.on('setting', (event, key, value) => {
        if (key === 'debug.enable') {
            debug = value
        }
    })

    ipcRenderer.send('get-setting', 'debug.enable', false)
}
<|endoftext|>


<commit_before>import React from 'react';
import createElement from './create-element';

const newLineRegex = /\n/g;
function getNewLines(str) {
  return str.match(newLineRegex);
}

function createLineElement({
  children,
  lineNumber,
  lineNumberStyle,
  lineProps,
  className = []
}) {
  const properties =
    (typeof lineProps === 'function' ? lineProps(lineNumber) : lineProps) || {};
  properties.className = properties.className
    ? className.concat(properties.className)
    : className;

  if (lineNumber) {
    children.unshift({
      type: 'element',
      tagName: 'span',
      properties: {
        key: `line-number--${lineNumber}`,
        className: ['react-syntax-highlighter-line-number'],
        style:
          typeof lineNumberStyle === 'function'
            ? numberStyle(lineNumberStyle)
            : lineNumberStyle
      },
      children: [
        {
          type: 'text',
          value: lineNumber
        }
      ]
    });
  }

  return {
    type: 'element',
    tagName: 'span',
    properties,
    children
  };
}

function flattenCodeTree(tree, className = [], newTree = []) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.type === 'text') {
      newTree.push(
        createLineElement({
          children: [node],
          className
        })
      );
    } else if (node.children) {
      const classNames = className.concat(node.properties.className);
      newTree = newTree.concat(flattenCodeTree(node.children, classNames));
    }
  }
  return newTree;
}

function wrapLinesInSpan(
  codeTree,
  lineProps,
  showLineNumbers,
  startingLineNumber,
  lineNumberStyle
) {
  const tree = flattenCodeTree(codeTree.value);
  const newTree = [];
  let lastLineBreakIndex = -1;
  let index = 0;
  while (index < tree.length) {
    const node = tree[index];
    const value = node.children[0].value;
    const newLines = getNewLines(value);
    if (newLines) {
      const splitValue = value.split('\n');
      splitValue.forEach((text, i) => {
        const lineNumber =
          showLineNumbers && newTree.length + startingLineNumber;
        const newChild = { type: 'text', value: `${text}\n` };
        if (i === 0) {
          const children = tree.slice(lastLineBreakIndex + 1, index).concat(
            createLineElement({
              children: [newChild],
              className: node.properties.className
            })
          );
          newTree.push(
            createLineElement({
              children,
              lineNumber,
              lineNumberStyle,
              lineProps
            })
          );
        } else if (i === splitValue.length - 1) {
          const stringChild =
            tree[index + 1] &&
            tree[index + 1].children &&
            tree[index + 1].children[0];
          if (stringChild) {
            const lastLineInPreviousSpan = { type: 'text', value: `${text}` };
            const newElem = createLineElement({
              children: [lastLineInPreviousSpan],
              className: node.properties.className
            });
            tree.splice(index + 1, 0, newElem);
          } else {
            newTree.push(
              createLineElement({
                children: [newChild],
                lineNumber,
                lineNumberStyle,
                lineProps,
                className: node.properties.className
              })
            );
          }
        } else {
          newTree.push(
            createLineElement({
              children: [newChild],
              lineNumber,
              lineNumberStyle,
              lineProps,
              className: node.properties.className
            })
          );
        }
      });
      lastLineBreakIndex = index;
    }
    index++;
  }
  if (lastLineBreakIndex !== tree.length - 1) {
    const children = tree.slice(lastLineBreakIndex + 1, tree.length);
    if (children && children.length) {
      newTree.push(
        createLineElement({
          children,
          lineNumber: newTree.length + startingLineNumber,
          lineNumberStyle,
          lineProps
        })
      );
    }
  }
  return newTree;
}

function defaultRenderer({ rows, stylesheet, useInlineStyles }) {
  return rows.map((node, i) =>
    createElement({
      node,
      stylesheet,
      useInlineStyles,
      key: `code-segement${i}`
    })
  );
}

function getCodeTree({ astGenerator, language, code, defaultCodeValue }) {
  if (astGenerator.getLanguage) {
    const hasLanguage = language && astGenerator.getLanguage(language);
    if (language === 'text') {
      return { value: defaultCodeValue, language: 'text' };
    } else if (hasLanguage) {
      return astGenerator.highlight(language, code);
    } else {
      return astGenerator.highlightAuto(code);
    }
  }
  try {
    return language && language !== 'text'
      ? { value: astGenerator.highlight(code, language) }
      : { value: defaultCodeValue };
  } catch (e) {
    return { value: defaultCodeValue };
  }
}

export default function(defaultAstGenerator, defaultStyle) {
  return function SyntaxHighlighter({
    language,
    children,
    style = defaultStyle,
    customStyle = {},
    codeTagProps = { style: style['code[class*="language-"]'] },
    useInlineStyles = true,
    showLineNumbers = false,
    startingLineNumber = 1,
    lineNumberContainerStyle,
    lineNumberStyle = {},
    wrapLines,
    lineProps = {},
    renderer,
    PreTag = 'pre',
    CodeTag = 'code',
    code = Array.isArray(children) ? children[0] : children,
    astGenerator,
    ...rest
  }) {
    astGenerator = astGenerator || defaultAstGenerator;

    const defaultPreStyle = style.hljs ||
      style['pre[class*="language-"]'] || { backgroundColor: '#fff' };
    const preProps = useInlineStyles
      ? Object.assign({}, rest, {
          style: Object.assign({}, defaultPreStyle, customStyle)
        })
      : Object.assign({}, rest, { className: 'hljs' });

    if (!astGenerator) {
      return (
        <PreTag {...preProps}>
          <CodeTag {...codeTagProps}>{code}</CodeTag>
        </PreTag>
      );
    }

    /*
     * some custom renderers rely on individual row elements so we need to turn wrapLines on
     * if renderer is provided and wrapLines is undefined
     */
    wrapLines = renderer && wrapLines === undefined ? true : wrapLines;
    renderer = renderer || defaultRenderer;
    const defaultCodeValue = [{ type: 'text', value: code }];
    const codeTree = getCodeTree({
      astGenerator,
      language,
      code,
      defaultCodeValue
    });
    if (codeTree.language === null) {
      codeTree.value = defaultCodeValue;
    }

    const tree = wrapLines
      ? wrapLinesInSpan(
          codeTree,
          lineProps,
          showLineNumbers,
          startingLineNumber,
          lineNumberStyle
        )
      : codeTree.value;

    return (
      <PreTag {...preProps}>
        <CodeTag {...codeTagProps}>
          {renderer({ rows: tree, stylesheet: style, useInlineStyles })}
        </CodeTag>
      </PreTag>
    );
  };
}
<commit_msg>correct fn vs arg reference<commit_after>import React from 'react';
import createElement from './create-element';

const newLineRegex = /\n/g;
function getNewLines(str) {
  return str.match(newLineRegex);
}

function createLineElement({
  children,
  lineNumber,
  lineNumberStyle,
  lineProps,
  className = []
}) {
  const properties =
    (typeof lineProps === 'function' ? lineProps(lineNumber) : lineProps) || {};
  properties.className = properties.className
    ? className.concat(properties.className)
    : className;

  if (lineNumber) {
    children.unshift({
      type: 'element',
      tagName: 'span',
      properties: {
        key: `line-number--${lineNumber}`,
        className: ['react-syntax-highlighter-line-number'],
        style:
          typeof lineNumberStyle === 'function'
            ? lineNumberStyle(lineNumber)
            : lineNumberStyle
      },
      children: [
        {
          type: 'text',
          value: lineNumber
        }
      ]
    });
  }

  return {
    type: 'element',
    tagName: 'span',
    properties,
    children
  };
}

function flattenCodeTree(tree, className = [], newTree = []) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.type === 'text') {
      newTree.push(
        createLineElement({
          children: [node],
          className
        })
      );
    } else if (node.children) {
      const classNames = className.concat(node.properties.className);
      newTree = newTree.concat(flattenCodeTree(node.children, classNames));
    }
  }
  return newTree;
}

function wrapLinesInSpan(
  codeTree,
  lineProps,
  showLineNumbers,
  startingLineNumber,
  lineNumberStyle
) {
  const tree = flattenCodeTree(codeTree.value);
  const newTree = [];
  let lastLineBreakIndex = -1;
  let index = 0;
  while (index < tree.length) {
    const node = tree[index];
    const value = node.children[0].value;
    const newLines = getNewLines(value);
    if (newLines) {
      const splitValue = value.split('\n');
      splitValue.forEach((text, i) => {
        const lineNumber =
          showLineNumbers && newTree.length + startingLineNumber;
        const newChild = { type: 'text', value: `${text}\n` };
        if (i === 0) {
          const children = tree.slice(lastLineBreakIndex + 1, index).concat(
            createLineElement({
              children: [newChild],
              className: node.properties.className
            })
          );
          newTree.push(
            createLineElement({
              children,
              lineNumber,
              lineNumberStyle,
              lineProps
            })
          );
        } else if (i === splitValue.length - 1) {
          const stringChild =
            tree[index + 1] &&
            tree[index + 1].children &&
            tree[index + 1].children[0];
          if (stringChild) {
            const lastLineInPreviousSpan = { type: 'text', value: `${text}` };
            const newElem = createLineElement({
              children: [lastLineInPreviousSpan],
              className: node.properties.className
            });
            tree.splice(index + 1, 0, newElem);
          } else {
            newTree.push(
              createLineElement({
                children: [newChild],
                lineNumber,
                lineNumberStyle,
                lineProps,
                className: node.properties.className
              })
            );
          }
        } else {
          newTree.push(
            createLineElement({
              children: [newChild],
              lineNumber,
              lineNumberStyle,
              lineProps,
              className: node.properties.className
            })
          );
        }
      });
      lastLineBreakIndex = index;
    }
    index++;
  }
  if (lastLineBreakIndex !== tree.length - 1) {
    const children = tree.slice(lastLineBreakIndex + 1, tree.length);
    if (children && children.length) {
      newTree.push(
        createLineElement({
          children,
          lineNumber: newTree.length + startingLineNumber,
          lineNumberStyle,
          lineProps
        })
      );
    }
  }
  return newTree;
}

function defaultRenderer({ rows, stylesheet, useInlineStyles }) {
  return rows.map((node, i) =>
    createElement({
      node,
      stylesheet,
      useInlineStyles,
      key: `code-segement${i}`
    })
  );
}

function getCodeTree({ astGenerator, language, code, defaultCodeValue }) {
  if (astGenerator.getLanguage) {
    const hasLanguage = language && astGenerator.getLanguage(language);
    if (language === 'text') {
      return { value: defaultCodeValue, language: 'text' };
    } else if (hasLanguage) {
      return astGenerator.highlight(language, code);
    } else {
      return astGenerator.highlightAuto(code);
    }
  }
  try {
    return language && language !== 'text'
      ? { value: astGenerator.highlight(code, language) }
      : { value: defaultCodeValue };
  } catch (e) {
    return { value: defaultCodeValue };
  }
}

export default function(defaultAstGenerator, defaultStyle) {
  return function SyntaxHighlighter({
    language,
    children,
    style = defaultStyle,
    customStyle = {},
    codeTagProps = { style: style['code[class*="language-"]'] },
    useInlineStyles = true,
    showLineNumbers = false,
    startingLineNumber = 1,
    lineNumberContainerStyle,
    lineNumberStyle = {},
    wrapLines,
    lineProps = {},
    renderer,
    PreTag = 'pre',
    CodeTag = 'code',
    code = Array.isArray(children) ? children[0] : children,
    astGenerator,
    ...rest
  }) {
    astGenerator = astGenerator || defaultAstGenerator;

    const defaultPreStyle = style.hljs ||
      style['pre[class*="language-"]'] || { backgroundColor: '#fff' };
    const preProps = useInlineStyles
      ? Object.assign({}, rest, {
          style: Object.assign({}, defaultPreStyle, customStyle)
        })
      : Object.assign({}, rest, { className: 'hljs' });

    if (!astGenerator) {
      return (
        <PreTag {...preProps}>
          <CodeTag {...codeTagProps}>{code}</CodeTag>
        </PreTag>
      );
    }

    /*
     * some custom renderers rely on individual row elements so we need to turn wrapLines on
     * if renderer is provided and wrapLines is undefined
     */
    wrapLines = renderer && wrapLines === undefined ? true : wrapLines;
    renderer = renderer || defaultRenderer;
    const defaultCodeValue = [{ type: 'text', value: code }];
    const codeTree = getCodeTree({
      astGenerator,
      language,
      code,
      defaultCodeValue
    });
    if (codeTree.language === null) {
      codeTree.value = defaultCodeValue;
    }

    const tree = wrapLines
      ? wrapLinesInSpan(
          codeTree,
          lineProps,
          showLineNumbers,
          startingLineNumber,
          lineNumberStyle
        )
      : codeTree.value;

    return (
      <PreTag {...preProps}>
        <CodeTag {...codeTagProps}>
          {renderer({ rows: tree, stylesheet: style, useInlineStyles })}
        </CodeTag>
      </PreTag>
    );
  };
}
<|endoftext|>


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

  angular.module('condor.crop', []);

  angular
    .module('condor.crop')
    .directive('crop', function() {
      return {
        restrict: 'EA',
        replace: true,
        scope: {
          src: '=',
          x: '@',
          y: '@'
        },
        template:
          '
'+
            '
'+
              '
'+
                  ''+
              '
'+
            '
'+
            '
'+
              '
'+
                '<button ng-click="crop()" class="btn btn-primary">  crop image</button>'+
              '
'+
            '
'+
          '
',
        link: function(scope, element, attribute) {
          var selfMutated = false;
          scope.uncropped = true;
          scope.x = isNaN(Number(scope.x)) || scope.x === '' ? 16 : Number(scope.x);
          scope.y = isNaN(Number(scope.y)) || scope.y === '' ? 9 : Number(scope.y);

          var unregisterListener = scope.$watch('src', function(newVal, oldVal) {
            if(selfMutated === true) {
              selfMutated = false;
            }

            else {
              scope.uncropped = true;
              $($('img', element)[0]).cropper('destroy');
              $($('img', element)[0]).cropper({
                aspectRatio: scope.x / scope.y,
                guides: false,
                rotatable: false,
                wheelZoomRatio: 0.01,
                autoCropArea: 1,
                built: function() {
                  scope.$apply(function() {
                    selfMutated = true;
                    scope.src = $($('img', element)[0]).cropper('getCroppedCanvas').toDataURL();
                  });
                }
              });
            }
          });

          scope.crop = function() {
            selfMutated = true;
            scope.src = $($('img', element)[0]).cropper('getCroppedCanvas').toDataURL();
            $($('img', element)[0]).cropper('destroy');
            scope.uncropped = false;
          };

          scope.$on('$destroy', function() {
            unregisterListener();
            $($('img', element)[0]).cropper('destroy');
          });
        }
      };
    });
})(window.angular);
<commit_msg>AFTER destroy<commit_after>;(function(angular) {
  'use strict';

  angular.module('condor.crop', []);

  angular
    .module('condor.crop')
    .directive('crop', function() {
      return {
        restrict: 'EA',
        replace: true,
        scope: {
          src: '=',
          x: '@',
          y: '@'
        },
        template:
          '
'+
            '
'+
              '
'+
                  ''+
              '
'+
            '
'+
            '
 0">'+
              '
'+
                '<button ng-click="crop()" class="btn btn-primary">  crop image</button>'+
              '
'+
            '
'+
          '
',
        link: function(scope, element, attribute) {
          /**
           * since we're mutating the data we're watching, after we self-mutate
           * we'll not be listing for any changes for the next 500ms
           */
          var _restSelfMutatedFlag = function() {
            var _selfie = setTimeout(function() {
              selfMutated = false;
              clearTimeout(_selfie);
            }, 500);
          };
          var selfMutated = false;
          scope.uncropped = true;
          scope.x = isNaN(Number(scope.x)) || scope.x === '' ? 16 : Number(scope.x);
          scope.y = isNaN(Number(scope.y)) || scope.y === '' ? 9 : Number(scope.y);

          var unregisterListener = scope.$watch('src', function(newVal, oldVal) {
            if(selfMutated === false) {
              scope.uncropped = true;
              $($('img', element)[0]).cropper('destroy');
              $($('img', element)[0]).attr({src: scope.src});
              $($('img', element)[0]).cropper({
                aspectRatio: scope.x / scope.y,
                guides: false,
                rotatable: false,
                wheelZoomRatio: 0.01,
                autoCropArea: 1,
                built: function() {
                  scope.$apply(function() {
                    selfMutated = true;
                    // assigning here doesn't affect the crop view's source
                    // since it's *outside* the digest cycle
                    scope.src = $($('img', element)[0]).cropper('getCroppedCanvas').toDataURL();
                    _restSelfMutatedFlag();
                  });
                }
              });
            }
          });

          scope.crop = function() {
            try {
              var newSrc = $($('img', element)[0]).cropper('getCroppedCanvas').toDataURL();
              selfMutated = true;
              scope.src = newSrc;
              $($('img', element)[0]).cropper('destroy');
              $($('img', element)[0]).attr({src: scope.src});
              _restSelfMutatedFlag();
            } catch(e) {
              console.warn('an invalid src was given, please make sure the image src is properly encoded i.e. to `DataURL`');
            }

            scope.uncropped = false;
          };

          scope.$on('$destroy', function() {
            unregisterListener();
            $($('img', element)[0]).cropper('destroy');
          });
        }
      };
    });
})(window.angular);
<|endoftext|>


<commit_before>function animateNode(node){
    var nodes = cy.$('node');
    var edges = cy.$('edge');

    //first normalizing all nodes and fading all nodes and edges
    normalizingNodes(nodes);
    fadingNodes(nodes);
    fadingEdges(edges);

    //then appearing the chosen node and the connected nodes and edges
    appearingNodes(node);
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() == node.id()){
            appearingEdges(edge);
            appearingNodes(target);
        }
        if (target.id() == node.id()){
            appearingEdges(edge);
            appearingNodes(source);
        }
    });

    //then animate the chosen node
    node.animate({
        css: { 'width':250, 'height':50 }
    }, {
        duration: 300
    })
    // set font style here for better animation (instead of in animate function).
    node.css('font-size', 14);
    node.css('font-weight', 'bolder');
    if (node.data().name != 'Hidden item')
        node.css('color', '#0000e5');
    node.select();
}

function displayNodeInfo(node){
    var html = "
Chosen item
"
    html += "
";
    var item_data = node.data();
    html += itemInfo(item_data);
    html += '
';

    html += '
';

    html += "
Connected items
";
    html += "
";
    var connected_nodes = connectedNodes(node);
    for(var i=0;i<connected_nodes.length;i++){
        var item_data = connected_nodes[i].data();
        html += itemInfo(item_data);
    }

    html += '
';

    var node_info = $('node_info');
    $('node_info').innerHTML = html;

    //can not use Effect.Appear here, it does not activate clientHeight
    node_info.style['display'] = 'block';
    alignCenterVertical(node_info, node_info.clientHeight);
}

function itemInfo(item_data){
    html = '
';
    if (item_data.name == 'Hidden item'){
        html += item_data.hidden_item_info;
    }else{
        html += item_data.link;
    }
    html += '
';
    return html;
}

function connectedNodes(node){
    var edges = cy.$('edge');
    var connected_nodes = [];
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() == node.id()){
            connected_nodes.push(target);
        }
        if (target.id() == node.id()){
            connected_nodes.push(source);
        }
    });
    return connected_nodes;
}

function processPanzoom() {
    //display panzoom
    $j('#cy').cytoscapePanzoom({
        panSpeed: 1
    });

    //set again the graph height if panzoom height is bigger
    var panzoom_height = 220;
    var graph_height = cy.container().style.height.split('px')[0];
    cy.container().style.height = Math.max(graph_height, panzoom_height) +'px';

    alignCenterVertical($j('.ui-cytoscape-panzoom')[0], panzoom_height);

    //reset on panzoom also reset all nodes and edges css
    $j('.ui-cytoscape-panzoom-reset').click(function () {
        var nodes = cy.$('node')
        normalizingNodes(nodes);
        appearingNodes(nodes);
        appearingEdges(cy.$('edge'));
        Effect.Fade('node_info', { duration: 0.25 });
    });
}

function alignCenterVertical(element, element_height){
    var graph_height = cy.container().style.height.split('px')[0];
    var distance_from_top = (graph_height - element_height)/2;
    if (distance_from_top > 0){
        element.style['top']=distance_from_top+'px';
    }else{
        element.style['top']='0px';
    }
}

function appearingNodes(nodes){
    nodes.css('opacity', 1);
}

function appearingEdges(edges){
    edges.css('opacity', 1);
}

function fadingNodes(nodes){
    nodes.css('opacity', 0.3);
}

function fadingEdges(edges){
    edges.css('opacity', 0.2);
}

function normalizingNodes(nodes){
    nodes.css('width',default_node_width);
    nodes.css('height',default_node_height);
    nodes.css('font-size',default_font_size);
    nodes.css('font-weight', 'normal');
    nodes.css('color',default_color);
    nodes.unselect();
}

function resizeGraph(){
    cy.fit(50);
    if (cy.zoom() > 1){
        cy.reset();
        cy.center();
    }
}

function labelPosition(node){
    var label_pos = new Object();
    var graph_pos = $j('#cy')[0].getBoundingClientRect();
    var node_posX = node.renderedPosition().x + graph_pos.left;
    var node_posY = node.renderedPosition().y + graph_pos.top;
    var font_size = node.renderedCss()['font-size'];
    var label = node.data().name;
    var ruler = $j('#ruler')[0];
    ruler.style.fontSize = font_size;
    ruler.style.fontWeight = 'bolder';
    ruler.innerHTML = label;
    var zoom_level = cy.zoom();
    var label_width = ruler.offsetWidth + 2*zoom_level;
    var label_height = ruler.offsetHeight;
    label_pos.minX = node_posX - label_width/2;
    label_pos.maxX = node_posX + label_width/2;
    label_pos.minY = node_posY - label_height/2;
    label_pos.maxY = node_posY + label_height/2;
    return label_pos;
}

function mouseOnLabel(node, mouse_event){
    var label_pos = labelPosition(node);
    var mouse_posX = mouse_event.clientX;
    var mouse_posY = mouse_event.clientY;
    var mouse_on_label = mouse_posX > label_pos.minX && mouse_posX < label_pos.maxX && mouse_posY > label_pos.minY && mouse_posY < label_pos.maxY;
    return mouse_on_label;
}

function clickLabelLink(node, mouse_event){
    if (mouseOnLabel(node, mouse_event)){
        var link = document.createElement('a');
        link.href = node.data().link.split('"')[1];
        clickLink(link);
    }
}

function disableMouseWheel(){
    var canvas_render = cy.renderer();
    var bindings = canvas_render.bindings;
    for( var i=0; i<bindings.length; i++){
        binding = bindings[i];
        var event = binding.event;
        if (event.match(/wheel/i) != null || event.match(/scroll/i) !=null){
            binding.target.removeEventListener(event, binding.handler, binding.useCapture);
        }
    }
}<commit_msg>Quyen's fix for hidden items in ISA graph should not be clickable (6f311286a967)<commit_after>function animateNode(node){
    var nodes = cy.$('node');
    var edges = cy.$('edge');

    //first normalizing all nodes and fading all nodes and edges
    normalizingNodes(nodes);
    fadingNodes(nodes);
    fadingEdges(edges);

    //then appearing the chosen node and the connected nodes and edges
    appearingNodes(node);
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() == node.id()){
            appearingEdges(edge);
            appearingNodes(target);
        }
        if (target.id() == node.id()){
            appearingEdges(edge);
            appearingNodes(source);
        }
    });

    //then animate the chosen node
    node.animate({
        css: { 'width':250, 'height':50 }
    }, {
        duration: 300
    })
    // set font style here for better animation (instead of in animate function).
    node.css('font-size', 14);
    node.css('font-weight', 'bolder');
    if (node.data().name != 'Hidden item')
        node.css('color', '#0000e5');
    node.select();
}

function displayNodeInfo(node){
    var html = "
Chosen item
"
    html += "
";
    var item_data = node.data();
    html += itemInfo(item_data);
    html += '
';

    html += '
';

    html += "
Connected items
";
    html += "
";
    var connected_nodes = connectedNodes(node);
    for(var i=0;i<connected_nodes.length;i++){
        var item_data = connected_nodes[i].data();
        html += itemInfo(item_data);
    }

    html += '
';

    var node_info = $('node_info');
    $('node_info').innerHTML = html;

    //can not use Effect.Appear here, it does not activate clientHeight
    node_info.style['display'] = 'block';
    alignCenterVertical(node_info, node_info.clientHeight);
}

function itemInfo(item_data){
    html = '
';
    if (item_data.name == 'Hidden item'){
        html += item_data.hidden_item_info;
    }else{
        html += item_data.link;
    }
    html += '
';
    return html;
}

function connectedNodes(node){
    var edges = cy.$('edge');
    var connected_nodes = [];
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() == node.id()){
            connected_nodes.push(target);
        }
        if (target.id() == node.id()){
            connected_nodes.push(source);
        }
    });
    return connected_nodes;
}

function processPanzoom() {
    //display panzoom
    $j('#cy').cytoscapePanzoom({
        panSpeed: 1
    });

    //set again the graph height if panzoom height is bigger
    var panzoom_height = 220;
    var graph_height = cy.container().style.height.split('px')[0];
    cy.container().style.height = Math.max(graph_height, panzoom_height) +'px';

    alignCenterVertical($j('.ui-cytoscape-panzoom')[0], panzoom_height);

    //reset on panzoom also reset all nodes and edges css
    $j('.ui-cytoscape-panzoom-reset').click(function () {
        var nodes = cy.$('node')
        normalizingNodes(nodes);
        appearingNodes(nodes);
        appearingEdges(cy.$('edge'));
        Effect.Fade('node_info', { duration: 0.25 });
    });
}

function alignCenterVertical(element, element_height){
    var graph_height = cy.container().style.height.split('px')[0];
    var distance_from_top = (graph_height - element_height)/2;
    if (distance_from_top > 0){
        element.style['top']=distance_from_top+'px';
    }else{
        element.style['top']='0px';
    }
}

function appearingNodes(nodes){
    nodes.css('opacity', 1);
}

function appearingEdges(edges){
    edges.css('opacity', 1);
}

function fadingNodes(nodes){
    nodes.css('opacity', 0.3);
}

function fadingEdges(edges){
    edges.css('opacity', 0.2);
}

function normalizingNodes(nodes){
    nodes.css('width',default_node_width);
    nodes.css('height',default_node_height);
    nodes.css('font-size',default_font_size);
    nodes.css('font-weight', 'normal');
    nodes.css('color',default_color);
    nodes.unselect();
}

function resizeGraph(){
    cy.fit(50);
    if (cy.zoom() > 1){
        cy.reset();
        cy.center();
    }
}

function labelPosition(node){
    var label_pos = new Object();
    var graph_pos = $j('#cy')[0].getBoundingClientRect();
    var node_posX = node.renderedPosition().x + graph_pos.left;
    var node_posY = node.renderedPosition().y + graph_pos.top;
    var font_size = node.renderedCss()['font-size'];
    var label = node.data().name;
    var ruler = $j('#ruler')[0];
    ruler.style.fontSize = font_size;
    ruler.style.fontWeight = 'bolder';
    ruler.innerHTML = label;
    var zoom_level = cy.zoom();
    var label_width = ruler.offsetWidth + 2*zoom_level;
    var label_height = ruler.offsetHeight;
    label_pos.minX = node_posX - label_width/2;
    label_pos.maxX = node_posX + label_width/2;
    label_pos.minY = node_posY - label_height/2;
    label_pos.maxY = node_posY + label_height/2;
    return label_pos;
}

function mouseOnLabel(node, mouse_event){
    var label_pos = labelPosition(node);
    var mouse_posX = mouse_event.clientX;
    var mouse_posY = mouse_event.clientY;
    var mouse_on_label = mouse_posX > label_pos.minX && mouse_posX < label_pos.maxX && mouse_posY > label_pos.minY && mouse_posY < label_pos.maxY;
    return mouse_on_label;
}

function clickLabelLink(node, mouse_event){
    if (node.data().name != "Hidden item"){
        if (mouseOnLabel(node, mouse_event)){
            var link = document.createElement('a');
            link.href = node.data().link.split('"')[1];
            clickLink(link);
        }
    }
}

function disableMouseWheel(){
    var canvas_render = cy.renderer();
    var bindings = canvas_render.bindings;
    for( var i=0; i<bindings.length; i++){
        binding = bindings[i];
        var event = binding.event;
        if (event.match(/wheel/i) != null || event.match(/scroll/i) !=null){
            binding.target.removeEventListener(event, binding.handler, binding.useCapture);
        }
    }
}<|endoftext|>


<commit_before>
$(function() {

$('body').prepend(
	'
' + document.title + '
' +
	'

' +
	'

' +
	'

'
);

});

function testWidgetDefaults(widget, defaults) {
    var pluginDefaults = $.extend({},
        $.widget.defaults,
        $.ui[widget].defaults
    );

    // ensure that all defualts have the correct value
    test('defined defaults', function() {
        $.each(defaults, function(key, val) {
            same(pluginDefaults[key], val, key);
        });
    });

    // ensure that all defaults were tested
    test('tested defaults', function() {
        $.each(pluginDefaults, function(key) {
            ok(key in defaults, key);
        });
    });

    // defaults after init
    test('defaults on init', function() {
        var el = $('
')[widget](),
            instance = el.data(widget);

        $.each(defaults, function(key, val) {
            same(instance.options[key], val, key);
        });
        el.remove();
    });
}

function testSettingOptions(widget, options) {
    test('option values', function() {
        var el = $('
')[widget](),
            instance = el.data(widget);

        $.each(options, function(i, option) {
            $.each({
                'null': null,
                'false': false,
                'true': true,
                zero: 0,
                number: 1,
                'empty string': '',
                string: 'string',
                'empty array': [],
                array: ['array'],
                'empty object': {},
                object: {obj: 'ect'},
                date: new Date(),
                regexp: /regexp/,
                'function': function() {}
            }, function(type, val) {
                el[widget]('option', option, val);
                same(instance.options[option], val, option + ': ' + type);
            });
        });
    });
}

function testWidgetOverrides(widget) {
    test('$.widget overrides', function() {
        $.each(['option', '_getData', '_trigger'], function(i, method) {
            ok($.widget.prototype[method] == $.ui[widget].prototype[method],
                'should not override ' + method);
        });
    });
}
function commonWidgetTests(widget, settings) {
    var options = [];
    $.each(settings.defaults, function(option) {
        options.push(option);
    });

	module(widget + ": common widget");

    testWidgetDefaults(widget, settings.defaults);
    testSettingOptions(widget, options);
    testWidgetOverrides(widget);
}
<commit_msg>whitespace<commit_after>
$(function() {

$('body').prepend(
	'
' + document.title + '
' +
	'

' +
	'

' +
	'

'
);

});

function testWidgetDefaults(widget, defaults) {
	var pluginDefaults = $.extend({},
		$.widget.defaults,
		$.ui[widget].defaults
	);

	// ensure that all defualts have the correct value
	test('defined defaults', function() {
		$.each(defaults, function(key, val) {
			same(pluginDefaults[key], val, key);
		});
	});

	// ensure that all defaults were tested
	test('tested defaults', function() {
		$.each(pluginDefaults, function(key) {
			ok(key in defaults, key);
		});
	});

	// defaults after init
	test('defaults on init', function() {
		var el = $('
')[widget](),
			instance = el.data(widget);

		$.each(defaults, function(key, val) {
			same(instance.options[key], val, key);
		});
		el.remove();
	});
}

function testSettingOptions(widget, options) {
	test('option values', function() {
		var el = $('
')[widget](),
			instance = el.data(widget);

		$.each(options, function(i, option) {
			$.each({
				'null': null,
				'false': false,
				'true': true,
				zero: 0,
				number: 1,
				'empty string': '',
				string: 'string',
				'empty array': [],
				array: ['array'],
				'empty object': {},
				object: {obj: 'ect'},
				date: new Date(),
				regexp: /regexp/,
				'function': function() {}
			}, function(type, val) {
				el[widget]('option', option, val);
				same(instance.options[option], val, option + ': ' + type);
			});
		});
	});
}

function testWidgetOverrides(widget) {
	test('$.widget overrides', function() {
		$.each(['option', '_getData', '_trigger'], function(i, method) {
			ok($.widget.prototype[method] == $.ui[widget].prototype[method],
				'should not override ' + method);
		});
	});
}
function commonWidgetTests(widget, settings) {
	var options = [];
	$.each(settings.defaults, function(option) {
		options.push(option);
	});

	module(widget + ": common widget");

	testWidgetDefaults(widget, settings.defaults);
	testSettingOptions(widget, options);
	testWidgetOverrides(widget);
}
<|endoftext|>