<commit_before>module.exports = function() {
    return {
        apps: ['superdesk-planning', 'superdesk.analytics', 'aap.apps'],
        importApps: ['superdesk-planning', 'superdesk-analytics', 'aap'],
        defaultRoute: '/workspace',
        workspace: {
            ingest: 1,
            content: 1,
            tasks: 0,
            planning: 1,
            assignments: 1
        },

        profile: {
            jid: false
        },

        item_profile: {
            change_profile: 1
        },

        editor: {
            toolbar: false,
            embeds: false,
            paste: {
                forcePlainText: true,
                cleanPastedHTML: false
            }
        },

        features: {
            elasticHighlight: 1,
            swimlane: {columnsLimit: 4},
            editFeaturedImage: 1,
            confirmMediaOnUpdate: 1,
            hideLiveSuggestions: 1,
            preview: 1,
            previewFormats: 1,
            noTakes: 1,
            searchShortcut: 1,
            slackNotifications: 1,
            editor3: 1,
            analytics: 1,
            editorAttachments: false,
            editorInlineComments: false,
            editorSuggestions: false,
        },

        activity: {
            'edit.item.popup': 0,
            'view.item.popup': 0
        },
        confirm_spike: false,

        view: {
            timeformat: 'HH:mm',
            dateformat: 'DD/MM/YYYY'
        },

        search: {
            slugline: 1, headline: 1, unique_name: 1, story_text: 1,
            byline: 1, keywords: 1, creator: 1, from_desk: 1,
            to_desk: 1, spike: 1, scheduled: 1, company_codes: 1,
            useDefaultTimezone: 1, ingest_provider: 1, raw_search: 1,
            featuremedia: 1, marked_desks: 1
        },

        infoRemovedFields: {
            keywords: true
        },

        defaultTimezone: 'Australia/Sydney',
        shortDateFormat: 'DD/MM',
        ArchivedDateFormat: 'D/MM/YYYY',
        ArchivedDateOnCalendarYear: 1,

        list: {
            'priority': [
                'urgency',
                'priority'
            ],
            'firstLine': [
                'wordcount',
                'slugline',
                'highlights',
                'associations',
                'queueError',
                'headline',
                'markedDesks',
                'assignment',
                'versioncreated'
            ],
            'secondLine': [
                'profile',
                'state',
                'embargo',
                'takekey',
                'signal',
                'broadcast',
                'flags',
                'updated',
                'category',
                'provider',
                'expiry',
                'desk'
            ],
            'singleLine': [
                'slugline',
                'highlights',
                'associations',
                'queueError',
                'takekey',
                'state',
                'update',
                'embargo',
                'flags',
                'updated',
                'headline',
                'markedDesks',
                'assignment',
                'wordcount',
                'provider',
                'versioncreator',
                'versioncreated'
            ],
            'narrowView': [
                'slugline',
                'takekey',
                'state',
                'markedDesks',
                'provider',
                'versioncreated'
            ],
            'singleLineView': true
        },
        langOverride: {
            'en': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            },

            'en_GB': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            },

            'en_US': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            },

            'en_AU': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            }
        }
    };
};
<commit_msg>rename config<commit_after>module.exports = function() {
    return {
        apps: ['superdesk-planning', 'superdesk.analytics', 'aap.apps'],
        importApps: ['superdesk-planning', 'superdesk-analytics', 'aap'],
        defaultRoute: '/workspace',
        workspace: {
            ingest: 1,
            content: 1,
            tasks: 0,
            planning: 1,
            assignments: 1
        },

        profile: {
            jid: false
        },

        item_profile: {
            change_profile: 1
        },

        editor: {
            toolbar: false,
            embeds: false,
            paste: {
                forcePlainText: true,
                cleanPastedHTML: false
            }
        },

        features: {
            elasticHighlight: 1,
            swimlane: {defaultNumberOfColumns: 4},
            editFeaturedImage: 1,
            confirmMediaOnUpdate: 1,
            hideLiveSuggestions: 1,
            preview: 1,
            previewFormats: 1,
            noTakes: 1,
            searchShortcut: 1,
            slackNotifications: 1,
            editor3: 1,
            analytics: 1,
            editorAttachments: false,
            editorInlineComments: false,
            editorSuggestions: false,
        },

        activity: {
            'edit.item.popup': 0,
            'view.item.popup': 0
        },
        confirm_spike: false,

        view: {
            timeformat: 'HH:mm',
            dateformat: 'DD/MM/YYYY'
        },

        search: {
            slugline: 1, headline: 1, unique_name: 1, story_text: 1,
            byline: 1, keywords: 1, creator: 1, from_desk: 1,
            to_desk: 1, spike: 1, scheduled: 1, company_codes: 1,
            useDefaultTimezone: 1, ingest_provider: 1, raw_search: 1,
            featuremedia: 1, marked_desks: 1
        },

        infoRemovedFields: {
            keywords: true
        },

        defaultTimezone: 'Australia/Sydney',
        shortDateFormat: 'DD/MM',
        ArchivedDateFormat: 'D/MM/YYYY',
        ArchivedDateOnCalendarYear: 1,

        list: {
            'priority': [
                'urgency',
                'priority'
            ],
            'firstLine': [
                'wordcount',
                'slugline',
                'highlights',
                'associations',
                'queueError',
                'headline',
                'markedDesks',
                'assignment',
                'versioncreated'
            ],
            'secondLine': [
                'profile',
                'state',
                'embargo',
                'takekey',
                'signal',
                'broadcast',
                'flags',
                'updated',
                'category',
                'provider',
                'expiry',
                'desk'
            ],
            'singleLine': [
                'slugline',
                'highlights',
                'associations',
                'queueError',
                'takekey',
                'state',
                'update',
                'embargo',
                'flags',
                'updated',
                'headline',
                'markedDesks',
                'assignment',
                'wordcount',
                'provider',
                'versioncreator',
                'versioncreated'
            ],
            'narrowView': [
                'slugline',
                'takekey',
                'state',
                'markedDesks',
                'provider',
                'versioncreated'
            ],
            'singleLineView': true
        },
        langOverride: {
            'en': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            },

            'en_GB': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            },

            'en_US': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            },

            'en_AU': {
                'Advanced Search': 'Advanced',
                'URGENCY': 'NEWS VALUE',
                'Urgency': 'News Value',
                'urgency': 'news value',
                'Urgency stats': 'News Value stats',
                'SERVICE': 'CATEGORY',
                'SERVICES': 'CATEGORIES',
                'Services': 'Categories',
                'Service': 'Category',
                'Mar': 'March',
                'Apr': 'April',
                'Jun': 'June',
                'Jul': 'July',
                'Sep': 'Sept',
                'ANPA Category': 'Category',
                'ANPA CATEGORY': 'CATEGORY'
            }
        }
    };
};
<|endoftext|>


<commit_before>(function (env) {
    "use strict";
    env.ddg_spice_pwned = function(api_result){
        if (!api_result || api_result.error) {
            return Spice.failed('pwned');
        }

        var query = DDG.get_query(),
            re    = /\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i, //capture email from query
            email = re.exec(query)[1];

		DDG.require("moment.js", function(){
	        Spice.add({
	            id: "pwned",
	            name: "Pwned",
	            data: api_result,
	            meta: {
	                sourceName: "Have I Been Pwned",
	                sourceUrl: 'https://haveibeenpwned.com/account/' + email,
                    primaryText: email + " is compromised:",
                    snippetChars: 170
	            },
	            normalize: function(item) {

	                if (item.fallback) {
	                    return {
	                        title: item.fallback
	                    };
	                } else {
	                    return {
	                        title: item.Name,
							altSubtitle: item.Domain,
							date: moment(item.BreachDate).format("MMM DD, YYYY"),
	                        description: DDG.strip_html(item.Description).replace(/"/g, "\"")
	                    };
	                }
	            },
	            templates: {
	                group: 'icon',
					item_detail: false,
					detail: false,
					variants: {
                        tileTitle: "1line-large",
                        tileSnippet: "large"
					},
                    options: {
                        footer: Spice.pwned.footer
                    }
	            },
			    relevancy: {
			        type: api_result.fallback ? null : "primary", // detect when api returned error
			        primary: [
			            {required: 'Title'},
			            {required: 'Name'},
			            {required: 'Domain'},
			            {required: 'DataClasses'}
			        ]
			    }
        	});
		});
    };
}(this));
<commit_msg>add link to details of pwned IA<commit_after>(function (env) {
    "use strict";
    env.ddg_spice_pwned = function(api_result){
        if (!api_result || api_result.error) {
            return Spice.failed('pwned');
        }

        var query = DDG.get_query(),
            re    = /\b([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,})\b/i, //capture email from query
            email = re.exec(query)[1],
            url   = 'https://haveibeenpwned.com/account/' + email;

		DDG.require("moment.js", function(){
	        Spice.add({
	            id: "pwned",
	            name: "Pwned",
	            data: api_result,
	            meta: {
	                sourceName: "Have I Been Pwned",
	                sourceUrl: url,
                    primaryText: email + " is compromised:",
                    snippetChars: 170
	            },
	            normalize: function(item) {

	                if (item.fallback) {
	                    return {
	                        title: item.fallback
	                    };
	                } else {
	                    return {
	                        title: item.Name,
							altSubtitle: item.Domain,
							date: moment(item.BreachDate).format("MMM DD, YYYY"),
	                        description: DDG.strip_html(item.Description).replace(/"/g, "\""),
                            url: url
	                    };
	                }
	            },
	            templates: {
	                group: 'icon',
					item_detail: false,
					detail: false,
					variants: {
                        tileTitle: "1line-large",
                        tileSnippet: "large"
					},
                    options: {
                        footer: Spice.pwned.footer
                    }
	            },
			    relevancy: {
			        type: api_result.fallback ? null : "primary", // detect when api returned error
			        primary: [
			            {required: 'Title'},
			            {required: 'Name'},
			            {required: 'Domain'},
			            {required: 'DataClasses'}
			        ]
			    }
        	});
		});
    };
}(this));
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import Card from './components/Card';
import Divider from './components/Divider';
import PriceItem from './components/PriceItem';
import OrderButton from './components/OrderButton';

import './App.css';

class App extends Component {
  state = {
    orders: [],
  }

  types = [
    { type: 'cola', label: 'Cola', price: 4 },
    { type: 'fanta', label: 'Fanta', price: 4 },
    { type: 'gummibärchen', label: 'Gummibärchen', price: 3.5 },
    { type: 'knabber', label: 'Knabber', price: 1.95 },
  ]

  onAddOrder = (PriceItem) => {
    this.setState({ orders: [...this.state.orders, PriceItem] });
  }

  onRemoveLastOrder = (PriceItem) => {
    this.setState({ orders: [...this.state.orders.slice(0, -1)] });
  }

  onResetOrders = (PriceItem) => {
    this.setState({ orders: [] });
  }

  getPriceForOrderType = (type) => {
    return this.types.find(t => t.type === type).price;
  }

  getLabelForOrderType = (type) => {
    return this.types.find(t => t.type === type).label;
  }

  getTotalPrice = () => {
    const { orders } = this.state;
    return orders.reduce((sum, order) => sum + this.getPriceForOrderType(order), 0);
  }

  render() {
    const { orders } = this.state;

    return (
      <Card title="Cashier">

          {this.types.map(({ type, label }) => (
            <OrderButton key={type} label={label} type={type} handleOnClick={this.onAddOrder} />
          ))}

        <Divider />

          <button onClick={this.onRemoveLastOrder}>Stornieren</button>
          <button onClick={this.onResetOrders}>Reset</button>

        {orders.length > 0 && <Divider />}

        {orders.map((orderType, i) => (
          <PriceItem
            key={i}
            label={this.getLabelForOrderType(orderType)}
            price={this.getPriceForOrderType(orderType)}
          />
        ))}

        <Divider />

            <PriceItem
              label="Total"
              price={this.getTotalPrice()}
            />

      </Card>
    );
  }
}

export default App;
<commit_msg>Remove div-wrapper and change formatting<commit_after>import React, { Component } from 'react';

import Card from './components/Card';
import Divider from './components/Divider';
import PriceItem from './components/PriceItem';
import OrderButton from './components/OrderButton';

import './App.css';

class App extends Component {
  state = {
    orders: [],
  }

  types = [
    { type: 'cola', label: 'Cola', price: 4 },
    { type: 'fanta', label: 'Fanta', price: 4 },
    { type: 'gummibärchen', label: 'Gummibärchen', price: 3.5 },
    { type: 'knabber', label: 'Knabber', price: 1.95 },
  ]

  onAddOrder = (PriceItem) => {
    this.setState({ orders: [...this.state.orders, PriceItem] });
  }

  onRemoveLastOrder = (PriceItem) => {
    this.setState({ orders: [...this.state.orders.slice(0, -1)] });
  }

  onResetOrders = (PriceItem) => {
    this.setState({ orders: [] });
  }

  getPriceForOrderType = (type) => {
    return this.types.find(t => t.type === type).price;
  }

  getLabelForOrderType = (type) => {
    return this.types.find(t => t.type === type).label;
  }

  getTotalPrice = () => {
    const { orders } = this.state;
    return orders.reduce((sum, order) => sum + this.getPriceForOrderType(order), 0);
  }

  render() {
    const { orders } = this.state;

    return (
      <Card title="Cashier">

          {this.types.map(({ type, label }) => (
            <OrderButton key={type} label={label} type={type} handleOnClick={this.onAddOrder} />
          ))}

        <Divider />

          <button onClick={this.onRemoveLastOrder}>Stornieren</button>
          <button onClick={this.onResetOrders}>Reset</button>

        {orders.length > 0 && <Divider />}

        {orders.map((orderType, i) => (
          <PriceItem
            key={i}
            label={this.getLabelForOrderType(orderType)}
            price={this.getPriceForOrderType(orderType)}
          />
        ))}

        <Divider />

          <PriceItem label="Total" price={this.getTotalPrice()} />

      </Card>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>WYMeditor.SKINS['refinery'] = {

	init: function(wym) {

		//render following sections as buttons
		$(wym._box).find(wym._options.toolsSelector)
			.addClass('wym_buttons');

		// auto add some margin to the main area sides if left area
		// or right area are not empty (if they contain sections)
		$(wym._box).find('div.wym_area_right ul')
			.parents('div.wym_area_right').show()
			.parents(wym._options.boxSelector)
			.find('div.wym_area_main')
			.css({'margin-right': '155px'});

		$(wym._box).find('div.wym_area_left ul')
			.parents('div.wym_area_left').show()
			.parents(wym._options.boxSelector)
			.find('div.wym_area_main')
			.css({'margin-left': '155px'});

		//make hover work under IE < 7
		$(wym._box).find('.wym_section').hover(function(){
			$(this).addClass('hover');
		},function(){
			$(this).removeClass('hover');
		});

    // adjust sizing
    $(wym._box).css('width', $(wym._element).width());
    $(wym).css({'height':$(wym).parent().height()-2, 'width':$(wym).parent().width()-2});

		$('.button').corner('6px');
	}
};
<commit_msg>adjust width code<commit_after>WYMeditor.SKINS['refinery'] = {

	init: function(wym) {

		//render following sections as buttons
		$(wym._box).find(wym._options.toolsSelector)
			.addClass('wym_buttons');

		// auto add some margin to the main area sides if left area
		// or right area are not empty (if they contain sections)
		$(wym._box).find('div.wym_area_right ul')
			.parents('div.wym_area_right').show()
			.parents(wym._options.boxSelector)
			.find('div.wym_area_main')
			.css({'margin-right': '155px'});

		$(wym._box).find('div.wym_area_left ul')
			.parents('div.wym_area_left').show()
			.parents(wym._options.boxSelector)
			.find('div.wym_area_main')
			.css({'margin-left': '155px'});

		//make hover work under IE < 7
		$(wym._box).find('.wym_section').hover(function(){
			$(this).addClass('hover');
		},function(){
			$(this).removeClass('hover');
		});

    // adjust sizing
    $(wym._box).css('width', $(wym._element).width()).find('.wym_iframe iframe').css('width', $(wym._box).width() - 2);

		$('.button').corner('6px');
	}
};
<|endoftext|>


<commit_before>/*
 * js-data-localforage
 * http://github.com/js-data/js-data-localforage
 *
 * Copyright (c) 2014 Jason Dobry <http://www.js-data.io/js-data-localforage>
 * Licensed under the MIT license. <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>
 */
module.exports = function (grunt) {
  'use strict';

  require('jit-grunt')(grunt, {
    coveralls: 'grunt-karma-coveralls'
  });
  require('time-grunt')(grunt);

  var pkg = grunt.file.readJSON('package.json');

  // Project configuration.
  grunt.initConfig({
    pkg: pkg,
    clean: {
      coverage: ['coverage/'],
      dist: ['dist/']
    },
    jshint: {
      all: ['Gruntfile.js', 'src/**/*.js', 'test/*.js'],
      jshintrc: '.jshintrc'
    },
    watch: {
      dist: {
        files: ['src/**/*.js'],
        tasks: ['build']
      }
    },
    uglify: {
      main: {
        options: {
          banner: '/**\n' +
            '* @author Jason Dobry <jason.dobry@gmail.com>\n' +
            '* @file js-data-localforage.min.js\n' +
            '* @version <%= pkg.version %> - Homepage <http://wwwjs-data.io/js-data-localforage>\n' +
            '* @copyright (c) 2014 Jason Dobry\n' +
            '* @license MIT <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>\n' +
            '*\n' +
            '* @overview My Adapter.\n' +
            '*/\n'
        },
        files: {
          'dist/js-data-localforage.min.js': ['dist/js-data-localforage.js']
        }
      }
    },
    browserify: {
      options: {
        browserifyOptions: {
          standalone: 'DSLocalForageAdapter'
        },
        external: ['js-data']
      },
      dist: {
        files: {
          'dist/js-data-localforage.js': ['src/index.js']
        }
      }
    },
    karma: {
      options: {
        configFile: './karma.conf.js'
      },
      dev: {
        browsers: ['Chrome'],
        autoWatch: true,
        singleRun: false,
        reporters: ['spec'],
        preprocessors: {}
      },
      min: {
        browsers: ['Firefox', 'PhantomJS'],
        options: {
          files: [
            'bower_components/js-data/dist/js-data.min.js',
            'dist/js-data-localforage.min.js',
            'karma.start.js',
            'test/**/*.js'
          ]
        }
      },
      ci: {
        browsers: ['Firefox', 'PhantomJS']
      }
    },
    coveralls: {
      options: {
        coverage_dir: 'coverage'
      }
    }
  });

  grunt.registerTask('version', function (filePath) {
    var file = grunt.file.read(filePath);

    file = file.replace(/<%= pkg\.version %>/gi, pkg.version);

    grunt.file.write(filePath, file);
  });

  grunt.registerTask('banner', function () {
    var file = grunt.file.read('dist/js-data-localforage.js');

    var banner = '/**\n' +
      '* @author Jason Dobry <jason.dobry@gmail.com>\n' +
      '* @file js-data-localforage.js\n' +
      '* @version ' + pkg.version + ' - Homepage <http://www.js-data.iojs-data-localforage/>\n' +
      '* @copyright (c) 2014 Jason Dobry \n' +
      '* @license MIT <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>\n' +
      '*\n' +
      '* @overview My Adapter.\n' +
      '*/\n';

    file = banner + file;

    grunt.file.write('dist/js-data-localforage.js', file);
  });

  grunt.registerTask('test', ['build', 'karma:ci', 'karma:min']);
  grunt.registerTask('build', [
    'clean',
    'jshint',
    'browserify',
    'banner',
    'uglify:main'
  ]);
  grunt.registerTask('go', ['build', 'watch:dist']);
  grunt.registerTask('default', ['build']);
};
<commit_msg>Fixed karma:min test.<commit_after>/*
 * js-data-localforage
 * http://github.com/js-data/js-data-localforage
 *
 * Copyright (c) 2014 Jason Dobry <http://www.js-data.io/js-data-localforage>
 * Licensed under the MIT license. <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>
 */
module.exports = function (grunt) {
  'use strict';

  require('jit-grunt')(grunt, {
    coveralls: 'grunt-karma-coveralls'
  });
  require('time-grunt')(grunt);

  var pkg = grunt.file.readJSON('package.json');

  // Project configuration.
  grunt.initConfig({
    pkg: pkg,
    clean: {
      coverage: ['coverage/'],
      dist: ['dist/']
    },
    jshint: {
      all: ['Gruntfile.js', 'src/**/*.js', 'test/*.js'],
      jshintrc: '.jshintrc'
    },
    watch: {
      dist: {
        files: ['src/**/*.js'],
        tasks: ['build']
      }
    },
    uglify: {
      main: {
        options: {
          banner: '/**\n' +
            '* @author Jason Dobry <jason.dobry@gmail.com>\n' +
            '* @file js-data-localforage.min.js\n' +
            '* @version <%= pkg.version %> - Homepage <http://wwwjs-data.io/js-data-localforage>\n' +
            '* @copyright (c) 2014 Jason Dobry\n' +
            '* @license MIT <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>\n' +
            '*\n' +
            '* @overview My Adapter.\n' +
            '*/\n'
        },
        files: {
          'dist/js-data-localforage.min.js': ['dist/js-data-localforage.js']
        }
      }
    },
    browserify: {
      options: {
        browserifyOptions: {
          standalone: 'DSLocalForageAdapter'
        },
        external: ['js-data']
      },
      dist: {
        files: {
          'dist/js-data-localforage.js': ['src/index.js']
        }
      }
    },
    karma: {
      options: {
        configFile: './karma.conf.js'
      },
      dev: {
        browsers: ['Chrome'],
        autoWatch: true,
        singleRun: false,
        reporters: ['spec'],
        preprocessors: {}
      },
      min: {
        browsers: ['Firefox', 'PhantomJS'],
        options: {
          files: [
            'bower_components/localforage/dist/localforage.js',
            'bower_components/js-data/dist/js-data.min.js',
            'dist/js-data-localforage.min.js',
            'karma.start.js',
            'test/**/*.js'
          ]
        }
      },
      ci: {
        browsers: ['Firefox', 'PhantomJS']
      }
    },
    coveralls: {
      options: {
        coverage_dir: 'coverage'
      }
    }
  });

  grunt.registerTask('version', function (filePath) {
    var file = grunt.file.read(filePath);

    file = file.replace(/<%= pkg\.version %>/gi, pkg.version);

    grunt.file.write(filePath, file);
  });

  grunt.registerTask('banner', function () {
    var file = grunt.file.read('dist/js-data-localforage.js');

    var banner = '/**\n' +
      '* @author Jason Dobry <jason.dobry@gmail.com>\n' +
      '* @file js-data-localforage.js\n' +
      '* @version ' + pkg.version + ' - Homepage <http://www.js-data.iojs-data-localforage/>\n' +
      '* @copyright (c) 2014 Jason Dobry \n' +
      '* @license MIT <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>\n' +
      '*\n' +
      '* @overview My Adapter.\n' +
      '*/\n';

    file = banner + file;

    grunt.file.write('dist/js-data-localforage.js', file);
  });

  grunt.registerTask('test', ['build', 'karma:ci', 'karma:min']);
  grunt.registerTask('build', [
    'clean',
    'jshint',
    'browserify',
    'banner',
    'uglify:main'
  ]);
  grunt.registerTask('go', ['build', 'watch:dist']);
  grunt.registerTask('default', ['build']);
};
<|endoftext|>


<commit_before>import express from 'express'
import path from 'path'
// import compression from 'compression'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { match, RouterContext } from 'react-router'
import rootReducer from '../universal/shared/reducers'
import routes from '../universal/routes'

const app = express()

// app.use(compression())

// serve our static stuff like index.css
app.use(express.static(path.join(__dirname, '../public')))

// send all requests to index.html so browserHistory works
app.use((req, res) => {
  match({ routes, location: req.url }, (err, redirect, props) => {
    if (err) {
      res.status(500).send(err.message)
    } else if (redirect) {
      res.redirect(redirect.pathname + redirect.search)
    } else if (props) {
      // hey we made it!
      // Create a new Redux store instance
      const store = createStore(rootReducer)
      // Render the component to a string
      const html = renderToString(
        <Provider store={store}>
          <RouterContext {...props}/>
        </Provider>
      )
      // Grab the initial state from our Redux store
      const initialState = store.getState()
      // Send the rendered page back to the client
      res.send(renderPage(html, initialState))
    } else {
      res.status(404).send('Not Found')
    }
  })
})

function renderPage(html, initialState) {
  return `
    <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Shandy Club</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" media="(device-height: 568px)" />
    <link rel="stylesheet" href="style.css" media="screen" charset="utf-8">

${html}

   `
}

const NODE_IP = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
const NODE_PORT = process.env.OPENSHIFT_NODEJS_PORT || 8080

const server = app.listen(NODE_PORT, NODE_IP, () => {

  console.log(`Production Express server running at http://${server.address().address}:${server.address().port}`)

})
<commit_msg>remove openshift server settings<commit_after>import express from 'express'
import path from 'path'
// import compression from 'compression'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { match, RouterContext } from 'react-router'
import rootReducer from '../universal/shared/reducers'
import routes from '../universal/routes'

const app = express()

// app.use(compression())

// serve our static stuff like index.css
app.use(express.static(path.join(__dirname, '../public')))

// send all requests to index.html so browserHistory works
app.use((req, res) => {
  match({ routes, location: req.url }, (err, redirect, props) => {
    if (err) {
      res.status(500).send(err.message)
    } else if (redirect) {
      res.redirect(redirect.pathname + redirect.search)
    } else if (props) {
      // hey we made it!
      // Create a new Redux store instance
      const store = createStore(rootReducer)
      // Render the component to a string
      const html = renderToString(
        <Provider store={store}>
          <RouterContext {...props}/>
        </Provider>
      )
      // Grab the initial state from our Redux store
      const initialState = store.getState()
      // Send the rendered page back to the client
      res.send(renderPage(html, initialState))
    } else {
      res.status(404).send('Not Found')
    }
  })
})

function renderPage(html, initialState) {
  return `
    <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Shandy Club</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" media="(device-height: 568px)" />
    <link rel="stylesheet" href="style.css" media="screen" charset="utf-8">

${html}

   `
}

const NODE_IP = '127.0.0.1'
const NODE_PORT = process.env.PORT || 8000

const server = app.listen(NODE_PORT, NODE_IP, () => {

  console.log(`🍺  Production server running at http://${server.address().address}:${server.address().port}`)

})
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var log = require('./libs/log')(module);
var config = require('./config');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var fs = require('fs');

var app = express();
//app.disable('x-powered-by');

app.set('port', config.get('port'));

app.use(cookieParser(config.get('session:cookie:cookieSecret')));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
//
app.use(bodyParser({ uploadDir: path.join(__dirname, 'files'), keepExtensions: true }));
//parse application/json
app.use(bodyParser.json());
//
app.use(methodOverride());

var sessionOption = {
    secret: config.get("session:secret"),
    key: config.get("session:key"),
//    store: new RedisStore(redisOption),
    cookie: {
        path     : '/',
        httpOnly : config.get('session:cookie:httpOnly'),
        maxAge   : config.get('session:cookie:maxAge')
    }
}

app.use(expressSession(sessionOption));

//app.use(function(req, res, next) {
//    res.header('Access-Control-Allow-Credentials', true);
//    res.header('Access-Control-Allow-Origin',      req.headers.origin);
//    res.header('Access-Control-Allow-Methods',     'GET,POST,PUT,DELETE');
//    res.header('Access-Control-Allow-Headers',     'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
//    next();
//});
//app.use(setControl);

// Enables CORS
var enableCORS = function(req, res, next) {
    // TODO :)
    //res.setHeader( 'X-Powered-By', 'Webitel CDR server' ); //
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    //res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }
};
// enable CORS!
app.use(enableCORS);

require('./routes')(app);

app.use(function(req, res, next){
    res.status(404);
    res.send({ error: 'Not found' });
    return;
});

app.use(function(err, req, res, next){
    res.status(err.status || 500);
    res.send({ error: err.message });
    return;
});

var useSSL = config.get('session:ssl:enabled');
if (useSSL) {
    console.log('useSSL = true');
    var key = fs.readFileSync(config.get('session:ssl:ssl_key'));
    var cert = fs.readFileSync(config.get('session:ssl:ssl_cert'));
    var https = require('https');
    var https_options = {
        key: key,
        cert: cert
    };
    var httpsServer = https.createServer(https_options, app).listen(app.get('port'), function() {
        console.log('Express server (https) listening on port ' + server.address().port);
    });
};
var httpServer = app.listen(app.get('port'), function() {
    console.log('Express server (http) listening on port ' + server.address().port);
});<commit_msg>fix console log port<commit_after>var express = require('express');
var path = require('path');
var log = require('./libs/log')(module);
var config = require('./config');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var fs = require('fs');

var app = express();
//app.disable('x-powered-by');

app.set('port', config.get('port'));

app.use(cookieParser(config.get('session:cookie:cookieSecret')));

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
//
app.use(bodyParser({ uploadDir: path.join(__dirname, 'files'), keepExtensions: true }));
//parse application/json
app.use(bodyParser.json());
//
app.use(methodOverride());

var sessionOption = {
    secret: config.get("session:secret"),
    key: config.get("session:key"),
//    store: new RedisStore(redisOption),
    cookie: {
        path     : '/',
        httpOnly : config.get('session:cookie:httpOnly'),
        maxAge   : config.get('session:cookie:maxAge')
    }
}

app.use(expressSession(sessionOption));

//app.use(function(req, res, next) {
//    res.header('Access-Control-Allow-Credentials', true);
//    res.header('Access-Control-Allow-Origin',      req.headers.origin);
//    res.header('Access-Control-Allow-Methods',     'GET,POST,PUT,DELETE');
//    res.header('Access-Control-Allow-Headers',     'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
//    next();
//});
//app.use(setControl);

// Enables CORS
var enableCORS = function(req, res, next) {
    // TODO :)
    //res.setHeader( 'X-Powered-By', 'Webitel CDR server' ); //
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    //res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }
};
// enable CORS!
app.use(enableCORS);

require('./routes')(app);

app.use(function(req, res, next){
    res.status(404);
    res.send({ error: 'Not found' });
    return;
});

app.use(function(err, req, res, next){
    res.status(err.status || 500);
    res.send({ error: err.message });
    return;
});

var useSSL = config.get('session:ssl:enabled');
if (useSSL) {
    console.log('useSSL = true');
    var key = fs.readFileSync(config.get('session:ssl:ssl_key'));
    var cert = fs.readFileSync(config.get('session:ssl:ssl_cert'));
    var https = require('https');
    var https_options = {
        key: key,
        cert: cert
    };
    var httpsServer = https.createServer(https_options, app).listen(app.get('port'), function() {
        console.log('Express server (https) listening on port ' + httpsServer.address().port);
    });
};
var httpServer = app.listen(app.get('port'), function() {
    console.log('Express server (http) listening on port ' + httpServer.address().port);
});<|endoftext|>


<commit_before>/**
 * ChatApp namespace
 * ================
 *
 * The ChatApp namespace contains all the other objects in this
 * application.
 */
window.ChatApp = { };

/**
 * Message Model
 * ===================
 *
 * The message model represents a single message.
 *
 * Messages have a 'dateTime', a 'nickName' and a 'content' attribute.
 */
window.ChatApp.Message = Backbone.Model.extend({

    initialize : function() {

        // If no date/time was set, we assume this message is created 'now'.
        if (!this.get('dateTime')) {
            this.set({ dateTime: new Date() });
        }

    }

});

/**
 * Message Collection
 * ===================
 *
 * The messages collection contains the list of messages.
 */
window.ChatApp.MessageCollection = Backbone.Collection.extend({

    model: ChatApp.Message

});

/**
 * User Model
 * ==========
 *
 * The users model represents a single (online) user.
 */
window.ChatApp.User = Backbone.Model.extend({

    initialize : function() {

    }

});

/**
 * User Collection
 * ===============
 *
 * The user collection contains the list of online users.
 */
window.ChatApp.UserCollection = Backbone.Collection.extend({

    model: ChatApp.User

});

/**
 * Connection
 * ==========
 *
 * The connection is responsible for connecting to the server, sending
 * messages and receiving events.
 */
window.ChatApp.Connection = function(userCollection, messageCollection, nickName, email) {

    this.userCollection = userCollection;
    this.messageCollection = messageCollection;
    this.nickName = nickName;
    this.email = email;

    this.listen();
    this.join();

};
_.extend(window.ChatApp.Connection.prototype, Backbone.Events, {

    userCollection : null,
    messageCollection : null,
    lastSequence : 0,

    listen : function() {

        var self = this;

        $.ajax('/eventpoll?since=' + this.lastSequence + '&nickName=' + this.nickName + '&email=' + this.email, {
            dataType : 'json',
            complete : function(jqXHR, textStatus) {
                self.listen();
            },
            success : function(data) {
                for(var ii=0;ii<data.length;ii++) {
                    var event = data[ii];
                    self.lastSequence = event.sequence;
                    switch(event.type) {

                        case 'message' :
                            console.log('MESSAGE: ' + event.nickName);
                            self.messageCollection.add({
                                message : event.message,
                                nickName : event.nickName,
                                dateTime : new Date(event.dateTime),
                                gravatar : event.gravatar
                            });
                            break;
                        case 'join' :
                            console.log('JOIN: ' + event.nickName);
                            self.userCollection.add({
                                nickName : event.nickName,
                                gravatar : event.gravatar
                            });
                            break;
                        case 'part' :
                            console.log('PART: ' + event.nickName);
                            self.userCollection.remove(
                                self.userCollection.find(
                                    function(item) { return item.get('nickName') === event.nickName; }
                                )
                            );
                            break;
                        default :
                            console.log('Unknown event: ' + event.type);
                            break;

                    }
                }
            }

        });

    },

    join : function() {

        $.ajax('/join?nickName=' + this.nickName + '&email=' + this.email);

    },

    message : function(message) {

        $.ajax('/message?nickName=' + this.nickName + '&email=' + this.email + '&message=' + message);

    }

});

/**
 * MessageList view
 * ================
 *
 * This view is responsible for updating the list of messages.
 * You must pass a 'collection' option, which should be an instance of
 * MessageCollection
 */
window.ChatApp.MessageListView = Backbone.View.extend({

    initialize : function() {

        if (!this.collection) {
            throw "To initialize the MessageList view, you must pass the 'collection' option.";
        }

        var self = this;
        this.collection.bind('add', function(message) {
            self.addMessage(message);
        });

    },

    addMessage : function(message) {

        var newElem = this.$('li.template').clone();
        newElem.removeClass('template');

        newElem.find('.nickName').text(message.get('nickName'));

        var ft = message.get('dateTime');

        var hour = ft.getHours();
        var min = ft.getMinutes();
        if (min<10) min = '0' + min;
        var sec = ft.getSeconds();
        if (sec<10) sec = '0' + sec;

        formattedTime = hour + ':' + min + ':' + sec;

        newElem.find('time').text(formattedTime);
        newElem.find('p').text(message.get('message'));
        newElem.css({
            backgroundImage: "url('" + message.get('gravatar') + "?s=55&d=retro')"
        });
        this.el.append(newElem);

        this.el.scrollTop(this.el[0].scrollHeight);

    }

});

/**
 * MessageInput view
 * ================
 *
 * This view is responsible for the 'input' area, which allows the user to
 * send a message to the chatroom.
 *
 * You must pass a 'connection' option, which should be an instance of
 * ChatApp.connection
 */
window.ChatApp.MessageInputView = Backbone.View.extend({

    events: {
        "submit form" : "submitMessage"
    },

    initialize : function() {

        if (!this.options.connection) {
            throw "To initialize the MessageInputView, you must pass the 'connection' option.";
        }

    },

    submitMessage : function(evt) {

        evt.preventDefault();

        var input = this.$('input');

        var message = {
            message: input.val()
        };

        if (message.message.length < 1) return;

        // Adding a new message to the collection
        this.options.connection.message(message.message);

        // Resetting the input field
        input.val('');

    }

});

/**
 * UserList view
 * ================
 *
 * This view is responsible for keeping the list of online users up to
 * date.
 * You must pass a 'collection' option, which should be an instance of
 * UserCollection
 */
window.ChatApp.UserListView = Backbone.View.extend({

    initialize : function() {

        if (!this.collection) {
            throw "To initialize the MessageList view, you must pass the 'collection' option.";
        }

        var self = this;
        this.collection.bind('add', function(user) {
            self.addUser(user);
        });
        this.collection.bind('remove', function(user) {
            self.removeUser(user);
        });

    },

    addUser : function(user) {

        var newElem = this.$('li.template').clone();
        newElem.removeClass('template');

        newElem.text(user.get('nickName'));
        newElem.attr('id','user-' + user.get('nickName'));

        newElem.css({
            backgroundImage: "url('" + user.get('gravatar') + "?s=25&d=retro')"
        });
        this.el.append(newElem);

    },

    removeUser : function(user) {

       $('#user-' + user.get('nickName')).remove();

    },

});

window.ChatApp.WelcomeView = Backbone.View.extend({

    events : {
        "submit form" : "connect"
    },

    connect : function(evt) {

        evt.preventDefault();
        this.el.hide();
        var nickName = this.$('input[name=nickName]').val();
        var email = this.$('input[name=email]').val();

        this.trigger('connect', {
            nickName : nickName,
            email : email
        });

    }

});

/**
 * The Application View
 * ====================
 *
 * The Application View is basically the main Application controller, and
 * is responsible for setting up all the other objects.
 */
window.ChatApp.Application = Backbone.View.extend({

    messageCollection : null,
    userCollection : null,

    messageListView : null,
    messageInputView : null,
    userListView : null,
    welcomeView : null,

    connection : null,

    nickName : null,
    email : null,

    el: 'body',

    initialize : function() {

        var self = this;

        this.messageCollection = new ChatApp.MessageCollection();
        this.userCollection = new ChatApp.UserCollection();

        this.welcomeView = new ChatApp.WelcomeView({
            el : this.$('section.welcome')
        });
        this.welcomeView.bind('connect', function(userInfo) {
            self.nickName = userInfo.nickName;
            self.email = userInfo.email;
            self.initializeConnection();
        });

    },
    initializeConnection : function() {

        this.connection = new ChatApp.Connection(this.userCollection, this.messageCollection, this.nickName, this.email);

        this.messageListView = new ChatApp.MessageListView({
            collection: this.messageCollection,
            el : this.$('section.messages')
        });
        this.messageInputView = new ChatApp.MessageInputView({
            connection: this.connection,
            el: this.$('section.inputArea')
        });
        this.userListView = new ChatApp.UserListView({
            collection: this.userCollection,
            el: this.$('section.userList')
        });

    },

});

/**
 * Using jQuery's DOM.ready
 */
$(function() {

    window.ChatApp.application = new ChatApp.Application;

});
<commit_msg>Fixed race condition where starting both long polling and joining would result in the join happening first and the long polling not picking it up. Ideally you'd want to get some signal from the long polling that it's atteneas are up, aligned and ready to receive, before you do the join, but with long polling that's difficult, so the next best thing, just start polling after we're joined and pick up any events that happened before it then.<commit_after>/**
 * ChatApp namespace
 * ================
 *
 * The ChatApp namespace contains all the other objects in this
 * application.
 */
window.ChatApp = { };

/**
 * Message Model
 * ===================
 *
 * The message model represents a single message.
 *
 * Messages have a 'dateTime', a 'nickName' and a 'content' attribute.
 */
window.ChatApp.Message = Backbone.Model.extend({

    initialize : function() {

        // If no date/time was set, we assume this message is created 'now'.
        if (!this.get('dateTime')) {
            this.set({ dateTime: new Date() });
        }

    }

});

/**
 * Message Collection
 * ===================
 *
 * The messages collection contains the list of messages.
 */
window.ChatApp.MessageCollection = Backbone.Collection.extend({

    model: ChatApp.Message

});

/**
 * User Model
 * ==========
 *
 * The users model represents a single (online) user.
 */
window.ChatApp.User = Backbone.Model.extend({

    initialize : function() {

    }

});

/**
 * User Collection
 * ===============
 *
 * The user collection contains the list of online users.
 */
window.ChatApp.UserCollection = Backbone.Collection.extend({

    model: ChatApp.User

});

/**
 * Connection
 * ==========
 *
 * The connection is responsible for connecting to the server, sending
 * messages and receiving events.
 */
window.ChatApp.Connection = function(userCollection, messageCollection, nickName, email) {

    this.userCollection = userCollection;
    this.messageCollection = messageCollection;
    this.nickName = nickName;
    this.email = email;

    var self = this;
    this.join(function() {
        self.listen();
    });

};
_.extend(window.ChatApp.Connection.prototype, Backbone.Events, {

    userCollection : null,
    messageCollection : null,
    lastSequence : 0,

    listen : function() {

        var self = this;

        $.ajax('/eventpoll?since=' + this.lastSequence + '&nickName=' + this.nickName + '&email=' + this.email, {
            dataType : 'json',
            complete : function(jqXHR, textStatus) {
                self.listen();
            },
            success : function(data) {
                for(var ii=0;ii<data.length;ii++) {
                    var event = data[ii];
                    self.lastSequence = event.sequence;
                    switch(event.type) {

                        case 'message' :
                            console.log('MESSAGE: ' + event.nickName);
                            self.messageCollection.add({
                                message : event.message,
                                nickName : event.nickName,
                                dateTime : new Date(event.dateTime),
                                gravatar : event.gravatar
                            });
                            break;
                        case 'join' :
                            console.log('JOIN: ' + event.nickName);
                            self.userCollection.add({
                                nickName : event.nickName,
                                gravatar : event.gravatar
                            });
                            break;
                        case 'part' :
                            console.log('PART: ' + event.nickName);
                            self.userCollection.remove(
                                self.userCollection.find(
                                    function(item) { return item.get('nickName') === event.nickName; }
                                )
                            );
                            break;
                        default :
                            console.log('Unknown event: ' + event.type);
                            break;

                    }
                }
            }

        });

    },

    join : function(onSuccess) {

        $.ajax('/join?nickName=' + this.nickName + '&email=' + this.email, { success: onSuccess });

    },

    message : function(message) {

        $.ajax('/message?nickName=' + this.nickName + '&email=' + this.email + '&message=' + message);

    }

});

/**
 * MessageList view
 * ================
 *
 * This view is responsible for updating the list of messages.
 * You must pass a 'collection' option, which should be an instance of
 * MessageCollection
 */
window.ChatApp.MessageListView = Backbone.View.extend({

    initialize : function() {

        if (!this.collection) {
            throw "To initialize the MessageList view, you must pass the 'collection' option.";
        }

        var self = this;
        this.collection.bind('add', function(message) {
            self.addMessage(message);
        });

    },

    addMessage : function(message) {

        var newElem = this.$('li.template').clone();
        newElem.removeClass('template');

        newElem.find('.nickName').text(message.get('nickName'));

        var ft = message.get('dateTime');

        var hour = ft.getHours();
        var min = ft.getMinutes();
        if (min<10) min = '0' + min;
        var sec = ft.getSeconds();
        if (sec<10) sec = '0' + sec;

        formattedTime = hour + ':' + min + ':' + sec;

        newElem.find('time').text(formattedTime);
        newElem.find('p').text(message.get('message'));
        newElem.css({
            backgroundImage: "url('" + message.get('gravatar') + "?s=55&d=retro')"
        });
        this.el.append(newElem);

        this.el.scrollTop(this.el[0].scrollHeight);

    }

});

/**
 * MessageInput view
 * ================
 *
 * This view is responsible for the 'input' area, which allows the user to
 * send a message to the chatroom.
 *
 * You must pass a 'connection' option, which should be an instance of
 * ChatApp.connection
 */
window.ChatApp.MessageInputView = Backbone.View.extend({

    events: {
        "submit form" : "submitMessage"
    },

    initialize : function() {

        if (!this.options.connection) {
            throw "To initialize the MessageInputView, you must pass the 'connection' option.";
        }

    },

    submitMessage : function(evt) {

        evt.preventDefault();

        var input = this.$('input');

        var message = {
            message: input.val()
        };

        if (message.message.length < 1) return;

        // Adding a new message to the collection
        this.options.connection.message(message.message);

        // Resetting the input field
        input.val('');

    }

});

/**
 * UserList view
 * ================
 *
 * This view is responsible for keeping the list of online users up to
 * date.
 * You must pass a 'collection' option, which should be an instance of
 * UserCollection
 */
window.ChatApp.UserListView = Backbone.View.extend({

    initialize : function() {

        if (!this.collection) {
            throw "To initialize the MessageList view, you must pass the 'collection' option.";
        }

        var self = this;
        this.collection.bind('add', function(user) {
            self.addUser(user);
        });
        this.collection.bind('remove', function(user) {
            self.removeUser(user);
        });

    },

    addUser : function(user) {

        var newElem = this.$('li.template').clone();
        newElem.removeClass('template');

        newElem.text(user.get('nickName'));
        newElem.attr('id','user-' + user.get('nickName'));

        newElem.css({
            backgroundImage: "url('" + user.get('gravatar') + "?s=25&d=retro')"
        });
        this.el.append(newElem);

    },

    removeUser : function(user) {

       $('#user-' + user.get('nickName')).remove();

    },

});

window.ChatApp.WelcomeView = Backbone.View.extend({

    events : {
        "submit form" : "connect"
    },

    connect : function(evt) {

        evt.preventDefault();
        this.el.hide();
        var nickName = this.$('input[name=nickName]').val();
        var email = this.$('input[name=email]').val();

        this.trigger('connect', {
            nickName : nickName,
            email : email
        });

    }

});

/**
 * The Application View
 * ====================
 *
 * The Application View is basically the main Application controller, and
 * is responsible for setting up all the other objects.
 */
window.ChatApp.Application = Backbone.View.extend({

    messageCollection : null,
    userCollection : null,

    messageListView : null,
    messageInputView : null,
    userListView : null,
    welcomeView : null,

    connection : null,

    nickName : null,
    email : null,

    el: 'body',

    initialize : function() {

        var self = this;

        this.messageCollection = new ChatApp.MessageCollection();
        this.userCollection = new ChatApp.UserCollection();

        this.welcomeView = new ChatApp.WelcomeView({
            el : this.$('section.welcome')
        });
        this.welcomeView.bind('connect', function(userInfo) {
            self.nickName = userInfo.nickName;
            self.email = userInfo.email;
            self.initializeConnection();
        });

    },
    initializeConnection : function() {

        this.connection = new ChatApp.Connection(this.userCollection, this.messageCollection, this.nickName, this.email);

        this.messageListView = new ChatApp.MessageListView({
            collection: this.messageCollection,
            el : this.$('section.messages')
        });
        this.messageInputView = new ChatApp.MessageInputView({
            connection: this.connection,
            el: this.$('section.inputArea')
        });
        this.userListView = new ChatApp.UserListView({
            collection: this.userCollection,
            el: this.$('section.userList')
        });

    },

});

/**
 * Using jQuery's DOM.ready
 */
$(function() {

    window.ChatApp.application = new ChatApp.Application;

});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import classNames from 'classnames';
import Card from './Card';
import css from './Dialog.css';

const Dialog = ({ visible, title, onClose, children }) => {
  const dialogClass = classNames(css.component, {
    [css.visible]: visible,
  });
  return (

      <Card
        classes={css.dialog}
        title={title}
        corner={

        }
      >
        {children}
      </Card>

  );
};

Dialog.defaultProps = {
  visible: false,
};

Dialog.propTypes = {
  visible: PropTypes.bool,
  title: PropTypes.string.isRequired,
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
  onClose: PropTypes.func.isRequired,
};

export default Dialog;
<commit_msg>Make it possible to hide close symbol of dialog (#81)<commit_after>import React, { PropTypes } from 'react';
import classNames from 'classnames';
import Card from './Card';
import css from './Dialog.css';

const Dialog = ({ visible, title, onClose, children, hideCloseSymbol }) => {
  const dialogClass = classNames(css.component, {
    [css.visible]: visible,
  });
  // eslint-disable-next-line jsx-a11y/no-static-element-interactions
  const corner = !hideCloseSymbol &&
;
  return (

      <Card
        classes={css.dialog}
        title={title}
        corner={corner}
      >
        {children}
      </Card>

  );
};

Dialog.defaultProps = {
  hideCloseSymbol: false,
  visible: false,
};

Dialog.propTypes = {
  hideCloseSymbol: PropTypes.bool,
  visible: PropTypes.bool,
  title: PropTypes.string.isRequired,
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
  onClose: PropTypes.func.isRequired,
};

export default Dialog;
<|endoftext|>


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

  angular.module('app.states')
    .run(appRun);

  /** @ngInject */
  function appRun(routerHelper, navigationHelper) {
    routerHelper.configureStates(getStates());
    navigationHelper.navItems(navItems());
    navigationHelper.sidebarItems(sidebarItems());
  }

  function getStates() {
    return {
      'admin.cms.create': {
        url: '/create',
        templateUrl: 'app/states/admin/cms/create/create.html',
        controller: StateController,
        controllerAs: 'vm',
        title: 'Admin CMS Create',
        resolve: {
          contentPageRecord: resolveContentPage
        }
      }
    };
  }

  function navItems() {
    return {};
  }

  function sidebarItems() {
    return {};
  }

  /** @ngInject */
  function resolveContentPage($stateParams, ContentPage) {
    return {};
  }

  /** @ngInject */
  function StateController(logger, contentPageRecord, $stateParams) {
    var vm = this;

    vm.title = 'Admin CMS Create';
    vm.contentPageRecord = contentPageRecord;
    vm.activate = activate;
    vm.home = 'admin.cms.list';
    vm.homeParams = { };

    activate();

    function activate() {
      logger.info('Activated Admin CMS Create View');
    }
  }
})();
<commit_msg>Return content page resource. Previously returning empty object for create which prevented the use of $ prefixed methods.<commit_after>(function() {
  'use strict';

  angular.module('app.states')
    .run(appRun);

  /** @ngInject */
  function appRun(routerHelper, navigationHelper) {
    routerHelper.configureStates(getStates());
    navigationHelper.navItems(navItems());
    navigationHelper.sidebarItems(sidebarItems());
  }

  function getStates() {
    return {
      'admin.cms.create': {
        url: '/create',
        templateUrl: 'app/states/admin/cms/create/create.html',
        controller: StateController,
        controllerAs: 'vm',
        title: 'Admin CMS Create',
        resolve: {
          contentPageRecord: resolveContentPage
        }
      }
    };
  }

  function navItems() {
    return {};
  }

  function sidebarItems() {
    return {};
  }

  /** @ngInject */
  function resolveContentPage($stateParams, ContentPage) {
    return new ContentPage();
  }

  /** @ngInject */
  function StateController(logger, contentPageRecord, $stateParams) {
    var vm = this;

    vm.title = 'Admin CMS Create';
    vm.contentPageRecord = contentPageRecord;
    vm.activate = activate;
    vm.home = 'admin.cms.list';
    vm.homeParams = { };

    activate();

    function activate() {
      logger.info('Activated Admin CMS Create View');
    }
  }
})();
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-keys-list@isnot
// @name           IITC plugin: Keys List
// @category       Keys
// @version        0.3.20160818
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @author         isnot
// @updateURL      none
// @downloadURL    none
// @description    [iitc-plugins] Export the manually entered key counts from the 'keys' plugin.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
  // ensure plugin framework is there, even if iitc is not yet loaded
  if (typeof window.plugin !== 'function') window.plugin = function() {};

  // PLUGIN START ////////////////////////////////////////////////////////

  // if the Keys/Cache plugin is not available, quit now
  if (!window.plugin.keys) {
    return console.warn("[KeysList] This plugin is dependent on the Keys plugin being present.");
  }
  if (!window.plugin.cachePortalDetailsOnMap) {
    return console.warn("[KeysList] This plugin is dependent on the Cache plugin being present.");
  }

  // Expand Cache BEGIN //////////////////////////////////////////////////////////
  var cache = window.plugin.cachePortalDetailsOnMap;
  cache.KEY_LOCALSTRAGE = 'plugin-cache-local-v1';

  cache.getPortalByGuid = function (guid) {
    var portal_cache = cache.cache[guid];

    // what is this?
    if (portal_cache && (portal_cache.length === 3)) {
      portal_cache.ent = delete portal_cache[2];
    }

    if (portal_cache && portal_cache.ent) {
      console.log('==KeysList gpbg ' + Object.keys(portal_cache).join(' '));
      return window.decodeArray.portalSummary(portal_cache.ent);
    }
  };

  cache.storeToLocal = function () {
    var lc = cache.cache;
    if (Object.keys(lc).length) {
      $.each(lc, function(guid, data) {
        if (data.ent) console.log(data.ent);
        // I dont know what I do...
        if ((typeof data.ent === 'object') && (data.ent.length === 3)) {
          data.ent = data.ent[2];
          data.loadtime = data.ent[1];
          delete data.ent[0];
          delete data.ent[1];
          delete data.ent[2];
        }
        lc[guid] = data;
      });
      localStorage.setItem(cache.KEY_LOCALSTRAGE, JSON.stringify(lc));
    }

    console.log('plugin-cache-local: storeToLocal ' + Object.keys(lc).length);
  };

  cache.loadFromLocal = function () {
    // if an existing portal cache, load it
    var raw = window.localStorage[cache.KEY_LOCALSTRAGE];
    if (raw) {
      cache.merge(JSON.parse(raw));
      console.log('plugin-cache-local: loadFromLocal ' + Object.keys(cache.cache).length);
    } else {
      // make a new cache
      window.localStorage[cache.KEY_LOCALSTRAGE] = "{}";
      console.log('plugin-cache-local: init');
    }
  };

  cache.merge = function (inbound) {
    //if (cache.cache.length < 1) {
    //  cache.cache = inbound;
    //  return inbound.length;
    //}

    $.each(inbound, function (guid, data) {
      console.log('==KeysList merge ' + Object.keys(data.ent).join(' '));
      if (data.ent && !cache.cache.hasOwnProperty(guid)) {
        cache.cache[guid] = data;
        console.log(data);
      }
    });
    return Object.keys(cache.cache).length;
  };

  // Expand Cache END //////////////////////////////////////////////////////////

  // use own namespace for plugin
  window.plugin.keysList = function() {};
  var self = window.plugin.keysList;
  self.INTEL_URL = 'https://www.ingress.com/intel';
  self.DEFAULT_ZOOM_LEVEL = '17';
  self.listAll = [];

  // fetch a portal info from a cached list if available
  self.getPortalDetails = function getPortalDetails(key) {
    var title = "(not detected)";
    var latLng = '0,0';
    var imageUrl = '';

    // try plugin cache
    var portal_cache = cache.getPortalByGuid(key.guid);
    if (portal_cache) {
      title = portal_cache.title;
      imageUrl = window.fixPortalImageUrl(portal_cache.image);
      console.log('==KsysList pc ' + portal_cache + Object.keys(portal_cache).join(' '));
    }

    var data = (window.portals[key.guid] && window.portals[key.guid].options.data) || window.portalDetail.get(key.guid) || null;
    if (data) {
      console.log('==KsysList pd ' + data.title);
      if (data.title) title = data.title;
      imageUrl = window.fixPortalImageUrl(data.image);
    }

    if (imageUrl.indexOf('//') === 0) {
      imageUrl = 'http:' + imageUrl;
    }
    if (imageUrl.indexOf(DEFAULT_PORTAL_IMG) !== -1) {
      imageUrl = '';
    }

    var hLatLng = window.findPortalLatLng(key.guid);
    if (hLatLng) {
      latLng = hLatLng.lat + ',' + hLatLng.lng;
    }

    key.title = title;
    key.latLng = latLng;
    key.imageUrl = imageUrl;
    if (latLng === '0,0') {
      key.intelMapUrl = '';
    } else {
      key.intelMapUrl = self.INTEL_URL + '?ll=' + latLng + '&z=' + self.DEFAULT_ZOOM_LEVEL + '&pll=' + latLng;
    }

    return key;
  };

  self.csvValue = function(str) {
    if (str) {
      return '"' + str.replace("/\"/g", '""') + '"';
    } else {
      return '';
    }
  };

  self.eachKey = function(key) {
    if (key.count > 0) {
      key = self.getPortalDetails(key);
      var csvline = [
        self.csvValue(key.title),
        parseInt(key.count, 10),
        self.csvValue(key.latLng),
        self.csvValue(key.intelMapUrl),
        self.csvValue(key.imageUrl),
        key.guid
      ];
      self.listAll.push(csvline.join(","));
    }
  };

  self.renderList = function() {
    self.listAll = [];

    $.each(plugin.keys.keys, function(key, count) {
      self.eachKey({"guid": key, "count": count});
    });

    var html = '
KeysList for ' + window.PLAYER.nickname + ' ' + self.listAll.length + 'portals of keys. ' + new Date().toISOString() +
        '
<textarea cols="78" rows="20">name,count,latlng,intelmap,image,guid' + "\n" + self.listAll.join("\n") + '</textarea>';
    dialog({
      title: 'KeysList',
      html: html,
      width: 600,
      position: {my: 'right center', at: 'center-60 center', of: window, collision: 'fit'}
    });
    // console.log("==KeysList " + window.PLAYER.nickname + " " + self.listAll.length + " " + new Date().toISOString());

    cache.storeToLocal();// for debug
  };

  var setup = function() {
    // console.log("==KeysList setup ");
    $('#toolbox').append('KeysListCsv');
    addHook('iitcLoaded',        window.plugin.cachePortalDetailsOnMap.loadFromLocal);
    addHook('mapDataRefreshEnd', window.plugin.cachePortalDetailsOnMap.storeToLocal);
  };

  // PLUGIN END //////////////////////////////////////////////////////////

  setup.info = plugin_info; //add the script info data to the function as a property
  if(!window.bootPlugins) window.bootPlugins = [];
  window.bootPlugins.push(setup);
  // if IITC has already booted, immediately run the 'setup' function
  if(window.iitcLoaded && typeof setup === 'function') setup();
} // wrapper end
// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);
<commit_msg>fix cache / update html<commit_after>// ==UserScript==
// @id             iitc-plugin-keys-list@isnot
// @name           IITC plugin: Keys List
// @category       Keys
// @version        0.3.20160818
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @author         isnot
// @updateURL      none
// @downloadURL    none
// @description    [iitc-plugins] Export the manually entered key counts from the 'keys' plugin.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
  // ensure plugin framework is there, even if iitc is not yet loaded
  if (typeof window.plugin !== 'function') window.plugin = function() {};

  // PLUGIN START ////////////////////////////////////////////////////////

  // if the Keys/Cache plugin is not available, quit now
  if (!window.plugin.keys) {
    return console.warn("[KeysList] This plugin is dependent on the Keys plugin being present.");
  }
  if (!window.plugin.cachePortalDetailsOnMap) {
    return console.warn("[KeysList] This plugin is dependent on the Cache plugin being present.");
  }

  // Expand Cache BEGIN //////////////////////////////////////////////////////////
  var cache = window.plugin.cachePortalDetailsOnMap;
  cache.KEY_LOCALSTRAGE = 'plugin-cache-local-v1';

  cache.getPortalByGuid = function (guid) {
    var portal_cache = cache.cache[guid];
    if (!portal_cache) return;

    var ent = portal_cache.ent;
    // what is this?
    if (Array.isArray(ent) && (ent.length === 3)) {
      ent = ent[2];
    }

    if (ent) {
      // console.log('==KeysList gpbg ' + Object.keys(ent).join(' '));
      return window.decodeArray.portalSummary(ent);
    }
  };

  cache.storeToLocal = function () {
    var lc = cache.cache;
    if (Object.keys(lc).length) {
      $.each(lc, function(guid, data) {
        // if (data.ent) console.log(data.ent);
        var d = {};
        // I dont know what I do...
        if (data.ent && Array.isArray(data.ent) && (data.ent.length === 3)) {
          d.loadtime = data.ent[1];
          d.ent = data.ent[2];
        } else {
          d.loadtime = data.loadtime;
          d.ent = data.ent;
        }
        lc[guid] = d;
      });
      localStorage.setItem(cache.KEY_LOCALSTRAGE, JSON.stringify(lc));
    }

    console.log('plugin-cache-local: storeToLocal ' + Object.keys(lc).length);
  };

  cache.loadFromLocal = function () {
    // if an existing portal cache, load it
    var raw = window.localStorage[cache.KEY_LOCALSTRAGE];
    if (raw) {
      cache.merge(JSON.parse(raw));
      console.log('plugin-cache-local: loadFromLocal ' + Object.keys(cache.cache).length);
    } else {
      // make a new cache
      window.localStorage[cache.KEY_LOCALSTRAGE] = "{}";
      console.log('plugin-cache-local: init');
    }
  };

  cache.merge = function (inbound) {
    $.each(inbound, function (guid, data) {
      console.log('plugin-cache-loacl: merge ' + data);
      if (data[ent] && !cache.cache[guid]) {
        cache.cache[guid] = data;
        // console.log(data);
      }
    });
    return Object.keys(cache.cache).length;
  };

  // Expand Cache END //////////////////////////////////////////////////////////

  // use own namespace for plugin
  window.plugin.keysList = function() {};
  var self = window.plugin.keysList;
  self.INTEL_URL = 'https://www.ingress.com/intel';
  self.DEFAULT_ZOOM_LEVEL = '17';
  self.listAll = [];

  // fetch a portal info from a cached list if available
  self.getPortalDetails = function getPortalDetails(key) {
    var title = "(not detected)";
    var latLng = '0,0';
    var imageUrl = '';

    // try plugin cache
    var portal_cache = cache.getPortalByGuid(key.guid);
    if (portal_cache) {
      title = portal_cache.title;
      imageUrl = window.fixPortalImageUrl(portal_cache.image);
      console.log('==KsysList from cache ' + portal_cache.title);
    }

    var data = (window.portals[key.guid] && window.portals[key.guid].options.data) || window.portalDetail.get(key.guid) || null;
    if (data) {
      console.log('==KsysList from view ' + data.title);
      if (data.title) title = data.title;
      imageUrl = window.fixPortalImageUrl(data.image);
    }

    if (imageUrl.indexOf('//') === 0) {
      imageUrl = 'http:' + imageUrl;
    }
    if (imageUrl.indexOf(DEFAULT_PORTAL_IMG) !== -1) {
      imageUrl = '';
    }

    var hLatLng = window.findPortalLatLng(key.guid);
    if (hLatLng) {
      latLng = hLatLng.lat + ',' + hLatLng.lng;
    }

    key.title = title;
    key.latLng = latLng;
    key.imageUrl = imageUrl;
    if (latLng === '0,0') {
      key.intelMapUrl = '';
    } else {
      key.intelMapUrl = self.INTEL_URL + '?ll=' + latLng + '&z=' + self.DEFAULT_ZOOM_LEVEL + '&pll=' + latLng;
    }

    return key;
  };

  self.csvValue = function(str) {
    if (str) {
      return '"' + str.replace("/\"/g", '""') + '"';
    } else {
      return '';
    }
  };

  self.eachKey = function(key) {
    if (key.count > 0) {
      key = self.getPortalDetails(key);
      var csvline = [
        self.csvValue(key.title),
        parseInt(key.count, 10),
        self.csvValue(key.latLng),
        self.csvValue(key.intelMapUrl),
        self.csvValue(key.imageUrl),
        key.guid
      ];
      self.listAll.push(csvline.join(","));
    }
  };

  self.renderList = function() {
    self.listAll = [];

    $.each(plugin.keys.keys, function(key, count) {
      self.eachKey({"guid": key, "count": count});
    });

    var html = '
KeysList for ' + window.PLAYER.nickname + ' ' + self.listAll.length + 'portals of keys. ' + new Date().toISOString() +
        '

name,count,latlng,intelmap,image,guid' + "\n" + self.listAll.join("\n") + '
';
    dialog({
      title: 'KeysList',
      html: html,
      width: 600,
      position: {my: 'right center', at: 'center-60 center', of: window, collision: 'fit'}
    });
    // console.log("==KeysList " + window.PLAYER.nickname + " " + self.listAll.length + " " + new Date().toISOString());
    // cache.storeToLocal();// for debug
  };

  self.setupCSS = function() {
    $("


<commit_before>'use strict';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    config = require('./config.json'),
    fs = require('fs'),
    runSequence = require('run-sequence');

// gulp.task('get', function() {
//     fs.readdir('./build', function(err, files) {
//         files.filter(function(file) { return file.substr(-5) === '.html'; })
//              .forEach(function(file) { console.log(file) });
//     });
// });

// gulp --type prod

var watch = false;
var copytext = config.copyright;

var onError = function(err) {
    $.util.beep();
    console.log(err);
};

var getStamp = function() {
    var myDate = new Date();

    var myYear = myDate.getFullYear().toString();
    var myMonth = ('0' + (myDate.getMonth() + 1)).slice(-2);
    var myDay = ('0' + myDate.getDate()).slice(-2);
    var mySeconds = myDate.getSeconds().toString();

    var myFullDate = myYear + myMonth + myDay + mySeconds;

    return myFullDate;
};

var patterns = [{
    pattern: /\.css/g,
    replacement: '\.css?' + getStamp()
}, {
    pattern: /\.js/g,
    replacement: '\.js?' + getStamp()
}, {
    pattern: /\.jpg/g,
    replacement: '\.jpg?' + getStamp()
}, {
    pattern: /\.ico/g,
    replacement: '\.ico?' + getStamp()
}, {
    pattern: /\.svg/g,
    replacement: '\.svg?' + getStamp()
}, {
    pattern: /\.png/g,
    replacement: '\.png?' + getStamp()
}, ];

gulp.task('browser-sync', function() {
    browserSync.init(null, {
        server: {
            baseDir: './build'
        }
    });
});

gulp.task('proxy', function() {
    gulp.src('/')
        .pipe($.run('./srvdir ' + config.glob.proxy + ':./build'));
});

gulp.task('clean-url', function(){
  gulp.src('build/**/*.html')
    .pipe($.replace(/\.html/g, ''))
    .pipe(gulp.dest('build'));
});

gulp.task('chmod', function() {
    return gulp.src('build/**/*')
        .pipe($.chmod(644))
        .pipe(gulp.dest('build'));
});

gulp.task('sitemap', function() {
    gulp.src('build/**/*.html', {
            read: false
        })
        .pipe($.sitemap({
            siteUrl: config.glob.site
        }))
        .pipe(gulp.dest('build/'));
});

gulp.task('clean', function() {
    return gulp.src(['./build/', '.sass-cache/', './.tmp', './jade/_includes/_html/'], {
            read: false
        })
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.rimraf());
});

gulp.task('files', function() {
    return gulp.src(['./files/**/*', './files/**/.*', '!./files/**/.DS_Store'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe(gulp.dest('build'))
        .pipe($.if(watch, reload({
            stream: true
        })));
});

gulp.task('jade-pre', function() {
    var filterUsemin = $.filter('**/*.+(js|css)');
    return gulp.src(['jade/_includes/_*.jade'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.jade({
            pretty: true,
        }))
        .pipe($.usemin({
            assetsDir: './',
            html: [$.if($.util.env.type === 'prod', $.htmlmin({
                collapseWhitespace: true,
                keepClosingSlash: true
            }))],
            css: [
                //($.if(env === 'production', $.uncss(config.uncss))),
                $.autoprefixer(config.autoprefixer),
                $.if($.util.env.type === 'prod', $.csso(), $.cssshrink())
            ],
            js: [
                $.if($.util.env.type === 'prod', $.uglify()),
                $.header(copytext)
            ]
        }))
        .pipe(filterUsemin)
        .pipe(gulp.dest('build'))
        .pipe(filterUsemin.restore())
        .pipe($.filter('**/*.+(html)'))
        .pipe(gulp.dest('jade/_includes/_html'));
});
gulp.task('jade-post', function() {
    return gulp.src(['jade/**/*.jade', '!jade/**/_*'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.jade({
            pretty: true,
            basedir: './jade'
        }))
        .pipe($.usemin({
            assetsDir: './',
            html: [$.if($.util.env.type === 'prod', $.htmlmin({
                collapseWhitespace: true,
                keepClosingSlash: true
            }))],
            css: [
                // ($.if(env === 'production', $.uncss(config.uncss))),
                $.autoprefixer(config.autoprefixer),
                $.if($.util.env.type === 'prod', $.csso(), $.cssshrink())
            ],
            js: [
                $.if($.util.env.type === 'prod', $.uglify()),
                $.header(copytext)
            ]
        }))
        .pipe(gulp.dest('build'))
        .pipe($.if(watch, reload({
            stream: true
        })));
});

gulp.task('sass', function() {
    return gulp.src('scss/**/*.scss')
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.rubySass({
            loadPath: 'bower_components/foundation/scss',
            style: 'compact',
            compass: true
        }))
        .pipe(gulp.dest('.tmp/css'));
});

gulp.task('images', function() {
    return gulp.src(['images/**/*', '!images/base64/**/*', '!images/base64'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe(gulp.dest('build/images'))
        .pipe($.filter('**/*.+(jpg|jpeg|png)'))
        .pipe($.webp())
        .pipe(gulp.dest('build/images'))
        .pipe($.if(watch, reload({
            stream: true
        })));
});
gulp.task('images-gen', function() {
    return gulp.src(['images/**/*'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.imagemin({
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest('images'));
});

gulp.task('cachebust', function() {
    return gulp.src('./build/**/*.+(html|css)')
        .pipe($.frep(patterns))
        .pipe(gulp.dest('build'))
});

gulp.task('jade', function(callback) {
    runSequence('jade-pre',
        'jade-post', ['sitemap', 'cachebust'],
        callback);
});

gulp.task('css', function(callback) {
    runSequence('sass',
        'jade',
        callback);
});

gulp.task('default', function(callback) {
    runSequence('clean', ['sass', 'images', 'files'],
        'jade',
        callback);
});

gulp.task('watch', ['default', 'browser-sync'], function() {
    gulp.watch(['scss/**/*.scss'], ['css']);
    gulp.watch(['jade/**/*.jade'], ['jade']);
    gulp.watch(['js/**/*.js'], ['jade']);
    gulp.watch(['images/**/*'], ['images']);
    watch = true;
});
<commit_msg>Remove unused module and code<commit_after>'use strict';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    config = require('./config.json'),
    runSequence = require('run-sequence');

// gulp --type prod

var watch = false;
var copytext = config.copyright;

var onError = function(err) {
    $.util.beep();
    console.log(err);
};

var getStamp = function() {
    var myDate = new Date();

    var myYear = myDate.getFullYear().toString();
    var myMonth = ('0' + (myDate.getMonth() + 1)).slice(-2);
    var myDay = ('0' + myDate.getDate()).slice(-2);
    var mySeconds = myDate.getSeconds().toString();

    var myFullDate = myYear + myMonth + myDay + mySeconds;

    return myFullDate;
};

var patterns = [{
    pattern: /\.css/g,
    replacement: '\.css?' + getStamp()
}, {
    pattern: /\.js/g,
    replacement: '\.js?' + getStamp()
}, {
    pattern: /\.jpg/g,
    replacement: '\.jpg?' + getStamp()
}, {
    pattern: /\.ico/g,
    replacement: '\.ico?' + getStamp()
}, {
    pattern: /\.svg/g,
    replacement: '\.svg?' + getStamp()
}, {
    pattern: /\.png/g,
    replacement: '\.png?' + getStamp()
}, ];

gulp.task('browser-sync', function() {
    browserSync.init(null, {
        server: {
            baseDir: './build'
        }
    });
});

gulp.task('proxy', function() {
    gulp.src('/')
        .pipe($.run('./srvdir ' + config.glob.proxy + ':./build'));
});

gulp.task('clean-url', function(){
  gulp.src('build/**/*.html')
    .pipe($.replace(/\.html/g, ''))
    .pipe(gulp.dest('build'));
});

gulp.task('chmod', function() {
    return gulp.src('build/**/*')
        .pipe($.chmod(644))
        .pipe(gulp.dest('build'));
});

gulp.task('sitemap', function() {
    gulp.src('build/**/*.html', {
            read: false
        })
        .pipe($.sitemap({
            siteUrl: config.glob.site
        }))
        .pipe(gulp.dest('build/'));
});

gulp.task('clean', function() {
    return gulp.src(['./build/', '.sass-cache/', './.tmp', './jade/_includes/_html/'], {
            read: false
        })
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.rimraf());
});

gulp.task('files', function() {
    return gulp.src(['./files/**/*', './files/**/.*', '!./files/**/.DS_Store'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe(gulp.dest('build'))
        .pipe($.if(watch, reload({
            stream: true
        })));
});

gulp.task('jade-pre', function() {
    var filterUsemin = $.filter('**/*.+(js|css)');
    return gulp.src(['jade/_includes/_*.jade'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.jade({
            pretty: true,
        }))
        .pipe($.usemin({
            assetsDir: './',
            html: [$.if($.util.env.type === 'prod', $.htmlmin({
                collapseWhitespace: true,
                keepClosingSlash: true
            }))],
            css: [
                //($.if(env === 'production', $.uncss(config.uncss))),
                $.autoprefixer(config.autoprefixer),
                $.if($.util.env.type === 'prod', $.csso(), $.cssshrink())
            ],
            js: [
                $.if($.util.env.type === 'prod', $.uglify()),
                $.header(copytext)
            ]
        }))
        .pipe(filterUsemin)
        .pipe(gulp.dest('build'))
        .pipe(filterUsemin.restore())
        .pipe($.filter('**/*.+(html)'))
        .pipe(gulp.dest('jade/_includes/_html'));
});
gulp.task('jade-post', function() {
    return gulp.src(['jade/**/*.jade', '!jade/**/_*'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.jade({
            pretty: true,
            basedir: './jade'
        }))
        .pipe($.usemin({
            assetsDir: './',
            html: [$.if($.util.env.type === 'prod', $.htmlmin({
                collapseWhitespace: true,
                keepClosingSlash: true
            }))],
            css: [
                // ($.if(env === 'production', $.uncss(config.uncss))),
                $.autoprefixer(config.autoprefixer),
                $.if($.util.env.type === 'prod', $.csso(), $.cssshrink())
            ],
            js: [
                $.if($.util.env.type === 'prod', $.uglify()),
                $.header(copytext)
            ]
        }))
        .pipe(gulp.dest('build'))
        .pipe($.if(watch, reload({
            stream: true
        })));
});

gulp.task('sass', function() {
    return gulp.src('scss/**/*.scss')
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.rubySass({
            loadPath: 'bower_components/foundation/scss',
            style: 'compact',
            compass: true
        }))
        .pipe(gulp.dest('.tmp/css'));
});

gulp.task('images', function() {
    return gulp.src(['images/**/*', '!images/base64/**/*', '!images/base64'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe(gulp.dest('build/images'))
        .pipe($.filter('**/*.+(jpg|jpeg|png)'))
        .pipe($.webp())
        .pipe(gulp.dest('build/images'))
        .pipe($.if(watch, reload({
            stream: true
        })));
});
gulp.task('images-gen', function() {
    return gulp.src(['images/**/*'])
        .pipe($.plumber({
            errorHandler: onError
        }))
        .pipe($.imagemin({
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest('images'));
});

gulp.task('cachebust', function() {
    return gulp.src('./build/**/*.+(html|css)')
        .pipe($.frep(patterns))
        .pipe(gulp.dest('build'))
});

gulp.task('jade', function(callback) {
    runSequence('jade-pre',
        'jade-post', ['sitemap', 'cachebust'],
        callback);
});

gulp.task('css', function(callback) {
    runSequence('sass',
        'jade',
        callback);
});

gulp.task('default', function(callback) {
    runSequence('clean', ['sass', 'images', 'files'],
        'jade',
        callback);
});

gulp.task('watch', ['default', 'browser-sync'], function() {
    gulp.watch(['scss/**/*.scss'], ['css']);
    gulp.watch(['jade/**/*.jade'], ['jade']);
    gulp.watch(['js/**/*.js'], ['jade']);
    gulp.watch(['images/**/*'], ['images']);
    watch = true;
});
<|endoftext|>


<commit_before>/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import setupGetInstanceId from '../../tools/setupGetInstanceId';

const { prefix } = settings;

const getInstanceId = setupGetInstanceId();

export default class Loading extends React.Component {
  constructor(props) {
    super(props);
    this.instanceId = getInstanceId();
  }

  static propTypes = {
    /**
     * Specify whether you want the loading indicator to be spinning or not
     */
    active: PropTypes.bool,

    /**
     * Provide an optional className to be applied to the containing node
     */
    className: PropTypes.string,

    /**
     * Specify whether you want the loader to be applied with an overlay
     */
    withOverlay: PropTypes.bool,

    /**
     * Specify whether you would like the small variant of <Loading>
     */
    small: PropTypes.bool,

    /**
     * Specify an description that would be used to best describe the loading state
     */
    description: PropTypes.string,
  };

  static defaultProps = {
    active: true,
    withOverlay: true,
    small: false,
    description: 'Active loading indicator',
  };

  render() {
    const {
      active,
      className,
      withOverlay,
      small,
      description,
      ...other
    } = this.props;

    const loadingClasses = classNames(`${prefix}--loading`, className, {
      [`${prefix}--loading--small`]: small,
      [`${prefix}--loading--stop`]: !active,
    });

    const overlayClasses = classNames(`${prefix}--loading-overlay`, {
      [`${prefix}--loading-overlay--stop`]: !active,
    });

    const loadingId = `loading-id-${this.instanceId}`;
    const spinnerRadius = small ? '26.8125' : '37.5';

    /**
     * Various screenreaders (JAWS, VoiceOver, NVDA...) interpret live regions differently
     * and change their interpretations over time. The aria on the div and the label
     * associated with the div are currently necessary for the loading state to be properly
     * read by all screenreaders. [0]
     *
     * JAWS does not read the loading state unless aria-atomic is set to true and the visually
     * hidden label is required for the loading state to be read in VoiceOver on iOS. Please
     * do not remove without testing on these platforms.
     *
     * [0] https://developer.paciellogroup.com/blog/2014/03/screen-reader-support-aria-live-regions/
     * */
    const loading = (

        <label id={loadingId} className={`${prefix}--visually-hidden`}>
          {description}

        <svg className={`${prefix}--loading__svg`} viewBox="-75 -75 150 150">
          <title>{description}</title>
          {small ? (
            <circle
              className={`${prefix}--loading__background`}
              cx="0"
              cy="0"
              r={spinnerRadius}
            />
          ) : null}
          <circle
            className={`${prefix}--loading__stroke`}
            cx="0"
            cy="0"
            r={spinnerRadius}
          />
        </svg>

    );

    return withOverlay ? (

{loading}

    ) : (
      loading
    );
  }
}
<commit_msg>refactor(loading): update from class to function (#5054)<commit_after>/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { settings } from 'carbon-components';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { useRef } from 'react';
import setupGetInstanceId from '../../tools/setupGetInstanceId';

const { prefix } = settings;
const getInstanceId = setupGetInstanceId();

function Loading({
  active,
  className: customClassName,
  withOverlay,
  small,
  description,
  ...rest
}) {
  const { current: instanceId } = useRef(getInstanceId());
  const loadingClassName = cx(customClassName, {
    [`${prefix}--loading`]: true,
    [`${prefix}--loading--small`]: small,
    [`${prefix}--loading--stop`]: !active,
  });
  const overlayClassName = cx({
    [`${prefix}--loading-overlay`]: true,
    [`${prefix}--loading-overlay--stop`]: !active,
  });
  const loadingId = `loading-id-${instanceId}`;
  const spinnerRadius = small ? '26.8125' : '37.5';

  const loading = (

      <label id={loadingId} className={`${prefix}--visually-hidden`}>
        {description}

      <svg className={`${prefix}--loading__svg`} viewBox="-75 -75 150 150">
        <title>{description}</title>
        {small ? (
          <circle
            className={`${prefix}--loading__background`}
            cx="0"
            cy="0"
            r={spinnerRadius}
          />
        ) : null}
        <circle
          className={`${prefix}--loading__stroke`}
          cx="0"
          cy="0"
          r={spinnerRadius}
        />
      </svg>

  );

  return withOverlay ? (

{loading}

  ) : (
    loading
  );
}

Loading.propTypes = {
  /**
   * Specify whether you want the loading indicator to be spinning or not
   */
  active: PropTypes.bool,

  /**
   * Provide an optional className to be applied to the containing node
   */
  className: PropTypes.string,

  /**
   * Specify whether you want the loader to be applied with an overlay
   */
  withOverlay: PropTypes.bool,

  /**
   * Specify whether you would like the small variant of <Loading>
   */
  small: PropTypes.bool,

  /**
   * Specify an description that would be used to best describe the loading state
   */
  description: PropTypes.string,
};

Loading.defaultProps = {
  active: true,
  withOverlay: true,
  small: false,
  description: 'Active loading indicator',
};

export default Loading;
<|endoftext|>


<commit_before>/* global ROC_PATH */

import { createMemoryHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';

export default function setupForRender(createStore, url) {
    const basename = ROC_PATH === '/' ? null : ROC_PATH;

    const completeUrl = basename ? basename + url : url;
    const memoryHistory = createMemoryHistory({
        entries: [completeUrl],
        basename
    });

    const store = createStore ? createStore(memoryHistory) : null;
    const history = syncHistoryWithStore(memoryHistory, store);

    return {
        store,
        history,
        url
    };
}
<commit_msg>Only sync with store when one exists.<commit_after>/* global ROC_PATH */

import { createMemoryHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';

export default function setupForRender(createStore, url) {
    const basename = ROC_PATH === '/' ? null : ROC_PATH;

    const completeUrl = basename ? basename + url : url;
    const memoryHistory = createMemoryHistory({
        entries: [completeUrl],
        basename
    });

    const store = createStore ? createStore(memoryHistory) : null;
    const history = store ? syncHistoryWithStore(memoryHistory, store) : memoryHistory;

    return {
        store,
        history,
        url
    };
}
<|endoftext|>