<commit_before>// spice callback function
function ddg_spice_quixey (api_result) {

    if (api_result.result_count == 0) return;

    var q = api_result.q.replace(/\s/g, '+');

    Spice.render({
        data: api_result,
        source_name: 'Quixey',
        source_url: 'https://www.quixey.com/search?q=' + q,     //api_result.q,
        header1: api_result.q + ' (App Search)',
        force_big_header: true,

        more_logo: "quixey_logo.png",

        template_frame: "carousel",                 // zci type
        template_normal: "quixey",                  // item template
        carousel_css_id: "quixey",                  // the div used for the carousel
        carousel_template_detail: "quixey_detail",  // detail view template
        carousel_items: Handlebars.helpers.organize(api_result.results) // item array
    });
}

(function() {

    // format a price
    // p is expected to be a number
    function qprice(p) {
        if (p == 0) {    // == type coercion is ok here
            return "FREE";
        }

        return "$" + (p/100).toFixed(2).toString();
    }

    // Check for relevant app results
    Handlebars.registerHelper("organize", function(results) {

        var res,
            apps = [],
            backupApps = [],
            categories = /action|adventure|arcade|board|business|casino|design|developer tools|dice|education|educational|entertainment|family|finance|graphics|graphics and design|health and fitness|kids|lifestyle|medical|music|networking|news|photography|productivity|puzzle|racing|role playing|simulation|social networking|social|sports|strategy|travel|trivia|utilities|video|weather/i,
            skip_words = [
                "app",
                "apps",
                "application",
                "applications",
                "android",
                "droid",
                "google play store",
                "google play",
                "windows phone",
                "windows phone 8",
                "windows mobile",
                "blackberry",
                "apple app store",
                "apple app",
                "ipod touch",
                "ipod",
                "iphone",
                "ipad",
                "ios",
                "free",
                "search"
            ];

        for (var i = 0; i < results.length; i++) {

            app = results[i];

            // check if this app result is relevant
            if (DDG.isRelevant(app.name.toLowerCase(), skip_words)) {
                apps.push(app);
            } else if (app.hasOwnProperty("short_desc") &&
                       DDG.isRelevant(app.short_desc.toLowerCase(), skip_words)) {
                            backupApps.push(app);
            } else if (app.custom.hasOwnProperty("category") &&
                       DDG.isRelevant(app.custom.category.toLowerCase(), skip_words)) {
                            backupApps.push(app);
            } else{
                continue;
            }
        }

        // Return highly relevant results
        if (apps.length > 0) {
            res = apps;
        }

        // Return mostly relevant results
        else if (backupApps.length > 0) {
            res = backupApps;
        }

        else {

            // No relevant results,
            // check if it was a categorical search
            // Eg."social apps for android"
            var q = DDG.get_query();
            res = q.match(categories) ? results : null;
        }
        return res;
    });

    // template helper for price formatting
    // {{price x}}
    Handlebars.registerHelper("price", function(obj) {
        return qprice(obj);
    });

    // template helper to format a price range
    Handlebars.registerHelper("pricerange", function(obj) {

        if (!this.editions)
            return "";

        var low  = this.editions[0].cents;
        var high = this.editions[0].cents;
        var tmp, range, lowp, highp;

        for (var i in this.editions) {
            tmp = this.editions[i].cents;
            if (tmp < low) low = tmp;
            if (tmp > high) high = tmp;
        }

        lowp = qprice(low);

        if (high > low) {
           highp = qprice(high);
           range = lowp + " - " + highp;
           this.hasPricerange = true;
        } else {
            range = lowp;
        }

        return range;
    });

    // template helper to replace iphone and ipod icons with
    // smaller 'Apple' icons
    Handlebars.registerHelper("platform_icon", function(icon_url) {
        if (this.id === 2004 || this.id === 2015) {
            return "https://icons.duckduckgo.com/i/itunes.apple.com.ico";
        }

        return "/iu/?u=" + icon_url + "&f=1";
    });

		// template helper that returns and unifies platform names
		Handlebars.registerHelper("platform_name", function() {
        var name;
        var platforms = this.platforms;

        name = platforms[0].name;

        if (platforms.length > 1) {
            switch (platforms[0].name) {
                case "iPhone" :
                case "iPad" :
                    name = "iOS";
                    break;

                case "Blackberry":
                case "Blackberry 10":
                    name = "Blackberry";
                    break;
            }
        }

        return name;
    });

    // template helper to give url for star icon
    Handlebars.registerHelper("quixey_star", function() {
        return DDG.get_asset_path("quixey", "star.png").replace("//", "/");
    });
})();<commit_msg>Quixey - added check before render() for relevant results<commit_after>// spice callback function
function ddg_spice_quixey (api_result) {

    if (api_result.result_count == 0) return;

    var q = api_result.q.replace(/\s/g, '+');

		var relevants = Handlebars.helpers.organize(api_result.results);

		if (!relevants) return;

		Spice.render({
        data: api_result,
        source_name: 'Quixey',
        source_url: 'https://www.quixey.com/search?q=' + q,     //api_result.q,
        header1: api_result.q + ' (App Search)',
        force_big_header: true,

        more_logo: "quixey_logo.png",

        template_frame: "carousel",                 // zci type
        template_normal: "quixey",                  // item template
        carousel_css_id: "quixey",                  // the div used for the carousel
        carousel_template_detail: "quixey_detail",  // detail view template
        carousel_items: relevants // item array
    });
}

(function() {

    // format a price
    // p is expected to be a number
    function qprice(p) {
        if (p == 0) {    // == type coercion is ok here
            return "FREE";
        }

        return "$" + (p/100).toFixed(2).toString();
    }

    // Check for relevant app results
    Handlebars.registerHelper("organize", function(results) {

        var res,
            apps = [],
            backupApps = [],
            categories = /action|adventure|arcade|board|business|casino|design|developer tools|dice|education|educational|entertainment|family|finance|graphics|graphics and design|health and fitness|kids|lifestyle|medical|music|networking|news|photography|productivity|puzzle|racing|role playing|simulation|social networking|social|sports|strategy|travel|trivia|utilities|video|weather/i,
            skip_words = [
                "app",
                "apps",
                "application",
                "applications",
                "android",
                "droid",
                "google play store",
                "google play",
                "windows phone",
                "windows phone 8",
                "windows mobile",
                "blackberry",
                "apple app store",
                "apple app",
                "ipod touch",
                "ipod",
                "iphone",
                "ipad",
                "ios",
                "free",
                "search"
            ];

        for (var i = 0; i < results.length; i++) {

            app = results[i];

            // check if this app result is relevant
            if (DDG.isRelevant(app.name.toLowerCase(), skip_words)) {
                apps.push(app);
            } else if (app.hasOwnProperty("short_desc") &&
                       DDG.isRelevant(app.short_desc.toLowerCase(), skip_words)) {
                            backupApps.push(app);
            } else if (app.custom.hasOwnProperty("category") &&
                       DDG.isRelevant(app.custom.category.toLowerCase(), skip_words)) {
                            backupApps.push(app);
            } else{
                continue;
            }
        }

        // Return highly relevant results
        if (apps.length > 0) {
            res = apps;
        }

        // Return mostly relevant results
        else if (backupApps.length > 0) {
            res = backupApps;
        }

        else {

            // No relevant results,
            // check if it was a categorical search
            // Eg."social apps for android"
            var q = DDG.get_query();
            res = q.match(categories) ? results : null;
        }
        return res;
    });

    // template helper for price formatting
    // {{price x}}
    Handlebars.registerHelper("price", function(obj) {
        return qprice(obj);
    });

    // template helper to format a price range
    Handlebars.registerHelper("pricerange", function(obj) {

        if (!this.editions)
            return "";

        var low  = this.editions[0].cents;
        var high = this.editions[0].cents;
        var tmp, range, lowp, highp;

        for (var i in this.editions) {
            tmp = this.editions[i].cents;
            if (tmp < low) low = tmp;
            if (tmp > high) high = tmp;
        }

        lowp = qprice(low);

        if (high > low) {
           highp = qprice(high);
           range = lowp + " - " + highp;
           this.hasPricerange = true;
        } else {
            range = lowp;
        }

        return range;
    });

    // template helper to replace iphone and ipod icons with
    // smaller 'Apple' icons
    Handlebars.registerHelper("platform_icon", function(icon_url) {
        if (this.id === 2004 || this.id === 2015) {
            return "https://icons.duckduckgo.com/i/itunes.apple.com.ico";
        }

        return "/iu/?u=" + icon_url + "&f=1";
    });

		// template helper that returns and unifies platform names
		Handlebars.registerHelper("platform_name", function() {
        var name;
        var platforms = this.platforms;

        name = platforms[0].name;

        if (platforms.length > 1) {
            switch (platforms[0].name) {
                case "iPhone" :
                case "iPad" :
                    name = "iOS";
                    break;

                case "Blackberry":
                case "Blackberry 10":
                    name = "Blackberry";
                    break;
            }
        }

        return name;
    });

    // template helper to give url for star icon
    Handlebars.registerHelper("quixey_star", function() {
        return DDG.get_asset_path("quixey", "star.png").replace("//", "/");
    });
})();<|endoftext|>


<commit_before>/**
 * Graph.js
 *
 * @author Andrew Bowler, Alberto Gomez-Estrada
 */

'use strict';

var React = require('react');
var ReactDOM = require('react-dom');
var Vis = require('vis');

var Graph = React.createClass({
  componentDidMount: function() {
    var element = ReactDOM.findDOMNode(this);
    this.setState({
      network: new Vis.Network(element, this.props.graphData, this.props.options)
    });
  },

  hasFilterOptions: function() {
    if (this.props.filter) {
      return this.props.filter.property && this.props.filter.option && this.props.filter.value;
    } else return false;
  },

  /**
   * If there are any filter options passed in, perform filtering. Otherwise do nothing.
   */
  doFilter: function() {
    if(this.hasFilterOptions() && !this.isGraphEmpty()) {
      var property = this.props.filter.property;
      var nodeObjects = this.props.graphData.nodes;
      console.log(nodeObjects);
      var nodeIDs = this.props.graphData.nodes.get({returnType: 'Object'});
      switch (this.props.filter.option) {
        case '>':
          for (var nodeID in nodeIDs) {
            if (this.props.graphData.nodes.get(nodeID)[property] > this.props.filter.value) {
              console.log(nodeObjects.get(nodeID));
              nodeObjects.update({id: nodeID, color: 'red'});
              console.log(nodeObjects.get(nodeID));
            }
          }
          break;
        default:
          break;
      }
    }
  },

  isGraphEmpty: function() {
    return this.props.graphData.nodes.length == 0 && this.props.graphData.edges.length == 0;
  },

  shouldComponentUpdate: function(nextProps, nextState) {
    return (this.props.graphData != nextProps.graphData) || (this.props.filter != nextProps.filter);
  },

  componentDidUpdate: function() {
    this.state.network.setData({
      nodes: this.props.graphData.nodes,
      edges: this.props.graphData.edges
    });

    this.doFilter();

    this.state.network.on('selectNode', function(event) {
      var nodeID = event.nodes[0];
      var node = this.state.network.body.data.nodes.get(nodeID);
      this.props.updateSelectedNode(node);
    }.bind(this));

    // Called when Vis is finished drawing the graph
    this.state.network.on('afterDrawing', function(event) {
      this.props.logger('Graph finished drawing');
    }.bind(this));
  },

  getDefaultProps: function() {
    return {
      options: {
        nodes: {
          shape: 'dot',
          fixed: true
        },
        edges: {
          arrows: {
            to: {
              scaleFactor: 0.5
            }
          },
          smooth: {
            type: 'continuous'
          }
        },
        physics: false,
        interaction: {
          dragNodes: false,
        }
      }
    }
  },

  getInitialState: function() {
    return {
      network: {}
    };
  },

  render: function() {
    return (

);
  }
});

module.exports = Graph;
<commit_msg>Fix integer parsing that gave incorrect results<commit_after>/**
 * Graph.js
 *
 * @author Andrew Bowler, Alberto Gomez-Estrada
 */

'use strict';

var React = require('react');
var ReactDOM = require('react-dom');
var Vis = require('vis');

var Graph = React.createClass({
  componentDidMount: function() {
    var element = ReactDOM.findDOMNode(this);
    this.setState({
      network: new Vis.Network(element, this.props.graphData, this.props.options)
    });
  },

  hasFilterOptions: function() {
    if (this.props.filter) {
      return this.props.filter.property && this.props.filter.option && this.props.filter.value;
    } else return false;
  },

  /**
   * If there are any filter options passed in, perform filtering. Otherwise do nothing.
   */
  doFilter: function() {
    if(this.hasFilterOptions() && !this.isGraphEmpty()) {
      var property = this.props.filter.property;
      var nodeObjects = this.props.graphData.nodes;
      var nodeIDs = this.props.graphData.nodes.get({returnType: 'Object'});
      switch (this.props.filter.option) {
        case '>':
          for (var nodeID in nodeIDs) {
            var propertyToFilter = this.props.graphData.nodes.get(nodeID)[property];
            if (parseInt(propertyToFilter) > this.props.filter.value)
              nodeObjects.update({id: nodeID, color: 'red'});
            else
              nodeObjects.update({id: nodeID, color: 'gray'});
          }
          break;
        default:
          break;
      }
    }
  },

  isGraphEmpty: function() {
    return this.props.graphData.nodes.length == 0 && this.props.graphData.edges.length == 0;
  },

  shouldComponentUpdate: function(nextProps, nextState) {
    return (this.props.graphData != nextProps.graphData) || (this.props.filter != nextProps.filter);
  },

  componentDidUpdate: function() {
    this.state.network.setData({
      nodes: this.props.graphData.nodes,
      edges: this.props.graphData.edges
    });

    this.doFilter();

    this.state.network.on('selectNode', function(event) {
      var nodeID = event.nodes[0];
      var node = this.state.network.body.data.nodes.get(nodeID);
      this.props.updateSelectedNode(node);
    }.bind(this));

    // Called when Vis is finished drawing the graph
    this.state.network.on('afterDrawing', function(event) {
      this.props.logger('Graph finished drawing');
    }.bind(this));
  },

  getDefaultProps: function() {
    return {
      options: {
        nodes: {
          shape: 'dot',
          fixed: true
        },
        edges: {
          arrows: {
            to: {
              scaleFactor: 0.5
            }
          },
          color: '#848484',
          smooth: {
            type: 'continuous'
          }
        },
        physics: false,
        interaction: {
          dragNodes: false,
        }
      }
    }
  },

  getInitialState: function() {
    return {
      network: {}
    };
  },

  render: function() {
    return (

);
  }
});

module.exports = Graph;
<|endoftext|>


<commit_before>import Field from '../Field';
import React from 'react';
import { FormField, FormInput, FormRow } from 'elemental';

module.exports = Field.create({

	displayName: 'NameField',

	focusTargetRef: 'first',

	valueChanged: function (which, event) {
		this.props.value[which] = event.target.value;
		this.props.onChange({
			path: this.props.path,
			value: this.props.value,
		});
	},

	renderValue () {
		return (
			<FormRow>
				<FormField width="one-half">
					<FormInput noedit style={{ width: '100%' }}>{this.props.value.first}</FormInput>
				</FormField>
				<FormField width="one-half">
					<FormInput noedit style={{ width: '100%' }}>{this.props.value.last}</FormInput>
				</FormField>
			</FormRow>
		);
	},

	renderField () {
		return (
			<FormRow>
				<FormField width="one-half">
					<FormInput name={this.props.paths.first} placeholder="First name" ref="first" value={this.props.value.first} onChange={this.valueChanged.bind(this, 'first')} autoComplete="off" />
				</FormField>
				<FormField width="one-half">
					<FormInput name={this.props.paths.last} placeholder="Last name" ref="last" value={this.props.value.last} onChange={this.valueChanged.bind(this, 'last')} autoComplete="off" />
				</FormField>
			</FormRow>
		);
	},

});
<commit_msg>tidy name field<commit_after>import Field from '../Field';
import React, { PropTypes } from 'react';
import { FormField, FormInput, FormRow } from 'elemental';

const NAME_SHAPE = {
	first: PropTypes.string,
	last: PropTypes.string,
};

module.exports = Field.create({
	displayName: 'NameField',
	focusTargetRef: 'first',
	propTypes: {
		onChange: PropTypes.func.isRequired,
		path: PropTypes.string.isRequired,
		paths: PropTypes.shape(NAME_SHAPE).isRequired,
		value: PropTypes.shape(NAME_SHAPE).isRequired,
	},

	valueChanged: function (which, event) {
		this.props.value[which] = event.target.value;
		this.props.onChange({
			path: this.props.path,
			value: this.props.value,
		});
	},
	renderValue () {
		const inputStyle = { width: '100%' };

		return (
			<FormRow>
				<FormField width="one-half">
					<FormInput noedit style={inputStyle}>
						{this.props.value.first}
					</FormInput>
				</FormField>
				<FormField width="one-half">
					<FormInput noedit style={inputStyle}>
						{this.props.value.last}
					</FormInput>
				</FormField>
			</FormRow>
		);
	},
	renderField () {
		return (
			<FormRow>
				<FormField width="one-half">
					<FormInput
						autoComplete="off"
						name={this.props.paths.first}
						onChange={this.valueChanged.bind(this, 'first')}
						placeholder="First name"
						ref="first"
						value={this.props.value.first}
					/>
				</FormField>
				<FormField width="one-half">
					<FormInput
						autoComplete="off"
						name={this.props.paths.last}
						onChange={this.valueChanged.bind(this, 'last')}
						placeholder="Last name"
						ref="last"
						value={this.props.value.last}
					/>
				</FormField>
			</FormRow>
		);
	},
});
<|endoftext|>


<commit_before>window.Chaskiq = {
  Helpers: {}
}
// Custom scripts
$(document).ready(function () {

    // MetsiMenu
    $('#side-menu').metisMenu();

    // Collapse ibox function
    $('.collapse-link').click( function() {
        var ibox = $(this).closest('div.ibox');
        var button = $(this).find('i');
        var content = ibox.find('div.ibox-content');
        content.slideToggle(200);
        button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
        ibox.toggleClass('').toggleClass('border-bottom');
        setTimeout(function () {
            ibox.resize();
            ibox.find('[id^=map-]').resize();
        }, 50);
    });

    // Close ibox function
    $('.close-link').click( function() {
        var content = $(this).closest('div.ibox');
        content.remove();
    });

    // Small todo handler
    $('.check-link').click( function(){
        var button = $(this).find('i');
        var label = $(this).next('span');
        button.toggleClass('fa-check-square').toggleClass('fa-square-o');
        label.toggleClass('todo-completed');
        return false;
    });

    // Append config box / Only for demo purpose
//    $.get("skin-config.html", function (data) {
//        $('body').append(data);
//    });

    // minimalize menu
    $('.navbar-minimalize').click(function () {
        $("body").toggleClass("mini-navbar");
        SmoothlyMenu();
    })

    // tooltips
    $('.tooltip-demo').tooltip({
        selector: "[data-toggle=tooltip]",
        container: "body"
    })

    // Move modal to body
    // Fix Bootstrap backdrop issu with animation.css
    $('.modal').appendTo("body")

    // Full height of sidebar
    function fix_height() {
        var heightWithoutNavbar = $("body > #wrapper").height() - 61;
        $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px");
    }
    fix_height();

    // Fixed Sidebar
    // unComment this only whe you have a fixed-sidebar
    //    $(window).bind("load", function() {
    //        if($("body").hasClass('fixed-sidebar')) {
    //            $('.sidebar-collapse').slimScroll({
    //                height: '100%',
    //                railOpacity: 0.9,
    //            });
    //        }
    //    })

    $(window).bind("load resize click scroll", function() {
        if(!$("body").hasClass('body-small')) {
            fix_height();
        }
    })

    $("[data-toggle=popover]")
        .popover();

    $('.input-group.date').datepicker({
      todayBtn: "linked",
      keyboardNavigation: false,

    });
});

// For demo purpose - animation css script
function animationHover(element, animation){
    element = $(element);
    element.hover(
        function() {
            element.addClass('animated ' + animation);
        },
        function(){
            //wait for animation to finish before removing classes
            window.setTimeout( function(){
                element.removeClass('animated ' + animation);
            }, 2000);
        });
}

// Minimalize menu when screen is less than 768px
$(function() {
    $(window).bind("load resize", function() {
        if ($(this).width() < 769) {
            $('body').addClass('body-small')
        } else {
            $('body').removeClass('body-small')
        }
    })
})

function SmoothlyMenu() {
    if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) {
        // Hide menu in order to smoothly turn on when maximize menu
        $('#side-menu').hide();
        // For smoothly turn on menu
        setTimeout(
            function () {
                $('#side-menu').fadeIn(400);
            }, 100);
    } else if ($('body').hasClass('fixed-sidebar')){
        $('#side-menu').hide();
        setTimeout(
            function () {
                $('#side-menu').fadeIn(400);
            }, 300);
    } else {
        // Remove all inline style from jquery fadeIn function to reset menu state
        $('#side-menu').removeAttr('style');
    }
}

var sendFile;

sendFile = function(file, callback) {
  var data;
  data = new FormData();
  data.append("image", file);
  return $.ajax({
    url: $('.summernote').data('upload-path'),
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data) {
      return callback(data);
    }
  });
};

window.InitSummernote = function(){
    $('.summernote').summernote({
      toolbar: [
        ['style', ['color', 'bold', 'italic', 'underline', 'fontsize']],
        ['font', ['strikethrough']],
        ['insert', ['picture', 'link']],
        ['fontsize', ['fontsize']],
        ['para', ['ul', 'ol', 'paragraph']],
      ]
    , onImageUpload: function(files, editor, $editable) {
        sendFile(files[0], function(data){
          url = data.image.url
          console.log($editable)
          console.log(url)
          editor.insertImage($editable, url)
        })
        //console.log('image upload:', files, editor, $editable);
      }
    });
}

<commit_msg>clean js<commit_after>window.Chaskiq = {
  Helpers: {}
}
// Custom scripts
$(document).ready(function () {

    // Close ibox function
    $('.close-link').click( function() {
        var content = $(this).closest('div.ibox');
        content.remove();
    });

    $("[data-toggle=popover]")
        .popover();

    $('.input-group.date').datepicker({
      todayBtn: "linked",
      keyboardNavigation: false,

    });
});

var sendFile;

sendFile = function(file, callback) {
  var data;
  data = new FormData();
  data.append("image", file);
  return $.ajax({
    url: $('.summernote').data('upload-path'),
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data) {
      return callback(data);
    }
  });
};

window.InitSummernote = function(){
    $('.summernote').summernote({
      toolbar: [
        ['style', ['color', 'bold', 'italic', 'underline', 'fontsize']],
        ['font', ['strikethrough']],
        ['insert', ['picture', 'link']],
        ['fontsize', ['fontsize']],
        ['para', ['ul', 'ol', 'paragraph']],
      ]
    , onImageUpload: function(files, editor, $editable) {
        sendFile(files[0], function(data){
          url = data.image.url
          console.log($editable)
          console.log(url)
          editor.insertImage($editable, url)
        })
        //console.log('image upload:', files, editor, $editable);
      }
    });
}

<|endoftext|>


<commit_before>var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var config = require('./webpack.config.js');
var compiler = webpack(config);

var server = new WebpackDevServer(compiler, {
    contentBase: "./dist",
    stats: {
        colors: true,
    }
});

server.listen(8080, '0.0.0.0', (err, result) => {
    if (err) {
        return console.log(err);
    }
    console.log('Listening at http://0.0.0.0:8080/');
});<commit_msg>chore(webpack): hmr<commit_after>var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var config = require('./webpack.config.js');
var compiler = webpack(config);

var server = new WebpackDevServer(compiler, {
    contentBase: "./dist",
    hot: true,
    stats: {
        colors: true,
    }
});

server.listen(8080, '0.0.0.0', (err, result) => {
    if (err) {
        return console.log(err);
    }
    console.log('Listening at http://0.0.0.0:8080/');
});<|endoftext|>


<commit_before>import * as d3 from 'd3';

import {CompositeChart} from './composite-chart';
import {lineChart} from './line-chart';
import {utils} from '../core/utils';

/**
 * A series chart is a chart that shows multiple series of data overlaid on one chart, where the
 * series is specified in the data. It is a specialization of Composite Chart and inherits all
 * composite features other than recomposing the chart.
 *
 * Examples:
 * - {@link http://dc-js.github.io/dc.js/examples/series.html Series Chart}
 * @class seriesChart
 * @memberof dc
 * @mixes dc.compositeChart
 * @example
 * // create a series chart under #chart-container1 element using the default global chart group
 * var seriesChart1 = dc.seriesChart("#chart-container1");
 * // create a series chart under #chart-container2 element using chart group A
 * var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA");
 * @param {String|node|d3.selection} parent - Any valid
 * {@link https://github.com/d3/d3-selection/blob/master/README.md#select d3 single selector} specifying
 * a dom block element such as a div; or a dom element or d3 selection.
 * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in.
 * Interaction with a chart will only trigger events and redraws within the chart's group.
 * @returns {dc.seriesChart}
 */
export const seriesChart = (parent, chartGroup) => new SeriesChart(parent, chartGroup);

export class SeriesChart extends CompositeChart {
    constructor (parent, chartGroup) {
        super(parent, chartGroup);

        const _chart = this;

        function keySort (a, b) {
            return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b));
        }

        var _charts = {};
        var _chartFunction = lineChart;
        var _seriesAccessor;
        var _seriesSort = d3.ascending;
        var _valueSort = keySort;

        _chart._mandatoryAttributes().push('seriesAccessor', 'chart');
        _chart.shareColors(true);

        _chart._preprocessData = function () {
            var keep = [];
            var childrenChanged;
            var nester = d3.nest().key(_seriesAccessor);
            if (_seriesSort) {
                nester.sortKeys(_seriesSort);
            }
            if (_valueSort) {
                nester.sortValues(_valueSort);
            }
            var nesting = nester.entries(_chart.data());
            var children =
                nesting.map(function (sub, i) {
                    var subChart = _charts[sub.key] || _chartFunction.call(_chart, _chart, chartGroup, sub.key, i);
                    if (!_charts[sub.key]) {
                        childrenChanged = true;
                    }
                    _charts[sub.key] = subChart;
                    keep.push(sub.key);
                    return subChart
                        .dimension(_chart.dimension())
                        .group({
                            all: typeof sub.values === 'function' ? sub.values : utils.constant(sub.values)
                        }, sub.key)
                        .keyAccessor(_chart.keyAccessor())
                        .valueAccessor(_chart.valueAccessor())
                        .brushOn(false);
                });
            // this works around the fact compositeChart doesn't really
            // have a removal interface
            Object.keys(_charts)
                .filter(function (c) {
                    return keep.indexOf(c) === -1;
                })
                .forEach(function (c) {
                    clearChart(c);
                    childrenChanged = true;
                });
            _chart._compose(children);
            if (childrenChanged && _chart.legend()) {
                _chart.legend().render();
            }
        };

        function clearChart (c) {
            if (_charts[c].g()) {
                _charts[c].g().remove();
            }
            delete _charts[c];
        }

        function resetChildren () {
            Object.keys(_charts).map(clearChart);
            _charts = {};
        }

        /**
         * Get or set the chart function, which generates the child charts.
         * @method chart
         * @memberof dc.seriesChart
         * @instance
         * @example
         * // put curve on the line charts used for the series
         * chart.chart(function(c) { return dc.lineChart(c).curve(d3.curveBasis); })
         * // do a scatter series chart
         * chart.chart(dc.scatterPlot)
         * @param {Function} [chartFunction=dc.lineChart]
         * @returns {Function|dc.seriesChart}
         */
        _chart.chart = function (chartFunction) {
            if (!arguments.length) {
                return _chartFunction;
            }
            _chartFunction = chartFunction;
            resetChildren();
            return _chart;
        };

        /**
         * **mandatory**
         *
         * Get or set accessor function for the displayed series. Given a datum, this function
         * should return the series that datum belongs to.
         * @method seriesAccessor
         * @memberof dc.seriesChart
         * @instance
         * @example
         * // simple series accessor
         * chart.seriesAccessor(function(d) { return "Expt: " + d.key[0]; })
         * @param {Function} [accessor]
         * @returns {Function|dc.seriesChart}
         */
        _chart.seriesAccessor = function (accessor) {
            if (!arguments.length) {
                return _seriesAccessor;
            }
            _seriesAccessor = accessor;
            resetChildren();
            return _chart;
        };

        /**
         * Get or set a function to sort the list of series by, given series values.
         * @method seriesSort
         * @memberof dc.seriesChart
         * @instance
         * @see {@link https://github.com/d3/d3-array/blob/master/README.md#ascending d3.ascending}
         * @see {@link https://github.com/d3/d3-array/blob/master/README.md#descending d3.descending}
         * @example
         * chart.seriesSort(d3.descending);
         * @param {Function} [sortFunction=d3.ascending]
         * @returns {Function|dc.seriesChart}
         */
        _chart.seriesSort = function (sortFunction) {
            if (!arguments.length) {
                return _seriesSort;
            }
            _seriesSort = sortFunction;
            resetChildren();
            return _chart;
        };

        /**
         * Get or set a function to sort each series values by. By default this is the key accessor which,
         * for example, will ensure a lineChart series connects its points in increasing key/x order,
         * rather than haphazardly.
         * @method valueSort
         * @memberof dc.seriesChart
         * @instance
         * @see {@link https://github.com/d3/d3-array/blob/master/README.md#ascending d3.ascending}
         * @see {@link https://github.com/d3/d3-array/blob/master/README.md#descending d3.descending}
         * @example
         * // Default value sort
         * _chart.valueSort(function keySort (a, b) {
         *     return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b));
         * });
         * @param {Function} [sortFunction]
         * @returns {Function|dc.seriesChart}
         */
        _chart.valueSort = function (sortFunction) {
            if (!arguments.length) {
                return _valueSort;
            }
            _valueSort = sortFunction;
            resetChildren();
            return _chart;
        };

        // make compose private
        _chart._compose = _chart.compose;
        delete _chart.compose;

        return _chart;
    }
}
<commit_msg>Convert series-chart to ES6 class - part 1<commit_after>import * as d3 from 'd3';

import {CompositeChart} from './composite-chart';
import {lineChart} from './line-chart';
import {utils} from '../core/utils';

/**
 * A series chart is a chart that shows multiple series of data overlaid on one chart, where the
 * series is specified in the data. It is a specialization of Composite Chart and inherits all
 * composite features other than recomposing the chart.
 *
 * Examples:
 * - {@link http://dc-js.github.io/dc.js/examples/series.html Series Chart}
 * @class seriesChart
 * @memberof dc
 * @mixes dc.compositeChart
 * @example
 * // create a series chart under #chart-container1 element using the default global chart group
 * var seriesChart1 = dc.seriesChart("#chart-container1");
 * // create a series chart under #chart-container2 element using chart group A
 * var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA");
 * @param {String|node|d3.selection} parent - Any valid
 * {@link https://github.com/d3/d3-selection/blob/master/README.md#select d3 single selector} specifying
 * a dom block element such as a div; or a dom element or d3 selection.
 * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in.
 * Interaction with a chart will only trigger events and redraws within the chart's group.
 * @returns {dc.seriesChart}
 */
export class SeriesChart extends CompositeChart {
    constructor (parent, chartGroup) {
        super(parent, chartGroup);

        this._keySort = (a, b) => d3.ascending(this.keyAccessor()(a), this.keyAccessor()(b));

        this._charts = {};
        this._chartFunction = lineChart;
        this._seriesAccessor = undefined;
        this._seriesSort = d3.ascending;
        this._valueSort = this._keySort;

        this._mandatoryAttributes().push('seriesAccessor', 'chart');
        this.shareColors(true);

        // ES6: this function has been overridden, actually defined and called in coordinate grid mixin
        // can not be moved out of the constructor before converting as a member function in the base class
        this._preprocessData = function () {
            const keep = [];
            let childrenChanged;
            const nester = d3.nest().key(this._seriesAccessor);
            if (this._seriesSort) {
                nester.sortKeys(this._seriesSort);
            }
            if (this._valueSort) {
                nester.sortValues(this._valueSort);
            }
            const nesting = nester.entries(this.data());
            const children =
                nesting.map((sub, i) => {
                    const subChart = this._charts[sub.key] || this._chartFunction.call(this, this, chartGroup, sub.key, i);
                    if (!this._charts[sub.key]) {
                        childrenChanged = true;
                    }
                    this._charts[sub.key] = subChart;
                    keep.push(sub.key);
                    return subChart
                        .dimension(this.dimension())
                        .group({
                            all: typeof sub.values === 'function' ? sub.values : utils.constant(sub.values)
                        }, sub.key)
                        .keyAccessor(this.keyAccessor())
                        .valueAccessor(this.valueAccessor())
                        .brushOn(false);
                });
            // ES6: do we add removal function in composite chart?
            // this works around the fact compositeChart doesn't really
            // have a removal interface
            const self = this;
            Object.keys(this._charts)
                .filter(c => keep.indexOf(c) === -1)
                .forEach(c => {
                    self._clearChart(c);
                    childrenChanged = true;
                });
            this._compose(children);
            if (childrenChanged && this.legend()) {
                this.legend().render();
            }
        };

        // ES6: consider creating a method _compose that calls super.compose and make overridden compose to throw exception
        // make compose private
        this._compose = this.compose;
        delete this.compose;
    }

    _clearChart (c) {
        if (this._charts[c].g()) {
            this._charts[c].g().remove();
        }
        delete this._charts[c];
    }

    _resetChildren () {
        Object.keys(this._charts).map(this._clearChart);
        this._charts = {};
    }

    /**
     * Get or set the chart function, which generates the child charts.
     * @method chart
     * @memberof dc.seriesChart
     * @instance
     * @example
     * // put curve on the line charts used for the series
     * chart.chart(function(c) { return dc.lineChart(c).curve(d3.curveBasis); })
     * // do a scatter series chart
     * chart.chart(dc.scatterPlot)
     * @param {Function} [chartFunction=dc.lineChart]
     * @returns {Function|dc.seriesChart}
     */
    chart (chartFunction) {
        if (!arguments.length) {
            return this._chartFunction;
        }
        this._chartFunction = chartFunction;
        this._resetChildren();
        return this;
    }

    /**
     * **mandatory**
     *
     * Get or set accessor function for the displayed series. Given a datum, this function
     * should return the series that datum belongs to.
     * @method seriesAccessor
     * @memberof dc.seriesChart
     * @instance
     * @example
     * // simple series accessor
     * chart.seriesAccessor(function(d) { return "Expt: " + d.key[0]; })
     * @param {Function} [accessor]
     * @returns {Function|dc.seriesChart}
     */
    seriesAccessor (accessor) {
        if (!arguments.length) {
            return this._seriesAccessor;
        }
        this._seriesAccessor = accessor;
        this._resetChildren();
        return this;
    }

    /**
     * Get or set a function to sort the list of series by, given series values.
     * @method seriesSort
     * @memberof dc.seriesChart
     * @instance
     * @see {@link https://github.com/d3/d3-array/blob/master/README.md#ascending d3.ascending}
     * @see {@link https://github.com/d3/d3-array/blob/master/README.md#descending d3.descending}
     * @example
     * chart.seriesSort(d3.descending);
     * @param {Function} [sortFunction=d3.ascending]
     * @returns {Function|dc.seriesChart}
     */
    seriesSort (sortFunction) {
        if (!arguments.length) {
            return this._seriesSort;
        }
        this._seriesSort = sortFunction;
        this._resetChildren();
        return this;
    }

    /**
     * Get or set a function to sort each series values by. By default this is the key accessor which,
     * for example, will ensure a lineChart series connects its points in increasing key/x order,
     * rather than haphazardly.
     * @method valueSort
     * @memberof dc.seriesChart
     * @instance
     * @see {@link https://github.com/d3/d3-array/blob/master/README.md#ascending d3.ascending}
     * @see {@link https://github.com/d3/d3-array/blob/master/README.md#descending d3.descending}
     * @example
     * // Default value sort
     * _chart.valueSort(function keySort (a, b) {
     *     return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b));
     * });
     * @param {Function} [sortFunction]
     * @returns {Function|dc.seriesChart}
     */
    valueSort (sortFunction) {
        if (!arguments.length) {
            return this._valueSort;
        }
        this._valueSort = sortFunction;
        this._resetChildren();
        return this;
    }

}

export const seriesChart = (parent, chartGroup) => new SeriesChart(parent, chartGroup);
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Glayzzle : the PHP engine on NodeJS
 *
 * Copyright (C) 2014 Glayzzle
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @url http://glayzzle.com
 * @license GNU-2
 */

var util    = require('util');
var fs      = require('fs');
var path    = require('path');
var engine  = require('../main');

// help screen
function printHelp() {
  util.puts('Usage: test [options] [-f] <file>');
  util.puts('');
  util.puts('  -f <file>                      Parse and test the specified file');
  util.puts('  -d <path>                      Parse each file in the specified path');
  util.puts('  -r                             Use recursivity with the specified path');
  util.puts('  -h, --help                     Print help and exit');
}

// aborts the execution with the specified error message
function abort(message) {
  util.error(message);
  process.exit(1);
}

/* Arguments */
var options = {
  debug: 0,
  filename: null,
  path: null,
  recursive: false
};

var args = process.argv.slice(2); // Trim 'node' and the script path.

function isOption(arg) {
  return (/^-/).test(arg);
}

function nextArg() {
  args.shift();
}

// Reading arguments
while (args.length > 0 && isOption(args[0])) {
  switch(args[0]) {
    case '-f':
      nextArg();
      options.filename = args[0];
      break;

    case '--debug':
      nextArg();
      options.debug = args[0];
      break;

    case '-d':
      nextArg();
      options.path = args[0];
      break;

    case '-r':
      options.recusive = true;
      break;

    case '-h':
    case '--help':
      printHelp();
      process.exit(0);
      break;

    default:
      abort('Unknown option: ' + args[0] + '.');
  }
  nextArg();
}

// Checking last parameters
if ( args.length > 0 ) {
  if ( args.length == 1 && !options.filename ) {
    options.filename = args[0];
  } else {
    abort('Too many arguments.');
  }
}
if ( !options.filename && !options.path ) {
  abort('Expecting a filename or a path.');
}

process.env.DEBUG = options.debug;

// Load tests handlers
var engines = [
    require('./formats/parser')
  , require('./formats/phpt')
  , require('./formats/token')
  , require('./formats/php')
  , require('./formats/ast')
];

// gets the extension of the specified filename
function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}

// run a test over the specified file
function test(filename) {
  console.log(' + ' + filename);
  try {
    if (options.ast) {
      return engines[4].run(
            filename
          , engine
      );
    }
    var extension = getExtension(filename);
    for(var i = 0; i<engines.length; i++) {
      if (engines[i].handles(filename, extension)) {
        if (engines[i].explode) {
          return engines[i].run(
            fs.readFileSync(filename).toString().split('\r\n')
            , filename
            , engine
          );
        } else {
          return engines[i].run(filename, engine);
        }
      }
    }
    console.info('\n(i) IGNORED : unrecognized extension "'+getExtension(filename)+'" for ' + filename);
    return false;
  } catch(e) {
    util.error( (e.stack || e) + '\n' );
    throw e;
    return false;
  }
}

// run tests
console.log('\n*** START TESTING ***\n');
if (options.filename) {
  if (!test(options.filename)) {
    abort('Error: test FAILED !!!');
  } else {
    console.log('Success');
  }
} else if (options.path) {
  var testFiles = function(path) {
    fs.readdir(path, function(err, files) {
      if (err) throw err;
      for(var i = 0; i < files.length; i ++) {
        var file = files[i];
        if (file[0] != '.') {
          var stat = fs.statSync(path + file);
          if (!stat.isDirectory()) {
            test(path + file);
          } else if (options.recusive) {
            testFiles(path + file + '/');
          }
        }
      }
    });
  };
  testFiles(options.path);
}
<commit_msg>Support \n EOL<commit_after>#!/usr/bin/env node

/**
 * Glayzzle : the PHP engine on NodeJS
 *
 * Copyright (C) 2014 Glayzzle
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @url http://glayzzle.com
 * @license GNU-2
 */

var util    = require('util');
var fs      = require('fs');
var path    = require('path');
var engine  = require('../main');

// help screen
function printHelp() {
  util.puts('Usage: test [options] [-f] <file>');
  util.puts('');
  util.puts('  -f <file>                      Parse and test the specified file');
  util.puts('  -d <path>                      Parse each file in the specified path');
  util.puts('  -r                             Use recursivity with the specified path');
  util.puts('  -h, --help                     Print help and exit');
}

// aborts the execution with the specified error message
function abort(message) {
  util.error(message);
  process.exit(1);
}

/* Arguments */
var options = {
  debug: 0,
  filename: null,
  path: null,
  recursive: false
};

var args = process.argv.slice(2); // Trim 'node' and the script path.

function isOption(arg) {
  return (/^-/).test(arg);
}

function nextArg() {
  args.shift();
}

// Reading arguments
while (args.length > 0 && isOption(args[0])) {
  switch(args[0]) {
    case '-f':
      nextArg();
      options.filename = args[0];
      break;

    case '--debug':
      nextArg();
      options.debug = args[0];
      break;

    case '-d':
      nextArg();
      options.path = args[0];
      break;

    case '-r':
      options.recusive = true;
      break;

    case '-h':
    case '--help':
      printHelp();
      process.exit(0);
      break;

    default:
      abort('Unknown option: ' + args[0] + '.');
  }
  nextArg();
}

// Checking last parameters
if ( args.length > 0 ) {
  if ( args.length == 1 && !options.filename ) {
    options.filename = args[0];
  } else {
    abort('Too many arguments.');
  }
}
if ( !options.filename && !options.path ) {
  abort('Expecting a filename or a path.');
}

process.env.DEBUG = options.debug;

// Load tests handlers
var engines = [
    require('./formats/parser')
  , require('./formats/phpt')
  , require('./formats/token')
  , require('./formats/php')
  , require('./formats/ast')
];

// gets the extension of the specified filename
function getExtension(filename) {
    var i = filename.lastIndexOf('.');
    return (i < 0) ? '' : filename.substr(i);
}

// run a test over the specified file
function test(filename) {
  console.log(' + ' + filename);
  try {
    if (options.ast) {
      return engines[4].run(
            filename
          , engine
      );
    }
    var extension = getExtension(filename),
        isWin = /^win/.test(process.platform);
    for(var i = 0; i<engines.length; i++) {
      if (engines[i].handles(filename, extension)) {
        if (engines[i].explode) {
          return engines[i].run(
            fs.readFileSync(filename).toString().split(
              isWin ? '\r\n' : '\n'
            )
            , filename
            , engine
          );
        } else {
          return engines[i].run(filename, engine);
        }
      }
    }
    console.info('\n(i) IGNORED : unrecognized extension "'+getExtension(filename)+'" for ' + filename);
    return false;
  } catch(e) {
    util.error( (e.stack || e) + '\n' );
    throw e;
    return false;
  }
}

// run tests
console.log('\n*** START TESTING ***\n');
if (options.filename) {
  if (!test(options.filename)) {
    abort('Error: test FAILED !!!');
  } else {
    console.log('Success');
  }
} else if (options.path) {
  var testFiles = function(path) {
    fs.readdir(path, function(err, files) {
      if (err) throw err;
      for(var i = 0; i < files.length; i ++) {
        var file = files[i];
        if (file[0] != '.') {
          var stat = fs.statSync(path + file);
          if (!stat.isDirectory()) {
            test(path + file);
          } else if (options.recusive) {
            testFiles(path + file + '/');
          }
        }
      }
    });
  };
  testFiles(options.path);
}
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:18-01-27');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:18-01-28');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>var Application = Application || {};

Application.Constants = angular.module('application.core.constants', []);
Application.Services = angular.module('application.core.services', []);
Application.Controllers = angular.module('application.core.controllers', []);
Application.Filters = angular.module('application.core.filters', []);
Application.Directives = angular.module('application.core.directives', []);

var app = angular.module('materialscommons',
                         [
                             'ui',
                             'ngCookies',
                             'ui.router',
                             'btford.socket-io',
                             'restangular',
                             'jmdobry.angular-cache',
                             'validation', 'validation.rule',  'wu.masonry',
                             'textAngular',
                             'treeGrid',
                             'ngDragDrop',
                             'ng-context-menu',
                             "cfp.hotkeys",
                             '$strap.directives', 'ui.bootstrap', 'toastr',
                             'tc.chartjs',
                             'application.core.constants', 'application.core.services',
                             'application.core.controllers',
                             'application.core.filters', 'application.core.directives']);

// This factory needs to hang off of this module for some reason
app.factory('msocket', ["socketFactory", function (socketFactory) {
    var msocket = socketFactory({
        ioSocket: io.connect('https://localhost:8082')
    });
    msocket.forward('file');
    msocket.forward('connect');
    msocket.forward('disconnect');
    msocket.forward('error');
    return msocket;
}]);

app.config(["$stateProvider", "$validationProvider", function ($stateProvider, $validationProvider) {

    mcglobals = {};
    doConfig();
    $stateProvider
    // Navbar
        .state('home', {
            url: '/home',
            templateUrl: 'application/core/home/home.html'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'application/core/login/login.html'
        })
        .state('logout', {
            url: '/logout',
            controller: 'logout'
        })
        .state('reviews', {
            url: '/reviews',
            templateUrl: 'application/core/reviews/reviews.html'
        })
        .state('machines', {
            url: '/machines',
            templateUrl: 'application/core/machines/machines.html'
        })

    /*
     ########################################################################
     ####################### Account ##################################
     ########################################################################
     */
        .state('account', {
            url: '/account',
            templateUrl: 'application/core/account/account.html'
        })
        .state('account.password', {
            url: '/password',
            templateUrl: 'application/core/account/password/password.html'
        })
        .state('account.apikey', {
            url: '/apikey',
            templateUrl: 'application/core/account/apikey/apikey.html'
        })
        .state('account.usergroup', {
            url: '/usergroup',
            templateUrl: 'application/core/account/usergroups/usergroup.html'
        })
        .state('account.usergroup.users', {
            url: '/users/:id',
            templateUrl: 'application/core/account/usergroups/users.html'
        })
        .state('account.templates', {
            url: '/templates',
            templateUrl: 'application/core/account/templates/templates.html'
        })

    /*
     ########################################################################
     ########################### Projects ###################################
     ########################################################################
     */
        .state('projects', {
            url: '/projects',
            abstract: true,
            template: '

',
            resolve: {
                Projects: "model.projects",
                projects: function (Projects) {
                    return Projects.getList();
                },

                Templates: "model.templates",
                templates: function(Templates) {
                    return Templates.getList();
                }
            }
        })
        .state('projects.project', {
            url: '/project/:id',
            templateUrl: 'application/core/projects/project/project.html',
            resolve: {
                project: ["$stateParams", "model.projects", "projects", "templates", function ($stateParams, Projects, projects, templates) {
                    // We use templates as a dependency so that they are all loaded before getting to this step.
                    // Otherwise the order of items being resolved isn't in the order we need them.
                    return Projects.get($stateParams.id);
                }]
            },
            onEnter: ["pubsub", "project", function(pubsub, project) {
                pubsub.send("reviews.change");
            }],
            controller: "projectsProject"
        })
        .state('projects.project.home', {
            url: '/home',
            templateUrl: 'application/core/projects/project/home/home.html',
            controller: "projectHome"
        })
        .state('projects.project.samples', {
            url: '/samples',
            templateUrl: 'application/core/projects/project/samples/samples.html',
            controller: "projectSamples"
        })
        .state('projects.project.samples.overview', {
            url: '/overview',
            templateUrl: "application/core/projects/project/samples/overview.html",
            controller: "projectSamplesOverview"
        })
        .state('projects.project.samples.create', {
            url: '/create/:sid',
            templateUrl: 'application/core/projects/project/samples/create.html',
            controller: "projectSamplesCreate"
        })
        .state('projects.project.tasks', {
            url: '/tasks',
            templateUrl: 'application/core/projects/project/tasks/tasks.html',
            controller: "projectTasks"
        })
        .state('projects.project.tasks.overview', {
            url: '/overview',
            templateUrl: "application/core/projects/project/tasks/overview.html",
            controller: "projectTasksOverview"
        })
        .state('projects.project.tasks.create', {
            url: '/create/:sid',
            templateUrl: 'application/core/projects/project/tasks/create.html',
            controller: "projectTasksCreate"
        })
        .state('projects.project.provenance', {
            url: '/provenance',
            templateUrl: 'application/core/projects/project/provenance/provenance.html',
            controller: "projectProvenance"
        })
        .state('projects.project.provenance.overview', {
            url: '/overview',
            templateUrl: 'application/core/projects/project/provenance/overview.html',
            controller: 'projectProvenanceOverview'
        })
        .state('projects.project.provenance.create', {
            url: '/create/:sid',
            templateUrl: 'application/core/projects/project/provenance/create.html',
            controller: "projectProvenanceCreate"
        })
        .state('projects.project.provenance.drafts', {
            url: '/drafts',
            templateUrl: 'application/core/projects/project/provenance/drafts.html',
            controller: "projectProvenanceDrafts"
        })
        .state('projects.project.reviews', {
            url: '/reviews',
            templateUrl: 'application/core/projects/project/reviews/reviews.html',
            controller: "projectReviews"
        })
        .state('projects.project.reviews.overview', {
            url: "/overview",
            templateUrl: "application/core/projects/project/reviews/overview.html",
            controller: "projectReviewsOverview"
        })
        .state('projects.project.reviews.create', {
            url: "/create/:sid",
            templateUrl: "application/core/projects/project/reviews/create.html",
            controller: "projectReviewsCreate"
        })
        .state('projects.project.notes', {
            url: '/notes',
            templateUrl: 'application/core/projects/project/notes/notes.html',
            controller: "projectNotes"
        })
        .state('projects.project.notes.overview', {
            url: '/overview',
            templateUrl: "application/core/projects/project/notes/overview.html",
            controller: "projectNotesOverview"
        })
        .state('projects.project.notes.create', {
            url: '/create/:sid',
            templateUrl: "application/core/projects/project/notes/create.html",
            controller: "projectNotesCreate"
        })
        .state('projects.project.files', {
            url: "/files",
            templateUrl: "application/core/projects/project/files/files.html",
            controller: "projectFiles"
        })
        .state('projects.project.files.overview', {
            url: "/overview",
            templateUrl: "application/core/projects/project/files/overview.html",
            controller: "projectFilesOverview"
        })
        .state('projects.project.files.view', {
            url: "/view/:fileid",
            templateUrl: "application/core/projects/project/files/view.html",
            controller: "projectFilesViewFile"
        })
        .state('projects.project.tags', {
            url: '/tags',
            templateUrl: "application/core/projects/project/tags/tags.html",
            controller: "projectTags"
        })
        .state('projects.project.tags.create', {
            url: '/create/:sid',
            templateUrl: "application/core/projects/project/tags/create.html",
            controller: "projectTagsCreate"
        });

    $validationProvider.setErrorHTML(function (msg) {
        return '' + msg + '';
    });

    $validationProvider.setSuccessHTML(function (msg) {
        return '' + msg + '';
    });

}]);

app.run(["$rootScope", "User", "Restangular", "recent", "ui", appRun]);

function appRun($rootScope, User, Restangular, recent, ui) {
    Restangular.setBaseUrl(mcglobals.apihost);

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
        if (User.isAuthenticated()) {
            $rootScope.email_address = User.u();
            ui.setShowFiles(toParams.id, false);
        }
    });

    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
        var projectID = fromParams.id;
        if (!fromState.abstract) {
            recent.pushLast(projectID, "ignore", fromState.name, fromParams);
        }
    });
}
<commit_msg>Formatting changes to make function fit on a single page horizontally.<commit_after>var Application = Application || {};

Application.Constants = angular.module('application.core.constants', []);
Application.Services = angular.module('application.core.services', []);
Application.Controllers = angular.module('application.core.controllers', []);
Application.Filters = angular.module('application.core.filters', []);
Application.Directives = angular.module('application.core.directives', []);

var app = angular.module('materialscommons',
                         [
                             'ui',
                             'ngCookies',
                             'ui.router',
                             'btford.socket-io',
                             'restangular',
                             'jmdobry.angular-cache',
                             'validation', 'validation.rule',  'wu.masonry',
                             'textAngular',
                             'treeGrid',
                             'ngDragDrop',
                             'ng-context-menu',
                             "cfp.hotkeys",
                             '$strap.directives', 'ui.bootstrap', 'toastr',
                             'tc.chartjs',
                             'application.core.constants', 'application.core.services',
                             'application.core.controllers',
                             'application.core.filters', 'application.core.directives']);

// This factory needs to hang off of this module for some reason
app.factory('msocket', ["socketFactory", function (socketFactory) {
    var msocket = socketFactory({
        ioSocket: io.connect('https://localhost:8082')
    });
    msocket.forward('file');
    msocket.forward('connect');
    msocket.forward('disconnect');
    msocket.forward('error');
    return msocket;
}]);

app.config(["$stateProvider", "$validationProvider", function ($stateProvider, $validationProvider) {

    mcglobals = {};
    doConfig();
    $stateProvider
    // Navbar
        .state('home', {
            url: '/home',
            templateUrl: 'application/core/home/home.html'
        })
        .state('login', {
            url: '/login',
            templateUrl: 'application/core/login/login.html'
        })
        .state('logout', {
            url: '/logout',
            controller: 'logout'
        })
        .state('reviews', {
            url: '/reviews',
            templateUrl: 'application/core/reviews/reviews.html'
        })
        .state('machines', {
            url: '/machines',
            templateUrl: 'application/core/machines/machines.html'
        })

    /*
     ########################################################################
     ####################### Account ##################################
     ########################################################################
     */
        .state('account', {
            url: '/account',
            templateUrl: 'application/core/account/account.html'
        })
        .state('account.password', {
            url: '/password',
            templateUrl: 'application/core/account/password/password.html'
        })
        .state('account.apikey', {
            url: '/apikey',
            templateUrl: 'application/core/account/apikey/apikey.html'
        })
        .state('account.usergroup', {
            url: '/usergroup',
            templateUrl: 'application/core/account/usergroups/usergroup.html'
        })
        .state('account.usergroup.users', {
            url: '/users/:id',
            templateUrl: 'application/core/account/usergroups/users.html'
        })
        .state('account.templates', {
            url: '/templates',
            templateUrl: 'application/core/account/templates/templates.html'
        })

    /*
     ########################################################################
     ########################### Projects ###################################
     ########################################################################
     */
        .state('projects', {
            url: '/projects',
            abstract: true,
            template: '

',
            resolve: {
                Projects: "model.projects",
                projects: function (Projects) {
                    return Projects.getList();
                },

                Templates: "model.templates",
                templates: function(Templates) {
                    return Templates.getList();
                }
            }
        })
        .state('projects.project', {
            url: '/project/:id',
            templateUrl: 'application/core/projects/project/project.html',
            resolve: {
                project: ["$stateParams", "model.projects", "projects", "templates",
                          function ($stateParams, Projects, projects, templates) {
                              // We use templates as a dependency so that they are all loaded
                              // before getting to this step. Otherwise the order of items
                              // being resolved isn't in the order we need them.
                              return Projects.get($stateParams.id);
                          }]
            },
            onEnter: ["pubsub", "project", function(pubsub, project) {
                pubsub.send("reviews.change");
            }],
            controller: "projectsProject"
        })
        .state('projects.project.home', {
            url: '/home',
            templateUrl: 'application/core/projects/project/home/home.html',
            controller: "projectHome"
        })
        .state('projects.project.samples', {
            url: '/samples',
            templateUrl: 'application/core/projects/project/samples/samples.html',
            controller: "projectSamples"
        })
        .state('projects.project.samples.overview', {
            url: '/overview',
            templateUrl: "application/core/projects/project/samples/overview.html",
            controller: "projectSamplesOverview"
        })
        .state('projects.project.samples.create', {
            url: '/create/:sid',
            templateUrl: 'application/core/projects/project/samples/create.html',
            controller: "projectSamplesCreate"
        })
        .state('projects.project.tasks', {
            url: '/tasks',
            templateUrl: 'application/core/projects/project/tasks/tasks.html',
            controller: "projectTasks"
        })
        .state('projects.project.tasks.overview', {
            url: '/overview',
            templateUrl: "application/core/projects/project/tasks/overview.html",
            controller: "projectTasksOverview"
        })
        .state('projects.project.tasks.create', {
            url: '/create/:sid',
            templateUrl: 'application/core/projects/project/tasks/create.html',
            controller: "projectTasksCreate"
        })
        .state('projects.project.provenance', {
            url: '/provenance',
            templateUrl: 'application/core/projects/project/provenance/provenance.html',
            controller: "projectProvenance"
        })
        .state('projects.project.provenance.overview', {
            url: '/overview',
            templateUrl: 'application/core/projects/project/provenance/overview.html',
            controller: 'projectProvenanceOverview'
        })
        .state('projects.project.provenance.create', {
            url: '/create/:sid',
            templateUrl: 'application/core/projects/project/provenance/create.html',
            controller: "projectProvenanceCreate"
        })
        .state('projects.project.provenance.drafts', {
            url: '/drafts',
            templateUrl: 'application/core/projects/project/provenance/drafts.html',
            controller: "projectProvenanceDrafts"
        })
        .state('projects.project.reviews', {
            url: '/reviews',
            templateUrl: 'application/core/projects/project/reviews/reviews.html',
            controller: "projectReviews"
        })
        .state('projects.project.reviews.overview', {
            url: "/overview",
            templateUrl: "application/core/projects/project/reviews/overview.html",
            controller: "projectReviewsOverview"
        })
        .state('projects.project.reviews.create', {
            url: "/create/:sid",
            templateUrl: "application/core/projects/project/reviews/create.html",
            controller: "projectReviewsCreate"
        })
        .state('projects.project.notes', {
            url: '/notes',
            templateUrl: 'application/core/projects/project/notes/notes.html',
            controller: "projectNotes"
        })
        .state('projects.project.notes.overview', {
            url: '/overview',
            templateUrl: "application/core/projects/project/notes/overview.html",
            controller: "projectNotesOverview"
        })
        .state('projects.project.notes.create', {
            url: '/create/:sid',
            templateUrl: "application/core/projects/project/notes/create.html",
            controller: "projectNotesCreate"
        })
        .state('projects.project.files', {
            url: "/files",
            templateUrl: "application/core/projects/project/files/files.html",
            controller: "projectFiles"
        })
        .state('projects.project.files.overview', {
            url: "/overview",
            templateUrl: "application/core/projects/project/files/overview.html",
            controller: "projectFilesOverview"
        })
        .state('projects.project.files.view', {
            url: "/view/:fileid",
            templateUrl: "application/core/projects/project/files/view.html",
            controller: "projectFilesViewFile"
        })
        .state('projects.project.tags', {
            url: '/tags',
            templateUrl: "application/core/projects/project/tags/tags.html",
            controller: "projectTags"
        })
        .state('projects.project.tags.create', {
            url: '/create/:sid',
            templateUrl: "application/core/projects/project/tags/create.html",
            controller: "projectTagsCreate"
        });

    $validationProvider.setErrorHTML(function (msg) {
        return '' + msg + '';
    });

    $validationProvider.setSuccessHTML(function (msg) {
        return '' + msg + '';
    });

}]);

app.run(["$rootScope", "User", "Restangular", "recent", "ui", appRun]);

function appRun($rootScope, User, Restangular, recent, ui) {
    Restangular.setBaseUrl(mcglobals.apihost);

    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
        if (User.isAuthenticated()) {
            $rootScope.email_address = User.u();
            ui.setShowFiles(toParams.id, false);
        }
    });

    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
        var projectID = fromParams.id;
        if (!fromState.abstract) {
            recent.pushLast(projectID, "ignore", fromState.name, fromParams);
        }
    });
}
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.events.variants')
    .controller('VariantSummaryController', VariantSummaryController)
    .directive('variantSummary', function() {
      return {
        restrict: 'E',
        scope: {
          showEvidenceGrid: '='
        },
        controller: 'VariantSummaryController',
        templateUrl: 'app/views/events/variants/summary/variantSummary.tpl.html'
      };
    });

  //@ngInject
  function VariantSummaryController($scope,
                                    $state,
                                    $stateParams,
                                    _,
                                    Security,
                                    Variants,
                                    VariantsViewOptions) {
    $scope.isAuthenticated = Security.isAuthenticated;
    $scope.isEdit = $state.includes('**.edit.**');
    $scope.stateParams = $stateParams;

    $scope.variant = parseVariant(Variants.data.item);
    $scope.evidence = Variants.data.evidence;

    $scope.clinvar_ignore = ['N/A', 'NONE FOUND']

    // watches any changes to the variant itself, but will also update evidence to pass to grid
    $scope.$watch(function() { return Variants.data.item; }, function(variant) {
      $scope.variant = variant;
      $scope.evidence = variant.evidence_items;
    }, true);

    $scope.$watch(function() { return Variants.data.myVariantInfo;}, function(myVariantInfo) {
      if(!_.isUndefined(myVariantInfo.cosmic)) {
        myVariantInfo.cosmic.cosmic_id_short = _.trim(myVariantInfo.cosmic.cosmic_id, 'COSM');
        myVariantInfo.entrez_id = $scope.variant.name;
      }
      $scope.myVariantInfo = myVariantInfo;
    }, true);

    $scope.VariantsViewOptions = VariantsViewOptions;
    $scope.backgroundColor = VariantsViewOptions.styles.view.backgroundColor;

    $scope.editClick = function() {
      if (Security.isAuthenticated()) {
        $state.go('events.genes.summary.variants.edit.basic', $stateParams);
      }
    };
  }

  function parseVariant(variant) {
    return variant;
  }
})();
<commit_msg>jslint fix<commit_after>(function() {
  'use strict';
  angular.module('civic.events.variants')
    .controller('VariantSummaryController', VariantSummaryController)
    .directive('variantSummary', function() {
      return {
        restrict: 'E',
        scope: {
          showEvidenceGrid: '='
        },
        controller: 'VariantSummaryController',
        templateUrl: 'app/views/events/variants/summary/variantSummary.tpl.html'
      };
    });

  //@ngInject
  function VariantSummaryController($scope,
                                    $state,
                                    $stateParams,
                                    _,
                                    Security,
                                    Variants,
                                    VariantsViewOptions) {
    $scope.isAuthenticated = Security.isAuthenticated;
    $scope.isEdit = $state.includes('**.edit.**');
    $scope.stateParams = $stateParams;

    $scope.variant = parseVariant(Variants.data.item);
    $scope.evidence = Variants.data.evidence;

    $scope.clinvar_ignore = ['N/A', 'NONE FOUND'];

    // watches any changes to the variant itself, but will also update evidence to pass to grid
    $scope.$watch(function() { return Variants.data.item; }, function(variant) {
      $scope.variant = variant;
      $scope.evidence = variant.evidence_items;
    }, true);

    $scope.$watch(function() { return Variants.data.myVariantInfo;}, function(myVariantInfo) {
      if(!_.isUndefined(myVariantInfo.cosmic)) {
        myVariantInfo.cosmic.cosmic_id_short = _.trim(myVariantInfo.cosmic.cosmic_id, 'COSM');
        myVariantInfo.entrez_id = $scope.variant.name;
      }
      $scope.myVariantInfo = myVariantInfo;
    }, true);

    $scope.VariantsViewOptions = VariantsViewOptions;
    $scope.backgroundColor = VariantsViewOptions.styles.view.backgroundColor;

    $scope.editClick = function() {
      if (Security.isAuthenticated()) {
        $state.go('events.genes.summary.variants.edit.basic', $stateParams);
      }
    };
  }

  function parseVariant(variant) {
    return variant;
  }
})();
<|endoftext|>


<commit_before>var winston = require('winston');

//constants
var c = {

    port: {

        'mongodb' : 27017,
        'explore' : 3000,
        'admin' : 3001,
        'sys-admin' : 3002
    },

    db: {

        fatalities: 'test-fatalities'
    },

    collection: {

        fatalities: 'test-fatalities'
    },

    url: {}
};

c.url.mongo = 'mongodb://localhost:' + c.port.mongodb + '/';

/*
 * @param location {array}
*/

var FILE_SEP = '.',
    LOGS_DIR = __dirname + '/../log/';

var logger = new (winston.Logger)({

    levels: {

        trace: 0,
        input: 1,
        verbose: 2,
        prompt: 3,
        debug: 4,
        info: 5,
        data: 6,
        help: 7,
        warn: 8,
        error: 9
    },

    colors: {

        trace: 'magenta',
        input: 'grey',
        verbose: 'cyan',
        prompt: 'grey',
        debug: 'blue',
        info: 'green',
        data: 'grey',
        help: 'cyan',
        warn: 'yellow',
        error: 'red'
    }
});

logger.add( winston.transports.Console, {

    level: 'trace',
    prettyPrint: true,
    colorize: true,
    silent: false,
    timestamp: false
});

logFileName = getLogFileName();

logger.add( winston.transports.File, {

    prettyPrint: false,
    level: 'trace',
    silent: false,
    timestamp: true,
    filename: logFileName,
    maxsize: 40000,
    maxFiles: 10,
    json: false
});

function getLogFileName () {

    var today = new Date(),
        d = today.getDate(),
        d = d < 10 ? '0' + d : d,
        m = today.getMonth() + 1,
        m = m < 10 ? '0' + m : m,
        y = today.getFullYear();

    return LOGS_DIR + y + '' + m + '' + d + '.log'
}

c.log = function (type, msg, data) {

    data = data ? data : '';

    return logger.log(type, msg, data);
};

c.getLog = function (log, location) {

    return function (type, msg, data) {

        data = data || {};
        data.location =location;

        log(type, msg, data);
    }
}

module.exports = c;<commit_msg>updating log levels<commit_after>var winston = require('winston');

//constants
var c = {

    port: {

        'mongodb' : 27017,
        'explore' : 3000,
        'admin' : 3001,
        'sys-admin' : 3002
    },

    db: {

        fatalities: 'test-fatalities'
    },

    collection: {

        fatalities: 'test-fatalities'
    },

    url: {}
};

c.url.mongo = 'mongodb://localhost:' + c.port.mongodb + '/';

/*
 * @param location {array}
*/

var FILE_SEP = '.',
    LOGS_DIR = __dirname + '/../log/';

var logger = new (winston.Logger)({

    levels: {

        trace: 0,
        info: 1,
        error: 2
    },

    colors: {

        trace: 'magenta',
        info: 'blue',
        error: 'red'
    }
});

logger.add( winston.transports.Console, {

    level: 'trace',
    prettyPrint: true,
    colorize: true,
    silent: false,
    timestamp: false
});

logFileName = getLogFileName();

logger.add( winston.transports.File, {

    prettyPrint: false,
    level: 'info',
    silent: false,
    timestamp: true,
    filename: logFileName,
    maxsize: 40000,
    maxFiles: 10,
    json: false
});

function getLogFileName () {

    var today = new Date(),
        d = today.getDate(),
        d = d < 10 ? '0' + d : d,
        m = today.getMonth() + 1,
        m = m < 10 ? '0' + m : m,
        y = today.getFullYear();

    return LOGS_DIR + y + '' + m + '' + d + '.log'
}

c.log = function (type, msg, data) {

    data = data ? data : '';

    return logger.log(type, msg, data);
};

c.getLog = function (log, location) {

    return function (type, msg, data) {

        data = data || {};
        data.location =location;

        log(type, msg, data);
    }
}

module.exports = c;<|endoftext|>


<commit_before>$.ninjaMessageOpen = function(customOptions){
  var options = $.extend({
    colors:$.ninjaColors,
    icon:null,
    id:null,
    onClose:function(){},
    onOpen:function(){},
    radius:$.ninjaRadius.half,
    seconds:0,
    text:null,
    title:null
  }, customOptions);
  var message = $(document.body).append('
').children('.ninjaMessage').attr('id', options.id).css({opacity:0.75}).append('

');
  var timer = null;
  if(options.seconds > 0){
    var milliseconds = options.seconds * 1000;
    timer = setTimeout(function(){
      $(message).ninjaMessageClose();
    }, milliseconds);
  };
  $(message).data({options:options});
  var handle = $('.ninjaMessageHandle', message).text(options.title).append('').css(options.colors.foreground);
  if(options.icon){
    if(options.title){
      $(handle).prepend(' ');
    };
    $(handle).prepend('');
    $('.ninjaMessageIcon', handle).ninjaIconCreate(options.icon).css({height:$(handle).height(), position:'relative', top:'-2px'});
  };
  $('.ninjaMessageClose', handle).ninjaButtonCreate({icon:'remove', onSelect:function(){
    $(message).ninjaMessageClose(timer);
  }}).ninjaRadius({radius:'0'});
  var content = $('.ninjaMessageContent', message).text(options.text).css(options.colors.foreground).ninjaRadius({corners:'bottom', radius:options.radius});
  $('.ninjaMessageReflection').css(options.colors.foreground).ninjaRadius({radius:options.radius}).position({
    at:'left bottom',
    of:message,
    my:'left top'
  }).css({opacity:0.125});
  $(document).keyup(function(event){
    if (event.keyCode == 27) { // esc key
      $(message).ninjaMessageClose(timer);
      $(document).unbind('keyup');
    }
  });
  $(message).position({
    at:'top',
    collision:'fit none',
    of:window,
    my:'top'
  }).slideDown('slow');
};

$.fn.ninjaMessageClose = function(timer){
  return this.each(function(i, message){
    clearTimeout(timer);
    var options = $(message).data().options;
    $(message).slideUp('slow', function() {
      options.onClose.call();
      $(message).remove();
    });
  });
};
<commit_msg>Fixes message to work correctly when there is no title specified.<commit_after>$.ninjaMessageOpen = function(customOptions){
  var options = $.extend({
    colors:$.ninjaColors,
    icon:null,
    id:null,
    onClose:function(){},
    onOpen:function(){},
    radius:$.ninjaRadius.half,
    seconds:0,
    text:null,
    title:null
  }, customOptions);
  var message = $(document.body).append('
').children('.ninjaMessage').attr('id', options.id).css({opacity:0.75}).append('

');
  var timer = null;
  if(options.seconds > 0){
    var milliseconds = options.seconds * 1000;
    timer = setTimeout(function(){
      $(message).ninjaMessageClose();
    }, milliseconds);
  };
  $(message).data({options:options});
  var handle = $('.ninjaMessageHandle', message).append('').css(options.colors.foreground);
  if(options.title){
    $(handle).text(options.title);
  };
  if(options.icon){
    if(options.title){
      $(handle).prepend(' ');
    };
    $(handle).prepend('');
    $('.ninjaMessageIcon', handle).ninjaIconCreate(options.icon).css({height:$(handle).height(), position:'relative', top:'-2px'});
  };
  $('.ninjaMessageClose', handle).ninjaButtonCreate({icon:'remove', onSelect:function(){
    $(message).ninjaMessageClose(timer);
  }}).ninjaRadius({radius:'0'});
  var content = $('.ninjaMessageContent', message).text(options.text).css(options.colors.foreground).ninjaRadius({corners:'bottom', radius:options.radius});
  $('.ninjaMessageReflection').css(options.colors.foreground).ninjaRadius({radius:options.radius}).position({
    at:'left bottom',
    of:message,
    my:'left top'
  }).css({opacity:0.125});
  $(document).keyup(function(event){
    if (event.keyCode == 27) { // esc key
      $(message).ninjaMessageClose(timer);
      $(document).unbind('keyup');
    }
  });
  $(message).position({
    at:'top',
    collision:'fit none',
    of:window,
    my:'top'
  }).slideDown('slow');
};

$.fn.ninjaMessageClose = function(timer){
  return this.each(function(i, message){
    clearTimeout(timer);
    var options = $(message).data().options;
    $(message).slideUp('slow', function() {
      options.onClose.call();
      $(message).remove();
    });
  });
};
<|endoftext|>