text:
'use strict';

angular.module('copayApp.controllers').controller('indexController', function($rootScope, $scope, $log, $filter, $timeout, latestReleaseService, bwcService, pushNotificationsService, lodash, go, profileService, configService, isCordova, rateService, storageService, addressService, gettext, gettextCatalog, amMoment, nodeWebkit, addonManager, isChromeApp, bwsError, txFormatService, uxLanguage, glideraService, coinbaseService, isMobile, addressbookService, walletService) {
  var self = this;
  var SOFT_CONFIRMATION_LIMIT = 12;
  var errors = bwcService.getErrors();
  var historyUpdateInProgress = {};

  var ret = {};
  ret.isCordova = isCordova;
  ret.isChromeApp = isChromeApp;
  ret.isSafari = isMobile.Safari();
  ret.isWindowsPhoneApp = isMobile.Windows() && isCordova;
  ret.onGoingProcess = {};
  ret.historyShowLimit = 10;
  ret.historyShowMoreLimit = 100;
  ret.isSearching = false;
  ret.prevState = 'walletHome';

  ret.menu = [{
    'title': gettext('Receive'),
    'icon': {
      false: 'icon-receive',
      true: 'icon-receive-active'
    },
    'link': 'receive'
  }, {
    'title': gettext('Activity'),
    'icon': {
      false: 'icon-activity',
      true: 'icon-activity-active'
    },
    'link': 'walletHome'
  }, {
    'title': gettext('Send'),
    'icon': {
      false: 'icon-send',
      true: 'icon-send-active'
    },
    'link': 'send'
  }];

  ret.addonViews = addonManager.addonViews();
  ret.txTemplateUrl = addonManager.txTemplateUrl() || 'views/includes/transaction.html';

  ret.tab = 'walletHome';
  var vanillaScope = ret;

  if (nodeWebkit.isDefined()) {
    latestReleaseService.checkLatestRelease(function(err, newRelease) {
      if (err) {
        $log.warn(err);
        return;
      }

      if (newRelease)
        $scope.newRelease = gettext('There is a new version of Copay. Please update');
    });
  }

  function strip(number) {
    return (parseFloat(number.toPrecision(12)));
  };

  self.goHome = function() {
    go.walletHome();
  };

  self.setOngoingProcess = function(processName, isOn) {
    $log.debug('onGoingProcess', processName, isOn);
    self[processName] = isOn;
    self.onGoingProcess[processName] = isOn;

    var name;
    self.anyOnGoingProcess = lodash.any(self.onGoingProcess, function(isOn, processName) {
      if (isOn)
        name = name || processName;
      return isOn;
    });
    // The first one
    self.onGoingProcessName = name;
    $timeout(function() {
      $rootScope.$apply();
    });
  };

  self.cleanInstance = function() {
    $log.debug('Cleaning Index Instance');
    lodash.each(self, function(v, k) {
      if (lodash.isFunction(v)) return;
      // This are to prevent flicker in mobile:
      if (k == 'hasProfile') return;
      if (k == 'tab') return;
      if (k == 'noFocusedWallet') return;
      if (k == 'backgroundColor') return;
      if (k == 'loadingWallet') {
        self.loadingWallet = true;
        return;
      }
      if (!lodash.isUndefined(vanillaScope[k])) {
        self[k] = vanillaScope[k];
        return;
      }

      delete self[k];
    });
  };

  self.setFocusedWallet = function() {
    var fc = profileService.focusedClient;
    if (!fc) return;

    self.cleanInstance();
    self.loadingWallet = true;
    self.setSpendUnconfirmed();

    $timeout(function() {
      $rootScope.$apply();
      self.hasProfile = true;
      self.noFocusedWallet = false;
      self.onGoingProcess = {};

      // Credentials Shortcuts
      self.m = fc.credentials.m;
      self.n = fc.credentials.n;
      self.network = fc.credentials.network;
      self.copayerId = fc.credentials.copayerId;
      self.copayerName = fc.credentials.copayerName;
      self.requiresMultipleSignatures = fc.credentials.m > 1;
      self.isShared = fc.credentials.n > 1;
      self.walletName = fc.credentials.walletName;
      self.walletId = fc.credentials.walletId;
      self.isComplete = fc.isComplete();
      self.canSign = fc.canSign();
      self.isPrivKeyExternal = fc.isPrivKeyExternal();
      self.isPrivKeyEncrypted = fc.isPrivKeyEncrypted();
      self.externalSource = fc.getPrivKeyExternalSourceName();
      self.account = fc.credentials.account;
      self.incorrectDerivation = fc.incorrectDerivation;

      if (self.externalSource == 'trezor')
        self.account++;

      self.txps = [];
      self.copayers = [];
      self.updateColor();
      self.updateAlias();
      self.setAddressbook();

      self.initGlidera();
      self.initCoinbase();

      self.setCustomBWSFlag();

      if (!self.isComplete) {
        $log.debug('Wallet not complete BEFORE update... redirecting');
        go.path('copayers');
      } else {
        if (go.is('copayers')) {
          $log.debug('Wallet Complete BEFORE update... redirect to home');
          go.walletHome();
        }
      }

      walletService.isBackupNeeded(fc, function(needsBackup) {
        self.needsBackup = needsBackup;
        self.openWallet(function() {
          if (!self.isComplete) {
            $log.debug('Wallet not complete after update... redirecting');
            go.path('copayers');
          } else {
            if (go.is('copayers')) {
              $log.debug('Wallet Complete after update... redirect to home');
              go.walletHome();
            }
          }
        });
      });
    });
  };

  self.setCustomBWSFlag = function() {
    var defaults = configService.getDefaults();
    var config = configService.getSync();

    self.usingCustomBWS = config.bwsFor && config.bwsFor[self.walletId] && (config.bwsFor[self.walletId] != defaults.bws.url);
  };

  self.setTab = function(tab, reset, tries, switchState) {
    tries = tries || 0;

    // check if the whole menu item passed
    if (typeof tab == 'object') {
      if (tab.open) {
        if (tab.link) {
          self.tab = tab.link;
        }
        tab.open();
        return;
      } else {
        return self.setTab(tab.link, reset, tries, switchState);
      }
    }
    if (self.tab === tab && !reset)
      return;

    if (!document.getElementById('menu-' + tab) && ++tries < 5) {
      return $timeout(function() {
        self.setTab(tab, reset, tries, switchState);
      }, 300);
    }

    if (!self.tab || !go.is('walletHome'))
      self.tab = 'walletHome';

    var changeTab = function() {
      if (document.getElementById(self.tab)) {
        document.getElementById(self.tab).className = 'tab-out tab-view ' + self.tab;
        var old = document.getElementById('menu-' + self.tab);
        if (old) {
          old.className = '';
        }
      }

      if (document.getElementById(tab)) {
        document.getElementById(tab).className = 'tab-in  tab-view ' + tab;
        var newe = document.getElementById('menu-' + tab);
        if (newe) {
          newe.className = 'active';
        }
      }

      self.tab = tab;
      $rootScope.$emit('Local/TabChanged', tab);
    };

    if (switchState && !go.is('walletHome')) {
      go.path('walletHome', function() {
        changeTab();
      });
      return;
    }

    changeTab();
  };

  self._updateRemotePreferencesFor = function(clients, prefs, cb) {
    var client = clients.shift();

    if (!client)
      return cb();

    $log.debug('Saving remote preferences', client.credentials.walletName, prefs);
    client.savePreferences(prefs, function(err) {
      // we ignore errors here
      if (err) $log.warn(err);

      self._updateRemotePreferencesFor(clients, prefs, cb);
    });
  };

  self.updateRemotePreferences = function(opts, cb) {
    var prefs = opts.preferences || {};
    var fc = profileService.focusedClient;

    // Update this JIC.
    var config = configService.getSync().wallet.settings;

    //prefs.email  (may come from arguments)
    prefs.language = self.defaultLanguageIsoCode;
    prefs.unit = config.unitCode;

    var clients = [];
    if (opts.saveAll) {
      clients = lodash.values(profileService.walletClients);
    } else {
      clients = [fc];
    };

    self._updateRemotePreferencesFor(clients, prefs, function(err) {
      if (err) return cb(err);
      if (!fc) return cb();

      fc.getPreferences(function(err, preferences) {
        if (err) {
          return cb(err);
        }
        self.preferences = preferences;
        return cb();
      });
    });
  };

  var _walletStatusHash = function(walletStatus) {
    var bal;
    if (walletStatus) {
      bal = walletStatus.balance.totalAmount;
    } else {
      bal = self.totalBalanceSat;
    }
    return bal;
  };

  self.updateAll = function(opts, initStatusHash, tries) {
    tries = tries || 0;
    opts = opts || {};
    var fc = profileService.focusedClient;
    if (!fc) return;

    var walletId = fc.credentials.walletId

    if (opts.untilItChanges && lodash.isUndefined(initStatusHash)) {
      initStatusHash = _walletStatusHash();
      $log.debug('Updating status until it changes. initStatusHash:' + initStatusHash)
    }
    var get = function(cb) {
      if (opts.walletStatus)
        return cb(null, opts.walletStatus);
      else {
        self.updateError = false;
        return fc.getStatus({
          twoStep: true
        }, function(err, ret) {
          if (err) {
            self.updateError = bwsError.msg(err, gettext('Could not update Wallet'));
          } else {
            if (!opts.quiet)
              self.setOngoingProcess('scanning', ret.wallet.scanStatus == 'running');
          }
          return cb(err, ret);
        });
      }
    };

    // If not untilItChanges...trigger history update now
    if (opts.triggerTxUpdate && !opts.untilItChanges) {
      $timeout(function() {
        self.debounceUpdateHistory();
      }, 1);
    }

    $timeout(function() {

      if (!opts.quiet)
        self.setOngoingProcess('updatingStatus', true);

      $log.debug('Updating Status:', fc.credentials.walletName, tries);
      get(function(err, walletStatus) {
        var currentStatusHash = _walletStatusHash(walletStatus);
        $log.debug('Status update. hash:' + currentStatusHash + ' Try:' + tries);
        if (!err && opts.untilItChanges && initStatusHash == currentStatusHash && tries < 7 && walletId == profileService.focusedClient.credentials.walletId) {
          return $timeout(function() {
            $log.debug('Retrying update... Try:' + tries)
            return self.updateAll({
              walletStatus: null,
              untilItChanges: true,
              triggerTxUpdate: opts.triggerTxUpdate,
            }, initStatusHash, ++tries);
          }, 1400 * tries);
        }

        if (walletId != profileService.focusedClient.credentials.walletId)
          return;

        if (!opts.quiet)
          self.setOngoingProcess('updatingStatus', false);

        if (err) {
          self.handleError(err);
          return;
        }
        $log.debug('Wallet Status:', walletStatus);
        self.setPendingTxps(walletStatus.pendingTxps);

        // Status Shortcuts
        self.walletName = walletStatus.wallet.name;
        self.walletSecret = walletStatus.wallet.secret;
        self.walletStatus = walletStatus.wallet.status;
        self.walletScanStatus = walletStatus.wallet.scanStatus;
        self.copayers = walletStatus.wallet.copayers;
        self.preferences = walletStatus.preferences;
        self.setBalance(walletStatus.balance);
        self.otherWallets = lodash.filter(profileService.getWallets(self.network), function(w) {
          return w.id != self.walletId;
        });

        // Notify external addons or plugins
        $rootScope.$emit('Local/BalanceUpdated', walletStatus.balance);
        $rootScope.$apply();

        if (opts.triggerTxUpdate && opts.untilItChanges) {
          $timeout(function() {
            self.debounceUpdateHistory();
          }, 1);
        } else {
          self.loadingWallet = false;
        }

        if (opts.cb) return opts.cb();
      });
    });
  };

  self.setSpendUnconfirmed = function(spendUnconfirmed) {
    self.spendUnconfirmed = spendUnconfirmed || configService.getSync().wallet.spendUnconfirmed;
  };

  self.updateBalance = function() {
    var fc = profileService.focusedClient;
    $timeout(function() {
      self.setOngoingProcess('updatingBalance', true);
      $log.debug('Updating Balance');
      fc.getBalance(function(err, balance) {
        self.setOngoingProcess('updatingBalance', false);
        if (err) {
          self.handleError(err);
          return;
        }
        $log.debug('Wallet Balance:', balance);
        self.setBalance(balance);
      });
    });
  };

  self.updatePendingTxps = function() {
    var fc = profileService.focusedClient;
    $timeout(function() {
      self.setOngoingProcess('updatingPendingTxps', true);
      $log.debug('Updating PendingTxps');
      fc.getTxProposals({}, function(err, txps) {
        self.setOngoingProcess('updatingPendingTxps', false);
        if (err) {
          self.handleError(err);
        } else {
          $log.debug('Wallet PendingTxps:', txps);
          self.setPendingTxps(txps);
        }
        $rootScope.$apply();
      });
    });
  };

  // This handles errors from BWS/index which normally
  // trigger from async events (like updates).
  // Debounce function avoids multiple popups
  var _handleError = function(err) {
    $log.warn('Client ERROR: ', err);
    if (err instanceof errors.NOT_AUTHORIZED) {
      self.notAuthorized = true;
      go.walletHome();
    } else if (err instanceof errors.NOT_FOUND) {
      self.showErrorPopup(gettext('Could not access Wallet Service: Not found'));
    } else {
      var msg = ""
      $scope.$emit('Local/ClientError', (err.error ? err.error : err));
      var msg = bwsError.msg(err, gettext('Error at Wallet Service'));
      self.showErrorPopup(msg);
    }
  };

  self.handleError = lodash.debounce(_handleError, 1000);

  self.openWallet = function(cb) {
    var fc = profileService.focusedClient;
    $timeout(function() {
      $rootScope.$apply();
      self.setOngoingProcess('openingWallet', true);
      self.updateError = false;
      fc.openWallet(function(err, walletStatus) {
        self.setOngoingProcess('openingWallet', false);
        if (err) {
          self.updateError = true;
          self.handleError(err);
          return;
        }
        $log.debug('Wallet Opened');

        self.updateAll(lodash.isObject(walletStatus) ? {
          walletStatus: walletStatus,
          cb: cb,
        } : {
          cb: cb
        });
        $rootScope.$apply();
      });
    });
  };

  self.setPendingTxps = function(txps) {
    self.pendingTxProposalsCountForUs = 0;
    var now = Math.floor(Date.now() / 1000);

    /* Uncomment to test multiple outputs */
    /*
    var txp = {
      message: 'test multi-output',
      fee: 1000,
      createdOn: new Date() / 1000,
      outputs: []
    };
    function addOutput(n) {
      txp.outputs.push({
        amount: 600,
        toAddress: '2N8bhEwbKtMvR2jqMRcTCQqzHP6zXGToXcK',
        message: 'output #' + (Number(n) + 1)
      });
    };
    lodash.times(150, addOutput);
    txps.push(txp);
    */

    lodash.each(txps, function(tx) {

      tx = txFormatService.processTx(tx);

      // no future transactions...
      if (tx.createdOn > now)
        tx.createdOn = now;

      var action = lodash.find(tx.actions, {
        copayerId: self.copayerId
      });

      if (!action && tx.status == 'pending') {
        tx.pendingForUs = true;
      }

      if (action && action.type == 'accept') {
        tx.statusForUs = 'accepted';
      } else if (action && action.type == 'reject') {
        tx.statusForUs = 'rejected';
      } else {
        tx.statusForUs = 'pending';
      }

      if (!tx.deleteLockTime)
        tx.canBeRemoved = true;

      if (tx.creatorId != self.copayerId) {
        self.pendingTxProposalsCountForUs = self.pendingTxProposalsCountForUs + 1;
      }
      addonManager.formatPendingTxp(tx);
    });
    self.txps = txps;
  };

  var SAFE_CONFIRMATIONS = 6;

  self.processNewTxs = function(txs) {
    var config = configService.getSync().wallet.settings;
    var now = Math.floor(Date.now() / 1000);
    var txHistoryUnique = {};
    var ret = [];
    self.hasUnsafeConfirmed = false;

    lodash.each(txs, function(tx) {
      tx = txFormatService.processTx(tx);

      // no future transactions...
      if (tx.time > now)
        tx.time = now;

      if (tx.confirmations >= SAFE_CONFIRMATIONS) {
        tx.safeConfirmed = SAFE_CONFIRMATIONS + '+';
      } else {
        tx.safeConfirmed = false;
        self.hasUnsafeConfirmed = true;
      }

      if (!txHistoryUnique[tx.txid]) {
        ret.push(tx);
        txHistoryUnique[tx.txid] = true;
      } else {
        $log.debug('Ignoring duplicate TX in history: ' + tx.txid)
      }
    });

    return ret;
  };

  self.updateAlias = function() {
    var config = configService.getSync();
    config.aliasFor = config.aliasFor || {};
    self.alias = config.aliasFor[self.walletId];
    var fc = profileService.focusedClient;
    fc.alias = self.alias;
  };

  self.updateColor = function() {
    var config = configService.getSync();
    config.colorFor = config.colorFor || {};
    self.backgroundColor = config.colorFor[self.walletId] || '#4A90E2';
    var fc = profileService.focusedClient;
    fc.backgroundColor = self.backgroundColor;
    if (isCordova && StatusBar.isVisible) {
      StatusBar.backgroundColorByHexString(fc.backgroundColor);
    }
  };

  self.setBalance = function(balance) {
    if (!balance) return;
    var config = configService.getSync().wallet.settings;
    var COIN = 1e8;

    // Address with Balance
    self.balanceByAddress = balance.byAddress;

    // Spend unconfirmed funds
    if (self.spendUnconfirmed) {
      self.totalBalanceSat = balance.totalAmount;
      self.lockedBalanceSat = balance.lockedAmount;
      self.availableBalanceSat = balance.availableAmount;
      self.totalBytesToSendMax = balance.totalBytesToSendMax;
      self.pendingAmount = null;
    } else {
      self.totalBalanceSat = balance.totalConfirmedAmount;
      self.lockedBalanceSat = balance.lockedConfirmedAmount;
      self.availableBalanceSat = balance.availableConfirmedAmount;
      self.totalBytesToSendMax = balance.totalBytesToSendConfirmedMax;
      self.pendingAmount = balance.totalAmount - balance.totalConfirmedAmount;
    }

    // Selected unit
    self.unitToSatoshi = config.unitToSatoshi;
    self.satToUnit = 1 / self.unitToSatoshi;
    self.unitName = config.unitName;

    //STR
    self.totalBalanceStr = profileService.formatAmount(self.totalBalanceSat) + ' ' + self.unitName;
    self.lockedBalanceStr = profileService.formatAmount(self.lockedBalanceSat) + ' ' + self.unitName;
    self.availableBalanceStr = profileService.formatAmount(self.availableBalanceSat) + ' ' + self.unitName;

    if (self.pendingAmount) {
      self.pendingAmountStr = profileService.formatAmount(self.pendingAmount) + ' ' + self.unitName;
    } else {
      self.pendingAmountStr = null;
    }

    self.alternativeName = config.alternativeName;
    self.alternativeIsoCode = config.alternativeIsoCode;

    // Check address
    addressService.isUsed(self.walletId, balance.byAddress, function(err, used) {
      if (used) {
        $log.debug('Address used. Creating new');
        $rootScope.$emit('Local/AddressIsUsed');
      }
    });

    rateService.whenAvailable(function() {

      var totalBalanceAlternative = rateService.toFiat(self.totalBalanceSat, self.alternativeIsoCode);
      var lockedBalanceAlternative = rateService.toFiat(self.lockedBalanceSat, self.alternativeIsoCode);
      var alternativeConversionRate = rateService.toFiat(100000000, self.alternativeIsoCode);

      self.totalBalanceAlternative = $filter('noFractionNumber')(totalBalanceAlternative, 2);
      self.lockedBalanceAlternative = $filter('noFractionNumber')(lockedBalanceAlternative, 2);
      self.alternativeConversionRate = $filter('noFractionNumber')(alternativeConversionRate, 2);

      self.alternativeBalanceAvailable = true;

      self.isRateAvailable = true;
      $rootScope.$apply();
    });

    if (!rateService.isAvailable()) {
      $rootScope.$apply();
    }
  };

  self.csvHistory = function() {

    function saveFile(name, data) {
      var chooser = document.querySelector(name);
      chooser.addEventListener("change", function(evt) {
        var fs = require('fs');
        fs.writeFile(this.value, data, function(err) {
          if (err) {
            $log.debug(err);
          }
        });
      }, false);
      chooser.click();
    }

    function formatDate(date) {
      var dateObj = new Date(date);
      if (!dateObj) {
        $log.debug('Error formating a date');
        return 'DateError'
      }
      if (!dateObj.toJSON()) {
        return '';
      }

      return dateObj.toJSON();
    }

    function formatString(str) {
      if (!str) return '';

      if (str.indexOf('"') !== -1) {
        //replace all
        str = str.replace(new RegExp('"', 'g'), '\'');
      }

      //escaping commas
      str = '\"' + str + '\"';

      return str;
    }

    var step = 6;
    var unique = {};

    function getHistory(cb) {
      storageService.getTxHistory(c.walletId, function(err, txs) {
        if (err) return cb(err);

        var txsFromLocal = [];
        try {
          txsFromLocal = JSON.parse(txs);
        } catch (ex) {
          $log.warn(ex);
        }

        allTxs.push(txsFromLocal);
        return cb(null, lodash.flatten(allTxs));
      });
    }

    if (isCordova) {
      $log.info('CSV generation not available in mobile');
      return;
    }
    var isNode = nodeWebkit.isDefined();
    var fc = profileService.focusedClient;
    var c = fc.credentials;
    if (!fc.isComplete()) return;
    var self = this;
    var allTxs = [];

    $log.debug('Generating CSV from History');
    self.setOngoingProcess('generatingCSV', true);

    getHistory(function(err, txs) {
      self.setOngoingProcess('generatingCSV', false);
      if (err) {
        self.handleError(err);
      } else {
        $log.debug('Wallet Transaction History:', txs);

        self.satToUnit = 1 / self.unitToSatoshi;
        var data = txs;
        var satToBtc = 1 / 100000000;
        self.csvContent = [];
        self.csvFilename = 'Copay-' + (self.alias || self.walletName) + '.csv';
        self.csvHeader = ['Date', 'Destination', 'Note', 'Amount', 'Currency', 'Txid', 'Creator', 'Copayers'];

        var _amount, _note, _copayers, _creator;
        data.forEach(function(it, index) {
          var amount = it.amount;

          if (it.action == 'moved')
            amount = 0;

          _copayers = '';
          _creator = '';

          if (it.actions && it.actions.length > 1) {
            for (var i = 0; i < it.actions.length; i++) {
              _copayers += it.actions[i].copayerName + ':' + it.actions[i].type + ' - ';
            }
            _creator = (it.creatorName && it.creatorName != 'undefined') ? it.creatorName : '';
          }
          _copayers = formatString(_copayers);
          _creator = formatString(_creator);
          _amount = (it.action == 'sent' ? '-' : '') + (amount * satToBtc).toFixed(8);
          _note = formatString((it.message ? it.message : ''));

          if (it.action == 'moved')
            _note += ' Moved:' + (it.amount * satToBtc).toFixed(8)

          self.csvContent.push({
            'Date': formatDate(it.time * 1000),
            'Destination': formatString(it.addressTo),
            'Note': _note,
            'Amount': _amount,
            'Currency': 'BTC',
            'Txid': it.txid,
            'Creator': _creator,
            'Copayers': _copayers
          });

          if (it.fees && (it.action == 'moved' || it.action == 'sent')) {
            var _fee = (it.fees * satToBtc).toFixed(8)
            self.csvContent.push({
              'Date': formatDate(it.time * 1000),
              'Destination': 'Bitcoin Network Fees',
              'Note': '',
              'Amount': '-' + _fee,
              'Currency': 'BTC',
              'Txid': '',
              'Creator': '',
              'Copayers': ''
            });
          }
        });
        return;
      }
    });
  };

  self.removeAndMarkSoftConfirmedTx = function(txs) {
    return lodash.filter(txs, function(tx) {
      if (tx.confirmations >= SOFT_CONFIRMATION_LIMIT)
        return tx;
      tx.recent = true;
    });
  }

  self.getSavedTxs = function(walletId, cb) {

    storageService.getTxHistory(walletId, function(err, txs) {
      if (err) return cb(err);

      var localTxs = [];

      if (!txs) {
        return cb(null, localTxs);
      }

      try {
        localTxs = JSON.parse(txs);
      } catch (ex) {
        $log.warn(ex);
      }
      return cb(null, lodash.compact(localTxs));
    });
  }

  self.updateLocalTxHistory = function(client, cb) {
    var FIRST_LIMIT = 5;
    var LIMIT = 50;
    var requestLimit = FIRST_LIMIT;
    var walletId = client.credentials.walletId;
    var config = configService.getSync().wallet.settings;

    var fixTxsUnit = function(txs) {
      if (!txs || !txs[0] || !txs[0].amountStr) return;

      var cacheUnit = txs[0].amountStr.split(' ')[1];

      if (cacheUnit == config.unitName)
        return;

      var name = ' ' + config.unitName;

      $log.debug('Fixing Tx Cache Unit to:' + name)
      lodash.each(txs, function(tx) {

        tx.amountStr = profileService.formatAmount(tx.amount, config.unitName) + name;
        tx.feeStr = profileService.formatAmount(tx.fees, config.unitName) + name;
      });
    };

    self.getSavedTxs(walletId, function(err, txsFromLocal) {
      if (err) return cb(err);

      fixTxsUnit(txsFromLocal);

      var confirmedTxs = self.removeAndMarkSoftConfirmedTx(txsFromLocal);
      var endingTxid = confirmedTxs[0] ? confirmedTxs[0].txid : null;

      // First update
      if (walletId == profileService.focusedClient.credentials.walletId) {
        self.completeHistory = txsFromLocal;
        self.setCompactTxHistory();
      }

      if (historyUpdateInProgress[walletId])
        return;

      historyUpdateInProgress[walletId] = true;

      function getNewTxs(newTxs, skip, i_cb) {
        self.getTxsFromServer(client, skip, endingTxid, requestLimit, function(err, res, shouldContinue) {
          if (err) return i_cb(err);

          newTxs = newTxs.concat(lodash.compact(res));
          skip = skip + requestLimit;

          $log.debug('Syncing TXs. Got:' + newTxs.length + ' Skip:' + skip, ' EndingTxid:', endingTxid, ' Continue:', shouldContinue);

          if (!shouldContinue) {
            newTxs = self.processNewTxs(newTxs);
            $log.debug('Finished Sync: New / soft confirmed Txs: ' + newTxs.length);
            return i_cb(null, newTxs);
          }

          requestLimit = LIMIT;
          getNewTxs(newTxs, skip, i_cb);

          // Progress update
          if (walletId == profileService.focusedClient.credentials.walletId) {
            self.txProgress = newTxs.length;
            if (self.completeHistory < FIRST_LIMIT && txsFromLocal.length == 0) {
              $log.debug('Showing partial history');
              var newHistory = self.processNewTxs(newTxs);
              newHistory = lodash.compact(newHistory.concat(confirmedTxs));
              self.completeHistory = newHistory;
              self.setCompactTxHistory();
            }
            $timeout(function() {
              $rootScope.$apply();
            });
          }
        });
      };

      getNewTxs([], 0, function(err, txs) {
        if (err) return cb(err);

        var newHistory = lodash.uniq(lodash.compact(txs.concat(confirmedTxs)), function(x) {
          return x.txid;
        });
        var historyToSave = JSON.stringify(newHistory);

        lodash.each(txs, function(tx) {
          tx.recent = true;
        })

        $log.debug('Tx History synced. Total Txs: ' + newHistory.length);

        // Final update
        if (walletId == profileService.focusedClient.credentials.walletId) {
          self.completeHistory = newHistory;
          self.setCompactTxHistory();
        }

        return storageService.setTxHistory(historyToSave, walletId, function() {
          $log.debug('Tx History saved.');

          return cb();
        });
      });
    });
  }

  self.showMore = function() {
    $timeout(function() {
      if (self.isSearching) {
        self.txHistorySearchResults = self.result.slice(0, self.nextTxHistory);
        $log.debug('Total txs: ', self.txHistorySearchResults.length + '/' + self.result.length);
        if (self.txHistorySearchResults.length >= self.result.length)
          self.historyShowMore = false;
      } else {
        self.txHistory = self.completeHistory.slice(0, self.nextTxHistory);
        self.txHistorySearchResults = self.txHistory;
        $log.debug('Total txs: ', self.txHistorySearchResults.length + '/' + self.completeHistory.length);
        if (self.txHistorySearchResults.length >= self.completeHistory.length)
          self.historyShowMore = false;
      }
      self.nextTxHistory += self.historyShowMoreLimit;
    }, 100);
  };

  self.startSearch = function() {
    self.isSearching = true;
    self.txHistorySearchResults = [];
    self.result = [];
    self.historyShowMore = false;
    self.nextTxHistory = self.historyShowMoreLimit;
  }

  self.cancelSearch = function() {
    self.isSearching = false;
    self.result = [];
    self.setCompactTxHistory();
  }

  self.updateSearchInput = function(search) {
    self.search = search;
    if (isCordova)
      window.plugins.toast.hide();
    self.throttleSearch();
  }

  self.throttleSearch = lodash.throttle(function() {

    function filter(search) {
      self.result = [];

      function computeSearchableString(tx) {
        var addrbook = '';
        if (tx.addressTo && self.addressbook && self.addressbook[tx.addressTo]) addrbook = self.addressbook[tx.addressTo] || '';
        var searchableDate = computeSearchableDate(new Date(tx.time * 1000));
        var message = tx.message ? tx.message : '';
        var addressTo = tx.addressTo ? tx.addressTo : '';
        return ((tx.amountStr + message + addressTo + addrbook + searchableDate).toString()).toLowerCase();
      }

      function computeSearchableDate(date) {
        var day = ('0' + date.getDate()).slice(-2).toString();
        var month = ('0' + (date.getMonth() + 1)).slice(-2).toString();
        var year = date.getFullYear();
        return [month, day, year].join('/');
      };

      if (lodash.isEmpty(search)) {
        self.historyShowMore = false;
        return [];
      }
      self.result = lodash.filter(self.completeHistory, function(tx) {
        if (!tx.searcheableString) tx.searcheableString = computeSearchableString(tx);
        return lodash.includes(tx.searcheableString, search.toLowerCase());
      });

      if (self.result.length > self.historyShowLimit) self.historyShowMore = true;
      else self.historyShowMore = false;

      return self.result;
    };

    self.txHistorySearchResults = filter(self.search).slice(0, self.historyShowLimit);
    if (isCordova)
      window.plugins.toast.showShortBottom(gettextCatalog.getString('Matches: ' + self.result.length));

    $timeout(function() {
      $rootScope.$apply();
    });

  }, 1000);

  self.getTxsFromServer = function(client, skip, endingTxid, limit, cb) {
    var res = [];

    client.getTxHistory({
      skip: skip,
      limit: limit
    }, function(err, txsFromServer) {
      if (err) return cb(err);

      if (!txsFromServer.length)
        return cb();

      var res = lodash.takeWhile(txsFromServer, function(tx) {
        return tx.txid != endingTxid;
      });

      return cb(null, res, res.length == limit);
    });
  };

  self.updateHistory = function() {
    var fc = profileService.focusedClient;
    if (!fc) return;
    var walletId = fc.credentials.walletId;

    if (!fc.isComplete()) {
      return;
    }

    $log.debug('Updating Transaction History');
    self.txHistoryError = false;
    self.updatingTxHistory = true;

    $timeout(function() {
      self.updateLocalTxHistory(fc, function(err) {
        historyUpdateInProgress[walletId] = self.updatingTxHistory = false;
        self.loadingWallet = false;
        self.txProgress = 0;
        if (err)
          self.txHistoryError = true;

        $timeout(function() {
          self.newTx = false
        }, 1000);

        $rootScope.$apply();
      });
    });
  };

  self.setCompactTxHistory = function() {
    self.isSearching = false;
    self.nextTxHistory = self.historyShowMoreLimit;
    self.txHistory = self.completeHistory ? self.completeHistory.slice(0, self.historyShowLimit) : null;
    self.txHistorySearchResults = self.txHistory;
    self.historyShowMore = self.completeHistory ? self.completeHistory.length > self.historyShowLimit : null;
  };

  self.debounceUpdateHistory = lodash.debounce(function() {
    self.updateHistory();
  }, 1000);

  self.throttledUpdateHistory = lodash.throttle(function() {
    self.updateHistory();
  }, 5000);

  self.showErrorPopup = function(msg, cb) {
    $log.warn('Showing err popup:' + msg);
    self.showAlert = {
      msg: msg,
      close: function() {
        self.showAlert = null;
        if (cb) return cb();
      },
    };
    $timeout(function() {
      $rootScope.$apply();
    });
  };

  self.recreate = function(cb) {
    var fc = profileService.focusedClient;
    self.setOngoingProcess('recreating', true);
    fc.recreateWallet(function(err) {
      self.notAuthorized = false;
      self.setOngoingProcess('recreating', false);

      if (err) {
        self.handleError(err);
        $rootScope.$apply();
        return;
      }

      profileService.setWalletClients();
      self.startScan(self.walletId);
    });
  };

  self.openMenu = function() {
    profileService.isDisclaimerAccepted(function(val) {
      if (val) go.swipe(true);
      else
        $log.debug('Disclaimer not accepted, cannot open menu');
    });
  };

  self.closeMenu = function() {
    go.swipe();
  };

  self.retryScan = function() {
    var self = this;
    self.startScan(self.walletId);
  }

  self.startScan = function(walletId) {
    $log.debug('Scanning wallet ' + walletId);
    var c = profileService.walletClients[walletId];
    if (!c.isComplete()) return;

    if (self.walletId == walletId)
      self.setOngoingProcess('scanning', true);

    c.startScan({
      includeCopayerBranches: true,
    }, function(err) {
      if (err && self.walletId == walletId) {
        self.setOngoingProcess('scanning', false);
        self.handleError(err);
        $rootScope.$apply();
      }
    });
  };

  self.setUxLanguage = function(cb) {
    uxLanguage.update(function(lang) {
      var userLang = lang;
      self.defaultLanguageIsoCode = userLang;
      self.defaultLanguageName = uxLanguage.getName(userLang);
      if (cb) return cb();
    });
  };

  self.initGlidera = function(accessToken) {
    self.glideraEnabled = configService.getSync().glidera.enabled;
    self.glideraTestnet = configService.getSync().glidera.testnet;
    var network = self.glideraTestnet ? 'testnet' : 'livenet';

    self.glideraToken = null;
    self.glideraError = null;
    self.glideraPermissions = null;
    self.glideraEmail = null;
    self.glideraPersonalInfo = null;
    self.glideraTxs = null;
    self.glideraStatus = null;

    if (!self.glideraEnabled) return;

    glideraService.setCredentials(network);

    var getToken = function(cb) {
      if (accessToken) {
        cb(null, accessToken);
      } else {
        storageService.getGlideraToken(network, cb);
      }
    };

    getToken(function(err, accessToken) {
      if (err || !accessToken) return;
      else {
        self.glideraLoading = 'Connecting to Glidera...';
        glideraService.getAccessTokenPermissions(accessToken, function(err, p) {
          self.glideraLoading = null;
          if (err) {
            self.glideraError = err;
          } else {
            self.glideraToken = accessToken;
            self.glideraPermissions = p;
            self.updateGlidera({
              fullUpdate: true
            });
          }
        });
      }
    });
  };

  self.updateGlidera = function(opts) {
    if (!self.glideraToken || !self.glideraPermissions) return;
    var accessToken = self.glideraToken;
    var permissions = self.glideraPermissions;

    opts = opts || {};

    glideraService.getStatus(accessToken, function(err, data) {
      self.glideraStatus = data;
    });

    glideraService.getLimits(accessToken, function(err, limits) {
      self.glideraLimits = limits;
    });

    if (permissions.transaction_history) {
      self.glideraLoadingHistory = 'Getting Glidera transactions...';
      glideraService.getTransactions(accessToken, function(err, data) {
        self.glideraLoadingHistory = null;
        self.glideraTxs = data;
      });
    }

    if (permissions.view_email_address && opts.fullUpdate) {
      self.glideraLoadingEmail = 'Getting Glidera Email...';
      glideraService.getEmail(accessToken, function(err, data) {
        self.glideraLoadingEmail = null;
        self.glideraEmail = data.email;
      });
    }
    if (permissions.personal_info && opts.fullUpdate) {
      self.glideraLoadingPersonalInfo = 'Getting Glidera Personal Information...';
      glideraService.getPersonalInfo(accessToken, function(err, data) {
        self.glideraLoadingPersonalInfo = null;
        self.glideraPersonalInfo = data;
      });
    }

  };

  self.initCoinbase = function(accessToken) {
    self.coinbaseEnabled = configService.getSync().coinbase.enabled;
    self.coinbaseTestnet = configService.getSync().coinbase.testnet;
    var network = self.coinbaseTestnet ? 'testnet' : 'livenet';

    self.coinbaseToken = null;
    self.coinbaseError = null;
    self.coinbasePermissions = null;
    self.coinbaseEmail = null;
    self.coinbasePersonalInfo = null;
    self.coinbaseTxs = null;
    self.coinbaseStatus = null;

    if (!self.coinbaseEnabled) return;

    coinbaseService.setCredentials(network);

    var getToken = function(cb) {
      if (accessToken) {
        cb(null, accessToken);
      } else {
        storageService.getCoinbaseToken(network, cb);
      }
    };

    getToken(function(err, accessToken) {
      if (err || !accessToken) return;
      else {
        self.coinbaseLoading = 'Getting primary account...';
        coinbaseService.getAccounts(accessToken, function(err, a) {
          self.coinbaseLoading = null;
          if (err) {
            self.coinbaseError = err;
            if (err.errors[0] && err.errors[0].id == 'expired_token') {
              self.refreshCoinbaseToken();
            }
          } else {
            self.coinbaseToken = accessToken;
            lodash.each(a.data, function(account) {
              if (account.primary && account.type == 'wallet') {
                self.coinbaseAccount = account;
                self.updateCoinbase();
              }
            });
          }
        });
      }
    });
  };

  self.updateCoinbase = lodash.debounce(function(opts) {
    if (!self.coinbaseToken || !self.coinbaseAccount) return;
    var accessToken = self.coinbaseToken;
    var accountId = self.coinbaseAccount.id;

    opts = opts || {};

    if (opts.updateAccount) {
      coinbaseService.getAccount(accessToken, accountId, function(err, a) {
        if (err) {
          self.coinbaseError = err;
          if (err.errors[0] && err.errors[0].id == 'expired_token') {
            self.refreshCoinbaseToken();
          }
          return;
        }
        self.coinbaseAccount = a.data;
      });
    }

    coinbaseService.getCurrentUser(accessToken, function(err, u) {
      if (err) {
        self.coinbaseError = err;
        if (err.errors[0] && err.errors[0].id == 'expired_token') {
          self.refreshCoinbaseToken();
        }
        return;
      }
      self.coinbaseUser = u.data;
    });

    coinbaseService.getPendingTransactions(function(err, txs) {
      self.coinbasePendingTransactions = lodash.isEmpty(txs) ? null : txs;
      lodash.forEach(txs, function(dataFromStorage, txId) {
        if ((dataFromStorage.type == 'sell' && dataFromStorage.status == 'completed') ||
            (dataFromStorage.type == 'buy' && dataFromStorage.status == 'completed') ||
            dataFromStorage.status == 'error' ||
            (dataFromStorage.type == 'send' && dataFromStorage.status == 'completed')) return;
        coinbaseService.getTransaction(accessToken, accountId, txId, function(err, tx) {
          if (err) {
            if (err.errors[0] && err.errors[0].id == 'expired_token') {
              self.refreshCoinbaseToken();
              return;
            }
            coinbaseService.savePendingTransaction(dataFromStorage, {status: 'error', error: err}, function(err) {
              if (err) $log.debug(err);
            });
            return;
          }
          _updateCoinbasePendingTransactions(dataFromStorage, tx.data);
          self.coinbasePendingTransactions[txId] = dataFromStorage;
          if (tx.data.type == 'send' && tx.data.status == 'completed' && tx.data.from) {
            coinbaseService.sellPrice(accessToken, dataFromStorage.sell_price_currency, function(err, s) {
              if (err) {
                if (err.errors[0] && err.errors[0].id == 'expired_token') {
                  self.refreshCoinbaseToken();
                  return;
                }
                coinbaseService.savePendingTransaction(dataFromStorage, {status: 'error', error: err}, function(err) {
                  if (err) $log.debug(err);
                });
                return;
              }
              var newSellPrice = s.data.amount;
              var variance = Math.abs((newSellPrice - dataFromStorage.sell_price_amount) / dataFromStorage.sell_price_amount * 100);
              if (variance < dataFromStorage.price_sensitivity.value) {
                self.sellPending(tx.data);
              } else {
                var error = {errors: [{ message: 'Price falls over the selected percentage' }]};
                coinbaseService.savePendingTransaction(dataFromStorage, {status: 'error', error: error}, function(err) {
                  if (err) $log.debug(err);
                });
              }
            });
          } else if (tx.data.type == 'buy' && tx.data.status == 'completed' && tx.data.buy) {
            self.sendToCopay(dataFromStorage);
          } else {
            coinbaseService.savePendingTransaction(dataFromStorage, {}, function(err) {
              if (err) $log.debug(err);
            });
          }
        });
      });
    });

  }, 1000);

  var _updateCoinbasePendingTransactions = function (obj/*, …*/) {
    for (var i=1; i<arguments.length; i++) {
      for (var prop in arguments[i]) {
        var val = arguments[i][prop];
        if (typeof val == "object")
          _updateCoinbasePendingTransactions(obj[prop], val);
        else
          obj[prop] = val ? val : obj[prop];
      }
    }
    return obj;
  };

  self.refreshCoinbaseToken = function() {
    var network = self.coinbaseTestnet ? 'testnet' : 'livenet';
    storageService.getCoinbaseRefreshToken(network, function(err, refreshToken) {
      if (!refreshToken) return;
      coinbaseService.refreshToken(refreshToken, function(err, data) {
        if (err) {
          self.coinbaseError = err;
        } else if (data && data.access_token && data.refresh_token) {
          storageService.setCoinbaseToken(network, data.access_token, function() {
            storageService.setCoinbaseRefreshToken(network, data.refresh_token, function() {
              $timeout(function() {
                self.initCoinbase(data.access_token);
              }, 100);
            });
          });
        }
      });
    });
  };

  self.sendToCopay = function(tx) {
    if (!tx) return;
    var data = {
      to: tx.toAddr,
      amount: tx.amount.amount,
      currency: tx.amount.currency,
      description: 'To Copay Wallet'
    };
    coinbaseService.sendTo(self.coinbaseToken, self.coinbaseAccount.id, data, function(err, res) {
      if (err) {
        if (err.errors[0] && err.errors[0].id == 'expired_token') {
          self.refreshCoinbaseToken();
          return;
        }
        coinbaseService.savePendingTransaction(tx, {status: 'error', error: err}, function(err) {
          if (err) $log.debug(err);
        });
      } else {
        if (!res.data.id) {
          coinbaseService.savePendingTransaction(tx, {status: 'error', error: err}, function(err) {
            if (err) $log.debug(err);
          });
          return;
        }
        coinbaseService.getTransaction(self.coinbaseToken, self.coinbaseAccount.id, res.data.id, function(err, sendTx) {
          coinbaseService.savePendingTransaction(tx, {remove: true}, function(err) {
            coinbaseService.savePendingTransaction(sendTx.data, {}, function(err) {
              $timeout(function() {
                self.updateCoinbase({updateAccount: true});
              }, 1000);
            });
          });
        });
      }
    });
  };

  self.sellPending = function(tx) {
    if (!tx) return;
    var data = tx.amount;
    data['commit'] = true;
    coinbaseService.sellRequest(self.coinbaseToken, self.coinbaseAccount.id, data, function(err, res) {
      if (err) {
        if (err.errors[0] && err.errors[0].id == 'expired_token') {
          self.refreshCoinbaseToken();
          return;
        }
        coinbaseService.savePendingTransaction(tx, {status: 'error', error: err}, function(err) {
          if (err) $log.debug(err);
        });
      } else {
        if (!res.data.transaction) {
          coinbaseService.savePendingTransaction(tx, {status: 'error', error: err}, function(err) {
            if (err) $log.debug(err);
          });
          return;
        }
        coinbaseService.savePendingTransaction(tx, {remove: true}, function(err) {
          coinbaseService.getTransaction(self.coinbaseToken, self.coinbaseAccount.id, res.data.transaction.id, function(err, updatedTx) {
            coinbaseService.savePendingTransaction(updatedTx.data, {}, function(err) {
              if (err) $log.debug(err);
              $timeout(function() {
                self.updateCoinbase({updateAccount: true});
              }, 1000);
            });
          });
        });
      }
    });
  };

  self.setAddressbook = function(ab) {
    if (ab) {
      self.addressbook = ab;
      return;
    }

    addressbookService.list(function(err, ab) {
      if (err) {
        $log.error('Error getting the addressbook');
        return;
      }
      self.addressbook = ab;
    });
  };

  $rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from, fromParams) {
    self.prevState = from.name || 'walletHome';
    self.tab = 'walletHome';
  });

  $rootScope.$on('Local/ClearHistory', function(event) {
    $log.debug('The wallet transaction history has been deleted');
    self.txHistory = self.completeHistory = self.txHistorySearchResults = [];
    self.debounceUpdateHistory();
  });

  $rootScope.$on('Local/AddressbookUpdated', function(event, ab) {
    self.setAddressbook(ab);
  });

  // UX event handlers
  $rootScope.$on('Local/ColorUpdated', function(event) {
    self.updateColor();
    $timeout(function() {
      $rootScope.$apply();
    });
  });

  $rootScope.$on('Local/AliasUpdated', function(event) {
    self.updateAlias();
    $timeout(function() {
      $rootScope.$apply();
    });
  });

  $rootScope.$on('Local/SpendUnconfirmedUpdated', function(event, spendUnconfirmed) {
    self.setSpendUnconfirmed(spendUnconfirmed);
    self.updateAll();
  });

  $rootScope.$on('Local/ProfileBound', function() {
    storageService.getRemotePrefsStoredFlag(function(err, val) {
      if (err || val) return;
      self.updateRemotePreferences({
        saveAll: true
      }, function() {
        $log.debug('Remote preferences saved');
        storageService.setRemotePrefsStoredFlag(function() {});
      });
    });
  });

  $rootScope.$on('Local/LanguageSettingUpdated', function() {
    self.setUxLanguage(function() {
      self.updateRemotePreferences({
        saveAll: true
      }, function() {
        $log.debug('Remote preferences saved')
      });
    });
  });

  $rootScope.$on('Local/GlideraUpdated', function(event, accessToken) {
    self.initGlidera(accessToken);
  });

  $rootScope.$on('Local/CoinbaseUpdated', function(event, accessToken) {
    self.initCoinbase(accessToken);
  });

  $rootScope.$on('Local/GlideraTx', function(event, accessToken, permissions) {
    self.updateGlidera();
  });

  $rootScope.$on('Local/CoinbaseTx', function(event) {
    self.updateCoinbase({
      updateAccount: true
    });
  });

  $rootScope.$on('Local/GlideraError', function(event) {
    self.debouncedUpdate();
  });

  $rootScope.$on('Local/UnitSettingUpdated', function(event) {
    self.updateAll({
      triggerTxUpdate: true,
    });
    self.updateRemotePreferences({
      saveAll: true
    }, function() {
      $log.debug('Remote preferences saved')
    });
  });

  $rootScope.$on('Local/EmailSettingUpdated', function(event, email, cb) {
    self.updateRemotePreferences({
      preferences: {
        email: email || null
      },
    }, cb);
  });

  $rootScope.$on('Local/WalletCompleted', function(event, walletId) {
    var fc = profileService.focusedClient;
    if (fc && fc.credentials.walletId == walletId) {
      // reset main wallet variables
      self.setFocusedWallet();
      go.walletHome();
    }
  });

  $rootScope.$on('Local/ProfileCreated', function(event) {
    self.updateRemotePreferences({
      saveAll: true
    }, function() {
      $log.debug('Remote preferences saved');
    });
  });

  self.debouncedUpdate = lodash.throttle(function() {
    self.updateAll({
      quiet: true
    });
    self.debounceUpdateHistory();
  }, 2000, {
    leading: false,
    trailing: true
  });

  $rootScope.$on('Local/Resume', function(event) {
    $log.debug('### Resume event');
    profileService.isDisclaimerAccepted(function(v) {
      if (!v) {
        $log.debug('Disclaimer not accepted, resume to home');
        go.path('disclaimer');
      }
    });
    self.debouncedUpdate();
  });

  $rootScope.$on('Local/BackupDone', function(event, walletId) {
    self.needsBackup = false;
    $log.debug('Backup done');
    storageService.setBackupFlag(walletId || self.walletId, function(err) {
      $log.debug('Backup stored');
    });
  });

  $rootScope.$on('Local/DeviceError', function(event, err) {
    self.showErrorPopup(err, function() {
      if (self.isCordova && navigator && navigator.app) {
        navigator.app.exitApp();
      }
    });
  });

  $rootScope.$on('Local/WalletImported', function(event, walletId) {
    self.needsBackup = false;
    storageService.setBackupFlag(walletId, function() {
      $log.debug('Backup done stored');
      addressService.expireAddress(walletId, function(err) {
        $timeout(function() {
          self.txHistory = self.completeHistory = self.txHistorySearchResults = [];
          storageService.removeTxHistory(walletId, function() {
            self.startScan(walletId);
          });
        }, 500);
      });
    });
  });

  $rootScope.$on('Local/TxModal', function(event, tx) {
    self.showTx = tx;
    $timeout(function() {
      $rootScope.$apply();
    });
  });

  $rootScope.$on('NewIncomingTx', function() {
    self.newTx = true;
    self.updateAll({
      walletStatus: null,
      untilItChanges: true,
      triggerTxUpdate: true,
    });
  });

  $rootScope.$on('NewBlock', function() {
    if (self.glideraEnabled) {
      $timeout(function() {
        self.updateGlidera();
      });
    }
    if (self.coinbaseEnabled) {
      $timeout(function() {
        self.updateCoinbase();
      });
    }
    if (self.pendingAmount) {
      self.updateAll({
        walletStatus: null,
        untilItChanges: null,
        triggerTxUpdate: true,
      });
    } else if (self.hasUnsafeConfirmed) {
      $log.debug('Wallet has transactions with few confirmations. Updating.')
      if (self.network == 'testnet') {
        self.throttledUpdateHistory();
      } else {
        self.debounceUpdateHistory();
      }
    }
  });

  $rootScope.$on('BalanceUpdated', function(e, n) {
    self.setBalance(n.data);
  });

  //untilItChange TRUE
  lodash.each(['NewOutgoingTx', 'NewOutgoingTxByThirdParty'], function(eventName) {
    $rootScope.$on(eventName, function(event) {
      self.newTx = true;
      self.updateAll({
        walletStatus: null,
        untilItChanges: true,
        triggerTxUpdate: true,
      });
    });
  });

  //untilItChange FALSE
  lodash.each(['NewTxProposal', 'TxProposalFinallyRejected', 'TxProposalRemoved', 'NewOutgoingTxByThirdParty',
    'Local/GlideraTx'
  ], function(eventName) {
    $rootScope.$on(eventName, function(event) {
      self.updateAll({
        walletStatus: null,
        untilItChanges: null,
        triggerTxUpdate: true,
      });
    });
  });

  //untilItChange Maybe
  $rootScope.$on('Local/TxProposalAction', function(event, untilItChanges) {
    self.newTx = untilItChanges;
    self.updateAll({
      walletStatus: null,
      untilItChanges: untilItChanges,
      triggerTxUpdate: true,
    });
  });

  $rootScope.$on('ScanFinished', function() {
    $log.debug('Scan Finished. Updating history');
    storageService.removeTxHistory(self.walletId, function() {
      self.updateAll({
        walletStatus: null,
        triggerTxUpdate: true,
      });
    });
  });

  lodash.each(['TxProposalRejectedBy', 'TxProposalAcceptedBy'], function(eventName) {
    $rootScope.$on(eventName, function() {
      var f = function() {
        if (self.updatingStatus) {
          return $timeout(f, 200);
        };
        self.updatePendingTxps();
      };
      f();
    });
  });

  $rootScope.$on('Local/NoWallets', function(event) {

    $timeout(function() {
      self.hasProfile = true;
      self.noFocusedWallet = true;
      self.isComplete = null;
      self.walletName = null;
      self.setUxLanguage();
      profileService.isDisclaimerAccepted(function(v) {
        if (v) {
          go.path('import');
        }
      });
    });
  });

  $rootScope.$on('Local/NewFocusedWallet', function() {
    self.setUxLanguage();
    self.setFocusedWallet();
    self.updateHistory();
    storageService.getCleanAndScanAddresses(function(err, walletId) {

      if (walletId && profileService.walletClients[walletId]) {
        $log.debug('Clear last address cache and Scan ', walletId);
        addressService.expireAddress(walletId, function(err) {
          self.startScan(walletId);
        });
        storageService.removeCleanAndScanAddresses(function() {
          $rootScope.$emit('Local/NewFocusedWalletReady');
        });
      } else {
        $rootScope.$emit('Local/NewFocusedWalletReady');
      }
    });
  });

  $rootScope.$on('Local/SetTab', function(event, tab, reset) {
    self.setTab(tab, reset);
  });

  $rootScope.$on('Local/NeedsConfirmation', function(event, txp, cb) {
    self.confirmTx = {
      txp: txFormatService.processTx(txp),
      callback: function(accept) {
        self.confirmTx = null;
        return cb(accept);
      }
    };
    $timeout(function() {
      $rootScope.$apply();
    });
  });

  $rootScope.$on('Local/NeedsPassword', function(event, isSetup, cb) {
    self.askPassword = {
      isSetup: isSetup,
      callback: function(err, pass) {
        self.askPassword = null;
        return cb(err, pass);
      },
    };
    $timeout(function() {
      $rootScope.$apply();
    });
  });

  lodash.each(['NewCopayer', 'CopayerUpdated'], function(eventName) {
    $rootScope.$on(eventName, function() {
      // Re try to open wallet (will triggers)
      self.setFocusedWallet();
    });
  });

  $rootScope.$on('Local/NewEncryptionSetting', function() {
    var fc = profileService.focusedClient;
    self.isPrivKeyEncrypted = fc.isPrivKeyEncrypted();
    $timeout(function() {
      $rootScope.$apply();
    });
  });

  /* Start setup */
  lodash.assign(self, vanillaScope);
});

redpajama_set_name: RedPajamaGithub


text:
Q: How to edit the DIV which renders only runtime. which is not present in HTML page? I have a small web app which has  tag which renders the only runtime I mean it does not appear in HTML page it appears only in chrome developers tools. How to eliminate such kind a tag and override or edit it.
I tried editing code via its script when I inspected for long it split document.querySelector("#m360CrA483349594983") but when I search entire project there's no sign of it!
demos written can be eliminated for sure!

Even I tried to Enable Local Overrides on but nothing seems to work that mysterious tag is kept coming saying

"demos written can be eliminated for sure!"

A: once the dom is ready you can access the element

A: Add body onload event listener in order to search for tag appearing at runtime.
Also, pay attention to tag ID value, it seems it is generated every time, so, you won't be able to find it by static ID

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Studio, Git and three ways merge On Android Studio, I created a new branch from the master and commited the new branch two times.
Then I checkedout the master and commited it one time.
So I have two branches with two distinct endpoints and a common parent.
Now I am trying a three ways merge:
right click on the new branch, click on the new branch name, then merge, but appears a popup

Couldn't merge TestMergeBranch
  CONFLICT (content): Merge conflict in
  (...  files' list  ...)

and nothing more happens.
Thus I click on VCS menu, Git, Resolve conflicts. Then I click Accept Yours button to resolve the conflicts on selected files. The Resolve window disappears, and again nothing more happens.
Thus I go to re-add to stage the resolved files but the Add option is disabled.
Any hints?
(Android Studio 2.0 on Ubuntu 14.04)
--- It needs an android-studio-git Tag ---

A:
Add option is disabled

If you are referring to the "Add to VCS" option, it should be disabled as the file is already tracked by git (it is for new files)
Try a commit instead and select the files you have resolved for addition/commit from the commit change dialog.

A: First checkout the branch you want to merge other branch(example if you want to merge the development to master then checkout master).
Right click on the branch which you want to merge to your checked out branch and use merge.
If you worked on the same files in the two branches it can't merge itself, hence throws a conflict.
Resolve the conflict manually
Add files to index(This will make it understand that conflicts are merged)
Commit the changes of the merge
Push to your remote.


Health Payment Solutions from Optum help payers meet cost containment objectives and administrative simplification goals set out in the Affordable Care Act by streamlining the claims payment process and reducing costs.
The new era of Electronic Data Interchange (EDI) requires leadership on multiple fronts: provider knowledge, payer knowledge, connectivity knowledge, coding expertise, leading technology and financial strength — only Optum has it all.
With a national, diversified network, EFT/ERA/VCP solutions from Optum create savings and efficiencies for both payers and providers.


text:
You are here: Home / news / Lee Osborne talks Evoke…
Lee Osborne talks Evoke…
Wed 15th August by Tasha
Lee Osborne has paid his dues in terms of hard work. His remix of Automanual was one of the hottest tracks around and was heavily publisised. We thought we would catch up and chat to Lee about his Gallery residency and his huge gig at Evoke, one of the hottest clubs in the South right now.
You have just been crowned the new Ministry of Sound and The Gallery Resident, a great feat! What does this mean to you?
I've really focused on my music over the past three years; I think that's made the difference and ultimately the basis of the residency. I've literally been in the studio non-stop and the stuff I've been working on over the past few months is a real step change, I really can't wait for the new releases, I'm looking forward to testing them out on that system!
The residency is a dream come true, I mean Ministry Of Sound is really the only real super club left in London and it's probably the most World's most prestigious. The Gallery is an institution every single week the programming is immaculate there really isn't anywhere in the UK where you will find A-Class super stars playing week in week out. My debut is with Ferry Corsten and you don't really get much bigger than that!
Your remix Automanual became one of the hottest tracks getting huge props from the likes Marco V – did you ever expect the track to become so big?
Ha! That's the one tune I always get asked about…I guess that's because it was the first time it was officially remixed and released on Marco V's label and the original was a massive anthem. I still love playing it, it destroys the floor every time – to be honest you never expect that one track to be so big and believe me I'm not complaining! My DeadMau5 rework was the same I think it even got 6 weeks continuous play on Radio 1…Look out for the next one 😉
Your part of the quartet with Ali Wilson, Matt Smallwood and Ben Gold – can you elaborate on what you guys do?
Ha well I wouldn't say quartet, myself Ali and Matt have been friends and collaborators for 15 years. Matt & Ali have been working together on their own sound for a while and with a lot of success winning a lot of critical acclaim from the likes of Carl Cox. Ben and I have been friends for about 7 years and work in the studio together when we can get the time! We've released on Armada (Captivating) and are now working on another collab coming your way very soon. All four of us are connected that's for sure and we're all from London, we have a very tight community! The boys 😉
You will play the hugely hyped Evoke club this coming month, are you excited to play?
I've seen the pictures! It looks crazy, it's the time first I've seen a club so packed every week! The line-ups look wicked as does the crowd. I love new clubs, brand new sound systems, big lights, excited clubbers. And I can't wait to play next to Robbie Rivera, I'm working on big room progressive house set – lots of groove and lots of bass!
What can we expect from your gig?
Exclusive re-works from myself as I said, lots of energy, lots of groove and bass! I'm not sure Essex will realize what has hit em' J.
You mix trance and progressive house together frequently – was this an angle you wanted to take or something you fell into?
It's all about the music, it doesn't really matter what specific genre it is, it's all about THAT sound and more importantly the dancefloor, the music I play is strictly for the clubs. DJ's and Producers have been crossing over for a long time now, it's creative and healthy for the scene. Personally the level of quality music has never been better.
Finally what's next for Lee Osborne?
A lot more touring to be honest, I'm looking forward to Ireland and Scotland coming up in a few weeks then moving on to South America, it's something I really want to concentrate on. The studio will not stop and I have some VERY exciting collaborations coming up. Exciting times.
Ant Brooks 'Wired EP'
The Together Winter Music Festival – selling out fast!
Weasel Blog: News / Comps / Interviews / Reviews / Ldn & Manc Events Recommends: Joey Beltram, Dinky, Layo & Bushwacka, Eastern Electrics, Jamie Jones, Maceo Plex, Joy Orbison, Tensnake, Will Saul, Glade, Heidi, Guillaume & The Coutu Dumonts, Richie Hawtin, mulletover, Carl Craig, Adam Beyer, Clement Meyer, Paco Osuna
Exclusive Interview With Clive Henry AND A Chance To Win VIP Tickets AND Vodka @ PWP PACHA London!
Kebi Teams up With Zach Fields to Unleash Chilled Summer Anthem 'Stay Up'

redpajama_set_name: RedPajamaCommonCrawl


text:
Tonsillectomy for Obstructive Sleep-Disordered Breathing or Recurrent Throat Infection in Children [Internet]
Rockville (MD): Agency for Healthcare Research and Quality (US); 2017 Jan. Report No.: 16(17)-EHC042-EF.
AHRQ Comparative Effectiveness Reviews.
David O Francis 1 , Sivakumar Chinnadurai 1 , Nila A Sathe 1 , Anna Morad 1 , Atia K Jordan 1 , Shanthi Krishnaswami 1 , Christopher Fonnesbeck 1 , Melissa L McPheeters 1
1 Vanderbilt Evidence-based Practice Center
Bookshelf ID: NBK424048
Objectives: To systematically review evidence addressing tonsillectomy in children with obstructive sleep-disordered breathing (OSDB) or recurrent throat infections.
Data sources: Multiple databases from January 1980 through June 2016.
Review methods: We included comparative studies of tonsillectomy, perioperative medications to improve outcomes, and postoperative medications for pain. We also included case series and database studies with ≥1,000 children to address harms. Two investigators independently screened studies and rated risk of bias. We extracted and summarized data qualitatively and quantitatively via Bayesian meta-analyses. We also assessed strength of the evidence (SOE).
Results: We identified 218 unique studies (141 randomized controlled trials [RCTs], 12 nonrandomized trials, 7 prospective and 5 retrospective cohort studies, and 53 database or registry studies or case series [67 low, 110 moderate, and 41 high risk of bias]). Populations; surgical approaches; anesthetic, analgesic, and antiemetic regimens varied across studies. For children with OSDB, most studies reported better sleep-related outcomes in those who had a tonsillectomy versus no surgery. For children with recurrent throat infections, tonsillectomy improved the number of infections, associated utilization (clinician visits), and work/school absences in the first postsurgical year. These benefits did not persist over time, however, and longer term outcomes are limited. Partial tonsillectomy was associated with faster return to normal diet or activity versus total tonsillectomy but also with a risk of tonsillar regrowth requiring reoperation. Commonly used "hot" techniques were generally associated with faster return to normal diet and activity than was cold dissection. In meta-analyses, frequency of post-tonsillectomy hemorrhage (PTH) was less than 4 percent, and frequency of bleeding-associated revisits or reoperations was less than 8 percent. Meta-analysis of nine RCTs reporting bleeding associated with perioperative dexamethasone compared with placebo did not indicate a significantly increased risk of bleeding with steroids, although confidence bounds were wide. Studies of perioperative medications were heterogeneous, but dexamethasone was consistently associated with less need for rescue analgesia than placebo. Preemptive perioperative 5-hydroxytryptamine (5-HT) antiemetics were associated with less need for postoperative antiemetics than placebo. Few studies of postoperative medications addressed the same agents or outcomes.
Conclusions: Tonsillectomy can produce short-term improvement in sleep outcomes compared with no surgery in children with OSDB (moderate SOE). In children with recurrent throat infections undergoing tonsillectomy, number of throat infections (moderate SOE) and associated health care utilization and work/school absences (low SOE) improved in the first postsurgical year. These benefits did not persist, and data on longer term results are lacking. Short-term improvements must be weighed against the risk of PTH (high SOE for low frequency of PTH). Surgical technique had little bearing on return to normal diet or activity (low SOE). Perioperative dexamethasone and pre-emptive 5-HT receptor antagonist antiemetics reduced the need for additional analgesics or antiemetics (low SOE). Dexamethasone did not increase risk of PTH compared with placebo, but estimates had wide confidence bounds (low SOE). Little evidence addressed the use of postoperative medications for pain-related outcomes (insufficient SOE).
Technical Expert Panel
Appendix A. Analytic Frameworks
Appendix B. Search Strategies
Appendix C. Information for Screening, Risk of Bias Assessment, and Strength of the Evidence
Appendix D. Excluded Studies
Appendix E. Methods for Meta-Analyses
Appendix F. Risk of Bias Ratings
Appendix G. Applicability of Findings
Appendix H. Detailed Tables of Findings
Appendix I. Summary of Existing Systematic Reviews
Prepared for: Agency for Healthcare Research and Quality, U.S. Department of Health and Human Services, Contract No. 290-2015-00003-I. Prepared by: Vanderbilt Evidence-based Practice Center, Nashville, TN


Rakhi Gayathri, a student of Electrical and Electronics Engineering (EEE), Amrita School of Engineering, Amritapuri campus, has returned from University of New Mexico (UNM) after completing the student exchange program.
She also extended her gratitude to the faculty members of EEE dept especially her HOD, Dr. Manjula G. Nair, Chairperson, Electrical and Electronic Engineering, Amrita School of Engineering, Amritapuri.
The UNM, founded in 1889, is a public research university in Albuquerque, New Mexico. The University offers bachelor's, master's, doctoral, and professional degree programs in a wide variety of fields.
The Amrita Center for International Programs creates opportunities for the diverse exchange of knowledge and ideas. The Institution works together with other universities in U.S and Europe, providing the students with opportunities to live and study at internationally renowned institutions.


I would like to say thank you for your great help and engagement at my participation at the workshop.
I want to express to you how much I appreciate your help and the flexibility associated with my cancellation and renewal of my registration as well as accommodation.
It was for me unforgettable and indescribably professional experience, that was potentiated by the beauty of your beautiful city and venue of the Workshop.
It was pleasure to meet you. I wish you a lot of nice moments in your private and professional life. Also i believe to see you again.
The Society of Magnetic Resonance Angiography recently held their 29th annual meeting in Stellenbosch. I was the Chair of the Organizing Committee for that meeting.
The meeting was attended by 190 delegates and accompanying persons from many countries around the world, and from every continent. I should also note that my own efforts were provided from San Francisco – perhaps as far as one can be from Stellenbosch. I had to rely on the organization support of a local team. It was therefore of great satisfaction to me that there was unanimous agreement amongst the delegates that the meeting was outstanding in every organizational aspect.
Suné van Rooyen and Dawne Johnson of ConsultUs were gracious, attentive to detail, and brilliant in execution of all aspects of the meeting. As in any meeting of this size, I had to face with a number of last minute unexpected problems but these were accommodated and managed expertly by ConsultUs. I personally felt that it was very easy to share my hopes and thoughts with Suné and Dawne, and they were able to meet and exceed those expectations. I provide them my enthusiastic endorsement.
ConsultUS was the local conference management team we brought on board for The Society of Magnetic Resonance Angiography (SMRA) conference which is attended by 190 delegates.
This conference moves each year around the world and this was the first time we hosted it in South Africa. The SMRA conference has 4 evening events and 3 full day spousal program. ConsultUS focuses on details and has excellent communication skills. Their team ensures the quality of the venue, audio visual and Food & Beverage is above average.
Our team in Canada met with them monthly via ZOOM and even with the time difference they were always available and gave our project the upmost of a priority. ConsultUS know the South African market very well and uses outstanding 3rd party vendors such as Jannie Loubser with Signature Tours for the spousal events. Suné & Dawne delivered beyond our expectations and right down to the local made lanyards gave it a local feel. If you are looking to have a conference in South Africa I would highly recommend ConsultUS! They will save you extensive dollars and bring your conference in on budget.
The pre‐conference preparation was amazing, the social functions fabulous, the onsite support amazing! ‐ The location was simply breathtaking and perfect for a conference of this size!
I talked to many of the delegates and sponsors during and after the conference, and the feedback was only positive! I did not hear a single negative word, and the fact that others would like to work with you to organize a conference at Spier is testament to how well this conference was done.
It is quite a challenge to organize a conference from half‐around‐the‐world away, but you made it so easy for me and the others on the ISRHML team. Thank you very much for making this an ISRHML conference to remember for all our delegates and a wonderful personal experience for me!
I'm going to miss seeing your emails in my inbox first thing in the morning, and having Skype calls with you, Evette and Lisanne at rather unusual times of the day. ‐ Hope we stay in touch!
It is now a little more than two weeks since we met in beautiful Cape Town, and we hope that everyone is now safely settled back home, perhaps after taking the opportunity for a few days of tourism in Africa.
As we start to move on to arrangements for next year it is appropriate to finally thank once again everyone who made this such a successful and happy meeting.
Starting with the original proposal back in 2012 and the choice of site and venue, Marnus van Wyk worked tirelessly to make our 2014 meeting one to really remember fondly. He, the Local Organising Committee and of course Dawne Johnson and the conference organisers, CONSULTUS, gave us a beautiful location and with meeting facilities and wireless access that worked perfectly. And of course more excellent food and drink than one could possibly imagine. None of that happens without a huge amount of preparation over many months and it is hard to overestimate the effort that the local organising team put in to make everything ran so well during the meeting. It is the sign of a very well organised conference that the arrangements become so smooth that we take them for granted.
No conference is possible without a programme, and for that we have to thank our 2014 Technical Programme Committee, chaired by Theo Samaras and Phil Chadwick. Starting with ideas from members of both Societies, they constructed an interesting and innovative programme that tried to reflect the broad range of interests within our Societies as well as bringing a few fresh ideas from outside. We must of course thank the plenary speakers, the workshop convenors and the four people who volunteered to give early morning tutorials, but we also must thank the people who presented posters and talks. Without them (you) there could be no conference. We also would like to thank the people who chaired all the sessions, and the people who came to them. It was great to see people arrive for the tutorials in the morning and to see people still there for the early evening seminars and workshops.
The future of our Societies and our meetings lies with students, and the joint Awards Committee chaired by Alexandre Legros and Heidi Danker-Hopfe worked hard to run the Student Awards competition. Their job of course would have been impossible without the people who judged the student presentations and posters – to you as well, we say thank you.
Our personal thanks go to Drs Jeffrey Carson and Astrid Chamson-Reig from Lawson Health Research Institute in Canada; they have been constant contributors whose hard work behind the scenes brought the programme and the awards to fruition.
The quality of the meeting is dependent on sponsorship; without the kind support of MMF, EPRI, GSMA, the US Office of Naval Research Global, ZonMw, FEKO, SAECA, IGEA and EMSS the meeting as we experienced it could not have happened.
Finally, and above all, we would like to thank everyone who came to Cape Town and made it such a wonderful meeting. Even the weather was mostly kind to us, though perhaps not even Marnus could have planned that so well!
Better late than never – i want to thank you for a real superb organisation of our Derm conference!
I wish you all the best for your future projects – and i am sure if we ever have to organize another conference we will contact you again!
We at the Centre for Higher and Adult Education at Stellenbosch University, had the priviledge of working with Consultus to present the second biannual Postgraduate Supervision conference in April 2009.
Throughout our co-operation the service rendered by Consultus was outstanding. From organising the venue, the events, registration and the web-page to finalising the financial statements and arrangements – everything went according to plan with efficiency and good relations that added to the success of the conference.
The professional and friendly service from Consultus, both to us and conferees alike, is highly appreciated and recommended to everyone who wishes to run a successful conference. We shall definitely approach Consultus again for organising our next conference in 2011.
Thank you to ConsultUS especially Christelle and Suné for their professionalism and efficiency during the organization of the SASHG conference in April 2009. It is a mammoth job to handle the multiple tasks simultaneously (including liaising with the international speakers, payment of sponsorships, venue arrangements, organizing the conference web site and the finances) but somehow you made it all seem easy!
You also accommodated all our requests and suggestions with a smile – with no task being too big. I think that your company played a major contribution in the success of our congress and the fact that we made a sizeable profit!
Thank you once again and keep up the good work!!
I would like to express my sincere thanks and appreciation to the management team and staff at Consultus Conferences for there work as conference coordinators of the 10th International Winelands Conference, 2006. Efficiency, flexibility and professionalism are words that immediately spring to mind and these, coupled with a very personal approach made for an outstanding event – praised by local and international delegates alike.
Conference, contributed greatly to the overall success of the Conference.
Dit is vir my aaangenaam om my mening oor Consultus te kan gee. Ons samewerking was in 2003, toe Consultus die Suid-Afrikaanse Hartvereniging se kongres in Kaapstad organiseer het. Ek was baie tevrede met julle diens, en uit kommentare van die deelnemers en die internasionale uitgenooide gaste kan ek met oortuiging sê dat Consultus uitstekende werk gedoen het.
Ek sal die firma sterk aanbeveel by enige voornemende kliënte.
Die tweejaarlikse kongres van die International Academy of Periodontology (IAP) vind oor twee weke in Salvador, Brasilië plaas.
Ek het gehoop om te kon bywoon, maar kon dit ongelukkig nie inpas nie. Ek wou juis gaan kyk of hulle die baie suksesvolle IAP-kongres wat in 2003 in Kaapstad plaasgevind het, kan nadoen!
Dit het my weer herinner aan die bekwame diens wat jy en jou kollegas van Consultus aan die Kongreskomitee gelewer het. Die professionele aanslag en flink reaksie op alle versoeke sal my altyd bybly. Daarbenewens was julle aandag aan detail asook die goeie hantering van die finansies, werklik bewonderingswaardig. Ek dink nou nog met trots terug aan al die verskillende produkte van IAP 2003: die netjies-versorgde brosjures; die professionele program; die puik plakkaat- en produkte-uitstallings; die suksesvolle webwerf; en die baie aangename sosiale aangeleenthede. Alle reëlings was werklik puik en die Brasiliane sal moet uithang om te kan bybly met wat Consultus in 2003 met die IAP-kongres vermag het!
Nogmaals dankie vir die puik diens, selfs op hierdie laat stadium laat dit my bors swel met trots!
Ek is deur Suné van Rooyen gevra om 'n sin of twee te skryf oor my ervaringe met consultUS [spesifiek rondom die rëel van kongresse], aangesien ek reeds hul dienste in die verlede in die verband benut het.
Ek moes drie jaar gelede 'n nasionale kongres reel en het hulle toe betrek om grootliks verantwoordelikheid te neem vir al die reelings. Dit was regtig 'n plesier om met so 'n uiters gemaklike en professionele span te kon saamwerk. Hulle het my volledig en deurlopend op die hoogte van sake gehou en uit hulle pad gegaan om kreatiewe idees te bedink en te implementeer. Hulle was egter ook oop vir my idees en, wat ek veral van gehou het, is die feit dat hulle die hele proses self duidelik baie geniet het.
Ek kan hulle dus regtig sonder voorbehoud baie sterk aanbeveel…consultUS is 'n puik span!.
Skakel gerus persoonlik as jy verdere inligting verlang.
Die kongres was werklik 'n groot sukses, al moet ek dit self ook sê. Amal was vol lof. Jy verdien 'n spesiale pluimpie want verskeie mense het spontaan vir my kom sê hoe vriendelik ek behulpsaam jy was. Dankie ook vir jou spesiale hulp met die dinee. Jy het soveel moeite gedoen om almal in te pas.
Daar is nog 'n paar klein sake wat ons nog moet bespreek meer ek wil eers hierdie bedanking by jou kry.
Ek hoop jy kon die naweek bietjie rus na al die harde werk.
"The feedback has been absolutely fantastic. I have had letters of thanks from all the International speakers and they are only full of praise for the whole congress".
Hiermee te bevestig dat ek in my hoedanigheid as plaaslike kongres- en wetenskaplike program-koordineerder reeds by twee geleenthede die dienste van bogenoemde ingespan het as kongresorganiseerders. Die betrokke kongresse was die 2003 National Psychopharmacology Congress (250+ kongresgangers) en die 2005 International Regional CINP in Africa Congress (400+ kongresgangers).
Ek het met beide geleenthede vir Suné v Rooyen as baie professioneel en beskikbaar ervaar. Hulle span het ook heelwat uitgebrei in die afgelope jare. Indien ek 'n soortgelyke funksie sou moes aanpak sou ek definitief oorweging skenk om weer van hulle dienste gebruik te maak.
Graag wil ek die komitee werklik gelukwens op 'n uitstekende Akademiese Jaarsdag, en veral op hulle ongelooflike goeie organisasie.
Congrats on a highly successful AJD.
My best wishes to you and your beautiful family.


text:
Гео́ргий Рубе́нович Баграту́ни (1918, город Тбилиси — , город Киев) — министр монтажных и специальных строительных работ УССР, заслуженный строитель УССР. Депутат Верховного Совета УССР 7—9-го созывов. Кандидат в члены ЦК КПУ в 1966—1980 г.

Биография
Армянин.

Образование высшее. Окончил в 1945 году Тбилисский институт инженеров железнодорожного транспорта, по специальности инженер-мостостроитель.

В 1945—1951 — начальник отдела технического контроля Сталинского завода металлоконструкций Сталинской области.

Член ВКП(б) с 1948 года.

В 1951—1953 — главный инженер Макеевского завода металлоконструкций Сталинской области. В 1953—1959 — главный инженер Ждановского завода металлоконструкций Сталинской области.

В 1959—1963 — главный инженер — заместитель начальника, начальник главного управления «Укрглавстальконструкция» Министерства строительства Украинской ССР.

В 1963—1965 — заместитель, 1-й заместитель министра монтажных и специальных строительных работ Украинской ССР.

В 1965—1979 — министр монтажных и специальных строительных работ Украинской ССР. За принципиально новое решение монтажа телевышек методом подращивания получил звание изобретателя СССР.

Награды
 Орден Ленина
 Орден Трудового Красного Знамени
 Орден «Знак Почёта»
 Орден Октябрьской Революции
 медали
 Государственная премия УССР в области науки и техники (1976)
 Почётная грамота Президиума Верховного Совета УССР
 заслуженный строитель Украинской ССР (1968)

Ссылки
 Комитет по Государственным премиям Украины в области науки и техники

Литература
 Депутати Верховної Ради УРСР. 9-е скликання—1975 р.

Депутаты Верховного Совета Украинской ССР 7-го созыва
Депутаты Верховного Совета Украинской ССР 8-го созыва
Депутаты Верховного Совета Украинской ССР 9-го созыва
Выпускники Тбилисского института инженеров железнодорожного транспорта
Министры монтажных и специальных строительных работ УССР

redpajama_set_name: RedPajamaWikipedia


text:
JCOPE, LEC Settle Public Officers Law Violations with Former Senator Marc Panepinto
Enforcement Actions Public Officers Law Code of Conduct
Will Pay $10,000 for Attempts to Obstruct JCOPE Investigation, Unwanted Advances Against Staffer
The Joint Commission on Public Ethics ("JCOPE") announced today that it and the Legislative Ethics Commission ("LEC") have reached a settlement agreement, including a $10,000 fine, to resolve its investigation into violations of the Public Officers Law by former state Senator Marc Panepinto for making unwanted sexual advances towards a staff member and attempting to obstruct JCOPE's ensuing investigation.
In the settlement, Panepinto admits that he violated Public Officers Law §§ 74(3)(d) and (h) and agrees to pay the $10,000 fine to the LEC. His admissions were based on facts he acknowledged in his guilty plea in 2018 to federal criminal charges brought by the United States Attorney for the Western District of New York.
Panepinto admitted to making unwanted verbal and physical sexual advances to a female staffer and then offering her money or future employment if she refused to cooperate with JCOPE's subsequent investigation into the allegations regarding that misconduct.
The LEC referred Panepinto's improper sexual conduct to JCOPE after it was provided with an internal investigation report by the state Senate following the staffer's resignation from Panepinto's office. Upon receiving the matter in 2016, JCOPE began investigating Panepinto, but, at the request of the U.S. Attorney, agreed to defer its inquiry and share information to facilitate the criminal prosecution. Panepinto's plea agreement with federal prosecutors provides for a two-month prison sentence, one year of supervised release, and an additional $9,500 fine.
JCOPE appreciates the assistance of the United State Attorney's office, as well as the Erie County District Attorney's Office, in resolving this matter.
Marc Panepinto Substantial Basis Investigation Report and Settlement Agreement
Contact Communications and Public Information Office
The Communications and Public Information Office is the point of contact for the public and members of the press with questions about JCOPE's mission and to request access to records such as the financial disclosure statements filed by state officials and employees, the statewide elected officials, members of the Legislature and legislative employees.