<commit_before>/*** Map Prototype ***/
var Map = function() {
  canvas = document.getElementById('field2');
  this.fp_context = canvas.getContext('2d');
}

Map.prototype = {
 /**
  * load(madData)
  *
  * Sets the map model to a specific map from a javascrit object.
  **/
  load: function(mapData) {
    this.model = mapData;
  },

 /**
  * render(context, player)
  *
  * Renders the minimap gridlines along with running the ray casts for the
  * projections.
  */
  render: function(context, player) {
    var mapData = this.model.data;
    var mapHeight = this.model.height;
    var mapWidth = this.model.width;

    // Clear our palet
    this.fp_context.clearRect (0, 0, 1000, 1000);

    var x = 0, y = 0;

    for(y=0; y < mapHeight+1; y++) {
      var grid_y = y * Config.blockSize;

      for(x=0; x < mapWidth+1; x++) {
        var grid_x = x * Config.blockSize;
        var map_element = this.get(x, y);

        var color = null;

        switch(map_element) {
          case 1:
            color = '#000';
          break;
        }

        if(color) Helper.rect(context, this.color, grid_x, grid_y, Config.blockSize, Config.blockSize);

        Helper.line(context, grid_x, 0, grid_x, Helper.toPixel(MapData.height));
      }

      Helper.line(context, 0, grid_y, Helper.toPixel(MapData.width), grid_y);
    }

    // run the raycast
    this.cast(context, player);
  },

 /**
  * get(x, y)
  *
  * Gets the map element for the given x,y coordinate. This allows us
  * to do simple bounds checking so we dont try to access an out of
  * bounds element.
  */
  get: function(x, y) {
    if(this.model.height > y && this.model.width > x && y >= 0 && x >= 0)
      return this.model.data[y][x];
    else // if the point is out of bounds, just render a wall
      return 1;
  },

 /**
  * cast(context, player)
  *
  * Handles casting a bunch of rays. The number of the rays is determined by
  * the Config.rayResolution variable while the spread of the rays is
  * determined by the Config.fov (field of view) variable. This method
  * calls the fireRay function to actually process the individual rays.
  **/
  cast: function(context, player) {
    var res = Math.floor(Config.rayResolution/2);
    var step = Config.fov/(Config.rayResolution-1);

    for(var i=0; i<Config.rayResolution; i++) {
      angle = player.direction + step * i - (Config.fov / 2);

      if(i == 0 || i == Config.rayResolution-1) {
        x = Helper.toPixel(player.x);
        y = Helper.toPixel(player.y);

        Helper.line(context, x, y, x + Math.cos(angle) * 100, y + Math.sin(angle) * 100);
      }

      var currentStep = this.fireRay(context, angle, player.x, player.y);

      var distance = Helper.distance(currentStep, player);
      var z = 1/distance * Math.cos(angle);

      var left = i*5;
      var width = 5;
      var height = -1000 * 1/distance;
      var top = 350-height/2;
      var color = (currentStep.x % 1 == 0) ? '#00f' : '#00A';

      Helper.rect(this.fp_context, color, left, top, width, height);
    }
  },

 /**
  * fireRay(context, angle, x, y)
  *
  * Processes a single ray at a given angle, from a given point. We return
  * when we hit a wall or exceed our range limit. the returned value is the step
  * at which we hit a wall.
  **/
  fireRay: function(context, angle, x, y) {
    var currentStep = {x: x, y: y};
    var sin = Math.sin(angle);
    var cos = Math.cos(angle);

    // the 100 value is basically our sight range
    for(var i=0; i<100; i++) {
      //Jump to the next X gridline
      currentStepX = jump(sin, cos, currentStep.x, currentStep.y);
      //Jump to the next Y gridline
      currentStepY = jump(cos, sin, currentStep.y, currentStep.x, true);

      currentStep = currentStepX.length2 < currentStepY.length2 ? currentStepX : currentStepY;

      if(this.wallCheck(currentStep)) {
        Helper.circle(context, 4, Helper.toPixel(currentStep.x), Helper.toPixel(currentStep.y), '#00f');
        return currentStep;
      }
    }

    /* Borrowed this function from another implementation. I made the mistake of
       finding this function and I have failed to come up with a different
       implementationa .*/
    function jump(rise, run, x, y, inverted) {
      if (run === 0) return { length2: Infinity};
      var dx = run > 0 ? Math.floor(x + 1) - x : Math.ceil(x - 1) - x;
      var dy = dx * (rise / run);

      return {
        x: inverted ? y + dy : x + dx,
        y: inverted ? x + dx : y + dy,
        length2: dx * dx + dy * dy
      };
    }
  },

 /**
  * wallCheck(step)
  *
  * takes the current position and checks to see if there is a wall around it. If the point is on the
  * Y gridline we check above and bellow, if it's on the X line we check to the left and right.
  **/
  wallCheck: function(step) {
    // Checks if the point is on the X-gridline
    if(step.x % 1 == 0) {
      if(this.get(step.x, Math.floor(step.y)) === 1 || this.get(step.x-1, Math.floor(step.y)) === 1) {
        return true;
      }
    } else {
      if(this.get(Math.floor(step.x), step.y) === 1 || this.get(Math.floor(step.x), step.y-1) === 1) {
        return true;
      }
    }

    return false;
  },

  toggleWall: function(x, y) {
    if(x < this.model.width && y < this.model.height && x >= 0 && y >= 0)
      this.model.data[y][x] = this.get(x,y) == 1? 0 : 1;
  },
};
<commit_msg>setting better colors<commit_after>/*** Map Prototype ***/
var Map = function() {
  canvas = document.getElementById('field2');
  this.fp_context = canvas.getContext('2d');
}

Map.prototype = {
 /**
  * load(madData)
  *
  * Sets the map model to a specific map from a javascrit object.
  **/
  load: function(mapData) {
    this.model = mapData;
  },

 /**
  * render(context, player)
  *
  * Renders the minimap gridlines along with running the ray casts for the
  * projections.
  */
  render: function(context, player) {
    var mapData = this.model.data;
    var mapHeight = this.model.height;
    var mapWidth = this.model.width;

    // Clear our palet
    this.fp_context.fillStyle   = "#3E4961"; // blue
    this.fp_context.fillRect (0, 0, 1000, 1000);
    this.fp_context.fillStyle   = "#96A9D1"; // blue
    this.fp_context.fillRect (0, 0, 1000, 350);

    var x = 0, y = 0;

    for(y=0; y < mapHeight+1; y++) {
      var grid_y = y * Config.blockSize;

      for(x=0; x < mapWidth+1; x++) {
        var grid_x = x * Config.blockSize;
        var map_element = this.get(x, y);

        var color = null;

        switch(map_element) {
          case 1:
            color = '#000';
          break;
        }

        if(color) Helper.rect(context, this.color, grid_x, grid_y, Config.blockSize, Config.blockSize);

        Helper.line(context, grid_x, 0, grid_x, Helper.toPixel(MapData.height));
      }

      Helper.line(context, 0, grid_y, Helper.toPixel(MapData.width), grid_y);
    }

    // run the raycast
    this.cast(context, player);
  },

 /**
  * get(x, y)
  *
  * Gets the map element for the given x,y coordinate. This allows us
  * to do simple bounds checking so we dont try to access an out of
  * bounds element.
  */
  get: function(x, y) {
    if(this.model.height > y && this.model.width > x && y >= 0 && x >= 0)
      return this.model.data[y][x];
    else // if the point is out of bounds, just render a wall
      return 1;
  },

 /**
  * cast(context, player)
  *
  * Handles casting a bunch of rays. The number of the rays is determined by
  * the Config.rayResolution variable while the spread of the rays is
  * determined by the Config.fov (field of view) variable. This method
  * calls the fireRay function to actually process the individual rays.
  **/
  cast: function(context, player) {
    var res = Math.floor(Config.rayResolution/2);
    var step = Config.fov/(Config.rayResolution-1);

    for(var i=0; i<Config.rayResolution; i++) {
      angle = player.direction + step * i - (Config.fov / 2);

      if(i == 0 || i == Config.rayResolution-1) {
        x = Helper.toPixel(player.x);
        y = Helper.toPixel(player.y);

        Helper.line(context, x, y, x + Math.cos(angle) * 100, y + Math.sin(angle) * 100);
      }

      var currentStep = this.fireRay(context, angle, player.x, player.y);

      var distance = Helper.distance(currentStep, player);
      var z = 1/distance * Math.cos(angle);

      var left = i*5;
      var width = 5;
      var height = -1000 * 1/distance;
      var top = 350-height/2;
      var color = (currentStep.x % 1 == 0) ? '#D69FF5' : '#BC6FE7';

      Helper.rect(this.fp_context, color, left, top, width, height);
    }
  },

 /**
  * fireRay(context, angle, x, y)
  *
  * Processes a single ray at a given angle, from a given point. We return
  * when we hit a wall or exceed our range limit. the returned value is the step
  * at which we hit a wall.
  **/
  fireRay: function(context, angle, x, y) {
    var currentStep = {x: x, y: y};
    var sin = Math.sin(angle);
    var cos = Math.cos(angle);

    // the 100 value is basically our sight range
    for(var i=0; i<100; i++) {
      //Jump to the next X gridline
      currentStepX = jump(sin, cos, currentStep.x, currentStep.y);
      //Jump to the next Y gridline
      currentStepY = jump(cos, sin, currentStep.y, currentStep.x, true);

      currentStep = currentStepX.length2 < currentStepY.length2 ? currentStepX : currentStepY;

      if(this.wallCheck(currentStep)) {
        Helper.circle(context, 4, Helper.toPixel(currentStep.x), Helper.toPixel(currentStep.y), '#00f');
        return currentStep;
      }
    }

    /* Borrowed this function from another implementation. I made the mistake of
       finding this function and I have failed to come up with a different
       implementationa .*/
    function jump(rise, run, x, y, inverted) {
      if (run === 0) return { length2: Infinity};
      var dx = run > 0 ? Math.floor(x + 1) - x : Math.ceil(x - 1) - x;
      var dy = dx * (rise / run);

      return {
        x: inverted ? y + dy : x + dx,
        y: inverted ? x + dx : y + dy,
        length2: dx * dx + dy * dy
      };
    }
  },

 /**
  * wallCheck(step)
  *
  * takes the current position and checks to see if there is a wall around it. If the point is on the
  * Y gridline we check above and bellow, if it's on the X line we check to the left and right.
  **/
  wallCheck: function(step) {
    // Checks if the point is on the X-gridline
    if(step.x % 1 == 0) {
      if(this.get(step.x, Math.floor(step.y)) === 1 || this.get(step.x-1, Math.floor(step.y)) === 1) {
        return true;
      }
    } else {
      if(this.get(Math.floor(step.x), step.y) === 1 || this.get(Math.floor(step.x), step.y-1) === 1) {
        return true;
      }
    }

    return false;
  },

  toggleWall: function(x, y) {
    if(x < this.model.width && y < this.model.height && x >= 0 && y >= 0)
      this.model.data[y][x] = this.get(x,y) == 1? 0 : 1;
  },
};
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const rp = require('request-promise');
const promisePool = require('es6-promise-pool');
const PromisePool = promisePool.PromisePool;
const secureCompare = require('secure-compare');
// Maximum concurrent account deletions.
const MAX_CONCURRENT = 3;

/**
 * When requested this Function will delete every user accounts that has been inactive for 30 days.
 * The request needs to be authorized by passing a 'key' query parameter in the URL. This key must
 * match a key set as an environment variable using `firebase functions:config:set cron.key="YOUR_KEY"`.
 */
exports.accountcleanup = functions.https.onRequest((req, res) => {
  const key = req.query.key;

  // Exit if the keys don't match.
  if (!secureCompare(key, functions.config().cron.key)) {
    console.log('The key provided in the request does not match the key set in the environment. Check that', key,
        'matches the cron.key attribute in `firebase env:get`');
    res.status(403).send('Security key does not match. Make sure your "key" URL query parameter matches the ' +
        'cron.key environment variable.');
    return null;
  }

  // Fetch all user details.
  return getInactiveUsers().then((inactiveUsers) => {
    // Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel.
    const promisePool = new PromisePool(() => deleteInactiveUser(inactiveUsers), MAX_CONCURRENT);
    return promisePool.start();
  }).then(() => {
    console.log('User cleanup finished');
    res.send('User cleanup finished');
    return null;
  });
});

/**
 * Deletes one inactive user from the list.
 */
function deleteInactiveUser(inactiveUsers) {
  if (inactiveUsers.length > 0) {
    const userToDelete = inactiveUsers.pop();

    // Delete the inactive user.
    return admin.auth().deleteUser(userToDelete.uid).then(() => {
      console.log('Deleted user account', userToDelete.uid, 'because of inactivity');
      return null;
    }).catch(error => {
      console.error('Deletion of inactive user account', userToDelete.uid, 'failed:', error);
      return null;
    });
  }
  return null;
}

/**
 * Returns the list of all inactive users.
 */
function getInactiveUsers(users = [], nextPageToken) {
  return admin.auth().listUsers(1000, nextPageToken).then((result) => {
    // Find users that have not signed in in the last 30 days.
    const inactiveUsers = result.users.filter(
        user => Date.parse(user.metadata.lastSignInTime) < (Date.now() - 30 * 24 * 60 * 60 * 1000));

    // Concat with list of previously found inactive users if there was more than 1000 users.
    users = users.concat(inactiveUsers);

    // If there are more users to fetch we fetch them.
    if (result.pageToken) {
      return getInactiveUsers(users, result.pageToken);
    }

    return users;
  });
}
<commit_msg>remove unused import<commit_after>/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const promisePool = require('es6-promise-pool');
const PromisePool = promisePool.PromisePool;
const secureCompare = require('secure-compare');
// Maximum concurrent account deletions.
const MAX_CONCURRENT = 3;

/**
 * When requested this Function will delete every user accounts that has been inactive for 30 days.
 * The request needs to be authorized by passing a 'key' query parameter in the URL. This key must
 * match a key set as an environment variable using `firebase functions:config:set cron.key="YOUR_KEY"`.
 */
exports.accountcleanup = functions.https.onRequest((req, res) => {
  const key = req.query.key;

  // Exit if the keys don't match.
  if (!secureCompare(key, functions.config().cron.key)) {
    console.log('The key provided in the request does not match the key set in the environment. Check that', key,
        'matches the cron.key attribute in `firebase env:get`');
    res.status(403).send('Security key does not match. Make sure your "key" URL query parameter matches the ' +
        'cron.key environment variable.');
    return null;
  }

  // Fetch all user details.
  return getInactiveUsers().then((inactiveUsers) => {
    // Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel.
    const promisePool = new PromisePool(() => deleteInactiveUser(inactiveUsers), MAX_CONCURRENT);
    return promisePool.start();
  }).then(() => {
    console.log('User cleanup finished');
    res.send('User cleanup finished');
    return null;
  });
});

/**
 * Deletes one inactive user from the list.
 */
function deleteInactiveUser(inactiveUsers) {
  if (inactiveUsers.length > 0) {
    const userToDelete = inactiveUsers.pop();

    // Delete the inactive user.
    return admin.auth().deleteUser(userToDelete.uid).then(() => {
      console.log('Deleted user account', userToDelete.uid, 'because of inactivity');
      return null;
    }).catch(error => {
      console.error('Deletion of inactive user account', userToDelete.uid, 'failed:', error);
      return null;
    });
  }
  return null;
}

/**
 * Returns the list of all inactive users.
 */
function getInactiveUsers(users = [], nextPageToken) {
  return admin.auth().listUsers(1000, nextPageToken).then((result) => {
    // Find users that have not signed in in the last 30 days.
    const inactiveUsers = result.users.filter(
        user => Date.parse(user.metadata.lastSignInTime) < (Date.now() - 30 * 24 * 60 * 60 * 1000));

    // Concat with list of previously found inactive users if there was more than 1000 users.
    users = users.concat(inactiveUsers);

    // If there are more users to fetch we fetch them.
    if (result.pageToken) {
      return getInactiveUsers(users, result.pageToken);
    }

    return users;
  });
}
<|endoftext|>


<commit_before>var fs = require('fs') ,
    knox = require('knox'),
    path = require('path'),
common = require('../../../api/common');

module.exports = function(req, res){
    console.log("Faces Game Upload")
    console.log(req.files)      ;
    var name= req.files.Filedata.name

    /*
    fs.readFile(req.files.Filedata.path, function (err, data) {
        var newPath = 'deliver/public/faces_game/uploads/'+name ;
        fs.writeFile(newPath, data, function (err) {

            if(err)
            {
                console.log('error :' + err )      ;
                for(var propertyName in err) {

                    console.log(propertyName + ": "+ err[propertyName])  ;
                }

                res.write(err);
                res.end();
            }
            else {
                console.log('success :' +'http://www.uru.org.il/faces_game/uploads/'+name)
                res.write('http://www.uru.org.il/faces_game/uploads/'+name);
                res.end();
            }
        });
    });

     */

    fu(req,function(err,value) {
        console.log(value)      ;
        if(err)
        {
            console.log('error :' )      ;
            for(var propertyName in err) {

                console.log(propertyName + ": "+ err[propertyName])  ;
            }

            res.write(err);
            res.end();
        }
        else {
            console.log('success :' +'http://www.uru.org.il/faces_game/uploads/'+name)
            res.write('http://www.uru.org.il/faces_game/uploads/'+name);
            res.end();
        }
    });

};

function fu(req,callback) {

    function writeToFile(fName, stream, callback){
        var filename=  fName,
            mypath =   'deliver/public/faces_game/uploads/'+fName ;// path.join(__dirname,'..','deliver','public','cdn', fName);

        os= fs.createWriteStream(mypath) ;
            stream.on('data',function(data) {
                os.write(data);
            });

            stream.on('end',function() {
                os.on('close', function () {
                    callback(null,{
                        filename: filename,
                        fullPath: fullPath
                    });
                });

                os.end();
            });

            stream.resume();

     };

    var knoxClient = require('j-forms').fields.getKnoxClient();

    fName       =req.files.Filedata.name;
    var stream = req.queueStream || req;

    if(knox && knoxClient)
    {
        // First, we write the file to disk. Then we upload it to Amazon.
        writeToFile(fName, stream, function(err,value) {

            if(err) {
                callback(err);
                return;
            }

            setTimeout(function() {

                var value_full_path = value.fullPath;

                stream = fs.createReadStream(value.fullPath);

                knoxClient.putStream(stream, '/' + value.filename + '_' + (new Date().getTime()), function(err, res){
                    if(err)
                        callback(err);
                    else {
                        var path = res.socket._httpMessage.url;

                        fs.unlink(value_full_path);
                        console.log("res.socket._httpMessage");
                        console.log(res.socket._httpMessage);
                        var value = {
                            path: path,
                            url: path
                        };
                        callback(null,value);
                    }
                });
            },200);
        });
    } else {
        writeToFile(fName, stream, function (err, value) {
            if (err) {
                callback(err);
            } else {
                callback(null, {
                    path: value.filename,
                    url: '/cdn/' + value.filename
                });
            }
        });
    }
};
  /*
      fs.readFile(req.files.upload_file.path, function (err, data) {
          var newPath = 'deliver/public/faces_game/uploads/'+name ;
          fs.writeFile(newPath, data, function (err) {
              if(err) {
                  res.write(err);
                  res.end();
              }else {
                  res.write('http://www.uru.org.il/faces_game/uploads/'+name);
                  res.end();
              }
          });
      });

      */
/*
<?php

// default path for the image to be stored //
$default_path = 'uploads/';

// check to see if a path was sent in from flash //
$target_path = ($_POST['dir']) ? $_POST['dir'] : $default_path;
if (!file_exists($target_path)) mkdir($target_path, 0777, true);

// full path to the saved image including filename //
$destination = $target_path . basename( $_FILES[ 'Filedata' ][ 'name' ] );

// move the image into the specified directory //
if (move_uploaded_file($_FILES[ 'Filedata' ][ 'tmp_name' ], $destination)) {
    echo basename( $_FILES[ 'Filedata' ][ 'name' ] );
} else {
    echo "FILE UPLOAD FAILED";
}
?>
  */

<commit_msg>faces<commit_after>var fs = require('fs') ,
    knox = require('knox'),
    path = require('path'),
common = require('../../../api/common');

module.exports = function(req, res){
    console.log("Faces Game Upload")
    console.log(req.files)      ;
    var name= req.files.Filedata.name

    /*
    fs.readFile(req.files.Filedata.path, function (err, data) {
        var newPath = 'deliver/public/faces_game/uploads/'+name ;
        fs.writeFile(newPath, data, function (err) {

            if(err)
            {
                console.log('error :' + err )      ;
                for(var propertyName in err) {

                    console.log(propertyName + ": "+ err[propertyName])  ;
                }

                res.write(err);
                res.end();
            }
            else {
                console.log('success :' +'http://www.uru.org.il/faces_game/uploads/'+name)
                res.write('http://www.uru.org.il/faces_game/uploads/'+name);
                res.end();
            }
        });
    });

     */

    fu(req,function(err,value) {
        console.log(value)      ;
        if(err)
        {
            console.log('error :' )      ;
            for(var propertyName in err) {

                console.log(propertyName + ": "+ err[propertyName])  ;
            }

            res.write(err);
            res.end();
        }
        else {
            console.log('success :' +'http://www.uru.org.il/faces_game/uploads/'+name)
            res.write('http://www.uru.org.il/faces_game/uploads/'+name);
            res.end();
        }
    });

};

function fu(req,callback) {

    function writeToFile(fName, stream, callback){
        var filename=  fName,
            mypath =   'deliver/public/faces_game/uploads/'+fName ;// path.join(__dirname,'..','deliver','public','cdn', fName);

        os= fs.createWriteStream(mypath) ;
            stream.on('data',function(data) {
                os.write(data);
            });

            stream.on('end',function() {
                os.on('close', function () {
                    callback(null,{
                        filename: filename,
                        fullPath: 'http://www.uru.org.il/faces_game/uploads/'+fName
                    });
                });

                os.end();
            });

            stream.resume();

     };

    var knoxClient = require('j-forms').fields.getKnoxClient();

    fName       =req.files.Filedata.name;
    var stream = req.queueStream || req;

    if(knox && knoxClient)
    {
        // First, we write the file to disk. Then we upload it to Amazon.
        writeToFile(fName, stream, function(err,value) {

            if(err) {
                callback(err);
                return;
            }

            setTimeout(function() {

                var value_full_path = value.fullPath;

                stream = fs.createReadStream(value.fullPath);

                knoxClient.putStream(stream, '/' + value.filename + '_' + (new Date().getTime()), function(err, res){
                    if(err)
                        callback(err);
                    else {
                        var path = res.socket._httpMessage.url;

                        fs.unlink(value_full_path);
                        console.log("res.socket._httpMessage");
                        console.log(res.socket._httpMessage);
                        var value = {
                            path: path,
                            url: path
                        };
                        callback(null,value);
                    }
                });
            },200);
        });
    } else {
        writeToFile(fName, stream, function (err, value) {
            if (err) {
                callback(err);
            } else {
                callback(null, {
                    path: value.filename,
                    url: '/cdn/' + value.filename
                });
            }
        });
    }
};
  /*
      fs.readFile(req.files.upload_file.path, function (err, data) {
          var newPath = 'deliver/public/faces_game/uploads/'+name ;
          fs.writeFile(newPath, data, function (err) {
              if(err) {
                  res.write(err);
                  res.end();
              }else {
                  res.write('http://www.uru.org.il/faces_game/uploads/'+name);
                  res.end();
              }
          });
      });

      */
/*
<?php

// default path for the image to be stored //
$default_path = 'uploads/';

// check to see if a path was sent in from flash //
$target_path = ($_POST['dir']) ? $_POST['dir'] : $default_path;
if (!file_exists($target_path)) mkdir($target_path, 0777, true);

// full path to the saved image including filename //
$destination = $target_path . basename( $_FILES[ 'Filedata' ][ 'name' ] );

// move the image into the specified directory //
if (move_uploaded_file($_FILES[ 'Filedata' ][ 'tmp_name' ], $destination)) {
    echo basename( $_FILES[ 'Filedata' ][ 'name' ] );
} else {
    echo "FILE UPLOAD FAILED";
}
?>
  */

<|endoftext|>


<commit_before>/**
 * Created by steve on 12/04/15.
 */
var React = require('react');
var ReactPropTypes = React.PropTypes;
var CartStore = require('../../stores/CartStore');
var CartActionCreators = require('../../actions/CartActionCreators');
var AddressActionCreators = require('../../actions/AddressActionCreators');
var OrderActionCreators = require('../../actions/OrderActionCreators');
var Cart = require('./Cart');
var CheckoutCart = require('./CheckoutCart');
var ShippingAddress = require('./ShippingAddress');
var ShippingTax = require('./ShippingTax');
var CheckoutDone = require('./CheckoutDone');
var Payment = require('./Payment');
var AuthStore = require('../../stores/AuthStore');
var classNames = require('classnames');
var utils = require('react-schema-form/lib/utils.js');

import RaisedButton from 'material-ui/lib/raised-button';
import IconButton from 'material-ui/lib/icon-button';
import Dialog from 'material-ui/lib/dialog';

function getStateFromStores() {
    return {
        cartItems: CartStore.getAll(),
        cartItemsCount: CartStore.getCartItemsCount(),
        cartTotal: CartStore.getCartTotal(),
        cartOpen: CartStore.getCartStatus(),
        shippingAddress: AuthStore.getShippingAddress() || {},
        screen: 'cart',
        title: 'Cart'
    };
}

var CheckoutButton = React.createClass({

    getInitialState: () => getStateFromStores(),

    handleCartClose: function() {
        this.setState({ cartOpen: false, screen: 'cart', title: 'Cart'});
    },

    handleCartReset: function() {
        CartActionCreators.reset();
        this.setState({ cartOpen: false, screen: 'cart', title: 'Cart'});
    },

    handleCartTouchTap(event) {
        if(AuthStore.isLoggedIn()) {
            this.setState({cartOpen: true});
        } else {
            this.props.history.push('login');
        }

    },

    open: function() {
        this.setState({cartOpen: true});
    },

    onShipping: function() {
        this.setState({
            screen: 'shippingAddress',
            title: 'Shipping Address'
        })
    },

    onConfirmShippingAddress: function() {
        var data = {};

        data.shippingAddress = this.state.shippingAddress;
        data.cartTotal = this.state.cartTotal;
        data.cartItems = this.state.cartItems;

        AddressActionCreators.confirmShippingAddress(data);
        this.setState({
            screen: 'shippingTax',
            title: 'Shipping and Tax'
        })
    },

    onUpdateShippingAddress: function() {
        var data = {};

        data.shippingAddress = this.state.shippingAddress;
        data.cartTotal = this.state.cartTotal;
        data.cartItems = this.state.cartItems;

        AddressActionCreators.updateShippingAddress(data);
        this.setState({
            screen: 'shippingTax',
            title: 'Shipping and Tax'
        })
    },

    onShippingAddressChange: function(key, val) {
        //console.log('ExamplePage.onModelChange:', key);
        //console.log('ExamplePage.onModelChange:', val);
        this.setState({shippingAddress: utils.selectOrSet(key, this.state.shippingAddress, val)});
    },

    onPayment: function() {
        // before switching to payment gateway, save the order here.
        var order = {};
        // all the numbers should be calculated on the server and only items should be passed here
        // need at least @rid/entityId, sku, quantity in order to calculate all the numbers.
        //console.log('cartItems', this.state.cartItems);
        var items = [];
        this.state.cartItems.forEach(function(cartItem) {
            var item = {};
            item.rid = cartItem.rid;
            item.sku = cartItem.sku;
            item.qty = cartItem.qty;
            items.push(item);
        });
        order.items = items;
        //console.log('order', order);

        OrderActionCreators.addOrder(order);
        this.setState({
            screen: 'payment',
            title: 'BrainTree Payment Gateway'
        })
    },

    onPlaceOrder: function() {
        this.setState({
            screen: 'checkoutDone',
            title: 'Order Summary'
        })
    },

    _onCartStoreChange: function() {
        //console.log('onChange is called', this.state.cartItems);
        this.setState({
            cartItems: CartStore.getAll(),
            cartItemsCount: CartStore.getCartItemsCount(),
            cartTotal: CartStore.getCartTotal()
        })
    },

    _onAuthStoreChange: function() {
        this.setState({
            shippingAddress: AuthStore.getShippingAddress() || {}
        })
    },

    componentDidMount: function() {
        CartStore.addChangeListener(this._onCartStoreChange);
        AuthStore.addChangeListener(this._onAuthStoreChange);
    },

    componentWillUnmount: function() {
        CartStore.removeChangeListener(this._onCartStoreChange);
        AuthStore.removeChangeListener(this._onAuthStoreChange);
    },

    render: function() {
        var actions = [];
        var contents;

        if(this.state.screen === 'cart') {
            contents =  <CheckoutCart cartItems = {this.state.cartItems} totalPrice= {this.state.cartTotal} />
            actions.push(<RaisedButton label="Buy now" primary={true} disabled={this.state.cartItems.length > 0? false : true} onTouchTap={this.onShipping} />)
            actions.push(<RaisedButton label="Cancel" secondary={true} onTouchTap={this.handleCartClose} />)
        } else if (this.state.screen === 'shippingAddress') {
            contents =  <ShippingAddress shippingAddress={this.state.shippingAddress} onShippingAddressChange={this.onShippingAddressChange} />
            actions.length = 0;
            actions.push(<RaisedButton label="Update" primary={true} onTouchTap={this.onUpdateShippingAddress} />);
            if(AuthStore.getShippingAddress()) {
                actions.push(<RaisedButton label="Confirm" primary={true} onTouchTap={this.onConfirmShippingAddress}/>);
            }
            actions.push(<RaisedButton label="Cancel" secondary={true} onTouchTap={this.handleCartClose} />);
        } else if (this.state.screen === 'shippingTax') {
            contents =  <ShippingTax cartItems = {this.state.cartItems} totalPrice= {this.state.cartTotal} />;
            actions.length = 0;
            actions.push(<RaisedButton label="Check out" primary={true} onTouchTap={this.onPayment} />);
            actions.push(<RaisedButton label="Cancel" secondary={true} onTouchTap={this.handleCartClose} />);
        } else if (this.state.screen === 'payment') {
            contents =  <Payment onPlaceOrder = {this.onPlaceOrder} />
        } else {
            contents =  <CheckoutDone />
            actions.length = 0;
            actions.push(<RaisedButton label="Close" primary={true} onTouchTap={this.handleCartReset} />);
        }

        var cartHeaderIconClasses = classNames({
            'cart-badge': true
        });

        return (

                <IconButton iconClassName="material-icons" onTouchTap={this.handleCartTouchTap}>shopping_cart</IconButton>
                {this.state.cartItemsCount}
                <Dialog
                    title={this.state.title}
                    actions={actions}
                    modal={true}
                    open={this.state.cartOpen}>
                    {contents}
                </Dialog>

        );

    }

});

module.exports = CheckoutButton;
<commit_msg>Modify shopping cart badge.<commit_after>/**
 * Created by steve on 12/04/15.
 */
var React = require('react');
var ReactPropTypes = React.PropTypes;
var CartStore = require('../../stores/CartStore');
var CartActionCreators = require('../../actions/CartActionCreators');
var AddressActionCreators = require('../../actions/AddressActionCreators');
var OrderActionCreators = require('../../actions/OrderActionCreators');
var Cart = require('./Cart');
var CheckoutCart = require('./CheckoutCart');
var ShippingAddress = require('./ShippingAddress');
var ShippingTax = require('./ShippingTax');
var CheckoutDone = require('./CheckoutDone');
var Payment = require('./Payment');
var AuthStore = require('../../stores/AuthStore');
var classNames = require('classnames');
var utils = require('react-schema-form/lib/utils.js');

import RaisedButton from 'material-ui/lib/raised-button';
import IconButton from 'material-ui/lib/icon-button';
import Dialog from 'material-ui/lib/dialog';
import Badge from 'material-ui/lib/badge';
import NotificationsIcon from 'material-ui/lib/svg-icons/social/notifications';

function getStateFromStores() {
    return {
        cartItems: CartStore.getAll(),
        cartItemsCount: CartStore.getCartItemsCount(),
        cartTotal: CartStore.getCartTotal(),
        cartOpen: CartStore.getCartStatus(),
        shippingAddress: AuthStore.getShippingAddress() || {},
        screen: 'cart',
        title: 'Cart'
    };
}

var CheckoutButton = React.createClass({

    getInitialState: () => getStateFromStores(),

    handleCartClose: function() {
        this.setState({ cartOpen: false, screen: 'cart', title: 'Cart'});
    },

    handleCartReset: function() {
        CartActionCreators.reset();
        this.setState({ cartOpen: false, screen: 'cart', title: 'Cart'});
    },

    handleCartTouchTap(event) {
        if(AuthStore.isLoggedIn()) {
            this.setState({cartOpen: true});
        } else {
            this.props.history.push('login');
        }

    },

    open: function() {
        this.setState({cartOpen: true});
    },

    onShipping: function() {
        this.setState({
            screen: 'shippingAddress',
            title: 'Shipping Address'
        })
    },

    onConfirmShippingAddress: function() {
        var data = {};

        data.shippingAddress = this.state.shippingAddress;
        data.cartTotal = this.state.cartTotal;
        data.cartItems = this.state.cartItems;

        AddressActionCreators.confirmShippingAddress(data);
        this.setState({
            screen: 'shippingTax',
            title: 'Shipping and Tax'
        })
    },

    onUpdateShippingAddress: function() {
        var data = {};

        data.shippingAddress = this.state.shippingAddress;
        data.cartTotal = this.state.cartTotal;
        data.cartItems = this.state.cartItems;

        AddressActionCreators.updateShippingAddress(data);
        this.setState({
            screen: 'shippingTax',
            title: 'Shipping and Tax'
        })
    },

    onShippingAddressChange: function(key, val) {
        //console.log('ExamplePage.onModelChange:', key);
        //console.log('ExamplePage.onModelChange:', val);
        this.setState({shippingAddress: utils.selectOrSet(key, this.state.shippingAddress, val)});
    },

    onPayment: function() {
        // before switching to payment gateway, save the order here.
        var order = {};
        // all the numbers should be calculated on the server and only items should be passed here
        // need at least @rid/entityId, sku, quantity in order to calculate all the numbers.
        //console.log('cartItems', this.state.cartItems);
        var items = [];
        this.state.cartItems.forEach(function(cartItem) {
            var item = {};
            item.rid = cartItem.rid;
            item.sku = cartItem.sku;
            item.qty = cartItem.qty;
            items.push(item);
        });
        order.items = items;
        //console.log('order', order);

        OrderActionCreators.addOrder(order);
        this.setState({
            screen: 'payment',
            title: 'BrainTree Payment Gateway'
        })
    },

    onPlaceOrder: function() {
        this.setState({
            screen: 'checkoutDone',
            title: 'Order Summary'
        })
    },

    _onCartStoreChange: function() {
        //console.log('onChange is called', this.state.cartItems);
        this.setState({
            cartItems: CartStore.getAll(),
            cartItemsCount: CartStore.getCartItemsCount(),
            cartTotal: CartStore.getCartTotal()
        })
    },

    _onAuthStoreChange: function() {
        this.setState({
            shippingAddress: AuthStore.getShippingAddress() || {}
        })
    },

    componentDidMount: function() {
        CartStore.addChangeListener(this._onCartStoreChange);
        AuthStore.addChangeListener(this._onAuthStoreChange);
    },

    componentWillUnmount: function() {
        CartStore.removeChangeListener(this._onCartStoreChange);
        AuthStore.removeChangeListener(this._onAuthStoreChange);
    },

    render: function() {
        var actions = [];
        var contents;

        if(this.state.screen === 'cart') {
            contents =  <CheckoutCart cartItems = {this.state.cartItems} totalPrice= {this.state.cartTotal} />
            actions.push(<RaisedButton label="Buy now" primary={true} disabled={this.state.cartItems.length > 0? false : true} onTouchTap={this.onShipping} />)
            actions.push(<RaisedButton label="Cancel" secondary={true} onTouchTap={this.handleCartClose} />)
        } else if (this.state.screen === 'shippingAddress') {
            contents =  <ShippingAddress shippingAddress={this.state.shippingAddress} onShippingAddressChange={this.onShippingAddressChange} />
            actions.length = 0;
            actions.push(<RaisedButton label="Update" primary={true} onTouchTap={this.onUpdateShippingAddress} />);
            if(AuthStore.getShippingAddress()) {
                actions.push(<RaisedButton label="Confirm" primary={true} onTouchTap={this.onConfirmShippingAddress}/>);
            }
            actions.push(<RaisedButton label="Cancel" secondary={true} onTouchTap={this.handleCartClose} />);
        } else if (this.state.screen === 'shippingTax') {
            contents =  <ShippingTax cartItems = {this.state.cartItems} totalPrice= {this.state.cartTotal} />;
            actions.length = 0;
            actions.push(<RaisedButton label="Check out" primary={true} onTouchTap={this.onPayment} />);
            actions.push(<RaisedButton label="Cancel" secondary={true} onTouchTap={this.handleCartClose} />);
        } else if (this.state.screen === 'payment') {
            contents =  <Payment onPlaceOrder = {this.onPlaceOrder} />
        } else {
            contents =  <CheckoutDone />
            actions.length = 0;
            actions.push(<RaisedButton label="Close" primary={true} onTouchTap={this.handleCartReset} />);
        }

        var cartHeaderIconClasses = classNames({
            'cart-badge': true
        });

        return (

                <Badge badgeContent={this.state.cartItemsCount} onTouchTap={this.handleCartTouchTap} primary={true} style={{margin: 0, padding: 0}} badgeStyle={{width:'22px', height: '22px'}}>
                    <IconButton iconClassName="material-icons" onTouchTap={this.handleCartTouchTap} iconStyle={{margin: 0}}>shopping_cart</IconButton>
                </Badge>
                <Dialog
                    title={this.state.title}
                    actions={actions}
                    modal={true}
                    open={this.state.cartOpen}>
                    {contents}
                </Dialog>

        );

    }

});

module.exports = CheckoutButton;
<|endoftext|>


<commit_before>"user strict";
Seed({
		name : "Mold.Lib.VDom.Builder",
		dna : "class",
		test : "Mold.Test.Lib.VDom.Builder",
		include : [
			"->Mold.Lib.Dom",
			"->Mold.Tools.Dev.CodeInclude",
			"Mold.Lib.VDom.ProtoNode",
			[
				{ DomNode : "Mold.Lib.VDom.DomNode" },
				{ BlockNode : "Mold.Lib.VDom.BlockNode" },
				{ ValueNode : "Mold.Lib.VDom.ValueNode" },
				{ TextNode : "Mold.Lib.VDom.TextNode" },
				{ AttributeNode : "Mold.Lib.VDom.AttributeNode" }
			]
		]
	},
	function(content){

		var _dom = new Mold.Lib.Dom(content);
		var _newDoc = document;
		var _doc = _dom.get();
		var _template = [];

		var BLOCK_START = "{{#";
		var BLOCK_NEGATIV = "{{^";
		var BLOCK_END = "{{/";
		var VALUE = "{{";
		var END = "}}";

		var _parseAttributes = function(attributes, domNode){

			var output = {};
			var i = 0, len = attributes.length;

			for(; i < len; i++){

				var selected = attributes[i];
				var newAttribute = new AttributeNode({
					name : selected.nodeName
				})

				domNode.addAttribute(newAttribute);
				newAttribute.addData(selected.nodeValue)

			}

		}

		var _parseNode = function(node, vDom, level){

			var level = level || 0;
			var parentNode = false;
			var collectedProtoDom = {};
			var i = 0, len = node.childNodes.length;

			for(; i < len; i++){
				var selected = node.childNodes[i];
				switch(selected.nodeType){

					//handel Elementnode
					case 1:

						var domNode = new DomNode({
							name : selected.nodeName
						});

						vDom.addNode(domNode);
						_parseAttributes(selected.attributes, domNode);
						_parseNode(selected, domNode)

						break;

					//handel Textnode
					case 3:
						//Block Node
						if(Mold.startsWith(selected.nodeValue, BLOCK_START)){

							var name = selected.nodeValue.replace(BLOCK_START, "").replace(END, "");
							var blockNode = new BlockNode({
								name : name
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;

							break;
						}

						//Block End
						if(Mold.startsWith(selected.nodeValue, BLOCK_END)){
							vDom = vDom.parent;
							break;
						}

						//Block Negativ
						if(Mold.startsWith(selected.nodeValue, BLOCK_NEGATIV)){

							break;
						}

						//Value
						if(Mold.startsWith(selected.nodeValue, VALUE)){
							var name = selected.nodeValue.replace(VALUE, "").replace(END, "");
							var valueNode = new ValueNode({
								name : name
							});

							vDom.addNode(valueNode);
							break;
						}

						//Standard text
						var textNode = new TextNode({
							name : "Text" + Mold.getId(),
							data : selected.nodeValue
						});

						vDom.addNode(textNode);

						break;
				}
			}
			return vDom;
		}

		this.dom = _parseNode(_doc, new DomNode({
			name : "root",
			protoDom : _doc
		}));

		this.publics = {

		}
	}
)<commit_msg>negativ block added<commit_after>"user strict";
Seed({
		name : "Mold.Lib.VDom.Builder",
		dna : "class",
		test : "Mold.Test.Lib.VDom.Builder",
		include : [
			"->Mold.Lib.Dom",
			"->Mold.Tools.Dev.CodeInclude",
			"Mold.Lib.VDom.ProtoNode",
			[
				{ DomNode : "Mold.Lib.VDom.DomNode" },
				{ BlockNode : "Mold.Lib.VDom.BlockNode" },
				{ ValueNode : "Mold.Lib.VDom.ValueNode" },
				{ TextNode : "Mold.Lib.VDom.TextNode" },
				{ AttributeNode : "Mold.Lib.VDom.AttributeNode" }
			]
		]
	},
	function(content){

		var _dom = new Mold.Lib.Dom(content);
		var _newDoc = document;
		var _doc = _dom.get();
		var _template = [];

		var BLOCK_START = "{{#";
		var BLOCK_NEGATIV = "{{^";
		var BLOCK_END = "{{/";
		var VALUE = "{{";
		var END = "}}";

		var _parseAttributes = function(attributes, domNode){

			var output = {};
			var i = 0, len = attributes.length;

			for(; i < len; i++){

				var selected = attributes[i];
				var newAttribute = new AttributeNode({
					name : selected.nodeName
				})

				domNode.addAttribute(newAttribute);
				newAttribute.addData(selected.nodeValue)

			}

		}

		var _parseNode = function(node, vDom, level){

			var level = level || 0;
			var parentNode = false;
			var collectedProtoDom = {};
			var i = 0, len = node.childNodes.length;

			for(; i < len; i++){
				var selected = node.childNodes[i];
				switch(selected.nodeType){

					//handel Elementnode
					case 1:

						var domNode = new DomNode({
							name : selected.nodeName
						});

						vDom.addNode(domNode);
						_parseAttributes(selected.attributes, domNode);
						_parseNode(selected, domNode)

						break;

					//handel Textnode
					case 3:
						//Block Node
						if(Mold.startsWith(selected.nodeValue, BLOCK_START)){

							var name = selected.nodeValue.replace(BLOCK_START, "").replace(END, "");
							var blockNode = new BlockNode({
								name : name
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;

							break;
						}

						//Block Negativ
						if(Mold.startsWith(selected.nodeValue, BLOCK_NEGATIV)){
							var name = selected.nodeValue.replace(BLOCK_NEGATIV, "").replace(END, "");
							var blockNode = new BlockNode({
								name : name,
								isNegative : true
							});
							vDom.addNode(blockNode);
							parentNode = vDom;
							vDom = blockNode;
							break;
						}

						//Block End
						if(Mold.startsWith(selected.nodeValue, BLOCK_END)){
							vDom = vDom.parent;
							break;
						}

						//Value
						if(Mold.startsWith(selected.nodeValue, VALUE)){
							var name = selected.nodeValue.replace(VALUE, "").replace(END, "");
							var valueNode = new ValueNode({
								name : name
							});

							vDom.addNode(valueNode);
							break;
						}

						//Standard text
						if(Mold.trim(selected.nodeValue)){
							var textNode = new TextNode({
								name : "Text" + Mold.getId(),
								data : selected.nodeValue
							});

							vDom.addNode(textNode);
						}

						break;
				}
			}
			return vDom;
		}

		this.dom = _parseNode(_doc, new DomNode({
			name : "root",
			protoDom : _doc
		}));

		this.publics = {

		}
	}
)<|endoftext|>


<commit_before>// Valid Word Abbreviation

// Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

// A string such as "word" contains only the following valid abbreviations:

// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
// Notice that only the above abbreviations are valid abbreviations of the string "word".
// Any other string is not a valid abbreviation of "word".

// Note:
// Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

// Example 1:
// Given s = "internationalization", abbr = "i12iz4n":

// Return true.
// Example 2:
// Given s = "apple", abbr = "a2e":

// Return false.
<commit_msg>add param<commit_after>// Valid Word Abbreviation

// Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

// A string such as "word" contains only the following valid abbreviations:

// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
// Notice that only the above abbreviations are valid abbreviations of the string "word".
// Any other string is not a valid abbreviation of "word".

// Note:
// Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

// Example 1:
// Given s = "internationalization", abbr = "i12iz4n":

// Return true.
// Example 2:
// Given s = "apple", abbr = "a2e":

// Return false.

/**
 * @param {string} word
 * @param {string} abbr
 * @return {boolean}
 */
<|endoftext|>


<commit_before>/* global angular */
(function () {
    'use strict';

    angular
        .module('plugins.series')
        .component('seriesView', {
            templateUrl: 'plugins/series/series.tmpl.html',
            controllerAs: 'vm',
            controller: seriesController
        });

    function seriesController($mdMedia, $mdDialog, $sce, $timeout, seriesService) {
        var vm = this;

        vm.sortOptions = [
            {
                nice: "Show name",
                small: "show_name"
            }, {
                nice: "Latest download date",
                small: "last_download_date"
            }
        ];

        vm.sortOption = "show_name";
        vm.order = "asc";

        var params = {
            forget: true
        };

        vm.searchTerm = '';

        vm.$onInit = activate;
        vm.forgetShow = forgetShow;
        vm.search = search;
        vm.toggleEpisodes = toggleEpisodes;
        vm.areEpisodesOnShowRow = areEpisodesOnShowRow;
        vm.getSeries = getSeries;
        vm.changeOrder = changeOrder;

        function activate() {
            getSeries();
        }

        function changeOrder() {
            vm.order === 'desc' ? setOrder('asc') : setOrder('desc');

            function setOrder(direction) {
                vm.order = direction;
                getSeries();
            }
        }

        function getSeries(page) {
            var options = {
                'page': page || 1,
                'per_page': 10,
                'in_config': 'all',
                'sort_by': vm.sortOption,
                'order': vm.order
            }
            seriesService.getShows(options)
                .then(setSeries)
                .cached(setSeries)
                .finally(function () {
                    vm.currentPage = options.page;
                });
        }

        function search() {
            vm.searchTerm ? searchShows() : emptySearch();

            function searchShows() {
                seriesService.searchShows(vm.searchTerm)
                    .then(setSeries)
                    .cached(setSeries)
                    .finally(function () {
                        vm.currentPage = 1;
                    });
            }

            function emptySearch() {
                getSeries();
            }
        }

        function setSeries(response) {
            vm.series = response.data;
            vm.linkHeader = response.headers().link;
        }

        function forgetShow(show) {
            var confirm = $mdDialog.confirm()
                .title('Confirm forgetting show.')
                .htmlContent($sce.trustAsHtml('Are you sure you want to completely forget ' + show.name + '?
 This will also forget all downloaded releases.'))
                .ok('Forget')
                .cancel('No');

            $mdDialog.show(confirm).then(function () {
                seriesService.deleteShow(show, params).then(function () {
                    getSeries(vm.currentPage);
                });
            });
        }

        function toggleEpisodes(show) {
            show === vm.selectedShow ? clearShow() : setSelectedShow();

            function clearShow() {
                vm.selectedShow = null;
            }

            function setSelectedShow() {
                vm.selectedShow = null;
                $timeout(function () {
                    vm.selectedShow = show;
                });
            }
        }

        function getNumberOfColumns() {
            if ($mdMedia('gt-lg')) {
                return 3;
            } else if ($mdMedia('gt-md')) {
                return 2;
            }
            return 1;
        }

        function areEpisodesOnShowRow(index) {
            var show = vm.selectedShow;

            if (!show) {
                return false;
            }

            var numberOfColumns = getNumberOfColumns();

            var column = index % numberOfColumns;
            var row = (index - column) / numberOfColumns;

            var showIndex = vm.series.indexOf(show);
            var showColumn = showIndex % numberOfColumns;
            var showRow = (showIndex - showColumn) / numberOfColumns;

            if (row !== showRow) {
                return false;
            }

            //Check if not last series, since it doesn't work correctly with the matrix here
            if (index !== vm.series.length - 1 && column !== numberOfColumns - 1) {
                return false;
            }

            return true;
        }
    }
}());
<commit_msg>[Fix][UI] Removing a show when in search mode, keeps the UI in search page #1559<commit_after>/* global angular */
(function () {
    'use strict';

    angular
        .module('plugins.series')
        .component('seriesView', {
            templateUrl: 'plugins/series/series.tmpl.html',
            controllerAs: 'vm',
            controller: seriesController
        });

    function seriesController($mdMedia, $mdDialog, $sce, $timeout, seriesService) {
        var vm = this;

        vm.sortOptions = [
            {
                nice: "Show name",
                small: "show_name"
            }, {
                nice: "Latest download date",
                small: "last_download_date"
            }
        ];

        vm.sortOption = "show_name";
        vm.order = "asc";

        var params = {
            forget: true
        };

        vm.searchTerm = '';

        vm.$onInit = activate;
        vm.forgetShow = forgetShow;
        vm.search = search;
        vm.toggleEpisodes = toggleEpisodes;
        vm.areEpisodesOnShowRow = areEpisodesOnShowRow;
        vm.getSeries = getSeries;
        vm.changeOrder = changeOrder;

        function activate() {
            getSeries();
        }

        function changeOrder() {
            vm.order === 'desc' ? setOrder('asc') : setOrder('desc');

            function setOrder(direction) {
                vm.order = direction;
                getSeries();
            }
        }

        function getSeries(page) {
            var options = {
                'page': page || 1,
                'per_page': 10,
                'in_config': 'all',
                'sort_by': vm.sortOption,
                'order': vm.order
            }
            seriesService.getShows(options)
                .then(setSeries)
                .cached(setSeries)
                .finally(function () {
                    vm.currentPage = options.page;
                });
        }

        function search() {
            vm.searchTerm ? searchShows() : emptySearch();

            function searchShows() {
                seriesService.searchShows(vm.searchTerm)
                    .then(setSeries)
                    .cached(setSeries)
                    .finally(function () {
                        vm.currentPage = 1;
                    });
            }

            function emptySearch() {
                getSeries();
            }
        }

        function setSeries(response) {
            vm.series = response.data;
            vm.linkHeader = response.headers().link;
        }

        function forgetShow(show) {
            var confirm = $mdDialog.confirm()
                .title('Confirm forgetting show.')
                .htmlContent($sce.trustAsHtml('Are you sure you want to completely forget ' + show.name + '?
 This will also forget all downloaded releases.'))
                .ok('Forget')
                .cancel('No');

            $mdDialog.show(confirm).then(function () {
                seriesService.deleteShow(show, params).then(function () {
                    vm.searchTerm ? search() : getSeries(vm.currentPage);
                });
            });
        }

        function toggleEpisodes(show) {
            show === vm.selectedShow ? clearShow() : setSelectedShow();

            function clearShow() {
                vm.selectedShow = null;
            }

            function setSelectedShow() {
                vm.selectedShow = null;
                $timeout(function () {
                    vm.selectedShow = show;
                });
            }
        }

        function getNumberOfColumns() {
            if ($mdMedia('gt-lg')) {
                return 3;
            } else if ($mdMedia('gt-md')) {
                return 2;
            }
            return 1;
        }

        function areEpisodesOnShowRow(index) {
            var show = vm.selectedShow;

            if (!show) {
                return false;
            }

            var numberOfColumns = getNumberOfColumns();

            var column = index % numberOfColumns;
            var row = (index - column) / numberOfColumns;

            var showIndex = vm.series.indexOf(show);
            var showColumn = showIndex % numberOfColumns;
            var showRow = (showIndex - showColumn) / numberOfColumns;

            if (row !== showRow) {
                return false;
            }

            //Check if not last series, since it doesn't work correctly with the matrix here
            if (index !== vm.series.length - 1 && column !== numberOfColumns - 1) {
                return false;
            }

            return true;
        }
    }
}());
<|endoftext|>


<commit_before>
module.exports = function(skill, info, bot, message) {
  bot.reply(message, 'that dude cray-cray'};
};
<commit_msg>Update BobTrump.js<commit_after>module.exports = function(skill, info, bot, message) {
  bot.reply(message, 'that dude cray-cray'};
};
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import { View, Text } from 'react-native'
import { endOfMonth, differenceInCalendarDays, getDate } from 'date-fns'
import _ from 'lodash'

import styles from './Trends.styles'

const Trends = ({ data, available }) => {
  const debitByDay = _(data)
    .groupBy('date')
    .mapValues(value => _.sum(value.map(({ amount }) => -amount)))
    .values()
    .value()

  const meanByDay = _(getDate(new Date()))
    .range()
    .map(index => _.get(debitByDay, [index], 0))
    .sort((a, b) => a - b)
    .slice(1, -1) // Remove min and max
    .mean()

  const daysLeftInMonth = differenceInCalendarDays(
    endOfMonth(new Date()),
    new Date(),
  )

  const dayLeftBeforeBankruptcy = available / meanByDay | 1

  return (
    <View style={styles.Trends}>
      <Text style={styles.big}>{available.toFixed(2)} €</Text>
      <Text style={styles.margin}>Total available</Text>
      <Text style={styles.big}>{meanByDay.toFixed(2)} €</Text>
      <Text style={styles.margin}>Spent by day (mean)</Text>
      <Text style={styles.big}>{debitByDay[0].toFixed(2)} €</Text>
      <Text style={styles.margin}>Spent today</Text>
      <Text style={styles.big}>{dayLeftBeforeBankruptcy}</Text>
      <Text style={styles.color}>Day(s) left before bankruptcy</Text>
      <Text style={styles.color}>{daysLeftInMonth} day(s) left in month</Text>
    </View>
  )
}

Trends.propTypes = {
  data: PropTypes.object.isRequired,
  available: PropTypes.number.isRequired,
}

export default Trends
<commit_msg>[UPD] add date to last spent<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { View, Text } from 'react-native'
import { endOfMonth, differenceInCalendarDays, getDate } from 'date-fns'
import _ from 'lodash'

import styles from './Trends.styles'

const Trends = ({ data, available }) => {
  const debitByDay = _(data)
    .groupBy('date')
    .map((value, date) => ({ date, amount: _.sum(value.map(({ amount }) => -amount)) }))
    .value()

  const meanByDay = _(getDate(new Date()))
    .range()
    .map(index => _.get(debitByDay, `[${index}].amount`, 0))
    .sort((a, b) => a - b)
    .slice(1, -1) // Remove min and max
    .mean()

  const daysLeftInMonth = differenceInCalendarDays(
    endOfMonth(new Date()),
    new Date(),
  )

  const dayLeftBeforeBankruptcy = available / meanByDay | 1

  return (
    <View style={styles.Trends}>
      <Text style={styles.big}>{available.toFixed(2)} €</Text>
      <Text style={styles.margin}>Total available</Text>
      <Text style={styles.big}>{meanByDay.toFixed(2)} €</Text>
      <Text style={styles.margin}>Spent by day (mean)</Text>
      <Text style={styles.big}>{debitByDay[0].amount.toFixed(2)} €</Text>
      <Text style={styles.margin}>Spent on {debitByDay[0].date}</Text>
      <Text style={styles.big}>{dayLeftBeforeBankruptcy}</Text>
      <Text style={styles.color}>Day(s) left before bankruptcy</Text>
      <Text style={styles.color}>{daysLeftInMonth} day(s) left in month</Text>
    </View>
  )
}

Trends.propTypes = {
  data: PropTypes.object.isRequired,
  available: PropTypes.number.isRequired,
}

export default Trends
<|endoftext|>


<commit_before>var m = require('mithril')
var Navbar         = require('../../components/navbar/navbar.js')
var Phases         = require('../../components/phases/phases.js')
var OutcomesGraph  = require('../../components/outcomesGraph/outcomesGraph.js')
var Messaging      = require('../../components/messaging/messaging.js')

exports.controller = function() {}

exports.view = function(ctrl) {

  return m('.container', [
    m.component(OutcomesGraph),
    m.component(Phases),
    m.component(Messaging)
  ])
}

//TO get users: GET request to

//
//

//

//

//
 This div is 12 - columns wide

//
This div is 6-columns wide

//
 This div is 6 - columns wide

//

//

//

//Ideas for Outcomes Page
//1) Active vs Inactive users
//Active = actively looking for a job
//Inactive = no longer looking for a job, but data should still be available<commit_msg>navbar home and student routes working<commit_after>var m = require('mithril')
var Navbar         = require('../../components/navbar/navbar.js')
// var Phases         = require('../../components/phases/phases.js')
var OutcomesGraph  = require('../../components/outcomesGraph/outcomesGraph.js')
var Messaging      = require('../../components/messaging/messaging.js')

exports.controller = function() {}

exports.view = function(ctrl) {

  return m('.container', [
    m.component(OutcomesGraph),
    m.component(Phases),
    m.component(Messaging)
  ])
}

//TO get users: GET request to

//
//

//

//

//
 This div is 12 - columns wide

//
This div is 6-columns wide

//
 This div is 6 - columns wide

//

//

//

//Ideas for Outcomes Page
//1) Active vs Inactive users
//Active = actively looking for a job
//Inactive = no longer looking for a job, but data should still be available<|endoftext|>


<commit_before>/**
 * ScreenshotsController
 * ====================
 * Handles display of a user screenshots.
 */

function ScreenshotsController($stateParams, $state, $location, screenshots, Screenshot, User) {
  var _this = this;
  this.screenshots = screenshots;
  this.url = '';

  /**
   * displays the form for adding another screenshot if the authenticated user
   * is the same user whos page we are viewing.
   */
  this.isUser = User.getUser() !== null && User.getUser().username === $stateParams.username;

  this.addScreenshot = function(url){
    Screenshot.addScreenshot(url)
      .then(function(data){
        console.log('response on create', data);
        // create an array if one doesnt exist, otherwise concat onto it
        _this.screenshots = Array.isArray(_this.screenshots)
          ? _this.screenshots.concat([data.data])
          : [data.data];

      });
  };

  // we are injecting screenshots from resolve but this might be useful in the future.
  this.getScreenshots = function(id){
    Screenshot.getScreenshots(id)
      .success(function(data){
        console.log(data);
        //this.screenshots = data; -> don't need this since we resolve the screenshots on app.js and inject them here
      });
  };

  this.changeView = function(screenshotId) {
    // navigate to nested user view screenshot
    $state.go('user.screenshot', { screenshotId: screenshotId });
  };
}

ScreenshotsController.$inject = [
  '$stateParams',
  '$state',
  '$location',
  'screenshots',
  'Screenshot',
  'User'
];

angular.module('Archivr.screenshots', [
  'Archivr.services.User',
  'Archivr.services.Screenshot'
]).controller('ScreenshotsController', ScreenshotsController);
<commit_msg>default to empty array<commit_after>/**
 * ScreenshotsController
 * ====================
 * Handles display of a user screenshots.
 */

function ScreenshotsController($stateParams, $state, $location, screenshots, Screenshot, User) {
  var _this = this;
  this.screenshots = screenshots === undefined ? [] : screenshots;
  this.url = '';

  /**
   * displays the form for adding another screenshot if the authenticated user
   * is the same user whos page we are viewing.
   */
  this.isUser = User.getUser() !== null && User.getUser().username === $stateParams.username;

  this.addScreenshot = function(url){
    Screenshot.addScreenshot(url)
      .then(function(data){
        console.log('response on create', data);
        // create an array if one doesnt exist, otherwise concat onto it
        _this.screenshots.push(data.data);

      });
  };

  // we are injecting screenshots from resolve but this might be useful in the future.
  this.getScreenshots = function(id){
    Screenshot.getScreenshots(id)
      .success(function(data){
        console.log(data);
        //this.screenshots = data; -> don't need this since we resolve the screenshots on app.js and inject them here
      });
  };

  this.changeView = function(screenshotId) {
    // navigate to nested user view screenshot
    $state.go('user.screenshot', { screenshotId: screenshotId });
  };
}

ScreenshotsController.$inject = [
  '$stateParams',
  '$state',
  '$location',
  'screenshots',
  'Screenshot',
  'User'
];

angular.module('Archivr.screenshots', [
  'Archivr.services.User',
  'Archivr.services.Screenshot'
]).controller('ScreenshotsController', ScreenshotsController);
<|endoftext|>


<commit_before>/*eslint-disable no-undef*/
import React from 'react'
import {findDOMNode} from 'react-dom'
import request from 'superagent'
import http from 'http'

class Instagram extends React.Component {
  static propTypes = {
    'embed': React.PropTypes.string
  }

  constructor (props) {
    super(props)
    this.state = {}
  }

  componentDidMount () {
    this.createInstagram()
  }

  componentDidUpdate (prevProps, prevState) {
    if (!prevState.html && this.state.html) {
      window.instgrm.Embeds.process()
    }
  }

  createInstagram () {
    const postUrl = this.props.embed

    request
      .get(`${process.env.API || http://localhost:3000/api}/getInsta?url=${postUrl}`)
      .end((err, res) => {
        if (err) console.error(err)
        else {
          this.setState({
            'html': res.body.html
          })
        }
      })
  }

  render () {
    if (!this.state.html) return null

    return (

    )
  }
}

export default Instagram
<commit_msg>string<commit_after>/*eslint-disable no-undef*/
import React from 'react'
import {findDOMNode} from 'react-dom'
import request from 'superagent'
import http from 'http'

class Instagram extends React.Component {
  static propTypes = {
    'embed': React.PropTypes.string
  }

  constructor (props) {
    super(props)
    this.state = {}
  }

  componentDidMount () {
    this.createInstagram()
  }

  componentDidUpdate (prevProps, prevState) {
    if (!prevState.html && this.state.html) {
      window.instgrm.Embeds.process()
    }
  }

  createInstagram () {
    const postUrl = this.props.embed

    request
      .get(`${process.env.API || 'http://localhost:3000/api'}/getInsta?url=${postUrl}`)
      .end((err, res) => {
        if (err) console.error(err)
        else {
          this.setState({
            'html': res.body.html
          })
        }
      })
  }

  render () {
    if (!this.state.html) return null

    return (

    )
  }
}

export default Instagram
<|endoftext|>


<commit_before>import React from 'react'

export default React.createClass({

	displayName: 'Results Component',

	render() {
		return (

	            [rabbitfighter@cryptolab.net]

	    )
	}
})<commit_msg>Fixed formatting<commit_after>import React from 'react'

export default React.createClass({

    displayName: 'Results Component',

    render() {
	return (

	        [rabbitfighter@cryptolab.net]

	)
    }
})
<|endoftext|>


<commit_before>var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // eval-source-map is faster for development
  devtool: '#eval-source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    })
  ]
})
<commit_msg>fix sourcemap<commit_after>var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // eval-source-map is faster, but cannot debug
  devtool: '#source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    })
  ]
})
<|endoftext|>


<commit_before>var config = require('./config')('development')
var webpack = require('webpack')

var scssLoaders = [
  'vue-style-loader',
  'css-loader',
  'postcss-loader',
  {
    loader: 'sass-loader',
    options: config.sassLoaderOptions
  }
]

module.exports = {
  entry: config.entry,

  output: {
    filename: '[name].js' // for multi chunks
  },

  resolve: config.resolve,
  resolveLoader: config.resolveLoader,

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.NamedModulesPlugin()
  ].concat(config.plugins),

  devServer: {
    noInfo: true,
    host: '0.0.0.0',
    port: config.port,
    disableHostCheck: true
  },
  devtool: '#cheap-module-eval-source-map',

  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            css: [
              'vue-style-loader',
              'css-loader'
            ],
            scss: scssLoaders
          }
        }
      },

      {
        // scss
        test: /\.scss$/,
        use: scssLoaders
      },

      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },

      {
        test: /\.svg$/,
        use: [
          'svg-sprite-loader',
          {
            loader: 'svgo-loader',
            options: {
              plugins: [
                { removeTitle: true },
                { removeAttrs: { attrs: '(class|fill)' } }
              ]
            }
          }
        ]
      },

      {
        test: /\.(png|jpg)$/,
        loader: 'file-loader'
      }
    ]
  }
}
<commit_msg>babel transform webpack-dev-server for lower devices<commit_after>var config = require('./config')('development')
var webpack = require('webpack')

var scssLoaders = [
  'vue-style-loader',
  'css-loader',
  'postcss-loader',
  {
    loader: 'sass-loader',
    options: config.sassLoaderOptions
  }
]

module.exports = {
  entry: config.entry,

  output: {
    filename: '[name].js' // for multi chunks
  },

  resolve: config.resolve,
  resolveLoader: config.resolveLoader,

  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.NamedModulesPlugin()
  ].concat(config.plugins),

  devServer: {
    noInfo: true,
    host: '0.0.0.0',
    port: config.port,
    disableHostCheck: true
  },
  devtool: '#cheap-module-eval-source-map',

  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            css: [
              'vue-style-loader',
              'css-loader'
            ],
            scss: scssLoaders
          }
        }
      },

      {
        // scss
        test: /\.scss$/,
        use: scssLoaders
      },

      {
        test: /\.js$/,
        // transform webpack-dev-server/client/index.js for iOS 8
        exclude: /node_modules\/(?!webpack-dev)/,
        loader: 'babel-loader'
      },

      {
        test: /\.svg$/,
        use: [
          'svg-sprite-loader',
          {
            loader: 'svgo-loader',
            options: {
              plugins: [
                { removeTitle: true },
                { removeAttrs: { attrs: '(class|fill)' } }
              ]
            }
          }
        ]
      },

      {
        test: /\.(png|jpg)$/,
        loader: 'file-loader'
      }
    ]
  }
}
<|endoftext|>


<commit_before>'use strict';

let fs = require('fs');
let path = require('path');
let fse = require('fs-extra');
let moment = require('moment');
let webpack = require('webpack');
let autoprefixer = require('autoprefixer');
let CopyWebpackPlugin = require('copy-webpack-plugin');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let CleanWebpackPlugin = require('clean-webpack-plugin');
let UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
let ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
let HtmlInlineSourceWebpackPlugin = require('html-inline-source-webpack-plugin');

const entry = require('./webpack.entry.json');
const packageJson = require('../package.json');

const alias = {};
const imageSize = 10240;
const sourcePath = path.join(__dirname, '../src');
const constant = {
    NODE_ENV : 'production',
    NAME : packageJson.name,
    VERSION : packageJson.version,
};

const banner =
`@ProjectName ${ packageJson.name }
@Version ${ packageJson.version }
@Author ${ packageJson.author.name }(${ packageJson.author.url })
@Update ${ moment().format('YYYY-MM-DD h:mm:ss a') }`;

process.argv.forEach(( param ) => {
    if (/^--/.test(param)) {
        let array = param.slice(2).split('=');
        let key = array[0];
        let value = array[1] || true;
        process.argv[key] = value;
    }
});

let config = {
    entry,
    output : process.argv.build == 'js' ? {
        path : './dist/',
        filename : `[name].min.js`,
        library : process.argv.library,
        libraryTarget : process.argv.libraryTarget,
    } : {
        path : './dist/',
        filename : 'js/[name].js',
        publicPath : '',
    },
    extensions : ['.vue', '.js', '.coffee', '.json', '.scss'],
    resolve : {
        alias,
    },
    module : {
        loaders : [
            {
                test : /\.vue$/,
                loader : 'vue',
            },
            {
                test : /\.(png|jpg|gif|svg)$/,
                loader : `url?limit=${ imageSize }&name=${ process.argv.build == 'js' ? '../' : '' }img/[name].[ext]?[hash]`,
            },
            {
                test : /\.css$/,
                loader : process.argv.build == 'js' ? 'css!postcss' : ExtractTextWebpackPlugin.extract('style', 'css!postcss'),
            },
            {
                test : /\.scss$/,
                loader : process.argv.build == 'js' ? 'css!postcss!sass' : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            },
            {
                test : /\.js$/,
                exclude : path.join(__dirname, '../node_modules/'),
                loader : 'babel',
                query : {
                    presets : ['es2015', 'stage-0'],
                    // plugins : ['transform-remove-strict-mode'],
                    // plugins: ['transform-runtime'],
                },
            },
            {
                test : /\.coffee/,
                loader : 'coffee',
            },
            {
                test : /\.(coffee\.md|litcoffee)$/,
                loader : 'coffee?literate',
            },
        ],
    },
    plugins : [
        new webpack.DefinePlugin({ 'process.env' : constants.map(( value ) => JSON.stringify(value)) });
        new webpack.BannerPlugin(banner),
    ],
    vue : {
        loaders : {
            sass : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            scss : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
        },
    },
    postcss () {
        return [autoprefixer({ browsers : ['last 2 versions'] })];
    },
};

if (process.argv.build == 'js') {
    config.plugins.unshift(
        new CleanWebpackPlugin(['dist'], { root : path.join(__dirname, '..') }),
        new webpack.optimize.UglifyJsPlugin({
            compress : {
                warnings : false,
            },
            output : {
                comments : false,
            },
        }),
        new UnminifiedWebpackPlugin()
    );
} else {
    config.plugins.unshift(
        new CleanWebpackPlugin(['dist'], { root : path.join(__dirname, '..') }),
        new CopyWebpackPlugin(fs.readdirSync(sourcePath).map(( filename ) => {
            if (filename[0] === '.') {
                return;
            }
            let file = path.join(sourcePath, filename);
            let stats = fs.statSync(file);
            if (stats.isDirectory()) {
                if (filename == 'entry') {
                    return;
                }
            }
            if (stats.isFile()) {
                if (path.extname(file) == '.html') {
                    return;
                }
                if (path.extname(file) == '.appcache') {
                    return;
                }
            }
            return {
                from : file,
                to : filename,
            };
        })),
        new webpack.optimize.UglifyJsPlugin({
            compress : {
                warnings : false,
            },
            output : {
                comments : false,
            },
        })
    );
    config.plugins.push(new ExtractTextWebpackPlugin('css/[name].css'));
    fs.readdirSync(sourcePath).forEach(( filename ) => {
        let template = path.join(sourcePath, filename);
        if (/\.(appcache|html)$/.test(filename)) {
            config.plugins.push(new HtmlWebpackPlugin({
                minify : false,
                inject : false,
                filename,
                template,
            }));
        }
    });
    config.plugins.push(new HtmlInlineSourceWebpackPlugin());
}

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

let fs = require('fs');
let path = require('path');
let fse = require('fs-extra');
let moment = require('moment');
let webpack = require('webpack');
let autoprefixer = require('autoprefixer');
let CopyWebpackPlugin = require('copy-webpack-plugin');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let CleanWebpackPlugin = require('clean-webpack-plugin');
let UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
let ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
let HtmlInlineSourceWebpackPlugin = require('html-inline-source-webpack-plugin');

const entry = require('./webpack.entry.json');
const packageJson = require('../package.json');

const alias = {};
const imageSize = 10240;
const sourcePath = path.resolve('../src');
const constants = {
    NODE_ENV : 'production',
    NAME : packageJson.name,
    VERSION : packageJson.version,
};

const banner =
`@ProjectName ${ packageJson.name }
@Version ${ packageJson.version }
@Author ${ packageJson.author.name }(${ packageJson.author.url })
@Update ${ moment().format('YYYY-MM-DD h:mm:ss a') }`;

process.argv.forEach(( param ) => {
    if (/^--/.test(param)) {
        let array = param.slice(2).split('=');
        let key = array[0];
        let value = array[1] || true;
        process.argv[key] = value;
    }
});

let config = {
    entry,
    output : process.argv.build == 'js' ? {
        path : './dist/',
        filename : `[name].min.js`,
        library : process.argv.library,
        libraryTarget : process.argv.libraryTarget,
    } : {
        path : './dist/',
        filename : 'js/[name].js',
        publicPath : '',
    },
    extensions : ['.vue', '.js', '.coffee', '.json', '.scss'],
    resolve : {
        alias,
    },
    module : {
        loaders : [
            {
                test : /\.vue$/,
                loader : 'vue',
            },
            {
                test : /\.(png|jpg|gif|svg)$/,
                loader : `url?limit=${ imageSize }&name=${ process.argv.build == 'js' ? '../' : '' }img/[name].[ext]?[hash]`,
            },
            {
                test : /\.css$/,
                loader : process.argv.build == 'js' ? 'css!postcss' : ExtractTextWebpackPlugin.extract('style', 'css!postcss'),
            },
            {
                test : /\.scss$/,
                loader : process.argv.build == 'js' ? 'css!postcss!sass' : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            },
            {
                test : /\.js$/,
                exclude : path.resolve('node_modules'),
                loader : 'babel',
                query : {
                    presets : ['es2015', 'stage-0'],
                    // plugins : ['transform-remove-strict-mode'],
                    // plugins: ['transform-runtime'],
                },
            },
            {
                test : /\.coffee/,
                loader : 'coffee',
            },
            {
                test : /\.(coffee\.md|litcoffee)$/,
                loader : 'coffee?literate',
            },
        ],
    },
    plugins : [
        new webpack.DefinePlugin({ 'process.env' : (Object.keys(constants).forEach(( key ) => constants[key] = JSON.stringify(constants[key])), constants) }),
        new webpack.BannerPlugin(banner),
    ],
    vue : {
        loaders : {
            sass : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
            scss : ExtractTextWebpackPlugin.extract('style', 'css!postcss!sass'),
        },
    },
    postcss () {
        return [autoprefixer({ browsers : ['last 2 versions'] })];
    },
};

if (process.argv.build == 'js') {
    config.plugins.unshift(
        new CleanWebpackPlugin(['dist'], { root : path.resolve('..') }),
        new webpack.optimize.UglifyJsPlugin({
            compress : {
                warnings : false,
            },
            output : {
                comments : false,
            },
        }),
        new UnminifiedWebpackPlugin()
    );
} else {
    config.plugins.unshift(
        new CleanWebpackPlugin(['dist'], { root : path.resolve('..') }),
        new CopyWebpackPlugin(fs.readdirSync(sourcePath).map(( filename ) => {
            if (filename[0] === '.') {
                return;
            }
            let file = path.join(sourcePath, filename);
            let stats = fs.statSync(file);
            if (stats.isDirectory()) {
                if (filename == 'entry') {
                    return;
                }
            }
            if (stats.isFile()) {
                if (path.extname(file) == '.html') {
                    return;
                }
                if (path.extname(file) == '.appcache') {
                    return;
                }
            }
            return {
                from : file,
                to : filename,
            };
        })),
        new webpack.optimize.UglifyJsPlugin({
            compress : {
                warnings : false,
            },
            output : {
                comments : false,
            },
        })
    );
    config.plugins.push(new ExtractTextWebpackPlugin('css/[name].css'));
    fs.readdirSync(sourcePath).forEach(( filename ) => {
        let template = path.join(sourcePath, filename);
        if (/\.(appcache|html)$/.test(filename)) {
            config.plugins.push(new HtmlWebpackPlugin({
                minify : false,
                inject : false,
                filename,
                template,
            }));
        }
    });
    config.plugins.push(new HtmlInlineSourceWebpackPlugin());
}

module.exports = config;
<|endoftext|>


<commit_before>var
  config = require('../config'),
  webpack = require('webpack'),
  merge = require('webpack-merge'),
  cssUtils = require('./css-utils'),
  baseWebpackConfig = require('./webpack.base.conf'),
  HtmlWebpackPlugin = require('html-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/hot-reload'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  // eval-source-map is faster for development
  devtool: '#eval-source-map',
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  module: {
    rules: cssUtils.styleRules({
      sourceMap: config.dev.cssSourceMap,
      postcss: true
    })
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'src/index.html',
      inject: true
    })
  ]
})
<commit_msg>chore: Disable webpack perf hints for dev mode<commit_after>var
  config = require('../config'),
  webpack = require('webpack'),
  merge = require('webpack-merge'),
  cssUtils = require('./css-utils'),
  baseWebpackConfig = require('./webpack.base.conf'),
  HtmlWebpackPlugin = require('html-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/hot-reload'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  // eval-source-map is faster for development
  devtool: '#eval-source-map',
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  module: {
    rules: cssUtils.styleRules({
      sourceMap: config.dev.cssSourceMap,
      postcss: true
    })
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'src/index.html',
      inject: true
    })
  ],
  performance: {
    hints: false
  }
})
<|endoftext|>


<commit_before>import { set } from 'lodash';
import { getModule, replaceCodeMemory, addNpmScriptMemory, addNpmPackageMemory } from '../utils';

export default async function genereateWebpackBuildTool(params) {
  set(params, ['build', 'webpack.config.js'], await getModule('build-tool/webpack/webpack.config.js'));

  await addNpmScriptMemory('build', 'webpack --display-error-details', params);
  await addNpmPackageMemory('webpack', params);
  await addNpmPackageMemory('webpack-dev-middleware', params, true);
  await addNpmPackageMemory('webpack-hot-middleware', params, true);
  await addNpmPackageMemory('babel-core', params);
  await addNpmPackageMemory('babel-loader', params);
  await addNpmPackageMemory('babel-preset-es2015', params);

  switch (params.framework) {
    case 'express':
      await replaceCodeMemory(params, 'server.js', 'WEBPACK_REQUIRE', await getModule('build-tool/webpack/webpack-require.js'));
      await replaceCodeMemory(params, 'server.js', 'WEBPACK_COMPILER', await getModule('build-tool/webpack/webpack-compiler.js'));
      await replaceCodeMemory(params, 'server.js', 'WEBPACK_MIDDLEWARE', await getModule('build-tool/webpack/webpack-middleware.js'));
      break;
    case 'meteor':
      break;
    default:
      break;
  }

  switch (params.cssPreprocessor) {
    case 'sass':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/sass-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/sass-middleware.js'));
      await addNpmPackageMemory('node-sass-middleware', params);
      break;
    case 'less':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/less-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/less-middleware.js'));
      await addNpmPackageMemory('less-middleware', params);
      break;
    case 'postcss':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/postcss-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/postcss-middleware.js'));
      await addNpmPackageMemory('postcss-middleware', params);
      await addNpmPackageMemory('postcss-cssnext', params);
      await addNpmPackageMemory('postcss-import', params);
      break;
    case 'stylus':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/stylus-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/stylus-middleware.js'));
      await addNpmPackageMemory('express-stylus', params);
      await addNpmPackageMemory('nib', params);
      break;
    default:
      break;
  }

  switch (params.jsFramework) {
    case 'react':
      await replaceCodeMemory(params, 'webpack.config.js', 'WEBPACK_JAVASCRIPT_LOADER', await getModule('build-tool/webpack/webpack-react-loader.js'));
      await replaceCodeMemory(params, 'app/store/configureStore.js', 'WEBPACK_HOT_REDUCER', await getModule('build-tool/webpack/webpack-hot-reducer.js'));
      await addNpmPackageMemory('babel-plugin-react-transform', params, true);
      await addNpmPackageMemory('react-transform-hmr', params, true);
      await addNpmPackageMemory('react-transform-catch-errors', params, true);
      await addNpmPackageMemory('babel-preset-react', params);
      await addNpmPackageMemory('redbox-react', params, true);
      break;
    case 'angularjs':
      break;
    default:
      await replaceCodeMemory(params, 'webpack.config.js', 'WEBPACK_JAVASCRIPT_LOADER', await getModule('build-tool/webpack/webpack-vanillajs-loader.js'));
      break;
  }
}
<commit_msg>add postinstall npm script for webpack generator<commit_after>import { set } from 'lodash';
import { getModule, replaceCodeMemory, addNpmScriptMemory, addNpmPackageMemory } from '../utils';

export default async function genereateWebpackBuildTool(params) {
  set(params, ['build', 'webpack.config.js'], await getModule('build-tool/webpack/webpack.config.js'));

  await addNpmScriptMemory('build', 'webpack --display-error-details', params);
  await addNpmScriptMemory('postinstall', 'npm run build', params);
  await addNpmPackageMemory('webpack', params);
  await addNpmPackageMemory('webpack-dev-middleware', params, true);
  await addNpmPackageMemory('webpack-hot-middleware', params, true);
  await addNpmPackageMemory('babel-core', params);
  await addNpmPackageMemory('babel-loader', params);
  await addNpmPackageMemory('babel-preset-es2015', params);

  switch (params.framework) {
    case 'express':
      await replaceCodeMemory(params, 'server.js', 'WEBPACK_REQUIRE', await getModule('build-tool/webpack/webpack-require.js'));
      await replaceCodeMemory(params, 'server.js', 'WEBPACK_COMPILER', await getModule('build-tool/webpack/webpack-compiler.js'));
      await replaceCodeMemory(params, 'server.js', 'WEBPACK_MIDDLEWARE', await getModule('build-tool/webpack/webpack-middleware.js'));
      break;
    case 'meteor':
      break;
    default:
      break;
  }

  switch (params.cssPreprocessor) {
    case 'sass':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/sass-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/sass-middleware.js'));
      await addNpmPackageMemory('node-sass-middleware', params);
      break;
    case 'less':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/less-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/less-middleware.js'));
      await addNpmPackageMemory('less-middleware', params);
      break;
    case 'postcss':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/postcss-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/postcss-middleware.js'));
      await addNpmPackageMemory('postcss-middleware', params);
      await addNpmPackageMemory('postcss-cssnext', params);
      await addNpmPackageMemory('postcss-import', params);
      break;
    case 'stylus':
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE_REQUIRE', await getModule('build-tool/none/stylus-middleware-require.js'));
      await replaceCodeMemory(params, 'server.js', 'CSS_PREPROCESSOR_MIDDLEWARE', await getModule('build-tool/none/stylus-middleware.js'));
      await addNpmPackageMemory('express-stylus', params);
      await addNpmPackageMemory('nib', params);
      break;
    default:
      break;
  }

  switch (params.jsFramework) {
    case 'react':
      await replaceCodeMemory(params, 'webpack.config.js', 'WEBPACK_JAVASCRIPT_LOADER', await getModule('build-tool/webpack/webpack-react-loader.js'));
      await replaceCodeMemory(params, 'app/store/configureStore.js', 'WEBPACK_HOT_REDUCER', await getModule('build-tool/webpack/webpack-hot-reducer.js'));
      await addNpmPackageMemory('babel-plugin-react-transform', params, true);
      await addNpmPackageMemory('react-transform-hmr', params, true);
      await addNpmPackageMemory('react-transform-catch-errors', params, true);
      await addNpmPackageMemory('babel-preset-react', params);
      await addNpmPackageMemory('redbox-react', params, true);
      break;
    case 'angularjs':
      break;
    default:
      await replaceCodeMemory(params, 'webpack.config.js', 'WEBPACK_JAVASCRIPT_LOADER', await getModule('build-tool/webpack/webpack-vanillajs-loader.js'));
      break;
  }
}
<|endoftext|>