<commit_before>var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var SaveAssetsJson = require('assets-webpack-plugin');

var addons = require('./addons.json');
var root = path.join(__dirname, 'website', 'static');
/** Return the absolute path given a path relative to ./website/static */
var staticPath = function(dir) {
    return path.join(root, dir);
};
var nodePath = function(dir) {
    return path.join(__dirname, 'node_modules', dir);
};
var addonsPath = function(dir) {
    return path.join(__dirname, 'website', 'addons', dir);
};

/**
 * Each JS module for a page on the OSF is webpack entry point. These are built
 * to website/static/public/
 */
var entry = {
    // JS
    'base-page': staticPath('js/pages/base-page.js'),
    'home-page': staticPath('js/pages/home-page.js'),
    'landing-page': staticPath('js/pages/landing-page.js'),
    'dashboard-page': staticPath('js/pages/dashboard-page.js'),
    'profile-page': staticPath('js/pages/profile-page.js'),
    'project-dashboard': staticPath('js/pages/project-dashboard-page.js'),
    'project-base-page': staticPath('js/pages/project-base-page.js'),
    'project-settings-page': staticPath('js/pages/project-settings-page.js'),
    'project-registrations-page': staticPath('js/pages/project-registrations-page.js'),
    'registration-retraction-page': staticPath('js/pages/registration-retraction-page.js'),
    'registration-edit-page': staticPath('js/pages/registration-edit-page.js'),
    'register-page': staticPath('js/pages/register-page.js'),
    'wiki-edit-page': staticPath('js/pages/wiki-edit-page.js'),
    'file-page': staticPath('js/pages/file-page.js'),
    'files-page': staticPath('js/pages/files-page.js'),
    'prereg-landing-page': staticPath('js/pages/prereg-landing-page.js'),
    'profile-settings-page': staticPath('js/pages/profile-settings-page.js'),
    'profile-account-settings-page': staticPath('js/pages/profile-account-settings-page.js'),
    'profile-settings-applications-list-page': staticPath('js/pages/profile-settings-applications-list-page.js'),
    'profile-settings-applications-detail-page': staticPath('js/pages/profile-settings-applications-detail-page.js'),
    'profile-settings-personal-tokens-list-page': staticPath('js/pages/profile-settings-personal-tokens-list-page.js'),
    'profile-settings-personal-tokens-detail-page': staticPath('js/pages/profile-settings-personal-tokens-detail-page.js'),
    'sharing-page': staticPath('js/pages/sharing-page.js'),
    'conference-page': staticPath('js/pages/conference-page.js'),
    'meetings-page': staticPath('js/pages/meetings-page.js'),
    'view-file-tree-page': staticPath('js/pages/view-file-tree-page.js'),
    'search-page': staticPath('js/pages/search-page.js'),
    'share-search-page': staticPath('js/pages/share-search-page.js'),
    'profile-settings-addons-page': staticPath('js/pages/profile-settings-addons-page.js'),
    'twofactor-page': staticPath('js/pages/twofactor-page.js'),
    'forgotpassword-page': staticPath('js/pages/forgotpassword-page.js'),
    'login-page': staticPath('js/pages/login-page.js'),
    'notifications-config-page': staticPath('js/pages/notifications-config-page.js'),
    'share-embed-page': staticPath('js/pages/share-embed-page.js'),
    'render-nodes': staticPath('js/pages/render-nodes.js'),
    'support-page': staticPath('js/pages/support-page.js'),
    // Commons chunk
    'vendor': [
        // Vendor libraries
        'knockout',
        'knockout.validation',
        'knockout.punches',
        'moment',
        'bootstrap',
        'bootbox',
        'bootstrap-editable',
        'select2',
        'dropzone',
        'knockout-sortable',
        'treebeard',
        'jquery.cookie',
        'URIjs',
        // Common internal modules
        'js/fangorn',
        'js/citations',
        'js/osfHelpers',
        'js/osfToggleHeight',
        'mithril',
        'js/qToggle',
        'js/components/autocomplete',
    ]
};

// Collect log text from addons
var mainLogs = require(staticPath('js/logActionsList.json'));
var addonLog;

// Collect adddons endpoints. If an addon's static folder has
// any of the following files, it will be added as an entry point
// and output to website/static/public/js/<addon-name>/files.js
var addonModules = ['files.js', 'node-cfg.js', 'user-cfg.js', 'file-detail.js', 'widget-cfg.js'];
addons.addons.forEach(function(addonName) {
    var baseDir = addonName + '/';
    addonModules.forEach(function(module) {
        var modulePath = path.join(__dirname, 'website', 'addons',
                                  addonName, 'static', module);
        if (fs.existsSync(modulePath)) {
            var entryPoint = baseDir + module.split('.')[0];
            entry[entryPoint] =  modulePath;
        }
    });
    var logTextPath = path.join(__dirname, 'website', 'addons',
        addonName, 'static', addonName + 'LogActionList.json');
    if(fs.existsSync(logTextPath)){
        addonLog = require(logTextPath);
        for (var attrname in addonLog) { mainLogs[attrname] = addonLog[attrname]; }
    }
});

fs.writeFileSync(staticPath('js/_allLogTexts.json'), JSON.stringify(mainLogs));

var resolve = {
    extensions: ['', '.es6.js', '.js', '.min.js'],
    root: root,
    // Look for required files in bower and npm directories
    modulesDirectories: ['./website/static/vendor/bower_components', 'node_modules'],
    // Need to alias libraries that aren't managed by bower or npm
    alias: {
        'knockout-sortable': staticPath('vendor/knockout-sortable/knockout-sortable.js'),
        'bootstrap-editable': staticPath('vendor/bootstrap-editable-custom/js/bootstrap-editable.js'),
        'jquery-blockui': staticPath('vendor/jquery-blockui/jquery.blockui.js'),
        'bootstrap': staticPath('vendor/bower_components/bootstrap/dist/js/bootstrap.min.js'),
        'jquery-tagsinput': staticPath('vendor/bower_components/jquery.tagsinput/jquery.tagsinput.js'),
        'zeroclipboard': staticPath('vendor/bower_components/zeroclipboard/dist/ZeroClipboard.js'),
        'history': nodePath('historyjs/scripts/bundled/html4+html5/jquery.history.js'),
        // Needed for knockout-sortable
        'jquery.ui.sortable': staticPath('vendor/bower_components/jquery-ui/ui/jquery.ui.sortable.js'),
        'truncate': staticPath('vendor/bower_components/truncate/jquery.truncate.js'),
        // Needed for ace code editor in wiki
        'ace-noconflict': staticPath('vendor/bower_components/ace-builds/src-noconflict/ace.js'),
        'ace-ext-language_tools': staticPath('vendor/bower_components/ace-builds/src-noconflict/ext-language_tools.js'),
        'ace-mode-markdown': staticPath('vendor/bower_components/ace-builds/src-noconflict/mode-markdown.js'),
        'pagedown-ace-converter': addonsPath('wiki/static/pagedown-ace/Markdown.Converter.js'),
        'pagedown-ace-sanitizer': addonsPath('wiki/static/pagedown-ace/Markdown.Sanitizer.js'),
        'pagedown-ace-editor': addonsPath('wiki/static/pagedown-ace/Markdown.Editor.js'),
        'wikiPage': addonsPath('wiki/static/wikiPage.js'),
        'highlight-css': nodePath('highlight.js/styles/default.css'),
        'pikaday-css': nodePath('pikaday/css/pikaday.css'),
        // Also alias some internal libraries for easy access
        'addons': path.join(__dirname, 'website', 'addons'),
        'tests': staticPath('js/tests'),
        // GASP Items not defined as main in its package.json
        'TweenLite' : nodePath('gsap/src/minified/TweenLite.min.js'),
        'EasePack' : nodePath('gsap/src/minified/easing/EasePack.min.js'),
        'sliderPips': staticPath('vendor/bower_components/jQuery-ui-Slider-Pips/dist/jquery-ui-slider-pips.min.js')
    }
};

var externals = {
    // require("jquery") is external and available
    //  on the global var jQuery, which is loaded with CDN
    'jquery': 'jQuery',
    'jquery-ui': 'jQuery.ui',
    'raven-js': 'Raven',
    'MathJax': 'MathJax'
};

var plugins = [
    // Bundle common code between modules
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
    // Bower support
    new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
    ),
    // Make jQuery available in all modules without having to do require('jquery')
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    // Slight hack to make sure that CommonJS is always used
    new webpack.DefinePlugin({
        'define.amd': false
    }),
];

var output = {
    path: './website/static/public/js/',
    // publicPath: '/static/', // used to generate urls to e.g. images
    filename: '[name].js',
    sourcePrefix: ''
};

module.exports = {
    entry: entry,
    resolve: resolve,
    externals: externals,
    plugins: plugins,
    output: output,
    module: {
        loaders: [
            {test: /\.es6\.js$/, exclude: [/node_modules/, /bower_components/, /vendor/], loader: 'babel-loader'},
            {test: /\.css$/, loaders: ['style', 'css']},
            // url-loader uses DataUrls; files-loader emits files
            {test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/ng'},
            {test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif'},
            {test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg'},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?mimetype=application/font-woff'},
            {test: /\.svg/, loader: 'file-loader'},
            {test: /\.eot/, loader: 'file-loader'},
            {test: /\.ttf/, loader: 'file-loader'},
            //Dirty hack because mime-type's json file is "special"
            {test: /db.json/, loader: 'json-loader'}
        ]
    }
};
<commit_msg>Remove support page from webpack<commit_after>var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var SaveAssetsJson = require('assets-webpack-plugin');

var addons = require('./addons.json');
var root = path.join(__dirname, 'website', 'static');
/** Return the absolute path given a path relative to ./website/static */
var staticPath = function(dir) {
    return path.join(root, dir);
};
var nodePath = function(dir) {
    return path.join(__dirname, 'node_modules', dir);
};
var addonsPath = function(dir) {
    return path.join(__dirname, 'website', 'addons', dir);
};

/**
 * Each JS module for a page on the OSF is webpack entry point. These are built
 * to website/static/public/
 */
var entry = {
    // JS
    'base-page': staticPath('js/pages/base-page.js'),
    'home-page': staticPath('js/pages/home-page.js'),
    'landing-page': staticPath('js/pages/landing-page.js'),
    'dashboard-page': staticPath('js/pages/dashboard-page.js'),
    'profile-page': staticPath('js/pages/profile-page.js'),
    'project-dashboard': staticPath('js/pages/project-dashboard-page.js'),
    'project-base-page': staticPath('js/pages/project-base-page.js'),
    'project-settings-page': staticPath('js/pages/project-settings-page.js'),
    'project-registrations-page': staticPath('js/pages/project-registrations-page.js'),
    'registration-retraction-page': staticPath('js/pages/registration-retraction-page.js'),
    'registration-edit-page': staticPath('js/pages/registration-edit-page.js'),
    'register-page': staticPath('js/pages/register-page.js'),
    'wiki-edit-page': staticPath('js/pages/wiki-edit-page.js'),
    'file-page': staticPath('js/pages/file-page.js'),
    'files-page': staticPath('js/pages/files-page.js'),
    'prereg-landing-page': staticPath('js/pages/prereg-landing-page.js'),
    'profile-settings-page': staticPath('js/pages/profile-settings-page.js'),
    'profile-account-settings-page': staticPath('js/pages/profile-account-settings-page.js'),
    'profile-settings-applications-list-page': staticPath('js/pages/profile-settings-applications-list-page.js'),
    'profile-settings-applications-detail-page': staticPath('js/pages/profile-settings-applications-detail-page.js'),
    'profile-settings-personal-tokens-list-page': staticPath('js/pages/profile-settings-personal-tokens-list-page.js'),
    'profile-settings-personal-tokens-detail-page': staticPath('js/pages/profile-settings-personal-tokens-detail-page.js'),
    'sharing-page': staticPath('js/pages/sharing-page.js'),
    'conference-page': staticPath('js/pages/conference-page.js'),
    'meetings-page': staticPath('js/pages/meetings-page.js'),
    'view-file-tree-page': staticPath('js/pages/view-file-tree-page.js'),
    'search-page': staticPath('js/pages/search-page.js'),
    'share-search-page': staticPath('js/pages/share-search-page.js'),
    'profile-settings-addons-page': staticPath('js/pages/profile-settings-addons-page.js'),
    'twofactor-page': staticPath('js/pages/twofactor-page.js'),
    'forgotpassword-page': staticPath('js/pages/forgotpassword-page.js'),
    'login-page': staticPath('js/pages/login-page.js'),
    'notifications-config-page': staticPath('js/pages/notifications-config-page.js'),
    'share-embed-page': staticPath('js/pages/share-embed-page.js'),
    'render-nodes': staticPath('js/pages/render-nodes.js'),
    // Commons chunk
    'vendor': [
        // Vendor libraries
        'knockout',
        'knockout.validation',
        'knockout.punches',
        'moment',
        'bootstrap',
        'bootbox',
        'bootstrap-editable',
        'select2',
        'dropzone',
        'knockout-sortable',
        'treebeard',
        'jquery.cookie',
        'URIjs',
        // Common internal modules
        'js/fangorn',
        'js/citations',
        'js/osfHelpers',
        'js/osfToggleHeight',
        'mithril',
        'js/qToggle',
        'js/components/autocomplete',
    ]
};

// Collect log text from addons
var mainLogs = require(staticPath('js/logActionsList.json'));
var addonLog;

// Collect adddons endpoints. If an addon's static folder has
// any of the following files, it will be added as an entry point
// and output to website/static/public/js/<addon-name>/files.js
var addonModules = ['files.js', 'node-cfg.js', 'user-cfg.js', 'file-detail.js', 'widget-cfg.js'];
addons.addons.forEach(function(addonName) {
    var baseDir = addonName + '/';
    addonModules.forEach(function(module) {
        var modulePath = path.join(__dirname, 'website', 'addons',
                                  addonName, 'static', module);
        if (fs.existsSync(modulePath)) {
            var entryPoint = baseDir + module.split('.')[0];
            entry[entryPoint] =  modulePath;
        }
    });
    var logTextPath = path.join(__dirname, 'website', 'addons',
        addonName, 'static', addonName + 'LogActionList.json');
    if(fs.existsSync(logTextPath)){
        addonLog = require(logTextPath);
        for (var attrname in addonLog) { mainLogs[attrname] = addonLog[attrname]; }
    }
});

fs.writeFileSync(staticPath('js/_allLogTexts.json'), JSON.stringify(mainLogs));

var resolve = {
    extensions: ['', '.es6.js', '.js', '.min.js'],
    root: root,
    // Look for required files in bower and npm directories
    modulesDirectories: ['./website/static/vendor/bower_components', 'node_modules'],
    // Need to alias libraries that aren't managed by bower or npm
    alias: {
        'knockout-sortable': staticPath('vendor/knockout-sortable/knockout-sortable.js'),
        'bootstrap-editable': staticPath('vendor/bootstrap-editable-custom/js/bootstrap-editable.js'),
        'jquery-blockui': staticPath('vendor/jquery-blockui/jquery.blockui.js'),
        'bootstrap': staticPath('vendor/bower_components/bootstrap/dist/js/bootstrap.min.js'),
        'jquery-tagsinput': staticPath('vendor/bower_components/jquery.tagsinput/jquery.tagsinput.js'),
        'zeroclipboard': staticPath('vendor/bower_components/zeroclipboard/dist/ZeroClipboard.js'),
        'history': nodePath('historyjs/scripts/bundled/html4+html5/jquery.history.js'),
        // Needed for knockout-sortable
        'jquery.ui.sortable': staticPath('vendor/bower_components/jquery-ui/ui/jquery.ui.sortable.js'),
        'truncate': staticPath('vendor/bower_components/truncate/jquery.truncate.js'),
        // Needed for ace code editor in wiki
        'ace-noconflict': staticPath('vendor/bower_components/ace-builds/src-noconflict/ace.js'),
        'ace-ext-language_tools': staticPath('vendor/bower_components/ace-builds/src-noconflict/ext-language_tools.js'),
        'ace-mode-markdown': staticPath('vendor/bower_components/ace-builds/src-noconflict/mode-markdown.js'),
        'pagedown-ace-converter': addonsPath('wiki/static/pagedown-ace/Markdown.Converter.js'),
        'pagedown-ace-sanitizer': addonsPath('wiki/static/pagedown-ace/Markdown.Sanitizer.js'),
        'pagedown-ace-editor': addonsPath('wiki/static/pagedown-ace/Markdown.Editor.js'),
        'wikiPage': addonsPath('wiki/static/wikiPage.js'),
        'highlight-css': nodePath('highlight.js/styles/default.css'),
        'pikaday-css': nodePath('pikaday/css/pikaday.css'),
        // Also alias some internal libraries for easy access
        'addons': path.join(__dirname, 'website', 'addons'),
        'tests': staticPath('js/tests'),
        // GASP Items not defined as main in its package.json
        'TweenLite' : nodePath('gsap/src/minified/TweenLite.min.js'),
        'EasePack' : nodePath('gsap/src/minified/easing/EasePack.min.js'),
        'sliderPips': staticPath('vendor/bower_components/jQuery-ui-Slider-Pips/dist/jquery-ui-slider-pips.min.js')
    }
};

var externals = {
    // require("jquery") is external and available
    //  on the global var jQuery, which is loaded with CDN
    'jquery': 'jQuery',
    'jquery-ui': 'jQuery.ui',
    'raven-js': 'Raven',
    'MathJax': 'MathJax'
};

var plugins = [
    // Bundle common code between modules
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
    // Bower support
    new webpack.ResolverPlugin(
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
    ),
    // Make jQuery available in all modules without having to do require('jquery')
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
    }),
    // Slight hack to make sure that CommonJS is always used
    new webpack.DefinePlugin({
        'define.amd': false
    }),
];

var output = {
    path: './website/static/public/js/',
    // publicPath: '/static/', // used to generate urls to e.g. images
    filename: '[name].js',
    sourcePrefix: ''
};

module.exports = {
    entry: entry,
    resolve: resolve,
    externals: externals,
    plugins: plugins,
    output: output,
    module: {
        loaders: [
            {test: /\.es6\.js$/, exclude: [/node_modules/, /bower_components/, /vendor/], loader: 'babel-loader'},
            {test: /\.css$/, loaders: ['style', 'css']},
            // url-loader uses DataUrls; files-loader emits files
            {test: /\.png$/, loader: 'url-loader?limit=100000&mimetype=image/ng'},
            {test: /\.gif$/, loader: 'url-loader?limit=10000&mimetype=image/gif'},
            {test: /\.jpg$/, loader: 'url-loader?limit=10000&mimetype=image/jpg'},
            {test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?mimetype=application/font-woff'},
            {test: /\.svg/, loader: 'file-loader'},
            {test: /\.eot/, loader: 'file-loader'},
            {test: /\.ttf/, loader: 'file-loader'},
            //Dirty hack because mime-type's json file is "special"
            {test: /db.json/, loader: 'json-loader'}
        ]
    }
};
<|endoftext|>


<commit_before>/**
 * Compare le regex envoyé à la valeur de ID, et impacte le form-group et le tip en conséquence
 * @param {string} regex
 * @param {string} id
 */
function checkValues(regex, id){
    if (regex.test($("#input_"+id).val())) {
        $("#group_"+id).removeClass("has-error");
        $("#group_"+id).addClass("has-success");
        $("#fb_"+id).removeClass("glyphicon-remove");
        $("#fb_"+id).addClass("glyphicon-ok");
        $("#tip_"+id).addClass("hidden");
        $("#validate_vehicule").prop("disabled",false);
    } else {
        $("#group_"+id).removeClass("has-success");
        $("#group_"+id).addClass("has-error");
        $("#fb_"+id).removeClass("glyphicon-ok");
        $("#fb_"+id).addClass("glyphicon-remove");
        $("#tip_"+id).removeClass("hidden");
        $("#validate_vehicule").prop("disabled",true);
    }
}

$(document).ready(function() {
    /**
     * Valide la valeur du numéro de chassis
     * Structure : 12345-12345-12345-12345
     */
    $("#input_chassis").focusout(function(){
        checkValues(/^([0-9]{5}-){3}[0-9]{5}$/, "chassis");
    });

    /**
     * Valide la valeur du numéro de plaque
     * Structure : [1-]ABC-123 ou [1-]abc-123
     */
    $("#input_plaque").focusout(function(){
        checkValues(/^(1-)?[a-zA-Z]{3}-[0-9]{3}$/, "plaque");
    });

    /**
     * Valide la valeur de la marque
     * Structure : n'accepte que les alphanumériques et les espaces
     */
    $("#input_marque").focusout(function () {
        checkValues(/^[a-zA-z0-9 ]+$/, "marque");
    });

    /**
     * Valide la valeur du modèle
     * Structure : n'accepte que les alphanumériques et les espaces
     */
    $("#input_modele").focusout(function () {
        checkValues(/^[a-zA-z0-9 ]+$/, "modele");
    });

    /**
     * Revérifie les valeurs des champs au moment de la validation
     *      (Redondant, mais au cas où)
     */
    $("#validate_vehicule").click(function () {
        checkValues(/^([0-9]{5}-){3}[0-9]{5}$/, "chassis");
        checkValues(/^(1-)?[a-zA-Z]{3}-[0-9]{3}$/, "plaque");
        checkValues(/^[a-zA-z0-9 ]+$/, "marque");
        checkValues(/^[a-zA-z0-9 ]+$/, "modele");
    });
});
<commit_msg>correct regex<commit_after>/**
 * Compare le regex envoyé à la valeur de ID, et impacte le form-group et le tip en conséquence
 * @param {string} regex
 * @param {string} id
 */
function checkValues(regex, id){
    if (regex.test($("#input_"+id).val())) {
        $("#group_"+id).removeClass("has-error");
        $("#group_"+id).addClass("has-success");
        $("#fb_"+id).removeClass("glyphicon-remove");
        $("#fb_"+id).addClass("glyphicon-ok");
        $("#tip_"+id).addClass("hidden");
        $("#validate_vehicule").prop("disabled",false);
    } else {
        $("#group_"+id).removeClass("has-success");
        $("#group_"+id).addClass("has-error");
        $("#fb_"+id).removeClass("glyphicon-ok");
        $("#fb_"+id).addClass("glyphicon-remove");
        $("#tip_"+id).removeClass("hidden");
        $("#validate_vehicule").prop("disabled",true);
    }
}

$(document).ready(function() {
    /**
     * Valide la valeur du numéro de chassis
     * Structure : 12345-12345-12345-12345
     */
    $("#input_chassis").focusout(function(){
        checkValues(/^([0-9]{5}-){3}[0-9]{5}$/, "chassis");
    });

    /**
     * Valide la valeur du numéro de plaque
     * Structure : [1-]ABC-123 ou [1-]abc-123
     */
    $("#input_plaque").focusout(function(){
        checkValues(/^(1-)?[a-zA-Z]{3}-[0-9]{3}$/, "plaque");
    });

    /**
     * Valide la valeur de la marque
     * Structure : n'accepte que les alphanumériques et les espaces
     */
    $("#input_marque").focusout(function () {
        checkValues(/^[a-zA-Z0-9 ]+$/, "marque");
    });

    /**
     * Valide la valeur du modèle
     * Structure : n'accepte que les alphanumériques et les espaces
     */
    $("#input_modele").focusout(function () {
        checkValues(/^[a-zA-Z0-9 ]+$/, "modele");
    });

    /**
     * Revérifie les valeurs des champs au moment de la validation
     *      (Redondant, mais au cas où)
     */
    $("#validate_vehicule").click(function () {
        checkValues(/^([0-9]{5}-){3}[0-9]{5}$/, "chassis");
        checkValues(/^(1-)?[a-zA-Z]{3}-[0-9]{3}$/, "plaque");
        checkValues(/^[a-zA-Z0-9 ]+$/, "marque");
        checkValues(/^[a-zA-Z0-9 ]+$/, "modele");
    });
});
<|endoftext|>


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

    function SimpleTestController() {
        var vm = this;

        vm.isBlue = true;
    }

    angular.module('skytutorial', ['sky'])
        .component('bbSimple', {
            template: '
<ng-transclude></ng-transclude>
',
            controller: angular.noop,
            bindings: {
                bbSimpleIsBlue: '<?'
            },
            transclude: true
        })
        .controller('SimpleTestController', SimpleTestController);
}());<commit_msg>use correct ng-class<commit_after>(function () {
    'use strict';

    function SimpleTestController() {
        var vm = this;

        vm.isBlue = true;
    }

    angular.module('skytutorial', ['sky'])
        .component('bbSimple', {
            template: '
<ng-transclude></ng-transclude>
',
            controller: angular.noop,
            bindings: {
                bbSimpleIsBlue: '<?'
            },
            transclude: true
        })
        .controller('SimpleTestController', SimpleTestController);
}());<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import withAsyncFetch from '../../hocs/AsyncContainer';
import ActionMenu from '../../ActionMenu';
import { EditButton, ReadItNowButton, DownloadButton } from '../../IconButton';
import { fetchStory } from '../../../../actions/storyActions';
import DataCard from '../../DataCard';
import TagsAndTagSetsTable from '../TagsAndTagSetsTable';
import StoryEntitiesContainer from '../../story/StoryEntitiesContainer';
import StoryNytThemesContainer from '../../story/StoryNytThemesContainer';
import messages from '../../../../resources/messages';
import { urlToTools } from '../../../../lib/urlUtil';
import { TAG_SET_NYT_THEMES, TAG_SET_CLIFF_ORGS, TAG_SET_CLIFF_PEOPLE } from '../../../../lib/tagUtil';
import { trimToMaxLength } from '../../../../lib/stringUtil';
import { storyPubDateToTimestamp } from '../../../../lib/dateUtil';
import Permissioned from '../../Permissioned';
import { PERMISSION_ADMIN } from '../../../../lib/auth';
import StatBar from '../../statbar/StatBar';

const localMessages = {
  title: { id: 'admin.story.title', defaultMessage: 'Story Info: ' },
  close: { id: 'admin.story.inContext.close', defaultMessage: 'Close' },
  readThisStory: { id: 'admin.story.readThisStory', defaultMessage: 'Read This Story' },
  editThisStory: { id: 'admin.story.editThisStory', defaultMessage: 'Edit This Story' },
  fullDescription: { id: 'admin.story.fullDescription', defaultMessage: 'Published in {media} on {publishDate} in {language}' },
  published: { id: 'admin.story.published', defaultMessage: 'Published in {media}' },
  readCachedCopy: { id: 'admin.story.details.readCached', defaultMessage: 'Read Cached Text (admin only)' },
  viewCachedHtml: { id: 'admin.story.details.viewCachedHtml', defaultMessage: 'View Cached HTML (admin only)' },
  downloadAllTagsCsv: { id: 'admin.story.details.downloadTagsCsv', defaultMessage: 'Download all story tags' },
  storyOptions: { id: 'admin.story.details.storyOptions', defaultMessage: 'Story Options' },
  otherStoryTagTitle: { id: 'admin.story.details.otherTags', defaultMessage: 'Additional Tags ang Tag Sets' },
};

class SelectedStoryContainer extends React.Component {
  goToUpdateUrl = (storyId) => {
    window.location = `admin/story/${storyId}/update`;
  }

  goToCachedUrl = (storyId) => {
    window.location = `/admin/story/${storyId}/cached`;
  }

  downloadCsv = (storyId) => {
    window.location = `/api/admin/story/${storyId}/storytags.csv`;
  }

  render() {
    const { selectedStory, selectedStoryId, handleStoryEditClick, handleStoryCachedTextClick } = this.props;
    const { formatDate, formatMessage } = this.props.intl;

    let content = null;
    if (selectedStoryId) {
      content = (

          <DataCard className="admin-story-view">
            <Row>
              <Col lg={12}>
                <ActionMenu>
                  <MenuItem onClick={() => window.open(selectedStory.url, '_blank')}>
                    <ListItemText><FormattedMessage {...localMessages.readThisStory} /></ListItemText>
                    <ListItemIcon><ReadItNowButton /></ListItemIcon>
                  </MenuItem>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryCachedTextClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.readCachedCopy} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => window.open(`/api/stories/${selectedStoryId}/raw.html`, '_blank')}>
                      <ListItemText><FormattedMessage {...localMessages.viewCachedHtml} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => handleStoryEditClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.editThisStory} /></ListItemText>
                      <ListItemIcon><EditButton tooltip={formatMessage(localMessages.editThisStory)} /></ListItemIcon>
                    </MenuItem>
                    <MenuItem onClick={() => this.downloadCsv(selectedStoryId)}>
                      <ListItemText>
                        <FormattedMessage {...localMessages.downloadAllTagsCsv} />
                      </ListItemText>
                      <ListItemIcon>
                        <DownloadButton />
                      </ListItemIcon>
                    </MenuItem>
                  </Permissioned>
                </ActionMenu>

                  <FormattedMessage {...localMessages.title} />
                  {trimToMaxLength(selectedStory.title, 80)}

              </Col>
            </Row>
            <Row>
              <Col lg={12}>
                <StatBar
                  columnWidth={2}
                  stats={[
                    { message: messages.sourceName,
                      data: (

                          {selectedStory.media_name || selectedStory.media.name}

                      ),
                    },
                    { message: messages.storyDate,
                      data: formatDate(storyPubDateToTimestamp(selectedStory.publish_date)),
                    },
                    { message: messages.language,
                      data: selectedStory.language ? selectedStory.language : '?',
                    },
                    { message: messages.mediaType,
                      data: selectedStory.media.metadata.media_type ? selectedStory.media.metadata.media_type.label : '?',
                      helpTitleMsg: messages.mediaTypeHelpTitle,
                      helpContentMsg: messages.mediaTypeHelpContent,
                    },
                    { message: messages.pubCountry,
                      data: selectedStory.media.metadata.pub_country ? selectedStory.media.metadata.pub_country.label : '?',
                    },
                    { message: messages.pubState,
                      data: selectedStory.media.metadata.pub_state ? selectedStory.media.metadata.pub_state.label : '?' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <StoryEntitiesContainer storyId={selectedStoryId} />
              </Col>
              <Col lg={3}>
                <StoryNytThemesContainer
                  storyId={selectedStoryId}
                  tags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id === TAG_SET_NYT_THEMES) : []}
                  hideFullListOption
                />
              </Col>
            </Row>
            <Row>
              <DataCard className="other-tags">

                  <DownloadButton tooltip={formatMessage(messages.download)} onClick={() => this.downloadCsv(selectedStoryId)} />

                  <FormattedMessage {...localMessages.otherStoryTagTitle} />

                <TagsAndTagSetsTable storyTags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id !== TAG_SET_NYT_THEMES && t.tag_sets_id !== TAG_SET_CLIFF_ORGS && t.tag_sets_id !== TAG_SET_CLIFF_PEOPLE) : []} />
              </DataCard>
            </Row>
          </DataCard>

      );
    }
    return content;
  }
}

SelectedStoryContainer.propTypes = {
  // from parent
  asyncFetch: PropTypes.func.isRequired,
  // from store
  fetchStatus: PropTypes.string.isRequired,
  selectedStory: PropTypes.object.isRequired,
  selectedStoryId: PropTypes.number,
  // from context
  intl: PropTypes.object.isRequired,
  handleStoryCachedTextClick: PropTypes.func.isRequired,
  handleStoryEditClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.story.info.fetchStatus,
  selectedStory: state.story.info,
  selectedStoryId: parseInt(state.story.info.stories_id, 10),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  asyncFetch: () => {
    if (ownProps.params && ownProps.params.id !== undefined) {
      dispatch(fetchStory(parseInt(ownProps.params.id, 10)));
    }
  },
  handleStoryCachedTextClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/cached`));
  },
  handleStoryEditClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/update`));
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    withAsyncFetch(
      SelectedStoryContainer
    )
  )
);
<commit_msg>#1369 container class for TagList<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import withAsyncFetch from '../../hocs/AsyncContainer';
import ActionMenu from '../../ActionMenu';
import { EditButton, ReadItNowButton, DownloadButton } from '../../IconButton';
import { fetchStory } from '../../../../actions/storyActions';
import DataCard from '../../DataCard';
import TagListContainer from './TagListContainer';
import StoryEntitiesContainer from '../../story/StoryEntitiesContainer';
import StoryNytThemesContainer from '../../story/StoryNytThemesContainer';
import messages from '../../../../resources/messages';
import { urlToTools } from '../../../../lib/urlUtil';
import { TAG_SET_NYT_THEMES } from '../../../../lib/tagUtil';
import { trimToMaxLength } from '../../../../lib/stringUtil';
import { storyPubDateToTimestamp } from '../../../../lib/dateUtil';
import Permissioned from '../../Permissioned';
import { PERMISSION_ADMIN } from '../../../../lib/auth';
import StatBar from '../../statbar/StatBar';

const localMessages = {
  title: { id: 'admin.story.title', defaultMessage: 'Story Info: ' },
  close: { id: 'admin.story.inContext.close', defaultMessage: 'Close' },
  readThisStory: { id: 'admin.story.readThisStory', defaultMessage: 'Read This Story' },
  editThisStory: { id: 'admin.story.editThisStory', defaultMessage: 'Edit This Story' },
  fullDescription: { id: 'admin.story.fullDescription', defaultMessage: 'Published in {media} on {publishDate} in {language}' },
  published: { id: 'admin.story.published', defaultMessage: 'Published in {media}' },
  readCachedCopy: { id: 'admin.story.details.readCached', defaultMessage: 'Read Cached Text (admin only)' },
  viewCachedHtml: { id: 'admin.story.details.viewCachedHtml', defaultMessage: 'View Cached HTML (admin only)' },
  downloadAllTagsCsv: { id: 'admin.story.details.downloadTagsCsv', defaultMessage: 'Download all story tags' },
  storyOptions: { id: 'admin.story.details.storyOptions', defaultMessage: 'Story Options' },
};

class SelectedStoryContainer extends React.Component {
  goToUpdateUrl = (storyId) => {
    window.location = `admin/story/${storyId}/update`;
  }

  goToCachedUrl = (storyId) => {
    window.location = `/admin/story/${storyId}/cached`;
  }

  downloadCsv = (storyId) => {
    window.location = `/api/admin/story/${storyId}/storytags.csv`;
  }

  render() {
    const { selectedStory, selectedStoryId, handleStoryEditClick, handleStoryCachedTextClick } = this.props;
    const { formatDate, formatMessage } = this.props.intl;

    let content = null;
    if (selectedStoryId) {
      content = (

          <DataCard className="admin-story-view">
            <Row>
              <Col lg={12}>
                <ActionMenu>
                  <MenuItem onClick={() => window.open(selectedStory.url, '_blank')}>
                    <ListItemText><FormattedMessage {...localMessages.readThisStory} /></ListItemText>
                    <ListItemIcon><ReadItNowButton /></ListItemIcon>
                  </MenuItem>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryCachedTextClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.readCachedCopy} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => window.open(`/api/stories/${selectedStoryId}/raw.html`, '_blank')}>
                      <ListItemText><FormattedMessage {...localMessages.viewCachedHtml} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => handleStoryEditClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.editThisStory} /></ListItemText>
                      <ListItemIcon><EditButton tooltip={formatMessage(localMessages.editThisStory)} /></ListItemIcon>
                    </MenuItem>
                    <MenuItem onClick={() => this.downloadCsv(selectedStoryId)}>
                      <ListItemText>
                        <FormattedMessage {...localMessages.downloadAllTagsCsv} />
                      </ListItemText>
                      <ListItemIcon>
                        <DownloadButton />
                      </ListItemIcon>
                    </MenuItem>
                  </Permissioned>
                </ActionMenu>

                  <FormattedMessage {...localMessages.title} />
                  {trimToMaxLength(selectedStory.title, 80)}

              </Col>
            </Row>
            <Row>
              <Col lg={12}>
                <StatBar
                  columnWidth={2}
                  stats={[
                    { message: messages.sourceName,
                      data: (

                          {selectedStory.media_name || selectedStory.media.name}

                      ),
                    },
                    { message: messages.storyDate,
                      data: formatDate(storyPubDateToTimestamp(selectedStory.publish_date)),
                    },
                    { message: messages.language,
                      data: selectedStory.language ? selectedStory.language : '?',
                    },
                    { message: messages.mediaType,
                      data: selectedStory.media.metadata.media_type ? selectedStory.media.metadata.media_type.label : '?',
                      helpTitleMsg: messages.mediaTypeHelpTitle,
                      helpContentMsg: messages.mediaTypeHelpContent,
                    },
                    { message: messages.pubCountry,
                      data: selectedStory.media.metadata.pub_country ? selectedStory.media.metadata.pub_country.label : '?',
                    },
                    { message: messages.pubState,
                      data: selectedStory.media.metadata.pub_state ? selectedStory.media.metadata.pub_state.label : '?' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <StoryEntitiesContainer storyId={selectedStoryId} />
              </Col>
              <Col lg={3}>
                <StoryNytThemesContainer
                  storyId={selectedStoryId}
                  tags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id === TAG_SET_NYT_THEMES) : []}
                  hideFullListOption
                />
              </Col>
            </Row>
            <Row>
              <Col lg={4}>
                <TagListContainer story={selectedStory} />
              </Col>
            </Row>
          </DataCard>

      );
    }
    return content;
  }
}

SelectedStoryContainer.propTypes = {
  // from parent
  asyncFetch: PropTypes.func.isRequired,
  // from store
  fetchStatus: PropTypes.string.isRequired,
  selectedStory: PropTypes.object.isRequired,
  selectedStoryId: PropTypes.number,
  // from context
  intl: PropTypes.object.isRequired,
  handleStoryCachedTextClick: PropTypes.func.isRequired,
  handleStoryEditClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.story.info.fetchStatus,
  selectedStory: state.story.info,
  selectedStoryId: parseInt(state.story.info.stories_id, 10),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  asyncFetch: () => {
    if (ownProps.params && ownProps.params.id !== undefined) {
      dispatch(fetchStory(parseInt(ownProps.params.id, 10)));
    }
  },
  handleStoryCachedTextClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/cached`));
  },
  handleStoryEditClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/update`));
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    withAsyncFetch(
      SelectedStoryContainer
    )
  )
);
<|endoftext|>


<commit_before>
function createConnectionElement(j) {
  var e = document.createElement("div");
  e.setAttribute("class", "connection");
  var auth = document.createElement("div");
  auth.appendChild(document.createTextNode("Connection: "+j.name));
  // authentication state
  if (j.authed) {
    auth.setAttribute("class", "authed");
    auth.appendChild(document.createTextNode("(authenticated)"));
  } else {
    auth.appendChild(document.createTextNode("(not authenticated)"));
  }
  e.appendChild(auth);

  // connection mode
  var mode = document.createElement("div");
  mode.setAttribute("class", "mode");
  mode.appendChild(document.createTextNode("mode: "+j.mode));
  e.appendChild(mode);
  var backlog = document.createElement("div");
  backlog.setAttribute("class", "backlog");
  backlog.appendChild(document.createTextNode("backlog: "+j.backlog));
  e.appendChild(backlog);
  var pending = document.createElement("div");
  pending.setAttribute("class", "pending");
  // pending articles
  var articles = Object.keys(j.pending);
  pending.appendChild(document.createTextNode("pending articles: "+articles.length));
  for ( var idx = 0 ; idx < articles.length; idx ++ ) {
    var msgid = articles[idx];
    var state = j.pending[msgid];
    var elem = document.createElement("div");
    elem.appendChild(document.createTextNode(msgid + ": " + state));
    elem.setAttribute("class", "pending_item "+state);
    pending.appendChild(elem);
  }
  e.appendChild(pending);
  // e.appendChild(document.createTextNode(JSON.stringify(j)));
  return e;
}

function inject_nntp_feed_element(feed, elem) {
  elem.appendChild(document.createElement("hr"));
  var name = document.createElement("div");
  name.setAttribute("class", "feeds_name");
  name_elem = document.createTextNode("Name: "+feed.State.Config.Name);
  name.appendChild(name_elem);
  elem.appendChild(name);
  var conns = document.createElement("div");
  conns.setAttribute("class", "connections");
  if (feed.Conns) {
    for ( var idx = 0 ; idx < feed.Conns.length; idx ++ ) {
      conns.appendChild(createConnectionElement(feed.Conns[idx]));
    }
  }
  elem.appendChild(conns);
}

function update_nntpchan_feed_ticker(elem, result_elem) {
  nntpchan_admin("feed.list", null, function(j) {
    if (j) {
      if (j.error) {
        console.log("nntpchan_feed_ticker: error, "+j.error);
      } else {
        // remove all children
        while(elem.children.length) {
          elem.children[0].remove();
        }
        var result = j.result;
        for (var idx = 0; idx < result.length; idx++) {
          var item = result[idx];
          var entry = document.createElement("div");
          inject_nntp_feed_element(item, entry);
          elem.appendChild(entry);
        }
      }
    }
  }, result_elem);
}

function nntp_feed_add() {
  var param = {};

  var e = document.getElementById("add_feed_name");
  param.name = e.value;
  e = document.getElementById("add_feed_host");
  param.host = e.value;
  e = document.getElementById("add_feed_port");
  param.port = parseInt(e.value);

  e = document.getElementById("nntpchan_feed_result");
  nntpchan_admin("feed.add", param, null, e);
}

function nntp_feed_del() {
  var e = document.getElementById("del_feed_name");
  var name = e.value;
  e = document.getElementById("nntpchan_feed_result");
  nntpchan_admin("feed.del", {name: name}, null, e);
}

function nntp_feed_update() {
  var e = document.getElementById("nntpchan_feeds");
  if (e) {
    setInterval(function(){
      var e1 = document.getElementById("nntpchan_feed_result");
      update_nntpchan_feed_ticker(e, e1);
    }, 1000);
  }
}
<commit_msg>more mod panel stuff<commit_after>
function createConnectionElement(j) {
  var e = document.createElement("div");
  e.setAttribute("class", "connection");
  var auth = document.createElement("div");
  auth.appendChild(document.createTextNode("Connection: "+j.name));
  // authentication state
  if (j.authed) {
    auth.setAttribute("class", "authed");
    auth.appendChild(document.createTextNode("(authenticated)"));
  } else {
    auth.appendChild(document.createTextNode("(not authenticated)"));
  }
  e.appendChild(auth);

  // connection mode
  var mode = document.createElement("div");
  mode.setAttribute("class", "mode");
  mode.appendChild(document.createTextNode("mode: "+j.mode));
  e.appendChild(mode);
  var backlog = document.createElement("div");
  backlog.setAttribute("class", "backlog");
  backlog.appendChild(document.createTextNode("backlog: "+j.backlog));
  e.appendChild(backlog);
  var pending = document.createElement("div");
  pending.setAttribute("class", "pending");
  // pending articles
  var articles = Object.keys(j.pending);
  pending.appendChild(document.createTextNode("pending articles: "+articles.length));
  for ( var idx = 0 ; idx < articles.length; idx ++ ) {
    var msgid = articles[idx];
    var state = j.pending[msgid];
    var elem = document.createElement("div");
    elem.appendChild(document.createTextNode(msgid + ": " + state));
    elem.setAttribute("class", "pending_item "+state);
    pending.appendChild(elem);
  }
  e.appendChild(pending);
  // e.appendChild(document.createTextNode(JSON.stringify(j)));
  return e;
}

function inject_nntp_feed_element(feed, elem) {
  elem.appendChild(document.createElement("hr"));
  var name = document.createElement("div");
  name.setAttribute("class", "feeds_name");
  name_elem = document.createTextNode("Name: "+feed.State.Config.Name);
  name.appendChild(name_elem);
  elem.appendChild(name);
  var conns = document.createElement("div");
  conns.setAttribute("class", "connections");
  if (feed.Conns) {
    for ( var idx = 0 ; idx < feed.Conns.length; idx ++ ) {
      conns.appendChild(createConnectionElement(feed.Conns[idx]));
    }
  }
  elem.appendChild(conns);
}

function update_nntpchan_feed_ticker(elem, result_elem) {
  nntpchan_admin("feed.list", null, function(j) {
    if (j) {
      if (j.error) {
        console.log("nntpchan_feed_ticker: error, "+j.error);
      } else {
        // remove all children
        while(elem.children.length) {
          elem.children[0].remove();
        }
        var result = j.result;
        result.sort(function(a, b) {
          var aname = a.State.Config.Name;
          var bname = a.state.Config.Name;
          if(aname > bname) return 1;
          else if (aname < bname) return -1;
          else return 0;
        });
        for (var idx = 0; idx < result.length; idx++) {
          var item = result[idx];
          var entry = document.createElement("div");
          inject_nntp_feed_element(item, entry);
          elem.appendChild(entry);
        }
      }
    }
  }, result_elem);
}

function nntp_feed_add() {
  var param = {};

  var e = document.getElementById("add_feed_name");
  param.name = e.value;
  e = document.getElementById("add_feed_host");
  param.host = e.value;
  e = document.getElementById("add_feed_port");
  param.port = parseInt(e.value);

  e = document.getElementById("nntpchan_feed_result");
  nntpchan_admin("feed.add", param, null, e);
}

function nntp_feed_del() {
  var e = document.getElementById("del_feed_name");
  var name = e.value;
  e = document.getElementById("nntpchan_feed_result");
  nntpchan_admin("feed.del", {name: name}, null, e);
}

function nntp_feed_update() {
  var e = document.getElementById("nntpchan_feeds");
  if (e) {
    setInterval(function(){
      var e1 = document.getElementById("nntpchan_feed_result");
      update_nntpchan_feed_ticker(e, e1);
    }, 1000);
  }
}
<|endoftext|>


<commit_before>//Changing the win to = Ti.Ui.currentWindow, just allowed me to declare anytime I wanted to modify something to appear in this window to just
//add "win." whatever else instead of having to write "Titanium.UI.currentWindow." then "add." over and over.
var win = Titanium.UI.currentWindow;
var latitude;
var longitude;

var isAndroid = false;
if (Titanium.Platform.name == 'android'){
	isAndroid = true;
}
/*
The following script showcases the Map Google API and current position of the user.
There is also a listener event that will change the way the map behaviors in accordance to
the GPS location of the user by shifting the view to their location on "eventListener('location')"

Will be adding a PHP script that will update the annotations on the map of the most up to date locations
of other recordings.
*/

//
// Begin Geo Location
//

Titanium.Geolocation.purpose = "Recieve User Location";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
// Set Distance filter. This dictates how often an event fires based on the distance the device moves. This value is in meters.
Titanium.Geolocation.distanceFilter = 10;

// Start by creating the Map with these current coordinates
var mapView = Titanium.Map.createView({
    mapType: Titanium.Map.STANDARD_TYPE,
    animate:true,
    region: {latitude:39.30109620906199, longitude:-76.60234451293945, latitudeDelta:0.1, longitudeDelta:0.1}, //latitude:39.30109620906199 longitude:-76.60234451293945
    regionFit:true,
    userLocation:true,
    visible: true
});

//THIS ONLY FIRES ONCE, ASYNC MEANING IT RUNS AND THEN EXISTS AND WON'T COME BACK. Gets the user's current location.
Titanium.Geolocation.getCurrentPosition(function(e){
        var region={
            latitude: e.coords.latitude,
            longitude: e.coords.longitude,
            animate:true,
            latitudeDelta:0.005,
            longitudeDelta:0.005
        };
        mapView.setLocation(region);
	});

win.add(mapView);

//I believe when the user changes their position, the map will follow them.
mapView.addEventListener('regionChanged', function(e) {
	var latitude = e.latitude;
	var longitude = e.longitude;
});

//Might be redundant, but this is to change the longitude, latitude values when the user moves more tha 10 meters.
Titanium.Geolocation.addEventListener('location', function(e){
	if (e.error) {
		Titanium.API.error('geo - postion' + e.error);
		return;
	}
	var updatedLocation = {
		latitude: e.coords.latitude,
		longitude: e.coords.longitude,
		animate:true,
		latitudeDelta:0.005,
		longitudeDelta:0.005
	};
	mapView.setLocation(updatedLocation);
	Titanium.API.info('geo - position' + updatedLocation);
});

				/*  NAV BAR - Looking at making a "Re-center" button and a "Zoom-in" and "Zoom-out" button for easier navigation
					For this to work I had to delete all the files already complied in the "build/iphone" folder within the project
					folder. I don't know why, but it made a clean rebuild and it started adding the bars and acknowledging the
					"Titanium.UI.iPhone" part of the code instead of declaring it "unknown".  */

				//I believe that these declare the variables without having them set to anything.
				var zoomin = null;
				var zoomout = null;

				/*I have no idea what the "wireClickHandlers" function is suppose to do; I copied this code from the Maps example
				  from the Titanium Appcelerator KitchenSink. I think these just make the "zoom" variables become functions that
				  affect the mapview - and that the "mapview.zoom" part actually details how it changes the map itself.*/

				var wireClickHandlers = function() {
					zoomin.addEventListener('click',function() {
						mapView.zoom(1);
					});
					zoomout.addEventListener('click',function() {
						mapView.zoom(-1);
					});
				};
			  /* This statement is just in place because the "remove all" button (from the Maps example in the Kitchen Sink) won't work on the Android
				 phone as is and needs to be adjusted. So (!isAndroid) = if it isn't the Android OS do the following. It was important to place anyways
				because below, the zoom-in and zoom-out buttons need to have a different method. It is "menu.add" with a title. */
		if (!isAndroid) {
				var flexSpace = Titanium.UI.createButton({
					systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
				});

				zoomin = Titanium.UI.createButton({
					title:'Zoom +',
					style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
				});

				zoomout = Titanium.UI.createButton({
					title:'Zoom -',
					style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
				});

				wireClickHandlers();
				/* The usage of "flexspace" below fills in the gaps. Since I placed a "flexspace" before the other identified buttons, it pushed those
				   buttons all the way to the right. If I wanted to add another button for any reason, just make sure to identify it and then determine
				   how much spacing is wanted. */
				win.setToolbar([flexSpace,zoomin,zoomout]);

		} else {
			var activity = Titanium.Android.currentActivity;
			activity.onCreateOptionsMenu = function() {
				var menu = e.menu;
				zoomin = menu.add({title : "Zoom In"});
				zoomout = menu.add({title : "Zoom Out"});
				wireClickHandlers();
			};
		};<commit_msg>Adding an xhr client to capture all database information at a PHP script on server.<commit_after>//Changing the win to = Ti.Ui.currentWindow, just allowed me to declare anytime I wanted to modify something to appear in this window to just
//add "win." whatever else instead of having to write "Titanium.UI.currentWindow." then "add." over and over.
var win = Titanium.UI.currentWindow;
var latitude;
var longitude;

var isAndroid = false;
if (Titanium.Platform.name == 'android'){
	isAndroid = true;
}
/*
The following script showcases the Map Google API and current position of the user.
There is also a listener event that will change the way the map behaviors in accordance to
the GPS location of the user by shifting the view to their location on "eventListener('location')"

Will be adding a PHP script that will update the annotations on the map of the most up to date locations
of other recordings.
*/

//
// Begin Geo Location
//

Titanium.Geolocation.purpose = "Recieve User Location";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
// Set Distance filter. This dictates how often an event fires based on the distance the device moves. This value is in meters.
Titanium.Geolocation.distanceFilter = 10;

// Start by creating the Map with these current coordinates
var mapView = Titanium.Map.createView({
    mapType: Titanium.Map.STANDARD_TYPE,
    animate:true,
    region: {latitude:39.30109620906199, longitude:-76.60234451293945, latitudeDelta:0.1, longitudeDelta:0.1}, //latitude:39.30109620906199 longitude:-76.60234451293945
    regionFit:true,
    userLocation:true,
    visible: true
});

//THIS ONLY FIRES ONCE, ASYNC MEANING IT RUNS AND THEN EXISTS AND WON'T COME BACK. Gets the user's current location.
Titanium.Geolocation.getCurrentPosition(function(e){
        var region={
            latitude: e.coords.latitude,
            longitude: e.coords.longitude,
            animate:true,
            latitudeDelta:0.005,
            longitudeDelta:0.005
        };
        mapView.setLocation(region);

			var latitude = e.coords.latitude;
			var longitude = e.coords.longitude;
			var geturl="http://localhost/getcoordinates.php?latitude="+latitude+"longitude="+longitude;
			Titanium.API.info(geturl);
		// Begin the "Get data" request

				var xhr = Titanium.Network.createHTTPClient();
				xhr.setTimeout(20000);
				xhr.open('GET', geturl, false); //http://localhost/gps_audio.php
				xhr.onerror = function(e)
				{
					Titanium.UI.createAlertDialog({title:'Error', message:e.error}).show();
					Titanium.API.info('IN ERROR' + e.error);
				};
				xhr.onload = function(){
					Titanium.API.info(this.responseText);
				};
				xhr.send();
	});

win.add(mapView);

//I believe when the user changes their position, the map will follow them.
mapView.addEventListener('regionChanged', function(e) {
	latitude = e.latitude;
 	longitude = e.longitude;
});

//Might be redundant, but this is to change the longitude, latitude values when the user moves more tha 10 meters.
Titanium.Geolocation.addEventListener('location', function(e){
	if (e.error) {
		Titanium.API.error('geo - postion' + e.error);
		return;
	}
	var updatedLocation = {
		latitude: e.coords.latitude,
		longitude: e.coords.longitude,
		animate:true,
		latitudeDelta:0.005,
		longitudeDelta:0.005
	};
	mapView.setLocation(updatedLocation);
	Titanium.API.info('geo - position' + updatedLocation);

	latitude = e.coords.latitude;
	longitude = e.coords.longitude;
	var geturl="http://localhost/getcoordinates.php?latitude="+latitude+"longitude="+longitude;
	Titanium.API.info(geturl);
// Begin the "Get data" request

		var xhr = Titanium.Network.createHTTPClient();
		xhr.setTimeout(20000);
		xhr.open('GET', geturl, false); //http://localhost/gps_audio.php
		xhr.onerror = function(e)
		{
			Titanium.UI.createAlertDialog({title:'Error', message:e.error}).show();
			Titanium.API.info('IN ERROR' + e.error);
		};
		xhr.onload = function(e){
			Titanium.API.info(this.responseText);
		};
		xhr.send();

});

				/*  NAV BAR - Looking at making a "Re-center" button and a "Zoom-in" and "Zoom-out" button for easier navigation
					For this to work I had to delete all the files already complied in the "build/iphone" folder within the project
					folder. I don't know why, but it made a clean rebuild and it started adding the bars and acknowledging the
					"Titanium.UI.iPhone" part of the code instead of declaring it "unknown".  */

				//I believe that these declare the variables without having them set to anything.
				var zoomin = null;
				var zoomout = null;

				/*I have no idea what the "wireClickHandlers" function is suppose to do; I copied this code from the Maps example
				  from the Titanium Appcelerator KitchenSink. I think these just make the "zoom" variables become functions that
				  affect the mapview - and that the "mapview.zoom" part actually details how it changes the map itself.*/

				var wireClickHandlers = function() {
					zoomin.addEventListener('click',function() {
						mapView.zoom(1);
					});
					zoomout.addEventListener('click',function() {
						mapView.zoom(-1);
					});
				};
			  /* This statement is just in place because the "remove all" button (from the Maps example in the Kitchen Sink) won't work on the Android
				 phone as is and needs to be adjusted. So (!isAndroid) = if it isn't the Android OS do the following. It was important to place anyways
				because below, the zoom-in and zoom-out buttons need to have a different method. It is "menu.add" with a title. */
		if (!isAndroid) {
				var flexSpace = Titanium.UI.createButton({
					systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
				});

				zoomin = Titanium.UI.createButton({
					title:'Zoom +',
					style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
				});

				zoomout = Titanium.UI.createButton({
					title:'Zoom -',
					style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED
				});

				wireClickHandlers();
				/* The usage of "flexspace" below fills in the gaps. Since I placed a "flexspace" before the other identified buttons, it pushed those
				   buttons all the way to the right. If I wanted to add another button for any reason, just make sure to identify it and then determine
				   how much spacing is wanted. */
				win.setToolbar([flexSpace,zoomin,zoomout]);

		} else {
			var activity = Titanium.Android.currentActivity;
			activity.onCreateOptionsMenu = function() {
				var menu = e.menu;
				zoomin = menu.add({title : "Zoom In"});
				zoomout = menu.add({title : "Zoom Out"});
				wireClickHandlers();
			};
		};<|endoftext|>


<commit_before>/* 	Class: $res
	Global object for managing the servlet response.

	All content produced via <$res.print> or <Myna.print> is appended to an
	internal response buffer. This content is nomally sent to the browser
	at the end of the request. By using the content maniplulation functions
	in this object (<getContent>, <clear> and <print>) you can alter content
	before it reaches the browser.

	Note that <flush> sends content to the browser immediately and resets the
	buffer.
*/
var $res = {
/* 	Function: clear
		Clears response buffer and returns the previous contents.

		Returns:
			Response content before it wwas cleared

		Detail:
			Response content created by <$res.print> is buffered internally. This function clears
			that buffer and returns it's previous contents.

		See:
			<$res.print>, <$res.getContent>
	*/
	clear:function (){
		var currentContent;
			currentContent =String($server_gateway.generatedContent.toString());
			$server_gateway.generatedContent.setLength(0);
		return currentContent;

	},
/* 	Function: getContent
		Returns current response buffer contents.

		Returns:
			Current response buffer contents

		Detail:
			Response content created by <$res.print> is buffered internally. This function returns
			the current contents of that buffer.

		See:
			<$res.print>, <$res.clear>

	*/
	getContent:function (){
		return String($server_gateway.generatedContent.toString());

	},
/* 	Function: flush
		Sends the current response buffer contents to the browser.

		Paramters:
			paddingSize	-	*Optional default 250* Number of space (" ") charcters to append
							to encourage the browser to display the content immediately.

		Returns:
			Current response buffer contents.

		Detail:
			Response content created by <$res.print> is buffered internally. This function
			sends the current contents of that buffer to the browser, and then clears the
			buffer and	returns its former contents. No changes to the HTTP response can be
			sent after a call to flushContent, such as cookies.

		See:
			<$res.print>, <$res.clear>

	*/
	flush:function (paddingSize){
		if (!$server.response) return "";
		if (paddingSize==undefined) paddingSize =250;
		var padding ="";

		new Array(paddingSize).forEach(function(){padding+=" "});
		$server.response.getWriter().print(padding);
		$server.response.getWriter().print($res.getContent());
		$server.response.flushBuffer();
		return $res.clear();
	},
/* 	Function: requestBasicAuth
		returns a "Basic" http auth request

		Parameters:
			realm - *default 'Myna Application Server'* an organization or
					application name to indicate to the user what
					credentials to enter

		Detail:
			sets the WWW-Authenticate header and returns a 401 HTTP status.
			any content sent after this function call will likely not be
			displayed by a browser

	*/
	requestBasicAuth:function(realm){
		$res.setHeader("WWW-Authenticate",'Basic realm="' + realm + '"');
		$res.setStatusCode(401,"Access Denied")
	},
/* 	Function: setContentType
		sets the content MIME type of the response.

		Parameters:
			type - *default 'text/html'* MIME content type string
		Returns:
			Current response buffer contents.

		Detail:
			Response content created by <$res.print> is buffered internally. This function returns
			the current contents of that buffer.

	*/
	setContentType:function(type){
		if ($server.response) $server.response.setContentType(java.lang.String(type));
	},
/* 	Function: setStatusCode
		returns an HTTP status code and optionally a message for this response

		Parameters:
			code 	- 	Numeric HTTP status code such as 403,401,500 etc
			msg		-	*Optional default null*
						A string message to return to the browser

		Example:
			$res.metaRedirect("some_other_page.ejs");
	*/
	setStatusCode:function(code,msg){
		if (msg){
			$server.response.sendError(code,msg);
		} else {
			$server.response.setStatus(code);
		}
	},
/* 	Function: metaRedirect
		redirect this page using META HTTP-EQUIV="refresh" tag. This method
		preserves any headers, such as cookies, sent to the browser during this
		request.

		Parameters:
			url - url to redirect to

		Example:
			$res.metaRedirect("some_other_page.ejs");
	*/
	metaRedirect:function(url){
		this.print('<META HTTP-EQUIV="refresh" content="0; url=' + url + '">');
	},
/* 	Function: setHeader
		sets a header to return to the browser

		Parameters:
			name 	-  	Header name
			value	-	Header value

		Example:
			$res.setHeader("Content-disposition", 'attachment; filename="result.xls"');

	*/
	setHeader:function(name,value){
		if ($server.response) $server.response.setHeader(name,value);
	},
/* 	Function: printBinary
		sends binary data to the browser

		Parameters:
			data 		-  	Binary data from <Myna.File.readBinary> or from binary
							database query (byte [])

			contentType -	*Optional, default application/octet-stream* MIME type of
							the binary data. If "" or null, the default will be used

			filename	-	*Optional, default null* if defined, a "Content-disposition"
							reponse header is set to present the standard "Save or Open?"
							dialog to the client. Use this if offering a file for download,
							but not if you expect the content to be rendered inline

		Detail:
			This function replaces the normal output of this response with the contents
			of _data_. Executing this function after a call to <$res.flush> will likely
			fail or currupt the file.

		Example:
			var bytes = new Myna.File("path_to_doc.pdf").readBinary();
			$res.printBinary(bytes,"application/pdf","result.pdf");

	*/
	printBinary:function(data,contentType,filename){
		if (!contentType || contentType=="") contentType="appplication/octet-stream";

		$res.setContentType(contentType);
		$server.response.setContentLength(data.length);
		if (filename){
			$res.setHeader("Content-disposition", 'attachment; filename="'+filename+'"');
		}
		var writer = $server.response.getOutputStream();
		writer.write(data,0,data.length);
	},
/* 	Function: print
		Appends content to the response buffer.

		Parameters:
			text - text to append to response buffer

		Returns:
			void

		Detail:
			Response content created by <$res.print> is buffered internally.
			At the end of the request this content is flushed to the browser

		See:
			<$res.clear>, <$res.getContent>
	*/
	print:function (text){
			$server_gateway.generatedContent.append(String(text));
	},
}<commit_msg>* added optional 'message' argument to .requestBasicAuth<commit_after>/* 	Class: $res
	Global object for managing the servlet response.

	All content produced via <$res.print> or <Myna.print> is appended to an
	internal response buffer. This content is nomally sent to the browser
	at the end of the request. By using the content maniplulation functions
	in this object (<getContent>, <clear> and <print>) you can alter content
	before it reaches the browser.

	Note that <flush> sends content to the browser immediately and resets the
	buffer.
*/
var $res = {
/* 	Function: clear
		Clears response buffer and returns the previous contents.

		Returns:
			Response content before it wwas cleared

		Detail:
			Response content created by <$res.print> is buffered internally. This function clears
			that buffer and returns it's previous contents.

		See:
			<$res.print>, <$res.getContent>
	*/
	clear:function (){
		var currentContent;
			currentContent =String($server_gateway.generatedContent.toString());
			$server_gateway.generatedContent.setLength(0);
		return currentContent;

	},
/* 	Function: getContent
		Returns current response buffer contents.

		Returns:
			Current response buffer contents

		Detail:
			Response content created by <$res.print> is buffered internally. This function returns
			the current contents of that buffer.

		See:
			<$res.print>, <$res.clear>

	*/
	getContent:function (){
		return String($server_gateway.generatedContent.toString());

	},
/* 	Function: flush
		Sends the current response buffer contents to the browser.

		Paramters:
			paddingSize	-	*Optional default 250* Number of space (" ") charcters to append
							to encourage the browser to display the content immediately.

		Returns:
			Current response buffer contents.

		Detail:
			Response content created by <$res.print> is buffered internally. This function
			sends the current contents of that buffer to the browser, and then clears the
			buffer and	returns its former contents. No changes to the HTTP response can be
			sent after a call to flushContent, such as cookies.

		See:
			<$res.print>, <$res.clear>

	*/
	flush:function (paddingSize){
		if (!$server.response) return "";
		if (paddingSize==undefined) paddingSize =250;
		var padding ="";

		new Array(paddingSize).forEach(function(){padding+=" "});
		$server.response.getWriter().print(padding);
		$server.response.getWriter().print($res.getContent());
		$server.response.flushBuffer();
		return $res.clear();
	},
/* 	Function: requestBasicAuth
		returns a "Basic" http auth request

		Parameters:
			realm 	- 	*Optional, default 'Myna Application Server'*
						an organization or application name to indicate to the
						user what credentials to enter
			message	-	*Optional, default null*
						A message to include withthe request. This may not be
						shown by the browser, or may only be shown after three
						failures

		Detail:
			sets the WWW-Authenticate header and returns a 401 HTTP status.
			any content sent after this function call will likely not be
			displayed by a browser

	*/
	requestBasicAuth:function(realm, message){
		$res.setHeader("WWW-Authenticate",'Basic realm="'
			+ (realm||"Myna Application Server") + '"');
		$res.setStatusCode(401,message||"")
	},
/* 	Function: setContentType
		sets the content MIME type of the response.

		Parameters:
			type - *default 'text/html'* MIME content type string
		Returns:
			Current response buffer contents.

		Detail:
			Response content created by <$res.print> is buffered internally. This function returns
			the current contents of that buffer.

	*/
	setContentType:function(type){
		if ($server.response) $server.response.setContentType(java.lang.String(type));
	},
/* 	Function: setStatusCode
		returns an HTTP status code and optionally a message for this response

		Parameters:
			code 	- 	Numeric HTTP status code such as 403,401,500 etc
			msg		-	*Optional default null*
						A string message to return to the browser

		Example:
			$res.metaRedirect("some_other_page.ejs");
	*/
	setStatusCode:function(code,msg){
		if (msg){
			$server.response.sendError(code,msg);
		} else {
			$server.response.setStatus(code);
		}
	},
/* 	Function: metaRedirect
		redirect this page using META HTTP-EQUIV="refresh" tag. This method
		preserves any headers, such as cookies, sent to the browser during this
		request.

		Parameters:
			url - url to redirect to

		Example:
			$res.metaRedirect("some_other_page.ejs");
	*/
	metaRedirect:function(url){
		this.print('<META HTTP-EQUIV="refresh" content="0; url=' + url + '">');
	},
/* 	Function: setHeader
		sets a header to return to the browser

		Parameters:
			name 	-  	Header name
			value	-	Header value

		Example:
			$res.setHeader("Content-disposition", 'attachment; filename="result.xls"');

	*/
	setHeader:function(name,value){
		if ($server.response) $server.response.setHeader(name,value);
	},
/* 	Function: printBinary
		sends binary data to the browser

		Parameters:
			data 		-  	Binary data from <Myna.File.readBinary> or from binary
							database query (byte [])

			contentType -	*Optional, default application/octet-stream* MIME type of
							the binary data. If "" or null, the default will be used

			filename	-	*Optional, default null* if defined, a "Content-disposition"
							reponse header is set to present the standard "Save or Open?"
							dialog to the client. Use this if offering a file for download,
							but not if you expect the content to be rendered inline

		Detail:
			This function replaces the normal output of this response with the contents
			of _data_. Executing this function after a call to <$res.flush> will likely
			fail or currupt the file.

		Example:
			var bytes = new Myna.File("path_to_doc.pdf").readBinary();
			$res.printBinary(bytes,"application/pdf","result.pdf");

	*/
	printBinary:function(data,contentType,filename){
		if (!contentType || contentType=="") contentType="appplication/octet-stream";

		$res.setContentType(contentType);
		$server.response.setContentLength(data.length);
		if (filename){
			$res.setHeader("Content-disposition", 'attachment; filename="'+filename+'"');
		}
		var writer = $server.response.getOutputStream();
		writer.write(data,0,data.length);
	},
/* 	Function: print
		Appends content to the response buffer.

		Parameters:
			text - text to append to response buffer

		Returns:
			void

		Detail:
			Response content created by <$res.print> is buffered internally.
			At the end of the request this content is flushed to the browser

		See:
			<$res.clear>, <$res.getContent>
	*/
	print:function (text){
		//Myna.log("debug","text - " + $server.isThread,text);
			$server_gateway.generatedContent.append(String(text));
	},
}<|endoftext|>


<commit_before>var tar = null;

document.addEventListener("mousedown", function(event){
	if(event.button == 2 || event.button == 0)
		tar = event.srcElement;
}, true);

window.onload = load();

function load(){
	dispatchToBackgroundScript({"query": "scanningFlag"}, function(response){
		if(response.scanning) // then create list of all images, and send to list.
		{
			var size = response.scanSize;
			var list = document.getElementsByTagName("img");
			var message = {};

			message.query = "addEnclosed";

			message.arr = [];
			for(var i = 0; i < list.length; i++)
			{
				if (list[i].height >= size && list[i].width >= size)
					message.arr.push(list[i].src);
			}

			if(message.arr.length == 0) // don't send a blank list.
				return;
			dispatchToBackgroundScript(message);
		}
	});
}

function dispatchToBackgroundScript(message, callback) {
	chrome.runtime.sendMessage(message, callback);
}

/** Adds all images thumbnailed on this site to the list.
 *
 * Useful on certain websites. Requirement: the element
 * that was right-clicked is a thumbnail that:
 * A) links to the full sized image, and
 * B) sits inside some element that has a class shared by all such thumbnails.
 *
 * If both of the above are true, then this function will return all images
 * from those links in an object, with the thumbnails as "samples"
 */
function getUrlsOfParentClass(request) {
	var list;

	var urlList = {};
	urlList.arr = [];
	urlList.sampArr = [];

	if(request.pageUrl.indexOf("http://imgur.com/") == 0){
 		// imgur sidebar.
		if(tar.getAttribute("class").indexOf("nav-link") >= 0)
		{
			list = document.getElementsByClassName("nav-link");
			for(var i = 0; i < list.length; i++)
			{
				var id = list[i].dataset.hash;
				var isAlbum = id.length <= 6; // this is a hack. ablums are usually 5 characters, images 7
				if(isAlbum)
					continue;
				var url = "http://i.imgur.com/" + id + ".jpg";
				var sampUrl = "http://i.imgur.com/" + id + "b.jpg";

				urlList.arr.push(url);
				urlList.sampArr.push(sampUrl);
			}
		}
		else // imgur main
		{
			list = document.getElementsByClassName("post");
			if(list != null && list.length >= 0)
			{
				console.log("in imgur");
				for(var i = 0; i < list.length; i++)
				{
					var id = list[i].id;
					var isAlbum = list[i].querySelector(".post-info").innerHTML.indexOf("album") > 0;
					if(isAlbum)
						continue;
					var isAnimated = list[i].querySelector(".post-info").innerHTML.indexOf("animated") > 0;
					var urlEnd = isAnimated ? ".gif" : ".jpg";
					var url = "http://i.imgur.com/" + id + urlEnd;

					var sampUrl = list[i].querySelector("img").src;

					urlList.arr.push(url);
					urlList.sampArr.push(sampUrl);
				}
			}
		}
	}
	else
	{
		var cl = tar.parentElement.getAttribute("class");
		var list = document.getElementsByClassName(cl);

		for(var i = 0; i < list.length; i++)
		{
			urlList.arr[i] = list[i].href;
			urlList.sampArr[i] = list[i].getElementsByTagName("img")[0].getAttribute("src");
		}
	}
	return urlList;
}

// Grabs the only image on page if only one. Otherwise, grabs all images above a prompted size.
function getUrlsOfPageImages() {
	var list = document.body.getElementsByTagName("img");

	if(list.length > 1)
	{
		var size = prompt("Minimum size of images (in px) to add to list:");
		if(size != null)
			return getUrlsOfPageImagesGivenSize(size, true);
	}
	else if(list.length == 1)
	{
		var response = {};
		response.arr = [];

		for(var i = 0; i < list.length; i++)
		{
			list[i].style.border = "2px solid red";
			response.arr.push(list[i].src);
		}

		return response;
	}
	// if they canceled on prompt, or 0 images
	return null;
}

// Grabs the only image on page if only one. Otherwise, grabs all images above a prompted size.
function getUrlsOfPageImagesGivenSize(dim, markRed) {
	var response = {};
	response.arr = [];

	var list = document.body.getElementsByTagName("img");
	for(var i = 0; i < list.length; i++)
	{
		if (list[i].height >= dim && list[i].width >= dim)
		{
			if(markRed)
				list[i].style.border = "2px solid red";
			response.arr.push(list[i].src);
		}
	}

	return response;
}

//receives messages from other scripts.
chrome.runtime.onMessage.addListener(
	function(request, sender, sendResponse) {
		console.log(request);
		if(request.query == "urlsOfParentClass") // from bg.js
			sendResponse(getUrlsOfParentClass(request));
		else if(request.query === "urlsOfPageImages") // from bg.js
			sendResponse(getUrlsOfPageImages());
		else if(request.query === "urlsOfPageImagesGivenSize") // from bg.js
			sendResponse(getUrlsOfPageImagesGivenSize(request.dimension, false));

	}
);
<commit_msg>Added deviantArt to thumbnail searcher<commit_after>var tar = null;

document.addEventListener("mousedown", function(event){
	if(event.button == 2 || event.button == 0)
		tar = event.srcElement;
}, true);

window.onload = load();

function load(){
	dispatchToBackgroundScript({"query": "scanningFlag"}, function(response){
		if(response.scanning) // then create list of all images, and send to list.
		{
			var size = response.scanSize;
			var list = document.getElementsByTagName("img");
			var message = {};

			message.query = "addEnclosed";

			message.arr = [];
			for(var i = 0; i < list.length; i++)
			{
				if (list[i].height >= size && list[i].width >= size)
					message.arr.push(list[i].src);
			}

			if(message.arr.length == 0) // don't send a blank list.
				return;
			dispatchToBackgroundScript(message);
		}
	});
}

function dispatchToBackgroundScript(message, callback) {
	chrome.runtime.sendMessage(message, callback);
}

/** Adds all images thumbnailed on this site to the list.
 *
 * Useful on certain websites. Requirement: the element
 * that was right-clicked is a thumbnail that:
 * A) links to the full sized image, and
 * B) sits inside some element that has a class shared by all such thumbnails.
 *
 * If both of the above are true, then this function will return all images
 * from those links in an object, with the thumbnails as "samples"
 */
function getUrlsOfParentClass(request) {
	var list;

	var urlList = {};
	urlList.arr = [];
	urlList.sampArr = [];

	if(request.pageUrl.indexOf("http://imgur.com/") == 0){
 		// imgur sidebar.
		if(tar.getAttribute("class").indexOf("nav-link") >= 0)
		{
			list = document.getElementsByClassName("nav-link");
			for(var i = 0; i < list.length; i++)
			{
				var id = list[i].dataset.hash;
				var isAlbum = id.length <= 6; // this is a hack. ablums are usually 5 characters, images 7
				if(isAlbum)
					continue;
				var url = "http://i.imgur.com/" + id + ".jpg";
				var sampUrl = "http://i.imgur.com/" + id + "b.jpg";

				urlList.arr.push(url);
				urlList.sampArr.push(sampUrl);
			}
		}
		else // imgur main
		{
			list = document.getElementsByClassName("post");
			if(list != null && list.length >= 0)
			{
				for(var i = 0; i < list.length; i++)
				{
					var id = list[i].id;
					var isAlbum = list[i].querySelector(".post-info").innerHTML.indexOf("album") > 0;
					if(isAlbum)
						continue;
					var isAnimated = list[i].querySelector(".post-info").innerHTML.indexOf("animated") > 0;
					var urlEnd = isAnimated ? ".gif" : ".jpg";
					var url = "http://i.imgur.com/" + id + urlEnd;

					var sampUrl = list[i].querySelector("img").src;

					urlList.arr.push(url);
					urlList.sampArr.push(sampUrl);
				}
			}
		}
	}
	else if(request.pageUrl.indexOf("deviantart.com/") >= 0){
		list = document.getElementsByClassName("thumb");
		if(list != null && list.length >= 0)
		{
			for(var i = 0; i < list.length; i++)
			{
				var url = list[i].dataset.superImg;
				var sampUrl = list[i].querySelector("img").src;

				urlList.arr.push(url);
				urlList.sampArr.push(sampUrl);
			}
		}
	}
	else
	{
		var cl = tar.parentElement.getAttribute("class");
		var list = document.getElementsByClassName(cl);

		for(var i = 0; i < list.length; i++)
		{
			urlList.arr[i] = list[i].href;
			urlList.sampArr[i] = list[i].getElementsByTagName("img")[0].getAttribute("src");
		}
	}
	return urlList;
}

// Grabs the only image on page if only one. Otherwise, grabs all images above a prompted size.
function getUrlsOfPageImages() {
	var list = document.body.getElementsByTagName("img");

	if(list.length > 1)
	{
		var size = prompt("Minimum size of images (in px) to add to list:");
		if(size != null)
			return getUrlsOfPageImagesGivenSize(size, true);
	}
	else if(list.length == 1)
	{
		var response = {};
		response.arr = [];

		for(var i = 0; i < list.length; i++)
		{
			list[i].style.border = "2px solid red";
			response.arr.push(list[i].src);
		}

		return response;
	}
	// if they canceled on prompt, or 0 images
	return null;
}

// Grabs the only image on page if only one. Otherwise, grabs all images above a prompted size.
function getUrlsOfPageImagesGivenSize(dim, markRed) {
	var response = {};
	response.arr = [];

	var list = document.body.getElementsByTagName("img");
	for(var i = 0; i < list.length; i++)
	{
		if (list[i].height >= dim && list[i].width >= dim)
		{
			if(markRed)
				list[i].style.border = "2px solid red";
			response.arr.push(list[i].src);
		}
	}

	return response;
}

//receives messages from other scripts.
chrome.runtime.onMessage.addListener(
	function(request, sender, sendResponse) {
		// console.log(request);
		if(request.query == "urlsOfParentClass") // from bg.js
			sendResponse(getUrlsOfParentClass(request));
		else if(request.query === "urlsOfPageImages") // from bg.js
			sendResponse(getUrlsOfPageImages());
		else if(request.query === "urlsOfPageImagesGivenSize") // from bg.js
			sendResponse(getUrlsOfPageImagesGivenSize(request.dimension, false));

	}
);
<|endoftext|>


<commit_before>import React from 'react';
import css from './NavButton.css';

const propTypes = {
  href: React.PropTypes.string,
  title: React.PropTypes.string,
  onClick: React.PropTypes.func,
  onKeyDown: React.PropTypes.func,
  children: React.PropTypes.node.isRequired,
  md: React.PropTypes.string, // eslint-disable-line
};

function NavButton(props) {
  function getClass() {
    const base = css.navButton;
    const hide = props.md === 'hide' ? css.hideMed : '';
    return `${base} ${hide}`;
  }

  const { children, md, bsRole, bsClass, ...buttonProps } = props; // eslint-disable-line

  if (props.href) {
    return (

        {props.children}

    );
  }

  return (
    <button
      type="button"
      className={getClass()}
      {...buttonProps}
    >

        {children}

    </button>
  );
}

NavButton.propTypes = propTypes;

export default NavButton;
<commit_msg>The NavButton component uses <Link to="x"> instead of  so that it doesn't force a reload when navigating to "/" for STRIPES-250.<commit_after>import React from 'react';
import Link from 'react-router/Link';
import css from './NavButton.css';

const propTypes = {
  href: React.PropTypes.string,
  title: React.PropTypes.string,
  onClick: React.PropTypes.func,
  onKeyDown: React.PropTypes.func,
  children: React.PropTypes.node.isRequired,
  md: React.PropTypes.string, // eslint-disable-line
};

function NavButton(props) {
  function getClass() {
    const base = css.navButton;
    const hide = props.md === 'hide' ? css.hideMed : '';
    return `${base} ${hide}`;
  }

  const { children, md, bsRole, bsClass, href, ...buttonProps } = props; // eslint-disable-line

  if (props.href) {
    return (
      <Link
        className={getClass()}
        to={href}
        {...buttonProps}
      >
        {props.children}
      </Link>
    );
  }

  return (
    <button
      type="button"
      className={getClass()}
      {...buttonProps}
    >

        {children}

    </button>
  );
}

NavButton.propTypes = propTypes;

export default NavButton;
<|endoftext|>


<commit_before>$( document ).ready(function() {
  let siteUrl = 'https://paulcaronnews.tumblr.com';
  $.ajax({
    url: `${siteUrl}/api/read/xml?num=10&&type=text`,
    dataType: 'jsonp'
  }).done(function(data) {
    let posts = data.posts,
    blogsHtml = `

                  RSS Feed

`;
    for(let x in posts){
      blogsHtml +=
        `

${posts[x]["regular-title"]} ${posts[x]["date"]}

            ${posts[x]["regular-body"]}

`;
    }
    blogsHtml += `

        For more see the archives ...

`
    $('#blogDiv').html(blogsHtml)
  });

});
<commit_msg>tumblrGetter: fix issue with MIME type not matching<commit_after>$( document ).ready(function() {
  let siteUrl = 'https://paulcaronnews.tumblr.com';
  $.ajax({
    url: `${siteUrl}/api/read/json?num=10&&type=text`,
    dataType: 'jsonp'
  }).done(function(data) {
    let posts = data.posts,
    blogsHtml = `

                  RSS Feed

`;
    for(let x in posts){
      blogsHtml +=
        `

${posts[x]["regular-title"]} ${posts[x]["date"]}

            ${posts[x]["regular-body"]}

`;
    }
    blogsHtml += `

        For more see the archives ...

`
    $('#blogDiv').html(blogsHtml)
  });

});
<|endoftext|>


<commit_before>const path = require('path')
const webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const root = path.join(__dirname)
const demo = path.join(root + '/demo/')
const dist = path.join(root + '/dist/')
const nodeModules = path.join(root, '/node_modules/')

module.exports = {
  entry: {
    app: [path.resolve(demo + 'index.js')]
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [demo, path.join(nodeModules, '@material')],
        options: {
          cacheDirectory: true
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          preserveWhitespace: false,
          loaders: {
            scss: ExtractTextPlugin.extract({
              fallback: 'style-loader',
              use: [
                {
                  loader: 'css-loader',
                  options: {
                    sourceMap: false,
                    importLoaders: 1
                  }
                },
                {
                  loader: 'postcss-loader'
                },
                {
                  loader: 'sass-loader',
                  options: {
                    includePaths: [nodeModules]
                  }
                }
              ]
            })
          }
        }
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
        exclude: /node_modules/,
        options: {
          minimize: true
        }
      },
      {
        test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
        loader: 'url-loader',
        options: {
          limit: 10000
        }
      }
    ]
  },
  resolve: {
    alias: {
      panels: path.resolve(demo + '/panels/'),
      views: path.resolve(demo + '/views/'),
      modules: path.resolve(demo + '/store/modules/'),
      routes: path.resolve(demo + '/router/routes/')
    },
    extensions: ['.js', '.json', '.css', '.scss', '.vue']
  },
  plugins: [
    new webpack.ProvidePlugin({
      Promise: 'core-js/fn/promise'
    }),
    new CleanWebpackPlugin(['public']),
    new HtmlWebpackPlugin({
      template: path.resolve(demo + 'index.html'),
      chunksSortMode: 'dependency'
      // hash: true
    }),
    // new ScriptExtHtmlWebpackPlugin({
    // prefetch: {
    // test: /\.js$/,
    // chunks: 'async'
    // }
    // }),
    new ExtractTextPlugin({
      filename: '[name].[chunkhash].min.css',
      allChunks: false
    })
  ],
  stats: {
    all: false,
    assets: true,
    chunkModules: true,
    chunkOrigins: true,
    errors: true,
    errorDetails: true,
    colors: true
  }
}
<commit_msg>fix(build): Fix CSS extract plugin (close #78)<commit_after>const path = require('path')
const webpack = require('webpack')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

const root = path.join(__dirname)
const demo = path.join(root + '/demo/')
const nodeModules = path.join(root, '/node_modules/')

module.exports = {
  entry: {
    app: [path.resolve(demo + 'index.js')]
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [demo, path.join(nodeModules, '@material')],
        options: {
          cacheDirectory: true
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          preserveWhitespace: false,
          loaders: {
            scss: ExtractTextPlugin.extract({
              fallback: 'style-loader',
              use: [
                {
                  loader: 'css-loader',
                  options: {
                    sourceMap: false,
                    importLoaders: 1
                  }
                },
                {
                  loader: 'postcss-loader'
                },
                {
                  loader: 'sass-loader',
                  options: {
                    includePaths: [nodeModules]
                  }
                }
              ]
            })
          }
        }
      },
      {
        test: /\.html$/,
        loader: 'html-loader',
        exclude: /node_modules/,
        options: {
          minimize: true
        }
      },
      {
        test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
        loader: 'url-loader',
        options: {
          limit: 10000
        }
      }
    ]
  },
  resolve: {
    alias: {
      panels: path.resolve(demo + '/panels/'),
      views: path.resolve(demo + '/views/'),
      modules: path.resolve(demo + '/store/modules/'),
      routes: path.resolve(demo + '/router/routes/')
    },
    extensions: ['.js', '.json', '.css', '.scss', '.vue']
  },
  plugins: [
    new webpack.ProvidePlugin({
      Promise: 'core-js/fn/promise'
    }),
    new CleanWebpackPlugin(['public']),
    new HtmlWebpackPlugin({
      template: path.resolve(demo + 'index.html'),
      chunksSortMode: 'dependency'
      // hash: true
    }),
    // new ScriptExtHtmlWebpackPlugin({
    // prefetch: {
    // test: /\.js$/,
    // chunks: 'async'
    // }
    // }),
    new ExtractTextPlugin({
      filename: '[name].[chunkhash].min.css',
      allChunks: true
    })
  ],
  stats: {
    all: false,
    assets: true,
    chunkModules: true,
    chunkOrigins: true,
    errors: true,
    errorDetails: true,
    colors: true
  }
}
<|endoftext|>