<commit_before>//var Rx = require('rx');
var arr = ["5", 2, 3, "hi", 7, 8, 9, "world"];
// of / skip / take / skipLast / takeLast / map / filter / reduce
var objOf = Rx.Observable.of(...arr).skip(2).take(6).takeLast(5).skipLast(2).map(x => parseInt(x))
    .filter(x => !isNaN(x)).reduce((x, y) => x + y, 0);
// from / first / last
var objFrom = Rx.Observable.from(arr).first().last().map(x => parseInt(x * x))
    .filter(x => !isNaN(x));
// merge / startWith / subscribe
var objMerge = Rx.Observable.merge(objOf, objFrom).startWith(">>> Begin <<<");
console.log("Hello Rxjs!");
objMerge.subscribe(x => console.log(x));
// just / flatMap / fromPromise
var objJustFlatMap = Rx.Observable.just("https://api.github.com/users")
    .flatMap(requestURL => Rx.Observable.fromPromise(jQuery.getJSON(requestURL)))
// fromEvent / buffer / delay / do
var countClick = document.querySelector("#countClick");
var clickResult = document.querySelector("#countClickResult");
var clickStream = Rx.Observable.fromEvent(countClick, "click");
var evenTimeStampStream = clickStream.buffer(() => clickStream.delay(1000))
    .map(event => event.length).do(length => console.log("Click Count : " + length)).filter(length => length === 2);
evenTimeStampStream.subscribe(event => {
    clickResult.innerHTML = "";
    objJustFlatMap.subscribe(data =>
        data.forEach(item =>
            clickResult.innerHTML += `

            ${item.login}

`))
})
// interval / concat / withLatestFrom
var timer1 = Rx.Observable.interval(2000).take(2);
var timer2 = Rx.Observable.interval(1000).take(3);
var timer3 = Rx.Observable.interval(500).take(4);
var timer4 = Rx.Observable.interval(1000);
var result1 = timer2.concat(timer3, timer1).withLatestFrom(timer4, (t123, t4) => [t123, t4]);
result1.subscribe(x => console.log(x));
// range / combineLatest
var weight = Rx.Observable.of(70, 72, 76, 79, 75);
var height = Rx.Observable.range(5, 3);
var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => { console.log("w : " + w + " : h :" + h); return w / (h * h) });
bmi.subscribe(x => console.log('BMI is ' + x));
// create
var objCreate = Rx.Observable.create(s => {
    s.next("Hello");
    s.next(Math.random());
    //s.error("Error!!!");
    s.next(s);
    s.completed();
});
objCreate.subscribe(n => console.log(n), e => console.error(e), () => console.log("World!"));
// defer / throw / empty
var clicksOrInterval = Rx.Observable.defer(() => {
    if (Math.random() > 0.5) {
        return Rx.Observable.throw('oops! :-)');
    } else {
        return Rx.Observable.empty().startWith(720);
    }
});
clicksOrInterval.subscribe(x => console.log(`clicksOrInterval : ${x}`), error => console.error(error));
// timer / mergeMap / never
var result2 = Rx.Observable.timer(10000, 1000).take(4).mergeMap(x =>
    x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.never().startWith("Empty")
);
result2.subscribe(x => console.log(x));
// fromEventPattern / dispose / Promise
function addClickHandler(handler) {
    document.addEventListener('click', handler);
}
function removeClickHandler(handler) {
    document.removeEventListener('click', handler);
}
var domClicks = Rx.Observable.fromEventPattern(
    addClickHandler,
    removeClickHandler
);
var subscription = domClicks.subscribe(mouseEvent => alert("X : " + mouseEvent.x + ", Y : " + mouseEvent.y));
var promise = new Promise(
    function (resolve, reject) {
        resolve("Dom click event has been disabled.");
        reject("Dom click event error.");
    }
);
clickStream.subscribe(e => {
    this.subscription.dispose();
    Rx.Observable.fromPromise(promise).subscribe(resolve => console.log(resolve), reject => console.error(reject));
});
// test test test
//var items1 = Rx.Observable.range(1, 10);
//var items2 = items1.map(i => i*100 );
//items1.withLatestFrom(items2, (i1, i2) => i1+i2).subscribe(x => console.log(x));
// scan / throttle / >>> audit
var oneClickResult = document.querySelector("#oneClickResult");
var oneClicks = Rx.Observable.fromEvent(document.querySelector("#oneClick"), 'click');
var result3 = oneClicks.throttle(3000);
oneClicks.map(c => 1).scan((acc, i) => acc + i, 0).subscribe(y =>
    console.log('%c One Clicked : ' + y, 'background: #222; color: #bada55'));
result3.subscribe(x => {
    oneClickResult.textContent = (oneClickResult.textContent === '' ? 0 : parseInt(oneClickResult.textContent)) + 1;
});
// zip
var zipObservable1 = Rx.Observable.interval(1000).take(5);
var zipObservable2 = Rx.Observable.interval(500).take(3);
Rx.Observable.zip(zipObservable1, zipObservable2, (z1, z2) => ({ Z1: z1, Z2: z2 })).subscribe(x => console.log(x));
// bufferCount / bufferTime / delayWhen
var objBufferCT = Rx.Observable.of('E', 'r', 'f', 'a', 'n').zip(Rx.Observable.interval(300).take(5), (x, y) => x);
objBufferCT.delay(new Date(new Date().getTime() + 1000)).bufferCount(2).reduce((p, c) => p + c, ">>>").subscribe(x => console.log(x));
objBufferCT.bufferTime(500)./*.delayWhen(x => Rx.Observable.interval(x.length * 1000).first()).*/subscribe(x => console.log(x));
//<commit_msg>bufferCount / bufferTime / delayWhen<commit_after>//var Rx = require('rx');
var arr = ["5", 2, 3, "hi", 7, 8, 9, "world"];
// of / skip / take / skipLast / takeLast / map / filter / reduce
var objOf = Rx.Observable.of(...arr).skip(2).take(6).takeLast(5).skipLast(2).map(x => parseInt(x))
    .filter(x => !isNaN(x)).reduce((x, y) => x + y, 0);
// from / first / last
var objFrom = Rx.Observable.from(arr).first().last().map(x => parseInt(x * x))
    .filter(x => !isNaN(x));
// merge / startWith / subscribe
var objMerge = Rx.Observable.merge(objOf, objFrom).startWith(">>> Begin <<<");
console.log("Hello Rxjs!");
objMerge.subscribe(x => console.log(x));
// just / flatMap / fromPromise
var objJustFlatMap = Rx.Observable.just("https://api.github.com/users")
    .flatMap(requestURL => Rx.Observable.fromPromise(jQuery.getJSON(requestURL)))
// fromEvent / buffer / delay / do
var countClick = document.querySelector("#countClick");
var clickResult = document.querySelector("#countClickResult");
var clickStream = Rx.Observable.fromEvent(countClick, "click");
var evenTimeStampStream = clickStream.buffer(() => clickStream.delay(1000))
    .map(event => event.length).do(length => console.log("Click Count : " + length)).filter(length => length === 2);
evenTimeStampStream.subscribe(event => {
    clickResult.innerHTML = "";
    objJustFlatMap.subscribe(data =>
        data.forEach(item =>
            clickResult.innerHTML += `

            ${item.login}

`))
})
// interval / concat / withLatestFrom
var timer1 = Rx.Observable.interval(2000).take(2);
var timer2 = Rx.Observable.interval(1000).take(3);
var timer3 = Rx.Observable.interval(500).take(4);
var timer4 = Rx.Observable.interval(1000);
var result1 = timer2.concat(timer3, timer1).withLatestFrom(timer4, (t123, t4) => [t123, t4]);
result1.subscribe(x => console.log(x));
// range / combineLatest
var weight = Rx.Observable.of(70, 72, 76, 79, 75);
var height = Rx.Observable.range(5, 3);
var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => { console.log("w : " + w + " : h :" + h); return w / (h * h) });
bmi.subscribe(x => console.log('BMI is ' + x));
// create
var objCreate = Rx.Observable.create(s => {
    s.next("Hello");
    s.next(Math.random());
    //s.error("Error!!!");
    s.next(s);
    s.completed();
});
objCreate.subscribe(n => console.log(n), e => console.error(e), () => console.log("World!"));
// defer / throw / empty
var clicksOrInterval = Rx.Observable.defer(() => {
    if (Math.random() > 0.5) {
        return Rx.Observable.throw('oops! :-)');
    } else {
        return Rx.Observable.empty().startWith(720);
    }
});
clicksOrInterval.subscribe(x => console.log(`clicksOrInterval : ${x}`), error => console.error(error));
// timer / mergeMap / never
var result2 = Rx.Observable.timer(10000, 1000).take(4).mergeMap(x =>
    x % 2 === 1 ? Rx.Observable.of('a', 'b', 'c') : Rx.Observable.never().startWith("Empty")
);
result2.subscribe(x => console.log(x));
// fromEventPattern / dispose / Promise
function addClickHandler(handler) {
    document.addEventListener('click', handler);
}
function removeClickHandler(handler) {
    document.removeEventListener('click', handler);
}
var domClicks = Rx.Observable.fromEventPattern(
    addClickHandler,
    removeClickHandler
);
var subscription = domClicks.subscribe(mouseEvent => alert("X : " + mouseEvent.x + ", Y : " + mouseEvent.y));
var promise = new Promise(
    function (resolve, reject) {
        resolve("Dom click event has been disabled.");
        reject("Dom click event error.");
    }
);
clickStream.subscribe(e => {
    this.subscription.dispose();
    Rx.Observable.fromPromise(promise).subscribe(resolve => console.log(resolve), reject => console.error(reject));
});
// test test test
//var items1 = Rx.Observable.range(1, 10);
//var items2 = items1.map(i => i*100 );
//items1.withLatestFrom(items2, (i1, i2) => i1+i2).subscribe(x => console.log(x));
// scan / throttle / >>> audit
var oneClickResult = document.querySelector("#oneClickResult");
var oneClicks = Rx.Observable.fromEvent(document.querySelector("#oneClick"), 'click');
var result3 = oneClicks.throttle(3000);
oneClicks.map(c => 1).scan((acc, i) => acc + i, 0).subscribe(y =>
    console.log('%c One Clicked : ' + y, 'background: #222; color: #bada55'));
result3.subscribe(x => {
    oneClickResult.textContent = (oneClickResult.textContent === '' ? 0 : parseInt(oneClickResult.textContent)) + 1;
});
// zip
var zipObservable1 = Rx.Observable.interval(1000).take(5);
var zipObservable2 = Rx.Observable.interval(500).take(3);
Rx.Observable.zip(zipObservable1, zipObservable2, (z1, z2) => ({ Z1: z1, Z2: z2 })).subscribe(x => console.log(x));
// bufferCount / bufferTime / delayWhen
var objBufferCT = Rx.Observable.of('E', 'r', 'f', 'a', 'n').zip(Rx.Observable.interval(300).take(5), (x, y) => x);
objBufferCT.delay(new Date(new Date().getTime() + 1000)).bufferCount(2).reduce((p, c) => p + c, ">>>").subscribe(x => console.log(x));
objBufferCT.bufferTime(500)./*delayWhen(x => Rx.Observable.interval(x.length * 1000).first()).*/subscribe(x => console.log(x));
//<|endoftext|>


<commit_before>/* Copyright (c) 2018 e-soa Jacques Desodt, MIT License */
'use strict'

/* THEN PATTERN
   then: {
      actions: [ {role: 'a_role', cmd: 'a_command', ... }, { ... }, ... ],
      async: true|false,
      results: {
        includes_start: true|false
      	name: 'a_field_name'
      }
   }
   See: https://github.com/jack-y/seneca-entity-crud/tree/master/docs/then.md
*/

/* Prerequisites */
const promise = require('bluebird')

var processThen = {}
processThen.separator = '%'
processThen.entityPattern = processThen.separator + '_entity' + processThen.separator

/* Gets the result object depending on the "then" results argument */
processThen.getResultEntity = function (entity, thenArgs, thenResults) {
  /* Initializes */
  var result = { success: true }
  /* Checks if a result object is needed */
  if (thenArgs && thenArgs.results) {
    /* Checks if the starting-action result must be used */
    if (thenArgs.results.includes_start) {
      result = { success: (entity !== null), entity: entity }
    }
    /* Checks if the "then" results must be added */
    if (thenArgs.results.name) {
      result[thenArgs.results.name] = thenResults
    }
  }
  /* Returns the result object */
  return result
}

/* Gets the result object depending on the "then" results argument */
processThen.getResultList = function (listResult, thenArgs, thenResults) {
  /* Initializes */
  var result = { success: true }
  /* Checks if a result object is needed */
  if (thenArgs && thenArgs.results) {
    /* Checks if the starting-action result must be used */
    if (thenArgs.results.includes_start) {
      result = { success: (listResult !== null), list: listResult, count: listResult ? listResult.length : 0 }
    }
    /* Checks if the "then" results must be added */
    if (thenArgs.results.name) {
      result[thenArgs.results.name] = thenResults
    }
  }
  /* Returns the result object */
  return result
}

/* Replaces the patterns in the object by the entity values */
processThen.replaceValues = function (entity, object) {
  /* Initializes */
  var newObject = {}
  /* Loops on the object properties */
  if (object !== null && typeof object === 'object') {
    for (var prop in object) {
      if (object.hasOwnProperty(prop)) {
        newObject[prop] = processThen.replaceValuesForProperty(entity, object[prop])
      }
    }
  }
  return newObject
}

/* Replacves the patterns by thier value in a string */
processThen.replaceValuesForString = function (entity, value) {
  /* Initializes */
  var newValue = null
  /* Checks the arguments */
  if (value && (typeof value === 'string' || value instanceof String)) {
    var newValue = value + ''
    /* Loops on the entity properties */
    if (entity !== null && typeof entity === 'object') {
      for (var prop in entity) {
        if (entity.hasOwnProperty(prop)) {
          var pattern = processThen.separator + prop + processThen.separator
          newValue = newValue.replace(new RegExp(pattern, 'g'), entity[prop]) + ''
        }
      }
    }
  }
  return newValue
}

/* Replaces the patterns in a value by the entity values */
processThen.replaceValuesForProperty = function (entity, value) {
  /* Initializes */
  var newValue = value
  /* Checks the args */
  if (value) {
    /* Special case: entity */
    if (value === processThen.entityPattern) {
      newValue = entity
    } else {
      /* Is the value a string? */
      if (typeof value === 'string' || value instanceof String) {
        newValue = processThen.replaceValuesForString(entity, value)
      } else {
        /* Is the value an object? */
        if (value !== null && typeof value === 'object') {
          newValue = processThen.replaceValues(entity, value)
        }
      }
    }
  }
  return newValue
}

/* Runs one action for one entity */
processThen.runAction = function (act, entity, action) {
  return new Promise(function (resolve, reject) {
    /* Replaces the values */
    var realAction = processThen.replaceValues(entity, action)
    /* Runs the action */
    act(realAction)
    .then(function (result) { return resolve(result) })
    .catch(function (err) { return reject(err) })
  })
}

/* Proceeds the "then" actions on an entity */
processThen.thenForEntity = function (act, entity, thenArgs) {
  return new Promise(function (resolve, reject) {
    /* Checks if the entity and the "then" actions array are defined */
    if (entity && thenArgs && thenArgs.actions && thenArgs.actions.length) {
      /* Checks the execution mode */
      if (thenArgs.async) {
        /* Runs the actions in asynchronous mode */
        processThen.thenForEntityAsync(act, entity, thenArgs)
        .then(function (thenResults) {
          return resolve(processThen.getResultEntity(entity, thenArgs, thenResults))
        })
        .catch(function (err) { return reject(err) })
      } else {
        /* Runs the actions in synchronous mode */
        processThen.thenForEntitySync(act, entity, thenArgs)
        .then(function (thenResults) {
          return resolve(processThen.getResultEntity(entity, thenArgs, thenResults))
        })
        .catch(function (err) { return reject(err) })
      }
    } else {
      return resolve({ success: (entity !== null), entity: entity })
    }
  })
}

/* Proceeds the "then" actions in asynchronous mode */
processThen.thenForEntityAsync = function (act, entity, thenArgs) {
  return new Promise(function (resolve, reject) {
    /* Checks the arguments */
    if (entity && thenArgs && thenArgs.actions) {
      /* Initializes */
      var promises = []
      /* Loops on the "then" actions and the list of entities */
      for (var i = 0; i < thenArgs.actions.length; i++) {
        promises.push(processThen.runAction(act, entity, thenArgs.actions[i]))
      }
      /* Runs the promises */
      if (promises.length > 0) {
        promise.all(promises)
        .then(function (results) { return resolve(results) })
        .catch(function (err) { return reject(err) }) // One action returns an error
      } else { return resolve([]) } // No action
    } else { return resolve([]) } // No argument
  })
}

/* Proceeds the "then" actions in synchronous mode */
processThen.thenForEntitySync = function (act, entity, thenArgs) {
  return new Promise(function (resolve, reject) {
    /* Initializes */
    var indexAction = 0
    var results = []
    /* The recursive function */
    var recursive = function (act, entity, actions, indexAction) {
      processThen.runAction(act, entity, actions[indexAction])
      .then(function (result) {
        /* Memorizes the result */
        results.push(result)
        /* Runs on the next action */
        indexAction++
        if (indexAction < actions.length) {
          recursive(act, entity, actions, indexAction)
        } else {
          /* All the actions on the entity are done */
          return resolve(results)
        }
      })
      .catch(function (err) { return reject(err) })
    }
    /* Checks if the lists are empty */
    if (entity && thenArgs && thenArgs.actions && thenArgs.actions.length > 0) {
      /* Calls the resursive function */
      recursive(act, entity, thenArgs.actions, indexAction)
    } else {
      /* Nothing to proceed */
      return resolve([])
    }
  })
}

/* Proceeds the "then" actions on a list of entities */
processThen.thenForList = function (act, listResult, thenArgs) {
  return new Promise(function (resolve, reject) {
    /* Checks if the list and the "then" actions array are defined */
    if (listResult && listResult.length && thenArgs && thenArgs.actions && thenArgs.actions.length) {
      /* Checks the execution mode */
      if (thenArgs.async) {
        /* Runs the actions in asynchronous mode */
        processThen.thenForListAsync(act, listResult, thenArgs)
        .then(function (thenResults) {
          return resolve(processThen.getResultList(listResult, thenArgs, thenResults))
        })
        .catch(function (err) { return reject(err) })
      } else {
        /* Runs the actions in synchronous mode */
        processThen.thenForListSync(act, listResult, thenArgs)
        .then(function (thenResults) {
          return resolve(processThen.getResultList(listResult, thenArgs, thenResults))
        })
        .catch(function (err) { return reject(err) })
      }
    } else {
      return resolve({ success: (listResult !== null), list: listResult, count: listResult ? listResult.length : 0 })
    }
  })
}

/* Proceeds the "then" actions in asynchronous mode */
processThen.thenForListAsync = function (act, listResult, thenArgs) {
  return new Promise(function (resolve, reject) {
    /* Checks the arguments */
    if (listResult && thenArgs && thenArgs.actions) {
      /* Initializes */
      var promises = []
      /* Loops on the "then" actions and the list of entities */
      for (var i = 0; i < thenArgs.actions.length; i++) {
        for (var j = 0; j < listResult.length; j++) {
          promises.push(processThen.runAction(act, listResult[j], thenArgs.actions[i]))
        }
      }
      /* Runs the promises */
      if (promises.length > 0) {
        promise.all(promises)
        .then(function (results) { return resolve(results) })
        .catch(function (err) { return reject(err) }) // One action returns an error
      } else { return resolve([]) } // No action
    } else { return resolve([]) } // No argument
  })
}

/* Proceeds the "then" actions in synchronous mode */
processThen.thenForListSync = function (act, listResult, thenArgs) {
  return new Promise(function (resolve, reject) {
    /* Initializes */
    var indexEntity = 0
    var indexAction = 0
    var results = []
    /* The recursive function */
    var recursive = function (act, entities, actions, indexEntity, indexAction) {
      processThen.runAction(act, entities[indexEntity], actions[indexAction])
      .then(function (result) {
        /* Memorizes the result */
        results.push(result)
        /* Runs on the next entity */
        indexEntity++
        if (indexEntity < entities.length) {
          recursive(act, entities, actions, indexEntity, indexAction)
        } else {
          /* Runs on the next action */
          indexEntity = 0
          indexAction++
          if (indexAction < actions.length) {
            recursive(act, entities, actions, indexEntity, indexAction)
          } else {
            /* All the actions on entities are done */
            return resolve(results)
          }
        }
      })
      .catch(function (err) { return reject(err) })
    }
    /* Checks if the lists are empty */
    if (listResult && listResult.length > 0 &&
      thenArgs && thenArgs.actions && thenArgs.actions.length > 0) {
      /* Calls the resursive function */
      recursive(act, listResult, thenArgs.actions, indexEntity, indexAction)
    } else {
      /* Nothing to proceed */
      return resolve([])
    }
  })
}

/* Exports this plugin */
module.exports = processThen
<commit_msg>This project has been moved to GitLab<commit_after><|endoftext|>


<commit_before>module.exports = {
    auth: {
        type: {
            Account: 'account',
            Profile: 'profile',
            Role: 'role'
        },
        collection: {
            Account: 'accounts',
            Role: 'roles'
        }
    },
    inventory: {
        StockIn: 'stock-ins',
        StockOut: 'stock-outs',
        Inventory: 'inventories',
        InventoryMovement: 'inventory-movements',
        TransferInDoc: 'transfer-in-docs',
        TransferOutDoc: 'transfer-out-docs',
        FinishedGoodsDoc: 'finished-goods-docs',
        ExpeditionDoc: 'expedition-docs',
        AdjustmentDoc: 'adjustment-docs',
        StockOpnameDoc: 'stock-opname-docs'
    },
    manufacture: {
        Finishing: 'finishings',
        CostCalculationDocument: 'cost-calculation-documents',
        FabricConsumptionDocument: 'fabric-consumption-documents',
        DesignTrackingBoard: 'design-tracking-boards',
        DesignTrackingStage: 'design-tracking-stages',
        DesignTrackingDesign: 'design-tracking-designs',
        DesignTrackingActivity: 'design-tracking-activities'
    },
    master: {
        Item: 'items',
        FinishedGoods: 'items',
        Material: 'items',
        article: {
            ArticleApproval: 'article-approvals',
            ArticleBrand: 'article-brands',
            ArticleCategory: 'article-categories',
            ArticleColor: 'article-colors',
            ArticleCostCalculationDetail: 'article-cost-calculation-details',
            ArticleCostCalculation: 'article-cost-calculations',
            ArticleCounter: 'article-counters',
            ArticleMaterial: 'article-materials',
            ArticleMotif: 'article-motifs',
            ArticleOrigin: 'article-origins',
            ArticleSeason: 'article-seasons',
            ArticleSize: 'article-sub-sizes',
            ArticleSubCounter: 'article-sub-counters',
            ArticleTheme: 'article-themes',
            ArticleType: 'article-types',
            ArticleVariant: 'article-variants',
            Article: 'articles',
            ArticleSeason: 'article-seasons',
            ArticleProcess: 'article-process',
            ArticleSubProcess: 'article-sub-process',
            ArticleCollection: 'article-collections',
            ArticleSubCollection: 'article-sub-collections',
            ArticleMaterialComposition: 'article-material-compositions',
            ArticleSubMaterialComposition: 'article-sub-material-compositions',
        },
        Module: 'modules',
        Bank: 'banks',
        CardType: 'card-types',
        Store: 'stores',
        Storage: 'storages',
        Supplier: 'suppliers',
        StoreShift: 'store-shifts',
        Division: 'division',
        Unit: 'unit',
        Colour: 'colours',
        collection: {
            Division: 'divisions',
            Unit: 'units',
            Colour: 'colours'
        },
        ExpeditionService: 'expedition-services',
        RangeDiscProduct: 'range-disc-products',
        DesignTrackingReason: 'design-tracking-reasons'
    },
    merchandiser: {
        SPKDoc: 'spk-docs'
    },
    sales: {
        SalesDoc: 'sales-docs',
        SalesReturnDoc: 'sales-return-docs',
        Promo: 'promos'
    },
    purchasing: {
        type: {
            PurchaseRequest: 'purchase-request'
        },
        collection: {
            PurchaseRequest: 'purchase-requests'
        }
    }
};<commit_msg>update map<commit_after>module.exports = {
    auth: {
        type: {
            Account: 'account',
            Profile: 'profile',
            Role: 'role'
        },
        collection: {
            Account: 'accounts',
            Role: 'roles'
        }
    },
    inventory: {
        StockIn: 'stock-ins',
        StockOut: 'stock-outs',
        Inventory: 'inventories',
        InventoryMovement: 'inventory-movements',
        TransferInDoc: 'transfer-in-docs',
        TransferOutDoc: 'transfer-out-docs',
        FinishedGoodsDoc: 'finished-goods-docs',
        ExpeditionDoc: 'expedition-docs',
        AdjustmentDoc: 'adjustment-docs',
        StockOpnameDoc: 'stock-opname-docs'
    },
    manufacture: {
        Finishing: 'finishings',
        CostCalculationDocument: 'cost-calculation-documents',
        FabricConsumptionDocument: 'fabric-consumption-documents',
        DesignTrackingBoard: 'design-tracking-boards',
        DesignTrackingStage: 'design-tracking-stages',
        DesignTrackingDesign: 'design-tracking-designs',
        DesignTrackingActivity: 'design-tracking-activities'
    },
    master: {
        Item: 'items',
        FinishedGoods: 'items',
        Material: 'items',
        article: {
            ArticleApproval: 'article-approvals',
            ArticleBrand: 'article-brands',
            ArticleCategory: 'article-categories',
            ArticleColor: 'article-colors',
            ArticleCostCalculationDetail: 'article-cost-calculation-details',
            ArticleCostCalculation: 'article-cost-calculations',
            ArticleCounter: 'article-counters',
            ArticleMaterial: 'article-materials',
            ArticleMotif: 'article-motifs',
            ArticleOrigin: 'article-origins',
            ArticleSeason: 'article-seasons',
            ArticleSize: 'article-sub-sizes',
            ArticleSubCounter: 'article-sub-counters',
            ArticleTheme: 'article-themes',
            ArticleType: 'article-types',
            ArticleVariant: 'article-variants',
            Article: 'articles',
            ArticleSeason: 'article-seasons',
            ArticleProcess: 'article-process',
            ArticleSubProcess: 'article-sub-process',
            ArticleCollection: 'article-collections',
            ArticleSubCollection: 'article-sub-collections',
            ArticleMaterialComposition: 'article-material-compositions',
            ArticleSubMaterialComposition: 'article-sub-material-compositions',
        },
        Module: 'modules',
        Bank: 'banks',
        CardType: 'card-types',
        Store: 'stores',
        Storage: 'storages',
        Supplier: 'suppliers',
        StoreShift: 'store-shifts',
        Division: 'division',
        Unit: 'unit',
        Colour: 'colours',
        collection: {
            Division: 'divisions',
            Unit: 'units',
            Colour: 'colours'
        },
        ExpeditionService: 'expedition-services',
        RangeDiscProduct: 'range-disc-products',
        DesignTrackingReason: 'design-tracking-reasons',
        Budget: 'budgets',
        Category: 'categories',
        Currency: 'currencies',
        uom: 'unit-of-measurements',
        Product: 'products'
    },
    merchandiser: {
        SPKDoc: 'spk-docs'
    },
    sales: {
        SalesDoc: 'sales-docs',
        SalesReturnDoc: 'sales-return-docs',
        Promo: 'promos'
    },
    purchasing: {
        type: {
            PurchaseRequest: 'purchase-request'
        },
        collection: {
            PurchaseRequest: 'purchase-requests'
        }
    }
};<|endoftext|>


<commit_before>var GameboyJS;
(function (GameboyJS) {
"use strict";

// Memory bank controllers

var MBC = {};

// Create an MBC instance depending on the type specified in the cartridge
MBC.getMbcInstance = function(memory, type) {
    var instance;
    switch (type) {
        case 0x00:
            instance = new MBC0(memory);
            break;
        case 0x01: case 0x02: case 0x03:
            instance = new MBC1(memory);
            break;
        case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13:
            instance = new MBC3(memory);
            break;
        default:
            throw new GameboyJS.UnimplementedException('MBC type not supported');
    }

    return instance;
};

var MBC1 = function(memory) {
    this.memory = memory;
    this.romBankNumber = 1;
    this.mode = 0; // mode 0 = ROM, mode 1 = RAM
    this.ramEnabled = true;
    this.extRam = new GameboyJS.ExtRam();
};

MBC1.prototype.loadRam = function(game, size) {
    this.extRam.loadRam(game, size);
};

MBC1.prototype.manageWrite = function(addr, value) {
    switch (addr & 0xF000) {
        case 0x0000: case 0x1000: // enable RAM
            this.ramEnabled = (value & 0x0A) ? true : false;
            if (this.ramEnabled) {
                this.extRam.saveRamData();
            }
            break;
        case 0x2000: case 0x3000: // ROM bank number lower 5 bits
            value &= 0x1F;
            if (value == 0) value = 1;
            var mask = this.mode ? 0 : 0xE0;
            this.romBankNumber = (this.romBankNumber & mask) +value;
            this.memory.loadRomBank(this.romBankNumber);
            break;
        case 0x4000: case 0x5000: // RAM bank or high bits ROM
            value &= 0x03;
            if (this.mode == 0) { // ROM upper bits
                this.romBankNumber = (this.romBankNumber&0x1F) | (value << 5);
                this.memory.loadRomBank(this.romBankNumber);
            } else { // RAM bank
                this.extRam.setRamBank(value);
            }
            break;
        case 0x6000: case 0x7000: // ROM / RAM mode
            this.mode = value & 1;
            break;
        case 0xA000: case 0xB000:
            this.extRam.manageWrite(addr - 0xA000, value);
            break;
    }
};
MBC1.prototype.readRam = function(addr) {
    return this.extRam.manageRead(addr - 0xA000);
};

var MBC3 = function(memory) {
    this.memory = memory;
    this.romBankNumber = 1;
    this.ramEnabled = true;
    this.extRam = new GameboyJS.ExtRam();
};

MBC3.prototype.loadRam = function(game, size) {
    this.extRam.loadRam(game, size);
};

MBC3.prototype.manageWrite = function(addr, value) {
    switch (addr & 0xF000) {
        case 0x0000: case 0x1000: // enable RAM
            this.ramEnabled = (value & 0x0A) ? true : false;
            if (this.ramEnabled) {
                this.extRam.saveRamData();
            }
            break;
        case 0x2000: case 0x3000: // ROM bank number
            value &= 0x7F;
            if (value == 0) value = 1;
            this.romBankNumber = value;
            this.memory.loadRomBank(this.romBankNumber);
            break;
        case 0x4000: case 0x5000: // RAM bank
            this.extRam.setRamBank(value);
            break;
        case 0x6000: case 0x7000: // Latch clock data
            throw new GameboyJS.UnimplementedException('cartridge clock not supported', false);
            break;
        case 0xA000: case 0xB000:
            this.extRam.manageWrite(addr - 0xA000, value);
            break;
    }
};
MBC3.prototype.readRam = function(addr) {
    return this.extRam.manageRead(addr - 0xA000);
};

// MBC0 exists for consistency and manages the no-MBC cartriges
var MBC0 = function(memory) {this.memory = memory;};

MBC0.prototype.manageWrite = function(addr, value) {
    this.memory.loadRomBank(value);
};
MBC0.prototype.readRam = function(addr) {return 0;};
MBC0.prototype.loadRam = function() {};

GameboyJS.MBC = MBC;
}(GameboyJS || (GameboyJS = {})));
<commit_msg>declare the MBC5 as an alias for MBC3<commit_after>var GameboyJS;
(function (GameboyJS) {
"use strict";

// Memory bank controllers

var MBC = {};

// Create an MBC instance depending on the type specified in the cartridge
MBC.getMbcInstance = function(memory, type) {
    var instance;
    switch (type) {
        case 0x00:
            instance = new MBC0(memory);
            break;
        case 0x01: case 0x02: case 0x03:
            instance = new MBC1(memory);
            break;
        case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13:
            instance = new MBC3(memory);
            break;
        case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E:
            instance = new MBC5(memory);
            break;
        default:
            throw new GameboyJS.UnimplementedException('MBC type not supported');
    }

    return instance;
};

var MBC1 = function(memory) {
    this.memory = memory;
    this.romBankNumber = 1;
    this.mode = 0; // mode 0 = ROM, mode 1 = RAM
    this.ramEnabled = true;
    this.extRam = new GameboyJS.ExtRam();
};

MBC1.prototype.loadRam = function(game, size) {
    this.extRam.loadRam(game, size);
};

MBC1.prototype.manageWrite = function(addr, value) {
    switch (addr & 0xF000) {
        case 0x0000: case 0x1000: // enable RAM
            this.ramEnabled = (value & 0x0A) ? true : false;
            if (this.ramEnabled) {
                this.extRam.saveRamData();
            }
            break;
        case 0x2000: case 0x3000: // ROM bank number lower 5 bits
            value &= 0x1F;
            if (value == 0) value = 1;
            var mask = this.mode ? 0 : 0xE0;
            this.romBankNumber = (this.romBankNumber & mask) +value;
            this.memory.loadRomBank(this.romBankNumber);
            break;
        case 0x4000: case 0x5000: // RAM bank or high bits ROM
            value &= 0x03;
            if (this.mode == 0) { // ROM upper bits
                this.romBankNumber = (this.romBankNumber&0x1F) | (value << 5);
                this.memory.loadRomBank(this.romBankNumber);
            } else { // RAM bank
                this.extRam.setRamBank(value);
            }
            break;
        case 0x6000: case 0x7000: // ROM / RAM mode
            this.mode = value & 1;
            break;
        case 0xA000: case 0xB000:
            this.extRam.manageWrite(addr - 0xA000, value);
            break;
    }
};
MBC1.prototype.readRam = function(addr) {
    return this.extRam.manageRead(addr - 0xA000);
};

var MBC3 = function(memory) {
    this.memory = memory;
    this.romBankNumber = 1;
    this.ramEnabled = true;
    this.extRam = new GameboyJS.ExtRam();
};

MBC3.prototype.loadRam = function(game, size) {
    this.extRam.loadRam(game, size);
};

MBC3.prototype.manageWrite = function(addr, value) {
    switch (addr & 0xF000) {
        case 0x0000: case 0x1000: // enable RAM
            this.ramEnabled = (value & 0x0A) ? true : false;
            if (this.ramEnabled) {
                this.extRam.saveRamData();
            }
            break;
        case 0x2000: case 0x3000: // ROM bank number
            value &= 0x7F;
            if (value == 0) value = 1;
            this.romBankNumber = value;
            this.memory.loadRomBank(this.romBankNumber);
            break;
        case 0x4000: case 0x5000: // RAM bank
            this.extRam.setRamBank(value);
            break;
        case 0x6000: case 0x7000: // Latch clock data
            throw new GameboyJS.UnimplementedException('cartridge clock not supported', false);
            break;
        case 0xA000: case 0xB000:
            this.extRam.manageWrite(addr - 0xA000, value);
            break;
    }
};
MBC3.prototype.readRam = function(addr) {
    return this.extRam.manageRead(addr - 0xA000);
};

// declare MBC5 for compatibility with most cartriges
// does not support rumble feature
var MBC5 = MBC3;

// MBC0 exists for consistency and manages the no-MBC cartriges
var MBC0 = function(memory) {this.memory = memory;};

MBC0.prototype.manageWrite = function(addr, value) {
    this.memory.loadRomBank(value);
};
MBC0.prototype.readRam = function(addr) {return 0;};
MBC0.prototype.loadRam = function() {};

GameboyJS.MBC = MBC;
}(GameboyJS || (GameboyJS = {})));
<|endoftext|>


<commit_before>/* -*- coding: utf-8 -*-

Copyright (c) 2016 Rafael Villar Burke <pachi@rvburke.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Author(s): Rafael Villar Burke <pachi@rvburke.com>
*/

/* MET format
Linea 1: nombre de archivo de clima. e.g. zonaD3.met
Línea 2: campos con datos de localización:
- latitud, grados
- longitud, grados
- altitud, metros
- longitud de referencia, grados

8760 líneas siguientes: campos con datos meteorológicos
- Día (1 a 31);
- Hora (1 a 24);
- Temperatura seca ( ◦ C);
- Temperatura efectiva del cielo ( ◦ C);
- Irradiancia solar directa sobre una superficie horizontal (W/m 2 );
- Irradiancia solar difusa sobre una superficie horizontal (W/m 2 );
- Humedad específica (kgH2O/kgaire seco);
- Humedad relativa ( %);
- Velocidad del viento (m/s);
- Dirección del viento (grados respecto al norte, E+, O-);
- Azimut solar (grados);
- Cénit solar (grados).
*/

const fs = require('fs');
const sol = require('./soljs.js');

// Compute primary energy (weighted energy) from data in filename
function readmetfile(metpath) {
  let datalines = fs.readFileSync(metpath, 'utf-8')
        .replace('\n\r', '\n').split('\n')
        .map(line => line.trim());
  // metadata
  const metname = datalines[0];
  const [latitud, longitud, altitud, longref] = datalines[1]
        .split(' ').map(parseFloat);
  const zc = metname.replace(/^zona/,"").replace(/\.met$/, "");
  const meta = { metname, zc, latitud, longitud, altitud, longref };
  // datalines
  let data = datalines.slice(2).map(x => x.split(/[\s,]+/).map(parseFloat));
  data = data.map(([ mes, dia, hora,
                     tempseca, tempcielo,
                     rdirhor, rdifhor,
                     humedadabs, humedadrel,
                     velviento, dirviento,
                     azimut, cenit ]) => (
                       { mes, dia, hora,
                         tempseca, tempcielo,
                         rdirhor, rdifhor,
                         humedadabs, humedadrel,
                         velviento, dirviento,
                         azimut, cenit }
                     )
                 );

  return { meta, data };
}

// Calcula radiación directa y difusa en una superficie orientada y con albedo
//
// latitude: latitud de la localización
// hourlydata: datos climáticos horarios (.data de climadata)
// surf: descripción de la superficie orientada (inclinación, azimuth)
//       { beta: [0, 180], gamma: [-180, 180] }
// albedo: reflectancia del entorno [0.0, 1.0]
function radiationForSurface(latitude, hourlydata, surf, albedo) {
  return hourlydata.map(
    d => {
      // Calcula altura solar = 90 - cenit y
      // corregir problema numérico con altitud solar = 0
      const salt = (d.cenit !== 90) ? 90 - d.cenit : 90 - 89.95;
      const rdir = sol.gsolbeam(d.rdirhor, salt);
      const dir = sol.idirtot(d.mes, d.dia, d.hora, rdir, d.rdifhor, salt,
                              latitude, surf.beta, surf.gamma);
      const dif = sol.idiftot(d.mes, d.dia, d.hora, rdir, d.rdifhor, salt,
                              latitude, surf.beta, surf.gamma, albedo);
      return { mes: d.mes, dia: d.dia, hora: d.hora, dir, dif, tot: dir + dif };
    });
}

// ************************* Exports *****************************************

module.exports = { readmetfile, radiationForSurface };
<commit_msg>soljs: actualiza comentario<commit_after>/* -*- coding: utf-8 -*-

Copyright (c) 2016 Rafael Villar Burke <pachi@rvburke.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Author(s): Rafael Villar Burke <pachi@rvburke.com>
*/

/* MET format
Linea 1: nombre de archivo de clima. e.g. zonaD3.met
Línea 2: campos con datos de localización:
- latitud, grados
- longitud, grados
- altitud, metros
- longitud de referencia, grados

8760 líneas siguientes: campos con datos meteorológicos
- Día (1 a 31);
- Hora (1 a 24);
- Temperatura seca ( ◦ C);
- Temperatura efectiva del cielo ( ◦ C);
- Irradiancia solar directa sobre una superficie horizontal (W/m 2 );
- Irradiancia solar difusa sobre una superficie horizontal (W/m 2 );
- Humedad específica (kgH2O/kgaire seco);
- Humedad relativa ( %);
- Velocidad del viento (m/s);
- Dirección del viento (grados respecto al norte, E+, O-);
- Azimut solar (grados);
- Cénit solar (grados).
*/

const fs = require('fs');
const sol = require('./soljs.js');

// Read hourly data from .met file in metpath
function readmetfile(metpath) {
  let datalines = fs.readFileSync(metpath, 'utf-8')
        .replace('\n\r', '\n').split('\n')
        .map(line => line.trim());
  // metadata
  const metname = datalines[0];
  const [latitud, longitud, altitud, longref] = datalines[1]
        .split(' ').map(parseFloat);
  const zc = metname.replace(/^zona/,"").replace(/\.met$/, "");
  const meta = { metname, zc, latitud, longitud, altitud, longref };
  // datalines
  let data = datalines.slice(2).map(x => x.split(/[\s,]+/).map(parseFloat));
  // TODO: filter empty lines
  data = data.map(([ mes, dia, hora,
                     tempseca, tempcielo,
                     rdirhor, rdifhor,
                     humedadabs, humedadrel,
                     velviento, dirviento,
                     azimut, cenit ]) => (
                       { mes, dia, hora,
                         tempseca, tempcielo,
                         rdirhor, rdifhor,
                         humedadabs, humedadrel,
                         velviento, dirviento,
                         azimut, cenit }
                     )
                 );

  return { meta, data };
}

// Calcula radiación directa y difusa en una superficie orientada y con albedo
//
// latitude: latitud de la localización
// hourlydata: datos climáticos horarios (.data de climadata)
// surf: descripción de la superficie orientada (inclinación, azimuth)
//       { beta: [0, 180], gamma: [-180, 180] }
// albedo: reflectancia del entorno [0.0, 1.0]
function radiationForSurface(latitude, hourlydata, surf, albedo) {
  return hourlydata.map(
    d => {
      // Calcula altura solar = 90 - cenit y
      // corregir problema numérico con altitud solar = 0
      const salt = (d.cenit !== 90) ? 90 - d.cenit : 90 - 89.95;
      const rdir = sol.gsolbeam(d.rdirhor, salt);
      const dir = sol.idirtot(d.mes, d.dia, d.hora, rdir, d.rdifhor, salt,
                              latitude, surf.beta, surf.gamma);
      const dif = sol.idiftot(d.mes, d.dia, d.hora, rdir, d.rdifhor, salt,
                              latitude, surf.beta, surf.gamma, albedo);
      return { mes: d.mes, dia: d.dia, hora: d.hora, dir, dif, tot: dir + dif };
    });
}

// ************************* Exports *****************************************

module.exports = { readmetfile, radiationForSurface };
<|endoftext|>


<commit_before>#!/usr/bin/env node
//@flow
const start = Date.now()

// theirs
const debug = require('debug')('now:main')
const { exists } = require('fs.promised')
const { join } = require('path')
const mkdirp = require('mkdirp-promise')
const minimist = require('minimist')

// ours
const error = require('./util/output/error')
const effect = require('./util/output/effect')
const param = require('./util/output/param')
const getHelp = require('./get-help')
const getWelcome = require('./get-welcome')
const getNowDir = require('./get-now-dir')
const getDefaultCfg = require('./get-default-cfg')
const getDefaultAuthCfg = require('./get-default-auth-cfg')
const hp = require('./util/humanize-path')
const providers = require('./providers')
const configFiles = require('./util/config-files')

const NOW_DIR = getNowDir()
const NOW_CONFIG_PATH = configFiles.getConfigFilePath()
const NOW_AUTH_CONFIG_PATH = configFiles.getAuthConfigFilePath()

const GLOBAL_COMMANDS = new Set(['help'])

const exit = code => {
  debug('finished in', Date.now() - start)
  process.exit(code)
}

const main = async argv_ => {
  const argv = minimist(argv_, {
    boolean: ['help', 'version'],
    alias: {
      help: 'h',
      version: 'v'
    }
  })

  // the second argument to the command can be a path
  // (as in: `now path/`) or a subcommand / provider
  // (as in: `now ls` or `now aws help`)
  let targetOrSubcommand: ?string = argv._[2]

  // we want to handle version or help directly only
  if (!targetOrSubcommand) {
    if (argv.version) {
      console.log(require('../package').version)
      return 0
    }
  }

  let nowDirExists

  try {
    nowDirExists = await exists(NOW_DIR)
  } catch (err) {
    console.error(
      error(
        'An unexpected error occurred while trying to find the ' +
          'now global directory: ' +
          err.message
      )
    )
    return 1
  }

  if (!nowDirExists) {
    try {
      await mkdirp(NOW_DIR)
    } catch (err) {
      error(
        'An unexpected error occurred while trying to create the ' +
          `now global directory "${hp(NOW_DIR)}" ` +
          err.message
      )
    }
  }

  let initConfig = false
  let initAuthConfig = false
  let configExists

  try {
    configExists = await exists(NOW_CONFIG_PATH)
  } catch (err) {
    console.error(
      error(
        'An unexpected error occurred while trying to find the ' +
          `now config file "${hp(NOW_CONFIG_PATH)}" ` +
          err.message
      )
    )
    return 1
  }

  let config

  if (configExists) {
    try {
      config = configFiles.readConfigFile()
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to read the ' +
            `now config in "${hp(NOW_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }

    try {
      config = JSON.parse(config)
    } catch (err) {
      console.error(
        error(
          `An error occurred while trying to parse "${hp(NOW_CONFIG_PATH)}": ` +
            err.message
        )
      )
      return 1
    }
  } else {
    config = getDefaultCfg()
    try {
      configFiles.writeToConfigFile(config)
      initConfig = true
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to write the ' +
            `default now config to "${hp(NOW_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }
  }

  let authConfigExists

  try {
    authConfigExists = await exists(NOW_AUTH_CONFIG_PATH)
  } catch (err) {
    console.error(
      error(
        'An unexpected error occurred while trying to find the ' +
          `now auth file "${hp(NOW_AUTH_CONFIG_PATH)}" ` +
          err.message
      )
    )
    return 1
  }

  let authConfig = null

  if (authConfigExists) {
    try {
      authConfig = configFiles.readAuthConfigFile()
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to read the ' +
            `now auth config in "${hp(NOW_AUTH_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }

    try {
      authConfig = JSON.parse(authConfig)

      if (!Array.isArray(authConfig.credentials)) {
        console.error(
          error(
            `The content of "${hp(NOW_AUTH_CONFIG_PATH)}" is invalid. ` +
              'No `credentials` list found inside'
          )
        )
        return 1
      }

      for (const [i, { provider }] of authConfig.credentials.entries()) {
        if (null == provider) {
          console.error(
            error(
              `Invalid credential found in "${hp(NOW_AUTH_CONFIG_PATH)}". ` +
                `Missing \`provider\` key in entry with index ${i}`
            )
          )
          return 1
        }

        if (!(provider in providers)) {
          console.error(
            error(
              `Invalid credential found in "${hp(NOW_AUTH_CONFIG_PATH)}". ` +
                `Unknown provider "${provider}"`
            )
          )
          return 1
        }
      }
    } catch (err) {
      console.error(
        error(
          `An error occurred while trying to parse "${hp(
            NOW_AUTH_CONFIG_PATH
          )}": ` + err.message
        )
      )
      return 1
    }
  } else {
    authConfig = getDefaultAuthCfg()
    try {
      configFiles.writeToAuthConfigFile(authConfig)
      initAuthConfig = true
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to write the ' +
            `default now config to "${hp(NOW_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }
  }

  if (initConfig || initAuthConfig) {
    console.log(
      effect(
        `Initialized default config in "${initConfig && initAuthConfig
          ? hp(NOW_DIR)
          : hp(initConfig ? NOW_CONFIG_PATH : NOW_AUTH_CONFIG_PATH)}"`
      )
    )
  }

  let suppliedProvider = null

  // if the target is something like `aws`
  if (targetOrSubcommand in providers) {
    debug('user supplied a known provider')
    const targetPath = join(process.cwd(), targetOrSubcommand)
    const targetPathExists = await exists(targetPath)

    if (targetPathExists) {
      console.error(
        error(
          `The supplied argument ${param(targetOrSubcommand)} is ambiguous. ` +
            'Both a directory and a provider are known'
        )
      )
      return 1
    }

    suppliedProvider = targetOrSubcommand
    targetOrSubcommand = argv._[3]
  }

  let { defaultProvider = null }: { defaultProvider: ?string } = config

  if (null === suppliedProvider) {
    if (null === defaultProvider) {
      // the first provider the user ever logged in to is
      // the default provider
      if (authConfig && authConfig.credentials.length) {
        debug('using first credential as default provider')
        defaultProvider = authConfig.credentials[0].provider
      } else {
        debug(`fallbacking to default now provider 'sh'`)
        defaultProvider = 'sh'
      }
    } else {
      debug('using provider supplied by user', defaultProvider)
      if (!(defaultProvider in providers)) {
        console.error(
          error(
            `The \`defaultProvider\` "${defaultProvider}" supplied in ` +
              `"${NOW_CONFIG_PATH}" is not a valid provider`
          )
        )
        return 1
      }
    }
  }

  // we special case help because it's a generic command with
  // information about all providers
  if (!suppliedProvider && argv.help) {
    console.log(getHelp(defaultProvider, providers))
    return 0
  }

  const provider: Object = providers[suppliedProvider || defaultProvider]

  // the context object to supply to the providers
  const ctx = {
    config,
    authConfig,
    argv: argv_
  }

  let subcommand

  // we check if we are deploying something
  if (targetOrSubcommand) {
    const targetPath = join(process.cwd(), targetOrSubcommand)
    const targetPathExists = await exists(targetPath)

    const subcommandExists =
      GLOBAL_COMMANDS.has(targetOrSubcommand) ||
      provider.subcommands.has(targetOrSubcommand)

    if (targetPathExists && subcommandExists) {
      console.error(
        error(
          `The supplied argument ${param(targetOrSubcommand)} is ambiguous. ` +
            'Both a directory and a subcommand are known'
        )
      )
      return 1
    }

    if (subcommandExists) {
      debug('user supplied known subcommand', targetOrSubcommand)
      subcommand = targetOrSubcommand
    } else {
      debug('user supplied a possible target for deployment')
      // our default command is deployment
      // at this point we're
      subcommand = 'deploy'
    }
  } else {
    debug('user supplied no target, defaulting to deploy')
    subcommand = 'deploy'
  }

  if (subcommand === 'deploy' && !authConfig.credentials.length) {
    debug('subcommand is deploy, but user has no credentials')
    console.log(getWelcome(provider, providers))
    return 0
  }

  if (subcommand === 'help') {
    console.log(getHelp(defaultProvider, providers))
    return 0
  }

  try {
    return provider[subcommand](ctx)
  } catch (err) {
    console.error(
      error(
        `An unexpected error occurred in provider ${subcommand}: ${err.stack}`
      )
    )
  }
}

debug('start')

const handleRejection = err => {
  debug('handling rejection')
  if (err) {
    if (err instanceof Error) {
      handleUnexpected(err)
    } else {
      console.error(error(`An unexpected rejection occurred\n  ${err}`))
    }
  } else {
    console.error(error('An unexpected empty rejection occurred'))
  }
  return 1
}

const handleUnexpected = err => {
  debug('handling unexpected error')
  console.error(
    error(`An unexpected error occurred!\n  ${err.stack} ${err.stack}`)
  )
  return 1
}

process.on('uncaughtRejection', handleRejection)
process.on('uncaughtException', handleUnexpected)

main(process.argv).then((code: number) => exit(code)).catch(handleUnexpected)
<commit_msg>handle unexpected rejections correctly<commit_after>#!/usr/bin/env node
//@flow
const start = Date.now()

// theirs
const debug = require('debug')('now:main')
const { exists } = require('fs.promised')
const { join } = require('path')
const mkdirp = require('mkdirp-promise')
const minimist = require('minimist')

// ours
const error = require('./util/output/error')
const effect = require('./util/output/effect')
const param = require('./util/output/param')
const getHelp = require('./get-help')
const getWelcome = require('./get-welcome')
const getNowDir = require('./get-now-dir')
const getDefaultCfg = require('./get-default-cfg')
const getDefaultAuthCfg = require('./get-default-auth-cfg')
const hp = require('./util/humanize-path')
const providers = require('./providers')
const configFiles = require('./util/config-files')

const NOW_DIR = getNowDir()
const NOW_CONFIG_PATH = configFiles.getConfigFilePath()
const NOW_AUTH_CONFIG_PATH = configFiles.getAuthConfigFilePath()

const GLOBAL_COMMANDS = new Set(['help'])

const exit = code => {
  debug('finished in', Date.now() - start)
  process.exit(code)
}

const main = async argv_ => {
  const argv = minimist(argv_, {
    boolean: ['help', 'version'],
    alias: {
      help: 'h',
      version: 'v'
    }
  })

  // the second argument to the command can be a path
  // (as in: `now path/`) or a subcommand / provider
  // (as in: `now ls` or `now aws help`)
  let targetOrSubcommand: ?string = argv._[2]

  // we want to handle version or help directly only
  if (!targetOrSubcommand) {
    if (argv.version) {
      console.log(require('../package').version)
      return 0
    }
  }

  let nowDirExists

  try {
    nowDirExists = await exists(NOW_DIR)
  } catch (err) {
    console.error(
      error(
        'An unexpected error occurred while trying to find the ' +
          'now global directory: ' +
          err.message
      )
    )
    return 1
  }

  if (!nowDirExists) {
    try {
      await mkdirp(NOW_DIR)
    } catch (err) {
      error(
        'An unexpected error occurred while trying to create the ' +
          `now global directory "${hp(NOW_DIR)}" ` +
          err.message
      )
    }
  }

  let initConfig = false
  let initAuthConfig = false
  let configExists

  try {
    configExists = await exists(NOW_CONFIG_PATH)
  } catch (err) {
    console.error(
      error(
        'An unexpected error occurred while trying to find the ' +
          `now config file "${hp(NOW_CONFIG_PATH)}" ` +
          err.message
      )
    )
    return 1
  }

  let config

  if (configExists) {
    try {
      config = configFiles.readConfigFile()
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to read the ' +
            `now config in "${hp(NOW_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }

    try {
      config = JSON.parse(config)
    } catch (err) {
      console.error(
        error(
          `An error occurred while trying to parse "${hp(NOW_CONFIG_PATH)}": ` +
            err.message
        )
      )
      return 1
    }
  } else {
    config = getDefaultCfg()
    try {
      configFiles.writeToConfigFile(config)
      initConfig = true
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to write the ' +
            `default now config to "${hp(NOW_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }
  }

  let authConfigExists

  try {
    authConfigExists = await exists(NOW_AUTH_CONFIG_PATH)
  } catch (err) {
    console.error(
      error(
        'An unexpected error occurred while trying to find the ' +
          `now auth file "${hp(NOW_AUTH_CONFIG_PATH)}" ` +
          err.message
      )
    )
    return 1
  }

  let authConfig = null

  if (authConfigExists) {
    try {
      authConfig = configFiles.readAuthConfigFile()
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to read the ' +
            `now auth config in "${hp(NOW_AUTH_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }

    try {
      authConfig = JSON.parse(authConfig)

      if (!Array.isArray(authConfig.credentials)) {
        console.error(
          error(
            `The content of "${hp(NOW_AUTH_CONFIG_PATH)}" is invalid. ` +
              'No `credentials` list found inside'
          )
        )
        return 1
      }

      for (const [i, { provider }] of authConfig.credentials.entries()) {
        if (null == provider) {
          console.error(
            error(
              `Invalid credential found in "${hp(NOW_AUTH_CONFIG_PATH)}". ` +
                `Missing \`provider\` key in entry with index ${i}`
            )
          )
          return 1
        }

        if (!(provider in providers)) {
          console.error(
            error(
              `Invalid credential found in "${hp(NOW_AUTH_CONFIG_PATH)}". ` +
                `Unknown provider "${provider}"`
            )
          )
          return 1
        }
      }
    } catch (err) {
      console.error(
        error(
          `An error occurred while trying to parse "${hp(
            NOW_AUTH_CONFIG_PATH
          )}": ` + err.message
        )
      )
      return 1
    }
  } else {
    authConfig = getDefaultAuthCfg()
    try {
      configFiles.writeToAuthConfigFile(authConfig)
      initAuthConfig = true
    } catch (err) {
      console.error(
        error(
          'An unexpected error occurred while trying to write the ' +
            `default now config to "${hp(NOW_CONFIG_PATH)}" ` +
            err.message
        )
      )
      return 1
    }
  }

  if (initConfig || initAuthConfig) {
    console.log(
      effect(
        `Initialized default config in "${initConfig && initAuthConfig
          ? hp(NOW_DIR)
          : hp(initConfig ? NOW_CONFIG_PATH : NOW_AUTH_CONFIG_PATH)}"`
      )
    )
  }

  let suppliedProvider = null

  // if the target is something like `aws`
  if (targetOrSubcommand in providers) {
    debug('user supplied a known provider')
    const targetPath = join(process.cwd(), targetOrSubcommand)
    const targetPathExists = await exists(targetPath)

    if (targetPathExists) {
      console.error(
        error(
          `The supplied argument ${param(targetOrSubcommand)} is ambiguous. ` +
            'Both a directory and a provider are known'
        )
      )
      return 1
    }

    suppliedProvider = targetOrSubcommand
    targetOrSubcommand = argv._[3]
  }

  let { defaultProvider = null }: { defaultProvider: ?string } = config

  if (null === suppliedProvider) {
    if (null === defaultProvider) {
      // the first provider the user ever logged in to is
      // the default provider
      if (authConfig && authConfig.credentials.length) {
        debug('using first credential as default provider')
        defaultProvider = authConfig.credentials[0].provider
      } else {
        debug(`fallbacking to default now provider 'sh'`)
        defaultProvider = 'sh'
      }
    } else {
      debug('using provider supplied by user', defaultProvider)
      if (!(defaultProvider in providers)) {
        console.error(
          error(
            `The \`defaultProvider\` "${defaultProvider}" supplied in ` +
              `"${NOW_CONFIG_PATH}" is not a valid provider`
          )
        )
        return 1
      }
    }
  }

  // we special case help because it's a generic command with
  // information about all providers
  if (!suppliedProvider && argv.help) {
    console.log(getHelp(defaultProvider, providers))
    return 0
  }

  const provider: Object = providers[suppliedProvider || defaultProvider]

  // the context object to supply to the providers
  const ctx = {
    config,
    authConfig,
    argv: argv_
  }

  let subcommand

  // we check if we are deploying something
  if (targetOrSubcommand) {
    const targetPath = join(process.cwd(), targetOrSubcommand)
    const targetPathExists = await exists(targetPath)

    const subcommandExists =
      GLOBAL_COMMANDS.has(targetOrSubcommand) ||
      provider.subcommands.has(targetOrSubcommand)

    if (targetPathExists && subcommandExists) {
      console.error(
        error(
          `The supplied argument ${param(targetOrSubcommand)} is ambiguous. ` +
            'Both a directory and a subcommand are known'
        )
      )
      return 1
    }

    if (subcommandExists) {
      debug('user supplied known subcommand', targetOrSubcommand)
      subcommand = targetOrSubcommand
    } else {
      debug('user supplied a possible target for deployment')
      // our default command is deployment
      // at this point we're
      subcommand = 'deploy'
    }
  } else {
    debug('user supplied no target, defaulting to deploy')
    subcommand = 'deploy'
  }

  if (subcommand === 'deploy' && !authConfig.credentials.length) {
    debug('subcommand is deploy, but user has no credentials')
    console.log(getWelcome(provider, providers))
    return 0
  }

  if (subcommand === 'help') {
    console.log(getHelp(defaultProvider, providers))
    return 0
  }

  try {
    return provider[subcommand](ctx)
  } catch (err) {
    console.error(
      error(
        `An unexpected error occurred in provider ${subcommand}: ${err.stack}`
      )
    )
  }
}

debug('start')

const handleRejection = err => {
  debug('handling rejection')
  if (err) {
    if (err instanceof Error) {
      handleUnexpected(err)
    } else {
      console.error(error(`An unexpected rejection occurred\n  ${err}`))
    }
  } else {
    console.error(error('An unexpected empty rejection occurred'))
  }
  return 1
}

const handleUnexpected = err => {
  debug('handling unexpected error')
  console.error(
    error(`An unexpected error occurred!\n  ${err.stack} ${err.stack}`)
  )
  return 1
}

process.on('unhandledRejection', handleRejection)
process.on('uncaughtException', handleUnexpected)

main(process.argv).then((code: number) => exit(code)).catch(handleUnexpected)
<|endoftext|>


<commit_before>/******************************************************************************
 *                                ~black.obj~                                 *
 *                              ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾                               *
 * Extensions to work with objects.                                           *
 *     _________________________________________________________________      *
 *        Copyright (c) 2011 Quildreen Motta // Licenced under MIT/X11        *
 ******************************************************************************/
void function (root) { var __old, obj

    , keys  = Object.keys
    , slice = Array.prototype.slice

    // Checks if an object has a key set in itself
    function has(obj, key) {
        return obj.hasOwnProperty(key)
    }

    // Returns a list of values in the object
    function values(obj) {
        return keys(obj).map(function(key) {
            return obj[key] })
    }

    // Returns a list of tuples (key, value) in the object
    function items(obj) {
        return keys(obj).map(function(key) {
            return [key, obj[key]] })
    }

    // Returns a property in the object, or default
    function attr(obj, key, def) {
        return obj[key] != null? obj[key]
                               : def
    }

    // Sets the property only if it hasn't been set yet
    function set_default(obj, key, value) {
        if (obj[key] == null) obj[key] = value
        return obj[key]
    }

    // Removes a property from the object, returns it or default
    function pop(obj, key, def) { var result
        result = attr(obj, key, def)

        delete obj[key]
        return result
    }

    // Checks if the object is empty
    function emptyp(obj) { var key
        for (key in obj)
            if (has(obj, key)) return false

        return true
    }

    // Extends an object with properties from multiple sources
    function extend(target) {
        slice.call(arguments, 1).forEach(function(source) {
            keys(source).reduce(function(acc, key) {
                target[key] = source[key]
                return target }, target )})

        return target
    }

    // Makes a shallow copy of an object
    function copy(obj) {
        return extend({ }, obj)
    }

    ///// Exports //////////////////////////////////////////////////////////////
    if (typeof exports == 'undefined') {
        if (!root.black) root.black = { }

        __old = root.obj.obj
        obj = root.obj.obj = { }

        ///// Method obj.make_local ////////////////////////////////////////////
        obj.make_local = function() {
            root.obj = __old
            return obj }}
    else
        obj = exports

    ///// -Properties under obj ////////////////////////////////////////////////
    obj.keys        = keys
    obj.values      = values
    obj.items       = items
    obj.attr        = attr
    obj.set_default = set_default
    obj.pop         = pop
    obj.extend      = extend
    obj.copy        = copy

}(this)
<commit_msg>fixes exporting to platforms without commonjs modules support.<commit_after>/******************************************************************************
 *                                ~black.obj~                                 *
 *                              ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾                               *
 * Extensions to work with objects.                                           *
 *     _________________________________________________________________      *
 *        Copyright (c) 2011 Quildreen Motta // Licenced under MIT/X11        *
 ******************************************************************************/
void function (root) { var __old, obj

    , keys  = Object.keys
    , slice = Array.prototype.slice

    // Checks if an object has a key set in itself
    function has(obj, key) {
        return obj.hasOwnProperty(key)
    }

    // Returns a list of values in the object
    function values(obj) {
        return keys(obj).map(function(key) {
            return obj[key] })
    }

    // Returns a list of tuples (key, value) in the object
    function items(obj) {
        return keys(obj).map(function(key) {
            return [key, obj[key]] })
    }

    // Returns a property in the object, or default
    function attr(obj, key, def) {
        return obj[key] != null? obj[key]
                               : def
    }

    // Sets the property only if it hasn't been set yet
    function set_default(obj, key, value) {
        if (obj[key] == null) obj[key] = value
        return obj[key]
    }

    // Removes a property from the object, returns it or default
    function pop(obj, key, def) { var result
        result = attr(obj, key, def)

        delete obj[key]
        return result
    }

    // Checks if the object is empty
    function emptyp(obj) { var key
        for (key in obj)
            if (has(obj, key)) return false

        return true
    }

    // Extends an object with properties from multiple sources
    function extend(target) {
        slice.call(arguments, 1).forEach(function(source) {
            keys(source).reduce(function(acc, key) {
                target[key] = source[key]
                return target }, target )})

        return target
    }

    // Makes a shallow copy of an object
    function copy(obj) {
        return extend({ }, obj)
    }

    ///// Exports //////////////////////////////////////////////////////////////
    if (typeof exports == 'undefined') {
        if (!root.black) root.black = { }

        __old = root.black.obj
        obj   = root.black..obj = { }

        ///// Method obj.make_local ////////////////////////////////////////////
        obj.make_local = function() {
            root.black.obj = __old
            return obj }}
    else
        obj = exports

    ///// -Properties under obj ////////////////////////////////////////////////
    obj.keys        = keys
    obj.values      = values
    obj.items       = items
    obj.attr        = attr
    obj.set_default = set_default
    obj.pop         = pop
    obj.extend      = extend
    obj.copy        = copy

}(this)
<|endoftext|>


<commit_before>function updateImage() {

	var d = new Date();
	var h = d.getHours().toString();
	var m = d.getMinutes().toString();
		if (m < 10) { m = '0' + m};

	var domain = 'http://labs.brunoamaral.eu/coffeeclock/'
	var image = domain + 'public/assets/images/clock/' + h + '00.JPG';

	var loadingImage = loadImage(image, function(img){
		var target = document.getElementById('coffeetable')
		target.appendChild(img);
	});

// 	var xhr = new XMLHttpRequest();

// 	xhr.open("GET", image, true);
// 	xhr.responseType = "arraybuffer";
// 	xhr.onload = function(e){
// 		var blob = new Blob([this.response], {type: "image/jpeg"});
// console.log(blob);
// 	        var loadingImage = loadImage(blob, function(img){
//                         document.getElementById('coffeetable').appendChild(img);
//                 console.log(blob); console.log(img)},
//                 {orientation: blob.exif.get('Orientation')}
//                 );
// 	}
// 	xhr.send();

};

$(document).ready(function(){
	updateImage() // call the first time
	setInterval(updateImage, 15 * 1000) // update each 5 seconds
});
<commit_msg>testing<commit_after>function updateImage() {

	var d = new Date();
	var h = d.getHours().toString();
	var m = d.getMinutes().toString();
		if (m < 10) { m = '0' + m};

	var domain = 'http://labs.brunoamaral.eu/coffeeclock/'
	var image = domain + 'public/assets/images/clock/' + h + '00.JPG';

	var loadingImage = loadImage(image, function(img){
		var target = document.getElementById('coffeetable')
		target.appendChild(img);
		console.log(image);
		}, {
			orientation: image.exif.get('orientation')
		}
	);

};

$(document).ready(function(){
	updateImage() // call the first time
	setInterval(updateImage, 15 * 1000) // update each 5 seconds
});
<|endoftext|>


<commit_before>'use strict'

require({
  map: {
    '*': {
      /* RequireJS plugins. */
      'async': 'webjars/requirejs-plugins/3ff54566f8/async',
      'json': 'webjars/requirejs-plugins/3ff54566f8/json',
      'goog': 'webjars/requirejs-plugins/3ff54566f8/goog',
      'noext': 'webjars/requirejs-plugins/3ff54566f8/noext',
      'text': 'webjars/requirejs-text/2.0.10/text'
    }
  },

  paths: {
    /* Core AngularJS packages. */
    'angular': 'webjars/angularjs/1.2.11/angular.min',
    'angular-animate': 'webjars/angularjs/1.2.11/angular-animate.min',
    'angular-resource': 'webjars/angularjs/1.2.11/angular-resource.min',
    'angular-route': 'webjars/angularjs/1.2.11/angular-route.min',
    'angular-sanitize': 'webjars/angularjs/1.2.11/angular-sanitize.min',

    'bootstrap': 'vendor/bootstrap/dist/js/bootstrap.min',

    'jquery': 'webjars/jquery/2.1.0/jquery.min',

    'moment': 'webjars/momentjs/2.5.0/min/moment.min',

    'restangular': 'webjars/restangular/1.3.1/restangular.min',

    'underscore': 'webjars/underscorejs/1.5.2/underscore-min'
  },

  shim: {
    'angular': {
      deps: [ 'jquery' ],
      exports: 'angular'
    },

    'angular-animate': ['angular'],
    'angular-resource': ['angular'],
    'angular-route': ['angular'],
    'angular-sanitize': ['angular'],

    'bootstrap': ['jquery'],

    'jquery': {
      exports: 'jQuery'
    },

    'moment': {
      exports: 'moment'
    },

    'restangular': {
      deps: [ 'angular', 'underscore' ]
    },

    'underscore': {
      exports: '_'
    }
  }

// optimize: 'uglify2',
// uglify2: {
//   warnings: false,
//   /* Mangling defeats Angular injection by function argument names. */
//   mangle: false
// }
})

define([
  'jquery'
  , 'angular'
  , 'underscore'

  , './controller'
  , 'text!./template.html'

  , 'angular-route'
  , 'restangular'

  , './code/index'
  , './invitation/index'
  , './itinerary/index'
], function ($, angular, _, controller, template) {
  $(function () {
    angular
      .module('taw', [
        'ngRoute',
        'restangular',
        'taw.code',
        'taw.invitation',
        'taw.itinerary'
      ])

      .filter('pick', function ($parse) {
        return function (source, field) {
          var getter = $parse(field)
          if (angular.isArray(source)) {
            return source.map(getter)
          } else {
            return getter(source)
          }
        }
      })

      .filter('join', function () {
        return function (source, initial, last) {
          if (angular.isArray(source)) {
            switch (source.length) {
              case 0:
                return ''
              case 1:
                return '' + source[0]
              case 2:
                return source.join(last)
              default:
                return (_.initial(source).join(initial) + initial).trim() + last + _.last(source)
            }
          } else {
            return '' + source
          }
        }
      })

      .config(function ($routeProvider, $locationProvider) {
        $routeProvider
          .when('/', {
            controller: controller,
            template: template,
            resolve: controller.resolve
          })
          .otherwise({
            redirectTo: '/'
          })

        $locationProvider.html5Mode(true)
      })

      .run(function (Restangular) {
        Restangular.setBaseUrl('/services')

        Restangular.setRestangularFields({
          id: "_id.$oid"
        })
      })

      .config(function ($httpProvider) {
        $httpProvider.interceptors.push(function ($parse, $rootScope, $q) {
          return {
            'response': function (response) {
              $parse('session._current').assign($rootScope, false)
              return response || $q.when(response)
            },

            'responseError': function (reason) {
              $parse('session._current').assign($rootScope, false)
              return $q.reject(reason)
            }
          }
        })
      })

      .run(function ($rootScope, $browser, $log) {
        $rootScope.$watch('session._current', function (current) {
          if (true === current) {
            return
          }

          /* It turns out Angular polls the browser cookies every 100 milliseconds and transfers the changes to its own $cookies service (see https://github.com/angular/angular.js/blob/1bb33cccbe12bda4c397ddabab35ba1df85d5137/src/ngCookies/cookies.js#L58-L66 for details). This would then require polling here to get the recent values. Instead, wait for another caller to invalidate the session's currency and then ask the browser directly for cookies. */

          var cookies = $browser.cookies()
            , rawCookie = cookies['PLAY_SESSION'] || ''

          var rawData = rawCookie.substring(rawCookie.indexOf('-') + 1, rawCookie.length - 1)
          var session = {}

          _.each(rawData.split('&'), function (rawPair) {
            if (!rawPair.length) {
              return
            }

            var pair = rawPair.split('=')

            try {
              session[pair[0]] = angular.fromJson(pair[1])
            } catch (e) {
              session[pair[0]] = pair[1]
            }
          })

          session._current = true

          $rootScope.session = session
        })
      })

    angular.bootstrap(document, ['taw'])
  })
})

<commit_msg>Don't change the controller when the query changes.<commit_after>'use strict'

require({
  map: {
    '*': {
      /* RequireJS plugins. */
      'async': 'webjars/requirejs-plugins/3ff54566f8/async',
      'json': 'webjars/requirejs-plugins/3ff54566f8/json',
      'goog': 'webjars/requirejs-plugins/3ff54566f8/goog',
      'noext': 'webjars/requirejs-plugins/3ff54566f8/noext',
      'text': 'webjars/requirejs-text/2.0.10/text'
    }
  },

  paths: {
    /* Core AngularJS packages. */
    'angular': 'webjars/angularjs/1.2.11/angular.min',
    'angular-animate': 'webjars/angularjs/1.2.11/angular-animate.min',
    'angular-resource': 'webjars/angularjs/1.2.11/angular-resource.min',
    'angular-route': 'webjars/angularjs/1.2.11/angular-route.min',
    'angular-sanitize': 'webjars/angularjs/1.2.11/angular-sanitize.min',

    'bootstrap': 'vendor/bootstrap/dist/js/bootstrap.min',

    'jquery': 'webjars/jquery/2.1.0/jquery.min',

    'moment': 'webjars/momentjs/2.5.0/min/moment.min',

    'restangular': 'webjars/restangular/1.3.1/restangular.min',

    'underscore': 'webjars/underscorejs/1.5.2/underscore-min'
  },

  shim: {
    'angular': {
      deps: [ 'jquery' ],
      exports: 'angular'
    },

    'angular-animate': ['angular'],
    'angular-resource': ['angular'],
    'angular-route': ['angular'],
    'angular-sanitize': ['angular'],

    'bootstrap': ['jquery'],

    'jquery': {
      exports: 'jQuery'
    },

    'moment': {
      exports: 'moment'
    },

    'restangular': {
      deps: [ 'angular', 'underscore' ]
    },

    'underscore': {
      exports: '_'
    }
  }

// optimize: 'uglify2',
// uglify2: {
//   warnings: false,
//   /* Mangling defeats Angular injection by function argument names. */
//   mangle: false
// }
})

define([
  'jquery'
  , 'angular'
  , 'underscore'

  , './controller'
  , 'text!./template.html'

  , 'angular-route'
  , 'restangular'

  , './code/index'
  , './invitation/index'
  , './itinerary/index'
], function ($, angular, _, controller, template) {
  $(function () {
    angular
      .module('taw', [
        'ngRoute',
        'restangular',
        'taw.code',
        'taw.invitation',
        'taw.itinerary'
      ])

      .filter('pick', function ($parse) {
        return function (source, field) {
          var getter = $parse(field)
          if (angular.isArray(source)) {
            return source.map(getter)
          } else {
            return getter(source)
          }
        }
      })

      .filter('join', function () {
        return function (source, initial, last) {
          if (angular.isArray(source)) {
            switch (source.length) {
              case 0:
                return ''
              case 1:
                return '' + source[0]
              case 2:
                return source.join(last)
              default:
                return (_.initial(source).join(initial) + initial).trim() + last + _.last(source)
            }
          } else {
            return '' + source
          }
        }
      })

      .config(function ($routeProvider, $locationProvider) {
        $routeProvider
          .when('/', {
            controller: controller,
            template: template,
            resolve: controller.resolve,
            reloadOnSearch: false
          })
          .otherwise({
            redirectTo: '/'
          })

        $locationProvider.html5Mode(true)
      })

      .run(function (Restangular) {
        Restangular.setBaseUrl('/services')

        Restangular.setRestangularFields({
          id: "_id.$oid"
        })
      })

      .config(function ($httpProvider) {
        $httpProvider.interceptors.push(function ($parse, $rootScope, $q) {
          return {
            'response': function (response) {
              $parse('session._current').assign($rootScope, false)
              return response || $q.when(response)
            },

            'responseError': function (reason) {
              $parse('session._current').assign($rootScope, false)
              return $q.reject(reason)
            }
          }
        })
      })

      .run(function ($rootScope, $browser, $log) {
        $rootScope.$watch('session._current', function (current) {
          if (true === current) {
            return
          }

          /* It turns out Angular polls the browser cookies every 100 milliseconds and transfers the changes to its own $cookies service (see https://github.com/angular/angular.js/blob/1bb33cccbe12bda4c397ddabab35ba1df85d5137/src/ngCookies/cookies.js#L58-L66 for details). This would then require polling here to get the recent values. Instead, wait for another caller to invalidate the session's currency and then ask the browser directly for cookies. */

          var cookies = $browser.cookies()
            , rawCookie = cookies['PLAY_SESSION'] || ''

          var rawData = rawCookie.substring(rawCookie.indexOf('-') + 1, rawCookie.length - 1)
          var session = {}

          _.each(rawData.split('&'), function (rawPair) {
            if (!rawPair.length) {
              return
            }

            var pair = rawPair.split('=')

            try {
              session[pair[0]] = angular.fromJson(pair[1])
            } catch (e) {
              session[pair[0]] = pair[1]
            }
          })

          session._current = true

          $rootScope.session = session
        })
      })

    angular.bootstrap(document, ['taw'])
  })
})

<|endoftext|>


<commit_before>var createPullRequestListHtml = R.pipe(R.sort(compareDate), R.map(pullRequestsToHtml));

var apiResponses = Bacon.combineAsArray(getPullRequests(), getDomReadyStream())
  .map(R.prop(0));

apiResponses.onValue(showResults);
apiResponses.onError(showError);

function compareDate(a, b) {
  return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
}

function pullRequestsToHtml(pr) {
  return $('<div>', {class: 'pull-request'})
    .append($('<span>', {class: 'repository', text: pr.repository}))
    .append($('<a>', {class: 'pr-title', href: pr.html_url, target: '_blank', text: pr.title}))
    .append($('<div>', {class: 'meta', text: getMetaText(pr)}));
}

function getMetaText(pr) {
  return '#' + pr.number + ' opened ' + moment(pr.created_at).fromNow() + ' by ' + pr.user.login;
}

function setSpinning(isSpinning) {
  if (isSpinning) {
    $('.github-logo').addClass('spinning');
  } else {
    $('.github-logo').removeClass('spinning');
  }
}

function showResults(results) {
  var pullRequestHtml = createPullRequestListHtml(results);
  $('#pull-requests').html(pullRequestHtml);

  setSpinning(false);
}

function showError(error) {
  setSpinning(false);
  console.log('ERROR', error);
}

function getDomReadyStream() {
  setSpinning(true);
  return Bacon.fromCallback(function(callback) {
    $(document).ready(callback);
  });
}

function getPullRequests() {
    return Bacon.fromPromise($.ajax({
        url: '/prs/',
        type: 'GET',
        dataType: 'json',
        timeout: 10000
    }));
}
<commit_msg>Wrap code to a strict closure function<commit_after>(function () {
    'use strict';

    var createPullRequestListHtml = R.pipe(R.sort(compareDate), R.map(pullRequestsToHtml));

    var apiResponses = Bacon.combineAsArray(getPullRequests(), getDomReadyStream())
        .map(R.prop(0));

    apiResponses.onValue(showResults);
    apiResponses.onError(showError);

    function compareDate(a, b) {
        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
    }

    function pullRequestsToHtml(pr) {
        return $('<div>', {
                class: 'pull-request'
            })
            .append($('<span>', {
                class: 'repository',
                text: pr.repository
            }))
            .append($('<a>', {
                class: 'pr-title',
                href: pr.html_url,
                target: '_blank',
                text: pr.title
            }))
            .append($('<div>', {
                class: 'meta',
                text: getMetaText(pr)
            }));
    }

    function getMetaText(pr) {
        return '#' + pr.number + ' opened ' + moment(pr.created_at).fromNow() + ' by ' + pr.user.login;
    }

    function setSpinning(isSpinning) {
        if (isSpinning) {
            $('.github-logo').addClass('spinning');
        } else {
            $('.github-logo').removeClass('spinning');
        }
    }

    function showResults(results) {
        var pullRequestHtml = createPullRequestListHtml(results);
        $('#pull-requests').html(pullRequestHtml);

        setSpinning(false);
    }

    function showError(error) {
        setSpinning(false);
        console.log('ERROR', error);
    }

    function getDomReadyStream() {
        setSpinning(true);
        return Bacon.fromCallback(function (callback) {
            $(document).ready(callback);
        });
    }

    function getPullRequests() {
        return Bacon.fromPromise($.ajax({
            url: '/prs/',
            type: 'GET',
            dataType: 'json',
            timeout: 10000
        }));
    }
}());
<|endoftext|>


<commit_before>import mdc from '../src/index-browser'
import $ from 'jquery'

$(function () {
  mdc.map = true
  $.get('sample.md', function (data) {
    mdc.init(data, false)
    window.addEventListener('hashchange', function () { scrollBy(0, -8) }) // a little gap to top
    if (window.location.hash.length > 0) {
      $('html,body').scrollTop($(window.location.hash).offset().top - 8) // scroll to hash element
    }
  })
})
<commit_msg>Minor change<commit_after>import mdc from '../src/index-browser'
import $ from 'jquery'

$(function () {
  mdc.map = true
  $.get('sample.md', function (data) {
    mdc.init(data, false)
    window.addEventListener('hashchange', function () { window.scrollBy(0, -8) }) // a little gap to top
    if (window.location.hash.length > 0) {
      $('html,body').scrollTop($(window.location.hash).offset().top - 8) // scroll to hash element
    }
  })
})
<|endoftext|>


<commit_before>

//Load Json with jquery
function refresh() {    // do once original document loaded and ready
                $.getJSON("http://btc.blockr.io/api/v1/coin/info", function(responseObject, diditwork) {
                        console.log(diditwork);
                        var displayText = responseObject.data.coin.name
                $("#responseArea2").html(displayText);
                } );  // getJSON
  } ); // onReady

$(document).ready(function(){
    window.setInterval(refresh, 2000);
});<commit_msg>new api<commit_after>

//Load Json with jquery
function refresh() {    // do once original document loaded and ready
                $.getJSON("http://btc.blockr.io/api/v1/coin/info", function(responseObject, diditwork) {
                        console.log(diditwork);
                        var displayText = responseObject.data.coin.name
                $("#responseArea2").html(displayText);
                };  // getJSON
  } ); // onReady

$(document).ready(function(){
    window.setInterval(refresh, 2000);
});<|endoftext|>


<commit_before>// -----------------------------------------------------------------
//  index.js
//
//  talking-drum
//  Copyright 2013. Colin Milhench. All rights reserved.
//
//  Colin Milhench
//

/* jshint browser:true */

window.ko.bindingHandlers.scrollBottom = {
  init: function(element, valueAccessor) {
    var previous = element.scrollTop;
    valueAccessor().subscribe(function(){
      if (element.scrollTop === previous) {
        element.scrollTop = element.scrollHeight;
        previous = element.scrollTop;
      }
    });
  }
};

window.ko.bindingHandlers.contract = {
  init: function(element, valueAccessor) {
    var resize = function(){
      // expected to run befor the expand so null the expanded one out here.
      element.parentNode.querySelector('[data-bind*="expand:"]').style['min-height'] = '80px';
      element.style['max-height'] = '100%';
      var style = window.getComputedStyle(element.parentNode);
      var bottom = parseInt(style['margin-top'], 10);
      var top = parseInt(style['margin-bottom'], 10);
      var space = window.innerHeight - (bottom + element.parentNode.offsetHeight + top);
      if (space < 0) {
        element.style['max-height'] = (element.offsetHeight + space) + 'px';
      }
    };
    valueAccessor().subscribe(resize);
    window.addEventListener('resize', resize);
    resize();
  }
};

window.ko.bindingHandlers.expand = {
  init: function(element, valueAccessor) {
    var resize = function(){
      element.style['min-height'] = '80px';
      var style = window.getComputedStyle(element.parentNode);
      var bottom = parseInt(style['margin-top'], 10);
      var top = parseInt(style['margin-bottom'], 10);
      var space = window.innerHeight - (bottom + element.parentNode.offsetHeight + top);
      if (space > 0) {
        element.style['min-height'] = (element.offsetHeight + space) + 'px';
      }
    };
    valueAccessor().subscribe(resize);
    window.addEventListener('resize', resize);
    resize();
  }
};

// -----------------------------------------------------------------
//  Initialization

var vm = new window.ViewModel();
var client = new window.Client(vm);
window.ko.applyBindings(vm);
window.client = client;

// -----------------------------------------------------------------
//  listen to socket events
var irc = window.io.connect('http://localhost:3000/irc');
var socket = irc.on('connect', function () {

  var send = [
    'write','pass','nick','user','send',
    'join','part','topic','kick','oper',
    'mode','invite','notice'
  ];
  var recv = Object.keys( window.Client.prototype).filter(function(key){
    return ['use'].indexOf(key) === -1;
  });

  send.forEach(function(event){
    client.on(event, socket.emit.bind(socket, event));
  });
  recv.forEach(function(event){
    socket.on(event, client[event].bind(client));
  });

  client.model.viewState(client.model.viewStates[1]);
  socket.on('disconnect', function() {
    client.model.viewState(client.model.viewStates[0]);
    send.forEach(function(event){
      client.removeAllListeners(event);
    });
    recv.forEach(function(event){
      socket.removeAllListeners(event);
    });
  });

});<commit_msg>add who, whois and whowas client\index<commit_after>// -----------------------------------------------------------------
//  index.js
//
//  talking-drum
//  Copyright 2013. Colin Milhench. All rights reserved.
//
//  Colin Milhench
//

/* jshint browser:true */

window.ko.bindingHandlers.scrollBottom = {
  init: function(element, valueAccessor) {
    var previous = element.scrollTop;
    valueAccessor().subscribe(function(){
      if (element.scrollTop === previous) {
        element.scrollTop = element.scrollHeight;
        previous = element.scrollTop;
      }
    });
  }
};

window.ko.bindingHandlers.contract = {
  init: function(element, valueAccessor) {
    var resize = function(){
      // expected to run befor the expand so null the expanded one out here.
      element.parentNode.querySelector('[data-bind*="expand:"]').style['min-height'] = '80px';
      element.style['max-height'] = '100%';
      var style = window.getComputedStyle(element.parentNode);
      var bottom = parseInt(style['margin-top'], 10);
      var top = parseInt(style['margin-bottom'], 10);
      var space = window.innerHeight - (bottom + element.parentNode.offsetHeight + top);
      if (space < 0) {
        element.style['max-height'] = (element.offsetHeight + space) + 'px';
      }
    };
    valueAccessor().subscribe(resize);
    window.addEventListener('resize', resize);
    resize();
  }
};

window.ko.bindingHandlers.expand = {
  init: function(element, valueAccessor) {
    var resize = function(){
      element.style['min-height'] = '80px';
      var style = window.getComputedStyle(element.parentNode);
      var bottom = parseInt(style['margin-top'], 10);
      var top = parseInt(style['margin-bottom'], 10);
      var space = window.innerHeight - (bottom + element.parentNode.offsetHeight + top);
      if (space > 0) {
        element.style['min-height'] = (element.offsetHeight + space) + 'px';
      }
    };
    valueAccessor().subscribe(resize);
    window.addEventListener('resize', resize);
    resize();
  }
};

// -----------------------------------------------------------------
//  Initialization

var vm = new window.ViewModel();
var client = new window.Client(vm);
window.ko.applyBindings(vm);
window.client = client;

// -----------------------------------------------------------------
//  listen to socket events
var irc = window.io.connect('http://localhost:3000/irc');
var socket = irc.on('connect', function () {

  var send = [
    'write','pass','nick','user','send',
    'join','part','topic','kick','oper',
    'mode','invite','notice','who','whois',
    'whowas'
  ];
  var recv = Object.keys( window.Client.prototype).filter(function(key){
    return ['use'].indexOf(key) === -1;
  });

  send.forEach(function(event){
    client.on(event, socket.emit.bind(socket, event));
  });
  recv.forEach(function(event){
    socket.on(event, client[event].bind(client));
  });

  client.model.viewState(client.model.viewStates[1]);
  socket.on('disconnect', function() {
    client.model.viewState(client.model.viewStates[0]);
    send.forEach(function(event){
      client.removeAllListeners(event);
    });
    recv.forEach(function(event){
      socket.removeAllListeners(event);
    });
  });

});<|endoftext|>


<commit_before>$(document).ready(function() {
   var msg = function(msg, type){
      alert(msg);
   };
   $("#formaddmovie").submit(function(event) {
      event.preventDefault();
      addMovie();
   });
   var addMovie = function() {
            var data = {
               title: $('#addMovieTitle').val();
               imdbid: $('#addMovieimdbid').val();
               boxofficemojoid: $('#addMovieboxofficemojoid').val();
               runtime: $('#addMovieruntime').val();
               date_opening: $('#addMoviedate_opening').val();
               date_opening_us: $('#addMoviedate_opening_us').val();
               date_opening_china: $('#addMoviedate_opening_china').val();
               date_release_disc: $('#addMoviedate_release_disc').val();
            };
            $.ajax("/movie/add"{
               type: "POST",
               data: data,
               dataType: "json",
               success: function(text) {
                  if(text == "success") {
                     msg('New Movie created. ' + text);
                  }
               }
            });
      };
});<commit_msg>mojo ripper<commit_after>$(document).ready(function() {
   var msg = function(msg, type){
      alert(msg);
   };
   $("#formaddmovie").submit(function(event) {
      event.preventDefault();
      addMovie();
   });
   var addMovie = function() {
            var data = {
               title: $('#addMovieTitle').val(),
               imdbid: $('#addMovieimdbid').val(),
               boxofficemojoid: $('#addMovieboxofficemojoid').val(),
               runtime: $('#addMovieruntime').val(),
               date_opening: $('#addMoviedate_opening').val(),
               date_opening_us: $('#addMoviedate_opening_us').val(),
               date_opening_china: $('#addMoviedate_opening_china').val(),
               date_release_disc: $('#addMoviedate_release_disc').val()
            };
            $.ajax("/movie/add"{
               type: "POST",
               data: data,
               dataType: "json",
               success: function(text) {
                  if(text == "success") {
                     msg('New Movie created. ' + text);
                  }
               }
            });
      };
});<|endoftext|>