<commit_before>define(['angular'], function (angular) {

    var module = angular.module('myapp', ['modelFactory']);

    module.factory('AnimalModel', function() {
        function Animal(val) {
            angular.extend(this, val);
        };

        Animal.prototype.dateAdded = function(val) {
            return new Date(val);
        };

        return Animal;
    });

    module.factory('ZooModel', function($modelFactory, AnimalModel){
        return $modelFactory('api/zoo', {
            defaults: {
                zooName: 'New Zoo'
            },
            map: {
                animals: function(animal){
                    return animal.map(function(a){ return new AnimalModel(a); })
                }
            },
            actions: {
                query: {
                    cache: true
                },
                $copy: {
                    method: 'POST',
                    url: 'copy'
                }
            }
        });
    });

    module.config(function ($stateProvider) {
        $stateProvider.state('zoo', {
            url: '/zoo',
            templateUrl: 'zoo.tpl.html',
            controller: 'ZooCtrl',
            resolve: {
                zoos: function (ZooModel) {
                    return ZooModel.query();
                }
            }
        });
    });

    module.controller('ZooCtrl', function ($scope, ZooModel, zoos) {

        //-> zoos = [ ZooModel({ type: 'National', name: 'DC Zoo', id: '123' }) ]
        $scope.zoos = zoos;

        $scope.editZoo = function(zoo){
            // UPDATE since we have an id
            zoo.$save().then(function(model){

                // cache was invalidated
                alert('Zoo was updated');
            });
        };

        $scope.deleteZoo = function(zoo){
            zoo.$destroy().then(function(){

                // cache was invalidated
                alert('Zoo was deleted');

                // zoo was automatically removed from array
                //-> $scope.zoos = [];
            });
        };

        $scope.createZoo = function(name){
            var newZoo = new ZooModel({
                name: name
            });

            // POST since no id
            zooModel.$save().then(function(model){
                //-> ZooModel({ name: 'whatever', newAnimal: true })

                // push our new zoo into the model
                // this will relate the zoo to the model
                // so if a user destorys this model it will
                // automatically be removed from the array too
                $scope.zoos.push(model);
            });
        };

        $scope.getZoo = function(id){
            // get a zoo by id
            ZooModel.get(id).then(function(model){
                $scope.newZoo = model;
            });
        };

        $scope.getPandas = function(){
            // get a zoo by animalType of panda
            // GET api/zoo?animalType=panda
            ZooModel.query({ animalType: 'panda' }).then(function(models){
                $scope.pandas = models;
            });
        };

        $scope.refreshZoos = function(){
            ZooModel.query().then(function(models){
                // models = [ ZooModel({ type: 'National', name: 'DC Zoo', id: '123' }) ]
                $scope.allZoos = models;
            });
        };

    });

    return module;
});
<commit_msg>Update simple.js<commit_after>define(['angular', 'model-factory'], function (angular) {

    var module = angular.module('myapp', ['modelFactory']);

    module.factory('AnimalModel', function() {
        function Animal(val) {
            angular.extend(this, val);
        };

        Animal.prototype.dateAdded = function(val) {
            return new Date(val);
        };

        return Animal;
    });

    module.factory('ZooModel', function($modelFactory, AnimalModel){
        return $modelFactory('api/zoo', {
            defaults: {
                zooName: 'New Zoo'
            },
            map: {
                animals: function(animal){
                    return animal.map(function(a){ return new AnimalModel(a); })
                }
            },
            actions: {
                query: {
                    cache: true
                },
                $copy: {
                    method: 'POST',
                    url: 'copy'
                }
            }
        });
    });

    module.config(function ($stateProvider) {
        $stateProvider.state('zoo', {
            url: '/zoo',
            templateUrl: 'zoo.tpl.html',
            controller: 'ZooCtrl',
            resolve: {
                zoos: function (ZooModel) {
                    return ZooModel.query();
                }
            }
        });
    });

    module.controller('ZooCtrl', function ($scope, ZooModel, zoos) {

        //-> zoos = [ ZooModel({ type: 'National', name: 'DC Zoo', id: '123' }) ]
        $scope.zoos = zoos;

        $scope.editZoo = function(zoo){
            // UPDATE since we have an id
            zoo.$save().then(function(model){

                // cache was invalidated
                alert('Zoo was updated');
            });
        };

        $scope.deleteZoo = function(zoo){
            zoo.$destroy().then(function(){

                // cache was invalidated
                alert('Zoo was deleted');

                // zoo was automatically removed from array
                //-> $scope.zoos = [];
            });
        };

        $scope.createZoo = function(name){
            var newZoo = new ZooModel({
                name: name
            });

            // POST since no id
            zooModel.$save().then(function(model){
                //-> ZooModel({ name: 'whatever', newAnimal: true })

                // push our new zoo into the model
                // this will relate the zoo to the model
                // so if a user destorys this model it will
                // automatically be removed from the array too
                $scope.zoos.push(model);
            });
        };

        $scope.getZoo = function(id){
            // get a zoo by id
            ZooModel.get(id).then(function(model){
                $scope.newZoo = model;
            });
        };

        $scope.getPandas = function(){
            // get a zoo by animalType of panda
            // GET api/zoo?animalType=panda
            ZooModel.query({ animalType: 'panda' }).then(function(models){
                $scope.pandas = models;
            });
        };

        $scope.refreshZoos = function(){
            ZooModel.query().then(function(models){
                // models = [ ZooModel({ type: 'National', name: 'DC Zoo', id: '123' }) ]
                $scope.allZoos = models;
            });
        };

    });

    return module;
});
<|endoftext|>


<commit_before>
var CartoDB = require('../');
var secret = require('./secret.js');

// please, fill secret.js using secret.js.example before launch the demo
var client = new CartoDB({user:secret.USER, api_key:secret.API_KEY});

client.on('connect', function() {
    console.log("connected");
});

client.connect();

client.on('data', function(data) {
    console.log(data.rows);
});

client.on('error', function(err) {
    console.log("some error ocurred");
});

// request two queries, put here your tables
client.query("select * from {table} limit 5", {table: 'tracker'});
client.query("select * from tracker limit 5 offset 5");

<commit_msg>updated simple example<commit_after>
var CartoDB = require('../');
var secret = require('./secret.js');

// please, fill secret.js using secret.js.example before launch the demo
var client = new CartoDB({user:secret.USER, api_key:secret.API_KEY});

var outputRows = function(err, data) {
  console.log(data.rows);
};

client.on('connect', function() {
  client
  .query("select * from {table} limit 5", {table: 'tracker'}, outputRows)
  .query("select * from tracker limit 5 offset 5", outputRows);
});

client.connect();

<|endoftext|>


<commit_before>import _, { replace } from 'lodash'
import selectorParser from 'postcss-selector-parser'
import postcss from 'postcss'
import substituteTailwindAtRules from '../lib/substituteTailwindAtRules'
import evaluateTailwindFunctions from '../lib/evaluateTailwindFunctions'
import substituteVariantsAtRules from '../lib/substituteVariantsAtRules'
import substituteResponsiveAtRules from '../lib/substituteResponsiveAtRules'
import convertLayerAtRulesToControlComments from '../lib/convertLayerAtRulesToControlComments'
import substituteScreenAtRules from '../lib/substituteScreenAtRules'
import prefixSelector from '../util/prefixSelector'
import { useMemo } from '../util/useMemo'

function hasAtRule(css, atRule) {
  let foundAtRule = false

  css.walkAtRules(atRule, () => {
    foundAtRule = true
    return false
  })

  return foundAtRule
}

function cloneWithoutChildren(node) {
  if (node.type === 'atrule') {
    return postcss.atRule({ name: node.name, params: node.params })
  }

  if (node.type === 'rule') {
    return postcss.rule({ name: node.name, selectors: node.selectors })
  }

  const clone = node.clone()
  clone.removeAll()
  return clone
}

const tailwindApplyPlaceholder = selectorParser.attribute({
  attribute: '__TAILWIND-APPLY-PLACEHOLDER__',
})

function generateRulesFromApply({ rule, utilityName: className, classPosition }, replaceWiths) {
  const parser = selectorParser(selectors => {
    let i = 0
    selectors.walkClasses(c => {
      if (classPosition === i++ && c.value === className) {
        c.replaceWith(tailwindApplyPlaceholder)
      }
    })
  })

  const processedSelectors = _.flatMap(rule.selectors, selector => {
    // You could argue we should make this replacement at the AST level, but if we believe
    // the placeholder string is safe from collisions then it is safe to do this is a simple
    // string replacement, and much, much faster.
    return replaceWiths.map(replaceWith =>
      parser.processSync(selector).replace('[__TAILWIND-APPLY-PLACEHOLDER__]', replaceWith)
    )
  })

  const cloned = rule.clone()
  let current = cloned
  let parent = rule.parent

  while (parent && parent.type !== 'root') {
    const parentClone = cloneWithoutChildren(parent)

    parentClone.append(current)
    current.parent = parentClone
    current = parentClone
    parent = parent.parent
  }

  cloned.selectors = processedSelectors
  return current
}

const extractUtilityNamesParser = selectorParser(selectors => {
  let classes = []
  selectors.walkClasses(c => classes.push(c.value))
  return classes
})

const extractUtilityNames = useMemo(
  selector => extractUtilityNamesParser.transformSync(selector),
  selector => selector
)

const cloneRuleWithParent = useMemo(
  rule => rule.clone({ parent: rule.parent }),
  rule => rule
)

function buildUtilityMap(css, lookupTree) {
  let index = 0
  const utilityMap = {}

  lookupTree.walkRules(rule => {
    const utilityNames = extractUtilityNames(rule.selector)

    utilityNames.forEach((utilityName, i) => {
      if (utilityMap[utilityName] === undefined) {
        utilityMap[utilityName] = []
      }

      utilityMap[utilityName].push({
        index,
        utilityName,
        classPosition: i,
        get rule() {
          return cloneRuleWithParent(rule)
        },
      })
      index++
    })
  })

  css.walkRules(rule => {
    const utilityNames = extractUtilityNames(rule.selector)

    utilityNames.forEach((utilityName, i) => {
      if (utilityMap[utilityName] === undefined) {
        utilityMap[utilityName] = []
      }

      utilityMap[utilityName].push({
        index,
        utilityName,
        classPosition: i,
        get rule() {
          return cloneRuleWithParent(rule)
        },
      })
      index++
    })
  })

  return utilityMap
}

function mergeAdjacentRules(initialRule, rulesToInsert) {
  let previousRule = initialRule

  rulesToInsert.forEach(toInsert => {
    if (
      toInsert.type === 'rule' &&
      previousRule.type === 'rule' &&
      toInsert.selector === previousRule.selector
    ) {
      previousRule.append(toInsert.nodes)
    } else if (
      toInsert.type === 'atrule' &&
      previousRule.type === 'atrule' &&
      toInsert.params === previousRule.params
    ) {
      const merged = mergeAdjacentRules(
        previousRule.nodes[previousRule.nodes.length - 1],
        toInsert.nodes
      )

      previousRule.append(merged)
    } else {
      previousRule = toInsert
    }

    toInsert.walk(n => {
      if (n.nodes && n.nodes.length === 0) {
        n.remove()
      }
    })
  })

  return rulesToInsert.filter(r => r.nodes.length > 0)
}

function makeExtractUtilityRules(css, lookupTree, config) {
  const utilityMap = buildUtilityMap(css, lookupTree)

  return function extractUtilityRules(utilityNames, rule) {
    const combined = []

    utilityNames.forEach(utilityName => {
      if (utilityMap[utilityName] === undefined) {
        // Look for prefixed utility in case the user has goofed
        const prefixedUtility = prefixSelector(config.prefix, `.${utilityName}`).slice(1)

        if (utilityMap[prefixedUtility] !== undefined) {
          throw rule.error(
            `The \`${utilityName}\` class does not exist, but \`${prefixedUtility}\` does. Did you forget the prefix?`
          )
        }

        throw rule.error(
          `The \`${utilityName}\` class does not exist. If you're sure that \`${utilityName}\` exists, make sure that any \`@import\` statements are being properly processed before Tailwind CSS sees your CSS, as \`@apply\` can only be used for classes in the same CSS tree.`,
          { word: utilityName }
        )
      }

      combined.push(...utilityMap[utilityName])
    })

    return combined.sort((a, b) => a.index - b.index)
  }
}

function processApplyAtRules(css, lookupTree, config) {
  const extractUtilityRules = makeExtractUtilityRules(css, lookupTree, config)

  do {
    css.walkRules(rule => {
      const applyRules = []

      // Only walk direct children to avoid issues with nesting plugins
      rule.each(child => {
        if (child.type === 'atrule' && child.name === 'apply') {
          applyRules.unshift(child)
        }
      })

      applyRules.forEach(applyRule => {
        const [
          importantEntries,
          applyUtilityNames,
          important = importantEntries.length > 0,
        ] = _.partition(applyRule.params.split(' '), n => n === '!important')

        const currentUtilityNames = extractUtilityNames(rule.selector)

        if (_.intersection(applyUtilityNames, currentUtilityNames).length > 0) {
          const currentUtilityName = _.intersection(applyUtilityNames, currentUtilityNames)[0]
          throw rule.error(
            `You cannot \`@apply\` the \`${currentUtilityName}\` utility here because it creates a circular dependency.`
          )
        }

        // Extract any post-apply declarations and re-insert them after apply rules
        const afterRule = rule.clone({ raws: {} })
        afterRule.nodes = afterRule.nodes.slice(rule.index(applyRule) + 1)
        rule.nodes = rule.nodes.slice(0, rule.index(applyRule) + 1)

        // Sort applys to match CSS source order
        const applys = extractUtilityRules(applyUtilityNames, applyRule)

        // Get new rules with the utility portion of the selector replaced with the new selector
        const rulesToInsert = [
          ...applys.map(applyUtility => {
            return generateRulesFromApply(applyUtility, rule.selectors)
          }),
          afterRule,
        ]

        const { nodes } = _.tap(postcss.root({ nodes: rulesToInsert }), root =>
          root.walkDecls(d => (d.important = important))
        )

        const mergedRules = mergeAdjacentRules(rule, nodes)

        applyRule.remove()
        rule.after(mergedRules)
      })

      // If the base rule has nothing in it (all applys were pseudo or responsive variants),
      // remove the rule fuggit.
      if (rule.nodes.length === 0) {
        rule.remove()
      }
    })

    // We already know that we have at least 1 @apply rule. Otherwise this
    // function would not have been called. Therefore we can execute this code
    // at least once. This also means that in the best case scenario we only
    // call this 2 times, instead of 3 times.
    // 1st time -> before we call this function
    // 2nd time -> when we check if we have to do this loop again (because do {} while (check))
    // .. instead of
    // 1st time -> before we call this function
    // 2nd time -> when we check the first time (because while (check) do {})
    // 3rd time -> when we re-check to see if we should do this loop again
  } while (hasAtRule(css, 'apply'))

  return css
}

let defaultTailwindTree = null

export default function applyComplexClasses(config, getProcessedPlugins, configChanged) {
  return function(css) {
    // We can stop already when we don't have any @apply rules. Vue users: you're welcome!
    if (!hasAtRule(css, 'apply')) {
      return css
    }

    // Tree already contains @tailwind rules, don't prepend default Tailwind tree
    if (hasAtRule(css, 'tailwind')) {
      return processApplyAtRules(css, postcss.root(), config)
    }

    // Tree contains no @tailwind rules, so generate all of Tailwind's styles and
    // prepend them to the user's CSS. Important for <style> blocks in Vue components.
    const generateLookupTree =
      configChanged || defaultTailwindTree === null
        ? () => {
            return postcss([
              substituteTailwindAtRules(config, getProcessedPlugins()),
              evaluateTailwindFunctions(config),
              substituteVariantsAtRules(config, getProcessedPlugins()),
              substituteResponsiveAtRules(config),
              convertLayerAtRulesToControlComments(config),
              substituteScreenAtRules(config),
            ])
              .process(
                `
                  @tailwind base;
                  @tailwind components;
                  @tailwind utilities;
                `,
                { from: undefined }
              )
              .then(result => {
                defaultTailwindTree = result
                return defaultTailwindTree
              })
          }
        : () => Promise.resolve(defaultTailwindTree)

    return generateLookupTree().then(result => {
      return processApplyAtRules(css, result.root, config)
    })
  }
}
<commit_msg>Remove unused import<commit_after>import _ from 'lodash'
import selectorParser from 'postcss-selector-parser'
import postcss from 'postcss'
import substituteTailwindAtRules from '../lib/substituteTailwindAtRules'
import evaluateTailwindFunctions from '../lib/evaluateTailwindFunctions'
import substituteVariantsAtRules from '../lib/substituteVariantsAtRules'
import substituteResponsiveAtRules from '../lib/substituteResponsiveAtRules'
import convertLayerAtRulesToControlComments from '../lib/convertLayerAtRulesToControlComments'
import substituteScreenAtRules from '../lib/substituteScreenAtRules'
import prefixSelector from '../util/prefixSelector'
import { useMemo } from '../util/useMemo'

function hasAtRule(css, atRule) {
  let foundAtRule = false

  css.walkAtRules(atRule, () => {
    foundAtRule = true
    return false
  })

  return foundAtRule
}

function cloneWithoutChildren(node) {
  if (node.type === 'atrule') {
    return postcss.atRule({ name: node.name, params: node.params })
  }

  if (node.type === 'rule') {
    return postcss.rule({ name: node.name, selectors: node.selectors })
  }

  const clone = node.clone()
  clone.removeAll()
  return clone
}

const tailwindApplyPlaceholder = selectorParser.attribute({
  attribute: '__TAILWIND-APPLY-PLACEHOLDER__',
})

function generateRulesFromApply({ rule, utilityName: className, classPosition }, replaceWiths) {
  const parser = selectorParser(selectors => {
    let i = 0
    selectors.walkClasses(c => {
      if (classPosition === i++ && c.value === className) {
        c.replaceWith(tailwindApplyPlaceholder)
      }
    })
  })

  const processedSelectors = _.flatMap(rule.selectors, selector => {
    // You could argue we should make this replacement at the AST level, but if we believe
    // the placeholder string is safe from collisions then it is safe to do this is a simple
    // string replacement, and much, much faster.
    return replaceWiths.map(replaceWith =>
      parser.processSync(selector).replace('[__TAILWIND-APPLY-PLACEHOLDER__]', replaceWith)
    )
  })

  const cloned = rule.clone()
  let current = cloned
  let parent = rule.parent

  while (parent && parent.type !== 'root') {
    const parentClone = cloneWithoutChildren(parent)

    parentClone.append(current)
    current.parent = parentClone
    current = parentClone
    parent = parent.parent
  }

  cloned.selectors = processedSelectors
  return current
}

const extractUtilityNamesParser = selectorParser(selectors => {
  let classes = []
  selectors.walkClasses(c => classes.push(c.value))
  return classes
})

const extractUtilityNames = useMemo(
  selector => extractUtilityNamesParser.transformSync(selector),
  selector => selector
)

const cloneRuleWithParent = useMemo(
  rule => rule.clone({ parent: rule.parent }),
  rule => rule
)

function buildUtilityMap(css, lookupTree) {
  let index = 0
  const utilityMap = {}

  lookupTree.walkRules(rule => {
    const utilityNames = extractUtilityNames(rule.selector)

    utilityNames.forEach((utilityName, i) => {
      if (utilityMap[utilityName] === undefined) {
        utilityMap[utilityName] = []
      }

      utilityMap[utilityName].push({
        index,
        utilityName,
        classPosition: i,
        get rule() {
          return cloneRuleWithParent(rule)
        },
      })
      index++
    })
  })

  css.walkRules(rule => {
    const utilityNames = extractUtilityNames(rule.selector)

    utilityNames.forEach((utilityName, i) => {
      if (utilityMap[utilityName] === undefined) {
        utilityMap[utilityName] = []
      }

      utilityMap[utilityName].push({
        index,
        utilityName,
        classPosition: i,
        get rule() {
          return cloneRuleWithParent(rule)
        },
      })
      index++
    })
  })

  return utilityMap
}

function mergeAdjacentRules(initialRule, rulesToInsert) {
  let previousRule = initialRule

  rulesToInsert.forEach(toInsert => {
    if (
      toInsert.type === 'rule' &&
      previousRule.type === 'rule' &&
      toInsert.selector === previousRule.selector
    ) {
      previousRule.append(toInsert.nodes)
    } else if (
      toInsert.type === 'atrule' &&
      previousRule.type === 'atrule' &&
      toInsert.params === previousRule.params
    ) {
      const merged = mergeAdjacentRules(
        previousRule.nodes[previousRule.nodes.length - 1],
        toInsert.nodes
      )

      previousRule.append(merged)
    } else {
      previousRule = toInsert
    }

    toInsert.walk(n => {
      if (n.nodes && n.nodes.length === 0) {
        n.remove()
      }
    })
  })

  return rulesToInsert.filter(r => r.nodes.length > 0)
}

function makeExtractUtilityRules(css, lookupTree, config) {
  const utilityMap = buildUtilityMap(css, lookupTree)

  return function extractUtilityRules(utilityNames, rule) {
    const combined = []

    utilityNames.forEach(utilityName => {
      if (utilityMap[utilityName] === undefined) {
        // Look for prefixed utility in case the user has goofed
        const prefixedUtility = prefixSelector(config.prefix, `.${utilityName}`).slice(1)

        if (utilityMap[prefixedUtility] !== undefined) {
          throw rule.error(
            `The \`${utilityName}\` class does not exist, but \`${prefixedUtility}\` does. Did you forget the prefix?`
          )
        }

        throw rule.error(
          `The \`${utilityName}\` class does not exist. If you're sure that \`${utilityName}\` exists, make sure that any \`@import\` statements are being properly processed before Tailwind CSS sees your CSS, as \`@apply\` can only be used for classes in the same CSS tree.`,
          { word: utilityName }
        )
      }

      combined.push(...utilityMap[utilityName])
    })

    return combined.sort((a, b) => a.index - b.index)
  }
}

function processApplyAtRules(css, lookupTree, config) {
  const extractUtilityRules = makeExtractUtilityRules(css, lookupTree, config)

  do {
    css.walkRules(rule => {
      const applyRules = []

      // Only walk direct children to avoid issues with nesting plugins
      rule.each(child => {
        if (child.type === 'atrule' && child.name === 'apply') {
          applyRules.unshift(child)
        }
      })

      applyRules.forEach(applyRule => {
        const [
          importantEntries,
          applyUtilityNames,
          important = importantEntries.length > 0,
        ] = _.partition(applyRule.params.split(' '), n => n === '!important')

        const currentUtilityNames = extractUtilityNames(rule.selector)

        if (_.intersection(applyUtilityNames, currentUtilityNames).length > 0) {
          const currentUtilityName = _.intersection(applyUtilityNames, currentUtilityNames)[0]
          throw rule.error(
            `You cannot \`@apply\` the \`${currentUtilityName}\` utility here because it creates a circular dependency.`
          )
        }

        // Extract any post-apply declarations and re-insert them after apply rules
        const afterRule = rule.clone({ raws: {} })
        afterRule.nodes = afterRule.nodes.slice(rule.index(applyRule) + 1)
        rule.nodes = rule.nodes.slice(0, rule.index(applyRule) + 1)

        // Sort applys to match CSS source order
        const applys = extractUtilityRules(applyUtilityNames, applyRule)

        // Get new rules with the utility portion of the selector replaced with the new selector
        const rulesToInsert = [
          ...applys.map(applyUtility => {
            return generateRulesFromApply(applyUtility, rule.selectors)
          }),
          afterRule,
        ]

        const { nodes } = _.tap(postcss.root({ nodes: rulesToInsert }), root =>
          root.walkDecls(d => (d.important = important))
        )

        const mergedRules = mergeAdjacentRules(rule, nodes)

        applyRule.remove()
        rule.after(mergedRules)
      })

      // If the base rule has nothing in it (all applys were pseudo or responsive variants),
      // remove the rule fuggit.
      if (rule.nodes.length === 0) {
        rule.remove()
      }
    })

    // We already know that we have at least 1 @apply rule. Otherwise this
    // function would not have been called. Therefore we can execute this code
    // at least once. This also means that in the best case scenario we only
    // call this 2 times, instead of 3 times.
    // 1st time -> before we call this function
    // 2nd time -> when we check if we have to do this loop again (because do {} while (check))
    // .. instead of
    // 1st time -> before we call this function
    // 2nd time -> when we check the first time (because while (check) do {})
    // 3rd time -> when we re-check to see if we should do this loop again
  } while (hasAtRule(css, 'apply'))

  return css
}

let defaultTailwindTree = null

export default function applyComplexClasses(config, getProcessedPlugins, configChanged) {
  return function(css) {
    // We can stop already when we don't have any @apply rules. Vue users: you're welcome!
    if (!hasAtRule(css, 'apply')) {
      return css
    }

    // Tree already contains @tailwind rules, don't prepend default Tailwind tree
    if (hasAtRule(css, 'tailwind')) {
      return processApplyAtRules(css, postcss.root(), config)
    }

    // Tree contains no @tailwind rules, so generate all of Tailwind's styles and
    // prepend them to the user's CSS. Important for <style> blocks in Vue components.
    const generateLookupTree =
      configChanged || defaultTailwindTree === null
        ? () => {
            return postcss([
              substituteTailwindAtRules(config, getProcessedPlugins()),
              evaluateTailwindFunctions(config),
              substituteVariantsAtRules(config, getProcessedPlugins()),
              substituteResponsiveAtRules(config),
              convertLayerAtRulesToControlComments(config),
              substituteScreenAtRules(config),
            ])
              .process(
                `
                  @tailwind base;
                  @tailwind components;
                  @tailwind utilities;
                `,
                { from: undefined }
              )
              .then(result => {
                defaultTailwindTree = result
                return defaultTailwindTree
              })
          }
        : () => Promise.resolve(defaultTailwindTree)

    return generateLookupTree().then(result => {
      return processApplyAtRules(css, result.root, config)
    })
  }
}
<|endoftext|>


<commit_before>module.exports = function (app) {
  /**
   * I can start putting my routing middlewares here
   */
  app.get('/',(req, res, next)=>{
    console.log('reqdze',req.body, req.fields, req.files)
    res.status(200)
      .format({
        html: _ => res.send('
It works!
'),
        text: _ => res.send('It works!'),
        json: _ => res.json({message: 'It works!'})
      })
  })

  return app
}
<commit_msg>remove debug log<commit_after>module.exports = function (app) {
  /**
   * I can start putting my routing middlewares here
   */
  app.get('/',(req, res, next)=>{
    res.status(200)
      .format({
        html: _ => res.send('
It works!
'),
        text: _ => res.send('It works!'),
        json: _ => res.json({message: 'It works!'})
      })
  })

  return app
}
<|endoftext|>


<commit_before>function checkPerms() {
 if (globalCode == 2639301) {
  document.getElementById('loadVideo').src = "https://darkheart527.github.io/domain-storage/XiaoYing - James.mp4";
  document.getElementById('gCArea').style.visibility = 'hidden';
  alert("Successful Login - Page Ex's Page Logged Into")
  localStorage.globalCode001 = globalCode;
 } else {
  document.getElementById('gCArea').style.visibility = 'hidden';
  alert('Your Gc is incorrect');
 }
}

function loadGlobal() {
 if (localStorage.globalCode001 == null) {
  alert('There Is A Global On This Page');
 } else
 document.getElementById('gcBox').value = Number(localStorage.globalCode001)
 globalCode = Number(localStorage.globalCode001);
 checkPerms();
}
<commit_msg>Update exPage.js<commit_after>function checkPerms() {
 if (globalCode == 2639301) {
  document.getElementById('loadVideo').src = "https://darkheart527.github.io/domain-storage/XiaoYing - James.mp4";
  document.getElementById('gCArea').style.visibility = 'hidden';
  alert("Successful Login - Page Ex's Page Logged Into")
  localStorage.globalCode001 = globalCode;
 } else {
  document.getElementById('gCArea').style.visibility = 'hidden';
  alert('Your Gc is incorrect');
 }
}

function loadGlobal() {
 if (localStorage.globalCode001 == null) {
  alert('There Is A Global On This Page');
 } else
 document.getElementById('gcBox').value = Number(localStorage.globalCode001);
 globalCode = Number(localStorage.globalCode001);
 checkPerms();
}
<|endoftext|>


<commit_before>// 'get' - Promise extension
//
// promise.get(name)
//
// Resolves with property of resolved object

"use strict";

var value    = require("es5-ext/object/valid-value")
  , deferred = require("../../deferred")

  , reduce = Array.prototype.reduce
  , resolve = deferred.resolve, reject = deferred.reject;

deferred.extend("get", function (/* …name*/) {
	var def;
	if (!this.pending) this.pending = [];
	def = deferred();
	this.pending.push("get", [arguments, def.resolve, def.reject]);
	return def.promise;

}, function (args, resolve, reject) {
	var result;
	if (this.failed) reject(this.value);
	try {
		result = reduce.call(args, function (obj, key) {
			return value(obj)[String(key)];
		}, this.value);
	} catch (e) {
		reject(e);
		return;
	}
	resolve(result);
}, function (/* …name*/) {
	var result;
	if (this.failed) return this;
	try {
		result = reduce.call(arguments, function (obj, key) {
			return value(obj)[String(key)];
		}, this.value);
	} catch (e) {
		return reject(e);
	}
	return resolve(result);
});
<commit_msg>style: prettier<commit_after>// 'get' - Promise extension
//
// promise.get(name)
//
// Resolves with property of resolved object

"use strict";

var value    = require("es5-ext/object/valid-value")
  , deferred = require("../../deferred");

var reduce = Array.prototype.reduce, resolve = deferred.resolve, reject = deferred.reject;

deferred.extend(
	"get",
	function (/* …name*/) {
		var def;
		if (!this.pending) this.pending = [];
		def = deferred();
		this.pending.push("get", [arguments, def.resolve, def.reject]);
		return def.promise;
	},
	function (args, resolve, reject) {
		var result;
		if (this.failed) reject(this.value);
		try {
			result = reduce.call(
				args,
				function (obj, key) {
					return value(obj)[String(key)];
				},
				this.value
			);
		} catch (e) {
			reject(e);
			return;
		}
		resolve(result);
	},
	function (/* …name*/) {
		var result;
		if (this.failed) return this;
		try {
			result = reduce.call(
				arguments,
				function (obj, key) {
					return value(obj)[String(key)];
				},
				this.value
			);
		} catch (e) {
			return reject(e);
		}
		return resolve(result);
	}
);
<|endoftext|>


<commit_before>const Cookies          = require('js-cookie');
const moment           = require('moment');
const ClientBase       = require('./client_base');
const Login            = require('./login');
const ServerTime       = require('./server_time');
const BinarySocket     = require('./socket_base');
const getElementById   = require('../common_functions').getElementById;
const isVisible        = require('../common_functions').isVisible;
const getLanguage      = require('../language').get;
const State            = require('../storage').State;
const getPropertyValue = require('../utility').getPropertyValue;
const getAppId         = require('../../config').getAppId;

const GTM = (() => {
    const isGtmApplicable = () => (/^(1|1098|14473|15284|1108)$/.test(getAppId()));

    const getCommonVariables = () => ({
        country_ip: State.getResponse('website_status.clients_country'),
        language  : getLanguage(),
        pageTitle : pageTitle(),
        pjax      : State.get('is_loaded_by_pjax'),
        url       : document.URL,
        ...ClientBase.isLoggedIn() && {
            visitorId: ClientBase.get('loginid'),
            bom_email: ClientBase.get('email'),
        },
    });

    const pushDataLayer = (data) => {
        if (isGtmApplicable() && !Login.isLoginPages()) {
            dataLayer.push({
                ...getCommonVariables(),
                ...data,
            });
        }
    };

    const pageTitle = () => {
        const t = /^.+[:-]\s*(.+)$/.exec(document.title);
        return t && t[1] ? t[1] : document.title;
    };

    const eventHandler = (get_settings) => {
        if (!isGtmApplicable()) return;
        const login_event       = localStorage.getItem('GTM_login');
        const is_new_account    = localStorage.getItem('GTM_new_account') === '1';

        localStorage.removeItem('GTM_login');
        localStorage.removeItem('GTM_new_account');

        const affiliate_token = Cookies.getJSON('affiliate_tracking');
        if (affiliate_token) {
            pushDataLayer({ bom_affiliate_token: affiliate_token.t });
        }

        // Get current time (moment, set by server), else fallback to client time
        const moment_now = window.time || moment().utc();
        const data = {
            visitorId         : ClientBase.get('loginid'),
            bom_account_type  : ClientBase.getAccountType(),
            bom_currency      : ClientBase.get('currency'),
            bom_country       : get_settings.country,
            bom_country_abbrev: get_settings.country_code,
            bom_email         : get_settings.email,
            url               : window.location.href,
            bom_today         : moment_now.unix(),
        };

        if (is_new_account) {
            data.event = 'new_account';
            data.bom_date_joined = data.bom_today;
        }

        if (!ClientBase.get('is_virtual')) {
            data.bom_age       = moment_now.diff(moment.unix(get_settings.date_of_birth).utc(), 'year');
            data.bom_firstname = get_settings.first_name;
            data.bom_lastname  = get_settings.last_name;
            data.bom_phone     = get_settings.phone;
        }

        if (login_event) {
            data.event = login_event;
            BinarySocket.wait('mt5_login_list').then((response) => {
                (response.mt5_login_list || []).forEach((obj) => {
                    const acc_type = (ClientBase.getMT5AccountType(obj.group) || '')
                        .replace('real_vanuatu', 'financial').replace('vanuatu_', '').replace('costarica', 'gaming'); // i.e. financial_cent, demo_cent, demo_gaming, real_gaming
                    if (acc_type) {
                        data[`mt5_${acc_type}_id`] = obj.login;
                    }
                });
                pushDataLayer(data);
            });
        } else {
            pushDataLayer(data);
        }

        // check if there are any transactions in the last 30 days for UX interview selection
        BinarySocket.send({ statement: 1, limit: 1 }).then((response) => {
            const last_transaction_timestamp = getPropertyValue(response, ['statement', 'transactions', '0', 'transaction_time']);
            pushDataLayer({
                bom_transaction_in_last_30d: !!last_transaction_timestamp && moment(last_transaction_timestamp * 1000).isAfter(ServerTime.get().subtract(30, 'days')),
            });
        });
    };

    const pushPurchaseData = (response) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        const buy = response.buy;
        if (!buy) return;
        const req  = response.echo_req.passthrough;
        const data = {
            event             : 'buy_contract',
            bom_ui            : 'legacy',
            bom_symbol        : req.symbol,
            bom_market        : getElementById('contract_markets').value,
            bom_currency      : req.currency,
            bom_contract_type : req.contract_type,
            bom_contract_id   : buy.contract_id,
            bom_transaction_id: buy.transaction_id,
            bom_buy_price     : buy.buy_price,
            bom_payout        : buy.payout,
        };
        Object.assign(data, {
            bom_amount     : req.amount,
            bom_basis      : req.basis,
            bom_expiry_type: getElementById('expiry_type').value,
        });
        if (data.bom_expiry_type === 'duration') {
            Object.assign(data, {
                bom_duration     : req.duration,
                bom_duration_unit: req.duration_unit,
            });
        }
        if (isVisible(getElementById('barrier'))) {
            data.bom_barrier = req.barrier;
        } else if (isVisible(getElementById('barrier_high'))) {
            data.bom_barrier_high = req.barrier;
            data.bom_barrier_low  = req.barrier2;
        }
        if (isVisible(getElementById('prediction'))) {
            data.bom_prediction = req.barrier;
        }

        pushDataLayer(data);
    };

    const mt5NewAccount = (response) => {
        const acc_type = response.mt5_new_account.mt5_account_type ?
            `${response.mt5_new_account.account_type}_${response.mt5_new_account.mt5_account_type}` : // financial_cent, demo_cent, ...
            `${response.mt5_new_account.account_type === 'demo' ? 'demo' : 'real'}_gaming`;           // demo_gaming, real_gaming

        const gtm_data = {
            event          : 'mt5_new_account',
            bom_email      : ClientBase.get('email'),
            bom_country    : State.getResponse('get_settings.country'),
            mt5_last_signup: acc_type,
        };

        gtm_data[`mt5_${acc_type}_id`] = response.mt5_new_account.login;

        if (/demo/.test(acc_type) && !ClientBase.get('is_virtual')) {
            gtm_data.visitorId = ClientBase.getAccountOfType('virtual').loginid;
        }

        pushDataLayer(gtm_data);
    };

    // Pushes deposit & withdrawal data from transaction-stream to GTM
    const pushTransactionData = (response, extra_data = {}) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        if (!response.transaction || !response.transaction.action) return;
        if (!['deposit', 'withdrawal'].includes(response.transaction.action)) return;

        const moment_now  = window.time || moment().utc();
        const storage_key = 'GTM_transactions';

        // Remove values from prev days so localStorage doesn't grow to infinity
        let gtm_transactions = JSON.parse(localStorage.getItem(storage_key)) || {};
        if (Object.prototype.hasOwnProperty.call(gtm_transactions, 'timestamp')) {
            if (moment_now.isAfter(moment.unix(gtm_transactions.timestamp).utc(), 'day')) {
                localStorage.removeItem(storage_key);
                gtm_transactions = { timestamp: moment_now.unix() };
            }
        }
        const transactions_arr = gtm_transactions.transactions || [];
        if (!transactions_arr.includes(response.transaction.transaction_id)) {
            const data = {
                event           : 'transaction',
                bom_account_type: ClientBase.getAccountType(),
                bom_today       : moment_now.unix(),
                transaction     : {
                    id     : response.transaction.transaction_id,
                    type   : response.transaction.action,
                    time   : response.transaction.transaction_time,
                    amount : response.transaction.amount,
                    balance: response.transaction.balance,
                },
            };
            Object.assign(data, extra_data);
            pushDataLayer(data);

            transactions_arr.push(response.transaction.transaction_id);
            gtm_transactions.transactions = transactions_arr;
            gtm_transactions.timestamp    = gtm_transactions.timestamp || moment_now.unix();

            localStorage.setItem(storage_key, JSON.stringify(gtm_transactions));
        }
    };

    return {
        pushDataLayer,
        eventHandler,
        pushPurchaseData,
        pushTransactionData,
        mt5NewAccount,
        setLoginFlag: (event_name) => { if (isGtmApplicable()) localStorage.setItem('GTM_login', event_name); },
    };
})();

module.exports = GTM;
<commit_msg>remove app-id<commit_after>const Cookies          = require('js-cookie');
const moment           = require('moment');
const ClientBase       = require('./client_base');
const Login            = require('./login');
const ServerTime       = require('./server_time');
const BinarySocket     = require('./socket_base');
const getElementById   = require('../common_functions').getElementById;
const isVisible        = require('../common_functions').isVisible;
const getLanguage      = require('../language').get;
const State            = require('../storage').State;
const getPropertyValue = require('../utility').getPropertyValue;
const getAppId         = require('../../config').getAppId;

const GTM = (() => {
    const isGtmApplicable = () => (/^(1|1098|14473|15284)$/.test(getAppId()));

    const getCommonVariables = () => ({
        country_ip: State.getResponse('website_status.clients_country'),
        language  : getLanguage(),
        pageTitle : pageTitle(),
        pjax      : State.get('is_loaded_by_pjax'),
        url       : document.URL,
        ...ClientBase.isLoggedIn() && {
            visitorId: ClientBase.get('loginid'),
            bom_email: ClientBase.get('email'),
        },
    });

    const pushDataLayer = (data) => {
        if (isGtmApplicable() && !Login.isLoginPages()) {
            dataLayer.push({
                ...getCommonVariables(),
                ...data,
            });
        }
    };

    const pageTitle = () => {
        const t = /^.+[:-]\s*(.+)$/.exec(document.title);
        return t && t[1] ? t[1] : document.title;
    };

    const eventHandler = (get_settings) => {
        if (!isGtmApplicable()) return;
        const login_event       = localStorage.getItem('GTM_login');
        const is_new_account    = localStorage.getItem('GTM_new_account') === '1';

        localStorage.removeItem('GTM_login');
        localStorage.removeItem('GTM_new_account');

        const affiliate_token = Cookies.getJSON('affiliate_tracking');
        if (affiliate_token) {
            pushDataLayer({ bom_affiliate_token: affiliate_token.t });
        }

        // Get current time (moment, set by server), else fallback to client time
        const moment_now = window.time || moment().utc();
        const data = {
            visitorId         : ClientBase.get('loginid'),
            bom_account_type  : ClientBase.getAccountType(),
            bom_currency      : ClientBase.get('currency'),
            bom_country       : get_settings.country,
            bom_country_abbrev: get_settings.country_code,
            bom_email         : get_settings.email,
            url               : window.location.href,
            bom_today         : moment_now.unix(),
        };

        if (is_new_account) {
            data.event = 'new_account';
            data.bom_date_joined = data.bom_today;
        }

        if (!ClientBase.get('is_virtual')) {
            data.bom_age       = moment_now.diff(moment.unix(get_settings.date_of_birth).utc(), 'year');
            data.bom_firstname = get_settings.first_name;
            data.bom_lastname  = get_settings.last_name;
            data.bom_phone     = get_settings.phone;
        }

        if (login_event) {
            data.event = login_event;
            BinarySocket.wait('mt5_login_list').then((response) => {
                (response.mt5_login_list || []).forEach((obj) => {
                    const acc_type = (ClientBase.getMT5AccountType(obj.group) || '')
                        .replace('real_vanuatu', 'financial').replace('vanuatu_', '').replace('costarica', 'gaming'); // i.e. financial_cent, demo_cent, demo_gaming, real_gaming
                    if (acc_type) {
                        data[`mt5_${acc_type}_id`] = obj.login;
                    }
                });
                pushDataLayer(data);
            });
        } else {
            pushDataLayer(data);
        }

        // check if there are any transactions in the last 30 days for UX interview selection
        BinarySocket.send({ statement: 1, limit: 1 }).then((response) => {
            const last_transaction_timestamp = getPropertyValue(response, ['statement', 'transactions', '0', 'transaction_time']);
            pushDataLayer({
                bom_transaction_in_last_30d: !!last_transaction_timestamp && moment(last_transaction_timestamp * 1000).isAfter(ServerTime.get().subtract(30, 'days')),
            });
        });
    };

    const pushPurchaseData = (response) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        const buy = response.buy;
        if (!buy) return;
        const req  = response.echo_req.passthrough;
        const data = {
            event             : 'buy_contract',
            bom_ui            : 'legacy',
            bom_symbol        : req.symbol,
            bom_market        : getElementById('contract_markets').value,
            bom_currency      : req.currency,
            bom_contract_type : req.contract_type,
            bom_contract_id   : buy.contract_id,
            bom_transaction_id: buy.transaction_id,
            bom_buy_price     : buy.buy_price,
            bom_payout        : buy.payout,
        };
        Object.assign(data, {
            bom_amount     : req.amount,
            bom_basis      : req.basis,
            bom_expiry_type: getElementById('expiry_type').value,
        });
        if (data.bom_expiry_type === 'duration') {
            Object.assign(data, {
                bom_duration     : req.duration,
                bom_duration_unit: req.duration_unit,
            });
        }
        if (isVisible(getElementById('barrier'))) {
            data.bom_barrier = req.barrier;
        } else if (isVisible(getElementById('barrier_high'))) {
            data.bom_barrier_high = req.barrier;
            data.bom_barrier_low  = req.barrier2;
        }
        if (isVisible(getElementById('prediction'))) {
            data.bom_prediction = req.barrier;
        }

        pushDataLayer(data);
    };

    const mt5NewAccount = (response) => {
        const acc_type = response.mt5_new_account.mt5_account_type ?
            `${response.mt5_new_account.account_type}_${response.mt5_new_account.mt5_account_type}` : // financial_cent, demo_cent, ...
            `${response.mt5_new_account.account_type === 'demo' ? 'demo' : 'real'}_gaming`;           // demo_gaming, real_gaming

        const gtm_data = {
            event          : 'mt5_new_account',
            bom_email      : ClientBase.get('email'),
            bom_country    : State.getResponse('get_settings.country'),
            mt5_last_signup: acc_type,
        };

        gtm_data[`mt5_${acc_type}_id`] = response.mt5_new_account.login;

        if (/demo/.test(acc_type) && !ClientBase.get('is_virtual')) {
            gtm_data.visitorId = ClientBase.getAccountOfType('virtual').loginid;
        }

        pushDataLayer(gtm_data);
    };

    // Pushes deposit & withdrawal data from transaction-stream to GTM
    const pushTransactionData = (response, extra_data = {}) => {
        if (!isGtmApplicable() || ClientBase.get('is_virtual')) return;
        if (!response.transaction || !response.transaction.action) return;
        if (!['deposit', 'withdrawal'].includes(response.transaction.action)) return;

        const moment_now  = window.time || moment().utc();
        const storage_key = 'GTM_transactions';

        // Remove values from prev days so localStorage doesn't grow to infinity
        let gtm_transactions = JSON.parse(localStorage.getItem(storage_key)) || {};
        if (Object.prototype.hasOwnProperty.call(gtm_transactions, 'timestamp')) {
            if (moment_now.isAfter(moment.unix(gtm_transactions.timestamp).utc(), 'day')) {
                localStorage.removeItem(storage_key);
                gtm_transactions = { timestamp: moment_now.unix() };
            }
        }
        const transactions_arr = gtm_transactions.transactions || [];
        if (!transactions_arr.includes(response.transaction.transaction_id)) {
            const data = {
                event           : 'transaction',
                bom_account_type: ClientBase.getAccountType(),
                bom_today       : moment_now.unix(),
                transaction     : {
                    id     : response.transaction.transaction_id,
                    type   : response.transaction.action,
                    time   : response.transaction.transaction_time,
                    amount : response.transaction.amount,
                    balance: response.transaction.balance,
                },
            };
            Object.assign(data, extra_data);
            pushDataLayer(data);

            transactions_arr.push(response.transaction.transaction_id);
            gtm_transactions.transactions = transactions_arr;
            gtm_transactions.timestamp    = gtm_transactions.timestamp || moment_now.unix();

            localStorage.setItem(storage_key, JSON.stringify(gtm_transactions));
        }
    };

    return {
        pushDataLayer,
        eventHandler,
        pushPurchaseData,
        pushTransactionData,
        mt5NewAccount,
        setLoginFlag: (event_name) => { if (isGtmApplicable()) localStorage.setItem('GTM_login', event_name); },
    };
})();

module.exports = GTM;
<|endoftext|>


<commit_before>var trade_contract_back = function () {
    $('#find_another_contract').on('click', function (e) {
        if (page.url.history_supported) {
            e.preventDefault();
            window.history.back();
        }
    }).addClass('unbind_later');
};

var toggleStreaming = function() {
   if (document.hidden || document.webkitHidden) {
       BetForm.spot.clear();
       BetPrice.streaming.stop();
       BetPrice.order_form.hide_buy_button();
   } else {
       BetPrice.streaming.start();
   }
};

pjax_config_page('/trade', function() {
    return {
        onLoad: function() {
            trade_contract_back();
            BetForm.init();
            BetAnalysis.register_actions();
            BetForm.restore();
            if (typeof document.webkitHidden !== 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener("webkitvisibilitychange", toggleStreaming, false);
                }
            } else if (typeof document.hidden !== 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener("visibilitychange", toggleStreaming);
                }
            }

        },
        onUnload: function() {
            BetForm.unregister_actions();
            BetPrice.deregister();
            BetPrice.clear_buy_results();
            BetPrice.streaming.stop();
            BetAnalysis.reset();
            if (typeof document.webkitHidden !== 'undefined') {
                document.removeEventListener("webkitvisibilitychange", toggleStreaming);
            } else if (typeof document.hidden !== 'undefined') {
                document.removeEventListener("visibilitychange", toggleStreaming);
            }
        }
    };
});

pjax_config_page('rise_fall_table', function() {
    var duration_amount;
    var duration_unit;
    return {
        onLoad: function() {
            var trading_time = new BetForm.TradingTime();
            var duration = new BetForm.Time.Duration(trading_time);
            trading_time.init();
            //Perform as if we are pricing R_100 bets.
            trading_time.underlying = function() {
                return 'R_100';
            };

            var selected_duration;
            //We dont want to read/pollute our betform durations.
            trading_time.value = function(value) {
                if(value) {
                    selected_duration = value;
                }

                if(!selected_duration) {
                    var duration = page.url.param('duration_amount');
                    var units = page.url.param('duration_units');
                    if(typeof duration_amount === 'undefined' || typeof duration_amount === 'undefined') {
                        var min_unit = this.min_unit();
                        duration = min_unit.min;
                        unit = min_unit.units;
                    }

                    selected_duration = duration + unit;
                }

                return selected_duration;
            };

            duration.init();
            duration.register();
            duration.update_ui();

            $('#atleast').on('change', function () {
                duration.update_units_select();
                duration.update_ui();
            }).addClass('unbind_later');

            $('#rise_fall_calculate').on('click', function (event) {
                event.preventDefault();
                var calculate_button = this;
                $(this).hide();
                $('#rise_fall_calculating').show();
                var form = $('form[name=rise_fall]').get(0);
                var url = page.url.url_for('resources/rise_fall_table', getFormParams(form));
                $('#rise_fall_prices_div').html('');
                $.ajax({
                    url: url,
                    data: {
                            ajax_only: 1,
                            prices_only:  1,
                        },
                }).done(function(response) {
                    $('#rise_fall_prices_div').html(response);
                    page.url.update(url);
                    $('#rise_fall_calculating').hide();
                    $('#rise_fall_calculate').show();
                });
            }).addClass('unbind_later');
        },
    };
});

pjax_config_page('portfolio|trade.cgi|statement|f_manager_statement|f_manager_history|f_profit_table|profit_table', function() {
    return {
        onLoad: function() {
            BetSell.register();
        },
        onUnload: function() {
            BetSell.cleanup();
        }
    };
});

pjax_config_page('chart_application', function () {
    return {
        onLoad: function () {
            load_chart_app();
        }
    };
});
<commit_msg>add pjax load for newtrade<commit_after>var trade_contract_back = function () {
    $('#find_another_contract').on('click', function (e) {
        if (page.url.history_supported) {
            e.preventDefault();
            window.history.back();
        }
    }).addClass('unbind_later');
};

var toggleStreaming = function() {
   if (document.hidden || document.webkitHidden) {
       BetForm.spot.clear();
       BetPrice.streaming.stop();
       BetPrice.order_form.hide_buy_button();
   } else {
       BetPrice.streaming.start();
   }
};

pjax_config_page('/trade.cgi', function() {
    return {
        onLoad: function() {
            trade_contract_back();
            BetForm.init();
            BetAnalysis.register_actions();
            BetForm.restore();
            if (typeof document.webkitHidden !== 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener("webkitvisibilitychange", toggleStreaming, false);
                }
            } else if (typeof document.hidden !== 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener("visibilitychange", toggleStreaming);
                }
            }

        },
        onUnload: function() {
            BetForm.unregister_actions();
            BetPrice.deregister();
            BetPrice.clear_buy_results();
            BetPrice.streaming.stop();
            BetAnalysis.reset();
            if (typeof document.webkitHidden !== 'undefined') {
                document.removeEventListener("webkitvisibilitychange", toggleStreaming);
            } else if (typeof document.hidden !== 'undefined') {
                document.removeEventListener("visibilitychange", toggleStreaming);
            }
        }
    };
});

pjax_config_page('rise_fall_table', function() {
    var duration_amount;
    var duration_unit;
    return {
        onLoad: function() {
            var trading_time = new BetForm.TradingTime();
            var duration = new BetForm.Time.Duration(trading_time);
            trading_time.init();
            //Perform as if we are pricing R_100 bets.
            trading_time.underlying = function() {
                return 'R_100';
            };

            var selected_duration;
            //We dont want to read/pollute our betform durations.
            trading_time.value = function(value) {
                if(value) {
                    selected_duration = value;
                }

                if(!selected_duration) {
                    var duration = page.url.param('duration_amount');
                    var units = page.url.param('duration_units');
                    if(typeof duration_amount === 'undefined' || typeof duration_amount === 'undefined') {
                        var min_unit = this.min_unit();
                        duration = min_unit.min;
                        unit = min_unit.units;
                    }

                    selected_duration = duration + unit;
                }

                return selected_duration;
            };

            duration.init();
            duration.register();
            duration.update_ui();

            $('#atleast').on('change', function () {
                duration.update_units_select();
                duration.update_ui();
            }).addClass('unbind_later');

            $('#rise_fall_calculate').on('click', function (event) {
                event.preventDefault();
                var calculate_button = this;
                $(this).hide();
                $('#rise_fall_calculating').show();
                var form = $('form[name=rise_fall]').get(0);
                var url = page.url.url_for('resources/rise_fall_table', getFormParams(form));
                $('#rise_fall_prices_div').html('');
                $.ajax({
                    url: url,
                    data: {
                            ajax_only: 1,
                            prices_only:  1,
                        },
                }).done(function(response) {
                    $('#rise_fall_prices_div').html(response);
                    page.url.update(url);
                    $('#rise_fall_calculating').hide();
                    $('#rise_fall_calculate').show();
                });
            }).addClass('unbind_later');
        },
    };
});

pjax_config_page('portfolio|trade.cgi|statement|f_manager_statement|f_manager_history|f_profit_table|profit_table', function() {
    return {
        onLoad: function() {
            BetSell.register();
        },
        onUnload: function() {
            BetSell.cleanup();
        }
    };
});

pjax_config_page('chart_application', function () {
    return {
        onLoad: function () {
            load_chart_app();
        }
    };
});

pjax_config_page('newtrade', function () {
    return {
        onLoad: function () {
            TradeSocket.init();
            TradeSocket.send({offerings: {contracts: 0}});
        },
        onUnload: function() {
            TradeSocket.close();
        }
    };
});
<|endoftext|>


<commit_before>;(function(window) {
  'use strict';

  var angular = window.angular;

  angular
    .module('tuchong-daily')
    .controller('home', [
      '$scope',
      'Store',
      '$ionicLoading',
      '$timeout',
      'imageLoader',
      'share',
      '$ionicModal',
      '$rootScope',
      '$cordovaDialogs',
      home
    ]);

  function home(scope, Store, $ionicLoading, $timeout, imageLoader, share, $ionicModal, $rootScope, $cordovaDialogs) {
    // When Push Received,
    // Render this notified post as first post.
    $rootScope.$on('pushNotificationReceived', pushNotificationReceived);

    scope.share = share.popup;
    scope.makeCssUri = makeCssUri;
    scope.openZoom = openZoom;
    scope.hideZoom = hideZoom;

    var slides = null;
    var childrenSlides = {};

    var backgrounds = scope.backgrounds = [];
    var childrens = scope.childrens = {};

    // Show loading
    $ionicLoading.show();

    // Read local cache from localStorage
    if (Store.cache.collections)
      return setup(Store.cache.collections);

    // Open a request
    fetch();

    // Fetch fresh data from API server
    function fetch(id) {
      var query = {};

      if (id)
        query.postId = id;

      Store[id ? 'post' : 'hot'].get(query, success, fail);

      function success(data) {
        if (id) {
          data.postId = id;
          return setup([data]);
        }

        if (!data.collections)
          return fail();

        // Setup a few slides
        setup(data.collections);

        // Save all data to cache
        Store.save('collections', data);
      }

      function fail(err) {
        $ionicLoading.show({
          template: ' 网络连接失败...请稍后再试'
        });
        return false;
      }
    }

    // Setup slides view
    function setup(data) {
      var rendered = scope.collections && scope.collections.length > 0;

      scope.collections = rendered ?
        scope.collections.concat(data) :
        data;

      // Show befor init slides
      if (!scope.slidesReady)
        scope.slidesReady = true;

      // Hide loading
      $ionicLoading.hide();

      var targetIndex = rendered && data.length === 1 ?
        findIndex(data[0].postId, scope.collections) :
        0;

      // Load cover image
      loadCover(targetIndex, {
        setupChildrenSwiper: true
      });

      if (targetIndex === 0)
        loadCover(1);

      // Init the slides on next tick
      $timeout(function() {
        // When Push Received
        if (rendered && slides) {
          slides.updateSlidesSize();

          if (targetIndex !== 0)
            slides.slideTo(targetIndex);

          return;
        }

        slides = new Swiper('.swiper-container-collection', {
          onSlideChangeStart: function() {
            loadCover(slides.activeIndex, {
              setupChildrenSwiper: true
            });
          }
        });
      }, 10);
    }

    // Lazy loading the cover image of a slide
    function loadCover(index, opts) {
      // If this collection have on one picture
      if (scope.collections[index].images.length === 1)
        return loadImage(index);

      // Else, load its first child
      loadChildImage(index, 0);

      if (!opts || !opts.setupChildrenSwiper)
        return;

      if ('undefined' !== typeof(childrenSlides[index]))
        return;

      // Then setup its children slides
      $timeout(function() {
        setupChildrenSwiper(index);
      }, 10);
    }

    function findIndex(id, arr) {
      var target;
      angular.forEach(arr, function(item, index){
        if (item.postId === id)
          target = index;
      });
      return target;
    }

    function setupChildrenSwiper(index) {
      childrenSlides[index] = new Swiper('#children-' + index, {
        direction: 'vertical',
        onSlideChangeStart: function() {
          loadChildImage(index, childrenSlides[index].activeIndex);
        }
      });
    }

    // Update slides async
    function loadImage(index) {
      if (backgrounds[index])
        return scope.$apply();

      imageLoader.load(
        scope.collections[index].images[0].uri + '.jpg',
        function(localImage) {
          scope.backgrounds[index] = localImage;
          scope.$apply();
        }
      );
    }

    function loadChildImage(parentIndex, index) {
      if (Array.isArray(scope.childrens[parentIndex]) && scope.childrens[parentIndex][index])
        return scope.$apply();

      if (!Array.isArray(scope.childrens[parentIndex]))
        scope.childrens[parentIndex] = [];

      imageLoader.load(
        scope.collections[parentIndex].images[index].uri + '.jpg',
        function(localImage) {
          scope.childrens[parentIndex][index] = localImage;
          scope.$apply();
        }
      );
    }

    function openZoom(uri) {
      scope.zoomImage = uri;

      $ionicLoading.show({
        scope: scope,
        templateUrl: 'zoom-modal',
        hideOnStateChange: true
      });
    }

    function hideZoom() {
      $ionicLoading.hide();
    }

    function makeCssUri(str) {
      if (!str)
        return 'none';

      return 'url(' + str + ')';
    }

    function pushNotificationReceived(event, notification) {
      if (notification.collectionId)
        return fetch(notification.collectionId);

      $cordovaDialogs.alert(
        notification.alert, // message
        '收到通知', // title,
        '知道了' // button
      )
    }
  }
})(this);<commit_msg>Preload next slides cover image and next childs cover image<commit_after>;(function(window) {
  'use strict';

  var angular = window.angular;

  angular
    .module('tuchong-daily')
    .controller('home', [
      '$scope',
      'Store',
      '$ionicLoading',
      '$timeout',
      'imageLoader',
      'share',
      '$ionicModal',
      '$rootScope',
      '$cordovaDialogs',
      home
    ]);

  function home(scope, Store, $ionicLoading, $timeout, imageLoader, share, $ionicModal, $rootScope, $cordovaDialogs) {
    // When Push Received,
    // Render this notified post as first post.
    $rootScope.$on('pushNotificationReceived', pushNotificationReceived);

    scope.share = share.popup;
    scope.makeCssUri = makeCssUri;
    scope.openZoom = openZoom;
    scope.hideZoom = hideZoom;

    var slides = null;
    var childrenSlides = {};

    var backgrounds = scope.backgrounds = [];
    var childrens = scope.childrens = {};

    // Show loading
    $ionicLoading.show();

    // Read local cache from localStorage
    if (Store.cache.collections)
      return setup(Store.cache.collections);

    // Open a request
    fetch();

    // Fetch fresh data from API server
    function fetch(id) {
      var query = {};

      if (id)
        query.postId = id;

      Store[id ? 'post' : 'hot'].get(query, success, fail);

      function success(data) {
        if (id) {
          data.postId = id;
          return setup([data]);
        }

        if (!data.collections)
          return fail();

        // Setup a few slides
        setup(data.collections);

        // Save all data to cache
        Store.save('collections', data);
      }

      function fail(err) {
        $ionicLoading.show({
          template: ' 网络连接失败...请稍后再试'
        });
        return false;
      }
    }

    // Setup slides view
    function setup(data) {
      var rendered = scope.collections && scope.collections.length > 0;

      scope.collections = rendered ?
        scope.collections.concat(data) :
        data;

      // Show befor init slides
      if (!scope.slidesReady)
        scope.slidesReady = true;

      // Hide loading
      $ionicLoading.hide();

      var targetIndex = rendered && data.length === 1 ?
        findIndex(data[0].postId, scope.collections) :
        0;

      // Load cover image
      loadCover(targetIndex, {
        setupChildrenSwiper: true
      });

      if (targetIndex === 0)
        loadCover(1);

      // Init the slides on next tick
      $timeout(function() {
        // When Push Received
        if (rendered && slides) {
          slides.updateSlidesSize();

          if (targetIndex !== 0)
            slides.slideTo(targetIndex);

          return;
        }

        slides = new Swiper('.swiper-container-collection', {
          onSlideChangeStart: function() {
            loadCover(slides.activeIndex + 1, {
              setupChildrenSwiper: true,
              loadFirstChild: true
            });
          }
        });
      }, 10);
    }

    // Lazy loading the cover image of a slide
    function loadCover(index, opts) {
      // If this collection have on one picture
      if (scope.collections[index].images.length === 1)
        return loadImage(index);

      loadChildImage(index, 0);

      // Load its first child if required
      if (opts && opts.loadFirstChild)
        loadChildImage(index, 1);

      if (!opts || !opts.setupChildrenSwiper)
        return;

      if ('undefined' !== typeof(childrenSlides[index]))
        return;

      // Then setup its children slides
      $timeout(function() {
        setupChildrenSwiper(index);
      }, 10);
    }

    function findIndex(id, arr) {
      var target;
      angular.forEach(arr, function(item, index){
        if (item.postId === id)
          target = index;
      });
      return target;
    }

    function setupChildrenSwiper(index) {
      childrenSlides[index] = new Swiper('#children-' + index, {
        direction: 'vertical',
        onSlideChangeStart: function() {
          loadChildImage(index, childrenSlides[index].activeIndex);
          loadChildImage(index, childrenSlides[index].activeIndex + 1);
        }
      });
    }

    // Update slides async
    function loadImage(index) {
      if (backgrounds[index])
        return scope.$apply();

      if (!scope.collections[index])
        return;

      imageLoader.load(
        scope.collections[index].images[0].uri + '.jpg',
        function(localImage) {
          scope.backgrounds[index] = localImage;
          scope.$apply();
        }
      );
    }

    function loadChildImage(parentIndex, index) {
      if (Array.isArray(scope.childrens[parentIndex]) && scope.childrens[parentIndex][index])
        return scope.$apply();

      if (!Array.isArray(scope.childrens[parentIndex]))
        scope.childrens[parentIndex] = [];

      if (!scope.collections[parentIndex])
        return;

      if (!scope.collections[parentIndex].images[index])
        return;

      imageLoader.load(
        scope.collections[parentIndex].images[index].uri + '.jpg',
        function(localImage) {
          scope.childrens[parentIndex][index] = localImage;
          scope.$apply();
        }
      );
    }

    function openZoom(uri) {
      scope.zoomImage = uri;

      $ionicLoading.show({
        scope: scope,
        templateUrl: 'zoom-modal',
        hideOnStateChange: true
      });
    }

    function hideZoom() {
      $ionicLoading.hide();
    }

    function makeCssUri(str) {
      if (!str)
        return 'none';

      return 'url(' + str + ')';
    }

    function pushNotificationReceived(event, notification) {
      if (notification.collectionId)
        return fetch(notification.collectionId);

      $cordovaDialogs.alert(
        notification.alert, // message
        '收到通知', // title,
        '知道了' // button
      )
    }
  }
})(this);<|endoftext|>


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

var repl = require('repl')
  , ravendb = require('ravendb')

var useStore = function(r, url) {
  r.context.store = ravendb.use(url)
  r.context.db = r.context.store.defaultDb
}

var defineCommands = function(r) {
  r.defineCommand('store', {
    help: 'Use the RavenDB datastore at a url ".store <url>"',
    action: function(url) {
      if (!url) url = r.context.db.getUrl()
      else useStore(r, url)

      console.log('Using datastore at: ' + url)
      r.displayPrompt()
    }
  })

  r.defineCommand('stats', {
    help: 'Show statistics for the current database',
    action: function() {
      try {
        r.context.db.getStats(function(error, stats) {
          if (error) {
            console.error(error)
            r.displayPrompt()
            return
          }

          console.log(stats)
          r.context._ = stats
          r.displayPrompt()
        })
      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('collections', {
    help: 'Show all collections in the current database',
    action: function() {
      try {
        r.context.db.getCollections(function(error, collections) {
          if (error) {
            console.error(error)
            r.displayPrompt()
            return
          }

          if (!collections) console.log("No collections found.")
          else {
            for(var i=0; i < collections.length; i++) {
              console.log(collections[i])
            }
          }
          r.context._ = collections
          r.displayPrompt()
        })
      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('create', {
    help: 'Save a document to a collection (e.g., .create CollectionName { id: "users/tony", firstName: "Tony" })',
    action: function(args) {
      try {
        var match = /(\w+)\s+(.*)/.exec(args)
        if (match.length != 3) throw Error('Wrong number of arguments; see .help for .savedoc usage')

        var collection = match[1]
        eval('var doc = ' + match[2])

        r.context.db.saveDocument(collection, doc, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('read', {
    help: 'Get a document given its id (e.g., .read users/tony)',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for more information')

        var id = args
        r.context.db.getDocument(id, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('delete', {
    help: 'Delete a document given its id (e.g., .delete users/tony)',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for more information')

        var id = args
        r.context.db.deleteDocument(id, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('find', {
    help: 'Find documents (e.g., .find { firstName: "Tony" })',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for .find usage')

        eval('var argsDoc = ' + args)

        r.context.db.find(argsDoc, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('docs', {
    help: 'Retrieve documents in a collection (e.g., .doc Users)',
    action: function(args) {
      try {
        var match = /(\w+)/.exec(args)

        var collection = (match && match.length == 2) ? match[1] : null

        r.context.db.getDocsInCollection(collection, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('count', {
    help: 'Show the count of documents in a collection or in the database if left blank (e.g., .count Users)',
    action: function(args) {
      try {
        r.context.db.getDocumentCount(args, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })
      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('createIndex', {
    help: "Create an index with a name, map, and optional reduce: .create-index foobar { map: 'from doc in docs.Albums\rwhere doc.Genre != null\rselect new { Genre = doc.Genre.Id }'}",
    action: function(args) {
      try {
        var name, index = null
        var match = /^(\w+)\s+(.*)$/.exec(args)

        if (match.length != 3) {
          console.error('Unable to craete index: wrong number of arguments.  Type ".help" to see usage')
          return
        }

        name = match[1]
        index = match[2]

        eval ('var createIndexIndex = ' + index )

        r.context.db.createIndex(name,
                                 createIndexIndex['map'],
                                 createIndexIndex['reduce'],
                                 function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })
      } catch(e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('deleteIndex', {
    help: 'Delete an given its name (e.g., .delete AlbumsByGenre)',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for more information')

        var name = args
        r.context.db.deleteIndex(name, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })
}

var startInteractiveREPL = function(store) {
  console.log('RavenDB shell')

  var r = repl.start("> ")
  defineCommands(r)
  useStore(r, store)

  return r
}

var startEvalREPL = function(store, string) {
  var r = repl.start("> ")
  defineCommands(r)

  useStore(r, store)

  var lines = string.split('\n')

  r.displayPrompt()
  lines.forEach(function(line) {
    if (line) {
      r.rli.write(line + '\n')
    }
  })
  return r
}

var startFileREPL = function(store, filename) {
  // TODO: Copy the .load command code or just call .load
  var r = repl.start("> ")
  defineCommands(r)

  useStore(r, store)

  r.rli.write('.load ' + filename + '\n')

  return r
}

var ArgumentParser = require('argparse').ArgumentParser;
var parser = new ArgumentParser({
  version: '0.0.1',
  addHelp:true,
  description: 'RavenDB command line shell'
});
parser.addArgument(
  [ '-f', '--file' ],
  {
    help: 'load and execute a file of shell commands',
    dest: 'file'
  }
)
parser.addArgument(
  [ '-e', '--eval' ],
  {
    help: 'evaluate a single string of shell commands',
    dest: 'eval'
  }
)
parser.addArgument(
  [ '-s', '--store' ],
  {
    help: 'specify which data store to use (defaults to http://localhost:8080 if not specfied)',
    defaultValue: 'http://localhost:8080',
    dest: 'store'
  }
)
parser.addArgument(
  [ '--keep-open' ],
  {
    help: 'keep the shell open when the passed in file or eval is done executing',
    action: 'storeTrue',
    defaultValue: false,
    dest: 'keep-open'
  }
)
var args = parser.parseArgs();

var shell
var keepOpen = args['keep-open'] || false
var evalString = args['eval']
var file = args['file']
var store = args['store']

if (evalString) {
    shell = startEvalREPL(store, evalString)
} else if (file) {
    shell = startFileREPL(store, file)
}

if (!shell) {
  shell = startInteractiveREPL(store)
} else {
  if (!keepOpen) {
    shell.rli.close()
  }
}

<commit_msg>tweak --keep-open and add -ko alias<commit_after>#!/usr/bin/env node

var repl = require('repl')
  , ravendb = require('ravendb')

var useStore = function(r, url) {
  r.context.store = ravendb.use(url)
  r.context.db = r.context.store.defaultDb
}

var defineCommands = function(r) {
  r.defineCommand('store', {
    help: 'Use the RavenDB datastore at a url ".store <url>"',
    action: function(url) {
      if (!url) url = r.context.db.getUrl()
      else useStore(r, url)

      console.log('Using datastore at: ' + url)
      r.displayPrompt()
    }
  })

  r.defineCommand('stats', {
    help: 'Show statistics for the current database',
    action: function() {
      try {
        r.context.db.getStats(function(error, stats) {
          if (error) {
            console.error(error)
            r.displayPrompt()
            return
          }

          console.log(stats)
          r.context._ = stats
          r.displayPrompt()
        })
      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('collections', {
    help: 'Show all collections in the current database',
    action: function() {
      try {
        r.context.db.getCollections(function(error, collections) {
          if (error) {
            console.error(error)
            r.displayPrompt()
            return
          }

          if (!collections) console.log("No collections found.")
          else {
            for(var i=0; i < collections.length; i++) {
              console.log(collections[i])
            }
          }
          r.context._ = collections
          r.displayPrompt()
        })
      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('create', {
    help: 'Save a document to a collection (e.g., .create CollectionName { id: "users/tony", firstName: "Tony" })',
    action: function(args) {
      try {
        var match = /(\w+)\s+(.*)/.exec(args)
        if (match.length != 3) throw Error('Wrong number of arguments; see .help for .savedoc usage')

        var collection = match[1]
        eval('var doc = ' + match[2])

        r.context.db.saveDocument(collection, doc, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('read', {
    help: 'Get a document given its id (e.g., .read users/tony)',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for more information')

        var id = args
        r.context.db.getDocument(id, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('delete', {
    help: 'Delete a document given its id (e.g., .delete users/tony)',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for more information')

        var id = args
        r.context.db.deleteDocument(id, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('find', {
    help: 'Find documents (e.g., .find { firstName: "Tony" })',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for .find usage')

        eval('var argsDoc = ' + args)

        r.context.db.find(argsDoc, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('docs', {
    help: 'Retrieve documents in a collection (e.g., .doc Users)',
    action: function(args) {
      try {
        var match = /(\w+)/.exec(args)

        var collection = (match && match.length == 2) ? match[1] : null

        r.context.db.getDocsInCollection(collection, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('count', {
    help: 'Show the count of documents in a collection or in the database if left blank (e.g., .count Users)',
    action: function(args) {
      try {
        r.context.db.getDocumentCount(args, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })
      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('createIndex', {
    help: "Create an index with a name, map, and optional reduce: .create-index foobar { map: 'from doc in docs.Albums\rwhere doc.Genre != null\rselect new { Genre = doc.Genre.Id }'}",
    action: function(args) {
      try {
        var name, index = null
        var match = /^(\w+)\s+(.*)$/.exec(args)

        if (match.length != 3) {
          console.error('Unable to craete index: wrong number of arguments.  Type ".help" to see usage')
          return
        }

        name = match[1]
        index = match[2]

        eval ('var createIndexIndex = ' + index )

        r.context.db.createIndex(name,
                                 createIndexIndex['map'],
                                 createIndexIndex['reduce'],
                                 function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })
      } catch(e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })

  r.defineCommand('deleteIndex', {
    help: 'Delete an given its name (e.g., .delete AlbumsByGenre)',
    action: function(args) {
      try {
        if (!args) throw Error('Wrong number of arguments; see .help for more information')

        var name = args
        r.context.db.deleteIndex(name, function(error, result) {
          if (error) console.error(error)

          if (result) console.log(result)
          r.context._ = result
          r.displayPrompt()
        })

      } catch (e) {
        console.error(e)
        r.displayPrompt()
      }
    }
  })
}

var startInteractiveREPL = function(store) {
  console.log('RavenDB shell')

  var r = repl.start("> ")
  defineCommands(r)
  useStore(r, store)

  return r
}

var startEvalREPL = function(store, string) {
  var r = repl.start("> ")
  defineCommands(r)

  useStore(r, store)

  var lines = string.split('\n')

  r.displayPrompt()
  lines.forEach(function(line) {
    if (line) {
      r.rli.write(line + '\n')
    }
  })
  return r
}

var startFileREPL = function(store, filename) {
  // TODO: Copy the .load command code or just call .load
  var r = repl.start("> ")
  defineCommands(r)

  useStore(r, store)

  r.rli.write('.load ' + filename + '\n')

  return r
}

var ArgumentParser = require('argparse').ArgumentParser;
var parser = new ArgumentParser({
  version: '0.0.1',
  addHelp:true,
  description: 'RavenDB command line shell'
});
parser.addArgument(
  [ '-f', '--file' ],
  {
    help: 'load and execute a file of shell commands',
    dest: 'file'
  }
)
parser.addArgument(
  [ '-e', '--eval' ],
  {
    help: 'evaluate a single string of shell commands',
    dest: 'eval'
  }
)
parser.addArgument(
  [ '-s', '--store' ],
  {
    help: 'specify which data store to use (defaults to http://localhost:8080 if not specfied)',
    defaultValue: 'http://localhost:8080',
    dest: 'store'
  }
)
parser.addArgument(
  [ '-ko', '--keep-open' ],
  {
    help: 'keep the shell open when the passed in file or eval is done executing',
    action: 'storeTrue',
    defaultValue: false,
    dest: 'keep-open'
  }
)
var args = parser.parseArgs();

var shell
var keepOpen = args['keep-open']
var evalString = args['eval']
var file = args['file']
var store = args['store']

if (evalString) {
    shell = startEvalREPL(store, evalString)
} else if (file) {
    shell = startFileREPL(store, file)
}

if (!shell) {
  shell = startInteractiveREPL(store)
} else {
  if (!keepOpen) {
    shell.rli.close()
  }
}

<|endoftext|>