<commit_before>import React, { Component } from 'react';
import { Text, View, Image, TextInput, ListView, TouchableHighlight } from 'react-native';
import helpers from '../helpers/helpers.js';
import styles from '../styles.ios.js';

export default class Recipe extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      steps: ds.cloneWithRows(props.recipe.analyzedInstructions[0].steps),
      ingredients: []
    }
  }

  componentWillMount() {
    this.renderIngredients();
  }

  goBack() {
    this.props.navigator.pop();
  }

  renderIngredients() {
    let ingredients = [];
    for (let ingredient of this.props.recipe.extendedIngredients) {
      ingredients.push(ingredient.originalString);
    }
    this.setState({
      ingredients: ingredients
    })
  }
  render() {
    const ingredients = this.state.ingredients.map((ingredient, i) => {
      return (
        <Text style = {styles.ingredientListText} key={i}>∙ {ingredient} </Text>
      )
    });
    const recipe = this.props.recipe;
    return(
      <View style={styles.recipe}>
          <View style={styles.resultsTitle}>
            <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}>
              <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} />
            </TouchableHighlight>
            <Text style={styles.resultsTitleText}>Instructions for {this.props.food}:</Text>
          </View>
          <View style={styles.ingredientContainer}>
            <View style={styles.ingredientList}>
              <Text> vegan: {recipe.vegan} gluten free: {recipe.glutenFree} dairy free: {recipe.dairyFree} cheap: {recipe.cheap} sustainable: {recipe.sustainable} servings: {recipe.servings} healthscore: {recipe.healthscore} </Text>
              <Text> url: {recipe.sourceUrl} </Text>
              <Text style={styles.recipeTitle}>Ingredients:</Text>
              <Text style={styles.ingredientListText}>{ingredients}</Text>
            </View>
            <Image source={{uri: this.props.image}} style={styles.recipeImage} />
          </View>
          <View>
            <Text style={styles.recipeTitle}>Directions:</Text>
          </View>
          <ListView
            style={styles.recipe}
            dataSource={this.state.steps}
            renderRow={(step, i) => {
              let image = step.ingredients[0] ? step.ingredients[0].image : 'https://spoonacular.com/recipeImages/buffalo-chicken-panini-with-blue-cheese-and-celery-sdf2-12413.jpg';
              return (
              <View
                key={i}
                style={styles.recipeStep}
                underlayColor="grey"
                >
                  <Image source={{uri: image}} style={styles.recipeImage} />
                  <Text style={styles.recipeStepText}>step {step.number}: {step.step}</Text>
              </View>
              )}}
          />
        </View>
    )
  }
}<commit_msg>added share facebook button on recipe and fixed dietary constraints<commit_after>import React, { Component } from 'react';
import { Text, View, Image, TextInput, ListView, TouchableHighlight } from 'react-native';
import helpers from '../helpers/helpers.js';
import styles from '../styles.ios.js';
import ShareFacebook from './ShareFacebook.ios.js';

export default class Recipe extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      steps: ds.cloneWithRows(props.recipe.analyzedInstructions[0].steps),
      ingredients: []
    }
  }

  componentWillMount() {
    this.renderIngredients();
    this.renderOptions();
  }

  goBack() {
    this.props.navigator.pop();
  }

  renderIngredients() {
    let ingredients = [];
    for (let ingredient of this.props.recipe.extendedIngredients) {
      ingredients.push(ingredient.originalString);
    }
    this.setState({
      ingredients: ingredients
    })
  }

  renderOptions() {
    const recipe = this.props.recipe;
    recipe.vegan = recipe.vegan ? '∙ Vegan' : false;
    recipe.glutenFree = recipe.glutenFree ? '∙ Gluten Free' : false;
    recipe.dairyFree = recipe.dairyFree ? '∙ Dairy Free' : false;
    if (!recipe.vegan && !recipe.glutenFree && !recipe.dairyFree) {
      recipe.dairyFree = 'No Dietary Restrictions';
    }
    recipe.cheap = recipe.cheap ? '$' : '$$$';
    recipe.sustainable = recipe.sustainable ? '∙ Recipe Sustainable' : false;
    recipe.servings = recipe.servings ? recipe.servings : 'Not available';
    recipe.healthscore = recipe.healthscore ? recipe.healthscore : 'Not available';
    // recipe.sourceUrl
  }
  render() {
    const ingredients = this.state.ingredients.map((ingredient, i) => {
      return (
        <Text style = {styles.ingredientListText} key={i}>∙ {ingredient} </Text>
      )
    });
    const recipe = this.props.recipe;
    return(
      <View style={styles.recipe}>
          <View style={styles.resultsTitle}>
            <TouchableHighlight style={styles.backButton} onPress={this.goBack.bind(this)}>
              <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} />
            </TouchableHighlight>
            <Text style={styles.resultsTitleText}>Instructions for {this.props.food}:</Text>
          </View>
          <View style={styles.ingredientContainer}>
            <View style={styles.ingredientList}>
              <Text style={styles.recipeTitle}>Dietary Constraints</Text>
              <Text style={styles.ingredientListText}> {recipe.vegan} {recipe.glutenFree} {recipe.dairyFree}</Text>
              <Text style={styles.recipeTitle}>Recipe Information:</Text>
              <Text style={styles.ingredientListText}> {recipe.cheap} {recipe.sustainable} ∙ Servings: {recipe.servings} ∙ Healthscore: {recipe.healthscore}</Text>
              <Text style={styles.recipeTitle}>Ingredients:</Text>
              <Text style={styles.ingredientListText}>{ingredients}</Text>
            </View>
            <View>
              <Image source={{uri: this.props.image}} style={styles.recipeImage} />
              <ShareFacebook url={this.props.recipe.sourceUrl} />
            </View>
          </View>
          <View>
            <Text style={styles.recipeTitle}>Directions:</Text>
          </View>
          <ListView
            style={styles.recipe}
            dataSource={this.state.steps}
            renderRow={(step, i) => {
              let image = step.ingredients[0] ? step.ingredients[0].image : 'https://spoonacular.com/recipeImages/buffalo-chicken-panini-with-blue-cheese-and-celery-sdf2-12413.jpg';
              return (
              <View
                key={i}
                style={styles.recipeStep}
                underlayColor="grey"
                >
                  <Image source={{uri: image}} style={styles.recipeImage} />
                  <Text style={styles.recipeStepText}>step {step.number}: {step.step}</Text>
              </View>
              )}}
          />
        </View>
    )
  }
}<|endoftext|>


<commit_before><commit_msg>rework orange sorting logic<commit_after><|endoftext|>


<commit_before>/**
 * hive.js
 * Copyright (C) 2013-2016 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Mozilla Public License version 2
 * as published by the Mozilla Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License
 * along with this program.  If not, see <https://www.mozilla.org/en-US/MPL/2.0/>.
 */
var koa = require('koa')
  , router = require('koa-router')
  , co = require('co')
  , cash = require('koa-cash')
  , http = require('http')
  , conditional = require('koa-conditional-get')
  , etag = require('koa-etag')

module.exports = setup
module.exports.provides = ['http']
module.exports.consumes = ['services', 'config', 'logger', 'hooks']

function setup(plugin, imports, register) {
  var services = imports.services
    , config = imports.config
    , logger = imports.logger.getLogger('http')
    , hooks = imports.hooks

  // Set up koa
  var koaApp = koa()

  // Log requests
  koaApp.use(function*(next) {
    logger.info(this.request.method, this.request.url)
    yield next
  })

  // Support conditional GET for client-side resource caching
  koaApp.use(conditional())
  koaApp.use(etag())

  // Add caching
  var cache = {}
  koaApp.use(cash({
    get: function*(key, maxAge) {
      if(!cache[key] || +Date - cache[key].timestamp > maxAge) return
      return cache[key].data
    }
  , set: function*(key, data) {
      cache[key] = { data: data, timestamp: +Date}
    }
  , maxAge: 2*60*60*1000
  }))

  // Use a router
  koaApp.router = router()

  // Error-handling middleware
  koaApp.on('error', function(er) {
    logger.error(er.stack || er.message || er)
  })

  // Register hive service
  services.registerService('http', function(opts) {
    var port = opts.port || config.get('http:port')

    // add router middleware last
    koaApp.use(koaApp.router.routes())

    var server = http.createServer(koaApp.callback())
    server.listen(port, function() {
      co(function*() {
        yield hooks.callHook('http:listening', server)
      }).then(function() {}, function(er){ logger.error(er.stack || er) })
    })
  })

  // register provider
  register(null, {
      http: koaApp
  })
}
<commit_msg>[http] Expose raw http server from the start<commit_after>/**
 * hive.js
 * Copyright (C) 2013-2016 Marcel Klehr <mklehr@gmx.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Mozilla Public License version 2
 * as published by the Mozilla Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License
 * along with this program.  If not, see <https://www.mozilla.org/en-US/MPL/2.0/>.
 */
var koa = require('koa')
  , router = require('koa-router')
  , co = require('co')
  , cash = require('koa-cash')
  , http = require('http')
  , conditional = require('koa-conditional-get')
  , etag = require('koa-etag')

module.exports = setup
module.exports.provides = ['http']
module.exports.consumes = ['services', 'config', 'logger', 'hooks']

function setup(plugin, imports, register) {
  var services = imports.services
    , config = imports.config
    , logger = imports.logger.getLogger('http')
    , hooks = imports.hooks

  // Set up koa
  var koaApp = koa()
  var server = http.createServer(koaApp.callback())
  koaApp.server = server

  // Log requests
  koaApp.use(function*(next) {
    logger.info(this.request.method, this.request.url)
    yield next
  })

  // Support conditional GET for client-side resource caching
  koaApp.use(conditional())
  koaApp.use(etag())

  // Add caching
  var cache = {}
  koaApp.use(cash({
    get: function*(key, maxAge) {
      if(!cache[key] || +Date - cache[key].timestamp > maxAge) return
      return cache[key].data
    }
  , set: function*(key, data) {
      cache[key] = { data: data, timestamp: +Date}
    }
  , maxAge: 2*60*60*1000
  }))

  // Use a router
  koaApp.router = router()

  // Error-handling middleware
  koaApp.on('error', function(er) {
    logger.error(er.stack || er.message || er)
  })

  // Register hive service
  services.registerService('http', function(opts) {
    var port = opts.port || config.get('http:port')

    // add router middleware last
    koaApp.use(koaApp.router.routes())

    server.listen(port, function() {
      co(function*() {
        yield hooks.callHook('http:listening', server)
      }).then(function() {}, function(er){ logger.error(er.stack || er) })
    })
  })

  // register provider
  register(null, {
      http: koaApp
  })
}
<|endoftext|>


<commit_before>import Head from 'next/head'
import React from 'react'
import { addPath } from '@components/image'

const favicon = require('@assets/images/favicon.png')
const appleTouchIcon = require('@assets/images/touch-icon.png')
const ogImage = require('@assets/images/blockstack_og.png')
const DEFAULT = {
  desc: `Blockstack is building an ecosystem that gives your users control over their fundamental digital rights: Identity, data-ownership, privacy, and security. Join us and help build the new internet.`,
  ogImage: addPath(ogImage.src)
}

const url = 'https://blockstack.org/'

const Meta = ({
  title,
  description = DEFAULT.desc,
  ogImage = DEFAULT.ogImage,
  ...rest
}) => {
  let metaOgImage = url + ogImage
  if (ogImage && ogImage.indexOf && (ogImage.indexOf('https://') >= 0)) {
    metaOgImage = ogImage
  } else if (ogImage && ogImage[0] === '/') {
    metaOgImage = url + ogImage.slice(1)
  }
  return (
    <Head>
      <meta name="description" content={description} />
      <link
        rel="shorticon icon"
        href={addPath(favicon.src)}
        type="image/x-icon"
      />
      <link rel="icon" href={addPath(favicon.src)} type="image/x-icon" />
      <link
        rel="apple-touch-icon-precomposed"
        href={addPath(appleTouchIcon.src)}
      />
      <link rel="canonical" href={url} />

      <meta property="og:image" content={metaOgImage} />
      <meta property="og:site_name" content="Blockstack.org" />
      <meta property="og:title" content={title} />
      <meta property="og:description" content={description} />
    </Head>
  )
}

export { Meta }
<commit_msg>add twitter metatags<commit_after>import Head from 'next/head'
import React from 'react'
import { addPath } from '@components/image'

const favicon = require('@assets/images/favicon.png')
const appleTouchIcon = require('@assets/images/touch-icon.png')
const ogImage = require('@assets/images/blockstack_og.png')
const DEFAULT = {
  desc: `Blockstack is building an ecosystem that gives your users control over their fundamental digital rights: Identity, data-ownership, privacy, and security. Join us and help build the new internet.`,
  ogImage: addPath(ogImage.src)
}

const url = 'https://blockstack.org/'

const Meta = ({
  title,
  description = DEFAULT.desc,
  ogImage = DEFAULT.ogImage,
  ...rest
}) => {
  let metaOgImage = url + ogImage
  if (ogImage && ogImage.indexOf && (ogImage.indexOf('https://') >= 0)) {
    metaOgImage = ogImage
  } else if (ogImage && ogImage[0] === '/') {
    metaOgImage = url + ogImage.slice(1)
  }
  return (
    <Head>
      <meta name="description" content={description} />
      <link
        rel="shorticon icon"
        href={addPath(favicon.src)}
        type="image/x-icon"
      />
      <link rel="icon" href={addPath(favicon.src)} type="image/x-icon" />
      <link
        rel="apple-touch-icon-precomposed"
        href={addPath(appleTouchIcon.src)}
      />
      <link rel="canonical" href={url} />

      <meta property="og:image" content={metaOgImage} />
      <meta property="og:site_name" content="Blockstack.org" />
      <meta property="og:title" content={title} />
      <meta property="og:description" content={description} />

      <meta name="twitter:card" content="summary_large_image">
      <meta name="twitter:site" content="@blockstack">
      <meta name="twitter:title" content={title}>
      <meta name="twitter:description" content={description}>
      <meta name="twitter:image" content={metaOgImage}>
    </Head>
  )
}

export { Meta }
<|endoftext|>


<commit_before>var abs = Math.abs;
function bindtouch(target, bindder, lockDirection = "x") {
    var direction, saved_x, saved_y;
    lockDirection = lockDirection.toLowerCase();
    if (!isFunction(bindder) && bindder instanceof Object) {
        var { start, move, end } = bindder;
    } else {
        var move = bindder;
    }
    moveupon(target, {
        start(event) {
            saved_x = event.clientX, saved_y = event.clientY;
            direction = 0;
            start.call(this, event);
        },
        move(event) {
            if (event.moveLocked) return;
            var clientX = event.clientX;
            var clientY = event.clientY;
            var deltax = clientX - saved_x;
            var deltay = clientY - saved_y;
            if (lockDirection) {
                if (!direction) {
                    if (abs(deltax) < MOVELOCK_DELTA && abs(deltay) < MOVELOCK_DELTA) return;
                    if (target.onmovestart) {
                        target.onmovestart();
                    }
                    if (abs(deltax) * .618 >= abs(deltay)) {
                        direction = "x";
                    } else if (abs(deltax) <= .618 * abs(deltay)) {
                        direction = "y";
                    } else {
                        return;
                    }
                }
                if (direction !== lockDirection)
                    return;
                if (direction === "y" && deltay === 0 || direction === "x" && deltax === 0) return;
            }
            event.moveLocked = true;
            var pos = move.call(this, null, event);
            if (pos instanceof Object) {
                var { x = 0, y = 0 } = pos;
                x += deltax;
                y += deltay;
                move.call(this, { x, y, deltax, deltay }, event);
                saved_x = clientX;
                saved_y = clientY;
            }
        },
        end() {
            end.call(this, event);
            direction = 0;
        }
    });

}
<commit_msg>删除全局变量<commit_after>var abs = Math.abs;
function bindtouch(target, bindder, lockDirection = "x") {
    var direction, saved_x, saved_y;
    lockDirection = lockDirection.toLowerCase();
    if (!isFunction(bindder) && bindder instanceof Object) {
        var { start, move, end } = bindder;
    } else {
        var move = bindder;
    }
    moveupon(target, {
        start(event) {
            saved_x = event.clientX, saved_y = event.clientY;
            direction = 0;
            start.call(this, event);
        },
        move(event) {
            if (event.moveLocked) return;
            var clientX = event.clientX;
            var clientY = event.clientY;
            var deltax = clientX - saved_x;
            var deltay = clientY - saved_y;
            if (lockDirection) {
                if (!direction) {
                    if (abs(deltax) < MOVELOCK_DELTA && abs(deltay) < MOVELOCK_DELTA) return;
                    if (target.onmovestart) {
                        target.onmovestart();
                    }
                    if (abs(deltax) * .618 >= abs(deltay)) {
                        direction = "x";
                    } else if (abs(deltax) <= .618 * abs(deltay)) {
                        direction = "y";
                    } else {
                        return;
                    }
                }
                if (direction !== lockDirection)
                    return;
                if (direction === "y" && deltay === 0 || direction === "x" && deltax === 0) return;
            }
            event.moveLocked = true;
            var pos = move.call(this, null, event);
            if (pos instanceof Object) {
                var { x = 0, y = 0 } = pos;
                x += deltax;
                y += deltay;
                move.call(this, { x, y, deltax, deltay }, event);
                saved_x = clientX;
                saved_y = clientY;
            }
        },
        end(event) {
            end.call(this, event);
            direction = 0;
        }
    });

}
<|endoftext|>


<commit_before>/**
 * Created by doug.schroeder on 2/10/16.
 */

module.exports = {
  run: function () {
    require('../../lib/spawn-gulp')(['watch-res-sass'].concat(process.argv.splice(3)));
  },
  help: 'Compiles and serves SCSS files for the responsive skin selected with li set-responsive-options.' +
  '\nSaved changes to local SCSS appears in the browser upon reload. View the compiled CSS at the URL set '+
  '\nwith li set-responsive-options.' +
  '\nRun this command from the root directory of a project. Run li set-responsive-options before running this command.'
};<commit_msg>Update server-sass command to use local-server gulp task.<commit_after>/**
 * Created by doug.schroeder on 2/10/16.
 */
'use strict';

module.exports = {
  run: function () {
    require('../../lib/spawn-gulp')(['watch-res-sass local-server'].concat(process.argv.splice(3)));
  },
  help: 'Compiles and serves SCSS files for the responsive skin selected with li set-responsive-options.' +
  '\nSaved changes to local SCSS appears in the browser upon reload. View the compiled CSS at the URL set '+
  '\nwith li set-responsive-options.' +
  '\nRun this command from the root directory of a project. Run li set-responsive-options before running this command.'
};<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var Memcached = require('memcached')
var restify = require('restify')
var config = require('../config')
var log = require('../log')(config.logLevel, 'customs-server')
var packageJson = require('../package.json')

var LIFETIME = config.recordLifetimeSeconds
var BLOCK_INTERVAL_MS = config.blockIntervalSeconds * 1000
var INVALID_AGENT_INTERVAL_MS = config.invalidAgentIntervalSeconds * 1000

var IpEmailRecord = require('../ip_email_record')(BLOCK_INTERVAL_MS, config.maxBadLogins)
var EmailRecord = require('../email_record')(BLOCK_INTERVAL_MS, config.maxEmails)
var IpRecord = require('../ip_record')(BLOCK_INTERVAL_MS, INVALID_AGENT_INTERVAL_MS)

var P = require('bluebird')
P.promisifyAll(Memcached.prototype)

var mc = new Memcached(
  config.memcached,
  {
    timeout: 500,
    retries: 1,
    retry: 1000,
    reconnect: 1000,
    idle: 30000,
    namespace: 'fxa~'
  }
)

var api = restify.createServer()
api.use(restify.bodyParser())

function ignore(err) {
  log.error({ op: 'memcachedError', err: err })
}

function fetchRecords(email, ip) {
  return P.all(
    [
      // get records and ignore errors by returning a new record
      mc.getAsync(email).then(EmailRecord.parse, EmailRecord.parse),
      mc.getAsync(ip).then(IpRecord.parse, IpRecord.parse),
      mc.getAsync(ip + email).then(IpEmailRecord.parse, IpEmailRecord.parse)
    ]
  )
}

function setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord) {
  return P.all(
    [
      // store records ignoring errors
      mc.setAsync(email, emailRecord, LIFETIME).caught(ignore),
      mc.setAsync(ip, ipRecord, LIFETIME).caught(ignore),
      mc.setAsync(ip + email, ipEmailRecord, LIFETIME).caught(ignore)
    ]
  )
}

function max(prev, cur) {
  return Math.max(prev, cur)
}

api.post(
  '/check',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    var agent = req.body.agent
    var action = req.body.action

    if (!email || !ip || !agent || !action) {
      var err = {code: 'MissingParameters', message: 'email, ip, agent and action are all required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, agent: agent, action: action, err: err })
      res.send(500, err)
      return next()
    }

    fetchRecords(email, ip)
      .spread(
        function (emailRecord, ipRecord, ipEmailRecord) {
          var blockEmail = emailRecord.update(action)
          var blockLogin = ipEmailRecord.update(action)
          var blockAgent = ipRecord.update(agent)

          if (blockLogin && ipEmailRecord.unblockIfReset(emailRecord.pr)) {
            blockLogin = 0
          }
          var retryAfter = [blockEmail, blockLogin, blockAgent].reduce(max)

          return setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord)
            .then(
              function () {
                return {
                  block: retryAfter > 0,
                  retryAfter: retryAfter
                }
                return
              }
            )
        }
      )
      .then(
        function (result) {
          log.info({ op: 'request.check', email: email, ip: ip, block: result.block })
          res.send(result)
        },
        function (err) {
          log.error({ op: 'request.check', email: email, ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/failedLoginAttempt',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    if (!email || !ip) {
      var err = {code: 'MissingParameters', message: 'email and ip are both required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(ip + email)
      .then(IpEmailRecord.parse, IpEmailRecord.parse)
      .then(
        function (ipEmailRecord) {
          ipEmailRecord.addBadLogin()
          return mc.setAsync(ip + email, ipEmailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.failedLoginAttempt', email: email, ip: ip })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/passwordReset',
  function (req, res, next) {
    var email = req.body.email
    if (!email) {
      var err = {code: 'MissingParameters', message: 'email is required'}
      log.error({ op: 'request.passwordReset', email: email, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(email)
      .then(EmailRecord.parse, EmailRecord.parse)
      .then(
        function (emailRecord) {
          emailRecord.passwordReset()
          return mc.setAsync(email, emailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.passwordReset', email: email })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.passwordReset', email: email, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.get(
  '/',
  function (req, res, next) {
    res.send({ version: packageJson.version })
    next()
  }
)

api.listen(
  config.port,
  function () {
    log.info({ op: 'listening', port: config.port })
  }
)
<commit_msg>Include all parameters in the logging of /check<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var Memcached = require('memcached')
var restify = require('restify')
var config = require('../config')
var log = require('../log')(config.logLevel, 'customs-server')
var packageJson = require('../package.json')

var LIFETIME = config.recordLifetimeSeconds
var BLOCK_INTERVAL_MS = config.blockIntervalSeconds * 1000
var INVALID_AGENT_INTERVAL_MS = config.invalidAgentIntervalSeconds * 1000

var IpEmailRecord = require('../ip_email_record')(BLOCK_INTERVAL_MS, config.maxBadLogins)
var EmailRecord = require('../email_record')(BLOCK_INTERVAL_MS, config.maxEmails)
var IpRecord = require('../ip_record')(BLOCK_INTERVAL_MS, INVALID_AGENT_INTERVAL_MS)

var P = require('bluebird')
P.promisifyAll(Memcached.prototype)

var mc = new Memcached(
  config.memcached,
  {
    timeout: 500,
    retries: 1,
    retry: 1000,
    reconnect: 1000,
    idle: 30000,
    namespace: 'fxa~'
  }
)

var api = restify.createServer()
api.use(restify.bodyParser())

function ignore(err) {
  log.error({ op: 'memcachedError', err: err })
}

function fetchRecords(email, ip) {
  return P.all(
    [
      // get records and ignore errors by returning a new record
      mc.getAsync(email).then(EmailRecord.parse, EmailRecord.parse),
      mc.getAsync(ip).then(IpRecord.parse, IpRecord.parse),
      mc.getAsync(ip + email).then(IpEmailRecord.parse, IpEmailRecord.parse)
    ]
  )
}

function setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord) {
  return P.all(
    [
      // store records ignoring errors
      mc.setAsync(email, emailRecord, LIFETIME).caught(ignore),
      mc.setAsync(ip, ipRecord, LIFETIME).caught(ignore),
      mc.setAsync(ip + email, ipEmailRecord, LIFETIME).caught(ignore)
    ]
  )
}

function max(prev, cur) {
  return Math.max(prev, cur)
}

api.post(
  '/check',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    var agent = req.body.agent
    var action = req.body.action

    if (!email || !ip || !agent || !action) {
      var err = {code: 'MissingParameters', message: 'email, ip, agent and action are all required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, agent: agent, action: action, err: err })
      res.send(500, err)
      return next()
    }

    fetchRecords(email, ip)
      .spread(
        function (emailRecord, ipRecord, ipEmailRecord) {
          var blockEmail = emailRecord.update(action)
          var blockLogin = ipEmailRecord.update(action)
          var blockAgent = ipRecord.update(agent)

          if (blockLogin && ipEmailRecord.unblockIfReset(emailRecord.pr)) {
            blockLogin = 0
          }
          var retryAfter = [blockEmail, blockLogin, blockAgent].reduce(max)

          return setRecords(email, ip, emailRecord, ipRecord, ipEmailRecord)
            .then(
              function () {
                return {
                  block: retryAfter > 0,
                  retryAfter: retryAfter
                }
                return
              }
            )
        }
      )
      .then(
        function (result) {
          log.info({ op: 'request.check', email: email, ip: ip, agent: agent, action: action, block: result.block })
          res.send(result)
        },
        function (err) {
          log.error({ op: 'request.check', email: email, ip: ip, agent: agent, action: action, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/failedLoginAttempt',
  function (req, res, next) {
    var email = req.body.email
    var ip = req.body.ip
    if (!email || !ip) {
      var err = {code: 'MissingParameters', message: 'email and ip are both required'}
      log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(ip + email)
      .then(IpEmailRecord.parse, IpEmailRecord.parse)
      .then(
        function (ipEmailRecord) {
          ipEmailRecord.addBadLogin()
          return mc.setAsync(ip + email, ipEmailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.failedLoginAttempt', email: email, ip: ip })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.failedLoginAttempt', email: email, ip: ip, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.post(
  '/passwordReset',
  function (req, res, next) {
    var email = req.body.email
    if (!email) {
      var err = {code: 'MissingParameters', message: 'email is required'}
      log.error({ op: 'request.passwordReset', email: email, err: err })
      res.send(500, err)
      next()
    }

    mc.getAsync(email)
      .then(EmailRecord.parse, EmailRecord.parse)
      .then(
        function (emailRecord) {
          emailRecord.passwordReset()
          return mc.setAsync(email, emailRecord, LIFETIME).caught(ignore)
        }
      )
      .then(
        function () {
          log.info({ op: 'request.passwordReset', email: email })
          res.send({})
        },
        function (err) {
          log.error({ op: 'request.passwordReset', email: email, err: err })
          res.send(500, err)
        }
      )
      .done(next, next)
  }
)

api.get(
  '/',
  function (req, res, next) {
    res.send({ version: packageJson.version })
    next()
  }
)

api.listen(
  config.port,
  function () {
    log.info({ op: 'listening', port: config.port })
  }
)
<|endoftext|>


<commit_before>'use strict';

function Git(grunt) {

    var path = require('path');

    /**
     * Gets the sha# from the bower file.
     * @returns sha The sha#.
     */
    function getSha(cwd) {
        var dotBowerJsonPath = path.resolve(cwd + '/.bower.json');

        return grunt.file.exists(dotBowerJsonPath) ?
            grunt.file.readJSON(dotBowerJsonPath)._resolution.commit.substring(0, 7):
            undefined;
    }

    /**
     * Gets the current version from the bower file.
     * @returns version The version
     */
    function getVersion(cwd) {
        var bowerJsonPath = path.resolve(cwd + '/bower.json');

        return grunt.file.exists(bowerJsonPath)?
            grunt.file.readJSON(bowerJsonPath).version.match(/([\d|\.]+)/)[1]:
            undefined;
    }

    /**
     * Gets the new version.
     * @returns newVersion The new version.
     */
    function getNewVersion(cwd, buildNumber) {
        var version = getVersion(cwd),
            sha = getSha(cwd),
            newVersion;

        if(version) {
            newVersion = version;
            if(buildNumber && sha) {
                newVersion = newVersion.concat('-build.' + buildNumber + '+sha.' + sha);
            }
        }
        return newVersion;
    }

    return {
        commands: {
            /* Clone the repository into the specified directory */
            clone: function (repository, workingDirectory, done) {
                var options = {
                    cmd: 'git',
                    args: ['clone', repository, workingDirectory],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not clone repository due to previous shown error.');
                    }
                    done();
                });
            },
            addAll: function (workingDirectory, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', '--work-tree', workingDirectory, 'add', '-A'],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not add pending changes due to previous show error.');
                    }
                    done();
                });
            },
            commit: function (workingDirectory, newVersion, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', '--work-tree', workingDirectory, 'commit', '-m', newVersion],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not add pending changes due to previous show error.');
                    }
                    done();
                });
            },
            tag: function (workingDirectory, newVersion, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', '--work-tree', workingDirectory, 'tag', newVersion],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not tag due to previous show error.');
                    }
                    done();
                });
            },
            push: function (workingDirectory, refs, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', 'push', 'origin', refs],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not tag due to previous show error.');
                    }
                    done();
                });
            }
        },
        /** Utility methods. */
        utils: {
            version: function (workingDirectory) {
                return getVersion(workingDirectory);
            },
            sha: function (workingDirectory) {
                return getSha(workingDirectory);
            },
            newVersion: function (workingDirectory, buildNumber) {
                return getNewVersion(workingDirectory, buildNumber);
            }
        }
    };
}

module.exports = Git;<commit_msg>Added function to get the previous sha hash<commit_after>'use strict';

function Git(grunt) {

    var path = require('path');

    /**
     * Gets the sha# from the bower file.
     * @returns sha The sha#.
     */
    function getSha(cwd) {
        var dotBowerJsonPath = path.resolve(cwd + '/.bower.json');

        return grunt.file.exists(dotBowerJsonPath) ?
            grunt.file.readJSON(dotBowerJsonPath)._resolution.commit.substring(0, 7):
            undefined;
    }

    /**
     * Gets the current version from the bower file.
     * @returns version The version
     */
    function getVersion(cwd) {
        var bowerJsonPath = path.resolve(cwd + '/bower.json');

        return grunt.file.exists(bowerJsonPath)?
            grunt.file.readJSON(bowerJsonPath).version.match(/([\d|\.]+)/)[1]:
            undefined;
    }

    /**
     * Gets the previous sha from the bower file from the repository.
     * @returns sha The sha
     */
    function getPreviousSha(wd) {
        var bowerJsonPath = path.resolve(wd + '/bower.json');
        if(grunt.file.exists(bowerJsonPath)) {
            var sha = undefined;
            try {
                sha = grunt.file.readJSON(bowerJsonPath).version.match(/.*sha\.(.*)/)[1]
            } finally {
                return sha;
            }
        }
    }

    /**
     * Gets the new version.
     * @returns newVersion The new version.
     */
    function getNewVersion(cwd, buildNumber) {
        var version = getVersion(cwd),
            sha = getSha(cwd),
            newVersion;

        if(version) {
            newVersion = version;
            if(buildNumber && sha) {
                newVersion = newVersion.concat('-build.' + buildNumber + '+sha.' + sha);
            }
        }
        return newVersion;
    }

    return {
        commands: {
            /* Clone the repository into the specified directory */
            clone: function (repository, workingDirectory, done) {
                var options = {
                    cmd: 'git',
                    args: ['clone', repository, workingDirectory],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not clone repository due to previous shown error.');
                    }
                    done();
                });
            },
            addAll: function (workingDirectory, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', '--work-tree', workingDirectory, 'add', '-A'],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not add pending changes due to previous show error.');
                    }
                    done();
                });
            },
            commit: function (workingDirectory, newVersion, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', '--work-tree', workingDirectory, 'commit', '-m', newVersion],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not add pending changes due to previous show error.');
                    }
                    done();
                });
            },
            tag: function (workingDirectory, newVersion, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', '--work-tree', workingDirectory, 'tag', newVersion],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not tag due to previous show error.');
                    }
                    done();
                });
            },
            push: function (workingDirectory, refs, done) {
                var options = {
                    cmd: 'git',
                    args: ['--git-dir', workingDirectory + '/.git', 'push', 'origin', refs],
                    opts: {
                        stdio: 'inherit'
                    }
                };
                grunt.util.spawn(options, function (error, result, code) {
                    if (error !== null) {
                        grunt.fail.fatal('Could not tag due to previous show error.');
                    }
                    done();
                });
            }
        },
        /** Utility methods. */
        utils: {
            version: function (workingDirectory) {
                return getVersion(workingDirectory);
            },
            sha: function (workingDirectory) {
                return getSha(workingDirectory);
            },
            previousSha: function (workingDirectory) {
                return getPreviousSha(workingDirectory);
            },
            newVersion: function (workingDirectory, buildNumber) {
                return getNewVersion(workingDirectory, buildNumber);
            }
        }
    };
}

module.exports = Git;<|endoftext|>


<commit_before>/*
 * grunt-hub
 * https://github.com/shama/grunt-hub
 *
 * Copyright (c) 2013 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var path = require('path');
  var chalk = require('chalk');
  var async = require('async');
  var _ = require('lodash')

  grunt.registerMultiTask('hub', 'Run multiple grunt projects', function() {
    var options = this.options({
      concurrent: 3,
      allowSelf: false
    });
    var args = (this.args.length < 1) ? false : this.args;

    var done = this.async();
    var errorCount = 0;
    // Get process.argv options without grunt.cli.tasks to pass to child processes
    var cliArgs = _.without.apply(null, [[].slice.call(process.argv, 2)].concat(grunt.cli.tasks));
    // Get it's own gruntfile
    var ownGruntfile += grunt.option('gruntfile') || grunt.file.expand({filter: 'isFile'}, '{G,g}runtfile.{js,coffee}')[0];
    ownGruntfile = path.resolve(process.cwd(), ownGruntfile || '');

    var lastGruntFileWritten;
    function write(gruntfile, buf, isError) {
      if (gruntfile !== lastGruntFileWritten) {
        grunt.log.writeln('');
        grunt.log.writeln('');
        grunt.log.writeln(chalk.cyan('>> ') + gruntfile + ':\n');
      }
      grunt.log[(isError) ? 'error' : 'write'](buf);
      lastGruntFileWritten = gruntfile;
    }

    // our queue for concurrently ran tasks
    var queue = async.queue(function(run, next) {
      grunt.log.ok('Running [' + run.tasks + '] on ' + run.gruntfile);
      var child = grunt.util.spawn({
        // Use grunt to run the tasks
        grunt: true,
        // Run from dirname of gruntfile
        opts: {cwd: path.dirname(run.gruntfile)},
        // Run task to be run and any cli options
        args: run.tasks.concat(cliArgs || [], '--gruntfile=' + run.gruntfile)
      }, function(err, res, code) {
        if (err) { errorCount++; }
        next();
      });
      child.stdout.on('data', function(buf) {
        write(run.gruntfile, buf);
      });
      child.stderr.on('data', function(buf) {
        write(run.gruntfile, buf, true);
      });
    }, options.concurrent);

    // When the queue is all done
    queue.drain = function() {
      done((errorCount === 0));
    };

    this.files.forEach(function(files) {
      var gruntfiles = grunt.file.expand({filter: 'isFile'}, files.src);
      gruntfiles.forEach(function(gruntfile) {
        gruntfile = path.resolve(process.cwd(), gruntfile);

        // Skip it's own gruntfile. Prevents infinite loops.
        if (!options.allowSelf && gruntfile === ownGruntfile) { return; }

        queue.push({
          gruntfile: gruntfile,
          tasks: args || files.tasks || ['default']
        });
      });
    });

  });

};
<commit_msg>Fix syntax error. Thanks @eugeneiiim!<commit_after>/*
 * grunt-hub
 * https://github.com/shama/grunt-hub
 *
 * Copyright (c) 2013 Kyle Robinson Young
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var path = require('path');
  var chalk = require('chalk');
  var async = require('async');
  var _ = require('lodash');

  grunt.registerMultiTask('hub', 'Run multiple grunt projects', function() {
    var options = this.options({
      concurrent: 3,
      allowSelf: false
    });
    var args = (this.args.length < 1) ? false : this.args;

    var done = this.async();
    var errorCount = 0;
    // Get process.argv options without grunt.cli.tasks to pass to child processes
    var cliArgs = _.without.apply(null, [[].slice.call(process.argv, 2)].concat(grunt.cli.tasks));
    // Get it's own gruntfile
    var ownGruntfile = grunt.option('gruntfile') || grunt.file.expand({filter: 'isFile'}, '{G,g}runtfile.{js,coffee}')[0];
    ownGruntfile = path.resolve(process.cwd(), ownGruntfile || '');

    var lastGruntFileWritten;
    function write(gruntfile, buf, isError) {
      if (gruntfile !== lastGruntFileWritten) {
        grunt.log.writeln('');
        grunt.log.writeln('');
        grunt.log.writeln(chalk.cyan('>> ') + gruntfile + ':\n');
      }
      grunt.log[(isError) ? 'error' : 'write'](buf);
      lastGruntFileWritten = gruntfile;
    }

    // our queue for concurrently ran tasks
    var queue = async.queue(function(run, next) {
      grunt.log.ok('Running [' + run.tasks + '] on ' + run.gruntfile);
      var child = grunt.util.spawn({
        // Use grunt to run the tasks
        grunt: true,
        // Run from dirname of gruntfile
        opts: {cwd: path.dirname(run.gruntfile)},
        // Run task to be run and any cli options
        args: run.tasks.concat(cliArgs || [], '--gruntfile=' + run.gruntfile)
      }, function(err, res, code) {
        if (err) { errorCount++; }
        next();
      });
      child.stdout.on('data', function(buf) {
        write(run.gruntfile, buf);
      });
      child.stderr.on('data', function(buf) {
        write(run.gruntfile, buf, true);
      });
    }, options.concurrent);

    // When the queue is all done
    queue.drain = function() {
      done((errorCount === 0));
    };

    this.files.forEach(function(files) {
      var gruntfiles = grunt.file.expand({filter: 'isFile'}, files.src);
      gruntfiles.forEach(function(gruntfile) {
        gruntfile = path.resolve(process.cwd(), gruntfile);

        // Skip it's own gruntfile. Prevents infinite loops.
        if (!options.allowSelf && gruntfile === ownGruntfile) { return; }

        queue.push({
          gruntfile: gruntfile,
          tasks: args || files.tasks || ['default']
        });
      });
    });

  });

};
<|endoftext|>


<commit_before>/*
 * Part of: "grunt-html-head-urls-min-toggle"
 * https://github.com/pinestec/grunt-html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

var help_needed = false;
var help_needed__pattern = /^--?h(elp)?$/i;

function scan_arguments(value, index, array) {
	if (index > 1) {
		if (value.search(help_needed__pattern) !== -1) {
			throw exception;
		}
	}
}
try {
	process.argv.forEach(scan_arguments);
} catch (exception) {
	help_needed = true;
}

if (help_needed) {
	var dummy_string_one = "/c/Users/hartung/workspace_node_js/html-head-urls-min-toggle/bin/objects_carver.js";
	var dummy_string_two = "C:\\Users\\hartung\\workspace_node_js\\html-head-urls-min-toggle\\bin\\objects_carver.js";
	var plain_file_name_RegExp = new RegExp("[^/\\\\]*$");
	var result_array = plain_file_name_RegExp.exec(dummy_string_two);
	if (result_array !== null) {
		console.log(result_array[0]);
	}
} else {
	console.log("NO HELP NEEDED...!");
}<commit_msg>Help output looks nice now... - MH - pT<commit_after>/*
 * Part of: "grunt-html-head-urls-min-toggle"
 * https://github.com/pinestec/grunt-html-head-urls-min-toggle
 *
 * Copyright (c) 2017 Michael Hartung
 * Licensed under the MIT license.
 */

'use strict';

var help_needed = false;
var help_needed__pattern = /^--?h(elp)?$/i;

function scan_arguments(value, index, array) {
	if (index > 1) {
		if (value.search(help_needed__pattern) !== -1) {
			throw exception;
		}
	}
}
try {
	process.argv.forEach(scan_arguments);
} catch (exception) {
	help_needed = true;
}

if (help_needed) {
	var plain_file_name_RegExp = new RegExp("([^/\\\\]*)$");
	var result_array = plain_file_name_RegExp.exec(process.argv[1]);
	if (result_array !== null) {
		console.log("usage:\t" + result_array[1] + " entire_filename [-h|--help] \n");
		console.log("Writing internally defined \"reference objects\" to disk with the help of \"JSON.stringify\"...");
		console.log("For later use with other packages.");
	}
} else {
	console.log("NO HELP NEEDED...!");
}<|endoftext|>


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

/**
 * Module dependencies
 */

var _ = require('lodash');
var async = require('async');
var reportback = require('reportback')();
var sailsgen = require('sails-generate');
var package = require('../package.json');
var rconf = require('../lib/app/configuration/rc');
var _generateAPI = require('./_generate-api');

/**
 * `sails generate`
 *
 * Generate module(s) for the app in our working directory.
 * Internally, uses ejs for rendering the various module templates.
 */

module.exports = function() {

  // Build initial scope
  var scope = {
    rootPath: process.cwd(),
    modules: {},
    sailsPackageJSON: package,
  };

  // Mix-in rc config
  _.merge(scope, rconf.generators);

  // TODO: just do a top-level merge and reference
  // `scope.generators.modules` as needed (simpler)
  _.merge(scope, rconf);

  // Pass the original CLI arguments down to the generator
  // (but first, remove commander's extra argument)
  // (also peel off the `generatorType` arg)
  var cliArguments = Array.prototype.slice.call(arguments);
  cliArguments.pop();
  scope.generatorType = cliArguments.shift();
  scope.args = cliArguments;

  // Create a new reportback
  var cb = reportback.extend();

  // Show usage if no generator type is defined
  if (!scope.generatorType) {
    return cb.log.error('Usage: sails generate [something]');
  }

  // Set the "invalid" exit to forward to "error"
  cb.error = function(msg) {
    var log = this.log || cb.log;
    log.error(msg);
    process.exit(1);
  };

  cb.invalid = 'error';

  // If the generator type is "api", we currently treat it as a special case.
  // (todo: pull this out into a simple generator)
  if (scope.generatorType === 'api') {
    if (scope.args.length === 0) {
      return cb.error('Usage: sails generate api [api name]');
    }
    _generateAPI(scope, cb);
  }

  // Otherwise just run whichever generator was requested.
  else {
    cb.success = function() {
      cb.log.info('Generated a new ' + scope.generatorType + ' `' + scope.id + '` at ' + scope.destDir + scope.globalID + '.js!');
    };

    //
    return sailsgen(scope, cb);
  }

};
<commit_msg>Improve output<commit_after>#!/usr/bin/env node

/**
 * Module dependencies
 */

var _ = require('lodash');
var util = require('util');
var async = require('async');
var reportback = require('reportback')();
var sailsgen = require('sails-generate');
var package = require('../package.json');
var rconf = require('../lib/app/configuration/rc');
var _generateAPI = require('./_generate-api');

/**
 * `sails generate`
 *
 * Generate module(s) for the app in our working directory.
 * Internally, uses ejs for rendering the various module templates.
 */

module.exports = function() {

  // Build initial scope
  var scope = {
    rootPath: process.cwd(),
    modules: {},
    sailsPackageJSON: package,
  };

  // Mix-in rc config
  _.merge(scope, rconf.generators);

  // TODO: just do a top-level merge and reference
  // `scope.generators.modules` as needed (simpler)
  _.merge(scope, rconf);

  // Pass the original CLI arguments down to the generator
  // (but first, remove commander's extra argument)
  // (also peel off the `generatorType` arg)
  var cliArguments = Array.prototype.slice.call(arguments);
  cliArguments.pop();
  scope.generatorType = cliArguments.shift();
  scope.args = cliArguments;

  // Create a new reportback
  var cb = reportback.extend();

  // Show usage if no generator type is defined
  if (!scope.generatorType) {
    return cb.log.error('Usage: sails generate [something]');
  }

  // Set the "invalid" exit to forward to "error"
  cb.error = function(msg) {
    var log = this.log || cb.log;
    log.error(msg);
    process.exit(1);
  };

  cb.invalid = 'error';

  // If the generator type is "api", we currently treat it as a special case.
  // (todo: pull this out into a simple generator)
  if (scope.generatorType === 'api') {
    if (scope.args.length === 0) {
      return cb.error('Usage: sails generate api [api name]');
    }
    _generateAPI(scope, cb);
  }

  // Otherwise just run whichever generator was requested.
  else {
    cb.success = function() {

      // Determine the output path
      var outputPath = scope.outputPath;
      if (!outputPath && scope.filename) {
        outputPath = scope.destDir + scope.filename;
      }
      var humanizedPath;
      if (outputPath) {
        humanizedPath = 'at ' + outputPath;
      }
      else {
        humanizedPath = 'in ' + scope.destDir;
      }

      cb.log.info(util.format(
        'Generated a new %s ("%s") %s!',
        scope.generatorType, scope.id, humanizedPath
      ));
    };

    //
    return sailsgen(scope, cb);
  }

};
<|endoftext|>


<commit_before>var myArray = [];
$("#submit").on('click', function() {
	if ( $('#box').val() || $('#box').text() ) {
		myArray = $('#box').val().replace(/\.|,|'/g, '').split('\n');
		if ( $('#output').length === 0) {
			$('form').append('<textarea id="output" rows="20" cols="50"></textarea>');
		}
		for( var i = 0; i<myArray.length; i++ ) {
			var newValue = myArray[i].toLowerCase().replace(/ /g, "-");
				if ( i === myArray.length - 1) {
					$('#output').append(newValue);
					$('#submit').attr('disabled', 'disabled');
					$('#clipboard').removeAttr('disabled');
				} else {
					$('#output').append(newValue + '\n');
				}
			}
		} else {
			alert('This is a required field.');
		}
	}
);

// copy to clipboard code

$('#clipboard').click(function(){
    var output = document.getElementById('output');
    output.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
    output.blur();
});

$("#reset_button").on('click', function(value) {
	$('#submit').removeAttr('disabled');
	$('#output').remove();
}
);

<commit_msg>disable 'Copy to clipboard' button on reset.<commit_after>var myArray = [];
$("#submit").on('click', function() {
	if ( $('#box').val() || $('#box').text() ) {
		myArray = $('#box').val().replace(/\.|,|'/g, '').split('\n');
		if ( $('#output').length === 0) {
			$('form').append('<textarea id="output" rows="20" cols="50"></textarea>');
		}
		for( var i = 0; i<myArray.length; i++ ) {
			var newValue = myArray[i].toLowerCase().replace(/ /g, "-");
				if ( i === myArray.length - 1) {
					$('#output').append(newValue);
					$('#submit').attr('disabled', 'disabled');
					$('#clipboard').removeAttr('disabled');
				} else {
					$('#output').append(newValue + '\n');
				}
			}
		} else {
			alert('This is a required field.');
		}
	}
);

// copy to clipboard code

$('#clipboard').click(function(){
    var output = document.getElementById('output');
    output.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
    output.blur();
});

$("#reset_button").on('click', function(value) {
	$('#submit').removeAttr('disabled');
	$('#output').remove();
	$('#clipboard').attr('disabled', 'disabled');
}
);

<|endoftext|>


<commit_before><commit_msg>Test bad input to ciede2000<commit_after><|endoftext|>


<commit_before>const defaultConfig = require('./web-ext-config.js')

module.exports = Object.assign(defaultConfig, {
  ignoreFiles: [],
  run: {
    chromiumProfile: './tmp-chromium',
    args: [
      '--auto-open-devtools-for-tabs',
      '--start-maximized',
      '--disable-breakpad',
      '--disable-default-apps',
      '--disable-signin-promo',
      '--disable-sync',
      '--no-default-browser-check',
      '--no-pings',
      '--restore-last-session'
    ],
    startUrl: [
      'https://accounts.spotify.com/en/login?continue=https://open.spotify.com/',
    ]
  }
})<commit_msg>Add more Chromium flags<commit_after>const defaultConfig = require('./web-ext-config.js')

module.exports = Object.assign(defaultConfig, {
  ignoreFiles: [],
  run: {
    chromiumProfile: './tmp-chromium',
    args: [
      // https://peter.sh/experiments/chromium-command-line-switches/
      '--auto-open-devtools-for-tabs',
      '--disable-breakpad',
      '--disable-cloud-import',
      '--disable-default-apps',
      '--disable-ntp-most-likely-favicons-from-server',
      '--disable-ntp-popular-sites',
      '--disable-offline-auto-reload',
      '--disable-signin-promo',
      '--disable-single-click-autofill',
      '--disable-sync',
      '--enable-features=WebUIDarkMode',
      '--force-dark-mode',
      '--host-rules="MAP *.google-analytics.com 0.0.0.0","MAP *.googleadservices.com 0.0.0.0","MAP *.doubleclick.net 0.0.0.0 │ ","MAP *.googletagservices.com 0.0.0.0"',
      '--no-default-browser-check',
      '--no-pings',
      '--password-store=basic',
      '--restore-last-session',
      '--safebrowsing-disable-extension-blacklist',
      '--start-maximized'
    ],
    startUrl: [
      'https://accounts.spotify.com/en/login?continue=https://open.spotify.com/',
    ]
  }
})<|endoftext|>


<commit_before><commit_msg>Clean test file<commit_after><|endoftext|>


<commit_before>var enml2md = require('../lib/enml2md.js'),
  should = require('should'),
  fs = require('fs'),
  util = require('util')

var tzMin = (new Date).getTimezoneOffset() // minutes

describe('EvernoteExport(enml_filename)', function() {
  var temp = require('temp')
  temp.track()
  describe('#export(directory, cbDone)', function() {
    it('creates an export directory', function(done) {
      temp.mkdir('enml2md', function(err, dirPath) {
        var enex = new enml2md.EvernoteExport('./test/fixtures/fixture1.enex')
        enex.export(dirPath, function () {
          fs.stat(dirPath, function (err, stats) {
            if (err) throw err
            stats.isDirectory().should.be.true
            done()
          })
        })
      })
    })
    it('creates exported files', function(done) {
      temp.mkdir('enml2md', function(err, dirPath) {
        var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
        enex.export(dirPath, function () {
          fs.readdir(dirPath, function (err, files) {
            if (err) throw err
            files.length.should.equal(2)
            done()
          })
        })
      })
    })
    it('can be called without a callback', function(done) {
      temp.mkdir('enml2md', function(err, dirPath) {
        var enex = new enml2md.EvernoteExport('./test/fixtures/fixture1.enex')
        enex.export(dirPath)
        var testDone = function () {
          enex.count.should.equal(1)
          if (enex.done) done()
          else setTimeout(testDone, 10)
        }
        setTimeout(testDone, 10)
      })
    })
  })
  describe('#each(cbEach, cbEnd)', function() {
    it('sets total #count at cbEnd()', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
      var cbEach = function (note) { // callback for each note
        // do nothing
      }
      var cbEnd = function () { // callback for the end
        enex.count.should.equal(2)
        done()
      }
      enex.each(cbEach, cbEnd)
    })
    it('calls cbEach(note)', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture1.enex')
      var expected_created = new Date(2013, 10, 2, 10, 0-tzMin, 55) // 20131102T100055Z
      var expected_updated = new Date(2013, 10, 2, 10, 3-tzMin, 49) // 20131102T100349Z
      var cbEach = function (note) { // callback for each note
        note.title.should.equal('Enml2md test fixture note')
        note.created.should.eql(expected_created)
        note.updated.should.eql(expected_updated)
        note.tags.should.contain('markdown')
        note.tags.should.contain('evernote')
        note.tags.length.should.equal(2)
        note.content.should.equal('fixture content\n\n')
      }
      var cbEnd = function () { // callback for the end
        enex.count.should.equal(1)
        done()
      }
      enex.each(cbEach, cbEnd)
    })
    it('can be called without cbEach()', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
      var cbEnd = function () { // callback for the end
        enex.count.should.equal(2)
        done()
      }
      enex.each(null, cbEnd)
    })
    it('can be called without both beEach() and cbEnd()', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
      var testDone = function () {
        enex.count.should.equal(2)
        done()
      }
      setTimeout(testDone, 20)
      enex.each(null, null)
    })
  })
})

describe('Note', function() {
  var note_enml = fs.readFileSync('./test/fixtures/note.enex')
  var note = enml2md.Note.parse(note_enml)
  it('.parse() returns a note object.', function() {
    note.should.be.an.instanceof(enml2md.Note)
  })
  it('#filename(extention) escapes title string.', function() {
    note.filename('.md').should.equal('a single note fixture test  1.md')
    note.filename('.txt').should.equal('a single note fixture test  1.txt')
  })
  it('#title is a title string.', function() {
    note.title.should.equal('a single note fixture/test: 1')
  })
  it('#created is a Date object.', function() {
    var date = new Date(2013, 10, 2, 10, 7-tzMin, 9) // 20131102T100709Z
    note.created.should.be.an.instanceof(Date)
    note.created.should.eql(date)
  })
  it('#updated is a Date object.', function() {
    var date = new Date(2013, 10, 2, 10, 7-tzMin, 13) // 20131102T100713Z
    note.updated.should.be.an.instanceof(Date)
    note.updated.should.eql(date)
  })
  it('#tags is an array of string.', function() {
    note.tags.should.be.an.instanceof(Array)
    note.tags.length.should.equal(2)
    note.tags[0].should.equal('markdown')
    note.tags[1].should.equal('evernote')
  })
  it('#content is a Markdown string.', function() {
    note.content.should.equal('fixture content\n\n')
  })
})<commit_msg>refactoring test<commit_after>var enml2md = require('../lib/enml2md.js'),
  should = require('should'),
  fs = require('fs'),
  util = require('util')

var tzMin = (new Date).getTimezoneOffset() // minutes

describe('EvernoteExport(enml_filename)', function() {
  var temp = require('temp')
  temp.track()
  describe('#export(directory, cbDone)', function() {
    it('creates an export directory', function(done) {
      temp.mkdir('enml2md', function(err, dirPath) {
        var enex = new enml2md.EvernoteExport('./test/fixtures/fixture1.enex')
        enex.export(dirPath, function () {
          fs.stat(dirPath, function (err, stats) {
            if (err) throw err
            stats.isDirectory().should.be.true
            done()
          })
        })
      })
    })
    it('creates exported files', function(done) {
      temp.mkdir('enml2md', function(err, dirPath) {
        var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
        enex.export(dirPath, function () {
          fs.readdir(dirPath, function (err, files) {
            if (err) throw err
            files.length.should.equal(2)
            done()
          })
        })
      })
    })
    it('can be called without a callback', function(done) {
      temp.mkdir('enml2md', function(err, dirPath) {
        var enex = new enml2md.EvernoteExport('./test/fixtures/fixture1.enex')
        enex.export(dirPath)
        var testDone = function () {
          enex.count.should.equal(1)
          if (enex.done) done()
          else setTimeout(testDone, 10)
        }
        setTimeout(testDone, 10)
      })
    })
  })
  describe('#each(cbEach, cbEnd)', function() {
    it('sets total #count at cbEnd()', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
      var cbEach = function (note) { // callback for each note
        // do nothing
      }
      var cbEnd = function () { // callback for the end
        enex.count.should.equal(2)
        done()
      }
      enex.each(cbEach, cbEnd)
    })
    it('calls cbEach(note)', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture1.enex')
      var expected_created = new Date(2013, 10, 2, 10, 0-tzMin, 55) // 20131102T100055Z
      var expected_updated = new Date(2013, 10, 2, 10, 3-tzMin, 49) // 20131102T100349Z
      var cbEach = function (note) { // callback for each note
        note.title.should.equal('Enml2md test fixture note')
        note.created.should.eql(expected_created)
        note.updated.should.eql(expected_updated)
        note.tags.should.contain('markdown')
        note.tags.should.contain('evernote')
        note.tags.length.should.equal(2)
        note.content.should.equal('fixture content\n\n')
      }
      var cbEnd = function () { // callback for the end
        enex.count.should.equal(1)
        done()
      }
      enex.each(cbEach, cbEnd)
    })
    it('can be called without cbEach()', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
      var cbEnd = function () { // callback for the end
        enex.count.should.equal(2)
        done()
      }
      enex.each(null, cbEnd)
    })
    it('can be called without both beEach() and cbEnd()', function(done) {
      var enex = new enml2md.EvernoteExport('./test/fixtures/fixture2.enex')
      var testDone = function () {
        enex.count.should.equal(2)
        done()
      }
      setTimeout(testDone, 20)
      enex.each(null, null)
    })
  })
})

describe('Note', function() {
  describe('without resources', function () {
    var note_enml = fs.readFileSync('./test/fixtures/note.enex')
    var note = enml2md.Note.parse(note_enml)
    it('.parse() returns a note object.', function() {
      note.should.be.an.instanceof(enml2md.Note)
    })
    it('#filename(extention) escapes title string.', function() {
      note.filename('.md').should.equal('a single note fixture test  1.md')
      note.filename('.txt').should.equal('a single note fixture test  1.txt')
    })
    it('#title is a title string.', function() {
      note.title.should.equal('a single note fixture/test: 1')
    })
    it('#created is a Date object.', function() {
      var date = new Date(2013, 10, 2, 10, 7-tzMin, 9) // 20131102T100709Z
      note.created.should.be.an.instanceof(Date)
      note.created.should.eql(date)
    })
    it('#updated is a Date object.', function() {
      var date = new Date(2013, 10, 2, 10, 7-tzMin, 13) // 20131102T100713Z
      note.updated.should.be.an.instanceof(Date)
      note.updated.should.eql(date)
    })
    it('#tags is an array of string.', function() {
      note.tags.should.be.an.instanceof(Array)
      note.tags.length.should.equal(2)
      note.tags[0].should.equal('markdown')
      note.tags[1].should.equal('evernote')
    })
    it('#content is a Markdown string.', function() {
      note.content.should.equal('fixture content\n\n')
    })
  })
})<|endoftext|>


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

// Service Worker
"use strict";

// The name of the cache in the client-side cache database.
var CACHE_NAME = 'my-site-cache-v1';

// The files we want to cache
var urlsToCache = [
  '/',
  '/index.js'
];

// Version number: 1
// (Increment this when the script changes, to force a reload.)
importScripts('polyfill/ballista-polyfill.js');

// Set the callback for the install step
self.addEventListener('install', event => {
  // Perform install steps
  console.log('install');

  /*
  event.waitUntil(caches.open(CACHE_NAME).then(cache => {
    console.log('Opened cache');
    return cache.addAll(urlsToCache);
  }));
  */
});

self.addEventListener('activate', event => {
  console.log('activate');
});

self.addEventListener('fetch', event => {
  console.log('fetch: ' + event.request.url);
  /*
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Cache hit - return response
        if (response) {
          console.log('cache hit: ' + event.request.url);
          return response;
        }

        console.log('cache miss: ' + event.request.url);
        return fetch(event.request.url);
      }
    )
  );
  */
});

// Map from client ID to Client.
var clientIdToClientMap = new Map;

// Map from client ID to Action.
var clientIdToActionMap = new Map;

var nextClientId = 0;

// Finds the most recently opened top-level client belonging to this service
// worker. Returns a promise. Rejects the promise if none found.
function findLastTopLevelClient() {
  return new Promise((resolve, reject) => {
    clients.matchAll().then(allClients => {
      for (var i = allClients.length - 1; i >= 0; i--) {
        if (allClients[i].frameType == 'top-level') {
          resolve(allClients[i]);
          return;
        }
      }
      reject(new Error('No available clients; please open a tab.'));
    });
  });
}

// Opens a new window and loads the file up. Returns the Client object
// associated with the window, in a promise.
function openFileInNewWindow(file, clientId) {
  return new Promise((resolve, reject) => {
    // TODO(mgiuca): We'd like to use clients.openWindow() to open a new client
    // here. Unfortunately, this is not allowed here because it is not in direct
    // response to a user gesture. Hopefully, the final API will allow it, but
    // for the polyfill, we just need to take control of an existing client.
    findLastTopLevelClient().then(client => {
      clientIdToClientMap.set(clientId, client);
      var message = {type: 'loadFile', file: file, clientId: clientId};
      client.postMessage(message);
      resolve(client);
    }, err => reject(err));
  });
}

self.addEventListener('message', event => {
  var data = event.data;
  var type = data.type;
  var clientId = data.clientId;

  if (type == 'update') {
    if (!clientIdToActionMap.has(clientId))
      throw new Error('Unknown clientId: ' + clientId);
    var action = clientIdToActionMap.get(clientId);

    var file = data.file;
    navigator.actions.update(action.id, {file: file});
  } else {
    console.log('Got unknown message:', data);
  }
});

navigator.actions.addEventListener('handle', event => {
  if (event.options.verb == 'open') {
    if (event.data.file === undefined) {
      console.log('Did not contain file.');
      return;
    }

    // Associate a unique client ID with a client. This is a hack because the
    // messages we get back from the client do not include a 'source' (in Chrome
    // 46) and therefore there is no way to know which client it is without an
    // out-of-band ID. (http://crbug.com/515741).
    var clientId = nextClientId++;

    clientIdToActionMap.set(clientId, event.action);

    // TODO(mgiuca): This can fail, but the current Ballista API provides no way
    // for a handler to designate failure when handling an 'action' event.
    openFileInNewWindow(event.data.file, clientId);
  } else {
    console.log('Received unknown action:', event.options.verb);
  }
});
<commit_msg>handler: Removed unused clientIdToClientMap.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Service Worker
"use strict";

// The name of the cache in the client-side cache database.
var CACHE_NAME = 'my-site-cache-v1';

// The files we want to cache
var urlsToCache = [
  '/',
  '/index.js'
];

// Version number: 1
// (Increment this when the script changes, to force a reload.)
importScripts('polyfill/ballista-polyfill.js');

// Set the callback for the install step
self.addEventListener('install', event => {
  // Perform install steps
  console.log('install');

  /*
  event.waitUntil(caches.open(CACHE_NAME).then(cache => {
    console.log('Opened cache');
    return cache.addAll(urlsToCache);
  }));
  */
});

self.addEventListener('activate', event => {
  console.log('activate');
});

self.addEventListener('fetch', event => {
  console.log('fetch: ' + event.request.url);
  /*
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Cache hit - return response
        if (response) {
          console.log('cache hit: ' + event.request.url);
          return response;
        }

        console.log('cache miss: ' + event.request.url);
        return fetch(event.request.url);
      }
    )
  );
  */
});

// Map from client ID to Action.
var clientIdToActionMap = new Map;

var nextClientId = 0;

// Finds the most recently opened top-level client belonging to this service
// worker. Returns a promise. Rejects the promise if none found.
function findLastTopLevelClient() {
  return new Promise((resolve, reject) => {
    clients.matchAll().then(allClients => {
      for (var i = allClients.length - 1; i >= 0; i--) {
        if (allClients[i].frameType == 'top-level') {
          resolve(allClients[i]);
          return;
        }
      }
      reject(new Error('No available clients; please open a tab.'));
    });
  });
}

// Opens a new window and loads the file up. Returns the Client object
// associated with the window, in a promise.
function openFileInNewWindow(file, clientId) {
  return new Promise((resolve, reject) => {
    // TODO(mgiuca): We'd like to use clients.openWindow() to open a new client
    // here. Unfortunately, this is not allowed here because it is not in direct
    // response to a user gesture. Hopefully, the final API will allow it, but
    // for the polyfill, we just need to take control of an existing client.
    findLastTopLevelClient().then(client => {
      var message = {type: 'loadFile', file: file, clientId: clientId};
      client.postMessage(message);
      resolve(client);
    }, err => reject(err));
  });
}

self.addEventListener('message', event => {
  var data = event.data;
  var type = data.type;
  var clientId = data.clientId;

  if (type == 'update') {
    if (!clientIdToActionMap.has(clientId))
      throw new Error('Unknown clientId: ' + clientId);
    var action = clientIdToActionMap.get(clientId);

    var file = data.file;
    navigator.actions.update(action.id, {file: file});
  } else {
    console.log('Got unknown message:', data);
  }
});

navigator.actions.addEventListener('handle', event => {
  if (event.options.verb == 'open') {
    if (event.data.file === undefined) {
      console.log('Did not contain file.');
      return;
    }

    // Associate a unique client ID with a client. This is a hack because the
    // messages we get back from the client do not include a 'source' (in Chrome
    // 46) and therefore there is no way to know which client it is without an
    // out-of-band ID. (http://crbug.com/515741).
    var clientId = nextClientId++;

    clientIdToActionMap.set(clientId, event.action);

    // TODO(mgiuca): This can fail, but the current Ballista API provides no way
    // for a handler to designate failure when handling an 'action' event.
    openFileInNewWindow(event.data.file, clientId);
  } else {
    console.log('Received unknown action:', event.options.verb);
  }
});
<|endoftext|>


<commit_before>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-creating-an-instance.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./config.json');

// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});

// AMI is amzn-ami-2011.09.1.x86_64-ebs
var instanceParams = {
   ImageId: 'ami-10fd7020',
   InstanceType: 't1.micro',
   KeyName: 'KEY_PAIR_NAME',
   MinCount: 1,
   MaxCount: 1
};

// Create a promise on an EC2 service object
var instancePromise = new AWS.EC2({apiVersion: '2016-11-15'}).runInstances(instanceParams).promise();

// Handle promise's fulfilled/rejected states
instancePromise.then(
  function(data) {
    console.log(data);
    var instanceId = data.Instances[0].InstanceId;
    console.log("Created instance", instanceId);
    // Add tags to the instance
    tagParams = {Resources: [instanceId], Tags: [
       {
          Key: 'Name',
          Value: 'SDK Sample'
       }
    ]};
    // Create a promise on an EC2 service object
    var tagPromise = new AWS.EC2({apiVersion: '2016-11-15'}).createTags(tagParams).promise();
    // Handle promise's fulfilled/rejected states
    tagPromise.then(
      function(data) {
        console.log("Instance tagged");
      }).catch(
        function(err) {
        console.error(err, err.stack);
      });
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
<commit_msg>Update ec2_createinstances.js<commit_after>// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.

// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide//ec2-example-creating-an-instance.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./config.json');

// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});

// AMI is amzn-ami-2011.09.1.x86_64-ebs
var instanceParams = {
   ImageId: 'AMI_ID',
   InstanceType: 't1.micro',
   KeyName: 'KEY_PAIR_NAME',
   MinCount: 1,
   MaxCount: 1
};

// Create a promise on an EC2 service object
var instancePromise = new AWS.EC2({apiVersion: '2016-11-15'}).runInstances(instanceParams).promise();

// Handle promise's fulfilled/rejected states
instancePromise.then(
  function(data) {
    console.log(data);
    var instanceId = data.Instances[0].InstanceId;
    console.log("Created instance", instanceId);
    // Add tags to the instance
    tagParams = {Resources: [instanceId], Tags: [
       {
          Key: 'Name',
          Value: 'SDK Sample'
       }
    ]};
    // Create a promise on an EC2 service object
    var tagPromise = new AWS.EC2({apiVersion: '2016-11-15'}).createTags(tagParams).promise();
    // Handle promise's fulfilled/rejected states
    tagPromise.then(
      function(data) {
        console.log("Instance tagged");
      }).catch(
        function(err) {
        console.error(err, err.stack);
      });
  }).catch(
    function(err) {
    console.error(err, err.stack);
  });
<|endoftext|>


<commit_before><commit_msg>swap around test order for better insight travis<commit_after><|endoftext|>


<commit_before>/*global describe, it */
'use strict';

var assert = require('assert');
var imagemin = require('../imagemin');
var path = require('path');

describe('Imagemin.optimize()', function () {
    it('should minify a GIF image', function (cb) {
        var src = path.join(__dirname, 'fixtures/test.gif');
        var dest = path.join(__dirname, 'tmp/test.gif');

        imagemin(src, dest, function () {
            assert(dest > src);
            cb();
        });
    });
    it('should minify a JPEG image', function (cb) {
        var src = path.join(__dirname, 'fixtures/test.jpg');
        var dest = path.join(__dirname, 'tmp/test.jpg');

        imagemin(src, dest, function () {
            assert(dest > src);
            cb();
        });
    });
    it('should minify a PNG image', function (cb) {
        var src = path.join(__dirname, 'fixtures/test.png');
        var dest = path.join(__dirname, 'tmp/test.png');

        imagemin(src, dest, function () {
            assert(dest > src);
            cb();
        });
    });
});

<commit_msg>Remove empty line<commit_after>/*global describe, it */
'use strict';

var assert = require('assert');
var imagemin = require('../imagemin');
var path = require('path');

describe('Imagemin.optimize()', function () {
    it('should minify a GIF image', function (cb) {
        var src = path.join(__dirname, 'fixtures/test.gif');
        var dest = path.join(__dirname, 'tmp/test.gif');

        imagemin(src, dest, function () {
            assert(dest > src);
            cb();
        });
    });
    it('should minify a JPEG image', function (cb) {
        var src = path.join(__dirname, 'fixtures/test.jpg');
        var dest = path.join(__dirname, 'tmp/test.jpg');

        imagemin(src, dest, function () {
            assert(dest > src);
            cb();
        });
    });
    it('should minify a PNG image', function (cb) {
        var src = path.join(__dirname, 'fixtures/test.png');
        var dest = path.join(__dirname, 'tmp/test.png');

        imagemin(src, dest, function () {
            assert(dest > src);
            cb();
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

//  ==========================================================================
//  Array Push
//  ==========================================================================

	// Syntax
	arr.shift();

	// Simple
	<commit_msg>array shift<commit_after>'use strict';

//  ==========================================================================
//  Array Push
//  ==========================================================================

	// Syntax
	arr.shift();

	// Simple
	var myList = ["angel", "home", "medical"];

	console.log("mylist before: " + mylist);

	var shifted = myList.shift();

	console.log("myList after: " + myList);
	console.log("element remove:" + shifted);

	// return:
		// myList before: angel, home, medical
		// myList after: home, medical
		// Element remove: angel

	var data = [1, 2, 3, 4];

	console.log(data.shift());
	console.log(data); // return: 2, 3, 4<|endoftext|>


<commit_before>var
  expect = require('chai').expect,
  path = require('path'),
  glob = require('glob'),
  fs = require('fs');

var js2coffee, name, input, output;
var groups = glob.sync(__dirname + '/../specs/*');

before(function () {
  js2coffee = require('../index');
});

describe('specs:', function () {
  groups.forEach(function (dirname) {
    var group = path.basename(dirname).replace(/_/g, ' ');

    describe(group, function () {
      var specs = glob.sync(dirname + '/*');

      specs.forEach(function (dirname) {
        var name = path.basename(dirname).replace(/_/g, ' ');

        if (~group.indexOf('pending')) {
          xit(name.trim(), function () {});
        } else {
          it(name, function () {
            var input = fs.readFileSync(dirname + '/input.js', 'utf-8');
            var output = fs.readFileSync(dirname + '/output.coffee', 'utf-8');
            var result = js2coffee(input);
            expect(result).eql(output);
          });
        }
      });
    });
  });
});
<commit_msg>Update test runner.<commit_after>var
  expect = require('chai').expect,
  path = require('path'),
  glob = require('glob'),
  fs = require('fs');

var js2coffee, name, input, output;
var groups = glob.sync(__dirname + '/../specs/*');

before(function () {
  js2coffee = require('../index');
});

groups.forEach(function (dirname) {
  var group = path.basename(dirname).replace(/_/g, ' ');

  describe(group, function () {
    var specs = glob.sync(dirname + '/*');

    specs.forEach(function (dirname) {
      var name = path.basename(dirname).replace(/_/g, ' ');

      var test = (~group.indexOf('pending')) ? xit : it;
      test(name, function () {
        var input = fs.readFileSync(dirname + '/input.js', 'utf-8');
        var output = fs.readFileSync(dirname + '/output.coffee', 'utf-8');
        var result = js2coffee(input);
        expect(result).eql(output);
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

var midpoint = require('../lib')
  , assert = require('chai').assert
  , richardson = require('richardson-extrapolation')

var ctors = {
  'float32': Float32Array,
  'float64': Float64Array,
  'array': function(){ return arguments[0] }
}

Object.keys(ctors).forEach(function(dtype) {
  var ctor = ctors[dtype]

  describe('midpoint integration (' + dtype + ')', function() {

    describe('integration of one variable', function() {
      var integrator, f, y0, t0, n

      beforeEach(function() {
        f = function(dydt, y) { dydt[0] = -y[0] }
        t0 = 1.5
        y0 = new ctor([1])
        n = 10

        integrator = midpoint( y0, f, t0, 1/n )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
      })

      it('takes multiple timesteps',function() {
        integrator.steps(n)
        assert.closeTo(integrator.y[0], Math.exp(-1), 1e-3 )
      })
    })

    describe('integration of two variables', function() {
      var integrator, f, y0, t0

      beforeEach(function() {
        f = function(dydt, y) {
          dydt[0] = -y[1]
          dydt[1] =  y[0]
        }

        t0 = 1.5
        y0 = new ctor([1,0])

        integrator = midpoint( y0, f, t0, 1 )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
      })

      it('increments the time',function() {
        integrator.step()
        assert.closeTo( integrator.t, t0 + integrator.dt, 1e-4 )
        integrator.step()
        assert.closeTo( integrator.t, t0 + 2*integrator.dt, 1e-4 )
      })

      it("takes a single timestep",function() {
        integrator.step()
        assert.closeTo( integrator.y[0], 0.5, 1e-4 )
        assert.closeTo( integrator.y[1], 1, 1e-4 )
      })

      it("takes multiple timesteps",function() {
        integrator.steps(2)
        assert.closeTo(integrator.y[0], -0.75, 1e-4 )
        assert.closeTo(integrator.y[1], 1, 1e-4)
      })

    })

    describe('convergence', function() {

      it('local truncation error is ~ O(h^3) in time', function() {
        // Integrate an exponential: dy/dt = -y  -->  y = exp(-t)
        var result = richardson(function(h) {
          var f = function(dydt, y) { dydt[0] = -y[0] }
          return midpoint( new ctor([1]), f, 0, h ).step().y[0] - Math.exp(-h)
        }, [0.06,0.02], { f: 0 } )

        assert.closeTo( result.n, 3, 1e-2, 'n ~ 3' )
      })

      it('local truncation error is order O(h^3)', function() {
        var result = richardson(function(h) {

          // Integrate along a sector of a circle:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = midpoint( new ctor([1,0]), f, 0, h ).step()

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-Math.cos(h),2) + Math.pow(i.y[1]-Math.sin(h),2) )

        }, 2*Math.PI/20, { f: 0 } )

        assert.closeTo( result.n, 3, 1e-2, 'n ~ 3' )
      })

      it('total accumulated error is order O(h^2)', function() {
        var result = richardson(function(h) {

          // Integrate around a circle with this step size:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = midpoint( new ctor([1,0]), f, 0, h ).steps( Math.floor(2*Math.PI/h + 0.5) )

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 2*Math.PI/40, { f: 0 } )

        assert.closeTo( result.n, 2, 1e-2, 'n ~ 2' )
      })

      it('total accumulated error is order O(h^2) in all variables', function() {

        var result = richardson(function(h) {
          // Integrate around a circle at an accelerating rate
          var f = function(dydt, y, t) {
            var s =  Math.sin(t * Math.PI) * Math.PI / 2
            dydt[0] = -y[1]* 2 * Math.PI * s
            dydt[1] =  y[0]* 2 * Math.PI * s
          }
          var i = midpoint( new ctor([1,0]), f, 0, h ).steps( Math.floor(1/h+0.5))

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 0.01, { f: 0 } )

        assert.closeTo( result.n, 2, 1e-2, 'n ~ 2' )
      })

    })

  })

})
<commit_msg>Test label typo fix<commit_after>'use strict'

var midpoint = require('../lib')
  , assert = require('chai').assert
  , richardson = require('richardson-extrapolation')

var ctors = {
  'float32': Float32Array,
  'float64': Float64Array,
  'array': function(){ return arguments[0] }
}

Object.keys(ctors).forEach(function(dtype) {
  var ctor = ctors[dtype]

  describe('midpoint integration (' + dtype + ')', function() {

    describe('integration of one variable', function() {
      var integrator, f, y0, t0, n

      beforeEach(function() {
        f = function(dydt, y) { dydt[0] = -y[0] }
        t0 = 1.5
        y0 = new ctor([1])
        n = 10

        integrator = midpoint( y0, f, t0, 1/n )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
      })

      it('takes multiple timesteps',function() {
        integrator.steps(n)
        assert.closeTo(integrator.y[0], Math.exp(-1), 1e-3 )
      })
    })

    describe('integration of two variables', function() {
      var integrator, f, y0, t0

      beforeEach(function() {
        f = function(dydt, y) {
          dydt[0] = -y[1]
          dydt[1] =  y[0]
        }

        t0 = 1.5
        y0 = new ctor([1,0])

        integrator = midpoint( y0, f, t0, 1 )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
      })

      it('increments the time',function() {
        integrator.step()
        assert.closeTo( integrator.t, t0 + integrator.dt, 1e-4 )
        integrator.step()
        assert.closeTo( integrator.t, t0 + 2*integrator.dt, 1e-4 )
      })

      it("takes a single timestep",function() {
        integrator.step()
        assert.closeTo( integrator.y[0], 0.5, 1e-4 )
        assert.closeTo( integrator.y[1], 1, 1e-4 )
      })

      it("takes multiple timesteps",function() {
        integrator.steps(2)
        assert.closeTo(integrator.y[0], -0.75, 1e-4 )
        assert.closeTo(integrator.y[1], 1, 1e-4)
      })

    })

    describe('convergence', function() {

      it('local truncation error is ~ O(h^3) in time', function() {
        // Integrate an exponential: dy/dt = -y  -->  y = exp(-t)
        var result = richardson(function(h) {
          var f = function(dydt, y) { dydt[0] = -y[0] }
          return midpoint( new ctor([1]), f, 0, h ).step().y[0] - Math.exp(-h)
        }, [0.06,0.02], { f: 0 } )

        assert.closeTo( result.n, 3, 1e-2, 'n ~ 3' )
      })

      it('local truncation error is order O(h^3)', function() {
        var result = richardson(function(h) {

          // Integrate along a sector of a circle:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = midpoint( new ctor([1,0]), f, 0, h ).step()

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-Math.cos(h),2) + Math.pow(i.y[1]-Math.sin(h),2) )

        }, 2*Math.PI/20, { f: 0 } )

        assert.closeTo( result.n, 3, 1e-2, 'n ~ 3' )
      })

      it('total accumulated error is order O(h^2)', function() {
        var result = richardson(function(h) {

          // Integrate around a circle with this step size:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = midpoint( new ctor([1,0]), f, 0, h ).steps( Math.floor(2*Math.PI/h + 0.5) )

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 2*Math.PI/40, { f: 0 } )

        assert.closeTo( result.n, 2, 1e-2, 'n ~ 2' )
      })

      it('total accumulated error is order O(h^2) in all variables', function() {

        var result = richardson(function(h) {
          // Integrate around a circle at an accelerating rate
          var f = function(dydt, y, t) {
            var s =  Math.sin(t * Math.PI) * Math.PI / 2
            dydt[0] = -y[1]* 2 * Math.PI * s
            dydt[1] =  y[0]* 2 * Math.PI * s
          }
          var i = midpoint( new ctor([1,0]), f, 0, h ).steps( Math.floor(1/h+0.5))

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 0.01, { f: 0 } )

        assert.closeTo( result.n, 2, 1e-2, 'n ~ 2' )
      })

    })

  })

})
<|endoftext|>


<commit_before>var _ = require('../utils')._;

module.exports = {
    pkcs1: require('./pkcs1'),
    pkcs1: require('./pkcs8'),
    components: require('./components'),

    detectAndImport: function (key, data, format) {
        if (format === undefined) {
            for (var scheme in module.exports) {
                if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
                    return true;
                }
            }
        } else if (format) {
            var fmt = formatParse(format);

            if (module.exports[fmt.scheme]) {
                if (fmt.keyType === 'private') {
                    module.exports[fmt.scheme].privateImport(key, data, fmt.keyOpt);
                } else {
                    module.exports[fmt.scheme].publicImport(key, data, fmt.keyOpt);
                }
            } else {
                throw Error('Unsupported key format');
            }
        }

        return false;
    },
};
<commit_msg>formats typo pkcs1 → pkcs8<commit_after>var _ = require('../utils')._;

module.exports = {
    pkcs1: require('./pkcs1'),
    pkcs8: require('./pkcs8'),
    components: require('./components'),

    detectAndImport: function (key, data, format) {
        if (format === undefined) {
            for (var scheme in module.exports) {
                if (typeof module.exports[scheme].autoImport === 'function' && module.exports[scheme].autoImport(key, data)) {
                    return true;
                }
            }
        } else if (format) {
            var fmt = formatParse(format);

            if (module.exports[fmt.scheme]) {
                if (fmt.keyType === 'private') {
                    module.exports[fmt.scheme].privateImport(key, data, fmt.keyOpt);
                } else {
                    module.exports[fmt.scheme].publicImport(key, data, fmt.keyOpt);
                }
            } else {
                throw Error('Unsupported key format');
            }
        }

        return false;
    },
};
<|endoftext|>