<commit_before>$(function() {

    var addListing = require('./firebase.js')['addListing'];
    var auth = require('./firebase.js')['auth'];
    var itemTitle;
    var itemDescription;
    var itemTags;
    var itemPrice;
    var itemHub;
    var itemUid;
    var itemImages;

    var checkBasicItems = function() {
        var checksPassed = true;
        itemUid = auth.currentUser.uid;
        itemTitle = $("#item-post-title").val();
        itemDescription = $("#item-post-description").val();
        itemTags = $('#itemTags').textext()[0].tags()._formData;
        itemPrice = $("#item-post-price").val();
        itemImages = [];
        $('#dropzone').find('img').each(function(index) {
            itemImages.push($(this).attr('src'));
        });

        // itemHub needs to be changed
        itemHub = "hardcodedForNow";

        if (!/^[\w\s]{5,30}$/.test(itemTitle)) {
            Materialize.toast('Title must be between 5 and 30 characters', 3000, 'rounded');
            checksPassed = false;
        } else if (!/^[\w\s\.]+$/.test(itemDescription) || itemDescription.length < 5) {
            Materialize.toast('Description can only contain letters and numbers', 3000, 'rounded');
            checksPassed = false;
        } else if(!itemPrice.match(/^[0-9]+([.][0-9]{0,2})?$/) || itemPrice < 0.01 || itemPrice > 3000) {
            Materialize.toast('only enter numbers, and an optional decimal', 3000, 'rounded');
            checksPassed = false;
        } else if(!/^[a-zA-Z\s]+$/.test(itemHub)) {
            checksPassed = false;
        } else if (itemTags.length < 2 || itemTags.length > 5) {
            Materialize.toast('Please enter 2 to 5 tags', 3000, 'rounded');
            checksPassed = false;
        } else if (itemImages.length < 1) {
            Materialize.toast('Please add at least one image', 3000, 'rounded');
            checksPassed = false;
        } else {
            for (var i = 0; i < itemTags.length; i += 1) {
                if (!/^[a-zA-Z\s]+$/.test(itemTags[i]) || itemTags[i].length > 15) {
                    Materialize.toast('tags can only contain letters and spaces, up to 15 characters', 3000, 'rounded');
                    checksPassed = false;
                }
            }
        }
        return checksPassed;
    };

    var addImagesToSlider = function() {
        let imageCount = ['one', 'two', 'three', 'four'];
        $('#carousel-wrapper').append($('

').addClass('carousel carousel-slider'));

        for (var i = 0; i < itemImages.length; i += 1) {
            $('.carousel-slider').append(
                $('').addClass('carousel-item').attr('href', '#' + imageCount[i] + '!').append(
                    $('').attr('src', itemImages[i])
                )
            );
        }
        $('.carousel.carousel-slider').carousel({full_width: true, indicators: true});
    };

    $("#post-preview").click(function () {
        if (checkBasicItems()) {
            addImagesToSlider();

            $('#preview-submit-tab').removeClass('disabled');
            $('ul.tabs').tabs('select_tab', 'preview-submit');
            $('#basic-info-tab').addClass('disabled');

            $('#preview-title').append(itemTitle);
            $('#preview-price').append(itemPrice);
            $('#preview-description').append(itemDescription);

            for (tag of itemTags) {
                $('#preview-tags').append(
                    $('').attr('href', '#').addClass('hub-card').text(tag)
                );
                $('#preview-tags').append(" ");
            }
        }
    });

    $('input.autocomplete').autocomplete({
        data: {
            "Loyola Marymount University": null,
            "UCLA": null,
            "Berkeley": 'http://placehold.it/250x250',
            "Donglehorn University": null
        }
    });

    $("main").on('click', '#add-listing', function (e) {
        e.preventDefault();
        var itemTitle = $("#item-post-title").val();
        var itemDescription = $("#item-post-description").val();
        var itemTags = $("#item-post-tags").val();
        var itemPrice = $("#item-post-price").val();
        var itemHub = $("#autocomplete-input").val();
        var itemUid = auth.currentUser.uid;
        console.log(itemUid);
    });

    $('#back-to-preview').on('click', function (e) {
        $('#basic-info-tab').removeClass('disabled');
        $('ul.tabs').tabs('select_tab', 'basic-info');
        $('#preview-submit-tab').addClass('disabled');

        $('#preview-title').empty();
        $('#preview-price').empty().text("$");
        $('#preview-description').empty();
        $('#preview-tags').empty().append(
            $('').attr('id', 'preview-tag-blurb').text('Tags: ')
        );
        $('#carousel-wrapper').empty();
    });

    //add listing
    $("main").on('click', '#add-listing', function (e) {
        if (itemTitle && itemDescription && itemTags && itemPrice) {
            addListing(itemTitle, itemDescription, itemTags, itemPrice, itemHub, itemUid);
            $("main").text("Item has been Posted :)");
        } else {
            alert("please enter a username and comment");
        }
    });

    var itemTagRef = $('#itemTags');
    if (itemTagRef.length > 0) {
        itemTagRef.textext({plugins : 'tags autocomplete'})
            .bind('getSuggestions', function(e, data){
                var list = [
                        'Table',
                        'Desk',
                        'Computer',
                        'Electronics',
                        'iPhone',
                        'Cell Phone',
                        'Apple',
                        'Macbook',
                        'Chair',
                        'Leather',
                        'Clothing',
                        'Bedroom',
                        'Bathroom',
                        'Couch',
                        'Kitchen',
                        'Living Room',
                        'Dinner Table'
                    ],
                    textext = $(e.target).textext()[0],
                    query = (data ? data.query : '') || '';

                $(this).trigger('setSuggestions',{
                    result : textext.itemManager().filter(list, query) }
                );
        });
    }

    var hubRef = $('#hub-selection');
    if (hubRef.length > 0) {
        hubRef.textext({plugins : 'tags autocomplete'})
                .bind('getSuggestions', function(e, data){
                    var list = [
                            'Loyola Marymount University',
                            'UCLA'
                        ],
                        textext = $(e.target).textext()[0],
                        query = (data ? data.query : '') || '';

                    $(this).trigger('setSuggestions',{
                        result : textext.itemManager().filter(list, query) }
                    );
        });
    };

    /**
        drophub to add images by clicking
        or by dragging and dropping
    **/
    var reader;
    var drop;

    $('#dropMain, .drop').on({
        'click': function(e) {
            $('#fileBox').click();
            drop = this;
            reader = new FileReader();
        },
        'dragover dragenter': function(e) {
            e.preventDefault();
            e.stopPropagation();
        },
        'drop': function(e) {
            var dropArea = this;
            var dataTransfer =  e.originalEvent.dataTransfer;
            if (dataTransfer && dataTransfer.files.length) {
                e.preventDefault();
                e.stopPropagation();
                $.each(dataTransfer.files, function(i, file) {
                    reader = new FileReader();
                    reader.onload = $.proxy(function(file, $fileList, event) {
                        var img = file.type.match('image.*')
                            ? $("").attr('src', event.target.result) : "";
                        $fileList.empty().append(img);
                    }, this, file, $(dropArea));
                    reader.readAsDataURL(file);
                });
            }
        }
    });

    $("#fileBox").change(function() {
        if (this.files && this.files[0]) {
            reader.onload = function (e) {
                $(drop).empty().append($("").attr("src", reader.result));
                $(drop).css('background-color', '#fff');
            }
            reader.readAsDataURL(this.files[0]);
        }
    });

    $('#show-hub-link').on('click', function () {
        $('#hub-popup').fadeIn();
    });

    $(document).mouseup(function (e) {
        var popup = $('#hub-popup');
        if (popup.is(e.target)) {
            popup.fadeOut();
        }
    });

    $('#submit-hub').on('click', function() {
        let hubs = $('#hub-selection').textext()[0].tags()._formData;

        if (hubs.length > 0 ) {
            $("#current-hubs-signed-in").empty();
            for (var i = 0; i < hubs.length; i += 1) {
                $('#current-hubs-signed-in').append(
                    $('').addClass('hub-card z-depth-1').append(hubs[i])

                );
                $("#current-hubs-signed-in").append(" ");
            }
            $('#hub-popup').fadeOut();
        }
    });

    $('#cancel-hub').on('click', function() {
        $('#hub-popup').fadeOut();
    });
});<commit_msg>removing code added from older commits<commit_after>$(function() {

    var addListing = require('./firebase.js')['addListing'];
    var auth = require('./firebase.js')['auth'];
    var itemTitle;
    var itemDescription;
    var itemTags;
    var itemPrice;
    var itemHub;
    var itemUid;
    var itemImages;

    var checkBasicItems = function() {
        var checksPassed = true;
        itemUid = auth.currentUser.uid;
        itemTitle = $("#item-post-title").val();
        itemDescription = $("#item-post-description").val();
        itemTags = $('#itemTags').textext()[0].tags()._formData;
        itemPrice = $("#item-post-price").val();
        itemImages = [];
        $('#dropzone').find('img').each(function(index) {
            itemImages.push($(this).attr('src'));
        });

        // itemHub needs to be changed
        itemHub = "hardcodedForNow";

        if (!/^[\w\s]{5,30}$/.test(itemTitle)) {
            Materialize.toast('Title must be between 5 and 30 characters', 3000, 'rounded');
            checksPassed = false;
        } else if (!/^[\w\s\.]+$/.test(itemDescription) || itemDescription.length < 5) {
            Materialize.toast('Description can only contain letters and numbers', 3000, 'rounded');
            checksPassed = false;
        } else if(!itemPrice.match(/^[0-9]+([.][0-9]{0,2})?$/) || itemPrice < 0.01 || itemPrice > 3000) {
            Materialize.toast('only enter numbers, and an optional decimal', 3000, 'rounded');
            checksPassed = false;
        } else if(!/^[a-zA-Z\s]+$/.test(itemHub)) {
            checksPassed = false;
        } else if (itemTags.length < 2 || itemTags.length > 5) {
            Materialize.toast('Please enter 2 to 5 tags', 3000, 'rounded');
            checksPassed = false;
        } else if (itemImages.length < 1) {
            Materialize.toast('Please add at least one image', 3000, 'rounded');
            checksPassed = false;
        } else {
            for (var i = 0; i < itemTags.length; i += 1) {
                if (!/^[a-zA-Z\s]+$/.test(itemTags[i]) || itemTags[i].length > 15) {
                    Materialize.toast('tags can only contain letters and spaces, up to 15 characters', 3000, 'rounded');
                    checksPassed = false;
                }
            }
        }
        return checksPassed;
    };

    var addImagesToSlider = function() {
        let imageCount = ['one', 'two', 'three', 'four'];
        $('#carousel-wrapper').append($('

').addClass('carousel carousel-slider'));

        for (var i = 0; i < itemImages.length; i += 1) {
            $('.carousel-slider').append(
                $('').addClass('carousel-item').attr('href', '#' + imageCount[i] + '!').append(
                    $('').attr('src', itemImages[i])
                )
            );
        }
        $('.carousel.carousel-slider').carousel({full_width: true, indicators: true});
    };

    $("#post-preview").click(function () {
        if (checkBasicItems()) {
            addImagesToSlider();

            $('#preview-submit-tab').removeClass('disabled');
            $('ul.tabs').tabs('select_tab', 'preview-submit');
            $('#basic-info-tab').addClass('disabled');

            $('#preview-title').append(itemTitle);
            $('#preview-price').append(itemPrice);
            $('#preview-description').append(itemDescription);

            for (tag of itemTags) {
                $('#preview-tags').append(
                    $('').attr('href', '#').addClass('hub-card').text(tag)
                );
                $('#preview-tags').append(" ");
            }
        }
    });

    $('#back-to-preview').on('click', function (e) {
        $('#basic-info-tab').removeClass('disabled');
        $('ul.tabs').tabs('select_tab', 'basic-info');
        $('#preview-submit-tab').addClass('disabled');

        $('#preview-title').empty();
        $('#preview-price').empty().text("$");
        $('#preview-description').empty();
        $('#preview-tags').empty().append(
            $('').attr('id', 'preview-tag-blurb').text('Tags: ')
        );
        $('#carousel-wrapper').empty();
    });

    //add listing
    $("main").on('click', '#add-listing', function (e) {
        if (itemTitle && itemDescription && itemTags && itemPrice) {
            addListing(itemTitle, itemDescription, itemTags, itemPrice, itemHub, itemUid);
            $("main").text("Item has been Posted :)");
        } else {
            alert("please enter a username and comment");
        }
    });

    var itemTagRef = $('#itemTags');
    if (itemTagRef.length > 0) {
        itemTagRef.textext({plugins : 'tags autocomplete'})
            .bind('getSuggestions', function(e, data){
                var list = [
                        'Table',
                        'Desk',
                        'Computer',
                        'Electronics',
                        'iPhone',
                        'Cell Phone',
                        'Apple',
                        'Macbook',
                        'Chair',
                        'Leather',
                        'Clothing',
                        'Bedroom',
                        'Bathroom',
                        'Couch',
                        'Kitchen',
                        'Living Room',
                        'Dinner Table'
                    ],
                    textext = $(e.target).textext()[0],
                    query = (data ? data.query : '') || '';

                $(this).trigger('setSuggestions',{
                    result : textext.itemManager().filter(list, query) }
                );
        });
    }

    var hubRef = $('#hub-selection');
    if (hubRef.length > 0) {
        hubRef.textext({plugins : 'tags autocomplete'})
                .bind('getSuggestions', function(e, data){
                    var list = [
                            'Loyola Marymount University',
                            'UCLA'
                        ],
                        textext = $(e.target).textext()[0],
                        query = (data ? data.query : '') || '';

                    $(this).trigger('setSuggestions',{
                        result : textext.itemManager().filter(list, query) }
                    );
        });
    };

    /**
        drophub to add images by clicking
        or by dragging and dropping
    **/
    var reader;
    var drop;

    $('#dropMain, .drop').on({
        'click': function(e) {
            $('#fileBox').click();
            drop = this;
            reader = new FileReader();
        },
        'dragover dragenter': function(e) {
            e.preventDefault();
            e.stopPropagation();
        },
        'drop': function(e) {
            var dropArea = this;
            var dataTransfer =  e.originalEvent.dataTransfer;
            if (dataTransfer && dataTransfer.files.length) {
                e.preventDefault();
                e.stopPropagation();
                $.each(dataTransfer.files, function(i, file) {
                    reader = new FileReader();
                    reader.onload = $.proxy(function(file, $fileList, event) {
                        var img = file.type.match('image.*')
                            ? $("").attr('src', event.target.result) : "";
                        $fileList.empty().append(img);
                    }, this, file, $(dropArea));
                    reader.readAsDataURL(file);
                });
            }
        }
    });

    $("#fileBox").change(function() {
        if (this.files && this.files[0]) {
            reader.onload = function (e) {
                $(drop).empty().append($("").attr("src", reader.result));
                $(drop).css('background-color', '#fff');
            }
            reader.readAsDataURL(this.files[0]);
        }
    });

    $('#show-hub-link').on('click', function () {
        $('#hub-popup').fadeIn();
    });

    $(document).mouseup(function (e) {
        var popup = $('#hub-popup');
        if (popup.is(e.target)) {
            popup.fadeOut();
        }
    });

    $('#submit-hub').on('click', function() {
        let hubs = $('#hub-selection').textext()[0].tags()._formData;

        if (hubs.length > 0 ) {
            $("#current-hubs-signed-in").empty();
            for (var i = 0; i < hubs.length; i += 1) {
                $('#current-hubs-signed-in').append(
                    $('').addClass('hub-card z-depth-1').append(hubs[i])

                );
                $("#current-hubs-signed-in").append(" ");
            }
            $('#hub-popup').fadeOut();
        }
    });

    $('#cancel-hub').on('click', function() {
        $('#hub-popup').fadeOut();
    });
});<|endoftext|>


<commit_before>/* eslint no-var: 0 */
var path = require('path');
var webpack = require('webpack');

// In webpack.config.js
module.exports = {
  devtool: 'source-map',
  entry: path.resolve(__dirname, 'src', 'app.js'),
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
      '__DEVTOOLS__': false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
      },
    }),
    new webpack.ProvidePlugin({
      'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    }),
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
      },
    ],
  },
  output: {filename: 'react-bundle.js', path: path.join(__dirname,'dist', 'static','js')},
};
<commit_msg>Fixed build by ignoring node_modules<commit_after>/* eslint no-var: 0 */
var path = require('path');
var webpack = require('webpack');

// In webpack.config.js
module.exports = {
  devtool: 'source-map',
  entry: path.resolve(__dirname, 'src', 'app.js'),
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
      '__DEVTOOLS__': false,
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false,
      },
    }),
    new webpack.ProvidePlugin({
      'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
    }),
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        include: path.join(__dirname, 'src'),
      },
    ],
  },
  output: {filename: 'react-bundle.js', path: path.join(__dirname,'dist', 'static','js')},
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const glob = require('glob');

const nodeExternals = require('webpack-node-externals');

module.exports = {
    target: 'node',
    entry: glob.sync('./test/**/*.js'),
    output: {
        path: path.resolve(__dirname, '_build'),
        filename: 'tests.js'
    },
    externals: [nodeExternals()],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: 'babel-loader'
            }
        ]
    }
};
<commit_msg>fix: Enable babel caching for webpack test conf<commit_after>'use strict';

const path = require('path');
const glob = require('glob');

const nodeExternals = require('webpack-node-externals');

module.exports = {
    target: 'node',
    entry: glob.sync('./test/**/*.js'),
    output: {
        path: path.resolve(__dirname, '_build'),
        filename: 'tests.js'
    },
    externals: [nodeExternals()],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                use: {
                    loader: 'babel-loader',
                    options: { cacheDirectory: true }
                }
            }
        ]
    }
};
<|endoftext|>


<commit_before>/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const merge = require('webpack-merge');
const CompressionPlugin = require('compression-webpack-plugin');
const commonConfig = require('./webpack.common.config');

module.exports = merge(commonConfig, {
  mode: 'production',
  devtool: 'source-map',

  entry: './src/client/index.js',

  output: {
    path: path.join(__dirname, 'dist/'),
    filename: '[name].[chunkhash].js',
  },

  optimization: {
    runtimeChunk: true,
    splitChunks: {
      chunks: 'all',
    },
  },

  plugins: [
    new CompressionPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.js$/,
      minRatio: 0.8,
    }),
  ],
});
<commit_msg>fix compression plugin<commit_after>/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const merge = require('webpack-merge');
const CompressionPlugin = require('compression-webpack-plugin');
const commonConfig = require('./webpack.common.config');

module.exports = merge(commonConfig, {
  mode: 'production',
  devtool: 'source-map',

  entry: './src/client/index.js',

  output: {
    path: path.join(__dirname, 'dist/'),
    filename: '[name].[chunkhash].js',
  },

  optimization: {
    runtimeChunk: true,
    splitChunks: {
      chunks: 'all',
    },
  },

  plugins: [
    new CompressionPlugin(),
  ],
});
<|endoftext|>


<commit_before>const webpack = require('webpack');
const path = require('path');

module.exports = {
  entry: './src/index.js',
  devtool: 'source-map',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'sync-client.min.js',
    libraryTarget: 'commonjs2',
    library: 'sync-client.min.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: ['transform-runtime'],
          presets: [
            ['es2015', { modules: false }],
          ],
        },
      },
    ],
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
      output: {
        comments: false,
      },
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') },
    }),
  ],
  resolve: {
    extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
    ],
  },
};
<commit_msg>Add source map to uglifyjs<commit_after>const webpack = require('webpack');
const path = require('path');

module.exports = {
  entry: './src/index.js',
  devtool: 'source-map',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'sync-client.min.js',
    libraryTarget: 'commonjs2',
    library: 'sync-client.min.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: ['transform-runtime'],
          presets: [
            ['es2015', { modules: false }],
          ],
        },
      },
    ],
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        screw_ie8: true,
        conditionals: true,
        unused: true,
        comparisons: true,
        sequences: true,
        dead_code: true,
        evaluate: true,
        if_return: true,
        join_vars: true,
      },
      output: {
        comments: false,
      },
      sourceMap: true,
    }),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify('production') },
    }),
  ],
  resolve: {
    extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
    ],
  },
};
<|endoftext|>


<commit_before>let path = require("path");
let ExtractTextPlugin = require("extract-text-webpack-plugin");

//Compile the plugin to extract the compiled css text into an external file
let extractSass = new ExtractTextPlugin({ filename:"bundle.test.css" });

//Export the webpack configuration
module.exports = {
    "entry": "./test/index.js",
    "output": {
        "path": path.resolve(__dirname, "./test/"),
        "filename": "bundle.test.js"
    },
    "resolve": {
        "modules": [
            path.resolve(__dirname, "./bower_components/"),
            path.resolve(__dirname, "./node_modules/")
        ],
    },
    "module": {
        "rules": [
            {
                "test": /\.scss$/,
                "use": extractSass.extract({
                    "fallback": "style-loader",
                    "use": [
                        {"loader": "css-loader"},
                        {
                            "loader": "sass-loader",
                            "options": {"includePaths": ["./bower_components/"]}
                        }
                    ]
                })
            }
        ]
    },
    "plugins": [extractSass]
};
<commit_msg>Changed plugin to extract css content. Added mode option<commit_after>let path = require("path");
let MiniCssExtract = require("mini-css-extract-plugin");

//Export the webpack configuration
module.exports = {
    "entry": "./test/index.js",
    "mode": "development",
    "output": {
        "path": path.resolve(__dirname, "./test/"),
        "filename": "bundle.test.js"
    },
    "resolve": {
        "modules": [
            path.resolve(__dirname, "./bower_components/"),
            path.resolve(__dirname, "./node_modules/")
        ],
    },
    "module": {
        "rules": [
            {
                "test": /\.scss$/,
                "use": [
                    MiniCssExtract.loader,
                    {loader: "css-loader"},
                    {
                        "loader": "sass-loader",
                        "options": {"includePaths": ["./node_modules/"]}
                    }
                ]
            }
        ]
    },
    "plugins": [
        new MiniCssExtract({filename: "bundle.test.css"})
    ]
};
<|endoftext|>


<commit_before>'use strict';

const define = require('./define');
const { resolve } = require('path');

const vendors = [
    // 'core-js/es6/map',
    // 'core-js/es6/set',
    'react',
    'react-dom',
    'react-router-dom',
    'axios',
    'store',
    // 'mobx',
    // 'mobx-react',
    // 'mobx-state-tree',
];

const index = [
    ...define.rs_development ? [
        '@babel/polyfill',
        `webpack-dev-server/client?http://${define.rs_host}:${define.rs_port}`,
        'webpack/hot/only-dev-server',
    ] : [],
    resolve(define.rs_root, 'index'),
];

const entryPoint = {
    vendors,
    index
}

module.exports.config = entryPoint;
<commit_msg>update<commit_after>'use strict';

const define = require('./define');
const { resolve } = require('path');

const vendors = [
    // 'core-js/es6/map',
    // 'core-js/es6/set',
    'react',
    'react-dom',
    'react-router-dom',
    'axios',
    'store2',
    // 'mobx',
    // 'mobx-react',
    // 'mobx-state-tree',
];

const index = [
    ...define.rs_development ? [
        '@babel/polyfill',
        `webpack-dev-server/client?http://${define.rs_host}:${define.rs_port}`,
        'webpack/hot/only-dev-server',
    ] : [],
    resolve(define.rs_root, 'index'),
];

const entryPoint = {
    vendors,
    index
}

module.exports.config = entryPoint;
<|endoftext|>


<commit_before>'use strict';

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./common.js');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = merge(common, {
    mode: 'production',
    output: {
        filename: '[name].min.js',
    },
    module: {
        rules: [
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                url: false,
                                minimize: true,
                                sourceMap: false,
                            },
                        },
                        {
                            loader: 'less-loader',
                            options: {
                                sourceMap: false,
                            },
                        },
                    ],
                }),
            },
        ],
    },
    plugins: [new UglifyJSPlugin(), new LodashModuleReplacementPlugin()],
});
<commit_msg>production 모드에서 min.js .js 파일 둘다 만들도록 설정 변경<commit_after>'use strict';

const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const common = require('./common.js');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = merge(common, {
    entry: {
        'entry.min': './src/entry.js',
    },
    mode: 'production',
    output: {
        filename: '[name].js',
    },
    module: {
        rules: [
            {
                test: /\.less$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                url: false,
                                minimize: true,
                                sourceMap: false,
                            },
                        },
                        {
                            loader: 'less-loader',
                            options: {
                                sourceMap: false,
                            },
                        },
                    ],
                }),
            },
        ],
    },
    plugins: [new UglifyJSPlugin({
        include: /\.min\.js$/,
    }), new LodashModuleReplacementPlugin()],
});
<|endoftext|>


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

// http://stackoverflow.com/a/4234006
$.ajaxSetup({beforeSend: function(xhr) {
  if (xhr.overrideMimeType)
  {
    xhr.overrideMimeType('application/json');
  }
}
});

function getSelectedType() {
  return document.getElementById('select-type').value;
}

var dataDir = 'data/';
var firstTooltipShown = false;

var map = new ol.Map({
  target: 'map',
  interactions: ol.interaction.defaults({keyboard:false}),  // disable because this moves the map when using the arrow keys to change the slider
});

var view = new ol.View({
  center: [0, 0],
  zoom: 3,
  projection: 'EPSG:3857'
});

map.setView(view);

var osmSource = new ol.source.OSM('OpenCycleMap');
osmSource.setUrl('http://a.tile.opencyclemap.org/transport/{z}/{x}/{y}.png');
//osmSource.setUrl('http://a.tile.openstreetmap.org/{z}/{x}/{y}.png');
//osmSource.setUrl('https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png');
//osmSource.setUrl('http://a.tile.stamen.com/toner/{z}/{x}/{y}.png');

var osmLayer = new ol.layer.Tile({source: osmSource});
map.addLayer(osmLayer);

var lon = 0.0;
var lat = 10.0;
view.setCenter(ol.proj.fromLonLat([lon, lat]));

map.addControl(new ol.control.FullScreen());
//map.addControl(new ol.control.ZoomSlider());

map.on('pointermove', function(evt) {
  var info = $('#info');

  function displayFeatureInfo(pixel) {
    info.css({
      left: (pixel[0] + 10) + 'px',
      top: (pixel[1] - 50) + 'px',
    });

    var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
      return feature;
    });

    if (feature) {
      var title = feature.get('title');
      if (title) {
        firstTooltipShown = true;
        info.text(title);
        info.show();
      } else if (!firstTooltipShown) {
        info.text('Tip: hover over lines to show their value.');
        info.show();
      } else {
        info.hide();
      }
    } else {
      info.hide();
    }
  }

  if (evt.dragging) {
    info.hide();
    return;
  }
  displayFeatureInfo(map.getEventPixel(evt.originalEvent));
});

var contourPlot = (function() {
  var plotTypesMonthsLayers = {};
  var plotTypesMonthsImages = {};

  function hideAllContours() {
    var type;
    var month;
    for (type in plotTypesMonthsLayers) {
      for (month in plotTypesMonthsLayers[type]) {
        plotTypesMonthsLayers[type][month].setVisible(false);
      }
    }

    for (type in plotTypesMonthsImages) {
      for (month in plotTypesMonthsImages[type]) {
        plotTypesMonthsImages[type][month].setVisible(false);
      }
    }
  }

  function lineStyleFunction(feature, resolution) {
    var scaleForPixelDensity = 1.0; //dpi_x/96.0;
    var lineWidth = feature.get('stroke-width') * scaleForPixelDensity * Math.pow(map.getView().getZoom()/2.0, 1.3);
    var lineStyle = new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: feature.get('stroke'),
        width: lineWidth,
        opacity: 0.0 //feature.get('opacity')
        //            width: map.getView().getZoom(),
      })
    });
    return lineStyle;
  }

  function createContoursLayer(dataType, monthNr) {
    var contourLayer = new ol.layer.VectorTile({
      source: new ol.source.VectorTile({
        url: dataDir + dataType + '/' + monthNr + '/tiles/{z}/{x}/{y}.geojson',
        format: new ol.format.GeoJSON(),
        projection: 'EPSG:3857',
        tileGrid: ol.tilegrid.createXYZ({
          maxZoom: 5,
          minZoom: 1,
          tileSize: [256, 256]
        }),
      }),
      style: lineStyleFunction
    });

    contourLayer.setZIndex(99);
    map.addLayer(contourLayer);
    return contourLayer;
  }

  function getImageOpacity() {
    var zoomedOut = 0.7;
    var zoomLevelToStart = 5;
    var zoom = view.getZoom();
    if (zoom < zoomLevelToStart) {
      return zoomedOut;
    }
    return zoomedOut - (view.getZoom()-zoomLevelToStart) / 5.0;
  }

  function createImageLayer(dataType, monthNr) {
    //    var extent = ol.extent.applyTransform([-180, -85, 180, 85], ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
    //    console.log(extent);
    return new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: dataDir + dataType + '/' + monthNr + '/maptiles/{z}/{x}/{-y}.png',
        projection: 'EPSG:3857',
        wrapX: false,
        tileGrid: ol.tilegrid.createXYZ({
          maxZoom: 5,
          minZoom: 1,
          tileSize: [256, 256]
        }),
      }),
      opacity: getImageOpacity()
    });
  }

  // increase contour line width when zooming
  map.getView().on('change:resolution', function(evt) {
    for (var type in plotTypesMonthsLayers) {
      for (var month in plotTypesMonthsLayers[type]) {
        plotTypesMonthsLayers[type][month].setStyle(lineStyleFunction);
      }
    }
  });

  return Object.freeze({
    showOrCreateContour: function(monthNr) {
      hideAllContours();
      var selectedType = getSelectedType();
      if ( !this.plotExists(selectedType, monthNr) ) {
        this.addContours(selectedType, monthNr);
      }
      else {
        var monthLayer = plotTypesMonthsLayers[selectedType][monthNr];
        var monthImage = plotTypesMonthsImages[selectedType][monthNr];
        monthImage.setVisible(true);
        monthLayer.setVisible(true);
      }
    },
    addContours: function(dataType, monthNr) {
      var contourLayer = createContoursLayer(dataType, monthNr);
      if ( !(dataType in plotTypesMonthsLayers)) {
        plotTypesMonthsLayers[dataType] = {};
        plotTypesMonthsImages[dataType] = {};
      }
      var imageLayer = createImageLayer(dataType, monthNr);
      map.addLayer(imageLayer);
      plotTypesMonthsImages[dataType][monthNr] = imageLayer;
      plotTypesMonthsLayers[dataType][monthNr] = contourLayer;
    },
    plotExists: function(typeName, monthNr) {
      return typeName in plotTypesMonthsLayers && plotTypesMonthsLayers[typeName].hasOwnProperty(monthNr);
    },
    updateOnZoom: function() {
      for (var type in plotTypesMonthsImages) {
        for (var month in plotTypesMonthsImages[type]) {
          plotTypesMonthsImages[type][month].setOpacity( getImageOpacity() );
        }
      }
    }
  });
})();

var colorbarLegend = (function() {
  return Object.freeze({
    update: function(dataType, monthNr) {
      var colorBarImage = document.getElementById('colorbar-legend-container');
      var imageUrl = dataDir + dataType + '/' + monthNr + '_colorbar.png';
      colorBarImage.style.backgroundImage = 'url(' + imageUrl + ')';
    }
  });
})();

var slider = (function() {
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan'];

  function slide(event, ui) {
    var monthNr = ui.value + 1;
    if (monthNr == 13) {
      $('#month-slider').slider('value', 0);
      monthNr = 1;
    }

    contourPlot.showOrCreateContour(monthNr);
    colorbarLegend.update(getSelectedType(), monthNr);
  }

  function update() {
    var monthNr = $('#month-slider').slider('value') + 1;
    if (monthNr == 13) {
      $('#month-slider').slider('value', 0);
      monthNr = 1;
    }

    contourPlot.showOrCreateContour(monthNr);
    colorbarLegend.update(getSelectedType(), monthNr);
  }

  function init() {
    $('#month-slider').slider({
      orientation: 'horizontal',
      range: 'min',
      min: 0,
      max: 12,
      value: 0,
      slide: slide,
      change: update
    })
    .slider('pips', {
      rest: 'label',
      labels: months
    });
    //    .slider('float');
  }

  return Object.freeze({
    update: update,
    init: init
  });
})();

map.on('moveend', function() {
  contourPlot.updateOnZoom();
});

var animationID = 0;

$(document).ready( function(){
  $('#info').hide();

  slider.init();

  function toggleAnimate() {
    function playAnimation() {
      var monthNr = $('#month-slider').slider('value');
      $('#month-slider').slider('value', monthNr+1);
    }

    var playButton = document.getElementById('animate-button');
    var selectedType = getSelectedType();
    if (playButton.innerHTML == 'Animate') {
      for (var i = 1; i < 13; ++i) {
        if ( !contourPlot.plotExists(selectedType, i) ) {
          contourPlot.addContours(selectedType, i);
        }
      }
      playButton.innerHTML = 'Stop';
      animationID = window.setInterval(playAnimation, 800);
    }
    else {
      window.clearInterval(animationID);
      playButton.innerHTML = 'Animate';
    }
  }

  document.getElementById('animate-button').onclick = toggleAnimate;

  document.getElementById('select-type').onchange = function() {
    var selection = getSelectedType();
    slider.update();
  };
});

window.onload = function() {
  var initialDataType = 'precipitation';
  var initialMonth = 1;

  function selectDataType(valueToSelect) {
    var element = document.getElementById('select-type');
    element.value = valueToSelect;
  }

  function setSliderValue(monthNr) {
    if (monthNr >= 13) {
      $('#month-slider').slider('value', 0);
    } else {
      $('#month-slider').slider('value', monthNr-1);
    }
  }

  selectDataType(initialDataType);
  setSliderValue(initialMonth);
  //    addContours(initialDataType, initialMonth);  // initial contour of January
};
<commit_msg>refactor climate map into function<commit_after>(function () {
   'use strict';
}());

// http://stackoverflow.com/a/4234006
$.ajaxSetup({beforeSend: function(xhr) {
  if (xhr.overrideMimeType)
  {
    xhr.overrideMimeType('application/json');
  }
}
});

function getSelectedType() {
  return document.getElementById('select-type').value;
}

var dataDir = 'data/';
var firstTooltipShown = false;

var climateMap = (function() {
  var lon = 0.0;
  var lat = 10.0;

  var map = new ol.Map({
    target: 'map',
    interactions: ol.interaction.defaults({keyboard:false}),  // disable because this moves the map when using the arrow keys to change the slider
  });

  var view = new ol.View({
    center: [0, 0],
    zoom: 3,
    projection: 'EPSG:3857'
  });

  view.setCenter(ol.proj.fromLonLat([lon, lat]));
  map.setView(view);

  var osmSource = new ol.source.OSM('OpenCycleMap');
  osmSource.setUrl('http://a.tile.opencyclemap.org/transport/{z}/{x}/{y}.png');
  //osmSource.setUrl('http://a.tile.openstreetmap.org/{z}/{x}/{y}.png');
  //osmSource.setUrl('https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png');
  //osmSource.setUrl('http://a.tile.stamen.com/toner/{z}/{x}/{y}.png');

  var osmLayer = new ol.layer.Tile({source: osmSource});
  map.addLayer(osmLayer);
  map.addControl(new ol.control.FullScreen());
  //map.addControl(new ol.control.ZoomSlider());

  return map;
})();

var contourPlot = (function() {
  var plotTypesMonthsLayers = {};
  var plotTypesMonthsImages = {};

  function hideAllContours() {
    var type;
    var month;
    for (type in plotTypesMonthsLayers) {
      for (month in plotTypesMonthsLayers[type]) {
        plotTypesMonthsLayers[type][month].setVisible(false);
      }
    }

    for (type in plotTypesMonthsImages) {
      for (month in plotTypesMonthsImages[type]) {
        plotTypesMonthsImages[type][month].setVisible(false);
      }
    }
  }

  function lineStyleFunction(feature, resolution) {
    var scaleForPixelDensity = 1.0; //dpi_x/96.0;
    var lineWidth = feature.get('stroke-width') * scaleForPixelDensity * Math.pow(climateMap.getView().getZoom()/2.0, 1.3);
    var lineStyle = new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: feature.get('stroke'),
        width: lineWidth,
        opacity: 0.0 //feature.get('opacity')
        //            width: climateMap.getView().getZoom(),
      })
    });
    return lineStyle;
  }

  function createContoursLayer(dataType, monthNr) {
    var contourLayer = new ol.layer.VectorTile({
      source: new ol.source.VectorTile({
        url: dataDir + dataType + '/' + monthNr + '/tiles/{z}/{x}/{y}.geojson',
        format: new ol.format.GeoJSON(),
        projection: 'EPSG:3857',
        tileGrid: ol.tilegrid.createXYZ({
          maxZoom: 5,
          minZoom: 1,
          tileSize: [256, 256]
        }),
      }),
      style: lineStyleFunction
    });

    contourLayer.setZIndex(99);
    climateMap.addLayer(contourLayer);
    return contourLayer;
  }

  function getImageOpacity() {
    var zoomedOut = 0.7;
    var zoomLevelToStart = 5;
    var zoom = climateMap.getView().getZoom();
    if (zoom < zoomLevelToStart) {
      return zoomedOut;
    }
    return zoomedOut - (climateMap.getView().getZoom()-zoomLevelToStart) / 5.0;
  }

  function createImageLayer(dataType, monthNr) {
    //    var extent = ol.extent.applyTransform([-180, -85, 180, 85], ol.proj.getTransform('EPSG:4326', 'EPSG:3857'));
    //    console.log(extent);
    return new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: dataDir + dataType + '/' + monthNr + '/maptiles/{z}/{x}/{-y}.png',
        projection: 'EPSG:3857',
        wrapX: false,
        tileGrid: ol.tilegrid.createXYZ({
          maxZoom: 5,
          minZoom: 1,
          tileSize: [256, 256]
        }),
      }),
      opacity: getImageOpacity()
    });
  }

  // increase contour line width when zooming
  climateMap.getView().on('change:resolution', function(evt) {
    for (var type in plotTypesMonthsLayers) {
      for (var month in plotTypesMonthsLayers[type]) {
        plotTypesMonthsLayers[type][month].setStyle(lineStyleFunction);
      }
    }
  });

  return Object.freeze({
    showOrCreateContour: function(monthNr) {
      hideAllContours();
      var selectedType = getSelectedType();
      if ( !this.plotExists(selectedType, monthNr) ) {
        this.addContours(selectedType, monthNr);
      }
      else {
        var monthImage = plotTypesMonthsImages[selectedType][monthNr];
        var monthLayer = plotTypesMonthsLayers[selectedType][monthNr];
        monthImage.setVisible(true);
        monthLayer.setVisible(true);
      }
    },
    addContours: function(dataType, monthNr) {
      var contourLayer = createContoursLayer(dataType, monthNr);
      if ( !(dataType in plotTypesMonthsLayers)) {
        plotTypesMonthsLayers[dataType] = {};
        plotTypesMonthsImages[dataType] = {};
      }
      var imageLayer = createImageLayer(dataType, monthNr);
      climateMap.addLayer(imageLayer);
      plotTypesMonthsImages[dataType][monthNr] = imageLayer;
      plotTypesMonthsLayers[dataType][monthNr] = contourLayer;
    },
    plotExists: function(typeName, monthNr) {
      return typeName in plotTypesMonthsLayers && plotTypesMonthsLayers[typeName].hasOwnProperty(monthNr);
    },
    updateOnZoom: function() {
      for (var type in plotTypesMonthsImages) {
        for (var month in plotTypesMonthsImages[type]) {
          plotTypesMonthsImages[type][month].setOpacity( getImageOpacity() );
        }
      }
    }
  });
})();

var colorbarLegend = (function() {
  return Object.freeze({
    update: function(dataType, monthNr) {
      var colorBarImage = document.getElementById('colorbar-legend-container');
      var imageUrl = dataDir + dataType + '/' + monthNr + '_colorbar.png';
      colorBarImage.style.backgroundImage = 'url(' + imageUrl + ')';
    }
  });
})();

var slider = (function() {
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan'];

  function slide(event, ui) {
    var monthNr = ui.value + 1;
    if (monthNr == 13) {
      $('#month-slider').slider('value', 0);
      monthNr = 1;
    }

    contourPlot.showOrCreateContour(monthNr);
    colorbarLegend.update(getSelectedType(), monthNr);
  }

  function update() {
    var monthNr = $('#month-slider').slider('value') + 1;
    if (monthNr == 13) {
      $('#month-slider').slider('value', 0);
      monthNr = 1;
    }

    contourPlot.showOrCreateContour(monthNr);
    colorbarLegend.update(getSelectedType(), monthNr);
  }

  function init() {
    $('#month-slider').slider({
      orientation: 'horizontal',
      range: 'min',
      min: 0,
      max: 12,
      value: 0,
      slide: slide,
      change: update
    })
    .slider('pips', {
      rest: 'label',
      labels: months
    });
    //    .slider('float');
  }

  return Object.freeze({
    update: update,
    init: init
  });
})();

var animationID = 0;

$(document).ready( function(){
  $('#info').hide();

  slider.init();

  function toggleAnimate() {
    function playAnimation() {
      var monthNr = $('#month-slider').slider('value');
      $('#month-slider').slider('value', monthNr+1);
    }

    var playButton = document.getElementById('animate-button');
    var selectedType = getSelectedType();
    if (playButton.innerHTML == 'Animate') {
      for (var i = 1; i < 13; ++i) {
        if ( !contourPlot.plotExists(selectedType, i) ) {
          contourPlot.addContours(selectedType, i);
        }
      }
      playButton.innerHTML = 'Stop';
      animationID = window.setInterval(playAnimation, 800);
    }
    else {
      window.clearInterval(animationID);
      playButton.innerHTML = 'Animate';
    }
  }

  document.getElementById('animate-button').onclick = toggleAnimate;

  document.getElementById('select-type').onchange = function() {
    var selection = getSelectedType();
    slider.update();
  };

  climateMap.on('moveend', function() {
    contourPlot.updateOnZoom();
  });

  climateMap.on('pointermove', function(evt) {
    var info = $('#info');

    function displayFeatureInfo(pixel) {
      info.css({
        left: (pixel[0] + 10) + 'px',
        top: (pixel[1] - 50) + 'px',
      });

      var feature = climateMap.forEachFeatureAtPixel(pixel, function(feature) {
        return feature;
      });

      if (feature) {
        var title = feature.get('title');
        if (title) {
          firstTooltipShown = true;
          info.text(title);
          info.show();
        } else if (!firstTooltipShown) {
          info.text('Tip: hover over lines to show their value.');
          info.show();
        } else {
          info.hide();
        }
      } else {
        info.hide();
      }
    }

    if (evt.dragging) {
      info.hide();
      return;
    }
    displayFeatureInfo(climateMap.getEventPixel(evt.originalEvent));
  });
});

window.onload = function() {
  var initialDataType = 'precipitation';
  var initialMonth = 1;

  function selectDataType(valueToSelect) {
    var element = document.getElementById('select-type');
    element.value = valueToSelect;
  }

  function setSliderValue(monthNr) {
    if (monthNr >= 13) {
      $('#month-slider').slider('value', 0);
    } else {
      $('#month-slider').slider('value', monthNr-1);
    }
  }

  selectDataType(initialDataType);
  setSliderValue(initialMonth);
  //    addContours(initialDataType, initialMonth);  // initial contour of January
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name Wargaming.net Forums Player Stats
// @namespace http://moofed.org
// @description Displays statistics for players of Wargaming.net games.
// @version 0.3.5
// @grant none
// @downloadURL https://moofed.org/user.js/wg-forum-stats.user.js
// @match http://forum.worldofwarplanes.com/index.php?/topic/*
// ==/UserScript==

var applicationID = '1a9527aa13c541208a58009172f7cff9';
var winRateColors = [[0.0, '#FE0E00'], [0.465, '#FE7903'], [0.485, '#F8F400'], [0.515, '#60FF00'], [0.565, '#02C9B3'], [0.645, '#D042F3'], [1.0, '#DEADBEEF']];

// select a list of matching elements, context is optional
function $(selector, context) {
  return (context || document).querySelectorAll(selector);
}

// select the first match only, context is optional
function $1(selector, context) {
  return (context || document).querySelector(selector);
}

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

function getCORS(url, success) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = success;
  xhr.send();
  return xhr;
}

function getWowpPlayerData(callback, accountList) {
  var url = "https://api.worldofwarplanes.com/wowp/account/info/" +
    "?application_id=" + applicationID +
    "&fields=statistics.battles,statistics.wins" +
    "&account_id=" + accountList;
  getCORS(url, function(request) {
    var response = request.currentTarget.response || request.target.responseTetxt;
    callback('Planes', JSON.parse(response));
  });
}

function getWotPlayerData(callback, accountList) {
  var url = "https://api.worldoftanks.com/wot/account/info/" +
    "?application_id=" + applicationID +
    "&fields=statistics.all.battles,statistics.all.wins" +
    "&account_id=" + accountList;
  getCORS(url, function(request) {
    var response = request.currentTarget.response || request.target.responseTetxt;
    callback('Tanks', JSON.parse(response));
  });
}

function buildAccountList() {
  var accountList = $("div.author_info")
  var accountIds = [];
  Array.prototype.forEach.call(accountList, function(item) {
    var profileURL = $1("a.name", item).getAttribute("href");
    var accountId = profileURL.match(/^https?:\/\/.*\w+-(\d+)\/$/)[1];
    accountIds.push(accountId);
  });
  return accountIds.join(',');
  //return accountIds.filter(onlyUnique).join(',');
  //return Array.prototype.filter.call(accountList, onlyUnique).join(",");
}

function displayStats(label, data) {
  var authorDivs = $("div.author_info");
  Array.prototype.forEach.call(authorDivs, function(item) {
    try {
      var profileURL = $1("a.name", item).getAttribute("href");
      var account_id = profileURL.match(/^https?:\/\/.*\w+-(\d+)\/$/)[1];
      var battlesElement = $1("div.user_details li.battles_count", item);
      var statsElement = battlesElement.cloneNode(true);
      var stats = data.data[account_id].statistics;
      if (stats.all != undefined) {
        // Workaround for WoT having multiple statistics types.
        stats = stats.all;
      }
      var wins = stats.wins;
      var battles = stats.battles;
      var winRate = wins / battles;
      var winRateText = round(winRate*100, 1) + '%';
      var winRateColor = getWinRateColor(winRate);
      statsElement.classList.remove('margin-top');
      $1("span.row_data", statsElement).textContent = winRateText;
      $1("span.row_title", statsElement).textContent = label + " wins";
      Array.prototype.forEach.call(statsElement.children, function(styleItem) {
        styleItem.style['text-shadow'] = '0px 0px 10px ' + winRateColor;
      });
      statsElement.setAttribute('title', battles + ' battles');
      battlesElement.parentElement.insertBefore(statsElement, battlesElement.nextSibling);
    } catch (e) {
      // Display nothing if stats not found.
      console.log(e);
    }});
}

function getWinRateColor(winRate) {
  var i = -1;
  var color = 'black';
  do {
    i += 1;
    color = winRateColors[i][1];
  } while (winRate >= winRateColors[i+1][0]);
  return color;
}

function run() {
  var accountList = buildAccountList();
  getWotPlayerData(displayStats, accountList)
  getWowpPlayerData(displayStats, accountList);
}

// in case the document is already rendered
if (document.readyState!='loading') run();
// modern browsers
  else if (document.addEventListener) document.addEventListener('DOMContentLoaded', run);
// IE <= 8
  else document.attachEvent('onreadystatechange', function(){
    if (document.readyState=='complete') run();
});<commit_msg>Run the script on the WoT forum<commit_after>// ==UserScript==
// @name Wargaming.net Forums Player Stats
// @namespace http://moofed.org
// @description Displays statistics for players of Wargaming.net games.
// @version 0.3.6
// @grant none
// @downloadURL https://moofed.org/user.js/wg-forum-stats.user.js
// @match http://forum.worldofwarplanes.com/index.php?/topic/*
// @match http://forum.worldoftanks.com/index.php?/topic/*
// ==/UserScript==

var applicationID = '1a9527aa13c541208a58009172f7cff9';
var winRateColors = [[0.0, '#FE0E00'], [0.465, '#FE7903'], [0.485, '#F8F400'], [0.515, '#60FF00'], [0.565, '#02C9B3'], [0.645, '#D042F3'], [1.0, '#DEADBEEF']];

// select a list of matching elements, context is optional
function $(selector, context) {
  return (context || document).querySelectorAll(selector);
}

// select the first match only, context is optional
function $1(selector, context) {
  return (context || document).querySelector(selector);
}

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

function getCORS(url, success) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = success;
  xhr.send();
  return xhr;
}

function getWowpPlayerData(callback, accountList) {
  var url = "https://api.worldofwarplanes.com/wowp/account/info/" +
    "?application_id=" + applicationID +
    "&fields=statistics.battles,statistics.wins" +
    "&account_id=" + accountList;
  getCORS(url, function(request) {
    var response = request.currentTarget.response || request.target.responseTetxt;
    callback('Planes', JSON.parse(response));
  });
}

function getWotPlayerData(callback, accountList) {
  var url = "https://api.worldoftanks.com/wot/account/info/" +
    "?application_id=" + applicationID +
    "&fields=statistics.all.battles,statistics.all.wins" +
    "&account_id=" + accountList;
  getCORS(url, function(request) {
    var response = request.currentTarget.response || request.target.responseTetxt;
    callback('Tanks', JSON.parse(response));
  });
}

function buildAccountList() {
  var accountList = $("div.author_info")
  var accountIds = [];
  Array.prototype.forEach.call(accountList, function(item) {
    var profileURL = $1("a.name", item).getAttribute("href");
    var accountId = profileURL.match(/^https?:\/\/.*\w+-(\d+)\/$/)[1];
    accountIds.push(accountId);
  });
  return accountIds.join(',');
  //return accountIds.filter(onlyUnique).join(',');
  //return Array.prototype.filter.call(accountList, onlyUnique).join(",");
}

function displayStats(label, data) {
  var authorDivs = $("div.author_info");
  Array.prototype.forEach.call(authorDivs, function(item) {
    try {
      var profileURL = $1("a.name", item).getAttribute("href");
      var account_id = profileURL.match(/^https?:\/\/.*\w+-(\d+)\/$/)[1];
      var battlesElement = $1("div.user_details li.battles_count", item);
      var statsElement = battlesElement.cloneNode(true);
      var stats = data.data[account_id].statistics;
      if (stats.all != undefined) {
        // Workaround for WoT having multiple statistics types.
        stats = stats.all;
      }
      var wins = stats.wins;
      var battles = stats.battles;
      var winRate = wins / battles;
      var winRateText = round(winRate*100, 1) + '%';
      var winRateColor = getWinRateColor(winRate);
      statsElement.classList.remove('margin-top');
      $1("span.row_data", statsElement).textContent = winRateText;
      $1("span.row_title", statsElement).textContent = label + " wins";
      Array.prototype.forEach.call(statsElement.children, function(styleItem) {
        styleItem.style['text-shadow'] = '0px 0px 10px ' + winRateColor;
      });
      statsElement.setAttribute('title', battles + ' battles');
      battlesElement.parentElement.insertBefore(statsElement, battlesElement.nextSibling);
    } catch (e) {
      // Display nothing if stats not found.
      console.log(e);
    }});
}

function getWinRateColor(winRate) {
  var i = -1;
  var color = 'black';
  do {
    i += 1;
    color = winRateColors[i][1];
  } while (winRate >= winRateColors[i+1][0]);
  return color;
}

function run() {
  var accountList = buildAccountList();
  getWotPlayerData(displayStats, accountList)
  getWowpPlayerData(displayStats, accountList);
}

// in case the document is already rendered
if (document.readyState!='loading') run();
// modern browsers
  else if (document.addEventListener) document.addEventListener('DOMContentLoaded', run);
// IE <= 8
  else document.attachEvent('onreadystatechange', function(){
    if (document.readyState=='complete') run();
});<|endoftext|>


<commit_before>import emitter from 'mitt';

let context;
let source;
let gainNode;
let loopCount;
let duration = 0;
let lastTime = 0;
let startTime;
const ZERO = 1e-25;

const audio = Object.assign(emitter(), {
  tick() {
    if (!source.buffer) return;

    const time = this.time = (context.currentTime - startTime) % duration;
    const { loopDuration } = this;

    // The position within the track as a multiple of loopDuration:
    this.progress = time / loopDuration;

    // The position within the individual loop as a value between 0 - 1:
    this.loopProgress = (time % loopDuration) / loopDuration;

    // True when the audio looped, false otherwise:
    this.looped = time < lastTime;

    if (this.looped) {
      // The index of the loop, used when the audio has more than one loops:
      this.loopIndex = Math.floor(this.progress * loopCount);
    }

    lastTime = time;
  },

  load(param, callback) {
    if (context) context.close();

    context = new AudioContext();
    source = context.createBufferSource();
    gainNode = context.createGain();

    source.connect(gainNode);
    gainNode.connect(context.destination);

    // Reset time, set loop count
    lastTime = 0;
    loopCount = param.loops;

    const request = new XMLHttpRequest();
    request.open('GET', param.src, true);
    request.responseType = 'arraybuffer';
    request.onload = () => {
      context.decodeAudioData(
        request.response,
        (response) => {
          // Load the file into the buffer
          source.buffer = response;

          duration = source.buffer.duration;
          this.loopDuration = duration / loopCount;
          source.loop = true;
          // Start audio and immediately suspend playback
          source.start(0);
          context.suspend();
          startTime = context.currentTime;
          if (callback) callback(null, param.src);
          audio.emit('load', param.src);
        },
        (err) => { callback(err); },
      );
    };

    request.send();
  },

  play() {
    context.resume();
  },

  pause() { context.suspend(); },

  fadeOut(callback) {
    if (!context) return;
    const fadeDuration = 2;
    // Fade out the music in 2 seconds
    gainNode.gain.exponentialRampToValueAtTime(
      ZERO,
      context.currentTime + fadeDuration,
    );

    setTimeout(callback, fadeDuration * 1000);
    audio.emit('faded-out');
  },

  time: 0,
  loopIndex: 0,
});

export default audio;
<commit_msg>check if callback exists<commit_after>import emitter from 'mitt';

let context;
let source;
let gainNode;
let loopCount;
let duration = 0;
let lastTime = 0;
let startTime;
const ZERO = 1e-25;

const audio = Object.assign(emitter(), {
  tick() {
    if (!source.buffer) return;

    const time = this.time = (context.currentTime - startTime) % duration;
    const { loopDuration } = this;

    // The position within the track as a multiple of loopDuration:
    this.progress = time / loopDuration;

    // The position within the individual loop as a value between 0 - 1:
    this.loopProgress = (time % loopDuration) / loopDuration;

    // True when the audio looped, false otherwise:
    this.looped = time < lastTime;

    if (this.looped) {
      // The index of the loop, used when the audio has more than one loops:
      this.loopIndex = Math.floor(this.progress * loopCount);
    }

    lastTime = time;
  },

  load(param, callback) {
    if (context) context.close();

    context = new AudioContext();
    source = context.createBufferSource();
    gainNode = context.createGain();

    source.connect(gainNode);
    gainNode.connect(context.destination);

    // Reset time, set loop count
    lastTime = 0;
    loopCount = param.loops;

    const request = new XMLHttpRequest();
    request.open('GET', param.src, true);
    request.responseType = 'arraybuffer';
    request.onload = () => {
      context.decodeAudioData(
        request.response,
        (response) => {
          // Load the file into the buffer
          source.buffer = response;

          duration = source.buffer.duration;
          this.loopDuration = duration / loopCount;
          source.loop = true;
          // Start audio and immediately suspend playback
          source.start(0);
          context.suspend();
          startTime = context.currentTime;
          if (callback) callback(null, param.src);
          audio.emit('load', param.src);
        },
        (err) => { callback(err); },
      );
    };

    request.send();
  },

  play() {
    context.resume();
  },

  pause() { context.suspend(); },

  fadeOut(callback) {
    if (!context) return;
    const fadeDuration = 2;
    // Fade out the music in 2 seconds
    gainNode.gain.exponentialRampToValueAtTime(
      ZERO,
      context.currentTime + fadeDuration,
    );

    if (callback) {
      setTimeout(callback, fadeDuration * 1000);
    }
    audio.emit('faded-out');
  },

  time: 0,
  loopIndex: 0,
});

export default audio;
<|endoftext|>


<commit_before>'use strict';
define(
    [
        'config',
        'three',
        'stats',
        'InputHandler',
        'Debug',
        'Camera',
        'GameObjectManager',
        'Grid',
        'Planet',
        'Star',
        'SpaceShip',
        'Player'
    ],
    function(config, THREE, Stats, InputHandler, Debug, Camera, GameObjectManager, Grid, Planet, Star, SpaceShip, Player) {
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild(renderer.domElement);

        config.maxAnisotropy = renderer.getMaxAnisotropy();

        let scene = new THREE.Scene();
        scene.fog = new THREE.Fog(0x000000, 100, 300);

        // Create camera
        let camera = new Camera(
            scene,
            renderer,
            config.camera.fov,
            config.canvasWidth / config.canvasHeight,
            0.1,
            1000,
            new THREE.Vector3(25, 75, 75)
        );

        // Create cube map
        let baseUrl = '/assets/textures/cubemap_';
        let urls = [
            baseUrl + 'left.png',
            baseUrl + 'right.png',
            baseUrl + 'top.png',
            baseUrl + 'bottom.png',
            baseUrl + 'front.png',
            baseUrl + 'back.png',
        ];
        var cube = new THREE.CubeTextureLoader().load(urls);
        cube.format = THREE.RGBFormat;
        scene.background = cube;

        scene.add(new THREE.AmbientLight( 0x101010 ));

        // Add objects
        GameObjectManager.add([
            new Grid(scene, 'xz_grid', { moveWithCamera: true }),

            new Planet(scene, 'homePlanet', {
                mass:     1.2E7,
                radius:   150,
                position: new THREE.Vector3(75, 0, 0),
                isSolid:  true,
                color:    0x33ff33
            }),

            new Planet(scene, 'redPlanet', {
                mass:     33.18,
                radius:   50,
                position: new THREE.Vector3(0, 18, 0),
                isSolid:  true,
                color:    0xff3333
            }),

            new Star(scene, 'sol', {
                mass:     1.9984E8,
                radius:   1400,
                color:    0xffff00
            }),

            new Player(scene, 'player', {
                mass:     3.42E-19,
                position: new THREE.Vector3(0, 0, -50)
            })
        ]);

        // Give objects a speed so they won't
        // just plunge back into the sun
        GameObjectManager.get('redPlanet').velocity.setX(0.2);
        GameObjectManager.get('redPlanet').velocity.setZ(0.3);

        GameObjectManager.get('homePlanet').velocity.setY(0.03);
        GameObjectManager.get('homePlanet').velocity.setZ(0.2);

        GameObjectManager.get('player').velocity.setX(.2);
        GameObjectManager.get('player').velocity.setZ(0);

        // Define variables to calculate deltaT
        // and smoothed deltaT
        let lastFrameTime    = 0;
        let lastDeltaTValues = [];
        let smoothDeltaT     = 0;

        let inputHandler = new InputHandler(scene, camera, GameObjectManager.get('player'));

        function update(currentFrameTime) {
            stats.begin();
            Debug.clear();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Smooth deltaT
            while(lastDeltaTValues.length >= config.framesToSmoothDeltaT) {
                lastDeltaTValues.splice(0, 1);
            }
            lastDeltaTValues.push(deltaT);
            smoothDeltaT = lastDeltaTValues.reduce(function(prev, cur) { return prev + cur;}) / lastDeltaTValues.length;

            // Update controls
            camera.controls.update();

            // Handle user input
            inputHandler.checkInput();

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT, smoothDeltaT);

            // Update all the objects
            GameObjectManager.update(deltaT, smoothDeltaT);

            // Render the scene
            renderer.render(scene, camera.camera);

            stats.end();
            requestAnimationFrame(update);
        }

        requestAnimationFrame(update);
    }
);<commit_msg>Fog starts further away now<commit_after>'use strict';
define(
    [
        'config',
        'three',
        'stats',
        'InputHandler',
        'Debug',
        'Camera',
        'GameObjectManager',
        'Grid',
        'Planet',
        'Star',
        'SpaceShip',
        'Player'
    ],
    function(config, THREE, Stats, InputHandler, Debug, Camera, GameObjectManager, Grid, Planet, Star, SpaceShip, Player) {
        let stats = new Stats();
        stats.showPanel(0);
        document.body.appendChild(stats.dom);

        let renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(config.canvasWidth, config.canvasHeight);
        document.getElementById('game').appendChild(renderer.domElement);

        config.maxAnisotropy = renderer.getMaxAnisotropy();

        let scene = new THREE.Scene();
        scene.fog = new THREE.Fog(0x000000, 100, 1000);

        // Create camera
        let camera = new Camera(
            scene,
            renderer,
            config.camera.fov,
            config.canvasWidth / config.canvasHeight,
            0.1,
            1000,
            new THREE.Vector3(25, 75, 75)
        );

        // Create cube map
        let baseUrl = '/assets/textures/cubemap_';
        let urls = [
            baseUrl + 'left.png',
            baseUrl + 'right.png',
            baseUrl + 'top.png',
            baseUrl + 'bottom.png',
            baseUrl + 'front.png',
            baseUrl + 'back.png',
        ];
        var cube = new THREE.CubeTextureLoader().load(urls);
        cube.format = THREE.RGBFormat;
        scene.background = cube;

        scene.add(new THREE.AmbientLight( 0x101010 ));

        // Add objects
        GameObjectManager.add([
            new Grid(scene, 'xz_grid', { moveWithCamera: true }),

            new Planet(scene, 'homePlanet', {
                mass:     1.2E7,
                radius:   150,
                position: new THREE.Vector3(75, 0, 0),
                isSolid:  true,
                color:    0x33ff33
            }),

            new Planet(scene, 'redPlanet', {
                mass:     33.18,
                radius:   50,
                position: new THREE.Vector3(0, 18, 0),
                isSolid:  true,
                color:    0xff3333
            }),

            new Star(scene, 'sol', {
                mass:     1.9984E8,
                radius:   1400,
                color:    0xffff00
            }),

            new Player(scene, 'player', {
                mass:     3.42E-19,
                position: new THREE.Vector3(0, 0, -50)
            })
        ]);

        // Give objects a speed so they won't
        // just plunge back into the sun
        GameObjectManager.get('redPlanet').velocity.setX(0.2);
        GameObjectManager.get('redPlanet').velocity.setZ(0.3);

        GameObjectManager.get('homePlanet').velocity.setY(0.03);
        GameObjectManager.get('homePlanet').velocity.setZ(0.2);

        GameObjectManager.get('player').velocity.setX(.2);
        GameObjectManager.get('player').velocity.setZ(0);

        // Define variables to calculate deltaT
        // and smoothed deltaT
        let lastFrameTime    = 0;
        let lastDeltaTValues = [];
        let smoothDeltaT     = 0;

        let inputHandler = new InputHandler(scene, camera, GameObjectManager.get('player'));

        function update(currentFrameTime) {
            stats.begin();
            Debug.clear();

            let deltaT = currentFrameTime - lastFrameTime;
            lastFrameTime = currentFrameTime;

            // Ugly hack to prevent "jumps" when the tab lost focus
            if(deltaT > 32) deltaT = 1000/60;

            // Smooth deltaT
            while(lastDeltaTValues.length >= config.framesToSmoothDeltaT) {
                lastDeltaTValues.splice(0, 1);
            }
            lastDeltaTValues.push(deltaT);
            smoothDeltaT = lastDeltaTValues.reduce(function(prev, cur) { return prev + cur;}) / lastDeltaTValues.length;

            // Update controls
            camera.controls.update();

            // Handle user input
            inputHandler.checkInput();

            // Update all the objects' positions
            GameObjectManager.updatePositions(deltaT, smoothDeltaT);

            // Update all the objects
            GameObjectManager.update(deltaT, smoothDeltaT);

            // Render the scene
            renderer.render(scene, camera.camera);

            stats.end();
            requestAnimationFrame(update);
        }

        requestAnimationFrame(update);
    }
);<|endoftext|>


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

var Benchmark = require("benchmark"),
    sprintf = require("sprintf").sprintf;

var Graph = require("..").Graph,
    alg = require("..").alg;

var NODE_SIZES = [100],
    EDGE_DENSITY = 0.2,
    KEY_SIZE = 10;

function runBenchmark(name, fn) {
  var options = {};
  options.onComplete = function(bench) {
    var target = bench.target,
        hz = target.hz,
        stats = target.stats,
        rme = stats.rme,
        samples = stats.sample.length,
        msg = sprintf("    %25s: %13s ops/sec \xb1 %s%% (%3d run(s) sampled)",
                      target.name,
                      Benchmark.formatNumber(hz.toFixed(2)),
                      rme.toFixed(2),
                      samples);
    console.log(msg);
  };
  options.onError = function(bench) {
    console.error("    " + bench.target.error);
  };
  options.setup = function() {
    this.count = Math.random() * 1000;
    this.nextInt = function(range) {
      return Math.floor(this.count++ % range );
    };
  };
  new Benchmark(name, fn, options).run();
}

function keys(count) {
  var ks = [],
      k;
  for (var i = 0; i < count; ++i) {
    k = "";
    for (var j = 0; j < KEY_SIZE; ++j) {
      k += String.fromCharCode(97 + Math.floor(Math.random() * 26));
    }
    ks.push(k);
  }
  return ks;
}

function buildGraph(numNodes, edgeDensity) {
  var g = new Graph(),
      numEdges = numNodes * numNodes * edgeDensity,
      ks = keys(numNodes);

  ks.forEach(function(k) { g.node(k); });

  for (var i = 0; i < numEdges; ++i) {
    var v, w;
    do {
      v = ks[Math.floor(Math.random() * ks.length)];
      w = ks[Math.floor(Math.random() * ks.length)];
    } while (g.hasEdge(v, w));
    g.edge(v, w);
  }
  return g;
}

runBenchmark("constructor", function () { new Graph(); });

NODE_SIZES.forEach(function(size) {
  var g = buildGraph(size, EDGE_DENSITY),
      nodeIds = g.allNodes(),
      nameSuffix = "(" + size + "," + EDGE_DENSITY + ")";

  runBenchmark("allNodes" + nameSuffix, function() {
    g.allNodes();
  });

  runBenchmark("node" + nameSuffix, function() {
    g.node("key");
  });

  runBenchmark("node + remove" + nameSuffix, function() {
    g.node("key");
    g.removeNode("key");
  });

  runBenchmark("predecessors" + nameSuffix, function() {
    g.predecessors(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("successors" + nameSuffix, function() {
    g.successors(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("neighbors" + nameSuffix, function() {
    g.neighbors(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("allEdges" + nameSuffix, function() {
    g.allEdges();
  });

  runBenchmark("edge" + nameSuffix, function() {
    g.edge("from", "to");
  });

  runBenchmark("edge + remove" + nameSuffix, function() {
    g.edge("from", "to");
    g.removeEdge("from", "to");
  });

  runBenchmark("inEdges" + nameSuffix, function() {
    g.inEdges(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("outEdges" + nameSuffix, function() {
    g.outEdges(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("nodeEdges" + nameSuffix, function() {
    g.nodeEdges(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("components" + nameSuffix, function() {
    alg.components(g);
  });

  runBenchmark("dijkstraAll" + nameSuffix, function() {
    alg.dijkstraAll(g);
  });

  runBenchmark("greedyFAS" + nameSuffix, function() {
    alg.greedyFAS(g);
  });

  runBenchmark("copy" + nameSuffix, function() {
    g.copy();
  });
});
<commit_msg>Fix to benchmark<commit_after>#!/usr/bin/env node

var Benchmark = require("benchmark"),
    sprintf = require("sprintf").sprintf;

var Graph = require("..").Graph,
    alg = require("..").alg;

var NODE_SIZES = [100],
    EDGE_DENSITY = 0.2,
    KEY_SIZE = 10;

function runBenchmark(name, fn) {
  var options = {};
  options.onComplete = function(bench) {
    var target = bench.target,
        hz = target.hz,
        stats = target.stats,
        rme = stats.rme,
        samples = stats.sample.length,
        msg = sprintf("    %25s: %13s ops/sec \xb1 %s%% (%3d run(s) sampled)",
                      target.name,
                      Benchmark.formatNumber(hz.toFixed(2)),
                      rme.toFixed(2),
                      samples);
    console.log(msg);
  };
  options.onError = function(bench) {
    console.error("    " + bench.target.error);
  };
  options.setup = function() {
    this.count = Math.random() * 1000;
    this.nextInt = function(range) {
      return Math.floor(this.count++ % range );
    };
  };
  new Benchmark(name, fn, options).run();
}

function keys(count) {
  var ks = [],
      k;
  for (var i = 0; i < count; ++i) {
    k = "";
    for (var j = 0; j < KEY_SIZE; ++j) {
      k += String.fromCharCode(97 + Math.floor(Math.random() * 26));
    }
    ks.push(k);
  }
  return ks;
}

function buildGraph(numNodes, edgeDensity) {
  var g = new Graph(),
      numEdges = numNodes * numNodes * edgeDensity,
      ks = keys(numNodes);

  ks.forEach(function(k) { g.node(k); });

  for (var i = 0; i < numEdges; ++i) {
    var v, w;
    do {
      v = ks[Math.floor(Math.random() * ks.length)];
      w = ks[Math.floor(Math.random() * ks.length)];
    } while (g.hasEdge(v, w));
    g.edge(v, w);
  }
  return g;
}

runBenchmark("constructor", function () { new Graph(); });

NODE_SIZES.forEach(function(size) {
  var g = buildGraph(size, EDGE_DENSITY),
      nodeIds = g.allNodes(),
      nameSuffix = "(" + size + "," + EDGE_DENSITY + ")";

  runBenchmark("allNodes" + nameSuffix, function() {
    g.allNodes();
  });

  runBenchmark("node" + nameSuffix, function() {
    g.node("key");
  });

  runBenchmark("node + remove" + nameSuffix, function() {
    g.node("key");
    g.removeNode("key");
  });

  runBenchmark("predecessors" + nameSuffix, function() {
    g.predecessors(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("successors" + nameSuffix, function() {
    g.successors(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("neighbors" + nameSuffix, function() {
    g.neighbors(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("allEdges" + nameSuffix, function() {
    g.allEdges();
  });

  runBenchmark("edge" + nameSuffix, function() {
    g.edge("from", "to");
  });

  runBenchmark("edge + remove" + nameSuffix, function() {
    g.edge("from", "to");
    g.removeEdge("from", "to");
  });

  runBenchmark("inEdges" + nameSuffix, function() {
    g.inEdges(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("outEdges" + nameSuffix, function() {
    g.outEdges(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("edges" + nameSuffix, function() {
    g.edges(nodeIds[this.nextInt(nodeIds.length)]);
  });

  runBenchmark("components" + nameSuffix, function() {
    alg.components(g);
  });

  runBenchmark("dijkstraAll" + nameSuffix, function() {
    alg.dijkstraAll(g);
  });

  runBenchmark("greedyFAS" + nameSuffix, function() {
    alg.greedyFAS(g);
  });

  runBenchmark("copy" + nameSuffix, function() {
    g.copy();
  });
});
<|endoftext|>


<commit_before>/* pcm accumulator examples (not exhaustive):

 <-------------- lW ---------------->
                   <--------------- W ---------------->
:            .....|.....       _______________         |
:        .'''     |     '''_---      |       |\        |
:.....'''         |_____--- '''......|       | \_______|
:.................|__________________|_______|__|______|
                  |<------ Sl ------>|      > Sr <     |endW
                  |beginSl           |endSl  |  |endSr
                  |beginW            |endlW  |beginSr

                      |< lW >|
                   <--------------- W ---------------->
                  |   |  ..  ______________            |
                  |   | '  `/        |     ---_        |
                  |___.'___/`.       |         ---_____|
                  |_______|__|_______|_________________|
                  |      >|Sl|<      |<------ Sr ----->|endW
                  |       |  |endSl  |beginSr          |endSr
                  |beginW |  |endlW
                  mult[0] |beginSl                     mult[n]

 <-------------- lW ----------------->
                          |<--W-->|
:            ..............  ___  |   |
:        .'''             |`/   \ |   |
:.....'''                 |/`....\|...|
:.........................|___|___|___|
                          |Sl |Sr |endW
                          |   |   |endSr
                          |   |beginSr
                          |   |endSl
                          |beginSl
                          |beginW
*/

/* block abstraction setup *********************************************/
var WORD_ALIGN = 8;

function vorbis_block_init(v, dv) {
  NOT_IMPLEMENTED();
}

function _vorbis_block_alloc(vb, bytes) {
  NOT_IMPLEMENTED();
}

/* reap the chain, pull the ripcord */
function _vorbis_block_ripcord(vb) {
  NOT_IMPLEMENTED();
}

function vorbis_block_clear(vb) {
  NOT_IMPLEMENTED();
}

/* Analysis side code, but directly related to blocking.  Thus it's
   here and not in analysis.c (which is for analysis transforms only).
   The init is here because some of it is shared */
function _vds_shared_init(v, vi, encp) {
  NOT_IMPLEMENTED();
}

/* arbitrary settings and spec-mandated numbers get filled in here */
function vorbis_analysis_init(v, vi) {
  NOT_IMPLEMENTED();
}

function vorbis_dsp_clear(v) {
  NOT_IMPLEMENTED();
}

function vorbis_analysis_buffer(v, vals) {
  NOT_IMPLEMENTED();
}

function _preextrapolate_helper(v) {
  NOT_IMPLEMENTED();
}

/* call with val<=0 to set eof */
function vorbis_analysis_wrote(v, vals) {
  NOT_IMPLEMENTED();
}

/* do the deltas, envelope shaping, pre-echo and determine the size of
   the next block on which to continue analysis */
function vorbis_analysis_blockout(v, vb) {
  NOT_IMPLEMENTED();
}

function vorbis_synthesis_restart(v) {
  NOT_IMPLEMENTED();
}

function vorbis_synthesis_init(v, vi) {
  if(_vds_shared_init(v,vi,0)){
    vorbis_dsp_clear(v);
    return 1;
  }
  vorbis_synthesis_restart(v);
  return 0;
}

/* Unlike in analysis, the window is only partially applied for each
   block.  The time domain envelope is not yet handled at the point of
   calling (as it relies on the previous block). */
function vorbis_synthesis_blockin(v, vb) {
  NOT_IMPLEMENTED();
}

/* pcm==NULL indicates we just want the pending samples, no more */
function vorbis_synthesis_pcmout(v, pcm){
  NOT_IMPLEMENTED();
}

function vorbis_synthesis_read(v, n) {
  NOT_IMPLEMENTED();
}

/* intended for use with a specific vorbisfile feature; we want access
   to the [usually synthetic/postextrapolated] buffer and lapping at
   the end of a decode cycle, specifically, a half-short-block worth.
   This funtion works like pcmout above, except it will also expose
   this implicit buffer data not normally decoded. */
function vorbis_synthesis_lapout(v, pcm) {
  NOT_IMPLEMENTED();
}

function vorbis_window(v, W){
  NOT_IMPLEMENTED();
}
<commit_msg>added: _vds_shared_init<commit_after>/* pcm accumulator examples (not exhaustive):

 <-------------- lW ---------------->
                   <--------------- W ---------------->
:            .....|.....       _______________         |
:        .'''     |     '''_---      |       |\        |
:.....'''         |_____--- '''......|       | \_______|
:.................|__________________|_______|__|______|
                  |<------ Sl ------>|      > Sr <     |endW
                  |beginSl           |endSl  |  |endSr
                  |beginW            |endlW  |beginSr

                      |< lW >|
                   <--------------- W ---------------->
                  |   |  ..  ______________            |
                  |   | '  `/        |     ---_        |
                  |___.'___/`.       |         ---_____|
                  |_______|__|_______|_________________|
                  |      >|Sl|<      |<------ Sr ----->|endW
                  |       |  |endSl  |beginSr          |endSr
                  |beginW |  |endlW
                  mult[0] |beginSl                     mult[n]

 <-------------- lW ----------------->
                          |<--W-->|
:            ..............  ___  |   |
:        .'''             |`/   \ |   |
:.....'''                 |/`....\|...|
:.........................|___|___|___|
                          |Sl |Sr |endW
                          |   |   |endSr
                          |   |beginSr
                          |   |endSl
                          |beginSl
                          |beginW
*/

/* block abstraction setup *********************************************/
var WORD_ALIGN = 8;

function vorbis_block_init(v, dv) {
  NOT_IMPLEMENTED();
}

function _vorbis_block_alloc(vb, bytes) {
  NOT_IMPLEMENTED();
}

/* reap the chain, pull the ripcord */
function _vorbis_block_ripcord(vb) {
  NOT_IMPLEMENTED();
}

function vorbis_block_clear(vb) {
  NOT_IMPLEMENTED();
}

/* Analysis side code, but directly related to blocking.  Thus it's
   here and not in analysis.c (which is for analysis transforms only).
   The init is here because some of it is shared */
function _vds_shared_init(v, vi, encp) {
  var i;
  var ci=vi.codec_setup;
  var b=NULL;
  var hs;

  if(ci===NULL) return 1;
  hs=ci.halfrate_flag;

  vorbis_dsp_state(v);
  b=v.backend_state=private_state();

  v.vi=vi;
  b.modebits=ilog2(ci.modes);

  b.transform[0]=calloc(VI_TRANSFORMB,[]);
  b.transform[1]=calloc(VI_TRANSFORMB,[]);

  /* MDCT is tranform 0 */

  b.transform[0][0]=mdct_lookup();
  b.transform[1][0]=mdct_lookup();
  mdct_init(b.transform[0][0],ci.blocksizes[0]>>hs);
  mdct_init(b.transform[1][0],ci.blocksizes[1]>>hs);

  /* Vorbis I uses only window type 0 */
  b.window[0]=ilog2(ci.blocksizes[0])-6;
  b.window[1]=ilog2(ci.blocksizes[1])-6;

  abort_books:while(1){
    if(encp){ /* encode/decode differ here */

      /* analysis always needs an fft */
      drft_init(b.fft_look[0],ci.blocksizes[0]);
      drft_init(b.fft_look[1],ci.blocksizes[1]);

      /* finish the codebooks */
      if(!ci.fullbooks){
        ci.fullbooks=calloc(ci.books,codebook);
        for(i=0;i<ci.books;i++)
          vorbis_book_init_encode(ci.fullbooks[i],ci.book_param[i]);
      }

      b.psy=calloc(ci.psys,vorbis_look_psy);
      for(i=0;i<ci.psys;i++){
        _vp_psy_init(b.psy[i],
                     ci.psy_param[i],
                     ci.psy_g_param,
                     ci.blocksizes[ci.psy_param[i].blockflag]/2,
                     vi.rate);
      }

      v.analysisp=1;
    }else{
      /* finish the codebooks */
      if(!ci.fullbooks){
        ci.fullbooks=calloc(ci.books,codebook);
        for(i=0;i<ci.books;i++){
          if(ci.book_param[i]===NULL)
            break abort_books;
          if(vorbis_book_init_decode(ci.fullbooks[i],ci.book_param[i]))
            break abort_books;
          /* decode codebooks are now standalone after init */
          vorbis_staticbook_destroy(ci.book_param[i]);
          ci.book_param[i]=NULL;
        }
      }
    }

    /* initialize the storage vectors. blocksize[1] is small for encode,
       but the correct size for decode */
    v.pcm_storage=ci.blocksizes[1];
    v.pcm=calloc(vi.channels,[]);
    v.pcmret=calloc(vi.channels,[]);
    {
      for(i=0;i<vi.channels;i++)
        v.pcm[i]=calloc(v.pcm_storage,float32);
    }

    /* all 1 (large block) or 0 (small block) */
    /* explicitly set for the sake of clarity */
    v.lW=0; /* previous window size */
    v.W=0;  /* current window size */

    /* all vector indexes */
    v.centerW=_int(ci.blocksizes[1]/2);

    v.pcm_current=v.centerW;

    /* initialize all the backend lookups */
    b.flr=calloc(ci.floors,[]);
    b.residue=calloc(ci.residues,[]);

    for(i=0;i<ci.floors;i++)
      b.flr[i]=_floor_P[ci.floor_type[i]].look(v,ci.floor_param[i]);

    for(i=0;i<ci.residues;i++)
      b.residue[i]=_residue_P[ci.residue_type[i]].look(v,ci.residue_param[i]);

    return 0;
  }

  // abort_books:
  for(i=0;i<ci.books;i++){
    if(ci.book_param[i]!==NULL){
      vorbis_staticbook_destroy(ci.book_param[i]);
      ci.book_param[i]=NULL;
    }
  }
  vorbis_dsp_clear(v);
  return -1;
}

/* arbitrary settings and spec-mandated numbers get filled in here */
function vorbis_analysis_init(v, vi) {
  NOT_IMPLEMENTED();
}

function vorbis_dsp_clear(v) {
  NOT_IMPLEMENTED();
}

function vorbis_analysis_buffer(v, vals) {
  NOT_IMPLEMENTED();
}

function _preextrapolate_helper(v) {
  NOT_IMPLEMENTED();
}

/* call with val<=0 to set eof */
function vorbis_analysis_wrote(v, vals) {
  NOT_IMPLEMENTED();
}

/* do the deltas, envelope shaping, pre-echo and determine the size of
   the next block on which to continue analysis */
function vorbis_analysis_blockout(v, vb) {
  NOT_IMPLEMENTED();
}

function vorbis_synthesis_restart(v) {
  NOT_IMPLEMENTED();
}

function vorbis_synthesis_init(v, vi) {
  if(_vds_shared_init(v,vi,0)){
    vorbis_dsp_clear(v);
    return 1;
  }
  vorbis_synthesis_restart(v);
  return 0;
}

/* Unlike in analysis, the window is only partially applied for each
   block.  The time domain envelope is not yet handled at the point of
   calling (as it relies on the previous block). */
function vorbis_synthesis_blockin(v, vb) {
  NOT_IMPLEMENTED();
}

/* pcm==NULL indicates we just want the pending samples, no more */
function vorbis_synthesis_pcmout(v, pcm){
  NOT_IMPLEMENTED();
}

function vorbis_synthesis_read(v, n) {
  NOT_IMPLEMENTED();
}

/* intended for use with a specific vorbisfile feature; we want access
   to the [usually synthetic/postextrapolated] buffer and lapping at
   the end of a decode cycle, specifically, a half-short-block worth.
   This funtion works like pcmout above, except it will also expose
   this implicit buffer data not normally decoded. */
function vorbis_synthesis_lapout(v, pcm) {
  NOT_IMPLEMENTED();
}

function vorbis_window(v, W){
  NOT_IMPLEMENTED();
}
<|endoftext|>


<commit_before>'use strict';
var Crawler = require('./lib/crawler.js').Crawler;
var _ = require('lodash');
var src = require('./program');
var Promise = require('bluebird');

module.exports = function(ipp, commander) {
  return new Promise(function(resolve, reject) {
    var logger = {log: _.noop, error: _.noop}; // no crawler logging for now
    var maxRequests = commander.count ? parseInt(commander.count, 10) : 100;
    var crawler = new Crawler(maxRequests, logger);
    crawler.getCrawl(ipp)
    .then(function(crawl) {
      // Store in database
      if (commander.store) {
        src
        .store(crawl, commander.store, commander.logsql)
        // Send message
        .then(function(row) {
          if (commander.message) {
            src
            .message(row, commander.message)
            .then(console.log) // todo logQueue option
            .catch(console.error); // message error
          }
        })
        .catch(console.error); // store error
      }
      return crawl;
    })
    .then(resolve) // return crawl
    .catch(reject); // getCrawl error
  });
};
<commit_msg>minor logging change<commit_after>'use strict';
var Crawler = require('./lib/crawler.js').Crawler;
var _ = require('lodash');
var src = require('./program');
var Promise = require('bluebird');

module.exports = function(ipp, commander) {
  return new Promise(function(resolve, reject) {
    var logger = {log: _.noop, error: _.noop}; // no crawler logging for now
    var maxRequests = commander.count ? parseInt(commander.count, 10) : 100;
    var crawler = new Crawler(maxRequests, logger);
    crawler.getCrawl(ipp)
    .then(function(crawl) {
      // Store in database
      if (commander.store) {
        src
        .store(crawl, commander.store, commander.logsql)
        // Send message
        .then(function(row) {
          if (commander.message) {
            src
            .message(row, commander.message)
            //.then(console.log) // todo logQueue option
            .catch(console.error); // message error
          }
        })
        .catch(console.error); // store error
      }
      return crawl;
    })
    .then(resolve) // return crawl
    .catch(reject); // getCrawl error
  });
};
<|endoftext|>


<commit_before>/**
 * @preserve Glift: A Responsive Javascript library for the game Go.
 *
 * @copyright Josh Hoak
 * @license MIT License (see LICENSE.txt)
 * --------------------------------------
 */

// Define some closure primitives for compatibility with dev mode. Closure
// compiler works off of regular expressions, so this shouldn't be an issue.
// This allows us to use goog.require and goog.provides in dev mode.
if (window && !window['goog']) {
  window['goog'] = {}
  window['goog']['require'] = function(ns) {
  };
  window['goog']['scope'] = function(fn) { fn() };
  window['goog']['provide'] = function(ns) {
  };
}

goog.provide('glift');

(function(w) {

var g = glift || w.glift || {};
if (w) {
  // expose Glift as a global.
  w.glift = g ;
}
})(window);
<commit_msg>Fix tests by checking typeof glift global.<commit_after>/**
 * @preserve Glift: A Responsive Javascript library for the game Go.
 *
 * @copyright Josh Hoak
 * @license MIT License (see LICENSE.txt)
 * --------------------------------------
 */

// Define some closure primitives for compatibility with dev mode. Closure
// compiler works off of regular expressions, so this shouldn't be an issue.
// This allows us to use goog.require and goog.provides in dev mode.
if (window && !window['goog']) {
  window['goog'] = {}
  window['goog']['require'] = function(ns) {
  };
  window['goog']['scope'] = function(fn) { fn() };
  window['goog']['provide'] = function(ns) {
  };
}

goog.provide('glift');

(function(w) {

var g;
if (typeof glift !== 'undefined') {
  g = glift;
} else if (typeof w.glift !== 'undefined') {
  g = w.glift
} else {
  g = {};
}
if (w) {
  // expose Glift as a global.
  w.glift = g ;
}
})(window);
<|endoftext|>


<commit_before><commit_msg>[#915] fix Draggable Entities name export under me namespace<commit_after><|endoftext|>


<commit_before><commit_msg>UPDATED: deleteRecord API<commit_after><|endoftext|>


<commit_before>var spdy = require('spdy-transport')
var EventEmitter = require('events').EventEmitter
var util = require('util')
var DuplexPassThrough = require('duplex-passthrough')

exports = module.exports = SpdyStreamMuxer
util.inherits(Connection, EventEmitter)

function SpdyStreamMuxer () {
  var self = this

  self.attach = function (transport, isListener) {
    var conn = spdy.connection.create(transport, {
      protocol: 'spdy',
      isServer: isListener
    })
    conn.start(3.1)
    return new Connection(conn)
  }
}

function Connection (conn) {
  var self = this

  self.dialStream = function (callback) {
    var ds = new DuplexPassThrough()

    conn.request({
      method: 'POST',
      path: '/',
      headers: {}
    }, function (err, stream) {
      if (err) {
        ds.emit('err', err)
        if (callback) { callback(err) }
        return
      }
      ds.wrapStream(stream)
      ds.emit('ready')
      if (callback) { callback(null, ds) }
    })

    return ds
  }

  conn.on('stream', function (stream) {
    stream.respond(200, {})
    self.emit('stream', stream)
  })

  conn.on('close', function () {
    self.emit('close', null)
  })

  conn.on('error', function (err) {
    self.emit('error', err)
  })
}
<commit_msg>Expose Connection.end<commit_after>var spdy = require('spdy-transport')
var EventEmitter = require('events').EventEmitter
var util = require('util')
var DuplexPassThrough = require('duplex-passthrough')

exports = module.exports = SpdyStreamMuxer
util.inherits(Connection, EventEmitter)

function SpdyStreamMuxer () {
  var self = this

  self.attach = function (transport, isListener) {
    var conn = spdy.connection.create(transport, {
      protocol: 'spdy',
      isServer: isListener
    })
    conn.start(3.1)
    return new Connection(conn)
  }
}

function Connection (conn) {
  var self = this

  self.dialStream = function (callback) {
    var ds = new DuplexPassThrough()

    conn.request({
      method: 'POST',
      path: '/',
      headers: {}
    }, function (err, stream) {
      if (err) {
        ds.emit('err', err)
        if (callback) { callback(err) }
        return
      }
      ds.wrapStream(stream)
      ds.emit('ready')
      if (callback) { callback(null, ds) }
    })

    return ds
  }

  conn.on('stream', function (stream) {
    stream.respond(200, {})
    self.emit('stream', stream)
  })

  conn.on('close', function () {
    self.emit('close', null)
  })

  conn.on('error', function (err) {
    self.emit('error', err)
  })

  self.end = function (cb) {
    conn.end(cb)
  }
}
<|endoftext|>