<commit_before>$.when($.ajax(loadBucket())).then(function () {
  //buckets = getBuckets();
   render();

});
var curBucket = 0;

$(document).ready(function(){

  $("#close-product").click(function(){
    $("#new-product").slideUp();
  });

  $("#add-product").click(function(){
    $("#new-product").slideDown();
  });

  $("#close-bucket").click(function(){
    $("#new-bucket").slideUp();
  });

  $("#add-bucket").click(function(){
    $("#new-bucket").slideDown();
  });

  $("#bucket-submit").click(function(){
    //saveChanges();
    var bucketName = $('#bucket-name').val();
    var color = $("input[name=color]:checked").val()
    var icon = $("input[name=icon]:checked").val()
    addBucket(bucketName, color, icon);
    //buckets = getBuckets();
    renderBuckets();
    $('#bucket-name').val("");
    $("#new-bucket").slideUp();
    saveChanges();
  });

  $("#delete-bucket").click(function(){
    removeBucket(arrBucket[curBucket]);
    saveChanges();
    renderBuckets();
    renderProducts(arrBucket[curBucket]);
  });

  $("#product-add").click(function(){
    //saveChanges();
    var productName = $('#product').val();
    var productPrice = $('#price').val();
    var productQuantity = $('#quantity').val();
    var productComment = $('#comments').val();
    var url = $('#pageURL').val();
    var imgURL = $('#prod_img').attr('src');
    arrBucket[curBucket].addProduct(url, imgURL, productPrice, productQuantity, productName, productComment);
    //saveChanges();
    //buckets = getBuckets();
    renderProducts(arrBucket[curBucket].products);
    $("#new-product").slideUp();
    saveChanges();
  });

});

function renderBuckets(){
  $("#buckets").empty();
  var collection = document.createElement("ul");
  $(collection).addClass("collection")
  for (i = 0; i < arrBucket.length; i++) {
    var title = arrBucket[i].name;
    var color = arrBucket[i].color;
    var icon = arrBucket[i].icon;
    if (i == 0) {
      $(collection).append('
' + icon + '
' + title +'

');
    } else {
      $(collection).append('
' + icon + '
' + title +'

');
    }
  }
  $("#buckets").append(collection);
  $(".bucket").click(function(){
    var circle = $(this).find("i");
    var classes = (circle.attr("class"));
    classes = classes.replace("material-icons circle","");
    $(this).addClass(classes);
    $(this).addClass("selected");
    $(circle).removeClass(classes);
    var siblings = $(this).siblings();
    $(siblings).each(function( index ) {
      if ($(siblings[index]).hasClass("selected")) {
        $(siblings[index]).removeClass("selected");
        classes = ($(siblings[index]).attr("class"));
        classes = classes.replace("collection-item bucket","");
        $(siblings[index]).find("i").addClass(classes);
        $(siblings[index]).removeClass(classes);
      }
    });
    // call render
    var name = $(this).find(".title")[0].innerHTML;
    for (i = 0; i < arrBucket.length; i++) {
      if (arrBucket[i].name == name) {
        curBucket = i;
        renderProducts(arrBucket[i].products);
      }
    }
  });
}

function render () {
  //buckets = getBuckets();
  if (arrBucket.length > 0){
    renderBuckets();
    renderProducts(arrBucket[curBucket].products);
  }
}

function renderProducts(productList){
  $("#product-list").empty();
  if (productList.length > 0) {
    for (j = 0; j < productList.length; j++) {
      var product = productList[j];
      var item = document.createElement("div");
      $(item).addClass("wishlist-item");
      $(item).addClass("valign-wrapper");
      $(item).append('delete

'+ product.price +'

' + product.quantity + '

'+ product.productName +'

'+ product.comment +'

create');
      $("#product-list").append(item);
    }
  } else {
    var item = document.createElement("div");
    item.innerHTML = "empty";
    $("#product-list").append(item);
  }
  $(".product-title").click(function() {
      chrome.tabs.update({
       url: $(this).attr("url")
     })
  });
  $(".checkbox").click(function(){
    var siblings = $(this).parent().parent().children();
    for (var i = 0; i < siblings.length; i++) {
      if (siblings[i] = $(this).parent()) {
        arrBucket[curBucket].removeProduct(arrBucket[curBucket].getProductList()[i]);
        saveChanges();
        break;
      }
    }
    $(this).parent().fadeOut();
  });
}
<commit_msg>More settings editing stuff<commit_after>$.when($.ajax(loadBucket())).then(function () {
  //buckets = getBuckets();
   render();

});
var curBucket = 0;

$(document).ready(function(){

  $("#close-product").click(function(){
    $("#new-product").slideUp();
  });

  $("#add-product").click(function(){
    $("#new-product").slideDown();
  });

  $("#close-bucket").click(function(){
    $("#new-bucket").slideUp();
  });

   $("#add-bucket").click(function(){
    $("#new-bucket-card").show();
    $("#update-bucket-card").hide();
    $("#new-bucket").slideDown();
  });

  $("#bucket-submit").click(function(){
    //saveChanges();
    var bucketName = $('#bucket-name').val();
    var color = $("input[name=color]:checked").val()
    var icon = $("input[name=icon]:checked").val()
    addBucket(bucketName, color, icon);
    //buckets = getBuckets();
    renderBuckets();
    $('#bucket-name').val("");
    $("#new-bucket").slideUp();
    saveChanges();
  });

  $("#delete-bucket").click(function(){
    removeBucket(arrBucket[curBucket]);
    $("#new-bucket").slideUp();
    saveChanges();
    renderBuckets();
    renderProducts(arrBucket[curBucket]);
  });

  $("#product-add").click(function(){
    //saveChanges();
    var productName = $('#product').val();
    var productPrice = $('#price').val();
    var productQuantity = $('#quantity').val();
    var productComment = $('#comments').val();
    var url = $('#pageURL').val();
    var imgURL = $('#prod_img').attr('src');
    arrBucket[curBucket].addProduct(url, imgURL, productPrice, productQuantity, productName, productComment);
    //saveChanges();
    //buckets = getBuckets();
    renderProducts(arrBucket[curBucket].products);
    $("#new-product").slideUp();
    saveChanges();
  });

});

function renderBuckets(){
  $("#buckets").empty();
  var collection = document.createElement("ul");
  $(collection).addClass("collection")
  for (i = 0; i < arrBucket.length; i++) {
    var title = arrBucket[i].name;
    var color = arrBucket[i].color;
    var icon = arrBucket[i].icon;
    if (i == 0) {
      $(collection).append('
' + icon + '
' + title +'settings

');
    } else {
      $(collection).append('
' + icon + '
' + title +'settings

');
    }
  }
  $("#buckets").append(collection);
  $(".bucket").click(function(){
    var circle = $(this).find("i");
    var classes = (circle.attr("class"));
    classes = classes.replace("material-icons circle","");
    $(this).addClass(classes);
    $(this).addClass("selected");
    $(circle).removeClass(classes);
    var siblings = $(this).siblings();
    $(siblings).each(function( index ) {

      if ($(siblings[index]).hasClass("selected")) {
      	$(".settingsGear").show();
        $(siblings[index]).removeClass("selected");
        classes = ($(siblings[index]).attr("class"));
        classes = classes.replace("collection-item bucket","");

        var icons = $(siblings[index]).find("i");
  	$(icons[0]).addClass(classes);
        $(siblings[index]).removeClass(classes);
        console.log(classes);
      }
    });

    //if the gear on the bucket is clicked
    $(".settingsGear").click(function(){
          $("#new-bucket-card").hide();
    	  $("#update-bucket-card").show();
	  $("#new-bucket").slideDown();
  });
    // call render
    var name = $(this).find(".title")[0].innerHTML;
    for (i = 0; i < arrBucket.length; i++) {
      if (arrBucket[i].name == name) {
        curBucket = i;
        renderProducts(arrBucket[i].products);
      }
    }
  });

}

function render () {
  //buckets = getBuckets();
  if (arrBucket.length > 0){
    renderBuckets();
    renderProducts(arrBucket[curBucket].products);
  }
}

function renderProducts(productList){
  $("#product-list").empty();
  if (productList.length > 0) {
    for (j = 0; j < productList.length; j++) {
      var product = productList[j];
      var item = document.createElement("div");
      $(item).addClass("wishlist-item");
      $(item).addClass("valign-wrapper");
      $(item).append('delete

'+ product.price +'

' + product.quantity + '

'+ product.productName +'

'+ product.comment +'

create');
      $("#product-list").append(item);
    }
  } else {
    var item = document.createElement("div");
    item.innerHTML = "empty";
    $("#product-list").append(item);
  }
  $(".product-title").click(function() {
      chrome.tabs.update({
       url: $(this).attr("url")
     })
  });
  $(".checkbox").click(function(){
    var siblings = $(this).parent().parent().children();
    for (var i = 0; i < siblings.length; i++) {
      if (siblings[i] = $(this).parent()) {
        arrBucket[curBucket].removeProduct(arrBucket[curBucket].getProductList()[i]);
        saveChanges();
        break;
      }
    }
    $(this).parent().fadeOut();
  });
}
<|endoftext|>


<commit_before>MapSearchApp.Views.MarkerView = Backbone.View.extend({

    initialize: function (params) {

        this.model.on("change:selected", function (ob1) {
            if (this.model.isSelected()) {
                this.$el.addClass("highlighted");
            } else {
                this.$el.removeClass("highlighted");
            }
        });

    },

    template: MapSearchApp.Services.templates.get("#marker-template"),

    render: function () {
        var json = this.model.toJSON();
        var m1 = {x: json.lat * 6,
            y: json.lng * 4};
        var html = this.template(m1);
        this.$el.html(html);
        if (this.model.isSelected()) {
            this.$el.addClass("highlighted");
        }

        return this;
    }

});

// CSS class: "highlighted"
// $obj.addClass("css-class")
// $obj.removeClass("css-class")
<commit_msg>click on marker works<commit_after>MapSearchApp.Views.MarkerView = Backbone.View.extend({

    initialize: function (params) {
        var that = this;
        //events on model
        this.model.on("change:selected", function (ob1) {
            this.render();
        }, this);
    },

    //use for events on this.$el
    events: {
        "click": "onClick"
    },

    onClick: function () {
        //console.log(this);
        this.model.toggleSelected();
    },

    template: MapSearchApp.Services.templates.get("#marker-template"),

    render: function () {
        var json = this.model.toJSON();
        var m1 = {x: json.lat * 6,
            y: json.lng * 4};
        var html = this.template(m1);
        this.$el.html(html);
        if (this.model.isSelected()) {
            this.$el.find('.marker').addClass("highlighted");
        }

        return this;
    }

});

// CSS class: "highlighted"
// $obj.addClass("css-class")
// $obj.removeClass("css-class")
<|endoftext|>


<commit_before>---
---

(function($) {
  "use strict";
  // From https://paste.ee/p/y1RvZ and https://justgetflux.com/
  // Modified by le717

  // TODO Testing
  window.similarproducts = {};

  function checkLenovo() {
    if (window.similarproducts) { // this variable is defined as soon as the malicious payload from Superfish is injected into the DOM
      // display a warning to your visitor that they've been hacked by Lenovo
      $(".page-wrapper").prepend('{% include lenovo.html %}'.replace("\n" "\n\\"));
    }
  }

  $(".lenovo .btn.close").on("click", function() {
    $(".lenovo").remove();
  });

  window.setTimeout(checkLenovo, 5000);
})(jQuery);
<commit_msg>. [ci skip]<commit_after>---
---

(function($) {
  "use strict";
  // From https://paste.ee/p/y1RvZ and https://justgetflux.com/
  // Modified by le717

  // TODO Testing
  window.similarproducts = {};

  function checkLenovo() {
    if (window.similarproducts) { // this variable is defined as soon as the malicious payload from Superfish is injected into the DOM
      // display a warning to your visitor that they've been hacked by Lenovo
      $(".page-wrapper").prepend('{% include lenovo.html %}'.replace(/\n/g, ""));
    }
  }

  $(".lenovo .btn.close").on("click", function() {
    $(".lenovo").remove();
  });

  window.setTimeout(checkLenovo, 5000);
})(jQuery);
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

//  ---------------------------------------------------------------------------

module.exports = class lykke extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'lykke',
            'name': 'Lykke',
            'countries': 'CH',
            'version': 'v1',
            'rateLimit': 200,
            'has': {
                'CORS': false,
                'fetchOHLCV': false,
                'fetchTrades': false,
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/34487620-3139a7b0-efe6-11e7-90f5-e520cef74451.jpg',
                'api': {
                    'mobile': 'https://api.lykkex.com/api',
                    'public': 'https://hft-api.lykke.com/api',
                    'private': 'https://hft-api.lykke.com/api',
                    'test': {
                        'mobile': 'https://api.lykkex.com/api',
                        'public': 'https://hft-service-dev.lykkex.net/api',
                        'private': 'https://hft-service-dev.lykkex.net/api',
                    },
                },
                'www': 'https://www.lykke.com',
                'doc': [
                    'https://hft-api.lykke.com/swagger/ui/',
                    'https://www.lykke.com/lykke_api',
                ],
                'fees': 'https://www.lykke.com/trading-conditions',
            },
            'api': {
                'mobile': {
                    'get': [
                        'AllAssetPairRates/{market}',
                    ],
                },
                'public': {
                    'get': [
                        'AssetPairs',
                        'AssetPairs/{id}',
                        'IsAlive',
                        'OrderBooks',
                        'OrderBooks/{AssetPairId}',
                    ],
                },
                'private': {
                    'get': [
                        'Orders',
                        'Orders/{id}',
                        'Wallets',
                    ],
                    'post': [
                        'Orders/limit',
                        'Orders/market',
                        'Orders/{id}/Cancel',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': false,
                    'percentage': true,
                    'maker': 0.0010,
                    'taker': 0.0019,
                },
                'funding': {
                    'tierBased': false,
                    'percentage': false,
                    'withdraw': {
                        'BTC': 0.001,
                    },
                    'deposit': {
                        'BTC': 0,
                    },
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privateGetWallets ();
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let currency = balance['AssetId'];
            let total = balance['Balance'];
            let used = balance['Reserved'];
            let free = total - used;
            result[currency] = {
                'free': free,
                'used': used,
                'total': total,
            };
        }
        return this.parseBalance (result);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostOrdersIdCancel ({ 'id': id });
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let query = {
            'AssetPairId': market['id'],
            'OrderAction': this.capitalize (side),
            'Volume': amount,
        };
        if (type === 'market') {
            query['Asset'] = (side === 'buy') ? market['base'] : market['quote'];
        } else if (type === 'limit') {
            query['Price'] = price;
        }
        let method = 'privatePostOrders' + this.capitalize (type);
        let result = await this[method] (this.extend (query, params));
        return {
            'id': undefined,
            'info': result,
        };
    }

    async fetchMarkets () {
        let markets = await this.publicGetAssetPairs ();
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['Id'];
            let base = market['BaseAssetId'];
            let quote = market['QuotingAssetId'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = market['Name'];
            let precision = {
                'amount': market['Accuracy'],
                'price': market['InvertedAccuracy'],
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'active': true,
                'info': market,
                'lot': Math.pow (10, -precision['amount']),
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': Math.pow (10, -precision['amount']),
                        'max': Math.pow (10, precision['amount']),
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': Math.pow (10, precision['price']),
                    },
                },
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        ticker = ticker['Result'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': parseFloat (ticker['Rate']['Bid']),
            'ask': parseFloat (ticker['Rate']['Ask']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': undefined,
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let ticker = await this.mobileGetAllAssetPairRatesMarket (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTicker (ticker, market);
    }

    parseOrderStatus (status) {
        if (status === 'Pending') {
            return 'open';
        } else if (status === 'InOrderBook') {
            return 'open';
        } else if (status === 'Processing') {
            return 'open';
        } else if (status === 'Matched') {
            return 'closed';
        } else if (status === 'Cancelled') {
            return 'canceled';
        } else if (status === 'NotEnoughFunds') {
            return 'NotEnoughFunds';
        } else if (status === 'NoLiquidity') {
            return 'NoLiquidity';
        } else if (status === 'UnknownAsset') {
            return 'UnknownAsset';
        } else if (status === 'LeadToNegativeSpread') {
            return 'LeadToNegativeSpread';
        }
        return status;
    }

    parseOrder (order, market = undefined) {
        let status = this.parseOrderStatus (order['Status']);
        let symbol = undefined;
        if (!market) {
            if ('AssetPairId' in order)
                if (order['AssetPairId'] in this.markets_by_id)
                    market = this.markets_by_id[order['AssetPairId']];
        }
        if (market)
            symbol = market['symbol'];
        let timestamp = undefined;
        if ('LastMatchTime' in order) {
            timestamp = this.parse8601 (order['LastMatchTime']);
        } else if ('Registered' in order) {
            timestamp = this.parse8601 (order['Registered']);
        } else if ('CreatedAt' in order) {
            timestamp = this.parse8601 (order['CreatedAt']);
        }
        let price = this.safeFloat (order, 'Price');
        let amount = this.safeFloat (order, 'Volume');
        let remaining = this.safeFloat (order, 'RemainingVolume');
        let filled = amount - remaining;
        let cost = filled * price;
        let result = {
            'info': order,
            'id': order['Id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            'side': undefined,
            'price': price,
            'cost': cost,
            'average': undefined,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': undefined,
        };
        return result;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        let response = await this.privateGetOrdersId (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (response);
    }

    async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetOrders ();
        return this.parseOrders (response, undefined, since, limit);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetOrders (this.extend ({
            'status': 'InOrderBook',
        }, params));
        return this.parseOrders (response, undefined, since, limit);
    }

    async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetOrders (this.extend ({
            'status': 'Matched',
        }, params));
        return this.parseOrders (response, undefined, since, limit);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetOrderBooksAssetPairId (this.extend ({
            'AssetPairId': this.marketId (symbol),
        }, params));
        let orderbook = {
            'timestamp': undefined,
            'bids': [],
            'asks': [],
        };
        let timestamp = undefined;
        for (let i = 0; i < response.length; i++) {
            let side = response[i];
            if (side['IsBuy']) {
                orderbook['bids'] = this.arrayConcat (orderbook['bids'], side['Prices']);
            } else {
                orderbook['asks'] = this.arrayConcat (orderbook['asks'], side['Prices']);
            }
            let timestamp = this.parse8601 (side['Timestamp']);
            if (!orderbook['timestamp']) {
                orderbook['timestamp'] = timestamp;
            } else {
                orderbook['timestamp'] = Math.max (orderbook['timestamp'], timestamp);
            }
        }
        if (!timestamp)
            timestamp = this.milliseconds ();
        return this.parseOrderBook (orderbook, orderbook['timestamp'], 'bids', 'asks', 'Price', 'Volume');
    }

    parseBidAsk (bidask, priceKey = 0, amountKey = 1) {
        let price = parseFloat (bidask[priceKey]);
        let amount = parseFloat (bidask[amountKey]);
        if (amount < 0)
            amount = -amount;
        return [ price, amount ];
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else if (api === 'private') {
            if (method === 'GET')
                if (Object.keys (query).length)
                    url += '?' + this.urlencode (query);
            this.checkRequiredCredentials ();
            headers = {
                'api-key': this.apiKey,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            };
            if (method === 'POST')
                if (Object.keys (params).length)
                    body = this.json (params);
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<commit_msg>lykke metainfo updated<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');

//  ---------------------------------------------------------------------------

module.exports = class lykke extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'lykke',
            'name': 'Lykke',
            'countries': 'CH',
            'version': 'v1',
            'rateLimit': 200,
            'has': {
                'CORS': false,
                'fetchOHLCV': false,
                'fetchTrades': false,
                'fetchOpenOrders': true,
                'fetchClosedOrders': true,
                'fetchOrders': true,
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/34487620-3139a7b0-efe6-11e7-90f5-e520cef74451.jpg',
                'api': {
                    'mobile': 'https://api.lykkex.com/api',
                    'public': 'https://hft-api.lykke.com/api',
                    'private': 'https://hft-api.lykke.com/api',
                    'test': {
                        'mobile': 'https://api.lykkex.com/api',
                        'public': 'https://hft-service-dev.lykkex.net/api',
                        'private': 'https://hft-service-dev.lykkex.net/api',
                    },
                },
                'www': 'https://www.lykke.com',
                'doc': [
                    'https://hft-api.lykke.com/swagger/ui/',
                    'https://www.lykke.com/lykke_api',
                ],
                'fees': 'https://www.lykke.com/trading-conditions',
            },
            'api': {
                'mobile': {
                    'get': [
                        'AllAssetPairRates/{market}',
                    ],
                },
                'public': {
                    'get': [
                        'AssetPairs',
                        'AssetPairs/{id}',
                        'IsAlive',
                        'OrderBooks',
                        'OrderBooks/{AssetPairId}',
                    ],
                },
                'private': {
                    'get': [
                        'Orders',
                        'Orders/{id}',
                        'Wallets',
                    ],
                    'post': [
                        'Orders/limit',
                        'Orders/market',
                        'Orders/{id}/Cancel',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'tierBased': false,
                    'percentage': true,
                    'maker': 0.0010,
                    'taker': 0.0019,
                },
                'funding': {
                    'tierBased': false,
                    'percentage': false,
                    'withdraw': {
                        'BTC': 0.001,
                    },
                    'deposit': {
                        'BTC': 0,
                    },
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        let balances = await this.privateGetWallets ();
        let result = { 'info': balances };
        for (let i = 0; i < balances.length; i++) {
            let balance = balances[i];
            let currency = balance['AssetId'];
            let total = balance['Balance'];
            let used = balance['Reserved'];
            let free = total - used;
            result[currency] = {
                'free': free,
                'used': used,
                'total': total,
            };
        }
        return this.parseBalance (result);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostOrdersIdCancel ({ 'id': id });
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let query = {
            'AssetPairId': market['id'],
            'OrderAction': this.capitalize (side),
            'Volume': amount,
        };
        if (type === 'market') {
            query['Asset'] = (side === 'buy') ? market['base'] : market['quote'];
        } else if (type === 'limit') {
            query['Price'] = price;
        }
        let method = 'privatePostOrders' + this.capitalize (type);
        let result = await this[method] (this.extend (query, params));
        return {
            'id': undefined,
            'info': result,
        };
    }

    async fetchMarkets () {
        let markets = await this.publicGetAssetPairs ();
        let result = [];
        for (let i = 0; i < markets.length; i++) {
            let market = markets[i];
            let id = market['Id'];
            let base = market['BaseAssetId'];
            let quote = market['QuotingAssetId'];
            base = this.commonCurrencyCode (base);
            quote = this.commonCurrencyCode (quote);
            let symbol = market['Name'];
            let precision = {
                'amount': market['Accuracy'],
                'price': market['InvertedAccuracy'],
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'active': true,
                'info': market,
                'lot': Math.pow (10, -precision['amount']),
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': Math.pow (10, -precision['amount']),
                        'max': Math.pow (10, precision['amount']),
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': Math.pow (10, precision['price']),
                    },
                },
            });
        }
        return result;
    }

    parseTicker (ticker, market = undefined) {
        let timestamp = this.milliseconds ();
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        ticker = ticker['Result'];
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': undefined,
            'low': undefined,
            'bid': parseFloat (ticker['Rate']['Bid']),
            'ask': parseFloat (ticker['Rate']['Ask']),
            'vwap': undefined,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': undefined,
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        let market = this.market (symbol);
        let ticker = await this.mobileGetAllAssetPairRatesMarket (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTicker (ticker, market);
    }

    parseOrderStatus (status) {
        if (status === 'Pending') {
            return 'open';
        } else if (status === 'InOrderBook') {
            return 'open';
        } else if (status === 'Processing') {
            return 'open';
        } else if (status === 'Matched') {
            return 'closed';
        } else if (status === 'Cancelled') {
            return 'canceled';
        } else if (status === 'NotEnoughFunds') {
            return 'NotEnoughFunds';
        } else if (status === 'NoLiquidity') {
            return 'NoLiquidity';
        } else if (status === 'UnknownAsset') {
            return 'UnknownAsset';
        } else if (status === 'LeadToNegativeSpread') {
            return 'LeadToNegativeSpread';
        }
        return status;
    }

    parseOrder (order, market = undefined) {
        let status = this.parseOrderStatus (order['Status']);
        let symbol = undefined;
        if (!market) {
            if ('AssetPairId' in order)
                if (order['AssetPairId'] in this.markets_by_id)
                    market = this.markets_by_id[order['AssetPairId']];
        }
        if (market)
            symbol = market['symbol'];
        let timestamp = undefined;
        if ('LastMatchTime' in order) {
            timestamp = this.parse8601 (order['LastMatchTime']);
        } else if ('Registered' in order) {
            timestamp = this.parse8601 (order['Registered']);
        } else if ('CreatedAt' in order) {
            timestamp = this.parse8601 (order['CreatedAt']);
        }
        let price = this.safeFloat (order, 'Price');
        let amount = this.safeFloat (order, 'Volume');
        let remaining = this.safeFloat (order, 'RemainingVolume');
        let filled = amount - remaining;
        let cost = filled * price;
        let result = {
            'info': order,
            'id': order['Id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            'side': undefined,
            'price': price,
            'cost': cost,
            'average': undefined,
            'amount': amount,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': undefined,
        };
        return result;
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        let response = await this.privateGetOrdersId (this.extend ({
            'id': id,
        }, params));
        return this.parseOrder (response);
    }

    async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetOrders ();
        return this.parseOrders (response, undefined, since, limit);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetOrders (this.extend ({
            'status': 'InOrderBook',
        }, params));
        return this.parseOrders (response, undefined, since, limit);
    }

    async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let response = await this.privateGetOrders (this.extend ({
            'status': 'Matched',
        }, params));
        return this.parseOrders (response, undefined, since, limit);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        let response = await this.publicGetOrderBooksAssetPairId (this.extend ({
            'AssetPairId': this.marketId (symbol),
        }, params));
        let orderbook = {
            'timestamp': undefined,
            'bids': [],
            'asks': [],
        };
        let timestamp = undefined;
        for (let i = 0; i < response.length; i++) {
            let side = response[i];
            if (side['IsBuy']) {
                orderbook['bids'] = this.arrayConcat (orderbook['bids'], side['Prices']);
            } else {
                orderbook['asks'] = this.arrayConcat (orderbook['asks'], side['Prices']);
            }
            let timestamp = this.parse8601 (side['Timestamp']);
            if (!orderbook['timestamp']) {
                orderbook['timestamp'] = timestamp;
            } else {
                orderbook['timestamp'] = Math.max (orderbook['timestamp'], timestamp);
            }
        }
        if (!timestamp)
            timestamp = this.milliseconds ();
        return this.parseOrderBook (orderbook, orderbook['timestamp'], 'bids', 'asks', 'Price', 'Volume');
    }

    parseBidAsk (bidask, priceKey = 0, amountKey = 1) {
        let price = parseFloat (bidask[priceKey]);
        let amount = parseFloat (bidask[amountKey]);
        if (amount < 0)
            amount = -amount;
        return [ price, amount ];
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api === 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else if (api === 'private') {
            if (method === 'GET')
                if (Object.keys (query).length)
                    url += '?' + this.urlencode (query);
            this.checkRequiredCredentials ();
            headers = {
                'api-key': this.apiKey,
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            };
            if (method === 'POST')
                if (Object.keys (params).length)
                    body = this.json (params);
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }
};
<|endoftext|>


<commit_before>import * as Actions from './actions';
import { combineReducers } from 'redux';
import R from 'ramda';

const nodeIds = (nodes) =>
  R.map(node => parseInt(node.id, 10))(R.values(nodes));

export const lastId = (nodes) => {
  const ids = nodeIds(nodes);
  // -1 is important because if nodes store doesn't contain nodes then we should return 0 as newId
  return R.reduce(R.max, -1, ids);
};

export const newId = (nodes) => lastId(nodes) + 1;

export const copyNode = (node) => R.clone(node);

const node = (state, action) => {
  switch (action.type) {
    case Actions.NODE_MOVE:
      return R.set(R.lensProp('position'), action.payload.position, state);
    case Actions.NODE_ADD:
      return R.view(R.lensProp('payload'), action);
    default:
      return state;
  }
};

export const nodes = (state, action) => {
  let movedNode = null;
  let newNode = null;
  let newNodeId = 0;

  switch (action.type) {

    case Actions.NODE_ADD:
      newNode = node(undefined, action);
      newNodeId = newId(state);
      newNode = R.set(R.lensProp('id'), newNodeId, newNode);
      return R.set(R.lensProp(newNodeId), newNode, state);

    case Actions.NODE_DELETE:
      return R.omit([action.payload.id.toString()], state);

    case Actions.NODE_MOVE:
      movedNode = node(R.view(R.lensProp(action.payload.id), state), action);
      return R.set(R.lensProp('id'), movedNode, state);

    default:
      return state;
  }
};

export const nodeApp = combineReducers({
  nodes,
});
<commit_msg>Auto stash for cherrypick of "feat(reducers) add empty reducers for each entity"<commit_after>import * as Actions from '../actions';
import { combineReducers } from 'redux';
import R from 'ramda';

const nodeIds = (nodes) =>
  R.map(node => parseInt(node.id, 10))(R.values(nodes));

export const lastId = (nodes) => {
  const ids = nodeIds(nodes);
  // -1 is important because if nodes store doesn't contain nodes then we should return 0 as newId
  return R.reduce(R.max, -1, ids);
};

export const newId = (nodes) => lastId(nodes) + 1;

export const copyNode = (node) => R.clone(node);

const node = (state, action) => {
  switch (action.type) {
    case Actions.NODE_MOVE:
      return R.set(R.lensProp('position'), action.payload.position, state);
    case Actions.NODE_ADD:
      return R.view(R.lensProp('payload'), action);
    default:
      return state;
  }
};

export const nodes = (state, action) => {
  let movedNode = null;
  let newNode = null;
  let newNodeId = 0;

  switch (action.type) {

    case Actions.NODE_ADD:
      newNode = node(undefined, action);
      newNodeId = newId(state);
      newNode = R.set(R.lensProp('id'), newNodeId, newNode);
      return R.set(R.lensProp(newNodeId), newNode, state);

    case Actions.NODE_DELETE:
      return R.omit([action.payload.id.toString()], state);

    case Actions.NODE_MOVE:
      movedNode = node(R.view(R.lensProp(action.payload.id), state), action);
      return R.set(R.lensProp('id'), movedNode, state);

    default:
      return state;
  }
};

export const nodeApp = combineReducers({
  nodes,
});
<|endoftext|>


<commit_before>'use strict';

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

/**
 * This module has "for debug" code.
 */

var ForDebug = {};

ForDebug.updateDisplay_ = function() {
  setTimeout(function() {
    if (timer1.numberOfTimingRecords()) {
      timer1.display_timing();
    }
    if (timer2.numberOfTimingRecords()) {
      timer2.display_timing();
    }
  }, 1);
};

/**
 * If timing data was collected display them on DOM ready.
 */
if (document.readyState == 'loading') {
  document.addEventListener("DOMContentLoaded", function(event) {
    ForDebug.updateDisplay_();
  });
} else {
  ForDebug.updateDisplay_();
}

ForDebug.getCookie = function(name, fallback) {
  name += '=';
  var cookies = document.cookie.split(';');
  for(var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    while (cookie.charAt(0)==' ') {
      cookie = cookie.substring(1);
    }
    if (cookie.indexOf(name) != -1) {
      return cookie.substring(name.length, cookie.length);
    }
  }
  return fallback;

};

ForDebug.Bandwidths = [
  { name: 'Full', value: '0' },
  { name: '10 Kbps', value: '10' },
  { name: '100 Kbps', value: '100' },
  { name: '250 Kbps', value: '250' },
  { name: 'Argentina - 1.0 Mbps', value: '1000' },
  { name: 'India - 1.3 Mbps', value: '1300' },
  { name: '3G mobile - 384 Kbps', value: '384' },
  { name: '3G stationary - 1.6 Mbps', value: '1600' },
  { name: 'China - 4.8 Mbps', value: '4800' },
  { name: 'Japan - 5.7 Mbps', value: '5700' },
  { name: 'South Korea - 14.7 Mbps', value: '14700' },
  { name: 'Taiwan - 3.4 Mbps', value: '3400' },
];

/**
 * Add a Bandwidth control.
 * @param {Object} incrFontMgr The incremental font manager.
 */
ForDebug.addBandwidthControl = function(incrFontMgr) {
  var label_innerHTML = "Akami mobile bandwidth " +
  "(2014 report pg 31): ";

  ForDebug.addDropDownCookieControl(ForDebug.Bandwidths, 100, 10,
    'lightYellow', label_innerHTML, 'bandwidth');
};

ForDebug.TimingTextSizes = [
  { name: 'Extra Large', value: '200%' },
  { name: 'Large', value: '150%' },
  { name: 'Regular', value: '100%' },
];

/**
 * Add a control to set the timing text size.
 * For the text to be readable on WebPageTest.org it needs to be quite large.
 * For other uses it can be a normal size
 * @param {Object} incrFontMgr The incremental font manager.
 */
ForDebug.addTimingTextSizeControl = function() {
  ForDebug.addDropDownCookieControl(ForDebug.TimingTextSizes, 140, 10,
    'lightYellow', "Timing Text Size", 'timing-text-size');
};

/**
 * Add a control to set the timing text size.
 * For the text to be readable on WebPageTest.org it needs to be quite large.
 * For other uses it can be a normal size
 * @param {Object} incrFontMgr The incremental font manager.
 */
ForDebug.addDropDownCookieControl = function(options, top, right, background_color, label_innerHTML, cookie_name) {
  if (document.readyState == 'loading') {
    document.addEventListener("DOMContentLoaded", function(event) {
      ForDebug.addDropDownCookieControl_(options, top, right, background_color, label_innerHTML, cookie_name);
    });
  } else {
    ForDebug.addDropDownCookieControl_(options, top, right, background_color, label_innerHTML, cookie_name);
  }
};

ForDebug.addDropDownCookieControl_ = function(options, top, right, background_color, label_innerHTML, cookie_name) {
  var span = document.createElement('span');
  span.style.position = 'absolute';
  span.style.top = top + 'px';
  span.style.right = right + 'px';
  span.style.backgroundColor = background_color;
  span.style.border = '1px solid gray';
  var label = document.createElement('span');
  label.innerHTML = label_innerHTML + ": ";
  span.appendChild(label);

  var cookie_value = ForDebug.getCookie(cookie_name, '0');
  var select = document.createElement("select");
  select.selectedIndex = 0;
  for (var i = 0; i < options.length; i++) {
    var option_info = options[i];
    var option = document.createElement("option");
    option.text = option_info.name;
    option.value = option_info.value;
    select.add(option);
    if (cookie_value == option_info.value) {
      select.selectedIndex = i;
    }
  }

  function setOptionChange(select) {
    var selectedOption = select.options[select.selectedIndex];
    document.cookie = cookie_name + '=' + selectedOption.value;
  }
  setOptionChange(select);

  select.onchange = function(event) {
    var select = event.currentTarget;
    setOptionChange(select);
  };

  span.appendChild(select);
  document.body.appendChild(span);
};

/**
 * Add a "drop DB" button.
 * @param {Object} incrFontMgr The incremental font manager.
 * @param {String} fontname The fontname.
 */
ForDebug.addDropIdbButton = function(incrFontMgr, fontname) {
  if (document.readyState == 'loading') {
    document.addEventListener("DOMContentLoaded", function(event) {
      ForDebug.addDropIdbButton_(incrFontMgr, fontname);
    });
  } else {
    ForDebug.addDropIdbButton_(incrFontMgr, fontname);
  }
};

/**
 * Add a "drop DB" button.
 * @param {Object} incrFontMgr The incremental font manager.
 * @param {String} fontname The fontname.
 */
ForDebug.addDropIdbButton_ = function(incrFontMgr, fontname) {
  var span = document.createElement('span');
  span.style.position = 'absolute';
  span.style.top = '10px';
  span.style.right = '10px';
  span.style.backgroundColor = 'white';
  span.style.border = '1px solid gray';
  var msg_span = document.createElement('span');
  msg_span.id = 'dropIdb_msg';
  span.appendChild(msg_span);
  var button = document.createElement('button');
  button.onclick = dropIdb;
  var label = document.createTextNode('drop DB');
  button.appendChild(label);
  span.appendChild(button);

  document.body.appendChild(span);

  function dropIdb() {
    var msg_span = document.getElementById('dropIdb_msg');
    ForDebug.dropIdb_(incrFontMgr, fontname, function(msg) {
      msg_span.innerHTML = msg;
    });
  }
};

/**
 * Drop the IndexedDB database.
 * @param {Object} incrFontMgr The incremental font manager.
 * @param {String} fontname The fontname.
 * @param {function} call Call this function with the status.
 * @return {Promise} The Promise for when the DB is dropped.
 * @private
 */
ForDebug.dropIdb_ = function(incrFontMgr, fontname, callback) {
  var db_name = IncrementalFont.DB_NAME + '/' + fontname;
  return incrFontMgr.getIDB_
  .then(function(db) {
    db.close();
    callback('dropping ' + db_name);
    var request = indexedDB.deleteDatabase(db_name);
    request.onsuccess = function(e) {
      callback('dropped ' + db_name);
    };
    request.onblocked = function() {
      callback('blocked dropping ' + db_name);
    };
    request.onerror = function(e) {
      debugger;
      callback('failed to drop ' + db_name + ': ' + e.code + '/' + e.message);
    };
  });
};

<commit_msg>minor tweak to speeds<commit_after>'use strict';

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

/**
 * This module has "for debug" code.
 */

var ForDebug = {};

ForDebug.updateDisplay_ = function() {
  setTimeout(function() {
    if (timer1.numberOfTimingRecords()) {
      timer1.display_timing();
    }
    if (timer2.numberOfTimingRecords()) {
      timer2.display_timing();
    }
  }, 1);
};

/**
 * If timing data was collected display them on DOM ready.
 */
if (document.readyState == 'loading') {
  document.addEventListener("DOMContentLoaded", function(event) {
    ForDebug.updateDisplay_();
  });
} else {
  ForDebug.updateDisplay_();
}

ForDebug.getCookie = function(name, fallback) {
  name += '=';
  var cookies = document.cookie.split(';');
  for(var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    while (cookie.charAt(0)==' ') {
      cookie = cookie.substring(1);
    }
    if (cookie.indexOf(name) != -1) {
      return cookie.substring(name.length, cookie.length);
    }
  }
  return fallback;

};

ForDebug.Bandwidths = [
  { name: 'Full', value: '0' },
  { name: '10 Kbps', value: '10' },
  { name: '100 Kbps', value: '100' },
  { name: '250 Kbps', value: '250' },
  { name: 'Argentina - 1.0 Mbps', value: '1000' },
  { name: 'India - 1.3 Mbps', value: '1300' },
  { name: '3G moving - 384 Kbps', value: '384' },
  { name: '3G stationary - 1.6 Mbps', value: '1600' },
  { name: 'China - 4.8 Mbps', value: '4800' },
  { name: 'Japan - 5.7 Mbps', value: '5700' },
  { name: 'South Korea - 14.7 Mbps', value: '14700' },
  { name: 'Taiwan - 3.4 Mbps', value: '3400' },
];

/**
 * Add a Bandwidth control.
 * @param {Object} incrFontMgr The incremental font manager.
 */
ForDebug.addBandwidthControl = function(incrFontMgr) {
  var label_innerHTML = "Akami mobile bandwidth " +
  "(2014 report pg 31): ";

  ForDebug.addDropDownCookieControl(ForDebug.Bandwidths, 100, 10,
    'lightYellow', label_innerHTML, 'bandwidth');
};

ForDebug.TimingTextSizes = [
  { name: 'Extra Large', value: '200%' },
  { name: 'Large', value: '150%' },
  { name: 'Regular', value: '100%' },
];

/**
 * Add a control to set the timing text size.
 * For the text to be readable on WebPageTest.org it needs to be quite large.
 * For other uses it can be a normal size
 * @param {Object} incrFontMgr The incremental font manager.
 */
ForDebug.addTimingTextSizeControl = function() {
  ForDebug.addDropDownCookieControl(ForDebug.TimingTextSizes, 140, 10,
    'lightYellow', "Timing Text Size", 'timing-text-size');
};

/**
 * Add a control to set the timing text size.
 * For the text to be readable on WebPageTest.org it needs to be quite large.
 * For other uses it can be a normal size
 * @param {Object} incrFontMgr The incremental font manager.
 */
ForDebug.addDropDownCookieControl = function(options, top, right, background_color, label_innerHTML, cookie_name) {
  if (document.readyState == 'loading') {
    document.addEventListener("DOMContentLoaded", function(event) {
      ForDebug.addDropDownCookieControl_(options, top, right, background_color, label_innerHTML, cookie_name);
    });
  } else {
    ForDebug.addDropDownCookieControl_(options, top, right, background_color, label_innerHTML, cookie_name);
  }
};

ForDebug.addDropDownCookieControl_ = function(options, top, right, background_color, label_innerHTML, cookie_name) {
  var span = document.createElement('span');
  span.style.position = 'absolute';
  span.style.top = top + 'px';
  span.style.right = right + 'px';
  span.style.backgroundColor = background_color;
  span.style.border = '1px solid gray';
  var label = document.createElement('span');
  label.innerHTML = label_innerHTML + ": ";
  span.appendChild(label);

  var cookie_value = ForDebug.getCookie(cookie_name, '0');
  var select = document.createElement("select");
  select.selectedIndex = 0;
  for (var i = 0; i < options.length; i++) {
    var option_info = options[i];
    var option = document.createElement("option");
    option.text = option_info.name;
    option.value = option_info.value;
    select.add(option);
    if (cookie_value == option_info.value) {
      select.selectedIndex = i;
    }
  }

  function setOptionChange(select) {
    var selectedOption = select.options[select.selectedIndex];
    document.cookie = cookie_name + '=' + selectedOption.value;
  }
  setOptionChange(select);

  select.onchange = function(event) {
    var select = event.currentTarget;
    setOptionChange(select);
  };

  span.appendChild(select);
  document.body.appendChild(span);
};

/**
 * Add a "drop DB" button.
 * @param {Object} incrFontMgr The incremental font manager.
 * @param {String} fontname The fontname.
 */
ForDebug.addDropIdbButton = function(incrFontMgr, fontname) {
  if (document.readyState == 'loading') {
    document.addEventListener("DOMContentLoaded", function(event) {
      ForDebug.addDropIdbButton_(incrFontMgr, fontname);
    });
  } else {
    ForDebug.addDropIdbButton_(incrFontMgr, fontname);
  }
};

/**
 * Add a "drop DB" button.
 * @param {Object} incrFontMgr The incremental font manager.
 * @param {String} fontname The fontname.
 */
ForDebug.addDropIdbButton_ = function(incrFontMgr, fontname) {
  var span = document.createElement('span');
  span.style.position = 'absolute';
  span.style.top = '10px';
  span.style.right = '10px';
  span.style.backgroundColor = 'white';
  span.style.border = '1px solid gray';
  var msg_span = document.createElement('span');
  msg_span.id = 'dropIdb_msg';
  span.appendChild(msg_span);
  var button = document.createElement('button');
  button.onclick = dropIdb;
  var label = document.createTextNode('drop DB');
  button.appendChild(label);
  span.appendChild(button);

  document.body.appendChild(span);

  function dropIdb() {
    var msg_span = document.getElementById('dropIdb_msg');
    ForDebug.dropIdb_(incrFontMgr, fontname, function(msg) {
      msg_span.innerHTML = msg;
    });
  }
};

/**
 * Drop the IndexedDB database.
 * @param {Object} incrFontMgr The incremental font manager.
 * @param {String} fontname The fontname.
 * @param {function} call Call this function with the status.
 * @return {Promise} The Promise for when the DB is dropped.
 * @private
 */
ForDebug.dropIdb_ = function(incrFontMgr, fontname, callback) {
  var db_name = IncrementalFont.DB_NAME + '/' + fontname;
  return incrFontMgr.getIDB_
  .then(function(db) {
    db.close();
    callback('dropping ' + db_name);
    var request = indexedDB.deleteDatabase(db_name);
    request.onsuccess = function(e) {
      callback('dropped ' + db_name);
    };
    request.onblocked = function() {
      callback('blocked dropping ' + db_name);
    };
    request.onerror = function(e) {
      debugger;
      callback('failed to drop ' + db_name + ': ' + e.code + '/' + e.message);
    };
  });
};

<|endoftext|>


<commit_before>pipe.once('dependencies::initialise', function init(pagelet) {
  'use strict';

  //
  // We don't need to have any other information from the pagelet then the
  // placeholders/elements that contain our packages-pagelet placeholders.
  //
  pagelet = $(pagelet.placeholders);

  //
  // Show more rows when we click on the table footer.
  //
  pagelet.on('click', 'tfoot.more a', function click(e) {
    e.preventDefault();

    var button = $(this);

    button.parents('table').find('tr.gone').fadeIn();
    button.parents('tfoot').fadeOut();
  });
});
<commit_msg>[migrate] Migrate to bigpipe 0.6<commit_after>pipe.once('dependencies:initialize', function init(pagelet) {
  'use strict';

  //
  // We don't need to have any other information from the pagelet then the
  // placeholders/elements that contain our packages-pagelet placeholders.
  //
  pagelet = $(pagelet.placeholders);

  //
  // Show more rows when we click on the table footer.
  //
  pagelet.on('click', 'tfoot.more a', function click(e) {
    e.preventDefault();

    var button = $(this);

    button.parents('table').find('tr.gone').fadeIn();
    button.parents('tfoot').fadeOut();
  });
});
<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var BaseObject = require('./base/base_object')
var CoreFactory = require('./components/core_factory')
var Loader = require('./components/loader')
var Mediator = require('./components/mediator')

class Player extends BaseObject {
  initialize(params) {
    window.p = this
    params.displayType || (params.displayType = 'pip')
    this.params = params
    this.loader = new Loader(this.params)
    this.coreFactory = new CoreFactory(this, this.loader)
    params.height || (params.height = 480);
    params.width || (params.width = 720);
  }

  attachTo(element) {
    this.params.parentElement = element
    this.core = this.coreFactory.create()
  }

  load(sources) {
    this.core.load(sources)
  }

  destroy() {
    this.core.destroy()
  }

  play() {
    this.core.mediaControl.container.play();
  }

  pause() {
    this.core.mediaControl.container.pause();
  }

  stop() {
    this.core.mediaControl.container.stop();
  }

  seek(time) {
    this.core.mediaControl.container.setCurrentTime(time);
  }

  setVolume(volume) {
    this.core.mediaControl.container.volume(volume);
  }

  mute() {
    this.core.mediaControl.container.volume(0);
  }

  unmute() {
    this.core.mediaControl.container.volume(100);
  }

  isPlaying() {
    return this.core.mediaControl.container.isPlaying();
  }
}

global.DEBUG = false

window.WP3 = { Player: Player, Mediator: Mediator }

module.exports = window.WP3
<commit_msg>s/WP3/Clappr/g closes #127<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var BaseObject = require('./base/base_object')
var CoreFactory = require('./components/core_factory')
var Loader = require('./components/loader')
var Mediator = require('./components/mediator')

class Player extends BaseObject {
  initialize(params) {
    window.p = this
    params.displayType || (params.displayType = 'pip')
    this.params = params
    this.loader = new Loader(this.params)
    this.coreFactory = new CoreFactory(this, this.loader)
    params.height || (params.height = 480);
    params.width || (params.width = 720);
  }

  attachTo(element) {
    this.params.parentElement = element
    this.core = this.coreFactory.create()
  }

  load(sources) {
    this.core.load(sources)
  }

  destroy() {
    this.core.destroy()
  }

  play() {
    this.core.mediaControl.container.play();
  }

  pause() {
    this.core.mediaControl.container.pause();
  }

  stop() {
    this.core.mediaControl.container.stop();
  }

  seek(time) {
    this.core.mediaControl.container.setCurrentTime(time);
  }

  setVolume(volume) {
    this.core.mediaControl.container.volume(volume);
  }

  mute() {
    this.core.mediaControl.container.volume(0);
  }

  unmute() {
    this.core.mediaControl.container.volume(100);
  }

  isPlaying() {
    return this.core.mediaControl.container.isPlaying();
  }
}

global.DEBUG = false

window.Clappr = { Player: Player, Mediator: Mediator }

module.exports = window.Clappr
<|endoftext|>


<commit_before>/* eslint-env mocha */

'use strict';

const assert = require('chai').assert;
const path = require('path');
const CrudController = require('../../controllers/Crud');

new CrudController({ //eslint-disable-line
    viewRoot: 'views/some/path',
    urlRoot: '/mount/point',
    humanName: 'Nothing here, move along',
    model: {}
});

describe('CrudController', () => {
    describe('constructor', () => {
        it('throws error if model is not passed', () => {
            function controllerFactory (model) {
                return new CrudController({
                    viewRoot: 'views/some/path',
                    urlRoot: '/mount/point',
                    humanName: 'Nothing here, move along',
                    model: model
                });
            }

            assert.throws(
                controllerFactory.bind(null, false),
                /Model not provided/,
                'correct error thrown'
            );

            assert.doesNotThrow(
                controllerFactory.bind(null, {}),
                'no errors thrown when model is present'
            );
        });
    });

    describe('parseForm', () => {
        it('calls callback', (done) => {
            CrudController.prototype.parseForm({some: 'data'}, (error, data) => {
                assert.isNull(error, 'error is null by default');
                assert.deepEqual(data, {some: 'data'});
                done();
            });
        });
    });

    describe('_getId', () => {
        it('gets id from various sources', () => {
            const req1 = {params: {id: 1234}, query: {}};
            const req2 = {params: {}, query: {id: 4321}};
            const req3 = {params: {id: 1234}, query: {id: 4321}};

            assert.equal(CrudController.prototype._getId(req1), 1234, 'from params');
            assert.equal(CrudController.prototype._getId(req2), 4321, 'from query');
            assert.equal(CrudController.prototype._getId(req3), 1234, 'from params first');
        });
    });

    describe('_renderItem', () => {
        it('calls res.render with correct params', (done) => {
            const controller = new CrudController({
                viewRoot: 'views/some/path',
                urlRoot: '/mount/point',
                humanName: 'Nothing here, move along',
                model: {}
            });

            const res = {
                render (viewPath, data) {
                    assert.equal(viewPath, path.normalize('views/some/path/item'));
                    assert.deepEqual(data, {some: 'item'});
                    done();
                }
            };

            controller._renderItem(res, {some: 'item'});
        });
    });

    describe('_renderList', () => {
        it('calls res.render with correct params', (done) => {
            const controller = new CrudController({
                viewRoot: 'views/some/path',
                urlRoot: '/mount/point',
                humanName: 'Nothing here, move along',
                model: {}
            });

            const res = {
                render (viewPath, data) {
                    assert.equal(viewPath, path.normalize('views/some/path/list'));
                    assert.deepEqual(data, {list: ['some', 'list']}, 'data correctly wrapped to object');
                    done();
                }
            };

            controller._renderList(res, ['some', 'list']);
        });
    });
});<commit_msg>Crud#_error tests<commit_after>/* eslint-env mocha */

'use strict';

const assert = require('chai').assert;
const path = require('path');
const CrudController = require('../../controllers/Crud');

new CrudController({ //eslint-disable-line
    viewRoot: 'views/some/path',
    urlRoot: '/mount/point',
    humanName: 'Nothing here, move along',
    model: {}
});

describe('CrudController', () => {
    describe('constructor', () => {
        it('throws error if model is not passed', () => {
            function controllerFactory (model) {
                return new CrudController({
                    viewRoot: 'views/some/path',
                    urlRoot: '/mount/point',
                    humanName: 'Nothing here, move along',
                    model: model
                });
            }

            assert.throws(
                controllerFactory.bind(null, false),
                /Model not provided/,
                'correct error thrown'
            );

            assert.doesNotThrow(
                controllerFactory.bind(null, {}),
                'no errors thrown when model is present'
            );
        });
    });

    describe('parseForm', () => {
        it('calls callback', (done) => {
            CrudController.prototype.parseForm({some: 'data'}, (error, data) => {
                assert.isNull(error, 'error is null by default');
                assert.deepEqual(data, {some: 'data'});
                done();
            });
        });
    });

    describe('_getId', () => {
        it('gets id from various sources', () => {
            const req1 = {params: {id: 1234}, query: {}};
            const req2 = {params: {}, query: {id: 4321}};
            const req3 = {params: {id: 1234}, query: {id: 4321}};

            assert.equal(CrudController.prototype._getId(req1), 1234, 'from params');
            assert.equal(CrudController.prototype._getId(req2), 4321, 'from query');
            assert.equal(CrudController.prototype._getId(req3), 1234, 'from params first');
        });
    });

    describe('_renderItem', () => {
        it('calls res.render with correct params', (done) => {
            const controller = new CrudController({
                viewRoot: 'views/some/path',
                urlRoot: '/mount/point',
                humanName: 'Nothing here, move along',
                model: {}
            });

            const res = {
                render (viewPath, data) {
                    assert.equal(viewPath, path.normalize('views/some/path/item'));
                    assert.deepEqual(data, {some: 'item'});
                    done();
                }
            };

            controller._renderItem(res, {some: 'item'});
        });
    });

    describe('_renderList', () => {
        it('calls res.render with correct params', (done) => {
            const controller = new CrudController({
                viewRoot: 'views/some/path',
                urlRoot: '/mount/point',
                humanName: 'Nothing here, move along',
                model: {}
            });

            const res = {
                render (viewPath, data) {
                    assert.equal(viewPath, path.normalize('views/some/path/list'));
                    assert.deepEqual(data, {list: ['some', 'list']}, 'data correctly wrapped to object');
                    done();
                }
            };

            controller._renderList(res, ['some', 'list']);
        });
    });

    describe('_error', () => {
        const res = {
            status (statusCode) {
                this.statusCode = statusCode;
                return this;
            },

            send (body) {
                this.body = body;
            }
        };

        const error = CrudController.prototype._error;

        beforeEach(() => {
            res.body = null;
            res.statusCode = null;
        });

        it('calls correct methods of res', () => {
            error(res, {answer: 42}, 555);
            assert.equal(res.statusCode, 555);
            assert.deepEqual(res.body, {answer: 42});
        });

        it('defaults to 500 status code', function () {
            error(res, {answer: 42});
            assert.equal(res.statusCode, 500);
            assert.deepEqual(res.body, {answer: 42});
        })
    });
});<|endoftext|>


<commit_before>module.exports = {
  pageTitle: ' Your application has been submitted.',
  secondTitle: 'What happens next',
  nextStep1: "Important: Keep your reference number – write it down, or print this page for your records",
  nextStep2: "Allow 21 business days for your application to be processed",
  nextStep3: "Once your application is processed, you will get a letter that says whether you’re eligibile for MSP. You may have a wait period",
  nextStep4: "Once you receive your first bill, you can get your BC Services Card. Visit ICBC  or Service BC to get one",
  nextStep5: "When you get your BC Services Card, register for the FairPharmacare plan. It can help with the cost of prescription drugs and some medical supplies. Registration is free and there are no premiums to pay",
  nextStep6: "Low income individuals or families who are Canadian or permanent residents qualify for help to pay the monthly fee. Find out about premium assistance</a",
  nextStep7: "Keep your personal information up to date. Change your name, address or gender",
  nextStep8: "Living outside the province for more than six months could cause your MSP enrollment to be cancelled. Learn more about eligibility for MSP",
  nextStep9: "If you have questions, contact Health Insurance BC"
}
<commit_msg>correct typo<commit_after>module.exports = {
  pageTitle: ' Your application has been submitted.',
  secondTitle: 'What happens next',
  nextStep1: "Important: Keep your reference number – write it down, or print this page for your records",
  nextStep2: "Allow 21 business days for your application to be processed",
  nextStep3: "Once your application is processed, you will get a letter that says whether you’re eligible for MSP. You may have a wait period",
  nextStep4: "Once you receive your first bill, you can get your BC Services Card. Visit ICBC  or Service BC to get one",
  nextStep5: "When you get your BC Services Card, register for the FairPharmacare plan. It can help with the cost of prescription drugs and some medical supplies. Registration is free and there are no premiums to pay",
  nextStep6: "Low income individuals or families who are Canadian or permanent residents qualify for help to pay the monthly fee. Find out about premium assistance</a",
  nextStep7: "Keep your personal information up to date. Change your name, address or gender",
  nextStep8: "Living outside the province for more than six months could cause your MSP enrollment to be cancelled. Learn more about eligibility for MSP",
  nextStep9: "If you have questions, contact Health Insurance BC"
}
<|endoftext|>


<commit_before>'use strict';

viewModel.MonitoringNotification = new Object();
var mn = viewModel.MonitoringNotification;
mn.minDatetemp = new Date();
mn.maxDatetemp = new Date();

mn.minDateRet = new Date();
mn.maxDateRet = new Date();

vm.currentMenu('Notification');
vm.currentTitle('Notification');
vm.isShowDataAvailability(false);
vm.breadcrumb([
    { title: "Monitoring", href: '#' },
    { title: 'Notification', href: viewModel.appName + 'page/monitoringnotification' }]);

var intervalTurbine = null;

mn.typeList = ko.observableArray([]);
mn.typeListData = ko.observableArray([]);

mn.UpdateProjectList = function(project) {
    setTimeout(function(){
        $('#projectList').data('kendoDropDownList').value(project);
        $("#projectList").data("kendoDropDownList").trigger("change");
    },1000)
}
mn.UpdateTurbineList = function(turbineList) {
    if(turbineList.length == 0){
         $("#turbineList").multiselect('selectAll', false).multiselect("refresh");
    }else{
        $('#turbineList').multiselect("deselectAll", false).multiselect("refresh");
        $('#turbineList').multiselect('select', turbineList);
    }

}
mn.LoadData = function() {
    app.loading(true);

    $.when(fa.LoadData()).done(function () {
        var project = fa.project
        if(project == "") {
            project = "Tejuva";
        }
        mn.typeList(mn.typeListData()[project]);
        var colnameType = $('#typeList').data('kendoDropDownList').value();

        var param = {
            period: fa.period,
            dateStart: fa.dateStart,
            dateEnd: fa.dateEnd,
            turbine: fa.turbine(),
            project: fa.project,
            tipe: colnameType,
        };

        mn.LoadDataAvail(param.project, "alarm");
        mn.generateGrid(param);
    });
}

mn.generateGrid = function(param){
    var nameFile = "Monitoring Notification_"+ moment(new Date()).format("Y-M-D")+"_"+time;

    $("#notificationGrid").html('');
    $("#notificationGrid").kendoGrid({
        dataSource: {
            serverPaging: true,
            serverSorting: true,
            transport: {
                read: {
                    url: viewModel.appName + "monitoringrealtime/getdatanotification",
                    type: "POST",
                    data: param,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                },
                parameterMap: function(options) {
                    return JSON.stringify(options);
                }
            },
            schema: {
                data: function data(res) {
                    if (!app.isFine(res)) {
                        return;
                    }
                    var totalFreq = res.data.Total;
                    var totalHour = res.data.Duration;

                    mn.minDateRet = new Date(res.data.mindate);
                    mn.maxDateRet = new Date(res.data.maxdate);

                    mn.checkCompleteDate()

                    setTimeout(function(){
                        app.loading(false);
                    }, 300)

                    return res.data.Data;
                },
                total: function data(res) {
                    return res.data.Total;
                }
            },
            pageSize: 10,
            sort: [ { field: "TimeStart", dir: "desc" }, { field: "TimeEnd", dir: "asc" } ],
        },
        sortable: true,
        // toolbar: ["excel"],
        excel: {
            fileName: nameFile+".xlsx",
            filterable: true,
            allPages: true
        },
        pageable: {
            refresh: true,
            pageSizes: true,
            buttonCount: 5
        },
        columns: [{
            field: "turbine",
            title: "Turbine",
            attributes: {
                style: "text-align:center;"
            },
            width: 90
        }, {
            field: "timestart",
            title: "Time Start",
            width: 130,
            attributes: {
                style: "text-align:center;"
            },
            template: "#= moment.utc(data.timestart).format('DD-MMM-YYYY') #       #=moment.utc(data.timestart).format('HH:mm:ss')#"
        }, {
            field: "timeend",
            title: "Time End",
            width: 130,
            attributes: {
                style: "text-align:center;"
            },
            template: "#= (moment.utc(data.timeend).format('DD-MM-YYYY') == '01-01-0001'?'Not yet finished' : (moment.utc(data.timeend).format('DD-MMM-YYYY') #       #=moment.utc(data.timeend).format('HH:mm:ss')))#"
        }, {
            field: "duration",
            title: "Duration (hh:mm:ss)",
             width: 120,
             attributes: {
                style: "text-align:center;"
            },
            template: "#= time(data.duration) #"
        }, {
            field: "startcond",
            title: "Start Value",
            attributes: {
                style: "text-align:center;"
            },
            width: 130,
        }, {
            field: "endcond",
            title: "End Value",
            attributes: {
                style: "text-align:center;"
            },
            width: 130,
        },{
            field: "description",
            title: "Description",
            width: 190,
            attributes: {
                style: "text-align:center;"
            },
        }]
    });

}

function time(s) {
    return new Date(s * 1e3).toISOString().slice(-13, -5);
}

mn.InitDateValue = function () {
    var maxDateData = new Date();

    var lastStartDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
    var lastEndDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));

    $('#dateStart').data('kendoDatePicker').value(lastStartDate);
    $('#dateEnd').data('kendoDatePicker').value(lastEndDate);
}

mn.LoadDataAvail = function(projectname, gridType){
    //fa.LoadData();
    var payload = {
        project: projectname,
        tipe: gridType
    };

    toolkit.ajaxPost(viewModel.appName + "monitoringrealtime/getdataalarmavaildate", payload, function (res) {
        if (!app.isFine(res)) {
            return;
        }
        if (res.data.Data.length == 0) {
            res.data.Data = [];
        } else {
            if (res.data.Data.length > 0) {
                mn.minDatetemp = new Date(res.data.Data[0]);
                mn.maxDatetemp = new Date(res.data.Data[1]);
                app.currentDateData = new Date(res.data.Data[1]);

                $('#availabledatestart').html(kendo.toString(moment.utc(mn.minDatetemp).format('DD-MMMM-YYYY')));
                $('#availabledateend').html(kendo.toString(moment.utc(mn.maxDatetemp).format('DD-MMMM-YYYY')));

                mn.checkCompleteDate()
            }
        }
    });
}

mn.exportToExcel = function(){
    $("#notificationGrid").getKendoGrid().saveAsExcel();
}

mn.checkCompleteDate = function () {
    var currentDateData = moment.utc(mn.maxDatetemp).format('YYYY-MM-DD');
    var prevDateData = moment.utc(mn.minDatetemp).format('YYYY-MM-DD');

    var dateStart = moment.utc(mn.minDateRet).format('YYYY-MM-DD');
    var dateEnd = moment.utc(mn.maxDateRet).format('YYYY-MM-DD');

    if ((dateEnd > currentDateData) || (dateStart > currentDateData)) {
        fa.infoPeriodIcon(true);
    } else if ((dateEnd < prevDateData) || (dateStart < prevDateData)) {
        fa.infoPeriodIcon(true);
    } else {
        fa.infoPeriodIcon(false);
        fa.infoPeriodRange("");
    }
}

// mn.ToByProject = function(){
//     setTimeout(function(){
//         app.loading(true);
//         app.resetLocalStorage();
//         var project =  $('#projectList').data('kendoDropDownList').value();
//         localStorage.setItem('projectname', project);
//         if(localStorage.getItem("projectname")){
//             window.location = viewModel.appName + "page/monitoringbyproject";
//         }
//     },1500);
// }

$(document).ready(function(){
    $('#btnRefresh').on('click', function () {
        fa.checkTurbine();
        mn.LoadData();
    });

    $.when(mn.InitDateValue()).done(function () {
        setTimeout(function() {
            mn.LoadData();
        }, 100);
    });

    setTimeout(function () {
        $("#typeList").data("kendoDropDownList").value("alltypes");
    }, 300);

    $('#projectList').kendoDropDownList({
        change: function () {
            var project = $('#projectList').data("kendoDropDownList").value();
            fa.populateTurbine(project);
            mn.typeList(mn.typeListData()[project]);
            $("#typeList").data("kendoDropDownList").value("alltypes");
        }
    });

    $('#typeList').on("change", function() {
        fa.checkTurbine();
        setTimeout(function() {
            mn.LoadData();
        }, 300);
    });
});
<commit_msg>modify space in notification<commit_after>'use strict';

viewModel.MonitoringNotification = new Object();
var mn = viewModel.MonitoringNotification;
mn.minDatetemp = new Date();
mn.maxDatetemp = new Date();

mn.minDateRet = new Date();
mn.maxDateRet = new Date();

vm.currentMenu('Notification');
vm.currentTitle('Notification');
vm.isShowDataAvailability(false);
vm.breadcrumb([
    { title: "Monitoring", href: '#' },
    { title: 'Notification', href: viewModel.appName + 'page/monitoringnotification' }]);

var intervalTurbine = null;

mn.typeList = ko.observableArray([]);
mn.typeListData = ko.observableArray([]);

mn.UpdateProjectList = function(project) {
    setTimeout(function(){
        $('#projectList').data('kendoDropDownList').value(project);
        $("#projectList").data("kendoDropDownList").trigger("change");
    },1000)
}
mn.UpdateTurbineList = function(turbineList) {
    if(turbineList.length == 0){
         $("#turbineList").multiselect('selectAll', false).multiselect("refresh");
    }else{
        $('#turbineList').multiselect("deselectAll", false).multiselect("refresh");
        $('#turbineList').multiselect('select', turbineList);
    }

}
mn.LoadData = function() {
    app.loading(true);

    $.when(fa.LoadData()).done(function () {
        var project = fa.project
        if(project == "") {
            project = "Tejuva";
        }
        mn.typeList(mn.typeListData()[project]);
        var colnameType = $('#typeList').data('kendoDropDownList').value();

        var param = {
            period: fa.period,
            dateStart: fa.dateStart,
            dateEnd: fa.dateEnd,
            turbine: fa.turbine(),
            project: fa.project,
            tipe: colnameType,
        };

        mn.LoadDataAvail(param.project, "alarm");
        mn.generateGrid(param);
    });
}

mn.generateGrid = function(param){
    var nameFile = "Monitoring Notification_"+ moment(new Date()).format("Y-M-D")+"_"+time;

    $("#notificationGrid").html('');
    $("#notificationGrid").kendoGrid({
        dataSource: {
            serverPaging: true,
            serverSorting: true,
            transport: {
                read: {
                    url: viewModel.appName + "monitoringrealtime/getdatanotification",
                    type: "POST",
                    data: param,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                },
                parameterMap: function(options) {
                    return JSON.stringify(options);
                }
            },
            schema: {
                data: function data(res) {
                    if (!app.isFine(res)) {
                        return;
                    }
                    var totalFreq = res.data.Total;
                    var totalHour = res.data.Duration;

                    mn.minDateRet = new Date(res.data.mindate);
                    mn.maxDateRet = new Date(res.data.maxdate);

                    mn.checkCompleteDate()

                    setTimeout(function(){
                        app.loading(false);
                    }, 300)

                    return res.data.Data;
                },
                total: function data(res) {
                    return res.data.Total;
                }
            },
            pageSize: 10,
            sort: [ { field: "TimeStart", dir: "desc" }, { field: "TimeEnd", dir: "asc" } ],
        },
        sortable: true,
        // toolbar: ["excel"],
        excel: {
            fileName: nameFile+".xlsx",
            filterable: true,
            allPages: true
        },
        pageable: {
            refresh: true,
            pageSizes: true,
            buttonCount: 5
        },
        columns: [{
            field: "turbine",
            title: "Turbine",
            attributes: {
                style: "text-align:center;"
            },
            width: 90
        }, {
            field: "timestart",
            title: "Time Start",
            width: 120,
            attributes: {
                style: "text-align:center;"
            },
            template: "#= moment.utc(data.timestart).format('DD-MMM-YYYY') #       #=moment.utc(data.timestart).format('HH:mm:ss')#"
        }, {
            field: "timeend",
            title: "Time End",
            width: 120,
            attributes: {
                style: "text-align:center;"
            },
            template: "#= (moment.utc(data.timeend).format('DD-MM-YYYY') == '01-01-0001'?'Not yet finished' : (moment.utc(data.timeend).format('DD-MMM-YYYY') #       #=moment.utc(data.timeend).format('HH:mm:ss')))#"
        }, {
            field: "duration",
            title: "Duration (hh:mm:ss)",
             width: 100,
             attributes: {
                style: "text-align:center;"
            },
            template: "#= time(data.duration) #"
        }, {
            field: "startcond",
            title: "Start Value",
            attributes: {
                style: "text-align:center;"
            },
            width: 160,
        }, {
            field: "endcond",
            title: "End Value",
            attributes: {
                style: "text-align:center;"
            },
            width: 160,
        },{
            field: "description",
            title: "Description",
            width: 170,
            attributes: {
                style: "text-align:center;"
            },
        }]
    });

}

function time(s) {
    return new Date(s * 1e3).toISOString().slice(-13, -5);
}

mn.InitDateValue = function () {
    var maxDateData = new Date();

    var lastStartDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));
    var lastEndDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0));

    $('#dateStart').data('kendoDatePicker').value(lastStartDate);
    $('#dateEnd').data('kendoDatePicker').value(lastEndDate);
}

mn.LoadDataAvail = function(projectname, gridType){
    //fa.LoadData();
    var payload = {
        project: projectname,
        tipe: gridType
    };

    toolkit.ajaxPost(viewModel.appName + "monitoringrealtime/getdataalarmavaildate", payload, function (res) {
        if (!app.isFine(res)) {
            return;
        }
        if (res.data.Data.length == 0) {
            res.data.Data = [];
        } else {
            if (res.data.Data.length > 0) {
                mn.minDatetemp = new Date(res.data.Data[0]);
                mn.maxDatetemp = new Date(res.data.Data[1]);
                app.currentDateData = new Date(res.data.Data[1]);

                $('#availabledatestart').html(kendo.toString(moment.utc(mn.minDatetemp).format('DD-MMMM-YYYY')));
                $('#availabledateend').html(kendo.toString(moment.utc(mn.maxDatetemp).format('DD-MMMM-YYYY')));

                mn.checkCompleteDate()
            }
        }
    });
}

mn.exportToExcel = function(){
    $("#notificationGrid").getKendoGrid().saveAsExcel();
}

mn.checkCompleteDate = function () {
    var currentDateData = moment.utc(mn.maxDatetemp).format('YYYY-MM-DD');
    var prevDateData = moment.utc(mn.minDatetemp).format('YYYY-MM-DD');

    var dateStart = moment.utc(mn.minDateRet).format('YYYY-MM-DD');
    var dateEnd = moment.utc(mn.maxDateRet).format('YYYY-MM-DD');

    if ((dateEnd > currentDateData) || (dateStart > currentDateData)) {
        fa.infoPeriodIcon(true);
    } else if ((dateEnd < prevDateData) || (dateStart < prevDateData)) {
        fa.infoPeriodIcon(true);
    } else {
        fa.infoPeriodIcon(false);
        fa.infoPeriodRange("");
    }
}

// mn.ToByProject = function(){
//     setTimeout(function(){
//         app.loading(true);
//         app.resetLocalStorage();
//         var project =  $('#projectList').data('kendoDropDownList').value();
//         localStorage.setItem('projectname', project);
//         if(localStorage.getItem("projectname")){
//             window.location = viewModel.appName + "page/monitoringbyproject";
//         }
//     },1500);
// }

$(document).ready(function(){
    $('#btnRefresh').on('click', function () {
        fa.checkTurbine();
        mn.LoadData();
    });

    $.when(mn.InitDateValue()).done(function () {
        setTimeout(function() {
            mn.LoadData();
        }, 100);
    });

    setTimeout(function () {
        $("#typeList").data("kendoDropDownList").value("alltypes");
    }, 300);

    $('#projectList').kendoDropDownList({
        change: function () {
            var project = $('#projectList').data("kendoDropDownList").value();
            fa.populateTurbine(project);
            mn.typeList(mn.typeListData()[project]);
            $("#typeList").data("kendoDropDownList").value("alltypes");
        }
    });

    $('#typeList').on("change", function() {
        fa.checkTurbine();
        setTimeout(function() {
            mn.LoadData();
        }, 300);
    });
});
<|endoftext|>


<commit_before>const { relative } = require('path')

module.exports = ReactUniversalServerLoader

function ReactUniversalServerLoader(source, map) {
  const filename = relative(this.options.context, this.resourcePath)
  const importPath = relative(this.context, this.resourcePath)
  const id = filename.replace(/[/\.]/g, '_')
  return createServerCode({ importPath, scriptSrc: '/' + filename, id })
}

function createServerCode({ importPath, scriptSrc, id }) {
  return `|import Component from './${importPath}'
          |import { renderToString } from 'react-dom/server'
          |
          |export default function WrapWithScript(props) {
          |  const content = renderToString(<Component id='${id}' {...props} />)
          |  return (
          |

          |

          |
          |

          |  )
          |}
          |`.split(/^[ \t]*\|/m).join('')
}
<commit_msg>Add `defer` tag to universal script tags, fixes #13<commit_after>const { relative } = require('path')

module.exports = ReactUniversalServerLoader

function ReactUniversalServerLoader(source, map) {
  const filename = relative(this.options.context, this.resourcePath)
  const importPath = relative(this.context, this.resourcePath)
  const id = filename.replace(/[/\.]/g, '_')
  return createServerCode({ importPath, scriptSrc: '/' + filename, id })
}

function createServerCode({ importPath, scriptSrc, id }) {
  return `|import Component from './${importPath}'
          |import { renderToString } from 'react-dom/server'
          |
          |export default function WrapWithScript(props) {
          |  const content = renderToString(<Component id='${id}' {...props} />)
          |  return (
          |

          |

          |
          |

          |  )
          |}
          |`.split(/^[ \t]*\|/m).join('')
}
<|endoftext|>


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

// call docCount servlet for no of documents in a index
const getCount = async (index, fileType) => {
    const params = new URLSearchParams();
    params.append(FILE_NAME, index);
    params.append(FILE_TYPE, fileType);
    const response = await fetch(GET_COUNT, {
        method: POST,
        body: params
    });
    const count = await response.json();
    return count;
}

// call stackTrace servlet for stack trace of a error
const callStackTraceServlet = async (logLineNo, fileName) => {
    const params = new URLSearchParams();
    params.append(LOG_LINE_NUMBER, logLineNo);
    params.append(FILE_NAME, fileName);
    const response = await fetch(STACK_TRACE, {
        method: POST,
        body: params
    });
    const stackTrace = await response.json();
    return stackTrace;
}

// fetch logs/errors/search results from pagination servlet
const callPaginationServlet = async(fileName, fileType, searchString, pageSpecs) => {
    const params = new URLSearchParams();
    params.append(START, pageSpecs.START);
    params.append(SIZE,  pageSpecs.SIZE);
    params.append(SEARCH_STRING, searchString);
    params.append(FILE_TYPE, fileType);
    params.append(FILE_NAME, fileName);
    const response = await fetch(PAGINATION, {
        method: POST,
        body: params
    });
    const fetchedData = await response.json();
    return fetchedData;
}

// delete all the
const deleteIndices = async() => {
    await fetch(DELETE, {
        method: POST
});

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

// call docCount servlet for no of documents in a index
const getCount = async (index, fileType) => {
    const params = new URLSearchParams();
    params.append(FILE_NAME, index);
    params.append(FILE_TYPE, fileType);
    const response = await fetch(GET_COUNT, {
        method: POST,
        body: params
    });
    const count = await response.json();
    return count;
}

// call stackTrace servlet for stack trace of a error
const callStackTraceServlet = async (logLineNo, fileName) => {
    const params = new URLSearchParams();
    params.append(LOG_LINE_NUMBER, logLineNo);
    params.append(FILE_NAME, fileName);
    const response = await fetch(STACK_TRACE, {
        method: POST,
        body: params
    });
    const stackTrace = await response.json();
    return stackTrace;
}

// fetch logs/errors/search results from pagination servlet
const callPaginationServlet = async(fileName, fileType, searchString, pageSpecs) => {
    const params = new URLSearchParams();
    params.append(START, pageSpecs.START);
    params.append(SIZE,  pageSpecs.SIZE);
    params.append(SEARCH_STRING, searchString);
    params.append(FILE_TYPE, fileType);
    params.append(FILE_NAME, fileName);
    const response = await fetch(PAGINATION, {
        method: POST,
        body: params
    });
    const fetchedData = await response.json();
    return fetchedData;
}

// delete all the
const deleteIndices = async() => {
    await fetch(DELETE, {
        method: POST
});
    alert("Data Deleted");
}<|endoftext|>