<commit_before>'use strict'

const { readFileSync } = require('fs')
const { resolve } = require('path')
const { URL } = require('url')
const { Server } = require('@hapi/hapi')
const hapiPluginWebsocket = require('hapi-plugin-websocket')
const authFunctionNameExtractor = require('./authFunctionNameExtractor.js')
const debugLog = require('./debugLog.js')
const getFunctionOptions = require('./getFunctionOptions.js')
const HandlerRunner = require('./handler-runner/index.js')
const LambdaContext = require('./LambdaContext.js')
const serverlessLog = require('./serverlessLog.js')
const {
  createUniqueId,
  parseQueryStringParameters,
} = require('./utils/index.js')
const {
  createConnectEvent,
  createDisconnectEvent,
  createEvent,
} = require('./websocketHelpers.js')

const { stringify } = JSON

// dummy placeholder url for the WHATWG URL constructor
// https://github.com/nodejs/node/issues/12682
// TODO move to common constants file
const BASE_URL_PLACEHOLDER = 'http://example'

module.exports = class ApiGatewayWebSocket {
  constructor(service, options, config) {
    this._actions = {}
    this._clients = new Map()
    this._config = config
    this._options = options
    this._provider = service.provider
    this._server = null
    this._service = service
    this._websocketsApiRouteSelectionExpression =
      this._provider.websocketsApiRouteSelectionExpression ||
      '$request.body.action'

    this._init()
  }

  _printBlankLine() {
    if (process.env.NODE_ENV !== 'test') {
      console.log()
    }
  }

  _init() {
    // start COPY PASTE FROM HTTP SERVER CODE
    const {
      enforceSecureCookies,
      host,
      httpsProtocol,
      preserveTrailingSlash,
      websocketPort,
    } = this._options

    const serverOptions = {
      host,
      port: websocketPort,
      router: {
        // removes trailing slashes on incoming paths
        stripTrailingSlash: !preserveTrailingSlash,
      },
      state: enforceSecureCookies
        ? {
            isHttpOnly: true,
            isSameSite: false,
            isSecure: true,
          }
        : {
            isHttpOnly: false,
            isSameSite: false,
            isSecure: false,
          },
    }

    // HTTPS support
    if (typeof httpsProtocol === 'string' && httpsProtocol.length > 0) {
      serverOptions.tls = {
        cert: readFileSync(resolve(httpsProtocol, 'cert.pem'), 'ascii'),
        key: readFileSync(resolve(httpsProtocol, 'key.pem'), 'ascii'),
      }
    }

    // Hapijs server
    this._server = new Server(serverOptions)

    // Enable CORS preflight response
    this._server.ext('onPreResponse', (request, h) => {
      if (request.headers.origin) {
        const response = request.response.isBoom
          ? request.response.output
          : request.response

        response.headers['access-control-allow-origin'] = request.headers.origin
        response.headers['access-control-allow-credentials'] = 'true'

        if (request.method === 'options') {
          response.statusCode = 200
          response.headers['access-control-expose-headers'] =
            'content-type, content-length, etag'
          response.headers['access-control-max-age'] = 60 * 10

          if (request.headers['access-control-request-headers']) {
            response.headers['access-control-allow-headers'] =
              request.headers['access-control-request-headers']
          }

          if (request.headers['access-control-request-method']) {
            response.headers['access-control-allow-methods'] =
              request.headers['access-control-request-method']
          }
        }
      }

      return h.continue
    })
    // end COPY PASTE FROM HTTP SERVER CODE
  }

  async createServer() {
    const doAction = (ws, connectionId, name, event, doDefaultAction) => {
      const sendError = (err) => {
        if (ws.readyState === /* OPEN */ 1) {
          ws.send(
            stringify({
              connectionId,
              message: 'Internal server error',
              requestId: '1234567890',
            }),
          )
        }

        // mimic AWS behaviour (close connection) when the $connect action handler throws
        if (name === '$connect') {
          ws.close()
        }

        debugLog(`Error in handler of action ${action}`, err)
      }

      let action = this._actions[name]

      if (!action && doDefaultAction) action = this._actions.$default
      if (!action) return

      function callback(err) {
        if (!err) return
        sendError(err)
      }

      // TEMP
      const func = {
        ...action.functionObj,
        name,
      }

      const context = new LambdaContext({
        callback,
        functionName: func.name,
        memorySize: func.memorySize || this._provider.memorySize,
        timeout: func.timeout || this._provider.timeout,
      })

      let p = null

      try {
        p = action.handlerRunner.run(event, context, callback)
      } catch (err) {
        sendError(err)
      }

      if (p) {
        p.catch((err) => {
          sendError(err)
        })
      }
    }

    this._server.route({
      method: 'POST',
      path: '/',
      options: {
        payload: {
          allow: 'application/json',
          output: 'data',
          parse: true,
        },
        plugins: {
          websocket: {
            initially: false,
            only: true,
            connect: ({ ws, req }) => {
              const { searchParams } = new URL(req.url, BASE_URL_PLACEHOLDER)
              const queryStringParameters = parseQueryStringParameters(
                searchParams,
              )
              const connection = {
                connectionId: createUniqueId(),
                connectionTime: Date.now(),
              }

              debugLog(`connect:${connection.connectionId}`)

              this._clients.set(ws, connection)

              let event = createConnectEvent(
                '$connect',
                'CONNECT',
                connection,
                this._options,
              )

              if (Object.keys(queryStringParameters || {}).length > 0) {
                event = { queryStringParameters, ...event }
              }

              doAction(ws, connection.connectionId, '$connect', event, false)
            },
            disconnect: ({ ws }) => {
              const connection = this._clients.get(ws)

              debugLog(`disconnect:${connection.connectionId}`)

              this._clients.delete(ws)

              const event = createDisconnectEvent(
                '$disconnect',
                'DISCONNECT',
                connection,
              )

              doAction(ws, connection.connectionId, '$disconnect', event, false)
            },
          },
        },
      },
      handler: (request, h) => {
        const { initially, ws } = request.websocket()

        if (!request.payload || initially) {
          return h.response().code(204)
        }

        const connection = this._clients.get(ws)
        let actionName = null

        if (
          this._websocketsApiRouteSelectionExpression.startsWith(
            '$request.body.',
          )
        ) {
          actionName = request.payload

          if (typeof actionName === 'object') {
            this._websocketsApiRouteSelectionExpression
              .replace('$request.body.', '')
              .split('.')
              .forEach((key) => {
                if (actionName) {
                  actionName = actionName[key]
                }
              })
          } else actionName = null
        }

        if (typeof actionName !== 'string') {
          actionName = null
        }

        const action = actionName || '$default'

        debugLog(`action:${action} on connection=${connection.connectionId}`)

        const event = createEvent(
          action,
          'MESSAGE',
          connection,
          request.payload,
        )

        doAction(ws, connection.connectionId, action, event, true)

        return h.response().code(204)
      },
    })

    this._server.route({
      handler: (request, h) => h.response().code(426),
      method: 'GET',
      path: '/{path*}',
    })

    this._server.route({
      method: 'POST',
      path: '/@connections/{connectionId}',
      options: {
        payload: {
          parse: false,
        },
      },
      handler: (request, h) => {
        debugLog(`got POST to ${request.url}`)

        const getByConnectionId = (map, searchValue) => {
          for (const [key, connection] of map.entries()) {
            if (connection.connectionId === searchValue) return key
          }

          return undefined
        }

        const ws = getByConnectionId(this._clients, request.params.connectionId)

        if (!ws) return h.response().code(410)
        if (!request.payload) return ''

        ws.send(request.payload.toString())

        debugLog(`sent data to connection:${request.params.connectionId}`)

        return ''
      },
    })

    this._server.route({
      options: {
        payload: {
          parse: false,
        },
      },
      method: 'DELETE',
      path: '/@connections/{connectionId}',
      handler: (request, h) => {
        debugLog(`got DELETE to ${request.url}`)

        const getByConnectionId = (map, searchValue) => {
          for (const [key, connection] of map.entries()) {
            if (connection.connectionId === searchValue) return key
          }

          return undefined
        }

        const ws = getByConnectionId(this._clients, request.params.connectionId)

        if (!ws) return h.response().code(410)

        ws.close()

        debugLog(`closed connection:${request.params.connectionId}`)

        return ''
      },
    })
  }

  createWsAction(functionName, functionObj, websocket) {
    const funOptions = getFunctionOptions(
      functionName,
      functionObj,
      this._config.servicePath,
      this._provider.runtime,
    )

    debugLog(`funOptions ${stringify(funOptions, null, 2)} `)
    this._printBlankLine()
    debugLog(functionName, 'runtime', this._provider.runtime)

    // TODO Remove (already in LambdaFunction)
    process.env = {
      _HANDLER: functionObj.handler,
      AWS_REGION: this._provider.region,
      ...this._provider.environment,
      ...this._service.functions[functionName].environment,
    }

    // TODO FIXME REMOVE use LambdaFunction class
    const handlerRunner = new HandlerRunner(funOptions, this._provider.stage)

    const actionName = websocket.route
    const action = {
      functionObj,
      functionName,
      funOptions,
      handlerRunner,
      servicePath: this._config.servicePath,
    }

    this._actions[actionName] = action
    serverlessLog(`Action '${websocket.route}'`)
  }

  _extractAuthFunctionName(endpoint) {
    const result = authFunctionNameExtractor(endpoint, serverlessLog)

    return result.unsupportedAuth ? null : result.authorizerName
  }

  async registerPlugins() {
    try {
      await this._server.register(hapiPluginWebsocket)
    } catch (e) {
      serverlessLog(e)
    }
  }

  async start() {
    const { host, httpsProtocol, websocketPort } = this._options

    try {
      await this._server.start()
    } catch (error) {
      console.error(
        `Unexpected error while starting serverless-offline websocket server on port ${websocketPort}:`,
        error,
      )
      process.exit(1)
    }

    this._printBlankLine()
    serverlessLog(
      `Offline [websocket] listening on ws${
        httpsProtocol ? 's' : ''
      }://${host}:${websocketPort}`,
    )
  }

  // stops the hapi server
  stop(timeout) {
    return this._server.stop({
      timeout,
    })
  }
}
<commit_msg>Remove unused props<commit_after>'use strict'

const { readFileSync } = require('fs')
const { resolve } = require('path')
const { URL } = require('url')
const { Server } = require('@hapi/hapi')
const hapiPluginWebsocket = require('hapi-plugin-websocket')
const authFunctionNameExtractor = require('./authFunctionNameExtractor.js')
const debugLog = require('./debugLog.js')
const getFunctionOptions = require('./getFunctionOptions.js')
const HandlerRunner = require('./handler-runner/index.js')
const LambdaContext = require('./LambdaContext.js')
const serverlessLog = require('./serverlessLog.js')
const {
  createUniqueId,
  parseQueryStringParameters,
} = require('./utils/index.js')
const {
  createConnectEvent,
  createDisconnectEvent,
  createEvent,
} = require('./websocketHelpers.js')

const { stringify } = JSON

// dummy placeholder url for the WHATWG URL constructor
// https://github.com/nodejs/node/issues/12682
// TODO move to common constants file
const BASE_URL_PLACEHOLDER = 'http://example'

module.exports = class ApiGatewayWebSocket {
  constructor(service, options, config) {
    this._actions = {}
    this._clients = new Map()
    this._config = config
    this._options = options
    this._provider = service.provider
    this._server = null
    this._service = service
    this._websocketsApiRouteSelectionExpression =
      this._provider.websocketsApiRouteSelectionExpression ||
      '$request.body.action'

    this._init()
  }

  _printBlankLine() {
    if (process.env.NODE_ENV !== 'test') {
      console.log()
    }
  }

  _init() {
    // start COPY PASTE FROM HTTP SERVER CODE
    const {
      enforceSecureCookies,
      host,
      httpsProtocol,
      preserveTrailingSlash,
      websocketPort,
    } = this._options

    const serverOptions = {
      host,
      port: websocketPort,
      router: {
        // removes trailing slashes on incoming paths
        stripTrailingSlash: !preserveTrailingSlash,
      },
      state: enforceSecureCookies
        ? {
            isHttpOnly: true,
            isSameSite: false,
            isSecure: true,
          }
        : {
            isHttpOnly: false,
            isSameSite: false,
            isSecure: false,
          },
    }

    // HTTPS support
    if (typeof httpsProtocol === 'string' && httpsProtocol.length > 0) {
      serverOptions.tls = {
        cert: readFileSync(resolve(httpsProtocol, 'cert.pem'), 'ascii'),
        key: readFileSync(resolve(httpsProtocol, 'key.pem'), 'ascii'),
      }
    }

    // Hapijs server
    this._server = new Server(serverOptions)

    // Enable CORS preflight response
    this._server.ext('onPreResponse', (request, h) => {
      if (request.headers.origin) {
        const response = request.response.isBoom
          ? request.response.output
          : request.response

        response.headers['access-control-allow-origin'] = request.headers.origin
        response.headers['access-control-allow-credentials'] = 'true'

        if (request.method === 'options') {
          response.statusCode = 200
          response.headers['access-control-expose-headers'] =
            'content-type, content-length, etag'
          response.headers['access-control-max-age'] = 60 * 10

          if (request.headers['access-control-request-headers']) {
            response.headers['access-control-allow-headers'] =
              request.headers['access-control-request-headers']
          }

          if (request.headers['access-control-request-method']) {
            response.headers['access-control-allow-methods'] =
              request.headers['access-control-request-method']
          }
        }
      }

      return h.continue
    })
    // end COPY PASTE FROM HTTP SERVER CODE
  }

  async createServer() {
    const doAction = (ws, connectionId, name, event, doDefaultAction) => {
      const sendError = (err) => {
        if (ws.readyState === /* OPEN */ 1) {
          ws.send(
            stringify({
              connectionId,
              message: 'Internal server error',
              requestId: '1234567890',
            }),
          )
        }

        // mimic AWS behaviour (close connection) when the $connect action handler throws
        if (name === '$connect') {
          ws.close()
        }

        debugLog(`Error in handler of action ${action}`, err)
      }

      let action = this._actions[name]

      if (!action && doDefaultAction) action = this._actions.$default
      if (!action) return

      function callback(err) {
        if (!err) return
        sendError(err)
      }

      // TEMP
      const func = {
        ...action.functionObj,
        name,
      }

      const context = new LambdaContext({
        callback,
        functionName: func.name,
        memorySize: func.memorySize || this._provider.memorySize,
        timeout: func.timeout || this._provider.timeout,
      })

      let p = null

      try {
        p = action.handlerRunner.run(event, context, callback)
      } catch (err) {
        sendError(err)
      }

      if (p) {
        p.catch((err) => {
          sendError(err)
        })
      }
    }

    this._server.route({
      method: 'POST',
      path: '/',
      options: {
        payload: {
          allow: 'application/json',
          output: 'data',
          parse: true,
        },
        plugins: {
          websocket: {
            initially: false,
            only: true,
            connect: ({ ws, req }) => {
              const { searchParams } = new URL(req.url, BASE_URL_PLACEHOLDER)
              const queryStringParameters = parseQueryStringParameters(
                searchParams,
              )
              const connection = {
                connectionId: createUniqueId(),
                connectionTime: Date.now(),
              }

              debugLog(`connect:${connection.connectionId}`)

              this._clients.set(ws, connection)

              let event = createConnectEvent(
                '$connect',
                'CONNECT',
                connection,
                this._options,
              )

              if (Object.keys(queryStringParameters || {}).length > 0) {
                event = { queryStringParameters, ...event }
              }

              doAction(ws, connection.connectionId, '$connect', event, false)
            },
            disconnect: ({ ws }) => {
              const connection = this._clients.get(ws)

              debugLog(`disconnect:${connection.connectionId}`)

              this._clients.delete(ws)

              const event = createDisconnectEvent(
                '$disconnect',
                'DISCONNECT',
                connection,
              )

              doAction(ws, connection.connectionId, '$disconnect', event, false)
            },
          },
        },
      },
      handler: (request, h) => {
        const { initially, ws } = request.websocket()

        if (!request.payload || initially) {
          return h.response().code(204)
        }

        const connection = this._clients.get(ws)
        let actionName = null

        if (
          this._websocketsApiRouteSelectionExpression.startsWith(
            '$request.body.',
          )
        ) {
          actionName = request.payload

          if (typeof actionName === 'object') {
            this._websocketsApiRouteSelectionExpression
              .replace('$request.body.', '')
              .split('.')
              .forEach((key) => {
                if (actionName) {
                  actionName = actionName[key]
                }
              })
          } else actionName = null
        }

        if (typeof actionName !== 'string') {
          actionName = null
        }

        const action = actionName || '$default'

        debugLog(`action:${action} on connection=${connection.connectionId}`)

        const event = createEvent(
          action,
          'MESSAGE',
          connection,
          request.payload,
        )

        doAction(ws, connection.connectionId, action, event, true)

        return h.response().code(204)
      },
    })

    this._server.route({
      handler: (request, h) => h.response().code(426),
      method: 'GET',
      path: '/{path*}',
    })

    this._server.route({
      method: 'POST',
      path: '/@connections/{connectionId}',
      options: {
        payload: {
          parse: false,
        },
      },
      handler: (request, h) => {
        debugLog(`got POST to ${request.url}`)

        const getByConnectionId = (map, searchValue) => {
          for (const [key, connection] of map.entries()) {
            if (connection.connectionId === searchValue) return key
          }

          return undefined
        }

        const ws = getByConnectionId(this._clients, request.params.connectionId)

        if (!ws) return h.response().code(410)
        if (!request.payload) return ''

        ws.send(request.payload.toString())

        debugLog(`sent data to connection:${request.params.connectionId}`)

        return ''
      },
    })

    this._server.route({
      options: {
        payload: {
          parse: false,
        },
      },
      method: 'DELETE',
      path: '/@connections/{connectionId}',
      handler: (request, h) => {
        debugLog(`got DELETE to ${request.url}`)

        const getByConnectionId = (map, searchValue) => {
          for (const [key, connection] of map.entries()) {
            if (connection.connectionId === searchValue) return key
          }

          return undefined
        }

        const ws = getByConnectionId(this._clients, request.params.connectionId)

        if (!ws) return h.response().code(410)

        ws.close()

        debugLog(`closed connection:${request.params.connectionId}`)

        return ''
      },
    })
  }

  createWsAction(functionName, functionObj, websocket) {
    const funOptions = getFunctionOptions(
      functionName,
      functionObj,
      this._config.servicePath,
      this._provider.runtime,
    )

    debugLog(`funOptions ${stringify(funOptions, null, 2)} `)
    this._printBlankLine()
    debugLog(functionName, 'runtime', this._provider.runtime)

    // TODO Remove (already in LambdaFunction)
    process.env = {
      _HANDLER: functionObj.handler,
      AWS_REGION: this._provider.region,
      ...this._provider.environment,
      ...this._service.functions[functionName].environment,
    }

    // TODO FIXME REMOVE use LambdaFunction class
    const handlerRunner = new HandlerRunner(funOptions, this._provider.stage)

    const actionName = websocket.route
    const action = {
      functionObj,
      handlerRunner,
      servicePath: this._config.servicePath,
    }

    this._actions[actionName] = action
    serverlessLog(`Action '${websocket.route}'`)
  }

  _extractAuthFunctionName(endpoint) {
    const result = authFunctionNameExtractor(endpoint, serverlessLog)

    return result.unsupportedAuth ? null : result.authorizerName
  }

  async registerPlugins() {
    try {
      await this._server.register(hapiPluginWebsocket)
    } catch (e) {
      serverlessLog(e)
    }
  }

  async start() {
    const { host, httpsProtocol, websocketPort } = this._options

    try {
      await this._server.start()
    } catch (error) {
      console.error(
        `Unexpected error while starting serverless-offline websocket server on port ${websocketPort}:`,
        error,
      )
      process.exit(1)
    }

    this._printBlankLine()
    serverlessLog(
      `Offline [websocket] listening on ws${
        httpsProtocol ? 's' : ''
      }://${host}:${websocketPort}`,
    )
  }

  // stops the hapi server
  stop(timeout) {
    return this._server.stop({
      timeout,
    })
  }
}
<|endoftext|>


<commit_before>$(function() {
  if ($('.greeting-category').size() === 0) {
    return;
  }

  var time = Math.floor(+new Date() / 600) * 600;

  var update = function() {
    $('.greeting-category').each(function() {
      var category = $(this);
      if (category.hasClass('greeting-category-deleted')) {
        return true; // continue
      }
      category.find('.greeting-group').each(function() {
        var element = $(this);
        var start = new Date(element.data('start-at'));
        var end = new Date(element.data('end-at'));
        if (time < start && !category.hasClass('greeting-category-before-the-start')) {
          category.find('.greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-info');
        }
        else if (time >= start && time < end && !category.hasClass('greeting-category-in-session')) {
          category.find('.greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-primary');
        }
        else if (time > end && !category.hasClass('greeting-category-after-th-end')) {
          category.find('.greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-success');
        }
      });
    });

    $('.greeting-category').each(function() {
      var element = $(this);
      var greetings = element.find('.greetings');
      if (greetings.children().size() > 0) {
        element.removeClass('greeting-category-empty');
      }
      else {
        element.addClass('greeting-category-empty');
      }
    });
  };

  update();

  setInterval(function() {
    var next = +new Date();
    if (next - time >= 60000) {
      time = Math.floor(next / 60000) * 60000;
      update();
    }
  }, 1000);
});
<commit_msg>動作タイミングを修正<commit_after>$(function() {
  if ($('.greeting-category').size() === 0) {
    return;
  }

  var time = Math.floor(+new Date() / 60000) * 60000;

  var update = function() {
    $('.greeting-category').each(function() {
      var category = $(this);
      if (category.hasClass('greeting-category-deleted')) {
        return true; // continue
      }
      category.find('.greeting-group').each(function() {
        var element = $(this);
        var start = new Date(element.data('start-at'));
        var end = new Date(element.data('end-at'));
        if (time < start && !category.hasClass('greeting-category-before-the-start')) {
          category.find('.greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-info');
        }
        else if (time >= start && time < end && !category.hasClass('greeting-category-in-session')) {
          category.find('.greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-primary');
        }
        else if (time > end && !category.hasClass('greeting-category-after-th-end')) {
          category.find('.greetings').append(this);
          element.find('.panel').attr('class', 'panel panel-success');
        }
      });
    });

    $('.greeting-category').each(function() {
      var element = $(this);
      var greetings = element.find('.greetings');
      if (greetings.children().size() > 0) {
        element.removeClass('greeting-category-empty');
      }
      else {
        element.addClass('greeting-category-empty');
      }
    });
  };

  update();

  setInterval(function() {
    var next = +new Date();
    if (next - time >= 60000) {
      time = Math.floor(next / 60000) * 60000;
      update();
    }
  }, 1000);
});
<|endoftext|>


<commit_before>/**
 * Created on : 2014.08.24., 5:26:26
 * Author     : Lajos Molnar <lajax.m@gmail.com>
 * since 1.0
 */

var translate = (function () {

    /**
     * @type string
     */
    var _originalMessage;

    /**
     * @param {object} $this
     */
    function _translateLanguage($this) {
        var data = {
            id: $this.data('id'),
            language_id: $('#language_id').val(),
            translation: $.trim($this.closest('tr').find('.translation').val())
        };

        helpers.post($('#language_id').data('url'), data);
    }

    /**
     * @param {object} $this
     */
    function _copySourceToTranslation($this) {
        var $translation = $this.closest('tr').find('.translation'),
            isEmptyTranslation = $.trim($translation.val()).length === 0,
            sourceMessage = $.trim($this.val());

        if (!isEmptyTranslation) {
            return;
        }

        if (typeof tm_googleApiKey === 'undefined') {
            // default bahavior - copy original text to translation field
            $translation.val(sourceMessage);
            _translateLanguage($this);
        } else {
            // google translation is enabled - translate and copy translation
            helpers.googleTranslate($.trim($this.val()), $('#language_id').val(), function(result) {
                if (result.success) {
                    $translation.val(result.text);
                } else {
                    $translation.val(sourceMessage);
                    helpers.showMessages(lajax.t('Google translation failed, source text was used as translation!'));
                }

                _translateLanguage($this);
            });
        }
    }

    return {
        init: function () {
            $('#translates').on('click', '.source', function () {
                _copySourceToTranslation($(this));
            });
            $('#translates').on('click', 'button', function () {
                _translateLanguage($(this));
            });
            $('#translates').on('focus', '.translation', function () {
                _originalMessage = $.trim($(this).val());
            });
            $('#translates').on('blur', '.translation', function () {
                if ($.trim($(this).val()) !== _originalMessage) {
                    _translateLanguage($(this).closest('tr').find('button'));
                }
            });
            $('#translates').on('change', "#search-form select", function(){
                $(this).parents("form").submit();
            });
        }
    };
})();

$(document).ready(function () {
    translate.init();
});
<commit_msg>Fix empty ID posted on message copying<commit_after>/**
 * Created on : 2014.08.24., 5:26:26
 * Author     : Lajos Molnar <lajax.m@gmail.com>
 * since 1.0
 */

var translate = (function () {

    /**
     * @type string
     */
    var _originalMessage;

    /**
     * @param {object} $this
     */
    function _translateLanguage($this) {
        var $translation = $this.closest('tr').find('.translation');

        var data = {
            id: $translation.data('id'),
            language_id: $('#language_id').val(),
            translation: $.trim($translation.val())
        };

        helpers.post($('#language_id').data('url'), data);
    }

    /**
     * @param {object} $this
     */
    function _copySourceToTranslation($this) {
        var $translation = $this.closest('tr').find('.translation'),
            isEmptyTranslation = $.trim($translation.val()).length === 0,
            sourceMessage = $.trim($this.val());

        if (!isEmptyTranslation) {
            return;
        }

        if (typeof tm_googleApiKey === 'undefined') {
            // default bahavior - copy original text to translation field
            $translation.val(sourceMessage);
            _translateLanguage($this);
        } else {
            // google translation is enabled - translate and copy translation
            helpers.googleTranslate($.trim($this.val()), $('#language_id').val(), function(result) {
                if (result.success) {
                    $translation.val(result.text);
                } else {
                    $translation.val(sourceMessage);
                    helpers.showMessages(lajax.t('Google translation failed, source text was used as translation!'));
                }

                _translateLanguage($this);
            });
        }
    }

    return {
        init: function () {
            $('#translates').on('click', '.source', function () {
                _copySourceToTranslation($(this));
            });
            $('#translates').on('click', 'button', function () {
                _translateLanguage($(this));
            });
            $('#translates').on('focus', '.translation', function () {
                _originalMessage = $.trim($(this).val());
            });
            $('#translates').on('blur', '.translation', function () {
                if ($.trim($(this).val()) !== _originalMessage) {
                    _translateLanguage($(this).closest('tr').find('button'));
                }
            });
            $('#translates').on('change', "#search-form select", function(){
                $(this).parents("form").submit();
            });
        }
    };
})();

$(document).ready(function () {
    translate.init();
});
<|endoftext|>


<commit_before>/* global google */

import config from '../config/config';

/**
 * Get the marker icon
 * @param {String} category The category of the location
 * @return {GoogleIconObject} icon The marker icon
 */
/* eslint-disable complexity */
export default function(category) {

  if (category === 'user') {
    return config.userIcon;
  }

  return create(category);
}

/**
 * Create the google icon object
 * @param {String} category The icon category
 * @return {GoogleIconObject} icon The marker icon
 */
function create(category) {
  let icon = document.querySelector(`#icon-${category}`);
  icon = icon || document.querySelector('#icon-all');

  const path = icon.querySelector('path').getAttribute('d');

  return {
    path: path,
    fillColor: 'white',
    fillOpacity: 1,
    scale: 1,
    strokeWeight: 0
  };
}
<commit_msg>style(get-icon): Style the get icon file.<commit_after>import config from '../config/config';

/**
 * Get the marker icon
 * @param {String} category The category of the location
 * @return {GoogleIconObject} icon The marker icon
 */

export default function(category) {
  if (category === 'user') {
    return config.userIcon;
  }

  return create(category);
}

/**
 * Create the google icon object
 * @param {String} category The icon category
 * @return {GoogleIconObject} icon The marker icon
 */
function create(category) {
  let icon = document.querySelector(`#icon-${category}`);
  icon = icon || document.querySelector('#icon-all');

  const path = icon.querySelector('path').getAttribute('d');

  return {
    path: path,
    fillColor: 'white',
    fillOpacity: 1,
    scale: 1,
    strokeWeight: 0
  };
}
<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
	ctx = canvas.getContext("2d"),
	width = 512,
	height = 480;
var paused = false;
var isGameOver = false;

//canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
	bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
	heroReady = true;
};
heroImage.src = "image/png/spaceKitty.png";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
	kittyReady = true;
};
kittyImage.src = "image/png/catDeathStar.png";

// Game objects
var hero = {
	speed: 256,
	x: 0,
	y: 0
};

var kitty = {
	x: 0,
	y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
	e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

var reset = function () {
	hero.x = (canvas.width / 2) - 16;
	hero.y = (canvas.height / 2) - 16;

	kitty.x = 32 + (Math.random() * (canvas.width - 64));
	kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
	if (38 in keysDown) {
		hero.y -= hero.speed * modifier;
	}
	if (40 in keysDown) {
		hero.y += hero.speed * modifier;
	}
	if (37 in keysDown) {
		hero.x -= hero.speed * modifier;
	}
	if (39 in keysDown) {
		hero.x += hero.speed * modifier;
	}

  // Stop from going off the page
	if (hero.x >= canvas.width - 32) {
		hero.x = canvas.width - 32;
	} else if (hero.x <= 0) {
		hero.x = 0;
	}

	if (hero.y >= canvas.height - 32) {
		hero.y = canvas.height - 32;
	} else if (hero.y <= 0) {
		hero.y = 0;
	}

  // Collision
	if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
		kittyCaught++;
		thenSwitch = nowSwitch;
		reset();
	}

	countDown = nowSwitch - thenSwitch;

	if (countDown >= 1000) {
		lives--;
		if (lives ==  0) {
			gameOver();
		}
		thenSwitch = nowSwitch;
		reset();
	}
};

// Render
var render = function () {
	if (bgReady) {
		ctx.drawImage(bgImage, 0, 0);
	}

	if (heroReady) {
		ctx.drawImage(heroImage, hero.x, hero.y);
	}

	if (kittyReady) {
		ctx.drawImage(kittyImage, kitty.x, kitty.y);
	}

	ctx.fillStyle = "#EEE";
	ctx.font = "24px Ubuntu";
	ctx.textAlign = "left";
	ctx.textBaseline = "top";
	ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
	ctx.fillText("Lives : " + lives, 365, 32);
	ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
	isGameOver = true;
	var caughtText = "You caught " + kittyCaught + " kitties."
	document.getElementById("startButton").value = "Start Over";
	document.getElementById("pauseButton").style.display = "none";
	ctx.fillStyle = "#000";
	ctx.fillRect (0, 0, canvas.width, canvas.height);
	ctx.font = "16px Ubuntu Mono";
	ctx.fillStyle = "#EEE";
	ctx.fillText("Game Over", 150, 180);
	ctx.fillText("Kitties only have nine lives.", 150, 230);
	ctx.fillText(caughtText, 150, 280);
	//document.write("Game Over. Kitties only have nine lives. You caught " + kittyCaught + " kitties.");
};

var main = function () {
	now = Date.now();
	var delta = now - then;

	nowSwitch = Date.now();

	if (!paused) {
		update(delta / 1100);
		if (!isGameOver) {
			render();
		}
	}

	then = now;
	requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var pause = function() {
	if (paused) {
		document.getElementById("pauseButton").value = "Pause";
		paused = false;
	} else {
		document.getElementById("pauseButton").value = "Resume";
		ctx.globalAlpha = 0.4;
		ctx.fillStyle = "#333";
		ctx.fillRect(0, 0, canvas.width, canvas.height);
		ctx.fillStyle = "#FFF";
		ctx.font = "50px Ubuntu Mono";
		ctx.globalAlpha = 1.0;
		ctx.fillText("Pawsed", 185, 200);
		paused = true;
	}
}

var initStart = function() {
	document.getElementById("startButton").value = "Reset";
	document.getElementById("pauseButton").style.display = "inline";
	then = thenSwitch = nowSwitch = Date.now();
	isGameOver = false;
	paused = false;
	reset();
	countDown = 0;
	lives = 9;
	kittyCaught = 0;
	//hero.x = (canvas.width / 2) - 16;
	//hero.y = (canvas.height / 2) - 16;
	main();
}

var initLook = function() {
	ctx.fillStyle = "rgb(20, 24, 73)";
	ctx.fillRect (0, 0, canvas.width, canvas.height);
	ctx.font = "50px Ubuntu Mono";
	ctx.fillStyle = "#EEE";
	ctx.fillText("Attack", 190, 190);
	ctx.fillText("of the", 200, 240);
	ctx.fillText("Space Kitty", 145, 290);
}

//initLook();
//start();
<commit_msg>Update index.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
	ctx = canvas.getContext("2d"),
	width = 512,
	height = 480;
var paused = false;
var isGameOver = false;

//canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
	bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
	heroReady = true;
};
heroImage.src = "image/png/spaceCat.png";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
	kittyReady = true;
};
kittyImage.src = "image/png/catDeathStar.png";

// Game objects
var hero = {
	speed: 256,
	x: 0,
	y: 0
};

var kitty = {
	x: 0,
	y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
	e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

var reset = function () {
	hero.x = (canvas.width / 2) - 16;
	hero.y = (canvas.height / 2) - 16;

	kitty.x = 32 + (Math.random() * (canvas.width - 64));
	kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
	if (38 in keysDown) {
		hero.y -= hero.speed * modifier;
	}
	if (40 in keysDown) {
		hero.y += hero.speed * modifier;
	}
	if (37 in keysDown) {
		hero.x -= hero.speed * modifier;
	}
	if (39 in keysDown) {
		hero.x += hero.speed * modifier;
	}

  // Stop from going off the page
	if (hero.x >= canvas.width - 32) {
		hero.x = canvas.width - 32;
	} else if (hero.x <= 0) {
		hero.x = 0;
	}

	if (hero.y >= canvas.height - 32) {
		hero.y = canvas.height - 32;
	} else if (hero.y <= 0) {
		hero.y = 0;
	}

  // Collision
	if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
		kittyCaught++;
		thenSwitch = nowSwitch;
		reset();
	}

	countDown = nowSwitch - thenSwitch;

	if (countDown >= 1000) {
		lives--;
		if (lives ==  0) {
			gameOver();
		}
		thenSwitch = nowSwitch;
		reset();
	}
};

// Render
var render = function () {
	if (bgReady) {
		ctx.drawImage(bgImage, 0, 0);
	}

	if (heroReady) {
		ctx.drawImage(heroImage, hero.x, hero.y);
	}

	if (kittyReady) {
		ctx.drawImage(kittyImage, kitty.x, kitty.y);
	}

	ctx.fillStyle = "#EEE";
	ctx.font = "24px Ubuntu";
	ctx.textAlign = "left";
	ctx.textBaseline = "top";
	ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
	ctx.fillText("Lives : " + lives, 365, 32);
	ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
	isGameOver = true;
	var caughtText = "You caught " + kittyCaught + " kitties."
	document.getElementById("startButton").value = "Start Over";
	document.getElementById("pauseButton").style.display = "none";
	ctx.fillStyle = "#000";
	ctx.fillRect (0, 0, canvas.width, canvas.height);
	ctx.font = "16px Ubuntu Mono";
	ctx.fillStyle = "#EEE";
	ctx.fillText("Game Over", 150, 180);
	ctx.fillText("Kitties only have nine lives.", 150, 230);
	ctx.fillText(caughtText, 150, 280);
	//document.write("Game Over. Kitties only have nine lives. You caught " + kittyCaught + " kitties.");
};

var main = function () {
	now = Date.now();
	var delta = now - then;

	nowSwitch = Date.now();

	if (!paused) {
		update(delta / 1100);
		if (!isGameOver) {
			render();
		}
	}

	then = now;
	requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var pause = function() {
	if (paused) {
		document.getElementById("pauseButton").value = "Pause";
		paused = false;
	} else {
		document.getElementById("pauseButton").value = "Resume";
		ctx.globalAlpha = 0.4;
		ctx.fillStyle = "#333";
		ctx.fillRect(0, 0, canvas.width, canvas.height);
		ctx.fillStyle = "#FFF";
		ctx.font = "50px Ubuntu Mono";
		ctx.globalAlpha = 1.0;
		ctx.fillText("Pawsed", 185, 200);
		paused = true;
	}
}

var initStart = function() {
	document.getElementById("startButton").value = "Reset";
	document.getElementById("pauseButton").style.display = "inline";
	then = thenSwitch = nowSwitch = Date.now();
	isGameOver = false;
	paused = false;
	reset();
	countDown = 0;
	lives = 9;
	kittyCaught = 0;
	//hero.x = (canvas.width / 2) - 16;
	//hero.y = (canvas.height / 2) - 16;
	main();
}

var initLook = function() {
	ctx.fillStyle = "rgb(20, 24, 73)";
	ctx.fillRect (0, 0, canvas.width, canvas.height);
	ctx.font = "50px Ubuntu Mono";
	ctx.fillStyle = "#EEE";
	ctx.fillText("Attack", 190, 190);
	ctx.fillText("of the", 200, 240);
	ctx.fillText("Space Kitty", 145, 290);
}

//initLook();
//start();
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { jobsTank, jobsHealer, jobsDps } from './helpers'
var images = require.context('./images', false, /\.png$/)

function HorizElement(props) {
  return (

          {props.text}

          {props.label}

  )
}

class CombatantHorizontal extends Component {
  render() {
    let order = this.props.rank
    let job = this.props.data.Job || 'WHO?'
    let jobClass
    if (jobsDps.indexOf(job.toLowerCase()) >= 0) {
      jobClass = ' job-dps'
    }
    if (jobsHealer.indexOf(job.toLowerCase()) >= 0) {
      jobClass = ' job-healer'
    }
    if (jobsTank.indexOf(job.toLowerCase()) >= 0) {
      jobClass = ' job-tank'
    }

    if (this.props.config.color !== 'byRole') jobClass = ''
    let width = `${parseInt(
      this.props.data.damage / this.props.encounterDamage * 100,
      10
    )}%`

    let hpsElement = (
      <HorizElement
        text={this.props.data.enchps}
        label="HPS"
        relevant={this.props.data.enchps > 0}
      />
    )
    let dpsElement = (
      <HorizElement
        text={this.props.data.encdps}
        label="DPS"
        relevant={this.props.data.encdps > 0}
      />
    )
    let classElement = (
      <HorizElement
        text={this.props.data.Job.toUpperCase()}
        label=""
        relevant="1"
      />
    )
    let jobIcon = (

    )
    let damagePercent = (

          {width}

    )
    let characterName = this.props.isSelf
      ? this.props.config.characterName
      : this.props.data.name
    return (

          {this.props.config.showRank
            ? {`${this.props.rank}. `}
            : null}

            {characterName}

          {this.props.config.showJobIcon ? jobIcon : null}
          {this.props.config.showHps ? hpsElement : classElement}
          {dpsElement}

        {this.props.config.showDamagePercent ? damagePercent : null}

    )
  }
}

export default CombatantHorizontal
<commit_msg>A much more clever refactor<commit_after>import React, { Component } from 'react'
import { jobRoles } from './helpers'
var images = require.context('./images', false, /\.png$/)

function HorizElement(props) {
  return (

          {props.text}

          {props.label}

  )
}

class CombatantHorizontal extends Component {
  render() {
    let order = this.props.rank
    let job = this.props.data.Job || 'WHO?'
    let jobClass

    // Color theme byRole
    if (this.props.config.color === 'byRole') {
      for (const role in jobRoles) {
        if (jobRoles[role].indexOf(job.toLowerCase()) >= 0) {
          jobClass = ` job-${role}`
        }
      }
    } else {
      jobClass = ''
    }

    let width = `${parseInt(
      this.props.data.damage / this.props.encounterDamage * 100,
      10
    )}%`

    let hpsElement = (
      <HorizElement
        text={this.props.data.enchps}
        label="HPS"
        relevant={this.props.data.enchps > 0}
      />
    )
    let dpsElement = (
      <HorizElement
        text={this.props.data.encdps}
        label="DPS"
        relevant={this.props.data.encdps > 0}
      />
    )
    let classElement = (
      <HorizElement
        text={this.props.data.Job.toUpperCase()}
        label=""
        relevant="1"
      />
    )
    let jobIcon = (

    )
    let damagePercent = (

          {width}

    )
    let characterName = this.props.isSelf
      ? this.props.config.characterName
      : this.props.data.name
    return (

          {this.props.config.showRank
            ? {`${this.props.rank}. `}
            : null}

            {characterName}

          {this.props.config.showJobIcon ? jobIcon : null}
          {this.props.config.showHps ? hpsElement : classElement}
          {dpsElement}

        {this.props.config.showDamagePercent ? damagePercent : null}

    )
  }
}

export default CombatantHorizontal
<|endoftext|>


<commit_before>let examples = [];

let example_1 = {
	name: 'Find words and convert to JS array',
	actions: [
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "FindAll"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "1", searchString: "[a-z]+"},
		{type: "FILTER_TOGGLE_CASE_INSENSITIVE", id: "1"},

		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Unique"},

		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Replace"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "3", searchString: "^(.+?)$"},
		{type: "FILTER_UPDATE_REPLACE_STRING", id: "3", replaceString: "'$1',"},

		{
			type: "UPDATE_INPUT_TEXT",
			text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
			"Cras ut pharetra ipsum, in interdum risus. " +
			"Donec ante mauris, pellentesque condimentum felis sed, dictum pulvinar elit. " +
			"Sed nulla metus, sagittis eu elit vel, adipdsdsdiscing interdum risus. " +
			"Mauris vitae ligula massa. " +
			"Integer in blandit arcu. " +

			"Aliquam laoreet justo a lorem pellentesque scelerisque. " +
			"Curabitur varius et odio ut condimentum. " +
			"Etiam cursus nunc et porttitor cursus. " +
			"Nulla blandit hendrerit metus, a auctor magna ullamcorper non. " +
			"Cras vitae metus tortor. " +
			"Proin venenatis eros et sem consectetur vehicula. " +
			"Donec commodo sit amet metus a scelerisque. " +
			"Sed vitae dapibus lorem. " +
			"Vestibulum sed varius nisl. " +

			"Curabitur id lobortis dui.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse egestas ultrices eros et cursus. " +
			"In quam erat, fermentum in volutpat eu, ornare eget enim. " +
			"Vivamus eu pharetra sem. " +
			"Mauris id congue urna. " +
			"Proin leo augue, pretium eu pulvinar sit amet, placerat eget sapien. " +
			"Phasellus porta nunc euismod ultricies dignissim. " +
			"Mauris luctus bibendum vehicula. " +
			"In hac habitasse platea dictumst. " +
			"Curabitur posuere ac felis non interdum. " +
			"Phasellus laoreet id purus id semper. "
		},
	]
};
examples.push(example_1);

let example_2 = {
	name: 'Convert Excel to JSON',
	actions: [
		{
			type: "UPDATE_INPUT_TEXT",
			text: "1	Aaa	2016-10-01	8\n" +
			"2	Bbb	2016-10-01	16\n" +
			"3	Ccc	2016-10-02	10\n" +
			"4	Ddd	2016-10-03	14\n" +
			"5	Eee	2016-10-05	16\n" +
			"6	Fff	2016-10-10	11\n" +
			"7	Ggg	2016-10-12	11\n" +
			"8	Hhh	2016-10-14	18\n" +
			"9	Iii	2016-10-20	18\n" +
			"10	Jjj	2016-10-24	7\n" +
			"11	Kkk	2016-10-30	17\n"
		},
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Replace"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "1", searchString: "^(.+?)\\t(.+?)\\t(.+?)\\t(.+?)$"},
		{type: "FILTER_UPDATE_REPLACE_STRING", id: "1", replaceString: '{"id":$1, "name": "$2", "startedAt": "$3", "total": $4}'},
	]
};
examples.push(example_2);

examples.push({
	name: 'Build JS constants',
	actions: [
		{
			type: "UPDATE_INPUT_TEXT",
			text: "<type>FOO</type>\n"
			+ "<type>BAR</type>\n"
			+ "<type>FOOBAR</type>\n"
			+ "<type>LOREM</type>\n"
			+ "<type>IPSUM</type>"
		},
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "MatchInLines"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "1", searchString: "<type>(.+?)</type>"},
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Replace"},
		{type: "FILTER_UPDATE_REPLACE_STRING", id: "2", replaceString: 'const $1 = "$1";'}
	]
});

export default examples;
<commit_msg>Refactored examples<commit_after>let examples = [];

examples.push({
	name: 'Find words and convert to JS array',
	actions: [
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "FindAll"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "1", searchString: "[a-z]+"},
		{type: "FILTER_TOGGLE_CASE_INSENSITIVE", id: "1"},

		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Unique"},

		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Replace"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "3", searchString: "^(.+?)$"},
		{type: "FILTER_UPDATE_REPLACE_STRING", id: "3", replaceString: "'$1',"},

		{
			type: "UPDATE_INPUT_TEXT",
			text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
			"Cras ut pharetra ipsum, in interdum risus. " +
			"Donec ante mauris, pellentesque condimentum felis sed, dictum pulvinar elit. " +
			"Sed nulla metus, sagittis eu elit vel, adipdsdsdiscing interdum risus. " +
			"Mauris vitae ligula massa. " +
			"Integer in blandit arcu. " +

			"Aliquam laoreet justo a lorem pellentesque scelerisque. " +
			"Curabitur varius et odio ut condimentum. " +
			"Etiam cursus nunc et porttitor cursus. " +
			"Nulla blandit hendrerit metus, a auctor magna ullamcorper non. " +
			"Cras vitae metus tortor. " +
			"Proin venenatis eros et sem consectetur vehicula. " +
			"Donec commodo sit amet metus a scelerisque. " +
			"Sed vitae dapibus lorem. " +
			"Vestibulum sed varius nisl. " +

			"Curabitur id lobortis dui.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse egestas ultrices eros et cursus. " +
			"In quam erat, fermentum in volutpat eu, ornare eget enim. " +
			"Vivamus eu pharetra sem. " +
			"Mauris id congue urna. " +
			"Proin leo augue, pretium eu pulvinar sit amet, placerat eget sapien. " +
			"Phasellus porta nunc euismod ultricies dignissim. " +
			"Mauris luctus bibendum vehicula. " +
			"In hac habitasse platea dictumst. " +
			"Curabitur posuere ac felis non interdum. " +
			"Phasellus laoreet id purus id semper. "
		},
	]
});

examples.push({
	name: 'Convert Excel to JSON',
	actions: [
		{
			type: "UPDATE_INPUT_TEXT",
			text: "1	Aaa	2016-10-01	8\n" +
			"2	Bbb	2016-10-01	16\n" +
			"3	Ccc	2016-10-02	10\n" +
			"4	Ddd	2016-10-03	14\n" +
			"5	Eee	2016-10-05	16\n" +
			"6	Fff	2016-10-10	11\n" +
			"7	Ggg	2016-10-12	11\n" +
			"8	Hhh	2016-10-14	18\n" +
			"9	Iii	2016-10-20	18\n" +
			"10	Jjj	2016-10-24	7\n" +
			"11	Kkk	2016-10-30	17\n"
		},
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Replace"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "1", searchString: "^(.+?)\\t(.+?)\\t(.+?)\\t(.+?)$"},
		{type: "FILTER_UPDATE_REPLACE_STRING", id: "1", replaceString: '{"id":$1, "name": "$2", "startedAt": "$3", "total": $4}'},
	]
});

examples.push({
	name: 'Build JS constants',
	actions: [
		{
			type: "UPDATE_INPUT_TEXT",
			text: "<type>FOO</type>\n"
			+ "<type>BAR</type>\n"
			+ "<type>FOOBAR</type>\n"
			+ "<type>LOREM</type>\n"
			+ "<type>IPSUM</type>"
		},
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "MatchInLines"},
		{type: "FILTER_UPDATE_SEARCH_STRING", id: "1", searchString: "<type>(.+?)</type>"},
		{type: "REGEXP_FLOW_ADD_FILTER", filterType: "Replace"},
		{type: "FILTER_UPDATE_REPLACE_STRING", id: "2", replaceString: 'const $1 = "$1";'}
	]
});

export default examples;
<|endoftext|>


<commit_before>// Initialize app
function showDivsConnect(){
    if(localStorage.getItem("logged_in")==true){
        $(".login").show();
        $(".logout").hide();
    }else{
        $(".login").hide();
        $(".logout").show();
    }
}

function checkConnectionFB() {
    facebookConnectPlugin.getLoginStatus(function(response) {
        if (response.status == 'connected') {
            var gar = facebookConnectPlugin.getAuthResponse();
            //localStorage.setItem("logged_in",true);
            showDivsConnect();
        } else {
            alert('not connected to FB');
            localStorage.setItem("logged_in",false);
        }
    });
}

function randSlider() {
    var num= Math.floor((Math.random() * 5) + 1);
    $(".full-page-video").css('background-image','url("http://wisi.com.co/assets/img/sliders/slider'+num+'.jpg")');
}
function findElement(selector) {
    var box = null;
    return $(".page-on-center").length > 0 ? (box = $(".view-main").find(".page-on-center " + selector),
        0 === box.length && (box = $(".view-main").find(".page-on-center" + selector))) : box = $(".view-main").find(".page").find(selector),
    box;
}

function naxvarBg() {
    var navbar = $(".navbar-anim-on-scroll"), box = null, cls = "active";
    return 0 === navbar.length ? !1 : (box = navbar.next().find($(".page-on-center").length > 0 ? ".page-on-center .page-content" : ".page .page-content"),
        box.scrollTop() > 10 ? navbar.addClass(cls) : navbar.removeClass(cls), void box.scroll(function() {
            $(this).scrollTop() > 40 ? navbar.addClass(cls) : navbar.removeClass(cls);
        }));
}

function hidePreloader() {
    jQuery(".page-preloader").animate({
        opacity: 0
    }, function() {
        jQuery(this).hide();
    });
}

var myApp = new Framework7({
    swipeBackPage: !1,
    pushState: !0,
    swipePanel: "left",
    modalTitle: "Title"
}), $$ = Dom7;

var fbLoginSuccess = function (response) {
   if (response.authResponse) {
       facebookConnectPlugin.api('/me?fields=id,email,first_name,last_name,gender,birthday', null,
           function(response) {
            var genre=38;
            if(response.gender=="male")genre=39;
            $.ajax({
              method: "POST",
              url: "http://wisi.com.co/api/social/sigin",
              data: { network:response.id,name:response.first_name,lastname:response.last_name,genre:genre,birthday:response.birthday }
          })
            .done(function( msg ) {
                alert( "Data Saved: " + msg );
                    //window.open('http://wisi.com.co/public/#/ad', '_system');
                });
           });

   }
}

$$("body").on("click", ".button-facebook", function() {
    facebookConnectPlugin.login(["public_profile","email"],
        fbLoginSuccess,
        function (error) { myApp.alert("Problemas conectando con Facebook!", ""); }
    );
});

var mainView = myApp.addView(".view-main", {
    dynamicNavbar: !0
});
$$(document).on("pageInit", function(e) {
    checkConnectionFB();
    var page = e.detail.page;
    myApp.calendar({
        input: "#ks-calendar-default"
    }), myApp.calendar({
        input: "#calendar-multiple",
        dateFormat: "M dd yyyy",
        multiple: !0
    }), myApp.calendar({
        input: "#calendar-range",
        dateFormat: "M dd yyyy",
        rangePicker: !0
    });
    var today = new Date(), weekLater = new Date().setDate(today.getDate() + 7);
    myApp.calendar({
        input: "#calendar-disabled",
        dateFormat: "M dd yyyy",
        disabled: {
            from: today,
            to: weekLater
        }
    }), myApp.calendar({
        container: "#calendar-inline-container",
        value: [ new Date() ]
    }), $$(".notification-default").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            message: "This is a simple notification message with title and message"
        });
    }), $$(".notification-full").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            subtitle: "Notification subtitle",
            message: "This is a simple notification message with custom icon and subtitle",
            media: ''
        });
    }), $$(".notification-custom").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: ''
        });
    }), $$(".notification-callback").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: '',
            onClose: function() {
                myApp.alert("Notification closed");
            }
        });
    }), $(".zoom").swipebox(), $(".navbar").removeClass("navbar-clear"), ("index" === page.name || "dashboard-1" === page.name || "post" === page.name || "menu" === page.name || "login" === page.name || "registration" === page.name || "article" === page.name || "splash" === page.name) && $(".navbar").addClass("navbar-clear"),
    $(".twitter-content").length > 0 && $(".twitter-content").twittie({
        count: 10
    }), $(".tweet").length > 0 && $(".tweet").twittie({
        count: 1
    }), $(".flickr-content").length > 0 && $(".flickr-content").jflickrfeed({
        limit: 15,
        qstrings: {
            id: "44244432@N03"
        },
        itemTemplate: '

'
    }, function(data) {
        $(".flickr-content li a").swipebox();
    }), $(".owl-carousel").length > 0 && $(".owl-carousel").owlCarousel(), $(".featured-articles-slider").length > 0 && $(".featured-articles-slider").owlCarousel({
        singleItem: !0,
        navigation: !1,
        navigationText: [],
        pagination: !1,
        uniqueHistory: !0,
        loop: !0,
        autoPlay: 3e3,
        stopOnHover: !0
    }), $(".js-validate").length > 0 && $("body").on("click", ".js-form-submit", function() {
        var form = $(this).parents("form"), valid = form.valid();
        if ("contact" === page.name && valid) {
            var data = form.serializeObject();
            myApp.showPreloader(), $.post("/email.php", data).done(function(data) {
                myApp.hidePreloader();
                var response = JSON.parse(data);
                response.error ? myApp.alert(response.msg, "") : (myApp.alert(response.msg, ""),
                    form.find("input[type=text], input[type=email], textarea").val(""));
            });
        }
    });
    // Conversation flag
    var conversationStarted = !1, myMessages = myApp.messages(".messages", {
        autoLayout: !0
    }), myMessagebar = myApp.messagebar(".messagebar");
    // Handle message
    $$(".messagebar .link").on("click", function() {
        // Message text
        var messageText = myMessagebar.value().trim();
        // Exit if empy message
        if (0 !== messageText.length) {
            // Empty messagebar
            myMessagebar.clear();
            // Random message type
            var avatar, name, messageType = [ "sent", "received" ][Math.round(Math.random())];
            "received" === messageType && (avatar = "http://lorempixel.com/output/people-q-c-100-100-9.jpg",
            name = "Kate"), // Add message
            myMessages.addMessage({
                // Message text
                text: messageText,
                // Random message type
                type: messageType,
                // Avatar and name:
                avatar: avatar,
                name: name,
                // Day
                day: conversationStarted ? !1 : "Today",
                time: conversationStarted ? !1 : new Date().getHours() + ":" + new Date().getMinutes()
            }), // Update conversation flag
            conversationStarted = !0;
        }
    });
}), $(document).ready(function() {
    //randSlider();
    localStorage.setItem("logged_in",false);
    alert(localStorage.getItem("logged_in"));
    checkConnectionFB();

    if ((null === localStorage.getItem("newOptions") || localStorage.getItem("newOptions") === !0) && (myApp.popup(".popup-splash"),
        localStorage.setItem("newOptions", !0)), $(".chart-content").length > 0) {
        var obj = document.querySelector(".chart-content"), ctx = obj.getContext("2d");
    showLineChart(ctx);
}
naxvarBg(), $(".js-toggle-menu").on("click", function() {
    $(this).next().slideToggle(200), $(this).find("span").toggleClass("icon-chevron-down").toggleClass("icon-chevron-up");
}), $("body").on("click", ".js-gallery-col", function() {
    var cols = $(this).data("cols");
    $(".gallery-list").attr({
        "data-cols": cols
    }), $(".js-gallery-col").removeClass("active"), $(this).addClass("active");
});
}), $.fn.serializeObject = function() {
    var o = {}, a = this.serializeArray();
    return $.each(a, function() {
        void 0 !== o[this.name] ? (o[this.name].push || (o[this.name] = [ o[this.name] ]),
            o[this.name].push(this.value || "")) : o[this.name] = this.value || "";
    }), o;
};<commit_msg>Test Name<commit_after>// Initialize app
function showDivsConnect(){
    if(localStorage.getItem("logged_in")==true){
        $(".login").show();
        $(".logout").hide();
        $(".names_user").html(localStorage.name+" "+localStorage.lastname);
    }else{
        $(".login").hide();
        $(".logout").show();
    }
}

function checkConnectionFB() {
    facebookConnectPlugin.getLoginStatus(function(response) {
        if (response.status == 'connected') {
            var gar = facebookConnectPlugin.getAuthResponse();
            showDivsConnect();
        } else {
            alert('not connected to FB');
            localStorage.setItem("logged_in",false);
        }
    });
}

function randSlider() {
    var num= Math.floor((Math.random() * 5) + 1);
    $(".full-page-video").css('background-image','url("http://wisi.com.co/assets/img/sliders/slider'+num+'.jpg")');
}
function findElement(selector) {
    var box = null;
    return $(".page-on-center").length > 0 ? (box = $(".view-main").find(".page-on-center " + selector),
        0 === box.length && (box = $(".view-main").find(".page-on-center" + selector))) : box = $(".view-main").find(".page").find(selector),
    box;
}

function naxvarBg() {
    var navbar = $(".navbar-anim-on-scroll"), box = null, cls = "active";
    return 0 === navbar.length ? !1 : (box = navbar.next().find($(".page-on-center").length > 0 ? ".page-on-center .page-content" : ".page .page-content"),
        box.scrollTop() > 10 ? navbar.addClass(cls) : navbar.removeClass(cls), void box.scroll(function() {
            $(this).scrollTop() > 40 ? navbar.addClass(cls) : navbar.removeClass(cls);
        }));
}

function hidePreloader() {
    jQuery(".page-preloader").animate({
        opacity: 0
    }, function() {
        jQuery(this).hide();
    });
}

var myApp = new Framework7({
    swipeBackPage: !1,
    pushState: !0,
    swipePanel: "left",
    modalTitle: "Title"
}), $$ = Dom7;

var fbLoginSuccess = function (res) {
   if (res.authResponse) {
       facebookConnectPlugin.api('/me?fields=id,email,first_name,last_name,gender,birthday', null,
           function(res) {
            var genre=38;
            if(res.gender=="male")genre=39;
            localStorage.setItem("id",res.id);
            localStorage.setItem("name",  res.first_name);
            localStorage.setItem("lastname",  res.last_name);
            localStorage.setItem("email",  res.email);
            localStorage.setItem("logged_in", true);
            localStorage.setItem("token", res.token.token);
            showDivsConnect();
            alert(JSON.stringify(res));
            $.ajax({
              method: "POST",
              url: "http://wisi.com.co/api/social/sigin",
              data: { network:res.id,name:res.first_name,lastname:res.last_name,genre:genre,birthday:res.birthday }
          })
            .done(function( msg ) {
                alert( "Data Saved: " + msg );
                    //window.open('http://wisi.com.co/public/#/ad', '_system');
                });
           });

   }
}

$$("body").on("click", ".button-facebook", function() {
    facebookConnectPlugin.login(["public_profile","email"],
        fbLoginSuccess,
        function (error) { myApp.alert("Problemas conectando con Facebook!", ""); }
    );
});

var mainView = myApp.addView(".view-main", {
    dynamicNavbar: !0
});
$$(document).on("pageInit", function(e) {
    checkConnectionFB();
    var page = e.detail.page;
    myApp.calendar({
        input: "#ks-calendar-default"
    }), myApp.calendar({
        input: "#calendar-multiple",
        dateFormat: "M dd yyyy",
        multiple: !0
    }), myApp.calendar({
        input: "#calendar-range",
        dateFormat: "M dd yyyy",
        rangePicker: !0
    });
    var today = new Date(), weekLater = new Date().setDate(today.getDate() + 7);
    myApp.calendar({
        input: "#calendar-disabled",
        dateFormat: "M dd yyyy",
        disabled: {
            from: today,
            to: weekLater
        }
    }), myApp.calendar({
        container: "#calendar-inline-container",
        value: [ new Date() ]
    }), $$(".notification-default").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            message: "This is a simple notification message with title and message"
        });
    }), $$(".notification-full").on("click", function() {
        myApp.addNotification({
            title: "Framework7",
            subtitle: "Notification subtitle",
            message: "This is a simple notification message with custom icon and subtitle",
            media: ''
        });
    }), $$(".notification-custom").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: ''
        });
    }), $$(".notification-callback").on("click", function() {
        myApp.addNotification({
            title: "My Awesome App",
            subtitle: "New message from John Doe",
            message: "Hello, how are you? Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut posuere erat. Pellentesque id elementum urna, a aliquam ante. Donec vitae volutpat orci. Aliquam sed molestie risus, quis tincidunt dui.",
            media: '',
            onClose: function() {
                myApp.alert("Notification closed");
            }
        });
    }), $(".zoom").swipebox(), $(".navbar").removeClass("navbar-clear"), ("index" === page.name || "dashboard-1" === page.name || "post" === page.name || "menu" === page.name || "login" === page.name || "registration" === page.name || "article" === page.name || "splash" === page.name) && $(".navbar").addClass("navbar-clear"),
    $(".twitter-content").length > 0 && $(".twitter-content").twittie({
        count: 10
    }), $(".tweet").length > 0 && $(".tweet").twittie({
        count: 1
    }), $(".flickr-content").length > 0 && $(".flickr-content").jflickrfeed({
        limit: 15,
        qstrings: {
            id: "44244432@N03"
        },
        itemTemplate: '

'
    }, function(data) {
        $(".flickr-content li a").swipebox();
    }), $(".owl-carousel").length > 0 && $(".owl-carousel").owlCarousel(), $(".featured-articles-slider").length > 0 && $(".featured-articles-slider").owlCarousel({
        singleItem: !0,
        navigation: !1,
        navigationText: [],
        pagination: !1,
        uniqueHistory: !0,
        loop: !0,
        autoPlay: 3e3,
        stopOnHover: !0
    }), $(".js-validate").length > 0 && $("body").on("click", ".js-form-submit", function() {
        var form = $(this).parents("form"), valid = form.valid();
        if ("contact" === page.name && valid) {
            var data = form.serializeObject();
            myApp.showPreloader(), $.post("/email.php", data).done(function(data) {
                myApp.hidePreloader();
                var response = JSON.parse(data);
                response.error ? myApp.alert(response.msg, "") : (myApp.alert(response.msg, ""),
                    form.find("input[type=text], input[type=email], textarea").val(""));
            });
        }
    });
    // Conversation flag
    var conversationStarted = !1, myMessages = myApp.messages(".messages", {
        autoLayout: !0
    }), myMessagebar = myApp.messagebar(".messagebar");
    // Handle message
    $$(".messagebar .link").on("click", function() {
        // Message text
        var messageText = myMessagebar.value().trim();
        // Exit if empy message
        if (0 !== messageText.length) {
            // Empty messagebar
            myMessagebar.clear();
            // Random message type
            var avatar, name, messageType = [ "sent", "received" ][Math.round(Math.random())];
            "received" === messageType && (avatar = "http://lorempixel.com/output/people-q-c-100-100-9.jpg",
            name = "Kate"), // Add message
            myMessages.addMessage({
                // Message text
                text: messageText,
                // Random message type
                type: messageType,
                // Avatar and name:
                avatar: avatar,
                name: name,
                // Day
                day: conversationStarted ? !1 : "Today",
                time: conversationStarted ? !1 : new Date().getHours() + ":" + new Date().getMinutes()
            }), // Update conversation flag
            conversationStarted = !0;
        }
    });
}), $(document).ready(function() {
    //randSlider();
    localStorage.setItem("logged_in",false);
    alert(localStorage.getItem("logged_in"));
    checkConnectionFB();

    if ((null === localStorage.getItem("newOptions") || localStorage.getItem("newOptions") === !0) && (myApp.popup(".popup-splash"),
        localStorage.setItem("newOptions", !0)), $(".chart-content").length > 0) {
        var obj = document.querySelector(".chart-content"), ctx = obj.getContext("2d");
    showLineChart(ctx);
}
naxvarBg(), $(".js-toggle-menu").on("click", function() {
    $(this).next().slideToggle(200), $(this).find("span").toggleClass("icon-chevron-down").toggleClass("icon-chevron-up");
}), $("body").on("click", ".js-gallery-col", function() {
    var cols = $(this).data("cols");
    $(".gallery-list").attr({
        "data-cols": cols
    }), $(".js-gallery-col").removeClass("active"), $(this).addClass("active");
});
}), $.fn.serializeObject = function() {
    var o = {}, a = this.serializeArray();
    return $.each(a, function() {
        void 0 !== o[this.name] ? (o[this.name].push || (o[this.name] = [ o[this.name] ]),
            o[this.name].push(this.value || "")) : o[this.name] = this.value || "";
    }), o;
};<|endoftext|>


<commit_before>/*global cordova, module*/

module.exports = {
    getdate: function (name, successCallback, errorCallback) {
        cordova.exec(successCallback, errorCallback, "Getdateinstallapp", "getdate", [name]);
    }
};
<commit_msg>Commit inicial<commit_after>var exec = require('cordova/exec');

var Gdia = {
    getdate: function (name, successCallback, errorCallback) {
        cordova.exec(successCallback, errorCallback, "Getdateinstallapp", "getdate", [name]);
    }
};
module.exports = Gdia;
<|endoftext|>


<commit_before>(function(catHACKlic){
  catHACKlic.defaultExam = [
    {
      "title":"Have I gone to Mass every Sunday? Have I participated at Mass or have I daydreamed or been present with a blank mind?",
      "page":"weakness"
    },
    {
      "title":"Have I prayed every day (15-20 minutes)?",
      "page":"weakness"
    },
    {
      "title":"Have I read the Bible? Have I studied the truths of our faith and allowed them to become more a part of the way I think and act? Have I read any spiritual books or religious literature?",
      "page":"weakness"
    },
    {
      "title":"Have I told God that I want to love him with my whole heart, mind and strength? Do I hold any resentments toward God?",
      "page":"weakness"
    },
    {
      "title":"Have I recognized my need for Jesus and his salvation? Have I asked the Holy Spirit to empower me to live the Christian life?",
      "page":"weakness"
    },
    {
      "title":"Have I been financially generous to the Church? Have I participated in parish or religious activities?",
      "page":"weakness"
    },
    {
      "title":"Have I held resentments toward the Church or Church authorities? Have I forgiven them?",
      "page":"weakness"
    },
    {
      "title":"Have I been rebellious, disobedient or disrespectful to anyone in authority?",
      "page":"weakness"
    },
    {
      "title":"Have I lied to or deceived others—friends, boss, or coworkers?",
      "page":"weakness"
    },
    {
      "title":"Have I been arrogant and stubborn?",
      "page":"weakness"
    },
    {
      "title":"Have I gotten angry or nurtured and held grudges and resentments?",
      "page":"weakness"
    },
    {
      "title":"Have I refused to forgive others—parents,relatives, employers, former friend, a former spouse? Have I cultivated hatred?",
      "page":"weakness"
    },
    {
      "title":"Have I felt sorry for myself or nurtured self-pity?",
      "page":"weakness"
    },
    {
      "title":"Have I engaged in sexual fantasies? Have I looked at others lustfully?",
      "page":"weakness"
    },
    {
      "title":"Have I read pornographic literature or looked at pornographic pictures, shows or movies?",
      "page":"weakness"
    },
    {
      "title":"Have I masturbated?",
      "page":"weakness"
    },
    {
      "title":"Have I lustfully kissed or sexually touched someone? Have I had sexual intercourse?",
      "page":"weakness"
    },
    {
      "title":"Have I had an abortion or encouraged another to have one?",
      "page":"weakness"
    },
    {
      "title":"Have I gossiped about others? Have I slandered anyone? HaveI told lies about others? Have I mocked or made fun of others?",
      "page":"weakness"
    },
    {
      "title":"Have I been a Christian witness to those with whom I work or associate? Have I spoken to anyone about the Gospel and how important it is to believe in Jesus?",
      "page":"weakness"
    },
    {
      "title":"Have I allowed the Gospel to influence my political and social opinions?",
      "page":"weakness"
    },
    {
      "title":"Have I had a proper Christian concern for the poor and needy?",
      "page":"weakness"
    },
    {
      "title":"Have I paid my taxes?",
      "page":"weakness"
    },
    {
      "title":"Have I fostered or nurtured hatred toward my ‘political’ opponents, either local, national or international?",
      "page":"weakness"
    },
    {
      "title":"Have I been prejudiced toward others because of race, color, religion or social status?",
      "page":"weakness"
    }
  ];
}( window.catHACKlic = window.catHACKlic || {} ));
<commit_msg>Reformatted the default examination<commit_after>(function(catHACKlic){
  catHACKlic.defaultExam = [
    {
      "title":"Have I participated at Mass or have I daydreamed or been present with a blank mind?",
      "page":"weakness"
    },
    {
      "title":"Have I prayed every day (15-20 minutes)?",
      "page":"weakness"
    },
    {
      "title":"Have I read the Bible?",
      "page":"weakness"
    },
    {
      "title":"Have I studied the truths of our faith and allowed them to become more a part of the way I think and act?",
      "page":"weakness"
    },
    {
      "title":"Have I read any spiritual books or religious literature?",
      "page":"weakness"
    },
    {
      "title":"Have I told God that I want to love him with my whole heart, mind and strength?",
      "page":"weakness"
    },
    {
      "title":"Do I hold any resentments toward God?",
      "page":"weakness"
    },
    {
      "title":"Have I recognized my need for Jesus and his salvation?",
      "page":"weakness"
    },
    {
      "title":"Have I asked the Holy Spirit to empower me to live the Christian life?",
      "page":"weakness"
    },
    {
      "title":"Have I been financially generous to the Church?",
      "page":"weakness"
    },
    {
      "title":"Have I participated in parish or religious activities?",
      "page":"weakness"
    },
    {
      "title":"Have I held resentments toward the Church or Church authorities? Have I forgiven them?",
      "page":"weakness"
    },
    {
      "title":"Have I been rebellious, disobedient or disrespectful to anyone in authority?",
      "page":"weakness"
    },
    {
      "title":"Have I lied to or deceived others—friends, boss, or coworkers?",
      "page":"weakness"
    },
    {
      "title":"Have I been arrogant and stubborn?",
      "page":"weakness"
    },
    {
      "title":"Have I gotten angry or nurtured and held grudges and resentments?",
      "page":"weakness"
    },
    {
      "title":"Have I refused to forgive others—parents, relatives, employers, former friend, a former spouse?",
      "page":"weakness"
    },
    {
      "title":"Have I cultivated hatred?",
      "page":"weakness"
    },
    {
      "title":"Have I felt sorry for myself or nurtured self-pity?",
      "page":"weakness"
    },
    {
      "title":"Have I looked at others lustfully?",
      "page":"weakness"
    },
    {
      "title":"Have I engaged in sexual fantasies?",
      "page":"weakness"
    },
    {
      "title":"Have I read pornographic literature or looked at pornographic pictures, shows or movies?",
      "page":"weakness"
    },
    {
      "title":"Have I masturbated?",
      "page":"weakness"
    },
    {
      "title":"Have I lustfully kissed or sexually touched someone?",
      "page":"weakness"
    },
    {
      "title":"Have I had sexual intercourse?",
      "page":"weakness"
    },
    {
      "title":"Have I had an abortion or encouraged another to have one?",
      "page":"weakness"
    },
    {
      "title":"Have I gossiped about others?",
      "page":"weakness"
    },
    {
      "title":"Have I slandered anyone?",
      "page":"weakness"
    },
    {
      "title":"Have I told lies about others? Have I mocked or made fun of others?",
      "page":"weakness"
    },
    {
      "title":"Have I mocked or made fun of others?",
      "page":"weakness"
    },
    {
      "title":"Have I spoken to anyone about the Gospel and how important it is to believe in Jesus?",
      "page":"weakness"
    },
    {
      "title":"Have I been a Christian witness to those with whom I work or associate?",
      "page":"weakness"
    },
    {
      "title":"Have I allowed the Gospel to influence my political and social opinions?",
      "page":"weakness"
    },
    {
      "title":"Have I had a proper Christian concern for the poor and needy?",
      "page":"weakness"
    },
    {
      "title":"Have I paid my taxes?",
      "page":"weakness"
    },
    {
      "title":"Have I fostered or nurtured hatred toward my ‘political’ opponents, either local, national or international?",
      "page":"weakness"
    },
    {
      "title":"Have I been prejudiced toward others because of race, color, religion or social status?",
      "page":"weakness"
    }
  ];
}( window.catHACKlic = window.catHACKlic || {} ));
<|endoftext|>


<commit_before>'use strict'

/**
 * Abstract base class that ensures required public methods are implemented by
 * inheriting classes.
 *
 * @example
 *
 * class BloomFilterCache extends Cache {
 *   constructor() {
 *     super()
 *   }
 *
 *   get(key) {}
 *   put(key, value, milliseconds) {}
 *   increment(key) {}
 *   incrementExpiration(key, seconds) {}
 * }
 *
 */
class Cache {
  /**
   * Do not call this constructor directly.
   */
  constructor() {
    if (new.target === Cache) {
      throw new TypeError('Cannot instantiate abstract base class: Cache')
    }

    const abstractMethods = [
      'get',
      'put',
      'increment',
      'incrementExpiration'
    ].map(name => {
      const implemented = typeof this[name] === 'function'
      return { name, implemented }
    })

    if (!abstractMethods.every(method => method.implemented)) {
      const message = 'Implementing class does not override abstract methods: '
      const unimplemented = abstractMethods
        .filter(method => !method.implemented)
        .map(method => method.name)
        .join(', ')

      throw new TypeError(message + unimplemented)
    }
  }
}

module.exports = Cache
<commit_msg>Mark secondsToExpiration as abstract method<commit_after>'use strict'

/**
 * Abstract base class that ensures required public methods are implemented by
 * inheriting classes.
 *
 * @example
 *
 * class BloomFilterCache extends Cache {
 *   constructor() {
 *     super()
 *   }
 *
 *   get(key) {}
 *   put(key, value, milliseconds) {}
 *   increment(key) {}
 *   incrementExpiration(key, seconds) {}
 * }
 *
 */
class Cache {
  /**
   * Do not call this constructor directly.
   */
  constructor() {
    if (new.target === Cache) {
      throw new TypeError('Cannot instantiate abstract base class: Cache')
    }

    const abstractMethods = [
      'get',
      'put',
      'increment',
      'incrementExpiration',
      'secondsToExpiration'
    ].map(name => {
      const implemented = typeof this[name] === 'function'
      return { name, implemented }
    })

    if (!abstractMethods.every(method => method.implemented)) {
      const message = 'Implementing class does not override abstract methods: '
      const unimplemented = abstractMethods
        .filter(method => !method.implemented)
        .map(method => method.name)
        .join(', ')

      throw new TypeError(message + unimplemented)
    }
  }
}

module.exports = Cache
<|endoftext|>