<commit_before>function makeLinkElem(link) {
  console.log(link.created);

  var time = new Date(link.created * 1000).toISOString().replace('T', ' ').replace(/\..*/, '');

  var html = '
';
  if (link.thumb) html += '';
  html += '
' + link.title + '
';
  html += '
' + link.user + '
';
  html += '
' + time + '
';
  html += '
';

  return html;
}

function saveSettings() {
  console.log('save settings');

  $.cookie('settings-name', $('#settings-name').val());

  $('#settings').modal('hide');
}

$(document).ready(function() {
  $('#settings-name').val($.cookie('settings-name'));

  $('#share').submit(function(e) {
    $('#waiting').show();
    $('.error').hide();

    var body = {
      uri:  $('#url').val(),
      user: $.cookie('settings-name'),
    };

    $.post('/', body, function(data) {
      $('#url').val('');
      $('#waiting').hide();

      if (data.error) {
        $('.error').show();
        $('.error').text(data.error);
      } else {
        $('.error').hide();
      }
    });

    e.preventDefault();
  });

  $(window).scroll(function() {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
      $.get('/json?b=' + oldest, function(data) {
        if (data.length > 0) {
          for (i in data) {
            $('#links').append(makeLinkElem(data[i]));
            oldest = data[i].created;
          }
          $('li').fadeIn();
        }
      });
    }
  });

  (function refresh() {
    $.ajax({
      url: '/json?a=' + newest,
      success: function(data) {
        if (data.length > 0) {
          for (i in data) {
            $('#links').prepend(makeLinkElem(data[i]));
          }
          newest = data[0].created;
          $('li').fadeIn();
        }
      },
      complete: function() {
        setTimeout(refresh, 1000);
      },
    });
  })();

  $('#settings form').submit(function(e) {
    saveSettings();
    e.preventDefault();
  });

  $('#save').click(function(e) {
    saveSettings();
    e.preventDefault();
  });
});
<commit_msg>Change settings to expire in 10 years<commit_after>function makeLinkElem(link) {
  console.log(link.created);

  var time = new Date(link.created * 1000).toISOString().replace('T', ' ').replace(/\..*/, '');

  var html = '
';
  if (link.thumb) html += '';
  html += '
' + link.title + '
';
  html += '
' + link.user + '
';
  html += '
' + time + '
';
  html += '
';

  return html;
}

function saveSettings() {
  console.log('save settings');

  $.cookie('settings-name', $('#settings-name').val(), { expires: 3650 });

  $('#settings').modal('hide');
}

$(document).ready(function() {
  $('#settings-name').val($.cookie('settings-name'));

  $('#share').submit(function(e) {
    $('#waiting').show();
    $('.error').hide();

    var body = {
      uri:  $('#url').val(),
      user: $.cookie('settings-name'),
    };

    $.post('/', body, function(data) {
      $('#url').val('');
      $('#waiting').hide();

      if (data.error) {
        $('.error').show();
        $('.error').text(data.error);
      } else {
        $('.error').hide();
      }
    });

    e.preventDefault();
  });

  $(window).scroll(function() {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
      $.get('/json?b=' + oldest, function(data) {
        if (data.length > 0) {
          for (i in data) {
            $('#links').append(makeLinkElem(data[i]));
            oldest = data[i].created;
          }
          $('li').fadeIn();
        }
      });
    }
  });

  (function refresh() {
    $.ajax({
      url: '/json?a=' + newest,
      success: function(data) {
        if (data.length > 0) {
          for (i in data) {
            $('#links').prepend(makeLinkElem(data[i]));
          }
          newest = data[0].created;
          $('li').fadeIn();
        }
      },
      complete: function() {
        setTimeout(refresh, 1000);
      },
    });
  })();

  $('#settings form').submit(function(e) {
    saveSettings();
    e.preventDefault();
  });

  $('#save').click(function(e) {
    saveSettings();
    e.preventDefault();
  });
});
<|endoftext|>


<commit_before>
//Server with Express
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/../..client'));

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!');
});

<commit_msg>fixed ../client<commit_after>var express = require('express');
var app = express();

app.use(express.static(__dirname + '/../client'));

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!');
});

<|endoftext|>


<commit_before>import NodePatcher from './NodePatcher';
import type { Node, ParseContext, Editor, Token } from './types';

export default class MemberAccessOpPatcher extends NodePatcher {
  constructor(node: Node, context: ParseContext, editor: Editor, expression: NodePatcher) {
    super(node, context, editor);
    this.expression = expression;
  }

  patch() {
    this.expression.patch();
    if (this.hasImplicitDot()) {
      // `@a` → `@.a`
      //          ^
      this.insert(this.expression.after, '.');
    }
  }

  hasImplicitDot(): boolean {
    return !this.expression.hasTokenAfter('.');
  }

  getMemberName(): string {
    return this.node.memberName;
  }

  getMemberNameToken(): Token {
    let tokenOffset = this.hasImplicitDot() ? /* NAME */ 1 : /* DOT NAME */ 2;
    return this.context.tokenAtIndex(this.expression.afterTokenIndex + tokenOffset);
  }

  /**
   * Member access is repeatable (in CoffeeScript) if the expression we're
   * accessing a member of is also repeatable. Technically speaking even this is
   * not safe since member access can have side-effects via getters and setters,
   * but this is the way the official CoffeeScript compiler works so we follow
   * suit.
   */
  isRepeatable(): boolean {
    return this.expression.isRepeatable();
  }

  /**
   * We can make member accesses repeatable by making the base expression
   * repeatable if it isn't already.
   */
  makeRepeatable(parens: boolean, ref: ?string=null) {
    if (this.isRepeatable()) {
      return super.makeRepeatable(parens, ref);
    } else {
      let expression = this.expression.makeRepeatable(true, 'base');
      return `${expression}.${this.getMemberName()}`;
    }
  }
}
<commit_msg>Override each patch method individually for better subclassing.<commit_after>import NodePatcher from './NodePatcher';
import type { Node, ParseContext, Editor, Token } from './types';

export default class MemberAccessOpPatcher extends NodePatcher {
  constructor(node: Node, context: ParseContext, editor: Editor, expression: NodePatcher) {
    super(node, context, editor);
    this.expression = expression;
  }

  patchAsExpression() {
    this.expression.patch();
    if (this.hasImplicitDot()) {
      // `@a` → `@.a`
      //          ^
      this.insert(this.expression.after, '.');
    }
  }

  patchAsStatement() {
    this.patchAsExpression();
  }

  hasImplicitDot(): boolean {
    return !this.expression.hasTokenAfter('.');
  }

  getMemberName(): string {
    return this.node.memberName;
  }

  getMemberNameToken(): Token {
    let tokenOffset = this.hasImplicitDot() ? /* NAME */ 1 : /* DOT NAME */ 2;
    return this.context.tokenAtIndex(this.expression.afterTokenIndex + tokenOffset);
  }

  /**
   * Member access is repeatable (in CoffeeScript) if the expression we're
   * accessing a member of is also repeatable. Technically speaking even this is
   * not safe since member access can have side-effects via getters and setters,
   * but this is the way the official CoffeeScript compiler works so we follow
   * suit.
   */
  isRepeatable(): boolean {
    return this.expression.isRepeatable();
  }

  /**
   * We can make member accesses repeatable by making the base expression
   * repeatable if it isn't already.
   */
  makeRepeatable(parens: boolean, ref: ?string=null) {
    if (this.isRepeatable()) {
      return super.makeRepeatable(parens, ref);
    } else {
      let expression = this.expression.makeRepeatable(true, 'base');
      return `${expression}.${this.getMemberName()}`;
    }
  }
}
<|endoftext|>


<commit_before>import path from 'path';
import CopyWebpackPlugin from 'copy-webpack-plugin';

let devConfig = {
    context: path.join(__dirname, 'app'),
    entry: [
        './app.js'
    ],
    output: {
        path: path.join(__dirname, 'build/assets/js'),
        publicPath: 'assets/js/',
        filename: 'app.js',
    },
    devtool: 'eval-source-map',
    devServer: {
        contentBase: 'public',
        historyApiFallback: false
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                loaders: ['style', 'css']
            },
            {
                test: /\.scss$/,
                exclude: /node_modules/,
                loaders: ['style', 'css', 'sass']
            },
            {
                test: /\.(jpg|png|ttf|eot|woff|woff2|svg)$/,
                exclude: /node_modules/,
                loader: 'url?limit=100000'
            }
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            // { from: '../public/**/*', to: '../build/*' }
            { from: '../public', to: '/build' },
        ])
    ]
}

if (process.env.NODE_ENV === 'production') {
    devConfig.devtool = '';
    devConfig.devServer = {};
};

export default devConfig;
<commit_msg>Remove useless comments from webpack.config.babel.js<commit_after>import path from 'path';
import CopyWebpackPlugin from 'copy-webpack-plugin';

let devConfig = {
    context: path.join(__dirname, 'app'),
    entry: [
        './app.js'
    ],
    output: {
        path: path.join(__dirname, 'build/assets/js'),
        publicPath: 'assets/js/',
        filename: 'app.js',
    },
    devtool: 'eval-source-map',
    devServer: {
        contentBase: 'public',
        historyApiFallback: false
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel',
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                loaders: ['style', 'css']
            },
            {
                test: /\.scss$/,
                exclude: /node_modules/,
                loaders: ['style', 'css', 'sass']
            },
            {
                test: /\.(jpg|png|ttf|eot|woff|woff2|svg)$/,
                exclude: /node_modules/,
                loader: 'url?limit=100000'
            }
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from: '../public',
                to: '/build'
            }
        ])
    ]
}

if (process.env.NODE_ENV === 'production') {
    devConfig.devtool = '';
    devConfig.devServer = {};
};

export default devConfig;
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

I18n.scoped('page_views', function(I18n) {
(function($, INST){
  $(document).ready(function(){
    var interactionSeconds = 0,
        $page_view_id = $("#page_view_id"),
        update_url = $("#page_view_update_path").attr('href'),
        eventInTime = false;

    INST.interaction_contexts = {};

    if(document.cookie && document.cookie.match(/last_page_view/)) {
      var match = document.cookie.match(/last_page_view=([^;]+)/);
      if(match && match[1]) {
        try {
          var data = $.parseJSON(unescape(match[1]));
          if(data && data.url && data.seconds) {
            setTimeout(function() {
              $.ajaxJSON(data.url, "PUT", {interaction_seconds: data.seconds}, function() {
              }, function() {}, 3000);
            });
          }
        } catch(e) {
        }
      }
      document.cookie = "last_page_view=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
    if($page_view_id.length > 0) {
      var secondsSinceLastEvent = 0;
      var intervalInSeconds = 60*5;
      $(document).bind('page_view_id_received', function(event, id) {
        $("#page_view_id").text(id);
        update_url = "/page_views/" + id;
      });
      $(document).bind('page_view_update', function(event, force) {
        var data = {};
        if($page_view_id.hasClass('contributed')) {
          data.contributed = true;
        }

        if(force || (interactionSeconds > 10 && secondsSinceLastEvent < intervalInSeconds)) {
          data.interaction_seconds = interactionSeconds;
          $.ajaxJSON(update_url, "PUT", data, function(resultData) {
            if(resultData && resultData.id) {
              $(document).triggerHandler('page_view_id_receved', resultData.id);
            }
          }, function() {});
          interactionSeconds = 0;
        }
      });
      setInterval(function() {
        $(document).triggerHandler('page_view_update');
      }, 1000*intervalInSeconds);
      window.onbeforeunload = function() {
        if(interactionSeconds > 30) {
          var exdate=new Date();
          exdate.setDate(exdate.getDate()+1);
          var value = JSON.stringify({url: update_url, seconds: interactionSeconds});
          document.cookie="last_page_view=" +escape(value);
        }
      };

      var eventInTime = false;
      $(document).bind('mousemove keypress mousedown focus', function() {
        eventInTime = true;
      });
      setInterval(function() {
        if(eventInTime) {
          interactionSeconds++;
          if(INST && INST.interaction_context && INST.interaction_contexts) {
            INST.interaction_contexts[INST.interaction_context] = (INST.interaction_contexts[INST.interaction_context] || 0) + 1;
          }
          eventInTime = false;
          if(secondsSinceLastEvent >= intervalInSeconds) {
            secondsSinceLastEvent = 0;
            $(document).triggerHandler('page_view_update');
          }
          secondsSinceLastEvent = 0;
        } else {
          secondsSinceLastEvent++;
        }
      }, 1000);
    }
  });
})(jQuery, INST);
})
<commit_msg>fix js files to not error when minified<commit_after>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

I18n.scoped('page_views', function(I18n) {
(function($, INST){
  $(document).ready(function(){
    var interactionSeconds = 0,
        $page_view_id = $("#page_view_id"),
        update_url = $("#page_view_update_path").attr('href'),
        eventInTime = false;

    INST.interaction_contexts = {};

    if(document.cookie && document.cookie.match(/last_page_view/)) {
      var match = document.cookie.match(/last_page_view=([^;]+)/);
      if(match && match[1]) {
        try {
          var data = $.parseJSON(unescape(match[1]));
          if(data && data.url && data.seconds) {
            setTimeout(function() {
              $.ajaxJSON(data.url, "PUT", {interaction_seconds: data.seconds}, function() {
              }, function() {}, 3000);
            });
          }
        } catch(e) {
        }
      }
      document.cookie = "last_page_view=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
    if($page_view_id.length > 0) {
      var secondsSinceLastEvent = 0;
      var intervalInSeconds = 60*5;
      $(document).bind('page_view_id_received', function(event, id) {
        $("#page_view_id").text(id);
        update_url = "/page_views/" + id;
      });
      $(document).bind('page_view_update', function(event, force) {
        var data = {};
        if($page_view_id.hasClass('contributed')) {
          data.contributed = true;
        }

        if(force || (interactionSeconds > 10 && secondsSinceLastEvent < intervalInSeconds)) {
          data.interaction_seconds = interactionSeconds;
          $.ajaxJSON(update_url, "PUT", data, function(resultData) {
            if(resultData && resultData.id) {
              $(document).triggerHandler('page_view_id_receved', resultData.id);
            }
          }, function() {});
          interactionSeconds = 0;
        }
      });
      setInterval(function() {
        $(document).triggerHandler('page_view_update');
      }, 1000*intervalInSeconds);
      window.onbeforeunload = function() {
        if(interactionSeconds > 30) {
          var exdate=new Date();
          exdate.setDate(exdate.getDate()+1);
          var value = JSON.stringify({url: update_url, seconds: interactionSeconds});
          document.cookie="last_page_view=" +escape(value);
        }
      };

      var eventInTime = false;
      $(document).bind('mousemove keypress mousedown focus', function() {
        eventInTime = true;
      });
      setInterval(function() {
        if(eventInTime) {
          interactionSeconds++;
          if(INST && INST.interaction_context && INST.interaction_contexts) {
            INST.interaction_contexts[INST.interaction_context] = (INST.interaction_contexts[INST.interaction_context] || 0) + 1;
          }
          eventInTime = false;
          if(secondsSinceLastEvent >= intervalInSeconds) {
            secondsSinceLastEvent = 0;
            $(document).triggerHandler('page_view_update');
          }
          secondsSinceLastEvent = 0;
        } else {
          secondsSinceLastEvent++;
        }
      }, 1000);
    }
  });
})(jQuery, INST);
});
<|endoftext|>


<commit_before>import 'ui/angular-bootstrap';
import 'plugins/kibana-time-plugin/lib/angular-bootstrap/css/btn-group.less';
import 'plugins/kibana-time-plugin/lib/angular-bootstrap/css/carousel.less';
import 'plugins/kibana-time-plugin/lib/angular-bootstrap/js/carousel.js';
import 'plugins/kibana-time-plugin/bower_components/bootstrap-addons/dist/css/bootstrap-addons.css';
import 'plugins/kibana-time-plugin/bower_components/bootstrap-addons/dist/js/bootstrap-addons.js';
import 'plugins/kibana-time-plugin/time.less';
import 'plugins/kibana-time-plugin/timeController';
import { VisFactoryProvider } from 'ui/vis/vis_factory';
import { CATEGORY } from 'ui/vis/vis_category';
import { VisTypesRegistryProvider } from 'ui/registry/vis_types';
import visTemplate from 'plugins/kibana-time-plugin/time.html';
import optionsTemplate from 'plugins/kibana-time-plugin/timeOptions.html';

VisTypesRegistryProvider.register(TimeVisProvider);

function TimeVisProvider(Private) {
  const VisFactory = Private(VisFactoryProvider);

  return VisFactory.createAngularVisualization({
    name: 'time',
    title: 'Time widget',
    icon: 'fa-clock-o',
    description: 'Add time inputs to your dashboards.',
    category: CATEGORY.OTHER,
    visConfig: {
      template: visTemplate,
      defaults: {
          enable_quick: true,
          enable_relative: true,
          enable_absolut: true,
          enable_animation: true,
      }
    },
    editorConfig: {
      optionsTemplate: optionsTemplate
    },
    requestHandler: 'none',
    responseHandler: 'none'
  });
}
<commit_msg>6.6 - Removal of category from visualization<commit_after>import 'ui/angular-bootstrap';
import 'plugins/kibana-time-plugin/lib/angular-bootstrap/css/btn-group.less';
import 'plugins/kibana-time-plugin/lib/angular-bootstrap/css/carousel.less';
import 'plugins/kibana-time-plugin/lib/angular-bootstrap/js/carousel.js';
import 'plugins/kibana-time-plugin/bower_components/bootstrap-addons/dist/css/bootstrap-addons.css';
import 'plugins/kibana-time-plugin/bower_components/bootstrap-addons/dist/js/bootstrap-addons.js';
import 'plugins/kibana-time-plugin/time.less';
import 'plugins/kibana-time-plugin/timeController';
import { VisFactoryProvider } from 'ui/vis/vis_factory';
import { VisTypesRegistryProvider } from 'ui/registry/vis_types';
import visTemplate from 'plugins/kibana-time-plugin/time.html';
import optionsTemplate from 'plugins/kibana-time-plugin/timeOptions.html';

VisTypesRegistryProvider.register(TimeVisProvider);

function TimeVisProvider(Private) {
  const VisFactory = Private(VisFactoryProvider);

  return VisFactory.createAngularVisualization({
    name: 'time',
    title: 'Time widget',
    icon: 'fa-clock-o',
    description: 'Add time inputs to your dashboards.',
    visConfig: {
      template: visTemplate,
      defaults: {
          enable_quick: true,
          enable_relative: true,
          enable_absolut: true,
          enable_animation: true,
      }
    },
    editorConfig: {
      optionsTemplate: optionsTemplate
    },
    requestHandler: 'none',
    responseHandler: 'none'
  });
}
<|endoftext|>


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

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SystemBellPlugin from 'system-bell-webpack-plugin';
import Clean from 'clean-webpack-plugin';
import merge from 'webpack-merge';
import React from 'react';
import ReactDOM from 'react-dom/server';

import renderJSX from './lib/render.jsx';
import App from './demo/App.jsx';
import pkg from './package.json';

const RENDER_UNIVERSAL = true;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = __dirname;
const config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, 'demo'),
    tests: path.join(ROOT_PATH, 'tests')
  },
  filename: 'boilerplate',
  library: 'Boilerplate'
};
const CSS_PATHS = [
  config.paths.demo,
  path.join(ROOT_PATH, 'style.css'),
  path.join(ROOT_PATH, 'node_modules/purecss'),
  path.join(ROOT_PATH, 'node_modules/highlight.js/styles/github.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.ie.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.css')
];

process.env.BABEL_ENV = TARGET;

const demoCommon = {
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg']
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.demo,
          config.paths.src
        ]
      }
    ],
    loaders: [
      {
        test: /\.png$/,
        loader: 'url?limit=100000&mimetype=image/png',
        include: config.paths.demo
      },
      {
        test: /\.jpg$/,
        loader: 'file',
        include: config.paths.demo
      },
      {
        test: /\.json$/,
        loader: 'json',
        include: path.join(ROOT_PATH, 'package.json')
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'start') {
  module.exports = merge(demoCommon, {
    devtool: 'eval-source-map',
    entry: config.paths.demo,
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"development"'
      }),
      new HtmlWebpackPlugin(Object.assign({}, {
        title: pkg.name + ' - ' + pkg.description,
        template: 'lib/index_template.ejs',

        inject: false
      }, renderJSX(__dirname, pkg))),
      new webpack.HotModuleReplacementPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css'],
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      host: process.env.HOST,
      port: process.env.PORT,
      stats: 'errors-only'
    }
  });
}

function NamedModulesPlugin(options) {
  this.options = options || {};
}
NamedModulesPlugin.prototype.apply = function(compiler) {
  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('before-module-ids', function(modules) {
      modules.forEach(function(module) {
        if(module.id === null && module.libIdent) {
          var id = module.libIdent({
            context: this.options.context || compiler.options.context
          });

          // Skip CSS files since those go through ExtractTextPlugin
          if(!id.endsWith('.css')) {
            module.id = id;
          }
        }
      }, this);
    }.bind(this));
  }.bind(this));
};

if (TARGET === 'gh-pages' || TARGET === 'gh-pages:stats') {
  module.exports = merge(demoCommon, {
    entry: {
      app: config.paths.demo,
      vendors: [
        'react'
      ],
      style: [
        'purecss',
        'highlight.js/styles/github.css',
        'react-ghfork/gh-fork-ribbon.ie.css',
        'react-ghfork/gh-fork-ribbon.css',
        './demo/main.css',
        './style.css'
      ]
    },
    output: {
      path: './gh-pages',
      filename: '[name].[chunkhash].js',
      chunkFilename: '[chunkhash].js'
    },
    plugins: [
      new Clean(['gh-pages'], {
        verbose: false
      }),
      new ExtractTextPlugin('[name].[chunkhash].css'),
      new webpack.DefinePlugin({
          // This affects the react lib size
        'process.env.NODE_ENV': '"production"'
      }),
      new HtmlWebpackPlugin(Object.assign({}, {
        title: pkg.name + ' - ' + pkg.description,
        template: 'lib/index_template.ejs',
        inject: false
      }, renderJSX(
        __dirname, pkg, RENDER_UNIVERSAL ? ReactDOM.renderToString(<App />) : '')
      )),
      new NamedModulesPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendors', 'manifest']
      })
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    }
  });
}

// !TARGET === prepush hook for test
if (TARGET === 'test' || TARGET === 'test:tdd' || !TARGET) {
  module.exports = merge(demoCommon, {
    module: {
      preLoaders: [
        {
          test: /\.jsx?$/,
          loaders: ['eslint'],
          include: [
            config.paths.tests
          ]
        }
      ],
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.src,
            config.paths.tests
          ]
        }
      ]
    }
  })
}

const distCommon = {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library
  },
  entry: config.paths.src,
  externals: {
    'react': {
        commonjs: 'react',
        commonjs2: 'react',
        amd: 'React',
        root: 'React'
    }
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'dist') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.js'
    }
  });
}

if (TARGET === 'dist:min') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.min.js'
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      })
    ]
  });
}
<commit_msg>Make styling work in development mode<commit_after>import * as path from 'path';

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SystemBellPlugin from 'system-bell-webpack-plugin';
import Clean from 'clean-webpack-plugin';
import merge from 'webpack-merge';
import React from 'react';
import ReactDOM from 'react-dom/server';

import renderJSX from './lib/render.jsx';
import App from './demo/App.jsx';
import pkg from './package.json';

const RENDER_UNIVERSAL = true;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = __dirname;
const config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, 'demo'),
    tests: path.join(ROOT_PATH, 'tests')
  },
  filename: 'boilerplate',
  library: 'Boilerplate'
};
const CSS_PATHS = [
  config.paths.demo,
  path.join(ROOT_PATH, 'style.css'),
  path.join(ROOT_PATH, 'node_modules/purecss'),
  path.join(ROOT_PATH, 'node_modules/highlight.js/styles/github.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.ie.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.css')
];
const STYLE_ENTRIES = [
  'purecss',
  'highlight.js/styles/github.css',
  'react-ghfork/gh-fork-ribbon.ie.css',
  'react-ghfork/gh-fork-ribbon.css',
  './demo/main.css',
  './style.css'
];

process.env.BABEL_ENV = TARGET;

const demoCommon = {
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg']
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.demo,
          config.paths.src
        ]
      }
    ],
    loaders: [
      {
        test: /\.png$/,
        loader: 'url?limit=100000&mimetype=image/png',
        include: config.paths.demo
      },
      {
        test: /\.jpg$/,
        loader: 'file',
        include: config.paths.demo
      },
      {
        test: /\.json$/,
        loader: 'json',
        include: path.join(ROOT_PATH, 'package.json')
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'start') {
  module.exports = merge(demoCommon, {
    devtool: 'eval-source-map',
    entry: {
      demo: [config.paths.demo].concat(STYLE_ENTRIES)
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"development"'
      }),
      new HtmlWebpackPlugin(Object.assign({}, {
        title: pkg.name + ' - ' + pkg.description,
        template: 'lib/index_template.ejs',

        inject: false
      }, renderJSX(__dirname, pkg))),
      new webpack.HotModuleReplacementPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css'],
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      host: process.env.HOST,
      port: process.env.PORT,
      stats: 'errors-only'
    }
  });
}

function NamedModulesPlugin(options) {
  this.options = options || {};
}
NamedModulesPlugin.prototype.apply = function(compiler) {
  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('before-module-ids', function(modules) {
      modules.forEach(function(module) {
        if(module.id === null && module.libIdent) {
          var id = module.libIdent({
            context: this.options.context || compiler.options.context
          });

          // Skip CSS files since those go through ExtractTextPlugin
          if(!id.endsWith('.css')) {
            module.id = id;
          }
        }
      }, this);
    }.bind(this));
  }.bind(this));
};

if (TARGET === 'gh-pages' || TARGET === 'gh-pages:stats') {
  module.exports = merge(demoCommon, {
    entry: {
      app: config.paths.demo,
      vendors: [
        'react'
      ],
      style: STYLE_ENTRIES
    },
    output: {
      path: './gh-pages',
      filename: '[name].[chunkhash].js',
      chunkFilename: '[chunkhash].js'
    },
    plugins: [
      new Clean(['gh-pages'], {
        verbose: false
      }),
      new ExtractTextPlugin('[name].[chunkhash].css'),
      new webpack.DefinePlugin({
          // This affects the react lib size
        'process.env.NODE_ENV': '"production"'
      }),
      new HtmlWebpackPlugin(Object.assign({}, {
        title: pkg.name + ' - ' + pkg.description,
        template: 'lib/index_template.ejs',
        inject: false
      }, renderJSX(
        __dirname, pkg, RENDER_UNIVERSAL ? ReactDOM.renderToString(<App />) : '')
      )),
      new NamedModulesPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendors', 'manifest']
      })
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    }
  });
}

// !TARGET === prepush hook for test
if (TARGET === 'test' || TARGET === 'test:tdd' || !TARGET) {
  module.exports = merge(demoCommon, {
    module: {
      preLoaders: [
        {
          test: /\.jsx?$/,
          loaders: ['eslint'],
          include: [
            config.paths.tests
          ]
        }
      ],
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.src,
            config.paths.tests
          ]
        }
      ]
    }
  })
}

const distCommon = {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library
  },
  entry: config.paths.src,
  externals: {
    'react': {
        commonjs: 'react',
        commonjs2: 'react',
        amd: 'React',
        root: 'React'
    }
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'dist') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.js'
    }
  });
}

if (TARGET === 'dist:min') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.min.js'
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      })
    ]
  });
}
<|endoftext|>


<commit_before>import {join} from 'path'

const config =
  { devtool: 'cheap-module-source-map'
  , devServer:
    { contentBase: './dist'
    }
  , entry:
    [ './src/index.js'
    ]
  , resolve:
    { extensions:
      [ ''
      , '.js'
      ]
    }
  , module:
    { loaders:
      [ { test: /\.js/
        , exclude: /node_modules/
        , loaders:
          [ 'babel'
          ]
        }
      ]
    }
  , output:
    { path: join(__dirname, 'lib')
    , publicPath: '/'
    , filename: 'bundle.js'
    }
  }

export default config
<commit_msg>chore(webpack): target node<commit_after>import {join} from 'path'

const config =
  { devtool: 'cheap-module-source-map'
  , devServer:
    { contentBase: './dist'
    }
  , entry:
    [ './src/index.js'
    ]
  , resolve:
    { extensions:
      [ ''
      , '.js'
      ]
    }
  , module:
    { loaders:
      [ { test: /\.js/
        , exclude: /node_modules/
        , loaders:
          [ 'babel'
          ]
        }
      ]
    }
  , output:
    { path: join(__dirname, 'lib')
    , publicPath: '/'
    , filename: 'bundle.js'
    }
  , target: 'electron'
  }

export default config
<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import OptimizeCssAssetsWebpackPlugin from 'optimize-css-assets-webpack-plugin';
import PwaManifestPlugin from 'webpack-pwa-manifest';
import WorkboxWebpackPlugin from 'workbox-webpack-plugin';
import PreloadWebpackPlugin from 'preload-webpack-plugin';

const NODE_ENV = process.env.NODE_ENV || 'development';

export default {
    entry: path.resolve(__dirname, 'source/index.js'),

    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: '/',
        filename: 'index.[hash].js'
    },

    mode: NODE_ENV,

    module: {
        rules: [ {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader']
        }, {
            test: /\.(png|webp|woff2?)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[hash].[ext]'
            }
        } ]
    },

    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
        }),

        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'source/index.html'),
            data: {
                projects: require('./data/projects.json'),
                articles: require('./data/articles.json'),
                events: require('./data/events.json')
            },
            baseUrl: process.env.BASE_URL || 'https://arnellebalane.com',
            minify: {
                collapseBooleanAttributes: true,
                collapseWhitespace: true
            }
        }),

        new PreloadWebpackPlugin(),

        new MiniCssExtractPlugin({
            filename: 'index.[hash].css'
        }),

        new OptimizeCssAssetsWebpackPlugin({
            assetNameRegExp: /\.css$/
        }),

        new PwaManifestPlugin({
            filename: '[name].[hash][ext]',
            name: 'Arnelle Balane',
            short_name: 'arnelle',
            description: 'Arnelle\'s Personal Website',
            icons: [ {
                src: path.resolve(__dirname, 'source/images/icon-512.png'),
                sizes: [16, 144, 192, 200, 512]
            } ],
            theme_color: '#ffeb3b',
            background_color: '#ffffff',
            display: 'fullscreen',
            start_url: '/',
            scope: '/'
        }),

        new WorkboxWebpackPlugin.GenerateSW({
            swDest: 'sw.js',
            skipWaiting: true,
            clientsClaim: true
        })
    ]
};
<commit_msg>html-webpack-plugin dont include any chunks and minify css<commit_after>import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import OptimizeCssAssetsWebpackPlugin from 'optimize-css-assets-webpack-plugin';
import PwaManifestPlugin from 'webpack-pwa-manifest';
import WorkboxWebpackPlugin from 'workbox-webpack-plugin';
import PreloadWebpackPlugin from 'preload-webpack-plugin';

const NODE_ENV = process.env.NODE_ENV || 'development';
const isProdEnv = NODE_ENV === 'production';

export default {
    entry: path.resolve(__dirname, 'source/index.js'),

    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: '/',
        filename: 'index.[hash].js'
    },

    mode: NODE_ENV,

    module: {
        rules: [ {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader']
        }, {
            test: /\.(png|webp|woff2?)$/,
            loader: 'file-loader',
            options: {
                name: '[name].[hash].[ext]'
            }
        } ]
    },

    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
        }),

        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, 'source/index.html'),
            data: {
                projects: require('./data/projects.json'),
                articles: require('./data/articles.json'),
                events: require('./data/events.json')
            },
            baseUrl: process.env.BASE_URL || 'https://arnellebalane.com',
            minify: {
                collapseBooleanAttributes: isProdEnv,
                collapseWhitespace: isProdEnv,
                minifyCSS: isProdEnv
            },
            chunks: []
        }),

        new PreloadWebpackPlugin(),

        new MiniCssExtractPlugin({
            filename: 'index.[hash].css'
        }),

        new OptimizeCssAssetsWebpackPlugin({
            assetNameRegExp: /\.css$/
        }),

        new PwaManifestPlugin({
            filename: '[name].[hash][ext]',
            name: 'Arnelle Balane',
            short_name: 'arnelle',
            description: 'Arnelle\'s Personal Website',
            icons: [ {
                src: path.resolve(__dirname, 'source/images/icon-512.png'),
                sizes: [16, 144, 192, 200, 512]
            } ],
            theme_color: '#ffeb3b',
            background_color: '#ffffff',
            display: 'fullscreen',
            start_url: '/',
            scope: '/'
        }),

        new WorkboxWebpackPlugin.GenerateSW({
            swDest: 'sw.js',
            skipWaiting: true,
            clientsClaim: true
        })
    ]
};
<|endoftext|>


<commit_before>
var cacheName = '20180726a';

var cacheFilesFirst = [
  '/',
  '/favicon.ico',
  '/assets/default.css',
  '/assets/ohjaaja-jukka.jpg',
  '/assets/ohjaaja-kari.jpg',
  '/assets/ohjaaja-kimmo.jpg',
  '/assets/ohjaaja-aaro.jpg',
  '/assets/rkhsk-logo.png',
  '/assets/rkhsk-nunchaku-754.png',
  '/assets/yuishinkai-logo.png'
];
var cacheFilesSoon = [
  '/assets/ohjaaja-jukka-300.jpg',
  '/assets/ohjaaja-kari-300.jpg',
  '/assets/ohjaaja-kimmo-300.jpg',
  '/assets/ohjaaja-aaro-300.jpg',
  '/assets/rkhsk-nunchaku-1507.png',
  '/assets/rkhsk-nunchaku-square-1024.png'
];

this.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      cache.addAll(cacheFilesSoon);
      return cache.addAll(cacheFilesFirst);
    }).catch(function(error) {
      console.error('Getting everything in cache failed.');
      console.error(error);
    })
  );
});

// Primarily use cache but fetch from the network when not found
this.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    }).catch(function(error) {
      console.error('Matching request from cache or network failed.');
      console.error(error);
    })
  );
});

// Remove any caches that are not the current
this.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(list) {
      return Promise.all(list.filter(function(key) {
        return key !== cacheName;
      }).map(function(key) {
        return caches.delete(key);
      }));
    }).catch(function(error) {
      console.error('Cleaning up older cache failed.');
      console.error(error);
    })
  );
});

this.addEventListener('backgroundfetched', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {

      const promises = event.fetches.map(({ request, response }) => {
        if (response && response.ok) {
          return cache.put(request, response.clone());
        }
      });

      return Promise.all(promises);
    }).catch(function(error) {
      console.error('Fetching in background failed.');
      console.error(error);
    })
  );
});
<commit_msg>Do not include html since I have no time to focus on making special case for it<commit_after>
var cacheName = '20180726b';

var cacheFilesFirst = [
  // '/',
  '/favicon.ico',
  '/assets/default.css',
  '/assets/ohjaaja-jukka.jpg',
  '/assets/ohjaaja-kari.jpg',
  '/assets/ohjaaja-kimmo.jpg',
  '/assets/ohjaaja-aaro.jpg',
  '/assets/rkhsk-logo.png',
  '/assets/rkhsk-nunchaku-754.png',
  '/assets/yuishinkai-logo.png'
];
var cacheFilesSoon = [
  '/assets/ohjaaja-jukka-300.jpg',
  '/assets/ohjaaja-kari-300.jpg',
  '/assets/ohjaaja-kimmo-300.jpg',
  '/assets/ohjaaja-aaro-300.jpg',
  '/assets/rkhsk-nunchaku-1507.png',
  '/assets/rkhsk-nunchaku-square-1024.png'
];

this.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      cache.addAll(cacheFilesSoon);
      return cache.addAll(cacheFilesFirst);
    }).catch(function(error) {
      console.error('Getting everything in cache failed.');
      console.error(error);
    })
  );
});

// Primarily use cache but fetch from the network when not found
this.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    }).catch(function(error) {
      console.error('Matching request from cache or network failed.');
      console.error(error);
    })
  );
});

// Remove any caches that are not the current
this.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(list) {
      return Promise.all(list.filter(function(key) {
        return key !== cacheName;
      }).map(function(key) {
        return caches.delete(key);
      }));
    }).catch(function(error) {
      console.error('Cleaning up older cache failed.');
      console.error(error);
    })
  );
});

this.addEventListener('backgroundfetched', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {

      const promises = event.fetches.map(({ request, response }) => {
        if (response && response.ok) {
          return cache.put(request, response.clone());
        }
      });

      return Promise.all(promises);
    }).catch(function(error) {
      console.error('Fetching in background failed.');
      console.error(error);
    })
  );
});
<|endoftext|>


<commit_before>// Includes file dependencies
define([
], function () {

    var ConfigPubstorm = {
        serverURL: "https://api.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://yorick.pubstorm.site/index.html"
    };

    var ConfigPatron = {
        serverURL: "https://api.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://patron.undergroundtheater.org"
    };

    var ConfigLocalhost = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost/index.html"
    };

    var ConfigGnuLorienDev = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost:63342/yorick/public/index.html",
        SAMPLE_TROUPE_ID: "k7zf9B7bwV"
    };

    var Config = {
        serverURL: "https://yorick-undergroundtheater-gnu-lorien.c9users.io/parse",
        redirect_uri: "https://yorick-undergroundtheater-gnu-lorien.c9users.io/index.html",
        SAMPLE_TROUPE_ID: "zCQcZnlFx5"
    };

    return Config;
    //return ConfigPatron;

});
<commit_msg>Set up netlify for custom staging domain<commit_after>// Includes file dependencies
define([
], function () {

    var ConfigPubstorm = {
        serverURL: "https://stagingapi.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://stagingpatron.undergroundtheater.org/index.html"
    };

    var ConfigPatron = {
        serverURL: "https://api.undergroundtheater.org/parse",
        facebookAppId: "1606746326305984",
        redirect_uri: "https://patron.undergroundtheater.org"
    };

    var ConfigLocalhost = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost/index.html"
    };

    var ConfigOldGnuLorienDev = {
        serverURL: "http://localhost:1337/parse",
        facebookAppId: "1607159299598020",
        redirect_uri: "http://localhost:63342/yorick/public/index.html",
        SAMPLE_TROUPE_ID: "k7zf9B7bwV"
    };

    var ConfigGnuLorienDev = {
        serverURL: "https://yorick-undergroundtheater-gnu-lorien.c9users.io/parse",
        redirect_uri: "https://yorick-undergroundtheater-gnu-lorien.c9users.io/index.html",
        SAMPLE_TROUPE_ID: "zCQcZnlFx5"
    };

    return ConfigGnuLorienDev;

});
<|endoftext|>


<commit_before>/**
 * Blockly Apps: Code
 *
 * Copyright 2012 Google Inc.
 * http://blockly.googlecode.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview JavaScript for Blockly Lua's Code application.
 * @author fraser@google.com (Neil Fraser)
 */

/**
 * Create a namespace for the application.
 */
var Code = {};

/**
 * List of tab names.
 * @private
 */
Code.TABS_ = ['blocks', 'lua', 'xml'];

Code.selected = 'blocks';

/**
 * Switch the visible pane when a tab is clicked.
 * @param {string} id ID of tab clicked.
 */
Code.tabClick = function(id) {
  // If the XML tab was open, save and render the content.
  if (document.getElementById('tab_xml').className == 'tabon') {
    var xmlTextarea = document.getElementById('content_xml');
    var xmlText = xmlTextarea.value;
    var xmlDom = null;
    try {
      xmlDom = Blockly.Xml.textToDom(xmlText);
    } catch (e) {
      var q =
          window.confirm(
              "Error parsing XML:\n%1\n\nSelect 'OK' to abandon your changes or 'Cancel' to further edit the XML.".replace('%1', e));
      if (!q) {
        // Leave the user on the XML tab.
        return;
      }
    }
    if (xmlDom) {
      Blockly.mainWorkspace.clear();
      Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xmlDom);
    }
  }

  // Deselect all tabs and hide all panes.
  for (var x in Code.TABS_) {
    var name = Code.TABS_[x];
    document.getElementById('tab_' + name).className = 'taboff';
    document.getElementById('content_' + name).style.visibility = 'hidden';
  }

  // Select the active tab.
  Code.selected = id.replace('tab_', '');
  document.getElementById(id).className = 'tabon';
  // Show the selected pane.
  document.getElementById('content_' + Code.selected).style.visibility =
      'visible';
  Code.renderContent();
  Blockly.fireUiEvent(window, 'resize');
};

/**
 * Populate the currently selected pane with content generated from the blocks.
 */
Code.renderContent = function() {
  var content = document.getElementById('content_' + Code.selected);
  // Initialize the pane.
  if (content.id == 'content_xml') {
    var xmlTextarea = document.getElementById('content_xml');
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    xmlTextarea.value = xmlText;
    xmlTextarea.focus();
  } else if (content.id == 'content_lua') {
    var code = Blockly.Lua.workspaceToCode();
    content.textContent = code;
    if (typeof prettyPrintOne == 'function') {
      code = content.innerHTML;
      code = prettyPrintOne(code, 'lang-lua');
      content.innerHTML = code;
    }
  }
};

/**
 * Initialize Blockly.  Called on page load.
 */
Code.init = function() {
  BlocklyApps.init();

  var toolbox = document.getElementById('toolbox');
  Blockly.inject(document.getElementById('content_blocks'),
      {path: '../../',
       toolbox: toolbox});

  var container = document.getElementById('content_area');
  var onresize = function(e) {
    var bBox = BlocklyApps.getBBox_(container);
    for (var x in Code.TABS_) {
      var el = document.getElementById('content_' + Code.TABS_[x]);
      el.style.top = bBox.y + 'px';
      el.style.left = bBox.x + 'px';
      // Height and width need to be set, read back, then set again to
      // compensate for scrollbars.
      el.style.height = bBox.height + 'px';
      el.style.height = (2 * bBox.height - el.offsetHeight) + 'px';
      el.style.width = bBox.width + 'px';
      el.style.width = (2 * bBox.width - el.offsetWidth) + 'px';
    }
    // Make the 'Blocks' tab line up with the toolbox.
    if (Blockly.Toolbox.width) {
      document.getElementById('tab_blocks').style.minWidth =
          (Blockly.Toolbox.width - 38) + 'px';
          // Account for the 19 pixel margin and on each side.
    }
  };
  window.addEventListener('resize', onresize, false);

  BlocklyApps.loadBlocks('');

  if ('BlocklyStorage' in window) {
    // Hook a save function onto unload.
    BlocklyStorage.backupOnUnload();
  }

  Code.tabClick('tab_' + Code.selected);
  Blockly.fireUiEvent(window, 'resize');

  BlocklyApps.bindClick('trashButton',
      function() {Code.discard(); Code.renderContent();});
};

if (window.location.pathname.match(/readonly.html$/)) {
  window.addEventListener('load', BlocklyApps.initReadonly);
} else {
  window.addEventListener('load', Code.init);
}

/**
 * Discard all blocks from the workspace.
 */
Code.discard = function() {
  var count = Blockly.mainWorkspace.getAllBlocks().length;
  if (count < 2 ||
      window.confirm("Error parsing XML:\n%1\n\nSelect 'OK' to abandon your changes or 'Cancel' to further edit the XML.".replace('%1', count))) {
    Blockly.mainWorkspace.clear();
    window.location.hash = '';
  }
};
<commit_msg>Fixed message shown when user clicks on trash can.<commit_after>/**
 * Blockly Apps: Code
 *
 * Copyright 2012 Google Inc.
 * http://blockly.googlecode.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview JavaScript for Blockly Lua's Code application.
 * @author fraser@google.com (Neil Fraser)
 */

/**
 * Create a namespace for the application.
 */
var Code = {};

/**
 * List of tab names.
 * @private
 */
Code.TABS_ = ['blocks', 'lua', 'xml'];

Code.selected = 'blocks';

/**
 * Switch the visible pane when a tab is clicked.
 * @param {string} id ID of tab clicked.
 */
Code.tabClick = function(id) {
  // If the XML tab was open, save and render the content.
  if (document.getElementById('tab_xml').className == 'tabon') {
    var xmlTextarea = document.getElementById('content_xml');
    var xmlText = xmlTextarea.value;
    var xmlDom = null;
    try {
      xmlDom = Blockly.Xml.textToDom(xmlText);
    } catch (e) {
      var q =
          window.confirm(
              "Error parsing XML:\n%1\n\nSelect 'OK' to abandon your changes or 'Cancel' to further edit the XML.".replace('%1', e));
      if (!q) {
        // Leave the user on the XML tab.
        return;
      }
    }
    if (xmlDom) {
      Blockly.mainWorkspace.clear();
      Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xmlDom);
    }
  }

  // Deselect all tabs and hide all panes.
  for (var x in Code.TABS_) {
    var name = Code.TABS_[x];
    document.getElementById('tab_' + name).className = 'taboff';
    document.getElementById('content_' + name).style.visibility = 'hidden';
  }

  // Select the active tab.
  Code.selected = id.replace('tab_', '');
  document.getElementById(id).className = 'tabon';
  // Show the selected pane.
  document.getElementById('content_' + Code.selected).style.visibility =
      'visible';
  Code.renderContent();
  Blockly.fireUiEvent(window, 'resize');
};

/**
 * Populate the currently selected pane with content generated from the blocks.
 */
Code.renderContent = function() {
  var content = document.getElementById('content_' + Code.selected);
  // Initialize the pane.
  if (content.id == 'content_xml') {
    var xmlTextarea = document.getElementById('content_xml');
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    xmlTextarea.value = xmlText;
    xmlTextarea.focus();
  } else if (content.id == 'content_lua') {
    var code = Blockly.Lua.workspaceToCode();
    content.textContent = code;
    if (typeof prettyPrintOne == 'function') {
      code = content.innerHTML;
      code = prettyPrintOne(code, 'lang-lua');
      content.innerHTML = code;
    }
  }
};

/**
 * Initialize Blockly.  Called on page load.
 */
Code.init = function() {
  BlocklyApps.init();

  var toolbox = document.getElementById('toolbox');
  Blockly.inject(document.getElementById('content_blocks'),
      {path: '../../',
       toolbox: toolbox});

  var container = document.getElementById('content_area');
  var onresize = function(e) {
    var bBox = BlocklyApps.getBBox_(container);
    for (var x in Code.TABS_) {
      var el = document.getElementById('content_' + Code.TABS_[x]);
      el.style.top = bBox.y + 'px';
      el.style.left = bBox.x + 'px';
      // Height and width need to be set, read back, then set again to
      // compensate for scrollbars.
      el.style.height = bBox.height + 'px';
      el.style.height = (2 * bBox.height - el.offsetHeight) + 'px';
      el.style.width = bBox.width + 'px';
      el.style.width = (2 * bBox.width - el.offsetWidth) + 'px';
    }
    // Make the 'Blocks' tab line up with the toolbox.
    if (Blockly.Toolbox.width) {
      document.getElementById('tab_blocks').style.minWidth =
          (Blockly.Toolbox.width - 38) + 'px';
          // Account for the 19 pixel margin and on each side.
    }
  };
  window.addEventListener('resize', onresize, false);

  BlocklyApps.loadBlocks('');

  if ('BlocklyStorage' in window) {
    // Hook a save function onto unload.
    BlocklyStorage.backupOnUnload();
  }

  Code.tabClick('tab_' + Code.selected);
  Blockly.fireUiEvent(window, 'resize');

  BlocklyApps.bindClick('trashButton',
      function() {Code.discard(); Code.renderContent();});
};

if (window.location.pathname.match(/readonly.html$/)) {
  window.addEventListener('load', BlocklyApps.initReadonly);
} else {
  window.addEventListener('load', Code.init);
}

/**
 * Discard all blocks from the workspace.
 */
Code.discard = function() {
  var count = Blockly.mainWorkspace.getAllBlocks().length;
  if (count < 2 ||
      window.confirm("Delete all %1 blocks?".replace('%1', count))) {
    Blockly.mainWorkspace.clear();
    window.location.hash = '';
  }
};
<|endoftext|>


<commit_before>"use strict";<commit_msg>Almost finished with the game<commit_after>/* global -Promise */
var Promise = require("bluebird"),
    prompt = require('prompt'),
    _ = require('underscore');

// prompt.message = "";
// prompt.delimiter = "";
prompt.colors = false;
prompt.start();
var getPrompt = Promise.promisify(prompt.get);

var guessProperties = [{
    name: 'Guess',
    validator: /^[1-6]{4}$/,
    warning: 'Guess must be 4 digits between 1 and 6'
}];

function promptGuess(code, guesses, maxGuesses) {
    console.log("You have " + (maxGuesses - guesses) + " remaining tries to crack the code.");
    return getPrompt(guessProperties).then(function(input) {
        var guess = input.Guess;
        guesses++;

        var correct = isGuessCorrect(code, guess);
        if (correct || (!correct && guesses >= maxGuesses)) {
            return {
                correct: correct,
                guesses: guesses
            };
        } else {
            console.log("Your score is: " + calculateScore(code, guess) + "\n");
            return promptGuess(code, guesses, maxGuesses);
        }
    });
}

function mainLoop() {
    var guesses = 0,
        maxGuesses = 10,
        correct = false,
        code = createSecretCode();

    console.log(code);
    var codeString = _.reduce(code, function(memo, num) {
        memo + num;
    }, "");
    promptGuess(code, guesses, maxGuesses).then(function(result) {
        if (result.correct) {
            console.log("You solved it! Took " + result.guesses + " guesses.");
        } else {
            console.log("You lose :( The code was: " + codeString);
        }
    }).catch(function(error) {
        if (error.name == 'OperationalError') {
            console.log("Thanks for playing!");
        } else {
            console.error(error);
        }
    });
}

function isGuessCorrect(code, guess) {
    var correct = true;
    for (var i = 0; i < code.length; i++) {
        if (code[i] != guess[i]) {
            return false;
        }
    }
    return true;
}

function calculateScore(code, guess) {
    var matches = "",
        wrongPos = "",
        codeCopy = code.slice(0),
        guessCopy = _.map(guess.split(""), function(num) {
            return parseInt(num);
        });

    //Loop to check for exact matches
    for (var i = 0; i < guess.length; i++) {
        if (guess[i] == code[i]) {
            matches += "+";
            codeCopy[i] = -1;
            guessCopy[i] = 0;
        }
    }

    for (var i = 0; i < guessCopy.length; i++) {
        var index = codeCopy.indexOf(guessCopy[i]);
        if (index > -1) {
            wrongPos += "-";
            codeCopy[index] = "";
        }
    }
    return matches + wrongPos;
}

function createSecretCode() {
    var code = [];
    for (var i = 0; i < 4; i++) {
        code[i] = Math.floor(Math.random() * (6) + 1);
    }
    return code;
}

mainLoop();<|endoftext|>


<commit_before>// AMD-ID "dojox/math/stats"
define(["dojo", "dojox"], function(dojo, dojox) {
dojo.getObject("math.stats", true, dojox);

(function(){
	var st = dojox.math.stats;
	dojo.mixin(st, {
		sd: function(/* Number[] */a){
			//	summary:
			//		Returns the standard deviation of the passed arguments.
			return Math.sqrt(st.variance(a));	//	Number
		},

		variance: function(/* Number[] */a){
			//	summary:
			//		Find the variance in the passed array of numbers.
			var mean=0, squares=0;
			dojo.forEach(a, function(item){
				mean+=item;
				squares+=Math.pow(item,2);
			});
			return (squares/a.length)-Math.pow(mean/a.length, 2);	//	Number
		},

		bestFit: function(/* Object[] || Number[] */a, /* String? */xProp, /* String? */yProp){
			//	summary:
			//		Calculate the slope and intercept in a linear fashion.  An array
			//		of objects is expected; optionally you can pass in the property
			//		names for "x" and "y", else x/y is used as the default.  If you
			//		pass an array of numbers, it will be mapped to a set of {x,y} objects
			//		where x = the array index.
			xProp = xProp || "x", yProp = yProp || "y";
			if(a[0] !== undefined && typeof(a[0]) == "number"){
				//	this is an array of numbers, so use the index as x.
				a = dojo.map(a, function(item, idx){
					return { x: idx, y: item };
				});
			}

			var sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, stt = 0, sts = 0, n = a.length, t;
			for(var i=0; i<n; i++){
				sx += a[i][xProp];
				sy += a[i][yProp];
				sxx += Math.pow(a[i][xProp], 2);
				syy += Math.pow(a[i][yProp], 2);
				sxy += a[i][xProp] * a[i][yProp];
			}

			//	we use the following because it's more efficient and accurate for determining the slope.
			for(i=0; i<n; i++){
				t = a[i][xProp] - sx/n;
				stt += t*t;
				sts += t*a[i][yProp];
			}
			var slope = sts/(stt||1);	//	prevent divide by zero.

			//	get Pearson's R
			var d = Math.sqrt((sxx - Math.pow(sx,2)/n) * (syy - Math.pow(sy,2)/n));
			if(d === 0){
				throw new Error("dojox.math.stats.bestFit: the denominator for Pearson's R is 0.");
			}

			var r = (sxy-(sx*sy/n)) / d;
			var r2 = Math.pow(r, 2);
			if(slope < 0){
				r = -r;
			}

			//	to use:  y = slope*x + intercept;
			return {	//	Object
				slope: slope,
				intercept: (sy - sx*slope)/(n||1),
				r: r,
				r2: r2
			};
		},

		forecast: function(/* Object[] || Number[] */a, /* Number */x, /* String? */xProp, /* String? */yProp){
			//	summary:
			//		Using the bestFit algorithm above, find y for the given x.
			var fit = st.bestFit(a, xProp, yProp);
			return (fit.slope * x) + fit.intercept;	//	Number
		},

		mean: function(/* Number[] */a){
			//	summary:
			//		Returns the mean value in the passed array.
			var t=0;
			dojo.forEach(a, function(v){
				t += v;
			});
			return t / Math.max(a.length, 1);	//	Number
		},

		min: function(/* Number[] */a){
			//	summary:
			//		Returns the min value in the passed array.
			return Math.min.apply(null, a);		//	Number
		},

		max: function(/* Number[] */a){
			//	summary:
			//		Returns the max value in the passed array.
			return Math.max.apply(null, a);		//	Number
		},

		median: function(/* Number[] */a){
			//	summary:
			//		Returns the value closest to the middle from a sorted version of the passed array.
			var t = a.slice(0).sort(function(a, b){ return a - b; });
			return (t[Math.floor(a.length/2)] + t[Math.ceil(a.length/2)])/2; // Number
		},

		mode: function(/* Number[] */a){
			//	summary:
			//		Returns the mode from the passed array (number that appears the most often).
			//		This is not the most efficient method, since it requires a double scan, but
			//		is ensures accuracy.
			var o = {}, r = 0, m = Number.MIN_VALUE;
			dojo.forEach(a, function(v){
				(o[v]!==undefined)?o[v]++:o[v]=1;
			});

			//	we did the lookup map because we need the number that appears the most.
			for(var p in o){
				if(m < o[p]){
					m = o[p], r = p;
				}
			}
			return r;	//	Number
		},

		sum: function(/* Number[] */a){
			//	summary:
			//		Return the sum of all the numbers in the passed array.  Does
			//		not check to make sure values within a are NaN (should simply
			//		return NaN).
			var sum = 0;
			dojo.forEach(a, function(n){
				sum += n;
			});
			return sum;	//	Number
		},

		approxLin: function(a, pos){
			//	summary:
			//		Returns a linearly approximated value from an array using
			//		a normalized float position value.
			//	a: Number[]:
			//		a sorted numeric array to be used for the approximation.
			//	pos: Number:
			//		a position number from 0 to 1. If outside of this range it
			//		will be clamped.
			//	returns: Number
			var p = pos * (a.length - 1), t = Math.ceil(p), f = t - 1;
			if(f < 0){ return a[0]; }
			if(t >= a.length){ return a[a.length - 1]; }
			return a[f] * (t - p) + a[t] * (p - f);	// Number
		},

		summary: function(a, alreadySorted){
			//	summary:
			//		Returns a non-parametric collection of summary statistics:
			//		the classic five-number summary extended to the Bowley's
			//		seven-figure summary.
			//	a: Number[]:
			//		a numeric array to be appraised.
			//	alreadySorted: Boolean?:
			//		a Boolean flag to indicated that the array is already sorted.
			//		This is an optional flag purely to improve the performance.
			//		If skipped, the array will be assumed unsorted.
			//	returns: Object
			if(!alreadySorted){
				a = a.slice(0);								// copy the array
				a.sort(function(a, b){ return a - b; });	// sort it properly
			}
			var	l = st.approxLin,
				result = {
					// the five-number summary
					min:	a[0],				// minimum
					p25:	l(a, 0.25),			// lower quartile
					med:	l(a, 0.5),			// median
					p75:	l(a, 0.75),			// upper quartile
					max:	a[a.length - 1],	// maximum
					// extended to the Bowley's seven-figure summary
					p10:	l(a, 0.1),			// first decile
					p90:	l(a, 0.9)			// last decile
				};
			return result;	// Object
		}
	});
})();

return dojox.math.stats;
});
<commit_msg>replaced absolute module ids with relative module ids on the road to zero abs module ids in dojo; refs #12672; \!strict<commit_after>// AMD-ID "dojox/math/stats"
define(["dojo", ".."], function(dojo, dojox) {
dojo.getObject("math.stats", true, dojox);

(function(){
	var st = dojox.math.stats;
	dojo.mixin(st, {
		sd: function(/* Number[] */a){
			//	summary:
			//		Returns the standard deviation of the passed arguments.
			return Math.sqrt(st.variance(a));	//	Number
		},

		variance: function(/* Number[] */a){
			//	summary:
			//		Find the variance in the passed array of numbers.
			var mean=0, squares=0;
			dojo.forEach(a, function(item){
				mean+=item;
				squares+=Math.pow(item,2);
			});
			return (squares/a.length)-Math.pow(mean/a.length, 2);	//	Number
		},

		bestFit: function(/* Object[] || Number[] */a, /* String? */xProp, /* String? */yProp){
			//	summary:
			//		Calculate the slope and intercept in a linear fashion.  An array
			//		of objects is expected; optionally you can pass in the property
			//		names for "x" and "y", else x/y is used as the default.  If you
			//		pass an array of numbers, it will be mapped to a set of {x,y} objects
			//		where x = the array index.
			xProp = xProp || "x", yProp = yProp || "y";
			if(a[0] !== undefined && typeof(a[0]) == "number"){
				//	this is an array of numbers, so use the index as x.
				a = dojo.map(a, function(item, idx){
					return { x: idx, y: item };
				});
			}

			var sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, stt = 0, sts = 0, n = a.length, t;
			for(var i=0; i<n; i++){
				sx += a[i][xProp];
				sy += a[i][yProp];
				sxx += Math.pow(a[i][xProp], 2);
				syy += Math.pow(a[i][yProp], 2);
				sxy += a[i][xProp] * a[i][yProp];
			}

			//	we use the following because it's more efficient and accurate for determining the slope.
			for(i=0; i<n; i++){
				t = a[i][xProp] - sx/n;
				stt += t*t;
				sts += t*a[i][yProp];
			}
			var slope = sts/(stt||1);	//	prevent divide by zero.

			//	get Pearson's R
			var d = Math.sqrt((sxx - Math.pow(sx,2)/n) * (syy - Math.pow(sy,2)/n));
			if(d === 0){
				throw new Error("dojox.math.stats.bestFit: the denominator for Pearson's R is 0.");
			}

			var r = (sxy-(sx*sy/n)) / d;
			var r2 = Math.pow(r, 2);
			if(slope < 0){
				r = -r;
			}

			//	to use:  y = slope*x + intercept;
			return {	//	Object
				slope: slope,
				intercept: (sy - sx*slope)/(n||1),
				r: r,
				r2: r2
			};
		},

		forecast: function(/* Object[] || Number[] */a, /* Number */x, /* String? */xProp, /* String? */yProp){
			//	summary:
			//		Using the bestFit algorithm above, find y for the given x.
			var fit = st.bestFit(a, xProp, yProp);
			return (fit.slope * x) + fit.intercept;	//	Number
		},

		mean: function(/* Number[] */a){
			//	summary:
			//		Returns the mean value in the passed array.
			var t=0;
			dojo.forEach(a, function(v){
				t += v;
			});
			return t / Math.max(a.length, 1);	//	Number
		},

		min: function(/* Number[] */a){
			//	summary:
			//		Returns the min value in the passed array.
			return Math.min.apply(null, a);		//	Number
		},

		max: function(/* Number[] */a){
			//	summary:
			//		Returns the max value in the passed array.
			return Math.max.apply(null, a);		//	Number
		},

		median: function(/* Number[] */a){
			//	summary:
			//		Returns the value closest to the middle from a sorted version of the passed array.
			var t = a.slice(0).sort(function(a, b){ return a - b; });
			return (t[Math.floor(a.length/2)] + t[Math.ceil(a.length/2)])/2; // Number
		},

		mode: function(/* Number[] */a){
			//	summary:
			//		Returns the mode from the passed array (number that appears the most often).
			//		This is not the most efficient method, since it requires a double scan, but
			//		is ensures accuracy.
			var o = {}, r = 0, m = Number.MIN_VALUE;
			dojo.forEach(a, function(v){
				(o[v]!==undefined)?o[v]++:o[v]=1;
			});

			//	we did the lookup map because we need the number that appears the most.
			for(var p in o){
				if(m < o[p]){
					m = o[p], r = p;
				}
			}
			return r;	//	Number
		},

		sum: function(/* Number[] */a){
			//	summary:
			//		Return the sum of all the numbers in the passed array.  Does
			//		not check to make sure values within a are NaN (should simply
			//		return NaN).
			var sum = 0;
			dojo.forEach(a, function(n){
				sum += n;
			});
			return sum;	//	Number
		},

		approxLin: function(a, pos){
			//	summary:
			//		Returns a linearly approximated value from an array using
			//		a normalized float position value.
			//	a: Number[]:
			//		a sorted numeric array to be used for the approximation.
			//	pos: Number:
			//		a position number from 0 to 1. If outside of this range it
			//		will be clamped.
			//	returns: Number
			var p = pos * (a.length - 1), t = Math.ceil(p), f = t - 1;
			if(f < 0){ return a[0]; }
			if(t >= a.length){ return a[a.length - 1]; }
			return a[f] * (t - p) + a[t] * (p - f);	// Number
		},

		summary: function(a, alreadySorted){
			//	summary:
			//		Returns a non-parametric collection of summary statistics:
			//		the classic five-number summary extended to the Bowley's
			//		seven-figure summary.
			//	a: Number[]:
			//		a numeric array to be appraised.
			//	alreadySorted: Boolean?:
			//		a Boolean flag to indicated that the array is already sorted.
			//		This is an optional flag purely to improve the performance.
			//		If skipped, the array will be assumed unsorted.
			//	returns: Object
			if(!alreadySorted){
				a = a.slice(0);								// copy the array
				a.sort(function(a, b){ return a - b; });	// sort it properly
			}
			var	l = st.approxLin,
				result = {
					// the five-number summary
					min:	a[0],				// minimum
					p25:	l(a, 0.25),			// lower quartile
					med:	l(a, 0.5),			// median
					p75:	l(a, 0.75),			// upper quartile
					max:	a[a.length - 1],	// maximum
					// extended to the Bowley's seven-figure summary
					p10:	l(a, 0.1),			// first decile
					p90:	l(a, 0.9)			// last decile
				};
			return result;	// Object
		}
	});
})();

return dojox.math.stats;
});
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2020
 */

import { SUPPLIER_CREDIT_ACTIONS } from '../actions/SupplierCreditActions';
import { UIDatabase } from '../database';
import { parsePositiveInteger } from '../utilities';

const mapBatchToObject = batches =>
  batches.map(batch => ({
    returnAmount: 0,
    id: batch.id,
    totalQuantity: batch.totalQuantity,
    itemBatch: batch,
    otherPartyName: batch.otherPartyName,
    batch: batch.batch,
    costPrice: batch.costPrice,
    itemName: batch.itemName,
    expiryDate: batch.expiryDate,
    itemCode: batch.itemCode,
  }));

const initialState = () => ({
  batches: [],
  open: false,
  sortKey: 'otherPartyName',
  isAscending: true,
  item: null,
  invoice: null,
  category: null,
  title: '',
  reasons: UIDatabase.objects('SupplierCreditCategory'),
});

export const SupplierCreditReducer = (state = initialState(), action) => {
  const { type } = action;

  switch (type) {
    case SUPPLIER_CREDIT_ACTIONS.EDIT_RETURN_AMOUNT: {
      const { batches } = state;
      const { payload } = action;
      const { batchId, returnAmount } = payload;

      const rowToEditIndex = batches.findIndex(({ id }) => id === batchId);

      const { totalQuantity } = batches[rowToEditIndex];
      const adjustmentAmount = parsePositiveInteger(returnAmount);

      const newRow = {
        ...batches[rowToEditIndex],
        returnAmount: adjustmentAmount <= totalQuantity ? adjustmentAmount : 0,
      };
      batches[rowToEditIndex] = newRow;

      return { ...state, batches: [...batches] };
    }

    case SUPPLIER_CREDIT_ACTIONS.EDIT_CATEGORY: {
      const { payload } = action;
      const { category } = payload;
      return { ...state, category };
    }

    case SUPPLIER_CREDIT_ACTIONS.CREATE_FROM_ITEM: {
      const { payload } = action;
      const { itemId } = payload;

      const item = UIDatabase.get('Item', itemId);

      return {
        ...state,
        batches: mapBatchToObject(item?.batches?.filtered('numberOfPacks > 0') ?? []),
        open: true,
        item,
        type: 'supplierCreditFromItem',
      };
    }

    case SUPPLIER_CREDIT_ACTIONS.CREATE_FROM_INVOICE: {
      const { payload } = action;
      const { invoice } = payload;

      const transactionBatches = invoice?.getTransactionBatches(UIDatabase) ?? [];
      const itemBatches = transactionBatches.map(({ itemBatch }) => itemBatch);

      return {
        ...state,
        open: true,
        batches: mapBatchToObject(itemBatches),
        invoice,
        type: 'supplierCreditFromInvoice',
      };
    }

    case SUPPLIER_CREDIT_ACTIONS.SORT: {
      const { isAscending, sortKey } = state;
      const { payload } = action;
      const { sortKey: newSortKey } = payload;

      return {
        ...state,
        sortKey: newSortKey,
        isAscending: sortKey === newSortKey ? !isAscending : true,
      };
    }

    case SUPPLIER_CREDIT_ACTIONS.CLOSE: {
      return initialState();
    }

    default:
      return state;
  }
};
<commit_msg>Add filtering by having a supplier and not being invad<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2020
 */

import { SUPPLIER_CREDIT_ACTIONS } from '../actions/SupplierCreditActions';
import { UIDatabase } from '../database';
import { parsePositiveInteger } from '../utilities';

const mapBatchToObject = batches =>
  batches.map(batch => ({
    returnAmount: 0,
    id: batch.id,
    totalQuantity: batch.totalQuantity,
    itemBatch: batch,
    otherPartyName: batch.otherPartyName,
    batch: batch.batch,
    costPrice: batch.costPrice,
    itemName: batch.itemName,
    expiryDate: batch.expiryDate,
    itemCode: batch.itemCode,
  }));

const initialState = () => ({
  batches: [],
  open: false,
  sortKey: 'otherPartyName',
  isAscending: true,
  item: null,
  invoice: null,
  category: null,
  title: '',
  reasons: UIDatabase.objects('SupplierCreditCategory'),
});

export const SupplierCreditReducer = (state = initialState(), action) => {
  const { type } = action;

  switch (type) {
    case SUPPLIER_CREDIT_ACTIONS.EDIT_RETURN_AMOUNT: {
      const { batches } = state;
      const { payload } = action;
      const { batchId, returnAmount } = payload;

      const rowToEditIndex = batches.findIndex(({ id }) => id === batchId);

      const { totalQuantity } = batches[rowToEditIndex];
      const adjustmentAmount = parsePositiveInteger(returnAmount);

      const newRow = {
        ...batches[rowToEditIndex],
        returnAmount: adjustmentAmount <= totalQuantity ? adjustmentAmount : 0,
      };
      batches[rowToEditIndex] = newRow;

      return { ...state, batches: [...batches] };
    }

    case SUPPLIER_CREDIT_ACTIONS.EDIT_CATEGORY: {
      const { payload } = action;
      const { category } = payload;
      return { ...state, category };
    }

    case SUPPLIER_CREDIT_ACTIONS.CREATE_FROM_ITEM: {
      const { payload } = action;
      const { itemId } = payload;

      const item = UIDatabase.get('Item', itemId);

      const query = 'numberOfPacks > 0 && supplier != null && supplier.isVisible == true';

      return {
        ...state,
        batches: mapBatchToObject(item?.batches?.filtered(query)),
        open: true,
        item,
        type: 'supplierCreditFromItem',
      };
    }

    case SUPPLIER_CREDIT_ACTIONS.CREATE_FROM_INVOICE: {
      const { payload } = action;
      const { invoice } = payload;

      const transactionBatches = invoice?.getTransactionBatches(UIDatabase) ?? [];
      const itemBatches = transactionBatches.map(({ itemBatch }) => itemBatch);

      return {
        ...state,
        open: true,
        batches: mapBatchToObject(itemBatches),
        invoice,
        type: 'supplierCreditFromInvoice',
      };
    }

    case SUPPLIER_CREDIT_ACTIONS.SORT: {
      const { isAscending, sortKey } = state;
      const { payload } = action;
      const { sortKey: newSortKey } = payload;

      return {
        ...state,
        sortKey: newSortKey,
        isAscending: sortKey === newSortKey ? !isAscending : true,
      };
    }

    case SUPPLIER_CREDIT_ACTIONS.CLOSE: {
      return initialState();
    }

    default:
      return state;
  }
};
<|endoftext|>


<commit_before>import Twitter from 'twitter'
import config from 'config'
import storage from 'electron-json-storage-sync'

const OAUTH_TOKEN_KEY = 'oauthToken'

const oauthInfo = storage.get(OAUTH_TOKEN_KEY)

const client = new Twitter({
  consumer_key: config.get('consumerKey'),
  consumer_secret: config.get('consumerSecret'),
  access_token_key: oauthInfo.data.oauth_access_token,
  access_token_secret: oauthInfo.data.oauth_access_token_secret
})

const params = {
  include_entities: true,
  tweet_mode: 'extended'
}

const state = {
  timeline: []
}

const mutations = {
  FETCH_TIMELINE (state, tweets) {
    state.timeline = tweets
  }
}

const actions = {
  fetchTimeline ({ commit }) {
    // do something async
    fetchTweets('statuses/home_timeline')
      .then((tweets) => {
        commit('FETCH_TIMELINE', tweets)
      })
  }
}

function fetchTweets (endpoint) {
  return new Promise((resolve, reject) => {
    client.get(endpoint, params, (err, tweets, res) => {
      if (!err) {
        resolve(tweets)
      } else {
        reject(err)
      }
    })
  })
}

export default {
  state,
  mutations,
  actions
}
<commit_msg>Add fetch mention timeline method<commit_after>import Twitter from 'twitter'
import config from 'config'
import storage from 'electron-json-storage-sync'

const OAUTH_TOKEN_KEY = 'oauthToken'

const oauthInfo = storage.get(OAUTH_TOKEN_KEY)

const client = new Twitter({
  consumer_key: config.get('consumerKey'),
  consumer_secret: config.get('consumerSecret'),
  access_token_key: oauthInfo.data.oauth_access_token,
  access_token_secret: oauthInfo.data.oauth_access_token_secret
})

const params = {
  include_entities: true,
  tweet_mode: 'extended'
}

const state = {
  timeline: [],
  mentions: []
}

const mutations = {
  FETCH_TIMELINE (state, tweets) {
    state.timeline = tweets
  },
  FETCH_MENTIONS (state, tweets) {
    state.mentions = tweets
  }
}

const actions = {
  fetchTimeline ({ commit }) {
    // do something async
    fetchTweets('statuses/home_timeline')
      .then((tweets) => {
        commit('FETCH_TIMELINE', tweets)
      })
  },
  fetchMentions ({ commit }) {
    // do something async
    fetchTweets('statuses/mentions_timeline')
      .then((tweets) => {
        commit('FETCH_MENTIONS', tweets)
      })
  }
}

function fetchTweets (endpoint) {
  return new Promise((resolve, reject) => {
    client.get(endpoint, params, (err, tweets, res) => {
      if (!err) {
        resolve(tweets)
      } else {
        reject(err)
      }
    })
  })
}

export default {
  state,
  mutations,
  actions
}
<|endoftext|>


<commit_before>/*
    ioBroker.lifx Widget-Set
    version: "0.0.1"
    Copyright Karsten Thiele
    adapted from iobroker.vis-jqui, jqui-mfd

*/

"use strict";

// add translations for edit mode

if (vis.editMode) {

    $.extend(systemDictionary, {
        "oid-bright":       {"en": "brightness", "de": "Helligkeit"},
        "oid-temp":         {"en": "light temperature", "de": "Lichttemperatur"},
        "oid-colormode":    {"en": "mode",  "de": "Modus"},
        "oid-sat":          {"en": "saturation",    "de": "Sättigung"},
        "oid-color":          {"en": "color",      "de": "Farbe"}
    });

vis.binds.lifx = {

    version: "0.0.1",

    showVersion: function() {

        if (vis.binds.deepcore.version) {

            console.log('Deepcore widget version: ' + vis.binds.deepcore.version);

            vis.binds.deepcore.version = null;

        }

    },

    lifxColormode: function (el, oid) {
            var $hue = $(el).parent().find('.hue-mode-hue');
            var $ct  = $(el).parent().find('.hue-mode-ct');
            var $ct  = $(el).parent().find('.hue-mode-ct');
            if (vis.states.attr(oid + '.val') == 'color') {
                $hue.hide();
                $ct.show();
            } else {
                $ct.hide();
                $hue.show();
            }

            vis.states.bind(oid + '.val', function (e, newVal, oldVal) {
                if (newVal == 'color') {
                    $hue.hide();
                    $ct.show();
                } else {
                    $ct.hide();
                    $hue.show();
                }
            });
        },
    };

vis.binds.lifx.showVersion();
<commit_msg>Update lifx.js<commit_after>/*
    ioBroker.lifx Widget-Set
    version: "0.0.1"
    Copyright Karsten Thiele
    adapted from iobroker.vis-jqui, jqui-mfd

*/

"use strict";

// add translations for edit mode

if (vis.editMode) {

    $.extend(systemDictionary, {
        "oid-bright":       {"en": "brightness", "de": "Helligkeit"},
        "oid-temp":         {"en": "light temperature", "de": "Lichttemperatur"},
        "oid-colormode":    {"en": "mode",  "de": "Modus"},
        "oid-sat":          {"en": "saturation",    "de": "Sättigung"},
        "oid-color":          {"en": "color",      "de": "Farbe"}
    });

vis.binds.lifxui = {

    version: "0.0.1",

    showVersion: function() {

        if (vis.binds.deepcore.version) {

            console.log('Deepcore widget version: ' + vis.binds.deepcore.version);

            vis.binds.deepcore.version = null;

        }

    },

    lifxColormode: function (el, oid) {
            var $hue = $(el).parent().find('.hue-mode-hue');
            var $ct  = $(el).parent().find('.hue-mode-ct');
            var $ct  = $(el).parent().find('.hue-mode-ct');
            if (vis.states.attr(oid + '.val') == 'color') {
                $hue.hide();
                $ct.show();
            } else {
                $ct.hide();
                $hue.show();
            }

            vis.states.bind(oid + '.val', function (e, newVal, oldVal) {
                if (newVal == 'color') {
                    $hue.hide();
                    $ct.show();
                } else {
                    $ct.hide();
                    $hue.show();
                }
            });
        },
    };

vis.binds.lifx.showVersion();
<|endoftext|>