<commit_before>Package.describe({
  summary: "A feature rich translation package"
});

Package._transitional_registerBuildPlugin({
  name: "compileLanguage",
  use: ["underscore"],
  sources: ["plugin/compile-language.js"],
  npmDependencies: { "js-yaml": "3.0.2" }
});

Package.on_use(function(api) {
  api.use(["underscore", "ejson", "deps"], ["client", "server"]);
  api.use(["http"], ["client"]);

  api.add_files([
    "lib/Locale.js",
    "lib/LanguageArray.js",
    "lib/NamespaceAbstract.js",
    "lib/FilterList.js",
    "lib/Translator.js",
    "lib/Translator/globalLang.js"
  ], ["client", "server"]);
  api.add_files([
    "client/Namespace.js",
    "client/helper.js"
  ], ["client"]);
  api.add_files([
    "server/Namespace.js"
  ], ["server"]);

  api.add_files(["Translator.js"], ["client", "server"]);
  api.export(["Translator"]);
});

Package.on_test(function (api) {
  api.use(["translator", "tinytest", "test-helpers"], ["client", "server"]);
  api.add_files([
    "tests/namespace.de_DE.lang.yml",
    "tests/namespace.en_US.lang.yml"
  ], ["client", "server"]);
  api.add_files([
    "tests/Locale.js",
    "tests/LanguageArray.js",
    "tests/Namespace.js",
    "tests/FilterList.js"
  ], ["client", "server"]);
});
<commit_msg>added parameter filter files<commit_after>Package.describe({
  summary: "A feature rich translation package"
});

Package._transitional_registerBuildPlugin({
  name: "compileLanguage",
  use: ["underscore"],
  sources: ["plugin/compile-language.js"],
  npmDependencies: { "js-yaml": "3.0.2" }
});

Package.on_use(function(api) {
  api.use(["underscore", "ejson", "deps"], ["client", "server"]);
  api.use(["http"], ["client"]);

  api.add_files([
    "lib/Locale.js",
    "lib/LanguageArray.js",
    "lib/NamespaceAbstract.js",
    "lib/FilterList.js",
    "lib/Translator.js",
    "lib/FilterList/parameter.js",
    "lib/Translator/globalLang.js"
  ], ["client", "server"]);
  api.add_files([
    "client/Namespace.js",
    "client/helper.js"
  ], ["client"]);
  api.add_files([
    "server/Namespace.js"
  ], ["server"]);

  api.add_files(["Translator.js"], ["client", "server"]);
  api.export(["Translator"]);
});

Package.on_test(function (api) {
  api.use(["translator", "tinytest", "test-helpers"], ["client", "server"]);
  api.add_files([
    "tests/namespace.de_DE.lang.yml",
    "tests/namespace.en_US.lang.yml"
  ], ["client", "server"]);
  api.add_files([
    "tests/Locale.js",
    "tests/LanguageArray.js",
    "tests/Namespace.js",
    "tests/FilterList.js",
    "tests/FilterList/parameter.js"
  ], ["client", "server"]);
});
<|endoftext|>


<commit_before>$(document).ready(function() {
  var rid = location.hash.substring(1);
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  var formToJSON = function(form){
    var json = {};
    $.each($(form).serializeArray(), function(key, elm){
      json[elm.name] = elm.value;
    });
    return json;
  };
$.getJSON("/api/db-dump", function(db_dump){
  var srcFromEnabled = function(rid) {
    var rs_info = get(db_dump.rulesets,["enabled",rid],undefined);
    if (rs_info) {
      return get(db_dump.rulesets,["krl",rs_info.hash,"src"],undefined);
    } else {
      return undefined;
    }
  }
  var srcFromVersions = function(rid,ifnone) {
    var hashobj;
    if (db_dump.rulesets) {
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return db_dump.rulesets.krl[hash].src;
      }
    }
    return ifnone;
  }
  var hashFromVersions = function(rid,ifnone) {
    var hashobj;
    if (db_dump.rulesets) {
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return hash;
      }
    }
    return ifnone;
  }
  var krlSrcInvite = "//click on a ruleset name to see its source here";
  var displayKrl = function() {
    $(this).parent().siblings(".krl-showing").toggleClass("krl-showing");
    if($(this).parent().hasClass("krl-showing")) {
      $(".krlsrc textarea").html(krlSrcInvite);
    } else {
      var rid = $(this).html();
      var src = srcFromEnabled(rid);
      if (src) {
        $(this).parent().removeClass("disabled");
      } else {
        $(this).parent().addClass("disabled");
        src = srcFromVersions(rid,"N/A");
      }
      if (location.hash.substring(1) === rid) {
        $(".krlsrc textarea").html(src);
      } else {
        location.hash = rid;
        location.reload();
      }
    }
    $(this).parent().toggleClass("krl-showing");
    $("pre#feedback").html("");
  }
  var renderContent =
    function(data){
      var mpl = Handlebars.compile($('#the-template').html());
      $('body').html(mpl(data));
      document.title = $('body h1').html();
      $(".krlrid span").click(displayKrl);
      $(".krlsrc input").val(rid);
      $(".lined").linedtextarea();
      if(rid){
        $(".krlrid").filter(function(){
          return $(this).find('span').text() === rid;
        }).toggleClass("krl-showing");
      }
    };
  var rs_data = {};
  rs_data.title = "Engine Rulesets";
  rs_data.descr = "These picos are hosted on this pico engine.";
  if(rid){
    rs_data.src = srcFromVersions(rid,krlSrcInvite);
  } else {
    rs_data.src = krlSrcInvite;
  }
  rs_data.rulesets = {};
  if (db_dump.rulesets && db_dump.rulesets.versions) {
    for(var aRid in db_dump.rulesets.versions) {
      rs_data.rulesets[aRid] = {};
      if (get(db_dump.rulesets,["enabled",aRid],undefined)) {
        rs_data.rulesets[aRid].enabled = true;
      }
    }
  }
  var ridRE = /^[a-zA-Z][a-zA-Z0-9_.-]*$/;
  rs_data.ridRE = ridRE.toString();
  renderContent(rs_data);
  $("form.ruleset-new").submit(function(e){
    e.preventDefault();
    var rid = this.rid.value;
    if (ridRE.test(rid)) {
      if (get(db_dump,["rulesets","versions",rid],undefined)) {
        location.hash = rid;
        location.reload();
      } else {
        $("pre#feedback").html("Registering...");
        var src = "ruleset "+rid+" {\n}";
        $.getJSON("/api/ruleset/register",{"src":src},function(result){
          location.hash = rid;
          location.reload();
        });
      }
    } else {
      alert("invalid ruleset id");
    }
  });
  $("div.krlsrc form button").click(function(){
    $(this).siblings(".clicked").toggleClass("clicked")
    $(this).toggleClass("clicked");
  });
  $("div.krlsrc").on("submit","form.ruleset-action",function(e){
    e.preventDefault();
    var $feedback = $("pre#feedback");
    $feedback.html("working...");
    var formAction = $(".clicked").attr("formaction");
    $(".clicked").toggleClass("clicked");
    var not_implemented = function(fa) {
      $feedback.html("use UI at localhost:8080/old");
      alert("not implemented: "+fa);
      $feedback.html("");
    };
    if (formAction === "/api/ruleset/enable") {
      var rsHash = hashFromVersions(this.rid.value,undefined);
      if (rsHash) {
        formAction += "/" + rsHash;
      }
    }
    if (formAction === "/api/ruleset/install") {
      formAction += "/" + this.rid.value;
    }
    $.getJSON(formAction,formToJSON(this),function(result){
      if(result.error){
        $feedback.html(result.error);
      } else if(result.code || result.ok){
        $feedback.html("ok");
        if (!formAction.startsWith("/api/ruleset/compile")) {
          location.reload();
        }
      } else {
        $feedback.html(JSON.stringify(result));
      }
    });
  });
});
});
<commit_msg>tweak to Engine Rulesets page description<commit_after>$(document).ready(function() {
  var rid = location.hash.substring(1);
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  var formToJSON = function(form){
    var json = {};
    $.each($(form).serializeArray(), function(key, elm){
      json[elm.name] = elm.value;
    });
    return json;
  };
$.getJSON("/api/db-dump", function(db_dump){
  var srcFromEnabled = function(rid) {
    var rs_info = get(db_dump.rulesets,["enabled",rid],undefined);
    if (rs_info) {
      return get(db_dump.rulesets,["krl",rs_info.hash,"src"],undefined);
    } else {
      return undefined;
    }
  }
  var srcFromVersions = function(rid,ifnone) {
    var hashobj;
    if (db_dump.rulesets) {
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return db_dump.rulesets.krl[hash].src;
      }
    }
    return ifnone;
  }
  var hashFromVersions = function(rid,ifnone) {
    var hashobj;
    if (db_dump.rulesets) {
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
    }
    if (hashobj) {
      for(var hash in hashobj)
      {
        return hash;
      }
    }
    return ifnone;
  }
  var krlSrcInvite = "//click on a ruleset name to see its source here";
  var displayKrl = function() {
    $(this).parent().siblings(".krl-showing").toggleClass("krl-showing");
    if($(this).parent().hasClass("krl-showing")) {
      $(".krlsrc textarea").html(krlSrcInvite);
    } else {
      var rid = $(this).html();
      var src = srcFromEnabled(rid);
      if (src) {
        $(this).parent().removeClass("disabled");
      } else {
        $(this).parent().addClass("disabled");
        src = srcFromVersions(rid,"N/A");
      }
      if (location.hash.substring(1) === rid) {
        $(".krlsrc textarea").html(src);
      } else {
        location.hash = rid;
        location.reload();
      }
    }
    $(this).parent().toggleClass("krl-showing");
    $("pre#feedback").html("");
  }
  var renderContent =
    function(data){
      var mpl = Handlebars.compile($('#the-template').html());
      $('body').html(mpl(data));
      document.title = $('body h1').html();
      $(".krlrid span").click(displayKrl);
      $(".krlsrc input").val(rid);
      $(".lined").linedtextarea();
      if(rid){
        $(".krlrid").filter(function(){
          return $(this).find('span').text() === rid;
        }).toggleClass("krl-showing");
      }
    };
  var rs_data = {};
  rs_data.title = "Engine Rulesets";
  rs_data.descr = "These rulesets are hosted on this pico engine.";
  if(rid){
    rs_data.src = srcFromVersions(rid,krlSrcInvite);
  } else {
    rs_data.src = krlSrcInvite;
  }
  rs_data.rulesets = {};
  if (db_dump.rulesets && db_dump.rulesets.versions) {
    for(var aRid in db_dump.rulesets.versions) {
      rs_data.rulesets[aRid] = {};
      if (get(db_dump.rulesets,["enabled",aRid],undefined)) {
        rs_data.rulesets[aRid].enabled = true;
      }
    }
  }
  var ridRE = /^[a-zA-Z][a-zA-Z0-9_.-]*$/;
  rs_data.ridRE = ridRE.toString();
  renderContent(rs_data);
  $("form.ruleset-new").submit(function(e){
    e.preventDefault();
    var rid = this.rid.value;
    if (ridRE.test(rid)) {
      if (get(db_dump,["rulesets","versions",rid],undefined)) {
        location.hash = rid;
        location.reload();
      } else {
        $("pre#feedback").html("Registering...");
        var src = "ruleset "+rid+" {\n}";
        $.getJSON("/api/ruleset/register",{"src":src},function(result){
          location.hash = rid;
          location.reload();
        });
      }
    } else {
      alert("invalid ruleset id");
    }
  });
  $("div.krlsrc form button").click(function(){
    $(this).siblings(".clicked").toggleClass("clicked")
    $(this).toggleClass("clicked");
  });
  $("div.krlsrc").on("submit","form.ruleset-action",function(e){
    e.preventDefault();
    var $feedback = $("pre#feedback");
    $feedback.html("working...");
    var formAction = $(".clicked").attr("formaction");
    $(".clicked").toggleClass("clicked");
    var not_implemented = function(fa) {
      $feedback.html("use UI at localhost:8080/old");
      alert("not implemented: "+fa);
      $feedback.html("");
    };
    if (formAction === "/api/ruleset/enable") {
      var rsHash = hashFromVersions(this.rid.value,undefined);
      if (rsHash) {
        formAction += "/" + rsHash;
      }
    }
    if (formAction === "/api/ruleset/install") {
      formAction += "/" + this.rid.value;
    }
    $.getJSON(formAction,formToJSON(this),function(result){
      if(result.error){
        $feedback.html(result.error);
      } else if(result.code || result.ok){
        $feedback.html("ok");
        if (!formAction.startsWith("/api/ruleset/compile")) {
          location.reload();
        }
      } else {
        $feedback.html(JSON.stringify(result));
      }
    });
  });
});
});
<|endoftext|>


<commit_before>const getCurrencies    = require('../user/get_currency').getCurrencies;
const Client           = require('../../base/client');
const BinarySocket     = require('../../base/socket');
const isCryptocurrency = require('../../common/currency').isCryptocurrency;
const elementInnerHtml = require('../../../_common/common_functions').elementInnerHtml;
const getElementById   = require('../../../_common/common_functions').getElementById;
const localize         = require('../../../_common/localize').localize;
const State            = require('../../../_common/storage').State;
const Url              = require('../../../_common/url');
const getPropertyValue = require('../../../_common/utility').getPropertyValue;

const Cashier = (() => {
    let href = '';

    const showContent = () => {
        Client.activateByClientType();
        const anchor = Url.paramsHash().anchor;
        let $toggler;
        if (anchor) {
            $toggler = $(`[data-anchor='${anchor}']`);
            $toggler.find('.td-description').addClass('active'); // toggle open description
            $toggler.find('.td-list').removeClass('active');
            $toggler.find('.toggler').addClass('open');
        }
        $('.toggler').on('click', (e) => {
            if ($(e.target)[0].nodeName === 'A') return;
            e.preventDefault();
            $toggler = $(e.target).closest('.toggler');
            $toggler.children().toggleClass('active');
            $toggler.toggleClass('open');
        });
        showCashierNote();
    };

    const showCashierNote = () => {
        // TODO: remove `wait` & residence check to release to all countries
        BinarySocket.wait('authorize').then(() => {
            $('.cashier_note').setVisibility(
                Client.isLoggedIn() &&                          // only show to logged-in clients
                !Client.get('is_virtual') &&                    // only show to real accounts
                !isCryptocurrency(Client.get('currency'))       // only show to fiat currencies
            );
        });
    };

    const showP2PVisibility = async () => {
        const is_agent = !(await BinarySocket.send({ p2p_agent_info: 1 })).error;
        if (is_agent) {
            $('#dp2p_info').setVisibility(1);
            return;
        }

        const has_buy = await checkP2PHasOffer('buy');
        if (has_buy) {
            $('#dp2p_info').setVisibility(true);
            return;
        }

        const has_sell = await checkP2PHasOffer('sell');
        if (has_sell) {
            $('#dp2p_info').setVisibility(true);
        }
    };

    const checkP2PHasOffer = (offer_type) => new Promise(async (resolve) => {
        const offer_list_response = await BinarySocket.send({ p2p_offer_list: 1, type: offer_type });
        resolve(getPropertyValue(offer_list_response, ['p2p_offer_list', 'list']).length);
    });

    const displayTopUpButton = () => {
        BinarySocket.wait('balance').then((response) => {
            const el_virtual_topup_info = getElementById('virtual_topup_info');
            const balance   = +response.balance.balance;
            const can_topup = balance <= 1000;
            const top_up_id = '#VRT_topup_link';
            const $a        = $(top_up_id);
            if (!$a) {
                return;
            }
            const classes   = ['toggle', 'button-disabled'];
            const new_el    = { class: $a.attr('class').replace(classes[+can_topup], classes[1 - +can_topup]), html: $a.html(), id: $a.attr('id') };
            if (can_topup) {
                href        = href || Url.urlFor('/cashier/top_up_virtualws');
                new_el.href = href;
            }
            el_virtual_topup_info.innerText = can_topup
                ? localize('Your virtual account balance is currently [_1] or less. You may top up your account with an additional [_2].', [`${Client.get('currency')} 1,000.00`, `${Client.get('currency')} 10,000.00`])
                : localize('You can top up your virtual account with an additional [_1] if your balance is [_2] or less.', [`${Client.get('currency')} 10,000.00`, `${Client.get('currency')} 1,000.00`]);
            $a.replaceWith($('', new_el));
            $(top_up_id).parent().setVisibility(1);
        });
    };

    const showCurrentCurrency = (currency, statement, mt5_logins) => {
        const has_no_mt5          = mt5_logins.length === 0;
        const has_no_transaction  = (statement.count === 0 && statement.transactions.length === 0);
        const el_acc_currency     = getElementById('account_currency');
        const el_currency_image   = getElementById('account_currency_img');
        const el_current_currency = getElementById('account_currency_current');
        const el_current_hint     = getElementById('account_currency_hint');
        const upgrade_info        = Client.getUpgradeInfo();
        const can_change          = Client.canChangeCurrency(statement, mt5_logins);
        const has_upgrade         = upgrade_info.can_upgrade || upgrade_info.can_open_multi
                                    || can_change;
        const account_action_text = has_upgrade ? `<br />${localize('[_1]Manage your accounts[_2]', [``, '</a>'])}` : '';

        const missingCriteria = (has_mt5, has_transaction) => {
            const existing_mt5_msg          = localize('You can no longer change the currency because you\'ve created an MT5 account.') + account_action_text;
            const existing_transaction_msg  = localize('You can no longer change the currency because you\'ve made a first-time deposit.') + account_action_text;

            return has_mt5 && !has_transaction ? existing_mt5_msg : existing_transaction_msg;
        };

        // Set messages based on currency being crypto or fiat
        // If fiat, set message based on if they're allowed to change currency or not
        // Condition is to have no MT5 accounts *and* have no transactions
        const currency_message = isCryptocurrency(currency)
            ? localize('This is your [_1] account.', `${currency}`)
            : has_no_mt5 && has_no_transaction
                ? localize('Your fiat account\'s currency is currently set to [_1].', `${currency}`)
                : localize('Your fiat account\'s currency is set to [_1].', `${currency}`);

        const currency_hint = isCryptocurrency(currency)
            ? localize('Don\'t want to trade in [_1]? You can open another cryptocurrency account.', `${currency}`) + account_action_text
            : has_no_mt5 && has_no_transaction
                ? localize('You can [_1]set a new currency[_2] before you deposit for the first time or create an MT5 account.', can_change ? [`<a href=${Url.urlFor('user/accounts')}>`, ''] : ['', ''])
                : missingCriteria(!has_no_mt5, !has_no_transaction);

        elementInnerHtml(el_current_currency, currency_message);
        elementInnerHtml(el_current_hint, currency_hint);
        el_currency_image.src = Url.urlForStatic(`/images/pages/cashier/icons/icon-${currency}.svg`);

        const available_currencies  = getCurrencies(State.getResponse('landing_company'));
        const has_more_crypto       = (available_currencies.find(cur => isCryptocurrency(cur)) || []).length > 0;
        const show_current_currency = !isCryptocurrency(currency) || (isCryptocurrency(currency) && has_more_crypto);

        el_acc_currency.setVisibility(show_current_currency);
    };

    const setCryptoMinimumWithdrawal = () => {
        BinarySocket.wait('website_status').then((response) => {
            $('#cryptocurrency tbody tr').each(function () {
                const $row = $(this);
                const $columns = $row.find('td:nth-child(2) div:nth-child(2)');

                const shortname = $columns.find('p:nth-child(1)').text();
                const $crypto_min_withdrawal = $columns.find('p:nth-child(3)');

                if (shortname && $crypto_min_withdrawal) {
                    const minimum_withdrawal = response
                        .website_status
                        .crypto_config[shortname]
                        .minimum_withdrawal;

                    $crypto_min_withdrawal.text(minimum_withdrawal);
                }
            });
        });
    };

    const onLoad = () => {
        if (Client.isLoggedIn()) {
            BinarySocket.send({ statement: 1, limit: 1 });
            BinarySocket.wait('authorize', 'mt5_login_list', 'statement').then(() => {
                const residence  = Client.get('residence');
                const currency   = Client.get('currency');

                if (Client.get('is_virtual')) {
                    displayTopUpButton();
                } else if (currency) {
                    showCurrentCurrency(
                        currency,
                        State.getResponse('statement'),
                        State.getResponse('mt5_login_list')
                    );
                    showP2PVisibility();
                }

                if (residence) {
                    BinarySocket.send({ paymentagent_list: residence }).then((response) => {
                        const list = getPropertyValue(response, ['paymentagent_list', 'list']);
                        if (list && list.length) {
                            const regex_currency = new RegExp(currency);
                            if (!/^UST$/.test(currency) || list.find(pa => regex_currency.test(pa.currencies))) {
                                $('#payment-agent-section').setVisibility(1);
                            }
                        }
                    });
                }

                if (isCryptocurrency(currency)) {
                    $('.crypto_currency').setVisibility(1);

                    const previous_href = $('#view_payment_methods').attr('href');
                    $('#view_payment_methods').attr('href', previous_href.concat('?anchor=cryptocurrency'));
                } else {
                    $('.normal_currency').setVisibility(1);
                }
            });
        }
        showContent();
    };

    return {
        onLoad,
        PaymentMethods: {
            onLoad: () => {
                showContent();
                setCryptoMinimumWithdrawal();
            },
        },
    };
})();

module.exports = Cashier;
<commit_msg>Update src/javascript/app/pages/cashier/cashier.js<commit_after>const getCurrencies    = require('../user/get_currency').getCurrencies;
const Client           = require('../../base/client');
const BinarySocket     = require('../../base/socket');
const isCryptocurrency = require('../../common/currency').isCryptocurrency;
const elementInnerHtml = require('../../../_common/common_functions').elementInnerHtml;
const getElementById   = require('../../../_common/common_functions').getElementById;
const localize         = require('../../../_common/localize').localize;
const State            = require('../../../_common/storage').State;
const Url              = require('../../../_common/url');
const getPropertyValue = require('../../../_common/utility').getPropertyValue;

const Cashier = (() => {
    let href = '';

    const showContent = () => {
        Client.activateByClientType();
        const anchor = Url.paramsHash().anchor;
        let $toggler;
        if (anchor) {
            $toggler = $(`[data-anchor='${anchor}']`);
            $toggler.find('.td-description').addClass('active'); // toggle open description
            $toggler.find('.td-list').removeClass('active');
            $toggler.find('.toggler').addClass('open');
        }
        $('.toggler').on('click', (e) => {
            if ($(e.target)[0].nodeName === 'A') return;
            e.preventDefault();
            $toggler = $(e.target).closest('.toggler');
            $toggler.children().toggleClass('active');
            $toggler.toggleClass('open');
        });
        showCashierNote();
    };

    const showCashierNote = () => {
        // TODO: remove `wait` & residence check to release to all countries
        BinarySocket.wait('authorize').then(() => {
            $('.cashier_note').setVisibility(
                Client.isLoggedIn() &&                          // only show to logged-in clients
                !Client.get('is_virtual') &&                    // only show to real accounts
                !isCryptocurrency(Client.get('currency'))       // only show to fiat currencies
            );
        });
    };

    const showP2PVisibility = async () => {
        const is_agent = !(await BinarySocket.send({ p2p_agent_info: 1 })).error;
        if (is_agent) {
            $('#dp2p_info').setVisibility(1);
            return;
        }

        const has_buy = await checkP2PHasOffer('buy');
        if (has_buy) {
            $('#dp2p_info').setVisibility(1);
            return;
        }

        const has_sell = await checkP2PHasOffer('sell');
        if (has_sell) {
            $('#dp2p_info').setVisibility(true);
        }
    };

    const checkP2PHasOffer = (offer_type) => new Promise(async (resolve) => {
        const offer_list_response = await BinarySocket.send({ p2p_offer_list: 1, type: offer_type });
        resolve(getPropertyValue(offer_list_response, ['p2p_offer_list', 'list']).length);
    });

    const displayTopUpButton = () => {
        BinarySocket.wait('balance').then((response) => {
            const el_virtual_topup_info = getElementById('virtual_topup_info');
            const balance   = +response.balance.balance;
            const can_topup = balance <= 1000;
            const top_up_id = '#VRT_topup_link';
            const $a        = $(top_up_id);
            if (!$a) {
                return;
            }
            const classes   = ['toggle', 'button-disabled'];
            const new_el    = { class: $a.attr('class').replace(classes[+can_topup], classes[1 - +can_topup]), html: $a.html(), id: $a.attr('id') };
            if (can_topup) {
                href        = href || Url.urlFor('/cashier/top_up_virtualws');
                new_el.href = href;
            }
            el_virtual_topup_info.innerText = can_topup
                ? localize('Your virtual account balance is currently [_1] or less. You may top up your account with an additional [_2].', [`${Client.get('currency')} 1,000.00`, `${Client.get('currency')} 10,000.00`])
                : localize('You can top up your virtual account with an additional [_1] if your balance is [_2] or less.', [`${Client.get('currency')} 10,000.00`, `${Client.get('currency')} 1,000.00`]);
            $a.replaceWith($('', new_el));
            $(top_up_id).parent().setVisibility(1);
        });
    };

    const showCurrentCurrency = (currency, statement, mt5_logins) => {
        const has_no_mt5          = mt5_logins.length === 0;
        const has_no_transaction  = (statement.count === 0 && statement.transactions.length === 0);
        const el_acc_currency     = getElementById('account_currency');
        const el_currency_image   = getElementById('account_currency_img');
        const el_current_currency = getElementById('account_currency_current');
        const el_current_hint     = getElementById('account_currency_hint');
        const upgrade_info        = Client.getUpgradeInfo();
        const can_change          = Client.canChangeCurrency(statement, mt5_logins);
        const has_upgrade         = upgrade_info.can_upgrade || upgrade_info.can_open_multi
                                    || can_change;
        const account_action_text = has_upgrade ? `<br />${localize('[_1]Manage your accounts[_2]', [``, '</a>'])}` : '';

        const missingCriteria = (has_mt5, has_transaction) => {
            const existing_mt5_msg          = localize('You can no longer change the currency because you\'ve created an MT5 account.') + account_action_text;
            const existing_transaction_msg  = localize('You can no longer change the currency because you\'ve made a first-time deposit.') + account_action_text;

            return has_mt5 && !has_transaction ? existing_mt5_msg : existing_transaction_msg;
        };

        // Set messages based on currency being crypto or fiat
        // If fiat, set message based on if they're allowed to change currency or not
        // Condition is to have no MT5 accounts *and* have no transactions
        const currency_message = isCryptocurrency(currency)
            ? localize('This is your [_1] account.', `${currency}`)
            : has_no_mt5 && has_no_transaction
                ? localize('Your fiat account\'s currency is currently set to [_1].', `${currency}`)
                : localize('Your fiat account\'s currency is set to [_1].', `${currency}`);

        const currency_hint = isCryptocurrency(currency)
            ? localize('Don\'t want to trade in [_1]? You can open another cryptocurrency account.', `${currency}`) + account_action_text
            : has_no_mt5 && has_no_transaction
                ? localize('You can [_1]set a new currency[_2] before you deposit for the first time or create an MT5 account.', can_change ? [`<a href=${Url.urlFor('user/accounts')}>`, ''] : ['', ''])
                : missingCriteria(!has_no_mt5, !has_no_transaction);

        elementInnerHtml(el_current_currency, currency_message);
        elementInnerHtml(el_current_hint, currency_hint);
        el_currency_image.src = Url.urlForStatic(`/images/pages/cashier/icons/icon-${currency}.svg`);

        const available_currencies  = getCurrencies(State.getResponse('landing_company'));
        const has_more_crypto       = (available_currencies.find(cur => isCryptocurrency(cur)) || []).length > 0;
        const show_current_currency = !isCryptocurrency(currency) || (isCryptocurrency(currency) && has_more_crypto);

        el_acc_currency.setVisibility(show_current_currency);
    };

    const setCryptoMinimumWithdrawal = () => {
        BinarySocket.wait('website_status').then((response) => {
            $('#cryptocurrency tbody tr').each(function () {
                const $row = $(this);
                const $columns = $row.find('td:nth-child(2) div:nth-child(2)');

                const shortname = $columns.find('p:nth-child(1)').text();
                const $crypto_min_withdrawal = $columns.find('p:nth-child(3)');

                if (shortname && $crypto_min_withdrawal) {
                    const minimum_withdrawal = response
                        .website_status
                        .crypto_config[shortname]
                        .minimum_withdrawal;

                    $crypto_min_withdrawal.text(minimum_withdrawal);
                }
            });
        });
    };

    const onLoad = () => {
        if (Client.isLoggedIn()) {
            BinarySocket.send({ statement: 1, limit: 1 });
            BinarySocket.wait('authorize', 'mt5_login_list', 'statement').then(() => {
                const residence  = Client.get('residence');
                const currency   = Client.get('currency');

                if (Client.get('is_virtual')) {
                    displayTopUpButton();
                } else if (currency) {
                    showCurrentCurrency(
                        currency,
                        State.getResponse('statement'),
                        State.getResponse('mt5_login_list')
                    );
                    showP2PVisibility();
                }

                if (residence) {
                    BinarySocket.send({ paymentagent_list: residence }).then((response) => {
                        const list = getPropertyValue(response, ['paymentagent_list', 'list']);
                        if (list && list.length) {
                            const regex_currency = new RegExp(currency);
                            if (!/^UST$/.test(currency) || list.find(pa => regex_currency.test(pa.currencies))) {
                                $('#payment-agent-section').setVisibility(1);
                            }
                        }
                    });
                }

                if (isCryptocurrency(currency)) {
                    $('.crypto_currency').setVisibility(1);

                    const previous_href = $('#view_payment_methods').attr('href');
                    $('#view_payment_methods').attr('href', previous_href.concat('?anchor=cryptocurrency'));
                } else {
                    $('.normal_currency').setVisibility(1);
                }
            });
        }
        showContent();
    };

    return {
        onLoad,
        PaymentMethods: {
            onLoad: () => {
                showContent();
                setCryptoMinimumWithdrawal();
            },
        },
    };
})();

module.exports = Cashier;
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado

/**
 * DOM drawable for a specific painted node. TODO docs
 *
 * API needed:
 * {
 *   initializeDOM: function( DOMSelfDrawable ) : DOMElement    Node itself responsible for pooling available DOM elements and state. Can use drawable.visualState to set flags and state
 *   updateDOM: function( DOMSelfDrawable )
 *   destroyDOM: function( DOMSelfDrawable )
 * }
 *
 * drawable.visualState.transformDirty should be included, and can be set to true by the drawable
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );
  var Drawable = require( 'SCENERY/display/Drawable' );

  scenery.DOMSelfDrawable = function DOMSelfDrawable( trail, renderer, transformTrail, instance ) {
    Drawable.call( this, trail, renderer, transformTrail );
    this.instance = instance;

    this.node = instance.trail.lastNode();

    this.visualState = null; // to be created in initializeDOM
    this.dirty = true;
    this.domElement = this.node.initializeDOM( this );

    // TODO: handle transforms?
    // TODO: check for the "force acceleration" flag
  };
  var DOMSelfDrawable = scenery.DOMSelfDrawable;

  inherit( Drawable, DOMSelfDrawable, {
    markTransformDirty: function() {
      this.visualState.transformDirty = true;
    },

    // called from the Node that we called initializeDOM on. should never be called after destroyDOM.
    markDirty: function() {
      if ( !this.dirty ) {
        this.dirty = true;

        // TODO: notify what we want to call update() later
        if ( this.block ) {
          this.block.markDOMDirty( this );
        }
      }
    },

    // called from the Node, probably during updateDOM
    getTransformMatrix: function() {

    },

    // called from elsewhere to update the DOM element
    update: function() {
      if ( this.dirty ) {
        this.dirty = false;
        this.node.updateDOM( this );
      }
    },

    dispose: function() {
      // super call
      Drawable.prototype.dispose.call( this );

      this.node.destroyDOM( this );
    }
  } );

  return DOMSelfDrawable;
} );
<commit_msg>Updating DOMSelfDrawable with the new transform system handling<commit_after>// Copyright 2002-2013, University of Colorado

/**
 * DOM drawable for a specific painted node. TODO docs
 *
 * API needed:
 * {
 *   initializeDOM: function( DOMSelfDrawable ) : DOMElement    Node itself responsible for pooling available DOM elements and state. Can use drawable.visualState to set flags and state
 *   updateDOM: function( DOMSelfDrawable )
 *   destroyDOM: function( DOMSelfDrawable )
 * }
 *
 * drawable.visualState.transformDirty should be included, and can be set to true by the drawable
 * drawable.visualState.forceAcceleration should be included, and can be set to true by the drawable
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var inherit = require( 'PHET_CORE/inherit' );
  var scenery = require( 'SCENERY/scenery' );
  var Drawable = require( 'SCENERY/display/Drawable' );

  scenery.DOMSelfDrawable = function DOMSelfDrawable( trail, renderer, transformTrail, instance ) {
    Drawable.call( this, trail, renderer, transformTrail );
    this.instance = instance;

    this.node = instance.trail.lastNode();

    this.visualState = null; // to be created in initializeDOM
    this.dirty = true;

    this.domElement = this.node.initializeDOM( this );

    // now that we called initializeDOM, update the visualState object with the flags it will need
    this.visualState.forceAcceleration = renderer & bitmaskForceAcceleration !== 0;
    this.markTransformDirty();

    // handle transform changes
    this.transformListener = this.markTransformDirty.bind( this );
    this.instance.addRelativeTransformListener( this.transformListener ); // when our relative tranform changes, notify us in the pre-repaint phase
    this.instance.addRelativeTransformPrecompute(); // trigger precomputation of the relative transform, since we will always need it when it is updated
  };
  var DOMSelfDrawable = scenery.DOMSelfDrawable;

  inherit( Drawable, DOMSelfDrawable, {
    markTransformDirty: function() {
      // update the visual state available to updateDOM, so that it will update the transform (Text needs to change the transform, so it is included)
      this.visualState.transformDirty = true;

      this.markDirty();
    },

    // called from the Node that we called initializeDOM on. should never be called after destroyDOM.
    markDirty: function() {
      if ( !this.dirty ) {
        this.dirty = true;

        // TODO: notify what we want to call update() later
        if ( this.block ) {
          this.block.markDOMDirty( this );
        }
      }
    },

    // called from the Node, probably during updateDOM
    getTransformMatrix: function() {
      this.instance.validateRelativeTransform();
      return this.instance.relativeMatrix;
    },

    // called from elsewhere to update the DOM element
    update: function() {
      if ( this.dirty ) {
        this.dirty = false;
        this.node.updateDOM( this );
      }
    },

    dispose: function() {
      // super call
      Drawable.prototype.dispose.call( this );

      this.node.destroyDOM( this );

      this.instance.removeRelativeTransformListener( this.transformListener );
      this.instance.removeRelativeTransformPrecompute();
    }
  } );

  return DOMSelfDrawable;
} );
<|endoftext|>


<commit_before>
Package.describe({
  name: 'garyascuy:osxdock',
  version: '0.0.1',
  summary: 'OSX Dock is a javascript library to have OSX Dock menu in the browser',
  git: 'https://github.com/Gary-Ascuy/osxdock.git',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.use('underscore');
  api.use('jquery');

  api.addFiles('main.js');
  api.addFiles('dock/eventManager.js');
  api.addFiles('dock/objectDock.js');

  api.export('OSX', 'client');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('garyascuy:osxdock');
  api.addFiles('tests.js');
});
<commit_msg>Updating package file<commit_after>
Package.describe({
  name: 'garyascuy:osxdock',
  version: '1.0.0',
  summary: 'OSX Dock is a javascript library to have MacOS dock in the browser ',
  git: 'https://github.com/Gary-Ascuy/osxdock.git',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.use('underscore');
  api.use('jquery');

  api.addFiles('main.js');
  api.addFiles('dock/eventManager.js');
  api.addFiles('dock/objectDock.js');

  api.export('OSX', 'client');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('garyascuy:osxdock');
  api.addFiles('tests.js');
});
<|endoftext|>


<commit_before>/*!

   Flowplayer HTML5 quality selector plugin

   Copyright (c) 2016, Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   revision: $GIT_ID$

*/

(function () {
  'use strict';
  var extension = function(flowplayer) {
    flowplayer(function(api, root) {
      var bean = flowplayer.bean
       ,  common = flowplayer.common
       ,  explicitSrc = false
       ,  hlsjs = false;

      if (api.conf.hlsjs !== false) {
          flowplayer.engines.forEach(function (engine) {
              if (engine.engineName === 'hlsjs' && engine.canPlay('application/x-mpegurl', api.conf)) {
                  hlsjs = true;
              }
          });
      }

      //only register once
      if (api.pluginQualitySelectorEnabled) return;
      api.pluginQualitySelectorEnabled = true;

      if (!flowplayer.support.inlineVideo) return; // No inline video

      if (api.conf.qualities) {
        api.conf.qualities = typeof api.conf.qualities === 'string' ? api.conf.qualities.split(',') : api.conf.qualities;
      }

      bean.on(root, 'click', '.fp-quality-selector li', function(ev) {
        var elem = ev.currentTarget;
        if (!common.hasClass(elem, 'active')) {
          var currentTime = api.finished ? 0 : api.video.time
           ,  quality = elem.getAttribute('data-quality')
           ,  src;
          src = processClip(api.video, quality);
          api.quality = quality;
          if (!src) return;
          explicitSrc = true;
          if (hlsjs && src.hlsjs !== false && !api.live && currentTime && quality === 'abr') {
              src.hlsjs = {startPosition: currentTime};
          }
          api.load(src, function() {
            //Make sure api is not in finished state anymore
            explicitSrc = false;
            api.finished = false;
            if (currentTime && !api.live && !(src.hlsjs && src.hlsjs.startPosition)) {
              api.seek(currentTime, function() {
                api.resume();
              });
            } else if (src.hlsjs) {
              src.hlsjs.startPosition = 0;
            }
          });
        }
      });

      api.on('load', function(ev, api, video) {
        api.qualities = video.qualities || api.conf.qualities || [];
        api.defaultQuality = video.defaultQuality || api.conf.defaultQuality;
        if (typeof api.qualities === 'string') api.qualities = api.qualities.split(',');
        if (!api.quality) return; // Let's go with default quality
        var desiredQuality = findOptimalQuality(api.quality, api.qualities)
         ,  newClip = processClip(video, desiredQuality, !explicitSrc);
        if (!explicitSrc && newClip) {
          ev.preventDefault();
          api.loading = false;
          api.load(newClip);
        }

      }).on('ready', function(ev, api, video) {
        var quality = /mpegurl/i.test(video.type) ? 'abr' :  getQualityFromSrc(video.src, api.qualities) || Math.min(video.height, video.width) + 'p';
        removeAllQualityClasses();
        common.addClass(root, 'quality-' + quality);
        var ui = common.find('.fp-ui', root)[0];
        common.removeNode(common.find('.fp-quality-selector', ui)[0]);
        if (api.qualities.length < 2) return;
        api.quality = quality;
        var selector = common.createElement('ul', {'class': 'fp-quality-selector'});
        ui.appendChild(selector);
        if (hasABRSource(video) && canPlay('application/x-mpegurl') || api.conf.swfHls) {
          selector.appendChild(common.createElement('li', {'data-quality': 'abr', 'class': quality === 'abr' ? 'active' : ''}, 'Auto'));
        }
        api.qualities.forEach(function(q) {
          selector.appendChild(common.createElement('li', {'data-quality': q, 'class': q == quality ? 'active': ''}, q));
        });

      }).on('unload', function() {
        removeAllQualityClasses();
        common.removeNode(common.find('.fp-quality-selector', root)[0]);

      });

      function hasABRSource(video) {
        return video.sources.some(function(src) {
          return /mpegurl/i.test(src.type);
        });
      }

      function canPlay(type) {
        var videoTag = document.createElement('video');
        return !!videoTag.canPlayType(type).replace('no', '');
      }

      function getQualityFromSrc(src, qualities) {
        var m = /-(\d+p)(\.(mp4|webm))?$/.exec(src);
        if (!m) return;
        if (qualities.indexOf(m[1]) === -1) return;
        return m[1];
      }

      function removeAllQualityClasses() {
        if (!api.qualities || !api.qualities.length) return;
        common.removeClass(root, 'quality-abr');
        api.qualities.forEach(function(quality) {
          common.removeClass(root, 'quality-' + quality);
        });
      }

      function findOptimalQuality(previousQuality, newQualities) {
        if (previousQuality === 'abr') return 'abr';
        var a = parseInt(previousQuality, 0), ret;
        newQualities.forEach(function(quality, i) {
          if (i == newQualities.length - 1 && !ret) { // The best we can do
            ret = quality;
          }
          if (parseInt(quality) <= a && parseInt(newQualities[i+1]) > a) { // Is between
            ret = quality;
          }
        });
        return ret;
      }

      function processClip(video, quality, clean) {
        var changed = false, re
         ,  isDefaultQuality = quality === api.defaultQuality
         ,  currentQuality = api.quality || Math.min(api.video.height, api.video.width) + 'p';
        if (currentQuality === api.defaultQuality) {
          re = /(.+?)((\.(mp4|webm)$|$))/;
        }
        else {
          re = /(-\d+p)?((\.(mp4|webm)$|$))/;
        }
        var newSources = video.sources.map(function(src) {
          if (quality === 'abr' || (clean && isDefaultQuality) || /mpegurl/i.test(src.type)) return src;
          var n = {
            type: src.type,
            src: src.src.replace(re, currentQuality === api.defaultQuality ?
                                 '$1-' + quality + '$2' :
                                   isDefaultQuality ? '$2' : '-' + quality + '$2')
          };
          if (n.src !== src.src) changed = true;
          return n;
        });
        var newSourcesStr = JSON.stringify(newSources);
        newSources.sort(function(a, b) {
          var re = /mpegurl/i, ret;
          if (quality === 'abr') ret = re.test(b.type) - re.test(a.type);
          else ret = re.test(a.type) - re.test(b.type);
          return ret;
        });
        changed = changed || JSON.stringify(newSources) !== newSourcesStr;
        var clip = flowplayer.extend({}, video, {
          sources: newSources
        });

        return changed ? clip : false;
      }

    });
  };

  if (typeof module === 'object' && module.exports) module.exports = extension;
  else if (window.flowplayer) extension(window.flowplayer);
}());
<commit_msg>Avoid IE8 error on canPlayType<commit_after>/*!

   Flowplayer HTML5 quality selector plugin

   Copyright (c) 2016, Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   revision: $GIT_ID$

*/

(function () {
  'use strict';
  var extension = function(flowplayer) {
    flowplayer(function(api, root) {
      var bean = flowplayer.bean
       ,  common = flowplayer.common
       ,  explicitSrc = false
       ,  hlsjs = false;

      if (api.conf.hlsjs !== false) {
          flowplayer.engines.forEach(function (engine) {
              if (engine.engineName === 'hlsjs' && engine.canPlay('application/x-mpegurl', api.conf)) {
                  hlsjs = true;
              }
          });
      }

      //only register once
      if (api.pluginQualitySelectorEnabled) return;
      api.pluginQualitySelectorEnabled = true;

      if (!flowplayer.support.inlineVideo) return; // No inline video

      if (api.conf.qualities) {
        api.conf.qualities = typeof api.conf.qualities === 'string' ? api.conf.qualities.split(',') : api.conf.qualities;
      }

      bean.on(root, 'click', '.fp-quality-selector li', function(ev) {
        var elem = ev.currentTarget;
        if (!common.hasClass(elem, 'active')) {
          var currentTime = api.finished ? 0 : api.video.time
           ,  quality = elem.getAttribute('data-quality')
           ,  src;
          src = processClip(api.video, quality);
          api.quality = quality;
          if (!src) return;
          explicitSrc = true;
          if (hlsjs && src.hlsjs !== false && !api.live && currentTime && quality === 'abr') {
              src.hlsjs = {startPosition: currentTime};
          }
          api.load(src, function() {
            //Make sure api is not in finished state anymore
            explicitSrc = false;
            api.finished = false;
            if (currentTime && !api.live && !(src.hlsjs && src.hlsjs.startPosition)) {
              api.seek(currentTime, function() {
                api.resume();
              });
            } else if (src.hlsjs) {
              src.hlsjs.startPosition = 0;
            }
          });
        }
      });

      api.on('load', function(ev, api, video) {
        api.qualities = video.qualities || api.conf.qualities || [];
        api.defaultQuality = video.defaultQuality || api.conf.defaultQuality;
        if (typeof api.qualities === 'string') api.qualities = api.qualities.split(',');
        if (!api.quality) return; // Let's go with default quality
        var desiredQuality = findOptimalQuality(api.quality, api.qualities)
         ,  newClip = processClip(video, desiredQuality, !explicitSrc);
        if (!explicitSrc && newClip) {
          ev.preventDefault();
          api.loading = false;
          api.load(newClip);
        }

      }).on('ready', function(ev, api, video) {
        var quality = /mpegurl/i.test(video.type) ? 'abr' :  getQualityFromSrc(video.src, api.qualities) || Math.min(video.height, video.width) + 'p';
        removeAllQualityClasses();
        common.addClass(root, 'quality-' + quality);
        var ui = common.find('.fp-ui', root)[0];
        common.removeNode(common.find('.fp-quality-selector', ui)[0]);
        if (api.qualities.length < 2) return;
        api.quality = quality;
        var selector = common.createElement('ul', {'class': 'fp-quality-selector'});
        ui.appendChild(selector);
        if (hasABRSource(video) && canPlay('application/x-mpegurl') || api.conf.swfHls) {
          selector.appendChild(common.createElement('li', {'data-quality': 'abr', 'class': quality === 'abr' ? 'active' : ''}, 'Auto'));
        }
        api.qualities.forEach(function(q) {
          selector.appendChild(common.createElement('li', {'data-quality': q, 'class': q == quality ? 'active': ''}, q));
        });

      }).on('unload', function() {
        removeAllQualityClasses();
        common.removeNode(common.find('.fp-quality-selector', root)[0]);

      });

      function hasABRSource(video) {
        return video.sources.some(function(src) {
          return /mpegurl/i.test(src.type);
        });
      }

      function canPlay(type) {
        var videoTag = common.createElement('video');
        return typeof videoTag.canPlayType === 'function' && !!videoTag.canPlayType(type).replace('no', '');
      }

      function getQualityFromSrc(src, qualities) {
        var m = /-(\d+p)(\.(mp4|webm))?$/.exec(src);
        if (!m) return;
        if (qualities.indexOf(m[1]) === -1) return;
        return m[1];
      }

      function removeAllQualityClasses() {
        if (!api.qualities || !api.qualities.length) return;
        common.removeClass(root, 'quality-abr');
        api.qualities.forEach(function(quality) {
          common.removeClass(root, 'quality-' + quality);
        });
      }

      function findOptimalQuality(previousQuality, newQualities) {
        if (previousQuality === 'abr') return 'abr';
        var a = parseInt(previousQuality, 0), ret;
        newQualities.forEach(function(quality, i) {
          if (i == newQualities.length - 1 && !ret) { // The best we can do
            ret = quality;
          }
          if (parseInt(quality) <= a && parseInt(newQualities[i+1]) > a) { // Is between
            ret = quality;
          }
        });
        return ret;
      }

      function processClip(video, quality, clean) {
        var changed = false, re
         ,  isDefaultQuality = quality === api.defaultQuality
         ,  currentQuality = api.quality || Math.min(api.video.height, api.video.width) + 'p';
        if (currentQuality === api.defaultQuality) {
          re = /(.+?)((\.(mp4|webm)$|$))/;
        }
        else {
          re = /(-\d+p)?((\.(mp4|webm)$|$))/;
        }
        var newSources = video.sources.map(function(src) {
          if (quality === 'abr' || (clean && isDefaultQuality) || /mpegurl/i.test(src.type)) return src;
          var n = {
            type: src.type,
            src: src.src.replace(re, currentQuality === api.defaultQuality ?
                                 '$1-' + quality + '$2' :
                                   isDefaultQuality ? '$2' : '-' + quality + '$2')
          };
          if (n.src !== src.src) changed = true;
          return n;
        });
        var newSourcesStr = JSON.stringify(newSources);
        newSources.sort(function(a, b) {
          var re = /mpegurl/i, ret;
          if (quality === 'abr') ret = re.test(b.type) - re.test(a.type);
          else ret = re.test(a.type) - re.test(b.type);
          return ret;
        });
        changed = changed || JSON.stringify(newSources) !== newSourcesStr;
        var clip = flowplayer.extend({}, video, {
          sources: newSources
        });

        return changed ? clip : false;
      }

    });
  };

  if (typeof module === 'object' && module.exports) module.exports = extension;
  else if (window.flowplayer) extension(window.flowplayer);
}());
<|endoftext|>


<commit_before>window.onload = function(){
		var labor_force_size = document.getElementById('labor_force_size')
		var labor_force_size_ref = firebase.database().ref('data_dashboard').child('labor_force_size');
		labor_force_size_ref.on('value', snap => labor_force_size.innerText = snap.val());

		var average_annual_wage = document.getElementById('average_annual_wage')
		var average_annual_wage_ref = firebase.database().ref('data_dashboard').child('average_annual_wage');
		average_annual_wage_ref.on('value', snap => average_annual_wage.innerText = snap.val());

		var average_annual_commute_time = document.getElementById('average_annual_commute_time')
		var average_annual_commute_time_ref = firebase.database().ref('data_dashboard').child('average_annual_commute_time');
		average_annual_commute_time_ref.on('value', snap => average_annual_commute_time.innerText = snap.val());

		var broadband_access = document.getElementById('broadband_access')
		var broadband_access_ref = firebase.database().ref('data_dashboard').child('broadband_access');
		broadband_access_ref.on('value', snap => broadband_access.innerText = snap.val());

		var churn_rate = document.getElementById('churn_rate')
		var churn_rate_ref = firebase.database().ref('data_dashboard').child('churn_rate');
		churn_rate_ref.on('value', snap => churn_rate.innerText = snap.val());

		var closings = document.getElementById('closings')
		var closings_ref = firebase.database().ref('data_dashboard').child('closings');
		closings_ref.on('value', snap => closings.innerText = snap.val());

		var cost_of_living = document.getElementById('cost_of_living')
		var cost_of_living_ref = firebase.database().ref('data_dashboard').child('cost_of_living');
		cost_of_living_ref.on('value', snap => cost_of_living.innerText = snap.val());

		var gross_domestic_product = document.getElementById('gross_domestic_product')
		var gross_domestic_product_ref = firebase.database().ref('data_dashboard').child('gross_domestic_product');
		gross_domestic_product_ref.on('value', snap => gross_domestic_product.innerText = snap.val());

		var jobs_employed_resident_ratio = document.getElementById('jobs_employed_resident_ratio')
		var jobs_employed_resident_ratio_ref = firebase.database().ref('data_dashboard').child('jobs_employed_resident_ratio');
		jobs_employed_resident_ratio_ref.on('value', snap => jobs_employed_resident_ratio.innerText = snap.val());

		var new_business_starts = document.getElementById('new_business_starts')
		var new_business_starts_ref = firebase.database().ref('data_dashboard').child('new_business_starts');
		new_business_starts_ref.on('value', snap => new_business_starts.innerText = snap.val());

		var new_housing_costs = document.getElementById('new_housing_costs')
		var new_housing_costs_ref = firebase.database().ref('data_dashboard').child('new_housing_costs');
		new_housing_costs_ref.on('value', snap => new_housing_costs.innerText = snap.val());

		var poverty_rate = document.getElementById('poverty_rate')
		var poverty_rate_ref = firebase.database().ref('data_dashboard').child('poverty_rate');
		poverty_rate_ref.on('value', snap => poverty_rate.innerText = snap.val());

		var sbir_grants = document.getElementById('sbir_grants')
		var sbir_grants_ref = firebase.database().ref('data_dashboard').child('sbir_grants');
		sbir_grants_ref.on('value', snap => sbir_grants.innerText = snap.val());

		var stage_ii_establishments = document.getElementById('stage_ii_establishments')
		var stage_ii_establishments_ref = firebase.database().ref('data_dashboard').child('stage_ii_establishments');
		stage_ii_establishments_ref.on('value', snap => stage_ii_establishments.innerText = snap.val());

		var stem_employment = document.getElementById('stem_employment')
		var stem_employment_ref = firebase.database().ref('data_dashboard').child('stem_employment');
		stem_employment_ref.on('value', snap => stem_employment.innerText = snap.val());

		var unemployment_rate = document.getElementById('unemployment_rate')
		var unemployment_rate_ref = firebase.database().ref('data_dashboard').child('unemployment_rate');
		unemployment_rate_ref.on('value', snap => unemployment_rate.innerText = snap.val());

		var chart_variable = 0;
		unemployment_rate_ref.on('value', snap => chart_variable = parseInt(snap.val()));

		var ctx = document.getElementById("myChart1");
		var myChart = new Chart(ctx, {
		    type: 'bar',
		    data: {
			labels: ["Business Startups", "Unemployment", "Average Commute", "Labor Force", "Broadband", "Churn Rate"],
			datasets: [{
			    label: 'Test Bar Graph',
			    data: [2, 3, 1, 4, 5, 3.5],
				backgroundColor: [
				'rgba(255, 99, 132, 0.2)',
				'rgba(54, 162, 235, 0.2)',
				'rgba(255, 206, 86, 0.2)',
				'rgba(75, 192, 192, 0.2)',
				'rgba(153, 102, 255, 0.2)',
				'rgba(255, 159, 64, 0.2)'
			    ],
			    borderColor: [
				'rgba(255,99,132,1)',
				'rgba(54, 162, 235, 1)',
				'rgba(255, 206, 86, 1)',
				'rgba(75, 192, 192, 1)',
				'rgba(153, 102, 255, 1)',
				'rgba(255, 159, 64, 1)'
			    ],
			    borderWidth: 1
			}]
		    },
		    options: {
			scales: {
			    yAxes: [{
				ticks: {
				    beginAtZero:true
				}
			    }]
			}
		    }
		});

	var dtx = document.getElementById("myChart2");
		var myChart = new Chart(dtx, {
		    type: 'line',
		    data: {
			labels: ["2015", "2013", "2014", "2015", "2016", "2017"],
			datasets: [{
			    label: 'Test line Graph',
			    data: [2, 3, 5, 3, 3.5, 2],
				backgroundColor: [
				'rgba(255, 99, 132, 0.2)',
				'rgba(54, 162, 235, 0.2)',
				'rgba(255, 206, 86, 0.2)',
				'rgba(75, 192, 192, 0.2)',
				'rgba(153, 102, 255, 0.2)',
				'rgba(255, 159, 64, 0.2)'
			    ],
			    borderColor: [
				'rgba(255,99,132,1)',
				'rgba(54, 162, 235, 1)',
				'rgba(255, 206, 86, 1)',
				'rgba(75, 192, 192, 1)',
				'rgba(153, 102, 255, 1)',
				'rgba(255, 159, 64, 1)'
			    ],
			    borderWidth: 1
			}]
		    },
		    options: {
			scales: {
			    yAxes: [{
				ticks: {
				    beginAtZero:true
				}
			    }]
			}
		    }
		});

	var pie_data = {
    		labels: [
        	"Variable One",
        	"Variable Two",
        	"Variable Three"
    		],
    		datasets: [
        	{
            	data: [300, 50, 100],
            	backgroundColor: [
                	"#FF6384",
                	"#36A2EB",
                	"#FFCE56"
            	],
           	 hoverBackgroundColor: [
                	"#FF6384",
                	"#36A2EB",
                	"#FFCE56"
            	]
        	}]
	};
	var etx = document.getElementById("myChart3");
	var myPieChart = new Chart(etx,{
    		type: 'pie',
    		data: pie_data,
    		options: {
        		animation:{
            			animateScale:true
        		}
    		}
	});

	var bubble_data = {
		datasets: [{
			label: 'First Dataset',
			data: [
				{
					x: 20,
					y: 30,
					r: 15
				},
				{
					x: 40,
					y: 10,
					r: 10
				}
			],
			backgroundColor:"#FF6384",
			hoverBackgroundColor: "#FF6384",
		},
		{
			label: 'Second Dataset',
			data: [
				{
					x: 50,
					y: 25,
					r: 30
				},
				{
					x: 5,
					y: 30,
					r: 30
				}
			],
			backgroundColor:"#36A2EB",
			hoverBackgroundColor: "#36A2EB",
		}]
	};

	var ftx = document.getElementById("myChart4");
	var myBubbleChart = new Chart(ftx,{
    		type: 'bubble',
    		data: bubble_data,
    		options: {
        		elements: {
           			 points: {
                			borderWidth: 1,
                			borderColor: 'rgb(0, 0, 0)'
            			}
        		}
    		}
	});
};
<commit_msg>Update firebase-data-dashboard.js<commit_after>window.onload = function(){
		var labor_force_size = document.getElementById('labor_force_size')
		var labor_force_size_ref = firebase.database().ref('data_dashboard').child('labor_force_size');
		labor_force_size_ref.on('value', snap => labor_force_size.innerText = snap.val());

		var average_annual_wage = document.getElementById('average_annual_wage')
		var average_annual_wage_ref = firebase.database().ref('data_dashboard').child('average_annual_wage');
		average_annual_wage_ref.on('value', snap => average_annual_wage.innerText = snap.val());

		var average_annual_commute_time = document.getElementById('average_annual_commute_time')
		var average_annual_commute_time_ref = firebase.database().ref('data_dashboard').child('average_annual_commute_time');
		average_annual_commute_time_ref.on('value', snap => average_annual_commute_time.innerText = snap.val());

		var broadband_access = document.getElementById('broadband_access')
		var broadband_access_ref = firebase.database().ref('data_dashboard').child('broadband_access');
		broadband_access_ref.on('value', snap => broadband_access.innerText = snap.val());

		var churn_rate = document.getElementById('churn_rate')
		var churn_rate_ref = firebase.database().ref('data_dashboard').child('churn_rate');
		churn_rate_ref.on('value', snap => churn_rate.innerText = snap.val());

		var closings = document.getElementById('closings')
		var closings_ref = firebase.database().ref('data_dashboard').child('closings');
		closings_ref.on('value', snap => closings.innerText = snap.val());

		var cost_of_living = document.getElementById('cost_of_living')
		var cost_of_living_ref = firebase.database().ref('data_dashboard').child('cost_of_living');
		cost_of_living_ref.on('value', snap => cost_of_living.innerText = snap.val());

		var gross_domestic_product = document.getElementById('gross_domestic_product')
		var gross_domestic_product_ref = firebase.database().ref('data_dashboard').child('gross_domestic_product');
		gross_domestic_product_ref.on('value', snap => gross_domestic_product.innerText = snap.val());

		var jobs_employed_resident_ratio = document.getElementById('jobs_employed_resident_ratio')
		var jobs_employed_resident_ratio_ref = firebase.database().ref('data_dashboard').child('jobs_employed_resident_ratio');
		jobs_employed_resident_ratio_ref.on('value', snap => jobs_employed_resident_ratio.innerText = snap.val());

		var new_business_starts = document.getElementById('new_business_starts')
		var new_business_starts_ref = firebase.database().ref('data_dashboard').child('new_business_starts');
		new_business_starts_ref.on('value', snap => new_business_starts.innerText = snap.val());

		var new_housing_costs = document.getElementById('new_housing_costs')
		var new_housing_costs_ref = firebase.database().ref('data_dashboard').child('new_housing_costs');
		new_housing_costs_ref.on('value', snap => new_housing_costs.innerText = snap.val());

		var poverty_rate = document.getElementById('poverty_rate')
		var poverty_rate_ref = firebase.database().ref('data_dashboard').child('poverty_rate');
		poverty_rate_ref.on('value', snap => poverty_rate.innerText = snap.val());

		var sbir_grants = document.getElementById('sbir_grants')
		var sbir_grants_ref = firebase.database().ref('data_dashboard').child('sbir_grants');
		sbir_grants_ref.on('value', snap => sbir_grants.innerText = snap.val());

		var stage_ii_establishments = document.getElementById('stage_ii_establishments')
		var stage_ii_establishments_ref = firebase.database().ref('data_dashboard').child('stage_ii_establishments');
		stage_ii_establishments_ref.on('value', snap => stage_ii_establishments.innerText = snap.val());

		var stem_employment = document.getElementById('stem_employment')
		var stem_employment_ref = firebase.database().ref('data_dashboard').child('stem_employment');
		stem_employment_ref.on('value', snap => stem_employment.innerText = snap.val());

		var unemployment_rate = document.getElementById('unemployment_rate')
		var unemployment_rate_ref = firebase.database().ref('data_dashboard').child('unemployment_rate');
		unemployment_rate_ref.on('value', snap => unemployment_rate.innerText = snap.val());

		var chart_variable = 0;
		unemployment_rate_ref.on('value', snap => chart_variable = parseInt(snap.val()));

		var ctx = document.getElementById("myChart1");
		var myChart = new Chart(ctx, {
		    type: 'bar',
		    data: {
			labels: ["Business Startups", "Unemployment", "Average Commute", "Labor Force", "Broadband", "Churn Rate"],
			datasets: [{
			    label: 'Test Bar Graph',
			    data: [2, 3, 1, 4, 5, 3.5],
				backgroundColor: [
				'rgba(255, 99, 132, 0.2)',
				'rgba(54, 162, 235, 0.2)',
				'rgba(255, 206, 86, 0.2)',
				'rgba(75, 192, 192, 0.2)',
				'rgba(153, 102, 255, 0.2)',
				'rgba(255, 159, 64, 0.2)'
			    ],
			    borderColor: [
				'rgba(255,99,132,1)',
				'rgba(54, 162, 235, 1)',
				'rgba(255, 206, 86, 1)',
				'rgba(75, 192, 192, 1)',
				'rgba(153, 102, 255, 1)',
				'rgba(255, 159, 64, 1)'
			    ],
			    borderWidth: 1
			}]
		    },
		    options: {
			scales: {
			    yAxes: [{
				ticks: {
				    beginAtZero:true
				}
			    }]
			}
		    }
		});

	var dtx = document.getElementById("myChart2");
		var myChart = new Chart(dtx, {
		    type: 'line',
		    data: {
			labels: ["2015", "2013", "2014", "2015", "2016", "2017"],
			datasets: [{
			    label: 'Test line Graph',
			    data: [2, 3, 5, 3, 3.5, 2],
				backgroundColor: [
				'rgba(255, 99, 132, 0.2)',
				'rgba(54, 162, 235, 0.2)',
				'rgba(255, 206, 86, 0.2)',
				'rgba(75, 192, 192, 0.2)',
				'rgba(153, 102, 255, 0.2)',
				'rgba(255, 159, 64, 0.2)'
			    ],
			    borderColor: [
				'rgba(255,99,132,1)',
				'rgba(54, 162, 235, 1)',
				'rgba(255, 206, 86, 1)',
				'rgba(75, 192, 192, 1)',
				'rgba(153, 102, 255, 1)',
				'rgba(255, 159, 64, 1)'
			    ],
			    borderWidth: 1
			}]
		    },
		    options: {
			scales: {
			    yAxes: [{
				ticks: {
				    beginAtZero:true
				}
			    }]
			}
		    }
		});

	var pie_data = {
    		labels: [
        	"Variable One",
        	"Variable Two",
        	"Variable Three"
    		],
    		datasets: [
        	{
            	data: [300, 50, 100],
            	backgroundColor: [
                	"#FF6384",
                	"#36A2EB",
                	"#FFCE56"
            	],
           	 hoverBackgroundColor: [
                	"#FF6384",
                	"#36A2EB",
                	"#FFCE56"
            	]
        	}]
	};
	var etx = document.getElementById("myChart3");
	var myPieChart = new Chart(etx,{
    		type: 'pie',
    		data: pie_data,
    		options: {
        		animation:{
            			animateScale:true
        		}
    		}
	});

	var bubble_data = {
		datasets: [{
			label: 'First Dataset',
			data: [
				{
					x: 20,
					y: 30,
					r: 15
				},
				{
					x: 40,
					y: 10,
					r: 10
				}
			],
			backgroundColor:"#FF6384",
			hoverBackgroundColor: "#FF6384",
		},
		{
			label: 'Second Dataset',
			data: [
				{
					x: 5,
					y: 25,
					r: 30
				},
				{
					x: 15,
					y: 15,
					r: 20
				}
			],
			backgroundColor:"#36A2EB",
			hoverBackgroundColor: "#36A2EB",
		}]
	};

	var ftx = document.getElementById("myChart4");
	var myBubbleChart = new Chart(ftx,{
    		type: 'bubble',
    		data: bubble_data,
    		options: {
        		elements: {
           			 points: {
                			borderWidth: 1,
                			borderColor: 'rgb(0, 0, 0)'
            			}
        		}
    		}
	});
};
<|endoftext|>


<commit_before>/* eslint no-shadow: 0, func-names: 0, no-unused-vars: 0, no-console: 0 */
var os = require('os');
var webpack = require('webpack');
var cfg = require('./webpack/webpack.config.production.js');
var packager = require('electron-packager');
var assign = require('object-assign');
var del = require('del');
var latest = require('github-latest-release');
var argv = require('minimist')(process.argv.slice(2));
var devDeps = Object.keys(require('./package.json').devDependencies);

var appName = argv.name || argv.n || 'ElectronReact';
var shouldUseAsar = argv.asar || argv.a || false;
var shouldBuildAll = argv.all || false;

var DEFAULT_OPTS = {
  dir: './',
  name: appName,
  asar: shouldUseAsar,
  ignore: [
    '/test($|/)',
    '/tools($|/)',
    '/release($|/)'
  ].concat(devDeps.map(function(name) { return '/node_modules/' + name + '($|/)'; }))
};

var icon = argv.icon || argv.i || 'app/app.icns';

if (icon) {
  DEFAULT_OPTS.icon = icon;
}

var version = argv.version || argv.v;

if (version) {
  DEFAULT_OPTS.version = version;
  startPack();
} else {
  latest('atom', 'electron', function(err, res) {
    if (err) {
      DEFAULT_OPTS.version = '0.28.3';
    } else {
      DEFAULT_OPTS.version = res.name.split('v')[1];
    }
    startPack();
  });
}

function startPack() {
  console.log('start pack...');
  webpack(cfg, function runWebpackBuild(err, stats) {
    if (err) return console.error(err);
    del('release')
    .then(function(paths) {
      if (shouldBuildAll) {
        // build for all platforms
        var archs = ['ia32', 'x64'];
        var platforms = ['linux', 'win32', 'darwin'];

        platforms.forEach(function(plat) {
          archs.forEach(function(arch) {
            pack(plat, arch, log(plat, arch));
          });
        });
      } else {
        // build for current platform only
        pack(os.platform(), os.arch(), log(os.platform(), os.arch()));
      }
    })
    .catch(function(err) {
      console.error(err);
    });
  });
}

function pack(plat, arch, cb) {
  // there is no darwin ia32 electron
  if (plat === 'darwin' && arch === 'ia32') return;

  var opts = assign({}, DEFAULT_OPTS, {
    platform: plat,
    arch: arch,
    out: 'release/' + plat + '-' + arch
  });

  packager(opts, cb);
}

function log(plat, arch) {
  return function(err, filepath) {
    if (err) return console.error(err);
    console.log(plat + '-' + arch + ' finished!');
  };
}
<commit_msg>Pass back the error message<commit_after>/* eslint no-shadow: 0, func-names: 0, no-unused-vars: 0, no-console: 0 */
var os = require('os');
var webpack = require('webpack');
var cfg = require('./webpack/webpack.config.production.js');
var packager = require('electron-packager');
var assign = require('object-assign');
var del = require('del');
var latest = require('github-latest-release');
var argv = require('minimist')(process.argv.slice(2));
var devDeps = Object.keys(require('./package.json').devDependencies);

var appName = argv.name || argv.n || 'ElectronReact';
var shouldUseAsar = argv.asar || argv.a || false;
var shouldBuildAll = argv.all || false;

var DEFAULT_OPTS = {
  dir: './',
  name: appName,
  asar: shouldUseAsar,
  ignore: [
    '/test($|/)',
    '/tools($|/)',
    '/release($|/)'
  ].concat(devDeps.map(function(name) { return '/node_modules/' + name + '($|/)'; }))
};

var icon = argv.icon || argv.i || 'app/app.icns';

if (icon) {
  DEFAULT_OPTS.icon = icon;
}

var version = argv.version || argv.v;

if (version) {
  DEFAULT_OPTS.version = version;
  startPack();
} else {
  latest('atom', 'electron', function(err, res) {
    if (err) {
      console.error("Error while fetching latest Electron release: " + err.message + "\n");
      DEFAULT_OPTS.version = '0.28.3';
    } else {
      DEFAULT_OPTS.version = res.name.split('v')[1];
    }
    startPack();
  });
}

function startPack() {
  console.log('start pack...');
  webpack(cfg, function runWebpackBuild(err, stats) {
    if (err) return console.error(err);
    del('release')
    .then(function(paths) {
      if (shouldBuildAll) {
        // build for all platforms
        var archs = ['ia32', 'x64'];
        var platforms = ['linux', 'win32', 'darwin'];

        platforms.forEach(function(plat) {
          archs.forEach(function(arch) {
            pack(plat, arch, log(plat, arch));
          });
        });
      } else {
        // build for current platform only
        pack(os.platform(), os.arch(), log(os.platform(), os.arch()));
      }
    })
    .catch(function(err) {
      console.error(err);
    });
  });
}

function pack(plat, arch, cb) {
  // there is no darwin ia32 electron
  if (plat === 'darwin' && arch === 'ia32') return;

  var opts = assign({}, DEFAULT_OPTS, {
    platform: plat,
    arch: arch,
    out: 'release/' + plat + '-' + arch
  });

  packager(opts, cb);
}

function log(plat, arch) {
  return function(err, filepath) {
    if (err) return console.error(err);
    console.log(plat + '-' + arch + ' finished!');
  };
}
<|endoftext|>


<commit_before>var crypto = require('crypto');
var config = require('../profile.json');
var Customer = require(config.CustomerModel);

exports.loginface = function (req, res, next) {
    // res.render('login', { layout: "login", title: '米特学堂后台管理系统' });
    res.render('admin', { layout: "admin", title: '米特学堂后台管理系统' });
}

exports.customersList = function (req, res, next) {

    // Customer.Model.find({}, function (err, response) {
    //     if (err) {
    //         console.log("Error:" + err);
    //         res.send('查询失败' + err);
    //     }
    //     else {
    //         // console.log("Res:" + response);
    //         res.render('customersList', {
    //             layout: "admin",
    //             title: '米特学堂后台管理系统',
    //             customersList:response
    //         });
    //     }
    // })
    try {
        console.log("开始执行");
        var page = Customer.PageQuery(1, 3, Customer.Model, "", {}, {});
    } catch (err) {
        console.log(err);
    }

    res.render('customersList', {
        layout: "admin",
        title: '米特学堂后台管理系统',
        customersList: {}
    });

}<commit_msg>customersList: pageResult<commit_after>var crypto = require('crypto');
var config = require('../profile.json');
var Customer = require(config.CustomerModel);

exports.loginface = function (req, res, next) {
    // res.render('login', { layout: "login", title: '米特学堂后台管理系统' });
    res.render('admin', { layout: "admin", title: '米特学堂后台管理系统' });
}

exports.customersList = function (req, res, next) {

    // Customer.Model.find({}, function (err, response) {
    //     if (err) {
    //         console.log("Error:" + err);
    //         res.send('查询失败' + err);
    //     }
    //     else {
    //         // console.log("Res:" + response);
    //         res.render('customersList', {
    //             layout: "admin",
    //             title: '米特学堂后台管理系统',
    //             customersList:response
    //         });
    //     }
    // })
    try {
        console.log("开始执行");
        var pageResult = Customer.PageQuery(1, 3, Customer.Model, "", {}, {});
    } catch (err) {
        console.log(err);
    }

    res.render('customersList', {
        layout: "admin",
        title: '米特学堂后台管理系统',
        customersList: pageResult
    });

}<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

import {OAuthTokenArrayPropType} from 'src/propTypes'
import {DropdownMenuButton, IconFont, UserIconWithHost} from 'src/pages/parts'
import {
  COLUMN_TIMELINE, COLUMN_FRIENDS, COLUMN_NOTIFICATIONS,
  TIMELINE_FEDERATION, TIMELINE_LOCAL, TIMELINE_HOME, SUBJECT_MIXED,
} from 'src/constants'
import TootWindow from '../TootWindow'

/**
 * ダッシュボードのヘッダ
 * [logo] [toot欄] [account icon] [account icon] [account icon] [account icon] .... [歯車]
 */
export default class DashboardHeader extends React.Component {
  static propTypes = {
    tokens: OAuthTokenArrayPropType.isRequired,
    onStartAddAccount: PropTypes.func.isRequired,
    onOpenColumn: PropTypes.func.isRequired,
    onGenKey: PropTypes.func.isRequired,
  }

  /**
   * @constructor
   */
  constructor(...args) {
    super(...args)

    this.state = {
      isShowTootWindow: false,
    }
  }

  /**
   * @override
   */
  render() {
    const {isShowTootWindow} = this.state
    const {tokens} = this.props

    return (

        <DropdownMenuButton modifier="mixedColumMenu" onRenderMenu={::this.onRenderCompoundMenu}>

        </DropdownMenuButton>

          <input
            className={`${isShowTootWindow ? 'is-hidden' : ''}`}
            type="text" placeholder="何してますか？忙しいですか？手伝ってもらってもいいですか？"
            onFocus={::this.onTootFocus} />
          {isShowTootWindow && <TootWindow onClose={::this.onTootWindowClose} />}

          {tokens.map((token) => this.renderAccount(token))}

            <button className="naumanniDashboard-header-addAccountButton"
              onClick={() => this.props.onStartAddAccount()}>
              <IconFont iconName="plus" />
            </button>

        <button className="naumanniDashboard-header-configButton">
          <IconFont iconName="cog" />
        </button>

    )
  }

  /**
   * ヘッダに顔アイコンを書くよ
   * @param {OAuthToken} token
   * @return {React.Component}
   */
  renderAccount(token) {
    if(token.isAlive()) {
      // 正常Token
      return (

          <DropdownMenuButton onRenderMenu={this.onRenderAccountMenu.bind(this, token)}>
            <UserIconWithHost account={token.account} />
          </DropdownMenuButton>

      )
    } else {
      // 読み込みに失敗したToken
      return (

          <DropdownMenuButton onRenderMenu={this.onRenderBadAccountMenu.bind(this, token)}>

×

          </DropdownMenuButton>

      )
    }
  }

  // callbacks
  onRenderCompoundMenu() {
    return (

          <IconFont className="menu-itemIcon" iconName="home" />
          統合ホームタイムライン

          <IconFont className="menu-itemIcon" iconName="users" />
          統合ローカルタイムライン

          <IconFont className="menu-itemIcon" iconName="globe" />
          統合連合タイムライン

          <IconFont className="menu-itemIcon" iconName="bell" />
          統合通知

    )
  }

  onRenderAccountMenu(token) {
    const {account} = token

    return (

          <UserIconWithHost account={account} />

            {account.display_name}

            {account.acct}

              {account.hasPublicKey && <IconFont iconName="key" />pub}

              {account.hasPrivateKey && <IconFont iconName="key" />prv}

            <button onClick={this.props.onGenKey.bind(this, token, account)}>鍵生成</button>

          <IconFont className="menu-itemIcon" iconName="home" />
          ホームタイムライン

          <IconFont className="menu-itemIcon" iconName="users" />
          ローカルタイムライン

          <IconFont className="menu-itemIcon" iconName="globe" />
          連合タイムライン

          <IconFont className="menu-itemIcon" iconName="bell" />
          通知

          <IconFont className="menu-itemIcon" iconName="mail" />
          メッセージ

    )
  }

  /**
   * 読み込みエラーになったTokenに関するMenu
   * @param {OAuthToken} token
   * @return {React.Component}
   */
  onRenderBadAccountMenu(token) {
    return (

          ホスト: {token.host}

            通信エラーです。
            相手先サーバーが不調か、このマシンがネットワークにつながっていない可能性があります。

    )
  }

  onTootFocus(e) {
    this.setState({isShowTootWindow: true})
  }

  onTootWindowClose() {
    this.setState({isShowTootWindow: false})
  }
}
<commit_msg>Update DashboardHeader.es6<commit_after>import React from 'react'
import PropTypes from 'prop-types'

import {OAuthTokenArrayPropType} from 'src/propTypes'
import {DropdownMenuButton, IconFont, UserIconWithHost} from 'src/pages/parts'
import {
  COLUMN_TIMELINE, COLUMN_FRIENDS, COLUMN_NOTIFICATIONS,
  TIMELINE_FEDERATION, TIMELINE_LOCAL, TIMELINE_HOME, SUBJECT_MIXED,
} from 'src/constants'
import TootWindow from '../TootWindow'

/**
 * ダッシュボードのヘッダ
 * [logo] [toot欄] [account icon] [account icon] [account icon] [account icon] .... [歯車]
 */
export default class DashboardHeader extends React.Component {
  static propTypes = {
    tokens: OAuthTokenArrayPropType.isRequired,
    onStartAddAccount: PropTypes.func.isRequired,
    onOpenColumn: PropTypes.func.isRequired,
    onGenKey: PropTypes.func.isRequired,
  }

  /**
   * @constructor
   */
  constructor(...args) {
    super(...args)

    this.state = {
      isShowTootWindow: false,
    }
  }

  /**
   * @override
   */
  render() {
    const {isShowTootWindow} = this.state
    const {tokens} = this.props

    return (

        <DropdownMenuButton modifier="mixedColumMenu" onRenderMenu={::this.onRenderCompoundMenu}>

        </DropdownMenuButton>

          <input
            className={`${isShowTootWindow ? 'is-hidden' : ''}`}
            type="text" placeholder="What's up?"
            onFocus={::this.onTootFocus} />
          {isShowTootWindow && <TootWindow onClose={::this.onTootWindowClose} />}

          {tokens.map((token) => this.renderAccount(token))}

            <button className="naumanniDashboard-header-addAccountButton"
              onClick={() => this.props.onStartAddAccount()}>
              <IconFont iconName="plus" />
            </button>

        <button className="naumanniDashboard-header-configButton">
          <IconFont iconName="cog" />
        </button>

    )
  }

  /**
   * ヘッダに顔アイコンを書くよ
   * @param {OAuthToken} token
   * @return {React.Component}
   */
  renderAccount(token) {
    if(token.isAlive()) {
      // 正常Token
      return (

          <DropdownMenuButton onRenderMenu={this.onRenderAccountMenu.bind(this, token)}>
            <UserIconWithHost account={token.account} />
          </DropdownMenuButton>

      )
    } else {
      // 読み込みに失敗したToken
      return (

          <DropdownMenuButton onRenderMenu={this.onRenderBadAccountMenu.bind(this, token)}>

×

          </DropdownMenuButton>

      )
    }
  }

  // callbacks
  onRenderCompoundMenu() {
    return (

          <IconFont className="menu-itemIcon" iconName="home" />
          United Home timeline

          <IconFont className="menu-itemIcon" iconName="users" />
          United Local timeline

          <IconFont className="menu-itemIcon" iconName="globe" />
          United Federated timeline

          <IconFont className="menu-itemIcon" iconName="bell" />
          United Notification

    )
  }

  onRenderAccountMenu(token) {
    const {account} = token

    return (

          <UserIconWithHost account={account} />

            {account.display_name}

            {account.acct}

              {account.hasPublicKey && <IconFont iconName="key" />pub}

              {account.hasPrivateKey && <IconFont iconName="key" />prv}

            <button onClick={this.props.onGenKey.bind(this, token, account)}>Create key</button>

          <IconFont className="menu-itemIcon" iconName="home" />
          Home timeline

          <IconFont className="menu-itemIcon" iconName="users" />
          Local timeline

          <IconFont className="menu-itemIcon" iconName="globe" />
          Federated timeline

          <IconFont className="menu-itemIcon" iconName="bell" />
          Notifications

          <IconFont className="menu-itemIcon" iconName="mail" />
          Message

    )
  }

  /**
   * 読み込みエラーになったTokenに関するMenu
   * @param {OAuthToken} token
   * @return {React.Component}
   */
  onRenderBadAccountMenu(token) {
    return (

          ホスト: {token.host}

            通信エラーです。
            相手先サーバーが不調か、このマシンがネットワークにつながっていない可能性があります。

    )
  }

  onTootFocus(e) {
    this.setState({isShowTootWindow: true})
  }

  onTootWindowClose() {
    this.setState({isShowTootWindow: false})
  }
}
<|endoftext|>


<commit_before>Package.describe({
  name: 'oorabona:autoform-nstates',
  summary: 'Custom N states input support for AutoForm',
  version: '0.1.0',
  git: 'https://github.com/oorabona/meteor-autoform-nstates.git',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.use('templating@1.0.0');
  api.use('blaze@2.0.0');
  api.use('aldeed:autoform@5.0.0');
  api.use('coffeescript@1.0.0');
  api.use('reactive-dict@1.0.0c');
  api.addFiles([
    'nstates.html',
    'nstates.coffee'
  ], 'client');
});
<commit_msg>Fixed definitely package file ! :)<commit_after>Package.describe({
  name: 'oorabona:autoform-nstates',
  summary: 'Custom N states input support for AutoForm',
  version: '0.1.0',
  git: 'https://github.com/oorabona/meteor-autoform-nstates.git',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.use('templating@1.0.0');
  api.use('blaze@2.0.0');
  api.use('aldeed:autoform@5.0.0');
  api.use('coffeescript@1.0.0');
  api.use('reactive-dict@1.0.0');
  api.addFiles([
    'nstates.html',
    'nstates.coffee'
  ], 'client');
});
<|endoftext|>


<commit_before>import {Slice, Fragment} from "../model"

import {Transform} from "./transform"
import {Step, StepResult} from "./step"
import {PosMap} from "./map"

// !! **`split`**
//   : Split a block node at `pos`. The parameter, if given, may be
//     `{type, ?attrs}` object giving the node type and optionally the
//     attributes of the node created to hold the content after the
//     split.

Step.define("split", {
  apply(doc, step) {
    let $pos = doc.resolve(step.from), parent = $pos.parent
    let cut = [parent.copy(), step.param ? step.param.type.create(step.attrs) : parent.copy()]
    return StepResult.fromReplace(doc, $pos.pos, $pos.pos, new Slice(Fragment.fromArray(cut), 1, 1))
  },
  posMap(step) {
    return new PosMap([step.from, 0, 2])
  },
  invert(step) {
    return new Step("join", step.from, step.from + 2)
  },
  paramToJSON(param) {
    return param && {type: param.type.name, attrs: param.attrs}
  },
  paramFromJSON(schema, json) {
    return json && {type: schema.nodeType(json.type), attrs: json.attrs}
  }
})

// :: (number, ?number, ?NodeType, ?Object) → Transform
// Split the node at the given position, and optionally, if `depth` is
// greater than one, any number of nodes above that. By default, the part
// split off will inherit the node type of the original node. This can
// be changed by passing `typeAfter` and `attrsAfter`.
Transform.prototype.split = function(pos, depth = 1, typeAfter, attrsAfter) {
  for (let i = 0; i < depth; i++)
    this.step("split", pos + i, pos + i,
              i == 0 && typeAfter ? {type: typeAfter, attrs: attrsAfter} : null)
  return this
}

// :: (number, ?number) → Transform
// Split at the given position, up to the given depth, if that
// position isn't already at the start or end of its parent node.
Transform.prototype.splitIfNeeded = function(pos, depth = 1) {
  let $pos = this.doc.resolve(pos), before = true
  for (let i = 0; i < depth; i++) {
    let d = $pos.depth - i, point = i == 0 ? $pos.pos : before ? $pos.before(d + 1) : $pos.after(d + 1)
    if (point == $pos.start(d)) before = true
    else if (point == $pos.end(d)) before = false
    else return this.split(point, depth - i)
  }
  return this
}
<commit_msg>Fix passing of attributes to node type after split<commit_after>import {Slice, Fragment} from "../model"

import {Transform} from "./transform"
import {Step, StepResult} from "./step"
import {PosMap} from "./map"

// !! **`split`**
//   : Split a block node at `pos`. The parameter, if given, may be
//     `{type, ?attrs}` object giving the node type and optionally the
//     attributes of the node created to hold the content after the
//     split.

Step.define("split", {
  apply(doc, step) {
    let $pos = doc.resolve(step.from), parent = $pos.parent
    let cut = [parent.copy(), step.param ? step.param.type.create(step.param.attrs) : parent.copy()]
    return StepResult.fromReplace(doc, $pos.pos, $pos.pos, new Slice(Fragment.fromArray(cut), 1, 1))
  },
  posMap(step) {
    return new PosMap([step.from, 0, 2])
  },
  invert(step) {
    return new Step("join", step.from, step.from + 2)
  },
  paramToJSON(param) {
    return param && {type: param.type.name, attrs: param.attrs}
  },
  paramFromJSON(schema, json) {
    return json && {type: schema.nodeType(json.type), attrs: json.attrs}
  }
})

// :: (number, ?number, ?NodeType, ?Object) → Transform
// Split the node at the given position, and optionally, if `depth` is
// greater than one, any number of nodes above that. By default, the part
// split off will inherit the node type of the original node. This can
// be changed by passing `typeAfter` and `attrsAfter`.
Transform.prototype.split = function(pos, depth = 1, typeAfter, attrsAfter) {
  for (let i = 0; i < depth; i++)
    this.step("split", pos + i, pos + i,
              i == 0 && typeAfter ? {type: typeAfter, attrs: attrsAfter} : null)
  return this
}

// :: (number, ?number) → Transform
// Split at the given position, up to the given depth, if that
// position isn't already at the start or end of its parent node.
Transform.prototype.splitIfNeeded = function(pos, depth = 1) {
  let $pos = this.doc.resolve(pos), before = true
  for (let i = 0; i < depth; i++) {
    let d = $pos.depth - i, point = i == 0 ? $pos.pos : before ? $pos.before(d + 1) : $pos.after(d + 1)
    if (point == $pos.start(d)) before = true
    else if (point == $pos.end(d)) before = false
    else return this.split(point, depth - i)
  }
  return this
}
<|endoftext|>