<commit_before>import { isObject } from './util';

export const keyPrefix = '#dt';
export const valuePrefix = ':dt';

// Splits an object of query params into 2 objects
// One for any params that matches the defined table keys
// and another object for all other params
// ({id: 1, name: 'pony', interests: 'ponying'}, { id: 'N' }) -> [{id: 1}, {name: 'pony', interests: 'ponying'}]
export function splitKeysAndParams(params, tableKeys) {
  if (!isObject(params) || !isObject(tableKeys)) {
    return null;
  }

  const keys = Object.keys(tableKeys);
  const paramKeys = Object.keys(params);
  return [
    paramKeys.reduce((acc, curr) => Object.assign(acc,
      keys.includes(curr) && { [curr]: params[curr] }
    ), {}),
    paramKeys.reduce((acc, curr) => Object.assign(acc,
      !keys.includes(curr) && { [curr]: params[curr] }
    ), {})
  ];
}

export function createFilterQuery(params) {
  const paramKeys = Object.keys(params);
  return {
    FilterExpression: paramKeys.reduce((acc, key) => {
      const maybeAnd = acc === '' ? '' : ' AND '
      return `${acc}${maybeAnd}(${keyPrefix}${key} = ${valuePrefix}${key})`;
    }, ''),
    ExpressionAttributeNames: paramKeys.reduce((acc, key) => {
      return Object.assign(acc, {
        [`${keyPrefix}${key}`]: key,
      });
    }, {}),
    ExpressionAttributeValues: paramKeys.reduce((acc, key) => {
      const val = params[key];
      return Object.assign(acc, {
        [`${valuePrefix}${key}`]: val,
      });
    }, {}),
  };
}

const comparisonKeys = [
  '$eq', // Matches values that are equal to a specified value. (default)
  '$gt', // Matches values that are greater than a specified value.
  '$gte', // Matches values that are greater than or equal to a specified value.
  '$lt', // Matches values that are less than a specified value.
  '$lte', // Matches values that are less than or equal to a specified value.
  '$ne', // Matches all values that are not equal to a specified value.
  '$in', // Matches any of the values specified in an array.
  '$nin', // Matches none of the values specified in an array.
];
export function constructComparisonString(key, value) {
  // If value is not an object we can return the default (equality comparison)
  const equalityString = `(${keyPrefix}${key} = ${valuePrefix}${key})`;
  if (!isObject(value)) {
    return equalityString;
  }

  const firstKey = Object.keys(value)[0];
  switch (firstKey) {
    case '$gt':
      return `(${keyPrefix}${key} > ${valuePrefix}${key})`;
    case '$gte':
      return `(${keyPrefix}${key} >= ${valuePrefix}${key})`;
    case '$lt':
      return `(${keyPrefix}${key} < ${valuePrefix}${key})`;
    case '$lte':
      return `(${keyPrefix}${key} <= ${valuePrefix}${key})`;
    case '$ne':
      return `(${keyPrefix}${key} <> ${valuePrefix}${key})`;
    case '$in':
      return `(${keyPrefix}${key} IN ${valuePrefix}${key})`;
    case '$nin':
      return `(${keyPrefix}${key} NOT IN ${valuePrefix}${key})`;
    default:
      return equalityString;
  }
}
<commit_msg>Made use of `constructComparisonString` in `createFilterQuery`<commit_after>import { isObject } from './util';

export const keyPrefix = '#dt';
export const valuePrefix = ':dt';

// Splits an object of query params into 2 objects
// One for any params that matches the defined table keys
// and another object for all other params
// ({id: 1, name: 'pony', interests: 'ponying'}, { id: 'N' }) -> [{id: 1}, {name: 'pony', interests: 'ponying'}]
export function splitKeysAndParams(params, tableKeys) {
  if (!isObject(params) || !isObject(tableKeys)) {
    return null;
  }

  const keys = Object.keys(tableKeys);
  const paramKeys = Object.keys(params);
  return [
    paramKeys.reduce((acc, curr) => Object.assign(acc,
      keys.includes(curr) && { [curr]: params[curr] }
    ), {}),
    paramKeys.reduce((acc, curr) => Object.assign(acc,
      !keys.includes(curr) && { [curr]: params[curr] }
    ), {})
  ];
}

export function createFilterQuery(params) {
  const paramKeys = Object.keys(params);
  return {
    FilterExpression: paramKeys.reduce((acc, key) => {
      const maybeAnd = acc === '' ? '' : ' AND '
      return `${acc}${maybeAnd}${constructComparisonString(key, params[key])}`;
    }, ''),
    ExpressionAttributeNames: paramKeys.reduce((acc, key) => {
      return Object.assign(acc, {
        [`${keyPrefix}${key}`]: key,
      });
    }, {}),
    ExpressionAttributeValues: paramKeys.reduce((acc, key) => {
      const val = params[key];
      return Object.assign(acc, {
        [`${valuePrefix}${key}`]: val,
      });
    }, {}),
  };
}

const comparisonKeys = [
  '$eq', // Matches values that are equal to a specified value. (default)
  '$gt', // Matches values that are greater than a specified value.
  '$gte', // Matches values that are greater than or equal to a specified value.
  '$lt', // Matches values that are less than a specified value.
  '$lte', // Matches values that are less than or equal to a specified value.
  '$ne', // Matches all values that are not equal to a specified value.
  '$in', // Matches any of the values specified in an array.
  '$nin', // Matches none of the values specified in an array.
];
export function constructComparisonString(key, value) {
  // If value is not an object we can return the default (equality comparison)
  const equalityString = `(${keyPrefix}${key} = ${valuePrefix}${key})`;
  if (!isObject(value)) {
    return equalityString;
  }

  const firstKey = Object.keys(value)[0];
  switch (firstKey) {
    case '$gt':
      return `(${keyPrefix}${key} > ${valuePrefix}${key})`;
    case '$gte':
      return `(${keyPrefix}${key} >= ${valuePrefix}${key})`;
    case '$lt':
      return `(${keyPrefix}${key} < ${valuePrefix}${key})`;
    case '$lte':
      return `(${keyPrefix}${key} <= ${valuePrefix}${key})`;
    case '$ne':
      return `(${keyPrefix}${key} <> ${valuePrefix}${key})`;
    case '$in':
      return `(${keyPrefix}${key} IN ${valuePrefix}${key})`;
    case '$nin':
      return `(${keyPrefix}${key} NOT IN ${valuePrefix}${key})`;
    default:
      return equalityString;
  }
}
<|endoftext|>


<commit_before>Ext.onReady(function() {
  Ext.override(Ext.Element, {
    fireEvent: function(eventName, options) {
      if (document.createEvent) {
        // dispatch for firefox + others
        var event = document.createEvent("HTMLEvents");
        event.initEvent(eventName, true, true); // event type,bubbling,cancelable
        event.data = options;
        return !this.dom.dispatchEvent(event);
      } else {
        // dispatch for IE
        var event = document.createEventObject();
        event.data = options;
        return this.dom.fireEvent('on' + eventName, event);
      }
    },

    callRemote: function() {
      var method = this.getAttribute('method') || this.getAttribute('data-method') || 'GET';
      var url    = this.getAttribute('action') || this.getAttribute('href');

      if (url === undefined) {
        throw "No URL specified for remote call (action or href must be present).";
      } else {
        this.fireEvent("ajax:before");
        var options = this.is('form') ? {form: this} : {};
        Ext.Ajax.request(Ext.apply(options, {
          url: url,
          method: method.toUpperCase(),
          scope: this,
          callback: function(options, success, response) {this.fireEvent("ajax:complete", response)},
          success: function(response) {this.fireEvent("ajax:success", response)},
          failure: function(response) {this.fireEvent("ajax:failure", response)}
        }));
        this.fireEvent("ajax:after");
      }
    }
  });

  /**
   * confirmation handler
   */
  Ext.getBody().on("click", function(event, element) {
    element = Ext.get(element);
    var message = element.getAttribute('data-confirm');
    if (confirm(message)) {
      element.set({"data-confirm-cancel": null});
    } else {
      element.set({"data-confirm-cancel": true});
      event.stopEvent();
    }
  }, this, {delegate: ':any(a|input)[data-confirm]'});

  Ext.getBody().on("click", function(event, element) {
    Ext.get(element).callRemote();
    event.preventDefault();
  }, this, {delegate: ':any(a:not([data-confirm-cancel])|input:not([data-confirm-cancel]))[data-remote]'});

  Ext.getBody().on("submit", function(event, element) {
    Ext.get(element).callRemote();
    event.preventDefault();
  }, this, {delegate: 'form[data-remote]'});

  /**
   * disable-with handlers
   */

  var disable_with_input_function = function(event, element) {
    Ext.fly(element).select('input[data-disable-with]').each(function(input) {
      input.set({'data-enable-with': input.getValue(),
                 value             : input.getAttribute('data-disable-with'),
                 disabled          : 'disabled'});
    });
  };

  Ext.getBody().on('submit', disable_with_input_function, this,
                   {delegate: 'form:has(input[data-disable-with])'});

  Ext.getBody().on('ajax:complete', function(event, element) {
    Ext.fly(element).select('input[data-disable-with]').each(function(input) {
      input.set({value             : input.getAttribute('data-enable-with'),
                 'data-enable-with': null,
                 disabled          : null});
    });
  }, this, {delegate: 'form:has(input[data-disable-with])'});
});<commit_msg>bug fix : prevent 'submit' callback execution before launching ajax request (otherwise it prevent 'ajax:before' callback)<commit_after>Ext.onReady(function() {
  Ext.override(Ext.Element, {
    fireEvent: function(eventName, options) {
      if (document.createEvent) {
        // dispatch for firefox + others
        var event = document.createEvent("HTMLEvents");
        event.initEvent(eventName, true, true); // event type,bubbling,cancelable
        event.data = options;
        return !this.dom.dispatchEvent(event);
      } else {
        // dispatch for IE
        var event = document.createEventObject();
        event.data = options;
        return this.dom.fireEvent('on' + eventName, event);
      }
    },

    callRemote: function() {
      var method = this.getAttribute('method') || this.getAttribute('data-method') || 'GET';
      var url    = this.getAttribute('action') || this.getAttribute('href');

      if (url === undefined) {
        throw "No URL specified for remote call (action or href must be present).";
      } else {
        this.fireEvent("ajax:before");
        var options = this.is('form') ? {form: this} : {};
        Ext.Ajax.request(Ext.apply(options, {
          url: url,
          method: method.toUpperCase(),
          scope: this,
          callback: function(options, success, response) {this.fireEvent("ajax:complete", response)},
          success: function(response) {this.fireEvent("ajax:success", response)},
          failure: function(response) {this.fireEvent("ajax:failure", response)}
        }));
        this.fireEvent("ajax:after");
      }
    }
  });

  /**
   * confirmation handler
   */
  Ext.getBody().on("click", function(event, element) {
    element = Ext.get(element);
    var message = element.getAttribute('data-confirm');
    if (confirm(message)) {
      element.set({"data-confirm-cancel": null});
    } else {
      element.set({"data-confirm-cancel": true});
      event.stopEvent();
    }
  }, this, {delegate: ':any(a|input)[data-confirm]'});

  /**
   * remote handlers
   */
  Ext.getBody().on("click", function(event, element) {
    event.preventDefault();
    Ext.get(element).callRemote();
  }, this, {delegate: ':any(a:not([data-confirm-cancel])|input:not([data-confirm-cancel]))[data-remote]'});

  Ext.getBody().on("submit", function(event, element) {
    event.preventDefault();
    Ext.get(element).callRemote();
  }, this, {delegate: 'form[data-remote]'});

  /**
   * disable-with handlers
   */

  var disable_with_input_function = function(event, element) {
    Ext.fly(element).select('input[data-disable-with]').each(function(input) {
      input.set({'data-enable-with': input.getValue(),
                 value             : input.getAttribute('data-disable-with'),
                 disabled          : 'disabled'});
    });
  };

  Ext.getBody().on('submit', disable_with_input_function, this,
                   {delegate: 'form:has(input[data-disable-with])'});

  Ext.getBody().on('ajax:complete', function(event, element) {
    Ext.fly(element).select('input[data-disable-with]').each(function(input) {
      input.set({value             : input.getAttribute('data-enable-with'),
                 'data-enable-with': null,
                 disabled          : null});
    });
  }, this, {delegate: 'form:has(input[data-disable-with])'});
});<|endoftext|>


<commit_before>import {
  fromGlobalId,
  connectionFromArray,
  nodeDefinitions,
  connectionDefinitions,
  connectionArgs
} from 'graphql-relay';

import {
  GraphQLList,
  GraphQLEnumType
} from 'graphql';

import {
  base64,
  unbase64,
} from './base64.js';

import _ from 'lodash';
import simplifyAST from './simplifyAST';

export class NodeTypeMapper {
  constructor() {
    this.map = { };
  }

  mapTypes(types) {
    Object.keys(types).forEach((k) => {
      let v = types[k];
      this.map[k] = v.type
        ? v
        : { type: v };
    });
  }

  item(type) {
    return this.map[type];
  }
}

export function idFetcher(sequelize, nodeTypeMapper) {
  return async (globalId, context) => {
    const {type, id} = fromGlobalId(globalId);

    const nodeType = nodeTypeMapper.item(type);
    if (nodeType && typeof nodeType.resolve === 'function') {
      const res = await Promise.resolve(nodeType.resolve(globalId, context));
      if (res) res.__graphqlType__ = type;
      return res;
    }

    const model = Object.keys(sequelize.models).find(model => model === type);
    return model
      ? sequelize.models[model].findById(id)
      : nodeType
        ? nodeType.type
        : null;
  };
}

export function typeResolver(nodeTypeMapper) {
  return obj => {
    var type = obj.__graphqlType__
               || (obj.Model
                 ? obj.Model.options.name.singular
                 : obj.name);

    if (!type) {
      throw new Error(`Unable to determine type of ${ typeof obj }. ` +
        `Either specify a resolve function in 'NodeTypeMapper' object, or specify '__graphqlType__' property on object.`);
    }

    const nodeType = nodeTypeMapper.item(type);
    return nodeType && nodeType.type || null;
  };
}

export function isConnection(type) {
  return typeof type.name !== 'undefined' && type.name.endsWith('Connection');
}

export function handleConnection(values, args) {
  return connectionFromArray(values, args);
}

export function sequelizeNodeInterface(sequelize) {
  let nodeTypeMapper = new NodeTypeMapper();
  const nodeObjects = nodeDefinitions(
    idFetcher(sequelize, nodeTypeMapper),
    typeResolver(nodeTypeMapper)
  );

  return {
    nodeTypeMapper,
    ...nodeObjects
  };
}

export function nodeType(connectionType) {
  return connectionType._fields.edges.type.ofType._fields.node.type;
}

export function sequelizeConnection({
  name,
  nodeType,
  target,
  orderBy: orderByEnum,
  before,
  after,
  connectionFields,
  edgeFields,
  where
}) {
  const {
    edgeType,
    connectionType
  } = connectionDefinitions({
    name,
    nodeType,
    connectionFields,
    edgeFields
  });

  const model = target.target ? target.target : target;
  const SEPERATOR = '$';
  const PREFIX = 'arrayconnection' + SEPERATOR;

  if (orderByEnum === undefined) {
    orderByEnum = new GraphQLEnumType({
      name: name + 'ConnectionOrder',
      values: {
        ID: {value: [model.primaryKeyAttribute, 'ASC']}
      }
    });
  }

  before = before || ((options) => options);
  after = after || ((result) => result);

  let $connectionArgs = {
    ...connectionArgs,
    orderBy: {
      type: new GraphQLList(orderByEnum)
    }
  };

  let orderByAttribute = function (orderAttr, {source, args, context, info}) {
    return typeof orderAttr === 'function' ? orderAttr(source, args, context, info) : orderAttr;
  };

  let orderByDirection = function (orderDirection, args) {
    if (args.last) {
      return orderDirection.indexOf('ASC') >= 0
              ? orderDirection.replace('ASC', 'DESC')
              : orderDirection.replace('DESC', 'ASC');
    }
    return orderDirection;
  };

  /**
   * Creates a cursor given a item returned from the Database
   * @param  {Object}   item   sequelize model instance
   * @param  {Integer}  index  the index of this item within the results, 0 indexed
   * @return {String}          The Base64 encoded cursor string
   */
  let toCursor = function (item, index) {
    let id = item.get(model.primaryKeyAttribute);
    return base64(PREFIX + id + SEPERATOR + index);
  };

  /**
   * Decode a cursor into its component parts
   * @param  {String} cursor Base64 encoded cursor
   * @return {Object}        Object containing ID and index
   */
  let fromCursor = function (cursor) {
    cursor = unbase64(cursor);
    cursor = cursor.substring(PREFIX.length, cursor.length);
    let [id, index] = cursor.split(SEPERATOR);

    return {
      id,
      index
    };
  };

  let argsToWhere = function (args) {
    let result = {};

    _.each(args, (value, key) => {
      if (key in $connectionArgs) return;
      _.assign(result, where(key, value));
    });

    return result;
  };

  let resolveEdge = function (item, index, queriedCursor, args = {}, source) {
    let startIndex = null;
    if (queriedCursor) startIndex = Number(queriedCursor.index);
    if (startIndex !== null) {
      startIndex++;
    } else {
      startIndex = 0;
    }

    return {
      cursor: toCursor(item, index + startIndex),
      node: item,
      source: source
    };
  };

  let $resolver = require('./resolver')(target, {
    handleConnection: false,
    list: true,
    before: function (options, args, context, info) {
      if (args.first || args.last) {
        options.limit = parseInt(args.first || args.last, 10);
      }
      if (!args.orderBy) {
        args.orderBy = [orderByEnum._values[0].value];
      } else if (typeof args.orderBy === 'string') {
        args.orderBy = [orderByEnum._nameLookup[args.orderBy].value];
      }

      let orderBy = args.orderBy;
      let orderAttribute = orderByAttribute(orderBy[0][0], {
        source: info.source,
        args,
        context,
        info
      });
      let orderDirection = orderByDirection(orderBy[0][1], args);

      options.order = [
        [orderAttribute, orderDirection]
      ];

      if (orderAttribute !== model.primaryKeyAttribute) {
        options.order.push([model.primaryKeyAttribute, orderByDirection('ASC', args)]);
      }

      if (typeof orderAttribute === 'string') {
        options.attributes.push(orderAttribute);
      }

      if (options.limit && !options.attributes.some(attribute => attribute.length === 2 && attribute[1] === 'full_count')) {
        if (model.sequelize.dialect.name === 'postgres') {
          options.attributes.push([
            model.sequelize.literal('COUNT(*) OVER()'),
            'full_count'
          ]);
        } else if (model.sequelize.dialect.name === 'mssql') {
          options.attributes.push([
            model.sequelize.literal('COUNT(1) OVER()'),
            'full_count'
          ]);
        }
      }

      options.where = argsToWhere(args);

      if (args.after || args.before) {
        let cursor = fromCursor(args.after || args.before);
        let startIndex = Number(cursor.index);

        if (startIndex >= 0) options.offset = startIndex + 1;
      }
      options.attributes = _.uniq(options.attributes);
      return before(options, args, context, info);
    },
    after: async function (values, args, context, info) {
      const {
        source,
      } = info;

      var cursor = null;

      if (args.after || args.before) {
        cursor = fromCursor(args.after || args.before);
      }

      let edges = values.map((value, idx) => {
        return resolveEdge(value, idx, cursor, args, source);
      });

      let firstEdge = edges[0];
      let lastEdge = edges[edges.length - 1];
      let fullCount = values[0] && values[0].dataValues.full_count && parseInt(values[0].dataValues.full_count, 10);

      if (!values[0]) {
        fullCount = 0;
      }

      if ((args.first || args.last) && (fullCount === null || fullCount === undefined)) {
        // In case of `OVER()` is not available, we need to get the full count from a second query.
        const options = await Promise.resolve(before({
          where: argsToWhere(args)
        }, args, context, info));

        if (target.count) {
          if (target.associationType) {
            fullCount = await target.count(source, options);
          } else {
            fullCount = await target.count(options);
          }
        } else {
          fullCount = await target.manyFromSource.count(source, options);
        }
      }

      let hasNextPage = false;
      let hasPreviousPage = false;
      if (args.first || args.last) {
        const count = parseInt(args.first || args.last, 10);
        let index = cursor ? Number(cursor.index) : null;
        if (index !== null) {
          index++;
        } else {
          index = 0;
        }

        hasNextPage = index + 1 + count <= fullCount;
        hasPreviousPage = index - count >= 0;

        if (args.last) {
          [hasNextPage, hasPreviousPage] = [hasPreviousPage, hasNextPage];
        }
      }

      return after({
        source,
        args,
        where: argsToWhere(args),
        edges,
        pageInfo: {
          startCursor: firstEdge ? firstEdge.cursor : null,
          endCursor: lastEdge ? lastEdge.cursor : null,
          hasNextPage: hasNextPage,
          hasPreviousPage: hasPreviousPage
        }
      });
    }
  });

  let resolver = (source, args, context, info) => {
    if (simplifyAST(info.fieldASTs[0], info).fields.edges) {
      return $resolver(source, args, context, info);
    }

    return {
      source,
      args,
      where: argsToWhere(args)
    };
  };

  return {
    connectionType,
    edgeType,
    nodeType,
    resolveEdge,
    connectionArgs: $connectionArgs,
    resolve: resolver
  };
}
<commit_msg>chore(package): update graphql to version 0.8.2 (#383)<commit_after>import {
  fromGlobalId,
  connectionFromArray,
  nodeDefinitions,
  connectionDefinitions,
  connectionArgs
} from 'graphql-relay';

import {
  GraphQLList,
  GraphQLEnumType
} from 'graphql';

import {
  base64,
  unbase64,
} from './base64.js';

import _ from 'lodash';
import simplifyAST from './simplifyAST';

export class NodeTypeMapper {
  constructor() {
    this.map = { };
  }

  mapTypes(types) {
    Object.keys(types).forEach((k) => {
      let v = types[k];
      this.map[k] = v.type
        ? v
        : { type: v };
    });
  }

  item(type) {
    return this.map[type];
  }
}

export function idFetcher(sequelize, nodeTypeMapper) {
  return async (globalId, context) => {
    const {type, id} = fromGlobalId(globalId);

    const nodeType = nodeTypeMapper.item(type);
    if (nodeType && typeof nodeType.resolve === 'function') {
      const res = await Promise.resolve(nodeType.resolve(globalId, context));
      if (res) res.__graphqlType__ = type;
      return res;
    }

    const model = Object.keys(sequelize.models).find(model => model === type);
    return model
      ? sequelize.models[model].findById(id)
      : nodeType
        ? nodeType.type
        : null;
  };
}

export function typeResolver(nodeTypeMapper) {
  return obj => {
    var type = obj.__graphqlType__
               || (obj.Model
                 ? obj.Model.options.name.singular
                 : obj.name);

    if (!type) {
      throw new Error(`Unable to determine type of ${ typeof obj }. ` +
        `Either specify a resolve function in 'NodeTypeMapper' object, or specify '__graphqlType__' property on object.`);
    }

    const nodeType = nodeTypeMapper.item(type);
    return nodeType && nodeType.type || null;
  };
}

export function isConnection(type) {
  return typeof type.name !== 'undefined' && type.name.endsWith('Connection');
}

export function handleConnection(values, args) {
  return connectionFromArray(values, args);
}

export function sequelizeNodeInterface(sequelize) {
  let nodeTypeMapper = new NodeTypeMapper();
  const nodeObjects = nodeDefinitions(
    idFetcher(sequelize, nodeTypeMapper),
    typeResolver(nodeTypeMapper)
  );

  return {
    nodeTypeMapper,
    ...nodeObjects
  };
}

export function nodeType(connectionType) {
  return connectionType._fields.edges.type.ofType._fields.node.type;
}

export function sequelizeConnection({
  name,
  nodeType,
  target,
  orderBy: orderByEnum,
  before,
  after,
  connectionFields,
  edgeFields,
  where
}) {
  const {
    edgeType,
    connectionType
  } = connectionDefinitions({
    name,
    nodeType,
    connectionFields,
    edgeFields
  });

  const model = target.target ? target.target : target;
  const SEPERATOR = '$';
  const PREFIX = 'arrayconnection' + SEPERATOR;

  if (orderByEnum === undefined) {
    orderByEnum = new GraphQLEnumType({
      name: name + 'ConnectionOrder',
      values: {
        ID: {value: [model.primaryKeyAttribute, 'ASC']}
      }
    });
  }

  before = before || ((options) => options);
  after = after || ((result) => result);

  let $connectionArgs = {
    ...connectionArgs,
    orderBy: {
      type: new GraphQLList(orderByEnum)
    }
  };

  let orderByAttribute = function (orderAttr, {source, args, context, info}) {
    return typeof orderAttr === 'function' ? orderAttr(source, args, context, info) : orderAttr;
  };

  let orderByDirection = function (orderDirection, args) {
    if (args.last) {
      return orderDirection.indexOf('ASC') >= 0
              ? orderDirection.replace('ASC', 'DESC')
              : orderDirection.replace('DESC', 'ASC');
    }
    return orderDirection;
  };

  /**
   * Creates a cursor given a item returned from the Database
   * @param  {Object}   item   sequelize model instance
   * @param  {Integer}  index  the index of this item within the results, 0 indexed
   * @return {String}          The Base64 encoded cursor string
   */
  let toCursor = function (item, index) {
    let id = item.get(model.primaryKeyAttribute);
    return base64(PREFIX + id + SEPERATOR + index);
  };

  /**
   * Decode a cursor into its component parts
   * @param  {String} cursor Base64 encoded cursor
   * @return {Object}        Object containing ID and index
   */
  let fromCursor = function (cursor) {
    cursor = unbase64(cursor);
    cursor = cursor.substring(PREFIX.length, cursor.length);
    let [id, index] = cursor.split(SEPERATOR);

    return {
      id,
      index
    };
  };

  let argsToWhere = function (args) {
    let result = {};

    _.each(args, (value, key) => {
      if (key in $connectionArgs) return;
      _.assign(result, where(key, value));
    });

    return result;
  };

  let resolveEdge = function (item, index, queriedCursor, args = {}, source) {
    let startIndex = null;
    if (queriedCursor) startIndex = Number(queriedCursor.index);
    if (startIndex !== null) {
      startIndex++;
    } else {
      startIndex = 0;
    }

    return {
      cursor: toCursor(item, index + startIndex),
      node: item,
      source: source
    };
  };

  let $resolver = require('./resolver')(target, {
    handleConnection: false,
    list: true,
    before: function (options, args, context, info) {
      if (args.first || args.last) {
        options.limit = parseInt(args.first || args.last, 10);
      }
      if (!args.orderBy) {
        args.orderBy = [orderByEnum._values[0].value];
      } else if (typeof args.orderBy === 'string') {
        args.orderBy = [orderByEnum._nameLookup[args.orderBy].value];
      }

      let orderBy = args.orderBy;
      let orderAttribute = orderByAttribute(orderBy[0][0], {
        source: info.source,
        args,
        context,
        info
      });
      let orderDirection = orderByDirection(orderBy[0][1], args);

      options.order = [
        [orderAttribute, orderDirection]
      ];

      if (orderAttribute !== model.primaryKeyAttribute) {
        options.order.push([model.primaryKeyAttribute, orderByDirection('ASC', args)]);
      }

      if (typeof orderAttribute === 'string') {
        options.attributes.push(orderAttribute);
      }

      if (options.limit && !options.attributes.some(attribute => attribute.length === 2 && attribute[1] === 'full_count')) {
        if (model.sequelize.dialect.name === 'postgres') {
          options.attributes.push([
            model.sequelize.literal('COUNT(*) OVER()'),
            'full_count'
          ]);
        } else if (model.sequelize.dialect.name === 'mssql') {
          options.attributes.push([
            model.sequelize.literal('COUNT(1) OVER()'),
            'full_count'
          ]);
        }
      }

      options.where = argsToWhere(args);

      if (args.after || args.before) {
        let cursor = fromCursor(args.after || args.before);
        let startIndex = Number(cursor.index);

        if (startIndex >= 0) options.offset = startIndex + 1;
      }
      options.attributes = _.uniq(options.attributes);
      return before(options, args, context, info);
    },
    after: async function (values, args, context, info) {
      const {
        source,
      } = info;

      var cursor = null;

      if (args.after || args.before) {
        cursor = fromCursor(args.after || args.before);
      }

      let edges = values.map((value, idx) => {
        return resolveEdge(value, idx, cursor, args, source);
      });

      let firstEdge = edges[0];
      let lastEdge = edges[edges.length - 1];
      let fullCount = values[0] && values[0].dataValues.full_count && parseInt(values[0].dataValues.full_count, 10);

      if (!values[0]) {
        fullCount = 0;
      }

      if ((args.first || args.last) && (fullCount === null || fullCount === undefined)) {
        // In case of `OVER()` is not available, we need to get the full count from a second query.
        const options = await Promise.resolve(before({
          where: argsToWhere(args)
        }, args, context, info));

        if (target.count) {
          if (target.associationType) {
            fullCount = await target.count(source, options);
          } else {
            fullCount = await target.count(options);
          }
        } else {
          fullCount = await target.manyFromSource.count(source, options);
        }
      }

      let hasNextPage = false;
      let hasPreviousPage = false;
      if (args.first || args.last) {
        const count = parseInt(args.first || args.last, 10);
        let index = cursor ? Number(cursor.index) : null;
        if (index !== null) {
          index++;
        } else {
          index = 0;
        }

        hasNextPage = index + 1 + count <= fullCount;
        hasPreviousPage = index - count >= 0;

        if (args.last) {
          [hasNextPage, hasPreviousPage] = [hasPreviousPage, hasNextPage];
        }
      }

      return after({
        source,
        args,
        where: argsToWhere(args),
        edges,
        pageInfo: {
          startCursor: firstEdge ? firstEdge.cursor : null,
          endCursor: lastEdge ? lastEdge.cursor : null,
          hasNextPage: hasNextPage,
          hasPreviousPage: hasPreviousPage
        }
      });
    }
  });

  let resolver = (source, args, context, info) => {
    var fieldNodes = info.fieldASTs || info.fieldNodes;
    if (simplifyAST(fieldNodes[0], info).fields.edges) {
      return $resolver(source, args, context, info);
    }

    return {
      source,
      args,
      where: argsToWhere(args)
    };
  };

  return {
    connectionType,
    edgeType,
    nodeType,
    resolveEdge,
    connectionArgs: $connectionArgs,
    resolve: resolver
  };
}
<|endoftext|>


<commit_before>//= require callback

if ("undefined" == typeof com) { var com = {}; }
if (!com.jivatechnology) { com.jivatechnology = {}; }

// this module function is called with com.jivatechnology as 'this'
(function(){

  var CallbackList = com.jivatechnology.CallbackList;

  var scope = this;

  this.Retry = (function() {

    // Private class level objects
    var merge_options = function(obj1,obj2){
      obj1 = obj1 || {};
      obj2 = obj2 || {};
      var obj3 = {};
      for (var attr1 in obj1) {
        if( obj1.hasOwnProperty(attr1) ){ obj3[attr1] = obj1[attr1]; }
      }
      for (var attr2 in obj2) {
        if( obj2.hasOwnProperty(attr2) ){ obj3[attr2] = obj2[attr2]; }
      }
      return obj3;
    };

    var create_getter_setter = function(options,name){
      return function(){
        if( arguments.length == 1 ){
          // Setter
          options[name] = arguments[0];
          return options[name];
        } else {
          // Getter
          return options[name];
        }
      };
    };

    var check_options = function(options){
      if( typeof options.func      != "function"  ){ throw "func must be set to a function"; }
      if( typeof options.fallback  != "function"  ){ throw "fallback must be set to a function"; }

      if( typeof options.interval  == "undefined" ){ throw "interval cannot be undefined"; }
      if( typeof options.max_tries != "number"    ){ throw "max_tries must be a number"; }
      if( typeof options.timeout   != "number"    ){ throw "timeout must be a number"; }
    };

    // Return the constructor
    return function(opts) {

      var that = this;

      var defaults = {
        max_tries: 10,
        interval:  1000,
        timeout:   32000,
        fallback:  scope.Retry.Fallbacks.Constant
      };

      var options = merge_options(defaults,opts);

      // Run the function
      var attempt = 0;
      var execute = function(){
        attempt++;
        try {
          create_timeout();
          that.func().call(that);
        } catch (err) {
          that.failure(err);
        }
      };

      // Monitor function has not timed out

      var timeout;
      var create_timeout = function(){
        if(!timeout){
          setTimeout(
            function(){ that.failure("timeout"); },
            that.timeout()
          );
        }
      };

      var clear_timeout = function(){
        clearTimeout(timeout);
      };

      // Retry logic

      var can_retry = function(){
        return attempt < that.max_tries();
      };

      var retry;
      var schedule_retry = function(){
        if(!retry){
          retry = setTimeout(function(){
            retry = null;
            execute();
          }, wait());
        }
      };

      // Calculate earliest to retry

      var wait = function(){
        try {
          var value = that.fallback().call(that);
          if(typeof value == "number" && value >= 0){
            return value;
          } else {
            that.failure("fallback returned invalid value",false);
          }
        } catch (err) {
          that.failure(err,false);
        }
      };

      // Simple state tracking

      var state = "ready";
      var is_ready = function(){
        return state == "ready";
      };

      var complete = function(){
        state = "completed";
      };

      // Privileged methods

      this.failure = function(err,retry){
        if(typeof retry == "undefined"){ retry = true; }

        if(is_ready()){
          if(retry && can_retry()){
            clear_timeout();
            schedule_retry();
          } else {
            that.onFailure.handle();
            complete();
          }
        }
      };

      this.success = function(){
        if(is_ready()){
          clear_timeout();
          that.onSuccess.handle();
          complete();
        }
      };

      this.run = function(){
        check_options(options);
        if(can_retry()){
          execute();
        } else {
          failure();
        }
      };

      this.max_tries = create_getter_setter(options,"max_tries");
      this.interval  = create_getter_setter(options,"interval");
      this.timeout   = create_getter_setter(options,"timeout");
      this.fallback  = create_getter_setter(options,"fallback");
      this.func      = create_getter_setter(options,"func");
      this.onSuccess = new CallbackList(options.onSuccess || []);
      this.onFailure = new CallbackList(options.onFailure || []);
      this.attempt   = function(){ return attempt; };

    };

  })();

  this.Retry.Fallbacks = {};
  this.Retry.Fallbacks.Constant = function(){
    return this.interval();
  };

  this.Retry.Fallbacks.Fibonacci = function(){
    if(typeof this.last1 != "number"){ this.last1 = this.interval(); }
    if(typeof this.last2 != "number"){ this.last2 = 0; }

    var value = this.last1 + this.last2;
    this.last2 = this.last1;
    this.last1 = value;

    return value;
  };

}).call(com.jivatechnology);
<commit_msg>Fix: Timeout checking was not being cleared properly<commit_after>//= require callback

if ("undefined" == typeof com) { var com = {}; }
if (!com.jivatechnology) { com.jivatechnology = {}; }

// this module function is called with com.jivatechnology as 'this'
(function(){

  var CallbackList = com.jivatechnology.CallbackList;

  var scope = this;

  this.Retry = (function() {

    // Private class level objects
    var merge_options = function(obj1,obj2){
      obj1 = obj1 || {};
      obj2 = obj2 || {};
      var obj3 = {};
      for (var attr1 in obj1) {
        if( obj1.hasOwnProperty(attr1) ){ obj3[attr1] = obj1[attr1]; }
      }
      for (var attr2 in obj2) {
        if( obj2.hasOwnProperty(attr2) ){ obj3[attr2] = obj2[attr2]; }
      }
      return obj3;
    };

    var create_getter_setter = function(options,name){
      return function(){
        if( arguments.length == 1 ){
          // Setter
          options[name] = arguments[0];
          return options[name];
        } else {
          // Getter
          return options[name];
        }
      };
    };

    var check_options = function(options){
      if( typeof options.func      != "function"  ){ throw "func must be set to a function"; }
      if( typeof options.fallback  != "function"  ){ throw "fallback must be set to a function"; }

      if( typeof options.interval  == "undefined" ){ throw "interval cannot be undefined"; }
      if( typeof options.max_tries != "number"    ){ throw "max_tries must be a number"; }
      if( typeof options.timeout   != "number"    ){ throw "timeout must be a number"; }
    };

    // Return the constructor
    return function(opts) {

      var that = this;

      var defaults = {
        max_tries: 10,
        interval:  1000,
        timeout:   32000,
        fallback:  scope.Retry.Fallbacks.Constant
      };

      var options = merge_options(defaults,opts);

      // Run the function
      var attempt = 0;
      var execute = function(){
        attempt++;
        try {
          create_timeout();
          that.func().call(that);
        } catch (err) {
          that.failure(err);
        }
      };

      // Monitor function has not timed out

      var timeout;
      var create_timeout = function(){
        if(!timeout){
          timeout = setTimeout(
            function(){ that.failure("timeout"); },
            that.timeout()
          );
        }
      };

      var clear_timeout = function(){
        clearTimeout(timeout);
        timeout = null;
      };

      // Retry logic

      var can_retry = function(){
        return attempt < that.max_tries();
      };

      var retry;
      var schedule_retry = function(){
        if(!retry){
          retry = setTimeout(function(){
            retry = null;
            execute();
          }, wait());
        }
      };

      // Calculate earliest to retry

      var wait = function(){
        try {
          var value = that.fallback().call(that);
          if(typeof value == "number" && value >= 0){
            return value;
          } else {
            that.failure("fallback returned invalid value",false);
          }
        } catch (err) {
          that.failure(err,false);
        }
      };

      // Simple state tracking

      var state = "ready";
      var is_ready = function(){
        return state == "ready";
      };

      var complete = function(){
        state = "completed";
      };

      // Privileged methods

      this.failure = function(err,retry){
        if(typeof retry == "undefined"){ retry = true; }

        if(is_ready()){
          if(retry && can_retry()){
            clear_timeout();
            schedule_retry();
          } else {
            that.onFailure.handle();
            complete();
          }
        }
      };

      this.success = function(){
        if(is_ready()){
          clear_timeout();
          that.onSuccess.handle();
          complete();
        }
      };

      this.run = function(){
        check_options(options);
        if(can_retry()){
          execute();
        } else {
          failure();
        }
      };

      this.max_tries = create_getter_setter(options,"max_tries");
      this.interval  = create_getter_setter(options,"interval");
      this.timeout   = create_getter_setter(options,"timeout");
      this.fallback  = create_getter_setter(options,"fallback");
      this.func      = create_getter_setter(options,"func");
      this.onSuccess = new CallbackList(options.onSuccess || []);
      this.onFailure = new CallbackList(options.onFailure || []);
      this.attempt   = function(){ return attempt; };

    };

  })();

  this.Retry.Fallbacks = {};
  this.Retry.Fallbacks.Constant = function(){
    return this.interval();
  };

  this.Retry.Fallbacks.Fibonacci = function(){
    if(typeof this.last1 != "number"){ this.last1 = this.interval(); }
    if(typeof this.last2 != "number"){ this.last2 = 0; }

    var value = this.last1 + this.last2;
    this.last2 = this.last1;
    this.last1 = value;

    return value;
  };

}).call(com.jivatechnology);
<|endoftext|>


<commit_before>// This file should not be pushed to the repo, just added here in order
// to be able to test this thing..

// @todo figure out how to do this properly..
var cb = require('./couchbase.js');

// Create a new instance of the couchbase
var bucket = cb.create({
    hosts : [ "localhost:9000" ],
    bucket : "default",
    password : "",
    user : ""
});

console.log("THe couchbase object looks like:\n", bucket);

bucket.on("error", function() {
    console.log("An unrecoverable error occurred. Terminate the couchbase bucket connection and retry");
    process.exit(1);
});

bucket.on("connect", function() {
    // At this time you know you're connected and you may reset the
    // error handler to something else..
    console.log("yay.. connected");

    bucket.get("foo", function(error, doc, meta) {
	if (error) {
            console.log("Object not found", meta);
	} else {
            console.log("found object: ", meta, doc);
	}
    });

    bucket.get([ "foo", "bar" ], function(error, doc, meta) {
	if (error) {
            console.log("Object not found", meta);
	} else {
            console.log("found object: ", meta, doc);
	}
    });

    bucket.set("foo", "bar", function(error, meta) {
	if (error) {
            console.log("Store failed: ", meta);
	} else {
            console.log("Store success ", meta);
	    bucket.set("foo", "bar2", meta, function(error, meta) {
		if (error) {
		    console.log("cas oper failed");
                } else {
		    console.log("cas oper success");
		    bucket.delete("foo", function(error, id) {
			if (error) {
			    console.log("Failed to delete ", id);
			} else {
			    console.log("Deleted ", id);

			    bucket.get([ "foo", "bar" ], function(error, doc, meta) {
				if (error) {
				    console.log("Object not found", meta);
				} else {
				    console.log("found object: ", meta, doc);
				}
			    });
			}
		    });
		}
	    });
	}
    });
});
<commit_msg>Remove obsolete file<commit_after><|endoftext|>


<commit_before>// Copyright 2012, Juan Soldi
// Licensed under the MIT license.
//
// Requres jQuery
// https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

var O = {

    EscapeRegExp: function (text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    },

    Override: function (obj1, obj2) {
        if ($.isPlainObject(obj2)) return $.extend(true, {}, obj1, obj2);
        else if ($.isArray(obj2)) return $.extend(true, [], obj1, obj2);
        else return obj2;
    },

    GetDefaultFunc: function (data) {
        /// <summary>
        /// Gets the default function ignoring the function in the data.
        /// </summary>
        if (typeof data !== 'undefined') {
            if ($.isArray(data) && this.attr('data-o')) return O.Each;
            else if (!this.find('*[data-o]').length) return O.Leaf;
            else return O.Container;
        }
        else {
            if (this.find('*[data-o]').length) return O.Container;
            else return O.Leaf;
        }
        return O.Auto;
    },

    GetFunc: function (data) {
        /// <summary>
        /// Gets the default function or the function in the data if any.
        /// </summary>
        return this.data('o-func') || O.GetDefaultFunc.apply(this, [data]);
    },

    ResolveExpressions: function (text, data, encode) {
        if (text) {
            var reg = "\\[(.*?)\\]";
            var matches = text.match(new RegExp(reg, 'g'));
            if (matches) {
                var exps = [];
                for (var i = 0; i < matches.length; i++) {
                    var match = matches[i];
                    var o = data;
                    var exp = match.substring(1, match.length - 1);
                    var result = eval(exp);
                    var esc = O.EscapeRegExp(exp);
                    var reg = "\\[" + esc + "\\]";
                    text = text.replace(new RegExp(reg, 'g'), encode ? encodeURIComponent(result) : result);
                }
            }
        }
        return text;
    },

    ResolveExpression: function ($elem, getExp, setExp, isUri, dataKey, data) {
        if (!$elem.data(dataKey)) $elem.data(dataKey, getExp());
        var text = $elem.data(dataKey);
        var resolved = O.ResolveExpressions(text, data, isUri);
        setExp(resolved);
    },

    ResolveAttribute: function ($elem, attrName, isUri, data) {
        O.ResolveExpression(
            $elem,
            function () { return $elem.attr(attrName); },
            function (val) { return $elem.attr(attrName, val); },
            isUri,
            'o-readonly-orig-attr-' + attrName,
            data
        );
    },

    ResolveText: function ($elem, data) {
        O.ResolveExpression(
            $elem,
            function () { return $elem.text(); },
            function (val) { return $elem.text(val); },
            false,
            'o-readonly-orig-text',
            data
        );
    },

    Leaf: function (data) {
        if (typeof data !== 'undefined') {
            //            if (this.children().length) {
            //                this.data('o-readonly-data', data);
            //                this.find('*').each(function () {
            //                    O.Leaf.apply($(this), [data]);
            //                });
            //            }
            //            else {
            switch (this.get(0).nodeName.toUpperCase()) {
                case 'INPUT':
                    var type = this.attr('type');
                    if (type && type.toLowerCase() == 'checkbox') {
                        if (data) this.attr('checked', 'checked');
                        else this.removeAttr('checked');
                    }
                    else this.val(data);
                    break;
                case 'A':
                    this.data('o-readonly-data', data);
                    O.ResolveAttribute(this, 'href', true, data);
                    O.ResolveText(this, data);
                    break;
                case 'BUTTON':
                    this.data('o-readonly-data', data);
                    O.ResolveAttribute(this, 'onclick', false, data);
                    break;
                case 'TEXTAREA':
                    this.val(data);
                    break;
                case 'SELECT':
                    if ($.isArray(data)) {
                        this.empty();
                        for (var i = 0; i < data.length; i++) {
                            var $opt = $('<option>');
                            $opt.val(data[i]);
                            $opt.text(data[i]);
                            $(this).append($opt);
                        }
                    }
                    else if ($.isPlainObject(data)) {
                        this.empty();
                        for (var id in data) {
                            var $opt = $('<option>');
                            $opt.val(id);
                            $opt.text(data[id]);
                            $(this).append($opt);
                        }
                    }
                    else this.val(data);
                    break;
                case 'OPTION':
                    this.val(data);
                    O.ResolveText(this, data);
                    break;
                default:
                    this.data('o-readonly-data', data);
                    O.ResolveText(this, data);
                    break;
            }
            //            }
        }
        else {
            switch (this.get(0).nodeName.toUpperCase()) {
                case 'INPUT':
                    var type = this.attr('type');
                    if (type && type.toLowerCase() == 'checkbox') {
                        return this.attr('checked');
                    }
                    else return this.val();
                case 'TEXTAREA':
                    return this.val();
                case 'SELECT':
                    return this.val();
                case 'OPTION':
                    return this.val();
                case 'A':
                case 'BUTTON':
                default:
                    return this.data('o-readonly-data');
            }
        }
    },

    Each: function (data) {
        if (typeof data === 'undefined') return [];
        else {
            var expression = this.attr('data-o');
            this.parent().children().each(function () {
                var $this = $(this);
                if ($this.data('o-parent') == expression) $this.remove();
            });
            var $last = this;
            oFunc = this.data('o-func');
            this.removeData('o-func');
            this.removeAttr('data-o');

            for (var i = 0; i < data.length; i++) {
                var $clone = this.clone(true, true);

                var innerFunc = $clone.data('o-clone-func');
                if (innerFunc) {
                    $clone.data('o-func', innerFunc);
                    $clone.removeData('o-clone-func');
                }

                $clone.removeAttr('id');
                $clone.show();
                O.Auto.apply($clone, [data[i]]);
                $clone.data('o-parent', expression);
                $clone.attr('data-o', expression + "[" + i + "]");
                $clone.insertAfter($last);
                $last = $clone;
            }
            this.data('o-func', oFunc);
            this.attr('data-o', expression);
            this.hide();
        }
    },

    Container: function (data) {
        var o;
        if (typeof data === 'undefined') o = {};
        else o = data;
        this.find('[data-o]').not(this.find('[data-o] [data-o]')).each(function () {
            var $this = $(this);
            var expression = $this.attr('data-o') || "o";
            if (typeof data === 'undefined') {
                var part = O.Auto.apply($this);
                if (typeof part !== 'undefined') {
                    var old_o = o;
                    eval(expression + " = part");
                    o = O.Override(old_o, o);
                }
            }
            else O.Auto.apply($this, [eval(expression)]);
        });
        return o;
    },

    Auto: function (data) {
        /// <summary>
        /// Calls the default function or the function in the data if any. Also, assigns the called function to the data.
        /// Doing "return O.Auto.apply($elem, [data]);" is equivalent to doing "return $elem.o(data)".
        /// </summary>
        var func = O.GetFunc.apply(this, [data]);
        if (func != O.Auto) {
            this.data('o-func', func);
            return func.apply(this, [data]);
        }
    },

    CallDefault: function (data) {
        /// <summary>
        /// Calls the default function for this element without assigning any function and ignoring the function in the data.
        /// The actual default is O.Auto. Use this only to ignore the function in the data.
        /// Must be called like "return O.CallDefault.apply(this, [data]);"
        /// </summary>
        var func = O.GetDefaultFunc.apply(this, [data]);
        if (func != O.CallDefault) return func.apply(this, [data]);
    }
}

$.fn.o = function (data) {
    /// <summary>
    /// If data is passed, assigns the data to the child elements starting from this element. If not, reads the data from the elements.
    /// To have an element use a custom function, assign the function to the 'o-func' jQuery data of the element. This function will
    /// take a data parameter and the "this" pointer will point to the jQuery selector for the element. If data is undefined, it must
    /// return the "o" data of the element, otherwise, it must assign data to the element. If the function returns undefined when
    /// reading, the result will not be added to the final resulting object.
    /// </summary>
        return O.Auto.apply($(this), [data]);
}
<commit_msg>More cleanup<commit_after>// Copyright 2012, Juan Soldi
// Licensed under the MIT license.
//
// Requres jQuery
// https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js

var O = {

    EscapeRegExp: function (text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    },

    Override: function (obj1, obj2) {
        if ($.isPlainObject(obj2)) return $.extend(true, {}, obj1, obj2);
        else if ($.isArray(obj2)) return $.extend(true, [], obj1, obj2);
        else return obj2;
    },

    GetDefaultFunc: function (data) {
        /// <summary>
        /// Gets the default function ignoring the function in the data.
        /// </summary>
        if (typeof data !== 'undefined') {
            if ($.isArray(data) && this.attr('data-o')) return O.Each;
            else if (!this.find('*[data-o]').length) return O.Leaf;
            else return O.Container;
        }
        else {
            if (this.find('*[data-o]').length) return O.Container;
            else return O.Leaf;
        }
        return O.Auto;
    },

    GetFunc: function (data) {
        /// <summary>
        /// Gets the default function or the function in the data if any.
        /// </summary>
        return this.data('o-func') || O.GetDefaultFunc.apply(this, [data]);
    },

    ResolveExpressions: function (text, data, encode) {
        if (text) {
            var reg = "\\[(.*?)\\]";
            var matches = text.match(new RegExp(reg, 'g'));
            if (matches) {
                var exps = [];
                for (var i = 0; i < matches.length; i++) {
                    var match = matches[i];
                    var o = data;
                    var exp = match.substring(1, match.length - 1);
                    var result = eval(exp);
                    var esc = O.EscapeRegExp(exp);
                    var reg = "\\[" + esc + "\\]";
                    text = text.replace(new RegExp(reg, 'g'), encode ? encodeURIComponent(result) : result);
                }
            }
        }
        return text;
    },

    ResolveExpression: function ($elem, getExp, setExp, isUri, dataKey, data) {
        if (!$elem.data(dataKey)) $elem.data(dataKey, getExp());
        var text = $elem.data(dataKey);
        var resolved = O.ResolveExpressions(text, data, isUri);
        setExp(resolved);
    },

    ResolveAttribute: function ($elem, attrName, isUri, data) {
        O.ResolveExpression(
            $elem,
            function () { return $elem.attr(attrName); },
            function (val) { return $elem.attr(attrName, val); },
            isUri,
            'o-readonly-orig-attr-' + attrName,
            data
        );
    },

    ResolveText: function ($elem, data) {
        O.ResolveExpression(
            $elem,
            function () { return $elem.text(); },
            function (val) { return $elem.text(val); },
            false,
            'o-readonly-orig-text',
            data
        );
    },

    Leaf: function (data) {
        if (typeof data !== 'undefined') {
            switch (this.get(0).nodeName.toUpperCase()) {
                case 'INPUT':
                    var type = this.attr('type');
                    if (type && type.toLowerCase() == 'checkbox') {
                        if (data) this.attr('checked', 'checked');
                        else this.removeAttr('checked');
                    }
                    else this.val(data);
                    break;
                case 'A':
                    this.data('o-readonly-data', data);
                    O.ResolveAttribute(this, 'href', true, data);
                    O.ResolveText(this, data);
                    break;
                case 'BUTTON':
                    this.data('o-readonly-data', data);
                    O.ResolveAttribute(this, 'onclick', false, data);
                    break;
                case 'TEXTAREA':
                    this.val(data);
                    break;
                case 'SELECT':
                    if ($.isArray(data)) {
                        this.empty();
                        for (var i = 0; i < data.length; i++) {
                            var $opt = $('<option>');
                            $opt.val(data[i]);
                            $opt.text(data[i]);
                            $(this).append($opt);
                        }
                    }
                    else if ($.isPlainObject(data)) {
                        this.empty();
                        for (var id in data) {
                            var $opt = $('<option>');
                            $opt.val(id);
                            $opt.text(data[id]);
                            $(this).append($opt);
                        }
                    }
                    else this.val(data);
                    break;
                case 'OPTION':
                    this.val(data);
                    O.ResolveText(this, data);
                    break;
                default:
                    this.data('o-readonly-data', data);
                    O.ResolveText(this, data);
                    break;
            }
        }
        else {
            switch (this.get(0).nodeName.toUpperCase()) {
                case 'INPUT':
                    var type = this.attr('type');
                    if (type && type.toLowerCase() == 'checkbox') {
                        return this.attr('checked');
                    }
                    else return this.val();
                case 'TEXTAREA':
                    return this.val();
                case 'SELECT':
                    return this.val();
                case 'OPTION':
                    return this.val();
                case 'A':
                case 'BUTTON':
                default:
                    return this.data('o-readonly-data');
            }
        }
    },

    Each: function (data) {
        if (typeof data === 'undefined') return [];
        else {
            var expression = this.attr('data-o');
            this.parent().children().each(function () {
                var $this = $(this);
                if ($this.data('o-parent') == expression) $this.remove();
            });
            var $last = this;
            oFunc = this.data('o-func');
            this.removeData('o-func');
            this.removeAttr('data-o');

            for (var i = 0; i < data.length; i++) {
                var $clone = this.clone(true, true);

                var innerFunc = $clone.data('o-clone-func');
                if (innerFunc) {
                    $clone.data('o-func', innerFunc);
                    $clone.removeData('o-clone-func');
                }

                $clone.find('*').andSelf().removeAttr('id');
                $clone.show();
                O.Auto.apply($clone, [data[i]]);
                $clone.data('o-parent', expression);
                $clone.attr('data-o', expression + "[" + i + "]");
                $clone.insertAfter($last);
                $last = $clone;
            }
            this.data('o-func', oFunc);
            this.attr('data-o', expression);
            this.hide();
        }
    },

    Container: function (data) {
        var o;
        if (typeof data === 'undefined') o = {};
        else o = data;
        this.find('[data-o]').not(this.find('[data-o] [data-o]')).each(function () {
            var $this = $(this);
            var expression = $this.attr('data-o') || "o";
            if (typeof data === 'undefined') {
                var part = O.Auto.apply($this);
                if (typeof part !== 'undefined') {
                    var old_o = o;
                    eval(expression + " = part");
                    o = O.Override(old_o, o);
                }
            }
            else O.Auto.apply($this, [eval(expression)]);
        });
        return o;
    },

    Auto: function (data) {
        /// <summary>
        /// Calls the default function or the function in the data if any. Also, assigns the called function to the data.
        /// Doing "return O.Auto.apply($elem, [data]);" is equivalent to doing "return $elem.o(data)".
        /// </summary>
        var func = O.GetFunc.apply(this, [data]);
        if (func != O.Auto) {
            this.data('o-func', func);
            return func.apply(this, [data]);
        }
    },

    CallDefault: function (data) {
        /// <summary>
        /// Calls the default function for this element without assigning any function and ignoring the function in the data.
        /// The actual default is O.Auto. Use this only to ignore the function in the data.
        /// Must be called like "return O.CallDefault.apply(this, [data]);"
        /// </summary>
        var func = O.GetDefaultFunc.apply(this, [data]);
        if (func != O.CallDefault) return func.apply(this, [data]);
    }
}

$.fn.o = function (data) {
    /// <summary>
    /// If data is passed, assigns the data to the child elements starting from this element. If not, reads the data from the elements.
    /// To have an element use a custom function, assign the function to the 'o-func' jQuery data of the element. This function will
    /// take a data parameter and the "this" pointer will point to the jQuery selector for the element. If data is undefined, it must
    /// return the "o" data of the element, otherwise, it must assign data to the element. If the function returns undefined when
    /// reading, the result will not be added to the final resulting object.
    /// </summary>
        return O.Auto.apply($(this), [data]);
}
<|endoftext|>


<commit_before>
var NAME                = 0,
    DOT                 = 1,
    CHARACTER_CLASS     = 2,
    ORDERED_CHOICE      = 3,
    SEQUENCE            = 4,
    STRING_LITERAL      = 5,
    ZERO_OR_MORE        = 6,
    ONE_OR_MORE         = 7,
    OPTIONAL            = 8,
    NEGATIVE_LOOKAHEAD  = 9,
    POSITIVE_LOOKAHEAD  = 10,
    ERROR_NAME          = 11,
    ERROR_CHOICE        = 12;

var factories = [];

factories[NAME] = function(id, next, state)
{
    // No actual work is done here, just pass it down the line.
    return parser(rules[id][2], next);
}

factories[DOT] = function(id, next, state)
{
    // Always succeed except if passed the end of the input.
    return function(character)
    {
        return character === null ? failure : next;
    }
}

factories[CHARACTER_CLASS] = function(id, next, state)
{
    var rule = rules[id];

    if (typeof rule[1].valueOf() === "string")
        rule[1] = new RegExp(rule[1], "g");

    return function(character)
    {
        if (character === null || !rule[1].test(character))
            return failure;

        return next;
    }
}

factories[STRING_LITERAL] = function(id, next, state)
{
    return function(character)
    {
        var string = rules[id][1],
            length = string.length;

        if (character === null)
            return length === 0 ? next : failure;

        if (string.charAt(state) === character)
            return state === length - 1 ? next : parser(id, next, state + 1);

        return failure;
    }
}

factories[SEQUENCE] = function(id, next, state)
{
    var rule = rules[id],
        index = state + 1;

    if (index < rule.length - 1)
        return parser(rule[index], parser(id, next, index));

    return parser(rule[index], next);
}

function capture(parser)
{
    var captured = function(character, uncapture)
    {
        if (uncapture)
            return parser;

        parser = parser(character);
captured.hash = parser.hash;
        return parser === failure ? parser : captured;
    }
captured.hash = parser.hash;
    return captured;
}

function choice(first, rest, captured)
{
    return function(character)
    {
        var firstResult = first(character);

        if (firstResult === captured)
            return firstResult(null, true);

        var restResult = rest(character);

        if (firstResult === failure)
            return restResult;

        if (restResult === failure)
            return firstResult;

        return choice(firstResult, restResult, captured);
    }
}

factories[ORDERED_CHOICE] = function(id, next, state)
{
    var rule = rules[id],
        count = rule.length,
        parsers = parser(rule[--count], next),
        captured = capture(next);

    while (count-- > 1)
        parsers = choice(parser(rule[count], captured), parsers, captured);

    return parsers;
}

factories[ZERO_OR_MORE] = function(id, next, state)
{
    var captured = capture(parser(id, next, state + 1));

    return choice(parser(rules[id][1], captured), next, captured);
}

factories[ONE_OR_MORE] = function(id, next, state)
{
    if (state === 0)
        return parser(rules[id][1], parser(id, next, state + 1));

    var captured = capture(parser(id, next, state + 1));

    return choice(parser(rules[id][1], captured), next, captured);
}

factories[OPTIONAL] = function(id, next, state)
{
    var captured = capture(next);

    return choice(parser(rules[id][1], captured), next, captured);
}

function dependency(lookahead, parser, expected, unexpected)
{
    return function(character)
    {
        var lookaheadResult = lookahead(character),
            parserResult = parser(character);

        if (lookahead === expected)
            return parserResult;

        if (lookahead === unexpected)
            return failure;

        return dependency(lookaheadResult, parserResult, expected, unexpected);
    }
}

factories[NEGATIVE_LOOKAHEAD] = function(id, next, state)
{
    return dependency(parser(rules[id][1], success), next, failure, success);
}

factories[POSITIVE_LOOKAHEAD] = function(id, next, state)
{
    return dependency(parser(rules[id][1], success), next, success, failure);
}

function success()
{
    //console.log("success");
    return success;
}

success.id = "s";
success.nameo = "success";
success.hash = "success";

function failure()
{
    //console.log("failure");
    return failure;
}

failure.id = "f";
failure.nameo = "faliure";
failure.hash = "failure";

var parserCache = { };

function description(id)
{
    switch (rules[id][0])
    {
        case NAME:              return "(" + rules[id][1] + ") ";
        case DOT:               return "[DOT] ";
        case CHARACTER_CLASS:   return rules[id][1] + " ";
        case ORDERED_CHOICE:    return "[CHOICE] ";
        case SEQUENCE:          return "[SEQ] ";
        case STRING_LITERAL:    return "\"" + rules[id][1] + "\" ";
/*
    ZERO_OR_MORE        = 6,
    ONE_OR_MORE         = 7,
    OPTIONAL            = 8,
    NEGATIVE_LOOKAHEAD  = 9,
    POSITIVE_LOOKAHEAD  = 10,
    ERROR_NAME          = 11,
    ERROR_CHOICE        = 12;*/
    }

    return "";
}

function parser(id, next, state)
{
    var hash = id + "@" + (state || 0) + " -> " + next.hash;

    if (parserCache.hasOwnProperty(hash))
        return parserCache[hash];

    parserCache[hash] = function(character)
    {
        console.log("entering " + description(id) + hash);
        return factories[rules[id][0]](id, next, state || 0)(character);
    }

    parserCache[hash].hash = hash;

    return parserCache[hash];
}

function read(path)
{
    return require("fs").readFileSync(path).toString();
}

var json = JSON.parse(read(process.argv[2])),
    rules = json["table"],
    input = process.argv[3],//read(process.argv[3]),
    lang = parser(json["nameToUID"]["DecimalLiteral"], success);

for (i = 0; i < input.length; ++i)
{
    console.log("[" + i + "] = " + input.charAt(i) + " : " + lang.hash);
    lang = lang(input.charAt(i));
    console.log("[" + i + "] = " + input.charAt(i) + " : " + lang.hash);
}

console.log("DONE AT INPUT END " + (lang === success) + " " + lang);

while (lang !== success && lang !== failure)
    lang = lang(null);

if (lang === success)
    console.log("success");
else
    console.log("failure");
<commit_msg>Fixes to choice.<commit_after>
var NAME                = 0,
    DOT                 = 1,
    CHARACTER_CLASS     = 2,
    ORDERED_CHOICE      = 3,
    SEQUENCE            = 4,
    STRING_LITERAL      = 5,
    ZERO_OR_MORE        = 6,
    ONE_OR_MORE         = 7,
    OPTIONAL            = 8,
    NEGATIVE_LOOKAHEAD  = 9,
    POSITIVE_LOOKAHEAD  = 10,
    ERROR_NAME          = 11,
    ERROR_CHOICE        = 12;

var factories = [];

factories[NAME] = function(id, next, state)
{
    // No actual work is done here, just pass it down the line.
    return parser(rules[id][2], next);
}

factories[DOT] = function(id, next, state)
{
    // Always succeed except if passed the end of the input.
    return function(character)
    {
        return character === null ? failure : next;
    }
}

factories[CHARACTER_CLASS] = function(id, next, state)
{
    var rule = rules[id];

    if (typeof rule[1].valueOf() === "string")
        rule[1] = new RegExp(rule[1], "g");

    return function(character)
    {
        if (character === null || !rule[1].test(character))
            return failure;

        return next;
    }
}

factories[STRING_LITERAL] = function(id, next, state)
{
    return function(character)
    {
        var string = rules[id][1],
            length = string.length;

        if (character === null)
            return length === 0 ? next : failure;

        if (string.charAt(state) === character)
            return state === length - 1 ? next : parser(id, next, state + 1);

        return failure;
    }
}

factories[SEQUENCE] = function(id, next, state)
{
    var rule = rules[id],
        index = state + 1;

    if (index < rule.length - 1)
        return parser(rule[index], parser(id, next, index));

    return parser(rule[index], next);
}

function capture(parser)
{
    var captured = function(character, uncapture)
    {
        if (uncapture)
            return parser;

        parser = parser(character);
captured.hash = parser.hash;
        return parser === failure ? parser : captured;
    }
captured.hash = parser.hash;
    return captured;
}

function markedChoice(first, rest, next, mark, markCalled)
{
    var f = function(character)
    {
console.log("GOING IN!");
        var firstResult = first(character);
console.log("GOT BACK " + firstResult.hash);
        // if first's next got called...
        if (firstResult === mark)
            return next;

        if (firstResult === markCalled)
            return next(character);
            if (!firstResult.hash)
                console.log(firstResult + "");
if (firstResult.hash && firstResult.hash.substr(0, 4) === "MARK")
    console.log("WTF " + character);
        var restResult = rest(character);

        if (firstResult === failure)
            return restResult;

//        if (restResult === failure)
//            return firstResult;

        return markedChoice(firstResult, restResult, next, mark, markCalled);
    }
    f.firster = first;
    f.mark = mark;
    f.hash = "(" + first.hash + " OR " + rest.hash + ")";
    return f;
}

var counter = 0;

function choice(id, next, rest)
{console.log("IM MARKING " + next.hash);
    function mark(character)
    {
        console.log("called with " + character + " " + next);
        return markCalled;
    }

    function markCalled(character)
    {
        console.log("should never happen");
        return markCalled;
    }
mark.hash = "MARKED(" + counter + ")[" + next.hash + "]";
markCalled.hash = "MARKED_CALLED(" + (counter++) + ")[" + next.hash + "]";
    return markedChoice(parser(id, mark), rest, next, mark, markCalled);
}

factories[ORDERED_CHOICE] = function(id, next, state)
{console.log("brand new!");
    var rule = rules[id],
        index = state + 1;

    if (index < rule.length - 1)
        return choice(rule[index], next, parser(id, next, index));

    return parser(rule[index], next);

    var rule = rules[id],
        count = rule.length,
        parsers = parser(rule[--count], next);

    while (count-- > 1)
        parsers = choice(rule[count], next, parsers);

    return parsers;
}

factories[ZERO_OR_MORE] = function(id, next, state)
{
    return choice(rules[id][1], parser(id, next, state + 1), next);
}

factories[ONE_OR_MORE] = function(id, next, state)
{
    if (state === 0)
        return parser(rules[id][1], parser(id, next, state + 1));

    return choice(rules[id][1], parser(id, next, state + 1), next);
}

factories[OPTIONAL] = function(id, next, state)
{
    return choice(rules[id][1], next, next);
}

function dependency(lookahead, parser, expected, unexpected)
{
    return function(character)
    {
        var lookaheadResult = lookahead(character),
            parserResult = parser(character);

        if (lookahead === expected)
            return parserResult;

        if (lookahead === unexpected)
            return failure;

        return dependency(lookaheadResult, parserResult, expected, unexpected);
    }
}

factories[NEGATIVE_LOOKAHEAD] = function(id, next, state)
{
    return dependency(parser(rules[id][1], success), next, failure, success);
}

factories[POSITIVE_LOOKAHEAD] = function(id, next, state)
{
    return dependency(parser(rules[id][1], success), next, success, failure);
}

function success()
{
    //console.log("success");
    return success;
}

success.id = "s";
success.nameo = "success";
success.hash = "success";

function failure()
{
    //console.log("failure");
    return failure;
}

failure.id = "f";
failure.nameo = "faliure";
failure.hash = "failure";

var parserCache = { };
okidoke = false;
function description(id)
{
    switch (rules[id][0])
    {
        case NAME:              return "(" + rules[id][1] + ") ";
        case DOT:               return "[DOT] ";
        case CHARACTER_CLASS:   return rules[id][1] + " ";
        case ORDERED_CHOICE:    return "[CHOICE] ";
        case SEQUENCE:          return "[SEQ] ";
        case STRING_LITERAL:    return "\"" + rules[id][1] + "\" ";
/*
    ZERO_OR_MORE        = 6,
    ONE_OR_MORE         = 7,
    OPTIONAL            = 8,
    NEGATIVE_LOOKAHEAD  = 9,
    POSITIVE_LOOKAHEAD  = 10,
    ERROR_NAME          = 11,
    ERROR_CHOICE        = 12;*/
    }

    return "";
}

function parser(id, next, state)
{parserCache = { };
    var hash = id + "@" + (state || 0) + " -> " + next.hash;

    if (parserCache.hasOwnProperty(hash))
        return parserCache[hash];

    parserCache[hash] = function(character)
    {
        console.log("entering " + description(id) + hash);
        return factories[rules[id][0]](id, next, state || 0)(character);
    }

    parserCache[hash].hash = hash;

    return parserCache[hash];
}

function read(path)
{
    return require("fs").readFileSync(path).toString();
}

var json = JSON.parse(read(process.argv[2])),
    rules = json["table"],
    input = process.argv[3],//read(process.argv[3]),
    lang = parser(json["nameToUID"]["LeftHandSideExpression"], success);//DecimalLiteral
console.log(rules);
for (i = 0; i < input.length; ++i)
{
    console.log("[" + i + "] = " + input.charAt(i) + " : " + lang.hash);
    lang = lang(input.charAt(i));
    console.log("[" + i + "] = " + input.charAt(i) + " : " + lang.hash);
    parserCache = { };
}
okidoke = true;
console.log("DONE AT INPUT END " + (lang === success) + " " + lang + " " + (lang.firster ? lang.firster.hash + " " + (lang.mark === lang.firster) : ""));

while (lang !== success && lang !== failure)
{
    lang = lang(null);
    parserCache = { };
}

if (lang === success)
    console.log("success");
else
    console.log("failure");
<|endoftext|>


<commit_before>//
//  LAZY Loading Images
//
//  Handles lazy loading of images in one or more targeted divs,
//  or in the entire page. It also keeps track of scrolling and
//  resizing events, and removes itself if the work is done.
//
//  Licensed under the terms of the MIT license.
//
//  (c) 2010 Balázs Galambosi
//

(function(window, document){
// glocal variables
var lazyAttr = "data-src",
    winH;

function throttle(fn, minDelay) {
  var lastCall = 0;
  return function() {
    var now = +new Date;
    if (now - lastCall < minDelay) {
      return;
    }
    lastCall = now;
    // we do not return anything as
    // https://github.com/documentcloud/underscore/issues/387
    fn.apply(this, arguments);
  }
}

// cross browser event handling
function addEvent( el, type, fn ) {
  if (el.attachEvent) {
    el.attachEvent && el.attachEvent( "on" + type, fn );
  } else {
    el.addEventListener( type, fn, false );
  }
}

// cross browser event handling
function removeEvent( el, type, fn ) {
  if (el.detachEvent) {
    el.detachEvent && el.detachEvent( "on" + type, fn );
  } else {
    el.removeEventListener( type, fn, false );
  }
}

// cross browser window height
function getWindowHeight() {
  winH = window.innerHeight ||
    (document.documentElement && document.documentElement.clientHeight) ||
    (document.body && document.body.clientHeight) ||
    10000;

  return winH;
}
var getWindowHeight = throttle(getWindowHeight, 30);

function getTopPos( el ) {
  return el.$$top || el.getBoundingClientRect().top;
}

// sorts images by their vertical positions
function img_sort( a, b ) {
  return getTopPos( a ) - getTopPos( b );
}

function LazyImg () {

  var imgs = null,    // images array (ordered)
      last = 0,    // last visible image (index)
      target = document,
      offset = 200; // prefetching vertical offset

  function destroy() {
    removeEvent( window, "scroll", fetchImages );
    removeEvent( window, "error", fetchImages );
    removeEvent( window, "resize", getWindowHeight );
  }

  function fetchImages() {
    var img, temp, len, i;

    // if it's the first time
    // initialize images array
    if ( !imgs && target ) {

      temp = target.getElementsByTagName( "img" );

      if ( temp.length ) {
        imgs = [];
        len  = temp.length;
      } else return;

      // fill the array for sorting
      for ( i = 0; i < len; i++ ) {
        img = temp[i];
        if ( img.nodeType === 1
            && img.getAttribute('src') === null
            && img.getAttribute(lazyAttr) ) {
          // store them and cache current
          // positions for faster sorting
          img.$$top = getTopPos( img );
          imgs.push( img );
        }
      }
      imgs.sort( img_sort );
    }

    // loop through the images
    while ( imgs[last] ) {

      img = imgs[last];

      // delete cached position
      if ( img.$$top ) img.$$top = null;

      // check if the img is above the fold
      if ( getTopPos( img ) < winH + offset )  {

        // then change the src
        img.src = img.getAttribute(lazyAttr);
        last++;
      }
      else return;
    }

    // we've fetched the last image -> finished
    if ( last && last === imgs.length )  {
      destroy();
    }
  }

  var fetchImages = throttle(fetchImages, 15);

  destroy();

  addEvent( window, "resize", getWindowHeight);
  addEvent( window, 'scroll', fetchImages );
  addEvent( window, 'error', fetchImages );

  getWindowHeight();
  setTimeout(fetchImages, 15);
}

// initialize
addEvent( window, "load", LazyImg);
LazyImg();

})(this, document)
<commit_msg>Complete refactor<commit_after>(function(window, document){

  function throttle(fn, minDelay) {
    var lastCall = 0;
    return function() {
      var now = +new Date;
      if (now - lastCall < minDelay) {
        return;
      }
      lastCall = now;
      // we do not return anything as
      // https://github.com/documentcloud/underscore/issues/387
      fn.apply(this, arguments);
    }
  }

  // cross browser event handling
  function addEvent( el, type, fn ) {
    if (el.attachEvent) {
      el.attachEvent && el.attachEvent( 'on' + type, fn );
    } else {
      el.addEventListener( type, fn, false );
    }
  }

  // cross browser event handling
  function removeEvent( el, type, fn ) {
    if (el.detachEvent) {
      el.detachEvent && el.detachEvent( 'on' + type, fn );
    } else {
      el.removeEventListener( type, fn, false );
    }
  }

  // glocal variables
  var
    lazyAttr = 'data-src',
    offset = 200,
    winH,

    // cross browser window height
    getWindowHeight = throttle(function getWindowHeight() {
      winH = window.innerHeight ||
        (document.documentElement && document.documentElement.clientHeight) ||
        (document.body && document.body.clientHeight) ||
        10000;
    }, 30),

    checkImages = throttle(function checkImages() {
      var imgs = document.getElementsByTagName('img'),
        last = imgs.length,
        current;

      for (current = 0; current < last; current++) {
        showIfVisible(imgs[current]);
      }
    }, 30);

  function showIfVisible(el) {
    if (el.getAttribute(lazyAttr) !== null && el.getBoundingClientRect().top < winH + offset) {
      el.src = el.getAttribute(lazyAttr);
      el.removeAttribute(lazyAttr);
    }
  }

  getWindowHeight();
  addEvent(window, 'resize', getWindowHeight);
  addEvent(window, 'scroll', checkImages);

})(this, document)
<|endoftext|>


<commit_before>// Info here: http://ad.aloodo.com/

function doAloodoPopup() {
	var url = 'http://www.aloodo.org/protection/';
	var message = 	'Third-party tracking detected. ' +
			'Missing or misconfigured tracking protection.';
	var txt = '' + message + '';

	if (typeof toastr=='undefined') {
		window.setTimeout(doAloodoPopup, 1000);
	} else {
		toastr.options = { 'timeOut': 30000 };
		toastr.error(txt);
	}
}

function toastrSetup() {
	if (typeof toastr !== 'undefined') {
		doAloodoPopup();
	}
	var sc = document.createElement('script');
	sc.setAttribute('src', 'http://ad.aloodo.com/toastr/toastr.js');
	document.body.appendChild(sc);
	sc.onload = doAloodoPopup();
	var cs = document.createElement('link');
	cs.setAttribute("rel", "stylesheet");
	cs.setAttribute("type", "text/css");
	cs.setAttribute("href", 'http://ad.aloodo.com/toastr/toastr.css');
	document.getElementsByTagName('head')[0].appendChild(cs);
}

function startAloodo(ev) {
	if (ev.data !== 'tracking detected') {
		return;
	}

	if (window.trackingAlternateLocation) {
		document.getElementsByTagName('body')[0].style.display='none';
		window.location.href = trackingAlternateLocation;
		return;
	}

	var safety = document.getElementById('tracking-safety');
	if (safety) {
		safety.style.display = 'none';
	}

	var done = false;
	var warning = document.getElementById('tracking-warning-block');
	if (warning) {
		warning.style.display = 'block';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-table-cell');
	if (warning) {
		warning.style.display = 'table-cell';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-inline');
	if (warning) {
		warning.style.display = 'inline';
		done = true;
	}
	if (done) { return; }

	if(typeof jQuery=='undefined') {
		var jq = document.createElement('script');
		jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js';
		jq.onload = toastrSetup;
		document.body.appendChild(jq);
	} else {
		toastrSetup();
	}
}

function isMSIE() {
	return "ActiveXObject" in window
}

function setupAloodo() {
	// This puts the tracker in an iframe.
	var ifr = document.createElement('iframe');
	ifr.src = "//ad.aloodo.com/track/";
	ifr.style.visibility = 'hidden';
	document.body.appendChild(ifr);
}

window.addEventListener("message", startAloodo, false);
document.addEventListener("DOMContentLoaded", setupAloodo);

// Workaround for not being able to send cross-domain messages
// from iframe to its parent.  Assumes that MSIE is unprotected
// if this script runs at all.
if (isMSIE()) {
	window.postMessage('tracking detected', '*');
}
<commit_msg>use a window event listener<commit_after>// Info here: http://ad.aloodo.com/

function doAloodoPopup() {
	var url = 'http://www.aloodo.org/protection/';
	var message = 	'Third-party tracking detected. ' +
			'Missing or misconfigured tracking protection.';
	var txt = '' + message + '';

	if (typeof toastr=='undefined') {
		window.setTimeout(doAloodoPopup, 1000);
	} else {
		toastr.options = { 'timeOut': 30000 };
		toastr.error(txt);
	}
}

function toastrSetup() {
	if (typeof toastr !== 'undefined') {
		doAloodoPopup();
	}
	var sc = document.createElement('script');
	sc.setAttribute('src', 'http://ad.aloodo.com/toastr/toastr.js');
	document.body.appendChild(sc);
	sc.onload = doAloodoPopup();
	var cs = document.createElement('link');
	cs.setAttribute("rel", "stylesheet");
	cs.setAttribute("type", "text/css");
	cs.setAttribute("href", 'http://ad.aloodo.com/toastr/toastr.css');
	document.getElementsByTagName('head')[0].appendChild(cs);
}

function startAloodo(ev) {
	if (ev.data !== 'tracking detected') {
		return;
	}

	if (window.trackingAlternateLocation) {
		document.getElementsByTagName('body')[0].style.display='none';
		window.location.href = trackingAlternateLocation;
		return;
	}

	var safety = document.getElementById('tracking-safety');
	if (safety) {
		safety.style.display = 'none';
	}

	var done = false;
	var warning = document.getElementById('tracking-warning-block');
	if (warning) {
		warning.style.display = 'block';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-table-cell');
	if (warning) {
		warning.style.display = 'table-cell';
		done = true;
	}
	var warning = document.getElementById('tracking-warning-inline');
	if (warning) {
		warning.style.display = 'inline';
		done = true;
	}
	if (done) { return; }

	if(typeof jQuery=='undefined') {
		var jq = document.createElement('script');
		jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js';
		jq.onload = toastrSetup;
		document.body.appendChild(jq);
	} else {
		toastrSetup();
	}
}

function isMSIE() {
	return "ActiveXObject" in window
}

function setupAloodo() {
	// This puts the tracker in an iframe.
	var ifr = document.createElement('iframe');
	ifr.src = "//ad.aloodo.com/track/";
	ifr.style.visibility = 'hidden';
	document.body.appendChild(ifr);
}

window.addEventListener("message", startAloodo, false);
window.addEventListener("load", setupAloodo);

// Workaround for not being able to send cross-domain messages
// from iframe to its parent.  Assumes that MSIE is unprotected
// if this script runs at all.
if (isMSIE()) {
	window.postMessage('tracking detected', '*');
}
<|endoftext|>


<commit_before>$( document ).ready(function() {
  $("#fancybox-manual-b").click(function() {
    $.fancybox().open({
      href : 'http://ad.nchusg.org/index.html',//在這邊放絕對網址會讓圖片爆掉,我還沒解決，所以讓他用相對路徑直接去連到廣告的頁面../advertisement/index.html
      type : 'iframe',
      padding : 5
    });
  });
  $("#fancybox-manual-b").click();
});              <commit_msg>廣告功能修復<commit_after>$( document ).ready(function() {
  $("#fancybox-manual-b").click(function() {
    $.fancybox.open({
      href : 'http://ad.nchusg.org/index.html',//在這邊放絕對網址會讓圖片爆掉,我還沒解決，所以讓他用相對路徑直接去連到廣告的頁面../advertisement/index.html
      type : 'iframe',
      padding : 5
    });
  });
  $("#fancybox-manual-b").click();
});              <|endoftext|>


<commit_before>const ADD = 0, SUB = 1, RIGHT = 2, LEFT = 3, OUT = 4, IN = 5,
  OPEN = 6, CLOSE = 7;

function* parseProgram(programString) {
  for (let opCode of programString) {
    switch (opCode) {
      case '+':
        yield {type: ADD, x: 1};
        break;
      case '-':
        yield {type: SUB, x: 1};
        break;
      case '>':
        yield {type: RIGHT, x: 1};
        break;
      case '<':
        yield {type: LEFT, x: 1};
        break;
      case '.':
        yield {type: OUT};
        break;
      case ',':
        yield {type: IN};
        break;
      case '[':
        yield {type: OPEN};
        break;
      case ']':
        yield {type: CLOSE};
        break;
    }
  }
}

function* contractProgram(program) {
  let prev;
  for (let ins of program) {
    if (!prev) {
      prev = ins;
    } else {
      if (prev.type === ins.type && prev.x) {
        prev.x += ins.x;
      } else {
        yield prev;
        prev = ins;
      }
    }
  }
  if (prev) {
    yield prev;
  }
}

function parseAndOptimizeProgram(programString) {
  return Array.from(contractProgram(parseProgram(programString)));
}

export default class Machine {
  constructor(programString, read, write, options={}) {
    if (read[Symbol.iterator]) {
      const iter = read[Symbol.iterator]();
      read = () => {
        const {value, done} = iter.next();
        return done ? null : value;
      };
    }

    this._cellSize = options.cellSize || 16;
    this._cellCount = options.cellCount || 4096;
    this._program = parseAndOptimizeProgram(programString);
    this._read = read;
    this._write = write;
    if (this._cellSize === 16) {
      this._memory = new Uint16Array(this._cellCount);
    } else if (this._cellSize === 8) {
      this._memory = new Uint8Array(this._cellCount);
    } else {
      throw new Error("Invalid cell size: "+this._cellSize);
    }
    this._pc = 0;
    this._dc = 0;
    this._EOF = options.EOF|0;
    this._complete = false;
  }

  get complete() {
    return this._complete;
  }

  run(steps=Infinity) {
    const programLen = this._program.length;
    let step = 0;
    while (step < steps) {
      if (this._pc >= programLen) {
        this._complete = true;
        break;
      }
      const ins = this._program[this._pc];
      switch (ins.type) {
        case ADD:
          this._memory[this._dc] += ins.x|0;
          break;
        case SUB:
          this._memory[this._dc] -= ins.x|0;
          break;
        case RIGHT:
          this._dc += ins.x|0;
          break;
        case LEFT:
          this._dc -= ins.x|0;
          break;
        case OUT:
          this._write(this._memory[this._dc]|0);
          break;
        case IN:
          const value = this._read();
          this._memory[this._dc] = value === null ? this._EOF|0 : value|0;
          break;
        case OPEN:
          if (this._memory[this._dc] === 0) {
            let openCount = 1;
            while (++this._pc < programLen && openCount > 0) {
              let currentOpCode = this._program[this._pc].type;
              if (currentOpCode === OPEN) {
                openCount++;
              } else if (currentOpCode === CLOSE) {
                openCount--;
              }
            }
            this._pc--;
          }
          break;
        case CLOSE:
          if (this._memory[this._dc] !== 0) {
            let openCount = 1;
            while (--this._pc > 0 && openCount > 0) {
              let currentOpCode = this._program[this._pc].type;
              if (currentOpCode === CLOSE) {
                openCount++;
              } else if (currentOpCode === OPEN) {
                openCount--;
              }
            }
          }
          break;
      }
      this._pc++;
      step++;
    }
    return step;
  }
}
<commit_msg>clearloop optimization<commit_after>const ADD = 0, SUB = 1, RIGHT = 2, LEFT = 3, OUT = 4, IN = 5,
  OPEN = 6, CLOSE = 7,
  CLEAR = 8;

function* parseProgram(programString) {
  for (let opCode of programString) {
    switch (opCode) {
      case '+':
        yield {type: ADD, x: 1};
        break;
      case '-':
        yield {type: SUB, x: 1};
        break;
      case '>':
        yield {type: RIGHT, x: 1};
        break;
      case '<':
        yield {type: LEFT, x: 1};
        break;
      case '.':
        yield {type: OUT};
        break;
      case ',':
        yield {type: IN};
        break;
      case '[':
        yield {type: OPEN};
        break;
      case ']':
        yield {type: CLOSE};
        break;
    }
  }
}

function* contractProgram(program) {
  let prev;
  for (let ins of program) {
    if (!prev) {
      prev = ins;
    } else {
      if (prev.type === ins.type && prev.x) {
        prev.x += ins.x;
      } else {
        yield prev;
        prev = ins;
      }
    }
  }
  if (prev) {
    yield prev;
  }
}

function* clearLoop(program) {
  const buffer = [];
  for (let ins of program) {
    if (buffer.length === 0) {
      if (ins.type === OPEN) {
        buffer.push(ins);
      } else {
        yield ins;
      }
    } else if (buffer.length === 1) {
      if (ins.type === SUB && ins.x === 1) {
        buffer.push(ins);
      } else {
        yield* buffer;
        yield ins;
        buffer.length = 0;
      }
    } else /* buffer.length === 2 */ {
      if (ins.type === CLOSE) {
        yield {type: CLEAR};
      } else {
        yield* buffer;
        yield ins;
      }
      buffer.length = 0;
    }
  }
}

function parseAndOptimizeProgram(programString) {
  return Array.from(contractProgram(clearLoop(parseProgram(programString))));
}

export default class Machine {
  constructor(programString, read, write, options={}) {
    if (read[Symbol.iterator]) {
      const iter = read[Symbol.iterator]();
      read = () => {
        const {value, done} = iter.next();
        return done ? null : value;
      };
    }

    this._cellSize = options.cellSize || 16;
    this._cellCount = options.cellCount || 4096;
    this._program = parseAndOptimizeProgram(programString);
    this._read = read;
    this._write = write;
    if (this._cellSize === 16) {
      this._memory = new Uint16Array(this._cellCount);
    } else if (this._cellSize === 8) {
      this._memory = new Uint8Array(this._cellCount);
    } else {
      throw new Error("Invalid cell size: "+this._cellSize);
    }
    this._pc = 0;
    this._dc = 0;
    this._EOF = options.EOF|0;
    this._complete = false;
  }

  get complete() {
    return this._complete;
  }

  run(steps=Infinity) {
    const programLen = this._program.length;
    let step = 0;
    while (step < steps) {
      if (this._pc >= programLen) {
        this._complete = true;
        break;
      }
      const ins = this._program[this._pc];
      switch (ins.type) {
        case ADD:
          this._memory[this._dc] += ins.x|0;
          break;
        case SUB:
          this._memory[this._dc] -= ins.x|0;
          break;
        case CLEAR:
          this._memory[this._dc] = 0;
          break;
        case RIGHT:
          this._dc += ins.x|0;
          break;
        case LEFT:
          this._dc -= ins.x|0;
          break;
        case OUT:
          this._write(this._memory[this._dc]|0);
          break;
        case IN:
          const value = this._read();
          this._memory[this._dc] = value === null ? this._EOF|0 : value|0;
          break;
        case OPEN:
          if (this._memory[this._dc] === 0) {
            let openCount = 1;
            while (++this._pc < programLen && openCount > 0) {
              let currentOpCode = this._program[this._pc].type;
              if (currentOpCode === OPEN) {
                openCount++;
              } else if (currentOpCode === CLOSE) {
                openCount--;
              }
            }
            this._pc--;
          }
          break;
        case CLOSE:
          if (this._memory[this._dc] !== 0) {
            let openCount = 1;
            while (--this._pc > 0 && openCount > 0) {
              let currentOpCode = this._program[this._pc].type;
              if (currentOpCode === CLOSE) {
                openCount++;
              } else if (currentOpCode === OPEN) {
                openCount--;
              }
            }
          }
          break;
      }
      this._pc++;
      step++;
    }
    return step;
  }
}
<|endoftext|>


<commit_before>var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var crypto = require('crypto');
var format = require('util').format;
var MONGO_LOC = 'mongodb://127.0.0.1/whopays';
var log = require('./logger');

module.exports = function() {
  var methods = {};
  MongoClient.connect(MONGO_LOC, function(err, db) {
    if(err) {
      log.warn(err);
      return;
    }

    db.createCollection('reports', function() {
      var collection = db.collection('reports');

      methods.findall = function(cb){
        collection.find().toArray(function(err,arr){
          cb(err,arr)
        });
      }

      methods.find = function(id, cb){
        try {
          var objectId = new ObjectID(id);
          collection.find(objectId).toArray(function(err, arr) {
            cb(err, arr);
          });
        } catch(e) {
          cb(e, []);
        }
      }
      methods.insert = function(data, cb){
        collection.insert(data, function(err, datum) {
          if (err) {
            log.warn(err)
            return cb(err);
          };
          return cb(err, data, datum);
        });
      }
    });
  });
  return methods;
}<commit_msg>Removed unreferend variable<commit_after>var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var format = require('util').format;
var MONGO_LOC = 'mongodb://127.0.0.1/whopays';
var log = require('./logger');

module.exports = function() {
  var methods = {};
  MongoClient.connect(MONGO_LOC, function(err, db) {
    if(err) {
      log.warn(err);
      return;
    }

    db.createCollection('reports', function() {
      var collection = db.collection('reports');

      methods.findall = function(cb){
        collection.find().toArray(function(err,arr){
          cb(err,arr)
        });
      }

      methods.find = function(id, cb){
        try {
          var objectId = new ObjectID(id);
          collection.find(objectId).toArray(function(err, arr) {
            cb(err, arr);
          });
        } catch(e) {
          cb(e, []);
        }
      }
      methods.insert = function(data, cb){
        collection.insert(data, function(err, datum) {
          if (err) {
            log.warn(err)
            return cb(err);
          };
          return cb(err, data, datum);
        });
      }
    });
  });
  return methods;
}
<|endoftext|>