<commit_before>'use strict';

var mongoose = require('mongoose'),
    LocalStrategy = require('passport-local').Strategy,
    TwitterStrategy = require('passport-twitter').Strategy,
    FacebookStrategy = require('passport-facebook').Strategy,
    GitHubStrategy = require('passport-github').Strategy,
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    LinkedinStrategy = require('passport-linkedin').Strategy,
    User = mongoose.model('User'),
    config = require('./config').passport;

module.exports = function(passport) {

    // Serialize the user id to push into the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // Deserialize the user object based on a pre-serialized token
    // which is the user id
    passport.deserializeUser(function(id, done) {
        User.findOne({
            _id: id
        }, function(err, user) {
            done(err, user && user.sanitize());
        });
    });

    // Use local strategy
    passport.use(new LocalStrategy({
            usernameField: 'email',
            passwordField: 'password'
        },
        function(email, password, done) {
            User.findOne({
                email: email
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    return done(null, false, {
                        message: 'Unknown user'
                    });
                }
                if (!user.authenticate(password)) {
                    return done(null, false, {
                        message: 'Invalid password'
                    });
                }
                return done(null, user.sanitize());
            });
        }
    ));

    // Use twitter strategy
    passport.use(new TwitterStrategy({
            consumerKey: config.twitter.clientID,
            consumerSecret: config.twitter.clientSecret,
            callbackURL: config.twitter.callbackURL
        },
        function(token, tokenSecret, profile, done) {
            User.findOne({
                'twitter.id_str': profile.id
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        username: profile.username,
                        provider: 'twitter',
                        twitter: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use facebook strategy
    passport.use(new FacebookStrategy({
            clientID: config.facebook.clientID,
            clientSecret: config.facebook.clientSecret,
            callbackURL: config.facebook.callbackURL
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'facebook.id': profile.id
            }, function(err, foundUser) {
                if (!foundUser) {
                    User.save({
                        firstName: profile.name.givenName,
                        lastName: profile.name.familyName,
                        email: profile.emails[0].value,
                        provider: 'facebook',
                        facebook: profile._json
                    }).then(function(newUser) {
                        return done(null, newUser.sanitize());
                    }).catch(function(err) {
                        return done(err);
                    });
                } else {
                    return done(err, foundUser && foundUser.sanitize());
                }
            });
        }
    ));

    // Use github strategy
    passport.use(new GitHubStrategy({
            clientID: config.github.clientID,
            clientSecret: config.github.clientSecret,
            callbackURL: config.github.callbackURL
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'github.id': profile.id
            }, function(err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.username,
                        provider: 'github',
                        github: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use google strategy
    passport.use(new GoogleStrategy({
            clientID: config.google.clientID,
            clientSecret: config.google.clientSecret,
            callbackURL: config.google.callbackURL
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'google.id': profile.id
            }, function(err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.emails[0].value,
                        provider: 'google',
                        google: profile._json
                    });
                    user.save(function(err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // use linkedin strategy
    passport.use(new LinkedinStrategy({
            consumerKey: config.linkedin.clientID,
            consumerSecret: config.linkedin.clientSecret,
            callbackURL: config.linkedin.callbackURL,
            profileFields: ['id', 'first-name', 'last-name', 'email-address', 'skills', 'location']
        },
        function(accessToken, refreshToken, profile, done) {
            User.findOne({
                'linkedin.id': profile.id
            }, function(err, foundUser) {
                if (!foundUser) {
                	console.log('checking');
                	console.dir(profile);
                    User.save({
                        firstName: profile._json.firstName,
                        lastName: profile._json.lastName,
                        email: profile._json.emailAddress,
                        provider: 'linkedin',
                        linkedin: profile._json
                    }).then(function(newUser) {
                        return done(null, newUser.sanitize());
                    }).catch(function(err) {
                        return done(err);
                    });
                } else {
                    return done(err, foundUser && foundUser.sanitize());
                }
            });
        }
    ));
};
<commit_msg>JSHInt needed to run to clean up files.<commit_after>'use strict';

var mongoose = require('mongoose'),
    LocalStrategy = require('passport-local').Strategy,
    TwitterStrategy = require('passport-twitter').Strategy,
    FacebookStrategy = require('passport-facebook').Strategy,
    GitHubStrategy = require('passport-github').Strategy,
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    LinkedinStrategy = require('passport-linkedin').Strategy,
    User = mongoose.model('User'),
    config = require('./config').passport;

module.exports = function (passport) {

    // Serialize the user id to push into the session
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    // Deserialize the user object based on a pre-serialized token
    // which is the user id
    passport.deserializeUser(function (id, done) {
        User.findOne({
            _id: id
        }, function (err, user) {
            done(err, user && user.sanitize());
        });
    });

    // Use local strategy
    passport.use(new LocalStrategy({
            usernameField: 'email',
            passwordField: 'password'
        },
        function (email, password, done) {
            User.findOne({
                email: email
            }, function (err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    return done(null, false, {
                        message: 'Unknown user'
                    });
                }
                if (!user.authenticate(password)) {
                    return done(null, false, {
                        message: 'Invalid password'
                    });
                }
                return done(null, user.sanitize());
            });
        }
    ));

    // Use twitter strategy
    passport.use(new TwitterStrategy({
            consumerKey: config.twitter.clientID,
            consumerSecret: config.twitter.clientSecret,
            callbackURL: config.twitter.callbackURL
        },
        function (token, tokenSecret, profile, done) {
            User.findOne({
                'twitter.id_str': profile.id
            }, function (err, user) {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        username: profile.username,
                        provider: 'twitter',
                        twitter: profile._json
                    });
                    user.save(function (err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use facebook strategy
    passport.use(new FacebookStrategy({
            clientID: config.facebook.clientID,
            clientSecret: config.facebook.clientSecret,
            callbackURL: config.facebook.callbackURL
        },
        function (accessToken, refreshToken, profile, done) {
            User.findOne({
                'facebook.id': profile.id
            }, function (err, foundUser) {
                if (!foundUser) {
                    User.save({
                        firstName: profile.name.givenName,
                        lastName: profile.name.familyName,
                        email: profile.emails[0].value,
                        provider: 'facebook',
                        facebook: profile._json
                    }).then(function (newUser) {
                        return done(null, newUser.sanitize());
                    }).catch(function (err) {
                        return done(err);
                    });
                } else {
                    return done(err, foundUser && foundUser.sanitize());
                }
            });
        }
    ));

    // Use github strategy
    passport.use(new GitHubStrategy({
            clientID: config.github.clientID,
            clientSecret: config.github.clientSecret,
            callbackURL: config.github.callbackURL
        },
        function (accessToken, refreshToken, profile, done) {
            User.findOne({
                'github.id': profile.id
            }, function (err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.username,
                        provider: 'github',
                        github: profile._json
                    });
                    user.save(function (err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // Use google strategy
    passport.use(new GoogleStrategy({
            clientID: config.google.clientID,
            clientSecret: config.google.clientSecret,
            callbackURL: config.google.callbackURL
        },
        function (accessToken, refreshToken, profile, done) {
            User.findOne({
                'google.id': profile.id
            }, function (err, user) {
                if (!user) {
                    user = new User({
                        name: profile.displayName,
                        email: profile.emails[0].value,
                        username: profile.emails[0].value,
                        provider: 'google',
                        google: profile._json
                    });
                    user.save(function (err) {
                        if (err) console.log(err);
                        return done(err, user);
                    });
                } else {
                    return done(err, user);
                }
            });
        }
    ));

    // use linkedin strategy
    passport.use(new LinkedinStrategy({
            consumerKey: config.linkedin.clientID,
            consumerSecret: config.linkedin.clientSecret,
            callbackURL: config.linkedin.callbackURL,
            profileFields: ['id', 'first-name', 'last-name', 'email-address', 'skills', 'location']
        },
        function (accessToken, refreshToken, profile, done) {
            User.findOne({
                'linkedin.id': profile.id
            }, function (err, foundUser) {
                if (!foundUser) {
                    console.log('checking');
                    console.dir(profile);
                    User.save({
                        firstName: profile._json.firstName,
                        lastName: profile._json.lastName,
                        email: profile._json.emailAddress,
                        provider: 'linkedin',
                        linkedin: profile._json
                    }).then(function (newUser) {
                        return done(null, newUser.sanitize());
                    }).catch(function (err) {
                        return done(err);
                    });
                } else {
                    return done(err, foundUser && foundUser.sanitize());
                }
            });
        }
    ));
};
<|endoftext|>


<commit_before>import { h, Component } from 'preact';

import logger from '../../../../helpers/logger/logger';

import productStore from '../../../../stores/product-store';

import productActions from '../../../../actions/product-actions';

import UI from '../../../UI';

export default class Competitor extends Component {
  convertXPtoLvl(value) {
    return Math.floor(value / 1000);
  }

  renderFeatureList(c, productId, rents: Array, ourCompany) {
    const ourCompanyId = 0;

    return c.features.map((f, featureId) => {
      let error;
      let differencePhrase = '';

      const difference = this.convertXPtoLvl(ourCompany.features.offer[featureId] - c.features[featureId].value);

      if (productStore.isShareableFeature(productId, featureId) && (difference > 0 || difference <= -1)) {
        let canRentTech = 'hide';

        let sender;
        let acceptor;

        let rentPhrase;
        let symbol;
        let symbolColor;

        let level;

        let rentStatus = {
          canAccept: true,
          canSend: true,
          weCanSend: true,
          weCanAccept: true,
          phrase: ''
        };

        const they = productStore.getRentingStatus(productId, featureId);
        rentStatus.theyCanAccept = they.canAccept;
        rentStatus.theyCanSend = they.canSend;

        const we = productStore.getRentingStatus(ourCompanyId, featureId);
        rentStatus.weCanAccept = we.canAccept;
        rentStatus.weCanSend = we.canSend;

        const weHaveConnectionAlready = productStore.isRentingAlready(productId, ourCompanyId, featureId);

        rents
          .filter(r => r.featureId === featureId && (r.out === productId || r.in === productId))
          .forEach(r => {
            const level = this.convertXPtoLvl(r.value);

            if (r.in === productId) {
              // if company accepts tech, it is frozen for any operations on this feature
              let name = r.out === ourCompanyId ? 'нас' : `"${r.senderName}"`;

              rentStatus.phrase = `Они арендуют технологию у ${name} (${level}lvl)`;
              rentStatus.canAccept = false;
              rentStatus.canSend = false;
            }

            if (r.out === productId) {
              // if company sends tech, it cannot accept anything, but can send this feature
              rentStatus.canAccept = false;
              rentStatus.canSend = true;
              rentStatus.phrase = 'Они сдают эту технологию в аренду';

              if (r.in === ourCompanyId) {
                rentStatus.phrase += ' нам';
              }
            }
          });

        if (difference > 0) {
          // our feature is better than competitor's one
          sender = ourCompanyId;
          acceptor = productId;

          symbol = UI.symbols.triangle.up;
          symbolColor = "positive";

          rentPhrase = "Сдать технологию в аренду на год";
          level = `+${difference}`;

          // we have incoming rent contract with another company
          // we have outgoing rent contract with another company

          if (rentStatus.weCanSend) {
            if (rentStatus.canAccept) {
              rentStatus.phrase = 'You can rent them this tech'
            } else {
              if (weHaveConnectionAlready) {
                rentStatus.phrase = 'Мы уже связаны договором';
              } else {
                rentStatus.phrase = 'Они связаны договором с другой компанией';
              }
            }
          } else {
            rentStatus.phrase = 'Они связаны договором с другой компанией';
          }
        } else {
          // we are worse than competitors
          acceptor = ourCompanyId;
          sender = productId;

          symbol = UI.symbols.triangle.down;
          symbolColor = "negative";

          rentPhrase = "Арендовать технологию на год";
          level = difference;
        }

        // errors
        // we have rent contract already with this company

        if (productStore.canRentTechFromAtoB(sender, acceptor, featureId)) {
          canRentTech = 'show';
        } else {
          if (weHaveConnectionAlready) {
            error = 'Договор аренды уже был заключён между нашими компаниями';
          } else {
            error = 'Они связаны договором аренды с другой компанией';
          }
        }

        // error = '';

        differencePhrase = (

            {symbol}
            {level}lvl {rentStatus.phrase}

{error}

            <span className={`${canRentTech}`}>
              <UI.Button
                text={rentPhrase}
                link
                onClick={() => productActions.rentTech(sender, acceptor, featureId)}
              />

        );

        return
{f.description}: {this.convertXPtoLvl(f.value)}lvl {differencePhrase}
;
      }

      return '';
    });
  }

  render({ rating, c, i, isCompetitor, onBuyCompany, rents, money }) {
    const ourCompany = productStore.getProduct(0);

    let background = 'competitor competeable';
    let companyTitle = `"${c.name}"`;
    let buyingCompanyButtonVisible = 'hide';

    if (isCompetitor) {
      background = 'competitor uncompeteable';
      companyTitle = `Компания №${i + 1} - "${c.name}"`;
      buyingCompanyButtonVisible = 'hide';
    }

    const hasEnoughMoney = money >= c.cost;

    const hypeChangePhrase = c.hypeDamping < 0 ? c.hypeDamping : `+${c.hypeDamping}`;
    //
    return (

{companyTitle}

Известность (HYPE): {c.hype} ({hypeChangePhrase} ежемесячно)

Рейтинг: {c.rating}

Клиенты: {c.clients} человек

Технологии

{this.renderFeatureList(c, i, rents, ourCompany)}

Рыночная стоимость: {c.cost}$

        <div className={`offset-mid ${buyingCompanyButtonVisible}`}>
          <UI.Button
            text={`Купить компанию "${c.name}"`}
            primary={hasEnoughMoney}
            disabled={!hasEnoughMoney}
            onClick={onBuyCompany ? onBuyCompany : () => {}}
          />

    )
  }
}
<commit_msg>rent rendering seems to work OK<commit_after>import { h, Component } from 'preact';

import logger from '../../../../helpers/logger/logger';

import productStore from '../../../../stores/product-store';

import productActions from '../../../../actions/product-actions';

import UI from '../../../UI';

export default class Competitor extends Component {
  convertXPtoLvl(value) {
    return Math.floor(value / 1000);
  }

  renderFeatureList(c, productId, rents: Array, ourCompany) {
    const ourCompanyId = 0;

    return c.features.map((f, featureId) => {
      let error;
      let differencePhrase = '';

      const difference = this.convertXPtoLvl(ourCompany.features.offer[featureId] - c.features[featureId].value);

      if (productStore.isShareableFeature(productId, featureId) && (difference > 0 || difference <= -1)) {
        let canRentTech = 'hide';

        let sender;
        let acceptor;

        let rentPhrase;
        let symbol;
        let symbolColor;

        let level;

        let rentStatus = {
          canAccept: true,
          canSend: true,
          weCanSend: true,
          weCanAccept: true,
          phrase: ''
        };

        const they = productStore.getRentingStatus(productId, featureId);
        rentStatus.theyCanAccept = they.canAccept;
        rentStatus.theyCanSend = they.canSend;

        const we = productStore.getRentingStatus(ourCompanyId, featureId);
        rentStatus.weCanAccept = we.canAccept;
        rentStatus.weCanSend = we.canSend;

        const weHaveConnectionAlready = productStore.isRentingAlready(productId, ourCompanyId, featureId);

        rents
          .filter(r => r.featureId === featureId && (r.out === productId || r.in === productId))
          .forEach(r => {
            const level = this.convertXPtoLvl(r.value);

            if (r.in === productId) {
              // if company accepts tech, it is frozen for any operations on this feature
              let name = r.out === ourCompanyId ? 'нас' : `"${r.senderName}"`;

              rentStatus.rentFromName = name;
              rentStatus.level = `(${level}lvl)`;

              rentStatus.canAccept = false;
              rentStatus.canSend = false;
            }

            if (r.out === productId) {
              // if company sends tech, it cannot accept anything, but can send this feature
              rentStatus.canAccept = false;
              rentStatus.canSend = true;
              rentStatus.phrase = 'Они сдают эту технологию в аренду';
            }
          });

        if (difference > 0) {
          // our feature is better than competitor's one
          sender = ourCompanyId;
          acceptor = productId;

          symbol = UI.symbols.triangle.up;
          symbolColor = "positive";

          rentPhrase = "Сдать технологию в аренду на год";
          level = `+${difference}`;

          // we have incoming rent contract with another company
          // we have outgoing rent contract with another company

          if (rentStatus.weCanSend) {
            if (rentStatus.theyCanAccept) {
              rentStatus.phrase = ''; // 'Мы можем сдать эту технологию в аренду';
              rentStatus.available = true;
            } else {
              if (weHaveConnectionAlready) {
                rentStatus.phrase = 'Мы уже связаны договором';
              } else {
                rentStatus.phrase = 'Они связаны договором с другой компанией';
              }
            }
          } else {
            rentStatus.phrase = 'Мы уже арендуем эту технологию';
          }
        } else {
          // we are worse than competitors
          acceptor = ourCompanyId;
          sender = productId;

          symbol = UI.symbols.triangle.down;
          symbolColor = "negative";

          rentPhrase = "Арендовать технологию на год";
          level = difference;

          if (rentStatus.weCanAccept) {
            if (rentStatus.theyCanSend) {
              rentStatus.phrase =''; // 'Мы можем арендовать эту технологию';
              rentStatus.available = true;
            } else {
              rentStatus.phrase = `Они арендуют эту технологию у компании
              "${rentStatus.rentFromName}" ${rentStatus.level}`;
            }
          } else {
            if (weHaveConnectionAlready) {
              rentStatus.phrase = 'Мы уже связаны договором с этой компанией';
            } else {
              rentStatus.phrase = 'Мы связаны договором с другой компанией';
            }
          }

        }

        // errors
        // we have rent contract already with this company

        // if (productStore.canRentTechFromAtoB(sender, acceptor, featureId)) {
        //   canRentTech = 'show';
        // } else {
        //   if (weHaveConnectionAlready) {
        //     error = 'Договор аренды уже был заключён между нашими компаниями';
        //   } else {
        //     error = 'Они связаны договором аренды с другой компанией';
        //   }
        // }
        if (rentStatus.available) {
          canRentTech = 'show';
        }

        error = '';

        differencePhrase = (

            {symbol}
            {level}lvl {rentStatus.phrase}

{error}

            <span className={`${canRentTech}`}>
              <UI.Button
                text={rentPhrase}
                secondary
                onClick={() => productActions.rentTech(sender, acceptor, featureId)}
              />

        );

        return
{f.description}: {this.convertXPtoLvl(f.value)}lvl {differencePhrase}
;
      }

      return '';
    });
  }

  render({ rating, c, i, isCompetitor, onBuyCompany, rents, money }) {
    const ourCompany = productStore.getProduct(0);

    let background = 'competitor competeable';
    let companyTitle = `"${c.name}"`;
    let buyingCompanyButtonVisible = 'hide';

    if (isCompetitor) {
      background = 'competitor uncompeteable';
      companyTitle = `Компания №${i + 1} - "${c.name}"`;
      buyingCompanyButtonVisible = 'hide';
    }

    const hasEnoughMoney = money >= c.cost;

    const hypeChangePhrase = c.hypeDamping < 0 ? c.hypeDamping : `+${c.hypeDamping}`;
    //
    return (

{companyTitle}

Известность (HYPE): {c.hype} ({hypeChangePhrase} ежемесячно)

Рейтинг: {c.rating}

Клиенты: {c.clients} человек

Технологии

{this.renderFeatureList(c, i, rents, ourCompany)}

Рыночная стоимость: {c.cost}$

        <div className={`offset-mid ${buyingCompanyButtonVisible}`}>
          <UI.Button
            text={`Купить компанию "${c.name}"`}
            primary={hasEnoughMoney}
            disabled={!hasEnoughMoney}
            onClick={onBuyCompany ? onBuyCompany : () => {}}
          />

    )
  }
}
<|endoftext|>


<commit_before>$(document).foundation({
  accordion: {
    content_class: 'content',
    active_class: 'active',
    multi_expand: true,
    toggleable: true
  }
});<commit_msg>Add sliding animations to item#show<commit_after>$('.item-body').fadeIn('slow');

$(document).foundation({
  accordion: {
    content_class: 'content',
    active_class: 'active',
    multi_expand: true,
    toggleable: true
  }
});

$(".yes").click(function(){
	$('.item-body').animate({
		"left": "+=2000px"
	});
});

$(".no").click(function(){
	$('.item-body').animate({
		"left": "-=2000px"
	});
});

$(".skip").click(function(){
	$('.item-body').animate({
		"top": "+=2000px"
	});
});

<|endoftext|>


<commit_before>module.exports = function(grunt) {
    var defaultConfig, packageFile, toolsConfig, toolsFile;

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-exec');
	grunt.loadNpmTasks('grunt-closure-tools');
	grunt.loadNpmTasks('grunt-replace');

	grunt.registerTask('setup_tools', 'Initialize tools.', function(){
        toolsConfig = 'tools.json';
        toolsFile = require('./' + toolsConfig);

        if (toolsFile)
            grunt.log.ok('Tools config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

	grunt.registerTask('cleanup_deploy_folder_init', 'Initialize tools.', function(){
		grunt.initConfig({
			clean: {
				options: {
					force: true
				},
				menu:[
					toolsFile['menu_path']
				]
			}
		});
    });

	grunt.registerTask('cleanup_deploy_folder',  ['cleanup_deploy_folder_init', 'clean']);

	grunt.registerTask('build_webword_init', 'Initialize build WebWord SDK.', function(){
        defaultConfig = './sdk_configs/webword.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('WebWord config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

	grunt.registerTask('build_nativeword_init', 'Initialize build NativeWord SDK.', function(){
        defaultConfig = './sdk_configs/nativeword.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('nativeword config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

    grunt.registerTask('build_webexcel_init', 'Initialize build WebExcel SDK.', function(){
        defaultConfig = './sdk_configs/webexcel.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('WebExcel config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

    grunt.registerTask('build_webpowerpoint_init', 'Initialize build WebPowerPoint SDK.', function(){
        defaultConfig = './sdk_configs/webpowerpoint.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('WebPowerPoint config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

	grunt.registerTask('build_sdk', 'Build sdk.', function(){
        if (packageFile) {
            if (packageFile['tasks']['build'])
                grunt.task.run(packageFile['tasks']['build']);
            else
                grunt.log.error().writeln('Not found "build" task in configure'.red);
        } else {
            grunt.log.error().writeln('Is not load configure file.'.red);
        }
    });

	grunt.registerTask('build_webword',     ['setup_tools', 'build_webword_init', 'build_sdk']);
	grunt.registerTask('build_nativeword', ['setup_tools', 'build_nativeword_init', 'build_sdk']);
    grunt.registerTask('build_webexcel',  ['setup_tools', 'build_webexcel_init', 'build_sdk']);
    grunt.registerTask('build_webpowerpoint', ['setup_tools', 'build_webpowerpoint_init', 'build_sdk']);

	grunt.registerTask('deploy_sdk_all', ['setup_tools', 'build_webword_init', 'deploy_sdk', 'build_webexcel_init', 'deploy_sdk', 'build_webpowerpoint_init', 'deploy_sdk']);

	grunt.registerTask('build_all_without_deploy', ['setup_tools', 'build_webword_init', 'build_sdk', 'build_webexcel_init', 'build_sdk', 'build_webpowerpoint_init', 'build_sdk']);
	grunt.registerTask('build_all', ['build_all_without_deploy', 'deploy_sdk_all']);
	grunt.registerTask('cleanup_and_build_all', ['setup_tools', 'cleanup_deploy_folder', 'build_all']);

	grunt.registerTask('up_sdk_src_init', 'Update SDK source', function() {
		grunt.initConfig({
			exec: {
				update_sources: {
					command: 'svn.exe up -q --non-interactive -r ' + packageFile['update_src']['revision'] + ' ' + packageFile['update_src']['src'],
					stdout: true
				},
				update_logs: {
					command: 'svn.exe up -q --non-interactive -r HEAD ' + packageFile['compile']['sdk']['log'],
					stdout: true
				}
			}
		});
    });

	grunt.registerTask('update_sources_webword', ['build_webword_init', 'up_sdk_src_init', 'exec']);
	grunt.registerTask('update_sources_webexcel', ['build_webexcel_init', 'up_sdk_src_init', 'exec']);
	grunt.registerTask('update_sources_webpowerpoint', ['build_webpowerpoint_init', 'up_sdk_src_init', 'exec']);

	grunt.registerTask('update_sources', ['update_sources_webword', 'update_sources_webexcel', 'update_sources_webpowerpoint']);

	grunt.registerTask('commit_logs_init', function() {
		var build_num = packageFile['info']['build'];
		var svn_rev = packageFile['update_src']['revision'];

		if(undefined !== process.env['BUILD_NUMBER'])
			build_num = parseInt(process.env['BUILD_NUMBER']);

		if(undefined !== process.env['SVN_REVISION'])
			svn_rev = parseInt(process.env['SVN_REVISION']);

		var commit_message ='\"Version: '+ packageFile['info']['version'] +
							' (build:' + build_num + ')' +
							' from svn rev: ' + svn_rev + '\"';
        grunt.initConfig({
			exec: {
				store_log: {
					command: 'svn.exe commit ' + packageFile['deploy']['store_log']['dst'] + ' -q -m ' + commit_message,
					stdout: false
				}
			}
        });
    });

	grunt.registerTask('commit_logs_webword', ['build_webword_init', 'commit_logs_init', 'exec']);
	grunt.registerTask('commit_logs_webexcel', ['build_webexcel_init', 'commit_logs_init', 'exec']);
	grunt.registerTask('commit_logs_webpowerpoint', ['build_webpowerpoint_init', 'commit_logs_init', 'exec']);

	grunt.registerTask('commit_logs', ['commit_logs_webword', 'commit_logs_webexcel', 'commit_logs_webpowerpoint']);

    grunt.registerTask('increment_build', function() {
		var pkg = grunt.file.readJSON(defaultConfig);
		pkg.info.build = parseInt(pkg.info.build) + 1;

		if(undefined !== process.env['BUILD_NUMBER']) {
			grunt.log.ok('Use Jenkins build number as sdk-all build number!'.yellow);
			packageFile['info']['build'] = parseInt(process.env['BUILD_NUMBER']);
			pkg.info.build = packageFile['info']['build'];
		}
		if(undefined !== process.env['SVN_REVISION']){
			packageFile['info']['rev'] = process.env['SVN_REVISION'];
		}
		else{
			packageFile['info']['rev'] = "unknown";
		}
		grunt.file.write(defaultConfig, JSON.stringify(pkg, null, 4));
    });

	grunt.registerTask('concat_js_api_init', 'Concatinate JS API', function() {
        grunt.initConfig({
            concat:  packageFile['concat_api']
        });
    });
	grunt.registerTask('concat_js_api', ['concat_js_api_init', 'concat']);

	grunt.registerTask('extract_js_api_init', 'Extract JS API', function(){
		grunt.file.mkdir( packageFile['compile']['sdk']['log'] );
		grunt.initConfig({
			exec: {
				api: {
					command: 'bin\\ExtractJSApi.exe ' + packageFile['extract_api']['src'] + ' ' + packageFile['extract_api']['dst'],
					stdout: false
				}
			}
		});
	});
	grunt.registerTask('extract_js_api', ['extract_js_api_init', 'exec']);

	grunt.registerTask('create_map_file', function() {
		//      ,    .
		var map_file_path = packageFile['compile']['sdk']['dst'] + '.map';
		var map_record = '//@ sourceMappingURL=' + packageFile['compile']['source_map']['url'] + '/' + map_file_path;

		var map_record_file_path = map_file_path + '.tmp';
		grunt.file.write(map_record_file_path, map_record);
	});

	grunt.registerTask('compile_sdk_init', function(compilation_level) {
		var map_file_path = packageFile['compile']['sdk']['dst'] + '.map';
		var map_record_file_path = map_file_path + '.tmp';
		var concat_res = {};
		concat_res[packageFile['compile']['sdk']['dst']] = [
					packageFile['compile']['sdk']['dst'],
					packageFile['compile']['defines']['dst'],
					map_record_file_path ];
		grunt.initConfig({
			closureCompiler: {
				options: {
					compilerFile: toolsFile['closure_compiler'],
					javaFlags: ['-Xms1024m']
				},
				sdk: {
					TEMPcompilerOpts: {
						compilation_level: compilation_level,
						externs: packageFile['compile']['sdk']['externs'],
						define: packageFile['compile']['sdk']['define'],
						warning_level: 'QUIET',
						variable_renaming_report: packageFile['compile']['sdk']['log'] + '/variable.map',
						property_renaming_report: packageFile['compile']['sdk']['log'] + '/property.map'/*,
						create_source_map: map_file_path,
						source_map_format: "V3"*/
					},
					src: packageFile['compile']['sdk']['src'],
					dest: packageFile['compile']['sdk']['dst']
				},
				defines: {
					TEMPcompilerOpts: {
						compilation_level: 'SIMPLE',
						warning_level: 'QUIET'
					},
					src: packageFile['compile']['defines']['src'],
					dest: packageFile['compile']['defines']['dst']
				}
			},
			create_map_file: {},
			concat: concat_res,
			clean: [
				packageFile['compile']['defines']['dst'],
				map_record_file_path
			],
			pkg: grunt.file.readJSON(defaultConfig),
			replace: {
				version: {
					options: {
						variables: {
							Version: packageFile['info']['version'],
							Build: packageFile['info']['build'].toString(),
							Rev: packageFile['info']['rev'].toString()
						}
					},
					files: {
						'<%= pkg.compile.sdk.dst %>': '<%= pkg.compile.sdk.dst %>'
					}
				}
			}
		});
	});

	grunt.registerTask('compile_sdk', ['compile_sdk_init:ADVANCED', 'closureCompiler', 'concat', 'replace', 'clean']);
	grunt.registerTask('compile_sdk_fast', ['compile_sdk_init:WHITESPACE_ONLY', 'closureCompiler', 'concat', 'replace', 'clean']);

	grunt.registerTask('compile_sdk_native', ['compile_sdk_init:ADVANCED', 'closureCompiler:sdk', 'concat', 'replace', 'clean']);
	grunt.registerTask('compile_sdk_native_fast', ['compile_sdk_init:WHITESPACE_ONLY', 'closureCompiler:sdk', 'concat', 'replace', 'clean']);

	grunt.registerTask('deploy_sdk_init', function() {
        grunt.initConfig({
		    pkg: grunt.file.readJSON(toolsConfig),
            copy:  packageFile['deploy']['copy']
        });
    });

	grunt.registerTask('deploy_sdk', ['deploy_sdk_init', 'copy']);

	grunt.registerTask('default', 'build_all_without_deploy');
};<commit_msg>Истправлени ошибки: and failed: ..\..\Excel\model\autofilters.js:4468: ERROR - this language feature is only supported in es6 mode: member declarations. Use --language_in=ECMASCRIPT6 or ECMASCRIPT6_STRICT to enable ES6 features.<commit_after>module.exports = function(grunt) {
    var defaultConfig, packageFile, toolsConfig, toolsFile;

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-exec');
	grunt.loadNpmTasks('grunt-closure-tools');
	grunt.loadNpmTasks('grunt-replace');

	grunt.registerTask('setup_tools', 'Initialize tools.', function(){
        toolsConfig = 'tools.json';
        toolsFile = require('./' + toolsConfig);

        if (toolsFile)
            grunt.log.ok('Tools config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

	grunt.registerTask('cleanup_deploy_folder_init', 'Initialize tools.', function(){
		grunt.initConfig({
			clean: {
				options: {
					force: true
				},
				menu:[
					toolsFile['menu_path']
				]
			}
		});
    });

	grunt.registerTask('cleanup_deploy_folder',  ['cleanup_deploy_folder_init', 'clean']);

	grunt.registerTask('build_webword_init', 'Initialize build WebWord SDK.', function(){
        defaultConfig = './sdk_configs/webword.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('WebWord config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

	grunt.registerTask('build_nativeword_init', 'Initialize build NativeWord SDK.', function(){
        defaultConfig = './sdk_configs/nativeword.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('nativeword config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

    grunt.registerTask('build_webexcel_init', 'Initialize build WebExcel SDK.', function(){
        defaultConfig = './sdk_configs/webexcel.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('WebExcel config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

    grunt.registerTask('build_webpowerpoint_init', 'Initialize build WebPowerPoint SDK.', function(){
        defaultConfig = './sdk_configs/webpowerpoint.json';
        packageFile = require(defaultConfig);

        if (packageFile)
            grunt.log.ok('WebPowerPoint config loaded successfully'.green);
        else
            grunt.log.error().writeln('Could not load config file'.red);
    });

	grunt.registerTask('build_sdk', 'Build sdk.', function(){
        if (packageFile) {
            if (packageFile['tasks']['build'])
                grunt.task.run(packageFile['tasks']['build']);
            else
                grunt.log.error().writeln('Not found "build" task in configure'.red);
        } else {
            grunt.log.error().writeln('Is not load configure file.'.red);
        }
    });

	grunt.registerTask('build_webword',     ['setup_tools', 'build_webword_init', 'build_sdk']);
	grunt.registerTask('build_nativeword', ['setup_tools', 'build_nativeword_init', 'build_sdk']);
    grunt.registerTask('build_webexcel',  ['setup_tools', 'build_webexcel_init', 'build_sdk']);
    grunt.registerTask('build_webpowerpoint', ['setup_tools', 'build_webpowerpoint_init', 'build_sdk']);

	grunt.registerTask('deploy_sdk_all', ['setup_tools', 'build_webword_init', 'deploy_sdk', 'build_webexcel_init', 'deploy_sdk', 'build_webpowerpoint_init', 'deploy_sdk']);

	grunt.registerTask('build_all_without_deploy', ['setup_tools', 'build_webword_init', 'build_sdk', 'build_webexcel_init', 'build_sdk', 'build_webpowerpoint_init', 'build_sdk']);
	grunt.registerTask('build_all', ['build_all_without_deploy', 'deploy_sdk_all']);
	grunt.registerTask('cleanup_and_build_all', ['setup_tools', 'cleanup_deploy_folder', 'build_all']);

	grunt.registerTask('up_sdk_src_init', 'Update SDK source', function() {
		grunt.initConfig({
			exec: {
				update_sources: {
					command: 'svn.exe up -q --non-interactive -r ' + packageFile['update_src']['revision'] + ' ' + packageFile['update_src']['src'],
					stdout: true
				},
				update_logs: {
					command: 'svn.exe up -q --non-interactive -r HEAD ' + packageFile['compile']['sdk']['log'],
					stdout: true
				}
			}
		});
    });

	grunt.registerTask('update_sources_webword', ['build_webword_init', 'up_sdk_src_init', 'exec']);
	grunt.registerTask('update_sources_webexcel', ['build_webexcel_init', 'up_sdk_src_init', 'exec']);
	grunt.registerTask('update_sources_webpowerpoint', ['build_webpowerpoint_init', 'up_sdk_src_init', 'exec']);

	grunt.registerTask('update_sources', ['update_sources_webword', 'update_sources_webexcel', 'update_sources_webpowerpoint']);

	grunt.registerTask('commit_logs_init', function() {
		var build_num = packageFile['info']['build'];
		var svn_rev = packageFile['update_src']['revision'];

		if(undefined !== process.env['BUILD_NUMBER'])
			build_num = parseInt(process.env['BUILD_NUMBER']);

		if(undefined !== process.env['SVN_REVISION'])
			svn_rev = parseInt(process.env['SVN_REVISION']);

		var commit_message ='\"Version: '+ packageFile['info']['version'] +
							' (build:' + build_num + ')' +
							' from svn rev: ' + svn_rev + '\"';
        grunt.initConfig({
			exec: {
				store_log: {
					command: 'svn.exe commit ' + packageFile['deploy']['store_log']['dst'] + ' -q -m ' + commit_message,
					stdout: false
				}
			}
        });
    });

	grunt.registerTask('commit_logs_webword', ['build_webword_init', 'commit_logs_init', 'exec']);
	grunt.registerTask('commit_logs_webexcel', ['build_webexcel_init', 'commit_logs_init', 'exec']);
	grunt.registerTask('commit_logs_webpowerpoint', ['build_webpowerpoint_init', 'commit_logs_init', 'exec']);

	grunt.registerTask('commit_logs', ['commit_logs_webword', 'commit_logs_webexcel', 'commit_logs_webpowerpoint']);

    grunt.registerTask('increment_build', function() {
		var pkg = grunt.file.readJSON(defaultConfig);
		pkg.info.build = parseInt(pkg.info.build) + 1;

		if(undefined !== process.env['BUILD_NUMBER']) {
			grunt.log.ok('Use Jenkins build number as sdk-all build number!'.yellow);
			packageFile['info']['build'] = parseInt(process.env['BUILD_NUMBER']);
			pkg.info.build = packageFile['info']['build'];
		}
		if(undefined !== process.env['SVN_REVISION']){
			packageFile['info']['rev'] = process.env['SVN_REVISION'];
		}
		else{
			packageFile['info']['rev'] = "unknown";
		}
		grunt.file.write(defaultConfig, JSON.stringify(pkg, null, 4));
    });

	grunt.registerTask('concat_js_api_init', 'Concatinate JS API', function() {
        grunt.initConfig({
            concat:  packageFile['concat_api']
        });
    });
	grunt.registerTask('concat_js_api', ['concat_js_api_init', 'concat']);

	grunt.registerTask('extract_js_api_init', 'Extract JS API', function(){
		grunt.file.mkdir( packageFile['compile']['sdk']['log'] );
		grunt.initConfig({
			exec: {
				api: {
					command: 'bin\\ExtractJSApi.exe ' + packageFile['extract_api']['src'] + ' ' + packageFile['extract_api']['dst'],
					stdout: false
				}
			}
		});
	});
	grunt.registerTask('extract_js_api', ['extract_js_api_init', 'exec']);

	grunt.registerTask('create_map_file', function() {
		//      ,    .
		var map_file_path = packageFile['compile']['sdk']['dst'] + '.map';
		var map_record = '//@ sourceMappingURL=' + packageFile['compile']['source_map']['url'] + '/' + map_file_path;

		var map_record_file_path = map_file_path + '.tmp';
		grunt.file.write(map_record_file_path, map_record);
	});

	grunt.registerTask('compile_sdk_init', function(compilation_level) {
		var map_file_path = packageFile['compile']['sdk']['dst'] + '.map';
		var map_record_file_path = map_file_path + '.tmp';
		var concat_res = {};
		concat_res[packageFile['compile']['sdk']['dst']] = [
					packageFile['compile']['sdk']['dst'],
					packageFile['compile']['defines']['dst'],
					map_record_file_path ];
		grunt.initConfig({
			closureCompiler: {
				options: {
					compilerFile: toolsFile['closure_compiler'],
					javaFlags: ['-Xms1024m']
				},
				sdk: {
					TEMPcompilerOpts: {
						compilation_level: compilation_level,
						externs: packageFile['compile']['sdk']['externs'],
						define: packageFile['compile']['sdk']['define'],
						warning_level: 'QUIET',
						variable_renaming_report: packageFile['compile']['sdk']['log'] + '/variable.map',
						property_renaming_report: packageFile['compile']['sdk']['log'] + '/property.map',
						language_in: "ECMASCRIPT6",
						language_out: "ES5"/*,
						create_source_map: map_file_path,
						source_map_format: "V3"*/
					},
					src: packageFile['compile']['sdk']['src'],
					dest: packageFile['compile']['sdk']['dst']
				},
				defines: {
					TEMPcompilerOpts: {
						compilation_level: 'SIMPLE',
						warning_level: 'QUIET'
					},
					src: packageFile['compile']['defines']['src'],
					dest: packageFile['compile']['defines']['dst']
				}
			},
			create_map_file: {},
			concat: concat_res,
			clean: [
				packageFile['compile']['defines']['dst'],
				map_record_file_path
			],
			pkg: grunt.file.readJSON(defaultConfig),
			replace: {
				version: {
					options: {
						variables: {
							Version: packageFile['info']['version'],
							Build: packageFile['info']['build'].toString(),
							Rev: packageFile['info']['rev'].toString()
						}
					},
					files: {
						'<%= pkg.compile.sdk.dst %>': '<%= pkg.compile.sdk.dst %>'
					}
				}
			}
		});
	});

	grunt.registerTask('compile_sdk', ['compile_sdk_init:ADVANCED', 'closureCompiler', 'concat', 'replace', 'clean']);
	grunt.registerTask('compile_sdk_fast', ['compile_sdk_init:WHITESPACE_ONLY', 'closureCompiler', 'concat', 'replace', 'clean']);

	grunt.registerTask('compile_sdk_native', ['compile_sdk_init:ADVANCED', 'closureCompiler:sdk', 'concat', 'replace', 'clean']);
	grunt.registerTask('compile_sdk_native_fast', ['compile_sdk_init:WHITESPACE_ONLY', 'closureCompiler:sdk', 'concat', 'replace', 'clean']);

	grunt.registerTask('deploy_sdk_init', function() {
        grunt.initConfig({
		    pkg: grunt.file.readJSON(toolsConfig),
            copy:  packageFile['deploy']['copy']
        });
    });

	grunt.registerTask('deploy_sdk', ['deploy_sdk_init', 'copy']);

	grunt.registerTask('default', 'build_all_without_deploy');
};<|endoftext|>


<commit_before>(function() {
  // helper functions
  function is_touch_device() {
    return 'ontouchstart' in window || // works on most browsers
           'onmsgesturechange' in window; // works on ie10
  }

  function fill(value, target, container) {
    if (value + target < container)
      value = container - target;
    return value > 0 ? 0 : value;
  }

  function uri2blob(dataURI) {
      var uriComponents = dataURI.split(',');
      var byteString = atob(uriComponents[1]);
      var mimeString = uriComponents[0].split(':')[1].split(';')[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++)
          ia[i] = byteString.charCodeAt(i);
      return new Blob([ab], { type: mimeString });
  }

	var pluginName = 'cropbox';

  function factory($) {
    function Crop($image, options) {
      this.width = null;
      this.height = null;
      this.minPercent = null;
      this.options = options;
      this.$image = $image;
      this.$image.hide().addClass('cropImage').wrap('
'); // wrap image in frame;
      this.$frame = this.$image.parent();
      this.init();
    }

    Crop.prototype = {
      init: function () {
        var self = this;

        if (is_touch_device())
          this.$frame.addClass('hover');
        else
          this.$frame.hover(function () { self.$frame.toggleClass('hover'); });

        var defaultControls = $('
', { 'class' : 'cropControls' })
              .append($('Drag to crop'))
              .append($('', { 'class' : 'cropZoomIn' }).on('click', $.proxy(this.zoomIn, this)))
              .append($('', { 'class' : 'cropZoomOut' }).on('click', $.proxy(this.zoomOut, this)));

        this.$frame.width(self.options.width).height(self.options.height);
        this.$frame.append(this.options.controls || defaultControls);

        this.$image.on('load', function() {
          self.width = this.width;
          self.height = this.height;
          self.focal = { x: Math.round(self.width / 2) ,y: Math.round(self.height / 2) };
          self.computeMinPercent();
          self.$image.fadeIn('fast'); //display image now that it has loaded
          self.update();
        }).prop('draggable', false).attr('src', self.$image.attr('src'));

        if (typeof $.fn.hammer === 'function' || typeof Hammer !== 'undefined') {
          var hammerit, dragData;
          if (typeof $.fn.hammer === 'function')
            hammerit = this.$image.hammer();
          else
            hammerit = Hammer(this.$image.get(0));

          hammerit.on('mousedown', function(e) {
            e.preventDefault(); // this prevents firefox's default image dragging
            e.stopPropagation();
          }).on("dragleft dragright dragup dragdown", function(e) {
            if (!dragData)
              dragData = {
                startX: parseInt(self.$image.css('left'), 10),
                startY: parseInt(self.$image.css('top'), 10)
              };
            dragData.dx = e.gesture.deltaX;
            dragData.dy = e.gesture.deltaY;
            e.gesture.preventDefault();
            e.gesture.stopPropagation();
            self.drag.call(self, dragData);
          }).on('release', function(e) {
            e.gesture.preventDefault();
            dragData = null;
            self.update.call(self);
          }).on('doubletap', function(e) {
            e.gesture.preventDefault();
            self.zoomIn.call(self);
          }).on('pinchin', function (e) {
            e.gesture.preventDefault();
            self.zoom.call(self, self.percent - e.gesture.scale / 110);
          }).on('pinchout', function (e) {
            e.gesture.preventDefault();
            self.zoom.call(self, self.percent + (e.gesture.scale - 1) / 110);
          });
        } else {
          this.$image.on('mousedown.' + pluginName, function(e1) {
            var dragData = {
              startX: parseInt(self.$image.css('left'), 10),
              startY: parseInt(self.$image.css('top'), 10)
            };
            e1.preventDefault();
            $(document).on('mousemove.' + pluginName, function (e2) {
              dragData.dx = e2.pageX - e1.pageX;
              dragData.dy = e2.pageY - e1.pageY;
              self.drag.call(self, dragData);
            }).on('mouseup.' + pluginName, function() {
              $(document).off('.' + pluginName);
            });
          });
        }
        if ($.fn.mousewheel) {
          this.$image.on('mousewheel', function (e) {
            e.preventDefault();
            if (e.deltaY < 0)
              self.zoomIn.call(self);
            else
              self.zoomOut.call(self);
          });
        }
      },

      computeMinPercent: function () {
        var widthRatio = this.options.width / this.width, heightRatio = this.options.height / this.height;
        if (widthRatio >= heightRatio)
          this.minPercent = this.width < this.options.width ? this.options.width / this.width : widthRatio;
        else
          this.minPercent = this.height < this.options.height ? this.options.height / this.height : heightRatio;
        this.zoom(this.percent || this.minPercent);
      },

      zoom: function(percent) {
        this.percent = Math.max(this.minPercent, Math.min(1, percent));
        this.$image.width(Math.ceil(this.width * this.percent));
        this.$image.css({
          left: fill(-Math.round(this.focal.x * this.percent - this.options.width / 2), this.$image.width(), this.options.width),
          top: fill(-Math.round(this.focal.y * this.percent - this.options.height / 2), this.$image.height(), this.options.height)
        });
      },
      zoomIn: function() {
        this.zoom(this.percent + (1 - this.minPercent) / (this.options.zoom - 1 || 1));
        this.update();
      },
      zoomOut: function() {
        this.zoom(this.percent - (1 - this.minPercent) / (this.options.zoom - 1 || 1));
        this.update();
      },
      drag: function(data) {
        this.$image.css({
          left: fill(data.startX + data.dx, this.$image.width(), this.options.width),
          top: fill(data.startY + data.dy, this.$image.height(), this.options.height)
        });
      },
      update: function() {
        this.focal = {
          x: Math.round((this.options.width / 2 - parseInt(this.$image.css('left'), 10)) / this.percent),
          y: Math.round((this.options.height / 2 - parseInt(this.$image.css ('top'), 10)) / this.percent)
        };
        this.result = {
          cropX: -Math.floor(parseInt(this.$image.css('left'), 10) / this.percent),
          cropY: -Math.floor(parseInt(this.$image.css('top'), 10) / this.percent),
          cropW: Math.round(this.options.width / this.percent),
          cropH: Math.round(this.options.height / this.percent),
          stretch: this.minPercent > 1
        };

        this.$image.trigger(pluginName, [this.result, this]);
      },
      getDataURI: function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.options.width;
        canvas.height = this.options.height;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(this.$image.get(0), this.result.cropX, this.result.cropY, this.result.cropW, this.result.cropH, 0, 0, this.options.width, this.options.height);

        return canvas.toDataURL();
      },
      getBlob: function () {
        return uri2blob(this.getDataURI());
      },
    };

    $.fn[pluginName] = function(options) {
      return this.each(function() {
        var inst = $.data(this, pluginName);
        if (!inst) {
          var opts = $.extend({}, $.fn[pluginName].defaultOptions, options);
          $.data(this, pluginName, new Crop($(this), opts));
        } else if (options) {
          $.extend(inst.options, options);
          inst.computeMinPercent();
        }
      });
    };

    $.fn[pluginName].defaultOptions = {
      width: 200,
      height: 200,
      zoom: 10,
      controls: null
    };
  }

  if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
      factory(require("jquery"));
  else if (typeof define === "function" && define.amd)
      define(["jquery"], factory);
  else
      factory(window.jQuery || window.Zepto);

})();
<commit_msg>Added stop function.<commit_after>(function() {
  // helper functions
  function is_touch_device() {
    return 'ontouchstart' in window || // works on most browsers
           'onmsgesturechange' in window; // works on ie10
  }

  function fill(value, target, container) {
    if (value + target < container)
      value = container - target;
    return value > 0 ? 0 : value;
  }

  function uri2blob(dataURI) {
      var uriComponents = dataURI.split(',');
      var byteString = atob(uriComponents[1]);
      var mimeString = uriComponents[0].split(':')[1].split(';')[0];
      var ab = new ArrayBuffer(byteString.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < byteString.length; i++)
          ia[i] = byteString.charCodeAt(i);
      return new Blob([ab], { type: mimeString });
  }

	var pluginName = 'cropbox';

  function factory($) {
    function Crop($image, options) {
      this.width = null;
      this.height = null;
      this.minPercent = null;
      this.options = options;
      this.$image = $image;
      this.$image.hide().addClass('cropImage').wrap('
'); // wrap image in frame;
      this.$frame = this.$image.parent();
      this.init();
    }

    Crop.prototype = {
      init: function () {
        var self = this;

        if (is_touch_device())
          this.$frame.addClass('hover');
        else
          this.$frame.hover(function () { self.$frame.toggleClass('hover'); });

        var defaultControls = $('
', { 'class' : 'cropControls' })
              .append($('Drag to crop'))
              .append($('', { 'class' : 'cropZoomIn' }).on('click', $.proxy(this.zoomIn, this)))
              .append($('', { 'class' : 'cropZoomOut' }).on('click', $.proxy(this.zoomOut, this)));

        this.$frame.width(self.options.width).height(self.options.height);
        this.$frame.append(this.options.controls || defaultControls);

        this.$image.on('load.' + pluginName, function() {
          self.width = this.width;
          self.height = this.height;
          self.focal = { x: Math.round(self.width / 2) ,y: Math.round(self.height / 2) };
          self.computeMinPercent();
          self.$image.fadeIn('fast'); //display image now that it has loaded
          self.update();
        }).prop('draggable', false).attr('src', self.$image.attr('src'));

        if (typeof $.fn.hammer === 'function' || typeof Hammer !== 'undefined') {
          var hammerit, dragData;
          if (typeof $.fn.hammer === 'function')
            hammerit = this.$image.hammer();
          else
            hammerit = Hammer(this.$image.get(0));

          hammerit.on('mousedown', function(e) {
            e.preventDefault(); // this prevents firefox's default image dragging
            e.stopPropagation();
          }).on("dragleft dragright dragup dragdown", function(e) {
            if (!dragData)
              dragData = {
                startX: parseInt(self.$image.css('left'), 10),
                startY: parseInt(self.$image.css('top'), 10)
              };
            dragData.dx = e.gesture.deltaX;
            dragData.dy = e.gesture.deltaY;
            e.gesture.preventDefault();
            e.gesture.stopPropagation();
            self.drag.call(self, dragData);
          }).on('release', function(e) {
            e.gesture.preventDefault();
            dragData = null;
            self.update.call(self);
          }).on('doubletap', function(e) {
            e.gesture.preventDefault();
            self.zoomIn.call(self);
          }).on('pinchin', function (e) {
            e.gesture.preventDefault();
            self.zoom.call(self, self.percent - e.gesture.scale / 110);
          }).on('pinchout', function (e) {
            e.gesture.preventDefault();
            self.zoom.call(self, self.percent + (e.gesture.scale - 1) / 110);
          });
        } else {
          this.$image.on('mousedown.' + pluginName, function(e1) {
            var dragData = {
              startX: parseInt(self.$image.css('left'), 10),
              startY: parseInt(self.$image.css('top'), 10)
            };
            e1.preventDefault();
            $(document).on('mousemove.' + pluginName, function (e2) {
              dragData.dx = e2.pageX - e1.pageX;
              dragData.dy = e2.pageY - e1.pageY;
              self.drag.call(self, dragData);
            }).on('mouseup.' + pluginName, function() {
              $(document).off('.' + pluginName);
            });
          });
        }
        if ($.fn.mousewheel) {
          this.$image.on('mousewheel.' + pluginName, function (e) {
            e.preventDefault();
            if (e.deltaY < 0)
              self.zoomIn.call(self);
            else
              self.zoomOut.call(self);
          });
        }
      },

      stop: function () {
        var hammerit;
        if (typeof $.fn.hammer === 'function')
          hammerit = this.$image.hammer();
        else if (typeof Hammer !== 'undefined')
          hammerit = Hammer(this.$image.get(0));
        if (hammerit)
          hammerit.off('mousedown dragleft dragright dragup dragdown release doubletap pinchin pinchout');
        this.$image.off('.' + pluginName);
        this.$image.removeClass('cropImage');
        this.$image.css({width: '', left: '', top: ''});
        this.$image.detach().insertAfter(this.$frame);
        this.$frame.remove();
      },

      computeMinPercent: function () {
        var widthRatio = this.options.width / this.width, heightRatio = this.options.height / this.height;
        if (widthRatio >= heightRatio)
          this.minPercent = this.width < this.options.width ? this.options.width / this.width : widthRatio;
        else
          this.minPercent = this.height < this.options.height ? this.options.height / this.height : heightRatio;
        this.zoom(this.percent || this.minPercent);
      },

      zoom: function(percent) {
        this.percent = Math.max(this.minPercent, Math.min(1, percent));
        this.$image.width(Math.ceil(this.width * this.percent));
        this.$image.css({
          left: fill(-Math.round(this.focal.x * this.percent - this.options.width / 2), this.$image.width(), this.options.width),
          top: fill(-Math.round(this.focal.y * this.percent - this.options.height / 2), this.$image.height(), this.options.height)
        });
      },
      zoomIn: function() {
        this.zoom(this.percent + (1 - this.minPercent) / (this.options.zoom - 1 || 1));
        this.update();
      },
      zoomOut: function() {
        this.zoom(this.percent - (1 - this.minPercent) / (this.options.zoom - 1 || 1));
        this.update();
      },
      drag: function(data) {
        this.$image.css({
          left: fill(data.startX + data.dx, this.$image.width(), this.options.width),
          top: fill(data.startY + data.dy, this.$image.height(), this.options.height)
        });
      },
      update: function() {
        this.focal = {
          x: Math.round((this.options.width / 2 - parseInt(this.$image.css('left'), 10)) / this.percent),
          y: Math.round((this.options.height / 2 - parseInt(this.$image.css ('top'), 10)) / this.percent)
        };
        this.result = {
          cropX: -Math.floor(parseInt(this.$image.css('left'), 10) / this.percent),
          cropY: -Math.floor(parseInt(this.$image.css('top'), 10) / this.percent),
          cropW: Math.round(this.options.width / this.percent),
          cropH: Math.round(this.options.height / this.percent),
          stretch: this.minPercent > 1
        };

        this.$image.trigger(pluginName, [this.result, this]);
      },
      getDataURI: function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.options.width;
        canvas.height = this.options.height;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(this.$image.get(0), this.result.cropX, this.result.cropY, this.result.cropW, this.result.cropH, 0, 0, this.options.width, this.options.height);

        return canvas.toDataURL();
      },
      getBlob: function () {
        return uri2blob(this.getDataURI());
      },
    };

    $.fn[pluginName] = function(options) {
      return this.each(function() {
        var inst = $.data(this, pluginName);
        if (!inst) {
          var opts = $.extend({}, $.fn[pluginName].defaultOptions, options);
          $.data(this, pluginName, new Crop($(this), opts));
        } else if (options) {
          $.extend(inst.options, options);
          inst.computeMinPercent();
        }
      });
    };

    $.fn[pluginName].defaultOptions = {
      width: 200,
      height: 200,
      zoom: 10,
      controls: null
    };
  }

  if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
      factory(require("jquery"));
  else if (typeof define === "function" && define.amd)
      define(["jquery"], factory);
  else
      factory(window.jQuery || window.Zepto);

})();
<|endoftext|>


<commit_before>/* jshint node:true */

var connect = require('connect');
var path = require('path');
var _ = require('underscore');
var io = require('socket.io-client');

var cloakServer = require('../src/server/cloak');
var createCloakClient = require('../src/client/cloak');

var clients;

function createServer() {
  return cloakServer;
}

function createClient() {
  var client = createCloakClient();
  client._setLibs(_, io);
  clients.push(client);
  return client;
}

module.exports = {

  setUp: function(callback) {
    try {
      this.port = 8091;
      this.host = 'http://localhost:' + this.port;
      console.log('creating server');
      this.server = createServer();
      clients = [];
      callback();
    }
    catch(e) {
      console.error(e);
    }
  },

  tearDown: function(callback) {
    try {
      _(clients).forEach(function(client) {
        if (client.connected()) {
          console.log('ending client');
          client.end();
        }
        else {
          console.log('client already disconnected');
        }
      });
      clients = null;
      console.log('stopping server');
      this.server.stop(function() {
        console.log('server stopped');
        callback();
      });
    }
    catch(e) {
      console.error(e);
    }
  },

  messageBasics: function(test) {

    test.expect(2);

    var server = this.server;
    var client = createClient();

    server.configure({
      port: this.port,
      messages: {
        dog: function(arg, user) {
          test.equals(arg.foo, 123);
          user.message('cat', {bar: 456});
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.message('dog', {foo: 123});
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  twoClients: function(test) {

    test.expect(4);

    var server = this.server;
    var client1 = createClient();
    var client2 = createClient();

    var doneCount = 0;

    server.configure({
      port: this.port,
      messages: {
        dog1: function(arg, user) {
          test.ok(true, 'received message from client 1');
          user.message('cat', {bar: 456});
        },
        dog2: function(arg, user) {
          test.ok(true, 'received message from client 2');
          user.message('cat', {bar: 789});
        }
      }
    });

    client1.configure({
      serverEvents: {
        begin: function() {
          client1.message('dog1');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    client2.configure({
      serverEvents: {
        begin: function() {
          client2.message('dog2');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 789);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  autoCreateRooms: function(test) {

    var server = this.server;
    var client1 = createClient();
    var client2 = createClient();

    var steps = [
      'joined Lobby',
      'joined Lobby',
      'joined Room 1',
      'joined Room 1',
      'leave room',
      'joined Lobby',
      'joined Lobby',
    ];

    test.expect(steps.length);

    function step(actual) {
      var expected = steps.shift();
      test.equals(actual, expected);
      if (steps.length === 0) {
        test.done();
      }
    }

    function joinRoomHandler(room) {
      step('joined '+ room.name);
      if (steps[0] === 'leave room') {
        step('leave room');
        client1.leaveRoom();
      }
    }

    server.configure({
      port: this.port,
      autoCreateRooms: true,
      minRoomMembers: 2
    });

    client1.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    client2.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  resume: function(test) {

    test.expect(1);

    var server = this.server;
    var client = createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  serverEvents: function(test) {

    test.expect(6);

    var server = this.server;
    var client = createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        connecting: function() {
          test.ok(true, 'connecting event happened');
        },
        connect: function() {
          test.ok(true, 'connect event happened');
        },
        begin: function() {
          test.ok(true, 'begin event happened');
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  }

};<commit_msg>comments for unit tests<commit_after>/* jshint node:true */

// Nodeunit tests for Cloak client and server

var connect = require('connect');
var path = require('path');
var _ = require('underscore');
var io = require('socket.io-client');

var cloakServer = require('../src/server/cloak');
var createCloakClient = require('../src/client/cloak');

var clients;

// Used in tests to create a new Cloak client. Using this
// function instead of doing it manually means clients
// will be properly cleaned up after tests are done.
function createClient() {
  var client = createCloakClient();
  client._setLibs(_, io);
  clients.push(client);
  return client;
}

module.exports = {

  // setUp is called before every test
  // Pepare a server and an empty client list
  setUp: function(callback) {
    try {
      this.port = 8091;
      this.host = 'http://localhost:' + this.port;
      console.log('creating server');
      this.server = cloakServer;
      clients = [];
      callback();
    }
    catch(e) {
      console.error(e);
    }
  },

  // tearDown is called after every test
  // Shut down server and all clients
  tearDown: function(callback) {
    try {
      _(clients).forEach(function(client) {
        if (client.connected()) {
          console.log('ending client');
          client.end();
        }
        else {
          console.log('client already disconnected');
        }
      });
      clients = null;
      console.log('stopping server');
      this.server.stop(function() {
        console.log('server stopped');
        callback();
      });
    }
    catch(e) {
      console.error(e);
    }
  },

  // Test basic messaging, to and from client
  messageBasics: function(test) {

    test.expect(2);

    var server = this.server;
    var client = createClient();

    server.configure({
      port: this.port,
      messages: {
        dog: function(arg, user) {
          test.equals(arg.foo, 123);
          user.message('cat', {bar: 456});
        }
      }
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client.message('dog', {foo: 123});
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test that the server can handle two clients
  // and send messages to the right one
  twoClients: function(test) {

    test.expect(4);

    var server = this.server;
    var client1 = createClient();
    var client2 = createClient();

    var doneCount = 0;

    server.configure({
      port: this.port,
      messages: {
        dog1: function(arg, user) {
          test.ok(true, 'received message from client 1');
          user.message('cat', {bar: 456});
        },
        dog2: function(arg, user) {
          test.ok(true, 'received message from client 2');
          user.message('cat', {bar: 789});
        }
      }
    });

    client1.configure({
      serverEvents: {
        begin: function() {
          client1.message('dog1');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 456);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    client2.configure({
      serverEvents: {
        begin: function() {
          client2.message('dog2');
        }
      },
      messages: {
        cat: function(arg) {
          test.equals(arg.bar, 789);
          doneCount++;
          if (doneCount === 2) {
            test.done();
          }
        }
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  // Test the autoCreateRooms server option with
  // minRoomMembers set to 2
  autoCreateRooms: function(test) {

    var server = this.server;
    var client1 = createClient();
    var client2 = createClient();

    var steps = [
      'joined Lobby',
      'joined Lobby',
      'joined Room 1',
      'joined Room 1',
      'leave room',
      'joined Lobby',
      'joined Lobby',
    ];

    test.expect(steps.length);

    function step(actual) {
      var expected = steps.shift();
      test.equals(actual, expected);
      if (steps.length === 0) {
        test.done();
      }
    }

    function joinRoomHandler(room) {
      step('joined '+ room.name);
      if (steps[0] === 'leave room') {
        step('leave room');
        client1.leaveRoom();
      }
    }

    server.configure({
      port: this.port,
      autoCreateRooms: true,
      minRoomMembers: 2
    });

    client1.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    client2.configure({
      serverEvents: {
        joinedRoom: joinRoomHandler
      }
    });

    server.run();
    client1.run(this.host);
    client2.run(this.host);

  },

  // Test the ability of a client to automatically
  // reconnect and resume after disconnection
  resume: function(test) {

    test.expect(1);

    var server = this.server;
    var client = createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        begin: function() {
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  },

  // Test as many server events as possible; right now
  // a few still need to be added because it's trickier
  // to test those ones.
  serverEvents: function(test) {

    test.expect(6);

    var server = this.server;
    var client = createClient();

    server.configure({
      port: this.port
    });

    client.configure({
      serverEvents: {
        connecting: function() {
          test.ok(true, 'connecting event happened');
        },
        connect: function() {
          test.ok(true, 'connect event happened');
        },
        begin: function() {
          test.ok(true, 'begin event happened');
          client._disconnect();
        },
        resume: function() {
          test.ok(true, 'resume happened');
          test.done();
        }
      }
    });

    server.run();
    client.run(this.host);

  }

};<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import MenuItem from 'material-ui/MenuItem';
import withAsyncFetch from '../../common/hocs/AsyncContainer';
import withCsvDownloadNotifyContainer from '../../common/hocs/CsvDownloadNotifyContainer';
import withSummary from '../../common/hocs/SummarizedVizualization';
import { fetchTopicTopStories, sortTopicTopStories, filterByFocus } from '../../../actions/topicActions';
import Permissioned from '../../common/Permissioned';
import { getUserRoles, hasPermissions, PERMISSION_LOGGED_IN } from '../../../lib/auth';
import { ExploreButton, DownloadButton } from '../../common/IconButton';
import ActionMenu from '../../common/ActionMenu';
import TopicStoryTable from '../TopicStoryTable';
import messages from '../../../resources/messages';
import { filteredLinkTo, filteredLocation, filtersAsUrlParams } from '../../util/location';
import { HELP_STORIES_CSV_COLUMNS } from '../../../lib/helpConstants';

const localMessages = {
  title: { id: 'topic.summary.stories.title', defaultMessage: 'Top Stories' },
  descriptionIntro: { id: 'topic.summary.stories.help.title', defaultMessage: '
The top stories within this topic can suggest the main ways it is talked about.  Sort by different measures to get a better picture of a story\'s influence.
' },
  downloadNoFBData: { id: 'topic.summary.stories.download.noFB', defaultMessage: 'Download Csv' },
  downloadWithFBData: { id: 'topic.summary.stories.download.withFB', defaultMessage: 'Download CSV w/Facebook collection date (takes longer)' },
};

const NUM_TO_SHOW = 10;

class StoriesSummaryContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { filters, sort, fetchData } = this.props;
    if ((nextProps.filters !== filters) || (nextProps.sort !== sort)) {
      fetchData(nextProps);
    }
  }
  onChangeSort = (newSort) => {
    const { sortData } = this.props;
    sortData(newSort);
  };
  downloadCsvNoFBData = () => {
    const { filters, sort, topicId, notifyOfCsvDownload } = this.props;
    const url = `/api/topics/${topicId}/stories.csv?${filtersAsUrlParams(filters)}&sort=${sort}`;
    window.location = url;
    notifyOfCsvDownload(HELP_STORIES_CSV_COLUMNS);
  }
  downloadCsvWithFBData = () => {
    const { filters, sort, topicId, notifyOfCsvDownload } = this.props;
    const url = `/api/topics/${topicId}/stories.csv?${filtersAsUrlParams(filters)}&sort=${sort}&fbData=1`;
    window.location = url;
    notifyOfCsvDownload(HELP_STORIES_CSV_COLUMNS);
  }
  render() {
    const { stories, sort, topicId, filters, handleFocusSelected, user, showTweetCounts } = this.props;
    const { formatMessage } = this.props.intl;
    const exploreUrl = `/topics/${topicId}/stories`;
    const isLoggedIn = hasPermissions(getUserRoles(user), PERMISSION_LOGGED_IN);
    return (
      <React.Fragment>
        <TopicStoryTable
          stories={stories}
          showTweetCounts={showTweetCounts}
          topicId={topicId}
          onChangeSort={isLoggedIn ? this.onChangeSort : null}
          onChangeFocusSelection={handleFocusSelected}
          sortedBy={sort}
          maxTitleLength={50}
        />
        <Permissioned onlyRole={PERMISSION_LOGGED_IN}>

            <ExploreButton linkTo={filteredLinkTo(exploreUrl, filters)} />
            <ActionMenu actionTextMsg={messages.downloadOptions}>
              <MenuItem
                className="action-icon-menu-item"
                id="topic-summary-top-stories-download"
                primaryText={formatMessage(localMessages.downloadNoFBData)}
                rightIcon={<DownloadButton />}
                onTouchTap={this.downloadCsvNoFBData}
              />
              <MenuItem
                className="action-icon-menu-item"
                id="topic-summary-top-stories-download-with-facebook"
                primaryText={formatMessage(localMessages.downloadWithFBData)}
                rightIcon={<DownloadButton />}
                onTouchTap={this.downloadCsvWithFBData}
              />
            </ActionMenu>

        </Permissioned>
      </React.Fragment>
    );
  }
}

StoriesSummaryContainer.propTypes = {
  // from the composition chain
  intl: PropTypes.object.isRequired,
  notifyOfCsvDownload: PropTypes.func.isRequired,
  // from parent
  topicId: PropTypes.number.isRequired,
  filters: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  // from dispatch
  fetchData: PropTypes.func.isRequired,
  handleFocusSelected: PropTypes.func.isRequired,
  sortData: PropTypes.func.isRequired,
  handleExplore: PropTypes.func.isRequired,
  // from state
  fetchStatus: PropTypes.string.isRequired,
  sort: PropTypes.string.isRequired,
  stories: PropTypes.array,
  user: PropTypes.object,
  showTweetCounts: PropTypes.bool,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.summary.topStories.fetchStatus,
  sort: state.topics.selected.summary.topStories.sort,
  stories: state.topics.selected.summary.topStories.stories,
  user: state.user,
  showTweetCounts: Boolean(state.topics.selected.info.ch_monitor_id),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (props) => {
    const params = {
      ...props.filters,
      sort: props.sort,
      limit: NUM_TO_SHOW,
    };
    dispatch(fetchTopicTopStories(props.topicId, params));
  },
  handleFocusSelected: (focusId) => {
    const params = {
      ...ownProps.filters,
      focusId,
      timespanId: null,
    };
    const newLocation = filteredLocation(ownProps.location, params);
    dispatch(push(newLocation));
    dispatch(filterByFocus(focusId));
  },
  sortData: (sort) => {
    dispatch(sortTopicTopStories(sort));
  },
  handleExplore: () => {
    const exploreUrl = filteredLinkTo(`/topics/${ownProps.topicId}/stories`, ownProps.filters);
    dispatch(push(exploreUrl));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData({
        topicId: ownProps.topicId,
        filters: ownProps.filters,
        sort: stateProps.sort,
      });
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      withSummary(localMessages.title, localMessages.descriptionIntro, messages.storiesTableHelpText, true)(
        withAsyncFetch(
          withCsvDownloadNotifyContainer(
            StoriesSummaryContainer
          )
        )
      )
    )
  );
<commit_msg>remove explore button<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import MenuItem from 'material-ui/MenuItem';
import withAsyncFetch from '../../common/hocs/AsyncContainer';
import withCsvDownloadNotifyContainer from '../../common/hocs/CsvDownloadNotifyContainer';
import withSummary from '../../common/hocs/SummarizedVizualization';
import { fetchTopicTopStories, sortTopicTopStories, filterByFocus } from '../../../actions/topicActions';
import Permissioned from '../../common/Permissioned';
import { getUserRoles, hasPermissions, PERMISSION_LOGGED_IN } from '../../../lib/auth';
import { DownloadButton } from '../../common/IconButton';
import ActionMenu from '../../common/ActionMenu';
import TopicStoryTable from '../TopicStoryTable';
import messages from '../../../resources/messages';
import { filteredLinkTo, filteredLocation, filtersAsUrlParams } from '../../util/location';
import { HELP_STORIES_CSV_COLUMNS } from '../../../lib/helpConstants';

const localMessages = {
  title: { id: 'topic.summary.stories.title', defaultMessage: 'Top Stories' },
  descriptionIntro: { id: 'topic.summary.stories.help.title', defaultMessage: '
The top stories within this topic can suggest the main ways it is talked about.  Sort by different measures to get a better picture of a story\'s influence.
' },
  downloadNoFBData: { id: 'topic.summary.stories.download.noFB', defaultMessage: 'Download Csv' },
  downloadWithFBData: { id: 'topic.summary.stories.download.withFB', defaultMessage: 'Download CSV w/Facebook collection date (takes longer)' },
};

const NUM_TO_SHOW = 10;

class StoriesSummaryContainer extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { filters, sort, fetchData } = this.props;
    if ((nextProps.filters !== filters) || (nextProps.sort !== sort)) {
      fetchData(nextProps);
    }
  }
  onChangeSort = (newSort) => {
    const { sortData } = this.props;
    sortData(newSort);
  };
  downloadCsvNoFBData = () => {
    const { filters, sort, topicId, notifyOfCsvDownload } = this.props;
    const url = `/api/topics/${topicId}/stories.csv?${filtersAsUrlParams(filters)}&sort=${sort}`;
    window.location = url;
    notifyOfCsvDownload(HELP_STORIES_CSV_COLUMNS);
  }
  downloadCsvWithFBData = () => {
    const { filters, sort, topicId, notifyOfCsvDownload } = this.props;
    const url = `/api/topics/${topicId}/stories.csv?${filtersAsUrlParams(filters)}&sort=${sort}&fbData=1`;
    window.location = url;
    notifyOfCsvDownload(HELP_STORIES_CSV_COLUMNS);
  }
  render() {
    const { stories, sort, topicId, handleFocusSelected, user, showTweetCounts } = this.props;
    const { formatMessage } = this.props.intl;
    const isLoggedIn = hasPermissions(getUserRoles(user), PERMISSION_LOGGED_IN);
    return (
      <React.Fragment>
        <TopicStoryTable
          stories={stories}
          showTweetCounts={showTweetCounts}
          topicId={topicId}
          onChangeSort={isLoggedIn ? this.onChangeSort : null}
          onChangeFocusSelection={handleFocusSelected}
          sortedBy={sort}
          maxTitleLength={50}
        />
        <Permissioned onlyRole={PERMISSION_LOGGED_IN}>

            <ActionMenu actionTextMsg={messages.downloadOptions}>
              <MenuItem
                className="action-icon-menu-item"
                id="topic-summary-top-stories-download"
                primaryText={formatMessage(localMessages.downloadNoFBData)}
                rightIcon={<DownloadButton />}
                onTouchTap={this.downloadCsvNoFBData}
              />
              <MenuItem
                className="action-icon-menu-item"
                id="topic-summary-top-stories-download-with-facebook"
                primaryText={formatMessage(localMessages.downloadWithFBData)}
                rightIcon={<DownloadButton />}
                onTouchTap={this.downloadCsvWithFBData}
              />
            </ActionMenu>

        </Permissioned>
      </React.Fragment>
    );
  }
}

StoriesSummaryContainer.propTypes = {
  // from the composition chain
  intl: PropTypes.object.isRequired,
  notifyOfCsvDownload: PropTypes.func.isRequired,
  // from parent
  topicId: PropTypes.number.isRequired,
  filters: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  // from dispatch
  fetchData: PropTypes.func.isRequired,
  handleFocusSelected: PropTypes.func.isRequired,
  sortData: PropTypes.func.isRequired,
  handleExplore: PropTypes.func.isRequired,
  // from state
  fetchStatus: PropTypes.string.isRequired,
  sort: PropTypes.string.isRequired,
  stories: PropTypes.array,
  user: PropTypes.object,
  showTweetCounts: PropTypes.bool,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.selected.summary.topStories.fetchStatus,
  sort: state.topics.selected.summary.topStories.sort,
  stories: state.topics.selected.summary.topStories.stories,
  user: state.user,
  showTweetCounts: Boolean(state.topics.selected.info.ch_monitor_id),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  fetchData: (props) => {
    const params = {
      ...props.filters,
      sort: props.sort,
      limit: NUM_TO_SHOW,
    };
    dispatch(fetchTopicTopStories(props.topicId, params));
  },
  handleFocusSelected: (focusId) => {
    const params = {
      ...ownProps.filters,
      focusId,
      timespanId: null,
    };
    const newLocation = filteredLocation(ownProps.location, params);
    dispatch(push(newLocation));
    dispatch(filterByFocus(focusId));
  },
  sortData: (sort) => {
    dispatch(sortTopicTopStories(sort));
  },
  handleExplore: () => {
    const exploreUrl = filteredLinkTo(`/topics/${ownProps.topicId}/stories`, ownProps.filters);
    dispatch(push(exploreUrl));
  },
});

function mergeProps(stateProps, dispatchProps, ownProps) {
  return Object.assign({}, stateProps, dispatchProps, ownProps, {
    asyncFetch: () => {
      dispatchProps.fetchData({
        topicId: ownProps.topicId,
        filters: ownProps.filters,
        sort: stateProps.sort,
      });
    },
  });
}

export default
  injectIntl(
    connect(mapStateToProps, mapDispatchToProps, mergeProps)(
      withSummary(localMessages.title, localMessages.descriptionIntro, messages.storiesTableHelpText, true)(
        withAsyncFetch(
          withCsvDownloadNotifyContainer(
            StoriesSummaryContainer
          )
        )
      )
    )
  );
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

module.exports = function(eventEmitter, githubToken) {
  var app = express();
  app.use(bodyParser.urlencoded({ extended: true }));

  app.get('/', (req, res) => {
    res.status(200).send('pong!');
  });

  app.post('/ghwebook', (req, res) => {
    const event     = req.headers['X-GitHub-Event'];
    const signature = req.headers['X-Hub-Signature'];
    console.log('>> req.body.payload', req.body.payload);
    console.log('>> req.body', req.body);
    verifySignature(signature, req.body.payload, (err, success) => {
      if (success) {
        eventEmitter.emit(event, req.body.payload);
      }
      res.status(200).send('ok');
    });
  });

  function verifySignature(originalSignature, payload, cb) {
    const hmac = crypto.createHmac('sha256', githubToken);

    hmac.on('readable', () => {
      const data = hmac.read();
      if (data) {
        const str  = data.toString('hex');
        const success = str === originalSignature;

        cb(null, success);
      }

    });

    hmac.write(payload);
    hmac.end();
  }

  return app;
};
<commit_msg>Adds some logs for debugging<commit_after>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

module.exports = function(eventEmitter, githubToken) {
  var app = express();
  app.use(bodyParser.urlencoded({ extended: true }));

  app.get('/', (req, res) => {
    res.status(200).send('pong!');
  });

  app.post('/ghwebook', (req, res) => {
    const event     = req.headers['X-GitHub-Event'];
    const signature = req.headers['X-Hub-Signature'];

    console.log('>> event', event);
    console.log('>> signature', signature);

    verifySignature(signature, req.body.payload, (err, success) => {
      console.log('>> success', success);
      if (success) {
        eventEmitter.emit(event, req.body.payload);
      }
      res.status(200).send('ok');
    });
  });

  function verifySignature(originalSignature, payload, cb) {
    const hmac = crypto.createHmac('sha256', githubToken);

    hmac.on('readable', () => {
      const data = hmac.read();
      if (data) {
        const str  = data.toString('hex');
        const success = str === originalSignature;

        cb(null, success);
      }

    });

    hmac.write(payload);
    hmac.end();
  }

  return app;
};
<|endoftext|>


<commit_before>'use strict';
var Heroku = require('heroku-client');

const HOST = "redis-api.heroku.com";
const PATH =  "/redis/v0/databases";
const ADDON = "heroku-redis";

function request(context, path, method) {
  return Heroku.request( {
    method: method || "GET",
    path: PATH+"/"+path,
    host: HOST,
    auth: context.auth.username+":"+context.auth.password,
    headers: {
      'Accept': 'application/json',
    },
  });
}

function make_addons_filter(filter) {
  if (filter) {
    filter = filter.toUpperCase();
  }

  function matches (addon) {
    for (var i=0; i<addon.config_vars.length; i++) {
      var cfg_name = addon.config_vars[i].toUpperCase();
      if (cfg_name.indexOf(filter) >= 0) {
        return true;
      }
    }
    return false;
  }

  function on_response(addons) {
    var redis_addons = [];
    for (var i=0; i < addons.length; i++) {
      var addon = addons[i];
      var service = addon.addon_service.name;

      if (service.indexOf(ADDON) === 0 && (!filter || matches(addon))) {
        redis_addons.push(addon);
      }
    }
    return redis_addons;
  }

  return on_response;
}

function make_config_var_filter(filter) {
  if (filter) {
    filter = filter.toUpperCase();
  }

  function on_response(config_vars) {
    var servers = [];

    for (var name in config_vars) {
      if (config_vars.hasOwnProperty(name)) {
        var url = config_vars[name];
        if ((url.indexOf('redis:') === 0) && (!filter || name.indexOf(filter) >= 0)) {
          servers.push({url: url, name: name});
        }
      }
    }
    return servers;
  }

  return on_response;
}

module.exports = {
  request: request,
  make_addons_filter: make_addons_filter,
  make_config_var_filter: make_config_var_filter,
};
<commit_msg>Allow to query staging addon.<commit_after>'use strict';
var Heroku = require('heroku-client');

const HOST = process.env.HEROKU_REDIS_HOST || "redis-api.heroku.com" ;
const PATH =  "/redis/v0/databases";
const ADDON = process.env.HEROKU_REDIS_ADDON_NAME || "heroku-redis";

function request(context, path, method) {
  return Heroku.request( {
    method: method || "GET",
    path: PATH+"/"+path,
    host: HOST,
    auth: context.auth.username+":"+context.auth.password,
    headers: {
      'Accept': 'application/json',
    },
  });
}

function make_addons_filter(filter) {
  if (filter) {
    filter = filter.toUpperCase();
  }

  function matches (addon) {
    for (var i=0; i<addon.config_vars.length; i++) {
      var cfg_name = addon.config_vars[i].toUpperCase();
      if (cfg_name.indexOf(filter) >= 0) {
        return true;
      }
    }
    return false;
  }

  function on_response(addons) {
    var redis_addons = [];
    for (var i=0; i < addons.length; i++) {
      var addon = addons[i];
      var service = addon.addon_service.name;

      if (service.indexOf(ADDON) === 0 && (!filter || matches(addon))) {
        redis_addons.push(addon);
      }
    }
    return redis_addons;
  }

  return on_response;
}

function make_config_var_filter(filter) {
  if (filter) {
    filter = filter.toUpperCase();
  }

  function on_response(config_vars) {
    var servers = [];

    for (var name in config_vars) {
      if (config_vars.hasOwnProperty(name)) {
        var url = config_vars[name];
        if ((url.indexOf('redis:') === 0) && (!filter || name.indexOf(filter) >= 0)) {
          servers.push({url: url, name: name});
        }
      }
    }
    return servers;
  }

  return on_response;
}

module.exports = {
  request: request,
  make_addons_filter: make_addons_filter,
  make_config_var_filter: make_config_var_filter,
};
<|endoftext|>