<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

document.addEventListener('deviceready', function () {
    Firebase.goOnline();
});

// Example faskes action
$('#not-available').on('click', function() {
	alert('Faskes is not available.')
})

function getNoAntri(tipe, username, name) {
  grease = '../poli/' + username + '.html';
  window.location.href = grease;
}

function tempatTidur(tipe, username) {
  // Firebase URL
  brea = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/tempat_tidur');

  // Waiting message
  wait = 'Getting data..';
  console.log(wait);
  alert(wait);

  // Get the data
  brea.on('value', function(snapshot) {
    satu = snapshot.val().satu;
    dua = snapshot.val().dua;
    tiga = snapshot.val().tiga;

    alert('Kelas I: ' + Number(satu) + '\n' + 'Kelas II: ' + Number(dua) + '\n' + 'Kelas III: ' + Number(tiga)); // Show user the data's
  })
}

function doctorProfile(nama, lulusan, tahun) {
  giant = 'Lulusan: ' + lulusan + '\n' + 'Tahun: ' + tahun; // Doctor content
  name = 'dr. ' + nama; // Doctor name

  alert(name + '\n' + giant); // Pop-up
}

function pilihPoli(username) {
  var nama = $('#nama').val(),
      nik = $('#nik').val(),
      poli = $('#poli').val();

  dipcifica = new Firebase('https://cepatsembuh.firebaseio.com/puskesmas/faskes/' + username),

  date = new Date(),
  year = date.getFullYear(),
  month = date.getMonth() + 1,
  day = date.getDate(),
  right_now = year + '-' + month + '-' + day,
  today = dipcifica.child(right_now),

  bpu = dipcifica.child('bpu'),
  bpg = dipcifica.child('bpg'),
  kia = dipcifica.child('kia'),

  bpu_pasien = today.child('bpu-pasien'),
  bpg_pasien = today.child('bpg-pasien'),
  kia_pasien = today.child('kia-pasien');

  if (nama === '' || nik.length != 16) {
    alert('Input tidak valid')
  } else {
    switch (poli) {
      // BPU
      case 'bpu':
        bpu.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
          }, function(error, committed, snapshot) {
              if (error) {
                  // Error message
                  alert('Koneksi anda tidak stabil' + error);
              } else {
                  // Send the Data
                  alert('Nomor Antrian: ' + snapshot.val() + '\n' + '*Harap screenshot ini dan tunjukan ke faskes anda');

                  // Push the prompt data
                  bpu_pasien.push().set({
                    nama: nama,
                    nik: nik,
                    no_antri: snapshot.val(),
                    poli: 'BPU'
                  })
              }
          });
        break;
      // BPG
      case 'bpg':
        bpg.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
          }, function(error, committed, snapshot) {
              if (error) {
                  // Error message
                  alert('Koneksi anda tidak stabil' + error);
              } else {
                  // Send the Data
                  alert('Nomor Antrian: ' + snapshot.val() + '\n' + '*Harap screenshot ini dan tunjukan ke faskes anda');

                  // Push the prompt data
                  bpg_pasien.push().set({
                    nama: nama,
                    nik: nik,
                    no_antri: snapshot.val(),
                    poli: 'BPG'
                  })
              }
          });
        break;
      // KIA
      case 'kia':
        kia.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
          }, function(error, committed, snapshot) {
              if (error) {
                  // Error message
                  alert('Koneksi anda tidak stabil' + error);
              } else {
                  // Send the Data
                  alert('Nomor Antrian: ' + snapshot.val() + '\n' + '*Harap screenshot ini dan tunjukan ke faskes anda');

                  // Push the prompt data
                  kia_pasien.push().set({
                    nama: nama,
                    nik: nik,
                    no_antri: snapshot.val(),
                    poli: 'KIA'
                  })
              }
          });
        break;

        // Null handler
        case null:
          alert('Anda belum memilih poli');
          break;
    }
  }
}
<commit_msg>Included date when giving no antri<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

document.addEventListener('deviceready', function () {
    Firebase.goOnline();
});

// Example faskes action
$('#not-available').on('click', function() {
	alert('Faskes is not available.')
})

function getNoAntri(tipe, username, name) {
  grease = '../poli/' + username + '.html';
  window.location.href = grease;
}

function tempatTidur(tipe, username) {
  // Firebase URL
  brea = new Firebase('http://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/tempat_tidur');

  // Waiting message
  wait = 'Getting data..';
  console.log(wait);
  alert(wait);

  // Get the data
  brea.on('value', function(snapshot) {
    satu = snapshot.val().satu;
    dua = snapshot.val().dua;
    tiga = snapshot.val().tiga;

    alert('Kelas I: ' + Number(satu) + '\n' + 'Kelas II: ' + Number(dua) + '\n' + 'Kelas III: ' + Number(tiga)); // Show user the data's
  })
}

function doctorProfile(nama, lulusan, tahun) {
  giant = 'Lulusan: ' + lulusan + '\n' + 'Tahun: ' + tahun; // Doctor content
  name = 'dr. ' + nama; // Doctor name

  alert(name + '\n' + giant); // Pop-up
}

function pilihPoli(username) {
  var nama = $('#nama').val(),
      nik = $('#nik').val(),
      poli = $('#poli').val();

  dipcifica = new Firebase('https://cepatsembuh.firebaseio.com/puskesmas/faskes/' + username),

  date = new Date(),
  year = date.getFullYear(),
  month = date.getMonth() + 1,
  day = date.getDate(),
  right_now = year + '-' + month + '-' + day,
  today = dipcifica.child(right_now),

  bpu = dipcifica.child('bpu'),
  bpg = dipcifica.child('bpg'),
  kia = dipcifica.child('kia'),

  bpu_pasien = today.child('bpu-pasien'),
  bpg_pasien = today.child('bpg-pasien'),
  kia_pasien = today.child('kia-pasien');

  if (nama === '' || nik.length != 16) {
    alert('Input tidak valid')
  } else {
    switch (poli) {
      // BPU
      case 'bpu':
        bpu.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
          }, function(error, committed, snapshot) {
              if (error) {
                  // Error message
                  alert('Koneksi anda tidak stabil' + error);
              } else {
                  // Send the Data
                  alert('Nomor Antrian: ' + snapshot.val() + '\n' + 'Datanglah pada: ' + String(right_now) + '\n' + '\n' + '*Harap screenshot ini dan tunjukan ke faskes anda');

                  // Push the prompt data
                  bpu_pasien.push().set({
                    nama: nama,
                    nik: nik,
                    no_antri: snapshot.val(),
                    poli: 'BPU'
                  })
              }
          });
        break;
      // BPG
      case 'bpg':
        bpg.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
          }, function(error, committed, snapshot) {
              if (error) {
                  // Error message
                  alert('Koneksi anda tidak stabil' + error);
              } else {
                  // Send the Data
                  alert('Nomor Antrian: ' + snapshot.val() + '\n' + 'Datanglah pada: ' + String(right_now) + '\n' + '\n' + '*Harap screenshot ini dan tunjukan ke faskes anda');

                  // Push the prompt data
                  bpg_pasien.push().set({
                    nama: nama,
                    nik: nik,
                    no_antri: snapshot.val(),
                    poli: 'BPG'
                  })
              }
          });
        break;
      // KIA
      case 'kia':
        kia.transaction(function(currentRank) {
          currentData = currentRank + 1;

          return currentData;
          }, function(error, committed, snapshot) {
              if (error) {
                  // Error message
                  alert('Koneksi anda tidak stabil' + error);
              } else {
                  // Send the Data
                  alert('Nomor Antrian: ' + snapshot.val() + '\n' + 'Datanglah pada: ' + String(right_now) + '\n' + '\n' + '*Harap screenshot ini dan tunjukan ke faskes anda');

                  // Push the prompt data
                  kia_pasien.push().set({
                    nama: nama,
                    nik: nik,
                    no_antri: snapshot.val(),
                    poli: 'KIA'
                  })
              }
          });
        break;

        // Null handler
        case null:
          alert('Anda belum memilih poli');
          break;
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Increasing the emulator loop time appears to improve things.<commit_after><|endoftext|>


<commit_before>import {uniques, flatten, adUnitsFilter} from './utils';
import {getPriceBucketString} from './cpmBucketManager';

var CONSTANTS = require('./constants.json');
var AUCTION_END = CONSTANTS.EVENTS.AUCTION_END;
var utils = require('./utils.js');
var events = require('./events');

var objectType_function = 'function';

var externalCallbacks = {byAdUnit: [], all: [], oneTime: null, timer: false};
var _granularity = CONSTANTS.GRANULARITY_OPTIONS.MEDIUM;
let _customPriceBucket;
var defaultBidderSettingsMap = {};

exports.setCustomPriceBucket = function(customConfig) {
  _customPriceBucket = customConfig;
};

/**
 * Returns a list of bidders that we haven't received a response yet
 * @return {array} [description]
 */
exports.getTimedOutBidders = function () {
  return $$PREBID_GLOBAL$$._bidsRequested
    .map(getBidderCode)
    .filter(uniques)
    .filter(bidder => $$PREBID_GLOBAL$$._bidsReceived
      .map(getBidders)
      .filter(uniques)
      .indexOf(bidder) < 0);
};

function timestamp() { return new Date().getTime(); }

function getBidderCode(bidSet) {
  return bidSet.bidderCode;
}

function getBidders(bid) {
  return bid.bidder;
}

function bidsBackAdUnit(adUnitCode) {
  const requested = $$PREBID_GLOBAL$$._bidsRequested
    .map(request => request.bids
      .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes))
      .filter(bid => bid.placementCode === adUnitCode))
    .reduce(flatten)
    .map(bid => {
      return bid.bidder === 'indexExchange' ?
          bid.sizes.length :
          1;
    }).reduce(add, 0);

  const received = $$PREBID_GLOBAL$$._bidsReceived.filter(bid => bid.adUnitCode === adUnitCode).length;
  return requested === received;
}

function add(a, b) {
  return a + b;
}

function bidsBackAll() {
  const requested = $$PREBID_GLOBAL$$._bidsRequested
    .map(request => request.bids)
    .reduce(flatten)
    .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes))
    .map(bid => {
      return bid.bidder === 'indexExchange' ?
        bid.sizes.length :
        1;
    }).reduce((a, b) => a + b, 0);

  const received = $$PREBID_GLOBAL$$._bidsReceived
    .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes)).length;

  return requested === received;
}

exports.bidsBackAll = function () {
  return bidsBackAll();
};

function getBidderRequest(bidder, adUnitCode) {
  return $$PREBID_GLOBAL$$._bidsRequested.find(request => {
    return request.bids
        .filter(bid => bid.bidder === bidder && bid.placementCode === adUnitCode).length > 0;
  }) || { start: null, requestId: null };
}

/*
 *   This function should be called to by the bidder adapter to register a bid response
 */
exports.addBidResponse = function (adUnitCode, bid) {
  if (bid) {

    const { requestId, start } = getBidderRequest(bid.bidderCode, adUnitCode);
    Object.assign(bid, {
      requestId: requestId,
      responseTimestamp: timestamp(),
      requestTimestamp: start,
      cpm: bid.cpm || 0,
      bidder: bid.bidderCode,
      adUnitCode
    });

    bid.timeToRespond = bid.responseTimestamp - bid.requestTimestamp;

    if (bid.timeToRespond > $$PREBID_GLOBAL$$.cbTimeout + $$PREBID_GLOBAL$$.timeoutBuffer) {
      const timedOut = true;

      exports.executeCallback(timedOut);
    }

    //emit the bidAdjustment event before bidResponse, so bid response has the adjusted bid value
    events.emit(CONSTANTS.EVENTS.BID_ADJUSTMENT, bid);

    //emit the bidResponse event
    events.emit(CONSTANTS.EVENTS.BID_RESPONSE, bid);

    //append price strings
    const priceStringsObj = getPriceBucketString(bid.cpm, _customPriceBucket);
    bid.pbLg = priceStringsObj.low;
    bid.pbMg = priceStringsObj.med;
    bid.pbHg = priceStringsObj.high;
    bid.pbAg = priceStringsObj.auto;
    bid.pbDg = priceStringsObj.dense;
    bid.pbCg = priceStringsObj.custom;

    //if there is any key value pairs to map do here
    var keyValues = {};
    if (bid.bidderCode && bid.cpm > 0) {
      keyValues = getKeyValueTargetingPairs(bid.bidderCode, bid);
    }

    bid.adserverTargeting = keyValues;
    $$PREBID_GLOBAL$$._bidsReceived.push(bid);
  }

  if (bid && bid.adUnitCode && bidsBackAdUnit(bid.adUnitCode)) {
    triggerAdUnitCallbacks(bid.adUnitCode);
  }

  if (bidsBackAll()) {
    exports.executeCallback();
  }
};

function getKeyValueTargetingPairs(bidderCode, custBidObj) {
  var keyValues = {};
  var bidder_settings = $$PREBID_GLOBAL$$.bidderSettings;

  //1) set the keys from "standard" setting or from prebid defaults
  if (custBidObj && bidder_settings) {
    //initialize default if not set
    const standardSettings = getStandardBidderSettings();
    setKeys(keyValues, standardSettings, custBidObj);
  }

  //2) set keys from specific bidder setting override if they exist
  if (bidderCode && custBidObj && bidder_settings && bidder_settings[bidderCode] && bidder_settings[bidderCode][CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING]) {
    setKeys(keyValues, bidder_settings[bidderCode], custBidObj);
    custBidObj.alwaysUseBid = bidder_settings[bidderCode].alwaysUseBid;
    custBidObj.sendStandardTargeting = bidder_settings[bidderCode].sendStandardTargeting;
  }

  //2) set keys from standard setting. NOTE: this API doesn't seem to be in use by any Adapter
  else if (defaultBidderSettingsMap[bidderCode]) {
    setKeys(keyValues, defaultBidderSettingsMap[bidderCode], custBidObj);
    custBidObj.alwaysUseBid = defaultBidderSettingsMap[bidderCode].alwaysUseBid;
    custBidObj.sendStandardTargeting = defaultBidderSettingsMap[bidderCode].sendStandardTargeting;
  }

  return keyValues;
}

exports.getKeyValueTargetingPairs = function() {
  return getKeyValueTargetingPairs(...arguments);
};

function setKeys(keyValues, bidderSettings, custBidObj) {
  var targeting = bidderSettings[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING];
  custBidObj.size = custBidObj.getSize();

  utils._each(targeting, function (kvPair) {
    var key = kvPair.key;
    var value = kvPair.val;

    if (keyValues[key]) {
      utils.logWarn('The key: ' + key + ' is getting ovewritten');
    }

    if (utils.isFn(value)) {
      try {
        value = value(custBidObj);
      } catch (e) {
        utils.logError('bidmanager', 'ERROR', e);
      }
    }

    if (
      (typeof bidderSettings.suppressEmptyKeys !== "undefined" && bidderSettings.suppressEmptyKeys === true ||
      key === "hb_deal") && // hb_deal is suppressed automatically if not set
      (
        utils.isEmptyStr(value) ||
        value === null ||
        value === undefined
      )
    ) {
      utils.logInfo("suppressing empty key '" + key + "' from adserver targeting");
    } else {
      keyValues[key] = value;
    }

  });

  return keyValues;
}

exports.setPriceGranularity = function setPriceGranularity(granularity) {
  var granularityOptions = CONSTANTS.GRANULARITY_OPTIONS;
  if (Object.keys(granularityOptions).filter(option => granularity === granularityOptions[option])) {
    _granularity = granularity;
  } else {
    utils.logWarn('Prebid Warning: setPriceGranularity was called with invalid setting, using' +
      ' `medium` as default.');
    _granularity = CONSTANTS.GRANULARITY_OPTIONS.MEDIUM;
  }
};

exports.registerDefaultBidderSetting = function (bidderCode, defaultSetting) {
  defaultBidderSettingsMap[bidderCode] = defaultSetting;
};

exports.executeCallback = function (timedOut) {
  // if there's still a timeout running, clear it now
  if (!timedOut && externalCallbacks.timer) {
    clearTimeout(externalCallbacks.timer);
  }

  if (externalCallbacks.all.called !== true) {
    processCallbacks(externalCallbacks.all);
    externalCallbacks.all.called = true;

    if (timedOut) {
      const timedOutBidders = exports.getTimedOutBidders();

      if (timedOutBidders.length) {
        events.emit(CONSTANTS.EVENTS.BID_TIMEOUT, timedOutBidders);
      }
    }
  }

  //execute one time callback
  if (externalCallbacks.oneTime) {
    events.emit(AUCTION_END);
    try {
      processCallbacks([externalCallbacks.oneTime]);
    }
    catch(e){
      utils.logError('Error executing bidsBackHandler', null, e);
    }
    finally {
      externalCallbacks.oneTime = null;
      externalCallbacks.timer = false;
      $$PREBID_GLOBAL$$.clearAuction();
    }
  }
};

exports.externalCallbackReset = function () {
  externalCallbacks.all.called = false;
};

function triggerAdUnitCallbacks(adUnitCode) {
  //todo : get bid responses and send in args
  var singleAdUnitCode = [adUnitCode];
  processCallbacks(externalCallbacks.byAdUnit, singleAdUnitCode);
}

function processCallbacks(callbackQueue, singleAdUnitCode) {
  if (utils.isArray(callbackQueue)) {
    callbackQueue.forEach(callback => {
      const adUnitCodes = singleAdUnitCode || $$PREBID_GLOBAL$$._adUnitCodes;
      const bids = [$$PREBID_GLOBAL$$._bidsReceived
                      .filter(adUnitsFilter.bind(this, adUnitCodes))
                      .reduce(groupByPlacement, {})];

      callback.apply($$PREBID_GLOBAL$$, bids);
    });
  }
}

/**
 * groupByPlacement is a reduce function that converts an array of Bid objects
 * to an object with placement codes as keys, with each key representing an object
 * with an array of `Bid` objects for that placement
 * @param prev previous value as accumulator object
 * @param item current array item
 * @param idx current index
 * @param arr the array being reduced
 * @returns {*} as { [adUnitCode]: { bids: [Bid, Bid, Bid] } }
 */
function groupByPlacement(prev, item, idx, arr) {
  // this uses a standard "array to map" operation that could be abstracted further
  if (item.adUnitCode in Object.keys(prev)) {
    // if the adUnitCode key is present in the accumulator object, continue
    return prev;
  } else {
    // otherwise add the adUnitCode key to the accumulator object and set to an object with an
    // array of Bids for that adUnitCode
    prev[item.adUnitCode] = {
      bids: arr.filter(bid => bid.adUnitCode === item.adUnitCode)
    };
    return prev;
  }
}

/**
 * Add a one time callback, that is discarded after it is called
 * @param {Function} callback
 * @param timer Timer to clear if callback is triggered before timer time's out
 */
exports.addOneTimeCallback = function (callback, timer) {
  externalCallbacks.oneTime = callback;
  externalCallbacks.timer = timer;
};

exports.addCallback = function (id, callback, cbEvent) {
  callback.id = id;
  if (CONSTANTS.CB.TYPE.ALL_BIDS_BACK === cbEvent) {
    externalCallbacks.all.push(callback);
  } else if (CONSTANTS.CB.TYPE.AD_UNIT_BIDS_BACK === cbEvent) {
    externalCallbacks.byAdUnit.push(callback);
  }
};

//register event for bid adjustment
events.on(CONSTANTS.EVENTS.BID_ADJUSTMENT, function (bid) {
  adjustBids(bid);
});

function adjustBids(bid) {
  var code = bid.bidderCode;
  var bidPriceAdjusted = bid.cpm;
  if (code && $$PREBID_GLOBAL$$.bidderSettings && $$PREBID_GLOBAL$$.bidderSettings[code]) {
    if (typeof $$PREBID_GLOBAL$$.bidderSettings[code].bidCpmAdjustment === objectType_function) {
      try {
        bidPriceAdjusted = $$PREBID_GLOBAL$$.bidderSettings[code].bidCpmAdjustment.call(null, bid.cpm, utils.extend({}, bid));
      }
      catch (e) {
        utils.logError('Error during bid adjustment', 'bidmanager.js', e);
      }
    }
  }

  if (bidPriceAdjusted >= 0) {
    bid.cpm = bidPriceAdjusted;
  }
}

exports.adjustBids = function() {
  return adjustBids(...arguments);
};

function getStandardBidderSettings() {
  let bidder_settings = $$PREBID_GLOBAL$$.bidderSettings;
  if (!bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD]) {
    bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD] = {
      adserverTargeting: [
        {
          key: 'hb_bidder',
          val: function (bidResponse) {
            return bidResponse.bidderCode;
          }
        }, {
          key: 'hb_adid',
          val: function (bidResponse) {
            return bidResponse.adId;
          }
        }, {
          key: 'hb_pb',
          val: function (bidResponse) {
            if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.AUTO) {
              return bidResponse.pbAg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.DENSE) {
              return bidResponse.pbDg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.LOW) {
              return bidResponse.pbLg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.MEDIUM) {
              return bidResponse.pbMg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.HIGH) {
              return bidResponse.pbHg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.CUSTOM) {
              return bidResponse.pbCg;
            }
          }
        }, {
          key: 'hb_size',
          val: function (bidResponse) {
            return bidResponse.size;
          }
        }, {
          key: 'hb_deal',
          val: function (bidResponse) {
            return bidResponse.dealId;
          }
        }
      ]
    };
  }
  return bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD];
}

function getStandardBidderAdServerTargeting() {
  return getStandardBidderSettings()[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING];
}

exports.getStandardBidderAdServerTargeting = getStandardBidderAdServerTargeting;
<commit_msg>Rewrite groupByPlacement to avoid multiple scans of array (#918)<commit_after>import {uniques, flatten, adUnitsFilter} from './utils';
import {getPriceBucketString} from './cpmBucketManager';

var CONSTANTS = require('./constants.json');
var AUCTION_END = CONSTANTS.EVENTS.AUCTION_END;
var utils = require('./utils.js');
var events = require('./events');

var objectType_function = 'function';

var externalCallbacks = {byAdUnit: [], all: [], oneTime: null, timer: false};
var _granularity = CONSTANTS.GRANULARITY_OPTIONS.MEDIUM;
let _customPriceBucket;
var defaultBidderSettingsMap = {};

exports.setCustomPriceBucket = function(customConfig) {
  _customPriceBucket = customConfig;
};

/**
 * Returns a list of bidders that we haven't received a response yet
 * @return {array} [description]
 */
exports.getTimedOutBidders = function () {
  return $$PREBID_GLOBAL$$._bidsRequested
    .map(getBidderCode)
    .filter(uniques)
    .filter(bidder => $$PREBID_GLOBAL$$._bidsReceived
      .map(getBidders)
      .filter(uniques)
      .indexOf(bidder) < 0);
};

function timestamp() { return new Date().getTime(); }

function getBidderCode(bidSet) {
  return bidSet.bidderCode;
}

function getBidders(bid) {
  return bid.bidder;
}

function bidsBackAdUnit(adUnitCode) {
  const requested = $$PREBID_GLOBAL$$._bidsRequested
    .map(request => request.bids
      .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes))
      .filter(bid => bid.placementCode === adUnitCode))
    .reduce(flatten)
    .map(bid => {
      return bid.bidder === 'indexExchange' ?
          bid.sizes.length :
          1;
    }).reduce(add, 0);

  const received = $$PREBID_GLOBAL$$._bidsReceived.filter(bid => bid.adUnitCode === adUnitCode).length;
  return requested === received;
}

function add(a, b) {
  return a + b;
}

function bidsBackAll() {
  const requested = $$PREBID_GLOBAL$$._bidsRequested
    .map(request => request.bids)
    .reduce(flatten)
    .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes))
    .map(bid => {
      return bid.bidder === 'indexExchange' ?
        bid.sizes.length :
        1;
    }).reduce((a, b) => a + b, 0);

  const received = $$PREBID_GLOBAL$$._bidsReceived
    .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes)).length;

  return requested === received;
}

exports.bidsBackAll = function () {
  return bidsBackAll();
};

function getBidderRequest(bidder, adUnitCode) {
  return $$PREBID_GLOBAL$$._bidsRequested.find(request => {
    return request.bids
        .filter(bid => bid.bidder === bidder && bid.placementCode === adUnitCode).length > 0;
  }) || { start: null, requestId: null };
}

/*
 *   This function should be called to by the bidder adapter to register a bid response
 */
exports.addBidResponse = function (adUnitCode, bid) {
  if (bid) {

    const { requestId, start } = getBidderRequest(bid.bidderCode, adUnitCode);
    Object.assign(bid, {
      requestId: requestId,
      responseTimestamp: timestamp(),
      requestTimestamp: start,
      cpm: bid.cpm || 0,
      bidder: bid.bidderCode,
      adUnitCode
    });

    bid.timeToRespond = bid.responseTimestamp - bid.requestTimestamp;

    if (bid.timeToRespond > $$PREBID_GLOBAL$$.cbTimeout + $$PREBID_GLOBAL$$.timeoutBuffer) {
      const timedOut = true;

      exports.executeCallback(timedOut);
    }

    //emit the bidAdjustment event before bidResponse, so bid response has the adjusted bid value
    events.emit(CONSTANTS.EVENTS.BID_ADJUSTMENT, bid);

    //emit the bidResponse event
    events.emit(CONSTANTS.EVENTS.BID_RESPONSE, bid);

    //append price strings
    const priceStringsObj = getPriceBucketString(bid.cpm, _customPriceBucket);
    bid.pbLg = priceStringsObj.low;
    bid.pbMg = priceStringsObj.med;
    bid.pbHg = priceStringsObj.high;
    bid.pbAg = priceStringsObj.auto;
    bid.pbDg = priceStringsObj.dense;
    bid.pbCg = priceStringsObj.custom;

    //if there is any key value pairs to map do here
    var keyValues = {};
    if (bid.bidderCode && bid.cpm > 0) {
      keyValues = getKeyValueTargetingPairs(bid.bidderCode, bid);
    }

    bid.adserverTargeting = keyValues;
    $$PREBID_GLOBAL$$._bidsReceived.push(bid);
  }

  if (bid && bid.adUnitCode && bidsBackAdUnit(bid.adUnitCode)) {
    triggerAdUnitCallbacks(bid.adUnitCode);
  }

  if (bidsBackAll()) {
    exports.executeCallback();
  }
};

function getKeyValueTargetingPairs(bidderCode, custBidObj) {
  var keyValues = {};
  var bidder_settings = $$PREBID_GLOBAL$$.bidderSettings;

  //1) set the keys from "standard" setting or from prebid defaults
  if (custBidObj && bidder_settings) {
    //initialize default if not set
    const standardSettings = getStandardBidderSettings();
    setKeys(keyValues, standardSettings, custBidObj);
  }

  //2) set keys from specific bidder setting override if they exist
  if (bidderCode && custBidObj && bidder_settings && bidder_settings[bidderCode] && bidder_settings[bidderCode][CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING]) {
    setKeys(keyValues, bidder_settings[bidderCode], custBidObj);
    custBidObj.alwaysUseBid = bidder_settings[bidderCode].alwaysUseBid;
    custBidObj.sendStandardTargeting = bidder_settings[bidderCode].sendStandardTargeting;
  }

  //2) set keys from standard setting. NOTE: this API doesn't seem to be in use by any Adapter
  else if (defaultBidderSettingsMap[bidderCode]) {
    setKeys(keyValues, defaultBidderSettingsMap[bidderCode], custBidObj);
    custBidObj.alwaysUseBid = defaultBidderSettingsMap[bidderCode].alwaysUseBid;
    custBidObj.sendStandardTargeting = defaultBidderSettingsMap[bidderCode].sendStandardTargeting;
  }

  return keyValues;
}

exports.getKeyValueTargetingPairs = function() {
  return getKeyValueTargetingPairs(...arguments);
};

function setKeys(keyValues, bidderSettings, custBidObj) {
  var targeting = bidderSettings[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING];
  custBidObj.size = custBidObj.getSize();

  utils._each(targeting, function (kvPair) {
    var key = kvPair.key;
    var value = kvPair.val;

    if (keyValues[key]) {
      utils.logWarn('The key: ' + key + ' is getting ovewritten');
    }

    if (utils.isFn(value)) {
      try {
        value = value(custBidObj);
      } catch (e) {
        utils.logError('bidmanager', 'ERROR', e);
      }
    }

    if (
      (typeof bidderSettings.suppressEmptyKeys !== "undefined" && bidderSettings.suppressEmptyKeys === true ||
      key === "hb_deal") && // hb_deal is suppressed automatically if not set
      (
        utils.isEmptyStr(value) ||
        value === null ||
        value === undefined
      )
    ) {
      utils.logInfo("suppressing empty key '" + key + "' from adserver targeting");
    } else {
      keyValues[key] = value;
    }

  });

  return keyValues;
}

exports.setPriceGranularity = function setPriceGranularity(granularity) {
  var granularityOptions = CONSTANTS.GRANULARITY_OPTIONS;
  if (Object.keys(granularityOptions).filter(option => granularity === granularityOptions[option])) {
    _granularity = granularity;
  } else {
    utils.logWarn('Prebid Warning: setPriceGranularity was called with invalid setting, using' +
      ' `medium` as default.');
    _granularity = CONSTANTS.GRANULARITY_OPTIONS.MEDIUM;
  }
};

exports.registerDefaultBidderSetting = function (bidderCode, defaultSetting) {
  defaultBidderSettingsMap[bidderCode] = defaultSetting;
};

exports.executeCallback = function (timedOut) {
  // if there's still a timeout running, clear it now
  if (!timedOut && externalCallbacks.timer) {
    clearTimeout(externalCallbacks.timer);
  }

  if (externalCallbacks.all.called !== true) {
    processCallbacks(externalCallbacks.all);
    externalCallbacks.all.called = true;

    if (timedOut) {
      const timedOutBidders = exports.getTimedOutBidders();

      if (timedOutBidders.length) {
        events.emit(CONSTANTS.EVENTS.BID_TIMEOUT, timedOutBidders);
      }
    }
  }

  //execute one time callback
  if (externalCallbacks.oneTime) {
    events.emit(AUCTION_END);
    try {
      processCallbacks([externalCallbacks.oneTime]);
    }
    catch(e){
      utils.logError('Error executing bidsBackHandler', null, e);
    }
    finally {
      externalCallbacks.oneTime = null;
      externalCallbacks.timer = false;
      $$PREBID_GLOBAL$$.clearAuction();
    }
  }
};

exports.externalCallbackReset = function () {
  externalCallbacks.all.called = false;
};

function triggerAdUnitCallbacks(adUnitCode) {
  //todo : get bid responses and send in args
  var singleAdUnitCode = [adUnitCode];
  processCallbacks(externalCallbacks.byAdUnit, singleAdUnitCode);
}

function processCallbacks(callbackQueue, singleAdUnitCode) {
  if (utils.isArray(callbackQueue)) {
    callbackQueue.forEach(callback => {
      const adUnitCodes = singleAdUnitCode || $$PREBID_GLOBAL$$._adUnitCodes;
      const bids = [$$PREBID_GLOBAL$$._bidsReceived
                      .filter(adUnitsFilter.bind(this, adUnitCodes))
                      .reduce(groupByPlacement, {})];

      callback.apply($$PREBID_GLOBAL$$, bids);
    });
  }
}

/**
 * groupByPlacement is a reduce function that converts an array of Bid objects
 * to an object with placement codes as keys, with each key representing an object
 * with an array of `Bid` objects for that placement
 * @returns {*} as { [adUnitCode]: { bids: [Bid, Bid, Bid] } }
 */
function groupByPlacement(bidsByPlacement, bid) {
  if (!bidsByPlacement[bid.adUnitCode])
    bidsByPlacement[bid.adUnitCode] = { bids: [] };

  bidsByPlacement[bid.adUnitCode].bids.push(bid);

  return bidsByPlacement;
}

/**
 * Add a one time callback, that is discarded after it is called
 * @param {Function} callback
 * @param timer Timer to clear if callback is triggered before timer time's out
 */
exports.addOneTimeCallback = function (callback, timer) {
  externalCallbacks.oneTime = callback;
  externalCallbacks.timer = timer;
};

exports.addCallback = function (id, callback, cbEvent) {
  callback.id = id;
  if (CONSTANTS.CB.TYPE.ALL_BIDS_BACK === cbEvent) {
    externalCallbacks.all.push(callback);
  } else if (CONSTANTS.CB.TYPE.AD_UNIT_BIDS_BACK === cbEvent) {
    externalCallbacks.byAdUnit.push(callback);
  }
};

//register event for bid adjustment
events.on(CONSTANTS.EVENTS.BID_ADJUSTMENT, function (bid) {
  adjustBids(bid);
});

function adjustBids(bid) {
  var code = bid.bidderCode;
  var bidPriceAdjusted = bid.cpm;
  if (code && $$PREBID_GLOBAL$$.bidderSettings && $$PREBID_GLOBAL$$.bidderSettings[code]) {
    if (typeof $$PREBID_GLOBAL$$.bidderSettings[code].bidCpmAdjustment === objectType_function) {
      try {
        bidPriceAdjusted = $$PREBID_GLOBAL$$.bidderSettings[code].bidCpmAdjustment.call(null, bid.cpm, utils.extend({}, bid));
      }
      catch (e) {
        utils.logError('Error during bid adjustment', 'bidmanager.js', e);
      }
    }
  }

  if (bidPriceAdjusted >= 0) {
    bid.cpm = bidPriceAdjusted;
  }
}

exports.adjustBids = function() {
  return adjustBids(...arguments);
};

function getStandardBidderSettings() {
  let bidder_settings = $$PREBID_GLOBAL$$.bidderSettings;
  if (!bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD]) {
    bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD] = {
      adserverTargeting: [
        {
          key: 'hb_bidder',
          val: function (bidResponse) {
            return bidResponse.bidderCode;
          }
        }, {
          key: 'hb_adid',
          val: function (bidResponse) {
            return bidResponse.adId;
          }
        }, {
          key: 'hb_pb',
          val: function (bidResponse) {
            if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.AUTO) {
              return bidResponse.pbAg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.DENSE) {
              return bidResponse.pbDg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.LOW) {
              return bidResponse.pbLg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.MEDIUM) {
              return bidResponse.pbMg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.HIGH) {
              return bidResponse.pbHg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.CUSTOM) {
              return bidResponse.pbCg;
            }
          }
        }, {
          key: 'hb_size',
          val: function (bidResponse) {
            return bidResponse.size;
          }
        }, {
          key: 'hb_deal',
          val: function (bidResponse) {
            return bidResponse.dealId;
          }
        }
      ]
    };
  }
  return bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD];
}

function getStandardBidderAdServerTargeting() {
  return getStandardBidderSettings()[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING];
}

exports.getStandardBidderAdServerTargeting = getStandardBidderAdServerTargeting;
<|endoftext|>


<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

document.addEventListener('deviceready', function () {
    Firebase.goOnline();
});

$('#not-available').on('click', function() {
	alert('Faskes is not available.')
})

function getNoAntri(tipe, username, name) {
  breanna = new Firebase('https://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username),
  antri = new Firebase("https://cepatsembuh.firebaseio.com/puskesmas/faskes/kelapa_gading/antrian");

  alert('Pastikan koneksi anda stabil'); // Make sure the connection is OK

  get = 'Getting data..';
  console.log(get);

  breanna.on("value", function(snapshot) {
    alert('Nomor Antrian: ' + snapshot.val().antrian)
  })

  antri.transaction(function(currentRank) {
     return currentRank + 1;
  });

  console.log('Data is ready');
}

function tempatTidur(tipe, username) {
  brea = new Firebase('https://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/tempat_tidur');

  wait = 'Getting data..';
  console.log(wait);
  alert(wait);

  brea.on('value', function(snapshot) {
    satu = snapshot.val().satu;
    dua = snapshot.val().dua;
    tiga = snapshot.val().tiga;

    alert('Kelas I: ' + satu + '\n' + 'Kelas II: ' + dua + '\n' + 'Kelas III: ' + tiga); // Show user the data's
  })
}

function doctorProfile(nama, lulusan, tahun) {
  giant = 'Lulusan: ' + lulusan + '\n' + 'Tahun: ' + tahun;
  name = 'dr. ' + nama;

  alert(name + '\n' + giant); // Pop-up
}
<commit_msg>Can I meet breanna yde?<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

document.addEventListener('deviceready', function () {
    Firebase.goOnline();
});

$('#not-available').on('click', function() {
	alert('Faskes is not available.')
})

function getNoAntri(tipe, username, name) {
  breanna = new Firebase('https://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username),
  antri = new Firebase("https://cepatsembuh.firebaseio.com/puskesmas/faskes/kelapa_gading/antrian");

  alert('Pastikan koneksi anda stabil'); // Make sure the connection is OK

  get = 'Getting data..';
  console.log(get);

  antri.on("value", function(snapshot) {
    alert('Nomor Antrian: ' + snapshot.val())
  })

  antri.transaction(function(currentRank) {
     return currentRank + 1;
  });

  console.log('Data is ready');
}

function tempatTidur(tipe, username) {
  brea = new Firebase('https://cepatsembuh.firebaseio.com/' + tipe + '/faskes/' + username + '/tempat_tidur');

  wait = 'Getting data..';
  console.log(wait);
  alert(wait);

  brea.on('value', function(snapshot) {
    satu = snapshot.val().satu;
    dua = snapshot.val().dua;
    tiga = snapshot.val().tiga;

    alert('Kelas I: ' + satu + '\n' + 'Kelas II: ' + dua + '\n' + 'Kelas III: ' + tiga); // Show user the data's
  })
}

function doctorProfile(nama, lulusan, tahun) {
  giant = 'Lulusan: ' + lulusan + '\n' + 'Tahun: ' + tahun;
  name = 'dr. ' + nama;

  alert(name + '\n' + giant); // Pop-up
}
<|endoftext|>


<commit_before><commit_msg>Change header on cli output for clarity<commit_after><|endoftext|>


<commit_before>// copied from https://dev.to/boywithsilverwings/configuring-preact-cli-with-tailwind-css-3ckj
module.exports = (config, env, helpers, params) => {
  const purgecss = require('@fullhuman/postcss-purgecss')({
    // Specify the paths to all of the template files in your project
    content: ['./src/**/*.js'],

    // Include any special characters you're using in this regular expression
    defaultExtractor: content => content.match(params.regex) || []
  })

  const postCssLoaders = helpers.getLoadersByName(config, 'postcss-loader')
  postCssLoaders.forEach(({ loader }) => {
    const plugins = loader.options.plugins

    // Add tailwind css at the top.
    plugins.unshift(require('tailwindcss'))

    // Add PurgeCSS only in production.
    if (false /* env.production */) { // eslint-disable-line
      plugins.push(purgecss)
    }
  })
  return config
}
<commit_msg>updated purgecss config, fingers crossed<commit_after>// copied from https://dev.to/boywithsilverwings/configuring-preact-cli-with-tailwind-css-3ckj
module.exports = (config, env, helpers, params) => {
  const purgecss = require('@fullhuman/postcss-purgecss')({
    // Specify the paths to all of the template files in your project
    content: ['./build/**/*.js', './build/**/*.html'],
    css: ['./build/**/*.css']
  })

  const postCssLoaders = helpers.getLoadersByName(config, 'postcss-loader')
  postCssLoaders.forEach(({ loader }) => {
    const plugins = loader.options.plugins

    // Add tailwind css at the top.
    plugins.unshift(require('tailwindcss'))

    // Add PurgeCSS only in production.
    if (env.production) {
      plugins.push(purgecss)
    }
  })
  return config
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Skywriter.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Kevin Dangoor (kdangoor@mozilla.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

/**
 * Array detector.
 * Firefox 3.5 and Safari 4 have this already. Chrome 4 however ...
 * Note to Dojo - your isArray is still broken: instanceof doesn't work with
 * Arrays taken from a different frame/window.
 */
if (!Array.isArray) {
    Array.isArray = function(data) {
        return data && Object.prototype.toString.call(data) === "[object Array]";
    };
}

// from MDC
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf)
{
	Array.prototype.indexOf = function(searchElement /*, fromIndex */)
	{
		if (this === void 0 || this === null)
	    	throw new TypeError();

		var t = Object(this);
		var len = t.length >>> 0;
		if (len === 0)
		    return -1;

		var n = 0;
		if (arguments.length > 0) {
		    n = Number(arguments[1]);
		    if (n !== n)
		        n = 0;
		    else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
		        n = (n > 0 || -1) * Math.floor(Math.abs(n));
		}

		if (n >= len)
		    return -1;

		var k = n >= 0
		    ? n
		    : Math.max(len - Math.abs(n), 0);

		for (; k < len; k++) {
			if (k in t && t[k] === searchElement)
			    return k;
		}
		return -1;
	};
}

/**
 * Retrieves the list of keys on an object.
 */
if (!Object.keys) {
    Object.keys = function(obj) {
        var k, ret = [];
        for (k in obj) {
            if (obj.hasOwnProperty(k)) {
                ret.push(k);
            }
        }
        return ret;
    };
}

if (!Function.prototype.bind) {
    // from MDC
    // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
    Function.prototype.bind = function () {
        var slice = [].slice;
        var args = slice.call(arguments, 1);
        var self = this;
        var nop = function () {};

        // optimize common case
        if (arguments.length == 1) {
	        var bound = return function() {
	            return fcn.apply(this instanceof nop ? this : obj, arguments);
	        };
        }
        else {
	        var bound = function () {
	            return self.apply(
	                this instanceof nop ? this : ( obj || {} ),
	                args.concat( slice.call(arguments) )
	            );
	        };
        }

        nop.prototype = self.prototype;
        bound.prototype = new nop();

        // From Narwhal
        bound.name = this.name;
        bound.displayName = this.displayName;
        bound.length = this.length;
        bound.unbound = self;

        return bound;
    };
}

exports.globalsLoaded = true;

});<commit_msg>fix syntax error<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Skywriter.
 *
 * The Initial Developer of the Original Code is
 * Mozilla.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Kevin Dangoor (kdangoor@mozilla.com)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {

/**
 * Array detector.
 * Firefox 3.5 and Safari 4 have this already. Chrome 4 however ...
 * Note to Dojo - your isArray is still broken: instanceof doesn't work with
 * Arrays taken from a different frame/window.
 */
if (!Array.isArray) {
    Array.isArray = function(data) {
        return data && Object.prototype.toString.call(data) === "[object Array]";
    };
}

// from MDC
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf)
{
	Array.prototype.indexOf = function(searchElement /*, fromIndex */)
	{
		if (this === void 0 || this === null)
	    	throw new TypeError();

		var t = Object(this);
		var len = t.length >>> 0;
		if (len === 0)
		    return -1;

		var n = 0;
		if (arguments.length > 0) {
		    n = Number(arguments[1]);
		    if (n !== n)
		        n = 0;
		    else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
		        n = (n > 0 || -1) * Math.floor(Math.abs(n));
		}

		if (n >= len)
		    return -1;

		var k = n >= 0
		    ? n
		    : Math.max(len - Math.abs(n), 0);

		for (; k < len; k++) {
			if (k in t && t[k] === searchElement)
			    return k;
		}
		return -1;
	};
}

/**
 * Retrieves the list of keys on an object.
 */
if (!Object.keys) {
    Object.keys = function(obj) {
        var k, ret = [];
        for (k in obj) {
            if (obj.hasOwnProperty(k)) {
                ret.push(k);
            }
        }
        return ret;
    };
}

if (!Function.prototype.bind) {
    // from MDC
    // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
    Function.prototype.bind = function () {
        var slice = [].slice;
        var args = slice.call(arguments, 1);
        var self = this;
        var nop = function () {};

        // optimize common case
        if (arguments.length == 1) {
	        var bound = function() {
	            return fcn.apply(this instanceof nop ? this : obj, arguments);
	        };
        }
        else {
	        var bound = function () {
	            return self.apply(
	                this instanceof nop ? this : ( obj || {} ),
	                args.concat( slice.call(arguments) )
	            );
	        };
        }

        nop.prototype = self.prototype;
        bound.prototype = new nop();

        // From Narwhal
        bound.name = this.name;
        bound.displayName = this.displayName;
        bound.length = this.length;
        bound.unbound = self;

        return bound;
    };
}

exports.globalsLoaded = true;

});<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var express = require('express');
var router = express.Router();
var drive_sequelize = require('../sequelize-models/drive-sequelize');
const log = require('debug')('nodejs-team:router-dive');
const error = require('debug')('nodejs-team:error');
const fs = require("fs");
var validate = require("../validation/validation");
var sha = require("../sha/sha");

router.get('/list', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-  With, Content-Type, Accept");
  var key = 0;
  if (req.query.path_id) {
    key = req.query.path_id;
  }
  var p = drive_sequelize.list(key);
  p.then(drives => {
      res.json(JSON.stringify(drives));
    })
    .catch(err => {
      next(err);
    });

});

router.post('/delete', function(req, res, next) {

  var key = 0;
  if (req.body.path_id != undefined) {
    key = req.body.path_id;
  }
  var p = drive_sequelize.get_drive(key);
  p.then(drive => {
      if (drive) {
        var isFile = validate.isDirectory(drive.path);
        var mul = drive_sequelize.multiple(key, isFile);
        mul.then(drives => {

          })
          .catch(err => {
            res.send(`Can't Delete.No File Found`);
            // needs to give an error json
            next(err);
          });
      }
    })
    .catch(err => {
      res.send(`Can't Delete.No File Found`);
      next(err);
    });

});

router.get('/move', function(req, res, next) {
  console.log("router move");
  var filePath = path.join(__dirname, '../drive', '');
  var result = validate.check_validation(filePath);
  if (result) {
    fs.readdir(filePath, function(err, id, destPath) {
      if (err)
        next(err);

      //////////////////////////////////////////////////////////
      id = 3; // TODO: Remove this test data! //
      destPath = 'test path'; // TODO: Remove this test data! //
      //////////////////////////////////////////////////////////

      var p = drive_sequelize.move(id, destPath);
      p.then(fileId => {
          res.json(JSON.stringify(p));
        })
        .catch(err => {
          next(err);
        });
    });
  } else {
    res.send(`Can't move. Faced Issue while Execution`);
  }

});

router.post('/add', function(req, res, next) {
  var src = path.join(__dirname, '../drive', '');

  var key = 0;
  if (req.body.path_id != undefined) {
    key = req.body.path_id;
  }
  if (req.body.file_path != undefined) {
    src = path.join(__dirname, req.body.file_path, '');
  }
  console.log(`src: ${src}`);
  let dest = path.join(__dirname, '../public/cloud/');
  fs.access(dest, (err) => {
    if (err)
      fs.mkdirSync(dest);

    if (key != 0) {
      var root = drive_sequelize.get_parent(key);
      root.then(p_drive => {
          // console.log(`Drive : ${p_drive}`);
          walkSync(src, dest, [], p_drive);
          var parent = drive_sequelize.list(key);
          parent.then(drives => {
              res.status(200).send(JSON.stringify(drives));
            })
            .catch(err => {
              next(err);
            });
        })
        .catch(err => {
          next(err);
        });
    } else {
      walkSync(src, dest, [], null);
      var parent = drive_sequelize.list(key);
      parent.then(drives => {
          res.status(200).send(JSON.stringify(drives));
        })
        .catch(err => {
          next(err);
        });
    }

  });

});

var walkSync = function(dir, dest, filelist, data) {
  // console.log(`dest in the params : ${dest}`);
  var files = fs.readdirSync(dir);
  filelist = filelist || [];
  // console.log(`All Files: ${files}`);
  files.forEach(function(file) {
    if (fs.statSync(path.join(dir, file)).isDirectory()) {
      // console.log(`Directory: ${path.join(dir, file)}`);
      var folder_name = path.basename(path.join(dir, file));
      // console.log(`folder_name: ${folder_name}`);
      if (data) {
        let destDir = path.join(dest, file, '/');
        // console.log(`Folder destDir ${destDir}`);
        fs.access(destDir, (err) => {
          if (err)
            fs.mkdirSync(destDir);
          var parent = drive_sequelize.create(data.id, folder_name, destDir, 1, 0);
          parent.then(drive => {
              filelist = walkSync(path.join(dir, file), destDir, filelist, drive);
            })
            .catch(err => {
              return;
            });
        });

      } else {
        let destDir = path.join(dest, file, '/');
        // console.log(`Folder destDir Root${destDir}`);
        fs.access(destDir, (err) => {
          if (err)
            fs.mkdirSync(destDir);
          var parent = drive_sequelize.create(0, folder_name, destDir, 1, 0);
          parent.then(drive => {
              filelist = walkSync(path.join(dir, file), destDir, filelist, drive);
            })
            .catch(err => {
              return;
            });
        });

      }

    } else {
      // console.log(`File: ${file}`);
      fs.stat(path.join(dir, file), function(err, stats) {
        if (stats) {
          // console.log(stats["size"]);
          var file_path = path.basename(path.join(dir, file));
          // console.log(`file_path: ${file_path}`);
          if (data) {
            let destDir = path.join(dest, file);
            // console.log(`File destDir ${destDir}`);
            fs.access(destDir, (err) => {
              var child = drive_sequelize.create(data.id, file, destDir, 2, stats["size"]);
              child.then(drive => {
                  copyFile(path.join(dir, file), path.join(dest, file));
                  filelist.push(file);
                })
                .catch(err => {
                  return;
                });
              // var sha_encyp = sha.getHash_Checksum(destDir);
              // sha_encyp.then(data => {
              //   drive_sequelize.update(data.id, sha_encyp);
              // }).catch(err => {
              //   next(err);
              // });
            });

          } else {
            let destDir = path.join(dest, file);
            // console.log(`File Root destDir ${destDir}`);
            fs.access(destDir, (err) => {
              var child = drive_sequelize.create(0, file, destDir, 2, stats["size"]);
              child.then(drive => {
                  copyFile(path.join(dir, file), path.join(dest, file));
                  filelist.push(file);

                })
                .catch(err => {
                  return;
                });
              // var sha_encyp = sha.getHash_Checksum(destDir);
              // sha_encyp.then(data => {
              //   drive_sequelize.update(0, sha_encyp);
              // }).catch(err => {
              //   next(err);
              // });
            });

          }
        } else {
          console.log("Read error");
          return;
        }
      });
    }

  });
  return filelist;
};

function copyFile(src, dest) {

  // console.log('src', src);
  // console.log('dest', dest);
  let readStream = fs.createReadStream(src);

  readStream.once('error', (err) => {
    console.log(err);
  });

  readStream.once('end', () => {
    // console.log('done copying');
  });

  readStream.pipe(fs.createWriteStream(dest));
}

module.exports = router;
<commit_msg>Error Handling<commit_after>'use strict';
var util = require('util');
var path = require('path');
var express = require('express');
var router = express.Router();
var drive_sequelize = require('../sequelize-models/drive-sequelize');
const log = require('debug')('nodejs-team:router-dive');
const error = require('debug')('nodejs-team:error');
const fs = require("fs");
var validate = require("../validation/validation");
var sha = require("../sha/sha");

router.get('/list', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-  With, Content-Type, Accept");
  var key = 0;
  if (req.query.path_id) {
    key = req.query.path_id;
  }
  var p = drive_sequelize.list(key);
  p.then(drives => {
      res.json(JSON.stringify(drives));
    })
    .catch(err => {
      res.status(404).send({ error: "No Drive found" });
    });

});

router.post('/delete', function(req, res, next) {

  var key = 0;
  if (req.body.path_id != undefined) {
    key = req.body.path_id;
  }
  var p = drive_sequelize.get_drive(key);
  p.then(drive => {
      if (drive) {
        var isFile = validate.isDirectory(drive.path);
        var mul = drive_sequelize.multiple(key, isFile);
        mul.then(drives => {
          })
          .catch(err => {
            res.status(404).send({ error: err});
          });
      }
    })
    .catch(err => {
          res.status(404).send({ error: err});
    });

});

router.get('/move', function(req, res, next) {
  console.log("router move");
  var filePath = path.join(__dirname, '../drive', '');
  var result = validate.check_validation(filePath);
  if (result) {
    fs.readdir(filePath, function(err, id, destPath) {
      if (err)
        res.status(404).send({ error: err });

      //////////////////////////////////////////////////////////
      id = 3; // TODO: Remove this test data! //
      destPath = 'test path'; // TODO: Remove this test data! //
      //////////////////////////////////////////////////////////

      var p = drive_sequelize.move(id, destPath);
      p.then(fileId => {
          res.json(JSON.stringify(p));
        })
        .catch(err => {
          res.status(404).send({ error: err });
        });
    });
  } else {
        res.status(404).send({ error: "Can't Move.No File Found" });
  }

});

router.post('/add', function(req, res, next) {
  var src = path.join(__dirname, '../drive', '');

  var key = 0;
  if (req.body.path_id != undefined) {
    key = req.body.path_id;
  }
  if (req.body.file_path != undefined) {
    src = path.join(__dirname, req.body.file_path, '');
  }
  console.log(`src: ${src}`);
  let dest = path.join(__dirname, '../public/cloud/');
  fs.access(dest, (err) => {
    if (err)
      fs.mkdirSync(dest);

    if (key != 0) {
      var root = drive_sequelize.get_parent(key);
      root.then(p_drive => {
          // console.log(`Drive : ${p_drive}`);
          walkSync(src, dest, [], p_drive);
          var parent = drive_sequelize.list(key);
          parent.then(drives => {
              res.status(200).send(JSON.stringify(drives));
            })
            .catch(err => {
              res.status(404).send({ error:err });
            });
        })
        .catch(err => {
          next(err);
        });
    } else {
      walkSync(src, dest, [], null);
      var parent = drive_sequelize.list(key);
      parent.then(drives => {
          res.status(200).send(JSON.stringify(drives));
        })
        .catch(err => {
            res.status(404).send({ error: err });
        });
    }

  });

});

var walkSync = function(dir, dest, filelist, data) {
  // console.log(`dest in the params : ${dest}`);
  var files = fs.readdirSync(dir);
  filelist = filelist || [];
  // console.log(`All Files: ${files}`);
  files.forEach(function(file) {
    if (fs.statSync(path.join(dir, file)).isDirectory()) {
      // console.log(`Directory: ${path.join(dir, file)}`);
      var folder_name = path.basename(path.join(dir, file));
      // console.log(`folder_name: ${folder_name}`);
      if (data) {
        let destDir = path.join(dest, file, '/');
        // console.log(`Folder destDir ${destDir}`);
        fs.access(destDir, (err) => {
          if (err)
            fs.mkdirSync(destDir);
          var parent = drive_sequelize.create(data.id, folder_name, destDir, 1, 0);
          parent.then(drive => {
              filelist = walkSync(path.join(dir, file), destDir, filelist, drive);
            })
            .catch(err => {
              return;
            });
        });

      } else {
        let destDir = path.join(dest, file, '/');
        // console.log(`Folder destDir Root${destDir}`);
        fs.access(destDir, (err) => {
          if (err)
            fs.mkdirSync(destDir);
          var parent = drive_sequelize.create(0, folder_name, destDir, 1, 0);
          parent.then(drive => {
              filelist = walkSync(path.join(dir, file), destDir, filelist, drive);
            })
            .catch(err => {
              return;
            });
        });

      }

    } else {
      // console.log(`File: ${file}`);
      fs.stat(path.join(dir, file), function(err, stats) {
        if (stats) {
          // console.log(stats["size"]);
          var file_path = path.basename(path.join(dir, file));
          // console.log(`file_path: ${file_path}`);
          if (data) {
            let destDir = path.join(dest, file);
            // console.log(`File destDir ${destDir}`);
            fs.access(destDir, (err) => {
              var child = drive_sequelize.create(data.id, file, destDir, 2, stats["size"]);
              child.then(drive => {
                  copyFile(path.join(dir, file), path.join(dest, file));
                  filelist.push(file);
                })
                .catch(err => {
                  return;
                });
              // var sha_encyp = sha.getHash_Checksum(destDir);
              // sha_encyp.then(data => {
              //   drive_sequelize.update(data.id, sha_encyp);
              // }).catch(err => {
              //   next(err);
              // });
            });

          } else {
            let destDir = path.join(dest, file);
            // console.log(`File Root destDir ${destDir}`);
            fs.access(destDir, (err) => {
              var child = drive_sequelize.create(0, file, destDir, 2, stats["size"]);
              child.then(drive => {
                  copyFile(path.join(dir, file), path.join(dest, file));
                  filelist.push(file);

                })
                .catch(err => {
                  return;
                });
              // var sha_encyp = sha.getHash_Checksum(destDir);
              // sha_encyp.then(data => {
              //   drive_sequelize.update(0, sha_encyp);
              // }).catch(err => {
              //   next(err);
              // });
            });

          }
        } else {
          console.log("Read error");
          return;
        }
      });
    }

  });
  return filelist;
};

function copyFile(src, dest) {

  // console.log('src', src);
  // console.log('dest', dest);
  let readStream = fs.createReadStream(src);

  readStream.once('error', (err) => {
    console.log(err);
  });

  readStream.once('end', () => {
    // console.log('done copying');
  });

  readStream.pipe(fs.createWriteStream(dest));
}

module.exports = router;
<|endoftext|>


<commit_before>
var SERVER_URL = "http://127.0.0.1:5000/";
var FILE_ICON = "images/document_icon.png"
var MONTHS = [
    "gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno",
    "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"
]

var logged_name = null;
var logged_auth = null;
var last_visited_id = null;
var last_visited_type = null;

// HTML MANAGEMENT
function read_form(type) {
    var name = $("#name").val();
    var psw = $("#psw").val();
    if(!name || !psw) {
        alert("Inserisci i campi richiesti");
        return false;
    }
    if(type == "login") {
        return [name, psw];
    }
    else {
        var email = $("#email").val();
        if(! /^.+@.+\..+$/.test(email)) {
            alert("Email non valida");
            return false;
        }
        return [name, psw, email];
    }
}

function pop_the_popup(data, e) {
    var obj = data.features[0].properties;

    if(obj.id_ritrovamento != null) {
        last_visited_id = obj.id_ritrovamento;
        last_visited_type = "ritrovamento";

        $("#popup_ritrovamento h3").html(obj.definizione || null);
        $("#popup_ritrovamento p").html(obj.descrizione_min || null);
        $("#popup_ritrovamento #periodo").html(obj.periodo_fine || null);
        $("#popup_ritrovamento #tipologia_ritrov").html(obj.tipologia_ritrov || null);

        popup.setContent(
            $("#popup_ritrovamento").html()
        );
    }
    else {
        last_visited_id = obj.id_interv_nuovo;
        last_visited_type = "intervento";

        $("#popup_intervento h3").html(obj.tipo_intervento || null);
        $("#popup_intervento time").html(obj.data_compilazione || null);
        $("#popup_intervento #metodo").html(obj.metodo || null);
        $("#popup_intervento #dir_scentifica").html(obj.dir_scentifica || null);
        $("#popup_intervento #ente_resp").html(obj.ente_resp || null);
        $("#popup_intervento #ente_schedatore").html(obj.ente_schedatore || null);
        $("#popup_intervento #esecutore_intervento").html(obj.esecutore_intervento || null);
        $("#popup_intervento #tipo_particella").html(obj.tipo_particella || null);

        popup.setContent(
            $("#popup_intervento").html()
        );
    }

    popup.setLatLng(e.latlng);
    map.openPopup(popup);
}

function opengeo_make_link(link) {
    return link.replace("/home/archeofi/homes", "http://opengeo.eu/archeofi2");
}

function display_opengeo(data) {
    // clean-up from the previous info displayed
    $("#descri").empty();
    $("#bibliography").hide();
    $("#biblio").empty();
    $("#gallery").hide();
    $("#image").empty();

    // add new infos
    $("#descri").html(data[0]["descr"]);

    var bibliography = data[0]["bibliografia"];
    if(bibliography) {
        for(var i=0, l=bibliography.length; i<l; i++) {
            var content = bibliography[i]["biblio"] + " " + bibliography[i]["pagine"] + "
";
        }
        $("#biblio").html( content);
        $("#bibliography").show();
    }

    var images = data[0]["images"];
    if(images.length > 0) {
        for(var i=0, l=images.length; i<l; i++) {
            var link = opengeo_make_link(images[i]["link"]);
            var thumb = opengeo_make_link(images[i]["thumbnail"]);
            $("#image").append( " \
                     \
                ");
        }
        $("#gallery").show();
    }
}

function file_thumb(entry) {
    // TODO: correggere in 'data:image/jpeg;base64,' + entry["photo_thumb"];
    var thumb = (
            ''
        +   '   '
        +   '\n'
    )
    return thumb;
}

function convert_time(epoch) {
    var date = new Date(1000 * epoch);
    return date.getDate() + ' ' + MONTHS[date.getMonth()] + ' ' + date.getFullYear()
            + ' ' + date.getHours() + ',' + date.getMinutes();
}

function display_contents(contents) {
    // 'contents' is a map with keys: 'num_results', 'objects', 'page', 'total_pages'
    $("#contents").empty();

    console.log(contents);

    contents["objects"].forEach( function(entry) {
        console.log(entry);

        $("#contents").append(
                '
'
            +   '
'
            +           entry["id_"]
            +   '
'
            +   (entry["comment"] ? '' + entry["comment"] + '' : '')
            +   (entry["filename"] ? file_thumb(entry) : '')
            +   '
'
            +   '       '
            +               entry["user"]
            +   '       '
            +   '       '
            +               convert_time(entry["creation_time"])
            +   '       '
            +   '
'
            +   '
'
            +   '       <button class="ui-btn ui-icon-like ui-btn-icon-notext ui-corner-all ui-nodisc-icon ui-btn-inline" '
            +   '               onclick="like(' + entry["id_"] + ', true);">'
            +   '           mi piace'
            +   '       </button>'
            +   '       <button class="ui-btn ui-icon-dislike ui-btn-icon-notext ui-corner-all ui-nodisc-icon ui-btn-inline" '
            +   '               onclick="like(' + entry["id_"] + ', false);">'
            +   '           non mi piace'
            +   '       </button>'
            +   '
'
            +   '
'
            +   '       '
            +   '           +' + entry["like"]
            +   '       '
            +   '       '
            +   '           -' + entry["unlike"]
            +   '       '
            +   '
'
            +   '
'
        );
    });
}

$(document).on('pageshow', '#info', function() {
    ask_opengeo(last_visited_type, last_visited_id);
    // TODO: risolvere problema doppi id
    get_contents(last_visited_id);

    if(!logged_auth) {
        $("#add_content").hide();
        $("#login_required").show();
    }
    else {
        $("#add_content").show();
        $("#login_required").hide();
    }
});

// INDIANA SERVER
function register(name, psw, email) {
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/indiana_user",
        data: JSON.stringify({ "name": name, "psw": psw, "email": email }),
        dataType: "json",
        contentType: "application/json",
        success: function(data) {
            alert("ok");
            return data.objects;
        },
        error: function() {
            alert("ops, something went wrong..");
        }
    });
}

function login(name, psw) {
    var auth = "Basic " + btoa(name + ":" + psw);
    $.ajax({
        type: "GET",
        url: SERVER_URL + "api/login/",
        headers: {
          "Authorization": auth
        },
        success: function(logged) {
            console.log("successfully logged");
            if(logged) {
                logged_auth = auth;
                logged_name = name;
                alert("User and psw saved.");
            }
        },
        error: function() {
            alert("ops, something went wrong..");
        }
    });
}

function post_a_comment(poi, comment) {
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/content",
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify({ "comment": comment, "poi": poi }),
        dataType: "json",
        contentType: "application/json",
        success: function() {
            console.log("comment published!");
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

function get_contents(poi) {
    $.ajax({
        type: "GET",
        url: SERVER_URL + "api/content",
        data: {
            "q": JSON.stringify({
                "filters": [{
                    "name": "poi",
                    "op": "==",
                    "val": poi
                }]
            })
        },
        dataType: "json",
        contentType: "application/json",
        success: function(received) {
            console.log("contents received.");
            display_contents(received);
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

function modify_comment(content_id, modified_content) {
    $.ajax({
        type: "PATCH",
        url: SERVER_URL + "api/content/" + content_id,
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify ({
            "comment": modified_content
        }),
        contentType: "application/json",
        success: function() {
            console.log("content modified.");
        },
        error: function() {
            console.log("ops, something went wrong..");
        },
        complete: function(data_response) {
            return data_response.responseText;
        }
    });
}

function remove_content(content_id) {
    $.ajax({
        type: "DELETE",
        url: SERVER_URL + "api/content/" + content_id,
        headers: {
          "Authorization": logged_auth
        },
        contentType: "application/json",
        success: function() {
            console.log("content deleted.");
        },
        error: function() {
            console.log("ops, something went wrong..");
        },
        complete: function(data_response) {
            return data_response.responseText;
        }
    });
}

function like(content_id, do_like) {
    if(!logged_auth) {
        alert("per dire se ti piace o no, prima devi fare login");
        return;
    }
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/like",
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify ({
            "content_id": content_id,
            "do_like": do_like
        }),
        contentType: "application/json",
        success: function() {
            console.log("liked.");
        },
        error: function() {
            console.log("ops, something went wrong..");
        },
        complete: function(data_response) {
            return data_response.responseText;
        }
    });
}

function upload(poi, comment, form_data, file_description) {
    var file_id = null;

    // posting announcement
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/content",
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify ({
            "poi": poi,
            "comment": comment,
            "upload_announcement": true,
            "file_description": file_description
        }),
        dataType: "json",
        contentType: "application/json",
        success: function(data) {
            console.log("file announced.");
            file_id = data["filename"];
            upload2(file_id, form_data);
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

function upload2(file_id, form_data) {
    // actually post the file
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/file/" + file_id,
        headers: {
          "Authorization": logged_auth
        },
        data: form_data,
        async: false,
        cache: false,
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        dataType: 'json',
        success: function() {
            console.log("file uploaded.");
        },
        error: function(x, t, m) {
            console.log(t);
        }
    });
}

function wms_proxy(bbox, width, height, x, y, e) {
    $.ajax({
        type: "GET",
        url: SERVER_URL + "api/proxy/" + bbox + '&' + width + '&' + height + '&' + x + '&' + y,
        success: function(data) {
            console.log("proxied.");
            console.log(data);
            pop_the_popup(data, e);
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

// OPENGEO SERVER
function ask_opengeo(type, id) {
    if(type == "ritrovamento")
        var prefix = "rit_id=";
    else if(type == "intervento")
        var prefix = "interv_id=";
    else
        return;
    $.getJSON(
        "http://opengeo.eu/archeofi2/api/archeofi_api.php?" + prefix + id + "&jsoncallback=?",
        function(data) {
            console.log(data);
            display_opengeo(data);
        }
    );
}
<commit_msg>fix display hour: 16,1 -> 16,01<commit_after>
var SERVER_URL = "http://127.0.0.1:5000/";
var FILE_ICON = "images/document_icon.png"
var MONTHS = [
    "gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno",
    "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"
]

var logged_name = null;
var logged_auth = null;
var last_visited_id = null;
var last_visited_type = null;

// HTML MANAGEMENT
function read_form(type) {
    var name = $("#name").val();
    var psw = $("#psw").val();
    if(!name || !psw) {
        alert("Inserisci i campi richiesti");
        return false;
    }
    if(type == "login") {
        return [name, psw];
    }
    else {
        var email = $("#email").val();
        if(! /^.+@.+\..+$/.test(email)) {
            alert("Email non valida");
            return false;
        }
        return [name, psw, email];
    }
}

function pop_the_popup(data, e) {
    var obj = data.features[0].properties;

    if(obj.id_ritrovamento != null) {
        last_visited_id = obj.id_ritrovamento;
        last_visited_type = "ritrovamento";

        $("#popup_ritrovamento h3").html(obj.definizione || null);
        $("#popup_ritrovamento p").html(obj.descrizione_min || null);
        $("#popup_ritrovamento #periodo").html(obj.periodo_fine || null);
        $("#popup_ritrovamento #tipologia_ritrov").html(obj.tipologia_ritrov || null);

        popup.setContent(
            $("#popup_ritrovamento").html()
        );
    }
    else {
        last_visited_id = obj.id_interv_nuovo;
        last_visited_type = "intervento";

        $("#popup_intervento h3").html(obj.tipo_intervento || null);
        $("#popup_intervento time").html(obj.data_compilazione || null);
        $("#popup_intervento #metodo").html(obj.metodo || null);
        $("#popup_intervento #dir_scentifica").html(obj.dir_scentifica || null);
        $("#popup_intervento #ente_resp").html(obj.ente_resp || null);
        $("#popup_intervento #ente_schedatore").html(obj.ente_schedatore || null);
        $("#popup_intervento #esecutore_intervento").html(obj.esecutore_intervento || null);
        $("#popup_intervento #tipo_particella").html(obj.tipo_particella || null);

        popup.setContent(
            $("#popup_intervento").html()
        );
    }

    popup.setLatLng(e.latlng);
    map.openPopup(popup);
}

function opengeo_make_link(link) {
    return link.replace("/home/archeofi/homes", "http://opengeo.eu/archeofi2");
}

function display_opengeo(data) {
    // clean-up from the previous info displayed
    $("#descri").empty();
    $("#bibliography").hide();
    $("#biblio").empty();
    $("#gallery").hide();
    $("#image").empty();

    // add new infos
    $("#descri").html(data[0]["descr"]);

    var bibliography = data[0]["bibliografia"];
    if(bibliography) {
        for(var i=0, l=bibliography.length; i<l; i++) {
            var content = bibliography[i]["biblio"] + " " + bibliography[i]["pagine"] + "
";
        }
        $("#biblio").html( content);
        $("#bibliography").show();
    }

    var images = data[0]["images"];
    if(images.length > 0) {
        for(var i=0, l=images.length; i<l; i++) {
            var link = opengeo_make_link(images[i]["link"]);
            var thumb = opengeo_make_link(images[i]["thumbnail"]);
            $("#image").append( " \
                     \
                ");
        }
        $("#gallery").show();
    }
}

function file_thumb(entry) {
    // TODO: correggere in 'data:image/jpeg;base64,' + entry["photo_thumb"];
    var thumb = (
            ''
        +   '   '
        +   '\n'
    )
    return thumb;
}

function convert_time(epoch) {
    var date = new Date(1000 * epoch);
    var minutes = date.getMinutes().toString();
    return date.getDate() + ' ' + MONTHS[date.getMonth()] + ' ' + date.getFullYear()
            + ' ' + date.getHours() + ','
            + (minutes.length < 2 ? "0" + minutes : minutes);
}

function display_contents(contents) {
    // 'contents' is a map with keys: 'num_results', 'objects', 'page', 'total_pages'
    $("#contents").empty();

    console.log(contents);

    contents["objects"].forEach( function(entry) {
        console.log(entry);

        $("#contents").append(
                '
'
            +   '
'
            +           entry["id_"]
            +   '
'
            +   (entry["comment"] ? '' + entry["comment"] + '' : '')
            +   (entry["filename"] ? file_thumb(entry) : '')
            +   '
'
            +   '       '
            +               entry["user"]
            +   '       '
            +   '       '
            +               convert_time(entry["creation_time"])
            +   '       '
            +   '
'
            +   '
'
            +   '       <button class="ui-btn ui-icon-like ui-btn-icon-notext ui-corner-all ui-nodisc-icon ui-btn-inline" '
            +   '               onclick="like(' + entry["id_"] + ', true);">'
            +   '           mi piace'
            +   '       </button>'
            +   '       <button class="ui-btn ui-icon-dislike ui-btn-icon-notext ui-corner-all ui-nodisc-icon ui-btn-inline" '
            +   '               onclick="like(' + entry["id_"] + ', false);">'
            +   '           non mi piace'
            +   '       </button>'
            +   '
'
            +   '
'
            +   '       '
            +   '           +' + entry["like"]
            +   '       '
            +   '       '
            +   '           -' + entry["unlike"]
            +   '       '
            +   '
'
            +   '
'
        );
    });
}

$(document).on('pageshow', '#info', function() {
    ask_opengeo(last_visited_type, last_visited_id);
    // TODO: risolvere problema doppi id
    get_contents(last_visited_id);

    if(!logged_auth) {
        $("#add_content").hide();
        $("#login_required").show();
    }
    else {
        $("#add_content").show();
        $("#login_required").hide();
    }
});

// INDIANA SERVER
function register(name, psw, email) {
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/indiana_user",
        data: JSON.stringify({ "name": name, "psw": psw, "email": email }),
        dataType: "json",
        contentType: "application/json",
        success: function(data) {
            alert("ok");
            return data.objects;
        },
        error: function() {
            alert("ops, something went wrong..");
        }
    });
}

function login(name, psw) {
    var auth = "Basic " + btoa(name + ":" + psw);
    $.ajax({
        type: "GET",
        url: SERVER_URL + "api/login/",
        headers: {
          "Authorization": auth
        },
        success: function(logged) {
            console.log("successfully logged");
            if(logged) {
                logged_auth = auth;
                logged_name = name;
                alert("User and psw saved.");
            }
        },
        error: function() {
            alert("ops, something went wrong..");
        }
    });
}

function post_a_comment(poi, comment) {
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/content",
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify({ "comment": comment, "poi": poi }),
        dataType: "json",
        contentType: "application/json",
        success: function() {
            console.log("comment published!");
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

function get_contents(poi) {
    $.ajax({
        type: "GET",
        url: SERVER_URL + "api/content",
        data: {
            "q": JSON.stringify({
                "filters": [{
                    "name": "poi",
                    "op": "==",
                    "val": poi
                }]
            })
        },
        dataType: "json",
        contentType: "application/json",
        success: function(received) {
            console.log("contents received.");
            display_contents(received);
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

function modify_comment(content_id, modified_content) {
    $.ajax({
        type: "PATCH",
        url: SERVER_URL + "api/content/" + content_id,
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify ({
            "comment": modified_content
        }),
        contentType: "application/json",
        success: function() {
            console.log("content modified.");
        },
        error: function() {
            console.log("ops, something went wrong..");
        },
        complete: function(data_response) {
            return data_response.responseText;
        }
    });
}

function remove_content(content_id) {
    $.ajax({
        type: "DELETE",
        url: SERVER_URL + "api/content/" + content_id,
        headers: {
          "Authorization": logged_auth
        },
        contentType: "application/json",
        success: function() {
            console.log("content deleted.");
        },
        error: function() {
            console.log("ops, something went wrong..");
        },
        complete: function(data_response) {
            return data_response.responseText;
        }
    });
}

function like(content_id, do_like) {
    if(!logged_auth) {
        alert("per dire se ti piace o no, prima devi fare login");
        return;
    }
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/like",
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify ({
            "content_id": content_id,
            "do_like": do_like
        }),
        contentType: "application/json",
        success: function() {
            console.log("liked.");
        },
        error: function() {
            console.log("ops, something went wrong..");
        },
        complete: function(data_response) {
            return data_response.responseText;
        }
    });
}

function upload(poi, comment, form_data, file_description) {
    var file_id = null;

    // posting announcement
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/content",
        headers: {
          "Authorization": logged_auth
        },
        data: JSON.stringify ({
            "poi": poi,
            "comment": comment,
            "upload_announcement": true,
            "file_description": file_description
        }),
        dataType: "json",
        contentType: "application/json",
        success: function(data) {
            console.log("file announced.");
            file_id = data["filename"];
            upload2(file_id, form_data);
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

function upload2(file_id, form_data) {
    // actually post the file
    $.ajax({
        type: "POST",
        url: SERVER_URL + "api/file/" + file_id,
        headers: {
          "Authorization": logged_auth
        },
        data: form_data,
        async: false,
        cache: false,
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        dataType: 'json',
        success: function() {
            console.log("file uploaded.");
        },
        error: function(x, t, m) {
            console.log(t);
        }
    });
}

function wms_proxy(bbox, width, height, x, y, e) {
    $.ajax({
        type: "GET",
        url: SERVER_URL + "api/proxy/" + bbox + '&' + width + '&' + height + '&' + x + '&' + y,
        success: function(data) {
            console.log("proxied.");
            console.log(data);
            pop_the_popup(data, e);
        },
        error: function() {
            console.log("ops, something went wrong..");
        }
    });
}

// OPENGEO SERVER
function ask_opengeo(type, id) {
    if(type == "ritrovamento")
        var prefix = "rit_id=";
    else if(type == "intervento")
        var prefix = "interv_id=";
    else
        return;
    $.getJSON(
        "http://opengeo.eu/archeofi2/api/archeofi_api.php?" + prefix + id + "&jsoncallback=?",
        function(data) {
            console.log(data);
            display_opengeo(data);
        }
    );
}
<|endoftext|>


<commit_before>const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message, betaMode) {
    var expression = /^[d]\!(\w+) *(.*)/;
    if (betaMode) expression = /^[d][b]\!(\w+) *(.*)/; // Use db!command instead of d!command if in beta mode
    var embed = utils.generateDekuDiv(message);
    if (message.content.match(expression)[2]) {
      var game = message.content.match(expression)[2];
      var count = message.guild.members.filter(m => {if(m.user.presence.game){ if(m.user.presence.game.name == game){return true;}}}).size;
      var text = '';
      if (count == 0) {
        text = "There is **no one** in this guild playing `" + game + "` at the moment";
      } else if (count == 1) {
        text = "There is **one person** in this guild playing `" + game + "` at the moment";
      } else {
        text = "There are **" + count + "** people playing `" + game + "` at the moment";
      }
      embed.addField("Currently playing", text);
    } else {
      embed.setColor(config.colors.error);
      embed.addField('You have to specify the game!', '**Usage:** `d!playing <game>`\n**Example:** `d!playing Overwatch`');
    }
    message.channel.send({embed});
  }
}
<commit_msg>Make d!playing not case-sensitive<commit_after>const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message, betaMode) {
    var expression = /^[d]\!(\w+) *(.*)/;
    if (betaMode) expression = /^[d][b]\!(\w+) *(.*)/; // Use db!command instead of d!command if in beta mode
    var embed = utils.generateDekuDiv(message);
    if (message.content.match(expression)[2]) {
      var game = message.content.match(expression)[2];
      var count = message.guild.members.filter(m => {if(m.user.presence.game){ if(m.user.presence.game.name.toLowerCase() == game.toLowerCase()){return true;}}}).size;
      var text = '';
      if (count == 0) {
        text = "There is **no one** in this guild playing `" + game + "` at the moment";
      } else if (count == 1) {
        text = "There is **one person** in this guild playing `" + game + "` at the moment";
      } else {
        text = "There are **" + count + "** people playing `" + game + "` at the moment";
      }
      embed.addField("Currently playing", text);
    } else {
      embed.setColor(config.colors.error);
      embed.addField('You have to specify the game!', '**Usage:** `d!playing <game>`\n**Example:** `d!playing Overwatch`');
    }
    message.channel.send({embed});
  }
}
<|endoftext|>


<commit_before>// Not available faskes
$('#not-available').on('click', function() {
	alert("Faskes is not available")
})

// Select faskes function
function selectFaskes(username) {
  window.location.href = 'faskes/' + username + '.html'
}

// Doctor profile using SweetAlert
function doctorProfile(nama, gambar, lulusan, tahun) {
  swal({
    title: "dr. " + nama,
    imageUrl: gambar,
    text: "Lulusan: " + lulusan + "<br>" + "Tahun: " + tahun,
    html: true
  })
  // Log input value for testing
  console.log('Nama: ' + nama);
  console.log('Gambar: ' + gambar);
  console.log('Lulusan: ' + lulusan);
  console.log('Tahun: ' + tahun);
}
<commit_msg>Remove doctor profile alert<commit_after>// Not available faskes
$('#not-available').on('click', function() {
	alert("Faskes is not available")
})

// Select faskes function
function selectFaskes(username) {
  window.location.href = 'faskes/' + username + '.html'
}
<|endoftext|>